[cipd] Add CIPD_DISABLE_NETWORK support to cipd proxy. This will allow verification testing with a read-only cache to ensure the proxy never attempts to hit the network. Bug: 538203306 Change-Id: Ib94f0972fc59c7539dd043116aa341c76a6a6964 Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/luci-go/+/8251624 Commit-Queue: Robbie Iannucci <iannucci@google.com> Reviewed-by: Dan Le Febvre <dlf@google.com>
diff --git a/cipd/client/cipd/client.go b/cipd/client/cipd/client.go index 0498ac6..441f7c5 100644 --- a/cipd/client/cipd/client.go +++ b/cipd/client/cipd/client.go
@@ -142,7 +142,7 @@ // ClientPackage is a package with the CIPD client. Used during self-update. ClientPackage = "infra/tools/cipd/${platform}" // UserAgent is HTTP user agent string for CIPD client. - UserAgent = "cipd 2.9.0" + UserAgent = "cipd 2.9.1" ) func init() {
diff --git a/cipd/client/cli/cmd_proxy.go b/cipd/client/cli/cmd_proxy.go index a2433ae..1dca485 100644 --- a/cipd/client/cli/cmd_proxy.go +++ b/cipd/client/cli/cmd_proxy.go
@@ -15,6 +15,7 @@ package cli import ( + "bytes" "context" "fmt" "io" @@ -23,6 +24,7 @@ "path/filepath" "github.com/maruel/subcommands" + "google.golang.org/grpc/codes" "google.golang.org/protobuf/encoding/prototext" "go.chromium.org/luci/auth" @@ -31,6 +33,7 @@ "go.chromium.org/luci/common/errors" "go.chromium.org/luci/common/logging" "go.chromium.org/luci/common/system/environ" + "go.chromium.org/luci/grpc/prpc" "go.chromium.org/luci/cipd/client/cipd" "go.chromium.org/luci/cipd/client/cipd/proxyserver" @@ -57,6 +60,7 @@ c.Flags.StringVar(&c.proxyPolicy, "proxy-policy", "-", "Path to a text protobuf file with cipd.proxy.Policy message (or - for reading from stdin).") c.Flags.StringVar(&c.readOnlyCacheDir, "read-only-cache-dir", "", fmt.Sprintf(`Directory for a shared read-only cache (can also be set by %s env var). Prepared with "cipd cache-prepare".`, cipd.EnvReadOnlyCacheDir)) + c.Flags.BoolVar(&c.disableNetwork, "disable-network", false, "If provided, client will make no network requests.") return c }, } @@ -69,6 +73,7 @@ unixSocket string // -unix-socket flag proxyPolicy string // -proxy-policy flag readOnlyCacheDir string // -read-only-cache-dir flag + disableNetwork bool // -disable-network flag } func (c *proxyRun) Run(a subcommands.Application, args []string, env subcommands.Env) int { @@ -76,10 +81,29 @@ return 1 } ctx := cli.GetContext(a, c, env) - return c.done(runProxy(ctx, c.authFlags, c.unixSocket, c.proxyPolicy, c.readOnlyCacheDir)) + return c.done(runProxy(ctx, c.authFlags, c.unixSocket, c.proxyPolicy, c.readOnlyCacheDir, c.disableNetwork)) } -func runProxy(ctx context.Context, authFlags authcli.Flags, unixSocket, proxyPolicy, readOnlyCacheDir string) (*proxyserver.ProxyStats, error) { +type disabledRoundTripper struct{} + +func (r disabledRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + const body = "cipd proxy: not in read-only cache and network is disabled" + hdr := http.Header{} + hdr.Set(prpc.HeaderGRPCCode, fmt.Sprint(int(codes.NotFound))) + return &http.Response{ + Status: "404 Not Found", + StatusCode: http.StatusNotFound, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + Body: io.NopCloser(bytes.NewBufferString(body)), + ContentLength: int64(len(body)), + Request: req, + Header: hdr, + }, nil +} + +func runProxy(ctx context.Context, authFlags authcli.Flags, unixSocket, proxyPolicy, readOnlyCacheDir string, disableNetwork bool) (*proxyserver.ProxyStats, error) { if unixSocket == "" { dir, err := os.MkdirTemp("", "cipd") if err != nil { @@ -101,6 +125,7 @@ cliOpts := &cipd.ClientOptions{ ServiceURL: "http://fake.example.com", ReadOnlyCacheDir: readOnlyCacheDir, + DisableNetwork: disableNetwork, } env := environ.FromCtx(ctx) env.Remove(cipd.EnvCacheDir) @@ -119,11 +144,17 @@ if err != nil { return nil, cipderr.BadArgument.Apply(errors.Fmt("bad auth options: %w", err)) } - httpClient, err := auth.NewAuthenticator(ctx, auth.SilentLogin, authOpts).Client() - if err != nil { - logging.Warningf(ctx, "Failed to initialize authenticated client: %s", err) - logging.Warningf(ctx, "Starting proxy in anonymous mode. Package fetches requiring authentication will fail.") - httpClient = http.DefaultClient + var httpClient *http.Client + if cliOpts.DisableNetwork { + httpClient = &http.Client{ + Transport: disabledRoundTripper{}, + } + } else { + if httpClient, err = auth.NewAuthenticator(ctx, auth.SilentLogin, authOpts).Client(); err != nil { + logging.Warningf(ctx, "Failed to initialize authenticated client: %s", err) + logging.Warningf(ctx, "Starting proxy in anonymous mode. Package fetches requiring authentication will fail.") + httpClient = http.DefaultClient + } } return runProxyImpl(ctx, unixSocket, policy, httpClient, cliOpts.ReadOnlyCacheDir) }
diff --git a/cipd/client/cli/cmd_proxy_test.go b/cipd/client/cli/cmd_proxy_test.go index 29c5015..93ffa8b 100644 --- a/cipd/client/cli/cmd_proxy_test.go +++ b/cipd/client/cli/cmd_proxy_test.go
@@ -16,6 +16,7 @@ import ( "context" + "net/http" "path/filepath" "testing" @@ -51,7 +52,7 @@ cipd.EnvReadOnlyCacheDir + "=relative/path", }).SetInCtx(context.Background()) - _, err := runProxy(ctx, authcli.Flags{}, "/dev/null", "-", "") + _, err := runProxy(ctx, authcli.Flags{}, "/dev/null", "-", "", false) assert.That(t, err, should.ErrLike("not an absolute path")) }) @@ -65,7 +66,47 @@ // With a bad policy file path, runProxy will proceed past readOnlyCacheDir resolution // and fail on readProxyPolicy, proving readOnlyCacheDir was accepted. - _, err = runProxy(ctx, authcli.Flags{}, "/dev/null", "/nonexistent/policy.textpb", "") + _, err = runProxy(ctx, authcli.Flags{}, "/dev/null", "/nonexistent/policy.textpb", "", false) assert.That(t, err, should.ErrLike("missing proxy policy file")) }) } + +func TestCmdProxy_DisableNetwork(t *testing.T) { + t.Parallel() + + cmd := cmdProxy(Parameters{}) + f := cmd.CommandRun().(*proxyRun) + + t.Run("Flag registration", func(t *testing.T) { + flag := f.Flags.Lookup("disable-network") + assert.That(t, flag != nil, should.BeTrue) + }) + + t.Run("Flag parsing", func(t *testing.T) { + c := cmdProxy(Parameters{}).CommandRun().(*proxyRun) + err := c.Flags.Parse([]string{"-disable-network"}) + assert.NoErr(t, err) + assert.That(t, c.disableNetwork, should.BeTrue) + }) + + t.Run("disabledRoundTripper returns 404", func(t *testing.T) { + req, err := http.NewRequest("GET", "http://example.com", nil) + assert.NoErr(t, err) + resp, err := disabledRoundTripper{}.RoundTrip(req) + assert.NoErr(t, err) + assert.That(t, resp.StatusCode, should.Equal(404)) + }) + + t.Run("Env var resolution - CIPD_DISABLE_NETWORK accepted", func(t *testing.T) { + for _, val := range []string{"1", "true"} { + ctx := environ.New([]string{ + cipd.EnvCIPDDisableNetwork + "=" + val, + }).SetInCtx(context.Background()) + + // With a bad policy file path, runProxy will proceed past env resolution + // and fail on readProxyPolicy, proving env was accepted. + _, err := runProxy(ctx, authcli.Flags{}, "/dev/null", "/nonexistent/policy.textpb", "", false) + assert.That(t, err, should.ErrLike("missing proxy policy file")) + } + }) +}