Repository navigation
fix: keep http.DefaultTransport a *http.Transport for OPA http.send #449
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dgilman-perplexity
wants to merge
1
commit into
block:main
Choose a base branch
from
dgilman-perplexity:fix/opa-http-send-default-transport
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+177
−17
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "encoding/pem" | ||
| "log/slog" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "os" | ||
| "os/exec" | ||
| "path/filepath" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/alecthomas/assert/v2" | ||
| "github.com/open-policy-agent/opa/v1/rego" | ||
|
|
||
| "github.com/block/cachew/internal/httputil" | ||
| "github.com/block/cachew/internal/logging" | ||
| ) | ||
|
|
||
| const opaTransportStartupChildEnv = "CACHEWD_OPA_TRANSPORT_STARTUP_CHILD" | ||
|
|
||
| func TestOPAHTTPSendWithTLSOptionsAfterProcessSetup(t *testing.T) { | ||
| if os.Getenv(opaTransportStartupChildEnv) != "1" { | ||
| cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^"+t.Name()+"$", "-test.count=1") | ||
| cmd.Env = append(os.Environ(), opaTransportStartupChildEnv+"=1") | ||
| output, err := cmd.CombinedOutput() | ||
| assert.NoError(t, err, "%s", output) | ||
| return | ||
| } | ||
| logger, ctx := logging.Configure(t.Context(), logging.Config{Level: slog.LevelError}) | ||
| configureProcess(logger, 0, time.Second, time.Minute) | ||
|
|
||
| _, ok := http.DefaultTransport.(*http.Transport) | ||
| assert.True(t, ok, "configureProcess must leave http.DefaultTransport a *http.Transport, got %T", http.DefaultTransport) | ||
| _, ok = httputil.UpstreamTransport().(*http.Transport) | ||
| assert.False(t, ok, "configureProcess must install the upstream transport") | ||
|
|
||
| var upstreamHits int | ||
| upstream := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { | ||
| upstreamHits++ | ||
| w.WriteHeader(http.StatusOK) | ||
| })) | ||
| t.Cleanup(upstream.Close) | ||
| caFile := filepath.Join(t.TempDir(), "ca.crt") | ||
| assert.NoError(t, os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{ | ||
| Type: "CERTIFICATE", Bytes: upstream.Certificate().Raw, | ||
| }), 0o600)) | ||
|
|
||
| query, err := rego.New( | ||
| rego.Query("data.cachew.allow"), | ||
| rego.Module("policy.rego", ` | ||
| package cachew | ||
|
|
||
| default allow := false | ||
|
|
||
| allow if { | ||
| resp := http.send({"method": "HEAD", "url": input.url, "tls_ca_cert_file": input.ca_file}) | ||
| resp.status_code == 200 | ||
| } | ||
| `), | ||
| ).PrepareForEval(ctx) | ||
| assert.NoError(t, err) | ||
|
|
||
| results, err := query.Eval(ctx, rego.EvalInput(map[string]any{"url": upstream.URL, "ca_file": caFile})) | ||
| assert.NoError(t, err) | ||
| assert.Equal(t, 1, len(results)) | ||
| assert.Equal(t, true, results[0].Expressions[0].Value) | ||
| assert.Equal(t, 1, upstreamHits) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| package httputil | ||
|
|
||
| import ( | ||
| "net/http" | ||
| "sync/atomic" | ||
| ) | ||
|
|
||
| // upstream is the transport cachewd installs for outbound requests that would | ||
| // otherwise use http.DefaultTransport. It is kept here instead of being | ||
| // assigned to http.DefaultTransport because third-party code, such as OPA's | ||
| // http.send, asserts that the global is a *http.Transport and panics on any | ||
| // wrapper. | ||
| var upstream atomic.Pointer[http.RoundTripper] //nolint:gochecknoglobals | ||
|
|
||
| // SetUpstreamTransport installs the shared outbound transport returned by | ||
| // [UpstreamTransport], leaving http.DefaultTransport unchanged. A nil | ||
| // transport restores the default of following http.DefaultTransport. | ||
| func SetUpstreamTransport(rt http.RoundTripper) { | ||
| if rt == nil { | ||
| upstream.Store(nil) | ||
| return | ||
| } | ||
| upstream.Store(&rt) | ||
| } | ||
|
|
||
| // UpstreamTransport returns the shared outbound transport. Until one is | ||
| // installed, requests go to whatever http.DefaultTransport is at request time, | ||
| // so tests can still swap the global to intercept upstream traffic. | ||
| func UpstreamTransport() http.RoundTripper { | ||
| return upstreamTransport{} | ||
| } | ||
|
|
||
| // UpstreamClient returns a client that sends through [UpstreamTransport]. | ||
| func UpstreamClient() *http.Client { | ||
| return &http.Client{Transport: UpstreamTransport()} | ||
| } | ||
|
|
||
| type upstreamTransport struct{} | ||
|
|
||
| func (upstreamTransport) RoundTrip(req *http.Request) (*http.Response, error) { | ||
| if rt := upstream.Load(); rt != nil { | ||
| return (*rt).RoundTrip(req) //nolint:wrapcheck | ||
| } | ||
| return http.DefaultTransport.RoundTrip(req) //nolint:wrapcheck | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| package httputil_test | ||
|
|
||
| import ( | ||
| "net/http" | ||
| "testing" | ||
|
|
||
| "github.com/alecthomas/assert/v2" | ||
|
|
||
| "github.com/block/cachew/internal/httputil" | ||
| ) | ||
|
|
||
| type staticTransport struct{ status int } | ||
|
|
||
| func (s staticTransport) RoundTrip(*http.Request) (*http.Response, error) { | ||
| return &http.Response{StatusCode: s.status, Body: http.NoBody}, nil | ||
| } | ||
|
|
||
| func TestUpstreamTransportFollowsDefaultUntilSet(t *testing.T) { | ||
| defaultTransport := http.DefaultTransport | ||
| t.Cleanup(func() { | ||
| http.DefaultTransport = defaultTransport //nolint:reassign | ||
| httputil.SetUpstreamTransport(nil) | ||
| }) | ||
| httputil.SetUpstreamTransport(nil) | ||
| http.DefaultTransport = staticTransport{status: http.StatusTeapot} //nolint:reassign | ||
| req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://example.com/", nil) | ||
| assert.NoError(t, err) | ||
|
|
||
| resp, err := httputil.UpstreamClient().Do(req) | ||
| assert.NoError(t, err) | ||
| assert.Equal(t, http.StatusTeapot, resp.StatusCode) | ||
|
|
||
| httputil.SetUpstreamTransport(staticTransport{status: http.StatusAccepted}) | ||
| resp, err = httputil.UpstreamClient().Do(req) | ||
| assert.NoError(t, err) | ||
| assert.Equal(t, http.StatusAccepted, resp.StatusCode) | ||
| assert.Equal[http.RoundTripper](t, staticTransport{status: http.StatusTeapot}, http.DefaultTransport) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.