-
Notifications
You must be signed in to change notification settings - Fork 23
Add support for additional backend headers #42
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
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/spotify/save-to-spotify/config" | ||
| ) | ||
|
|
||
| // startBackendTestServer starts a test server that records request headers. | ||
| // If asBackend is true, config.BackendBaseURL is pointed at it so the | ||
| // additional-headers transport treats it as the backend host. | ||
| func startBackendTestServer(t *testing.T, asBackend bool) (*httptest.Server, *http.Header) { | ||
| t.Helper() | ||
|
|
||
| var gotHeaders http.Header | ||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| gotHeaders = r.Header | ||
| w.WriteHeader(200) | ||
| })) | ||
| t.Cleanup(srv.Close) | ||
|
|
||
| if asBackend { | ||
| origURL := config.BackendBaseURL | ||
| config.BackendBaseURL = srv.URL | ||
| t.Cleanup(func() { config.BackendBaseURL = origURL }) | ||
| } | ||
|
|
||
| return srv, &gotHeaders | ||
| } | ||
|
|
||
| func setAdditionalHeaders(t *testing.T, headers map[string]string) { | ||
| t.Helper() | ||
| orig := config.AdditionalHeaders() | ||
| config.SetAdditionalHeaders(headers) | ||
| t.Cleanup(func() { config.SetAdditionalHeaders(orig) }) | ||
| } | ||
|
|
||
| func doTestAPIRequest(t *testing.T, srv *httptest.Server) { | ||
| t.Helper() | ||
| req, _ := http.NewRequestWithContext(context.Background(), "GET", srv.URL+"/api/v1/shows", nil) | ||
| resp, err := doAPIRequest(req, &config.TokenData{AccessToken: "test-token"}) | ||
| if err != nil { | ||
| t.Fatalf("doAPIRequest: %v", err) | ||
| } | ||
| resp.Body.Close() | ||
| } | ||
|
|
||
| func TestDoAPIRequest_NoAdditionalHeaders(t *testing.T) { | ||
| setAdditionalHeaders(t, nil) | ||
| srv, gotHeaders := startBackendTestServer(t, true) | ||
| doTestAPIRequest(t, srv) | ||
|
|
||
| if got := gotHeaders.Get("Authorization"); got != "Bearer test-token" { | ||
| t.Errorf("Authorization = %q, want %q", got, "Bearer test-token") | ||
| } | ||
| if got := gotHeaders.Get("X-STS-Test"); got != "" { | ||
| t.Errorf("X-STS-Test should be absent, got %q", got) | ||
| } | ||
| } | ||
|
|
||
| func TestDoAPIRequest_WithAdditionalHeaders(t *testing.T) { | ||
| setAdditionalHeaders(t, map[string]string{"X-STS-Test": "1"}) | ||
| srv, gotHeaders := startBackendTestServer(t, true) | ||
| doTestAPIRequest(t, srv) | ||
|
|
||
| if got := gotHeaders.Get("Authorization"); got != "Bearer test-token" { | ||
| t.Errorf("Authorization = %q, want %q", got, "Bearer test-token") | ||
| } | ||
| if got := gotHeaders.Get("X-STS-Test"); got != "1" { | ||
| t.Errorf("X-STS-Test = %q, want %q", got, "1") | ||
| } | ||
| } | ||
|
|
||
| func TestDoAPIRequest_HeadersScopedToBackendHost(t *testing.T) { | ||
| setAdditionalHeaders(t, map[string]string{"X-STS-Test": "1"}) | ||
| srv, gotHeaders := startBackendTestServer(t, false) | ||
| doTestAPIRequest(t, srv) | ||
|
|
||
| if got := gotHeaders.Get("X-STS-Test"); got != "" { | ||
| t.Errorf("X-STS-Test should not be sent to non-backend host, got %q", got) | ||
| } | ||
| } | ||
|
|
||
| func TestDoAPIRequest_InvalidHeaderValueDoesNotBreakRequests(t *testing.T) { | ||
| setAdditionalHeaders(t, map[string]string{"X-STS-Bad": "a\nb", "X-STS-Ok": "1"}) | ||
| srv, gotHeaders := startBackendTestServer(t, true) | ||
| doTestAPIRequest(t, srv) | ||
|
|
||
| if got := gotHeaders.Get("X-STS-Bad"); got != "" { | ||
| t.Errorf("X-STS-Bad should have been dropped, got %q", got) | ||
| } | ||
| if got := gotHeaders.Get("X-STS-Ok"); got != "1" { | ||
| t.Errorf("X-STS-Ok = %q, want %q", got, "1") | ||
| } | ||
| } |
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 |
|---|---|---|
|
|
@@ -5,9 +5,11 @@ import ( | |
| "errors" | ||
| "fmt" | ||
| "io/fs" | ||
| "net/textproto" | ||
| "net/url" | ||
| "os" | ||
| "path/filepath" | ||
| "sort" | ||
| "strings" | ||
| "time" | ||
| ) | ||
|
|
@@ -23,6 +25,7 @@ const ( | |
| EnvVarClientID = "SAVE_TO_SPOTIFY_CLIENT_ID" | ||
| EnvVarNoUpdateCheck = "SAVE_TO_SPOTIFY_NO_UPDATE_CHECK" | ||
| EnvVarReleasesAPIURL = "SAVE_TO_SPOTIFY_RELEASES_API_URL" | ||
| EnvVarHeaders = "SAVE_TO_SPOTIFY_HEADERS" | ||
|
|
||
| Scopes = "sts-content-management" | ||
|
|
||
|
|
@@ -285,3 +288,97 @@ func GetClientID() string { | |
| } | ||
| return ClientID | ||
| } | ||
|
|
||
| // additionalHeaderPrefix is the canonical MIME form of the required "X-STS-" | ||
| // header prefix. Keys are canonicalized before the prefix check, so any casing | ||
| // of X-STS-* is accepted. | ||
| const additionalHeaderPrefix = "X-Sts-" | ||
|
|
||
| var additionalHeaders = parseAdditionalHeaders() | ||
|
|
||
| // AdditionalHeaders returns extra HTTP headers to send on backend API requests. | ||
| // Parsed from SAVE_TO_SPOTIFY_HEADERS, a JSON object of header name/value | ||
| // pairs. Keys are in canonical MIME form. Only X-STS-* headers (any casing) | ||
| // with valid HTTP header names and values are accepted; others are silently | ||
| // dropped. | ||
| func AdditionalHeaders() map[string]string { return additionalHeaders } | ||
|
|
||
| // SetAdditionalHeaders replaces the additional backend headers, applying the | ||
| // same X-STS-* validation as env parsing. Used in tests. | ||
| func SetAdditionalHeaders(h map[string]string) { additionalHeaders = filterAdditionalHeaders(h) } | ||
|
|
||
| func parseAdditionalHeaders() map[string]string { | ||
| raw := os.Getenv(EnvVarHeaders) | ||
| if raw == "" { | ||
| return nil | ||
| } | ||
|
|
||
| var entries map[string]string | ||
| if err := json.Unmarshal([]byte(raw), &entries); err != nil { | ||
| fmt.Fprintf(os.Stderr, "Warning: %s contains invalid JSON, ignoring: %v\n", EnvVarHeaders, err) | ||
| return nil | ||
| } | ||
| return filterAdditionalHeaders(entries) | ||
| } | ||
|
|
||
| // filterAdditionalHeaders canonicalizes keys and keeps only valid X-STS-* | ||
| // headers. Keys are visited in sorted order so two spellings of the same | ||
| // header collapse deterministically. | ||
| func filterAdditionalHeaders(in map[string]string) map[string]string { | ||
| keys := make([]string, 0, len(in)) | ||
| for k := range in { | ||
| keys = append(keys, k) | ||
| } | ||
| sort.Strings(keys) | ||
|
|
||
| headers := make(map[string]string) | ||
| for _, k := range keys { | ||
| key := textproto.CanonicalMIMEHeaderKey(strings.TrimSpace(k)) | ||
| val := strings.TrimSpace(in[k]) | ||
| if val == "" || !strings.HasPrefix(key, additionalHeaderPrefix) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The X-STS-* prefix check is critical, without it a value like {"Authorization": "Bearer ..."} in SAVE_TO_SPOTIFY_HEADERS would silently overwrite the CLI's own auth header, since the transport runs after doAPIRequest sets Authorization. |
||
| continue | ||
| } | ||
| if !isValidHeaderName(key) || !isValidHeaderValue(val) { | ||
| continue | ||
| } | ||
| headers[key] = val | ||
| } | ||
| if len(headers) == 0 { | ||
| return nil | ||
| } | ||
| return headers | ||
| } | ||
|
|
||
| // isValidHeaderName reports whether s is a valid RFC 7230 header field name | ||
| // (a token). CanonicalMIMEHeaderKey returns invalid names unchanged, so names | ||
| // it could not canonicalize are rejected here. | ||
| func isValidHeaderName(s string) bool { | ||
| if s == "" { | ||
| return false | ||
| } | ||
| for i := 0; i < len(s); i++ { | ||
| c := s[i] | ||
| switch { | ||
| case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9': | ||
| case c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' || | ||
| c == '*' || c == '+' || c == '-' || c == '.' || c == '^' || c == '_' || | ||
| c == '`' || c == '|' || c == '~': | ||
| default: | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } | ||
|
|
||
| // isValidHeaderValue reports whether s is a valid RFC 7230 header field value: | ||
| // no control characters other than horizontal tab. A value that fails this | ||
| // check would make net/http reject every request it is attached to. | ||
| func isValidHeaderValue(s string) bool { | ||
| for i := 0; i < len(s); i++ { | ||
| c := s[i] | ||
| if (c < 0x20 && c != '\t') || c == 0x7f { | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } | ||
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.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this would happen when the SAVE_TO_SPOTIFY_HEADERS var is set but contains invalid json, would be good to log when that happens
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good call — added a warning to stderr when the JSON is malformed:
Warning: SAVE_TO_SPOTIFY_HEADERS contains invalid JSON, ignoring: <err>