From c299a96624e7b9c1667084361b79a0e0b132993a Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Tue, 28 Oct 2025 15:23:47 -0700 Subject: [PATCH] all: apply consistent imports of "json" packages This runs: go run ./cmd/jsonimports -update -ignore=tempfork/ which applies the following rules: * Until the Go standard library formally accepts "encoding/json/v2" and "encoding/json/jsontext" into the standard library (i.e., they are no longer considered experimental), we forbid any code from directly importing those packages. Go code should instead import "github.com/go-json-experiment/json" and "github.com/go-json-experiment/json/jsontext". The latter packages contain aliases to the standard library if built on Go 1.25 with the goexperiment.jsonv2 tag specified. * Imports of "encoding/json" or "github.com/go-json-experiment/json/v1" must be explicitly imported under the package name "jsonv1". If both packages need to be imported, then the former should be imported under the package name "jsonv1std". * Imports of "github.com/go-json-experiment/json" must be explicitly imported under the package name "jsonv2". The latter two rules exist to provide clarity when reading code. Without them, it is unclear whether "json.Marshal" refers to v1 or v2. With them, however, it is clear that "jsonv1.Marshal" is calling v1 and that "jsonv2.Marshal" is calling v2. Updates tailscale/corp#791 Signed-off-by: Joe Tsai --- .github/workflows/jsonimports.yml | 37 +++++++++ client/local/local.go | 40 +++++----- client/local/serve.go | 4 +- client/local/tailnetlock.go | 12 +-- client/tailscale/acl.go | 22 +++--- client/tailscale/devices.go | 10 +-- client/tailscale/dns.go | 20 ++--- client/tailscale/keys.go | 10 +-- client/tailscale/routes.go | 8 +- client/tailscale/tailscale.go | 4 +- client/web/web.go | 14 ++-- client/web/web_test.go | 6 +- clientupdate/clientupdate.go | 4 +- cmd/connector-gen/aws.go | 4 +- cmd/connector-gen/github.go | 4 +- cmd/containerboot/egressservices.go | 8 +- cmd/containerboot/ingressservices.go | 8 +- cmd/containerboot/kube.go | 4 +- cmd/containerboot/main_test.go | 14 ++-- cmd/containerboot/serve.go | 4 +- cmd/derper/bootstrap_dns.go | 6 +- cmd/derper/bootstrap_dns_test.go | 4 +- cmd/derper/cert.go | 4 +- cmd/derper/derper.go | 6 +- cmd/gitops-pusher/cache.go | 6 +- cmd/gitops-pusher/gitops-pusher.go | 6 +- cmd/gitops-pusher/gitops-pusher_test.go | 10 +-- cmd/hello/hello.go | 4 +- cmd/jsonimports/format.go | 4 +- cmd/jsonimports/jsonimports.go | 28 ++++++- cmd/k8s-nameserver/main.go | 4 +- cmd/k8s-operator/api-server-proxy-pg.go | 8 +- cmd/k8s-operator/api-server-proxy-pg_test.go | 6 +- cmd/k8s-operator/dnsrecords.go | 6 +- cmd/k8s-operator/dnsrecords_test.go | 6 +- cmd/k8s-operator/e2e/proxy_test.go | 4 +- cmd/k8s-operator/egress-eps.go | 4 +- cmd/k8s-operator/egress-eps_test.go | 6 +- cmd/k8s-operator/egress-services.go | 12 +-- cmd/k8s-operator/egress-services_test.go | 4 +- cmd/k8s-operator/ingress-for-pg.go | 22 +++--- cmd/k8s-operator/ingress-for-pg_test.go | 10 +-- cmd/k8s-operator/nameserver_test.go | 4 +- cmd/k8s-operator/operator_test.go | 4 +- cmd/k8s-operator/proxygroup.go | 14 ++-- cmd/k8s-operator/proxygroup_test.go | 14 ++-- cmd/k8s-operator/sts.go | 10 +-- cmd/k8s-operator/svc-for-pg.go | 18 ++--- cmd/k8s-operator/svc-for-pg_test.go | 6 +- cmd/k8s-operator/testutils_test.go | 16 ++-- cmd/k8s-operator/tsrecorder.go | 4 +- cmd/k8s-operator/tsrecorder_test.go | 4 +- cmd/natc/ippool/consensusippool.go | 24 +++--- cmd/natc/ippool/consensusippool_test.go | 6 +- cmd/natc/ippool/consensusippoolserialize.go | 6 +- cmd/natc/natc.go | 6 +- cmd/netlogfmt/main.go | 4 +- cmd/sniproxy/sniproxy_test.go | 4 +- cmd/stunstamp/stunstamp.go | 4 +- cmd/tailscale/cli/appcroutes.go | 8 +- cmd/tailscale/cli/cli.go | 4 +- cmd/tailscale/cli/cli_test.go | 6 +- cmd/tailscale/cli/configure-synology-cert.go | 18 ++--- .../cli/configure-synology-cert_test.go | 10 +-- cmd/tailscale/cli/debug.go | 34 ++++---- cmd/tailscale/cli/netcheck.go | 8 +- cmd/tailscale/cli/network-lock.go | 8 +- cmd/tailscale/cli/serve_legacy.go | 6 +- cmd/tailscale/cli/serve_v2.go | 8 +- cmd/tailscale/cli/serve_v2_test.go | 8 +- cmd/tailscale/cli/status.go | 4 +- cmd/tailscale/cli/syspolicy.go | 4 +- cmd/tailscale/cli/up.go | 6 +- cmd/tailscale/cli/version.go | 4 +- cmd/tailscale/cli/whois.go | 6 +- cmd/tailscaled/debug.go | 6 +- cmd/tailscaled/tailscaled_windows.go | 4 +- cmd/testwrapper/testwrapper.go | 8 +- cmd/tsconnect/build-pkg.go | 6 +- cmd/tsconnect/build.go | 6 +- cmd/tsconnect/serve.go | 4 +- cmd/tsconnect/wasm/wasm_js.go | 4 +- cmd/tsidp/tsidp.go | 28 +++---- cmd/tsidp/tsidp_test.go | 32 ++++---- control/controlclient/direct.go | 22 +++--- control/controlclient/direct_test.go | 4 +- control/controlclient/map.go | 4 +- control/controlclient/map_test.go | 10 +-- control/controlclient/status.go | 4 +- control/ts2021/client.go | 4 +- control/ts2021/client_test.go | 4 +- control/ts2021/conn.go | 4 +- derp/derp_client.go | 6 +- derp/derp_test.go | 4 +- derp/derphttp/derphttp_test.go | 6 +- derp/derpserver/derpserver.go | 12 +-- docs/webhooks/example.go | 4 +- drive/remote_permissions.go | 4 +- drive/remote_permissions_test.go | 4 +- feature/appconnectors/appconnectors.go | 6 +- feature/clientupdate/clientupdate.go | 10 +-- feature/posture/posture.go | 4 +- feature/relayserver/relayserver.go | 4 +- feature/taildrop/localapi.go | 10 +-- feature/taildrop/peerapi.go | 4 +- feature/tpm/attestation.go | 6 +- feature/tpm/attestation_test.go | 4 +- feature/tpm/tpm.go | 10 +-- feature/tpm/tpm_test.go | 8 +- feature/wakeonlan/wakeonlan.go | 4 +- gokrazy/build.go | 10 +-- health/state.go | 4 +- hostinfo/hostinfo_test.go | 4 +- internal/client/tailscale/vip_service.go | 8 +- ipn/auditlog/auditlog.go | 6 +- ipn/conffile/conffile.go | 6 +- ipn/ipnauth/actor.go | 6 +- ipn/ipnlocal/c2n.go | 12 +-- ipn/ipnlocal/c2n_test.go | 10 +-- ipn/ipnlocal/cert.go | 4 +- ipn/ipnlocal/dnsconfig_test.go | 6 +- ipn/ipnlocal/local.go | 8 +- ipn/ipnlocal/local_test.go | 12 +-- ipn/ipnlocal/network-lock.go | 34 ++++---- ipn/ipnlocal/network-lock_test.go | 42 +++++----- ipn/ipnlocal/peerapi.go | 8 +- ipn/ipnlocal/peerapi_test.go | 4 +- ipn/ipnlocal/profiles.go | 6 +- ipn/ipnlocal/serve.go | 12 +-- ipn/ipnlocal/serve_test.go | 6 +- ipn/ipnlocal/ssh_test.go | 4 +- ipn/ipnlocal/web_client.go | 4 +- ipn/ipnserver/server.go | 4 +- ipn/localapi/debug.go | 28 +++---- ipn/localapi/debugderp.go | 4 +- ipn/localapi/localapi.go | 78 +++++++++---------- ipn/localapi/localapi_drive.go | 8 +- ipn/localapi/localapi_test.go | 6 +- ipn/localapi/serve.go | 6 +- ipn/localapi/syspolicy_api.go | 4 +- ipn/localapi/tailnetlock.go | 26 +++---- ipn/prefs.go | 6 +- ipn/prefs_test.go | 14 ++-- ipn/store/kubestore/store_kube_test.go | 4 +- ipn/store/mem/store_mem.go | 6 +- ipn/store/stores.go | 8 +- jsondb/db.go | 6 +- k8s-operator/api-proxy/proxy.go | 4 +- k8s-operator/api-proxy/proxy_events_test.go | 6 +- k8s-operator/sessionrecording/fakes/fakes.go | 6 +- k8s-operator/sessionrecording/spdy/conn.go | 4 +- .../sessionrecording/spdy/conn_test.go | 4 +- .../sessionrecording/tsrecorder/tsrecorder.go | 4 +- k8s-operator/sessionrecording/ws/conn.go | 4 +- kube/egressservices/egressservices.go | 12 +-- kube/egressservices/egressservices_test.go | 6 +- kube/k8s-proxy/conf/conf.go | 4 +- kube/kubeclient/client.go | 8 +- kube/kubeclient/client_test.go | 6 +- kube/kubetypes/types_test.go | 4 +- kube/state/state.go | 4 +- log/sockstatlog/logger.go | 4 +- logpolicy/logpolicy.go | 6 +- logtail/example/logreprocess/logreprocess.go | 6 +- logtail/logtail_test.go | 6 +- metrics/multilabelmap_test.go | 4 +- net/dns/resolver/tsdns_test.go | 10 +-- net/dnsfallback/dnsfallback.go | 10 +-- net/dnsfallback/dnsfallback_test.go | 6 +- net/dnsfallback/update-dns-fallbacks.go | 6 +- net/flowtrack/flowtrack.go | 6 +- net/flowtrack/flowtrack_test.go | 6 +- net/netmon/interfaces_test.go | 4 +- net/netmon/netmon.go | 4 +- net/speedtest/speedtest_client.go | 6 +- net/speedtest/speedtest_server.go | 6 +- net/udprelay/endpoint/endpoint_test.go | 8 +- portlist/netstat_test.go | 6 +- prober/derp.go | 4 +- prober/derp_test.go | 4 +- prober/prober.go | 6 +- prober/prober_test.go | 8 +- sessionrecording/connect.go | 4 +- sessionrecording/connect_test.go | 4 +- ssh/tailssh/incubator.go | 6 +- ssh/tailssh/incubator_plan9.go | 6 +- ssh/tailssh/privs_test.go | 10 +-- ssh/tailssh/tailssh.go | 12 +-- ssh/tailssh/tailssh_test.go | 6 +- syncs/shardedint.go | 4 +- tailcfg/c2ntypes.go | 6 +- tailcfg/tailcfg.go | 8 +- tailcfg/tailcfg_test.go | 18 ++--- tsconsensus/http.go | 12 +-- tsconsensus/monitor.go | 8 +- tsconsensus/tsconsensus.go | 10 +-- tsconsensus/tsconsensus_test.go | 18 ++--- tstest/deptest/deptest.go | 4 +- tstest/integration/gen_deps.go | 4 +- tstest/integration/integration.go | 8 +- tstest/integration/integration_test.go | 18 ++--- tstest/integration/testcontrol/testcontrol.go | 14 ++-- tstest/integration/vms/distros.go | 4 +- tstest/integration/vms/dns_tester.go | 4 +- tstest/mts/mts.go | 8 +- tstest/natlab/vnet/vnet.go | 6 +- tstime/mono/mono_test.go | 6 +- tstime/rate/value.go | 6 +- tstime/tstime_test.go | 6 +- tsweb/log.go | 4 +- types/appctype/appconnector_test.go | 10 +-- types/ipproto/ipproto_test.go | 6 +- types/jsonx/json.go | 8 +- types/jsonx/json_test.go | 16 ++-- types/key/control.go | 6 +- types/key/control_test.go | 6 +- types/key/derp.go | 6 +- types/key/disco_test.go | 8 +- types/key/hardware_attestation.go | 6 +- types/key/machine_test.go | 8 +- types/key/node_test.go | 8 +- types/logger/logger.go | 8 +- types/netlogtype/netlogtype_test.go | 4 +- types/netmap/netmap.go | 4 +- types/opt/bool_test.go | 8 +- types/opt/value_test.go | 8 +- types/prefs/prefs_test.go | 6 +- types/tkatype/tkatype_test.go | 6 +- util/cloudenv/cloudenv.go | 4 +- util/expvarx/expvarx.go | 4 +- util/reload/reload.go | 4 +- util/set/set.go | 6 +- util/set/set_test.go | 10 +-- util/syspolicy/setting/snapshot_test.go | 6 +- util/winutil/svcdiag_windows.go | 10 +-- wgengine/filter/filter_test.go | 4 +- wgengine/router/osrouter/router_windows.go | 6 +- 237 files changed, 1031 insertions(+), 966 deletions(-) create mode 100644 .github/workflows/jsonimports.yml diff --git a/.github/workflows/jsonimports.yml b/.github/workflows/jsonimports.yml new file mode 100644 index 000000000..1e69efc57 --- /dev/null +++ b/.github/workflows/jsonimports.yml @@ -0,0 +1,37 @@ +name: jsonimports + +env: + HOME: ${{ github.workspace }} + +on: + push: + branches: + - main + - "release-branch/*" + paths: + - "**.go" + pull_request: + paths: + - "**.go" + +concurrency: + group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + check: + runs-on: [ self-hosted, linux ] + timeout-minutes: 5 + + steps: + - name: Check out code + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + + - name: Set up Go + uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0 + with: + cache: true + go-version-file: go.mod + + - name: Check that all Go files use the right "json" import + run: go run tailscale.com/cmd/jsonimports -ignore=tempfork/ diff --git a/client/local/local.go b/client/local/local.go index 2382a1225..f07c0f4b7 100644 --- a/client/local/local.go +++ b/client/local/local.go @@ -10,7 +10,7 @@ import ( "cmp" "context" "encoding/base64" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -216,7 +216,7 @@ func IsPreconditionsFailedError(err error) bool { // object of type errorJSON, its non-empty error body. func bestError(err error, body []byte) error { var j errorJSON - if err := json.Unmarshal(body, &j); err == nil && j.Error != "" { + if err := jsonv1.Unmarshal(body, &j); err == nil && j.Error != "" { return errors.New(j.Error) } return err @@ -224,7 +224,7 @@ func bestError(err error, body []byte) error { func errorMessageFromBody(body []byte) string { var j errorJSON - if err := json.Unmarshal(body, &j); err == nil && j.Error != "" { + if err := jsonv1.Unmarshal(body, &j); err == nil && j.Error != "" { return j.Error } return strings.TrimSpace(string(body)) @@ -300,7 +300,7 @@ func WhoIs(ctx context.Context, remoteAddr string) (*apitype.WhoIsResponse, erro } func decodeJSON[T any](b []byte) (ret T, err error) { - if err := json.Unmarshal(b, &ret); err != nil { + if err := jsonv1.Unmarshal(b, &ret); err != nil { var zero T return zero, fmt.Errorf("failed to unmarshal JSON into %T: %w", ret, err) } @@ -462,7 +462,7 @@ func (lc *Client) StreamBusEvents(ctx context.Context) iter.Seq2[eventbus.DebugE return } defer res.Body.Close() - dec := json.NewDecoder(bufio.NewReader(res.Body)) + dec := jsonv1.NewDecoder(bufio.NewReader(res.Body)) for { var evt eventbus.DebugEvent if err := dec.Decode(&evt); err == io.EOF { @@ -590,7 +590,7 @@ func (lc *Client) DebugResultJSON(ctx context.Context, action string) (any, erro return nil, fmt.Errorf("error %w: %s", err, body) } var x any - if err := json.Unmarshal(body, &x); err != nil { + if err := jsonv1.Unmarshal(body, &x); err != nil { return nil, err } return x, nil @@ -603,7 +603,7 @@ func (lc *Client) QueryOptionalFeatures(ctx context.Context) (*apitype.OptionalF return nil, fmt.Errorf("error %w: %s", err, body) } var x apitype.OptionalFeatures - if err := json.Unmarshal(body, &x); err != nil { + if err := jsonv1.Unmarshal(body, &x); err != nil { return nil, err } return &x, nil @@ -638,7 +638,7 @@ func (lc *Client) SetComponentDebugLogging(ctx context.Context, component string var res struct { Error string } - if err := json.Unmarshal(body, &res); err != nil { + if err := jsonv1.Unmarshal(body, &res); err != nil { return err } if res.Error != "" { @@ -778,7 +778,7 @@ func (lc *Client) CheckIPForwarding(ctx context.Context) error { var jres struct { Warning string } - if err := json.Unmarshal(body, &jres); err != nil { + if err := jsonv1.Unmarshal(body, &jres); err != nil { return fmt.Errorf("invalid JSON from check-ip-forwarding: %w", err) } if jres.Warning != "" { @@ -798,7 +798,7 @@ func (lc *Client) CheckUDPGROForwarding(ctx context.Context) error { var jres struct { Warning string } - if err := json.Unmarshal(body, &jres); err != nil { + if err := jsonv1.Unmarshal(body, &jres); err != nil { return fmt.Errorf("invalid JSON from check-udp-gro-forwarding: %w", err) } if jres.Warning != "" { @@ -817,7 +817,7 @@ func (lc *Client) CheckReversePathFiltering(ctx context.Context) error { var jres struct { Warning string } - if err := json.Unmarshal(body, &jres); err != nil { + if err := jsonv1.Unmarshal(body, &jres); err != nil { return fmt.Errorf("invalid JSON from check-reverse-path-filtering: %w", err) } if jres.Warning != "" { @@ -838,7 +838,7 @@ func (lc *Client) SetUDPGROForwarding(ctx context.Context) error { var jres struct { Warning string } - if err := json.Unmarshal(body, &jres); err != nil { + if err := jsonv1.Unmarshal(body, &jres); err != nil { return fmt.Errorf("invalid JSON from set-udp-gro-forwarding: %w", err) } if jres.Warning != "" { @@ -864,7 +864,7 @@ func (lc *Client) GetPrefs(ctx context.Context) (*ipn.Prefs, error) { return nil, err } var p ipn.Prefs - if err := json.Unmarshal(body, &p); err != nil { + if err := jsonv1.Unmarshal(body, &p); err != nil { return nil, fmt.Errorf("invalid prefs JSON: %w", err) } return &p, nil @@ -894,7 +894,7 @@ func (lc *Client) GetDNSOSConfig(ctx context.Context) (*apitype.DNSOSConfig, err return nil, err } var osCfg apitype.DNSOSConfig - if err := json.Unmarshal(body, &osCfg); err != nil { + if err := jsonv1.Unmarshal(body, &osCfg); err != nil { return nil, fmt.Errorf("invalid dns.OSConfig: %w", err) } return &osCfg, nil @@ -912,7 +912,7 @@ func (lc *Client) QueryDNS(ctx context.Context, name string, queryType string) ( return nil, nil, err } var res apitype.DNSQueryResponse - if err := json.Unmarshal(body, &res); err != nil { + if err := jsonv1.Unmarshal(body, &res); err != nil { return nil, nil, fmt.Errorf("invalid query response: %w", err) } return res.Bytes, res.Resolvers, nil @@ -1011,7 +1011,7 @@ func (lc *Client) CurrentDERPMap(ctx context.Context) (*tailcfg.DERPMap, error) if err != nil { return nil, err } - if err = json.Unmarshal(res, &derpMap); err != nil { + if err = jsonv1.Unmarshal(res, &derpMap); err != nil { return nil, fmt.Errorf("invalid derp map json: %w", err) } return &derpMap, nil @@ -1098,7 +1098,7 @@ type jsonReader struct { // jsonBody returns an io.Reader that marshals v as JSON and then reads it. func jsonBody(v any) jsonReader { - b, err := json.Marshal(v) + b, err := jsonv1.Marshal(v) if err != nil { return jsonReader{err: err} } @@ -1271,7 +1271,7 @@ func (lc *Client) WatchIPNBus(ctx context.Context, mask ipn.NotifyWatchOpt) (*IP res.Body.Close() return nil, errors.New(res.Status) } - dec := json.NewDecoder(res.Body) + dec := jsonv1.NewDecoder(res.Body) return &IPNBusWatcher{ ctx: ctx, httpRes: res, @@ -1350,7 +1350,7 @@ func (lc *Client) DriveShareList(ctx context.Context) ([]*drive.Share, error) { return nil, err } var shares []*drive.Share - err = json.Unmarshal(result, &shares) + err = jsonv1.Unmarshal(result, &shares) return shares, err } @@ -1361,7 +1361,7 @@ func (lc *Client) DriveShareList(ctx context.Context) ([]*drive.Share, error) { type IPNBusWatcher struct { ctx context.Context // from original WatchIPNBus call httpRes *http.Response - dec *json.Decoder + dec *jsonv1.Decoder mu sync.Mutex closed bool diff --git a/client/local/serve.go b/client/local/serve.go index 51d15e7e5..744fa6f48 100644 --- a/client/local/serve.go +++ b/client/local/serve.go @@ -7,7 +7,7 @@ package local import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/http" @@ -34,7 +34,7 @@ func (lc *Client) GetServeConfig(ctx context.Context) (*ipn.ServeConfig, error) } func getServeConfigFromJSON(body []byte) (sc *ipn.ServeConfig, err error) { - if err := json.Unmarshal(body, &sc); err != nil { + if err := jsonv1.Unmarshal(body, &sc); err != nil { return nil, err } return sc, nil diff --git a/client/local/tailnetlock.go b/client/local/tailnetlock.go index 9d37d2f35..d78cbb31a 100644 --- a/client/local/tailnetlock.go +++ b/client/local/tailnetlock.go @@ -8,7 +8,7 @@ package local import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/url" @@ -38,7 +38,7 @@ func (lc *Client) NetworkLockInit(ctx context.Context, keys []tka.Key, disableme SupportDisablement []byte } - if err := json.NewEncoder(&b).Encode(initRequest{Keys: keys, DisablementValues: disablementValues, SupportDisablement: supportDisablement}); err != nil { + if err := jsonv1.NewEncoder(&b).Encode(initRequest{Keys: keys, DisablementValues: disablementValues, SupportDisablement: supportDisablement}); err != nil { return nil, err } @@ -62,7 +62,7 @@ func (lc *Client) NetworkLockWrapPreauthKey(ctx context.Context, preauthKey stri TSKey string TKAKey string // key.NLPrivate.MarshalText } - if err := json.NewEncoder(&b).Encode(wrapRequest{TSKey: preauthKey, TKAKey: string(encodedPrivate)}); err != nil { + if err := jsonv1.NewEncoder(&b).Encode(wrapRequest{TSKey: preauthKey, TKAKey: string(encodedPrivate)}); err != nil { return "", err } @@ -81,7 +81,7 @@ func (lc *Client) NetworkLockModify(ctx context.Context, addKeys, removeKeys []t RemoveKeys []tka.Key } - if err := json.NewEncoder(&b).Encode(modifyRequest{AddKeys: addKeys, RemoveKeys: removeKeys}); err != nil { + if err := jsonv1.NewEncoder(&b).Encode(modifyRequest{AddKeys: addKeys, RemoveKeys: removeKeys}); err != nil { return err } @@ -100,7 +100,7 @@ func (lc *Client) NetworkLockSign(ctx context.Context, nodeKey key.NodePublic, r RotationPublic []byte } - if err := json.NewEncoder(&b).Encode(signRequest{NodeKey: nodeKey, RotationPublic: rotationPublic}); err != nil { + if err := jsonv1.NewEncoder(&b).Encode(signRequest{NodeKey: nodeKey, RotationPublic: rotationPublic}); err != nil { return err } @@ -134,7 +134,7 @@ func (lc *Client) NetworkLockLog(ctx context.Context, maxEntries int) ([]ipnstat func (lc *Client) NetworkLockForceLocalDisable(ctx context.Context) error { // This endpoint expects an empty JSON stanza as the payload. var b bytes.Buffer - if err := json.NewEncoder(&b).Encode(struct{}{}); err != nil { + if err := jsonv1.NewEncoder(&b).Encode(struct{}{}); err != nil { return err } diff --git a/client/tailscale/acl.go b/client/tailscale/acl.go index 929ec2b3b..064bde198 100644 --- a/client/tailscale/acl.go +++ b/client/tailscale/acl.go @@ -8,7 +8,7 @@ package tailscale import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/http" "net/netip" @@ -103,7 +103,7 @@ func (c *Client) ACL(ctx context.Context) (acl *ACL, err error) { // Otherwise, try to decode the response. var aclDetails ACLDetails - if err = json.Unmarshal(b, &aclDetails); err != nil { + if err = jsonv1.Unmarshal(b, &aclDetails); err != nil { return nil, err } acl = &ACL{ @@ -146,7 +146,7 @@ func (c *Client) ACLHuJSON(ctx context.Context) (acl *ACLHuJSON, err error) { ACL []byte `json:"acl"` Warnings []string `json:"warnings"` }{} - if err := json.Unmarshal(b, &data); err != nil { + if err := jsonv1.Unmarshal(b, &data); err != nil { return nil, fmt.Errorf("json.Unmarshal %q: %w", b, err) } @@ -206,7 +206,7 @@ func (c *Client) aclPOSTRequest(ctx context.Context, body []byte, avoidCollision if resp.StatusCode != http.StatusOK { // check if test error var ate ACLTestError - if err := json.Unmarshal(b, &ate); err != nil { + if err := jsonv1.Unmarshal(b, &ate); err != nil { return nil, "", err } ate.Status = resp.StatusCode @@ -230,7 +230,7 @@ func (c *Client) SetACL(ctx context.Context, acl ACL, avoidCollisions bool) (res err = fmt.Errorf("tailscale.SetACL: %w", err) } }() - postData, err := json.Marshal(acl.ACL) + postData, err := jsonv1.Marshal(acl.ACL) if err != nil { return nil, err } @@ -241,7 +241,7 @@ func (c *Client) SetACL(ctx context.Context, acl ACL, avoidCollisions bool) (res // Otherwise, try to decode the response. var aclDetails ACLDetails - if err = json.Unmarshal(b, &aclDetails); err != nil { + if err = jsonv1.Unmarshal(b, &aclDetails); err != nil { return nil, err } res = &ACL{ @@ -353,7 +353,7 @@ func (c *Client) previewACLPostRequest(ctx context.Context, body []byte, preview if resp.StatusCode != http.StatusOK { return nil, HandleErrorResponse(b, resp) } - if err = json.Unmarshal(b, &res); err != nil { + if err = jsonv1.Unmarshal(b, &res); err != nil { return nil, err } @@ -373,7 +373,7 @@ func (c *Client) PreviewACLForUser(ctx context.Context, acl ACL, user string) (r err = fmt.Errorf("tailscale.PreviewACLForUser: %w", err) } }() - postData, err := json.Marshal(acl.ACL) + postData, err := jsonv1.Marshal(acl.ACL) if err != nil { return nil, err } @@ -402,7 +402,7 @@ func (c *Client) PreviewACLForIPPort(ctx context.Context, acl ACL, ipport netip. err = fmt.Errorf("tailscale.PreviewACLForIPPort: %w", err) } }() - postData, err := json.Marshal(acl.ACL) + postData, err := jsonv1.Marshal(acl.ACL) if err != nil { return nil, err } @@ -484,7 +484,7 @@ func (c *Client) ValidateACLJSON(ctx context.Context, source, dest string) (test }() tests := []ACLTest{{User: source, Allow: []string{dest}}} - postData, err := json.Marshal(tests) + postData, err := jsonv1.Marshal(tests) if err != nil { return nil, err } @@ -514,7 +514,7 @@ func (c *Client) ValidateACLJSON(ctx context.Context, source, dest string) (test var res ACLTestError // The test returned errors. - if err = json.Unmarshal(b, &res); err != nil { + if err = jsonv1.Unmarshal(b, &res); err != nil { // failed to unmarshal return nil, err } diff --git a/client/tailscale/devices.go b/client/tailscale/devices.go index 0664f9e63..57240baee 100644 --- a/client/tailscale/devices.go +++ b/client/tailscale/devices.go @@ -8,7 +8,7 @@ package tailscale import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "log" "net/http" @@ -160,7 +160,7 @@ func (c *Client) Devices(ctx context.Context, fields *DeviceFieldsOpts) (deviceL } var devices GetDevicesResponse - err = json.Unmarshal(b, &devices) + err = jsonv1.Unmarshal(b, &devices) return devices.Devices, err } @@ -198,7 +198,7 @@ func (c *Client) Device(ctx context.Context, deviceID string, fields *DeviceFiel return nil, HandleErrorResponse(b, resp) } - err = json.Unmarshal(b, &device) + err = jsonv1.Unmarshal(b, &device) return device, err } @@ -243,7 +243,7 @@ func (c *Client) SetAuthorized(ctx context.Context, deviceID string, authorized params := &struct { Authorized bool `json:"authorized"` }{Authorized: authorized} - data, err := json.Marshal(params) + data, err := jsonv1.Marshal(params) if err != nil { return err } @@ -271,7 +271,7 @@ func (c *Client) SetTags(ctx context.Context, deviceID string, tags []string) er params := &struct { Tags []string `json:"tags"` }{Tags: tags} - data, err := json.Marshal(params) + data, err := jsonv1.Marshal(params) if err != nil { return err } diff --git a/client/tailscale/dns.go b/client/tailscale/dns.go index bbdc7c56c..1af5e2711 100644 --- a/client/tailscale/dns.go +++ b/client/tailscale/dns.go @@ -8,7 +8,7 @@ package tailscale import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/http" @@ -65,7 +65,7 @@ func (c *Client) dnsGETRequest(ctx context.Context, endpoint string) ([]byte, er func (c *Client) dnsPOSTRequest(ctx context.Context, endpoint string, postData any) ([]byte, error) { path := c.BuildTailnetURL("dns", endpoint) - data, err := json.Marshal(&postData) + data, err := jsonv1.Marshal(&postData) if err != nil { return nil, err } @@ -103,7 +103,7 @@ func (c *Client) DNSConfig(ctx context.Context) (cfg *apitype.DNSConfig, err err return nil, err } var dnsResp apitype.DNSConfig - err = json.Unmarshal(b, &dnsResp) + err = jsonv1.Unmarshal(b, &dnsResp) return &dnsResp, err } @@ -119,7 +119,7 @@ func (c *Client) SetDNSConfig(ctx context.Context, cfg apitype.DNSConfig) (resp if err != nil { return nil, err } - err = json.Unmarshal(b, &dnsResp) + err = jsonv1.Unmarshal(b, &dnsResp) return &dnsResp, err } @@ -136,7 +136,7 @@ func (c *Client) NameServers(ctx context.Context) (nameservers []string, err err return nil, err } var dnsResp DNSNameServers - err = json.Unmarshal(b, &dnsResp) + err = jsonv1.Unmarshal(b, &dnsResp) return dnsResp.DNS, err } @@ -157,7 +157,7 @@ func (c *Client) SetNameServers(ctx context.Context, nameservers []string) (dnsR if err != nil { return nil, err } - err = json.Unmarshal(b, &dnsResp) + err = jsonv1.Unmarshal(b, &dnsResp) return dnsResp, err } @@ -175,7 +175,7 @@ func (c *Client) DNSPreferences(ctx context.Context) (dnsResp *DNSPreferences, e if err != nil { return nil, err } - err = json.Unmarshal(b, &dnsResp) + err = jsonv1.Unmarshal(b, &dnsResp) return dnsResp, err } @@ -195,7 +195,7 @@ func (c *Client) SetDNSPreferences(ctx context.Context, magicDNS bool) (dnsResp if err != nil { return } - err = json.Unmarshal(b, &dnsResp) + err = jsonv1.Unmarshal(b, &dnsResp) return dnsResp, err } @@ -211,7 +211,7 @@ func (c *Client) SearchPaths(ctx context.Context) (searchpaths []string, err err return nil, err } var dnsResp *DNSSearchPaths - err = json.Unmarshal(b, &dnsResp) + err = jsonv1.Unmarshal(b, &dnsResp) return dnsResp.SearchPaths, err } @@ -228,6 +228,6 @@ func (c *Client) SetSearchPaths(ctx context.Context, searchpaths []string) (newS return nil, err } var dnsResp DNSSearchPaths - err = json.Unmarshal(b, &dnsResp) + err = jsonv1.Unmarshal(b, &dnsResp) return dnsResp.SearchPaths, err } diff --git a/client/tailscale/keys.go b/client/tailscale/keys.go index 79e19e998..66a82495e 100644 --- a/client/tailscale/keys.go +++ b/client/tailscale/keys.go @@ -6,7 +6,7 @@ package tailscale import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/http" "time" @@ -57,7 +57,7 @@ func (c *Client) Keys(ctx context.Context) ([]string, error) { var keys struct { Keys []*Key `json:"keys"` } - if err := json.Unmarshal(b, &keys); err != nil { + if err := jsonv1.Unmarshal(b, &keys); err != nil { return nil, err } ret := make([]string, 0, len(keys.Keys)) @@ -94,7 +94,7 @@ func (c *Client) CreateKeyWithExpiry(ctx context.Context, caps KeyCapabilities, Capabilities KeyCapabilities `json:"capabilities"` ExpirySeconds int64 `json:"expirySeconds,omitempty"` }{caps, int64(expirySeconds)} - bs, err := json.Marshal(keyRequest) + bs, err := jsonv1.Marshal(keyRequest) if err != nil { return "", nil, err } @@ -117,7 +117,7 @@ func (c *Client) CreateKeyWithExpiry(ctx context.Context, caps KeyCapabilities, Key Secret string `json:"key"` } - if err := json.Unmarshal(b, &key); err != nil { + if err := jsonv1.Unmarshal(b, &key); err != nil { return "", nil, err } return key.Secret, &key.Key, nil @@ -141,7 +141,7 @@ func (c *Client) Key(ctx context.Context, id string) (*Key, error) { } var key Key - if err := json.Unmarshal(b, &key); err != nil { + if err := jsonv1.Unmarshal(b, &key); err != nil { return nil, err } return &key, nil diff --git a/client/tailscale/routes.go b/client/tailscale/routes.go index b72f2743f..cb04202a3 100644 --- a/client/tailscale/routes.go +++ b/client/tailscale/routes.go @@ -8,7 +8,7 @@ package tailscale import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/http" "net/netip" @@ -48,7 +48,7 @@ func (c *Client) Routes(ctx context.Context, deviceID string) (routes *Routes, e } var sr Routes - err = json.Unmarshal(b, &sr) + err = jsonv1.Unmarshal(b, &sr) return &sr, err } @@ -67,7 +67,7 @@ func (c *Client) SetRoutes(ctx context.Context, deviceID string, subnets []netip } }() params := &postRoutesParams{Routes: subnets} - data, err := json.Marshal(params) + data, err := jsonv1.Marshal(params) if err != nil { return nil, err } @@ -88,7 +88,7 @@ func (c *Client) SetRoutes(ctx context.Context, deviceID string, subnets []netip } var srr *Routes - if err := json.Unmarshal(b, &srr); err != nil { + if err := jsonv1.Unmarshal(b, &srr); err != nil { return nil, err } return srr, err diff --git a/client/tailscale/tailscale.go b/client/tailscale/tailscale.go index 76e44454b..1476f1612 100644 --- a/client/tailscale/tailscale.go +++ b/client/tailscale/tailscale.go @@ -12,7 +12,7 @@ package tailscale import ( - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -198,7 +198,7 @@ func (e ErrResponse) Error() string { // Deprecated: use [tailscale.com/client/tailscale/v2] instead. func HandleErrorResponse(b []byte, resp *http.Response) error { var errResp ErrResponse - if err := json.Unmarshal(b, &errResp); err != nil { + if err := jsonv1.Unmarshal(b, &errResp); err != nil { return fmt.Errorf("json.Unmarshal %q: %w", b, err) } errResp.Status = resp.StatusCode diff --git a/client/web/web.go b/client/web/web.go index dbd3d5df0..7defcf0ed 100644 --- a/client/web/web.go +++ b/client/web/web.go @@ -7,7 +7,7 @@ package web import ( "cmp" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -604,7 +604,7 @@ func (a *apiHandler[data]) handle(h http.HandlerFunc) { func (a *apiHandler[data]) handleJSON(h func(ctx context.Context, data data) error) { defer a.r.Body.Close() var body data - if err := json.NewDecoder(a.r.Body).Decode(&body); err != nil { + if err := jsonv1.NewDecoder(a.r.Body).Decode(&body); err != nil { http.Error(a.w, err.Error(), http.StatusInternalServerError) return } @@ -1275,9 +1275,9 @@ func (s *Server) serveTailscaleUp(w http.ResponseWriter, r *http.Request) { var opt tailscaleUpOptions type mi map[string]any - if err := json.NewDecoder(r.Body).Decode(&opt); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&opt); err != nil { w.WriteHeader(400) - json.NewEncoder(w).Encode(mi{"error": err.Error()}) + jsonv1.NewEncoder(w).Encode(mi{"error": err.Error()}) return } @@ -1287,11 +1287,11 @@ func (s *Server) serveTailscaleUp(w http.ResponseWriter, r *http.Request) { s.logf("tailscaleUp = (URL %v, %v)", url != "", err) if err != nil { w.WriteHeader(http.StatusInternalServerError) - json.NewEncoder(w).Encode(mi{"error": err.Error()}) + jsonv1.NewEncoder(w).Encode(mi{"error": err.Error()}) return } if url != "" { - json.NewEncoder(w).Encode(mi{"url": url}) + jsonv1.NewEncoder(w).Encode(mi{"url": url}) } else { io.WriteString(w, "{}") } @@ -1376,7 +1376,7 @@ func enforcePrefix(prefix string, h http.HandlerFunc) http.HandlerFunc { func writeJSON(w http.ResponseWriter, data any) { w.Header().Set("Content-Type", "application/json") - if err := json.NewEncoder(w).Encode(data); err != nil { + if err := jsonv1.NewEncoder(w).Encode(data); err != nil { w.Header().Set("Content-Type", "text/plain") http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/client/web/web_test.go b/client/web/web_test.go index 9ba16bccf..46c02bd05 100644 --- a/client/web/web_test.go +++ b/client/web/web_test.go @@ -6,7 +6,7 @@ package web import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -796,7 +796,7 @@ func TestServeAuth(t *testing.T) { } var wantResp string if tt.wantResp != nil { - b, _ := json.Marshal(tt.wantResp) + b, _ := jsonv1.Marshal(tt.wantResp) wantResp = string(b) } if diff := cmp.Diff(gotResp, string(wantResp)); diff != "" { @@ -1458,7 +1458,7 @@ func mockLocalAPI(t *testing.T, whoIs map[string]*apitype.WhoIsResponse, self fu } var metricNames []metricName - if err := json.NewDecoder(r.Body).Decode(&metricNames); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&metricNames); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } diff --git a/clientupdate/clientupdate.go b/clientupdate/clientupdate.go index 84b289615..b049232b7 100644 --- a/clientupdate/clientupdate.go +++ b/clientupdate/clientupdate.go @@ -12,7 +12,7 @@ import ( "bytes" "compress/gzip" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -1207,7 +1207,7 @@ func latestPackages(track string) (*trackPackages, error) { } defer res.Body.Close() var latest trackPackages - if err := json.NewDecoder(res.Body).Decode(&latest); err != nil { + if err := jsonv1.NewDecoder(res.Body).Decode(&latest); err != nil { return nil, fmt.Errorf("decoding JSON: %v: %w", res.Status, err) } return &latest, nil diff --git a/cmd/connector-gen/aws.go b/cmd/connector-gen/aws.go index bd2632ae2..eb71f22b5 100644 --- a/cmd/connector-gen/aws.go +++ b/cmd/connector-gen/aws.go @@ -4,7 +4,7 @@ package main import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "log" "net/http" @@ -40,7 +40,7 @@ func aws() { defer r.Body.Close() var aws AWSMeta - if err := json.NewDecoder(r.Body).Decode(&aws); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&aws); err != nil { log.Fatal(err) } diff --git a/cmd/connector-gen/github.go b/cmd/connector-gen/github.go index def40872d..50064d637 100644 --- a/cmd/connector-gen/github.go +++ b/cmd/connector-gen/github.go @@ -4,7 +4,7 @@ package main import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "log" "net/http" @@ -51,7 +51,7 @@ func github() { var ghm GithubMeta - if err := json.NewDecoder(r.Body).Decode(&ghm); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&ghm); err != nil { log.Fatal(err) } r.Body.Close() diff --git a/cmd/containerboot/egressservices.go b/cmd/containerboot/egressservices.go index fe835a69e..2af4f629d 100644 --- a/cmd/containerboot/egressservices.go +++ b/cmd/containerboot/egressservices.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "log" @@ -393,7 +393,7 @@ func (ep *egressProxy) getConfigs() (*egressservices.Configs, error) { return nil, nil } cfg := &egressservices.Configs{} - if err := json.Unmarshal(j, &cfg); err != nil { + if err := jsonv1.Unmarshal(j, &cfg); err != nil { return nil, err } return cfg, nil @@ -413,7 +413,7 @@ func (ep *egressProxy) getStatus(ctx context.Context) (*egressservices.Status, e if !ok { return nil, nil } - if err := json.Unmarshal([]byte(raw), status); err != nil { + if err := jsonv1.Unmarshal([]byte(raw), status); err != nil { return nil, fmt.Errorf("error unmarshalling previous config: %w", err) } if reflect.DeepEqual(status.PodIPv4, ep.podIPv4) { @@ -434,7 +434,7 @@ func (ep *egressProxy) setStatus(ctx context.Context, status *egressservices.Sta if err != nil { return fmt.Errorf("error retrieving state Secret: %w", err) } - bs, err := json.Marshal(status) + bs, err := jsonv1.Marshal(status) if err != nil { return fmt.Errorf("error marshalling service config: %w", err) } diff --git a/cmd/containerboot/ingressservices.go b/cmd/containerboot/ingressservices.go index 1a2da9567..7c9801fd1 100644 --- a/cmd/containerboot/ingressservices.go +++ b/cmd/containerboot/ingressservices.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "log" "net/netip" @@ -131,7 +131,7 @@ func (p *ingressProxy) getConfigs() (*ingressservices.Configs, error) { return nil, nil } cfg := &ingressservices.Configs{} - if err := json.Unmarshal(j, &cfg); err != nil { + if err := jsonv1.Unmarshal(j, &cfg); err != nil { return nil, err } return cfg, nil @@ -152,7 +152,7 @@ func (p *ingressProxy) getStatus(ctx context.Context) (*ingressservices.Status, if !ok { return nil, nil } - if err := json.Unmarshal([]byte(raw), status); err != nil { + if err := jsonv1.Unmarshal([]byte(raw), status); err != nil { return nil, fmt.Errorf("error unmarshalling previous config: %w", err) } return status, nil @@ -189,7 +189,7 @@ func (p *ingressProxy) recordStatus(ctx context.Context, newCfg *ingressservices if err != nil { return fmt.Errorf("error retrieving state Secret: %w", err) } - bs, err := json.Marshal(status) + bs, err := jsonv1.Marshal(status) if err != nil { return fmt.Errorf("error marshalling status: %w", err) } diff --git a/cmd/containerboot/kube.go b/cmd/containerboot/kube.go index e566fa483..20e14a28d 100644 --- a/cmd/containerboot/kube.go +++ b/cmd/containerboot/kube.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "log" @@ -73,7 +73,7 @@ func (kc *kubeClient) storeDeviceEndpoints(ctx context.Context, fqdn string, add for _, addr := range addresses { ips = append(ips, addr.Addr().String()) } - deviceIPs, err := json.Marshal(ips) + deviceIPs, err := jsonv1.Marshal(ips) if err != nil { return err } diff --git a/cmd/containerboot/main_test.go b/cmd/containerboot/main_test.go index 96feef682..9beac7da9 100644 --- a/cmd/containerboot/main_test.go +++ b/cmd/containerboot/main_test.go @@ -9,7 +9,7 @@ import ( "bytes" _ "embed" "encoding/base64" - "encoding/json" + jsonv1 "encoding/json" "encoding/pem" "errors" "fmt" @@ -1347,7 +1347,7 @@ func (l *localAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) { if f, ok := w.(http.Flusher); ok { f.Flush() } - enc := json.NewEncoder(w) + enc := jsonv1.NewEncoder(w) l.Lock() defer l.Unlock() for { @@ -1456,7 +1456,7 @@ func (k *kubeServer) serveSSAR(w http.ResponseWriter, r *http.Request) { } `json:"resourceAttributes"` } `json:"spec"` } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&req); err != nil { panic(fmt.Sprintf("decoding SSAR request: %v", err)) } ok := true @@ -1490,7 +1490,7 @@ func (k *kubeServer) serveSecret(w http.ResponseWriter, r *http.Request) { v := base64.StdEncoding.EncodeToString([]byte(v)) ret["data"][k] = v } - if err := json.NewEncoder(w).Encode(ret); err != nil { + if err := jsonv1.NewEncoder(w).Encode(ret); err != nil { panic("encode failed") } case "PATCH": @@ -1502,7 +1502,7 @@ func (k *kubeServer) serveSecret(w http.ResponseWriter, r *http.Request) { switch r.Header.Get("Content-Type") { case "application/json-patch+json": req := []kubeclient.JSONPatch{} - if err := json.Unmarshal(bs, &req); err != nil { + if err := jsonv1.Unmarshal(bs, &req); err != nil { panic(fmt.Sprintf("json decode failed: %v. Body:\n\n%s", err, string(bs))) } for _, op := range req { @@ -1534,7 +1534,7 @@ func (k *kubeServer) serveSecret(w http.ResponseWriter, r *http.Request) { req := struct { Data map[string][]byte `json:"data"` }{} - if err := json.Unmarshal(bs, &req); err != nil { + if err := jsonv1.Unmarshal(bs, &req); err != nil { panic(fmt.Sprintf("json decode failed: %v. Body:\n\n%s", err, string(bs))) } for key, val := range req.Data { @@ -1555,7 +1555,7 @@ func mustBase64(t *testing.T, v any) string { } func mustJSON(t *testing.T, v any) []byte { - b, err := json.Marshal(v) + b, err := jsonv1.Marshal(v) if err != nil { t.Fatalf("error converting %v to json: %v", v, err) } diff --git a/cmd/containerboot/serve.go b/cmd/containerboot/serve.go index 5fa8e580d..0d94fd56c 100644 --- a/cmd/containerboot/serve.go +++ b/cmd/containerboot/serve.go @@ -8,7 +8,7 @@ package main import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "log" "os" "path/filepath" @@ -164,7 +164,7 @@ func readServeConfig(path, certDomain string) (*ipn.ServeConfig, error) { } j = bytes.ReplaceAll(j, []byte("${TS_CERT_DOMAIN}"), []byte(certDomain)) var sc ipn.ServeConfig - if err := json.Unmarshal(j, &sc); err != nil { + if err := jsonv1.Unmarshal(j, &sc); err != nil { return nil, err } return &sc, nil diff --git a/cmd/derper/bootstrap_dns.go b/cmd/derper/bootstrap_dns.go index a58f040ba..db7af42b4 100644 --- a/cmd/derper/bootstrap_dns.go +++ b/cmd/derper/bootstrap_dns.go @@ -6,7 +6,7 @@ package main import ( "context" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "expvar" "log" "math/rand/v2" @@ -75,7 +75,7 @@ func refreshBootstrapDNS() { for _, vv := range dnsEntries.IPs { slicesx.Shuffle(vv) } - j, err := json.MarshalIndent(dnsEntries.IPs, "", "\t") + j, err := jsonv1.MarshalIndent(dnsEntries.IPs, "", "\t") if err != nil { // leave the old values in place return @@ -156,7 +156,7 @@ func handleBootstrapDNS(w http.ResponseWriter, r *http.Request) { if remoteAddrMatchesPercent(r.RemoteAddr, percent) { // Only return the specific query, not everything. m := map[string][]net.IP{q: m.IPs[q]} - j, err := json.MarshalIndent(m, "", "\t") + j, err := jsonv1.MarshalIndent(m, "", "\t") if err == nil { w.Write(j) return diff --git a/cmd/derper/bootstrap_dns_test.go b/cmd/derper/bootstrap_dns_test.go index 9b99103ab..ae70c2298 100644 --- a/cmd/derper/bootstrap_dns_test.go +++ b/cmd/derper/bootstrap_dns_test.go @@ -5,7 +5,7 @@ package main import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "io" "net" "net/http" @@ -53,7 +53,7 @@ func getBootstrapDNS(t *testing.T, q string) map[string][]net.IP { } var m map[string][]net.IP var buf bytes.Buffer - if err := json.NewDecoder(io.TeeReader(res.Body, &buf)).Decode(&m); err != nil { + if err := jsonv1.NewDecoder(io.TeeReader(res.Body, &buf)).Decode(&m); err != nil { t.Fatalf("error decoding response body %q: %v", buf.Bytes(), err) } return m diff --git a/cmd/derper/cert.go b/cmd/derper/cert.go index b95755c64..b0e583adb 100644 --- a/cmd/derper/cert.go +++ b/cmd/derper/cert.go @@ -11,7 +11,7 @@ import ( "crypto/tls" "crypto/x509" "crypto/x509/pkix" - "encoding/json" + jsonv1 "encoding/json" "encoding/pem" "errors" "fmt" @@ -107,7 +107,7 @@ func NewManualCertManager(certdir, hostname string) (certProvider, error) { HostName: hostname, CertName: fmt.Sprintf("sha256-raw:%-02x", sha256.Sum256(x509Cert.Raw)), } - dnJSON, _ := json.Marshal(dn) + dnJSON, _ := jsonv1.Marshal(dn) log.Printf("Using self-signed certificate for IP address %q. Configure it in DERPMap using: (https://tailscale.com/s/custom-derp)\n %s", hostname, dnJSON) } return &manualCertManager{ diff --git a/cmd/derper/derper.go b/cmd/derper/derper.go index 857d7def3..3582c2584 100644 --- a/cmd/derper/derper.go +++ b/cmd/derper/derper.go @@ -14,7 +14,7 @@ import ( "cmp" "context" "crypto/tls" - "encoding/json" + jsonv1 "encoding/json" "errors" "expvar" "flag" @@ -133,7 +133,7 @@ func loadConfig() config { panic("unreachable") default: var cfg config - if err := json.Unmarshal(b, &cfg); err != nil { + if err := jsonv1.Unmarshal(b, &cfg); err != nil { log.Fatalf("derper: config: %v", err) } return cfg @@ -148,7 +148,7 @@ func writeNewConfig() config { cfg := config{ PrivateKey: k, } - b, err := json.MarshalIndent(cfg, "", "\t") + b, err := jsonv1.MarshalIndent(cfg, "", "\t") if err != nil { log.Fatal(err) } diff --git a/cmd/gitops-pusher/cache.go b/cmd/gitops-pusher/cache.go index 6792e5e63..681541738 100644 --- a/cmd/gitops-pusher/cache.go +++ b/cmd/gitops-pusher/cache.go @@ -4,7 +4,7 @@ package main import ( - "encoding/json" + jsonv1 "encoding/json" "os" ) @@ -38,7 +38,7 @@ func (c *Cache) Save(fname string) error { } defer fout.Close() - return json.NewEncoder(fout).Encode(c) + return jsonv1.NewEncoder(fout).Encode(c) } // LoadCache loads the cache from a given file. @@ -51,7 +51,7 @@ func LoadCache(fname string) (*Cache, error) { } defer fin.Close() - err = json.NewDecoder(fin).Decode(&result) + err = jsonv1.NewDecoder(fin).Decode(&result) if err != nil { return nil, err } diff --git a/cmd/gitops-pusher/gitops-pusher.go b/cmd/gitops-pusher/gitops-pusher.go index 690ca2870..8a6059626 100644 --- a/cmd/gitops-pusher/gitops-pusher.go +++ b/cmd/gitops-pusher/gitops-pusher.go @@ -10,7 +10,7 @@ import ( "bytes" "context" "crypto/sha256" - "encoding/json" + jsonv1 "encoding/json" "flag" "fmt" "io" @@ -288,7 +288,7 @@ func applyNewACL(ctx context.Context, client *http.Client, tailnet, apiKey, poli want := http.StatusOK if got != want { var ate ACLGitopsTestError - err := json.NewDecoder(resp.Body).Decode(&ate) + err := jsonv1.NewDecoder(resp.Body).Decode(&ate) if err != nil { return err } @@ -324,7 +324,7 @@ func testNewACLs(ctx context.Context, client *http.Client, tailnet, apiKey, poli defer resp.Body.Close() var ate ACLGitopsTestError - err = json.NewDecoder(resp.Body).Decode(&ate) + err = jsonv1.NewDecoder(resp.Body).Decode(&ate) if err != nil { return err } diff --git a/cmd/gitops-pusher/gitops-pusher_test.go b/cmd/gitops-pusher/gitops-pusher_test.go index e08b06c9c..72453ee05 100644 --- a/cmd/gitops-pusher/gitops-pusher_test.go +++ b/cmd/gitops-pusher/gitops-pusher_test.go @@ -4,7 +4,7 @@ package main import ( - "encoding/json" + jsonv1 "encoding/json" "strings" "testing" @@ -31,9 +31,9 @@ func TestEmbeddedTypeUnmarshal(t *testing.T) { } t.Run("unmarshal gitops type from acl type", func(t *testing.T) { - b, _ := json.Marshal(aclTestErr) + b, _ := jsonv1.Marshal(aclTestErr) var e ACLGitopsTestError - err := json.Unmarshal(b, &e) + err := jsonv1.Unmarshal(b, &e) if err != nil { t.Fatal(err) } @@ -42,9 +42,9 @@ func TestEmbeddedTypeUnmarshal(t *testing.T) { } }) t.Run("unmarshal acl type from gitops type", func(t *testing.T) { - b, _ := json.Marshal(gitopsErr) + b, _ := jsonv1.Marshal(gitopsErr) var e tailscale.ACLTestError - err := json.Unmarshal(b, &e) + err := jsonv1.Unmarshal(b, &e) if err != nil { t.Fatal(err) } diff --git a/cmd/hello/hello.go b/cmd/hello/hello.go index fa116b28b..4256c9786 100644 --- a/cmd/hello/hello.go +++ b/cmd/hello/hello.go @@ -8,7 +8,7 @@ import ( "context" "crypto/tls" _ "embed" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "html/template" @@ -41,7 +41,7 @@ func main() { if err != nil { log.Fatal(err) } - e := json.NewEncoder(os.Stdout) + e := jsonv1.NewEncoder(os.Stdout) e.SetIndent("", "\t") e.Encode(res) return diff --git a/cmd/jsonimports/format.go b/cmd/jsonimports/format.go index 6dbd17558..b29859fcf 100644 --- a/cmd/jsonimports/format.go +++ b/cmd/jsonimports/format.go @@ -43,7 +43,9 @@ func mustFormatFile(in []byte) (out []byte) { "github.com/go-json-experiment/json", "github.com/go-json-experiment/json/v1", "github.com/go-json-experiment/json/jsontext": - jsonImports[pkgPath] = append(jsonImports[pkgPath], imp) + if imp.Name.String() != "_" { + jsonImports[pkgPath] = append(jsonImports[pkgPath], imp) + } } } if len(jsonImports) == 0 { diff --git a/cmd/jsonimports/jsonimports.go b/cmd/jsonimports/jsonimports.go index 4be2e10cb..8307ba195 100644 --- a/cmd/jsonimports/jsonimports.go +++ b/cmd/jsonimports/jsonimports.go @@ -60,8 +60,23 @@ import ( "tailscale.com/util/safediff" ) +type ignoreList []string + +func (s *ignoreList) String() string { + return strings.Join(*s, ",") +} + +func (s *ignoreList) Set(value string) error { + for v := range strings.SplitSeq(value, ",") { + *s = append(*s, strings.TrimSpace(v)) + } + return nil +} + func main() { + var ignore ignoreList update := flag.Bool("update", false, "update all Go source files") + flag.Var(&ignore, "ignore", "files and directories to ignore (may be repeated)") flag.Parse() // Change working directory to Git repository root. @@ -87,6 +102,13 @@ func main() { return } + // Ignore files that match the ignore prefixes. + for _, prefix := range ignore { + if strings.HasPrefix(file, prefix) { + return + } + } + // Format all "json" imports in the Go source file. srcIn := must.Get(os.ReadFile(file)) srcOut := mustFormatFile(srcIn) @@ -118,7 +140,11 @@ func main() { if numDiffs > 0 && !*update { fmt.Printf(`%d files with "json" imports that need formatting`+"\n", numDiffs) fmt.Println("Please run:") - fmt.Println("\t./tool/go run tailscale.com/cmd/jsonimports -update") + var ignoreFlags string + for _, path := range ignore { + ignoreFlags += " -ignore=" + path + } + fmt.Println("\t./tool/go run tailscale.com/cmd/jsonimports -update" + ignoreFlags) os.Exit(1) } } diff --git a/cmd/k8s-nameserver/main.go b/cmd/k8s-nameserver/main.go index 84e65452d..1d886dd77 100644 --- a/cmd/k8s-nameserver/main.go +++ b/cmd/k8s-nameserver/main.go @@ -10,7 +10,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "log" "net" @@ -240,7 +240,7 @@ func (n *nameserver) resetRecords() error { return nil } dnsCfg := &operatorutils.Records{} - err = json.Unmarshal(dnsCfgBytes, dnsCfg) + err = jsonv1.Unmarshal(dnsCfgBytes, dnsCfg) if err != nil { return fmt.Errorf("error unmarshalling nameserver configuration: %v\n", err) } diff --git a/cmd/k8s-operator/api-server-proxy-pg.go b/cmd/k8s-operator/api-server-proxy-pg.go index 252859eb3..52abedf5b 100644 --- a/cmd/k8s-operator/api-server-proxy-pg.go +++ b/cmd/k8s-operator/api-server-proxy-pg.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "maps" @@ -392,7 +392,7 @@ func (r *KubeAPIServerTSServiceReconciler) maybeAdvertiseServices(ctx context.Co } // Update the config Secret. - cfgB, err := json.Marshal(conf.VersionedConfig{ + cfgB, err := jsonv1.Marshal(conf.VersionedConfig{ Version: "v1alpha1", ConfigV1Alpha1: &cfg.Parsed, }) @@ -437,7 +437,7 @@ func exclusiveOwnerAnnotations(pg *tsapi.ProxyGroup, operatorID string, svc *tai } if svc == nil { c := ownerAnnotationValue{OwnerRefs: []OwnerRef{ref}} - json, err := json.Marshal(c) + json, err := jsonv1.Marshal(c) if err != nil { return nil, fmt.Errorf("[unexpected] unable to marshal Tailscale Service's owner annotation contents: %w, please report this", err) } @@ -466,7 +466,7 @@ func exclusiveOwnerAnnotations(pg *tsapi.ProxyGroup, operatorID string, svc *tai o.OwnerRefs[0].Resource.Name = pg.Name } - oBytes, err := json.Marshal(o) + oBytes, err := jsonv1.Marshal(o) if err != nil { return nil, err } diff --git a/cmd/k8s-operator/api-server-proxy-pg_test.go b/cmd/k8s-operator/api-server-proxy-pg_test.go index dfef63f22..0912e858d 100644 --- a/cmd/k8s-operator/api-server-proxy-pg_test.go +++ b/cmd/k8s-operator/api-server-proxy-pg_test.go @@ -4,7 +4,7 @@ package main import ( - "encoding/json" + jsonv1 "encoding/json" "reflect" "strings" "testing" @@ -64,7 +64,7 @@ func TestAPIServerProxyReconciler(t *testing.T) { }, } expectedCfg := *initialCfg - initialCfgB, err := json.Marshal(initialCfg) + initialCfgB, err := jsonv1.Marshal(initialCfg) if err != nil { t.Fatalf("marshaling initial config: %v", err) } @@ -86,7 +86,7 @@ func TestAPIServerProxyReconciler(t *testing.T) { Build() expectCfg := func(c *conf.VersionedConfig) { t.Helper() - cBytes, err := json.Marshal(c) + cBytes, err := jsonv1.Marshal(c) if err != nil { t.Fatalf("marshaling expected config: %v", err) } diff --git a/cmd/k8s-operator/dnsrecords.go b/cmd/k8s-operator/dnsrecords.go index 1a9395aa0..213481cf2 100644 --- a/cmd/k8s-operator/dnsrecords.go +++ b/cmd/k8s-operator/dnsrecords.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "slices" "strings" @@ -314,12 +314,12 @@ func (dnsRR *dnsRecordsReconciler) updateDNSConfig(ctx context.Context, update f } dnsRecords := operatorutils.Records{Version: operatorutils.Alpha1Version, IP4: map[string][]string{}} if cm.Data != nil && cm.Data[operatorutils.DNSRecordsCMKey] != "" { - if err := json.Unmarshal([]byte(cm.Data[operatorutils.DNSRecordsCMKey]), &dnsRecords); err != nil { + if err := jsonv1.Unmarshal([]byte(cm.Data[operatorutils.DNSRecordsCMKey]), &dnsRecords); err != nil { return err } } update(&dnsRecords) - dnsRecordsBs, err := json.Marshal(dnsRecords) + dnsRecordsBs, err := jsonv1.Marshal(dnsRecords) if err != nil { return fmt.Errorf("error marshalling DNS records: %w", err) } diff --git a/cmd/k8s-operator/dnsrecords_test.go b/cmd/k8s-operator/dnsrecords_test.go index 13898078f..f1bea541a 100644 --- a/cmd/k8s-operator/dnsrecords_test.go +++ b/cmd/k8s-operator/dnsrecords_test.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "testing" @@ -469,7 +469,7 @@ func expectHostsRecords(t *testing.T, cl client.Client, wantsHosts map[string][] t.Fatal("dnsconfig ConfigMap does not contain dnsconfig") } dnsConfig := &operatorutils.Records{} - if err := json.Unmarshal([]byte(dnsConfigString), dnsConfig); err != nil { + if err := jsonv1.Unmarshal([]byte(dnsConfigString), dnsConfig); err != nil { t.Fatalf("unmarshaling dnsconfig: %v", err) } if diff := cmp.Diff(dnsConfig.IP4, wantsHosts); diff != "" { @@ -491,7 +491,7 @@ func expectHostsRecordsWithIPv6(t *testing.T, cl client.Client, wantsHostsIPv4, t.Fatal("dnsconfig ConfigMap does not contain dnsconfig") } dnsConfig := &operatorutils.Records{} - if err := json.Unmarshal([]byte(dnsConfigString), dnsConfig); err != nil { + if err := jsonv1.Unmarshal([]byte(dnsConfigString), dnsConfig); err != nil { t.Fatalf("unmarshaling dnsconfig: %v", err) } if diff := cmp.Diff(dnsConfig.IP4, wantsHostsIPv4); diff != "" { diff --git a/cmd/k8s-operator/e2e/proxy_test.go b/cmd/k8s-operator/e2e/proxy_test.go index b3010f97e..ab733d233 100644 --- a/cmd/k8s-operator/e2e/proxy_test.go +++ b/cmd/k8s-operator/e2e/proxy_test.go @@ -4,7 +4,7 @@ package e2e import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "testing" "time" @@ -99,7 +99,7 @@ func hostNameFromOperatorSecret(t *testing.T, s corev1.Secret) string { } prefs := ipn.Prefs{} - if err := json.Unmarshal(prefsBytes, &prefs); err != nil { + if err := jsonv1.Unmarshal(prefsBytes, &prefs); err != nil { t.Fatal(err) } diff --git a/cmd/k8s-operator/egress-eps.go b/cmd/k8s-operator/egress-eps.go index 3441e12ba..f99ce2dfb 100644 --- a/cmd/k8s-operator/egress-eps.go +++ b/cmd/k8s-operator/egress-eps.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/netip" "reflect" @@ -189,7 +189,7 @@ func (er *egressEpsReconciler) podIsReadyToRouteTraffic(ctx context.Context, pod return false, nil } svcStatus := &egressservices.Status{} - if err := json.Unmarshal(svcStatusBS, svcStatus); err != nil { + if err := jsonv1.Unmarshal(svcStatusBS, svcStatus); err != nil { return false, fmt.Errorf("error unmarshalling egress service status: %w", err) } if !strings.EqualFold(podIP, svcStatus.PodIPv4) { diff --git a/cmd/k8s-operator/egress-eps_test.go b/cmd/k8s-operator/egress-eps_test.go index bd80112ae..dabf57af6 100644 --- a/cmd/k8s-operator/egress-eps_test.go +++ b/cmd/k8s-operator/egress-eps_test.go @@ -6,7 +6,7 @@ package main import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "math/rand/v2" "testing" @@ -144,7 +144,7 @@ func configMapForSvc(t *testing.T, svc *corev1.Service, p uint16) *corev1.Config } name := tailnetSvcName(svc) cfgs := egressservices.Configs{name: cfg} - bs, err := json.Marshal(&cfgs) + bs, err := jsonv1.Marshal(&cfgs) if err != nil { t.Fatalf("error marshalling config: %v", err) } @@ -176,7 +176,7 @@ func serviceStatusForPodIP(t *testing.T, svc *corev1.Service, ip string, p uint1 PodIPv4: ip, Services: map[string]*egressservices.ServiceStatus{svcName: &svcSt}, } - bs, err := json.Marshal(st) + bs, err := jsonv1.Marshal(st) if err != nil { t.Fatalf("error marshalling service status: %v", err) } diff --git a/cmd/k8s-operator/egress-services.go b/cmd/k8s-operator/egress-services.go index ca6562071..0bf267f12 100644 --- a/cmd/k8s-operator/egress-services.go +++ b/cmd/k8s-operator/egress-services.go @@ -8,7 +8,7 @@ package main import ( "context" "crypto/sha256" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "math/rand/v2" @@ -352,7 +352,7 @@ func (esr *egressSvcsReconciler) provision(ctx context.Context, proxyGroupName s if !reflect.DeepEqual(gotCfg, wantsCfg) { l.Debugf("updating egress services ConfigMap %s", cm.Name) mak.Set(cfgs, tailnetSvc, wantsCfg) - bs, err := json.Marshal(cfgs) + bs, err := jsonv1.Marshal(cfgs) if err != nil { return nil, false, fmt.Errorf("error marshalling egress services configs: %w", err) } @@ -485,7 +485,7 @@ func (esr *egressSvcsReconciler) ensureEgressSvcCfgDeleted(ctx context.Context, return nil } cfgs := &egressservices.Configs{} - if err := json.Unmarshal(bs, cfgs); err != nil { + if err := jsonv1.Unmarshal(bs, cfgs); err != nil { return fmt.Errorf("error unmarshalling egress services configs") } tailnetSvc := tailnetSvcName(svc) @@ -497,7 +497,7 @@ func (esr *egressSvcsReconciler) ensureEgressSvcCfgDeleted(ctx context.Context, l.Infof("before deleting config %+#v", *cfgs) delete(*cfgs, tailnetSvc) l.Infof("after deleting config %+#v", *cfgs) - bs, err := json.Marshal(cfgs) + bs, err := jsonv1.Marshal(cfgs) if err != nil { return fmt.Errorf("error marshalling egress services configs: %w", err) } @@ -665,7 +665,7 @@ func egressSvcsConfigs(ctx context.Context, cl client.Client, proxyGroupName, ts } cfgs = &egressservices.Configs{} if len(cm.BinaryData[egressservices.KeyEgressServices]) != 0 { - if err := json.Unmarshal(cm.BinaryData[egressservices.KeyEgressServices], cfgs); err != nil { + if err := jsonv1.Unmarshal(cm.BinaryData[egressservices.KeyEgressServices], cfgs); err != nil { return nil, nil, fmt.Errorf("error unmarshaling egress services config %v: %w", cm.BinaryData[egressservices.KeyEgressServices], err) } } @@ -715,7 +715,7 @@ func svcConfigurationUpToDate(svc *corev1.Service, l *zap.SugaredLogger) bool { } func cfgHash(c cfg, l *zap.SugaredLogger) string { - bs, err := json.Marshal(c) + bs, err := jsonv1.Marshal(c) if err != nil { // Don't use l.Error as that messes up component logs with, in this case, unnecessary stack trace. l.Infof("error marhsalling Config: %v", err) diff --git a/cmd/k8s-operator/egress-services_test.go b/cmd/k8s-operator/egress-services_test.go index d8a5dfd32..74395ca03 100644 --- a/cmd/k8s-operator/egress-services_test.go +++ b/cmd/k8s-operator/egress-services_test.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "testing" @@ -284,7 +284,7 @@ func configFromCM(t *testing.T, cm *corev1.ConfigMap, svcName string) *egressser return nil } cfgs := &egressservices.Configs{} - if err := json.Unmarshal(cfgBs, cfgs); err != nil { + if err := jsonv1.Unmarshal(cfgBs, cfgs); err != nil { t.Fatalf("error unmarshalling config: %v", err) } cfg, ok := (*cfgs)[svcName] diff --git a/cmd/k8s-operator/ingress-for-pg.go b/cmd/k8s-operator/ingress-for-pg.go index 3afeb528f..a23acec0a 100644 --- a/cmd/k8s-operator/ingress-for-pg.go +++ b/cmd/k8s-operator/ingress-for-pg.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "math/rand/v2" @@ -303,7 +303,7 @@ func (r *HAIngressReconciler) maybeProvision(ctx context.Context, hostname strin if !reflect.DeepEqual(gotCfg, ingCfg) { logger.Infof("Updating serve config") mak.Set(&cfg.Services, serviceName, ingCfg) - cfgBytes, err := json.Marshal(cfg) + cfgBytes, err := jsonv1.Marshal(cfg) if err != nil { return false, fmt.Errorf("error marshaling serve config: %w", err) } @@ -488,7 +488,7 @@ func (r *HAIngressReconciler) maybeCleanupProxyGroup(ctx context.Context, proxyG } if serveConfigChanged { - cfgBytes, err := json.Marshal(cfg) + cfgBytes, err := jsonv1.Marshal(cfg) if err != nil { return false, fmt.Errorf("marshaling serve config: %w", err) } @@ -573,7 +573,7 @@ func (r *HAIngressReconciler) maybeCleanup(ctx context.Context, hostname string, // 5. Remove the Tailscale Service from the serve config for the ProxyGroup. logger.Infof("Removing TailscaleService %q from serve config for ProxyGroup %q", hostname, pg) delete(cfg.Services, serviceName) - cfgBytes, err := json.Marshal(cfg) + cfgBytes, err := jsonv1.Marshal(cfg) if err != nil { return false, fmt.Errorf("error marshaling serve config: %w", err) } @@ -622,7 +622,7 @@ func (r *HAIngressReconciler) proxyGroupServeConfig(ctx context.Context, pg stri } cfg = &ipn.ServeConfig{} if len(cm.BinaryData[serveConfigKey]) != 0 { - if err := json.Unmarshal(cm.BinaryData[serveConfigKey], cfg); err != nil { + if err := jsonv1.Unmarshal(cm.BinaryData[serveConfigKey], cfg); err != nil { return nil, nil, fmt.Errorf("error unmarshaling ingress serve config %v: %w", cm.BinaryData[serveConfigKey], err) } } @@ -733,7 +733,7 @@ func (r *HAIngressReconciler) cleanupTailscaleService(ctx context.Context, svc * } o.OwnerRefs = slices.Delete(o.OwnerRefs, ix, ix+1) logger.Infof("Deleting Tailscale Service %q", svc.Name) - json, err := json.Marshal(o) + json, err := jsonv1.Marshal(o) if err != nil { return false, fmt.Errorf("error marshalling updated Tailscale Service owner reference: %w", err) } @@ -784,7 +784,7 @@ func (a *HAIngressReconciler) maybeUpdateAdvertiseServicesConfig(ctx context.Con var updated bool for fileName, confB := range secret.Data { var conf ipn.ConfigVAlpha - if err := json.Unmarshal(confB, &conf); err != nil { + if err := jsonv1.Unmarshal(confB, &conf); err != nil { return fmt.Errorf("error unmarshalling ProxyGroup config: %w", err) } @@ -804,7 +804,7 @@ func (a *HAIngressReconciler) maybeUpdateAdvertiseServicesConfig(ctx context.Con } // Update the Secret. - confB, err := json.Marshal(conf) + confB, err := jsonv1.Marshal(conf) if err != nil { return fmt.Errorf("error marshalling ProxyGroup config: %w", err) } @@ -880,7 +880,7 @@ func ownerAnnotations(operatorID string, svc *tailscale.VIPService) (map[string] } if svc == nil { c := ownerAnnotationValue{OwnerRefs: []OwnerRef{ref}} - json, err := json.Marshal(c) + json, err := jsonv1.Marshal(c) if err != nil { return nil, fmt.Errorf("[unexpected] unable to marshal Tailscale Service's owner annotation contents: %w, please report this", err) } @@ -902,7 +902,7 @@ func ownerAnnotations(operatorID string, svc *tailscale.VIPService) (map[string] return nil, fmt.Errorf("Tailscale Service %s is owned by another resource: %#v; cannot be reused for an Ingress", svc.Name, o.OwnerRefs[0].Resource) } o.OwnerRefs = append(o.OwnerRefs, ref) - json, err := json.Marshal(o) + json, err := jsonv1.Marshal(o) if err != nil { return nil, fmt.Errorf("error marshalling updated owner references: %w", err) } @@ -921,7 +921,7 @@ func parseOwnerAnnotation(tsSvc *tailscale.VIPService) (*ownerAnnotationValue, e return nil, nil } o := &ownerAnnotationValue{} - if err := json.Unmarshal([]byte(tsSvc.Annotations[ownerAnnotation]), o); err != nil { + if err := jsonv1.Unmarshal([]byte(tsSvc.Annotations[ownerAnnotation]), o); err != nil { return nil, fmt.Errorf("error parsing Tailscale Service's %s annotation %q: %w", ownerAnnotation, tsSvc.Annotations[ownerAnnotation], err) } return o, nil diff --git a/cmd/k8s-operator/ingress-for-pg_test.go b/cmd/k8s-operator/ingress-for-pg_test.go index 77e5ecb37..e7eb1b3e6 100644 --- a/cmd/k8s-operator/ingress-for-pg_test.go +++ b/cmd/k8s-operator/ingress-for-pg_test.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "maps" "reflect" @@ -166,7 +166,7 @@ func TestIngressPGReconciler(t *testing.T) { } cfg := &ipn.ServeConfig{} - if err := json.Unmarshal(cm.BinaryData[serveConfigKey], cfg); err != nil { + if err := jsonv1.Unmarshal(cm.BinaryData[serveConfigKey], cfg); err != nil { t.Fatalf("unmarshaling serve config: %v", err) } @@ -215,7 +215,7 @@ func TestIngressPGReconciler(t *testing.T) { } cfg = &ipn.ServeConfig{} - if err := json.Unmarshal(cm.BinaryData[serveConfigKey], cfg); err != nil { + if err := jsonv1.Unmarshal(cm.BinaryData[serveConfigKey], cfg); err != nil { t.Fatalf("unmarshaling serve config: %v", err) } @@ -771,7 +771,7 @@ func verifyServeConfig(t *testing.T, fc client.Client, serviceName string, wantH } cfg := &ipn.ServeConfig{} - if err := json.Unmarshal(cm.BinaryData["serve-config.json"], cfg); err != nil { + if err := jsonv1.Unmarshal(cm.BinaryData["serve-config.json"], cfg); err != nil { t.Fatalf("unmarshaling serve config: %v", err) } @@ -814,7 +814,7 @@ func verifyTailscaledConfig(t *testing.T, fc client.Client, pgName string, expec t.Helper() var expected string if expectedServices != nil && len(expectedServices) > 0 { - expectedServicesJSON, err := json.Marshal(expectedServices) + expectedServicesJSON, err := jsonv1.Marshal(expectedServices) if err != nil { t.Fatalf("marshaling expected services: %v", err) } diff --git a/cmd/k8s-operator/nameserver_test.go b/cmd/k8s-operator/nameserver_test.go index 6da52d8a2..77e20f3f1 100644 --- a/cmd/k8s-operator/nameserver_test.go +++ b/cmd/k8s-operator/nameserver_test.go @@ -9,7 +9,7 @@ package main import ( - "encoding/json" + jsonv1 "encoding/json" "testing" "time" @@ -150,7 +150,7 @@ func TestNameserverReconciler(t *testing.T) { // Verify that when another actor sets ConfigMap data, it does not get // overwritten by nameserver reconciler. dnsRecords := &operatorutils.Records{Version: "v1alpha1", IP4: map[string][]string{"foo.ts.net": {"1.2.3.4"}}} - bs, err := json.Marshal(dnsRecords) + bs, err := jsonv1.Marshal(dnsRecords) if err != nil { t.Fatalf("error marshalling ConfigMap contents: %v", err) } diff --git a/cmd/k8s-operator/operator_test.go b/cmd/k8s-operator/operator_test.go index 5af237342..4e4b6b9db 100644 --- a/cmd/k8s-operator/operator_test.go +++ b/cmd/k8s-operator/operator_test.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "testing" "time" @@ -1282,7 +1282,7 @@ func TestServiceProxyClassAnnotation(t *testing.T) { slist := &corev1.SecretList{} fc.List(context.Background(), slist, client.InNamespace("operator-ns")) for _, i := range slist.Items { - l, _ := json.Marshal(i.Labels) + l, _ := jsonv1.Marshal(i.Labels) t.Logf("found secret %q with labels %q ", i.Name, string(l)) } diff --git a/cmd/k8s-operator/proxygroup.go b/cmd/k8s-operator/proxygroup.go index 946e017a2..a65d40a4b 100644 --- a/cmd/k8s-operator/proxygroup.go +++ b/cmd/k8s-operator/proxygroup.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "net/http" @@ -796,7 +796,7 @@ func (r *ProxyGroupReconciler) ensureConfigSecretsCreated(ctx context.Context, p } if !deviceAuthed { existingCfg := conf.ConfigV1Alpha1{} - if err := json.Unmarshal(existingCfgSecret.Data[kubetypes.KubeAPIServerConfigFile], &existingCfg); err != nil { + if err := jsonv1.Unmarshal(existingCfgSecret.Data[kubetypes.KubeAPIServerConfigFile], &existingCfg); err != nil { return nil, fmt.Errorf("error unmarshalling existing config: %w", err) } if existingCfg.AuthKey != nil { @@ -835,7 +835,7 @@ func (r *ProxyGroupReconciler) ensureConfigSecretsCreated(ctx context.Context, p if existingCfgSecret != nil { if k8sProxyCfg, ok := cfgSecret.Data[kubetypes.KubeAPIServerConfigFile]; ok { k8sCfg := &conf.ConfigV1Alpha1{} - if err := json.Unmarshal(k8sProxyCfg, k8sCfg); err != nil { + if err := jsonv1.Unmarshal(k8sProxyCfg, k8sCfg); err != nil { return nil, fmt.Errorf("failed to unmarshal kube-apiserver config: %w", err) } @@ -862,7 +862,7 @@ func (r *ProxyGroupReconciler) ensureConfigSecretsCreated(ctx context.Context, p cfg.StaticEndpoints = endpoints[nodePortSvcName] } - cfgB, err := json.Marshal(cfg) + cfgB, err := jsonv1.Marshal(cfg) if err != nil { return nil, fmt.Errorf("error marshalling k8s-proxy config: %w", err) } @@ -881,7 +881,7 @@ func (r *ProxyGroupReconciler) ensureConfigSecretsCreated(ctx context.Context, p } for cap, cfg := range configs { - cfgJSON, err := json.Marshal(cfg) + cfgJSON, err := jsonv1.Marshal(cfg) if err != nil { return nil, fmt.Errorf("error marshalling tailscaled config: %w", err) } @@ -923,7 +923,7 @@ func (r *ProxyGroupReconciler) findStaticEndpoints(ctx context.Context, existing oldConfB := existingCfgSecret.Data[tsoperator.TailscaledConfigFileName(106)] if len(oldConfB) > 0 { var oldConf ipn.ConfigVAlpha - if err := json.Unmarshal(oldConfB, &oldConf); err == nil { + if err := jsonv1.Unmarshal(oldConfB, &oldConf); err == nil { currAddrs = oldConf.StaticEndpoints } else { logger.Debugf("failed to unmarshal tailscaled config from secret %q: %v", existingCfgSecret.Name, err) @@ -1150,7 +1150,7 @@ func (r *ProxyGroupReconciler) getRunningProxies(ctx context.Context, pg *tsapi. if ipsB := m.stateSecret.Data[kubetypes.KeyDeviceIPs]; len(ipsB) > 0 { ips := []string{} - if err := json.Unmarshal(ipsB, &ips); err != nil { + if err := jsonv1.Unmarshal(ipsB, &ips); err != nil { return nil, fmt.Errorf("failed to extract device IPs from state Secret %q: %w", m.stateSecret.Name, err) } device.TailnetIPs = ips diff --git a/cmd/k8s-operator/proxygroup_test.go b/cmd/k8s-operator/proxygroup_test.go index 2bcc9fb7a..835d23264 100644 --- a/cmd/k8s-operator/proxygroup_test.go +++ b/cmd/k8s-operator/proxygroup_test.go @@ -6,7 +6,7 @@ package main import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/netip" "slices" @@ -705,7 +705,7 @@ func TestProxyGroupWithStaticEndpoints(t *testing.T) { config := &ipn.ConfigVAlpha{} foundConfig := false for _, d := range sec.Data { - if err := json.Unmarshal(d, config); err == nil { + if err := jsonv1.Unmarshal(d, config); err == nil { foundConfig = true break } @@ -1383,7 +1383,7 @@ func TestKubeAPIServerType_DoesNotOverwriteServicesConfig(t *testing.T) { HealthCheckEnabled: opt.NewBool(true), }, } - cfgB, err := json.Marshal(cfg) + cfgB, err := jsonv1.Marshal(cfg) if err != nil { t.Fatalf("failed to marshal config: %v", err) } @@ -1405,7 +1405,7 @@ func TestKubeAPIServerType_DoesNotOverwriteServicesConfig(t *testing.T) { // then check the proxygroup reconciler doesn't overwrite it. cfg.APIServerProxy.ServiceName = ptr.To(tailcfg.ServiceName("svc:some-svc-name")) cfg.AdvertiseServices = []string{"svc:should-not-be-overwritten"} - cfgB, err = json.Marshal(cfg) + cfgB, err = jsonv1.Marshal(cfg) if err != nil { t.Fatalf("failed to marshal config: %v", err) } @@ -1433,7 +1433,7 @@ func TestIngressAdvertiseServicesConfigPreserved(t *testing.T) { } existingServices := []string{"svc1", "svc2"} - existingConfigBytes, err := json.Marshal(ipn.ConfigVAlpha{ + existingConfigBytes, err := jsonv1.Marshal(ipn.ConfigVAlpha{ AdvertiseServices: existingServices, Version: "should-get-overwritten", }) @@ -1464,7 +1464,7 @@ func TestIngressAdvertiseServicesConfigPreserved(t *testing.T) { }) expectReconciled(t, reconciler, "", pgName) - expectedConfigBytes, err := json.Marshal(ipn.ConfigVAlpha{ + expectedConfigBytes, err := jsonv1.Marshal(ipn.ConfigVAlpha{ // Preserved. AdvertiseServices: existingServices, @@ -1802,7 +1802,7 @@ func addNodeIDToStateSecrets(t *testing.T, fc client.WithWatch, pg *tsapi.ProxyG t.Helper() const key = "profile-abc" for i := range pgReplicas(pg) { - bytes, err := json.Marshal(map[string]any{ + bytes, err := jsonv1.Marshal(map[string]any{ "Config": map[string]any{ "NodeID": fmt.Sprintf("nodeid-%d", i), }, diff --git a/cmd/k8s-operator/sts.go b/cmd/k8s-operator/sts.go index c52ffce85..bf6bbbd91 100644 --- a/cmd/k8s-operator/sts.go +++ b/cmd/k8s-operator/sts.go @@ -8,7 +8,7 @@ package main import ( "context" _ "embed" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "net/http" @@ -417,7 +417,7 @@ func (a *tailscaleSTSReconciler) provisionSecrets(ctx context.Context, logger *z var latestConfig ipn.ConfigVAlpha for key, val := range configs { fn := tsoperator.TailscaledConfigFileName(key) - b, err := json.Marshal(val) + b, err := jsonv1.Marshal(val) if err != nil { return nil, fmt.Errorf("error marshalling tailscaled config: %w", err) } @@ -430,7 +430,7 @@ func (a *tailscaleSTSReconciler) provisionSecrets(ctx context.Context, logger *z } if stsC.ServeConfig != nil { - j, err := json.Marshal(stsC.ServeConfig) + j, err := jsonv1.Marshal(stsC.ServeConfig) if err != nil { return nil, err } @@ -585,7 +585,7 @@ func deviceInfo(sec *corev1.Secret, podUID string, log *zap.SugaredLogger) (dev } if rawDeviceIPs, ok := sec.Data[kubetypes.KeyDeviceIPs]; ok { ips := make([]string, 0) - if err := json.Unmarshal(rawDeviceIPs, &ips); err != nil { + if err := jsonv1.Unmarshal(rawDeviceIPs, &ips); err != nil { return nil, err } dev.ips = ips @@ -1091,7 +1091,7 @@ func latestConfigFromSecret(s *corev1.Secret) (*ipn.ConfigVAlpha, error) { var conf *ipn.ConfigVAlpha if latestStr != "" { conf = &ipn.ConfigVAlpha{} - if err := json.Unmarshal([]byte(s.Data[latestStr]), conf); err != nil { + if err := jsonv1.Unmarshal([]byte(s.Data[latestStr]), conf); err != nil { return nil, fmt.Errorf("error unmarshaling tailscaled config from Secret %q in field %q: %w", s.Name, latestStr, err) } } diff --git a/cmd/k8s-operator/svc-for-pg.go b/cmd/k8s-operator/svc-for-pg.go index 62cc36bd4..acc6b0078 100644 --- a/cmd/k8s-operator/svc-for-pg.go +++ b/cmd/k8s-operator/svc-for-pg.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "net/http" @@ -317,7 +317,7 @@ func (r *HAServiceReconciler) maybeProvision(ctx context.Context, hostname strin existingCfg := cfgs[serviceName.String()] if !reflect.DeepEqual(existingCfg, cfg) { mak.Set(&cfgs, serviceName.String(), cfg) - cfgBytes, err := json.Marshal(cfgs) + cfgBytes, err := jsonv1.Marshal(cfgs) if err != nil { return false, fmt.Errorf("error marshaling ingress config: %w", err) } @@ -417,7 +417,7 @@ func (r *HAServiceReconciler) maybeCleanup(ctx context.Context, hostname string, } logger.Infof("Removing Tailscale Service %q from ingress config for ProxyGroup %q", hostname, pgName) delete(cfgs, serviceName.String()) - cfgBytes, err := json.Marshal(cfgs) + cfgBytes, err := jsonv1.Marshal(cfgs) if err != nil { return false, fmt.Errorf("error marshaling ingress config: %w", err) } @@ -470,7 +470,7 @@ func (r *HAServiceReconciler) maybeCleanupProxyGroup(ctx context.Context, proxyG } if ingressConfigChanged { - configBytes, err := json.Marshal(config) + configBytes, err := jsonv1.Marshal(config) if err != nil { return false, fmt.Errorf("marshaling serve config: %w", err) } @@ -573,7 +573,7 @@ func cleanupTailscaleService(ctx context.Context, tsClient tsClient, name tailcf } o.OwnerRefs = slices.Delete(o.OwnerRefs, ix, ix+1) logger.Infof("Updating Tailscale Service %q", name) - json, err := json.Marshal(o) + json, err := jsonv1.Marshal(o) if err != nil { return false, fmt.Errorf("error marshalling updated Tailscale Service owner reference: %w", err) } @@ -606,7 +606,7 @@ func (a *HAServiceReconciler) backendRoutesSetup(ctx context.Context, serviceNam } gotCfgB := secret.Data[ingressservices.IngressConfigKey] var gotCfgs ingressservices.Status - if err := json.Unmarshal(gotCfgB, &gotCfgs); err != nil { + if err := jsonv1.Unmarshal(gotCfgB, &gotCfgs); err != nil { return false, fmt.Errorf("error unmarshalling ingress config: %w", err) } statusUpToDate, err := isCurrentStatus(gotCfgs, pod, logger) @@ -668,7 +668,7 @@ func (a *HAServiceReconciler) maybeUpdateAdvertiseServicesConfig(ctx context.Con var updated bool for fileName, confB := range secret.Data { var conf ipn.ConfigVAlpha - if err := json.Unmarshal(confB, &conf); err != nil { + if err := jsonv1.Unmarshal(confB, &conf); err != nil { return fmt.Errorf("error unmarshalling ProxyGroup config: %w", err) } @@ -701,7 +701,7 @@ func (a *HAServiceReconciler) maybeUpdateAdvertiseServicesConfig(ctx context.Con conf.AdvertiseServices = append(conf.AdvertiseServices, serviceName.String()) } - confB, err := json.Marshal(conf) + confB, err := jsonv1.Marshal(conf) if err != nil { return fmt.Errorf("error marshalling ProxyGroup config: %w", err) } @@ -770,7 +770,7 @@ func ingressSvcsConfigs(ctx context.Context, cl client.Client, proxyGroupName, t } cfgs = ingressservices.Configs{} if len(cm.BinaryData[ingressservices.IngressConfigKey]) != 0 { - if err := json.Unmarshal(cm.BinaryData[ingressservices.IngressConfigKey], &cfgs); err != nil { + if err := jsonv1.Unmarshal(cm.BinaryData[ingressservices.IngressConfigKey], &cfgs); err != nil { return nil, nil, fmt.Errorf("error unmarshaling ingress services config %v: %w", cm.BinaryData[ingressservices.IngressConfigKey], err) } } diff --git a/cmd/k8s-operator/svc-for-pg_test.go b/cmd/k8s-operator/svc-for-pg_test.go index baaa07727..03130147d 100644 --- a/cmd/k8s-operator/svc-for-pg_test.go +++ b/cmd/k8s-operator/svc-for-pg_test.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "math/rand/v2" "net/netip" @@ -67,7 +67,7 @@ func TestServicePGReconciler(t *testing.T) { } cfgs := ingressservices.Configs{} - if err := json.Unmarshal(cm.BinaryData[ingressservices.IngressConfigKey], &cfgs); err != nil { + if err := jsonv1.Unmarshal(cm.BinaryData[ingressservices.IngressConfigKey], &cfgs); err != nil { t.Fatalf("unmarshaling serve config: %v", err) } @@ -368,7 +368,7 @@ func updateIngressConfigSecret(t *testing.T, fc client.Client, stateSecret *core PodIPv4: "4.3.2.1", } - icJson, err := json.Marshal(ingressStatus) + icJson, err := jsonv1.Marshal(ingressStatus) if err != nil { t.Fatalf("failed to json marshal ingress config: %s", err.Error()) } diff --git a/cmd/k8s-operator/testutils_test.go b/cmd/k8s-operator/testutils_test.go index b4c468c8e..92e4f9d7d 100644 --- a/cmd/k8s-operator/testutils_test.go +++ b/cmd/k8s-operator/testutils_test.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/http" "net/netip" @@ -501,7 +501,7 @@ func expectedSecret(t *testing.T, cl client.Client, opts configOpts) *corev1.Sec }, } if opts.serveConfig != nil { - serveConfigBs, err := json.Marshal(opts.serveConfig) + serveConfigBs, err := jsonv1.Marshal(opts.serveConfig) if err != nil { t.Fatalf("error marshalling serve config: %v", err) } @@ -548,12 +548,12 @@ func expectedSecret(t *testing.T, cl client.Client, opts configOpts) *corev1.Sec } } conf.AdvertiseRoutes = routes - bnn, err := json.Marshal(conf) + bnn, err := jsonv1.Marshal(conf) if err != nil { t.Fatalf("error marshalling tailscaled config") } conf.AppConnector = nil - bn, err := json.Marshal(conf) + bn, err := jsonv1.Marshal(conf) if err != nil { t.Fatalf("error marshalling tailscaled config") } @@ -897,11 +897,11 @@ func removeAuthKeyIfExistsModifier(t *testing.T) func(s *corev1.Secret) { t.Helper() if len(secret.StringData["cap-95.hujson"]) != 0 { conf := &ipn.ConfigVAlpha{} - if err := json.Unmarshal([]byte(secret.StringData["cap-95.hujson"]), conf); err != nil { + if err := jsonv1.Unmarshal([]byte(secret.StringData["cap-95.hujson"]), conf); err != nil { t.Fatalf("error umarshalling 'cap-95.hujson' contents: %v", err) } conf.AuthKey = nil - b, err := json.Marshal(conf) + b, err := jsonv1.Marshal(conf) if err != nil { t.Fatalf("error marshalling 'cap-95.huson' contents: %v", err) } @@ -909,11 +909,11 @@ func removeAuthKeyIfExistsModifier(t *testing.T) func(s *corev1.Secret) { } if len(secret.StringData["cap-107.hujson"]) != 0 { conf := &ipn.ConfigVAlpha{} - if err := json.Unmarshal([]byte(secret.StringData["cap-107.hujson"]), conf); err != nil { + if err := jsonv1.Unmarshal([]byte(secret.StringData["cap-107.hujson"]), conf); err != nil { t.Fatalf("error umarshalling 'cap-107.hujson' contents: %v", err) } conf.AuthKey = nil - b, err := json.Marshal(conf) + b, err := jsonv1.Marshal(conf) if err != nil { t.Fatalf("error marshalling 'cap-107.huson' contents: %v", err) } diff --git a/cmd/k8s-operator/tsrecorder.go b/cmd/k8s-operator/tsrecorder.go index c922f78fe..dcc6b24d9 100644 --- a/cmd/k8s-operator/tsrecorder.go +++ b/cmd/k8s-operator/tsrecorder.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "net/http" @@ -433,7 +433,7 @@ func getDevicePrefs(secret *corev1.Secret) (prefs prefs, ok bool, err error) { if !ok { return prefs, false, nil } - if err := json.Unmarshal(profileBytes, &prefs); err != nil { + if err := jsonv1.Unmarshal(profileBytes, &prefs); err != nil { return prefs, false, fmt.Errorf("failed to extract node profile info from state Secret %s: %w", secret.Name, err) } diff --git a/cmd/k8s-operator/tsrecorder_test.go b/cmd/k8s-operator/tsrecorder_test.go index 184af2344..76d255ec5 100644 --- a/cmd/k8s-operator/tsrecorder_test.go +++ b/cmd/k8s-operator/tsrecorder_test.go @@ -7,7 +7,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "strings" "testing" @@ -180,7 +180,7 @@ func TestRecorder(t *testing.T) { }) t.Run("populate_node_info_in_state_secret_and_see_it_appear_in_status", func(t *testing.T) { - bytes, err := json.Marshal(map[string]any{ + bytes, err := jsonv1.Marshal(map[string]any{ "Config": map[string]any{ "NodeID": "nodeid-123", "UserProfile": map[string]any{ diff --git a/cmd/natc/ippool/consensusippool.go b/cmd/natc/ippool/consensusippool.go index 64807b6c2..5fb77ffa8 100644 --- a/cmd/natc/ippool/consensusippool.go +++ b/cmd/natc/ippool/consensusippool.go @@ -5,7 +5,7 @@ package ippool import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "log" @@ -68,7 +68,7 @@ func (ipp *ConsensusIPPool) IPForDomain(nid tailcfg.NodeID, domain string) (neti ReuseDeadline: now.Add(-1 * ipp.unusedAddressLifetime), UpdatedAt: now, } - bs, err := json.Marshal(args) + bs, err := jsonv1.Marshal(args) if err != nil { return netip.Addr{}, err } @@ -86,7 +86,7 @@ func (ipp *ConsensusIPPool) IPForDomain(nid tailcfg.NodeID, domain string) (neti return netip.Addr{}, result.Err } var addr netip.Addr - err = json.Unmarshal(result.Result, &addr) + err = jsonv1.Unmarshal(result.Result, &addr) return addr, err } @@ -230,7 +230,7 @@ type readDomainForIPArgs struct { // executeReadDomainForIP parses a readDomainForIP log entry and applies it. func (ipp *ConsensusIPPool) executeReadDomainForIP(bs []byte) tsconsensus.CommandResult { var args readDomainForIPArgs - err := json.Unmarshal(bs, &args) + err := jsonv1.Unmarshal(bs, &args) if err != nil { return tsconsensus.CommandResult{Err: err} } @@ -249,7 +249,7 @@ func (ipp *ConsensusIPPool) applyReadDomainForIP(from tailcfg.NodeID, addr netip } return ww.Domain }() - resultBs, err := json.Marshal(domain) + resultBs, err := jsonv1.Marshal(domain) return tsconsensus.CommandResult{Result: resultBs, Err: err} } @@ -259,7 +259,7 @@ func (ipp *ConsensusIPPool) readDomainForIP(nid tailcfg.NodeID, addr netip.Addr) NodeID: nid, Addr: addr, } - bs, err := json.Marshal(args) + bs, err := jsonv1.Marshal(args) if err != nil { return "", err } @@ -277,7 +277,7 @@ func (ipp *ConsensusIPPool) readDomainForIP(nid tailcfg.NodeID, addr netip.Addr) return "", result.Err } var domain string - err = json.Unmarshal(result.Result, &domain) + err = jsonv1.Unmarshal(result.Result, &domain) return domain, err } @@ -291,7 +291,7 @@ type markLastUsedArgs struct { // executeMarkLastUsed parses a markLastUsed log entry and applies it. func (ipp *ConsensusIPPool) executeMarkLastUsed(bs []byte) tsconsensus.CommandResult { var args markLastUsedArgs - err := json.Unmarshal(bs, &args) + err := jsonv1.Unmarshal(bs, &args) if err != nil { return tsconsensus.CommandResult{Err: err} } @@ -339,7 +339,7 @@ func (ipp *ConsensusIPPool) markLastUsed(nid tailcfg.NodeID, addr netip.Addr, do Domain: domain, UpdatedAt: lastUsed, } - bs, err := json.Marshal(args) + bs, err := jsonv1.Marshal(args) if err != nil { return err } @@ -369,7 +369,7 @@ type checkoutAddrArgs struct { // executeCheckoutAddr parses a checkoutAddr raft log entry and applies it. func (ipp *ConsensusIPPool) executeCheckoutAddr(bs []byte) tsconsensus.CommandResult { var args checkoutAddrArgs - err := json.Unmarshal(bs, &args) + err := jsonv1.Unmarshal(bs, &args) if err != nil { return tsconsensus.CommandResult{Err: err} } @@ -377,7 +377,7 @@ func (ipp *ConsensusIPPool) executeCheckoutAddr(bs []byte) tsconsensus.CommandRe if err != nil { return tsconsensus.CommandResult{Err: err} } - resultBs, err := json.Marshal(addr) + resultBs, err := jsonv1.Marshal(addr) if err != nil { return tsconsensus.CommandResult{Err: err} } @@ -424,7 +424,7 @@ func (ipp *ConsensusIPPool) applyCheckoutAddr(nid tailcfg.NodeID, domain string, // Apply is part of the raft.FSM interface. It takes an incoming log entry and applies it to the state. func (ipp *ConsensusIPPool) Apply(l *raft.Log) any { var c tsconsensus.Command - if err := json.Unmarshal(l.Data, &c); err != nil { + if err := jsonv1.Unmarshal(l.Data, &c); err != nil { panic(fmt.Sprintf("failed to unmarshal command: %s", err.Error())) } switch c.Name { diff --git a/cmd/natc/ippool/consensusippool_test.go b/cmd/natc/ippool/consensusippool_test.go index 242cdffaf..4d24c195e 100644 --- a/cmd/natc/ippool/consensusippool_test.go +++ b/cmd/natc/ippool/consensusippool_test.go @@ -5,7 +5,7 @@ package ippool import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" "net/netip" @@ -30,7 +30,7 @@ type FakeConsensus struct { } func (c *FakeConsensus) ExecuteCommand(cmd tsconsensus.Command) (tsconsensus.CommandResult, error) { - b, err := json.Marshal(cmd) + b, err := jsonv1.Marshal(cmd) if err != nil { return tsconsensus.CommandResult{}, err } @@ -345,7 +345,7 @@ func TestConsensusRestore(t *testing.T) { } // restore the snapshot - bs, err := json.Marshal(snap) + bs, err := jsonv1.Marshal(snap) if err != nil { t.Fatal(err) } diff --git a/cmd/natc/ippool/consensusippoolserialize.go b/cmd/natc/ippool/consensusippoolserialize.go index 97dc02f2c..5f2b82471 100644 --- a/cmd/natc/ippool/consensusippoolserialize.go +++ b/cmd/natc/ippool/consensusippoolserialize.go @@ -4,7 +4,7 @@ package ippool import ( - "encoding/json" + jsonv1 "encoding/json" "io" "log" "maps" @@ -73,7 +73,7 @@ func (mipr *persistableIPRange) toIPRange() netipx.IPRange { // - the FSM must discard all previous state before restoring func (ipp *ConsensusIPPool) Restore(rc io.ReadCloser) error { var snap fsmSnapshot - if err := json.NewDecoder(rc).Decode(&snap); err != nil { + if err := jsonv1.NewDecoder(rc).Decode(&snap); err != nil { return err } ipset, ppm, err := snap.getData() @@ -93,7 +93,7 @@ type fsmSnapshot struct { // Persist is part of the raft.FSMSnapshot interface // According to the docs Persist may be called concurrently with Apply func (f fsmSnapshot) Persist(sink raft.SnapshotSink) error { - if err := json.NewEncoder(sink).Encode(f); err != nil { + if err := jsonv1.NewEncoder(sink).Encode(f); err != nil { log.Printf("Error encoding snapshot as JSON: %v", err) return sink.Cancel() } diff --git a/cmd/natc/natc.go b/cmd/natc/natc.go index a4f53d657..93258c365 100644 --- a/cmd/natc/natc.go +++ b/cmd/natc/natc.go @@ -8,7 +8,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "expvar" "flag" @@ -652,7 +652,7 @@ func httpClusterAdmin(ipp *ippool.ConsensusIPPool) http.Handler { http.Error(w, "", http.StatusInternalServerError) return } - if err := json.NewEncoder(w).Encode(c); err != nil { + if err := jsonv1.NewEncoder(w).Encode(c); err != nil { log.Printf("cluster admin http: error encoding raft configuration: %v", err) } }) @@ -664,7 +664,7 @@ func httpClusterAdmin(ipp *ippool.ConsensusIPPool) http.Handler { http.Error(w, err.Error(), http.StatusInternalServerError) return } - if err := json.NewEncoder(w).Encode(idx); err != nil { + if err := jsonv1.NewEncoder(w).Encode(idx); err != nil { log.Printf("cluster admin http: error encoding delete index: %v", err) return } diff --git a/cmd/netlogfmt/main.go b/cmd/netlogfmt/main.go index 65e87098f..f948d00d7 100644 --- a/cmd/netlogfmt/main.go +++ b/cmd/netlogfmt/main.go @@ -27,7 +27,7 @@ package main import ( "cmp" "encoding/base64" - "encoding/json" + jsonv1 "encoding/json" "flag" "fmt" "io" @@ -305,7 +305,7 @@ func mustMakeNamesByAddr() map[netip.Addr]string { Addrs []netip.Addr `json:"addresses"` } `json:"devices"` } - must.Do(json.Unmarshal(b, &m)) + must.Do(jsonv1.Unmarshal(b, &m)) // Construct a unique mapping of Tailscale IP addresses to hostnames. // For brevity, we start with the first segment of the name and diff --git a/cmd/sniproxy/sniproxy_test.go b/cmd/sniproxy/sniproxy_test.go index cd2e070bd..2efe040e3 100644 --- a/cmd/sniproxy/sniproxy_test.go +++ b/cmd/sniproxy/sniproxy_test.go @@ -5,7 +5,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "flag" "fmt" "log" @@ -144,7 +144,7 @@ func TestSNIProxyWithNetmapConfig(t *testing.T) { }, }, } - b, err := json.Marshal(config) + b, err := jsonv1.Marshal(config) if err != nil { t.Fatal(err) } diff --git a/cmd/stunstamp/stunstamp.go b/cmd/stunstamp/stunstamp.go index 71ed50569..91ec81797 100644 --- a/cmd/stunstamp/stunstamp.go +++ b/cmd/stunstamp/stunstamp.go @@ -9,7 +9,7 @@ import ( "cmp" "context" "crypto/tls" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -80,7 +80,7 @@ func getDERPMap(ctx context.Context, url string) (*tailcfg.DERPMap, error) { return nil, fmt.Errorf("non-200 derp map resp: %d", resp.StatusCode) } dm := tailcfg.DERPMap{} - err = json.NewDecoder(resp.Body).Decode(&dm) + err = jsonv1.NewDecoder(resp.Body).Decode(&dm) if err != nil { return nil, fmt.Errorf("failed to decode derp map resp: %v", err) } diff --git a/cmd/tailscale/cli/appcroutes.go b/cmd/tailscale/cli/appcroutes.go index 4a1ba87e3..2317415ba 100644 --- a/cmd/tailscale/cli/appcroutes.go +++ b/cmd/tailscale/cli/appcroutes.go @@ -5,7 +5,7 @@ package cli import ( "context" - "encoding/json" + jsonv1 "encoding/json" "flag" "fmt" "slices" @@ -52,11 +52,11 @@ https://tailscale.com/kb/1281/app-connectors } func getAllOutput(ri *appctype.RouteInfo) (string, error) { - domains, err := json.MarshalIndent(ri.Domains, " ", " ") + domains, err := jsonv1.MarshalIndent(ri.Domains, " ", " ") if err != nil { return "", err } - control, err := json.MarshalIndent(ri.Control, " ", " ") + control, err := jsonv1.MarshalIndent(ri.Control, " ", " ") if err != nil { return "", err } @@ -131,7 +131,7 @@ func runAppcRoutesInfo(ctx context.Context, args []string) error { } if appcRoutesArgs.domainMap { - domains, err := json.Marshal(routeInfo.Domains) + domains, err := jsonv1.Marshal(routeInfo.Domains) if err != nil { return err } diff --git a/cmd/tailscale/cli/cli.go b/cmd/tailscale/cli/cli.go index 5ebc23a5b..591eefa57 100644 --- a/cmd/tailscale/cli/cli.go +++ b/cmd/tailscale/cli/cli.go @@ -7,7 +7,7 @@ package cli import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -505,7 +505,7 @@ type flagDoc struct { func printJSONDocs(root *ffcli.Command) error { docs := jsonDocsWalk(root) - return json.NewEncoder(os.Stdout).Encode(docs) + return jsonv1.NewEncoder(os.Stdout).Encode(docs) } func jsonDocsWalk(cmd *ffcli.Command) *commandDoc { diff --git a/cmd/tailscale/cli/cli_test.go b/cmd/tailscale/cli/cli_test.go index 2e1bec8c9..efdc395a1 100644 --- a/cmd/tailscale/cli/cli_test.go +++ b/cmd/tailscale/cli/cli_test.go @@ -6,7 +6,7 @@ package cli import ( "bytes" stdcmp "cmp" - "encoding/json" + jsonv1 "encoding/json" "flag" "fmt" "io" @@ -905,8 +905,8 @@ func TestPrefsFromUpArgs(t *testing.T) { t.Fatal("tt.want is nil") } if !got.Equals(tt.want) { - jgot, _ := json.MarshalIndent(got, "", "\t") - jwant, _ := json.MarshalIndent(tt.want, "", "\t") + jgot, _ := jsonv1.MarshalIndent(got, "", "\t") + jwant, _ := jsonv1.MarshalIndent(tt.want, "", "\t") if bytes.Equal(jgot, jwant) { t.Logf("prefs differ only in non-JSON-visible ways (nil/non-nil zero-length arrays)") } diff --git a/cmd/tailscale/cli/configure-synology-cert.go b/cmd/tailscale/cli/configure-synology-cert.go index b5168ef92..b3ca8caec 100644 --- a/cmd/tailscale/cli/configure-synology-cert.go +++ b/cmd/tailscale/cli/configure-synology-cert.go @@ -7,7 +7,7 @@ package cli import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -153,7 +153,7 @@ func listCerts(ctx context.Context, c synoAPICaller) ([]certificateInfo, error) var payload struct { Certificates []certificateInfo `json:"certificates"` } - if err := json.Unmarshal(rawData, &payload); err != nil { + if err := jsonv1.Unmarshal(rawData, &payload); err != nil { return nil, fmt.Errorf("decoding certificate list response payload: %w", err) } @@ -179,7 +179,7 @@ func uploadCert(ctx context.Context, c synoAPICaller, certFile, keyFile string, var payload struct { NewID string `json:"id"` } - if err := json.Unmarshal(rawData, &payload); err != nil { + if err := jsonv1.Unmarshal(rawData, &payload); err != nil { return fmt.Errorf("decoding certificate upload response payload: %w", err) } log.Printf("Tailnet Certificate uploaded with ID %q.", payload.NewID) @@ -189,13 +189,13 @@ func uploadCert(ctx context.Context, c synoAPICaller, certFile, keyFile string, } type synoAPICaller interface { - Call(context.Context, string, string, map[string]string) (json.RawMessage, error) + Call(context.Context, string, string, map[string]string) (jsonv1.RawMessage, error) } type apiResponse struct { - Success bool `json:"success"` - Error *apiError `json:"error,omitempty"` - Data json.RawMessage `json:"data"` + Success bool `json:"success"` + Error *apiError `json:"error,omitempty"` + Data jsonv1.RawMessage `json:"data"` } type apiError struct { @@ -206,7 +206,7 @@ type apiError struct { // synowebapiCommand implements synoAPICaller using the /usr/syno/bin/synowebapi binary. Must be run as root. type synowebapiCommand struct{} -func (s synowebapiCommand) Call(ctx context.Context, api, method string, params map[string]string) (json.RawMessage, error) { +func (s synowebapiCommand) Call(ctx context.Context, api, method string, params map[string]string) (jsonv1.RawMessage, error) { args := []string{"--exec", fmt.Sprintf("api=%s", api), fmt.Sprintf("method=%s", method)} for k, v := range params { @@ -219,7 +219,7 @@ func (s synowebapiCommand) Call(ctx context.Context, api, method string, params } var payload apiResponse - if err := json.Unmarshal(out, &payload); err != nil { + if err := jsonv1.Unmarshal(out, &payload); err != nil { return nil, fmt.Errorf("decoding response json from %q method of %q API: %w", method, api, err) } diff --git a/cmd/tailscale/cli/configure-synology-cert_test.go b/cmd/tailscale/cli/configure-synology-cert_test.go index c7da5622f..1fb3fab2a 100644 --- a/cmd/tailscale/cli/configure-synology-cert_test.go +++ b/cmd/tailscale/cli/configure-synology-cert_test.go @@ -7,18 +7,18 @@ package cli import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "reflect" "testing" ) type fakeAPICaller struct { - Data json.RawMessage + Data jsonv1.RawMessage Error error } -func (c fakeAPICaller) Call(_ context.Context, _, _ string, _ map[string]string) (json.RawMessage, error) { +func (c fakeAPICaller) Call(_ context.Context, _, _ string, _ map[string]string) (jsonv1.RawMessage, error) { return c.Data, c.Error } @@ -32,7 +32,7 @@ func Test_listCerts(t *testing.T) { { name: "normal response", caller: fakeAPICaller{ - Data: json.RawMessage(`{ + Data: jsonv1.RawMessage(`{ "certificates" : [ { "desc" : "Tailnet Certificate", @@ -123,7 +123,7 @@ func Test_listCerts(t *testing.T) { }, { name: "payload decode error", - caller: fakeAPICaller{json.RawMessage("This isn't JSON!"), nil}, + caller: fakeAPICaller{jsonv1.RawMessage("This isn't JSON!"), nil}, wantErr: true, }, } diff --git a/cmd/tailscale/cli/debug.go b/cmd/tailscale/cli/debug.go index 2836ae298..532a2efc8 100644 --- a/cmd/tailscale/cli/debug.go +++ b/cmd/tailscale/cli/debug.go @@ -9,7 +9,7 @@ import ( "cmp" "context" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -387,7 +387,7 @@ func runGoBuildInfo(ctx context.Context, args []string) error { if !ok { return errors.New("no Go build info") } - e := json.NewEncoder(os.Stdout) + e := jsonv1.NewEncoder(os.Stdout) e.SetIndent("", "\t") return e.Encode(bi) } @@ -453,7 +453,7 @@ func runDebug(ctx context.Context, args []string) error { if err != nil { fatalf("%v\n", err) } - e := json.NewEncoder(Stdout) + e := jsonv1.NewEncoder(Stdout) e.SetIndent("", "\t") e.Encode(wfs) return nil @@ -607,7 +607,7 @@ func runPrefs(ctx context.Context, args []string) error { if prefsArgs.pretty { outln(prefs.Pretty()) } else { - j, _ := json.MarshalIndent(prefs, "", "\t") + j, _ := jsonv1.MarshalIndent(prefs, "", "\t") outln(string(j)) } return nil @@ -646,7 +646,7 @@ func runWatchIPN(ctx context.Context, args []string) error { if !watchIPNArgs.netmap { n.NetMap = nil } - j, _ := json.MarshalIndent(n, "", "\t") + j, _ := jsonv1.MarshalIndent(n, "", "\t") fmt.Printf("%s\n", j) } return nil @@ -674,7 +674,7 @@ func runNetmap(ctx context.Context, args []string) error { if err != nil { return err } - j, _ := json.MarshalIndent(n.NetMap, "", "\t") + j, _ := jsonv1.MarshalIndent(n.NetMap, "", "\t") fmt.Printf("%s\n", j) return nil } @@ -686,7 +686,7 @@ func runDERPMap(ctx context.Context, args []string) error { "failed to get local derp map, instead `curl %s/derpmap/default`: %w", ipn.DefaultControlURL, err, ) } - enc := json.NewEncoder(Stdout) + enc := jsonv1.NewEncoder(Stdout) enc.SetIndent("", "\t") enc.Encode(dm) return nil @@ -701,7 +701,7 @@ func forcePreferDERP(ctx context.Context, args []string) error { if err != nil { return fmt.Errorf("expected exactly one integer argument: %w", err) } - b, err := json.Marshal(n) + b, err := jsonv1.Marshal(n) if err != nil { return fmt.Errorf("failed to marshal DERP region: %w", err) } @@ -765,7 +765,7 @@ func runStat(ctx context.Context, args []string) error { func runHostinfo(ctx context.Context, args []string) error { hi := hostinfo.New() - j, _ := json.MarshalIndent(hi, "", " ") + j, _ := jsonv1.MarshalIndent(hi, "", " ") Stdout.Write(j) return nil } @@ -789,7 +789,7 @@ func runDaemonLogs(ctx context.Context, args []string) error { if err != nil { return err } - d := json.NewDecoder(logs) + d := jsonv1.NewDecoder(logs) for { var line struct { Text string `json:"text"` @@ -837,7 +837,7 @@ func runDaemonBusGraph(ctx context.Context, args []string) error { } if daemonBusGraphArgs.format == "dot" { var topics eventbus.DebugTopics - if err := json.Unmarshal(graph, &topics); err != nil { + if err := jsonv1.Unmarshal(graph, &topics); err != nil { return fmt.Errorf("unable to parse json: %w", err) } fmt.Print(generateDOTGraph(topics.Topics)) @@ -1019,7 +1019,7 @@ func runTS2021(ctx context.Context, args []string) error { log.Printf("Status: %v", res.Status) return errors.New(res.Status) } - if err := json.NewDecoder(res.Body).Decode(&keys); err != nil { + if err := jsonv1.NewDecoder(res.Body).Decode(&keys); err != nil { log.Printf("JSON: %v", err) return fmt.Errorf("decoding /keys JSON: %w", err) } @@ -1061,7 +1061,7 @@ func runTS2021(ctx context.Context, args []string) error { return fmt.Errorf("reading dial plan JSON file: %w", err) } dialPlan = new(tailcfg.ControlDialPlan) - if err := json.Unmarshal(b, dialPlan); err != nil { + if err := jsonv1.Unmarshal(b, dialPlan); err != nil { return fmt.Errorf("unmarshaling dial plan JSON file: %w", err) } } else if ts2021Args.aceHost != "" { @@ -1203,7 +1203,7 @@ func runDebugDERP(ctx context.Context, args []string) error { if err != nil { return err } - fmt.Printf("%s\n", must.Get(json.MarshalIndent(st, "", " "))) + fmt.Printf("%s\n", must.Get(jsonv1.MarshalIndent(st, "", " "))) return nil } @@ -1265,7 +1265,7 @@ func runPeerEndpointChanges(ctx context.Context, args []string) error { } var dst bytes.Buffer - if err := json.Indent(&dst, body, "", " "); err != nil { + if err := jsonv1.Indent(&dst, body, "", " "); err != nil { return fmt.Errorf("indenting returned JSON: %w", err) } @@ -1284,7 +1284,7 @@ func debugControlKnobs(ctx context.Context, args []string) error { if err != nil { return err } - e := json.NewEncoder(os.Stdout) + e := jsonv1.NewEncoder(os.Stdout) e.SetIndent("", " ") e.Encode(v) return nil @@ -1379,7 +1379,7 @@ func runPeerRelayServers(ctx context.Context, args []string) error { if err != nil { return err } - e := json.NewEncoder(os.Stdout) + e := jsonv1.NewEncoder(os.Stdout) e.SetIndent("", " ") e.Encode(v) return nil diff --git a/cmd/tailscale/cli/netcheck.go b/cmd/tailscale/cli/netcheck.go index 5ae8db8fa..823cbcd8c 100644 --- a/cmd/tailscale/cli/netcheck.go +++ b/cmd/tailscale/cli/netcheck.go @@ -5,7 +5,7 @@ package cli import ( "context" - "encoding/json" + jsonv1 "encoding/json" "flag" "fmt" "io" @@ -135,9 +135,9 @@ func printReport(dm *tailcfg.DERPMap, report *netcheck.Report) error { switch netcheckArgs.format { case "": case "json": - j, err = json.MarshalIndent(report, "", "\t") + j, err = jsonv1.MarshalIndent(report, "", "\t") case "json-line": - j, err = json.Marshal(report) + j, err = jsonv1.Marshal(report) default: return fmt.Errorf("unknown output format %q", netcheckArgs.format) } @@ -256,7 +256,7 @@ func prodDERPMap(ctx context.Context, httpc *http.Client) (*tailcfg.DERPMap, err return nil, fmt.Errorf("fetch prodDERPMap: %v: %s", res.Status, b) } var derpMap tailcfg.DERPMap - if err = json.Unmarshal(b, &derpMap); err != nil { + if err = jsonv1.Unmarshal(b, &derpMap); err != nil { return nil, fmt.Errorf("fetch prodDERPMap: %w", err) } return &derpMap, nil diff --git a/cmd/tailscale/cli/network-lock.go b/cmd/tailscale/cli/network-lock.go index a15d9ab88..78b823d3b 100644 --- a/cmd/tailscale/cli/network-lock.go +++ b/cmd/tailscale/cli/network-lock.go @@ -10,7 +10,7 @@ import ( "context" "crypto/rand" "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -219,7 +219,7 @@ func runNetworkLockStatus(ctx context.Context, args []string) error { } if nlStatusArgs.json { - enc := json.NewEncoder(os.Stdout) + enc := jsonv1.NewEncoder(os.Stdout) enc.SetIndent("", " ") return enc.Encode(st) } @@ -678,7 +678,7 @@ func nlDescribeUpdate(update ipnstate.NetworkLockUpdate, color bool) (string, er default: // Print a JSON encoding of the AUM as a fallback. - e := json.NewEncoder(&stanza) + e := jsonv1.NewEncoder(&stanza) e.SetIndent("", "\t") if err := e.Encode(aum); err != nil { return "", err @@ -703,7 +703,7 @@ func runNetworkLockLog(ctx context.Context, args []string) error { return fixTailscaledConnectError(err) } if nlLogArgs.json { - enc := json.NewEncoder(Stdout) + enc := jsonv1.NewEncoder(Stdout) enc.SetIndent("", " ") return enc.Encode(updates) } diff --git a/cmd/tailscale/cli/serve_legacy.go b/cmd/tailscale/cli/serve_legacy.go index 5c2d8eefa..f81184f95 100644 --- a/cmd/tailscale/cli/serve_legacy.go +++ b/cmd/tailscale/cli/serve_legacy.go @@ -7,7 +7,7 @@ package cli import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -238,7 +238,7 @@ func (e *serveEnv) runServe(ctx context.Context, args []string) error { return err } sc := new(ipn.ServeConfig) - if err := json.Unmarshal(valb, sc); err != nil { + if err := jsonv1.Unmarshal(valb, sc); err != nil { return fmt.Errorf("invalid JSON: %w", err) } return e.lc.SetServeConfig(ctx, sc) @@ -617,7 +617,7 @@ func (e *serveEnv) runServeStatus(ctx context.Context, args []string) error { return err } if e.json { - j, err := json.MarshalIndent(sc, "", " ") + j, err := jsonv1.MarshalIndent(sc, "", " ") if err != nil { return err } diff --git a/cmd/tailscale/cli/serve_v2.go b/cmd/tailscale/cli/serve_v2.go index 74458a950..6970819b9 100644 --- a/cmd/tailscale/cli/serve_v2.go +++ b/cmd/tailscale/cli/serve_v2.go @@ -7,7 +7,7 @@ package cli import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -368,7 +368,7 @@ func (e *serveEnv) runServeCombined(subcmd serveMode) execFunc { return err } sc := new(ipn.ServeConfig) - if err := json.Unmarshal(valb, sc); err != nil { + if err := jsonv1.Unmarshal(valb, sc); err != nil { return fmt.Errorf("invalid JSON: %w", err) } return e.lc.SetServeConfig(ctx, sc) @@ -755,7 +755,7 @@ func (e *serveEnv) runServeGetConfig(ctx context.Context, args []string) (err er } mak.Set(&scf.Services, svcName, sdf) } - j, err = json.MarshalIndent(scf, "", " ") + j, err = jsonv1.MarshalIndent(scf, "", " ") if err != nil { return err } @@ -769,7 +769,7 @@ func (e *serveEnv) runServeGetConfig(ctx context.Context, args []string) (err er return err } sdf.Version = "0.0.1" - j, err = json.MarshalIndent(sdf, "", " ") + j, err = jsonv1.MarshalIndent(sdf, "", " ") if err != nil { return err } diff --git a/cmd/tailscale/cli/serve_v2_test.go b/cmd/tailscale/cli/serve_v2_test.go index 7f7f2c37c..a5a8fb4f0 100644 --- a/cmd/tailscale/cli/serve_v2_test.go +++ b/cmd/tailscale/cli/serve_v2_test.go @@ -6,7 +6,7 @@ package cli import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/netip" "os" @@ -966,8 +966,8 @@ func TestServeDevConfigMutations(t *testing.T) { got = lc.config } if !reflect.DeepEqual(got, st.want) { - gotbts, _ := json.MarshalIndent(got, "", "\t") - wantbts, _ := json.MarshalIndent(st.want, "", "\t") + gotbts, _ := jsonv1.MarshalIndent(got, "", "\t") + wantbts, _ := jsonv1.MarshalIndent(st.want, "", "\t") t.Fatalf("step: %d, cmd: %v, diff:\n%s", i, st.command, cmp.Diff(string(gotbts), string(wantbts))) } @@ -1484,7 +1484,7 @@ func TestMessageForPort(t *testing.T) { netip.MustParseAddr("fd7a:115c:a1e0:ab12:4843:cd96:6565:6565"), }, } - svcIPMapJSON, _ := json.Marshal(svcIPMap) + svcIPMapJSON, _ := jsonv1.Marshal(svcIPMap) svcIPMapJSONRawMSG := tailcfg.RawMessage(svcIPMapJSON) tests := []struct { diff --git a/cmd/tailscale/cli/status.go b/cmd/tailscale/cli/status.go index 89b18335b..5c9f9f6e2 100644 --- a/cmd/tailscale/cli/status.go +++ b/cmd/tailscale/cli/status.go @@ -6,7 +6,7 @@ package cli import ( "cmp" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -94,7 +94,7 @@ func runStatus(ctx context.Context, args []string) error { } } } - j, err := json.MarshalIndent(st, "", " ") + j, err := jsonv1.MarshalIndent(st, "", " ") if err != nil { return err } diff --git a/cmd/tailscale/cli/syspolicy.go b/cmd/tailscale/cli/syspolicy.go index 97f3f2122..07fb1e6ea 100644 --- a/cmd/tailscale/cli/syspolicy.go +++ b/cmd/tailscale/cli/syspolicy.go @@ -7,7 +7,7 @@ package cli import ( "context" - "encoding/json" + jsonv1 "encoding/json" "flag" "fmt" "os" @@ -80,7 +80,7 @@ func runSysPolicyReload(ctx context.Context, args []string) error { func printPolicySettings(policy *setting.Snapshot) { if syspolicyArgs.json { - json, err := json.MarshalIndent(policy, "", "\t") + json, err := jsonv1.MarshalIndent(policy, "", "\t") if err != nil { errf("syspolicy marshalling error: %v", err) } else { diff --git a/cmd/tailscale/cli/up.go b/cmd/tailscale/cli/up.go index 91a6b6087..7cfdef988 100644 --- a/cmd/tailscale/cli/up.go +++ b/cmd/tailscale/cli/up.go @@ -6,7 +6,7 @@ package cli import ( "context" "encoding/base64" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -729,7 +729,7 @@ func runUp(ctx context.Context, cmd string, args []string, upArgs upArgsT) (retE } } - data, err := json.MarshalIndent(js, "", "\t") + data, err := jsonv1.MarshalIndent(js, "", "\t") if err != nil { printf("upOutputJSON marshalling error: %v", err) } else { @@ -848,7 +848,7 @@ func checkUpWarnings(ctx context.Context) { func printUpDoneJSON(state ipn.State, errorString string) { js := &upOutputJSON{BackendState: state.String(), Error: errorString} - data, err := json.MarshalIndent(js, "", " ") + data, err := jsonv1.MarshalIndent(js, "", " ") if err != nil { log.Printf("printUpDoneJSON marshalling error: %v", err) } else { diff --git a/cmd/tailscale/cli/version.go b/cmd/tailscale/cli/version.go index b25502d5a..505b60c3c 100644 --- a/cmd/tailscale/cli/version.go +++ b/cmd/tailscale/cli/version.go @@ -5,7 +5,7 @@ package cli import ( "context" - "encoding/json" + jsonv1 "encoding/json" "flag" "fmt" @@ -69,7 +69,7 @@ func runVersion(ctx context.Context, args []string) error { Meta: m, Upstream: upstreamVer, } - e := json.NewEncoder(Stdout) + e := jsonv1.NewEncoder(Stdout) e.SetIndent("", "\t") return e.Encode(out) } diff --git a/cmd/tailscale/cli/whois.go b/cmd/tailscale/cli/whois.go index 44ff68dec..bb3c86e3d 100644 --- a/cmd/tailscale/cli/whois.go +++ b/cmd/tailscale/cli/whois.go @@ -5,7 +5,7 @@ package cli import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -47,7 +47,7 @@ func runWhoIs(ctx context.Context, args []string) error { return err } if whoIsArgs.json { - ec := json.NewEncoder(Stdout) + ec := jsonv1.NewEncoder(Stdout) ec.SetIndent("", " ") ec.Encode(who) return nil @@ -77,7 +77,7 @@ func runWhoIs(ctx context.Context, args []string) error { // To make the output more readable, we have to reindent the JSON // values so they line up with the cap name. if len(vals) > 0 { - v, _ := json.MarshalIndent(vals, " ", " ") + v, _ := jsonv1.MarshalIndent(vals, " ", " ") printf(" - %s:\n", cap) printf(" %s\n", v) diff --git a/cmd/tailscaled/debug.go b/cmd/tailscaled/debug.go index b16cb28e0..06d368a56 100644 --- a/cmd/tailscaled/debug.go +++ b/cmd/tailscaled/debug.go @@ -8,7 +8,7 @@ package main import ( "context" "crypto/tls" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -103,7 +103,7 @@ func runMonitor(ctx context.Context, loop bool) error { defer b.Close() dump := func(st *netmon.State) { - j, _ := json.MarshalIndent(st, "", " ") + j, _ := jsonv1.MarshalIndent(st, "", " ") os.Stderr.Write(j) } mon, err := netmon.New(b, log.Printf) @@ -232,7 +232,7 @@ func checkDerp(ctx context.Context, derpRegion string) (err error) { return fmt.Errorf("fetch derp map: %v: %s", res.Status, b) } var dmap tailcfg.DERPMap - if err = json.Unmarshal(b, &dmap); err != nil { + if err = jsonv1.Unmarshal(b, &dmap); err != nil { return fmt.Errorf("fetch DERP map: %w", err) } getRegion := func() *tailcfg.DERPRegion { diff --git a/cmd/tailscaled/tailscaled_windows.go b/cmd/tailscaled/tailscaled_windows.go index 3019bbaf9..37c7130f3 100644 --- a/cmd/tailscaled/tailscaled_windows.go +++ b/cmd/tailscaled/tailscaled_windows.go @@ -21,7 +21,7 @@ package main // import "tailscale.com/cmd/tailscaled" import ( "bufio" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -380,7 +380,7 @@ func beFirewallKillswitch() bool { // Note(maisem): when local lan access toggled, tailscaled needs to // inform the firewall to let local routes through. The set of routes // is passed in via stdin encoded in json. - dcd := json.NewDecoder(os.Stdin) + dcd := jsonv1.NewDecoder(os.Stdin) for { var routes []netip.Prefix if err := dcd.Decode(&routes); err != nil { diff --git a/cmd/testwrapper/testwrapper.go b/cmd/testwrapper/testwrapper.go index 173edee73..246bcd28a 100644 --- a/cmd/testwrapper/testwrapper.go +++ b/cmd/testwrapper/testwrapper.go @@ -12,7 +12,7 @@ import ( "bytes" "cmp" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -112,7 +112,7 @@ func runTests(ctx context.Context, attempt int, pt *packageTests, goTestArgs, te resultMap := make(map[string]map[string]*testAttempt) // pkg -> test -> testAttempt for s.Scan() { var goOutput goTestOutput - if err := json.Unmarshal(s.Bytes(), &goOutput); err != nil { + if err := jsonv1.Unmarshal(s.Bytes(), &goOutput); err != nil { return fmt.Errorf("failed to parse go test output %q: %w", s.Bytes(), err) } pkg := cmp.Or( @@ -265,7 +265,7 @@ func main() { os.Exit(1) } if thisRun.attempt > 1 { - j, _ := json.Marshal(thisRun.tests) + j, _ := jsonv1.Marshal(thisRun.tests) fmt.Printf("\n\nAttempt #%d: Retrying flaky tests:\n\nflakytest failures JSON: %s\n\n", thisRun.attempt, j) } @@ -326,7 +326,7 @@ func main() { if len(fatalFailures) > 0 { tests := slicesx.MapKeys(fatalFailures) sort.Strings(tests) - j, _ := json.Marshal(tests) + j, _ := jsonv1.Marshal(tests) fmt.Printf("non-flakytest failures: %s\n", j) } fmt.Println() diff --git a/cmd/tsconnect/build-pkg.go b/cmd/tsconnect/build-pkg.go index 047504858..32a480362 100644 --- a/cmd/tsconnect/build-pkg.go +++ b/cmd/tsconnect/build-pkg.go @@ -6,7 +6,7 @@ package main import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "log" "os" @@ -77,12 +77,12 @@ func updateVersion() error { if err != nil { return fmt.Errorf("Could not standardize template package.json: %w", err) } - if err := json.Unmarshal(packageJSONBytes, &packageJSON); err != nil { + if err := jsonv1.Unmarshal(packageJSONBytes, &packageJSON); err != nil { return fmt.Errorf("Could not unmarshal package.json: %w", err) } packageJSON["version"] = version.Long() - packageJSONBytes, err = json.MarshalIndent(packageJSON, "", " ") + packageJSONBytes, err = jsonv1.MarshalIndent(packageJSON, "", " ") if err != nil { return fmt.Errorf("Could not marshal package.json: %w", err) } diff --git a/cmd/tsconnect/build.go b/cmd/tsconnect/build.go index 364ebf536..6e12ed5f5 100644 --- a/cmd/tsconnect/build.go +++ b/cmd/tsconnect/build.go @@ -6,7 +6,7 @@ package main import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "log" "os" @@ -61,7 +61,7 @@ func runBuild() { // which are awkward if we're running with a different cwd at serving time). func fixEsbuildMetadataPaths(metadataStr string) ([]byte, error) { var metadata EsbuildMetadata - if err := json.Unmarshal([]byte(metadataStr), &metadata); err != nil { + if err := jsonv1.Unmarshal([]byte(metadataStr), &metadata); err != nil { return nil, fmt.Errorf("Cannot parse metadata: %w", err) } distAbsPath, err := filepath.Abs(*distDir) @@ -80,7 +80,7 @@ func fixEsbuildMetadataPaths(metadataStr string) ([]byte, error) { delete(metadata.Outputs, outputPath) metadata.Outputs[outputRelPath] = output } - return json.Marshal(metadata) + return jsonv1.Marshal(metadata) } func precompressDist(fastCompression bool) error { diff --git a/cmd/tsconnect/serve.go b/cmd/tsconnect/serve.go index d780bdd57..c2aaa90a8 100644 --- a/cmd/tsconnect/serve.go +++ b/cmd/tsconnect/serve.go @@ -8,7 +8,7 @@ package main import ( "bytes" "embed" - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" "io/fs" @@ -80,7 +80,7 @@ func generateServeIndex(distFS fs.FS) ([]byte, error) { return nil, fmt.Errorf("Could not read esbuild-metadata.json: %w", err) } var esbuildMetadata EsbuildMetadata - if err := json.Unmarshal(esbuildMetadataBytes, &esbuildMetadata); err != nil { + if err := jsonv1.Unmarshal(esbuildMetadataBytes, &esbuildMetadata); err != nil { return nil, fmt.Errorf("Could not parse esbuild-metadata.json: %w", err) } entryPointsToHashedDistPaths := make(map[string]string) diff --git a/cmd/tsconnect/wasm/wasm_js.go b/cmd/tsconnect/wasm/wasm_js.go index 2e81fa4a8..44e58129b 100644 --- a/cmd/tsconnect/wasm/wasm_js.go +++ b/cmd/tsconnect/wasm/wasm_js.go @@ -13,7 +13,7 @@ import ( "bytes" "context" "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "fmt" "log" "math/rand/v2" @@ -291,7 +291,7 @@ func (i *jsIPN) run(jsCallbacks js.Value) { }), LockedOut: nm.TKAEnabled && nm.SelfNode.KeySignature().Len() == 0, } - if jsonNetMap, err := json.Marshal(jsNetMap); err == nil { + if jsonNetMap, err := jsonv1.Marshal(jsNetMap); err == nil { jsCallbacks.Call("notifyNetMap", string(jsonNetMap)) } else { log.Printf("Could not generate JSON netmap: %v", err) diff --git a/cmd/tsidp/tsidp.go b/cmd/tsidp/tsidp.go index c02b09745..5914a6a89 100644 --- a/cmd/tsidp/tsidp.go +++ b/cmd/tsidp/tsidp.go @@ -16,7 +16,7 @@ import ( "crypto/x509" "encoding/base64" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "encoding/pem" "errors" "flag" @@ -223,7 +223,7 @@ func main() { f, err := os.Open(clientsFilePath) if err == nil { - if err := json.NewDecoder(f).Decode(&srv.funnelClients); err != nil { + if err := jsonv1.NewDecoder(f).Decode(&srv.funnelClients); err != nil { log.Fatalf("could not parse %s: %v", clientsFilePath, err) } f.Close() @@ -694,7 +694,7 @@ func (s *idpServer) serveUserInfo(w http.ResponseWriter, r *http.Request) { // Write the final result w.Header().Set("Content-Type", "application/json") - if err := json.NewEncoder(w).Encode(userInfo); err != nil { + if err := jsonv1.NewEncoder(w).Encode(userInfo); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } @@ -810,14 +810,14 @@ func addClaimValue(sets map[string]map[string]struct{}, claim string, val any) { // Returns the merged claims map or an error if any protected claim is violated or JSON (un)marshaling fails. func withExtraClaims(v any, rules []capRule) (map[string]any, error) { // Marshal the static struct - data, err := json.Marshal(v) + data, err := jsonv1.Marshal(v) if err != nil { return nil, err } // Unmarshal into a generic map var claimMap map[string]any - if err := json.Unmarshal(data, &claimMap); err != nil { + if err := jsonv1.Unmarshal(data, &claimMap); err != nil { return nil, err } @@ -993,7 +993,7 @@ func (s *idpServer) serveToken(w http.ResponseWriter, r *http.Request) { s.mu.Unlock() w.Header().Set("Content-Type", "application/json") - if err := json.NewEncoder(w).Encode(oidcTokenResponse{ + if err := jsonv1.NewEncoder(w).Encode(oidcTokenResponse{ AccessToken: at, TokenType: "Bearer", ExpiresIn: 5 * 60, @@ -1074,7 +1074,7 @@ func (s *idpServer) serveJWKS(w http.ResponseWriter, r *http.Request) { } // TODO(maisem): maybe only marshal this once and reuse? // TODO(maisem): implement key rotation. - je := json.NewEncoder(w) + je := jsonv1.NewEncoder(w) je.SetIndent("", " ") if err := je.Encode(jose.JSONWebKeySet{ Keys: []jose.JSONWebKey{ @@ -1202,7 +1202,7 @@ func (s *idpServer) serveOpenIDConfig(w http.ResponseWriter, r *http.Request) { } w.Header().Set("Content-Type", "application/json") - je := json.NewEncoder(w) + je := jsonv1.NewEncoder(w) je.SetIndent("", " ") if err := je.Encode(openIDProviderMetadata{ AuthorizationEndpoint: authorizeEndpoint, @@ -1261,7 +1261,7 @@ func (s *idpServer) serveClients(w http.ResponseWriter, r *http.Request) { case "DELETE": s.serveDeleteClient(w, r, path) case "GET": - json.NewEncoder(w).Encode(&funnelClient{ + jsonv1.NewEncoder(w).Encode(&funnelClient{ ID: c.ID, Name: c.Name, Secret: "", @@ -1301,7 +1301,7 @@ func (s *idpServer) serveNewClient(w http.ResponseWriter, r *http.Request) { delete(s.funnelClients, clientID) return } - json.NewEncoder(w).Encode(newClient) + jsonv1.NewEncoder(w).Encode(newClient) } func (s *idpServer) serveGetClientsList(w http.ResponseWriter, r *http.Request) { @@ -1320,7 +1320,7 @@ func (s *idpServer) serveGetClientsList(w http.ResponseWriter, r *http.Request) }) } s.mu.Unlock() - json.NewEncoder(w).Encode(redactedClients) + jsonv1.NewEncoder(w).Encode(redactedClients) } func (s *idpServer) serveDeleteClient(w http.ResponseWriter, r *http.Request, clientID string) { @@ -1356,7 +1356,7 @@ func (s *idpServer) serveDeleteClient(w http.ResponseWriter, r *http.Request, cl // otherwise uses oidc-funnel-clients.json. s.mu must be held while calling this. func (s *idpServer) storeFunnelClientsLocked() error { var buf bytes.Buffer - if err := json.NewEncoder(&buf).Encode(s.funnelClients); err != nil { + if err := jsonv1.NewEncoder(&buf).Encode(s.funnelClients); err != nil { return err } @@ -1421,7 +1421,7 @@ func (sk *signingKey) MarshalJSON() ([]byte, error) { Bytes: x509.MarshalPKCS1PrivateKey(sk.k), } bts := pem.EncodeToMemory(&b) - return json.Marshal(rsaPrivateKeyJSONWrapper{ + return jsonv1.Marshal(rsaPrivateKeyJSONWrapper{ Key: base64.URLEncoding.EncodeToString(bts), ID: sk.kid, }) @@ -1429,7 +1429,7 @@ func (sk *signingKey) MarshalJSON() ([]byte, error) { func (sk *signingKey) UnmarshalJSON(b []byte) error { var wrapper rsaPrivateKeyJSONWrapper - if err := json.Unmarshal(b, &wrapper); err != nil { + if err := jsonv1.Unmarshal(b, &wrapper); err != nil { return err } if len(wrapper.Key) == 0 { diff --git a/cmd/tsidp/tsidp_test.go b/cmd/tsidp/tsidp_test.go index 4f5af9e59..5b22e0b09 100644 --- a/cmd/tsidp/tsidp_test.go +++ b/cmd/tsidp/tsidp_test.go @@ -19,7 +19,7 @@ package main import ( "crypto/rand" "crypto/rsa" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -79,7 +79,7 @@ func normalizeMap(t *testing.T, m map[string]any) map[string]any { func mustMarshalJSON(t *testing.T, v any) tailcfg.RawMessage { t.Helper() - b, err := json.Marshal(v) + b, err := jsonv1.Marshal(v) if err != nil { panic(err) } @@ -461,13 +461,13 @@ func TestExtraClaims(t *testing.T) { } // Marshal to JSON then unmarshal back to map[string]any - gotClaims, err := json.Marshal(claims) + gotClaims, err := jsonv1.Marshal(claims) if err != nil { t.Errorf("json.Marshal(claims) error = %v", err) } var gotClaimsMap map[string]any - if err := json.Unmarshal(gotClaims, &gotClaimsMap); err != nil { + if err := jsonv1.Unmarshal(gotClaims, &gotClaimsMap); err != nil { t.Fatalf("json.Unmarshal(gotClaims) error = %v", err) } @@ -671,7 +671,7 @@ func TestServeToken(t *testing.T) { var resp struct { IDToken string `json:"id_token"` } - if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + if err := jsonv1.Unmarshal(rr.Body.Bytes(), &resp); err != nil { t.Fatalf("failed to unmarshal response: %v", err) } @@ -861,7 +861,7 @@ func TestExtraUserInfo(t *testing.T) { } var resp map[string]any - if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + if err := jsonv1.Unmarshal(rr.Body.Bytes(), &resp); err != nil { t.Fatalf("failed to parse JSON response: %v", err) } @@ -898,7 +898,7 @@ func TestFunnelClientsPersistence(t *testing.T) { }, } - testData, err := json.Marshal(testClients) + testData, err := jsonv1.Marshal(testClients) if err != nil { t.Fatalf("failed to marshal test data: %v", err) } @@ -915,7 +915,7 @@ func TestFunnelClientsPersistence(t *testing.T) { srv.funnelClients = make(map[string]*funnelClient) f, err := os.Open(tmpFile) if err == nil { - if err := json.NewDecoder(f).Decode(&srv.funnelClients); err != nil { + if err := jsonv1.NewDecoder(f).Decode(&srv.funnelClients); err != nil { t.Fatalf("could not parse %s: %v", tmpFile, err) } f.Close() @@ -950,7 +950,7 @@ func TestFunnelClientsPersistence(t *testing.T) { srv.funnelClients = make(map[string]*funnelClient) f, err := os.Open(nonExistentFile) if err == nil { - if err := json.NewDecoder(f).Decode(&srv.funnelClients); err != nil { + if err := jsonv1.NewDecoder(f).Decode(&srv.funnelClients); err != nil { t.Fatalf("could not parse %s: %v", nonExistentFile, err) } f.Close() @@ -982,7 +982,7 @@ func TestFunnelClientsPersistence(t *testing.T) { } // Save clients to file (simulating saveFunnelClients) - data, err := json.Marshal(srv1.funnelClients) + data, err := jsonv1.Marshal(srv1.funnelClients) if err != nil { t.Fatalf("failed to marshal clients: %v", err) } @@ -995,7 +995,7 @@ func TestFunnelClientsPersistence(t *testing.T) { srv2.funnelClients = make(map[string]*funnelClient) f, err := os.Open(tmpFile2) if err == nil { - if err := json.NewDecoder(f).Decode(&srv2.funnelClients); err != nil { + if err := jsonv1.NewDecoder(f).Decode(&srv2.funnelClients); err != nil { t.Fatalf("could not parse %s: %v", tmpFile2, err) } f.Close() @@ -1255,7 +1255,7 @@ func TestMigrateOAuthClients(t *testing.T) { // Setup old file if needed if tt.setupOldFile { - oldData, err := json.Marshal(tt.oldFileContent) + oldData, err := jsonv1.Marshal(tt.oldFileContent) if err != nil { t.Fatalf("failed to marshal old file content: %v", err) } @@ -1267,7 +1267,7 @@ func TestMigrateOAuthClients(t *testing.T) { // Setup new file if needed if tt.setupNewFile { - newData, err := json.Marshal(tt.newFileContent) + newData, err := jsonv1.Marshal(tt.newFileContent) if err != nil { t.Fatalf("failed to marshal new file content: %v", err) } @@ -1309,7 +1309,7 @@ func TestMigrateOAuthClients(t *testing.T) { } var clients map[string]*funnelClient - if err := json.Unmarshal(data, &clients); err != nil { + if err := jsonv1.Unmarshal(data, &clients); err != nil { t.Fatalf("failed to unmarshal new file: %v", err) } @@ -1854,7 +1854,7 @@ func TestServeTokenWithClientValidation(t *testing.T) { ExpiresIn int `json:"expires_in"` } - if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + if err := jsonv1.Unmarshal(rr.Body.Bytes(), &resp); err != nil { t.Fatalf("failed to unmarshal response: %v", err) } @@ -2035,7 +2035,7 @@ func TestServeUserInfoWithClientValidation(t *testing.T) { } var resp map[string]any - if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + if err := jsonv1.Unmarshal(rr.Body.Bytes(), &resp); err != nil { t.Fatalf("failed to parse JSON response: %v", err) } diff --git a/control/controlclient/direct.go b/control/controlclient/direct.go index 63a12b249..d0143d20d 100644 --- a/control/controlclient/direct.go +++ b/control/controlclient/direct.go @@ -10,7 +10,7 @@ import ( "crypto" "crypto/sha256" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -379,7 +379,7 @@ func (c *Direct) SetHostinfo(hi *tailcfg.Hostinfo) bool { return false } c.hostinfo = hi.Clone() - j, _ := json.Marshal(c.hostinfo) + j, _ := jsonv1.Marshal(c.hostinfo) c.logf("[v1] HostInfo: %s", j) return true } @@ -681,7 +681,7 @@ func (c *Direct) doLogin(ctx context.Context, opt loginOpt) (mustRegen bool, new } } if DevKnob.DumpRegister() { - j, _ := json.MarshalIndent(request, "", "\t") + j, _ := jsonv1.MarshalIndent(request, "", "\t") c.logf("RegisterRequest: %s", j) } @@ -722,7 +722,7 @@ func (c *Direct) doLogin(ctx context.Context, opt loginOpt) (mustRegen bool, new return regen, opt.URL, nil, fmt.Errorf("register request: %v", err) } if DevKnob.DumpRegister() { - j, _ := json.MarshalIndent(resp, "", "\t") + j, _ := jsonv1.MarshalIndent(resp, "", "\t") c.logf("RegisterResponse: %s", j) } @@ -1257,7 +1257,7 @@ func decode(res *http.Response, v any) error { if res.StatusCode != 200 { return fmt.Errorf("%d: %v", res.StatusCode, string(msg)) } - return json.Unmarshal(msg, v) + return jsonv1.Unmarshal(msg, v) } var jsonEscapedZero = []byte(`\u0000`) @@ -1281,14 +1281,14 @@ func (sess *mapSession) decodeMsg(compressedMsg []byte, v *tailcfg.MapResponse) if DevKnob.DumpNetMaps() { var buf bytes.Buffer - json.Indent(&buf, b, "", " ") + jsonv1.Indent(&buf, b, "", " ") log.Printf("MapResponse: %s", buf.Bytes()) } if bytes.Contains(b, jsonEscapedZero) { log.Printf("[unexpected] zero byte in controlclient.Direct.decodeMsg into %T: %q", v, b) } - if err := json.Unmarshal(b, v); err != nil { + if err := jsonv1.Unmarshal(b, v); err != nil { return fmt.Errorf("response: %v", err) } if v.KeepAlive && string(b) == justKeepAliveStr { @@ -1300,7 +1300,7 @@ func (sess *mapSession) decodeMsg(compressedMsg []byte, v *tailcfg.MapResponse) // encode JSON encodes v as JSON, logging tailcfg.MapRequest values if // debugMap is set. func encode(v any) ([]byte, error) { - b, err := json.Marshal(v) + b, err := jsonv1.Marshal(v) if err != nil { return nil, err } @@ -1331,7 +1331,7 @@ func loadServerPubKeys(ctx context.Context, httpc *http.Client, serverURL string return nil, fmt.Errorf("fetch control key: %v", res.Status) } var out tailcfg.OverTLSPublicKeyResponse - jsonErr := json.Unmarshal(b, &out) + jsonErr := jsonv1.Unmarshal(b, &out) if jsonErr == nil { return &out, nil } @@ -1568,7 +1568,7 @@ func (c *Direct) setDNSNoise(ctx context.Context, req *tailcfg.SetDNSRequest) er return fmt.Errorf("set-dns response: %v, %.200s", res.Status, strings.TrimSpace(string(msg))) } var setDNSRes tailcfg.SetDNSResponse - if err := json.NewDecoder(res.Body).Decode(&setDNSRes); err != nil { + if err := jsonv1.NewDecoder(res.Body).Decode(&setDNSRes); err != nil { c.logf("error decoding SetDNSResponse: %v", err) return fmt.Errorf("set-dns-response: %w", err) } @@ -1635,7 +1635,7 @@ func postPingResult(start time.Time, logf logger.Logf, c *http.Client, pr *tailc ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() - jsonPingRes, err := json.Marshal(res) + jsonPingRes, err := jsonv1.Marshal(res) if err != nil { return err } diff --git a/control/controlclient/direct_test.go b/control/controlclient/direct_test.go index dd93dc7b3..bac380916 100644 --- a/control/controlclient/direct_test.go +++ b/control/controlclient/direct_test.go @@ -4,7 +4,7 @@ package controlclient import ( - "encoding/json" + jsonv1 "encoding/json" "net/http" "net/http/httptest" "net/netip" @@ -134,7 +134,7 @@ func TestTsmpPing(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() body := new(ipnstate.PingResult) - if err := json.NewDecoder(r.Body).Decode(body); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(body); err != nil { t.Fatal(err) } if pingRes.IP != body.IP { diff --git a/control/controlclient/map.go b/control/controlclient/map.go index eafdb2d56..fb2b3ae8f 100644 --- a/control/controlclient/map.go +++ b/control/controlclient/map.go @@ -8,7 +8,7 @@ import ( "context" "crypto/sha256" "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "io" "maps" "net" @@ -598,7 +598,7 @@ func (ms *mapSession) patchifyPeersChanged(resp *tailcfg.MapResponse) { if p, ok := ms.patchifyPeer(n); ok { patchifiedPeer.Add(1) if debugPatchifyPeer() { - patchj, _ := json.Marshal(p) + patchj, _ := jsonv1.Marshal(p) ms.logf("debug: patchifyPeer[ID=%v]: %s", n.ID, patchj) } if p != nil { diff --git a/control/controlclient/map_test.go b/control/controlclient/map_test.go index 2be4b6ad7..c40b79456 100644 --- a/control/controlclient/map_test.go +++ b/control/controlclient/map_test.go @@ -6,7 +6,7 @@ package controlclient import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "maps" "net/netip" @@ -524,7 +524,7 @@ func TestNetmapForResponse(t *testing.T) { t.Fatal("nil Node in 1st netmap") } if !reflect.DeepEqual(nm1.SelfNode, wantNode) { - j, _ := json.Marshal(nm1.SelfNode) + j, _ := jsonv1.Marshal(nm1.SelfNode) t.Errorf("Node mismatch in 1st netmap; got: %s", j) } @@ -534,7 +534,7 @@ func TestNetmapForResponse(t *testing.T) { t.Fatal("nil Node in 1st netmap") } if !reflect.DeepEqual(nm2.SelfNode, wantNode) { - j, _ := json.Marshal(nm2.SelfNode) + j, _ := jsonv1.Marshal(nm2.SelfNode) t.Errorf("Node mismatch in 2nd netmap; got: %s", j) } }) @@ -1002,7 +1002,7 @@ func TestPatchifyPeersChanged(t *testing.T) { ms := newTestMapSession(t, nu) ms.updateStateFromResponse(tt.mr0) mr1 := new(tailcfg.MapResponse) - must.Do(json.Unmarshal(must.Get(json.Marshal(tt.mr1)), mr1)) + must.Do(jsonv1.Unmarshal(must.Get(jsonv1.Marshal(tt.mr1)), mr1)) ms.patchifyPeersChanged(mr1) opts := []cmp.Option{ cmp.Comparer(func(a, b netip.AddrPort) bool { return a == b }), @@ -1450,7 +1450,7 @@ func TestNetmapForMapResponseForDebug(t *testing.T) { func TestLearnZstdOfKeepAlive(t *testing.T) { keepAliveMsgZstd := (func() []byte { - msg := must.Get(json.Marshal(tailcfg.MapResponse{ + msg := must.Get(jsonv1.Marshal(tailcfg.MapResponse{ KeepAlive: true, })) return zstdframe.AppendEncode(nil, msg, zstdframe.FastestCompression) diff --git a/control/controlclient/status.go b/control/controlclient/status.go index d0fdf80d7..6d302c7fd 100644 --- a/control/controlclient/status.go +++ b/control/controlclient/status.go @@ -4,7 +4,7 @@ package controlclient import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "reflect" @@ -117,7 +117,7 @@ func (s *Status) Equal(s2 *Status) bool { } func (s Status) String() string { - b, err := json.MarshalIndent(s, "", "\t") + b, err := jsonv1.MarshalIndent(s, "", "\t") if err != nil { panic(err) } diff --git a/control/ts2021/client.go b/control/ts2021/client.go index ca10b1d1b..40eccf527 100644 --- a/control/ts2021/client.go +++ b/control/ts2021/client.go @@ -7,7 +7,7 @@ import ( "bytes" "cmp" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "log" @@ -291,7 +291,7 @@ func (nc *Client) Post(ctx context.Context, path string, nodeKey key.NodePublic, } func (nc *Client) DoWithBody(ctx context.Context, method, path string, nodeKey key.NodePublic, body any) (*http.Response, error) { - jbody, err := json.Marshal(body) + jbody, err := jsonv1.Marshal(body) if err != nil { return nil, err } diff --git a/control/ts2021/client_test.go b/control/ts2021/client_test.go index 72fa1f442..4a0004967 100644 --- a/control/ts2021/client_test.go +++ b/control/ts2021/client_test.go @@ -6,7 +6,7 @@ package ts2021 import ( "context" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "io" "math" "net/http" @@ -323,7 +323,7 @@ func (up *Upgrader) ServeHTTP(w http.ResponseWriter, r *http.Request) { if !up.sendEarlyPayload { return nil } - earlyJSON, err := json.Marshal(&tailcfg.EarlyNoise{ + earlyJSON, err := jsonv1.Marshal(&tailcfg.EarlyNoise{ NodeKeyChallenge: up.challenge.Public(), }) if err != nil { diff --git a/control/ts2021/conn.go b/control/ts2021/conn.go index 52d663272..c95100c68 100644 --- a/control/ts2021/conn.go +++ b/control/ts2021/conn.go @@ -10,7 +10,7 @@ import ( "bytes" "context" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "errors" "io" "sync" @@ -150,7 +150,7 @@ func (c *Conn) readHeader() { setErr(err) return } - if err := json.Unmarshal(payBuf, &c.earlyPayload); err != nil { + if err := jsonv1.Unmarshal(payBuf, &c.earlyPayload); err != nil { setErr(err) return } diff --git a/derp/derp_client.go b/derp/derp_client.go index d28905cd2..2bab08b74 100644 --- a/derp/derp_client.go +++ b/derp/derp_client.go @@ -6,7 +6,7 @@ package derp import ( "bufio" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -154,7 +154,7 @@ func (c *Client) parseServerInfo(b []byte) (*ServerInfo, error) { return nil, fmt.Errorf("failed to open naclbox from server key %s", c.serverKey) } info := new(ServerInfo) - if err := json.Unmarshal(msg, info); err != nil { + if err := jsonv1.Unmarshal(msg, info); err != nil { return nil, fmt.Errorf("invalid JSON: %v", err) } return info, nil @@ -193,7 +193,7 @@ func (c *ClientInfo) Equal(other *ClientInfo) bool { } func (c *Client) sendClientKey() error { - msg, err := json.Marshal(ClientInfo{ + msg, err := jsonv1.Marshal(ClientInfo{ Version: ProtocolVersion, MeshKey: c.meshKey, CanAckPings: c.canAckPings, diff --git a/derp/derp_test.go b/derp/derp_test.go index 52793f90f..adb581ecc 100644 --- a/derp/derp_test.go +++ b/derp/derp_test.go @@ -7,7 +7,7 @@ import ( "bufio" "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "expvar" "fmt" @@ -64,7 +64,7 @@ func TestClientInfoUnmarshal(t *testing.T) { t.Run(i, func(t *testing.T) { t.Parallel() var got ClientInfo - err := json.Unmarshal([]byte(in.json), &got) + err := jsonv1.Unmarshal([]byte(in.json), &got) if in.wantErr != "" { if err == nil || !strings.Contains(err.Error(), in.wantErr) { t.Errorf("Unmarshal(%q) = %v, want error containing %q", in.json, err, in.wantErr) diff --git a/derp/derphttp/derphttp_test.go b/derp/derphttp/derphttp_test.go index 5208481ed..db0effb79 100644 --- a/derp/derphttp/derphttp_test.go +++ b/derp/derphttp/derphttp_test.go @@ -7,7 +7,7 @@ import ( "bytes" "context" "crypto/tls" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -574,7 +574,7 @@ func TestManualDial(t *testing.T) { t.Fatalf("fetching DERPMap: %v", err) } defer res.Body.Close() - if err := json.NewDecoder(res.Body).Decode(dm); err != nil { + if err := jsonv1.NewDecoder(res.Body).Decode(dm); err != nil { t.Fatalf("decoding DERPMap: %v", err) } @@ -601,7 +601,7 @@ func TestURLDial(t *testing.T) { t.Fatalf("fetching DERPMap: %v", err) } defer res.Body.Close() - if err := json.NewDecoder(res.Body).Decode(dm); err != nil { + if err := jsonv1.NewDecoder(res.Body).Decode(dm); err != nil { t.Fatalf("decoding DERPMap: %v", err) } diff --git a/derp/derpserver/derpserver.go b/derp/derpserver/derpserver.go index 31cf9363a..4fc99f892 100644 --- a/derp/derpserver/derpserver.go +++ b/derp/derpserver/derpserver.go @@ -16,7 +16,7 @@ import ( "crypto/x509" "crypto/x509/pkix" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "errors" "expvar" "fmt" @@ -1396,7 +1396,7 @@ func (s *Server) verifyClient(ctx context.Context, clientKey key.NodePublic, inf ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() - jreq, err := json.Marshal(&tailcfg.DERPAdmitClientRequest{ + jreq, err := jsonv1.Marshal(&tailcfg.DERPAdmitClientRequest{ NodePublic: clientKey, Source: clientIP, }) @@ -1420,7 +1420,7 @@ func (s *Server) verifyClient(ctx context.Context, clientKey key.NodePublic, inf return fmt.Errorf("admission controller: %v", res.Status) } var jres tailcfg.DERPAdmitClientResponse - if err := json.NewDecoder(io.LimitReader(res.Body, 4<<10)).Decode(&jres); err != nil { + if err := jsonv1.NewDecoder(io.LimitReader(res.Body, 4<<10)).Decode(&jres); err != nil { return err } if !jres.Allow { @@ -1503,7 +1503,7 @@ func (s *Server) noteClientActivity(c *sclient) { type ServerInfo = derp.ServerInfo func (s *Server) sendServerInfo(bw *lazyBufioWriter, clientKey key.NodePublic) error { - msg, err := json.Marshal(ServerInfo{Version: derp.ProtocolVersion}) + msg, err := jsonv1.Marshal(ServerInfo{Version: derp.ProtocolVersion}) if err != nil { return err } @@ -1548,7 +1548,7 @@ func (s *Server) recvClientKey(br *bufio.Reader) (clientKey key.NodePublic, info return zpub, nil, fmt.Errorf("msgbox: cannot open len=%d with client key %s", msgLen, clientKey) } info = new(derp.ClientInfo) - if err := json.Unmarshal(msg, info); err != nil { + if err := jsonv1.Unmarshal(msg, info); err != nil { return zpub, nil, fmt.Errorf("msg: %v", err) } return clientKey, info, nil @@ -2335,7 +2335,7 @@ func parseSSOutput(raw string) map[netip.AddrPort]BytesSentRecv { func (s *Server) ServeDebugTraffic(w http.ResponseWriter, r *http.Request) { prevState := map[netip.AddrPort]BytesSentRecv{} - enc := json.NewEncoder(w) + enc := jsonv1.NewEncoder(w) for r.Context().Err() == nil { output, err := exec.Command("ss", "-i", "-H", "-t").Output() if err != nil { diff --git a/docs/webhooks/example.go b/docs/webhooks/example.go index 712028362..997cd8855 100644 --- a/docs/webhooks/example.go +++ b/docs/webhooks/example.go @@ -10,7 +10,7 @@ import ( "crypto/sha256" "crypto/subtle" "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -105,7 +105,7 @@ func verifyWebhookSignature(req *http.Request, secret string) (events []event, e } // If verified, return the events. - if err := json.Unmarshal(b, &events); err != nil { + if err := jsonv1.Unmarshal(b, &events); err != nil { return nil, err } return events, nil diff --git a/drive/remote_permissions.go b/drive/remote_permissions.go index 420eff9a0..0ad0d2e32 100644 --- a/drive/remote_permissions.go +++ b/drive/remote_permissions.go @@ -4,7 +4,7 @@ package drive import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" ) @@ -37,7 +37,7 @@ func ParsePermissions(rawGrants [][]byte) (Permissions, error) { permissions := make(Permissions) for _, rawGrant := range rawGrants { var g grant - err := json.Unmarshal(rawGrant, &g) + err := jsonv1.Unmarshal(rawGrant, &g) if err != nil { return nil, fmt.Errorf("unmarshal raw grants %s: %v", rawGrant, err) } diff --git a/drive/remote_permissions_test.go b/drive/remote_permissions_test.go index ff039c800..c3c66eb6c 100644 --- a/drive/remote_permissions_test.go +++ b/drive/remote_permissions_test.go @@ -4,7 +4,7 @@ package drive import ( - "encoding/json" + jsonv1 "encoding/json" "testing" ) @@ -40,7 +40,7 @@ func TestPermissions(t *testing.T) { t.Run(tt.share, func(t *testing.T) { var rawPerms [][]byte for _, perm := range tt.perms { - b, err := json.Marshal(perm) + b, err := jsonv1.Marshal(perm) if err != nil { t.Fatal(err) } diff --git a/feature/appconnectors/appconnectors.go b/feature/appconnectors/appconnectors.go index 28f5ccde3..3dd6a8b59 100644 --- a/feature/appconnectors/appconnectors.go +++ b/feature/appconnectors/appconnectors.go @@ -5,7 +5,7 @@ package appconnectors import ( - "encoding/json" + jsonv1 "encoding/json" "net/http" "tailscale.com/ipn/ipnlocal" @@ -28,12 +28,12 @@ func handleC2NAppConnectorDomainRoutesGet(b *ipnlocal.LocalBackend, w http.Respo appConnector := b.AppConnector() if appConnector == nil { w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) return } res.Domains = appConnector.DomainRoutes() w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) } diff --git a/feature/clientupdate/clientupdate.go b/feature/clientupdate/clientupdate.go index 45fd21129..a25f5ecda 100644 --- a/feature/clientupdate/clientupdate.go +++ b/feature/clientupdate/clientupdate.go @@ -7,7 +7,7 @@ package clientupdate import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "net/http" @@ -214,7 +214,7 @@ func serveUpdateProgress(h *localapi.Handler, w http.ResponseWriter, r *http.Req ups := ext.GetSelfUpdateProgress() - json.NewEncoder(w).Encode(ups) + jsonv1.NewEncoder(w).Encode(ups) } func (e *extension) pushSelfUpdateProgress(up ipnstate.UpdateProgress) { @@ -237,7 +237,7 @@ func handleC2NUpdateGet(b *ipnlocal.LocalBackend, w http.ResponseWriter, r *http res.Started = e.c2nUpdateStarted() w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) } func handleC2NUpdatePost(b *ipnlocal.LocalBackend, w http.ResponseWriter, r *http.Request) { @@ -253,7 +253,7 @@ func handleC2NUpdatePost(b *ipnlocal.LocalBackend, w http.ResponseWriter, r *htt e.logf("c2n: POST /update failed: %s", res.Err) } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) }() if !res.Enabled { @@ -444,7 +444,7 @@ func (e *extension) startAutoUpdate(logPrefix string) (retErr error) { if err != nil { return fmt.Errorf("failed to find cmd/tailscale binary: %w", err) } - if err := json.Unmarshal(out, &ver); err != nil { + if err := jsonv1.Unmarshal(out, &ver); err != nil { return fmt.Errorf("invalid JSON from cmd/tailscale version --json: %w", err) } if ver.Long != version.Long() { diff --git a/feature/posture/posture.go b/feature/posture/posture.go index 8e1945d7d..e89e5bb74 100644 --- a/feature/posture/posture.go +++ b/feature/posture/posture.go @@ -7,7 +7,7 @@ package posture import ( - "encoding/json" + jsonv1 "encoding/json" "net/http" "tailscale.com/ipn/ipnext" @@ -91,7 +91,7 @@ func handleC2NPostureIdentityGet(b *ipnlocal.LocalBackend, w http.ResponseWriter e.logf("c2n: posture identity disabled=%v reported %d serials %d hwaddrs", res.PostureDisabled, len(res.SerialNumbers), len(res.IfaceHardwareAddrs)) w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) } // getHardwareAddrs returns the hardware addresses for the machine. If the list diff --git a/feature/relayserver/relayserver.go b/feature/relayserver/relayserver.go index df2fb4cb7..8678bd863 100644 --- a/feature/relayserver/relayserver.go +++ b/feature/relayserver/relayserver.go @@ -6,7 +6,7 @@ package relayserver import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "log" "net/http" @@ -56,7 +56,7 @@ func servePeerRelayDebugSessions(h *localapi.Handler, w http.ResponseWriter, r * } st := e.serverStatus() - j, err := json.Marshal(st) + j, err := jsonv1.Marshal(st) if err != nil { http.Error(w, fmt.Sprintf("failed to marshal json: %v", err), http.StatusInternalServerError) return diff --git a/feature/taildrop/localapi.go b/feature/taildrop/localapi.go index 8a3904f9f..e85855b26 100644 --- a/feature/taildrop/localapi.go +++ b/feature/taildrop/localapi.go @@ -6,7 +6,7 @@ package taildrop import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" "maps" @@ -201,7 +201,7 @@ func multiFilePost(h *localapi.Handler, progressUpdates chan (ipn.OutgoingFile), } var manifest []ipn.OutgoingFile - err := json.NewDecoder(part).Decode(&manifest) + err := jsonv1.NewDecoder(part).Decode(&manifest) if err != nil { http.Error(ww, fmt.Sprintf("invalid manifest: %s", err), http.StatusBadRequest) return @@ -318,7 +318,7 @@ func singleFilePut( h.Logf("fetch remote hashes status code: %d", resp.StatusCode) default: resumeStart := time.Now() - dec := json.NewDecoder(resp.Body) + dec := jsonv1.NewDecoder(resp.Body) offset, remainingBody, err = resumeReader(body, func() (out blockChecksum, err error) { err = dec.Decode(&out) return out, err @@ -404,7 +404,7 @@ func serveFiles(h *localapi.Handler, w http.ResponseWriter, r *http.Request) { } } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(wfs) + jsonv1.NewEncoder(w).Encode(wfs) return } name, err := url.PathUnescape(suffix) @@ -454,5 +454,5 @@ func serveFileTargets(h *localapi.Handler, w http.ResponseWriter, r *http.Reques } mak.NonNilSliceForJSON(&fts) w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(fts) + jsonv1.NewEncoder(w).Encode(fts) } diff --git a/feature/taildrop/peerapi.go b/feature/taildrop/peerapi.go index b75ce33b8..60406cbd7 100644 --- a/feature/taildrop/peerapi.go +++ b/feature/taildrop/peerapi.go @@ -4,7 +4,7 @@ package taildrop import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" "net/http" @@ -84,7 +84,7 @@ func handlePeerPutWithBackend(h ipnlocal.PeerAPIHandler, ext extensionForPut, w http.Error(w, ErrInvalidFileName.Error(), http.StatusBadRequest) return } - enc := json.NewEncoder(w) + enc := jsonv1.NewEncoder(w) switch r.Method { case "GET": id := clientID(h.Peer().StableID()) diff --git a/feature/tpm/attestation.go b/feature/tpm/attestation.go index 597d4a649..5d7c252f5 100644 --- a/feature/tpm/attestation.go +++ b/feature/tpm/attestation.go @@ -5,7 +5,7 @@ package tpm import ( "crypto" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -149,7 +149,7 @@ func (ak *attestationKey) MarshalJSON() ([]byte, error) { if ak == nil || len(ak.tpmPublic.Bytes()) == 0 || len(ak.tpmPrivate.Buffer) == 0 { return []byte("null"), nil } - return json.Marshal(attestationKeySerialized{ + return jsonv1.Marshal(attestationKeySerialized{ TPMPublic: ak.tpmPublic.Bytes(), TPMPrivate: ak.tpmPrivate.Buffer, }) @@ -158,7 +158,7 @@ func (ak *attestationKey) MarshalJSON() ([]byte, error) { // UnmarshalJSON implements json.Unmarshaler. func (ak *attestationKey) UnmarshalJSON(data []byte) (retErr error) { var aks attestationKeySerialized - if err := json.Unmarshal(data, &aks); err != nil { + if err := jsonv1.Unmarshal(data, &aks); err != nil { return err } diff --git a/feature/tpm/attestation_test.go b/feature/tpm/attestation_test.go index e7ff72987..03e19846d 100644 --- a/feature/tpm/attestation_test.go +++ b/feature/tpm/attestation_test.go @@ -9,7 +9,7 @@ import ( "crypto/ecdsa" "crypto/rand" "crypto/sha256" - "encoding/json" + jsonv1 "encoding/json" "runtime" "sync" "testing" @@ -112,7 +112,7 @@ func TestAttestationKeyUnmarshal(t *testing.T) { t.Fatal(err) } var ak2 attestationKey - if err := json.Unmarshal(buf, &ak2); err != nil { + if err := jsonv1.Unmarshal(buf, &ak2); err != nil { t.Fatal(err) } t.Cleanup(func() { diff --git a/feature/tpm/tpm.go b/feature/tpm/tpm.go index 4b27a241f..80d18152f 100644 --- a/feature/tpm/tpm.go +++ b/feature/tpm/tpm.go @@ -7,7 +7,7 @@ package tpm import ( "bytes" "crypto/rand" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "iter" @@ -190,7 +190,7 @@ func newStore(logf logger.Logf, path string) (ipn.StateStore, error) { // State file exists, unseal and parse it. var sealed encryptedData - if err := json.Unmarshal(bs, &sealed); err != nil { + if err := jsonv1.Unmarshal(bs, &sealed); err != nil { return nil, fmt.Errorf("failed to unmarshal state file: %w", err) } if len(sealed.Data) == 0 || sealed.Key == nil || len(sealed.Nonce) == 0 { @@ -200,7 +200,7 @@ func newStore(logf logger.Logf, path string) (ipn.StateStore, error) { if err != nil { return nil, fmt.Errorf("failed to unseal state file: %w", err) } - if err := json.Unmarshal(data.Data, &parsed); err != nil { + if err := jsonv1.Unmarshal(data.Data, &parsed); err != nil { return nil, fmt.Errorf("failed to parse state file: %w", err) } return &tpmStore{ @@ -246,7 +246,7 @@ func (s *tpmStore) WriteState(k ipn.StateKey, bs []byte) error { } func (s *tpmStore) writeSealed() error { - bs, err := json.Marshal(s.cache) + bs, err := jsonv1.Marshal(s.cache) if err != nil { return err } @@ -254,7 +254,7 @@ func (s *tpmStore) writeSealed() error { if err != nil { return fmt.Errorf("failed to seal state file: %w", err) } - buf, err := json.Marshal(sealed) + buf, err := jsonv1.Marshal(sealed) if err != nil { return err } diff --git a/feature/tpm/tpm_test.go b/feature/tpm/tpm_test.go index afce570fc..ee33e6ba0 100644 --- a/feature/tpm/tpm_test.go +++ b/feature/tpm/tpm_test.go @@ -6,7 +6,7 @@ package tpm import ( "bytes" "crypto/rand" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "iter" @@ -289,7 +289,7 @@ func TestMigrateStateToTPM(t *testing.T) { t.Fatal(err) } var data map[string]any - if err := json.Unmarshal(buf, &data); err != nil { + if err := jsonv1.Unmarshal(buf, &data); err != nil { t.Fatal(err) } gotKeys := slices.Collect(maps.Keys(data)) @@ -325,7 +325,7 @@ func newMockTPMSeal(logf logger.Logf, path string) (ipn.StateStore, error) { Nonce string Data map[ipn.StateKey][]byte } - if err := json.Unmarshal(buf, &data); err != nil { + if err := jsonv1.Unmarshal(buf, &data); err != nil { return nil, err } if data.Key == "" || data.Nonce == "" { @@ -354,7 +354,7 @@ func (p *mockTPMSealProvider) flushState() error { "nonce": "bar", "data": p.data, } - buf, err := json.Marshal(data) + buf, err := jsonv1.Marshal(data) if err != nil { return err } diff --git a/feature/wakeonlan/wakeonlan.go b/feature/wakeonlan/wakeonlan.go index 96c424084..bc01725ca 100644 --- a/feature/wakeonlan/wakeonlan.go +++ b/feature/wakeonlan/wakeonlan.go @@ -5,7 +5,7 @@ package wakeonlan import ( - "encoding/json" + jsonv1 "encoding/json" "log" "net" "net/http" @@ -83,7 +83,7 @@ func handleC2NWoL(b *ipnlocal.LocalBackend, w http.ResponseWriter, r *http.Reque func writeJSON(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(v) + jsonv1.NewEncoder(w).Encode(v) } func canWakeOnLAN(h ipnlocal.PeerAPIHandler) bool { diff --git a/gokrazy/build.go b/gokrazy/build.go index c1ee1cbeb..6e9e60214 100644 --- a/gokrazy/build.go +++ b/gokrazy/build.go @@ -11,7 +11,7 @@ package main import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -83,7 +83,7 @@ func main() { if err != nil { log.Fatalf("reading config.json: %v", err) } - if err := json.Unmarshal(confJSON, &conf); err != nil { + if err := jsonv1.Unmarshal(confJSON, &conf); err != nil { log.Fatalf("unmarshaling config.json: %v", err) } switch conf.GOARCH() { @@ -200,7 +200,7 @@ func startImportSnapshot() (importTaskID string, err error) { "Tags": [] } */ - if err := json.Unmarshal(out, &resp); err != nil { + if err := jsonv1.Unmarshal(out, &resp); err != nil { return "", fmt.Errorf("unmarshal response: %v: %s", err, out) } return resp.ImportTaskID, nil @@ -244,7 +244,7 @@ func waitForImportSnapshot(importTaskID string) (snapID string, err error) { } `json:"SnapshotTaskDetail"` } `json:"ImportSnapshotTasks"` } - if err := json.Unmarshal(out, &resp); err != nil { + if err := jsonv1.Unmarshal(out, &resp); err != nil { return "", fmt.Errorf("unmarshal response: %v: %s", err, out) } if len(resp.ImportSnapshotTasks) > 0 { @@ -311,7 +311,7 @@ func makeAMI(name, ebsSnapID string) (ami string, err error) { var resp struct { ImageID string `json:"ImageId"` } - if err := json.Unmarshal(out, &resp); err != nil { + if err := jsonv1.Unmarshal(out, &resp); err != nil { return "", fmt.Errorf("unmarshal response: %v: %s", err, out) } if resp.ImageID == "" { diff --git a/health/state.go b/health/state.go index e6d937b6a..5679a5470 100644 --- a/health/state.go +++ b/health/state.go @@ -6,7 +6,7 @@ package health import ( "crypto/sha256" "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "time" "tailscale.com/feature/buildfeatures" @@ -57,7 +57,7 @@ type UnhealthyState struct { // different runs of the same binary. func (u UnhealthyState) hash() []byte { hasher := sha256.New() - enc := json.NewEncoder(hasher) + enc := jsonv1.NewEncoder(hasher) // hash.Hash.Write never returns an error, so this will only fail if u is // not marshalable, in which case we have much bigger problems. diff --git a/hostinfo/hostinfo_test.go b/hostinfo/hostinfo_test.go index 15b6971b6..2fac616d4 100644 --- a/hostinfo/hostinfo_test.go +++ b/hostinfo/hostinfo_test.go @@ -4,7 +4,7 @@ package hostinfo import ( - "encoding/json" + jsonv1 "encoding/json" "os" "strings" "testing" @@ -15,7 +15,7 @@ func TestNew(t *testing.T) { if hi == nil { t.Fatal("no Hostinfo") } - j, err := json.MarshalIndent(hi, " ", "") + j, err := jsonv1.MarshalIndent(hi, " ", "") if err != nil { t.Fatal(err) } diff --git a/internal/client/tailscale/vip_service.go b/internal/client/tailscale/vip_service.go index 48c59ce45..5f635de15 100644 --- a/internal/client/tailscale/vip_service.go +++ b/internal/client/tailscale/vip_service.go @@ -6,7 +6,7 @@ package tailscale import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/http" @@ -58,7 +58,7 @@ func (client *Client) GetVIPService(ctx context.Context, name tailcfg.ServiceNam return nil, HandleErrorResponse(b, resp) } svc := &VIPService{} - if err := json.Unmarshal(b, svc); err != nil { + if err := jsonv1.Unmarshal(b, svc); err != nil { return nil, err } return svc, nil @@ -81,7 +81,7 @@ func (client *Client) ListVIPServices(ctx context.Context) (*VIPServiceList, err return nil, HandleErrorResponse(b, resp) } result := &VIPServiceList{} - if err := json.Unmarshal(b, result); err != nil { + if err := jsonv1.Unmarshal(b, result); err != nil { return nil, err } return result, nil @@ -92,7 +92,7 @@ func (client *Client) ListVIPServices(ctx context.Context) (*VIPServiceList, err // lost during the update. If the VIPService was created without any IP addresses explicitly set (so that they were // auto-allocated by Tailscale) any subsequent request to this function that does not set any IP addresses will error. func (client *Client) CreateOrUpdateVIPService(ctx context.Context, svc *VIPService) error { - data, err := json.Marshal(svc) + data, err := jsonv1.Marshal(svc) if err != nil { return err } diff --git a/ipn/auditlog/auditlog.go b/ipn/auditlog/auditlog.go index 0460bc4e2..848fc3b8a 100644 --- a/ipn/auditlog/auditlog.go +++ b/ipn/auditlog/auditlog.go @@ -6,7 +6,7 @@ package auditlog import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "sort" @@ -438,7 +438,7 @@ func (s *logStateStore) save(key ipn.ProfileID, txns []*transaction) error { return errors.New("empty key") } - data, err := json.Marshal(txns) + data, err := jsonv1.Marshal(txns) if err != nil { return err } @@ -463,6 +463,6 @@ func (s *logStateStore) load(key ipn.ProfileID) ([]*transaction, error) { } var txns []*transaction - err = json.Unmarshal(data, &txns) + err = jsonv1.Unmarshal(data, &txns) return txns, err } diff --git a/ipn/conffile/conffile.go b/ipn/conffile/conffile.go index 3a2aeffb3..0f75b9052 100644 --- a/ipn/conffile/conffile.go +++ b/ipn/conffile/conffile.go @@ -7,7 +7,7 @@ package conffile import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "fmt" "os" "runtime" @@ -75,7 +75,7 @@ func Load(path string) (*Config, error) { var ver struct { Version string `json:"version"` } - if err := json.Unmarshal(c.Std, &ver); err != nil { + if err := jsonv1.Unmarshal(c.Std, &ver); err != nil { if !buildfeatures.HasHuJSONConf { return nil, fmt.Errorf("error parsing config file %s, which must be valid standard JSON: %w", path, err) } @@ -90,7 +90,7 @@ func Load(path string) (*Config, error) { } c.Version = ver.Version - jd := json.NewDecoder(bytes.NewReader(c.Std)) + jd := jsonv1.NewDecoder(bytes.NewReader(c.Std)) jd.DisallowUnknownFields() err = jd.Decode(&c.Parsed) if err != nil { diff --git a/ipn/ipnauth/actor.go b/ipn/ipnauth/actor.go index 108bdd341..ffa54e2db 100644 --- a/ipn/ipnauth/actor.go +++ b/ipn/ipnauth/actor.go @@ -5,7 +5,7 @@ package ipnauth import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "tailscale.com/client/tailscale/apitype" @@ -100,13 +100,13 @@ func (id ClientID) String() string { // MarshalJSON implements [json.Marshaler]. // It is primarily used for testing. func (id ClientID) MarshalJSON() ([]byte, error) { - return json.Marshal(id.v) + return jsonv1.Marshal(id.v) } // UnmarshalJSON implements [json.Unmarshaler]. // It is primarily used for testing. func (id *ClientID) UnmarshalJSON(b []byte) error { - return json.Unmarshal(b, &id.v) + return jsonv1.Unmarshal(b, &id.v) } type actorWithRequestReason struct { diff --git a/ipn/ipnlocal/c2n.go b/ipn/ipnlocal/c2n.go index 0c228060f..2a21ca937 100644 --- a/ipn/ipnlocal/c2n.go +++ b/ipn/ipnlocal/c2n.go @@ -4,7 +4,7 @@ package ipnlocal import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" "net/http" @@ -130,7 +130,7 @@ func (b *LocalBackend) handleC2N(w http.ResponseWriter, r *http.Request) { func writeJSON(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(v) + jsonv1.NewEncoder(w).Encode(v) } func handleC2NEcho(b *LocalBackend, w http.ResponseWriter, r *http.Request) { @@ -170,7 +170,7 @@ func handleC2NDebugNetMap(b *LocalBackend, w http.ResponseWriter, r *http.Reques // redactAndMarshal redacts private keys from the given netmap, clears fields // that should be omitted, and marshals it to JSON. - redactAndMarshal := func(nm *netmap.NetworkMap, omitFields []string) (json.RawMessage, error) { + redactAndMarshal := func(nm *netmap.NetworkMap, omitFields []string) (jsonv1.RawMessage, error) { for _, f := range omitFields { field := reflect.ValueOf(nm).Elem().FieldByName(f) if !field.IsValid() { @@ -180,7 +180,7 @@ func handleC2NDebugNetMap(b *LocalBackend, w http.ResponseWriter, r *http.Reques field.SetZero() } nm, _ = redactNetmapPrivateKeys(nm) - return json.Marshal(nm) + return jsonv1.Marshal(nm) } var omitFields []string @@ -188,7 +188,7 @@ func handleC2NDebugNetMap(b *LocalBackend, w http.ResponseWriter, r *http.Reques if r.Method == httpm.POST { var req tailcfg.C2NDebugNetmapRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, fmt.Sprintf("failed to decode request body: %v", err), http.StatusBadRequest) return } @@ -298,7 +298,7 @@ func handleC2NSSHUsernames(b *LocalBackend, w http.ResponseWriter, r *http.Reque } var req tailcfg.C2NSSHUsernamesRequest if r.Method == "POST" { - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } diff --git a/ipn/ipnlocal/c2n_test.go b/ipn/ipnlocal/c2n_test.go index 95cd5fa69..4aafbc726 100644 --- a/ipn/ipnlocal/c2n_test.go +++ b/ipn/ipnlocal/c2n_test.go @@ -7,7 +7,7 @@ import ( "bytes" "cmp" "crypto/x509" - "encoding/json" + jsonv1 "encoding/json" "net/http/httptest" "net/url" "os" @@ -128,7 +128,7 @@ func TestHandleC2NTLSCertStatus(t *testing.T) { } if wantStatus == 200 { var got tailcfg.C2NTLSCertInfo - if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + if err := jsonv1.Unmarshal(rec.Body.Bytes(), &got); err != nil { t.Fatalf("bad JSON: %v", err) } if !reflect.DeepEqual(&got, tt.want) { @@ -535,7 +535,7 @@ func TestHandleC2NDebugNetmap(t *testing.T) { rec := httptest.NewRecorder() req := httptest.NewRequest("GET", "/debug/netmap", nil) if tt.req != nil { - b, err := json.Marshal(tt.req) + b, err := jsonv1.Marshal(tt.req) if err != nil { t.Fatalf("json.Marshal: %v", err) } @@ -548,11 +548,11 @@ func TestHandleC2NDebugNetmap(t *testing.T) { t.Fatalf("status code = %v; want %v. Body: %s", res.Status, wantStatus, rec.Body.Bytes()) } var resp tailcfg.C2NDebugNetmapResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + if err := jsonv1.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("bad JSON: %v", err) } got := &netmap.NetworkMap{} - if err := json.Unmarshal(resp.Current, got); err != nil { + if err := jsonv1.Unmarshal(resp.Current, got); err != nil { t.Fatalf("bad JSON: %v", err) } diff --git a/ipn/ipnlocal/cert.go b/ipn/ipnlocal/cert.go index ab49976c8..13c11cfcb 100644 --- a/ipn/ipnlocal/cert.go +++ b/ipn/ipnlocal/cert.go @@ -16,7 +16,7 @@ import ( "crypto/tls" "crypto/x509" "crypto/x509/pkix" - "encoding/json" + jsonv1 "encoding/json" "encoding/pem" "errors" "fmt" @@ -116,7 +116,7 @@ func (b *LocalBackend) GetCertPEMWithValidity(ctx context.Context, domain string if !acmeDebug() { return } - j, _ := json.MarshalIndent(v, "", "\t") + j, _ := jsonv1.MarshalIndent(v, "", "\t") log.Printf("acme %T: %s", v, j) } diff --git a/ipn/ipnlocal/dnsconfig_test.go b/ipn/ipnlocal/dnsconfig_test.go index 71f175148..c4cb9839c 100644 --- a/ipn/ipnlocal/dnsconfig_test.go +++ b/ipn/ipnlocal/dnsconfig_test.go @@ -5,7 +5,7 @@ package ipnlocal import ( "cmp" - "encoding/json" + jsonv1 "encoding/json" "net/netip" "reflect" "testing" @@ -354,8 +354,8 @@ func TestDNSConfigForNetmap(t *testing.T) { var log tstest.MemLogger got := dnsConfigForNetmap(tt.nm, peersMap(tt.peers), tt.prefs.View(), tt.expired, log.Logf, verOS) if !reflect.DeepEqual(got, tt.want) { - gotj, _ := json.MarshalIndent(got, "", "\t") - wantj, _ := json.MarshalIndent(tt.want, "", "\t") + gotj, _ := jsonv1.MarshalIndent(got, "", "\t") + wantj, _ := jsonv1.MarshalIndent(tt.want, "", "\t") t.Errorf("wrong\n got: %s\n\nwant: %s\n", gotj, wantj) } if got := log.String(); got != tt.wantLog { diff --git a/ipn/ipnlocal/local.go b/ipn/ipnlocal/local.go index ffab4b69d..c252bddd3 100644 --- a/ipn/ipnlocal/local.go +++ b/ipn/ipnlocal/local.go @@ -11,7 +11,7 @@ import ( "crypto/sha256" "encoding/binary" "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -7158,7 +7158,7 @@ func (b *LocalBackend) storeRouteInfo(ri appctype.RouteInfo) error { return nil } key := namespaceKeyForCurrentProfile(b.pm, routeInfoStateStoreKey) - bs, err := json.Marshal(ri) + bs, err := jsonv1.Marshal(ri) if err != nil { return err } @@ -7178,7 +7178,7 @@ func (b *LocalBackend) readRouteInfoLocked() (*appctype.RouteInfo, error) { if err != nil { return nil, err } - if err := json.Unmarshal(bs, ri); err != nil { + if err := jsonv1.Unmarshal(bs, ri); err != nil { return nil, err } return ri, nil @@ -7713,7 +7713,7 @@ func (b *LocalBackend) vipServiceHash(services []*tailcfg.VIPService) string { if len(services) == 0 { return "" } - buf, err := json.Marshal(services) + buf, err := jsonv1.Marshal(services) if err != nil { b.logf("vipServiceHashLocked: %v", err) return "" diff --git a/ipn/ipnlocal/local_test.go b/ipn/ipnlocal/local_test.go index 33ecb688c..ab13bed13 100644 --- a/ipn/ipnlocal/local_test.go +++ b/ipn/ipnlocal/local_test.go @@ -6,7 +6,7 @@ package ipnlocal import ( "context" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "maps" @@ -3819,7 +3819,7 @@ func TestTCPHandlerForDstWithVIPService(t *testing.T) { netip.MustParseAddr("fd7a:115c:a1e0:ab12:4843:cd96:8585:8585"), }, } - svcIPMapJSON, err := json.Marshal(svcIPMap) + svcIPMapJSON, err := jsonv1.Marshal(svcIPMap) if err != nil { t.Fatal(err) } @@ -4234,11 +4234,11 @@ func TestDriveManageShares(t *testing.T) { } else { r := <-result - got, err := json.MarshalIndent(r, "", " ") + got, err := jsonv1.MarshalIndent(r, "", " ") if err != nil { t.Fatalf("can't marshal got: %v", err) } - want, err := json.MarshalIndent(e, "", " ") + want, err := jsonv1.MarshalIndent(e, "", " ") if err != nil { t.Fatalf("can't marshal want: %v", err) } @@ -6257,7 +6257,7 @@ func TestConfigFileReload(t *testing.T) { path := filepath.Join(dir, "tailscale.conf") // Write initial config - initialJSON, err := json.Marshal(tc.initial.Parsed) + initialJSON, err := jsonv1.Marshal(tc.initial.Parsed) if err != nil { t.Fatal(err) } @@ -6273,7 +6273,7 @@ func TestConfigFileReload(t *testing.T) { b := newTestLocalBackendWithSys(t, sys) // Update config file - updatedJSON, err := json.Marshal(tc.updated.Parsed) + updatedJSON, err := jsonv1.Marshal(tc.updated.Parsed) if err != nil { t.Fatal(err) } diff --git a/ipn/ipnlocal/network-lock.go b/ipn/ipnlocal/network-lock.go index f26c81011..c5ba72553 100644 --- a/ipn/ipnlocal/network-lock.go +++ b/ipn/ipnlocal/network-lock.go @@ -12,7 +12,7 @@ import ( "crypto/rand" "encoding/base64" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -1185,7 +1185,7 @@ func signNodeKey(nodeInfo tailcfg.TKASignInfo, signer key.NLPrivate) (*tka.NodeK func (b *LocalBackend) tkaInitBegin(ourNodeKey key.NodePublic, aum tka.AUM) (*tailcfg.TKAInitBeginResponse, error) { var req bytes.Buffer - if err := json.NewEncoder(&req).Encode(tailcfg.TKAInitBeginRequest{ + if err := jsonv1.NewEncoder(&req).Encode(tailcfg.TKAInitBeginRequest{ Version: tailcfg.CurrentCapabilityVersion, NodeKey: ourNodeKey, GenesisAUM: aum.Serialize(), @@ -1209,7 +1209,7 @@ func (b *LocalBackend) tkaInitBegin(ourNodeKey key.NodePublic, aum tka.AUM) (*ta return nil, fmt.Errorf("request returned (%d): %s", res.StatusCode, string(body)) } a := new(tailcfg.TKAInitBeginResponse) - err = json.NewDecoder(&io.LimitedReader{R: res.Body, N: 10 * 1024 * 1024}).Decode(a) + err = jsonv1.NewDecoder(&io.LimitedReader{R: res.Body, N: 10 * 1024 * 1024}).Decode(a) res.Body.Close() if err != nil { return nil, fmt.Errorf("decoding JSON: %w", err) @@ -1220,7 +1220,7 @@ func (b *LocalBackend) tkaInitBegin(ourNodeKey key.NodePublic, aum tka.AUM) (*ta func (b *LocalBackend) tkaInitFinish(ourNodeKey key.NodePublic, nks map[tailcfg.NodeID]tkatype.MarshaledSignature, supportDisablement []byte) (*tailcfg.TKAInitFinishResponse, error) { var req bytes.Buffer - if err := json.NewEncoder(&req).Encode(tailcfg.TKAInitFinishRequest{ + if err := jsonv1.NewEncoder(&req).Encode(tailcfg.TKAInitFinishRequest{ Version: tailcfg.CurrentCapabilityVersion, NodeKey: ourNodeKey, Signatures: nks, @@ -1246,7 +1246,7 @@ func (b *LocalBackend) tkaInitFinish(ourNodeKey key.NodePublic, nks map[tailcfg. return nil, fmt.Errorf("request returned (%d): %s", res.StatusCode, string(body)) } a := new(tailcfg.TKAInitFinishResponse) - err = json.NewDecoder(&io.LimitedReader{R: res.Body, N: 1024 * 1024}).Decode(a) + err = jsonv1.NewDecoder(&io.LimitedReader{R: res.Body, N: 1024 * 1024}).Decode(a) res.Body.Close() if err != nil { return nil, fmt.Errorf("decoding JSON: %w", err) @@ -1271,7 +1271,7 @@ func (b *LocalBackend) tkaFetchBootstrap(ourNodeKey key.NodePublic, head tka.AUM } var req bytes.Buffer - if err := json.NewEncoder(&req).Encode(bootstrapReq); err != nil { + if err := jsonv1.NewEncoder(&req).Encode(bootstrapReq); err != nil { return nil, fmt.Errorf("encoding request: %v", err) } @@ -1294,7 +1294,7 @@ func (b *LocalBackend) tkaFetchBootstrap(ourNodeKey key.NodePublic, head tka.AUM return nil, fmt.Errorf("request returned (%d): %s", res.StatusCode, string(body)) } a := new(tailcfg.TKABootstrapResponse) - err = json.NewDecoder(&io.LimitedReader{R: res.Body, N: 1024 * 1024}).Decode(a) + err = jsonv1.NewDecoder(&io.LimitedReader{R: res.Body, N: 1024 * 1024}).Decode(a) res.Body.Close() if err != nil { return nil, fmt.Errorf("decoding JSON: %w", err) @@ -1335,7 +1335,7 @@ func (b *LocalBackend) tkaDoSyncOffer(ourNodeKey key.NodePublic, offer tka.SyncO } var req bytes.Buffer - if err := json.NewEncoder(&req).Encode(syncReq); err != nil { + if err := jsonv1.NewEncoder(&req).Encode(syncReq); err != nil { return nil, fmt.Errorf("encoding request: %v", err) } @@ -1355,7 +1355,7 @@ func (b *LocalBackend) tkaDoSyncOffer(ourNodeKey key.NodePublic, offer tka.SyncO return nil, fmt.Errorf("request returned (%d): %s", res.StatusCode, string(body)) } a := new(tailcfg.TKASyncOfferResponse) - err = json.NewDecoder(&io.LimitedReader{R: res.Body, N: 10 * 1024 * 1024}).Decode(a) + err = jsonv1.NewDecoder(&io.LimitedReader{R: res.Body, N: 10 * 1024 * 1024}).Decode(a) res.Body.Close() if err != nil { return nil, fmt.Errorf("decoding JSON: %w", err) @@ -1384,7 +1384,7 @@ func (b *LocalBackend) tkaDoSyncSend(ourNodeKey key.NodePublic, head tka.AUMHash } var req bytes.Buffer - if err := json.NewEncoder(&req).Encode(sendReq); err != nil { + if err := jsonv1.NewEncoder(&req).Encode(sendReq); err != nil { return nil, fmt.Errorf("encoding request: %v", err) } @@ -1404,7 +1404,7 @@ func (b *LocalBackend) tkaDoSyncSend(ourNodeKey key.NodePublic, head tka.AUMHash return nil, fmt.Errorf("request returned (%d): %s", res.StatusCode, string(body)) } a := new(tailcfg.TKASyncSendResponse) - err = json.NewDecoder(&io.LimitedReader{R: res.Body, N: 10 * 1024 * 1024}).Decode(a) + err = jsonv1.NewDecoder(&io.LimitedReader{R: res.Body, N: 10 * 1024 * 1024}).Decode(a) res.Body.Close() if err != nil { return nil, fmt.Errorf("decoding JSON: %w", err) @@ -1420,7 +1420,7 @@ func (b *LocalBackend) tkaDoDisablement(ourNodeKey key.NodePublic, head tka.AUMH } var req bytes.Buffer - if err := json.NewEncoder(&req).Encode(tailcfg.TKADisableRequest{ + if err := jsonv1.NewEncoder(&req).Encode(tailcfg.TKADisableRequest{ Version: tailcfg.CurrentCapabilityVersion, NodeKey: ourNodeKey, Head: string(headBytes), @@ -1446,7 +1446,7 @@ func (b *LocalBackend) tkaDoDisablement(ourNodeKey key.NodePublic, head tka.AUMH return nil, fmt.Errorf("request returned (%d): %s", res.StatusCode, string(body)) } a := new(tailcfg.TKADisableResponse) - err = json.NewDecoder(&io.LimitedReader{R: res.Body, N: 1024 * 1024}).Decode(a) + err = jsonv1.NewDecoder(&io.LimitedReader{R: res.Body, N: 1024 * 1024}).Decode(a) res.Body.Close() if err != nil { return nil, fmt.Errorf("decoding JSON: %w", err) @@ -1457,7 +1457,7 @@ func (b *LocalBackend) tkaDoDisablement(ourNodeKey key.NodePublic, head tka.AUMH func (b *LocalBackend) tkaSubmitSignature(ourNodeKey key.NodePublic, sig tkatype.MarshaledSignature) (*tailcfg.TKASubmitSignatureResponse, error) { var req bytes.Buffer - if err := json.NewEncoder(&req).Encode(tailcfg.TKASubmitSignatureRequest{ + if err := jsonv1.NewEncoder(&req).Encode(tailcfg.TKASubmitSignatureRequest{ Version: tailcfg.CurrentCapabilityVersion, NodeKey: ourNodeKey, Signature: sig, @@ -1482,7 +1482,7 @@ func (b *LocalBackend) tkaSubmitSignature(ourNodeKey key.NodePublic, sig tkatype return nil, fmt.Errorf("request returned (%d): %s", res.StatusCode, string(body)) } a := new(tailcfg.TKASubmitSignatureResponse) - err = json.NewDecoder(&io.LimitedReader{R: res.Body, N: 1024 * 1024}).Decode(a) + err = jsonv1.NewDecoder(&io.LimitedReader{R: res.Body, N: 1024 * 1024}).Decode(a) res.Body.Close() if err != nil { return nil, fmt.Errorf("decoding JSON: %w", err) @@ -1493,7 +1493,7 @@ func (b *LocalBackend) tkaSubmitSignature(ourNodeKey key.NodePublic, sig tkatype func (b *LocalBackend) tkaReadAffectedSigs(ourNodeKey key.NodePublic, key tkatype.KeyID) (*tailcfg.TKASignaturesUsingKeyResponse, error) { var encodedReq bytes.Buffer - if err := json.NewEncoder(&encodedReq).Encode(tailcfg.TKASignaturesUsingKeyRequest{ + if err := jsonv1.NewEncoder(&encodedReq).Encode(tailcfg.TKASignaturesUsingKeyRequest{ Version: tailcfg.CurrentCapabilityVersion, NodeKey: ourNodeKey, KeyID: key, @@ -1518,7 +1518,7 @@ func (b *LocalBackend) tkaReadAffectedSigs(ourNodeKey key.NodePublic, key tkatyp return nil, fmt.Errorf("request returned (%d): %s", resp.StatusCode, string(body)) } a := new(tailcfg.TKASignaturesUsingKeyResponse) - err = json.NewDecoder(&io.LimitedReader{R: resp.Body, N: 1024 * 1024}).Decode(a) + err = jsonv1.NewDecoder(&io.LimitedReader{R: resp.Body, N: 1024 * 1024}).Decode(a) resp.Body.Close() if err != nil { return nil, fmt.Errorf("decoding JSON: %w", err) diff --git a/ipn/ipnlocal/network-lock_test.go b/ipn/ipnlocal/network-lock_test.go index c7c4c905f..d1cfa07f0 100644 --- a/ipn/ipnlocal/network-lock_test.go +++ b/ipn/ipnlocal/network-lock_test.go @@ -8,7 +8,7 @@ package ipnlocal import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net" "net/http" @@ -107,7 +107,7 @@ func TestTKAEnablementFlow(t *testing.T) { switch r.URL.Path { case "/machine/tka/bootstrap": body := new(tailcfg.TKABootstrapRequest) - if err := json.NewDecoder(r.Body).Decode(body); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(body); err != nil { t.Fatal(err) } if body.Version != tailcfg.CurrentCapabilityVersion { @@ -124,7 +124,7 @@ func TestTKAEnablementFlow(t *testing.T) { out := tailcfg.TKABootstrapResponse{ GenesisAUM: genesisAUM.Serialize(), } - if err := json.NewEncoder(w).Encode(out); err != nil { + if err := jsonv1.NewEncoder(w).Encode(out); err != nil { t.Fatal(err) } @@ -136,7 +136,7 @@ func TestTKAEnablementFlow(t *testing.T) { t.Fatal(err) } w.WriteHeader(200) - if err := json.NewEncoder(w).Encode(tailcfg.TKASyncOfferResponse{ + if err := jsonv1.NewEncoder(w).Encode(tailcfg.TKASyncOfferResponse{ Head: string(head), }); err != nil { t.Fatal(err) @@ -147,7 +147,7 @@ func TestTKAEnablementFlow(t *testing.T) { t.Fatal(err) } w.WriteHeader(200) - if err := json.NewEncoder(w).Encode(tailcfg.TKASyncSendResponse{ + if err := jsonv1.NewEncoder(w).Encode(tailcfg.TKASyncSendResponse{ Head: string(head), }); err != nil { t.Fatal(err) @@ -231,7 +231,7 @@ func TestTKADisablementFlow(t *testing.T) { switch r.URL.Path { case "/machine/tka/bootstrap": body := new(tailcfg.TKABootstrapRequest) - if err := json.NewDecoder(r.Body).Decode(body); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(body); err != nil { t.Fatal(err) } if body.Version != tailcfg.CurrentCapabilityVersion { @@ -259,7 +259,7 @@ func TestTKADisablementFlow(t *testing.T) { out := tailcfg.TKABootstrapResponse{ DisablementSecret: disablement, } - if err := json.NewEncoder(w).Encode(out); err != nil { + if err := jsonv1.NewEncoder(w).Encode(out); err != nil { t.Fatal(err) } @@ -442,7 +442,7 @@ func TestTKASync(t *testing.T) { switch r.URL.Path { case "/machine/tka/sync/offer": body := new(tailcfg.TKASyncOfferRequest) - if err := json.NewDecoder(r.Body).Decode(body); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(body); err != nil { t.Fatal(err) } t.Logf("got sync offer:\n%+v", body) @@ -474,13 +474,13 @@ func TestTKASync(t *testing.T) { t.Logf("responding to sync offer with:\n%+v", resp) w.WriteHeader(200) - if err := json.NewEncoder(w).Encode(resp); err != nil { + if err := jsonv1.NewEncoder(w).Encode(resp); err != nil { t.Fatal(err) } case "/machine/tka/sync/send": body := new(tailcfg.TKASyncSendRequest) - if err := json.NewDecoder(r.Body).Decode(body); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(body); err != nil { t.Fatal(err) } t.Logf("got sync send:\n%+v", body) @@ -507,7 +507,7 @@ func TestTKASync(t *testing.T) { } w.WriteHeader(200) - if err := json.NewEncoder(w).Encode(tailcfg.TKASyncSendResponse{ + if err := jsonv1.NewEncoder(w).Encode(tailcfg.TKASyncSendResponse{ Head: string(head), }); err != nil { t.Fatal(err) @@ -739,7 +739,7 @@ func TestTKADisable(t *testing.T) { switch r.URL.Path { case "/machine/tka/disable": body := new(tailcfg.TKADisableRequest) - if err := json.NewDecoder(r.Body).Decode(body); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(body); err != nil { t.Fatal(err) } if body.Version != tailcfg.CurrentCapabilityVersion { @@ -761,7 +761,7 @@ func TestTKADisable(t *testing.T) { } w.WriteHeader(200) - if err := json.NewEncoder(w).Encode(tailcfg.TKADisableResponse{}); err != nil { + if err := jsonv1.NewEncoder(w).Encode(tailcfg.TKADisableResponse{}); err != nil { t.Fatal(err) } @@ -833,7 +833,7 @@ func TestTKASign(t *testing.T) { switch r.URL.Path { case "/machine/tka/sign": body := new(tailcfg.TKASubmitSignatureRequest) - if err := json.NewDecoder(r.Body).Decode(body); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(body); err != nil { t.Fatal(err) } if body.Version != tailcfg.CurrentCapabilityVersion { @@ -853,7 +853,7 @@ func TestTKASign(t *testing.T) { } w.WriteHeader(200) - if err := json.NewEncoder(w).Encode(tailcfg.TKASubmitSignatureResponse{}); err != nil { + if err := jsonv1.NewEncoder(w).Encode(tailcfg.TKASubmitSignatureResponse{}); err != nil { t.Fatal(err) } @@ -918,7 +918,7 @@ func TestTKAForceDisable(t *testing.T) { switch r.URL.Path { case "/machine/tka/bootstrap": body := new(tailcfg.TKABootstrapRequest) - if err := json.NewDecoder(r.Body).Decode(body); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(body); err != nil { t.Fatal(err) } if body.Version != tailcfg.CurrentCapabilityVersion { @@ -932,7 +932,7 @@ func TestTKAForceDisable(t *testing.T) { out := tailcfg.TKABootstrapResponse{ GenesisAUM: genesis.Serialize(), } - if err := json.NewEncoder(w).Encode(out); err != nil { + if err := jsonv1.NewEncoder(w).Encode(out); err != nil { t.Fatal(err) } @@ -1056,7 +1056,7 @@ func TestTKAAffectedSigs(t *testing.T) { switch r.URL.Path { case "/machine/tka/affected-sigs": body := new(tailcfg.TKASignaturesUsingKeyRequest) - if err := json.NewDecoder(r.Body).Decode(body); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(body); err != nil { t.Fatal(err) } if body.Version != tailcfg.CurrentCapabilityVersion { @@ -1067,7 +1067,7 @@ func TestTKAAffectedSigs(t *testing.T) { } w.WriteHeader(200) - if err := json.NewEncoder(w).Encode(tailcfg.TKASignaturesUsingKeyResponse{ + if err := jsonv1.NewEncoder(w).Encode(tailcfg.TKASignaturesUsingKeyResponse{ Signatures: []tkatype.MarshaledSignature{s.Serialize()}, }); err != nil { t.Fatal(err) @@ -1155,7 +1155,7 @@ func TestTKARecoverCompromisedKeyFlow(t *testing.T) { switch r.URL.Path { case "/machine/tka/sync/send": body := new(tailcfg.TKASyncSendRequest) - if err := json.NewDecoder(r.Body).Decode(body); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(body); err != nil { t.Fatal(err) } t.Logf("got sync send:\n%+v", body) @@ -1181,7 +1181,7 @@ func TestTKARecoverCompromisedKeyFlow(t *testing.T) { } w.WriteHeader(200) - if err := json.NewEncoder(w).Encode(tailcfg.TKASubmitSignatureResponse{}); err != nil { + if err := jsonv1.NewEncoder(w).Encode(tailcfg.TKASubmitSignatureResponse{}); err != nil { t.Fatal(err) } diff --git a/ipn/ipnlocal/peerapi.go b/ipn/ipnlocal/peerapi.go index a045086d4..764f2e721 100644 --- a/ipn/ipnlocal/peerapi.go +++ b/ipn/ipnlocal/peerapi.go @@ -6,7 +6,7 @@ package ipnlocal import ( "context" "encoding/base64" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "hash/crc32" @@ -628,7 +628,7 @@ func (h *peerAPIHandler) handleServeEnv(w http.ResponseWriter, r *http.Request) data.Env = os.Environ() w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(data) + jsonv1.NewEncoder(w).Encode(data) } func (h *peerAPIHandler) handleServeMagicsock(w http.ResponseWriter, r *http.Request) { @@ -842,7 +842,7 @@ func dnsQueryForName(name, typStr string) []byte { func writePrettyDNSReply(w io.Writer, res []byte) (err error) { defer func() { if err != nil { - j, _ := json.Marshal(struct { + j, _ := jsonv1.Marshal(struct { Error string }{err.Error()}) j = append(j, '\n') @@ -902,7 +902,7 @@ func writePrettyDNSReply(w io.Writer, res []byte) (err error) { } } } - j, _ := json.Marshal(gotIPs) + j, _ := jsonv1.Marshal(gotIPs) j = append(j, '\n') w.Write(j) return nil diff --git a/ipn/ipnlocal/peerapi_test.go b/ipn/ipnlocal/peerapi_test.go index 3c9f57f1f..dada49f7d 100644 --- a/ipn/ipnlocal/peerapi_test.go +++ b/ipn/ipnlocal/peerapi_test.go @@ -5,7 +5,7 @@ package ipnlocal import ( "context" - "encoding/json" + jsonv1 "encoding/json" "net/http" "net/http/httptest" "net/netip" @@ -307,7 +307,7 @@ func TestPeerAPIPrettyReplyCNAME(t *testing.T) { t.Errorf("unexpected status code: %v", w.Code) } var addrs []string - json.NewDecoder(w.Body).Decode(&addrs) + jsonv1.NewDecoder(w.Body).Decode(&addrs) if len(addrs) == 0 { t.Fatalf("no addresses returned") } diff --git a/ipn/ipnlocal/profiles.go b/ipn/ipnlocal/profiles.go index 9c2176378..b58f97a00 100644 --- a/ipn/ipnlocal/profiles.go +++ b/ipn/ipnlocal/profiles.go @@ -6,7 +6,7 @@ package ipnlocal import ( "cmp" "crypto/rand" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "runtime" @@ -788,7 +788,7 @@ func (pm *profileManager) DeleteAllProfilesForUser() error { } func (pm *profileManager) writeKnownProfiles() error { - b, err := json.Marshal(pm.knownProfiles) + b, err := jsonv1.Marshal(pm.knownProfiles) if err != nil { return err } @@ -884,7 +884,7 @@ func readKnownProfiles(store ipn.StateStore) (map[ipn.ProfileID]ipn.LoginProfile prfB, err := store.ReadState(ipn.KnownProfilesStateKey) switch err { case nil: - if err := json.Unmarshal(prfB, &knownProfiles); err != nil { + if err := jsonv1.Unmarshal(prfB, &knownProfiles); err != nil { return nil, fmt.Errorf("unmarshaling known profiles: %w", err) } case ipn.ErrStateNotExist: diff --git a/ipn/ipnlocal/serve.go b/ipn/ipnlocal/serve.go index 554761ed7..8b5b82143 100644 --- a/ipn/ipnlocal/serve.go +++ b/ipn/ipnlocal/serve.go @@ -12,7 +12,7 @@ import ( "crypto/sha256" "crypto/tls" "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -325,7 +325,7 @@ func (b *LocalBackend) setServeConfigLocked(config *ipn.ServeConfig, etag string // and not use b.lastServeConfJSON as that might // be a Go nil value, which produces a different // checksum from a JSON "null" value. - prevBytes, err := json.Marshal(prevConfig) + prevBytes, err := jsonv1.Marshal(prevConfig) if err != nil { return fmt.Errorf("error encoding previous config: %w", err) } @@ -338,7 +338,7 @@ func (b *LocalBackend) setServeConfigLocked(config *ipn.ServeConfig, etag string var bs []byte if config != nil { - j, err := json.Marshal(config) + j, err := jsonv1.Marshal(config) if err != nil { return fmt.Errorf("encoding serve config: %w", err) } @@ -956,7 +956,7 @@ func (b *LocalBackend) addAppCapabilitiesHeader(r *httputil.ProxyRequest) error } } - peerCapsSerialized, err := json.Marshal(peerCapsFiltered) + peerCapsSerialized, err := jsonv1.Marshal(peerCapsFiltered) if err != nil { b.logf("serve: failed to serialize filtered PeerCapMap: %v", err) return fmt.Errorf("unable to process app capabilities") @@ -1230,7 +1230,7 @@ func handleC2NVIPServicesGet(b *LocalBackend, w http.ResponseWriter, r *http.Req res.ServicesHash = b.vipServiceHash(res.VIPServices) w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) } var metricIngressCalls = clientmetric.NewCounter("peerapi_ingress") @@ -1397,7 +1397,7 @@ func (b *LocalBackend) reloadServeConfigLocked(prefs ipn.PrefsView) { } b.lastServeConfJSON = mem.B(confj) var conf ipn.ServeConfig - if err := json.Unmarshal(confj, &conf); err != nil { + if err := jsonv1.Unmarshal(confj, &conf); err != nil { b.logf("invalid ServeConfig %q in StateStore: %v", confKey, err) b.serveConfig = ipn.ServeConfigView{} return diff --git a/ipn/ipnlocal/serve_test.go b/ipn/ipnlocal/serve_test.go index c3e5b2ff9..c57fb3941 100644 --- a/ipn/ipnlocal/serve_test.go +++ b/ipn/ipnlocal/serve_test.go @@ -12,7 +12,7 @@ import ( "crypto/sha256" "crypto/tls" "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -224,7 +224,7 @@ func TestGetServeHandler(t *testing.T) { func getEtag(t *testing.T, b any) string { t.Helper() - bts, err := json.Marshal(b) + bts, err := jsonv1.Marshal(b) if err != nil { t.Fatal(err) } @@ -364,7 +364,7 @@ func TestServeConfigServices(t *testing.T) { netip.MustParseAddr("fd7a:115c:a1e0:ab12:4843:cd96:626b:628b"), }, } - svcIPMapJSON, err := json.Marshal(svcIPMap) + svcIPMapJSON, err := jsonv1.Marshal(svcIPMap) if err != nil { t.Fatal(err) } diff --git a/ipn/ipnlocal/ssh_test.go b/ipn/ipnlocal/ssh_test.go index b24cd6732..55d542565 100644 --- a/ipn/ipnlocal/ssh_test.go +++ b/ipn/ipnlocal/ssh_test.go @@ -6,7 +6,7 @@ package ipnlocal import ( - "encoding/json" + jsonv1 "encoding/json" "reflect" "testing" @@ -58,5 +58,5 @@ func TestGetSSHUsernames(t *testing.T) { if err != nil { t.Fatal(err) } - t.Logf("Got: %s", must.Get(json.Marshal(res))) + t.Logf("Got: %s", must.Get(jsonv1.Marshal(res))) } diff --git a/ipn/ipnlocal/web_client.go b/ipn/ipnlocal/web_client.go index a3c9387e4..0dec5868d 100644 --- a/ipn/ipnlocal/web_client.go +++ b/ipn/ipnlocal/web_client.go @@ -7,7 +7,7 @@ package ipnlocal import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -200,7 +200,7 @@ func (b *LocalBackend) doWebClientNoiseRequest(ctx context.Context, id string, s return nil, fmt.Errorf("failed request: %s", body) } var authResp *tailcfg.WebClientAuthResponse - if err := json.Unmarshal(body, &authResp); err != nil { + if err := jsonv1.Unmarshal(body, &authResp); err != nil { return nil, err } return authResp, nil diff --git a/ipn/ipnserver/server.go b/ipn/ipnserver/server.go index d473252e1..58060eb07 100644 --- a/ipn/ipnserver/server.go +++ b/ipn/ipnserver/server.go @@ -8,7 +8,7 @@ package ipnserver import ( "context" "encoding/base64" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -145,7 +145,7 @@ func (s *Server) serveServerStatus(w http.ResponseWriter, r *http.Request) { if lb == nil { res.Error = "backend not ready" } - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) } func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) { diff --git a/ipn/localapi/debug.go b/ipn/localapi/debug.go index 8aca7f009..bfd5b06f1 100644 --- a/ipn/localapi/debug.go +++ b/ipn/localapi/debug.go @@ -7,7 +7,7 @@ package localapi import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" "net" @@ -66,7 +66,7 @@ func (h *Handler) serveDebugPeerEndpointChanges(w http.ResponseWriter, r *http.R return } - e := json.NewEncoder(w) + e := jsonv1.NewEncoder(w) e.SetIndent("", "\t") e.Encode(chs) } @@ -86,7 +86,7 @@ func (h *Handler) serveComponentDebugLogging(w http.ResponseWriter, r *http.Requ res.Error = err.Error() } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) } func (h *Handler) serveDebugDialTypes(w http.ResponseWriter, r *http.Request) { @@ -194,7 +194,7 @@ func (h *Handler) serveDebug(w http.ResponseWriter, r *http.Request) { err = h.b.DebugReSTUN() case "notify": var n ipn.Notify - err = json.NewDecoder(r.Body).Decode(&n) + err = jsonv1.NewDecoder(r.Body).Decode(&n) if err != nil { break } @@ -210,7 +210,7 @@ func (h *Handler) serveDebug(w http.ResponseWriter, r *http.Request) { case "control-knobs": k := h.b.ControlKnobs() w.Header().Set("Content-Type", "application/json") - err = json.NewEncoder(w).Encode(k.AsDebugJSON()) + err = jsonv1.NewEncoder(w).Encode(k.AsDebugJSON()) if err == nil { return } @@ -218,7 +218,7 @@ func (h *Handler) serveDebug(w http.ResponseWriter, r *http.Request) { err = h.b.DebugPickNewDERP() case "force-prefer-derp": var n int - err = json.NewDecoder(r.Body).Decode(&n) + err = jsonv1.NewDecoder(r.Body).Decode(&n) if err != nil { break } @@ -228,7 +228,7 @@ func (h *Handler) serveDebug(w http.ResponseWriter, r *http.Request) { slices.SortFunc(servers, func(a, b netip.Addr) int { return a.Compare(b) }) - err = json.NewEncoder(w).Encode(servers) + err = jsonv1.NewEncoder(w).Encode(servers) if err == nil { return } @@ -274,7 +274,7 @@ func (h *Handler) serveDebugPacketFilterRules(w http.ResponseWriter, r *http.Req } w.Header().Set("Content-Type", "application/json") - enc := json.NewEncoder(w) + enc := jsonv1.NewEncoder(w) enc.SetIndent("", "\t") enc.Encode(nm.PacketFilterRules) } @@ -291,7 +291,7 @@ func (h *Handler) serveDebugPacketFilterMatches(w http.ResponseWriter, r *http.R } w.Header().Set("Content-Type", "application/json") - enc := json.NewEncoder(w) + enc := jsonv1.NewEncoder(w) enc.SetIndent("", "\t") enc.Encode(nm.PacketFilter) } @@ -352,11 +352,11 @@ func (h *Handler) serveDebugBusEvents(w http.ResponseWriter, r *http.Request) { data.To = append(data.To, client.Name()) } - if msg, err := json.Marshal(data); err != nil { + if msg, err := jsonv1.Marshal(data); err != nil { data.Event = debugEventError{Error: fmt.Sprintf( "failed to marshal JSON for %T", event.Event, )} - if errMsg, err := json.Marshal(data); err != nil { + if errMsg, err := jsonv1.Marshal(data); err != nil { fmt.Fprintf(w, `{"Count": %d, "Event":"[ERROR] failed to marshal JSON for %T\n"}`, i, event.Event) @@ -418,7 +418,7 @@ func (h *Handler) serveEventBusGraph(w http.ResponseWriter, r *http.Request) { } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(topics) + jsonv1.NewEncoder(w).Encode(topics) } func (h *Handler) serveDebugLog(w http.ResponseWriter, r *http.Request) { @@ -442,7 +442,7 @@ func (h *Handler) serveDebugLog(w http.ResponseWriter, r *http.Request) { } var logRequest logRequestJSON - if err := json.NewDecoder(r.Body).Decode(&logRequest); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&logRequest); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } @@ -471,5 +471,5 @@ func (h *Handler) serveDebugOptionalFeatures(w http.ResponseWriter, r *http.Requ Features: feature.Registered(), } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(of) + jsonv1.NewEncoder(w).Encode(of) } diff --git a/ipn/localapi/debugderp.go b/ipn/localapi/debugderp.go index 3edbc0856..aa22f9822 100644 --- a/ipn/localapi/debugderp.go +++ b/ipn/localapi/debugderp.go @@ -9,7 +9,7 @@ import ( "cmp" "context" "crypto/tls" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net" "net/http" @@ -38,7 +38,7 @@ func (h *Handler) serveDebugDERPRegion(w http.ResponseWriter, r *http.Request) { } var st ipnstate.DebugDERPRegionReport defer func() { - j, _ := json.Marshal(st) + j, _ := jsonv1.Marshal(st) w.Header().Set("Content-Type", "application/json") w.Write(j) }() diff --git a/ipn/localapi/localapi.go b/ipn/localapi/localapi.go index 9e7c16891..b4fd013f8 100644 --- a/ipn/localapi/localapi.go +++ b/ipn/localapi/localapi.go @@ -7,7 +7,7 @@ package localapi import ( "bytes" "cmp" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -352,7 +352,7 @@ func (h *Handler) serveIDToken(w http.ResponseWriter, r *http.Request) { Audience: aud, NodeKey: nm.NodeKey, } - b, err := json.Marshal(req) + b, err := jsonv1.Marshal(req) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -398,7 +398,7 @@ func (h *Handler) serveBugReport(w http.ResponseWriter, r *http.Request) { if note := r.URL.Query().Get("note"); len(note) > 0 { h.logf("user bugreport note: %s", note) } - hi, _ := json.Marshal(hostinfo.New()) + hi, _ := jsonv1.Marshal(hostinfo.New()) h.logf("user bugreport hostinfo: %s", hi) if err := h.b.HealthTracker().OverallError(); err != nil { h.logf("user bugreport health: %s", err.Error()) @@ -514,7 +514,7 @@ func (h *Handler) serveSetDeviceAttrs(w http.ResponseWriter, r *http.Request) { return } var req map[string]any - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } @@ -581,7 +581,7 @@ func (h *Handler) serveWhoIsWithBackend(w http.ResponseWriter, r *http.Request, if n.Addresses().Len() > 0 { res.CapMap = b.PeerCaps(n.Addresses().At(0).Addr()) } - j, err := json.MarshalIndent(res, "", "\t") + j, err := jsonv1.MarshalIndent(res, "", "\t") if err != nil { http.Error(w, "JSON encoding error", http.StatusInternalServerError) return @@ -712,7 +712,7 @@ func (h *Handler) reloadConfig(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(&res) + jsonv1.NewEncoder(w).Encode(&res) } func (h *Handler) serveResetAuth(w http.ResponseWriter, r *http.Request) { @@ -742,7 +742,7 @@ func (h *Handler) serveCheckIPForwarding(w http.ResponseWriter, r *http.Request) warning = err.Error() } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(struct { + jsonv1.NewEncoder(w).Encode(struct { Warning string }{ Warning: warning, @@ -768,7 +768,7 @@ func (h *Handler) serveCheckReversePathFiltering(w http.ResponseWriter, r *http. warning = msg.String() } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(struct { + jsonv1.NewEncoder(w).Encode(struct { Warning string }{ Warning: warning, @@ -785,7 +785,7 @@ func (h *Handler) serveCheckUDPGROForwarding(w http.ResponseWriter, r *http.Requ warning = err.Error() } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(struct { + jsonv1.NewEncoder(w).Encode(struct { Warning string }{ Warning: warning, @@ -806,7 +806,7 @@ func (h *Handler) serveSetUDPGROForwarding(w http.ResponseWriter, r *http.Reques warning = err.Error() } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(struct { + jsonv1.NewEncoder(w).Encode(struct { Warning string }{ Warning: warning, @@ -825,7 +825,7 @@ func (h *Handler) serveStatus(w http.ResponseWriter, r *http.Request) { } else { st = h.b.StatusWithoutPeers() } - e := json.NewEncoder(w) + e := jsonv1.NewEncoder(w) e.SetIndent("", "\t") e.Encode(st) } @@ -842,7 +842,7 @@ func InUseOtherUserIPNStream(w http.ResponseWriter, r *http.Request, err error) if r.Method != httpm.GET || r.URL.Path != "/localapi/v0/watch-ipn-bus" { return false } - js, err := json.Marshal(&ipn.Notify{ + js, err := jsonv1.Marshal(&ipn.Notify{ Version: version.Long(), State: ptr.To(ipn.InUseOtherUser), ErrMessage: ptr.To(err.Error()), @@ -887,7 +887,7 @@ func (h *Handler) serveWatchIPNBus(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") ctx := r.Context() - enc := json.NewEncoder(w) + enc := jsonv1.NewEncoder(w) h.b.WatchNotificationsAs(ctx, h.Actor, mask, f.Flush, func(roNotify *ipn.Notify) (keepGoing bool) { err := enc.Encode(roNotify) if err != nil { @@ -923,7 +923,7 @@ func (h *Handler) serveStart(w http.ResponseWriter, r *http.Request) { return } var o ipn.Options - if err := json.NewDecoder(r.Body).Decode(&o); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&o); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } @@ -966,7 +966,7 @@ func (h *Handler) servePrefs(w http.ResponseWriter, r *http.Request) { return } mp := new(ipn.MaskedPrefs) - if err := json.NewDecoder(r.Body).Decode(mp); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(mp); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } @@ -974,7 +974,7 @@ func (h *Handler) servePrefs(w http.ResponseWriter, r *http.Request) { if err := h.b.MaybeClearAppConnector(mp); err != nil { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusInternalServerError) - json.NewEncoder(w).Encode(resJSON{Error: err.Error()}) + jsonv1.NewEncoder(w).Encode(resJSON{Error: err.Error()}) return } } @@ -983,7 +983,7 @@ func (h *Handler) servePrefs(w http.ResponseWriter, r *http.Request) { if err != nil { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusBadRequest) - json.NewEncoder(w).Encode(resJSON{Error: err.Error()}) + jsonv1.NewEncoder(w).Encode(resJSON{Error: err.Error()}) return } case httpm.GET, httpm.HEAD: @@ -993,7 +993,7 @@ func (h *Handler) servePrefs(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Type", "application/json") - e := json.NewEncoder(w) + e := jsonv1.NewEncoder(w) e.SetIndent("", "\t") e.Encode(prefs) } @@ -1012,7 +1012,7 @@ func (h *Handler) serveCheckPrefs(w http.ResponseWriter, r *http.Request) { return } p := new(ipn.Prefs) - if err := json.NewDecoder(r.Body).Decode(p); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(p); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } @@ -1022,7 +1022,7 @@ func (h *Handler) serveCheckPrefs(w http.ResponseWriter, r *http.Request) { res.Error = err.Error() } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) } // WriteErrorJSON writes a JSON object (with a single "error" string field) to w @@ -1037,7 +1037,7 @@ func WriteErrorJSON(w http.ResponseWriter, err error) { type E struct { Error string `json:"error"` } - json.NewEncoder(w).Encode(E{err.Error()}) + jsonv1.NewEncoder(w).Encode(E{err.Error()}) } func (h *Handler) serveSetDNS(w http.ResponseWriter, r *http.Request) { @@ -1056,7 +1056,7 @@ func (h *Handler) serveSetDNS(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(struct{}{}) + jsonv1.NewEncoder(w).Encode(struct{}{}) } func (h *Handler) serveDERPMap(w http.ResponseWriter, r *http.Request) { @@ -1065,7 +1065,7 @@ func (h *Handler) serveDERPMap(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Type", "application/json") - e := json.NewEncoder(w) + e := jsonv1.NewEncoder(w) e.SetIndent("", "\t") e.Encode(h.b.DERPMap()) } @@ -1147,7 +1147,7 @@ func (h *Handler) servePing(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) } func (h *Handler) serveDial(w http.ResponseWriter, r *http.Request) { @@ -1219,7 +1219,7 @@ func (h *Handler) serveSetPushDeviceToken(w http.ResponseWriter, r *http.Request return } var params apitype.SetPushDeviceTokenRequest - if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(¶ms); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } @@ -1237,7 +1237,7 @@ func (h *Handler) serveHandlePushMessage(w http.ResponseWriter, r *http.Request) return } var pushMessageBody map[string]any - if err := json.NewDecoder(r.Body).Decode(&pushMessageBody); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&pushMessageBody); err != nil { http.Error(w, "failed to decode JSON body: "+err.Error(), http.StatusBadRequest) return } @@ -1260,7 +1260,7 @@ func (h *Handler) serveUploadClientMetrics(w http.ResponseWriter, r *http.Reques } var clientMetrics []clientMetricJSON - if err := json.NewDecoder(r.Body).Decode(&clientMetrics); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&clientMetrics); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } @@ -1292,7 +1292,7 @@ func (h *Handler) serveUploadClientMetrics(w http.ResponseWriter, r *http.Reques } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(struct{}{}) + jsonv1.NewEncoder(w).Encode(struct{}{}) } func (h *Handler) serveSetGUIVisible(w http.ResponseWriter, r *http.Request) { @@ -1306,7 +1306,7 @@ func (h *Handler) serveSetGUIVisible(w http.ResponseWriter, r *http.Request) { SessionID string // the last SessionID sent to the client in ipn.Notify.SessionID } var req setGUIVisibleRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } @@ -1341,7 +1341,7 @@ func (h *Handler) serveSetUseExitNodeEnabled(w http.ResponseWriter, r *http.Requ return } w.Header().Set("Content-Type", "application/json") - e := json.NewEncoder(w) + e := jsonv1.NewEncoder(w) e.SetIndent("", "\t") e.Encode(prefs) } @@ -1369,7 +1369,7 @@ func (h *Handler) serveProfiles(w http.ResponseWriter, r *http.Request) { switch r.Method { case httpm.GET: w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(h.b.ListProfiles()) + jsonv1.NewEncoder(w).Encode(h.b.ListProfiles()) case httpm.PUT: err := h.b.NewProfile() if err != nil { @@ -1391,7 +1391,7 @@ func (h *Handler) serveProfiles(w http.ResponseWriter, r *http.Request) { switch r.Method { case httpm.GET: w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(h.b.CurrentProfile()) + jsonv1.NewEncoder(w).Encode(h.b.CurrentProfile()) default: http.Error(w, "use GET", http.StatusMethodNotAllowed) } @@ -1410,7 +1410,7 @@ func (h *Handler) serveProfiles(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(profiles[profileIndex]) + jsonv1.NewEncoder(w).Encode(profiles[profileIndex]) case httpm.POST: err := h.b.SwitchProfile(profileID) if err != nil { @@ -1460,7 +1460,7 @@ func (h *Handler) serveQueryFeature(w http.ResponseWriter, r *http.Request) { return } - b, err := json.Marshal(&tailcfg.QueryFeatureRequest{ + b, err := jsonv1.Marshal(&tailcfg.QueryFeatureRequest{ NodeKey: nm.NodeKey, Feature: feature, }) @@ -1521,7 +1521,7 @@ func (h *Handler) serveUpdateCheck(w http.ResponseWriter, r *http.Request) { cv = &tailcfg.ClientVersion{RunningLatest: true} } - json.NewEncoder(w).Encode(cv) + jsonv1.NewEncoder(w).Encode(cv) } // serveDNSOSConfig serves the current system DNS configuration as a JSON object, if @@ -1563,7 +1563,7 @@ func (h *Handler) serveDNSOSConfig(w http.ResponseWriter, r *http.Request) { SearchDomains: searchDomains, MatchDomains: matchDomains, } - json.NewEncoder(w).Encode(response) + jsonv1.NewEncoder(w).Encode(response) } // serveDNSQuery provides the ability to perform DNS queries using the internal @@ -1607,7 +1607,7 @@ func (h *Handler) serveDNSQuery(w http.ResponseWriter, r *http.Request) { } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(&apitype.DNSQueryResponse{ + jsonv1.NewEncoder(w).Encode(&apitype.DNSQueryResponse{ Bytes: res, Resolvers: rrs, }) @@ -1666,7 +1666,7 @@ func (h *Handler) serveSuggestExitNode(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) } // Shutdown is an eventbus value published when tailscaled shutdown @@ -1723,5 +1723,5 @@ func (h *Handler) serveGetAppcRouteInfo(w http.ResponseWriter, r *http.Request) } } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(res) + jsonv1.NewEncoder(w).Encode(res) } diff --git a/ipn/localapi/localapi_drive.go b/ipn/localapi/localapi_drive.go index eb765ec2e..acaa85eea 100644 --- a/ipn/localapi/localapi_drive.go +++ b/ipn/localapi/localapi_drive.go @@ -6,7 +6,7 @@ package localapi import ( - "encoding/json" + jsonv1 "encoding/json" "errors" "io" "net/http" @@ -53,7 +53,7 @@ func (h *Handler) serveShares(w http.ResponseWriter, r *http.Request) { switch r.Method { case httpm.PUT: var share drive.Share - err := json.NewDecoder(r.Body).Decode(&share) + err := jsonv1.NewDecoder(r.Body).Decode(&share) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return @@ -105,7 +105,7 @@ func (h *Handler) serveShares(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) case httpm.POST: var names [2]string - err := json.NewDecoder(r.Body).Decode(&names) + err := jsonv1.NewDecoder(r.Body).Decode(&names) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return @@ -130,7 +130,7 @@ func (h *Handler) serveShares(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) case httpm.GET: shares := h.b.DriveGetShares() - err := json.NewEncoder(w).Encode(shares) + err := jsonv1.NewEncoder(w).Encode(shares) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/ipn/localapi/localapi_test.go b/ipn/localapi/localapi_test.go index fa24717f7..4412b8005 100644 --- a/ipn/localapi/localapi_test.go +++ b/ipn/localapi/localapi_test.go @@ -6,7 +6,7 @@ package localapi import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "go/ast" @@ -77,7 +77,7 @@ func TestSetPushDeviceToken(t *testing.T) { c := s.Client() want := "my-test-device-token" - body, err := json.Marshal(apitype.SetPushDeviceTokenRequest{PushDeviceToken: want}) + body, err := jsonv1.Marshal(apitype.SetPushDeviceTokenRequest{PushDeviceToken: want}) if err != nil { t.Fatal(err) } @@ -172,7 +172,7 @@ func TestWhoIsArgTypes(t *testing.T) { t.Fatalf("response code %d", rec.Code) } var res apitype.WhoIsResponse - if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil { + if err := jsonv1.Unmarshal(rec.Body.Bytes(), &res); err != nil { t.Fatalf("parsing response %#q: %v", rec.Body.Bytes(), err) } if got, want := res.Node.ID, tailcfg.NodeID(123); got != want { diff --git a/ipn/localapi/serve.go b/ipn/localapi/serve.go index 56c8b486c..4f4f9fb51 100644 --- a/ipn/localapi/serve.go +++ b/ipn/localapi/serve.go @@ -8,7 +8,7 @@ package localapi import ( "crypto/sha256" "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "net/http" @@ -32,7 +32,7 @@ func (h *Handler) serveServeConfig(w http.ResponseWriter, r *http.Request) { return } config := h.b.ServeConfig() - bts, err := json.Marshal(config) + bts, err := jsonv1.Marshal(config) if err != nil { http.Error(w, "error encoding config: "+err.Error(), http.StatusInternalServerError) return @@ -48,7 +48,7 @@ func (h *Handler) serveServeConfig(w http.ResponseWriter, r *http.Request) { return } configIn := new(ipn.ServeConfig) - if err := json.NewDecoder(r.Body).Decode(configIn); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(configIn); err != nil { WriteErrorJSON(w, fmt.Errorf("decoding config: %w", err)) return } diff --git a/ipn/localapi/syspolicy_api.go b/ipn/localapi/syspolicy_api.go index edb82e042..a16d0deeb 100644 --- a/ipn/localapi/syspolicy_api.go +++ b/ipn/localapi/syspolicy_api.go @@ -6,7 +6,7 @@ package localapi import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/http" "strings" @@ -62,7 +62,7 @@ func (h *Handler) servePolicy(w http.ResponseWriter, r *http.Request) { } w.Header().Set("Content-Type", "application/json") - e := json.NewEncoder(w) + e := jsonv1.NewEncoder(w) e.SetIndent("", "\t") e.Encode(effectivePolicy) } diff --git a/ipn/localapi/tailnetlock.go b/ipn/localapi/tailnetlock.go index 4baadb733..50eff887f 100644 --- a/ipn/localapi/tailnetlock.go +++ b/ipn/localapi/tailnetlock.go @@ -6,7 +6,7 @@ package localapi import ( - "encoding/json" + jsonv1 "encoding/json" "io" "net/http" "strconv" @@ -43,7 +43,7 @@ func (h *Handler) serveTKAStatus(w http.ResponseWriter, r *http.Request) { return } - j, err := json.MarshalIndent(h.b.NetworkLockStatus(), "", "\t") + j, err := jsonv1.MarshalIndent(h.b.NetworkLockStatus(), "", "\t") if err != nil { http.Error(w, "JSON encoding error", http.StatusInternalServerError) return @@ -67,7 +67,7 @@ func (h *Handler) serveTKASign(w http.ResponseWriter, r *http.Request) { RotationPublic []byte } var req signRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } @@ -96,7 +96,7 @@ func (h *Handler) serveTKAInit(w http.ResponseWriter, r *http.Request) { SupportDisablement []byte } var req initRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } @@ -111,7 +111,7 @@ func (h *Handler) serveTKAInit(w http.ResponseWriter, r *http.Request) { return } - j, err := json.MarshalIndent(h.b.NetworkLockStatus(), "", "\t") + j, err := jsonv1.MarshalIndent(h.b.NetworkLockStatus(), "", "\t") if err != nil { http.Error(w, "JSON encoding error", http.StatusInternalServerError) return @@ -135,7 +135,7 @@ func (h *Handler) serveTKAModify(w http.ResponseWriter, r *http.Request) { RemoveKeys []tka.Key } var req modifyRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } @@ -162,7 +162,7 @@ func (h *Handler) serveTKAWrapPreauthKey(w http.ResponseWriter, r *http.Request) TKAKey string // key.NLPrivate.MarshalText } var req wrapRequest - if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 12*1024)).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(http.MaxBytesReader(w, r.Body, 12*1024)).Decode(&req); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } @@ -195,13 +195,13 @@ func (h *Handler) serveTKAVerifySigningDeeplink(w http.ResponseWriter, r *http.R URL string } var req verifyRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "invalid JSON for verifyRequest body", http.StatusBadRequest) return } res := h.b.NetworkLockVerifySigningDeeplink(req.URL) - j, err := json.MarshalIndent(res, "", "\t") + j, err := jsonv1.MarshalIndent(res, "", "\t") if err != nil { http.Error(w, "JSON encoding error", http.StatusInternalServerError) return @@ -246,7 +246,7 @@ func (h *Handler) serveTKALocalDisable(w http.ResponseWriter, r *http.Request) { // Require a JSON stanza for the body as an additional CSRF protection. var req struct{} - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } @@ -280,7 +280,7 @@ func (h *Handler) serveTKALog(w http.ResponseWriter, r *http.Request) { return } - j, err := json.MarshalIndent(updates, "", "\t") + j, err := jsonv1.MarshalIndent(updates, "", "\t") if err != nil { http.Error(w, "JSON encoding error", http.StatusInternalServerError) return @@ -306,7 +306,7 @@ func (h *Handler) serveTKAAffectedSigs(w http.ResponseWriter, r *http.Request) { return } - j, err := json.MarshalIndent(sigs, "", "\t") + j, err := jsonv1.MarshalIndent(sigs, "", "\t") if err != nil { http.Error(w, "JSON encoding error", http.StatusInternalServerError) return @@ -330,7 +330,7 @@ func (h *Handler) serveTKAGenerateRecoveryAUM(w http.ResponseWriter, r *http.Req ForkFrom string } var req verifyRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := jsonv1.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "invalid JSON for verifyRequest body", http.StatusBadRequest) return } diff --git a/ipn/prefs.go b/ipn/prefs.go index 81dd1c1c3..6d851a730 100644 --- a/ipn/prefs.go +++ b/ipn/prefs.go @@ -6,7 +6,7 @@ package ipn import ( "bytes" "cmp" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "log" @@ -625,7 +625,7 @@ func (p PrefsView) ToBytes() []byte { } func (p *Prefs) ToBytes() []byte { - data, err := json.MarshalIndent(p, "", "\t") + data, err := jsonv1.MarshalIndent(p, "", "\t") if err != nil { log.Fatalf("Prefs marshal: %v\n", err) } @@ -957,7 +957,7 @@ func PrefsFromBytes(b []byte, base *Prefs) error { return nil } - return json.Unmarshal(b, base) + return jsonv1.Unmarshal(b, base) } var jsonEscapedZero = []byte(`\u0000`) diff --git a/ipn/prefs_test.go b/ipn/prefs_test.go index 233616409..90d32f4d9 100644 --- a/ipn/prefs_test.go +++ b/ipn/prefs_test.go @@ -4,7 +4,7 @@ package ipn import ( - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "net/netip" @@ -750,8 +750,8 @@ func TestPrefsApplyEdits(t *testing.T) { got := tt.prefs.Clone() got.ApplyEdits(tt.edit) if !got.Equals(tt.want) { - gotj, _ := json.Marshal(got) - wantj, _ := json.Marshal(tt.want) + gotj, _ := jsonv1.Marshal(got) + wantj, _ := jsonv1.Marshal(tt.want) t.Errorf("fail.\n got: %s\nwant: %s\n", gotj, wantj) } }) @@ -1114,13 +1114,13 @@ func TestNotifyPrefsJSONRoundtrip(t *testing.T) { if n.Prefs != nil && n.Prefs.Valid() { t.Fatal("Prefs should not be valid at start") } - b, err := json.Marshal(n) + b, err := jsonv1.Marshal(n) if err != nil { t.Fatal(err) } var n2 Notify - if err := json.Unmarshal(b, &n2); err != nil { + if err := jsonv1.Unmarshal(b, &n2); err != nil { t.Fatal(err) } if n2.Prefs != nil && n2.Prefs.Valid() { @@ -1132,7 +1132,7 @@ func TestNotifyPrefsJSONRoundtrip(t *testing.T) { // downgrade to older versions that require it. func TestPrefsDowngrade(t *testing.T) { var p Prefs - j, err := json.Marshal(p) + j, err := jsonv1.Marshal(p) if err != nil { t.Fatal(err) } @@ -1141,7 +1141,7 @@ func TestPrefsDowngrade(t *testing.T) { AllowSingleHosts bool } var op oldPrefs - if err := json.Unmarshal(j, &op); err != nil { + if err := jsonv1.Unmarshal(j, &op); err != nil { t.Fatal(err) } if !op.AllowSingleHosts { diff --git a/ipn/store/kubestore/store_kube_test.go b/ipn/store/kubestore/store_kube_test.go index 8c8e5e870..76db5b713 100644 --- a/ipn/store/kubestore/store_kube_test.go +++ b/ipn/store/kubestore/store_kube_test.go @@ -6,7 +6,7 @@ package kubestore import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "strings" "testing" @@ -718,7 +718,7 @@ func TestNewWithClient(t *testing.T) { return } var got map[ipn.StateKey][]byte - if err := json.Unmarshal(gotJSON, &got); err != nil { + if err := jsonv1.Unmarshal(gotJSON, &got); err != nil { t.Errorf("failed to unmarshal memory store JSON: %v", err) return } diff --git a/ipn/store/mem/store_mem.go b/ipn/store/mem/store_mem.go index 6f474ce99..a91b66fa7 100644 --- a/ipn/store/mem/store_mem.go +++ b/ipn/store/mem/store_mem.go @@ -6,7 +6,7 @@ package mem import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "sync" xmaps "golang.org/x/exp/maps" @@ -71,7 +71,7 @@ func (s *Store) LoadFromMap(m map[string][]byte) { func (s *Store) LoadFromJSON(data []byte) error { s.mu.Lock() defer s.mu.Unlock() - return json.Unmarshal(data, &s.cache) + return jsonv1.Unmarshal(data, &s.cache) } // ExportToJSON exports the content of the cache to @@ -83,5 +83,5 @@ func (s *Store) ExportToJSON() ([]byte, error) { // Avoid "null" serialization. return []byte("{}"), nil } - return json.MarshalIndent(s.cache, "", " ") + return jsonv1.MarshalIndent(s.cache, "", " ") } diff --git a/ipn/store/stores.go b/ipn/store/stores.go index bf175da41..022e60425 100644 --- a/ipn/store/stores.go +++ b/ipn/store/stores.go @@ -6,7 +6,7 @@ package store import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "iter" @@ -189,7 +189,7 @@ func NewFileStore(logf logger.Logf, path string) (ipn.StateStore, error) { path: path, cache: map[ipn.StateKey][]byte{}, } - if err := json.Unmarshal(bs, &ret.cache); err != nil { + if err := jsonv1.Unmarshal(bs, &ret.cache); err != nil { return nil, err } @@ -215,7 +215,7 @@ func (s *FileStore) WriteState(id ipn.StateKey, bs []byte) error { return nil } s.cache[id] = bytes.Clone(bs) - bs, err := json.MarshalIndent(s.cache, "", " ") + bs, err := jsonv1.MarshalIndent(s.cache, "", " ") if err != nil { return err } @@ -264,7 +264,7 @@ func maybeMigrateLocalStateFile(logf logger.Logf, path string) error { return err } var content map[string]any - if err := json.Unmarshal(bs, &content); err != nil { + if err := jsonv1.Unmarshal(bs, &content); err != nil { return fmt.Errorf("failed to unmarshal %q: %w", path, err) } keys := slices.Sorted(maps.Keys(content)) diff --git a/jsondb/db.go b/jsondb/db.go index 68bb05af4..2b599ecff 100644 --- a/jsondb/db.go +++ b/jsondb/db.go @@ -6,7 +6,7 @@ package jsondb import ( - "encoding/json" + jsonv1 "encoding/json" "errors" "io/fs" "os" @@ -36,7 +36,7 @@ func Open[T any](path string) (*DB[T], error) { } var val T - if err := json.Unmarshal(bs, &val); err != nil { + if err := jsonv1.Unmarshal(bs, &val); err != nil { return nil, err } @@ -48,7 +48,7 @@ func Open[T any](path string) (*DB[T], error) { // Save writes db.Data back to disk. func (db *DB[T]) Save() error { - bs, err := json.Marshal(db.Data) + bs, err := jsonv1.Marshal(db.Data) if err != nil { return err } diff --git a/k8s-operator/api-proxy/proxy.go b/k8s-operator/api-proxy/proxy.go index 762a52f1f..4bf9ce755 100644 --- a/k8s-operator/api-proxy/proxy.go +++ b/k8s-operator/api-proxy/proxy.go @@ -9,7 +9,7 @@ import ( "bytes" "context" "crypto/tls" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -391,7 +391,7 @@ func (ap *APIServerProxy) recordRequestAsEvent(req *http.Request, who *apitype.W fail := true for _, addr := range addrs { data := new(bytes.Buffer) - if err := json.NewEncoder(data).Encode(event); err != nil { + if err := jsonv1.NewEncoder(data).Encode(event); err != nil { return fmt.Errorf("error marshaling request event: %w", err) } diff --git a/k8s-operator/api-proxy/proxy_events_test.go b/k8s-operator/api-proxy/proxy_events_test.go index 8bcf48436..a4855b85d 100644 --- a/k8s-operator/api-proxy/proxy_events_test.go +++ b/k8s-operator/api-proxy/proxy_events_test.go @@ -7,7 +7,7 @@ package apiproxy import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "errors" "io" "net/http" @@ -331,7 +331,7 @@ func TestRecordRequestAsEvent(t *testing.T) { Request: sessionrecording.Request{ Method: "POST", Path: "/api/v1/pods", - Body: json.RawMessage(`{"foo":"bar"}`), + Body: jsonv1.RawMessage(`{"foo":"bar"}`), QueryParameters: url.Values{}, }, Kubernetes: sessionrecording.KubernetesRequestInfo{ @@ -523,7 +523,7 @@ func TestRecordRequestAsEvent(t *testing.T) { if tt.wantEvent != nil { for _, sentData := range sender.sent { var got sessionrecording.Event - if err := json.Unmarshal(sentData, &got); err != nil { + if err := jsonv1.Unmarshal(sentData, &got); err != nil { t.Fatalf("failed to unmarshal sent event: %v", err) } diff --git a/k8s-operator/sessionrecording/fakes/fakes.go b/k8s-operator/sessionrecording/fakes/fakes.go index 94853df19..6424b509c 100644 --- a/k8s-operator/sessionrecording/fakes/fakes.go +++ b/k8s-operator/sessionrecording/fakes/fakes.go @@ -9,7 +9,7 @@ package fakes import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "fmt" "math/rand" "net" @@ -96,7 +96,7 @@ func (t *TestSessionRecorder) Bytes() []byte { func CastLine(t *testing.T, p []byte, clock tstime.Clock) []byte { t.Helper() - j, err := json.Marshal([]any{ + j, err := jsonv1.Marshal([]any{ clock.Now().Sub(clock.Now()).Seconds(), "o", string(p), @@ -119,7 +119,7 @@ func AsciinemaCastHeaderMsg(t *testing.T, width, height int) []byte { Width: width, Height: height, } - bs, err := json.Marshal(ch) + bs, err := jsonv1.Marshal(ch) if err != nil { t.Fatalf("error marshalling CastHeader: %v", err) } diff --git a/k8s-operator/sessionrecording/spdy/conn.go b/k8s-operator/sessionrecording/spdy/conn.go index 9fefca11f..8592ee642 100644 --- a/k8s-operator/sessionrecording/spdy/conn.go +++ b/k8s-operator/sessionrecording/spdy/conn.go @@ -11,7 +11,7 @@ import ( "bytes" "context" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net" "net/http" @@ -146,7 +146,7 @@ func (c *conn) Read(b []byte) (int, error) { case c.resizeStreamID.Load(): var msg spdyResizeMsg - if err = json.Unmarshal(sf.Payload, &msg); err != nil { + if err = jsonv1.Unmarshal(sf.Payload, &msg); err != nil { return 0, fmt.Errorf("error umarshalling resize msg: %w", err) } c.ch.Width = msg.Width diff --git a/k8s-operator/sessionrecording/spdy/conn_test.go b/k8s-operator/sessionrecording/spdy/conn_test.go index 3c1cb8427..a025fbe06 100644 --- a/k8s-operator/sessionrecording/spdy/conn_test.go +++ b/k8s-operator/sessionrecording/spdy/conn_test.go @@ -7,7 +7,7 @@ package spdy import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "reflect" "testing" @@ -320,7 +320,7 @@ func Test_conn_WriteRand(t *testing.T) { func resizeMsgBytes(t *testing.T, width, height int) []byte { t.Helper() - bs, err := json.Marshal(spdyResizeMsg{Width: width, Height: height}) + bs, err := jsonv1.Marshal(spdyResizeMsg{Width: width, Height: height}) if err != nil { t.Fatalf("error marshalling resizeMsg: %v", err) } diff --git a/k8s-operator/sessionrecording/tsrecorder/tsrecorder.go b/k8s-operator/sessionrecording/tsrecorder/tsrecorder.go index a5bdf7ddd..1f125fe26 100644 --- a/k8s-operator/sessionrecording/tsrecorder/tsrecorder.go +++ b/k8s-operator/sessionrecording/tsrecorder/tsrecorder.go @@ -7,7 +7,7 @@ package tsrecorder import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" "sync" @@ -87,7 +87,7 @@ func (rec *Client) write(data any) error { if rec.failedOpen { return nil } - j, err := json.Marshal(data) + j, err := jsonv1.Marshal(data) if err != nil { return fmt.Errorf("error marshalling data as json: %v", err) } diff --git a/k8s-operator/sessionrecording/ws/conn.go b/k8s-operator/sessionrecording/ws/conn.go index a618f85fb..6072228b7 100644 --- a/k8s-operator/sessionrecording/ws/conn.go +++ b/k8s-operator/sessionrecording/ws/conn.go @@ -10,7 +10,7 @@ package ws import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -198,7 +198,7 @@ func (c *conn) Read(b []byte) (int, error) { // https://github.com/kubernetes/client-go/blob/v0.30.0-rc.1/tools/remotecommand/websocket.go#L218 if readMsg.streamID.Load() == remotecommand.StreamResize && c.hasTerm { var msg tsrecorder.ResizeMsg - if err = json.Unmarshal(readMsg.payload, &msg); err != nil { + if err = jsonv1.Unmarshal(readMsg.payload, &msg); err != nil { return 0, fmt.Errorf("error umarshalling resize message: %w", err) } diff --git a/kube/egressservices/egressservices.go b/kube/egressservices/egressservices.go index 2515f1bf3..bb1081616 100644 --- a/kube/egressservices/egressservices.go +++ b/kube/egressservices/egressservices.go @@ -9,7 +9,7 @@ package egressservices import ( - "encoding/json" + jsonv1 "encoding/json" "net/netip" ) @@ -62,15 +62,15 @@ type PortMaps map[PortMap]struct{} // with efficient lookups in code. It implements custom JSON marshalling // methods to convert between being a list in JSON and a set (map with empty // values) in code. -var _ json.Marshaler = &PortMaps{} -var _ json.Marshaler = PortMaps{} -var _ json.Unmarshaler = &PortMaps{} +var _ jsonv1.Marshaler = &PortMaps{} +var _ jsonv1.Marshaler = PortMaps{} +var _ jsonv1.Unmarshaler = &PortMaps{} func (p *PortMaps) UnmarshalJSON(data []byte) error { *p = make(map[PortMap]struct{}) var l []PortMap - if err := json.Unmarshal(data, &l); err != nil { + if err := jsonv1.Unmarshal(data, &l); err != nil { return err } @@ -87,7 +87,7 @@ func (p PortMaps) MarshalJSON() ([]byte, error) { l = append(l, pm) } - return json.Marshal(l) + return jsonv1.Marshal(l) } // Status represents the currently configured firewall rules for all egress diff --git a/kube/egressservices/egressservices_test.go b/kube/egressservices/egressservices_test.go index 806ad91be..d7bd7c219 100644 --- a/kube/egressservices/egressservices_test.go +++ b/kube/egressservices/egressservices_test.go @@ -4,7 +4,7 @@ package egressservices import ( - "encoding/json" + jsonv1 "encoding/json" "testing" "github.com/google/go-cmp/cmp" @@ -32,7 +32,7 @@ func Test_jsonUnmarshalConfig(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cfg := Config{} - if gotErr := json.Unmarshal(tt.bs, &cfg); (gotErr != nil) != tt.wantsErr { + if gotErr := jsonv1.Unmarshal(tt.bs, &cfg); (gotErr != nil) != tt.wantsErr { t.Errorf("json.Unmarshal returned error %v, wants error %v", gotErr, tt.wantsErr) } if diff := cmp.Diff(cfg, tt.wantsCfg); diff != "" { @@ -65,7 +65,7 @@ func Test_jsonMarshalConfig(t *testing.T) { MatchPort: tt.matchPort, TargetPort: tt.targetPort}: {}}} - gotBs, gotErr := json.Marshal(&cfg) + gotBs, gotErr := jsonv1.Marshal(&cfg) if gotErr != nil { t.Errorf("json.Marshal(%+#v) returned unexpected error %v", cfg, gotErr) } diff --git a/kube/k8s-proxy/conf/conf.go b/kube/k8s-proxy/conf/conf.go index 529495243..565d0a565 100644 --- a/kube/k8s-proxy/conf/conf.go +++ b/kube/k8s-proxy/conf/conf.go @@ -8,7 +8,7 @@ package conf import ( - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "net/netip" @@ -83,7 +83,7 @@ func Load(raw []byte) (c Config, err error) { return c, fmt.Errorf("error parsing config as HuJSON/JSON: %w", err) } var ver VersionedConfig - if err := json.Unmarshal(c.Std, &ver); err != nil { + if err := jsonv1.Unmarshal(c.Std, &ver); err != nil { return c, fmt.Errorf("error parsing config: %w", err) } rootV1Alpha1 := (ver.Version == v1Alpha1) diff --git a/kube/kubeclient/client.go b/kube/kubeclient/client.go index 0ed960f4d..dd5b1d33e 100644 --- a/kube/kubeclient/client.go +++ b/kube/kubeclient/client.go @@ -14,7 +14,7 @@ import ( "context" "crypto/tls" "crypto/x509" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -167,7 +167,7 @@ func getError(resp *http.Response) error { return nil } st := &kubeapi.Status{} - if err := json.NewDecoder(resp.Body).Decode(st); err != nil { + if err := jsonv1.NewDecoder(resp.Body).Decode(st); err != nil { return err } return st @@ -209,7 +209,7 @@ func newKubeAPIRequest(c *client) kubeAPIRequestFunc { return err } if out != nil { - return json.NewDecoder(resp.Body).Decode(out) + return jsonv1.NewDecoder(resp.Body).Decode(out) } return nil } @@ -228,7 +228,7 @@ func (c *client) newRequest(ctx context.Context, method, url string, in any) (*h body = bytes.NewReader(in) default: var b bytes.Buffer - if err := json.NewEncoder(&b).Encode(in); err != nil { + if err := jsonv1.NewEncoder(&b).Encode(in); err != nil { return nil, err } body = &b diff --git a/kube/kubeclient/client_test.go b/kube/kubeclient/client_test.go index 8599e7e3c..38256231d 100644 --- a/kube/kubeclient/client_test.go +++ b/kube/kubeclient/client_test.go @@ -5,7 +5,7 @@ package kubeclient import ( "context" - "encoding/json" + jsonv1 "encoding/json" "net/http" "net/http/httptest" "os" @@ -114,7 +114,7 @@ func Test_client_Event(t *testing.T) { func TestReturnsKubeStatusError(t *testing.T) { cl := clientForKubeHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusForbidden) - _ = json.NewEncoder(w).Encode(kubeapi.Status{Code: http.StatusForbidden, Message: "test error"}) + _ = jsonv1.NewEncoder(w).Encode(kubeapi.Status{Code: http.StatusForbidden, Message: "test error"}) })) _, err := cl.GetSecret(t.Context(), "test-secret") @@ -185,7 +185,7 @@ func fakeKubeAPIRequest(t *testing.T, argSets []args) kubeAPIRequestFunc { t.Errorf("[%d] unexpected payload (-want + got):\n%s", count, d) } if len(a.setOut) != 0 { - if err := json.Unmarshal(a.setOut, gotOut); err != nil { + if err := jsonv1.Unmarshal(a.setOut, gotOut); err != nil { t.Fatalf("[%d] error unmarshalling output: %v", count, err) } } diff --git a/kube/kubetypes/types_test.go b/kube/kubetypes/types_test.go index ea1846b32..b1e97ce05 100644 --- a/kube/kubetypes/types_test.go +++ b/kube/kubetypes/types_test.go @@ -4,7 +4,7 @@ package kubetypes import ( - "encoding/json" + jsonv1 "encoding/json" "testing" ) @@ -24,7 +24,7 @@ func TestUnmarshalAPIServerProxyMode(t *testing.T) { var s struct { Mode *APIServerProxyMode `json:",omitempty"` } - err := json.Unmarshal([]byte(tc.data), &s) + err := jsonv1.Unmarshal([]byte(tc.data), &s) if tc.expected == "" { if err == nil { t.Errorf("expected error for %q, got none", tc.data) diff --git a/kube/state/state.go b/kube/state/state.go index 2605f0952..cd2d14e30 100644 --- a/kube/state/state.go +++ b/kube/state/state.go @@ -12,7 +12,7 @@ package state import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "tailscale.com/ipn" @@ -95,7 +95,7 @@ func KeepKeysUpdated(ctx context.Context, store ipn.StateStore, lc klc.LocalClie for _, addr := range addrs.AsSlice() { deviceIPs = append(deviceIPs, addr.Addr().String()) } - deviceIPsValue, err := json.Marshal(deviceIPs) + deviceIPsValue, err := jsonv1.Marshal(deviceIPs) if err != nil { return err } diff --git a/log/sockstatlog/logger.go b/log/sockstatlog/logger.go index e0744de0f..f232eb424 100644 --- a/log/sockstatlog/logger.go +++ b/log/sockstatlog/logger.go @@ -9,7 +9,7 @@ package sockstatlog import ( "context" "crypto/sha256" - "encoding/json" + jsonv1 "encoding/json" "io" "net/http" "os" @@ -208,7 +208,7 @@ func (l *Logger) poll() { // logEvents reads events from the event channel at logInterval and logs them to disk. // This method does not return. func (l *Logger) logEvents() { - enc := json.NewEncoder(l) + enc := jsonv1.NewEncoder(l) flush := func() { for { select { diff --git a/logpolicy/logpolicy.go b/logpolicy/logpolicy.go index 9c7e62ab0..736fa4b5f 100644 --- a/logpolicy/logpolicy.go +++ b/logpolicy/logpolicy.go @@ -11,7 +11,7 @@ import ( "bytes" "context" "crypto/tls" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -142,7 +142,7 @@ func (c *Config) Validate(collection string) error { // ToBytes returns the JSON representation of c. func (c *Config) ToBytes() []byte { - data, err := json.MarshalIndent(c, "", "\t") + data, err := jsonv1.MarshalIndent(c, "", "\t") if err != nil { log.Fatalf("logpolicy.Config marshal: %v", err) } @@ -174,7 +174,7 @@ func ConfigFromFile(statefile string) (*Config, error) { // ConfigFromBytes parses a Config from its JSON encoding. func ConfigFromBytes(jsonEnc []byte) (*Config, error) { c := &Config{} - if err := json.Unmarshal(jsonEnc, c); err != nil { + if err := jsonv1.Unmarshal(jsonEnc, c); err != nil { return nil, err } return c, nil diff --git a/logtail/example/logreprocess/logreprocess.go b/logtail/example/logreprocess/logreprocess.go index aae65df9f..69d57211f 100644 --- a/logtail/example/logreprocess/logreprocess.go +++ b/logtail/example/logreprocess/logreprocess.go @@ -6,7 +6,7 @@ package main import ( "bufio" - "encoding/json" + jsonv1 "encoding/json" "flag" "io" "log" @@ -61,7 +61,7 @@ func main() { scanner := bufio.NewScanner(resp.Body) for scanner.Scan() { var msg Msg - if err := json.Unmarshal(scanner.Bytes(), &msg); err != nil { + if err := jsonv1.Unmarshal(scanner.Bytes(), &msg); err != nil { log.Fatalf("logreprocess of %q: %v", string(scanner.Bytes()), err) } var pMsg *ProcessedMsg @@ -85,7 +85,7 @@ func main() { continue // write later } - b, err := json.Marshal(pMsg) + b, err := jsonv1.Marshal(pMsg) if err != nil { log.Fatal(err) } diff --git a/logtail/logtail_test.go b/logtail/logtail_test.go index a92f88b4b..55b1edeb6 100644 --- a/logtail/logtail_test.go +++ b/logtail/logtail_test.go @@ -6,7 +6,7 @@ package logtail import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "io" "net/http" "net/http/httptest" @@ -224,7 +224,7 @@ func TestParseAndRemoveLogLevel(t *testing.T) { func unmarshalOne(t *testing.T, body []byte) map[string]any { t.Helper() var entries []map[string]any - err := json.Unmarshal(body, &entries) + err := jsonv1.Unmarshal(body, &entries) if err != nil { t.Error(err) } @@ -288,7 +288,7 @@ func TestEncode(t *testing.T) { if got != tt.want { t.Errorf("for %q,\n got: %#q\nwant: %#q\n", tt.in, got, tt.want) } - if err := json.Compact(new(bytes.Buffer), buf.buf.Bytes()); err != nil { + if err := jsonv1.Compact(new(bytes.Buffer), buf.buf.Bytes()); err != nil { t.Errorf("invalid output JSON for %q: %s", tt.in, got) } } diff --git a/metrics/multilabelmap_test.go b/metrics/multilabelmap_test.go index 195696234..3275969ae 100644 --- a/metrics/multilabelmap_test.go +++ b/metrics/multilabelmap_test.go @@ -5,7 +5,7 @@ package metrics import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "expvar" "fmt" "io" @@ -142,7 +142,7 @@ func TestMultiLabelMapExpvar(t *testing.T) { // Ensure that the String method is valid JSON to ensure that it can be // used by expvar. encoded := []byte(em.String()) - if !json.Valid(encoded) { + if !jsonv1.Valid(encoded) { t.Fatalf("invalid JSON: %s", encoded) } diff --git a/net/dns/resolver/tsdns_test.go b/net/dns/resolver/tsdns_test.go index f0dbb48b3..1008a3d97 100644 --- a/net/dns/resolver/tsdns_test.go +++ b/net/dns/resolver/tsdns_test.go @@ -7,7 +7,7 @@ import ( "bytes" "context" "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "log" @@ -1368,8 +1368,8 @@ func TestHandleExitNodeDNSQueryWithNetPkg(t *testing.T) { Port: 6, }, }; !reflect.DeepEqual(got, want) { - jgot, _ := json.Marshal(got) - jwant, _ := json.Marshal(want) + jgot, _ := jsonv1.Marshal(got) + jwant, _ := jsonv1.Marshal(want) t.Errorf("SRV = %s; want %s", jgot, jwant) } }) @@ -1393,8 +1393,8 @@ func TestHandleExitNodeDNSQueryWithNetPkg(t *testing.T) { {Host: "ns1.foo."}, {Host: "ns2.bar."}, }; !reflect.DeepEqual(got, want) { - jgot, _ := json.Marshal(got) - jwant, _ := json.Marshal(want) + jgot, _ := jsonv1.Marshal(got) + jwant, _ := jsonv1.Marshal(want) t.Errorf("NS = %s; want %s", jgot, jwant) } }) diff --git a/net/dnsfallback/dnsfallback.go b/net/dnsfallback/dnsfallback.go index 74b625970..16e33670e 100644 --- a/net/dnsfallback/dnsfallback.go +++ b/net/dnsfallback/dnsfallback.go @@ -13,7 +13,7 @@ package dnsfallback import ( "context" _ "embed" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "net" @@ -154,7 +154,7 @@ func bootstrapDNSMap(ctx context.Context, serverName string, serverIP netip.Addr if res.StatusCode != 200 { return nil, errors.New(res.Status) } - if err := json.NewDecoder(res.Body).Decode(&dm); err != nil { + if err := jsonv1.NewDecoder(res.Body).Decode(&dm); err != nil { return nil, err } return dm, nil @@ -210,7 +210,7 @@ func GetDERPMap() *tailcfg.DERPMap { // getStaticDERPMap returns the DERP map that was compiled into this binary. func getStaticDERPMap() *tailcfg.DERPMap { dm := new(tailcfg.DERPMap) - if err := json.Unmarshal(staticDERPMapJSON, dm); err != nil { + if err := jsonv1.Unmarshal(staticDERPMapJSON, dm); err != nil { panic(err) } return dm @@ -236,7 +236,7 @@ func UpdateCache(c *tailcfg.DERPMap, logf logger.Logf) { return } - d, err := json.Marshal(c) + d, err := jsonv1.Marshal(c) if err != nil { logf("[v1] dnsfallback: UpdateCache error marshaling: %v", err) return @@ -273,7 +273,7 @@ func SetCachePath(path string, logf logger.Logf) { defer f.Close() dm := new(tailcfg.DERPMap) - if err := json.NewDecoder(f).Decode(dm); err != nil { + if err := jsonv1.NewDecoder(f).Decode(dm); err != nil { logf("[v1] dnsfallback: SetCachePath error decoding %q: %v", path, err) return } diff --git a/net/dnsfallback/dnsfallback_test.go b/net/dnsfallback/dnsfallback_test.go index 7f8810574..84f06dd53 100644 --- a/net/dnsfallback/dnsfallback_test.go +++ b/net/dnsfallback/dnsfallback_test.go @@ -5,7 +5,7 @@ package dnsfallback import ( "context" - "encoding/json" + jsonv1 "encoding/json" "flag" "os" "path/filepath" @@ -61,7 +61,7 @@ func TestCache(t *testing.T) { }, }, } - d, err := json.Marshal(initialCache) + d, err := jsonv1.Marshal(initialCache) if err != nil { t.Fatal(err) } @@ -123,7 +123,7 @@ func TestCacheUnchanged(t *testing.T) { }, }, } - d, err := json.Marshal(initialCache) + d, err := jsonv1.Marshal(initialCache) if err != nil { t.Fatal(err) } diff --git a/net/dnsfallback/update-dns-fallbacks.go b/net/dnsfallback/update-dns-fallbacks.go index 384e77e10..518a9b466 100644 --- a/net/dnsfallback/update-dns-fallbacks.go +++ b/net/dnsfallback/update-dns-fallbacks.go @@ -6,7 +6,7 @@ package main import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "log" "net/http" @@ -25,7 +25,7 @@ func main() { os.Exit(1) } dm := new(tailcfg.DERPMap) - if err := json.NewDecoder(res.Body).Decode(dm); err != nil { + if err := jsonv1.NewDecoder(res.Body).Decode(dm); err != nil { log.Fatal(err) } for rid, r := range dm.Regions { @@ -35,7 +35,7 @@ func main() { r.RegionCode = fmt.Sprintf("r%d", rid) r.RegionName = r.RegionCode } - out, err := json.MarshalIndent(dm, "", "\t") + out, err := jsonv1.MarshalIndent(dm, "", "\t") if err != nil { log.Fatal(err) } diff --git a/net/flowtrack/flowtrack.go b/net/flowtrack/flowtrack.go index 8b3d799f7..c60be372a 100644 --- a/net/flowtrack/flowtrack.go +++ b/net/flowtrack/flowtrack.go @@ -11,7 +11,7 @@ package flowtrack import ( "container/list" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/netip" @@ -62,7 +62,7 @@ func (t Tuple) String() string { } func (t Tuple) MarshalJSON() ([]byte, error) { - return json.Marshal(tupleOld{ + return jsonv1.Marshal(tupleOld{ Proto: t.proto, Src: netip.AddrPortFrom(t.SrcAddr(), t.srcPort), Dst: netip.AddrPortFrom(t.DstAddr(), t.dstPort), @@ -71,7 +71,7 @@ func (t Tuple) MarshalJSON() ([]byte, error) { func (t *Tuple) UnmarshalJSON(b []byte) error { var ot tupleOld - if err := json.Unmarshal(b, &ot); err != nil { + if err := jsonv1.Unmarshal(b, &ot); err != nil { return err } *t = MakeTuple(ot.Proto, ot.Src, ot.Dst) diff --git a/net/flowtrack/flowtrack_test.go b/net/flowtrack/flowtrack_test.go index 1a13f7753..61ac35553 100644 --- a/net/flowtrack/flowtrack_test.go +++ b/net/flowtrack/flowtrack_test.go @@ -4,7 +4,7 @@ package flowtrack import ( - "encoding/json" + jsonv1 "encoding/json" "net/netip" "testing" @@ -109,7 +109,7 @@ func TestStringJSON(t *testing.T) { t.Errorf("String = %q; want %q", got, want) } - got, err := json.Marshal(v) + got, err := jsonv1.Marshal(v) if err != nil { t.Fatal(err) } @@ -119,7 +119,7 @@ func TestStringJSON(t *testing.T) { } var back Tuple - if err := json.Unmarshal(got, &back); err != nil { + if err := jsonv1.Unmarshal(got, &back); err != nil { t.Fatal(err) } if back != v { diff --git a/net/netmon/interfaces_test.go b/net/netmon/interfaces_test.go index e4274819f..403e13c2e 100644 --- a/net/netmon/interfaces_test.go +++ b/net/netmon/interfaces_test.go @@ -4,7 +4,7 @@ package netmon import ( - "encoding/json" + jsonv1 "encoding/json" "net" "net/netip" "testing" @@ -17,7 +17,7 @@ func TestGetState(t *testing.T) { if err != nil { t.Fatal(err) } - j, err := json.MarshalIndent(st, "", "\t") + j, err := jsonv1.MarshalIndent(st, "", "\t") if err != nil { t.Errorf("JSON: %v", err) } diff --git a/net/netmon/netmon.go b/net/netmon/netmon.go index f7d1b1107..61299940b 100644 --- a/net/netmon/netmon.go +++ b/net/netmon/netmon.go @@ -7,7 +7,7 @@ package netmon import ( - "encoding/json" + jsonv1 "encoding/json" "errors" "net/netip" "runtime" @@ -537,7 +537,7 @@ func prefixesMajorEqual(a, b []netip.Prefix) bool { } func jsonSummary(x any) any { - j, err := json.Marshal(x) + j, err := jsonv1.Marshal(x) if err != nil { return err } diff --git a/net/speedtest/speedtest_client.go b/net/speedtest/speedtest_client.go index 299a12a8d..9e3fcbc5d 100644 --- a/net/speedtest/speedtest_client.go +++ b/net/speedtest/speedtest_client.go @@ -4,7 +4,7 @@ package speedtest import ( - "encoding/json" + jsonv1 "encoding/json" "errors" "net" "time" @@ -22,14 +22,14 @@ func RunClient(direction Direction, duration time.Duration, host string) ([]Resu conf := config{TestDuration: duration, Version: version, Direction: direction} defer conn.Close() - encoder := json.NewEncoder(conn) + encoder := jsonv1.NewEncoder(conn) if err = encoder.Encode(conf); err != nil { return nil, err } var response configResponse - decoder := json.NewDecoder(conn) + decoder := jsonv1.NewDecoder(conn) if err = decoder.Decode(&response); err != nil { return nil, err } diff --git a/net/speedtest/speedtest_server.go b/net/speedtest/speedtest_server.go index 9dd78b195..5921cf59f 100644 --- a/net/speedtest/speedtest_server.go +++ b/net/speedtest/speedtest_server.go @@ -5,7 +5,7 @@ package speedtest import ( "crypto/rand" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -42,9 +42,9 @@ func handleConnection(conn net.Conn) error { defer conn.Close() var conf config - decoder := json.NewDecoder(conn) + decoder := jsonv1.NewDecoder(conn) err := decoder.Decode(&conf) - encoder := json.NewEncoder(conn) + encoder := jsonv1.NewEncoder(conn) // Both return and encode errors that occurred before the test started. if err != nil { diff --git a/net/udprelay/endpoint/endpoint_test.go b/net/udprelay/endpoint/endpoint_test.go index f12a6e2f6..857f8a1bf 100644 --- a/net/udprelay/endpoint/endpoint_test.go +++ b/net/udprelay/endpoint/endpoint_test.go @@ -4,7 +4,7 @@ package endpoint import ( - "encoding/json" + jsonv1 "encoding/json" "math" "net/netip" "testing" @@ -62,7 +62,7 @@ func TestServerEndpointJSONUnmarshal(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var out ServerEndpoint - err := json.Unmarshal(tt.json, &out) + err := jsonv1.Unmarshal(tt.json, &out) if tt.wantErr != (err != nil) { t.Fatalf("wantErr: %v (err == nil): %v", tt.wantErr, err == nil) } @@ -93,12 +93,12 @@ func TestServerEndpointJSONMarshal(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - b, err := json.Marshal(&tt.serverEndpoint) + b, err := jsonv1.Marshal(&tt.serverEndpoint) if err != nil { t.Fatal(err) } var got ServerEndpoint - err = json.Unmarshal(b, &got) + err = jsonv1.Unmarshal(b, &got) if err != nil { t.Fatal(err) } diff --git a/portlist/netstat_test.go b/portlist/netstat_test.go index 023b75b79..4a9730f2f 100644 --- a/portlist/netstat_test.go +++ b/portlist/netstat_test.go @@ -7,7 +7,7 @@ package portlist import ( "bufio" - "encoding/json" + jsonv1 "encoding/json" "fmt" "strings" "testing" @@ -75,8 +75,8 @@ func TestParsePortsNetstat(t *testing.T) { t.Fatal(err) } pl = sortAndDedup(pl) - jgot, _ := json.MarshalIndent(pl, "", "\t") - jwant, _ := json.MarshalIndent(want, "", "\t") + jgot, _ := jsonv1.MarshalIndent(pl, "", "\t") + jwant, _ := jsonv1.MarshalIndent(want, "", "\t") if len(pl) != len(want) { t.Fatalf("Got:\n%s\n\nWant:\n%s\n", jgot, jwant) } diff --git a/prober/derp.go b/prober/derp.go index 52e56fd4e..3b5c05092 100644 --- a/prober/derp.go +++ b/prober/derp.go @@ -10,7 +10,7 @@ import ( crand "crypto/rand" "crypto/tls" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "errors" "expvar" "fmt" @@ -595,7 +595,7 @@ func (d *derpProber) updateMap(ctx context.Context) error { return fmt.Errorf("fetching %s: %s", d.derpMapURL, res.Status) } dm = new(tailcfg.DERPMap) - if err := json.NewDecoder(res.Body).Decode(dm); err != nil { + if err := jsonv1.NewDecoder(res.Body).Decode(dm); err != nil { return fmt.Errorf("decoding %s JSON: %v", d.derpMapURL, err) } } diff --git a/prober/derp_test.go b/prober/derp_test.go index 08a65d697..9b52bcbd3 100644 --- a/prober/derp_test.go +++ b/prober/derp_test.go @@ -7,7 +7,7 @@ import ( "context" "crypto/sha256" "crypto/tls" - "encoding/json" + jsonv1 "encoding/json" "net" "net/http" "net/http/httptest" @@ -61,7 +61,7 @@ func TestDerpProber(t *testing.T) { }, } srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - resp, err := json.Marshal(dm) + resp, err := jsonv1.Marshal(dm) if err != nil { t.Fatal(err) } diff --git a/prober/prober.go b/prober/prober.go index 9073a9502..078a69577 100644 --- a/prober/prober.go +++ b/prober/prober.go @@ -11,7 +11,7 @@ import ( "cmp" "container/ring" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "hash/fnv" "log" @@ -564,7 +564,7 @@ func (p *Prober) RunHandler(w http.ResponseWriter, r *http.Request) error { } w.Header().Set("Content-Type", "application/json") w.WriteHeader(respStatus) - if err := json.NewEncoder(w).Encode(resp); err != nil { + if err := jsonv1.NewEncoder(w).Encode(resp); err != nil { return tsweb.Error(http.StatusInternalServerError, "error encoding JSON response", err) } return nil @@ -632,7 +632,7 @@ func (p *Prober) RunAllHandler(w http.ResponseWriter, r *http.Request) error { Results: results, } var b bytes.Buffer - if err := json.NewEncoder(&b).Encode(resp); err != nil { + if err := jsonv1.NewEncoder(&b).Encode(resp); err != nil { return tsweb.Error(http.StatusInternalServerError, "error encoding JSON response", err) } diff --git a/prober/prober_test.go b/prober/prober_test.go index 1e045fa89..f199c4584 100644 --- a/prober/prober_test.go +++ b/prober/prober_test.go @@ -5,7 +5,7 @@ package prober import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -624,7 +624,7 @@ func TestProberRunHandler(t *testing.T) { t.Fatalf("failed to read response body: %v", err) } - if err := json.Unmarshal(body, &gotJSON); err != nil { + if err := jsonv1.Unmarshal(body, &gotJSON); err != nil { t.Fatalf("failed to unmarshal JSON response: %v; body: %s", err, body) } if diff := cmp.Diff(tt.wantJSONResponse, gotJSON, cmpopts.IgnoreFields(ProbeInfo{}, "Start", "End", "Labels", "RecentLatencies")); diff != "" { @@ -748,7 +748,7 @@ func TestRunAllHandler(t *testing.T) { t.Fatalf("failed to read response body: %v", err) } - if err := json.Unmarshal(body, &gotJSON); err != nil { + if err := jsonv1.Unmarshal(body, &gotJSON); err != nil { t.Fatalf("failed to unmarshal JSON response: %v; body: %s", err, body) } if diff := cmp.Diff(tc.wantJSONResponse, gotJSON, cmpopts.IgnoreFields(ProbeInfo{}, "Start", "End", "Labels", "RecentLatencies")); diff != "" { @@ -813,7 +813,7 @@ func TestExcludeInRunAll(t *testing.T) { t.Fatalf("failed to read response body: %v", err) } - if err := json.Unmarshal(body, &gotJSON); err != nil { + if err := jsonv1.Unmarshal(body, &gotJSON); err != nil { t.Fatalf("failed to unmarshal JSON response: %v; body: %s", err, body) } diff --git a/sessionrecording/connect.go b/sessionrecording/connect.go index 9d20b41f9..b73aeaf84 100644 --- a/sessionrecording/connect.go +++ b/sessionrecording/connect.go @@ -7,7 +7,7 @@ package sessionrecording import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -295,7 +295,7 @@ func connectV2(ctx context.Context, hc *http.Client, ap netip.AddrPort) (io.Writ defer close(acks) defer resp.Body.Close() defer pw.Close() - dec := json.NewDecoder(resp.Body) + dec := jsonv1.NewDecoder(resp.Body) for { var frame v2ResponseFrame if err := dec.Decode(&frame); err != nil { diff --git a/sessionrecording/connect_test.go b/sessionrecording/connect_test.go index e834828f5..8334a3a1c 100644 --- a/sessionrecording/connect_test.go +++ b/sessionrecording/connect_test.go @@ -8,7 +8,7 @@ import ( "context" "crypto/rand" "crypto/sha256" - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" "net" @@ -78,7 +78,7 @@ func TestConnectToRecorder(t *testing.T) { // Send acks for received bytes. tick := time.NewTicker(time.Millisecond) defer tick.Stop() - enc := json.NewEncoder(w) + enc := jsonv1.NewEncoder(w) outer: for { select { diff --git a/ssh/tailssh/incubator.go b/ssh/tailssh/incubator.go index dd280143e..62274a006 100644 --- a/ssh/tailssh/incubator.go +++ b/ssh/tailssh/incubator.go @@ -13,7 +13,7 @@ package tailssh import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -229,7 +229,7 @@ func (ss *sshSession) newIncubatorCommand(logf logger.Logf) (cmd *exec.Cmd, err } if len(env) > 0 { - encoded, err := json.Marshal(env) + encoded, err := jsonv1.Marshal(env) if err != nil { return nil, fmt.Errorf("failed to encode environment: %w", err) } @@ -339,7 +339,7 @@ func (ia incubatorArgs) forwardedEnviron() (env, allowedExtraKeys []string, err var extraEnviron []string - err = json.Unmarshal([]byte(unquoted), &extraEnviron) + err = jsonv1.Unmarshal([]byte(unquoted), &extraEnviron) if err != nil { return nil, nil, fmt.Errorf("unable to parse encodedEnv %q: %w", ia.encodedEnv, err) } diff --git a/ssh/tailssh/incubator_plan9.go b/ssh/tailssh/incubator_plan9.go index 61b6a54eb..696fb0942 100644 --- a/ssh/tailssh/incubator_plan9.go +++ b/ssh/tailssh/incubator_plan9.go @@ -10,7 +10,7 @@ package tailssh import ( - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -125,7 +125,7 @@ func (ss *sshSession) newIncubatorCommand(logf logger.Logf) (cmd *exec.Cmd, err } if len(env) > 0 { - encoded, err := json.Marshal(env) + encoded, err := jsonv1.Marshal(env) if err != nil { return nil, fmt.Errorf("failed to encode environment: %w", err) } @@ -203,7 +203,7 @@ func (ia incubatorArgs) forwardedEnviron() ([]string, string, error) { var extraEnviron []string - err = json.Unmarshal([]byte(unquoted), &extraEnviron) + err = jsonv1.Unmarshal([]byte(unquoted), &extraEnviron) if err != nil { return nil, "", fmt.Errorf("unable to parse encodedEnv %q: %w", ia.encodedEnv, err) } diff --git a/ssh/tailssh/privs_test.go b/ssh/tailssh/privs_test.go index 32b219a77..ef2da52e4 100644 --- a/ssh/tailssh/privs_test.go +++ b/ssh/tailssh/privs_test.go @@ -6,7 +6,7 @@ package tailssh import ( - "encoding/json" + jsonv1 "encoding/json" "errors" "os" "os/exec" @@ -41,7 +41,7 @@ func TestDoDropPrivileges(t *testing.T) { t.Logf("in child process") var input SubprocInput - if err := json.Unmarshal([]byte(v), &input); err != nil { + if err := jsonv1.Unmarshal([]byte(v), &input); err != nil { t.Fatal(err) } @@ -54,7 +54,7 @@ func TestDoDropPrivileges(t *testing.T) { additional, _ := syscall.Getgroups() // Print our IDs - json.NewEncoder(f).Encode(SubprocOutput{ + jsonv1.NewEncoder(f).Encode(SubprocOutput{ UID: os.Getuid(), GID: os.Getgid(), EUID: os.Geteuid(), @@ -82,7 +82,7 @@ func TestDoDropPrivileges(t *testing.T) { t.Fatal(err) } - inputb, err := json.Marshal(input) + inputb, err := jsonv1.Marshal(input) if err != nil { t.Fatal(err) } @@ -156,7 +156,7 @@ func TestDoDropPrivileges(t *testing.T) { }) var out SubprocOutput - if err := json.Unmarshal(subprocOut, &out); err != nil { + if err := jsonv1.Unmarshal(subprocOut, &out); err != nil { t.Logf("%s", subprocOut) t.Fatal(err) } diff --git a/ssh/tailssh/tailssh.go b/ssh/tailssh/tailssh.go index 7d12ab45f..2db544ba0 100644 --- a/ssh/tailssh/tailssh.go +++ b/ssh/tailssh/tailssh.go @@ -10,7 +10,7 @@ import ( "bytes" "context" "crypto/rand" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -553,7 +553,7 @@ func (c *conn) sshPolicy() (_ *tailcfg.SSHPolicy, ok bool) { return nil, false } p := new(tailcfg.SSHPolicy) - if err := json.Unmarshal(f, p); err != nil { + if err := jsonv1.Unmarshal(f, p); err != nil { c.logf("invalid JSON in %v: %v", debugPolicyFile, err) return nil, false } @@ -775,7 +775,7 @@ func (c *conn) fetchSSHAction(ctx context.Context, url string) (*tailcfg.SSHActi continue } a := new(tailcfg.SSHAction) - err = json.NewDecoder(res.Body).Decode(a) + err = jsonv1.NewDecoder(res.Body).Decode(a) res.Body.Close() if err != nil { c.logf("invalid next SSHAction JSON from %v: %v", url, err) @@ -1364,7 +1364,7 @@ func (ss *sshSession) startNewRecording() (_ *recording, err error) { } else { ch.SrcNodeTags = ss.conn.info.node.Tags().AsSlice() } - j, err := json.Marshal(ch) + j, err := jsonv1.Marshal(ch) if err != nil { return nil, err } @@ -1396,7 +1396,7 @@ func (ss *sshSession) notifyControl(ctx context.Context, nodeKey key.NodePublic, RecordingAttempts: attempts, } - body, err := json.Marshal(re) + body, err := jsonv1.Marshal(re) if err != nil { ss.logf("notifyControl: unable to marshal SSHNotifyRequest:", err) return @@ -1478,7 +1478,7 @@ type loggingWriter struct { func (w *loggingWriter) Write(p []byte) (n int, err error) { if !w.recordingFailedOpen { - j, err := json.Marshal([]any{ + j, err := jsonv1.Marshal([]any{ time.Since(w.r.start).Seconds(), w.dir, string(p), diff --git a/ssh/tailssh/tailssh_test.go b/ssh/tailssh/tailssh_test.go index 3b6d3c52c..cbb2f4d5d 100644 --- a/ssh/tailssh/tailssh_test.go +++ b/ssh/tailssh/tailssh_test.go @@ -12,7 +12,7 @@ import ( "crypto/ed25519" "crypto/elliptic" "crypto/rand" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -461,7 +461,7 @@ func (ts *localState) DoNoiseRequest(req *http.Request) (*http.Response, error) return rec.Result(), nil } rec.WriteHeader(http.StatusOK) - if err := json.NewEncoder(rec).Encode(a); err != nil { + if err := jsonv1.NewEncoder(rec).Encode(a); err != nil { return nil, err } return rec.Result(), nil @@ -783,7 +783,7 @@ func TestSSHRecordingNonInteractive(t *testing.T) { <-ctx.Done() // wait for recording to finish var ch sessionrecording.CastHeader - if err := json.NewDecoder(bytes.NewReader(recording)).Decode(&ch); err != nil { + if err := jsonv1.NewDecoder(bytes.NewReader(recording)).Decode(&ch); err != nil { t.Fatal(err) } if ch.SSHUser != sshUser { diff --git a/syncs/shardedint.go b/syncs/shardedint.go index 28c4168d5..79630b35e 100644 --- a/syncs/shardedint.go +++ b/syncs/shardedint.go @@ -4,7 +4,7 @@ package syncs import ( - "encoding/json" + jsonv1 "encoding/json" "strconv" "sync/atomic" @@ -59,7 +59,7 @@ func (m *ShardedInt) GetDistribution() []int64 { // String implements the expvar.Var interface func (m *ShardedInt) String() string { - v, _ := json.Marshal(m.Value()) + v, _ := jsonv1.Marshal(m.Value()) return string(v) } diff --git a/tailcfg/c2ntypes.go b/tailcfg/c2ntypes.go index d78baef1c..ef7bd06d4 100644 --- a/tailcfg/c2ntypes.go +++ b/tailcfg/c2ntypes.go @@ -6,7 +6,7 @@ package tailcfg import ( - "encoding/json" + jsonv1 "encoding/json" "net/netip" ) @@ -141,8 +141,8 @@ type C2NDebugNetmapRequest struct { // netmap.NetworkMap values, they are returned as json.RawMessage. type C2NDebugNetmapResponse struct { // Current is the current network map (netmap.NetworkMap). - Current json.RawMessage `json:"current"` + Current jsonv1.RawMessage `json:"current"` // Candidate is a network map produced based on the candidate MapResponse. - Candidate json.RawMessage `json:"candidate,omitzero"` + Candidate jsonv1.RawMessage `json:"candidate,omitzero"` } diff --git a/tailcfg/tailcfg.go b/tailcfg/tailcfg.go index a95d0559c..30b50bda9 100644 --- a/tailcfg/tailcfg.go +++ b/tailcfg/tailcfg.go @@ -10,7 +10,7 @@ package tailcfg import ( "bytes" "cmp" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "maps" @@ -321,7 +321,7 @@ func (m *RawMessage) UnmarshalJSON(data []byte) error { // MarshalCapJSON returns a capability rule in RawMessage string format. func MarshalCapJSON[T any](capRule T) (RawMessage, error) { - bs, err := json.Marshal(capRule) + bs, err := jsonv1.Marshal(capRule) if err != nil { return "", fmt.Errorf("error marshalling capability rule: %w", err) } @@ -1603,7 +1603,7 @@ func UnmarshalNodeCapViewJSON[T any](cm views.MapSlice[NodeCapability, RawMessag out := make([]T, 0, vals.Len()) for _, v := range vals.All() { var t T - if err := json.Unmarshal([]byte(v), &t); err != nil { + if err := jsonv1.Unmarshal([]byte(v), &t); err != nil { return nil, err } out = append(out, t) @@ -1645,7 +1645,7 @@ func UnmarshalCapViewJSON[T any](cm views.MapSlice[PeerCapability, RawMessage], out := make([]T, 0, vals.Len()) for _, v := range vals.All() { var t T - if err := json.Unmarshal([]byte(v), &t); err != nil { + if err := jsonv1.Unmarshal([]byte(v), &t); err != nil { return nil, err } out = append(out, t) diff --git a/tailcfg/tailcfg_test.go b/tailcfg/tailcfg_test.go index addd2330b..cc4e5abd3 100644 --- a/tailcfg/tailcfg_test.go +++ b/tailcfg/tailcfg_test.go @@ -4,7 +4,7 @@ package tailcfg_test import ( - "encoding/json" + jsonv1 "encoding/json" "net/netip" "os" "reflect" @@ -674,7 +674,7 @@ func TestEndpointTypeMarshal(t *testing.T) { EndpointPortmapped, EndpointSTUN4LocalPort, } - got, err := json.Marshal(eps) + got, err := jsonv1.Marshal(eps) if err != nil { t.Fatal(err) } @@ -721,7 +721,7 @@ func TestUnmarshalHealth(t *testing.T) { } for _, tt := range tests { var mr MapResponse - if err := json.Unmarshal([]byte(tt.in), &mr); err != nil { + if err := jsonv1.Unmarshal([]byte(tt.in), &mr); err != nil { t.Fatal(err) } if !reflect.DeepEqual(mr.Health, tt.want) { @@ -788,18 +788,18 @@ func TestRawMessage(t *testing.T) { } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - j := must.Get(json.Marshal(tc.val)) + j := must.Get(jsonv1.Marshal(tc.val)) var gotWire map[string][]RawMessage - if err := json.Unmarshal(j, &gotWire); err != nil { + if err := jsonv1.Unmarshal(j, &gotWire); err != nil { t.Fatalf("unmarshal: %v", err) } if !reflect.DeepEqual(gotWire, tc.wire) { t.Errorf("got %#v; want %#v", gotWire, tc.wire) } - j = must.Get(json.Marshal(tc.wire)) + j = must.Get(jsonv1.Marshal(tc.wire)) var gotVal map[string][]rule - if err := json.Unmarshal(j, &gotVal); err != nil { + if err := jsonv1.Unmarshal(j, &gotVal); err != nil { t.Fatalf("unmarshal: %v", err) } if !reflect.DeepEqual(gotVal, tc.val) { @@ -1017,8 +1017,8 @@ func TestDisplayMessageEqual(t *testing.T) { got := test.value1.Equal(test.value2) if got != test.wantEqual { - value1 := must.Get(json.MarshalIndent(test.value1, "", " ")) - value2 := must.Get(json.MarshalIndent(test.value2, "", " ")) + value1 := must.Get(jsonv1.MarshalIndent(test.value1, "", " ")) + value2 := must.Get(jsonv1.MarshalIndent(test.value2, "", " ")) t.Errorf("value1.Equal(value2): got %t, want %t\nvalue1:\n%s\nvalue2:\n%s", got, test.wantEqual, value1, value2) } }) diff --git a/tsconsensus/http.go b/tsconsensus/http.go index d2a44015f..e7e580794 100644 --- a/tsconsensus/http.go +++ b/tsconsensus/http.go @@ -6,7 +6,7 @@ package tsconsensus import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -40,7 +40,7 @@ func readAllMaxBytes(r io.Reader) ([]byte, error) { func (rac *commandClient) join(host string, jr joinRequest) error { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - rBs, err := json.Marshal(jr) + rBs, err := jsonv1.Marshal(jr) if err != nil { return err } @@ -85,7 +85,7 @@ func (rac *commandClient) executeCommand(host string, bs []byte) (CommandResult, return CommandResult{}, fmt.Errorf("remote responded %d: %s", resp.StatusCode, string(respBs)) } var cr CommandResult - if err = json.Unmarshal(respBs, &cr); err != nil { + if err = jsonv1.Unmarshal(respBs, &cr); err != nil { return CommandResult{}, err } return cr, nil @@ -119,7 +119,7 @@ func (h authedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (c *Consensus) handleJoinHTTP(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() - decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodyBytes+1)) + decoder := jsonv1.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodyBytes+1)) var jr joinRequest err := decoder.Decode(&jr) if err != nil { @@ -149,7 +149,7 @@ func (c *Consensus) handleJoinHTTP(w http.ResponseWriter, r *http.Request) { func (c *Consensus) handleExecuteCommandHTTP(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() - decoder := json.NewDecoder(r.Body) + decoder := jsonv1.NewDecoder(r.Body) var cmd Command err := decoder.Decode(&cmd) if err != nil { @@ -161,7 +161,7 @@ func (c *Consensus) handleExecuteCommandHTTP(w http.ResponseWriter, r *http.Requ http.Error(w, err.Error(), http.StatusInternalServerError) return } - if err := json.NewEncoder(w).Encode(result); err != nil { + if err := jsonv1.NewEncoder(w).Encode(result); err != nil { log.Printf("error encoding execute command result: %v", err) return } diff --git a/tsconsensus/monitor.go b/tsconsensus/monitor.go index 61a5a74a0..525b82357 100644 --- a/tsconsensus/monitor.go +++ b/tsconsensus/monitor.go @@ -5,7 +5,7 @@ package tsconsensus import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" "log" @@ -65,7 +65,7 @@ func (m *monitor) handleFullStatus(w http.ResponseWriter, r *http.Request) { http.Error(w, "", http.StatusInternalServerError) return } - if err := json.NewEncoder(w).Encode(s); err != nil { + if err := jsonv1.NewEncoder(w).Encode(s); err != nil { log.Printf("monitor: error encoding full status: %v", err) return } @@ -124,7 +124,7 @@ func (m *monitor) handleNetmap(w http.ResponseWriter, r *http.Request) { http.Error(w, "", http.StatusInternalServerError) return } - encoder := json.NewEncoder(w) + encoder := jsonv1.NewEncoder(w) encoder.SetIndent("", "\t") if err := encoder.Encode(n); err != nil { log.Printf("monitor: error encoding netmap: %v", err) @@ -143,7 +143,7 @@ func (m *monitor) handleDial(w http.ResponseWriter, r *http.Request) { http.Error(w, "", http.StatusInternalServerError) return } - err = json.Unmarshal(bs, &dialParams) + err = jsonv1.Unmarshal(bs, &dialParams) if err != nil { log.Printf("monitor: error unmarshalling json: %v", err) http.Error(w, "", http.StatusBadRequest) diff --git a/tsconsensus/tsconsensus.go b/tsconsensus/tsconsensus.go index 1f7dc1b7b..9a222e780 100644 --- a/tsconsensus/tsconsensus.go +++ b/tsconsensus/tsconsensus.go @@ -25,7 +25,7 @@ package tsconsensus import ( "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "log" @@ -397,7 +397,7 @@ func (c *Consensus) bootstrap(ctx context.Context, auth *authorization, opts Boo // ExecuteCommand propagates a Command to be executed on the leader. Which // uses raft to Apply it to the followers. func (c *Consensus) ExecuteCommand(cmd Command) (CommandResult, error) { - b, err := json.Marshal(cmd) + b, err := jsonv1.Marshal(cmd) if err != nil { return CommandResult{}, err } @@ -435,7 +435,7 @@ type Command struct { // The Name can be used to dispatch the command when received. Name string // The Args are serialized for transport. - Args json.RawMessage + Args jsonv1.RawMessage } // A CommandResult is a representation of the result of a state @@ -445,7 +445,7 @@ type CommandResult struct { // including any error from the underlying operation and deserialization problems etc. Err error // Result is serialized for transport. - Result json.RawMessage + Result jsonv1.RawMessage } type lookElsewhereError struct { @@ -484,7 +484,7 @@ func (c *Consensus) getLeader() (string, error) { } func (c *Consensus) executeCommandLocally(cmd Command) (CommandResult, error) { - b, err := json.Marshal(cmd) + b, err := jsonv1.Marshal(cmd) if err != nil { return CommandResult{}, err } diff --git a/tsconsensus/tsconsensus_test.go b/tsconsensus/tsconsensus_test.go index 17f3d881f..e196de56f 100644 --- a/tsconsensus/tsconsensus_test.go +++ b/tsconsensus/tsconsensus_test.go @@ -7,7 +7,7 @@ import ( "bufio" "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -48,11 +48,11 @@ type fsm struct { } func commandWith(t *testing.T, s string) []byte { - jsonArgs, err := json.Marshal(s) + jsonArgs, err := jsonv1.Marshal(s) if err != nil { t.Fatal(err) } - bs, err := json.Marshal(Command{ + bs, err := jsonv1.Marshal(Command{ Args: jsonArgs, }) if err != nil { @@ -63,12 +63,12 @@ func commandWith(t *testing.T, s string) []byte { func fromCommand(bs []byte) (string, error) { var cmd Command - err := json.Unmarshal(bs, &cmd) + err := jsonv1.Unmarshal(bs, &cmd) if err != nil { return "", err } var args string - err = json.Unmarshal(cmd.Args, &args) + err = jsonv1.Unmarshal(cmd.Args, &args) if err != nil { return "", err } @@ -85,7 +85,7 @@ func (f *fsm) Apply(l *raft.Log) any { } } f.applyEvents = append(f.applyEvents, s) - result, err := json.Marshal(len(f.applyEvents)) + result, err := jsonv1.Marshal(len(f.applyEvents)) if err != nil { panic("should be able to Marshal that?") } @@ -403,7 +403,7 @@ func assertCommandsWorkOnAnyNode(t testing.TB, participants []*participant) { for i, p := range participants { si := fmt.Sprintf("%d", i) want = append(want, si) - bs, err := json.Marshal(si) + bs, err := jsonv1.Marshal(si) if err != nil { t.Fatal(err) } @@ -415,7 +415,7 @@ func assertCommandsWorkOnAnyNode(t testing.TB, participants []*participant) { t.Fatalf("%d: Result Error ExecuteCommand: %v", i, res.Err) } var retVal int - err = json.Unmarshal(res.Result, &retVal) + err = jsonv1.Unmarshal(res.Result, &retVal) if err != nil { t.Fatal(err) } @@ -722,7 +722,7 @@ func TestOnlyTaggedPeersCanJoin(t *testing.T) { ipv4, _ := tsJoiner.TailscaleIPs() url := fmt.Sprintf("http://%s/join", ps[0].c.commandAddr(ps[0].c.self.hostAddr)) - payload, err := json.Marshal(joinRequest{ + payload, err := jsonv1.Marshal(joinRequest{ RemoteHost: ipv4.String(), RemoteID: "node joiner", }) diff --git a/tstest/deptest/deptest.go b/tstest/deptest/deptest.go index c0b6d8b8c..28a7cad7f 100644 --- a/tstest/deptest/deptest.go +++ b/tstest/deptest/deptest.go @@ -7,7 +7,7 @@ package deptest import ( - "encoding/json" + jsonv1 "encoding/json" "os" "os/exec" "path/filepath" @@ -56,7 +56,7 @@ func (c DepChecker) Check(t *testing.T) { Imports []string Deps []string } - if err := json.Unmarshal(out, &res); err != nil { + if err := jsonv1.Unmarshal(out, &res); err != nil { t.Fatal(err) } diff --git a/tstest/integration/gen_deps.go b/tstest/integration/gen_deps.go index 23bb95ee5..a56d389fd 100644 --- a/tstest/integration/gen_deps.go +++ b/tstest/integration/gen_deps.go @@ -7,7 +7,7 @@ package main import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "fmt" "log" "os" @@ -31,7 +31,7 @@ func generate(goos string) { if err != nil { log.Fatalf("GOOS=%s GOARCH=amd64 %s: %v", goos, cmd, err) } - if err := json.Unmarshal(j, &x); err != nil { + if err := jsonv1.Unmarshal(j, &x); err != nil { log.Fatal(err) } var out bytes.Buffer diff --git a/tstest/integration/integration.go b/tstest/integration/integration.go index 6700205cf..090a7d5f5 100644 --- a/tstest/integration/integration.go +++ b/tstest/integration/integration.go @@ -11,7 +11,7 @@ import ( "bytes" "context" "crypto/tls" - "encoding/json" + jsonv1 "encoding/json" "flag" "fmt" "io" @@ -442,10 +442,10 @@ func (lc *LogCatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) { } var jreq []Entry if len(bodyBytes) > 0 && bodyBytes[0] == '[' { - err = json.Unmarshal(bodyBytes, &jreq) + err = jsonv1.Unmarshal(bodyBytes, &jreq) } else { var ent Entry - err = json.Unmarshal(bodyBytes, &ent) + err = jsonv1.Unmarshal(bodyBytes, &ent) jreq = append(jreq, ent) } @@ -1057,7 +1057,7 @@ func (n *TestNode) Status() (*ipnstate.Status, error) { return nil, fmt.Errorf("running tailscale status: %v, %s", err, out) } st := new(ipnstate.Status) - if err := json.Unmarshal(out, st); err != nil { + if err := jsonv1.Unmarshal(out, st); err != nil { return nil, fmt.Errorf("decoding tailscale status JSON: %w\njson:\n%s", err, out) } return st, nil diff --git a/tstest/integration/integration_test.go b/tstest/integration/integration_test.go index 64f49c7b8..fc229eea1 100644 --- a/tstest/integration/integration_test.go +++ b/tstest/integration/integration_test.go @@ -8,7 +8,7 @@ package integration import ( "bytes" "context" - "encoding/json" + jsonv1 "encoding/json" "errors" "flag" "fmt" @@ -167,7 +167,7 @@ func TestControlKnobs(t *testing.T) { } t.Logf("control-knobs output:\n%s", out) var m map[string]any - if err := json.Unmarshal(out, &m); err != nil { + if err := jsonv1.Unmarshal(out, &m); err != nil { t.Fatal(err) } if got, want := m["DisableUPnP"], true; got != want { @@ -725,7 +725,7 @@ func TestConfigFileAuthKey(t *testing.T) { n1.configFile = filepath.Join(n1.dir, "config.json") authKeyFile := filepath.Join(n1.dir, "my-auth-key") must.Do(os.WriteFile(authKeyFile, fmt.Appendf(nil, "%s\n", authKey), 0666)) - must.Do(os.WriteFile(n1.configFile, must.Get(json.Marshal(ipn.ConfigVAlpha{ + must.Do(os.WriteFile(n1.configFile, must.Get(jsonv1.Marshal(ipn.ConfigVAlpha{ Version: "alpha0", AuthKey: ptr.To("file:" + authKeyFile), ServerURL: ptr.To(n1.env.ControlServer.URL), @@ -1894,7 +1894,7 @@ func TestEncryptStateMigration(t *testing.T) { } t.Logf("state file content:\n%s", buf) var content map[string]any - if err := json.Unmarshal(buf, &content); err != nil { + if err := jsonv1.Unmarshal(buf, &content); err != nil { t.Fatalf("parsing %q: %v", n.stateFile, err) } for _, k := range wantStateKeys { @@ -1965,7 +1965,7 @@ func TestPeerRelayPing(t *testing.T) { return fmt.Errorf("debug peer-relay-servers failed: %v", err) } servers := make([]string, 0) - err = json.Unmarshal(out, &servers) + err = jsonv1.Unmarshal(out, &servers) if err != nil { return fmt.Errorf("failed to unmarshal debug peer-relay-servers: %v", err) } @@ -2108,7 +2108,7 @@ func TestC2NDebugNetmap(t *testing.T) { var req *http.Request if cand != nil { - body := must.Get(json.Marshal(&tailcfg.C2NDebugNetmapRequest{Candidate: cand})) + body := must.Get(jsonv1.Marshal(&tailcfg.C2NDebugNetmapRequest{Candidate: cand})) req = must.Get(http.NewRequestWithContext(ctx, "POST", "/debug/netmap", bytes.NewReader(body))) } else { req = must.Get(http.NewRequestWithContext(ctx, "GET", "/debug/netmap", nil)) @@ -2123,10 +2123,10 @@ func TestC2NDebugNetmap(t *testing.T) { respBody := must.Get(io.ReadAll(httpResp.Body)) var resp tailcfg.C2NDebugNetmapResponse - must.Do(json.Unmarshal(respBody, &resp)) + must.Do(jsonv1.Unmarshal(respBody, &resp)) var current netmap.NetworkMap - must.Do(json.Unmarshal(resp.Current, ¤t)) + must.Do(jsonv1.Unmarshal(resp.Current, ¤t)) if !current.PrivateKey.IsZero() { t.Errorf("current netmap has non-zero private key: %v", current.PrivateKey) @@ -2134,7 +2134,7 @@ func TestC2NDebugNetmap(t *testing.T) { // Check candidate netmap if we sent a map response. if cand != nil { var candidate netmap.NetworkMap - must.Do(json.Unmarshal(resp.Candidate, &candidate)) + must.Do(jsonv1.Unmarshal(resp.Candidate, &candidate)) if !candidate.PrivateKey.IsZero() { t.Errorf("candidate netmap has non-zero private key: %v", candidate.PrivateKey) } diff --git a/tstest/integration/testcontrol/testcontrol.go b/tstest/integration/testcontrol/testcontrol.go index f9a33705b..9f76a5b5e 100644 --- a/tstest/integration/testcontrol/testcontrol.go +++ b/tstest/integration/testcontrol/testcontrol.go @@ -10,7 +10,7 @@ import ( "cmp" "context" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -427,7 +427,7 @@ func (s *Server) serveKey(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(&tailcfg.OverTLSPublicKeyResponse{ + jsonv1.NewEncoder(w).Encode(&tailcfg.OverTLSPublicKeyResponse{ LegacyPublicKey: legacyKey, PublicKey: noiseKey, }) @@ -729,7 +729,7 @@ func (s *Server) serveRegister(w http.ResponseWriter, r *http.Request, mkey key. go panic("serveRegister: request has zero node key") } if s.Verbose { - j, _ := json.MarshalIndent(req, "", "\t") + j, _ := jsonv1.MarshalIndent(req, "", "\t") log.Printf("Got %T: %s", req, j) } if s.RequireAuthKey != "" && (req.Auth == nil || req.Auth.AuthKey != s.RequireAuthKey) { @@ -1023,7 +1023,7 @@ func (s *Server) serveMap(w http.ResponseWriter, r *http.Request, mkey key.Machi res.Node.KeyExpiry = time.Now().Add(-1 * time.Minute) } // TODO: add minner if/when needed - resBytes, err := json.Marshal(res) + resBytes, err := jsonv1.Marshal(res) if err != nil { s.logf("json.Marshal: %v", err) return @@ -1228,7 +1228,7 @@ func (s *Server) takeRawMapMessage(nk key.NodePublic) (mapResJSON []byte, ok boo } var err error - mapResJSON, err = json.Marshal(mr) + mapResJSON, err = jsonv1.Marshal(mr) if err != nil { panic(err) } @@ -1263,13 +1263,13 @@ func (s *Server) decode(msg []byte, v any) error { if len(msg) == msgLimit { return errors.New("encrypted message too long") } - return json.Unmarshal(msg, v) + return jsonv1.Unmarshal(msg, v) } func (s *Server) encode(compress bool, v any) (b []byte, err error) { var isBytes bool if b, isBytes = v.([]byte); !isBytes { - b, err = json.Marshal(v) + b, err = jsonv1.Marshal(v) if err != nil { return nil, err } diff --git a/tstest/integration/vms/distros.go b/tstest/integration/vms/distros.go index ca2bf53ba..172607962 100644 --- a/tstest/integration/vms/distros.go +++ b/tstest/integration/vms/distros.go @@ -5,7 +5,7 @@ package vms import ( _ "embed" - "encoding/json" + jsonv1 "encoding/json" "log" "github.com/tailscale/hujson" @@ -55,7 +55,7 @@ var Distros []Distro = func() []Distro { if err != nil { log.Fatalf("error decoding distros: %v", err) } - if err := json.Unmarshal(b, &result); err != nil { + if err := jsonv1.Unmarshal(b, &result); err != nil { log.Fatalf("error decoding distros: %v", err) } return result diff --git a/tstest/integration/vms/dns_tester.go b/tstest/integration/vms/dns_tester.go index 50b39bb5f..9c732c715 100644 --- a/tstest/integration/vms/dns_tester.go +++ b/tstest/integration/vms/dns_tester.go @@ -11,7 +11,7 @@ package main import ( "context" - "encoding/json" + jsonv1 "encoding/json" "flag" "net" "os" @@ -49,6 +49,6 @@ func lookup(ctx context.Context, target string) error { return err } - json.NewEncoder(os.Stdout).Encode(hosts) + jsonv1.NewEncoder(os.Stdout).Encode(hosts) return nil } diff --git a/tstest/mts/mts.go b/tstest/mts/mts.go index c10d69d8d..dc560ea05 100644 --- a/tstest/mts/mts.go +++ b/tstest/mts/mts.go @@ -11,7 +11,7 @@ package main import ( "bufio" "context" - "encoding/json" + jsonv1 "encoding/json" "flag" "fmt" "io" @@ -119,7 +119,7 @@ func runMTSServer(args []string) error { if !ok { return fmt.Errorf("no instance named %q", name) } - je := json.NewEncoder(os.Stdout) + je := jsonv1.NewEncoder(os.Stdout) je.SetIndent("", " ") if err := je.Encode(inst); err != nil { return err @@ -242,7 +242,7 @@ func getJSON[T any](res *http.Response, err error) (T, error) { body, _ := io.ReadAll(res.Body) return ret, fmt.Errorf("unexpected status: %v: %s", res.Status, body) } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { + if err := jsonv1.NewDecoder(res.Body).Decode(&ret); err != nil { return ret, err } return ret, nil @@ -484,7 +484,7 @@ type listResponseInstance struct { func writeJSON(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json") - e := json.NewEncoder(w) + e := jsonv1.NewEncoder(w) e.SetIndent("", " ") e.Encode(v) } diff --git a/tstest/natlab/vnet/vnet.go b/tstest/natlab/vnet/vnet.go index 49d47f029..6bd97bceb 100644 --- a/tstest/natlab/vnet/vnet.go +++ b/tstest/natlab/vnet/vnet.go @@ -16,7 +16,7 @@ import ( "context" "crypto/tls" "encoding/binary" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "io" @@ -80,7 +80,7 @@ func (s *Server) PopulateDERPMapIPs() error { return fmt.Errorf("tailscale debug derp-map: %v", err) } var dm tailcfg.DERPMap - if err := json.Unmarshal(out, &dm); err != nil { + if err := jsonv1.Unmarshal(out, &dm); err != nil { return fmt.Errorf("unmarshal DERPMap: %v", err) } for _, r := range dm.Regions { @@ -423,7 +423,7 @@ func (n *network) serveLogCatcherConn(clientRemoteIP netip.Addr, c net.Conn) { } Text string } - if err := json.Unmarshal(all, &logs); err != nil { + if err := jsonv1.Unmarshal(all, &logs); err != nil { log.Printf("Logs decode error: %v", err) return } diff --git a/tstime/mono/mono_test.go b/tstime/mono/mono_test.go index 67a8614ba..547bc0c29 100644 --- a/tstime/mono/mono_test.go +++ b/tstime/mono/mono_test.go @@ -4,7 +4,7 @@ package mono import ( - "encoding/json" + jsonv1 "encoding/json" "testing" "time" ) @@ -19,12 +19,12 @@ func TestNow(t *testing.T) { func TestUnmarshalZero(t *testing.T) { var tt time.Time - buf, err := json.Marshal(tt) + buf, err := jsonv1.Marshal(tt) if err != nil { t.Fatal(err) } var m Time - err = json.Unmarshal(buf, &m) + err = jsonv1.Unmarshal(buf, &m) if err != nil { t.Fatal(err) } diff --git a/tstime/rate/value.go b/tstime/rate/value.go index 610f06bbd..5be919b76 100644 --- a/tstime/rate/value.go +++ b/tstime/rate/value.go @@ -4,7 +4,7 @@ package rate import ( - "encoding/json" + jsonv1 "encoding/json" "fmt" "math" "sync" @@ -200,12 +200,12 @@ func (r *Value) MarshalJSON() ([]byte, error) { if r.HalfLife > 0 { v.HalfLife = r.HalfLife.String() } - return json.Marshal(v) + return jsonv1.Marshal(v) } func (r *Value) UnmarshalJSON(b []byte) error { var v jsonValue - if err := json.Unmarshal(b, &v); err != nil { + if err := jsonv1.Unmarshal(b, &v); err != nil { return err } halfLife, err := time.ParseDuration(v.HalfLife) diff --git a/tstime/tstime_test.go b/tstime/tstime_test.go index 556ad4e8b..1d1fe3428 100644 --- a/tstime/tstime_test.go +++ b/tstime/tstime_test.go @@ -4,7 +4,7 @@ package tstime import ( - "encoding/json" + jsonv1 "encoding/json" "testing" "time" @@ -40,13 +40,13 @@ func TestParseDuration(t *testing.T) { func TestGoDuration(t *testing.T) { wantDur := GoDuration{time.Hour + time.Minute + time.Second + time.Millisecond + time.Microsecond + time.Nanosecond} - gotJSON := string(must.Get(json.Marshal(wantDur))) + gotJSON := string(must.Get(jsonv1.Marshal(wantDur))) wantJSON := `"1h1m1.001001001s"` if gotJSON != wantJSON { t.Errorf("json.Marshal(%v) = %s, want %s", wantDur, gotJSON, wantJSON) } var gotDur GoDuration - must.Do(json.Unmarshal([]byte(wantJSON), &gotDur)) + must.Do(jsonv1.Unmarshal([]byte(wantJSON), &gotDur)) if gotDur != wantDur { t.Errorf("json.Unmarshal(%s) = %v, want %v", wantJSON, gotDur, wantDur) } diff --git a/tsweb/log.go b/tsweb/log.go index 51f95e95f..dcfecac90 100644 --- a/tsweb/log.go +++ b/tsweb/log.go @@ -4,7 +4,7 @@ package tsweb import ( - "encoding/json" + jsonv1 "encoding/json" "strings" "time" ) @@ -59,6 +59,6 @@ func (m AccessLogRecord) String() string { m.Time = time.Now() } var buf strings.Builder - json.NewEncoder(&buf).Encode(m) + jsonv1.NewEncoder(&buf).Encode(m) return strings.TrimRight(buf.String(), "\n") } diff --git a/types/appctype/appconnector_test.go b/types/appctype/appconnector_test.go index 390d1776a..4bafef46d 100644 --- a/types/appctype/appconnector_test.go +++ b/types/appctype/appconnector_test.go @@ -4,7 +4,7 @@ package appctype import ( - "encoding/json" + jsonv1 "encoding/json" "net/netip" "strings" "testing" @@ -46,7 +46,7 @@ func TestGolden(t *testing.T) { }} var config AppConnectorConfig - if err := json.NewDecoder(strings.NewReader(golden)).Decode(&config); err != nil { + if err := jsonv1.NewDecoder(strings.NewReader(golden)).Decode(&config); err != nil { t.Fatalf("failed to decode golden config: %v", err) } @@ -60,10 +60,10 @@ func TestGolden(t *testing.T) { func TestRoundTrip(t *testing.T) { var config AppConnectorConfig - must.Do(json.NewDecoder(strings.NewReader(golden)).Decode(&config)) - b := must.Get(json.Marshal(config)) + must.Do(jsonv1.NewDecoder(strings.NewReader(golden)).Decode(&config)) + b := must.Get(jsonv1.Marshal(config)) var config2 AppConnectorConfig - must.Do(json.Unmarshal(b, &config2)) + must.Do(jsonv1.Unmarshal(b, &config2)) assertEqual(t, "DNAT", config.DNAT, config2.DNAT) } diff --git a/types/ipproto/ipproto_test.go b/types/ipproto/ipproto_test.go index 102b79cff..527917e75 100644 --- a/types/ipproto/ipproto_test.go +++ b/types/ipproto/ipproto_test.go @@ -5,7 +5,7 @@ package ipproto import ( "encoding" - "encoding/json" + jsonv1 "encoding/json" "fmt" "testing" @@ -123,14 +123,14 @@ func TestProtoUnmarshalJSON(t *testing.T) { for i := range 256 { j := []byte(fmt.Sprintf(`%d`, i)) - must.Do(json.Unmarshal(j, &p)) + must.Do(jsonv1.Unmarshal(j, &p)) if got, want := p, Proto(i); got != want { t.Errorf("Proto(%d) = %v, want %v", i, got, want) } } for name, wantProto := range acceptedNames { - must.Do(json.Unmarshal([]byte(fmt.Sprintf(`"%s"`, name)), &p)) + must.Do(jsonv1.Unmarshal([]byte(fmt.Sprintf(`"%s"`, name)), &p)) if got, want := p, wantProto; got != want { t.Errorf("Proto(%q) = %v, want %v", name, got, want) } diff --git a/types/jsonx/json.go b/types/jsonx/json.go index 3f01ea358..15e4e0a1d 100644 --- a/types/jsonx/json.go +++ b/types/jsonx/json.go @@ -13,7 +13,7 @@ import ( "fmt" "reflect" - "github.com/go-json-experiment/json" + jsonv2 "github.com/go-json-experiment/json" "github.com/go-json-experiment/json/jsontext" ) @@ -122,7 +122,7 @@ func MakeInterfaceCoders[T any](valuesByName map[string]T) (c struct { if err := enc.WriteToken(jsontext.String(name)); err != nil { return err } - if err := json.MarshalEncode(enc, *val); err != nil { + if err := jsonv2.MarshalEncode(enc, *val); err != nil { return err } if err := enc.WriteToken(jsontext.EndObject); err != nil { @@ -139,7 +139,7 @@ func MakeInterfaceCoders[T any](valuesByName map[string]T) (c struct { *val = zero // store nil interface value for JSON null return nil case tok.Kind() != '{': - return &json.SemanticError{JSONKind: tok.Kind(), GoType: reflect.TypeFor[T]()} + return &jsonv2.SemanticError{JSONKind: tok.Kind(), GoType: reflect.TypeFor[T]()} } var v reflect.Value switch tok, err := dec.ReadToken(); { @@ -154,7 +154,7 @@ func MakeInterfaceCoders[T any](valuesByName map[string]T) (c struct { } v = reflect.New(t) } - if err := json.UnmarshalDecode(dec, v.Interface()); err != nil { + if err := jsonv2.UnmarshalDecode(dec, v.Interface()); err != nil { return err } *val = v.Elem().Interface().(T) diff --git a/types/jsonx/json_test.go b/types/jsonx/json_test.go index 0f2a646c4..584e0a21d 100644 --- a/types/jsonx/json_test.go +++ b/types/jsonx/json_test.go @@ -7,7 +7,7 @@ import ( "errors" "testing" - "github.com/go-json-experiment/json" + jsonv2 "github.com/go-json-experiment/json" "github.com/go-json-experiment/json/jsontext" "github.com/google/go-cmp/cmp" "tailscale.com/types/ptr" @@ -46,9 +46,9 @@ func (w *InterfaceWrapper) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } func TestInterfaceCoders(t *testing.T) { - var opts json.Options = json.JoinOptions( - json.WithMarshalers(json.MarshalToFunc(interfaceCoders.Marshal)), - json.WithUnmarshalers(json.UnmarshalFromFunc(interfaceCoders.Unmarshal)), + var opts jsonv2.Options = jsonv2.JoinOptions( + jsonv2.WithMarshalers(jsonv2.MarshalToFunc(interfaceCoders.Marshal)), + jsonv2.WithUnmarshalers(jsonv2.UnmarshalFromFunc(interfaceCoders.Unmarshal)), ) errSkipMarshal := errors.New("skip marshal") @@ -105,13 +105,13 @@ func TestInterfaceCoders(t *testing.T) { }} { t.Run(tt.label, func(t *testing.T) { if tt.wantMarshalError != errSkipMarshal { - switch gotJSON, err := json.Marshal(&tt.wantVal); { + switch gotJSON, err := jsonv2.Marshal(&tt.wantVal); { case !errors.Is(err, tt.wantMarshalError): t.Fatalf("json.Marshal(%v) error = %v, want %v", tt.wantVal, err, tt.wantMarshalError) case string(gotJSON) != tt.wantJSON: t.Fatalf("json.Marshal(%v) = %s, want %s", tt.wantVal, gotJSON, tt.wantJSON) } - switch gotJSON, err := json.Marshal(&tt.wantVal.Interface, opts); { + switch gotJSON, err := jsonv2.Marshal(&tt.wantVal.Interface, opts); { case !errors.Is(err, tt.wantMarshalError): t.Fatalf("json.Marshal(%v) error = %v, want %v", tt.wantVal, err, tt.wantMarshalError) case string(gotJSON) != tt.wantJSON: @@ -121,14 +121,14 @@ func TestInterfaceCoders(t *testing.T) { if tt.wantJSON != "" { gotVal := makeFiller() - if err := json.Unmarshal([]byte(tt.wantJSON), &gotVal); !errors.Is(err, tt.wantUnmarshalError) { + if err := jsonv2.Unmarshal([]byte(tt.wantJSON), &gotVal); !errors.Is(err, tt.wantUnmarshalError) { t.Fatalf("json.Unmarshal(%v) error = %v, want %v", tt.wantJSON, err, tt.wantUnmarshalError) } if d := cmp.Diff(gotVal, tt.wantVal); d != "" { t.Fatalf("json.Unmarshal(%v):\n%s", tt.wantJSON, d) } gotVal = makeFiller() - if err := json.Unmarshal([]byte(tt.wantJSON), &gotVal.Interface, opts); !errors.Is(err, tt.wantUnmarshalError) { + if err := jsonv2.Unmarshal([]byte(tt.wantJSON), &gotVal.Interface, opts); !errors.Is(err, tt.wantUnmarshalError) { t.Fatalf("json.Unmarshal(%v) error = %v, want %v", tt.wantJSON, err, tt.wantUnmarshalError) } if d := cmp.Diff(gotVal, tt.wantVal); d != "" { diff --git a/types/key/control.go b/types/key/control.go index 96021249b..6ce8551f0 100644 --- a/types/key/control.go +++ b/types/key/control.go @@ -3,7 +3,7 @@ package key -import "encoding/json" +import jsonv1 "encoding/json" // ControlPrivate is a Tailscale control plane private key. // @@ -37,12 +37,12 @@ func (k ControlPrivate) Public() MachinePublic { // MarshalJSON implements json.Marshaler. func (k ControlPrivate) MarshalJSON() ([]byte, error) { - return json.Marshal(k.mkey.k) + return jsonv1.Marshal(k.mkey.k) } // UnmarshalJSON implements json.Unmarshaler. func (k *ControlPrivate) UnmarshalJSON(bs []byte) error { - return json.Unmarshal(bs, &k.mkey.k) + return jsonv1.Unmarshal(bs, &k.mkey.k) } // SealTo wraps cleartext into a NaCl box (see diff --git a/types/key/control_test.go b/types/key/control_test.go index a98a586f3..6cb7c29cc 100644 --- a/types/key/control_test.go +++ b/types/key/control_test.go @@ -4,7 +4,7 @@ package key import ( - "encoding/json" + jsonv1 "encoding/json" "testing" ) @@ -19,7 +19,7 @@ func TestControlKey(t *testing.T) { var got struct { PrivateKey ControlPrivate } - if err := json.Unmarshal([]byte(serialized), &got); err != nil { + if err := jsonv1.Unmarshal([]byte(serialized), &got); err != nil { t.Fatalf("decoding serialized ControlPrivate: %v", err) } @@ -27,7 +27,7 @@ func TestControlKey(t *testing.T) { t.Fatalf("Serialized ControlPrivate didn't deserialize as expected, got %v want %v", got.PrivateKey, want) } - bs, err := json.Marshal(got) + bs, err := jsonv1.Marshal(got) if err != nil { t.Fatalf("json reserialization of ControlPrivate failed: %v", err) } diff --git a/types/key/derp.go b/types/key/derp.go index 1466b85bc..f94ef6213 100644 --- a/types/key/derp.go +++ b/types/key/derp.go @@ -6,7 +6,7 @@ package key import ( "crypto/subtle" "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "errors" "fmt" "strings" @@ -26,13 +26,13 @@ type DERPMesh struct { // MarshalJSON implements the [encoding/json.Marshaler] interface. func (k DERPMesh) MarshalJSON() ([]byte, error) { - return json.Marshal(k.String()) + return jsonv1.Marshal(k.String()) } // UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. func (k *DERPMesh) UnmarshalJSON(data []byte) error { var s string - json.Unmarshal(data, &s) + jsonv1.Unmarshal(data, &s) if hex.DecodedLen(len(s)) != len(k.k) { return fmt.Errorf("types/key/derp: cannot unmarshal, incorrect size mesh key len: %d, must be %d, %w", hex.DecodedLen(len(s)), len(k.k), ErrInvalidMeshKey) diff --git a/types/key/disco_test.go b/types/key/disco_test.go index 131fe350f..b03a6b382 100644 --- a/types/key/disco_test.go +++ b/types/key/disco_test.go @@ -5,7 +5,7 @@ package key import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "testing" ) @@ -55,20 +55,20 @@ func TestDiscoSerialization(t *testing.T) { } var a key - if err := json.Unmarshal([]byte(serialized), &a); err != nil { + if err := jsonv1.Unmarshal([]byte(serialized), &a); err != nil { t.Fatal(err) } if a.Pub != pub { t.Errorf("wrong deserialization of public key, got %#v want %#v", a.Pub, pub) } - bs, err := json.MarshalIndent(a, "", " ") + bs, err := jsonv1.MarshalIndent(a, "", " ") if err != nil { t.Fatal(err) } var b bytes.Buffer - json.Indent(&b, []byte(serialized), "", " ") + jsonv1.Indent(&b, []byte(serialized), "", " ") if got, want := string(bs), b.String(); got != want { t.Error("json serialization doesn't roundtrip") } diff --git a/types/key/hardware_attestation.go b/types/key/hardware_attestation.go index 9d4a21ee4..af776cd84 100644 --- a/types/key/hardware_attestation.go +++ b/types/key/hardware_attestation.go @@ -8,7 +8,7 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/subtle" - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" @@ -28,8 +28,8 @@ const pubkeyLength = 65 // uncompressed P-256 // This key can only be marshalled and unmarshaled on the same machine. type HardwareAttestationKey interface { crypto.Signer - json.Marshaler - json.Unmarshaler + jsonv1.Marshaler + jsonv1.Unmarshaler io.Closer Clone() HardwareAttestationKey IsZero() bool diff --git a/types/key/machine_test.go b/types/key/machine_test.go index 157df9e43..e088b5f35 100644 --- a/types/key/machine_test.go +++ b/types/key/machine_test.go @@ -5,7 +5,7 @@ package key import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "strings" "testing" ) @@ -68,7 +68,7 @@ func TestMachineSerialization(t *testing.T) { } var a keypair - if err := json.Unmarshal([]byte(serialized), &a); err != nil { + if err := jsonv1.Unmarshal([]byte(serialized), &a); err != nil { t.Fatal(err) } if !a.Priv.Equal(priv) { @@ -78,13 +78,13 @@ func TestMachineSerialization(t *testing.T) { t.Errorf("wrong deserialization of public key, got %#v want %#v", a.Pub, pub) } - bs, err := json.MarshalIndent(a, "", " ") + bs, err := jsonv1.MarshalIndent(a, "", " ") if err != nil { t.Fatal(err) } var b bytes.Buffer - json.Indent(&b, []byte(serialized), "", " ") + jsonv1.Indent(&b, []byte(serialized), "", " ") if got, want := string(bs), b.String(); got != want { t.Error("json serialization doesn't roundtrip") } diff --git a/types/key/node_test.go b/types/key/node_test.go index 80a2dadf9..431e6da17 100644 --- a/types/key/node_test.go +++ b/types/key/node_test.go @@ -6,7 +6,7 @@ package key import ( "bufio" "bytes" - "encoding/json" + jsonv1 "encoding/json" "strings" "testing" ) @@ -83,7 +83,7 @@ func TestNodeSerialization(t *testing.T) { } var a keypair - if err := json.Unmarshal([]byte(serialized), &a); err != nil { + if err := jsonv1.Unmarshal([]byte(serialized), &a); err != nil { t.Fatal(err) } if !a.Priv.Equal(priv) { @@ -93,13 +93,13 @@ func TestNodeSerialization(t *testing.T) { t.Errorf("wrong deserialization of public key, got %#v want %#v", a.Pub, pub) } - bs, err := json.MarshalIndent(a, "", " ") + bs, err := jsonv1.MarshalIndent(a, "", " ") if err != nil { t.Fatal(err) } var b bytes.Buffer - json.Indent(&b, []byte(serialized), "", " ") + jsonv1.Indent(&b, []byte(serialized), "", " ") if got, want := string(bs), b.String(); got != want { t.Error("json serialization doesn't roundtrip") } diff --git a/types/logger/logger.go b/types/logger/logger.go index 6c4edf633..8b9b0a70f 100644 --- a/types/logger/logger.go +++ b/types/logger/logger.go @@ -10,7 +10,7 @@ import ( "bufio" "bytes" "container/list" - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" "log" @@ -45,12 +45,12 @@ type Context context.Context // jenc is a json.Encode + bytes.Buffer pair wired up to be reused in a pool. type jenc struct { buf bytes.Buffer - enc *json.Encoder + enc *jsonv1.Encoder } var jencPool = &sync.Pool{New: func() any { je := new(jenc) - je.enc = json.NewEncoder(&je.buf) + je.enc = jsonv1.NewEncoder(&je.buf) return je }} @@ -378,7 +378,7 @@ func AsJSON(v any) fmt.Formatter { type asJSONResult struct{ v any } func (a asJSONResult) Format(s fmt.State, verb rune) { - v, err := json.Marshal(a.v) + v, err := jsonv1.Marshal(a.v) if err != nil { fmt.Fprintf(s, "%%!JSON-ERROR:%v", err) return diff --git a/types/netlogtype/netlogtype_test.go b/types/netlogtype/netlogtype_test.go index 00f89b228..7a254f603 100644 --- a/types/netlogtype/netlogtype_test.go +++ b/types/netlogtype/netlogtype_test.go @@ -6,7 +6,7 @@ package netlogtype import ( - "encoding/json" + jsonv1 "encoding/json" "math" "net/netip" "testing" @@ -27,7 +27,7 @@ func TestMaxSize(t *testing.T) { Counts{math.MaxUint64, math.MaxUint64, math.MaxUint64, math.MaxUint64}, } - outJSON := must.Get(json.Marshal(cc)) + outJSON := must.Get(jsonv1.Marshal(cc)) if string(outJSON) != maxJSONConnCounts { t.Errorf("JSON mismatch (-got +want):\n%s", cmp.Diff(string(outJSON), maxJSONConnCounts)) } diff --git a/types/netmap/netmap.go b/types/netmap/netmap.go index cc6bec1db..ad13c2928 100644 --- a/types/netmap/netmap.go +++ b/types/netmap/netmap.go @@ -6,7 +6,7 @@ package netmap import ( "cmp" - "encoding/json" + jsonv1 "encoding/json" "fmt" "net/netip" "sort" @@ -438,7 +438,7 @@ func (b *NetworkMap) ConciseDiffFrom(a *NetworkMap) string { } func (nm *NetworkMap) JSON() string { - b, err := json.MarshalIndent(*nm, "", " ") + b, err := jsonv1.MarshalIndent(*nm, "", " ") if err != nil { return fmt.Sprintf("[json error: %v]", err) } diff --git a/types/opt/bool_test.go b/types/opt/bool_test.go index dddbcfc19..d4c8dc742 100644 --- a/types/opt/bool_test.go +++ b/types/opt/bool_test.go @@ -4,7 +4,7 @@ package opt import ( - "encoding/json" + jsonv1 "encoding/json" "flag" "reflect" "strings" @@ -72,7 +72,7 @@ func TestBool(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - j, err := json.Marshal(tt.in) + j, err := jsonv1.Marshal(tt.in) if err != nil { t.Fatal(err) } @@ -87,7 +87,7 @@ func TestBool(t *testing.T) { // And back again: newVal := reflect.New(reflect.TypeOf(tt.in)) out := newVal.Interface() - if err := json.Unmarshal(j, out); err != nil { + if err := jsonv1.Unmarshal(j, out); err != nil { t.Fatalf("Unmarshal %#q: %v", j, err) } got := newVal.Elem().Interface() @@ -123,7 +123,7 @@ func TestBoolEqualBool(t *testing.T) { } func TestUnmarshalAlloc(t *testing.T) { - b := json.Unmarshaler(new(Bool)) + b := jsonv1.Unmarshaler(new(Bool)) n := testing.AllocsPerRun(10, func() { b.UnmarshalJSON(trueBytes) }) if n > 0 { t.Errorf("got %v allocs, want 0", n) diff --git a/types/opt/value_test.go b/types/opt/value_test.go index 890f9a579..d269d7528 100644 --- a/types/opt/value_test.go +++ b/types/opt/value_test.go @@ -4,7 +4,7 @@ package opt import ( - "encoding/json" + jsonv1 "encoding/json" "reflect" "testing" @@ -97,7 +97,7 @@ func TestValue(t *testing.T) { want: bools.IfElse( // Detect whether v1 "encoding/json" supports `omitzero` or not. // TODO(Go1.24): Remove this after `omitzero` is supported. - string(must.Get(json.Marshal(struct { + string(must.Get(jsonv1.Marshal(struct { X int `json:",omitzero"` }{}))) == `{}`, `{"True":true,"False":false}`, // omitzero supported @@ -235,7 +235,7 @@ func TestValue(t *testing.T) { if tt.jsonv2 { j, err = jsonv2.Marshal(tt.in) } else { - j, err = json.Marshal(tt.in) + j, err = jsonv1.Marshal(tt.in) } if err != nil { t.Fatal(err) @@ -254,7 +254,7 @@ func TestValue(t *testing.T) { if tt.jsonv2 { err = jsonv2.Unmarshal(j, out) } else { - err = json.Unmarshal(j, out) + err = jsonv1.Unmarshal(j, out) } if err != nil { t.Fatalf("Unmarshal %#q: %v", j, err) diff --git a/types/prefs/prefs_test.go b/types/prefs/prefs_test.go index d6af745bf..7b5869c8e 100644 --- a/types/prefs/prefs_test.go +++ b/types/prefs/prefs_test.go @@ -5,7 +5,7 @@ package prefs import ( "bytes" - "encoding/json" + jsonv1 "encoding/json" "errors" "net/netip" "reflect" @@ -346,8 +346,8 @@ func TestMarshalUnmarshal(t *testing.T) { }{ { name: "json", - marshal: json.Marshal, - unmarshal: json.Unmarshal, + marshal: jsonv1.Marshal, + unmarshal: jsonv1.Unmarshal, }, { name: "jsonv2", diff --git a/types/tkatype/tkatype_test.go b/types/tkatype/tkatype_test.go index c81891b9c..3e5e2f39b 100644 --- a/types/tkatype/tkatype_test.go +++ b/types/tkatype/tkatype_test.go @@ -4,7 +4,7 @@ package tkatype import ( - "encoding/json" + jsonv1 "encoding/json" "testing" "golang.org/x/crypto/blake2s" @@ -24,7 +24,7 @@ func TestSigHashSize(t *testing.T) { func TestMarshaledSignatureJSON(t *testing.T) { sig := MarshaledSignature("abcdef") - j, err := json.Marshal(sig) + j, err := jsonv1.Marshal(sig) if err != nil { t.Fatal(err) } @@ -34,7 +34,7 @@ func TestMarshaledSignatureJSON(t *testing.T) { } var back MarshaledSignature - if err := json.Unmarshal([]byte(encoded), &back); err != nil { + if err := jsonv1.Unmarshal([]byte(encoded), &back); err != nil { t.Fatal(err) } if string(back) != string(sig) { diff --git a/util/cloudenv/cloudenv.go b/util/cloudenv/cloudenv.go index f55f7dfb0..493f65ae8 100644 --- a/util/cloudenv/cloudenv.go +++ b/util/cloudenv/cloudenv.go @@ -6,7 +6,7 @@ package cloudenv import ( "context" - "encoding/json" + jsonv1 "encoding/json" "log" "math/rand/v2" "net" @@ -202,7 +202,7 @@ func getCloud() Cloud { var meta struct { AzEnvironment string `json:"azEnvironment"` } - if err := json.NewDecoder(res.Body).Decode(&meta); err != nil { + if err := jsonv1.NewDecoder(res.Body).Decode(&meta); err != nil { return "" } if strings.HasPrefix(meta.AzEnvironment, "Azure") { diff --git a/util/expvarx/expvarx.go b/util/expvarx/expvarx.go index 762f65d06..84f773379 100644 --- a/util/expvarx/expvarx.go +++ b/util/expvarx/expvarx.go @@ -5,7 +5,7 @@ package expvarx import ( - "encoding/json" + jsonv1 "encoding/json" "expvar" "sync" "time" @@ -84,6 +84,6 @@ func (s *SafeFunc) Value() any { // String implements stringer in the same pattern as [expvar.Func], calling // Value and serializing the result as JSON, ignoring errors. func (s *SafeFunc) String() string { - v, _ := json.Marshal(s.Value()) + v, _ := jsonv1.Marshal(s.Value()) return string(v) } diff --git a/util/reload/reload.go b/util/reload/reload.go index f18f9ebd1..1e47221fb 100644 --- a/util/reload/reload.go +++ b/util/reload/reload.go @@ -7,7 +7,7 @@ package reload import ( "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "math/rand/v2" "os" @@ -180,7 +180,7 @@ func FromJSONFile[T any](path string) ReloadOpts[T] { }, Unmarshal: func(b []byte) (T, error) { var ret, zero T - if err := json.Unmarshal(b, &ret); err != nil { + if err := jsonv1.Unmarshal(b, &ret); err != nil { return zero, err } return ret, nil diff --git a/util/set/set.go b/util/set/set.go index eb0697536..2a6f489c6 100644 --- a/util/set/set.go +++ b/util/set/set.go @@ -5,7 +5,7 @@ package set import ( - "encoding/json" + jsonv1 "encoding/json" "maps" ) @@ -81,12 +81,12 @@ func (s Set[T]) Equal(other Set[T]) bool { } func (s Set[T]) MarshalJSON() ([]byte, error) { - return json.Marshal(s.Slice()) + return jsonv1.Marshal(s.Slice()) } func (s *Set[T]) UnmarshalJSON(buf []byte) error { var ss []T - if err := json.Unmarshal(buf, &ss); err != nil { + if err := jsonv1.Unmarshal(buf, &ss); err != nil { return err } *s = SetOf(ss) diff --git a/util/set/set_test.go b/util/set/set_test.go index 85913ad24..95be4b018 100644 --- a/util/set/set_test.go +++ b/util/set/set_test.go @@ -4,7 +4,7 @@ package set import ( - "encoding/json" + jsonv1 "encoding/json" "slices" "testing" ) @@ -128,13 +128,13 @@ func TestSetJSONRoundTrip(t *testing.T) { for _, tt := range tests { t.Run(tt.desc, func(t *testing.T) { t.Run("strings", func(t *testing.T) { - buf, err := json.Marshal(tt.strings) + buf, err := jsonv1.Marshal(tt.strings) if err != nil { t.Fatalf("json.Marshal: %v", err) } t.Logf("marshaled: %s", buf) var s Set[string] - if err := json.Unmarshal(buf, &s); err != nil { + if err := jsonv1.Unmarshal(buf, &s); err != nil { t.Fatalf("json.Unmarshal: %v", err) } if !s.Equal(tt.strings) { @@ -142,13 +142,13 @@ func TestSetJSONRoundTrip(t *testing.T) { } }) t.Run("ints", func(t *testing.T) { - buf, err := json.Marshal(tt.ints) + buf, err := jsonv1.Marshal(tt.ints) if err != nil { t.Fatalf("json.Marshal: %v", err) } t.Logf("marshaled: %s", buf) var s Set[int] - if err := json.Unmarshal(buf, &s); err != nil { + if err := jsonv1.Unmarshal(buf, &s); err != nil { t.Fatalf("json.Unmarshal: %v", err) } if !s.Equal(tt.ints) { diff --git a/util/syspolicy/setting/snapshot_test.go b/util/syspolicy/setting/snapshot_test.go index 762a9681c..0fe74c67d 100644 --- a/util/syspolicy/setting/snapshot_test.go +++ b/util/syspolicy/setting/snapshot_test.go @@ -5,7 +5,7 @@ package setting import ( "cmp" - "encoding/json" + jsonv1 "encoding/json" "testing" "time" @@ -556,7 +556,7 @@ func TestMarshalUnmarshalSnapshot(t *testing.T) { if useJSONv2 { gotJSON, err = jsonv2.Marshal(tt.snapshot) } else { - gotJSON, err = json.Marshal(tt.snapshot) + gotJSON, err = jsonv1.Marshal(tt.snapshot) } if err != nil { t.Fatal(err) @@ -570,7 +570,7 @@ func TestMarshalUnmarshalSnapshot(t *testing.T) { if useJSONv2 { err = jsonv2.Unmarshal(gotJSON, &gotBack) } else { - err = json.Unmarshal(gotJSON, &gotBack) + err = jsonv1.Unmarshal(gotJSON, &gotBack) } if err != nil { t.Fatal(err) diff --git a/util/winutil/svcdiag_windows.go b/util/winutil/svcdiag_windows.go index 372377cf9..bbdee940f 100644 --- a/util/winutil/svcdiag_windows.go +++ b/util/winutil/svcdiag_windows.go @@ -5,7 +5,7 @@ package winutil import ( "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "fmt" "strings" "unsafe" @@ -37,7 +37,7 @@ func LogSvcState(logf logger.Logf, rootSvcName string) { return } - json, err := json.MarshalIndent(logEntries, "", " ") + json, err := jsonv1.MarshalIndent(logEntries, "", " ") if err != nil { logf("Error marshaling service log entries: %v", err) return @@ -149,7 +149,7 @@ func (tsdi *_SERVICE_TRIGGER_SPECIFIC_DATA_ITEM) MarshalJSON() ([]byte, error) { m.Data = hex.EncodeToString(data) } - return json.Marshal(m) + return jsonv1.Marshal(m) } type _SERVICE_TRIGGER struct { @@ -176,7 +176,7 @@ func (ti *_SERVICE_TRIGGER) MarshalJSON() ([]byte, error) { if ti.triggerSubtype != nil { m.TriggerSubtype = ti.triggerSubtype.String() } - return json.Marshal(m) + return jsonv1.Marshal(m) } type _SERVICE_TRIGGER_INFO struct { @@ -187,7 +187,7 @@ type _SERVICE_TRIGGER_INFO struct { func (sti *_SERVICE_TRIGGER_INFO) MarshalJSON() ([]byte, error) { triggers := unsafe.Slice(sti.pTriggers, sti.cTriggers) - return json.Marshal(triggers) + return jsonv1.Marshal(triggers) } // getSvcTriggerInfo obtains information about any system events that may be diff --git a/wgengine/filter/filter_test.go b/wgengine/filter/filter_test.go index ae39eeb08..61f874b6f 100644 --- a/wgengine/filter/filter_test.go +++ b/wgengine/filter/filter_test.go @@ -5,7 +5,7 @@ package filter import ( "encoding/hex" - "encoding/json" + jsonv1 "encoding/json" "flag" "fmt" "net/netip" @@ -1077,7 +1077,7 @@ func benchmarkFile(b *testing.B, file string, opt benchOpt) { if err != nil { b.Fatal(err) } - if err := json.Unmarshal(bts, &matches); err != nil { + if err := jsonv1.Unmarshal(bts, &matches); err != nil { b.Fatal(err) } diff --git a/wgengine/router/osrouter/router_windows.go b/wgengine/router/osrouter/router_windows.go index a1acbe3b6..af7858e03 100644 --- a/wgengine/router/osrouter/router_windows.go +++ b/wgengine/router/osrouter/router_windows.go @@ -6,7 +6,7 @@ package osrouter import ( "bufio" "context" - "encoding/json" + jsonv1 "encoding/json" "fmt" "io" "net/netip" @@ -155,7 +155,7 @@ type firewallTweaker struct { fwProc *exec.Cmd // stop makes fwProc exit when closed. fwProcWriter io.WriteCloser - fwProcEncoder *json.Encoder + fwProcEncoder *jsonv1.Encoder // The path to the 'netsh.exe' binary, populated during the first call // to runFirewall. @@ -388,7 +388,7 @@ func (ft *firewallTweaker) doSet(local []string, killswitch bool, clear bool, pr } ft.fwProcWriter = in ft.fwProc = proc - ft.fwProcEncoder = json.NewEncoder(in) + ft.fwProcEncoder = jsonv1.NewEncoder(in) } // Note(maisem): when local lan access toggled, we need to inform the // firewall to let the local routes through. The set of routes is passed