diff --git a/cmd/src/login.go b/cmd/src/login.go index ab5a097c71..88f010d09a 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -7,9 +7,12 @@ import ( "io" "os" "strings" + "time" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/sourcegraph/src-cli/internal/keyring" + "github.com/sourcegraph/src-cli/internal/oauthdevice" ) func init() { @@ -17,7 +20,7 @@ func init() { Usage: - src login SOURCEGRAPH_URL + src login [flags] SOURCEGRAPH_URL Examples: @@ -28,6 +31,15 @@ Examples: Authenticate to Sourcegraph.com: $ src login https://sourcegraph.com + + Use OAuth device flow to authenticate: + + $ src login --device-flow https://sourcegraph.com + + + Override the default client id used during device flow when authenticating: + + $ src login --device-flow https://sourcegraph.com --client-id sgo_my_own_client_id ` flagSet := flag.NewFlagSet("login", flag.ExitOnError) @@ -37,7 +49,9 @@ Examples: } var ( - apiFlags = api.NewFlags(flagSet) + apiFlags = api.NewFlags(flagSet) + useDeviceFlow = flagSet.Bool("device-flow", false, "Use OAuth device flow to obtain an access token interactively") + OAuthClientID = flagSet.String("client-id", oauthdevice.DefaultClientID, "Client ID to use with OAuth device flow. Will use the predefined src cli client ID if not specified.") ) handler := func(args []string) error { @@ -52,9 +66,21 @@ Examples: return cmderrors.Usage("expected exactly one argument: the Sourcegraph URL, or SRC_ENDPOINT to be set") } + if *OAuthClientID == "" { + return cmderrors.Usage("no value specified for client-id") + } + client := cfg.apiClient(apiFlags, io.Discard) - return loginCmd(context.Background(), cfg, client, endpoint, os.Stdout) + return loginCmd(context.Background(), loginParams{ + cfg: cfg, + client: client, + endpoint: endpoint, + out: os.Stdout, + useDeviceFlow: *useDeviceFlow, + apiFlags: apiFlags, + deviceFlowClient: oauthdevice.NewClient(*OAuthClientID), + }) } commands = append(commands, &command{ @@ -64,8 +90,21 @@ Examples: }) } -func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg string, out io.Writer) error { - endpointArg = cleanEndpoint(endpointArg) +type loginParams struct { + cfg *config + client api.Client + endpoint string + out io.Writer + useDeviceFlow bool + apiFlags *api.Flags + deviceFlowClient oauthdevice.Client +} + +func loginCmd(ctx context.Context, p loginParams) error { + endpointArg := cleanEndpoint(p.endpoint) + cfg := p.cfg + client := p.client + out := p.out printProblem := func(problem string) { fmt.Fprintf(out, "❌ Problem: %s\n", problem) @@ -86,7 +125,29 @@ func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg s noToken := cfg.AccessToken == "" endpointConflict := endpointArg != cfg.Endpoint - if noToken || endpointConflict { + + secretStore, err := keyring.Open() + if err != nil { + printProblem(fmt.Sprintf("could not open keyring for secret storage: %s", err)) + } + + cfg.Endpoint = endpointArg + + if p.useDeviceFlow { + token, err := runDeviceFlow(ctx, endpointArg, out, p.deviceFlowClient) + if err != nil { + printProblem(fmt.Sprintf("Device flow authentication failed: %s", err)) + fmt.Fprintln(out, createAccessTokenMessage) + return cmderrors.ExitCode1 + } + + if err := oauthdevice.StoreToken(secretStore, token); err != nil { + printProblem(fmt.Sprintf("Failed to store token in keyring store: %s", err)) + return cmderrors.ExitCode1 + } + + client = cfg.apiClient(p.apiFlags, out) + } else if noToken || endpointConflict { fmt.Fprintln(out) switch { case noToken: @@ -122,6 +183,43 @@ func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg s } fmt.Fprintln(out) fmt.Fprintf(out, "✔️ Authenticated as %s on %s\n", result.CurrentUser.Username, endpointArg) + + if p.useDeviceFlow { + fmt.Fprintln(out) + fmt.Fprintf(out, "To use this access token, set the following environment variables in your terminal:\n\n") + fmt.Fprintf(out, " export SRC_ENDPOINT=%s\n", endpointArg) + fmt.Fprintf(out, " export SRC_ACCESS_TOKEN=%s\n", cfg.AccessToken) + } + fmt.Fprintln(out) return nil } + +func runDeviceFlow(ctx context.Context, endpoint string, out io.Writer, client oauthdevice.Client) (*oauthdevice.Token, error) { + authResp, err := client.Start(ctx, endpoint, nil) + if err != nil { + return nil, err + } + + fmt.Fprintln(out) + fmt.Fprintf(out, "To authenticate, visit %s and enter the code: %s\n", authResp.VerificationURI, authResp.UserCode) + if authResp.VerificationURIComplete != "" { + fmt.Fprintln(out) + fmt.Fprintf(out, "Alternatively, you can open: %s\n", authResp.VerificationURIComplete) + } + fmt.Fprintln(out) + fmt.Fprint(out, "Waiting for authorization...") + defer fmt.Fprintf(out, "DONE\n\n") + + interval := time.Duration(authResp.Interval) * time.Second + if interval <= 0 { + interval = 5 * time.Second + } + + resp, err := client.Poll(ctx, endpoint, authResp.DeviceCode, interval, authResp.ExpiresIn) + if err != nil { + return nil, err + } + + return resp.Token(endpoint), nil +} diff --git a/cmd/src/main.go b/cmd/src/main.go index 9f8ba4ca33..dc500b78dc 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -15,6 +15,8 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/keyring" + "github.com/sourcegraph/src-cli/internal/oauthdevice" ) const usageText = `src is a tool that provides access to Sourcegraph instances. @@ -123,7 +125,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, @@ -131,7 +133,17 @@ func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { Out: out, ProxyURL: c.ProxyURL, ProxyPath: c.ProxyPath, - }) + } + store, err := keyring.Open() + if err != nil { + panic("HALP") + } + + if t, err := oauthdevice.LoadToken(store, 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 818ed24368..6c7dd8dc6f 100644 --- a/go.mod +++ b/go.mod @@ -45,6 +45,8 @@ require ( cloud.google.com/go/auth v0.17.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect cloud.google.com/go/monitoring v1.24.2 // indirect + github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect + github.com/99designs/keyring v1.2.2 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.29.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 // 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.0 // 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 @@ -71,6 +74,7 @@ require ( github.com/docker/docker-credential-helpers v0.8.0 // indirect github.com/docker/go-connections v0.4.0 // indirect github.com/docker/go-units v0.5.0 // indirect + github.com/dvsekhvalnov/jose2go v1.5.0 // indirect github.com/envoyproxy/go-control-plane/envoy v1.32.4 // indirect github.com/felixge/fgprof v0.9.3 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect @@ -78,12 +82,14 @@ require ( github.com/go-chi/chi/v5 v5.0.10 // 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 v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gofrs/uuid/v5 v5.0.0 // indirect github.com/google/gnostic-models v0.6.8 // indirect github.com/google/go-containerregistry v0.15.2 // indirect github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect + github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect github.com/jackc/pgconn v1.14.3 // indirect github.com/jackc/pgio v1.0.0 // indirect @@ -92,6 +98,7 @@ require ( github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/morikuni/aec v1.0.0 // indirect + github.com/mtibben/percent v0.2.1 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.0-rc4 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect diff --git a/go.sum b/go.sum index 8c25134d27..9c1df39938 100644 --- a/go.sum +++ b/go.sum @@ -20,6 +20,10 @@ cloud.google.com/go/storage v1.50.0 h1:3TbVkzTooBvnZsk7WaAQfOsNrdoM8QHusXA1cpk6Q cloud.google.com/go/storage v1.50.0/go.mod h1:l7XeiD//vx5lfqE3RavfmU9yvk5Pp0Zhcv482poyafY= cloud.google.com/go/trace v1.11.6 h1:2O2zjPzqPYAHrn3OKl029qlqG6W8ZdYaOWRyr8NgMT4= cloud.google.com/go/trace v1.11.6/go.mod h1:GA855OeDEBiBMzcckLPE2kDunIpC72N+Pq8WFieFjnI= +github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs= +github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4= +github.com/99designs/keyring v1.2.2 h1:pZd3neh/EmUzWONb35LxQfvuY7kiSXAq3HQd97+XBn0= +github.com/99designs/keyring v1.2.2/go.mod h1:wes/FrByc8j7lFOAGLGSNEg8f/PaI3cgTBqhFkHUrPk= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= @@ -138,6 +142,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.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= +github.com/danieljoos/wincred v1.2.0 h1:ozqKHaLK0W/ii4KVbbvluM91W2H3Sh0BncbUNPS7jLE= +github.com/danieljoos/wincred v1.2.0/go.mod h1:FzQLLMKBFdvu+osBrnFODiv32YGwCfx0SkRa/eYHgec= 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= @@ -164,6 +170,8 @@ github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4 github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/dvsekhvalnov/jose2go v1.5.0 h1:3j8ya4Z4kMCwT5nXIKFSV84YS+HdqSSO0VsTQxaLAeM= +github.com/dvsekhvalnov/jose2go v1.5.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU= github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.13.4 h1:zEqyPVyku6IvWCFwux4x9RxkLOMUL+1vC9xUFv5l2/M= @@ -211,6 +219,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 v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0= +github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= 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= @@ -254,6 +264,8 @@ github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 h1:cLN4IBkmkYZNnk7E github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs= +github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= +github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY= github.com/hexops/autogold v1.3.1 h1:YgxF9OHWbEIUjhDbpnLhgVsjUDsiHDTyDfy2lrfdlzo= github.com/hexops/autogold v1.3.1/go.mod h1:sQO+mQUCVfxOKPht+ipDSkJ2SCJ7BNJVHZexsXqWMx4= @@ -353,6 +365,8 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs= +github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns= github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= diff --git a/internal/api/api.go b/internal/api/api.go index e0bc234558..e1097ff9e0 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/oauthdevice" "github.com/sourcegraph/src-cli/internal/version" ) @@ -85,6 +86,8 @@ type ClientOpts struct { ProxyURL *url.URL ProxyPath string + + OAuthToken *oauthdevice.Token } func buildTransport(opts ClientOpts, flags *Flags) *http.Transport { @@ -102,6 +105,13 @@ func buildTransport(opts ClientOpts, flags *Flags) *http.Transport { transport = withProxyTransport(transport, opts.ProxyURL, opts.ProxyPath) } + if opt.AccessToken == "" && opt.OAuthToken != nil { + transport = &oauthdevice.Transport{ + Base: transport, + Token: opts.OAuthToken + } + } + return transport } diff --git a/internal/keyring/keyring.go b/internal/keyring/keyring.go new file mode 100644 index 0000000000..47b18e03bb --- /dev/null +++ b/internal/keyring/keyring.go @@ -0,0 +1,62 @@ +// Package keyring provides secure credential storage using the system keychain. +package keyring + +import ( + "github.com/99designs/keyring" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +const serviceName = "sourcegraph-cli" + +// Store provides secure credential storage operations. +type Store struct { + ring keyring.Keyring +} + +// Open opens the system keyring for the Sourcegraph CLI. +func Open() (*Store, error) { + ring, err := keyring.Open(keyring.Config{ + ServiceName: serviceName, + KeychainName: "login", // This is the default name for the keychain where MacOS puts all login passwords + KeychainTrustApplication: true, // the keychain can trust src-cli! + }) + if err != nil { + return nil, errors.Wrap(err, "opening keyring") + } + return &Store{ring: ring}, nil +} + +// Set stores a key-value pair in the keyring. +func (s *Store) Set(key string, data []byte) error { + err := s.ring.Set(keyring.Item{ + Key: key, + Data: data, + Label: key, + }) + if err != nil { + return errors.Wrap(err, "storing item in keyring") + } + return nil +} + +// Get retrieves a value by key from the keyring. +// Returns nil, nil if the key is not found. +func (s *Store) Get(key string) ([]byte, error) { + item, err := s.ring.Get(key) + if err != nil { + if err == keyring.ErrKeyNotFound { + return nil, nil + } + return nil, errors.Wrap(err, "getting item from keyring") + } + return item.Data, nil +} + +// Delete removes a key from the keyring. +func (s *Store) Delete(key string) error { + err := s.ring.Remove(key) + if err != nil && err != keyring.ErrKeyNotFound { + return errors.Wrap(err, "removing item from keyring") + } + return nil +} diff --git a/internal/oauthdevice/device_flow.go b/internal/oauthdevice/device_flow.go new file mode 100644 index 0000000000..8937c7866b --- /dev/null +++ b/internal/oauthdevice/device_flow.go @@ -0,0 +1,419 @@ +// Package oauthdevice implements the OAuth 2.0 Device Authorization Grant (RFC 8628) +// for authenticating with Sourcegraph instances. +package oauthdevice + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/sourcegraph/src-cli/internal/keyring" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +const ( + // DefaultClientID is a predefined Client ID built into Sourcegraph + DefaultClientID = "sgo_cid_sourcegraph-cli" + + // wellKnownPath is the path on the sourcegraph server where clients can discover OAuth configuration + wellKnownPath = "/.well-known/openid-configuration" + + // Key used to store the token in the store + KeyOAuth = "Sourcegraph CLI key storage" + + GrantTypeDeviceCode string = "urn:ietf:params:oauth:grant-type:device_code" + + ScopeOpenID string = "openid" + ScopeProfile string = "profile" + ScopeEmail string = "email" + ScopeOfflineAccess string = "offline_access" + ScopeUserAll string = "user:all" +) + +var defaultScopes = []string{ScopeEmail, ScopeOfflineAccess, ScopeOpenID, ScopeProfile, ScopeUserAll} + +// OIDCConfiguration represents the relevant fields from the OpenID Connect +// Discovery document at /.well-known/openid-configuration +type OIDCConfiguration struct { + Issuer string `json:"issuer,omitempty"` + TokenEndpoint string `json:"token_endpoint,omitempty"` + DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint,omitempty"` +} + +type DeviceAuthResponse struct { + DeviceCode string `json:"device_code"` + UserCode string `json:"user_code"` + VerificationURI string `json:"verification_uri"` + VerificationURIComplete string `json:"verification_uri_complete,omitempty"` + ExpiresIn int `json:"expires_in"` + Interval int `json:"interval"` +} + +type TokenResponse struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token,omitempty"` + ExpiresIn int `json:"expires_in,omitempty"` + TokenType string `json:"token_type"` + Scope string `json:"scope,omitempty"` +} + +type Token struct { + Endpoint string `json:"endpoint"` + 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 { + 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, token *Token) (*TokenResponse, error) +} + +type httpClient struct { + clientID string + client *http.Client + // cached OIDC configuration per endpoint + configCache map[string]*OIDCConfiguration +} + +func NewClient(clientID string) Client { + return &httpClient{ + clientID: clientID, + client: &http.Client{ + Timeout: 30 * time.Second, + }, + configCache: make(map[string]*OIDCConfiguration), + } +} + +func NewClientWithHTTPClient(c *http.Client) Client { + return &httpClient{ + client: c, + configCache: make(map[string]*OIDCConfiguration), + } +} + +// Discover fetches the openid-configuration which contains all the routes a client should +// use for authorization, device flows, tokens etc. +// +// Before making any requests, the configCache is checked and if there is a cache hit, the +// cached config is returned. +func (c *httpClient) Discover(ctx context.Context, endpoint string) (*OIDCConfiguration, error) { + endpoint = strings.TrimRight(endpoint, "/") + + if config, ok := c.configCache[endpoint]; ok { + return config, nil + } + + reqURL := endpoint + wellKnownPath + + req, err := http.NewRequestWithContext(ctx, "GET", reqURL, nil) + if err != nil { + return nil, errors.Wrap(err, "creating discovery request") + } + req.Header.Set("Accept", "application/json") + + resp, err := c.client.Do(req) + if err != nil { + return nil, errors.Wrap(err, "discovery request failed") + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, errors.Wrap(err, "reading discovery response") + } + + if resp.StatusCode != http.StatusOK { + return nil, errors.Newf("discovery failed with status %d: %s", resp.StatusCode, string(body)) + } + + var config OIDCConfiguration + if err := json.Unmarshal(body, &config); err != nil { + return nil, errors.Wrap(err, "parsing discovery response") + } + + c.configCache[endpoint] = &config + + return &config, nil +} + +// Start starts the OAuth device flow with the given endpoint. If no scopes are given the default scopes are used. +// +// Default Scopes: "openid" "profile" "email" "offline_access" "user:all" +func (c *httpClient) Start(ctx context.Context, endpoint string, scopes []string) (*DeviceAuthResponse, error) { + endpoint = strings.TrimRight(endpoint, "/") + + // Discover OIDC configuration + config, err := c.Discover(ctx, endpoint) + if err != nil { + return nil, errors.Wrap(err, "OIDC discovery failed") + } + + if config.DeviceAuthorizationEndpoint == "" { + return nil, errors.New("device authorization endpoint not found in OIDC configuration; the server may not support device flow") + } + + data := url.Values{} + data.Set("client_id", DefaultClientID) + if len(scopes) > 0 { + data.Set("scope", strings.Join(scopes, " ")) + } else { + data.Set("scope", strings.Join(defaultScopes, " ")) + } + + req, err := http.NewRequestWithContext(ctx, "POST", config.DeviceAuthorizationEndpoint, strings.NewReader(data.Encode())) + if err != nil { + return nil, errors.Wrap(err, "creating device auth request") + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := c.client.Do(req) + if err != nil { + return nil, errors.Wrap(err, "device auth request failed") + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, errors.Wrap(err, "reading device auth response") + } + + if resp.StatusCode != http.StatusOK { + var errResp ErrorResponse + if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" { + return nil, errors.Newf("device auth failed: %s: %s", errResp.Error, errResp.ErrorDescription) + } + return nil, errors.Newf("device auth failed with status %d: %s", resp.StatusCode, string(body)) + } + + var authResp DeviceAuthResponse + if err := json.Unmarshal(body, &authResp); err != nil { + return nil, errors.Wrap(err, "parsing device auth response") + } + + return &authResp, nil +} + +// Poll polls the OAuth token endpoint until the device has been authorized or not +// +// We poll as long as the authorization is pending. If the server tells us to slow down, we will wait 5 secs extra. +// +// Polling will stop when: +// - Device is authorized, and a token is returned +// - Device code has expried +// - User denied authorization +func (c *httpClient) Poll(ctx context.Context, endpoint, deviceCode string, interval time.Duration, expiresIn int) (*TokenResponse, error) { + endpoint = strings.TrimRight(endpoint, "/") + + // Discover OIDC configuration (should be cached from Start) + config, err := c.Discover(ctx, endpoint) + if err != nil { + return nil, errors.Wrap(err, "OIDC discovery failed") + } + + if config.TokenEndpoint == "" { + return nil, errors.New("token endpoint not found in OIDC configuration") + } + + deadline := time.Now().Add(time.Duration(expiresIn) * time.Second) + + for { + if time.Now().After(deadline) { + return nil, errors.New("device code expired") + } + + if !testing.Testing() { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(interval): + } + } + + tokenResp, err := c.pollOnce(ctx, config.TokenEndpoint, deviceCode) + if err != nil { + var pollErr *PollError + if errors.As(err, &pollErr) { + switch pollErr.Code { + case "authorization_pending": + continue + case "slow_down": + interval += 5 * time.Second + continue + case "expired_token": + return nil, errors.New("device code expired") + case "access_denied": + return nil, errors.New("authorization was denied by the user") + } + } + return nil, err + } + + return tokenResp, nil + } +} + +type PollError struct { + Code string + Description string +} + +func (e *PollError) Error() string { + if e.Description != "" { + return fmt.Sprintf("%s: %s", e.Code, e.Description) + } + return e.Code +} + +func (c *httpClient) pollOnce(ctx context.Context, tokenEndpoint, deviceCode string) (*TokenResponse, error) { + data := url.Values{} + data.Set("client_id", DefaultClientID) + data.Set("device_code", deviceCode) + data.Set("grant_type", GrantTypeDeviceCode) + + req, err := http.NewRequestWithContext(ctx, "POST", tokenEndpoint, strings.NewReader(data.Encode())) + if err != nil { + return nil, errors.Wrap(err, "creating token request") + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := c.client.Do(req) + if err != nil { + return nil, errors.Wrap(err, "token request failed") + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, errors.Wrap(err, "reading token response") + } + + if resp.StatusCode != http.StatusOK { + var errResp ErrorResponse + if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" { + return nil, &PollError{Code: errResp.Error, Description: errResp.ErrorDescription} + } + return nil, errors.Newf("token request failed with status %d: %s", resp.StatusCode, string(body)) + } + + var tokenResp TokenResponse + if err := json.Unmarshal(body, &tokenResp); err != nil { + return nil, errors.Wrap(err, "parsing token response") + } + + return &tokenResp, nil +} + +// Refresh exchanges a refresh token for a new access token. +func (c *httpClient) Refresh(ctx context.Context, token *Token) (*TokenResponse, error) { + config, err := c.Discover(ctx, token.Endpoint) + if err != nil { + errors.Wrap(err, "failed to discover OIDC configuration") + } + + if config.TokenEndpoint == "" { + 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", token.RefreshToken) + + req, err := http.NewRequestWithContext(ctx, "POST", config.TokenEndpoint, strings.NewReader(data.Encode())) + if err != nil { + return nil, errors.Wrap(err, "creating refresh token request") + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := c.client.Do(req) + if err != nil { + return nil, errors.Wrap(err, "refresh token request failed") + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, errors.Wrap(err, "reading refresh token response") + } + + if resp.StatusCode != http.StatusOK { + var errResp ErrorResponse + if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" { + return nil, errors.Newf("refresh token failed: %s: %s", errResp.Error, errResp.ErrorDescription) + } + return nil, errors.Newf("refresh token failed with status %d: %s", resp.StatusCode, string(body)) + } + + var tokenResp TokenResponse + if err := json.Unmarshal(body, &tokenResp); err != nil { + return nil, errors.Wrap(err, "parsing refresh token response") + } + + 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 StoreToken(store *keyring.Store, token *Token) error { + 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") + } + + key := fmt.Sprintf("%s <%s>", KeyOAuth, token.Endpoint) + return store.Set(key, data) +} + +func LoadToken(store *keyring.Store, endpoint string) (*Token, error) { + key := fmt.Sprintf("%s <%s>", KeyOAuth, endpoint) + var t Token + data, err := store.Get(key) + if err != nil { + return nil, errors.Wrap(err, "failed to get token from store") + } + + if err := json.Unmarshal(data, &t); err != nil { + return nil, errors.Wrap(err, "failed to unmarshall token") + } + + return &t, nil +} diff --git a/internal/oauthdevice/device_flow_test.go b/internal/oauthdevice/device_flow_test.go new file mode 100644 index 0000000000..1b958253db --- /dev/null +++ b/internal/oauthdevice/device_flow_test.go @@ -0,0 +1,557 @@ +package oauthdevice + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +const ( + testDeviceAuthPath = "/device/code" + testTokenPath = "/token" +) + +type testServerOptions struct { + handlers map[string]http.HandlerFunc + wellKnownFunc func(w http.ResponseWriter, r *http.Request) +} + +func newTestServer(t *testing.T, opts testServerOptions) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case wellKnownPath: + if opts.wellKnownFunc != nil { + opts.wellKnownFunc(w, r) + } else { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(OIDCConfiguration{ + Issuer: "http://" + r.Host, + DeviceAuthorizationEndpoint: "http://" + r.Host + testDeviceAuthPath, + TokenEndpoint: "http://" + r.Host + testTokenPath, + }) + } + default: + if handler, ok := opts.handlers[r.URL.Path]; ok { + handler(w, r) + } else { + t.Errorf("unexpected path: %s", r.URL.Path) + http.Error(w, "not found", http.StatusNotFound) + } + } + })) +} + +func TestDiscover_Success(t *testing.T) { + server := newTestServer(t, testServerOptions{}) + defer server.Close() + + client := NewClient(DefaultClientID) + config, err := client.Discover(context.Background(), server.URL) + if err != nil { + t.Fatalf("Discover() error = %v", err) + } + + if config.DeviceAuthorizationEndpoint != server.URL+testDeviceAuthPath { + t.Errorf("DeviceAuthorizationEndpoint = %q, want %q", config.DeviceAuthorizationEndpoint, server.URL+testDeviceAuthPath) + } + if config.TokenEndpoint != server.URL+testTokenPath { + t.Errorf("TokenEndpoint = %q, want %q", config.TokenEndpoint, server.URL+testTokenPath) + } +} + +func TestDiscover_Caching(t *testing.T) { + var callCount int32 + server := newTestServer(t, testServerOptions{ + wellKnownFunc: func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&callCount, 1) + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(OIDCConfiguration{ + DeviceAuthorizationEndpoint: "http://example.com/device", + TokenEndpoint: "http://example.com/token", + }) + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + + // Populate the cache + _, err := client.Discover(context.Background(), server.URL) + if err != nil { + t.Fatalf("Discover() error = %v", err) + } + + // Second call should use cache + _, err = client.Discover(context.Background(), server.URL) + if err != nil { + t.Fatalf("Discover() error = %v", err) + } + + if atomic.LoadInt32(&callCount) != 1 { + t.Errorf("callCount = %d, want 1 (second call should use cache)", callCount) + } +} + +func TestDiscover_Error(t *testing.T) { + server := newTestServer(t, testServerOptions{ + wellKnownFunc: func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "not found", http.StatusNotFound) + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + _, err := client.Discover(context.Background(), server.URL) + if err == nil { + t.Fatal("Discover() expected error, got nil") + } + + if !strings.Contains(err.Error(), "404") { + t.Errorf("error = %q, want to contain '404'", err.Error()) + } +} + +func TestStart_Success(t *testing.T) { + wantResponse := DeviceAuthResponse{ + DeviceCode: "test-device-code", + UserCode: "ABCD-1234", + VerificationURI: "https://example.com/device", + VerificationURIComplete: "https://example.com/device?user_code=ABCD-1234", + ExpiresIn: 1800, + Interval: 5, + } + + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testDeviceAuthPath: func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + t.Errorf("unexpected method: %s", r.Method) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + if err := r.ParseForm(); err != nil { + t.Errorf("failed to parse form: %v", err) + http.Error(w, "bad request", http.StatusBadRequest) + return + } + + if got := r.FormValue("client_id"); got != DefaultClientID { + t.Errorf("unexpected client_id: got %q, want %q", got, DefaultClientID) + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(wantResponse) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + resp, err := client.Start(context.Background(), server.URL, nil) + if err != nil { + t.Fatalf("Start() error = %v", err) + } + + if resp.DeviceCode != wantResponse.DeviceCode { + t.Errorf("DeviceCode = %q, want %q", resp.DeviceCode, wantResponse.DeviceCode) + } + if resp.UserCode != wantResponse.UserCode { + t.Errorf("UserCode = %q, want %q", resp.UserCode, wantResponse.UserCode) + } + if resp.VerificationURI != wantResponse.VerificationURI { + t.Errorf("VerificationURI = %q, want %q", resp.VerificationURI, wantResponse.VerificationURI) + } + if resp.VerificationURIComplete != wantResponse.VerificationURIComplete { + t.Errorf("VerificationURIComplete = %q, want %q", resp.VerificationURIComplete, wantResponse.VerificationURIComplete) + } + if resp.ExpiresIn != wantResponse.ExpiresIn { + t.Errorf("ExpiresIn = %d, want %d", resp.ExpiresIn, wantResponse.ExpiresIn) + } + if resp.Interval != wantResponse.Interval { + t.Errorf("Interval = %d, want %d", resp.Interval, wantResponse.Interval) + } +} + +func TestStart_WithScopes(t *testing.T) { + var receivedScope string + + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testDeviceAuthPath: func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + t.Errorf("failed to parse form: %v", err) + http.Error(w, "bad request", http.StatusBadRequest) + return + } + receivedScope = r.FormValue("scope") + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(DeviceAuthResponse{ + DeviceCode: "test-device-code", + UserCode: "ABCD-1234", + VerificationURI: "https://example.com/device", + ExpiresIn: 1800, + Interval: 5, + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + _, err := client.Start(context.Background(), server.URL, []string{"read", "write"}) + if err != nil { + t.Fatalf("Start() error = %v", err) + } + + if receivedScope != "read write" { + t.Errorf("scope = %q, want %q", receivedScope, "read write") + } +} + +func TestStart_Error(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testDeviceAuthPath: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "invalid_client", + ErrorDescription: "Unknown client", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + _, err := client.Start(context.Background(), server.URL, nil) + if err == nil { + t.Fatal("Start() expected error, got nil") + } + + wantErr := "device auth failed: invalid_client: Unknown client" + if err.Error() != wantErr { + t.Errorf("error = %q, want %q", err.Error(), wantErr) + } +} + +func TestStart_NoDeviceEndpoint(t *testing.T) { + server := newTestServer(t, testServerOptions{ + wellKnownFunc: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(OIDCConfiguration{ + TokenEndpoint: "http://example.com/token", + }) + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + _, err := client.Start(context.Background(), server.URL, nil) + if err == nil { + t.Fatal("Start() expected error, got nil") + } + + if !strings.Contains(err.Error(), "device authorization endpoint not found") { + t.Errorf("error = %q, want to contain 'device authorization endpoint not found'", err.Error()) + } +} + +func TestPoll_Success(t *testing.T) { + wantToken := TokenResponse{ + AccessToken: "test-access-token", + ExpiresIn: 3600, + Scope: "read write", + TokenType: "Bearer", + } + + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + t.Errorf("unexpected method: %s", r.Method) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + if err := r.ParseForm(); err != nil { + t.Errorf("failed to parse form: %v", err) + http.Error(w, "bad request", http.StatusBadRequest) + return + } + + if got := r.FormValue("client_id"); got != DefaultClientID { + t.Errorf("unexpected client_id: got %q, want %q", got, DefaultClientID) + } + if got := r.FormValue("grant_type"); got != GrantTypeDeviceCode { + t.Errorf("unexpected grant_type: got %q", got) + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(wantToken) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + resp, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + if err != nil { + t.Fatalf("Poll() error = %v", err) + } + + if resp.AccessToken != wantToken.AccessToken { + t.Errorf("AccessToken = %q, want %q", resp.AccessToken, wantToken.AccessToken) + } + if resp.TokenType != wantToken.TokenType { + t.Errorf("TokenType = %q, want %q", resp.TokenType, wantToken.TokenType) + } + +} + +func TestPoll_AuthorizationPending(t *testing.T) { + var callCount int32 + + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + count := atomic.AddInt32(&callCount, 1) + + w.Header().Set("Content-Type", "application/json") + + if count < 3 { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "authorization_pending", + ErrorDescription: "The user has not yet completed authorization", + }) + return + } + + json.NewEncoder(w).Encode(TokenResponse{ + AccessToken: "test-access-token", + TokenType: "Bearer", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + resp, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + if err != nil { + t.Fatalf("Poll() error = %v", err) + } + + if resp.AccessToken != "test-access-token" { + t.Errorf("AccessToken = %q, want %q", resp.AccessToken, "test-access-token") + } + + if atomic.LoadInt32(&callCount) != 3 { + t.Errorf("callCount = %d, want 3", callCount) + } +} + +func TestPoll_SlowDown(t *testing.T) { + var callCount int32 + + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + count := atomic.AddInt32(&callCount, 1) + + w.Header().Set("Content-Type", "application/json") + + if count == 1 { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "slow_down", + }) + return + } + + json.NewEncoder(w).Encode(TokenResponse{ + AccessToken: "test-access-token", + TokenType: "Bearer", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + resp, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + if err != nil { + t.Fatalf("Poll() error = %v", err) + } + + if resp.AccessToken != "test-access-token" { + t.Errorf("AccessToken = %q, want %q", resp.AccessToken, "test-access-token") + } + + if atomic.LoadInt32(&callCount) != 2 { + t.Errorf("callCount = %d, want 2", callCount) + } +} + +func TestPoll_ExpiredToken(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "expired_token", + ErrorDescription: "The device code has expired", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + _, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + if err == nil { + t.Fatal("Poll() expected error, got nil") + } + + wantErr := "device code expired" + if err.Error() != wantErr { + t.Errorf("error = %q, want %q", err.Error(), wantErr) + } +} + +func TestPoll_AccessDenied(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "access_denied", + ErrorDescription: "The user denied the request", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + _, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + if err == nil { + t.Fatal("Poll() expected error, got nil") + } + + wantErr := "authorization was denied by the user" + if err.Error() != wantErr { + t.Errorf("error = %q, want %q", err.Error(), wantErr) + } +} + +func TestPoll_Timeout(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "authorization_pending", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + _, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 0) + if err == nil { + t.Fatal("Poll() expected error, got nil") + } + + wantErr := "device code expired" + if err.Error() != wantErr { + t.Errorf("error = %q, want %q", err.Error(), wantErr) + } +} + +func TestPoll_ContextCancellation(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "authorization_pending", + }) + }, + }, + }) + defer server.Close() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + client := NewClient(DefaultClientID).(*httpClient) + _, err := client.Poll(ctx, server.URL, "test-device-code", 10*time.Millisecond, 3600) + if err == nil { + t.Fatal("Poll() expected error, got nil") + } + + if err != context.Canceled && !strings.Contains(err.Error(), "context canceled") { + t.Errorf("error = %v, want context.Canceled or wrapped context canceled error", err) + } +} + +func TestRefresh_Success(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + if got := r.FormValue("grant_type"); got != "refresh_token" { + t.Errorf("grant_type = %q, want %q", got, "refresh_token") + } + if got := r.FormValue("refresh_token"); got != "test-refresh-token" { + t.Errorf("refresh_token = %q, want %q", got, "test-refresh-token") + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(TokenResponse{ + AccessToken: "new-access-token", + RefreshToken: "new-refresh-token", + ExpiresIn: 3600, + TokenType: "Bearer", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + 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) + } + + if resp.AccessToken != "new-access-token" { + t.Errorf("AccessToken = %q, want %q", resp.AccessToken, "new-access-token") + } + if resp.RefreshToken != "new-refresh-token" { + t.Errorf("RefreshToken = %q, want %q", resp.RefreshToken, "new-refresh-token") + } +} diff --git a/internal/oauthdevice/http_transport.go b/internal/oauthdevice/http_transport.go new file mode 100644 index 0000000000..483b45108d --- /dev/null +++ b/internal/oauthdevice/http_transport.go @@ -0,0 +1,49 @@ +package oauthdevice + +import ( + "context" + "net/http" + "time" +) + +var _ http.Transport + +var _ http.RoundTripper = (*Transport)(nil) + +type Transport struct { + Base http.RoundTripper + Token *Token +} + +// RoundTrip implements http.RoundTripper. +func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { + ctx := req.Context() + token, err := maybeRefresh(ctx, t.Token) + if err != nil { + return nil, err + } + t.Token = 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(DefaultClientID) + + resp, err := client.Refresh(ctx, token) + if err != nil { + return nil, err + } + + return resp.Token(token.Endpoint), nil +}