Skip to content

Commit 229df98

Browse files
authored
Merge pull request #94 from thalassa-cloud/fix-missing-ua
fix(tokenexchange): set missing custom user agent in token exchange calls
2 parents 9a892d9 + cd27a13 commit 229df98

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

pkg/client/auth.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,9 @@ func (c *thalassaCloudClient) fetchOIDCTokenExchange(ctx context.Context) (*oaut
250250
return nil, fmt.Errorf("OIDC token exchange: build request: %w", err)
251251
}
252252
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
253+
if ua := strings.TrimSpace(c.userAgent); ua != "" {
254+
httpReq.Header.Set("User-Agent", ua)
255+
}
253256

254257
resp, err := c.tokenExchangeHTTPClient().Do(httpReq)
255258
if err != nil {

pkg/client/client_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,7 @@ func TestOIDCTokenExchangeExchangesAndSetsBearer(t *testing.T) {
276276
case r.URL.Path == "/oidc/token" && r.Method == http.MethodPost:
277277
tokenCalls++
278278
require.Equal(t, "application/x-www-form-urlencoded", r.Header.Get("Content-Type"))
279+
assert.Equal(t, DefaultUserAgent, r.Header.Get("User-Agent"))
279280
require.NoError(t, r.ParseForm())
280281
assert.Equal(t, "urn:ietf:params:oauth:grant-type:token-exchange", r.FormValue("grant_type"))
281282
assert.Equal(t, "gitlab-id-token", r.FormValue("subject_token"))
@@ -367,6 +368,37 @@ func TestOIDCTokenExchangeSubjectTokenFile(t *testing.T) {
367368
assert.Equal(t, "jwt-from-mounted-file", gotSubject)
368369
}
369370

371+
func TestOIDCTokenExchangeUsesCustomUserAgent(t *testing.T) {
372+
const customUA = "my-app/2 token-exchange"
373+
var gotUA string
374+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
375+
if r.URL.Path == "/oidc/token" && r.Method == http.MethodPost {
376+
gotUA = r.Header.Get("User-Agent")
377+
w.Header().Set("Content-Type", "application/json")
378+
w.WriteHeader(http.StatusOK)
379+
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "t", "expires_in": 60})
380+
return
381+
}
382+
w.WriteHeader(http.StatusNotFound)
383+
}))
384+
defer srv.Close()
385+
386+
cl, err := NewClient(
387+
WithBaseURL(srv.URL),
388+
WithUserAgent(customUA),
389+
WithAuthOIDCTokenExchange(OIDCTokenExchangeConfig{
390+
TokenURL: srv.URL + "/oidc/token",
391+
SubjectToken: "jwt",
392+
OrganisationID: "o",
393+
ServiceAccountID: "s",
394+
}),
395+
)
396+
require.NoError(t, err)
397+
_, err = cl.Do(context.Background(), cl.R(), GET, "/any")
398+
require.NoError(t, err)
399+
assert.Equal(t, customUA, gotUA)
400+
}
401+
370402
func TestOIDCTokenExchangeSubjectTokenFilePrecedenceOverString(t *testing.T) {
371403
dir := t.TempDir()
372404
tokenPath := filepath.Join(dir, "idtoken")

0 commit comments

Comments
 (0)