package api import ( "context" "crypto/sha256" "errors" "fmt" "io" "net" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "strings" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/zalando/go-keyring" gitlab "gitlab.com/gitlab-org/api/client-go/v3" "gitlab.com/gitlab-org/cli/internal/config" ) type roundTripFunc func(*http.Request) (*http.Response, error) func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } func TestBuildInfoUserAgent(t *testing.T) { tests := []struct { name string buildInfo BuildInfo expectedUA string }{ { name: "without coding agent", buildInfo: BuildInfo{ Version: "1.50.0", Platform: "linux", Architecture: "amd64", }, expectedUA: "glab/1.50.0 (linux, amd64)", }, { name: "with coding agent", buildInfo: BuildInfo{ Version: "1.50.0", Platform: "darwin", Architecture: "arm64", CodingAgent: "claude-code", }, expectedUA: "glab/1.50.0 (darwin, arm64) Coding-Agent/claude-code", }, { name: "empty coding agent omits suffix", buildInfo: BuildInfo{ Version: "DEV", Platform: "windows", Architecture: "amd64", CodingAgent: "", }, expectedUA: "glab/DEV (windows, amd64)", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.expectedUA, tt.buildInfo.UserAgent()) }) } } func TestNewClientFromConfig(t *testing.T) { t.Setenv("GITLAB_TOKEN", "") t.Setenv("GITLAB_ACCESS_TOKEN", "") t.Setenv("OAUTH_TOKEN", "") t.Setenv("GLAB_IS_OAUTH2", "") t.Setenv("JOB_TOKEN", "") t.Setenv("CI_JOB_TOKEN", "") t.Setenv("GITLAB_CI", "") t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "") t.Setenv("CI_SERVER_FQDN", "") t.Setenv("CI_SERVER_PROTOCOL", "") t.Setenv("GITLAB_HOST", "") t.Setenv("GITLAB_API_HOST", "") t.Setenv("API_PROTOCOL", "") tests := []struct { name string envVars map[string]string repoHost string expectedAuthKey string expectedAuthVal string expectedBaseURL string }{ { // GITLAB_HOST makes the passed-in host the default host, for // which environment credentials resolve. name: "OAuth2 access token", envVars: map[string]string{ "GITLAB_TOKEN": "oauth2-access-token", "GLAB_IS_OAUTH2": "true", "GITLAB_HOST": "example.com", }, repoHost: "example.com", expectedAuthKey: "Authorization", expectedAuthVal: "Bearer oauth2-access-token", expectedBaseURL: "https://example.com/api/v4/", }, { name: "PAT auth", envVars: map[string]string{ "GITLAB_TOKEN": "some-pat", "GITLAB_HOST": "example.com", }, repoHost: "example.com", expectedAuthKey: gitlab.AccessTokenHeaderName, expectedAuthVal: "some-pat", expectedBaseURL: "https://example.com/api/v4/", }, { name: "job token from env without CI", envVars: map[string]string{ "JOB_TOKEN": "my-job-token", "GITLAB_HOST": "example.com", }, repoHost: "example.com", expectedAuthKey: gitlab.JobTokenHeaderName, expectedAuthVal: "my-job-token", expectedBaseURL: "https://example.com/api/v4/", }, { name: "custom protocol from env", envVars: map[string]string{ "GITLAB_TOKEN": "my-pat", "GITLAB_HOST": "example.com", "API_PROTOCOL": "http", }, repoHost: "example.com", expectedAuthKey: gitlab.AccessTokenHeaderName, expectedAuthVal: "my-pat", expectedBaseURL: "http://example.com/api/v4/", }, { // Under CI auto-login the CI server is the default host, so // environment credentials resolve for it. name: "CI auto-login uses CI variables", envVars: map[string]string{ "GLAB_ENABLE_CI_AUTOLOGIN": "true", "GITLAB_CI": "true", "CI_JOB_TOKEN": "ci-tok", "CI_SERVER_FQDN": "ci.example.com", }, repoHost: "ci.example.com", expectedAuthKey: gitlab.JobTokenHeaderName, expectedAuthVal: "ci-tok", expectedBaseURL: "https://ci.example.com/api/v4/", }, { name: "CI auto-login with custom protocol", envVars: map[string]string{ "GLAB_ENABLE_CI_AUTOLOGIN": "true", "GITLAB_CI": "true", "CI_JOB_TOKEN": "ci-tok", "CI_SERVER_FQDN": "ci.example.com", "CI_SERVER_PROTOCOL": "http", }, repoHost: "ci.example.com", expectedAuthKey: gitlab.JobTokenHeaderName, expectedAuthVal: "ci-tok", expectedBaseURL: "http://ci.example.com/api/v4/", }, { name: "CI auto-login PAT takes precedence over job token", envVars: map[string]string{ "GLAB_ENABLE_CI_AUTOLOGIN": "true", "GITLAB_CI": "true", "GITLAB_TOKEN": "my-pat", "CI_JOB_TOKEN": "ci-tok", "CI_SERVER_FQDN": "ci.example.com", }, repoHost: "ci.example.com", expectedAuthKey: gitlab.AccessTokenHeaderName, expectedAuthVal: "my-pat", expectedBaseURL: "https://ci.example.com/api/v4/", }, { name: "CI auto-login disabled falls back to PAT and passed-in host", envVars: map[string]string{ "GITLAB_CI": "true", "GLAB_ENABLE_CI_AUTOLOGIN": "false", "GITLAB_TOKEN": "my-pat", "GITLAB_HOST": "manual.example.com", "CI_JOB_TOKEN": "ci-tok", "CI_SERVER_FQDN": "ci.example.com", }, repoHost: "manual.example.com", expectedAuthKey: gitlab.AccessTokenHeaderName, expectedAuthVal: "my-pat", expectedBaseURL: "https://manual.example.com/api/v4/", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for k, v := range tt.envVars { t.Setenv(k, v) } client, err := NewClientFromConfig( tt.repoHost, config.NewBlankConfig(), false, "test-agent", ) require.NoError(t, err) key, value, err := client.AuthSource().Header(t.Context()) require.NoError(t, err) assert.Equal(t, tt.expectedAuthKey, key) assert.Equal(t, tt.expectedAuthVal, value) assert.Equal(t, tt.expectedBaseURL, client.BaseURL()) }) } } // TestNewClientFromConfig_EnvTokenScopedToTrustedHosts pins the fix for // https://gitlab.com/gitlab-org/cli/-/work_items/8545: a token from the // environment is never sent to a host named only in a command argument. func TestNewClientFromConfig_EnvTokenScopedToTrustedHosts(t *testing.T) { for _, k := range []string{ "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN", "GLAB_IS_OAUTH2", "JOB_TOKEN", "CI_JOB_TOKEN", "GITLAB_CI", "GLAB_ENABLE_CI_AUTOLOGIN", "CI_SERVER_FQDN", "GITLAB_HOST", "GITLAB_API_HOST", "API_PROTOCOL", } { t.Setenv(k, "") } t.Setenv("GITLAB_TOKEN", "env-pat") assertAuthHeader := func(t *testing.T, client *Client, expectedValue string) { t.Helper() _, value, err := client.AuthSource().Header(t.Context()) require.NoError(t, err) assert.Equal(t, expectedValue, value) } t.Run("withheld from a host that is neither default nor configured", func(t *testing.T) { client, err := NewClientFromConfig("attacker.example.com", config.NewBlankConfig(), false, "test-agent") require.NoError(t, err) // No credential must be attached: the client is unauthenticated. _, _, err = client.AuthSource().Header(t.Context()) require.ErrorContains(t, err, "unauthenticated") }) t.Run("sent to the default host", func(t *testing.T) { client, err := NewClientFromConfig("gitlab.com", config.NewBlankConfig(), false, "test-agent") require.NoError(t, err) assertAuthHeader(t, client, "env-pat") }) t.Run("sent to the default host named by GITLAB_HOST", func(t *testing.T) { t.Setenv("GITLAB_HOST", "gitlab.example.com") client, err := NewClientFromConfig("gitlab.example.com", config.NewBlankConfig(), false, "test-agent") require.NoError(t, err) assertAuthHeader(t, client, "env-pat") }) t.Run("sent to the default host named by GITLAB_HOST with a subfolder", func(t *testing.T) { t.Setenv("GITLAB_HOST", "https://gitlab.example.com/gitlab") client, err := NewClientFromConfig("gitlab.example.com/gitlab", config.NewBlankConfig(), false, "test-agent") require.NoError(t, err) assertAuthHeader(t, client, "env-pat") }) t.Run("sent to a configured host", func(t *testing.T) { cfg := config.NewFromString("hosts:\n gitlab.example.com:\n user: someone\n") client, err := NewClientFromConfig("gitlab.example.com", cfg, false, "test-agent") require.NoError(t, err) assertAuthHeader(t, client, "env-pat") }) } func TestNewClientFromConfig_AuthContextPrecedence(t *testing.T) { tests := []struct { name string envVars map[string]string expectedAuthKey string expectedAuthValue string expectedRefreshes int64 expectConfigUnchanged bool }{ { name: "GITLAB_TOKEN PAT overrides stored OAuth", envVars: map[string]string{"GITLAB_TOKEN": "env-pat"}, expectedAuthKey: gitlab.AccessTokenHeaderName, expectedAuthValue: "env-pat", expectConfigUnchanged: true, }, { name: "GITLAB_ACCESS_TOKEN PAT overrides stored OAuth", envVars: map[string]string{"GITLAB_ACCESS_TOKEN": "env-pat"}, expectedAuthKey: gitlab.AccessTokenHeaderName, expectedAuthValue: "env-pat", expectConfigUnchanged: true, }, { name: "OAUTH_TOKEN preserves stored OAuth context", envVars: map[string]string{"OAUTH_TOKEN": "environment-oauth-token"}, expectedAuthKey: "Authorization", expectedAuthValue: "Bearer refreshed-access-token", expectedRefreshes: 1, }, { name: "stored OAuth is preserved without an override", expectedAuthKey: "Authorization", expectedAuthValue: "Bearer refreshed-access-token", expectedRefreshes: 1, }, { name: "explicit environment OAuth is preserved", envVars: map[string]string{ "GITLAB_TOKEN": "environment-oauth-token", "GLAB_IS_OAUTH2": "true", }, expectedAuthKey: "Authorization", expectedAuthValue: "Bearer refreshed-access-token", expectedRefreshes: 1, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Setenv("GITLAB_TOKEN", "") t.Setenv("GITLAB_ACCESS_TOKEN", "") t.Setenv("OAUTH_TOKEN", "") t.Setenv("GLAB_IS_OAUTH2", "") for key, value := range tt.envVars { t.Setenv(key, value) } var refreshRequests atomic.Int64 server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { refreshRequests.Add(1) w.Header().Set("Content-Type", "application/json") _, _ = io.WriteString(w, `{"access_token":"refreshed-access-token","token_type":"Bearer","refresh_token":"refreshed-refresh-token","expires_in":3600}`) })) t.Cleanup(server.Close) hostname := strings.TrimPrefix(server.URL, "https://") configDir := t.TempDir() cfg := config.NewBlankConfigInDir(configDir) require.NoError(t, cfg.Set(hostname, "api_host", hostname)) require.NoError(t, cfg.Set(hostname, "client_id", "test-client-id")) require.NoError(t, cfg.Set(hostname, "skip_tls_verify", "true")) require.NoError(t, cfg.Set(hostname, "is_oauth2", "true")) require.NoError(t, cfg.Set(hostname, "token", "stored-oauth-token")) require.NoError(t, cfg.Set(hostname, "oauth2_refresh_token", "stored-refresh-token")) require.NoError(t, cfg.Set(hostname, "oauth2_expiry_date", time.Now().Add(-time.Hour).Format(time.RFC3339))) require.NoError(t, cfg.Write()) configPath := filepath.Join(configDir, "config.yml") configBefore, err := os.ReadFile(configPath) require.NoError(t, err) client, err := NewClientFromConfig(hostname, cfg, false, "test-agent") require.NoError(t, err) key, value, err := client.AuthSource().Header(t.Context()) require.NoError(t, err) assert.Equal(t, tt.expectedAuthKey, key) assert.Equal(t, tt.expectedAuthValue, value) assert.Equal(t, tt.expectedRefreshes, refreshRequests.Load()) configAfter, err := os.ReadFile(configPath) require.NoError(t, err) if tt.expectConfigUnchanged { assert.Equal(t, sha256.Sum256(configBefore), sha256.Sum256(configAfter)) } else { assert.NotEqual(t, sha256.Sum256(configBefore), sha256.Sum256(configAfter)) } }) } } func TestNewClientFromConfig_DuoWorkflowID(t *testing.T) { t.Setenv("GITLAB_TOKEN", "test-pat") t.Setenv("DUO_WORKFLOW_WORKFLOW_ID", "") receivedHeaders := make(chan string, 4) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { receivedHeaders <- req.Header.Get("X-Gitlab-Duo-Workflow-Id") w.WriteHeader(http.StatusNoContent) })) t.Cleanup(server.Close) hostname := strings.TrimPrefix(server.URL, "http://") baseURL, err := url.Parse(server.URL + "/api") require.NoError(t, err) newConfig := func(customHeaderValue string) config.Config { configYAML := fmt.Sprintf("hosts:\n %q:\n api_protocol: http\n", hostname) if customHeaderValue != "" { configYAML += fmt.Sprintf(" custom_headers:\n - name: X-Gitlab-Duo-Workflow-Id\n value: %q\n", customHeaderValue) } return config.NewFromString(configYAML) } sentDuoWorkflowIDHeader := func(t *testing.T, client *Client, req *http.Request) string { t.Helper() resp, err := client.httpClient.Do(req) require.NoError(t, err) require.NoError(t, resp.Body.Close()) return <-receivedHeaders } t.Run("header injected when env var is set", func(t *testing.T) { t.Setenv("DUO_WORKFLOW_WORKFLOW_ID", "workflow-id-xyz") client, err := NewClientFromConfig(hostname, newConfig(""), false, "test-agent") require.NoError(t, err) req, err := NewHTTPRequest(t.Context(), client, "GET", baseURL, nil, []string{}, false) require.NoError(t, err) assert.Equal(t, "workflow-id-xyz", sentDuoWorkflowIDHeader(t, client, req)) }) t.Run("no header when env var is empty", func(t *testing.T) { t.Setenv("DUO_WORKFLOW_WORKFLOW_ID", "") client, err := NewClientFromConfig(hostname, newConfig(""), false, "test-agent") require.NoError(t, err) req, err := NewHTTPRequest(t.Context(), client, "GET", baseURL, nil, []string{}, false) require.NoError(t, err) assert.Empty(t, sentDuoWorkflowIDHeader(t, client, req)) }) t.Run("env var overrides X-Gitlab-Duo-Workflow-Id from config headers", func(t *testing.T) { t.Setenv("DUO_WORKFLOW_WORKFLOW_ID", "from-env") client, err := NewClientFromConfig(hostname, newConfig("from-config"), false, "test-agent") require.NoError(t, err) req, err := NewHTTPRequest(t.Context(), client, "GET", baseURL, nil, []string{}, false) require.NoError(t, err) assert.Equal(t, "from-env", sentDuoWorkflowIDHeader(t, client, req)) }) t.Run("malformed workflow ID is ignored", func(t *testing.T) { t.Setenv("DUO_WORKFLOW_WORKFLOW_ID", "workflow\r\nid") client, err := NewClientFromConfig(hostname, newConfig(""), false, "test-agent") require.NoError(t, err) req, err := NewHTTPRequest(t.Context(), client, "GET", baseURL, nil, []string{}, false) require.NoError(t, err) assert.Empty(t, sentDuoWorkflowIDHeader(t, client, req)) }) } func TestNewClientFromConfig_OAuth2NoTokenReturnsError(t *testing.T) { t.Setenv("GITLAB_TOKEN", "") t.Setenv("GLAB_IS_OAUTH2", "true") // Environment credentials and flags only resolve for trusted hosts; make // the host the default one so GLAB_IS_OAUTH2 applies. t.Setenv("GITLAB_HOST", "example.gitlab.com") _, err := NewClientFromConfig( "example.gitlab.com", config.NewBlankConfig(), false, "dummy user agent", ) require.ErrorIs(t, err, ErrUnauthenticated) // The message should be actionable rather than the old low-level jargon. assert.EqualError(t, err, "OAuth2 authentication is configured for \"example.gitlab.com\" but no access or refresh token was found (the stored credentials may be missing or incomplete); run `glab auth login --hostname example.gitlab.com` to re-authenticate") } func TestNewClientFromConfig_SurfacesKeyringReadError(t *testing.T) { t.Setenv("GITLAB_TOKEN", "") keyring.MockInitWithError(errors.New("keyring locked")) t.Cleanup(keyring.MockInit) cfg := config.NewBlankConfig() require.NoError(t, cfg.Set("example.gitlab.com", "use_keyring", "true")) // A failed keyring read must surface as a clear error rather than being // silently treated as an absent (empty) credential. _, err := NewClientFromConfig("example.gitlab.com", cfg, false, "dummy user agent") require.Error(t, err) assert.Contains(t, err.Error(), "keyring") } func TestNewClientFromConfig_KeyringTokenMissing(t *testing.T) { keyring.MockInit() t.Cleanup(keyring.MockInit) t.Setenv("GITLAB_TOKEN", "") t.Setenv("GITLAB_ACCESS_TOKEN", "") t.Setenv("OAUTH_TOKEN", "") t.Setenv("GLAB_IS_OAUTH2", "") t.Setenv("JOB_TOKEN", "") t.Setenv("CI_JOB_TOKEN", "") t.Setenv("GITLAB_CI", "") t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "") t.Setenv("GLAB_USE_KEYRING", "") t.Setenv("USE_KEYRING", "") keyringHost := "---\nhosts:\n gitlab.example.com:\n use_keyring: \"true\"\n" t.Run("returns an actionable error", func(t *testing.T) { _, err := NewClientFromConfig("gitlab.example.com", config.NewFromString(keyringHost), false, "test-agent") require.ErrorIs(t, err, ErrUnauthenticated) assert.Contains(t, err.Error(), "keyring") assert.Contains(t, err.Error(), "re-authenticate") assert.Contains(t, err.Error(), "glab auth login --hostname gitlab.example.com") }) t.Run("a token from the environment still wins", func(t *testing.T) { t.Setenv("GITLAB_TOKEN", "env-pat") client, err := NewClientFromConfig("gitlab.example.com", config.NewFromString(keyringHost), false, "test-agent") require.NoError(t, err) key, value, err := client.AuthSource().Header(t.Context()) require.NoError(t, err) assert.Equal(t, gitlab.AccessTokenHeaderName, key) assert.Equal(t, "env-pat", value) }) t.Run("a job token still authenticates", func(t *testing.T) { t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "true") t.Setenv("GITLAB_CI", "true") t.Setenv("CI_JOB_TOKEN", "env-job-token") client, err := NewClientFromConfig("gitlab.example.com", config.NewFromString(keyringHost), false, "test-agent") require.NoError(t, err) key, value, err := client.AuthSource().Header(t.Context()) require.NoError(t, err) assert.Equal(t, gitlab.JobTokenHeaderName, key) assert.Equal(t, "env-job-token", value) }) t.Run("a host without use_keyring stays unauthenticated", func(t *testing.T) { cfg := config.NewFromString("---\nhosts:\n gitlab.example.com:\n user: someone\n") client, err := NewClientFromConfig("gitlab.example.com", cfg, false, "test-agent") require.NoError(t, err) _, _, err = client.AuthSource().Header(t.Context()) require.ErrorContains(t, err, "unauthenticated") }) // The keyring is only read when the host itself sets use_keyring, so // GLAB_USE_KEYRING alone must not turn a tokenless host into an error. t.Run("GLAB_USE_KEYRING does not apply to a host without use_keyring", func(t *testing.T) { t.Setenv("GLAB_USE_KEYRING", "true") cfg := config.NewFromString("---\nhosts:\n gitlab.example.com:\n user: someone\n") client, err := NewClientFromConfig("gitlab.example.com", cfg, false, "test-agent") require.NoError(t, err) _, _, err = client.AuthSource().Header(t.Context()) require.ErrorContains(t, err, "unauthenticated") }) t.Run("a top-level use_keyring does not apply to a host without use_keyring", func(t *testing.T) { cfg := config.NewFromString("---\nuse_keyring: \"true\"\nhosts:\n gitlab.example.com:\n user: someone\n") client, err := NewClientFromConfig("gitlab.example.com", cfg, false, "test-agent") require.NoError(t, err) _, _, err = client.AuthSource().Header(t.Context()) require.ErrorContains(t, err, "unauthenticated") }) t.Run("a top-level use_keyring keeps the token from the host entry", func(t *testing.T) { cfg := config.NewFromString("---\nuse_keyring: \"true\"\nhosts:\n gitlab.example.com:\n token: config-pat\n") client, err := NewClientFromConfig("gitlab.example.com", cfg, false, "test-agent") require.NoError(t, err) key, value, err := client.AuthSource().Header(t.Context()) require.NoError(t, err) assert.Equal(t, gitlab.AccessTokenHeaderName, key) assert.Equal(t, "config-pat", value) }) } func TestNewClientFromConfig_WithoutAuthentication(t *testing.T) { keyring.MockInit() t.Cleanup(keyring.MockInit) t.Setenv("GITLAB_TOKEN", "") t.Setenv("GITLAB_ACCESS_TOKEN", "") t.Setenv("OAUTH_TOKEN", "") t.Setenv("GLAB_IS_OAUTH2", "") t.Setenv("JOB_TOKEN", "") t.Setenv("CI_JOB_TOKEN", "") t.Setenv("GITLAB_CI", "") t.Setenv("GLAB_USE_KEYRING", "") t.Setenv("USE_KEYRING", "") var gotHeader string server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotHeader = r.Header.Get("X-Test-Header") w.WriteHeader(http.StatusOK) })) t.Cleanup(server.Close) hostname := strings.TrimPrefix(server.URL, "https://") cfg := config.NewFromString(fmt.Sprintf(` --- hosts: %s: use_keyring: "true" is_oauth2: "true" skip_tls_verify: "true" custom_headers: - name: X-Test-Header value: from-config `, hostname)) client, err := NewClientFromConfig(hostname, cfg, false, "test-agent", WithoutAuthentication()) require.NoError(t, err) _, _, err = client.AuthSource().Header(t.Context()) require.ErrorContains(t, err, "unauthenticated") req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, server.URL, http.NoBody) require.NoError(t, err) resp, err := client.HTTPClient().Do(req) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, "from-config", gotHeader) } func TestNewClientFromConfig_WithoutAuthenticationSkipsKeyringRead(t *testing.T) { t.Setenv("GITLAB_TOKEN", "") keyring.MockInitWithError(errors.New("keyring locked")) t.Cleanup(keyring.MockInit) cfg := config.NewBlankConfig() require.NoError(t, cfg.Set("example.gitlab.com", "use_keyring", "true")) client, err := NewClientFromConfig("example.gitlab.com", cfg, false, "dummy user agent", WithoutAuthentication()) require.NoError(t, err) _, _, err = client.AuthSource().Header(t.Context()) require.ErrorContains(t, err, "unauthenticated") } // TestNewClientFromConfig_WithoutTokenFromEnvironment pins the option glab // uses when it acts on behalf of a process that inherits the user's shell // environment, such as the Docker credential helper: the environment must // not be able to decide which identity the request is made as. func TestNewClientFromConfig_WithoutTokenFromEnvironment(t *testing.T) { t.Setenv("GITLAB_TOKEN", "env-pat") t.Setenv("GITLAB_ACCESS_TOKEN", "") cfg := config.NewFromString(` --- hosts: gitlab.example.com: token: config-pat `) t.Run("the environment wins by default", func(t *testing.T) { client, err := NewClientFromConfig("gitlab.example.com", cfg, false, "test-agent") require.NoError(t, err) key, value, err := client.AuthSource().Header(t.Context()) require.NoError(t, err) assert.Equal(t, gitlab.AccessTokenHeaderName, key) assert.Equal(t, "env-pat", value) }) t.Run("the option restricts resolution to config", func(t *testing.T) { client, err := NewClientFromConfig("gitlab.example.com", cfg, false, "test-agent", WithoutTokenFromEnvironment()) require.NoError(t, err) key, value, err := client.AuthSource().Header(t.Context()) require.NoError(t, err) assert.Equal(t, gitlab.AccessTokenHeaderName, key) assert.Equal(t, "config-pat", value) }) // A host with no stored credential must not silently fall back to the // environment: an unauthenticated client makes the failure visible // instead of acting as whoever GITLAB_TOKEN names. t.Run("a host without a stored token yields an unauthenticated client", func(t *testing.T) { blank := config.NewFromString("---\nhosts:\n other.example.com:\n user: someone\n") client, err := NewClientFromConfig("other.example.com", blank, false, "test-agent", WithoutTokenFromEnvironment()) require.NoError(t, err) _, _, err = client.AuthSource().Header(t.Context()) require.ErrorContains(t, err, "unauthenticated") }) // A stray GLAB_IS_OAUTH2 must not flip a PAT-configured host onto the // OAuth2 auth flow: without this, isOAuth2 would read "true" from the // environment, sending the client down the oauth2AccessTokenOnlyAuthSource // branch (Authorization: Bearer) instead of AccessTokenAuthSource // (PRIVATE-TOKEN), even though the token value itself is correct. t.Run("the option also ignores GLAB_IS_OAUTH2", func(t *testing.T) { t.Setenv("GLAB_IS_OAUTH2", "true") client, err := NewClientFromConfig("gitlab.example.com", cfg, false, "test-agent", WithoutTokenFromEnvironment()) require.NoError(t, err) key, value, err := client.AuthSource().Header(t.Context()) require.NoError(t, err) assert.Equal(t, gitlab.AccessTokenHeaderName, key) assert.Equal(t, "config-pat", value) }) // job_token is deliberately excluded from the option: CI_JOB_TOKEN // authentication must keep working under CI auto-login regardless of // whether the caller asked to ignore the environment for the identity // (token/is_oauth2) lookups. t.Run("the option does not affect job_token", func(t *testing.T) { t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "true") t.Setenv("GITLAB_CI", "true") t.Setenv("CI_JOB_TOKEN", "env-job-token") blank := config.NewFromString("---\nhosts:\n other.example.com:\n user: someone\n") client, err := NewClientFromConfig("other.example.com", blank, false, "test-agent", WithoutTokenFromEnvironment()) require.NoError(t, err) key, value, err := client.AuthSource().Header(t.Context()) require.NoError(t, err) assert.Equal(t, gitlab.JobTokenHeaderName, key) assert.Equal(t, "env-job-token", value) }) } // The access-token-only path has no refresh token, so the stored expiry is the // only expiry anything downstream can report. func TestNewClientFromConfig_AccessTokenOnlyCarriesStoredExpiry(t *testing.T) { tests := []struct { name string expiryLine string expectedExpiry time.Time }{ { name: "RFC3339", expiryLine: ` oauth2_expiry_date: "2099-01-02T03:04:05Z"`, expectedExpiry: time.Date(2099, time.January, 2, 3, 4, 5, 0, time.UTC), }, { name: "absent", expiryLine: "", expectedExpiry: time.Time{}, }, { name: "unparseable is ignored rather than fatal", expiryLine: ` oauth2_expiry_date: "not-a-date"`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for _, k := range []string{"GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN", "GLAB_IS_OAUTH2"} { t.Setenv(k, "") } cfg := config.NewFromString("hosts:\n example.com:\n is_oauth2: \"true\"\n token: an-access-token\n" + tt.expiryLine + "\n") client, err := NewClientFromConfig("example.com", cfg, false, "ua") require.NoError(t, err) cred, err := client.Credential(t.Context()) require.NoError(t, err) assert.Equal(t, CredentialOAuth2, cred.Kind) assert.Equal(t, "an-access-token", cred.Token) assert.True(t, tt.expectedExpiry.Equal(cred.Expiry), "want %s, got %s", tt.expectedExpiry, cred.Expiry) assert.Empty(t, cred.RefreshToken, "there is no refresh token in this path") }) } } // forget() leaves is_oauth2 and a lapsed oauth2_expiry_date behind. A fresh // token from the environment must not be judged against that stale date. func TestNewClientFromConfig_EnvTokenIgnoresStoredExpiry(t *testing.T) { for _, k := range []string{"GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN", "GLAB_IS_OAUTH2"} { t.Setenv(k, "") } t.Setenv("OAUTH_TOKEN", "env-access-token") cfg := config.NewFromString("hosts:\n example.com:\n is_oauth2: \"true\"\n oauth2_expiry_date: \"2000-01-02T03:04:05Z\"\n") client, err := NewClientFromConfig("example.com", cfg, false, "ua") require.NoError(t, err) key, value, err := client.AuthSource().Header(t.Context()) require.NoError(t, err) assert.Equal(t, gitlab.OAuthTokenHeaderName, key) assert.Equal(t, "Bearer env-access-token", value) cred, err := client.Credential(t.Context()) require.NoError(t, err) assert.Equal(t, "env-access-token", cred.Token) assert.True(t, cred.Expiry.IsZero(), "the stored expiry is not the environment token's") } func TestNewClientFromConfig_DoesNotRetryPostOnServerError(t *testing.T) { t.Setenv("GITLAB_TOKEN", "test-pat") var requests atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { requests.Add(1) w.WriteHeader(http.StatusBadGateway) })) t.Cleanup(server.Close) hostname := strings.TrimPrefix(server.URL, "http://") cfg := config.NewFromString(fmt.Sprintf("hosts:\n %q:\n api_protocol: http\n", hostname)) client, err := NewClientFromConfig(hostname, cfg, false, "test-agent") require.NoError(t, err) _, _, err = client.Lab().Issues.CreateIssue("group/project", &gitlab.CreateIssueOptions{Title: new("title")}) require.Error(t, err) assert.Equal(t, int32(1), requests.Load()) } func TestNewClientFromConfig_RetriesPostOnRateLimit(t *testing.T) { t.Setenv("GITLAB_TOKEN", "test-pat") var requests atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if requests.Add(1) == 1 { w.WriteHeader(http.StatusTooManyRequests) return } w.WriteHeader(http.StatusCreated) _, _ = io.WriteString(w, `{"iid": 1}`) })) t.Cleanup(server.Close) hostname := strings.TrimPrefix(server.URL, "http://") cfg := config.NewFromString(fmt.Sprintf("hosts:\n %q:\n api_protocol: http\n", hostname)) client, err := NewClientFromConfig(hostname, cfg, false, "test-agent") require.NoError(t, err) _, _, err = client.Lab().Issues.CreateIssue("group/project", &gitlab.CreateIssueOptions{Title: new("title")}) require.NoError(t, err) assert.Equal(t, int32(2), requests.Load()) } func TestWithSafeRetries_RetriesPostOnServerError(t *testing.T) { t.Setenv("GITLAB_TOKEN", "test-pat") var requests atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if requests.Add(1) == 1 { w.WriteHeader(http.StatusBadGateway) return } w.WriteHeader(http.StatusCreated) _, _ = io.WriteString(w, `{"iid": 1}`) })) t.Cleanup(server.Close) hostname := strings.TrimPrefix(server.URL, "http://") cfg := config.NewFromString(fmt.Sprintf("hosts:\n %q:\n api_protocol: http\n", hostname)) client, err := NewClientFromConfig(hostname, cfg, false, "test-agent") require.NoError(t, err) _, _, err = client.Lab().Issues.CreateIssue("group/project", &gitlab.CreateIssueOptions{Title: new("title")}, WithSafeRetries()) require.NoError(t, err) assert.Equal(t, int32(2), requests.Load()) } func TestWithSafeRetries_DoesNotRetryUnknownHost(t *testing.T) { var dials atomic.Int32 transport := &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { dials.Add(1) return nil, &net.DNSError{Err: "no such host", Name: "gitlab.invalid", IsNotFound: true} }, } client, err := NewClient( func(*http.Client) (gitlab.AuthSource, error) { return gitlab.Unauthenticated{}, nil }, WithBaseURL("https://gitlab.invalid/api/v4/"), WithHTTPClient(&http.Client{Transport: transport}), ) require.NoError(t, err) _, _, err = client.Lab().Issues.CreateIssue("group/project", &gitlab.CreateIssueOptions{Title: new("title")}, WithSafeRetries()) require.Error(t, err) assert.Equal(t, int32(1), dials.Load()) }