diff --git a/cmd/src/login.go b/cmd/src/login.go index e85a0bd4e9..5a73ef4cc8 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -112,7 +112,9 @@ func loginCmd(ctx context.Context, p loginParams) error { export SRC_ACCESS_TOKEN=(your access token) To verify that it's working, run the login command again. -`, endpointArg, endpointArg) + + Alternatively, you can try logging in using OAuth by running: src login --oauth %s +`, endpointArg, endpointArg, endpointArg) if cfg.ConfigFilePath != "" { fmt.Fprintln(out) @@ -121,6 +123,17 @@ func loginCmd(ctx context.Context, p loginParams) error { noToken := cfg.AccessToken == "" endpointConflict := endpointArg != cfg.Endpoint + if !p.useOAuth && (noToken || endpointConflict) { + fmt.Fprintln(out) + switch { + case noToken: + printProblem("No access token is configured.") + case endpointConflict: + printProblem(fmt.Sprintf("The configured endpoint is %s, not %s.", cfg.Endpoint, endpointArg)) + } + fmt.Fprintln(out, createAccessTokenMessage) + return cmderrors.ExitCode1 + } if p.useOAuth { token, err := runOAuthDeviceFlow(ctx, endpointArg, out, p.deviceFlowClient) @@ -130,19 +143,20 @@ func loginCmd(ctx context.Context, p loginParams) error { return cmderrors.ExitCode1 } - cfg.AccessToken = token - cfg.Endpoint = endpointArg - client = cfg.apiClient(p.apiFlags, out) - } else if noToken || endpointConflict { - fmt.Fprintln(out) - switch { - case noToken: - printProblem("No access token is configured.") - case endpointConflict: - printProblem(fmt.Sprintf("The configured endpoint is %s, not %s.", cfg.Endpoint, endpointArg)) + if err := oauth.StoreToken(ctx, token); err != nil { + fmt.Fprintln(out) + fmt.Fprintf(out, "āš ļø Warning: Failed to store token in keyring store: %q. Continuing with this session only.\n", err) } - fmt.Fprintln(out, createAccessTokenMessage) - return cmderrors.ExitCode1 + + client = api.NewClient(api.ClientOpts{ + Endpoint: cfg.Endpoint, + AdditionalHeaders: cfg.AdditionalHeaders, + Flags: p.apiFlags, + Out: out, + ProxyURL: cfg.ProxyURL, + ProxyPath: cfg.ProxyPath, + OAuthToken: token, + }) } // See if the user is already authenticated. @@ -179,10 +193,10 @@ func loginCmd(ctx context.Context, p loginParams) error { return nil } -func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, client oauth.Client) (string, error) { +func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, client oauth.Client) (*oauth.Token, error) { authResp, err := client.Start(ctx, endpoint, nil) if err != nil { - return "", err + return nil, err } authURL := authResp.VerificationURIComplete @@ -204,12 +218,14 @@ func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, cli interval = 5 * time.Second } - tokenResp, err := client.Poll(ctx, endpoint, authResp.DeviceCode, interval, authResp.ExpiresIn) + resp, err := client.Poll(ctx, endpoint, authResp.DeviceCode, interval, authResp.ExpiresIn) if err != nil { - return "", err + return nil, err } - return tokenResp.AccessToken, nil + token := resp.Token(endpoint) + token.ClientID = client.ClientID() + return token, nil } func openInBrowser(url string) error { diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index ef7d01e019..ab7a15056a 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/sourcegraph/src-cli/internal/oauth" ) func TestLogin(t *testing.T) { @@ -18,7 +19,13 @@ func TestLogin(t *testing.T) { t.Helper() var out bytes.Buffer - err = loginCmd(context.Background(), loginParams{cfg: cfg, client: cfg.apiClient(nil, io.Discard), endpoint: endpointArg, out: &out}) + err = loginCmd(context.Background(), loginParams{ + cfg: cfg, + client: cfg.apiClient(nil, io.Discard), + endpoint: endpointArg, + out: &out, + deviceFlowClient: oauth.NewClient(oauth.DefaultClientID), + }) return strings.TrimSpace(out.String()), err } @@ -27,7 +34,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "āŒ Problem: No access token is configured.\n\nšŸ›  To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again." + wantOut := "āŒ Problem: No access token is configured.\n\nšŸ›  To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth https://sourcegraph.example.com" if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -38,7 +45,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "āŒ Problem: No access token is configured.\n\nšŸ›  To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again." + wantOut := "āŒ Problem: No access token is configured.\n\nšŸ›  To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth https://sourcegraph.example.com" if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -49,7 +56,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "āš ļø Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove f. See https://github.com/sourcegraph/src-cli#readme for more information.\n\nāŒ Problem: No access token is configured.\n\nšŸ›  To fix: Create an access token by going to https://example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again." + wantOut := "āš ļø Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove f. See https://github.com/sourcegraph/src-cli#readme for more information.\n\nāŒ Problem: No access token is configured.\n\nšŸ›  To fix: Create an access token by going to https://example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth https://example.com" if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -67,7 +74,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "āŒ Problem: Invalid access token.\n\nšŸ›  To fix: Create an access token by going to $ENDPOINT/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=$ENDPOINT\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)" + wantOut := "āŒ Problem: Invalid access token.\n\nšŸ›  To fix: Create an access token by going to $ENDPOINT/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=$ENDPOINT\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth $ENDPOINT\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)" wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", endpoint) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) diff --git a/cmd/src/main.go b/cmd/src/main.go index edfb1073d7..41e5c55cd0 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/json" "flag" "io" @@ -15,6 +16,7 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/oauth" ) const usageText = `src is a tool that provides access to Sourcegraph instances. @@ -122,7 +124,7 @@ type config struct { // apiClient returns an api.Client built from the configuration. func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { - return api.NewClient(api.ClientOpts{ + opts := api.ClientOpts{ Endpoint: c.Endpoint, AccessToken: c.AccessToken, AdditionalHeaders: c.AdditionalHeaders, @@ -130,7 +132,16 @@ func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { Out: out, ProxyURL: c.ProxyURL, ProxyPath: c.ProxyPath, - }) + } + + // Only use OAuth if we do not have SRC_ACCESS_TOKEN set + if c.AccessToken == "" { + if t, err := oauth.LoadToken(context.Background(), c.Endpoint); err == nil { + opts.OAuthToken = t + } + } + + return api.NewClient(opts) } // readConfig reads the config file from the given path. diff --git a/go.mod b/go.mod index 3c9e3eb338..0a04972e5a 100644 --- a/go.mod +++ b/go.mod @@ -30,6 +30,7 @@ require ( github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.11.1 github.com/tliron/glsp v0.2.2 + github.com/zalando/go-keyring v0.2.6 golang.org/x/sync v0.18.0 google.golang.org/api v0.256.0 google.golang.org/protobuf v1.36.10 @@ -41,6 +42,7 @@ require ( ) require ( + al.essio.dev/pkg/shellescape v1.5.1 // indirect cel.dev/expr v0.24.0 // indirect cloud.google.com/go/auth v0.17.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect @@ -64,6 +66,7 @@ require ( github.com/clipperhouse/uax29/v2 v2.2.0 // indirect github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443 // indirect github.com/containerd/stargz-snapshotter/estargz v0.14.3 // indirect + github.com/danieljoos/wincred v1.2.2 // indirect github.com/distribution/reference v0.6.0 // indirect github.com/docker/cli v24.0.4+incompatible // indirect github.com/docker/distribution v2.8.2+incompatible // indirect @@ -78,6 +81,7 @@ require ( github.com/go-chi/chi/v5 v5.2.2 // indirect github.com/go-jose/go-jose/v4 v4.1.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect github.com/gofrs/uuid/v5 v5.0.0 // indirect github.com/google/gnostic-models v0.6.9 // indirect github.com/google/go-containerregistry v0.19.1 // indirect diff --git a/go.sum b/go.sum index f47d1d10c9..6cbdc71412 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +al.essio.dev/pkg/shellescape v1.5.1 h1:86HrALUujYS/h+GtqoB26SBEdkWfmMI6FubjXlsXyho= +al.essio.dev/pkg/shellescape v1.5.1/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890= cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY= cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw= cloud.google.com/go v0.120.0 h1:wc6bgG9DHyKqF5/vQvX1CiZrtHnxJjBlKUyF9nP6meA= @@ -139,6 +141,8 @@ github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglD github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= +github.com/danieljoos/wincred v1.2.2 h1:774zMFJrqaeYCK2W57BgAem/MLi6mtSE47MB6BOJ0i0= +github.com/danieljoos/wincred v1.2.2/go.mod h1:w7w4Utbrz8lqeMbDAK0lkNJUv5sAOkFi7nd/ogr0Uh8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -212,6 +216,8 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M= @@ -243,6 +249,8 @@ github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgY github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ= @@ -495,6 +503,8 @@ github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk= github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= +github.com/zalando/go-keyring v0.2.6 h1:r7Yc3+H+Ux0+M72zacZoItR3UDxeWfKTcabvkI8ua9s= +github.com/zalando/go-keyring v0.2.6/go.mod h1:2TCrxYrbUNYfNS/Kgy/LSrkSQzZ5UPVH85RwfczwvcI= github.com/zeebo/errs v1.4.0 h1:XNdoD/RRMKP7HD0UhJnIzUy74ISdGGxURlYG8HSWSfM= github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= diff --git a/internal/api/api.go b/internal/api/api.go index 5f750c1d4a..ef9f822a7a 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -18,6 +18,7 @@ import ( "github.com/kballard/go-shellquote" "github.com/mattn/go-isatty" + "github.com/sourcegraph/src-cli/internal/oauth" "github.com/sourcegraph/src-cli/internal/version" ) @@ -85,21 +86,35 @@ type ClientOpts struct { ProxyURL *url.URL ProxyPath string + + OAuthToken *oauth.Token } -func buildTransport(opts ClientOpts, flags *Flags) *http.Transport { - transport := http.DefaultTransport.(*http.Transport).Clone() +func buildTransport(opts ClientOpts, flags *Flags) http.RoundTripper { + var transport http.RoundTripper + { + tp := http.DefaultTransport.(*http.Transport).Clone() - if flags.insecureSkipVerify != nil && *flags.insecureSkipVerify { - transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} - } + if flags.insecureSkipVerify != nil && *flags.insecureSkipVerify { + tp.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + } - if transport.TLSClientConfig == nil { - transport.TLSClientConfig = &tls.Config{} + if tp.TLSClientConfig == nil { + tp.TLSClientConfig = &tls.Config{} + } + + if opts.ProxyURL != nil || opts.ProxyPath != "" { + tp = withProxyTransport(tp, opts.ProxyURL, opts.ProxyPath) + } + + transport = tp } - if opts.ProxyURL != nil || opts.ProxyPath != "" { - transport = withProxyTransport(transport, opts.ProxyURL, opts.ProxyPath) + if opts.AccessToken == "" && opts.OAuthToken != nil { + transport = &oauth.Transport{ + Base: transport, + Token: opts.OAuthToken, + } } return transport @@ -168,6 +183,7 @@ func (c *client) createHTTPRequest(ctx context.Context, method, p string, body i } else { req.Header.Set("User-Agent", "src-cli/"+version.BuildTag) } + if c.opts.AccessToken != "" { req.Header.Set("Authorization", "token "+c.opts.AccessToken) } @@ -249,10 +265,20 @@ func (r *request) do(ctx context.Context, result any) (bool, error) { // confirm the status code. You can test this easily with e.g. an invalid // endpoint like -endpoint=https://google.com if resp.StatusCode != http.StatusOK { - if resp.StatusCode == http.StatusUnauthorized && isatty.IsCygwinTerminal(os.Stdout.Fd()) { - fmt.Println("You may need to specify or update your access token to use this endpoint.") - fmt.Println("See https://github.com/sourcegraph/src-cli#readme") - fmt.Println("") + if resp.StatusCode == http.StatusUnauthorized { + if oauth.IsOAuthTransport(r.client.httpClient.Transport) { + fmt.Println("The OAuth token is invalid. Please check that the Sourcegraph CLI client is still authorized.") + fmt.Println("") + fmt.Printf("To re-authorize, run: src login --oauth %s\n", r.client.opts.Endpoint) + fmt.Println("") + fmt.Println("Learn more at https://github.com/sourcegraph/src-cli#readme") + fmt.Println("") + } + if isatty.IsCygwinTerminal(os.Stdout.Fd()) { + fmt.Println("You may need to specify or update your access token to use this endpoint.") + fmt.Println("See https://github.com/sourcegraph/src-cli#readme") + fmt.Println("") + } } body, err := io.ReadAll(resp.Body) if err != nil { diff --git a/internal/oauth/flow.go b/internal/oauth/flow.go index 584244cc43..7f22be3530 100644 --- a/internal/oauth/flow.go +++ b/internal/oauth/flow.go @@ -3,6 +3,7 @@ package oauth import ( + "cmp" "context" "encoding/json" "fmt" @@ -13,6 +14,8 @@ import ( "testing" "time" + "github.com/sourcegraph/src-cli/internal/secrets" + "github.com/sourcegraph/sourcegraph/lib/errors" ) @@ -30,6 +33,10 @@ const ( ScopeEmail string = "email" ScopeOfflineAccess string = "offline_access" ScopeUserAll string = "user:all" + + // storeKeyFmt is the format of the key name that will be used to store a value + // typically the last element is the endpoint the value is for ie. src:oauth:https://sourcegraph.sourcegraph.com + storeKeyFmt string = "src:oauth:%s" ) var defaultScopes = []string{ScopeEmail, ScopeOfflineAccess, ScopeOpenID, ScopeProfile, ScopeUserAll} @@ -54,21 +61,30 @@ type DeviceAuthResponse struct { type TokenResponse struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token,omitempty"` - TokenType string `json:"token_type"` ExpiresIn int `json:"expires_in,omitempty"` + TokenType string `json:"token_type"` Scope string `json:"scope,omitempty"` } +type Token struct { + Endpoint string `json:"endpoint"` + ClientID string `json:"client_id,omitempty"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token,omitempty"` + ExpiresAt time.Time `json:"expires_at"` +} + type ErrorResponse struct { Error string `json:"error"` ErrorDescription string `json:"error_description,omitempty"` } type Client interface { + ClientID() string Discover(ctx context.Context, endpoint string) (*OIDCConfiguration, error) Start(ctx context.Context, endpoint string, scopes []string) (*DeviceAuthResponse, error) Poll(ctx context.Context, endpoint, deviceCode string, interval time.Duration, expiresIn int) (*TokenResponse, error) - Refresh(ctx context.Context, endpoint, refreshToken string) (*TokenResponse, error) + Refresh(ctx context.Context, token *Token) (*TokenResponse, error) } type httpClient struct { @@ -79,22 +95,23 @@ type httpClient struct { } func NewClient(clientID string) Client { - return &httpClient{ - clientID: clientID, - client: &http.Client{ - Timeout: 30 * time.Second, - }, - configCache: make(map[string]*OIDCConfiguration), - } + return NewClientWithHTTPClient(clientID, &http.Client{ + Timeout: 30 * time.Second, + }) } -func NewClientWithHTTPClient(c *http.Client) Client { +func NewClientWithHTTPClient(clientID string, c *http.Client) Client { return &httpClient{ + clientID: cmp.Or(clientID, DefaultClientID), client: c, configCache: make(map[string]*OIDCConfiguration), } } +func (c *httpClient) ClientID() string { + return c.clientID +} + // Discover fetches the openid-configuration which contains all the routes a client should // use for authorization, device flows, tokens etc. // @@ -157,7 +174,7 @@ func (c *httpClient) Start(ctx context.Context, endpoint string, scopes []string } data := url.Values{} - data.Set("client_id", DefaultClientID) + data.Set("client_id", c.clientID) if len(scopes) > 0 { data.Set("scope", strings.Join(scopes, " ")) } else { @@ -271,7 +288,7 @@ func (e *PollError) Error() string { func (c *httpClient) pollOnce(ctx context.Context, tokenEndpoint, deviceCode string) (*TokenResponse, error) { data := url.Values{} - data.Set("client_id", DefaultClientID) + data.Set("client_id", c.clientID) data.Set("device_code", deviceCode) data.Set("grant_type", GrantTypeDeviceCode) @@ -310,22 +327,20 @@ func (c *httpClient) pollOnce(ctx context.Context, tokenEndpoint, deviceCode str } // Refresh exchanges a refresh token for a new access token. -func (c *httpClient) Refresh(ctx context.Context, endpoint, refreshToken string) (*TokenResponse, error) { - endpoint = strings.TrimRight(endpoint, "/") - - config, err := c.Discover(ctx, endpoint) +func (c *httpClient) Refresh(ctx context.Context, token *Token) (*TokenResponse, error) { + config, err := c.Discover(ctx, token.Endpoint) if err != nil { - return nil, errors.Wrap(err, "OIDC discovery failed") + return nil, errors.Wrap(err, "failed to discover OIDC configuration") } if config.TokenEndpoint == "" { - return nil, errors.New("token endpoint not found in OIDC configuration") + return nil, errors.New("OIDC configuration has no token endpoint") } data := url.Values{} data.Set("client_id", c.clientID) data.Set("grant_type", "refresh_token") - data.Set("refresh_token", refreshToken) + data.Set("refresh_token", token.RefreshToken) req, err := http.NewRequestWithContext(ctx, "POST", config.TokenEndpoint, strings.NewReader(data.Encode())) if err != nil { @@ -358,5 +373,64 @@ func (c *httpClient) Refresh(ctx context.Context, endpoint, refreshToken string) return nil, errors.Wrap(err, "parsing refresh token response") } - return &tokenResp, nil + return &tokenResp, err +} + +func (t *TokenResponse) Token(endpoint string) *Token { + return &Token{ + Endpoint: strings.TrimRight(endpoint, "/"), + RefreshToken: t.RefreshToken, + AccessToken: t.AccessToken, + ExpiresAt: time.Now().Add(time.Second * time.Duration(t.ExpiresIn)), + } +} + +func (t *Token) HasExpired() bool { + return time.Now().After(t.ExpiresAt) +} + +func (t *Token) ExpiringIn(d time.Duration) bool { + future := time.Now().Add(d) + return future.After(t.ExpiresAt) +} + +func oauthKey(endpoint string) string { + return fmt.Sprintf(storeKeyFmt, endpoint) +} + +func StoreToken(ctx context.Context, token *Token) error { + store, err := secrets.Open(ctx) + if err != nil { + return err + } + data, err := json.Marshal(token) + if err != nil { + return errors.Wrap(err, "failed to marshal token") + } + + if token.Endpoint == "" { + return errors.New("token endpoint cannot be empty when storing the token") + } + + return store.Put(oauthKey(token.Endpoint), data) +} + +func LoadToken(ctx context.Context, endpoint string) (*Token, error) { + store, err := secrets.Open(ctx) + if err != nil { + return nil, err + } + + key := oauthKey(endpoint) + data, err := store.Get(key) + if err != nil { + return nil, err + } + + var t Token + if err := json.Unmarshal(data, &t); err != nil { + return nil, errors.Wrap(err, "failed to unmarshal token") + } + + return &t, nil } diff --git a/internal/oauth/flow_test.go b/internal/oauth/flow_test.go index 8c82d9d119..0b1ad5dc93 100644 --- a/internal/oauth/flow_test.go +++ b/internal/oauth/flow_test.go @@ -267,9 +267,9 @@ func TestStart_NoDeviceEndpoint(t *testing.T) { func TestPoll_Success(t *testing.T) { wantToken := TokenResponse{ AccessToken: "test-access-token", - TokenType: "Bearer", ExpiresIn: 3600, Scope: "read write", + TokenType: "Bearer", } server := newTestServer(t, testServerOptions{ @@ -313,6 +313,7 @@ func TestPoll_Success(t *testing.T) { if resp.TokenType != wantToken.TokenType { t.Errorf("TokenType = %q, want %q", resp.TokenType, wantToken.TokenType) } + } func TestPoll_AuthorizationPending(t *testing.T) { @@ -527,8 +528,8 @@ func TestRefresh_Success(t *testing.T) { json.NewEncoder(w).Encode(TokenResponse{ AccessToken: "new-access-token", RefreshToken: "new-refresh-token", - TokenType: "Bearer", ExpiresIn: 3600, + TokenType: "Bearer", }) }, }, @@ -536,7 +537,13 @@ func TestRefresh_Success(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID) - resp, err := client.Refresh(context.Background(), server.URL, "test-refresh-token") + token := &Token{ + Endpoint: server.URL, + AccessToken: "new-access-token", + RefreshToken: "test-refresh-token", + ExpiresAt: time.Now().Add(time.Second * time.Duration(3600)), + } + resp, err := client.Refresh(context.Background(), token) if err != nil { t.Fatalf("Refresh() error = %v", err) } @@ -548,3 +555,19 @@ func TestRefresh_Success(t *testing.T) { t.Errorf("RefreshToken = %q, want %q", resp.RefreshToken, "new-refresh-token") } } + +func TestRefresh_DiscoverFailure(t *testing.T) { + client := NewClient(DefaultClientID) + token := &Token{ + Endpoint: "http://127.0.0.1:1", + RefreshToken: "test-refresh-token", + } + + _, err := client.Refresh(context.Background(), token) + if err == nil { + t.Fatal("Refresh() expected error, got nil") + } + if !strings.Contains(err.Error(), "failed to discover OIDC configuration") { + t.Errorf("error = %q, want discovery failure context", err.Error()) + } +} diff --git a/internal/oauth/http_transport.go b/internal/oauth/http_transport.go new file mode 100644 index 0000000000..9407bc625f --- /dev/null +++ b/internal/oauth/http_transport.go @@ -0,0 +1,65 @@ +package oauth + +import ( + "context" + "net/http" + "time" +) + +var _ http.Transport + +var _ http.RoundTripper = (*Transport)(nil) + +type Transport struct { + Base http.RoundTripper + Token *Token +} + +// storeRefreshedTokenFn is the function the transport should use to persist the token - mainly used during +// tests to swap out the implementation out with a mock +var storeRefreshedTokenFn = StoreToken + +// RoundTrip implements http.RoundTripper. +func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { + ctx := req.Context() + prevToken := t.Token + token, err := maybeRefresh(ctx, t.Token) + if err != nil { + return nil, err + } + t.Token = token + if token != prevToken { + // try to save the token if we fail let the request continue with in memory token + _ = storeRefreshedTokenFn(ctx, token) + } + + req2 := req.Clone(req.Context()) + req2.Header.Set("Authorization", "Bearer "+t.Token.AccessToken) + + if t.Base != nil { + return t.Base.RoundTrip(req2) + } + return http.DefaultTransport.RoundTrip(req2) +} + +func maybeRefresh(ctx context.Context, token *Token) (*Token, error) { + // token has NOT expired or NOT about to expire in 30s + if !(token.HasExpired() || token.ExpiringIn(time.Duration(30)*time.Second)) { + return token, nil + } + client := NewClient(token.ClientID) + + resp, err := client.Refresh(ctx, token) + if err != nil { + return nil, err + } + + next := resp.Token(token.Endpoint) + next.ClientID = token.ClientID + return next, nil +} + +func IsOAuthTransport(trp http.RoundTripper) bool { + _, ok := trp.(*Transport) + return ok +} diff --git a/internal/oauth/http_transport_test.go b/internal/oauth/http_transport_test.go new file mode 100644 index 0000000000..4dac832d05 --- /dev/null +++ b/internal/oauth/http_transport_test.go @@ -0,0 +1,172 @@ +package oauth + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type roundTripperFunc func(*http.Request) (*http.Response, error) + +func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +func newRefreshServer(t *testing.T, accessToken string) *httptest.Server { + t.Helper() + return newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"access_token":"` + accessToken + `","refresh_token":"new-refresh","expires_in":3600}`)) + }, + }, + }) +} + +func TestMaybeRefresh(t *testing.T) { + server := newRefreshServer(t, "new-token") + defer server.Close() + + tests := []struct { + name string + token *Token + wantAccess string + wantSame bool + }{ + { + name: "unchanged when still valid", + token: &Token{ + AccessToken: "valid-token", + ExpiresAt: time.Now().Add(time.Hour), + }, + wantAccess: "valid-token", + wantSame: true, + }, + { + name: "refreshes expired token", + token: &Token{ + Endpoint: server.URL, + AccessToken: "expired-token", + RefreshToken: "refresh-token", + ExpiresAt: time.Now().Add(-time.Hour), + }, + wantAccess: "new-token", + }, + { + name: "refreshes token expiring soon", + token: &Token{ + Endpoint: server.URL, + AccessToken: "expiring-soon-token", + RefreshToken: "refresh-token", + ExpiresAt: time.Now().Add(10 * time.Second), + }, + wantAccess: "new-token", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := maybeRefresh(context.Background(), tt.token) + if err != nil { + t.Fatalf("maybeRefresh() error = %v", err) + } + if got.AccessToken != tt.wantAccess { + t.Errorf("AccessToken = %q, want %q", got.AccessToken, tt.wantAccess) + } + if tt.wantSame && got != tt.token { + t.Errorf("token pointer changed for unexpired token") + } + }) + } +} + +func TestTransportRoundTrip(t *testing.T) { + tests := []struct { + name string + token *Token + persistErr error + wantAuthHeader string + wantStoreCalls int + }{ + { + name: "uses existing token without persisting", + token: &Token{ + AccessToken: "valid-token", + ExpiresAt: time.Now().Add(time.Hour), + }, + wantAuthHeader: "Bearer valid-token", + wantStoreCalls: 0, + }, + { + name: "persists refreshed token", + token: &Token{ + AccessToken: "expired-token", + RefreshToken: "refresh-token", + ExpiresAt: time.Now().Add(-time.Hour), + }, + wantAuthHeader: "Bearer new-token", + wantStoreCalls: 1, + }, + { + name: "ignores persist failures", + token: &Token{ + AccessToken: "expired-token", + RefreshToken: "refresh-token", + ExpiresAt: time.Now().Add(-time.Hour), + }, + persistErr: errors.New("persist failed"), + wantAuthHeader: "Bearer new-token", + wantStoreCalls: 1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.wantStoreCalls > 0 { + server := newRefreshServer(t, "new-token") + defer server.Close() + tt.token.Endpoint = server.URL + } + + originalStoreFn := storeRefreshedTokenFn + defer func() { storeRefreshedTokenFn = originalStoreFn }() + + var storeCalls int + var storedToken *Token + storeRefreshedTokenFn = func(_ context.Context, token *Token) error { + storeCalls++ + storedToken = token + return tt.persistErr + } + + var capturedAuth string + tr := &Transport{ + Base: roundTripperFunc(func(req *http.Request) (*http.Response, error) { + capturedAuth = req.Header.Get("Authorization") + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil + }), + Token: tt.token, + } + + _, err := tr.RoundTrip(httptest.NewRequest(http.MethodGet, "http://example.com", nil)) + if err != nil { + t.Fatalf("RoundTrip() error = %v", err) + } + + if capturedAuth != tt.wantAuthHeader { + t.Errorf("Authorization = %q, want %q", capturedAuth, tt.wantAuthHeader) + } + if storeCalls != tt.wantStoreCalls { + t.Errorf("store calls = %d, want %d", storeCalls, tt.wantStoreCalls) + } + if tt.wantStoreCalls > 0 && (storedToken == nil || storedToken.AccessToken != "new-token") { + t.Errorf("stored token = %#v, want access token %q", storedToken, "new-token") + } + }) + } +} diff --git a/internal/secrets/keyring.go b/internal/secrets/keyring.go new file mode 100644 index 0000000000..d3f18eccc7 --- /dev/null +++ b/internal/secrets/keyring.go @@ -0,0 +1,86 @@ +package secrets + +import ( + "context" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/zalando/go-keyring" +) + +var ErrSecretNotFound = errors.New("secret not found") + +// Store provides secure credential storage operations. +type Store interface { + Get(key string) ([]byte, error) + Put(key string, data []byte) error + Delete(key string) error +} + +type keyringStore struct { + ctx context.Context + serviceName string +} + +// Open opens the system keyring for the Sourcegraph CLI. +func Open(ctx context.Context) (Store, error) { + return &keyringStore{ctx: ctx, serviceName: "Sourcegraph CLI"}, nil +} + +// withContext runs fn in a goroutine and returns its result, or ctx.Err() if the context is cancelled first. +func withContext[T any](ctx context.Context, fn func() (T, error)) (T, error) { + type result struct { + val T + err error + } + ch := make(chan result, 1) + go func() { + val, err := fn() + ch <- result{val, err} + }() + + select { + case <-ctx.Done(): + var zero T + return zero, ctx.Err() + case r := <-ch: + return r.val, r.err + } +} + +// Put stores a key-value pair in the keyring. +func (k *keyringStore) Put(key string, data []byte) error { + _, err := withContext(k.ctx, func() (struct{}, error) { + err := keyring.Set(k.serviceName, key, string(data)) + if err != nil { + return struct{}{}, errors.Wrap(err, "storing item in keyring") + } + return struct{}{}, nil + }) + return err +} + +// Get retrieves a value by key from the keyring. +func (k *keyringStore) Get(key string) ([]byte, error) { + return withContext(k.ctx, func() ([]byte, error) { + secret, err := keyring.Get(k.serviceName, key) + if err != nil { + if err == keyring.ErrNotFound { + return nil, ErrSecretNotFound + } + return nil, errors.Wrap(err, "getting item from keyring") + } + return []byte(secret), nil + }) +} + +// Delete removes a key from the keyring. +func (k *keyringStore) Delete(key string) error { + _, err := withContext(k.ctx, func() (struct{}, error) { + err := keyring.Delete(k.serviceName, key) + if err != nil && err != keyring.ErrNotFound { + return struct{}{}, errors.Wrap(err, "removing item from keyring") + } + return struct{}{}, nil + }) + return err +}