diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 00d0abe..20e45f8 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -46,7 +46,7 @@ jobs: run: go build ./... && go vet ./... - name: Test - run: go test -race -count=1 -coverprofile=coverage.out -coverpkg=./... ./... + run: go test -race -count=1 -coverprofile=coverage.out -coverpkg=. ./... - name: Coverage run: go tool cover -func=coverage.out | tail -1 diff --git a/.golangci.yml b/.golangci.yml index d4f378e..776af00 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -26,7 +26,7 @@ linters: generated: lax rules: - path: _test\.go$ - linters: [funlen, dupl, maintidx, cyclop, gocognit] + linters: [funlen, dupl, maintidx, cyclop, gocognit, testpackage] - path: ^examples/ linters: [errcheck, forbidigo, gosec, funlen, lll, ineffassign, staticcheck] diff --git a/README.md b/README.md index 409573a..b04b123 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,27 @@ # sociable -Authenticate with Google, GitHub, GitLab, Facebook, LinkedIn, Bitbucket, -Slack, Twitch, X, or any OAuth 2 or OpenID Connect provider, on `net/http`. -You get back who the person is and a token to use. +Social sign-in on `net/http`, shaped after Laravel Socialite. You get back +who the person is and a token to use. ```go -sociable.Configure(sociable.Config{ - Key: os.Getenv("APP_KEY"), - Drivers: sociable.Drivers{ - "github": {ClientID: id, ClientSecret: secret, Redirect: "/auth/github/callback"}, - "google": {ClientID: id, ClientSecret: secret, Redirect: "/auth/google/callback"}, - }, -}) +social := sociable.New( + sociable.WithKey(os.Getenv("APP_KEY")), + sociable.WithAPIURL("https://api.example"), + sociable.WithDriver[sociable.GoogleProvider]("google", sociable.Credentials{ + ClientID: os.Getenv("GOOGLE_CLIENT_ID"), + ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"), + RedirectURL: "/auth/google/callback", + }), +) ``` ```go -http.HandleFunc("/auth/github", func(w http.ResponseWriter, r *http.Request) { - sociable.Driver("github").Redirect(w, r) +http.HandleFunc("/auth/google", func(w http.ResponseWriter, r *http.Request) { + social.Driver("google").Redirect(w, r) }) -http.HandleFunc("/auth/github/callback", func(w http.ResponseWriter, r *http.Request) { - user, err := sociable.Driver("github").User(w, r) +http.HandleFunc("/auth/google/callback", func(w http.ResponseWriter, r *http.Request) { + user, err := social.Driver("google").User(w, r) if err != nil { http.Error(w, "sign-in failed", http.StatusBadRequest) return @@ -29,175 +30,130 @@ http.HandleFunc("/auth/github/callback", func(w http.ResponseWriter, r *http.Req user.ID, user.Nickname, user.Name, user.Email, user.EmailVerified, user.Avatar user.Token.AccessToken, user.Token.RefreshToken, user.Token.Expiry user.ApprovedScopes - user.Raw }) ``` ## Configuration -| Field | | +| Option | | |---|---| -| `Key` | encrypts the cookie that carries the handshake between redirect and callback. Any string. | -| `URL` | the application's own URL, for a `Redirect` given as a path. | -| `Drivers` | a name to its `ClientID`, `ClientSecret`, `Redirect` and optional `Scopes`. | -| `Session` | an application's own session, instead of the cookie. `Key` is then not needed. | -| `Client` | the HTTP client used to talk to providers. | +| `WithKey` | encrypts the cookie that carries the handshake between redirect and callback. Any string. | +| `WithSession` | an application's own session, instead of the cookie. `WithKey` is then not needed. | +| `WithAPIURL` | the application's own URL. A `RedirectURL` given as a path is resolved against it, and `https://` marks the cookie Secure behind a proxy. | +| `WithDriver[Provider]` | registers a provider type under a name, with its `ClientID`, `ClientSecret`, `RedirectURL` and, for a self-hosted provider, `BaseURL`. | -`Redirect` is a full URL, or a path resolved against `URL`. +`APP_KEY` and `API_URL` are read from the environment when the option is not given. ## Shaping the redirect -All optional, all chainable: +All optional, all chainable, the same names as Socialite: ```go -sociable.Driver("google"). - Scopes("https://www.googleapis.com/auth/drive.readonly"). // adds to the driver's - With(map[string]string{"access_type": "offline", "prompt": "consent"}). +social.Driver("google"). + Scopes("https://www.googleapis.com/auth/drive.readonly"). // adds to the provider's + With(map[string]string{"access_type": "offline", "prompt": "consent"}). // extra auth URL parameters Redirect(w, r) -sociable.Driver("google").SetScopes("openid", "email").Redirect(w, r) // replaces them -sociable.Driver("github").RedirectURL("https://other.example/cb").Redirect(w, r) +social.Driver("google").SetScopes("openid", "email").Redirect(w, r) // replaces them +social.Driver("google").RedirectURL("https://other.example/cb").Redirect(w, r) +social.Driver("google").Stateless().Redirect(w, r) // no session, no state check ``` -`WithState` carries values through the flow. They come back on `user.State` -at the callback and never travel through the provider: - -```go -sociable.Driver("github").WithState(map[string]string{"invite": code}).Redirect(w, r) - -user, _ := sociable.Driver("github").User(w, r) -user.State["invite"] -``` - -`AuthURL(w, r)` is `Redirect` without the redirecting, for a handler that -sends the browser itself. - ## Tokens ```go -user, err := sociable.Driver("github").UserFromToken(ctx, token) // a token you already hold -token, err := sociable.Driver("google").RefreshToken(ctx, refreshToken) // a live one; persist what comes back -client := sociable.Driver("google").Client(ctx, token) // an *http.Client that presents and refreshes it +user, err := social.Driver("google").UserFromToken(ctx, token) // a token you already hold +token, err := social.Driver("google").RefreshToken(ctx, refreshToken) // a live one; persist what comes back ``` -`Stateless()` runs a callback this server did not start, for a native app -that brings its own code. - ## Errors ```go -user, err := sociable.Driver("github").User(w, r) +user, err := social.Driver("google").User(w, r) switch { -case errors.Is(err, sociable.ErrAccessDenied): // the person said no -case errors.Is(err, sociable.ErrInvalidState): // not started here, already used, or expired -case errors.Is(err, sociable.ErrUnknownDriver): -case errors.Is(err, sociable.ErrNotConfigured): -case err != nil: // the provider refused, the exchange failed, the id token did not verify +case errors.Is(err, sociable.ErrAccessDenied): // the person said no +case errors.Is(err, sociable.ErrInvalidState): // not started here, already used, or tampered with +case errors.Is(err, sociable.ErrUnknownDriver): // no driver configured under that name +case errors.Is(err, sociable.ErrIDToken): // the OpenID Connect id token did not verify +case err != nil: // the provider refused, the exchange or the profile failed } ``` Every provider refusal matches `ErrAuthorization` and carries the provider's -words as an `*AuthorizationError`. A failed ID token is `ErrIDToken`, a -failed exchange `ErrExchange`, a profile that would not load `ErrProfile`. +words as an `*AuthorizationError`. ## Your own provider -Any OpenID Connect provider is its issuer: +A provider is its endpoints, its scopes, and how it reads the person behind +a token. The client it gets already presents the token. ```go -sociable.Extend("okta", func(c sociable.Credentials) sociable.Provider { - return sociable.OpenID(c, "https://acme.okta.com") -}) -``` +type Acme struct{} -Any OAuth 2 provider is its endpoints and a mapping: +func (Acme) Endpoint(c sociable.Credentials) oauth2.Endpoint { + return oauth2.Endpoint{AuthURL: c.BaseURL + "/oauth/authorize", TokenURL: c.BaseURL + "/oauth/token"} +} -```go -sociable.Extend("acme", func(c sociable.Credentials) sociable.Provider { - return sociable.OAuth2{ - Credentials: c, - Endpoint: oauth2.Endpoint{AuthURL: base + "/oauth/authorize", TokenURL: base + "/oauth/token"}, - Scopes: []string{"profile", "email"}, - ProfileURL: base + "/oauth/userinfo", - Map: func(raw map[string]any) sociable.User { - return sociable.User{ID: sociable.String(raw, "sub"), Name: sociable.String(raw, "name"), Email: sociable.String(raw, "email")} - }, - } -}) +func (Acme) Scoping() sociable.Scoping { + return sociable.Scoping{Scopes: []string{"profile", "email"}, Separator: " "} +} + +func (Acme) GetUserByToken(ctx context.Context, client *http.Client, token *oauth2.Token, c sociable.Credentials) (*fastjson.Value, error) { + response, err := client.Get(c.BaseURL + "/oauth/userinfo") + // ... read the body, fastjson.ParseBytes +} + +func (Acme) MapUserToStruct(json *fastjson.Value) (*sociable.User, error) { + return &sociable.User{ID: string(json.GetStringBytes("sub")), Email: string(json.GetStringBytes("email"))}, nil +} ``` -Then it is configured and used like a built-in: +The provider is a zero value: what it needs to know, an issuer or a host, +comes in through `Credentials.BaseURL`. + +Optional, when it applies: ```go -"acme": {ClientID: id, ClientSecret: secret, Redirect: "/auth/acme/callback"}, -sociable.Driver("acme").Redirect(w, r) +func (Acme) Issuer() string { return "https://acme.example" } // OpenID Connect: the id token is verified +func (Acme) UsesPKCE() bool { return false } // a provider that cannot do PKCE ``` -A provider with more to read than one document implements `User` itself. -It gets an `*http.Client` that already presents the token: +Then it is configured and used like a built-in: ```go -func (self github) User(ctx context.Context, client *http.Client, token *oauth2.Token) (*sociable.User, error) { - user, err := self.OAuth2.User(ctx, client, token) - if err != nil || user.Email != "" { - return user, err - } - - var emails []email - if err := sociable.GetJSON(ctx, client, "https://api.github.com/user/emails", &emails); err != nil { - return nil, err - } - // ... -} +sociable.WithDriver[Acme]("acme", sociable.Credentials{BaseURL: "https://acme.example", ...}) +social.Driver("acme").Redirect(w, r) ``` -A provider that is not OAuth at all, a login widget for instance, implements -`Redirect(w, r, callback, state)` and `Callback(r)` itself and the flow gets -out of the way. The state check still runs. - ## Tests `Fake` swaps a driver for one that returns the user you give it, the way -`Socialite::fake` does. Fields you leave blank get a test person's values, -the same ones as Socialite's fake user. Nothing else needs configuring, -nothing talks to a provider, and a test drives the callback directly: +`Socialite::fake` does. A test makes a manager of its own and hands it to +the application, so nothing needs configuring, nothing talks to a provider, +and tests run in parallel: ```go -fake := sociable.Fake("github", sociable.User{Email: "arjen@example.test"}) -t.Cleanup(fake.Restore) +social := sociable.New() +social.Fake("github", &sociable.User{ID: "github-123", Email: "jason@example.com"}) recorder := httptest.NewRecorder() -app.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/auth/github/callback", nil)) +App(social).ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/auth/github/callback", nil)) if recorder.Header().Get("Location") != "/dashboard" { t.Fatalf("landed on %s", recorder.Header().Get("Location")) } ``` -What `Fake` returns records every redirect the handler asked for, so a -test of the redirect side can check how the person was sent off: - -```go -fake := sociable.Fake("google", sociable.User{}) - -app.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/connect/drive", nil)) - -fake.AssertRedirected(t, func(r sociable.Redirect) bool { - return slices.Contains(r.Scopes, "https://www.googleapis.com/auth/drive.readonly") -}) -``` - -`AssertNotRedirected`, `AssertRedirectedCount` and `Redirects` go with it. +`Fake("github")` without a user makes the redirect go to a URL nobody +serves, for testing the redirect side. ## What is on by default PKCE on every request, a nonce and a verified ID token for every OpenID -Connect provider, state compared in constant time, a handshake that expires -and is spent whether the callback succeeds or not. None of it needs -mentioning at the call site. +Connect provider, state compared in constant time, and a handshake that +expires after ten minutes and is spent whether the callback succeeds or +not. None of it needs mentioning at the call site. Built on [golang.org/x/oauth2](https://pkg.go.dev/golang.org/x/oauth2) for the protocol and [go-oidc](https://github.com/coreos/go-oidc) for ID tokens. -Every request to a provider, the exchange included, goes through `Client`, -so a traced transport there traces all of it. diff --git a/configuration.go b/configuration.go new file mode 100644 index 0000000..9fc24dd --- /dev/null +++ b/configuration.go @@ -0,0 +1,59 @@ +package sociable + +import "os" + +type config struct { + Key string + + // APIURL is the application's own URL, where the callback routes live. + // A RedirectURL given as a path is resolved against it, and it decides + // whether the handshake cookie is marked Secure. + APIURL string + + // Session holds the handshake. nil is a cookie encrypted under Key. + Session Session + + Drivers map[string]DriverContract +} + +func configure() config { + return config{ + Key: os.Getenv("APP_KEY"), + APIURL: os.Getenv("API_URL"), + Drivers: map[string]DriverContract{}, + } +} + +type option func(*Manager) + +func WithKey(key string) option { + return func(m *Manager) { + m.config.Key = key + } +} + +func WithSession(session Session) option { + return func(m *Manager) { + m.config.Session = session + } +} + +func WithAPIURL(url string) option { + return func(m *Manager) { + m.config.APIURL = url + } +} + +// WithDriver registers a provider type under a name. +func WithDriver[T Provider](name string, credentials Credentials) option { + return func(m *Manager) { + var provider T + + m.config.Drivers[name] = driver{ + manager: m, + name: name, + provider: provider, + credentials: credentials, + } + } +} diff --git a/driver.chain.go b/driver.chain.go new file mode 100644 index 0000000..4bc3782 --- /dev/null +++ b/driver.chain.go @@ -0,0 +1,60 @@ +package sociable + +import ( + "maps" + "slices" +) + +// The chain shapes one redirect. Every method returns a changed copy, so +// nothing leaks into the next request. + +// Scopes adds to the provider's scopes. Socialite's scopes(). +func (self driver) Scopes(scopes ...string) DriverContract { + self.scopes = append(self.scoped(), scopes...) + return self +} + +// SetScopes replaces the provider's scopes. Socialite's setScopes(). +func (self driver) SetScopes(scopes ...string) DriverContract { + self.scopes = scopes + return self +} + +// With adds query parameters to the auth URL: access_type, prompt, +// login_hint, whatever the provider understands. Socialite's with(). What is +// given here wins over what the flow would send. +func (self driver) With(params map[string]string) DriverContract { + merged := maps.Clone(self.params) + if merged == nil { + merged = map[string]string{} + } + + maps.Copy(merged, params) + + self.params = merged + return self +} + +// RedirectURL overrides the callback URL for this request. Socialite's +// redirectUrl(). +func (self driver) RedirectURL(url string) DriverContract { + self.redirect = url + return self +} + +// Stateless skips the handshake, for a callback this server did not start. +// Socialite's stateless(). Nothing is kept between the two steps, so PKCE is +// off and the state is not checked. +func (self driver) Stateless() DriverContract { + self.stateless = true + return self +} + +// scoped is the scopes in effect: the chain's, or the provider's. +func (self driver) scoped() []string { + if self.scopes != nil || self.provider == nil { + return slices.Clone(self.scopes) + } + + return slices.Clone(self.provider.Scoping().Scopes) +} diff --git a/driver.go b/driver.go new file mode 100644 index 0000000..918a3a7 --- /dev/null +++ b/driver.go @@ -0,0 +1,78 @@ +package sociable + +import ( + "context" + "net/http" + "strings" + + "golang.org/x/oauth2" +) + +type driver struct { + manager *Manager + name string + provider Provider + credentials Credentials + + // Set by the chain, for one request. + scopes []string // nil means the provider's + params map[string]string // extra auth URL parameters + redirect string // "" means the credentials' + + // stateless skips the session: nothing is kept between the redirect and + // the callback, so no state check and no PKCE. Socialite's stateless(). + stateless bool +} + +type DriverContract interface { + Scopes(scopes ...string) DriverContract + SetScopes(scopes ...string) DriverContract + With(params map[string]string) DriverContract + RedirectURL(url string) DriverContract + Stateless() DriverContract + + Redirect(w http.ResponseWriter, r *http.Request) error + User(w http.ResponseWriter, r *http.Request) (*User, error) + Callback(w http.ResponseWriter, r *http.Request) (*oauth2.Token, error) + UserFromToken(ctx context.Context, token *oauth2.Token) (*User, error) + RefreshToken(ctx context.Context, refreshToken string) (*oauth2.Token, error) +} + +// session is the configured one, or a cookie under Key. +func (self driver) session() (Session, error) { + self.manager.mutex.RLock() + defer self.manager.mutex.RUnlock() + + if self.manager.config.Session != nil { + return self.manager.config.Session, nil + } + + return newCookieSession(self.manager.config.Key, self.secure()) +} + +// secure is whether the application is served over TLS: this request is, or +// APIURL says so, for a proxy that terminates it. +func (self driver) secure() bool { + return strings.HasPrefix(self.manager.config.APIURL, "https://") +} + +func (self driver) config() *oauth2.Config { + redirect := self.redirect + if redirect == "" { + redirect = self.credentials.RedirectURL + } + + // A path is resolved against the application's URL, Socialite's + // formatRedirectUrl. + if strings.HasPrefix(redirect, "/") { + redirect = strings.TrimSuffix(self.manager.config.APIURL, "/") + redirect + } + + return &oauth2.Config{ + ClientID: self.credentials.ClientID, + ClientSecret: self.credentials.ClientSecret, + RedirectURL: redirect, + Endpoint: self.provider.Endpoint(self.credentials), + Scopes: self.scoped(), + } +} diff --git a/driver.redirect.go b/driver.redirect.go new file mode 100644 index 0000000..69c547c --- /dev/null +++ b/driver.redirect.go @@ -0,0 +1,88 @@ +package sociable + +import ( + "encoding/json" + "maps" + "net/http" + "slices" + "strings" + "time" + + "golang.org/x/oauth2" +) + +// handshake is what the callback needs to trust what came back: the state it +// issued and the PKCE verifier whose challenge it sent. +type handshake struct { + State string `json:"state"` + Verifier string `json:"verifier,omitempty"` + Nonce string `json:"nonce,omitempty"` + ExpiresAt time.Time `json:"expiresAt"` +} + +const ( + sessionKey = "sociable" + handshakeLifetime = 10 * time.Minute +) + +// Redirect sends the browser to the provider. The state and verifier it +// sends along are kept in the session, so the callback can check what came +// back and finish the exchange. +func (self driver) Redirect(w http.ResponseWriter, r *http.Request) error { + if self.name == "" { + return ErrUnknownDriver + } + + config := self.config() + scoping := self.provider.Scoping() + + issued := handshake{State: random(32), ExpiresAt: time.Now().Add(handshakeLifetime)} + options := []oauth2.AuthCodeOption{} + + // PKCE is on unless the provider says it cannot, or there is no session + // to keep the verifier in. + if unprotected, ok := self.provider.(unprotectedProvider); !self.stateless && (!ok || unprotected.UsesPKCE()) { + issued.Verifier = oauth2.GenerateVerifier() + options = append(options, oauth2.S256ChallengeOption(issued.Verifier)) + } + + // An OpenID Connect request, which asking for openid makes it, carries a + // nonce the ID token must echo. + if slices.Contains(config.Scopes, "openid") { + issued.Nonce = random(32) + options = append(options, oauth2.SetAuthURLParam("nonce", issued.Nonce)) + } + + for _, key := range slices.Sorted(maps.Keys(self.params)) { + options = append(options, oauth2.SetAuthURLParam(key, self.params[key])) + } + + // x/oauth2 joins scopes with a space. A provider that separates them + // otherwise gets the parameter set over it. + if scoping.Separator != "" && scoping.Separator != " " { + options = append(options, oauth2.SetAuthURLParam("scope", strings.Join(config.Scopes, scoping.Separator))) + } + + if !self.stateless { + if err := self.remember(w, r, issued); err != nil { + return err + } + } + + http.Redirect(w, r, config.AuthCodeURL(issued.State, options...), http.StatusFound) + return nil +} + +func (self driver) remember(w http.ResponseWriter, r *http.Request, issued handshake) error { + session, err := self.session() + if err != nil { + return err + } + + payload, err := json.Marshal(issued) + if err != nil { + return err + } + + return session.Put(w, r, sessionKey, string(payload)) +} diff --git a/driver.token.go b/driver.token.go new file mode 100644 index 0000000..85dfb94 --- /dev/null +++ b/driver.token.go @@ -0,0 +1,33 @@ +package sociable + +import ( + "context" + "fmt" + + "golang.org/x/oauth2" +) + +// UserFromToken asks the provider about a token the application already +// holds. Socialite's userFromToken. +func (self driver) UserFromToken(ctx context.Context, token *oauth2.Token) (*User, error) { + if self.name == "" { + return nil, ErrUnknownDriver + } + + return self.userFor(ctx, token) +} + +// RefreshToken trades a refresh token for a live token. Socialite's +// refreshToken. Persist what comes back: it may carry a new refresh token. +func (self driver) RefreshToken(ctx context.Context, refreshToken string) (*oauth2.Token, error) { + if self.name == "" { + return nil, ErrUnknownDriver + } + + token, err := self.config().TokenSource(ctx, &oauth2.Token{RefreshToken: refreshToken}).Token() + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrExchange, err) + } + + return token, nil +} diff --git a/driver.user.go b/driver.user.go new file mode 100644 index 0000000..2dc91c2 --- /dev/null +++ b/driver.user.go @@ -0,0 +1,190 @@ +package sociable + +import ( + "context" + "crypto/subtle" + "encoding/json" + "fmt" + "net/http" + "slices" + "strings" + "sync" + "time" + + "github.com/coreos/go-oidc/v3/oidc" + "golang.org/x/oauth2" +) + +// User finishes the flow at the callback and returns the person the provider +// vouches for, with their token. +func (self driver) User(w http.ResponseWriter, r *http.Request) (*User, error) { + if self.name == "" { + return nil, ErrUnknownDriver + } + + token, err := self.Callback(w, r) + if err != nil { + return nil, err + } + + user, err := self.userFor(r.Context(), token) + if err != nil { + return nil, err + } + + user.ApprovedScopes = approved(token, self.provider.Scoping().Separator) + return user, nil +} + +// userFor is Socialite's userInstance: the raw document fetched, mapped, and +// the token attached. The client presents the token and refreshes it when +// it can. +func (self driver) userFor(ctx context.Context, token *oauth2.Token) (*User, error) { + raw, err := self.provider.GetUserByToken(ctx, self.config().Client(ctx, token), token, self.credentials) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrProfile, err) + } + + user, err := self.provider.MapUserToStruct(raw) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrProfile, err) + } + + user.Token = token + return user, nil +} + +// callback is the first half of the callback: the handshake read back and +// checked against the query, a refusal reported, and the code exchanged for +// a token. +func (self driver) Callback(w http.ResponseWriter, r *http.Request) (*oauth2.Token, error) { + issued, err := self.recall(w, r) + if err != nil { + return nil, err + } + + query := r.URL.Query() + + if code := query.Get("error"); code != "" { + return nil, &AuthorizationError{ + Code: code, + Description: query.Get("error_description"), + URI: query.Get("error_uri"), + } + } + + options := []oauth2.AuthCodeOption{} + if issued.Verifier != "" { + options = append(options, oauth2.VerifierOption(issued.Verifier)) + } + + token, err := self.config().Exchange(r.Context(), query.Get("code"), options...) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrExchange, err) + } + + // An ID token comes only with an OpenID Connect request, which is what + // asking for openid makes it. + if issuer, ok := self.provider.(openIDProvider); ok && slices.Contains(self.scoped(), "openid") { + if err := self.verifyIDToken(r.Context(), issuer.Issuer(), token, issued.Nonce); err != nil { + return nil, err + } + } + + return token, nil +} + +// recall reads the handshake back and checks the callback's state against +// it. The handshake is spent whether or not the check passes, so a failed +// attempt cannot be replayed. Stateless has nothing to recall. +func (self driver) recall(w http.ResponseWriter, r *http.Request) (handshake, error) { + if self.stateless { + return handshake{}, nil + } + + session, err := self.session() + if err != nil { + return handshake{}, err + } + + payload, err := session.Pull(w, r, sessionKey) + if err != nil || payload == "" { + return handshake{}, ErrInvalidState + } + + var issued handshake + if err := json.Unmarshal([]byte(payload), &issued); err != nil { + return handshake{}, ErrInvalidState + } + + if time.Now().After(issued.ExpiresAt) { + return handshake{}, ErrInvalidState + } + + // A comparison that stops at the first wrong byte tells anyone who can + // time it how much of a guess was right. + if subtle.ConstantTimeCompare([]byte(issued.State), []byte(r.URL.Query().Get("state"))) != 1 { + return handshake{}, ErrInvalidState + } + + return issued, nil +} + +// verifyIDToken checks the id_token that came with the access token: +// signature against the issuer's published keys, issuer, audience, expiry, +// and the nonce the redirect sent. Socialite's getUserFromJwtToken. +func (self driver) verifyIDToken(ctx context.Context, issuer string, token *oauth2.Token, nonce string) error { + raw, _ := token.Extra("id_token").(string) + if raw == "" { + return fmt.Errorf("%w: the token response carried no id_token", ErrIDToken) + } + + provider, err := discover(ctx, issuer) + if err != nil { + return fmt.Errorf("%w: %w", ErrIDToken, err) + } + + verified, err := provider.Verifier(&oidc.Config{ClientID: self.credentials.ClientID}).Verify(ctx, raw) + if err != nil { + return fmt.Errorf("%w: %w", ErrIDToken, err) + } + + if nonce != "" && verified.Nonce != nonce { + return fmt.Errorf("%w: nonce does not match", ErrIDToken) + } + + return nil +} + +// issuers caches discovery per issuer, so the keys are fetched once and not +// on every sign-in. +var issuers sync.Map + +func discover(ctx context.Context, issuer string) (*oidc.Provider, error) { + if cached, ok := issuers.Load(issuer); ok { + return cached.(*oidc.Provider), nil + } + + provider, err := oidc.NewProvider(ctx, issuer) + if err != nil { + return nil, err + } + + issuers.Store(issuer, provider) + return provider, nil +} + +// approved is what the provider granted. RFC 6749 section 5.1 lets that +// differ from what was asked. Socialite's setApprovedScopes. +func approved(token *oauth2.Token, separator string) []string { + scope, _ := token.Extra("scope").(string) + if scope == "" { + return nil + } + + if separator == "" { + separator = " " + } + + return strings.Split(scope, separator) +} diff --git a/driver_test.go b/driver_test.go new file mode 100644 index 0000000..86ded58 --- /dev/null +++ b/driver_test.go @@ -0,0 +1,189 @@ +package sociable + +import ( + "errors" + "net/http" + "net/http/httptest" + "testing" +) + +func TestRedirectURLIsResolvedAgainstAPIURL(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + + cases := map[string]struct { + api, redirect, want string + }{ + "path": {"https://app.example", "/cb", "https://app.example/cb"}, + "trailing slash": {"https://app.example/", "/cb", "https://app.example/cb"}, + "full url": {"https://app.example", "https://other.example/cb", "https://other.example/cb"}, + "path without api": {"", "/cb", "/cb"}, + "chain overrides": {"https://app.example", "/cb", "https://app.example/other"}, + "chain with full": {"https://app.example", "/cb", "https://elsewhere.example/x"}, + } + + for name, c := range cases { + t.Run(name, func(t *testing.T) { + t.Parallel() + + m := New(WithKey("k"), WithAPIURL(c.api), + WithDriver[stub]("stub", Credentials{ClientID: "id", BaseURL: server.URL, RedirectURL: c.redirect})) + + d := m.Driver("stub") + + switch name { + case "chain overrides": + d = d.RedirectURL("/other") + case "chain with full": + d = d.RedirectURL("https://elsewhere.example/x") + } + + query, _ := redirected(t, d) + + if got := query.Get("redirect_uri"); got != c.want { + t.Errorf("redirect_uri = %q, want %q", got, c.want) + } + }) + } +} + +func TestChainDoesNotLeakBetweenRequests(t *testing.T) { + t.Parallel() + + m := manager[stub](newProviderServer(t)) + + shaped := m.Driver("stub").Scopes("c").With(map[string]string{"prompt": "consent"}).RedirectURL("/other") + plain := m.Driver("stub") + + query, _ := redirected(t, shaped) + if query.Get("scope") != "a b c" || query.Get("prompt") != "consent" || query.Get("redirect_uri") != "https://app.example/other" { + t.Errorf("shaped: %v", query) + } + + query, _ = redirected(t, plain) + if query.Get("scope") != "a b" || query.Has("prompt") || query.Get("redirect_uri") != "https://app.example/cb" { + t.Errorf("plain was shaped too: %v", query) + } +} + +func TestScopes(t *testing.T) { + t.Parallel() + + m := manager[stub](newProviderServer(t)) + + query, _ := redirected(t, m.Driver("stub").Scopes("c", "d")) + if query.Get("scope") != "a b c d" { + t.Errorf("Scopes adds: %q", query.Get("scope")) + } + + query, _ = redirected(t, m.Driver("stub").SetScopes("only")) + if query.Get("scope") != "only" { + t.Errorf("SetScopes replaces: %q", query.Get("scope")) + } + + query, _ = redirected(t, m.Driver("stub").SetScopes("only").Scopes("more")) + if query.Get("scope") != "only more" { + t.Errorf("Scopes after SetScopes: %q", query.Get("scope")) + } +} + +func TestWithMergesAndTheLastWins(t *testing.T) { + t.Parallel() + + m := manager[stub](newProviderServer(t)) + + d := m.Driver("stub"). + With(map[string]string{"prompt": "none", "hd": "example.com"}). + With(map[string]string{"prompt": "consent"}) + + query, _ := redirected(t, d) + + if query.Get("prompt") != "consent" || query.Get("hd") != "example.com" { + t.Errorf("params: %v", query) + } + + // What is given wins over what the flow would send. + query, _ = redirected(t, m.Driver("stub").With(map[string]string{"scope": "mine"})) + if query.Get("scope") != "mine" { + t.Errorf("scope override: %q", query.Get("scope")) + } +} + +func TestSessionIsRequired(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + m := New(WithDriver[stub]("stub", Credentials{ClientID: "id", BaseURL: server.URL, RedirectURL: "/cb"})) + + w, r := httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil) + + if err := m.Driver("stub").Redirect(w, r); !errors.Is(err, ErrMissingKeyOrSession) { + t.Errorf("Redirect: %v", err) + } + + if _, err := m.Driver("stub").User(w, r); !errors.Is(err, ErrMissingKeyOrSession) { + t.Errorf("User: %v", err) + } +} + +func TestApplicationSession(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + session := &memorySession{values: map[string]string{}} + m := manager[stub](server, WithSession(session)) + + query, cookies := redirected(t, m.Driver("stub")) + + if len(cookies) != 0 { + t.Errorf("cookie set with an application session: %v", cookies) + } + + if session.values[sessionKey] == "" { + t.Error("handshake not in the session") + } + + user, err := m.Driver("stub").User(httptest.NewRecorder(), callback("code=c&state="+query.Get("state"), nil)) + if err != nil || user.ID != "42" { + t.Errorf("user = %+v, %v", user, err) + } + + if _, kept := session.values[sessionKey]; kept { + t.Error("handshake not pulled") + } + + // A session that cannot store the handshake stops the redirect. + session.putErr = errors.New("full") + + if err := m.Driver("stub").Redirect(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)); !errors.Is(err, session.putErr) { + t.Errorf("Redirect with failing session: %v", err) + } +} + +func TestCookieIsSecureOverTLS(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + + _, cookies := redirected(t, manager[stub](server).Driver("stub")) // APIURL is https + if !cookies[0].Secure { + t.Error("https APIURL: cookie not Secure") + } + + _, cookies = redirected(t, manager[stub](server, WithAPIURL("http://app.example")).Driver("stub")) + if cookies[0].Secure { + t.Error("http APIURL: cookie Secure") + } + + recorder := httptest.NewRecorder() + overTLS := httptest.NewRequest(http.MethodGet, "https://app.example/auth", nil) + + if err := manager[stub](server, WithAPIURL("http://app.example")).Driver("stub").Redirect(recorder, overTLS); err != nil { + t.Fatal(err) + } + + if !recorder.Result().Cookies()[0].Secure { + t.Error("TLS request: cookie not Secure") + } +} diff --git a/errors.go b/errors.go index 08e6bdb..0dbd032 100644 --- a/errors.go +++ b/errors.go @@ -6,15 +6,16 @@ import ( ) var ( - // ErrUnknownDriver means no driver is configured under that name. - ErrUnknownDriver = errors.New("sociable: unknown driver") + ErrUnknownDriver = errors.New("sociable: unknown driver") + ErrDriverNotConfigured = errors.New("sociable: driver not configured") - // ErrNotConfigured means the driver has no credentials or no endpoints, - // because discovery failed. Refuse the route rather than redirect. - ErrNotConfigured = errors.New("sociable: driver not configured") + ErrMissingKeyOrSession = errors.New("sociable: a Key or a Session is required") + ErrSessionSealed = errors.New("sociable: the cookie cannot be opened") +) +var ( // ErrInvalidState means the callback was not started here, was already - // used, expired, or came back with another state. + // used, or came back with another state. ErrInvalidState = errors.New("sociable: invalid state") // ErrAuthorization is what every provider refusal matches. @@ -23,16 +24,15 @@ var ( // ErrAccessDenied is the refusal that means the person said no. ErrAccessDenied = fmt.Errorf("%w: access denied", ErrAuthorization) - // ErrExchange means the code could not be exchanged for a token, or the - // token is not usable. + // ErrExchange means the code could not be exchanged for a token. ErrExchange = errors.New("sociable: token exchange failed") + // ErrProfile means the provider would not describe the person. + ErrProfile = errors.New("sociable: could not read the profile") + // ErrIDToken means the ID token failed verification: signature, issuer, // audience, expiry or nonce. ErrIDToken = errors.New("sociable: the id token could not be verified") - - // ErrProfile means the provider would not describe the person. - ErrProfile = errors.New("sociable: could not read the profile") ) // AuthorizationError is a refusal the provider sent back on the redirect, in diff --git a/errors_test.go b/errors_test.go new file mode 100644 index 0000000..3d20828 --- /dev/null +++ b/errors_test.go @@ -0,0 +1,33 @@ +package sociable + +import ( + "errors" + "testing" +) + +func TestAuthorizationError(t *testing.T) { + t.Parallel() + + bare := &AuthorizationError{Code: "access_denied"} + described := &AuthorizationError{Code: "invalid_scope", Description: "unknown scope"} + + if bare.Error() != "sociable: the provider refused: access_denied" { + t.Errorf("bare = %q", bare.Error()) + } + + if described.Error() != "sociable: the provider refused: invalid_scope: unknown scope" { + t.Errorf("described = %q", described.Error()) + } + + if !errors.Is(bare, ErrAuthorization) || !errors.Is(bare, ErrAccessDenied) { + t.Error("access_denied should match both") + } + + if !errors.Is(described, ErrAuthorization) || errors.Is(described, ErrAccessDenied) { + t.Error("another code should match ErrAuthorization only") + } + + if errors.Is(described, ErrExchange) { + t.Error("matched an unrelated error") + } +} diff --git a/examples/basic/main.go b/examples/basic/main.go new file mode 100644 index 0000000..40cace5 --- /dev/null +++ b/examples/basic/main.go @@ -0,0 +1,56 @@ +// Sign in with Google on net/http. +// +// GOOGLE_CLIENT_ID=... GOOGLE_CLIENT_SECRET=... APP_KEY=anything go run ./examples/basic +// +// Then open http://localhost:8080/auth/google. +package main + +import ( + "encoding/json" + "errors" + "log" + "net/http" + "os" + + "github.com/gonstruct/sociable" +) + +func main() { + social := sociable.New( + sociable.WithKey(os.Getenv("APP_KEY")), + sociable.WithAPIURL("http://localhost:8080"), + sociable.WithDriver[sociable.GoogleProvider]("google", sociable.Credentials{ + ClientID: os.Getenv("GOOGLE_CLIENT_ID"), + ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"), + RedirectURL: "/auth/google/callback", // resolved against APIURL + }), + ) + + http.HandleFunc("/auth/google", func(w http.ResponseWriter, r *http.Request) { + if err := social.Driver("google").Redirect(w, r); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + }) + + http.HandleFunc("/auth/google/callback", func(w http.ResponseWriter, r *http.Request) { + user, err := social.Driver("google").User(w, r) + + switch { + case errors.Is(err, sociable.ErrAccessDenied): + http.Error(w, "you said no", http.StatusForbidden) + return + case errors.Is(err, sociable.ErrInvalidState): + http.Error(w, "start again", http.StatusBadRequest) + return + case err != nil: + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(user) + }) + + log.Println("listening on http://localhost:8080/auth/google") + log.Fatal(http.ListenAndServe(":8080", nil)) +} diff --git a/examples/custom-provider/main.go b/examples/custom-provider/main.go new file mode 100644 index 0000000..d491eb0 --- /dev/null +++ b/examples/custom-provider/main.go @@ -0,0 +1,92 @@ +// A provider of your own: any OpenID Connect issuer, given as BaseURL. +// +// A provider is its endpoints, its scopes, how it fetches the person's +// document, and how it maps it. Declaring Issuer makes the flow verify the +// ID token. The provider is a zero value, so the issuer comes in through +// the credentials. +package main + +import ( + "context" + "io" + "log" + "net/http" + "os" + + "github.com/gonstruct/sociable" + "github.com/valyala/fastjson" + "golang.org/x/oauth2" +) + +type OktaProvider struct{} + +func (OktaProvider) Endpoint(c sociable.Credentials) oauth2.Endpoint { + return oauth2.Endpoint{ + AuthURL: c.BaseURL + "/oauth2/v1/authorize", + TokenURL: c.BaseURL + "/oauth2/v1/token", + } +} + +func (OktaProvider) Issuer() string { return "https://acme.okta.com" } + +func (OktaProvider) Scoping() sociable.Scoping { + return sociable.Scoping{Scopes: []string{"openid", "profile", "email"}, Separator: " "} +} + +func (OktaProvider) GetUserByToken(ctx context.Context, client *http.Client, _ *oauth2.Token, c sociable.Credentials) (*fastjson.Value, error) { + request, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/oauth2/v1/userinfo", nil) + if err != nil { + return nil, err + } + + response, err := client.Do(request) // the client already presents the token + if err != nil { + return nil, err + } + defer response.Body.Close() + + body, err := io.ReadAll(response.Body) + if err != nil { + return nil, err + } + + return fastjson.ParseBytes(body) +} + +func (OktaProvider) MapUserToStruct(json *fastjson.Value) (*sociable.User, error) { + return &sociable.User{ + ID: string(json.GetStringBytes("sub")), + Nickname: string(json.GetStringBytes("preferred_username")), + Name: string(json.GetStringBytes("name")), + Email: string(json.GetStringBytes("email")), + EmailVerified: json.GetBool("email_verified"), + }, nil +} + +func main() { + social := sociable.New( + sociable.WithKey(os.Getenv("APP_KEY")), + sociable.WithDriver[OktaProvider]("okta", sociable.Credentials{ + ClientID: os.Getenv("OKTA_CLIENT_ID"), + ClientSecret: os.Getenv("OKTA_CLIENT_SECRET"), + BaseURL: "https://acme.okta.com", + RedirectURL: "http://localhost:8080/auth/okta/callback", + }), + ) + + http.HandleFunc("/auth/okta", func(w http.ResponseWriter, r *http.Request) { + social.Driver("okta").Redirect(w, r) + }) + + http.HandleFunc("/auth/okta/callback", func(w http.ResponseWriter, r *http.Request) { + user, err := social.Driver("okta").User(w, r) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + w.Write([]byte("hello " + user.Name)) + }) + + log.Fatal(http.ListenAndServe(":8080", nil)) +} diff --git a/examples/testing/app.go b/examples/testing/app.go new file mode 100644 index 0000000..0167478 --- /dev/null +++ b/examples/testing/app.go @@ -0,0 +1,49 @@ +// A sign-in handler and its test, with Fake standing in for GitHub. +package main + +import ( + "log" + "net/http" + "os" + + "github.com/gonstruct/sociable" +) + +// App is the part under test: two routes and an in-memory account store. It +// takes the manager, so tests hand in one of their own and run in parallel. +func App(social *sociable.Manager) http.Handler { + accounts := map[string]string{} // github id -> name + + mux := http.NewServeMux() + + mux.HandleFunc("/auth/github", func(w http.ResponseWriter, r *http.Request) { + social.Driver("github").Scopes("read:org").Redirect(w, r) + }) + + mux.HandleFunc("/auth/github/callback", func(w http.ResponseWriter, r *http.Request) { + user, err := social.Driver("github").User(w, r) + if err != nil { + http.Error(w, "sign-in failed", http.StatusBadRequest) + return + } + + accounts[user.ID] = user.Name + + http.Redirect(w, r, "/dashboard", http.StatusFound) + }) + + return mux +} + +func main() { + social := sociable.New( + sociable.WithKey(os.Getenv("APP_KEY")), + sociable.WithDriver[sociable.GitHubProvider]("github", sociable.Credentials{ + ClientID: os.Getenv("GITHUB_CLIENT_ID"), + ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"), + RedirectURL: "http://localhost:8080/auth/github/callback", + }), + ) + + log.Fatal(http.ListenAndServe(":8080", App(social))) +} diff --git a/examples/testing/app_test.go b/examples/testing/app_test.go new file mode 100644 index 0000000..5fd1d32 --- /dev/null +++ b/examples/testing/app_test.go @@ -0,0 +1,45 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gonstruct/sociable" +) + +// The two tests from Socialite's documentation. Each test has a manager of +// its own, so nothing is configured, nothing talks to GitHub, and they run +// in parallel. + +func TestUserIsRedirectedToGitHub(t *testing.T) { + t.Parallel() + + social := sociable.New() + social.Fake("github") + + recorder := httptest.NewRecorder() + App(social).ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/auth/github", nil)) + + if recorder.Code != http.StatusFound { + t.Fatalf("status %d, want a redirect", recorder.Code) + } +} + +func TestUserCanLoginWithGitHub(t *testing.T) { + t.Parallel() + + social := sociable.New() + social.Fake("github", &sociable.User{ + ID: "github-123", + Name: "Jason Beggs", + Email: "jason@example.com", + }) + + recorder := httptest.NewRecorder() + App(social).ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/auth/github/callback", nil)) + + if location := recorder.Header().Get("Location"); location != "/dashboard" { + t.Fatalf("landed on %q, want /dashboard", location) + } +} diff --git a/fake.go b/fake.go index a570909..e5045c4 100644 --- a/fake.go +++ b/fake.go @@ -1,107 +1,55 @@ package sociable import ( - "fmt" - "slices" - "sync" - "testing" -) - -// Faked is a faked driver: the user it answers with, and every redirect it -// was asked for, so a test can check what the handler sent the person off -// with. -type Faked struct { - manager *Manager - driver string - user User + "context" + "net/http" - mutex sync.Mutex - redirects []Redirect -} + "golang.org/x/oauth2" +) -// Redirect is one call to Redirect or AuthURL on a faked driver, as the -// handler shaped it. -type Redirect struct { - Scopes []string - Params map[string]string - State map[string]string - RedirectURL string -} +// fakeDriver is what Fake swaps in: Socialite's FakeProvider. It answers +// Redirect and User itself and hands everything else to the driver it +// replaced. +type fakeDriver struct { + name string + user *User -// Restore puts the real driver back. Register it with t.Cleanup so a fake on -// the default manager does not outlive its test. -func (self *Faked) Restore() { - self.manager.restore(self.driver, self) + // driver is the one this fake replaced. An unknown name wraps an empty + // driver, so a test needs no credentials. + driver DriverContract } -// Redirects are the redirects so far, oldest first. -func (self *Faked) Redirects() []Redirect { - self.mutex.Lock() - defer self.mutex.Unlock() - - return slices.Clone(self.redirects) +// Redirect is a 302 to a URL nobody serves. No session, no state, no PKCE. +func (self fakeDriver) Redirect(w http.ResponseWriter, r *http.Request) error { + http.Redirect(w, r, "https://sociable.fake/"+self.name+"/authorize", http.StatusFound) + return nil } -// AssertRedirected fails the test unless a redirect happened that every -// condition accepts. -func (self *Faked) AssertRedirected(t testing.TB, conditions ...func(Redirect) bool) { - t.Helper() - - for _, redirect := range self.Redirects() { - if accepted(redirect, conditions) { - return - } +// User is the user Fake was given. Nothing on the request is read. +func (self fakeDriver) User(w http.ResponseWriter, r *http.Request) (*User, error) { + if self.user != nil { + return self.user, nil } - t.Errorf("sociable: %s was not redirected to as expected; redirects: %s", self.driver, self.describe()) -} - -// AssertNotRedirected fails the test if a redirect happened that every -// condition accepts. With no conditions, any redirect fails it. -func (self *Faked) AssertNotRedirected(t testing.TB, conditions ...func(Redirect) bool) { - t.Helper() - - for _, redirect := range self.Redirects() { - if accepted(redirect, conditions) { - t.Errorf("sociable: %s was redirected to: %+v", self.driver, redirect) - - return - } - } + return self.driver.User(w, r) } -// AssertRedirectedCount fails the test unless exactly count redirects -// happened. -func (self *Faked) AssertRedirectedCount(t testing.TB, count int) { - t.Helper() - - if got := len(self.Redirects()); got != count { - t.Errorf("sociable: %s was redirected to %d times, want %d", self.driver, got, count) - } +func (self fakeDriver) Callback(w http.ResponseWriter, r *http.Request) (*oauth2.Token, error) { + return self.driver.Callback(w, r) } -func (self *Faked) record(redirect Redirect) { - self.mutex.Lock() - defer self.mutex.Unlock() - - self.redirects = append(self.redirects, redirect) +func (self fakeDriver) UserFromToken(ctx context.Context, token *oauth2.Token) (*User, error) { + return self.driver.UserFromToken(ctx, token) } -func (self *Faked) describe() string { - redirects := self.Redirects() - if len(redirects) == 0 { - return "none" - } - - return fmt.Sprintf("%+v", redirects) +func (self fakeDriver) RefreshToken(ctx context.Context, refresh string) (*oauth2.Token, error) { + return self.driver.RefreshToken(ctx, refresh) } -func accepted(redirect Redirect, conditions []func(Redirect) bool) bool { - for _, condition := range conditions { - if !condition(redirect) { - return false - } - } - - return true -} +// The chain returns the fake itself, so Driver("x").Scopes(...).Redirect(...) +// stays faked. +func (self fakeDriver) Scopes(...string) DriverContract { return self } +func (self fakeDriver) SetScopes(...string) DriverContract { return self } +func (self fakeDriver) With(map[string]string) DriverContract { return self } +func (self fakeDriver) RedirectURL(string) DriverContract { return self } +func (self fakeDriver) Stateless() DriverContract { return self } diff --git a/fake_test.go b/fake_test.go new file mode 100644 index 0000000..518056f --- /dev/null +++ b/fake_test.go @@ -0,0 +1,95 @@ +package sociable + +import ( + "errors" + "net/http" + "net/http/httptest" + "testing" + + "golang.org/x/oauth2" +) + +func TestFakeRedirectsNowhere(t *testing.T) { + t.Parallel() + + m := New() // nothing configured, not even a key + m.Fake("github") + + recorder := httptest.NewRecorder() + if err := m.Driver("github").Redirect(recorder, httptest.NewRequest(http.MethodGet, "/auth", nil)); err != nil { + t.Fatal(err) + } + + if recorder.Code != http.StatusFound || recorder.Header().Get("Location") != "https://sociable.fake/github/authorize" { + t.Errorf("%d %s", recorder.Code, recorder.Header().Get("Location")) + } + + if len(recorder.Result().Cookies()) != 0 { + t.Error("a handshake was stored") + } +} + +func TestFakeAnswersTheCallback(t *testing.T) { + t.Parallel() + + m := New() + m.Fake("github", &User{ID: "github-123", Name: "Jason Beggs"}) + + // Nothing on the request: no code, no state, no cookie. + user, err := m.Driver("github").User(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/cb", nil)) + if err != nil || user.ID != "github-123" { + t.Errorf("user = %+v, %v", user, err) + } +} + +func TestFakeSurvivesTheChain(t *testing.T) { + t.Parallel() + + m := manager[stub](newProviderServer(t)) + m.Fake("stub", &User{ID: "faked"}) + + d := m.Driver("stub").Scopes("x").SetScopes("y").With(map[string]string{"a": "b"}).RedirectURL("/x").Stateless() + + recorder := httptest.NewRecorder() + _ = d.Redirect(recorder, httptest.NewRequest(http.MethodGet, "/auth", nil)) + + if recorder.Header().Get("Location") != "https://sociable.fake/stub/authorize" { + t.Errorf("the chain reached the real driver: %s", recorder.Header().Get("Location")) + } + + if user, _ := d.User(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/cb", nil)); user.ID != "faked" { + t.Errorf("user = %+v", user) + } +} + +func TestFakeForwardsWhatItDoesNotFake(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + m := manager[stub](server) + m.Fake("stub") // no user + + w, r := httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/cb", nil) + + // Without a user, User is the real one: it wants a handshake. + if _, err := m.Driver("stub").User(w, r); !errors.Is(err, ErrInvalidState) { + t.Errorf("User: %v", err) + } + + if _, err := m.Driver("stub").Callback(w, r); !errors.Is(err, ErrInvalidState) { + t.Errorf("Callback: %v", err) + } + + if user, err := m.Driver("stub").UserFromToken(t.Context(), &oauth2.Token{AccessToken: "at"}); err != nil || user.ID != "42" { + t.Errorf("UserFromToken: %+v, %v", user, err) + } + + if token, err := m.Driver("stub").RefreshToken(t.Context(), "r"); err != nil || token.AccessToken != "at" { + t.Errorf("RefreshToken: %+v, %v", token, err) + } + + // Other drivers are untouched. + if _, err := m.Driver("other").User(w, r); !errors.Is(err, ErrUnknownDriver) { + t.Errorf("other driver: %v", err) + } +} diff --git a/flow.go b/flow.go deleted file mode 100644 index a5518c8..0000000 --- a/flow.go +++ /dev/null @@ -1,478 +0,0 @@ -package sociable - -import ( - "context" - "crypto/subtle" - "encoding/json" - "errors" - "fmt" - "maps" - "net/http" - "slices" - "strings" - "time" - - "golang.org/x/oauth2" -) - -// Flow is a driver bound to one request. It is a value: every method that -// shapes it returns a changed copy, so nothing leaks into the next request. -type Flow struct { - manager *Manager - name string - credentials Credentials - provider Provider - fake *Faked - err error - - scopes []string - redirect string - params map[string]string - state map[string]string - stateless bool -} - -// Scopes adds to the driver's scopes. -func (self Flow) Scopes(scopes ...string) Flow { - self.scopes = dedupe(append(self.scoped(), scopes...)) - - return self -} - -// SetScopes replaces the driver's scopes. -func (self Flow) SetScopes(scopes ...string) Flow { - self.scopes = dedupe(scopes) - - return self -} - -// RedirectURL overrides the callback for this request. -func (self Flow) RedirectURL(url string) Flow { - self.redirect = url - - return self -} - -// With adds parameters to the authorization URL: login_hint, prompt, -// access_type, whatever the provider understands. -func (self Flow) With(params map[string]string) Flow { - merged := maps.Clone(self.params) - if merged == nil { - merged = map[string]string{} - } - - for key, value := range params { - if !reserved(key) { - merged[key] = value - } - } - - self.params = merged - - return self -} - -// WithState carries values through the flow. They come back on User.State at -// the callback, and never travel through the provider. -func (self Flow) WithState(state map[string]string) Flow { - self.state = maps.Clone(state) - - return self -} - -// Stateless skips the handshake, for a callback this server did not start. -// Nothing is kept between the two steps, so PKCE is off and WithState has -// nowhere to go. -func (self Flow) Stateless() Flow { - self.stateless = true - - return self -} - -// Redirect sends the browser to the provider. -func (self Flow) Redirect(w http.ResponseWriter, r *http.Request) error { - if self.err != nil { - return self.err - } - - if self.fake != nil { - http.Redirect(w, r, self.fakeURL(), http.StatusFound) - - return nil - } - - if redirector, ok := self.provider.(Redirector); ok { - handshake, err := self.begin(w, r) - if err != nil { - return err - } - - return redirector.Redirect(w, r, self.callback(), handshake.State) - } - - url, err := self.AuthURL(w, r) - if err != nil { - return err - } - - http.Redirect(w, r, url, http.StatusFound) - - return nil -} - -// AuthURL is Redirect without the redirecting, for a handler that sends the -// browser itself. It still starts the handshake for this browser. -func (self Flow) AuthURL(w http.ResponseWriter, r *http.Request) (string, error) { - if self.err != nil { - return "", self.err - } - - if self.fake != nil { - return self.fakeURL(), nil - } - - config := self.config() - if config.ClientID == "" || config.Endpoint.AuthURL == "" || config.RedirectURL == "" { - return "", ErrNotConfigured - } - - handshake, err := self.begin(w, r) - if err != nil { - return "", err - } - - options := []oauth2.AuthCodeOption{} - if handshake.Verifier != "" { - options = append(options, oauth2.S256ChallengeOption(handshake.Verifier)) - } - if handshake.Nonce != "" { - options = append(options, oauth2.SetAuthURLParam("nonce", handshake.Nonce)) - } - for _, key := range slices.Sorted(maps.Keys(self.params)) { - options = append(options, oauth2.SetAuthURLParam(key, self.params[key])) - } - - return config.AuthCodeURL(handshake.State, options...), nil -} - -// User finishes the flow at the callback and returns the person the provider -// vouches for, with their token. -func (self Flow) User(w http.ResponseWriter, r *http.Request) (*User, error) { - if self.err != nil { - return nil, self.err - } - - if self.fake != nil { - return self.faked(), nil - } - - handshake, err := self.end(w, r) - if err != nil { - return nil, err - } - - if code := r.URL.Query().Get("error"); code != "" { - return nil, &AuthorizationError{ - Code: code, - Description: r.URL.Query().Get("error_description"), - URI: r.URL.Query().Get("error_uri"), - } - } - - var user *User - if authenticator, ok := self.provider.(Authenticator); ok { - user, err = authenticator.Callback(r) - } else { - user, err = self.exchange(r, handshake) - } - if err != nil { - return nil, err - } - - user.State = handshake.Custom - - return user, nil -} - -// UserFromToken asks the provider about a token the application already -// holds. -func (self Flow) UserFromToken(ctx context.Context, token *oauth2.Token) (*User, error) { - if self.err != nil { - return nil, self.err - } - - if self.fake != nil { - return self.faked(), nil - } - - if token == nil || token.AccessToken == "" { - return nil, fmt.Errorf("%w: no access token", ErrExchange) - } - - return self.userFor(self.context(ctx), self.config(), token, "") -} - -// RefreshToken trades a refresh token for a live token. Persist what comes -// back: it may carry a new refresh token, and the old one may be retired. -func (self Flow) RefreshToken(ctx context.Context, refreshToken string) (*oauth2.Token, error) { - if self.err != nil { - return nil, self.err - } - - if self.fake != nil { - return self.faked().Token, nil - } - - config := self.config() - if config.ClientID == "" || config.Endpoint.TokenURL == "" { - return nil, ErrNotConfigured - } - - token, err := config.TokenSource(self.context(ctx), &oauth2.Token{RefreshToken: refreshToken}).Token() - if err != nil { - return nil, fmt.Errorf("%w: %w", ErrExchange, err) - } - - return token, nil -} - -// Client is an HTTP client that presents the token to the provider's API and -// refreshes it when it can. -func (self Flow) Client(ctx context.Context, token *oauth2.Token) *http.Client { - if self.err != nil || self.fake != nil { - return oauth2.NewClient(ctx, oauth2.StaticTokenSource(token)) - } - - return self.config().Client(self.context(ctx), token) -} - -// fakeURL records the redirect on the fake and returns a URL that goes -// nowhere, the way Socialite's fake does. -func (self Flow) fakeURL() string { - self.fake.record(Redirect{ - Scopes: slices.Clone(self.scopes), - Params: maps.Clone(self.params), - State: maps.Clone(self.state), - RedirectURL: self.redirect, - }) - - return "https://sociable.fake/" + self.name + "/authorize" -} - -// faked is a copy of the fake's user, State included: a test that fakes a -// driver gives the user the state the handler expects to read. -func (self Flow) faked() *User { - user := self.fake.user - - return &user -} - -func (self Flow) begin(w http.ResponseWriter, r *http.Request) (handshake, error) { - if self.stateless { - return handshake{}, nil - } - - issued := handshake{ - State: random(32), - Custom: self.state, - ExpiresAt: time.Now().Add(handshakeLifetime), - } - - if self.usesPKCE() { - issued.Verifier = oauth2.GenerateVerifier() - } - - if self.usesNonce() { - issued.Nonce = random(32) - } - - payload, err := json.Marshal(issued) - if err != nil { - return handshake{}, err - } - - if err := self.manager.session.Put(w, r, sessionKey, string(payload)); err != nil { - return handshake{}, err - } - - return issued, nil -} - -// end reads the handshake back and checks the callback against it. The -// handshake is spent whether or not the check passes, so a failed attempt -// cannot be replayed. -func (self Flow) end(w http.ResponseWriter, r *http.Request) (handshake, error) { - if self.stateless { - return handshake{}, nil - } - - payload, err := self.manager.session.Pull(w, r, sessionKey) - if err != nil || payload == "" { - return handshake{}, ErrInvalidState - } - - var issued handshake - if err := json.Unmarshal([]byte(payload), &issued); err != nil { - return handshake{}, ErrInvalidState - } - - if issued.State == "" || time.Now().After(issued.ExpiresAt) { - return handshake{}, ErrInvalidState - } - - // A comparison that stops at the first wrong byte tells anyone who can - // time it how much of a guess was right. - if subtle.ConstantTimeCompare([]byte(issued.State), []byte(r.URL.Query().Get("state"))) != 1 { - return handshake{}, ErrInvalidState - } - - return issued, nil -} - -func (self Flow) exchange(r *http.Request, issued handshake) (*User, error) { - config := self.config() - if config.ClientID == "" || config.Endpoint.TokenURL == "" || config.RedirectURL == "" { - return nil, ErrNotConfigured - } - - ctx := self.context(r.Context()) - - options := []oauth2.AuthCodeOption{} - if issued.Verifier != "" { - options = append(options, oauth2.VerifierOption(issued.Verifier)) - } - - token, err := config.Exchange(ctx, r.URL.Query().Get("code"), options...) - if err != nil { - return nil, fmt.Errorf("%w: %w", ErrExchange, err) - } - - if token.AccessToken == "" { - return nil, fmt.Errorf("%w: the response carried no access token", ErrExchange) - } - - return self.userFor(ctx, config, token, issued.Nonce) -} - -func (self Flow) userFor(ctx context.Context, config *oauth2.Config, token *oauth2.Token, nonce string) (*User, error) { - ctx = withNonce(ctx, nonce) - - // The client presents the token and refreshes it when it can. - user, err := self.provider.User(ctx, config.Client(ctx, token), token) - if err != nil { - if errors.Is(err, ErrIDToken) { - return nil, err - } - - return nil, fmt.Errorf("%w: %w", ErrProfile, err) - } - - user.Token = token - user.ApprovedScopes = approved(token, config.Scopes) - - return user, nil -} - -// config is the provider's, with this request's changes applied to a copy. -func (self Flow) config() *oauth2.Config { - config := *self.provider.Config() - config.RedirectURL = self.callback() - - if self.scopes != nil { - config.Scopes = self.scopes - } - - return &config -} - -// callback is the redirect URL for this request, resolved against the -// application's URL when it is a path. A path with no URL to resolve against -// is nothing, which the flow reports as not configured. -func (self Flow) callback() string { - redirect := self.redirect - if redirect == "" { - redirect = self.credentials.Redirect - } - - if !strings.HasPrefix(redirect, "/") { - return redirect - } - - if self.manager.config.URL == "" { - return "" - } - - return strings.TrimSuffix(self.manager.config.URL, "/") + redirect -} - -// context carries the configured HTTP client to the oauth2 library. -func (self Flow) context(ctx context.Context) context.Context { - return context.WithValue(ctx, oauth2.HTTPClient, self.manager.config.Client) -} - -func (self Flow) scoped() []string { - if self.scopes != nil || self.provider == nil { - return slices.Clone(self.scopes) - } - - return slices.Clone(self.provider.Config().Scopes) -} - -// usesPKCE is true unless the provider says it cannot. OAuth 2.1 requires it -// of every client, so opting out is the decision that has to be written down. -func (self Flow) usesPKCE() bool { - if self.stateless { - return false - } - - unprotected, ok := self.provider.(Unprotected) - - return !ok || unprotected.UsesPKCE() -} - -// usesNonce is true for an OpenID Connect request, which is what asking for -// the openid scope makes it. -func (self Flow) usesNonce() bool { - return slices.ContainsFunc(self.scoped(), func(scope string) bool { - return strings.EqualFold(scope, "openid") - }) -} - -// approved is what the provider granted. RFC 6749 section 5.1 lets that differ -// from what was asked, and says that leaving it out means the two are equal. -func approved(token *oauth2.Token, requested []string) []string { - scope, _ := token.Extra("scope").(string) - - if fields := strings.Fields(scope); len(fields) > 0 { - return fields - } - - return requested -} - -// reserved names the parameters the flow decides. A call site that could set -// them could disable the checks the callback depends on. -func reserved(key string) bool { - switch strings.ToLower(key) { - case "state", "nonce", "code_challenge", "code_challenge_method", "client_id", "redirect_uri", "response_type", "scope": - return true - default: - return false - } -} - -func dedupe(values []string) []string { - seen := make(map[string]struct{}, len(values)) - unique := make([]string, 0, len(values)) - - for _, value := range values { - if _, done := seen[value]; done { - continue - } - - seen[value] = struct{}{} - unique = append(unique, value) - } - - return unique -} diff --git a/flow_test.go b/flow_test.go deleted file mode 100644 index 3c2676a..0000000 --- a/flow_test.go +++ /dev/null @@ -1,269 +0,0 @@ -package sociable_test - -import ( - "errors" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/gonstruct/sociable" -) - -func TestSignIn(t *testing.T) { - as := newAuthorizationServer(t) - as.scope = "profile email" - app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - - result := signIn(t, browser(t), app, "acme") - - if result.Error != "" { - t.Fatalf("sign in failed: %s", result.Error) - } - if result.User.ID != "42" || result.User.Nickname != "arjen" || result.User.Email != "arjen@example.test" { - t.Errorf("user = %+v", result.User) - } - if result.User.Token.AccessToken != "t0ken" || result.User.Token.RefreshToken != "r3fresh" { - t.Errorf("token = %+v", result.User.Token) - } - if strings.Join(result.User.ApprovedScopes, " ") != "profile email" { - t.Errorf("approved scopes = %v", result.User.ApprovedScopes) - } - - sent := as.lastRequest() - if sent.Get("code_challenge") == "" || sent.Get("code_challenge_method") != "S256" { - t.Errorf("PKCE was not on: %v", sent) - } - if sent.Get("redirect_uri") != app.URL+"/auth/acme/callback" { - t.Errorf("redirect_uri = %s", sent.Get("redirect_uri")) - } - if sent.Get("scope") != "profile" { - t.Errorf("scope = %s", sent.Get("scope")) - } -} - -func TestOptionsShapeTheAuthorizationRequest(t *testing.T) { - as := newAuthorizationServer(t) - app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - app.before = func(flow sociable.Flow) sociable.Flow { - return flow.Scopes("email").With(map[string]string{"login_hint": "arjen", "state": "overridden"}) - } - - signIn(t, browser(t), app, "acme") - - sent := as.lastRequest() - if sent.Get("scope") != "profile email" { - t.Errorf("scope = %s", sent.Get("scope")) - } - if sent.Get("login_hint") != "arjen" { - t.Errorf("login_hint = %s", sent.Get("login_hint")) - } - if sent.Get("state") == "overridden" { - t.Error("a call site could override the state") - } -} - -func TestStateTravelsThroughTheFlow(t *testing.T) { - as := newAuthorizationServer(t) - app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - app.before = func(flow sociable.Flow) sociable.Flow { - return flow.WithState(map[string]string{"user_id": "7", "domain": "example.test"}) - } - - result := signIn(t, browser(t), app, "acme") - - if result.Error != "" { - t.Fatalf("sign in failed: %s", result.Error) - } - if result.User.State["user_id"] != "7" || result.User.State["domain"] != "example.test" { - t.Errorf("state = %v", result.User.State) - } - if as.lastRequest().Has("user_id") { - t.Error("state leaked to the provider") - } -} - -func TestDenial(t *testing.T) { - as := newAuthorizationServer(t) - as.deny = true - app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - - if result := signIn(t, browser(t), app, "acme"); result.Error != "denied" { - t.Errorf("error = %q, want denied", result.Error) - } -} - -func TestACallbackCannotBeReplayed(t *testing.T) { - as := newAuthorizationServer(t) - app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - - client := browser(t) - var callback string - client.CheckRedirect = func(r *http.Request, _ []*http.Request) error { - if strings.HasSuffix(r.URL.Path, "/callback") { - callback = r.URL.String() - } - - return nil - } - - if result := signIn(t, client, app, "acme"); result.Error != "" { - t.Fatalf("first sign in failed: %s", result.Error) - } - - response, err := client.Get(callback) - if err != nil { - t.Fatal(err) - } - defer response.Body.Close() - - var result outcome - _ = decode(response, &result) - if result.Error != "state" { - t.Errorf("replay error = %q, want state", result.Error) - } -} - -func TestACallbackNobodyStartedIsRefused(t *testing.T) { - as := newAuthorizationServer(t) - app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - - response, err := browser(t).Get(app.URL + "/auth/acme/callback?code=c0de&state=guess") - if err != nil { - t.Fatal(err) - } - defer response.Body.Close() - - var result outcome - _ = decode(response, &result) - if result.Error != "state" { - t.Errorf("error = %q, want state", result.Error) - } -} - -func TestAWrongSecretFailsTheExchange(t *testing.T) { - as := newAuthorizationServer(t) - as.secret = "another" - app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - - if result := signIn(t, browser(t), app, "acme"); result.Error != "exchange" { - t.Errorf("error = %q, want exchange", result.Error) - } -} - -func TestAnUnknownDriverIsAnError(t *testing.T) { - app := newApplication(t, nil, func(*sociable.Manager) {}) - - err := app.auth.Driver("nope").Redirect(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) - if !errors.Is(err, sociable.ErrUnknownDriver) { - t.Errorf("err = %v", err) - } - - // Configured, but no provider of that name. - app2 := newApplication(t, func(config *sociable.Config) { - config.Drivers["mystery"] = sociable.Credentials{ClientID: "x"} - }, func(*sociable.Manager) {}) - - err = app2.auth.Driver("mystery").Redirect(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) - if !errors.Is(err, sociable.ErrUnknownDriver) { - t.Errorf("err = %v", err) - } -} - -func TestAnApplicationSessionReplacesTheCookie(t *testing.T) { - as := newAuthorizationServer(t) - session := &memorySession{values: map[string]string{}} - app := newApplication(t, func(config *sociable.Config) { - config.Key = "" - config.Session = session - }, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - - client := browser(t) - if result := signIn(t, client, app, "acme"); result.Error != "" { - t.Fatalf("sign in failed: %s", result.Error) - } - - if session.puts != 1 || session.pulls != 1 { - t.Errorf("session saw %d puts and %d pulls", session.puts, session.pulls) - } - - for _, cookie := range client.Jar.Cookies(mustParse(app.URL)) { - if cookie.Name == "sociable" { - t.Error("a cookie was set alongside the session") - } - } -} - -func TestStatelessSkipsTheHandshake(t *testing.T) { - as := newAuthorizationServer(t) - app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - app.before = func(flow sociable.Flow) sociable.Flow { return flow.Stateless() } - - response, err := browser(t).Get(app.URL + "/auth/acme/callback?code=c0de") - if err != nil { - t.Fatal(err) - } - defer response.Body.Close() - - var result outcome - _ = decode(response, &result) - if result.Error != "" || result.User.ID != "42" { - t.Errorf("result = %+v", result) - } -} - -func TestFake(t *testing.T) { - app := newApplication(t, nil, func(auth *sociable.Manager) { - auth.Fake("github", sociable.User{ID: "1", Email: "arjen@example.test"}) - }) - - // The redirect goes nowhere real; a test calls the callback directly. - recorder := httptest.NewRecorder() - if err := app.auth.Driver("github").Redirect(recorder, httptest.NewRequest(http.MethodGet, "/auth/github", nil)); err != nil { - t.Fatal(err) - } - if location := recorder.Header().Get("Location"); location != "https://sociable.fake/github/authorize" { - t.Errorf("redirected to %s", location) - } - - response, err := browser(t).Get(app.URL + "/auth/github/callback") - if err != nil { - t.Fatal(err) - } - defer response.Body.Close() - - var result outcome - _ = decode(response, &result) - if result.Error != "" { - t.Fatalf("callback failed: %s", result.Error) - } - if result.User.ID != "1" || result.User.Email != "arjen@example.test" || result.User.Token.AccessToken != "fake-token" { - t.Errorf("user = %+v", result.User) - } -} - -func TestConfigureRequiresSomewhereToKeepTheHandshake(t *testing.T) { - if _, err := sociable.New(sociable.Config{}); !errors.Is(err, sociable.ErrNoKey) { - t.Errorf("err = %v", err) - } -} - -type memorySession struct { - values map[string]string - puts, pulls int -} - -func (self *memorySession) Put(_ http.ResponseWriter, _ *http.Request, key, value string) error { - self.puts++ - self.values[key] = value - - return nil -} - -func (self *memorySession) Pull(_ http.ResponseWriter, _ *http.Request, key string) (string, error) { - self.pulls++ - value := self.values[key] - delete(self.values, key) - - return value, nil -} diff --git a/go.mod b/go.mod index e8cf6e2..79210b7 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,11 @@ go 1.26.0 require ( github.com/coreos/go-oidc/v3 v3.21.0 - github.com/go-jose/go-jose/v4 v4.1.5 + github.com/valyala/fastjson v1.6.10 golang.org/x/oauth2 v0.37.0 ) + +require ( + cloud.google.com/go/compute/metadata v0.3.0 // indirect + github.com/go-jose/go-jose/v4 v4.1.4 // indirect +) diff --git a/go.sum b/go.sum index 60726c4..4ba7d25 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,10 @@ +cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc= +cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM= github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= -github.com/go-jose/go-jose/v4 v4.1.5 h1:RjgjO2LOtWOJKUC5wpwY9LR3B3vwVAz6JS2YHfYU6eA= -github.com/go-jose/go-jose/v4 v4.1.5/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4= +github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE= golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= diff --git a/helpers.go b/helpers.go new file mode 100644 index 0000000..367e2df --- /dev/null +++ b/helpers.go @@ -0,0 +1,15 @@ +package sociable + +import ( + "crypto/rand" + "encoding/base64" +) + +// random is an unguessable string of size bytes. rand.Read cannot fail since +// Go 1.24, so there is no error to handle. +func random(size int) string { + buffer := make([]byte, size) + _, _ = rand.Read(buffer) + + return base64.RawURLEncoding.EncodeToString(buffer) +} diff --git a/helpers_test.go b/helpers_test.go index 089454b..45340b1 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -1,240 +1,319 @@ -package sociable_test +package sociable import ( + "context" + "crypto" + "crypto/rand" + "crypto/rsa" "crypto/sha256" "encoding/base64" "encoding/json" "errors" + "math/big" "net/http" - "net/http/cookiejar" "net/http/httptest" "net/url" - "sync" "testing" + "time" - "github.com/gonstruct/sociable" + "github.com/valyala/fastjson" "golang.org/x/oauth2" ) -// authorizationServer is a fake provider: it hands out a code, exchanges it for -// a token when the PKCE verifier and the secret are right, and serves a -// profile to a bearer of that token. -type authorizationServer struct { +// stub is a provider whose endpoints and profile live at Credentials.BaseURL, +// so every test points it at a server of its own. +type stub struct{} + +func (stub) Endpoint(c Credentials) oauth2.Endpoint { + return oauth2.Endpoint{AuthURL: c.BaseURL + "/auth", TokenURL: c.BaseURL + "/token"} +} + +func (stub) Scoping() Scoping { return Scoping{Scopes: []string{"a", "b"}, Separator: " "} } + +func (stub) GetUserByToken(ctx context.Context, client *http.Client, _ *oauth2.Token, c Credentials) (*fastjson.Value, error) { + return fetch(ctx, client, c.BaseURL+"/user", nil) +} + +func (stub) MapUserToStruct(json *fastjson.Value) (*User, error) { + return &User{ID: string(json.GetStringBytes("id")), Name: string(json.GetStringBytes("name"))}, nil +} + +// commaStub separates scopes with a comma. +type commaStub struct{ stub } + +func (commaStub) Scoping() Scoping { return Scoping{Scopes: []string{"a", "b"}, Separator: ","} } + +// noPKCEStub cannot do PKCE. +type noPKCEStub struct{ stub } + +func (noPKCEStub) UsesPKCE() bool { return false } + +// openidStub asks for openid and names the issuer the OIDC tests serve. +type openidStub struct{ stub } + +func (openidStub) Scoping() Scoping { return Scoping{Scopes: []string{"openid", "a"}, Separator: " "} } +func (openidStub) Issuer() string { return oidcIssuer } + +// oidcIssuer is set by the one test group that serves an issuer. Those tests +// do not run in parallel. +var oidcIssuer string + +// badMapStub cannot map. +type badMapStub struct{ stub } + +func (badMapStub) MapUserToStruct(*fastjson.Value) (*User, error) { return nil, errors.New("no map") } + +// providerServer answers the token and profile calls a driver makes. +type providerServer struct { *httptest.Server - mutex sync.Mutex - secret string - challenge string - scope string - profile map[string]any - deny bool - requests []url.Values + token map[string]any // the token response; nil answers 400 + profile map[string]any // the profile document; nil answers 500 + form url.Values // what the last token request posted + auth string // the Authorization header on the last profile call } -func newAuthorizationServer(t *testing.T) *authorizationServer { +func newProviderServer(t *testing.T) *providerServer { t.Helper() - as := &authorizationServer{ - secret: "s3cret", - profile: map[string]any{"id": float64(42), "login": "arjen", "email": "arjen@example.test"}, + server := &providerServer{ + token: map[string]any{"access_token": "at", "token_type": "bearer", "scope": "a b"}, + profile: map[string]any{"id": "42", "name": "Test User"}, } - mux := http.NewServeMux() - mux.HandleFunc("/authorize", as.authorize) - mux.HandleFunc("/token", as.token) - mux.HandleFunc("/me", as.me) + server.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") - as.Server = httptest.NewServer(mux) - t.Cleanup(as.Close) + switch r.URL.Path { + case "/token": + _ = r.ParseForm() + server.form = r.PostForm + + if server.token == nil { + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(map[string]any{"error": "invalid_grant"}) + return + } + + _ = json.NewEncoder(w).Encode(server.token) + case "/user": + server.auth = r.Header.Get("Authorization") + + if server.profile == nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + + _ = json.NewEncoder(w).Encode(server.profile) + default: + http.NotFound(w, r) + } + })) - return as + t.Cleanup(server.Close) + + return server } -func (as *authorizationServer) authorize(w http.ResponseWriter, r *http.Request) { - as.mutex.Lock() - as.requests = append(as.requests, r.URL.Query()) - as.challenge = r.URL.Query().Get("code_challenge") - as.mutex.Unlock() +// manager is a Manager with one driver, "stub", pointed at the server. +func manager[T Provider](server *providerServer, options ...option) *Manager { + return New(append([]option{ + WithKey("test-key"), + WithAPIURL("https://app.example"), + WithDriver[T]("stub", Credentials{ClientID: "id", ClientSecret: "secret", BaseURL: server.URL, RedirectURL: "/cb"}), + }, options...)...) +} - back, _ := url.Parse(r.URL.Query().Get("redirect_uri")) - query := url.Values{"state": {r.URL.Query().Get("state")}} +// redirected runs Redirect and hands back the auth URL's query and the +// cookies that were set. +func redirected(t *testing.T, d DriverContract) (url.Values, []*http.Cookie) { + t.Helper() - if as.deny { - query.Set("error", "access_denied") - query.Set("error_description", "the person said no") - } else { - query.Set("code", "c0de") + recorder := httptest.NewRecorder() + if err := d.Redirect(recorder, httptest.NewRequest(http.MethodGet, "/auth", nil)); err != nil { + t.Fatalf("redirect: %v", err) } - back.RawQuery = query.Encode() - http.Redirect(w, r, back.String(), http.StatusFound) -} + if recorder.Code != http.StatusFound { + t.Fatalf("redirect status %d", recorder.Code) + } -func (as *authorizationServer) token(w http.ResponseWriter, r *http.Request) { - _ = r.ParseForm() + location, err := url.Parse(recorder.Header().Get("Location")) + if err != nil { + t.Fatal(err) + } - if r.PostForm.Get("code") != "c0de" || r.PostForm.Get("client_secret") != as.secret { - http.Error(w, `{"error":"invalid_grant"}`, http.StatusBadRequest) + return location.Query(), recorder.Result().Cookies() +} - return +// callback is the request the provider sends the browser back with, carrying +// the cookies from the redirect. +func callback(query string, cookies []*http.Cookie) *http.Request { + request := httptest.NewRequest(http.MethodGet, "/cb?"+query, nil) + for _, cookie := range cookies { + request.AddCookie(cookie) } - as.mutex.Lock() - challenge := as.challenge - as.mutex.Unlock() + return request +} - if challenge != "" { - sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier"))) - if base64.RawURLEncoding.EncodeToString(sum[:]) != challenge { - http.Error(w, `{"error":"invalid_grant","error_description":"bad verifier"}`, http.StatusBadRequest) +// signIn runs the whole flow against the driver and returns what User gave. +func signIn(t *testing.T, d DriverContract) (*User, error) { + t.Helper() - return - } - } + query, cookies := redirected(t, d) - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]any{ - "access_token": "t0ken", "token_type": "bearer", "refresh_token": "r3fresh", "expires_in": 3600, "scope": as.scope, - }) + return d.User(httptest.NewRecorder(), callback("code=c&state="+query.Get("state"), cookies)) } -func (as *authorizationServer) me(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Authorization") != "Bearer t0ken" { - http.Error(w, "unauthorized", http.StatusUnauthorized) +// rewriting sends every request to the test server, whatever host the +// provider hard-coded, keeping the path. +type rewriting struct{ to *url.URL } - return - } +func (self rewriting) RoundTrip(request *http.Request) (*http.Response, error) { + request.URL.Scheme = self.to.Scheme + request.URL.Host = self.to.Host - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(as.profile) + return http.DefaultTransport.RoundTrip(request) } -func (as *authorizationServer) lastRequest() url.Values { - as.mutex.Lock() - defer as.mutex.Unlock() +// rewritingClient is a client that talks to the given handler regardless of +// URL, and records the last request it saw. +func rewritingClient(t *testing.T, handler http.HandlerFunc) (*http.Client, *http.Request) { + t.Helper() + + var last http.Request - return as.requests[len(as.requests)-1] + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + last = *r + last.Header = r.Header.Clone() + w.Header().Set("Content-Type", "application/json") + handler(w, r) + })) + t.Cleanup(server.Close) + + to, _ := url.Parse(server.URL) + + return &http.Client{Transport: rewriting{to: to}}, &last } -func (as *authorizationServer) factory() sociable.Factory { - return func(credentials sociable.Credentials) sociable.Provider { - return sociable.OAuth2{ - Credentials: credentials, - Endpoint: oauth2.Endpoint{AuthURL: as.URL + "/authorize", TokenURL: as.URL + "/token"}, - Scopes: []string{"profile"}, - ProfileURL: as.URL + "/me", - Map: func(raw map[string]any) sociable.User { - return sociable.User{ID: sociable.String(raw, "id"), Nickname: sociable.String(raw, "login"), Email: sociable.String(raw, "email")} - }, - } - } +func encode(document any) http.HandlerFunc { + return func(w http.ResponseWriter, _ *http.Request) { _ = json.NewEncoder(w).Encode(document) } } -// application is a site with the two handlers, answering the callback with the -// user or the error as JSON so a test can read what happened. -type application struct { +// issuer is a fake OpenID Connect issuer: discovery, a key set, and ID tokens +// signed with its key. +type issuer struct { *httptest.Server - auth *sociable.Manager - before func(sociable.Flow) sociable.Flow + key *rsa.PrivateKey } -type outcome struct { - User *sociable.User `json:"user"` - Error string `json:"error"` -} - -func newApplication(t *testing.T, configure func(config *sociable.Config), extend func(auth *sociable.Manager)) *application { +func newIssuer(t *testing.T) *issuer { t.Helper() - app := &application{before: func(flow sociable.Flow) sociable.Flow { return flow }} + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } - mux := http.NewServeMux() - mux.HandleFunc("/auth/{driver}", func(w http.ResponseWriter, r *http.Request) { - if err := app.before(app.auth.Driver(r.PathValue("driver"))).Redirect(w, r); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - } - }) - mux.HandleFunc("/auth/{driver}/callback", func(w http.ResponseWriter, r *http.Request) { - user, err := app.before(app.auth.Driver(r.PathValue("driver"))).User(w, r) + self := &issuer{key: key} + self.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") - if err != nil { - _ = json.NewEncoder(w).Encode(outcome{Error: classify(err)}) - - return + switch r.URL.Path { + case "/.well-known/openid-configuration": + _ = json.NewEncoder(w).Encode(map[string]any{ + "issuer": self.URL, + "authorization_endpoint": self.URL + "/auth", + "token_endpoint": self.URL + "/token", + "jwks_uri": self.URL + "/keys", + "id_token_signing_alg_values_supported": []string{"RS256"}, + }) + case "/keys": + _ = json.NewEncoder(w).Encode(map[string]any{"keys": []map[string]any{{ + "kty": "RSA", "kid": "k", "alg": "RS256", "use": "sig", + "n": base64.RawURLEncoding.EncodeToString(key.PublicKey.N.Bytes()), + "e": base64.RawURLEncoding.EncodeToString(big.NewInt(int64(key.PublicKey.E)).Bytes()), + }}}) + default: + http.NotFound(w, r) } + })) - _ = json.NewEncoder(w).Encode(outcome{User: user}) - }) + t.Cleanup(self.Close) - app.Server = httptest.NewServer(mux) - t.Cleanup(app.Close) + return self +} - config := sociable.Config{ - Key: "test-key", - URL: app.URL, - Drivers: sociable.Drivers{ - "acme": {ClientID: "client", ClientSecret: "s3cret", Redirect: "/auth/acme/callback"}, - }, - } - if configure != nil { - configure(&config) +// idToken is a signed ID token for the audience with the nonce. Signed with +// another key, it does not verify. +func (self *issuer) idToken(t *testing.T, audience, nonce string, key *rsa.PrivateKey) string { + t.Helper() + + if key == nil { + key = self.key } - auth, err := sociable.New(config) + header, _ := json.Marshal(map[string]string{"alg": "RS256", "kid": "k"}) + claims, _ := json.Marshal(map[string]any{ + "iss": self.URL, "aud": audience, "sub": "sub-1", "nonce": nonce, + "iat": time.Now().Unix(), "exp": time.Now().Add(time.Hour).Unix(), + }) + + signing := base64.RawURLEncoding.EncodeToString(header) + "." + base64.RawURLEncoding.EncodeToString(claims) + digest := sha256.Sum256([]byte(signing)) + + signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:]) if err != nil { - t.Fatalf("New: %v", err) + t.Fatal(err) } - app.auth = auth - extend(auth) - - return app -} - -func classify(err error) string { - switch { - case errors.Is(err, sociable.ErrAccessDenied): - return "denied" - case errors.Is(err, sociable.ErrInvalidState): - return "state" - case errors.Is(err, sociable.ErrExchange): - return "exchange" - case errors.Is(err, sociable.ErrIDToken): - return "idtoken" - case errors.Is(err, sociable.ErrUnknownDriver): - return "unknown" - default: - return err.Error() - } + return signing + "." + base64.RawURLEncoding.EncodeToString(signature) } -func browser(t *testing.T) *http.Client { +// handshakeFrom opens the handshake the redirect stored in the cookies. +func handshakeFrom(t *testing.T, cookies []*http.Cookie) handshake { t.Helper() - jar, err := cookiejar.New(nil) + session, err := newCookieSession("test-key", false) if err != nil { t.Fatal(err) } - return &http.Client{Jar: jar} + payload, err := session.Pull(httptest.NewRecorder(), callback("", cookies), sessionKey) + if err != nil { + t.Fatal(err) + } + + var issued handshake + if err := json.Unmarshal([]byte(payload), &issued); err != nil { + t.Fatal(err) + } + + return issued } -func signIn(t *testing.T, client *http.Client, app *application, driver string) outcome { - t.Helper() +// memorySession is a Session of the application's own. +type memorySession struct { + values map[string]string + putErr error +} - response, err := client.Get(app.URL + "/auth/" + driver) - if err != nil { - t.Fatalf("sign in: %v", err) +func (self *memorySession) Put(_ http.ResponseWriter, _ *http.Request, key, value string) error { + if self.putErr != nil { + return self.putErr } - defer response.Body.Close() - var result outcome - if err := json.NewDecoder(response.Body).Decode(&result); err != nil { - t.Fatalf("decode outcome: %v", err) - } + self.values[key] = value + + return nil +} + +func (self *memorySession) Pull(_ http.ResponseWriter, _ *http.Request, key string) (string, error) { + value := self.values[key] + delete(self.values, key) - return result + return value, nil } diff --git a/openid.go b/openid.go deleted file mode 100644 index 1057f9f..0000000 --- a/openid.go +++ /dev/null @@ -1,120 +0,0 @@ -package sociable - -import ( - "context" - "fmt" - "net/http" - "sync" - - "github.com/coreos/go-oidc/v3/oidc" - "golang.org/x/oauth2" -) - -// OpenID is a provider for any OpenID Connect issuer. Endpoints and signing -// keys come from discovery, and the identity from an ID token verified for its -// signature, issuer, audience, expiry and nonce. -// -// sociable.Extend("okta", func(c sociable.Credentials) sociable.Provider { -// return sociable.OpenID(c, "https://acme.okta.com") -// }) -func OpenID(credentials Credentials, issuer string) Provider { - return &openID{credentials: credentials, issuer: issuer} -} - -type openID struct { - credentials Credentials - issuer string - - once sync.Once - discovered *oidc.Provider - discovery error -} - -// Config is the endpoints from discovery. When discovery failed the endpoints -// are empty, and the flow reports the driver as not configured. -func (self *openID) Config() *oauth2.Config { - scopes := self.credentials.Scopes - if len(scopes) == 0 { - scopes = []string{"openid", "email", "profile"} - } - - config := &oauth2.Config{ - ClientID: self.credentials.ClientID, - ClientSecret: self.credentials.ClientSecret, - Scopes: scopes, - } - - if provider := self.provider(); provider != nil { - config.Endpoint = provider.Endpoint() - } - - return config -} - -func (self *openID) User(ctx context.Context, _ *http.Client, token *oauth2.Token) (*User, error) { - raw, _ := token.Extra("id_token").(string) - if raw == "" { - return nil, fmt.Errorf("%w: the token response carried no id_token", ErrIDToken) - } - - provider := self.provider() - if provider == nil { - return nil, fmt.Errorf("%w: discovery failed: %w", ErrIDToken, self.discovery) - } - - verified, err := provider.Verifier(&oidc.Config{ClientID: self.credentials.ClientID}).Verify(ctx, raw) - if err != nil { - return nil, fmt.Errorf("%w: %w", ErrIDToken, err) - } - - if nonce := nonceFrom(ctx); nonce != "" && verified.Nonce != nonce { - return nil, fmt.Errorf("%w: nonce does not match", ErrIDToken) - } - - var claims map[string]any - if err := verified.Claims(&claims); err != nil { - return nil, fmt.Errorf("%w: %w", ErrIDToken, err) - } - - user := Claims(claims) - - return &user, nil -} - -func (self *openID) provider() *oidc.Provider { - self.once.Do(func() { - self.discovered, self.discovery = oidc.NewProvider(context.Background(), self.issuer) - }) - - return self.discovered -} - -// Claims is the standard mapping of OpenID Connect claims to a User. -func Claims(claims map[string]any) User { - nickname := String(claims, "preferred_username") - if nickname == "" { - nickname = String(claims, "given_name") - } - - return User{ - ID: String(claims, "sub"), - Nickname: nickname, - Name: String(claims, "name"), - Email: String(claims, "email"), - EmailVerified: Bool(claims, "email_verified"), - Avatar: String(claims, "picture"), - Raw: claims, - } -} - -type nonceKey struct{} - -func withNonce(ctx context.Context, nonce string) context.Context { - return context.WithValue(ctx, nonceKey{}, nonce) -} - -func nonceFrom(ctx context.Context) string { - nonce, _ := ctx.Value(nonceKey{}).(string) - - return nonce -} diff --git a/openid_test.go b/openid_test.go deleted file mode 100644 index 0303d63..0000000 --- a/openid_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package sociable_test - -import ( - "crypto/rand" - "crypto/rsa" - "encoding/json" - "net/http" - "net/http/httptest" - "net/url" - "testing" - "time" - - "github.com/go-jose/go-jose/v4" - "github.com/go-jose/go-jose/v4/jwt" - "github.com/gonstruct/sociable" -) - -// issuer is a fake OpenID Connect provider: discovery, a key set, an -// authorization endpoint that echoes the nonce, and a token endpoint that -// signs an ID token with it. -type issuer struct { - *httptest.Server - - key *rsa.PrivateKey - audience string - nonce string - claims map[string]any -} - -func newIssuer(t *testing.T) *issuer { - t.Helper() - - key, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - t.Fatal(err) - } - - op := &issuer{key: key, audience: "client"} - - mux := http.NewServeMux() - mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) { - _ = json.NewEncoder(w).Encode(map[string]any{ - "issuer": op.URL, - "authorization_endpoint": op.URL + "/authorize", - "token_endpoint": op.URL + "/token", - "jwks_uri": op.URL + "/keys", - "id_token_signing_alg_values_supported": []string{"RS256"}, - }) - }) - mux.HandleFunc("/keys", func(w http.ResponseWriter, _ *http.Request) { - _ = json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &key.PublicKey, KeyID: "k1", Algorithm: "RS256", Use: "sig"}}}) - }) - mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) { - op.nonce = r.URL.Query().Get("nonce") - back, _ := url.Parse(r.URL.Query().Get("redirect_uri")) - back.RawQuery = url.Values{"code": {"c0de"}, "state": {r.URL.Query().Get("state")}}.Encode() - http.Redirect(w, r, back.String(), http.StatusFound) - }) - mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]any{"access_token": "t0ken", "token_type": "bearer", "id_token": op.idToken(t)}) - }) - - op.Server = httptest.NewServer(mux) - t.Cleanup(op.Close) - - return op -} - -func (op *issuer) idToken(t *testing.T) string { - t.Helper() - - signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: op.key}, (&jose.SignerOptions{}).WithHeader("kid", "k1")) - if err != nil { - t.Fatal(err) - } - - claims := map[string]any{ - "iss": op.URL, "aud": op.audience, "sub": "google-123", "exp": time.Now().Add(time.Hour).Unix(), "iat": time.Now().Unix(), - "nonce": op.nonce, "email": "arjen@example.test", "email_verified": true, "name": "Arjen", "picture": "https://example.test/a.png", - } - for key, value := range op.claims { - claims[key] = value - } - - token, err := jwt.Signed(signer).Claims(claims).Serialize() - if err != nil { - t.Fatal(err) - } - - return token -} - -func (op *issuer) factory() sociable.Factory { - return func(credentials sociable.Credentials) sociable.Provider { return sociable.OpenID(credentials, op.URL) } -} - -func TestOpenIDSignsInFromAVerifiedIDToken(t *testing.T) { - op := newIssuer(t) - app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", op.factory()) }) - - result := signIn(t, browser(t), app, "acme") - - if result.Error != "" { - t.Fatalf("sign in failed: %s", result.Error) - } - if result.User.ID != "google-123" || result.User.Email != "arjen@example.test" || !result.User.EmailVerified || result.User.Name != "Arjen" { - t.Errorf("user = %+v", result.User) - } - if op.nonce == "" { - t.Error("no nonce was sent") - } -} - -func TestOpenIDRefusesAnIDTokenForAnotherAudience(t *testing.T) { - op := newIssuer(t) - op.audience = "somebody-else" - app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", op.factory()) }) - - if result := signIn(t, browser(t), app, "acme"); result.Error != "idtoken" { - t.Errorf("error = %q, want idtoken", result.Error) - } -} - -func TestOpenIDRefusesAnIDTokenWithAnotherNonce(t *testing.T) { - op := newIssuer(t) - op.claims = map[string]any{"nonce": "replayed"} - app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", op.factory()) }) - - if result := signIn(t, browser(t), app, "acme"); result.Error != "idtoken" { - t.Errorf("error = %q, want idtoken", result.Error) - } -} diff --git a/provider.bitbucket.go b/provider.bitbucket.go new file mode 100644 index 0000000..3f83a12 --- /dev/null +++ b/provider.bitbucket.go @@ -0,0 +1,63 @@ +package sociable + +import ( + "context" + "net/http" + + "github.com/valyala/fastjson" + "golang.org/x/oauth2" + "golang.org/x/oauth2/endpoints" +) + +// BitbucketProvider reads the user document and the primary confirmed +// address from the emails endpoint, which is the only place Bitbucket puts +// it. +type BitbucketProvider struct{} + +func (self BitbucketProvider) Endpoint(Credentials) oauth2.Endpoint { + return endpoints.Bitbucket +} + +func (self BitbucketProvider) Scoping() Scoping { + return Scoping{ + Scopes: []string{"email"}, + Separator: " ", + } +} + +func (self BitbucketProvider) GetUserByToken(ctx context.Context, client *http.Client, _ *oauth2.Token, _ Credentials) (*fastjson.Value, error) { + profile, err := fetch(ctx, client, "https://api.bitbucket.org/2.0/user", nil) + if err != nil { + return nil, err + } + + emails, err := fetch(ctx, client, "https://api.bitbucket.org/2.0/user/emails", nil) + if err != nil { + return nil, err + } + + var arena fastjson.Arena + + for _, email := range emails.GetArray("values") { + if email.GetBool("is_primary") && email.GetBool("is_confirmed") { + profile.Set("email", arena.NewStringBytes(email.GetStringBytes("email"))) + + break + } + } + + return profile, nil +} + +func (self BitbucketProvider) MapUserToStruct(json *fastjson.Value) (*User, error) { + email := string(json.GetStringBytes("email")) + + return &User{ + ID: string(json.GetStringBytes("uuid")), + Nickname: string(json.GetStringBytes("username")), + Name: string(json.GetStringBytes("display_name")), + Email: email, + EmailVerified: email != "", + Avatar: string(json.GetStringBytes("links", "avatar", "href")), + }, nil +} diff --git a/provider.facebook.go b/provider.facebook.go new file mode 100644 index 0000000..c46193c --- /dev/null +++ b/provider.facebook.go @@ -0,0 +1,52 @@ +package sociable + +import ( + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "net/http" + + "github.com/valyala/fastjson" + "golang.org/x/oauth2" + "golang.org/x/oauth2/endpoints" +) + +// FacebookProvider reads the Graph API's me document, with the +// appsecret_proof Facebook asks for from server-side apps. +type FacebookProvider struct{} + +func (self FacebookProvider) Endpoint(Credentials) oauth2.Endpoint { + return endpoints.Facebook +} + +func (self FacebookProvider) Scoping() Scoping { + return Scoping{ + Scopes: []string{"email"}, + Separator: ",", + } +} + +func (self FacebookProvider) GetUserByToken(ctx context.Context, client *http.Client, token *oauth2.Token, credentials Credentials) (*fastjson.Value, error) { + url := "https://graph.facebook.com/v22.0/me?fields=id,name,email,picture.width(1920)" + + if credentials.ClientSecret != "" { + mac := hmac.New(sha256.New, []byte(credentials.ClientSecret)) + mac.Write([]byte(token.AccessToken)) + url += "&appsecret_proof=" + hex.EncodeToString(mac.Sum(nil)) + } + + return fetch(ctx, client, url, nil) +} + +func (self FacebookProvider) MapUserToStruct(json *fastjson.Value) (*User, error) { + email := string(json.GetStringBytes("email")) + + return &User{ + ID: string(json.GetStringBytes("id")), + Name: string(json.GetStringBytes("name")), + Email: email, + EmailVerified: email != "", + Avatar: string(json.GetStringBytes("picture", "data", "url")), + }, nil +} diff --git a/provider.github.go b/provider.github.go new file mode 100644 index 0000000..253cc60 --- /dev/null +++ b/provider.github.go @@ -0,0 +1,69 @@ +package sociable + +import ( + "context" + "net/http" + "strconv" + + "github.com/valyala/fastjson" + "golang.org/x/oauth2" + "golang.org/x/oauth2/endpoints" +) + +// GitHubProvider reads the profile and, when the profile hides the address, +// the primary verified one from the emails endpoint. +type GitHubProvider struct{} + +func (self GitHubProvider) Endpoint(Credentials) oauth2.Endpoint { + return endpoints.GitHub +} + +func (self GitHubProvider) Scoping() Scoping { + return Scoping{ + Scopes: []string{"read:user", "user:email"}, + Separator: " ", + } +} + +func (self GitHubProvider) GetUserByToken(ctx context.Context, client *http.Client, _ *oauth2.Token, _ Credentials) (*fastjson.Value, error) { + headers := map[string]string{"Accept": "application/vnd.github+json"} + + profile, err := fetch(ctx, client, "https://api.github.com/user", headers) + if err != nil { + return nil, err + } + + if len(profile.GetStringBytes("email")) > 0 { + return profile, nil + } + + emails, err := fetch(ctx, client, "https://api.github.com/user/emails", headers) + if err != nil { + return nil, err + } + + var arena fastjson.Arena + + for _, email := range emails.GetArray() { + if email.GetBool("primary") && email.GetBool("verified") { + profile.Set("email", arena.NewStringBytes(email.GetStringBytes("email"))) + + break + } + } + + return profile, nil +} + +func (self GitHubProvider) MapUserToStruct(json *fastjson.Value) (*User, error) { + email := string(json.GetStringBytes("email")) + + return &User{ + ID: strconv.FormatInt(json.GetInt64("id"), 10), + Nickname: string(json.GetStringBytes("login")), + Name: string(json.GetStringBytes("name")), + Email: email, + EmailVerified: email != "", + Avatar: string(json.GetStringBytes("avatar_url")), + }, nil +} diff --git a/provider.gitlab.go b/provider.gitlab.go new file mode 100644 index 0000000..12ac469 --- /dev/null +++ b/provider.gitlab.go @@ -0,0 +1,56 @@ +package sociable + +import ( + "context" + "net/http" + "strconv" + "strings" + + "github.com/valyala/fastjson" + "golang.org/x/oauth2" +) + +// GitLabProvider signs in against gitlab.com, or a self-hosted instance +// given as BaseURL. +type GitLabProvider struct{} + +func (self GitLabProvider) host(credentials Credentials) string { + if credentials.BaseURL != "" { + return strings.TrimSuffix(credentials.BaseURL, "/") + } + + return "https://gitlab.com" +} + +func (self GitLabProvider) Endpoint(credentials Credentials) oauth2.Endpoint { + host := self.host(credentials) + + return oauth2.Endpoint{ + AuthURL: host + "/oauth/authorize", + TokenURL: host + "/oauth/token", + } +} + +func (self GitLabProvider) Scoping() Scoping { + return Scoping{ + Scopes: []string{"read_user"}, + Separator: " ", + } +} + +func (self GitLabProvider) GetUserByToken(ctx context.Context, client *http.Client, _ *oauth2.Token, credentials Credentials) (*fastjson.Value, error) { + return fetch(ctx, client, self.host(credentials)+"/api/v4/user", nil) +} + +func (self GitLabProvider) MapUserToStruct(json *fastjson.Value) (*User, error) { + email := string(json.GetStringBytes("email")) + + return &User{ + ID: strconv.FormatInt(json.GetInt64("id"), 10), + Nickname: string(json.GetStringBytes("username")), + Name: string(json.GetStringBytes("name")), + Email: email, + EmailVerified: email != "", + Avatar: string(json.GetStringBytes("avatar_url")), + }, nil +} diff --git a/provider.go b/provider.go index a084824..665e1ee 100644 --- a/provider.go +++ b/provider.go @@ -2,164 +2,98 @@ package sociable import ( "context" - "encoding/json" "fmt" + "io" "net/http" - "strconv" - "strings" + "github.com/valyala/fastjson" "golang.org/x/oauth2" ) -// Provider is what a driver is made of: the oauth2 configuration it was -// issued, and how to read the person behind a token. The flow around those two -// things is this package's. -// -// The client already presents the token, so a provider reads its profile -// with a plain Get. +// Provider is what a driver is made of, Socialite's four abstract methods: +// where to send the browser, what to ask for, how to read the raw document +// behind a token, and how to map it. The provider is a zero value, so what +// it needs to know comes in through the credentials. type Provider interface { - Config() *oauth2.Config - User(ctx context.Context, client *http.Client, token *oauth2.Token) (*User, error) -} + Endpoint(credentials Credentials) oauth2.Endpoint + Scoping() Scoping -// Factory builds a Provider from the credentials configured under its name. -type Factory func(credentials Credentials) Provider + // GetUserByToken fetches the provider's document for the person. The + // client already presents the token, the way Socialite's getHttpClient + // does. Socialite's getUserByToken. + GetUserByToken(ctx context.Context, client *http.Client, token *oauth2.Token, credentials Credentials) (*fastjson.Value, error) -// Redirector is a provider that sends the browser itself, for a sign-in that -// is not an authorization URL: a widget, a form. It receives the callback URL -// and the state the callback must bring back. -type Redirector interface { - Redirect(w http.ResponseWriter, r *http.Request, callback, state string) error + // MapUserToStruct turns that document into a User. The driver calls it, + // and fills in the token afterwards. Socialite's mapUserToObject. + MapUserToStruct(json *fastjson.Value) (*User, error) } -// Authenticator is a provider that reads the person from the callback itself, -// with no code to exchange. -type Authenticator interface { - Callback(r *http.Request) (*User, error) +type Scoping struct { + Scopes []string + Separator string } -// Unprotected is a provider that cannot do PKCE. Every provider that stays -// silent does it. -type Unprotected interface { - UsesPKCE() bool +// User is who the provider vouches for. +type User struct { + // ID is the provider's stable identifier for this person. Store this, + // not the email, which can change. + ID string + + Nickname string + Name string + Email string + EmailVerified bool + Avatar string + + // Token carries the access token, the refresh token when the provider + // issued one, and the expiry. + Token *oauth2.Token + + // ApprovedScopes are the scopes the provider granted, which need not be + // the ones that were asked for. + ApprovedScopes []string } -// OAuth2 is a provider described by its endpoints and a profile mapping, which -// is all most providers need. -type OAuth2 struct { - Credentials Credentials - Endpoint oauth2.Endpoint - - // Scopes are the defaults, for credentials that name none. - Scopes []string - - // ProfileURL is fetched with the token, and Map turns the document into a - // User. Raw is filled in when Map leaves it empty, or when there is no - // Map at all. - ProfileURL string - Map func(raw map[string]any) User - - WithoutPKCE bool -} - -func (self OAuth2) Config() *oauth2.Config { - scopes := self.Credentials.Scopes - if len(scopes) == 0 { - scopes = self.Scopes - } - - return &oauth2.Config{ - ClientID: self.Credentials.ClientID, - ClientSecret: self.Credentials.ClientSecret, - Endpoint: self.Endpoint, - Scopes: scopes, - } +// unprotectedProvider is a provider that cannot do PKCE. Every provider that +// stays silent does it. +type unprotectedProvider interface { + UsesPKCE() bool } -func (self OAuth2) UsesPKCE() bool { return !self.WithoutPKCE } - -func (self OAuth2) User(ctx context.Context, client *http.Client, _ *oauth2.Token) (*User, error) { - var raw map[string]any - if err := GetJSON(ctx, client, self.ProfileURL, &raw); err != nil { - return nil, err - } - - user := User{} - if self.Map != nil { - user = self.Map(raw) - } - - if user.Raw == nil { - user.Raw = raw - } - - return &user, nil +// openIDProvider is an OpenID Connect issuer. The ID token it returns with +// the access token is verified for signature, issuer, audience, expiry and +// nonce before the person is trusted. +type openIDProvider interface { + Issuer() string } -// GetJSON fetches a JSON document into any value, with a client that -// presents the token. A status other than 200 is an error. -func GetJSON(ctx context.Context, client *http.Client, url string, into any) error { +// fetch is a provider's GET of a JSON document, with the client that presents +// the token. Socialite's getHttpClient()->get() and json_decode in one. +func fetch(ctx context.Context, client *http.Client, url string, headers map[string]string) (*fastjson.Value, error) { request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { - return err + return nil, err } request.Header.Set("Accept", "application/json") + for key, value := range headers { + request.Header.Set(key, value) + } response, err := client.Do(request) if err != nil { - return fmt.Errorf("get %s: %w", url, err) + return nil, err } defer response.Body.Close() if response.StatusCode != http.StatusOK { - return fmt.Errorf("get %s: status %d", url, response.StatusCode) - } - - if err := json.NewDecoder(response.Body).Decode(into); err != nil { - return fmt.Errorf("decode %s: %w", url, err) - } - - return nil -} - -// String reads a string at a dotted path, such as "picture.data.url". A number -// is formatted, so a numeric id reads as one. -func String(raw map[string]any, path string) string { - switch value := lookup(raw, path).(type) { - case string: - return value - case float64: - if value == float64(int64(value)) { - return strconv.FormatInt(int64(value), 10) - } - - return strconv.FormatFloat(value, 'f', -1, 64) - case bool: - return strconv.FormatBool(value) - default: - return "" + return nil, fmt.Errorf("get %s: status %d", url, response.StatusCode) } -} - -// Bool reads a boolean at a dotted path. -func Bool(raw map[string]any, path string) bool { - value, _ := lookup(raw, path).(bool) - - return value -} -func lookup(raw map[string]any, path string) any { - var current any = raw - - for _, key := range strings.Split(path, ".") { - object, ok := current.(map[string]any) - if !ok { - return nil - } - - current = object[key] + body, err := io.ReadAll(io.LimitReader(response.Body, 10<<20)) + if err != nil { + return nil, err } - return current + return fastjson.ParseBytes(body) } diff --git a/provider.google.go b/provider.google.go new file mode 100644 index 0000000..3449f32 --- /dev/null +++ b/provider.google.go @@ -0,0 +1,44 @@ +package sociable + +import ( + "context" + "net/http" + + "github.com/valyala/fastjson" + "golang.org/x/oauth2" + "golang.org/x/oauth2/google" +) + +// GoogleProvider signs in through OpenID Connect. For a refresh token, +// redirect With(map[string]string{"access_type": "offline", "prompt": "consent"}). +type GoogleProvider struct{} + +func (self GoogleProvider) Endpoint(Credentials) oauth2.Endpoint { + return google.Endpoint +} + +func (self GoogleProvider) Issuer() string { + return "https://accounts.google.com" +} + +func (self GoogleProvider) Scoping() Scoping { + return Scoping{ + Scopes: []string{"openid", "profile", "email"}, + Separator: " ", + } +} + +func (self GoogleProvider) GetUserByToken(ctx context.Context, client *http.Client, _ *oauth2.Token, _ Credentials) (*fastjson.Value, error) { + return fetch(ctx, client, "https://www.googleapis.com/oauth2/v3/userinfo", nil) +} + +func (self GoogleProvider) MapUserToStruct(json *fastjson.Value) (*User, error) { + return &User{ + ID: string(json.GetStringBytes("sub")), + Nickname: string(json.GetStringBytes("given_name")), + Name: string(json.GetStringBytes("name")), + Email: string(json.GetStringBytes("email")), + EmailVerified: json.GetBool("email_verified"), + Avatar: string(json.GetStringBytes("picture")), + }, nil +} diff --git a/provider.linkedin.go b/provider.linkedin.go new file mode 100644 index 0000000..167fff4 --- /dev/null +++ b/provider.linkedin.go @@ -0,0 +1,43 @@ +package sociable + +import ( + "context" + "net/http" + + "github.com/valyala/fastjson" + "golang.org/x/oauth2" + "golang.org/x/oauth2/endpoints" +) + +// LinkedInProvider signs in through OpenID Connect. +type LinkedInProvider struct{} + +func (self LinkedInProvider) Endpoint(Credentials) oauth2.Endpoint { + return endpoints.LinkedIn +} + +func (self LinkedInProvider) Issuer() string { + return "https://www.linkedin.com/oauth" +} + +func (self LinkedInProvider) Scoping() Scoping { + return Scoping{ + Scopes: []string{"openid", "profile", "email"}, + Separator: " ", + } +} + +func (self LinkedInProvider) GetUserByToken(ctx context.Context, client *http.Client, _ *oauth2.Token, _ Credentials) (*fastjson.Value, error) { + return fetch(ctx, client, "https://api.linkedin.com/v2/userinfo", nil) +} + +func (self LinkedInProvider) MapUserToStruct(json *fastjson.Value) (*User, error) { + return &User{ + ID: string(json.GetStringBytes("sub")), + Nickname: string(json.GetStringBytes("given_name")), + Name: string(json.GetStringBytes("name")), + Email: string(json.GetStringBytes("email")), + EmailVerified: json.GetBool("email_verified"), + Avatar: string(json.GetStringBytes("picture")), + }, nil +} diff --git a/provider.slack.go b/provider.slack.go new file mode 100644 index 0000000..5c784d4 --- /dev/null +++ b/provider.slack.go @@ -0,0 +1,45 @@ +package sociable + +import ( + "context" + "net/http" + + "github.com/valyala/fastjson" + "golang.org/x/oauth2" +) + +// SlackProvider signs in through OpenID Connect. These are Slack's Sign in +// with Slack endpoints, not the workspace-app ones in x/oauth2. +type SlackProvider struct{} + +func (self SlackProvider) Endpoint(Credentials) oauth2.Endpoint { + return oauth2.Endpoint{ + AuthURL: "https://slack.com/openid/connect/authorize", + TokenURL: "https://slack.com/api/openid.connect.token", + } +} + +func (self SlackProvider) Issuer() string { + return "https://slack.com" +} + +func (self SlackProvider) Scoping() Scoping { + return Scoping{ + Scopes: []string{"openid", "email", "profile"}, + Separator: " ", + } +} + +func (self SlackProvider) GetUserByToken(ctx context.Context, client *http.Client, _ *oauth2.Token, _ Credentials) (*fastjson.Value, error) { + return fetch(ctx, client, "https://slack.com/api/openid.connect.userInfo", nil) +} + +func (self SlackProvider) MapUserToStruct(json *fastjson.Value) (*User, error) { + return &User{ + ID: string(json.GetStringBytes("sub")), + Name: string(json.GetStringBytes("name")), + Email: string(json.GetStringBytes("email")), + EmailVerified: json.GetBool("email_verified"), + Avatar: string(json.GetStringBytes("picture")), + }, nil +} diff --git a/provider.twitch.go b/provider.twitch.go new file mode 100644 index 0000000..354bb6e --- /dev/null +++ b/provider.twitch.go @@ -0,0 +1,53 @@ +package sociable + +import ( + "context" + "errors" + "net/http" + + "github.com/valyala/fastjson" + "golang.org/x/oauth2" + "golang.org/x/oauth2/endpoints" +) + +// TwitchProvider reads the Helix users document, which needs the client id +// on the request as well as the token. +type TwitchProvider struct{} + +func (self TwitchProvider) Endpoint(Credentials) oauth2.Endpoint { + return endpoints.Twitch +} + +func (self TwitchProvider) Scoping() Scoping { + return Scoping{ + Scopes: []string{"user:read:email"}, + Separator: " ", + } +} + +func (self TwitchProvider) GetUserByToken(ctx context.Context, client *http.Client, _ *oauth2.Token, credentials Credentials) (*fastjson.Value, error) { + users, err := fetch(ctx, client, "https://api.twitch.tv/helix/users", map[string]string{"Client-Id": credentials.ClientID}) + if err != nil { + return nil, err + } + + data := users.GetArray("data") + if len(data) == 0 { + return nil, errors.New("twitch: empty users response") + } + + return data[0], nil +} + +func (self TwitchProvider) MapUserToStruct(json *fastjson.Value) (*User, error) { + email := string(json.GetStringBytes("email")) + + return &User{ + ID: string(json.GetStringBytes("id")), + Nickname: string(json.GetStringBytes("login")), + Name: string(json.GetStringBytes("display_name")), + Email: email, + EmailVerified: email != "", + Avatar: string(json.GetStringBytes("profile_image_url")), + }, nil +} diff --git a/provider.x.go b/provider.x.go new file mode 100644 index 0000000..7d0e42f --- /dev/null +++ b/provider.x.go @@ -0,0 +1,47 @@ +package sociable + +import ( + "context" + "net/http" + + "github.com/valyala/fastjson" + "golang.org/x/oauth2" + "golang.org/x/oauth2/endpoints" +) + +// XProvider reads the users/me document. X issues an email only to apps +// approved for it. +type XProvider struct{} + +func (self XProvider) Endpoint(Credentials) oauth2.Endpoint { + return endpoints.X +} + +func (self XProvider) Scoping() Scoping { + return Scoping{ + Scopes: []string{"users.read", "tweet.read"}, + Separator: " ", + } +} + +func (self XProvider) GetUserByToken(ctx context.Context, client *http.Client, _ *oauth2.Token, _ Credentials) (*fastjson.Value, error) { + user, err := fetch(ctx, client, "https://api.x.com/2/users/me?user.fields=profile_image_url,confirmed_email", nil) + if err != nil { + return nil, err + } + + return user.Get("data"), nil +} + +func (self XProvider) MapUserToStruct(json *fastjson.Value) (*User, error) { + email := string(json.GetStringBytes("confirmed_email")) + + return &User{ + ID: string(json.GetStringBytes("id")), + Nickname: string(json.GetStringBytes("username")), + Name: string(json.GetStringBytes("name")), + Email: email, + EmailVerified: email != "", + Avatar: string(json.GetStringBytes("profile_image_url")), + }, nil +} diff --git a/provider_test.go b/provider_test.go new file mode 100644 index 0000000..c9d136b --- /dev/null +++ b/provider_test.go @@ -0,0 +1,428 @@ +package sociable + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "golang.org/x/oauth2" +) + +// same fails unless the mapped user is want, token and scopes aside. +func same(t *testing.T, got *User, want User) { + t.Helper() + + if got.ID != want.ID || got.Nickname != want.Nickname || got.Name != want.Name || + got.Email != want.Email || got.EmailVerified != want.EmailVerified || got.Avatar != want.Avatar { + t.Errorf("user = %+v, want %+v", *got, want) + } +} + +func TestFetch(t *testing.T) { + t.Parallel() + + client, last := rewritingClient(t, func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/ok": + _, _ = w.Write([]byte(`{"id":"1"}`)) + case "/broken": + _, _ = w.Write([]byte(`{"id":`)) + case "/truncated": + w.Header().Set("Content-Length", "100") + _, _ = w.Write([]byte(`{"id":"1"}`)) + default: + w.WriteHeader(http.StatusForbidden) + } + }) + + document, err := fetch(t.Context(), client, "https://api.example/ok", map[string]string{"X-Extra": "yes"}) + if err != nil || string(document.GetStringBytes("id")) != "1" { + t.Errorf("document = %v, %v", document, err) + } + + if last.Header.Get("Accept") != "application/json" || last.Header.Get("X-Extra") != "yes" { + t.Errorf("headers = %v", last.Header) + } + + if _, err := fetch(t.Context(), client, "https://api.example/forbidden", nil); err == nil || !strings.Contains(err.Error(), "403") { + t.Errorf("status: %v", err) + } + + if _, err := fetch(t.Context(), client, "https://api.example/broken", nil); err == nil { + t.Error("broken json accepted") + } + + if _, err := fetch(t.Context(), client, "https://api.example/truncated", nil); err == nil { + t.Error("truncated body accepted") + } + + if _, err := fetch(t.Context(), client, "http://bad host/", nil); err == nil { + t.Error("bad url accepted") + } + + closed := httptest.NewServer(http.NotFoundHandler()) + closed.Close() + + if _, err := fetch(t.Context(), closed.Client(), closed.URL, nil); err == nil { + t.Error("unreachable server accepted") + } +} + +func TestGoogle(t *testing.T) { + t.Parallel() + + var p GoogleProvider + + if p.Endpoint(Credentials{}).AuthURL == "" || p.Issuer() != "https://accounts.google.com" || p.Scoping().Scopes[0] != "openid" { + t.Error("configuration") + } + + client, last := rewritingClient(t, encode(map[string]any{ + "sub": "1", "given_name": "Ada", "name": "Ada L", "email": "ada@x", "email_verified": true, "picture": "p", + })) + + raw, err := p.GetUserByToken(t.Context(), client, nil, Credentials{}) + if err != nil { + t.Fatal(err) + } + + if last.URL.Path != "/oauth2/v3/userinfo" { + t.Errorf("fetched %s", last.URL.Path) + } + + user, _ := p.MapUserToStruct(raw) + same(t, user, User{ID: "1", Nickname: "Ada", Name: "Ada L", Email: "ada@x", EmailVerified: true, Avatar: "p"}) +} + +func TestGitHub(t *testing.T) { + t.Parallel() + + var p GitHubProvider + + if p.Endpoint(Credentials{}).AuthURL == "" || p.Scoping().Scopes[0] != "read:user" { + t.Error("configuration") + } + + t.Run("email on the profile", func(t *testing.T) { + t.Parallel() + + calls := 0 + client, last := rewritingClient(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + encode(map[string]any{"id": 42, "login": "ada", "name": "Ada", "email": "ada@x", "avatar_url": "p"})(w, r) + }) + + raw, err := p.GetUserByToken(t.Context(), client, nil, Credentials{}) + if err != nil { + t.Fatal(err) + } + + if calls != 1 || last.Header.Get("Accept") != "application/vnd.github+json" { + t.Errorf("calls = %d, accept = %q", calls, last.Header.Get("Accept")) + } + + user, _ := p.MapUserToStruct(raw) + same(t, user, User{ID: "42", Nickname: "ada", Name: "Ada", Email: "ada@x", EmailVerified: true, Avatar: "p"}) + }) + + t.Run("email from the emails endpoint", func(t *testing.T) { + t.Parallel() + + client, _ := rewritingClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/user/emails" { + encode([]map[string]any{ + {"email": "old@x", "primary": false, "verified": true}, + {"email": "unverified@x", "primary": true, "verified": false}, + {"email": "ada@x", "primary": true, "verified": true}, + })(w, r) + return + } + + encode(map[string]any{"id": 42, "login": "ada", "email": nil})(w, r) + }) + + raw, err := p.GetUserByToken(t.Context(), client, nil, Credentials{}) + if err != nil { + t.Fatal(err) + } + + user, _ := p.MapUserToStruct(raw) + if user.Email != "ada@x" || !user.EmailVerified { + t.Errorf("user = %+v", *user) + } + }) + + t.Run("emails endpoint fails", func(t *testing.T) { + t.Parallel() + + client, _ := rewritingClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/user/emails" { + w.WriteHeader(http.StatusForbidden) + return + } + + encode(map[string]any{"id": 42})(w, r) + }) + + if _, err := p.GetUserByToken(t.Context(), client, nil, Credentials{}); err == nil { + t.Error("no error") + } + }) + + t.Run("profile fails", func(t *testing.T) { + t.Parallel() + + client, _ := rewritingClient(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusUnauthorized) }) + + if _, err := p.GetUserByToken(t.Context(), client, nil, Credentials{}); err == nil { + t.Error("no error") + } + }) +} + +func TestGitLab(t *testing.T) { + t.Parallel() + + var p GitLabProvider + + if p.Endpoint(Credentials{}).AuthURL != "https://gitlab.com/oauth/authorize" { + t.Errorf("default host: %s", p.Endpoint(Credentials{}).AuthURL) + } + + hosted := Credentials{BaseURL: "https://git.acme.example/"} + if p.Endpoint(hosted).TokenURL != "https://git.acme.example/oauth/token" { + t.Errorf("self-hosted: %s", p.Endpoint(hosted).TokenURL) + } + + if p.Scoping().Scopes[0] != "read_user" { + t.Error("scopes") + } + + client, last := rewritingClient(t, encode(map[string]any{"id": 7, "username": "ada", "name": "Ada", "email": "ada@x", "avatar_url": "p"})) + + raw, err := p.GetUserByToken(t.Context(), client, nil, hosted) + if err != nil { + t.Fatal(err) + } + + if last.URL.Path != "/api/v4/user" { + t.Errorf("fetched %s", last.URL.Path) + } + + user, _ := p.MapUserToStruct(raw) + same(t, user, User{ID: "7", Nickname: "ada", Name: "Ada", Email: "ada@x", EmailVerified: true, Avatar: "p"}) +} + +func TestFacebook(t *testing.T) { + t.Parallel() + + var p FacebookProvider + + if p.Endpoint(Credentials{}).AuthURL == "" || p.Scoping().Separator != "," { + t.Error("configuration") + } + + client, last := rewritingClient(t, encode(map[string]any{ + "id": "9", "name": "Ada", "email": "ada@x", "picture": map[string]any{"data": map[string]any{"url": "p"}}, + })) + + token := &oauth2.Token{AccessToken: "at"} + + raw, err := p.GetUserByToken(t.Context(), client, token, Credentials{ClientSecret: "s"}) + if err != nil { + t.Fatal(err) + } + + mac := hmac.New(sha256.New, []byte("s")) + mac.Write([]byte("at")) + + if last.URL.Query().Get("appsecret_proof") != hex.EncodeToString(mac.Sum(nil)) || !strings.Contains(last.URL.Query().Get("fields"), "email") { + t.Errorf("query = %v", last.URL.Query()) + } + + user, _ := p.MapUserToStruct(raw) + same(t, user, User{ID: "9", Name: "Ada", Email: "ada@x", EmailVerified: true, Avatar: "p"}) + + if _, err := p.GetUserByToken(t.Context(), client, token, Credentials{}); err != nil || last.URL.Query().Has("appsecret_proof") { + t.Errorf("without a secret: proof=%q, %v", last.URL.Query().Get("appsecret_proof"), err) + } +} + +func TestBitbucket(t *testing.T) { + t.Parallel() + + var p BitbucketProvider + + if p.Endpoint(Credentials{}).AuthURL == "" || p.Scoping().Scopes[0] != "email" { + t.Error("configuration") + } + + client, _ := rewritingClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/2.0/user/emails" { + encode(map[string]any{"values": []map[string]any{ + {"email": "old@x", "is_primary": false, "is_confirmed": true}, + {"email": "ada@x", "is_primary": true, "is_confirmed": true}, + }})(w, r) + return + } + + encode(map[string]any{ + "uuid": "{u}", "username": "ada", "display_name": "Ada", + "links": map[string]any{"avatar": map[string]any{"href": "p"}}, + })(w, r) + }) + + raw, err := p.GetUserByToken(t.Context(), client, nil, Credentials{}) + if err != nil { + t.Fatal(err) + } + + user, _ := p.MapUserToStruct(raw) + same(t, user, User{ID: "{u}", Nickname: "ada", Name: "Ada", Email: "ada@x", EmailVerified: true, Avatar: "p"}) + + failing, _ := rewritingClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/2.0/user/emails" { + w.WriteHeader(http.StatusForbidden) + return + } + + encode(map[string]any{"uuid": "{u}"})(w, r) + }) + + if _, err := p.GetUserByToken(t.Context(), failing, nil, Credentials{}); err == nil { + t.Error("emails failing: no error") + } + + down, _ := rewritingClient(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusUnauthorized) }) + + if _, err := p.GetUserByToken(t.Context(), down, nil, Credentials{}); err == nil { + t.Error("profile failing: no error") + } +} + +func TestLinkedIn(t *testing.T) { + t.Parallel() + + var p LinkedInProvider + + if p.Endpoint(Credentials{}).AuthURL == "" || p.Issuer() == "" || p.Scoping().Scopes[0] != "openid" { + t.Error("configuration") + } + + client, last := rewritingClient(t, encode(map[string]any{ + "sub": "1", "given_name": "Ada", "name": "Ada L", "email": "ada@x", "email_verified": true, "picture": "p", + })) + + raw, err := p.GetUserByToken(t.Context(), client, nil, Credentials{}) + if err != nil { + t.Fatal(err) + } + + if last.URL.Path != "/v2/userinfo" { + t.Errorf("fetched %s", last.URL.Path) + } + + user, _ := p.MapUserToStruct(raw) + same(t, user, User{ID: "1", Nickname: "Ada", Name: "Ada L", Email: "ada@x", EmailVerified: true, Avatar: "p"}) +} + +func TestSlack(t *testing.T) { + t.Parallel() + + var p SlackProvider + + if p.Endpoint(Credentials{}).AuthURL != "https://slack.com/openid/connect/authorize" || + p.Issuer() != "https://slack.com" || p.Scoping().Scopes[0] != "openid" { + t.Error("configuration") + } + + client, last := rewritingClient(t, encode(map[string]any{ + "sub": "U1", "name": "Ada", "email": "ada@x", "email_verified": true, "picture": "p", + })) + + raw, err := p.GetUserByToken(t.Context(), client, nil, Credentials{}) + if err != nil { + t.Fatal(err) + } + + if last.URL.Path != "/api/openid.connect.userInfo" { + t.Errorf("fetched %s", last.URL.Path) + } + + user, _ := p.MapUserToStruct(raw) + same(t, user, User{ID: "U1", Name: "Ada", Email: "ada@x", EmailVerified: true, Avatar: "p"}) +} + +func TestTwitch(t *testing.T) { + t.Parallel() + + var p TwitchProvider + + if p.Endpoint(Credentials{}).AuthURL == "" || p.Scoping().Scopes[0] != "user:read:email" { + t.Error("configuration") + } + + client, last := rewritingClient(t, encode(map[string]any{"data": []map[string]any{ + {"id": "9", "login": "ada", "display_name": "Ada", "email": "ada@x", "profile_image_url": "p"}, + }})) + + raw, err := p.GetUserByToken(t.Context(), client, nil, Credentials{ClientID: "cid"}) + if err != nil { + t.Fatal(err) + } + + if last.Header.Get("Client-Id") != "cid" || last.URL.Path != "/helix/users" { + t.Errorf("request = %s %v", last.URL.Path, last.Header) + } + + user, _ := p.MapUserToStruct(raw) + same(t, user, User{ID: "9", Nickname: "ada", Name: "Ada", Email: "ada@x", EmailVerified: true, Avatar: "p"}) + + empty, _ := rewritingClient(t, encode(map[string]any{"data": []any{}})) + + if _, err := p.GetUserByToken(t.Context(), empty, nil, Credentials{}); err == nil { + t.Error("empty data: no error") + } + + down, _ := rewritingClient(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusUnauthorized) }) + + if _, err := p.GetUserByToken(t.Context(), down, nil, Credentials{}); err == nil { + t.Error("failing: no error") + } +} + +func TestX(t *testing.T) { + t.Parallel() + + var p XProvider + + if p.Endpoint(Credentials{}).AuthURL == "" || p.Scoping().Scopes[0] != "users.read" { + t.Error("configuration") + } + + client, last := rewritingClient(t, encode(map[string]any{"data": map[string]any{ + "id": "9", "username": "ada", "name": "Ada", "confirmed_email": "ada@x", "profile_image_url": "p", + }})) + + raw, err := p.GetUserByToken(t.Context(), client, nil, Credentials{}) + if err != nil { + t.Fatal(err) + } + + if last.URL.Path != "/2/users/me" || !strings.Contains(last.URL.Query().Get("user.fields"), "confirmed_email") { + t.Errorf("request = %s %v", last.URL.Path, last.URL.Query()) + } + + user, _ := p.MapUserToStruct(raw) + same(t, user, User{ID: "9", Nickname: "ada", Name: "Ada", Email: "ada@x", EmailVerified: true, Avatar: "p"}) + + down, _ := rewritingClient(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusUnauthorized) }) + + if _, err := p.GetUserByToken(t.Context(), down, nil, Credentials{}); err == nil { + t.Error("failing: no error") + } +} diff --git a/providers.go b/providers.go deleted file mode 100644 index d2554a6..0000000 --- a/providers.go +++ /dev/null @@ -1,251 +0,0 @@ -package sociable - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - - "golang.org/x/oauth2" - "golang.org/x/oauth2/endpoints" -) - -// builtin are the drivers a name picks without an Extend. -var builtin = map[string]Factory{ - "google": Google, - "github": GitHub, - "gitlab": GitLab, - "facebook": Facebook, - "linkedin": LinkedIn, - "bitbucket": Bitbucket, - "slack": Slack, - "twitch": Twitch, - "x": X, -} - -// Google signs in through OpenID Connect. For a refresh token, redirect with -// With(map[string]string{"access_type": "offline", "prompt": "consent"}). -func Google(credentials Credentials) Provider { - return OpenID(credentials, "https://accounts.google.com") -} - -// LinkedIn signs in through OpenID Connect. -func LinkedIn(credentials Credentials) Provider { - return OpenID(credentials, "https://www.linkedin.com/oauth") -} - -// Slack signs in through OpenID Connect. -func Slack(credentials Credentials) Provider { - return OpenID(credentials, "https://slack.com") -} - -// GitHub reads the profile and, when the profile hides the address, the -// primary verified one from the emails endpoint. -func GitHub(credentials Credentials) Provider { - return github{OAuth2{ - Credentials: credentials, - Endpoint: endpoints.GitHub, - Scopes: []string{"read:user", "user:email"}, - ProfileURL: "https://api.github.com/user", - Map: func(raw map[string]any) User { - email := String(raw, "email") - - return User{ - ID: String(raw, "id"), - Nickname: String(raw, "login"), - Name: String(raw, "name"), - Email: email, - EmailVerified: email != "", - Avatar: String(raw, "avatar_url"), - } - }, - }} -} - -type github struct{ OAuth2 } - -func (self github) User(ctx context.Context, client *http.Client, token *oauth2.Token) (*User, error) { - user, err := self.OAuth2.User(ctx, client, token) - if err != nil || user.Email != "" { - return user, err - } - - var emails []struct { - Email string `json:"email"` - Primary bool `json:"primary"` - Verified bool `json:"verified"` - } - if err := GetJSON(ctx, client, "https://api.github.com/user/emails", &emails); err != nil { - return nil, err - } - - for _, candidate := range emails { - if candidate.Primary { - user.Email, user.EmailVerified = candidate.Email, candidate.Verified - - break - } - } - - return user, nil -} - -// GitLab signs in against gitlab.com. For a self-hosted instance, Extend with -// an OAuth2 that points at it. -func GitLab(credentials Credentials) Provider { - return OAuth2{ - Credentials: credentials, - Endpoint: endpoints.GitLab, - Scopes: []string{"read_user"}, - ProfileURL: "https://gitlab.com/api/v4/user", - Map: func(raw map[string]any) User { - return User{ - ID: String(raw, "id"), - Nickname: String(raw, "username"), - Name: String(raw, "name"), - Email: String(raw, "email"), - EmailVerified: String(raw, "email") != "", - Avatar: String(raw, "avatar_url"), - } - }, - } -} - -// Facebook reads the Graph API's me document. -func Facebook(credentials Credentials) Provider { - return OAuth2{ - Credentials: credentials, - Endpoint: endpoints.Facebook, - Scopes: []string{"email"}, - ProfileURL: "https://graph.facebook.com/v19.0/me?fields=id,name,email,picture.width(400)", - Map: func(raw map[string]any) User { - return User{ - ID: String(raw, "id"), - Name: String(raw, "name"), - Email: String(raw, "email"), - EmailVerified: String(raw, "email") != "", - Avatar: String(raw, "picture.data.url"), - } - }, - } -} - -// Bitbucket reads the user document and the primary address from the emails -// endpoint, which is the only place Bitbucket puts it. -func Bitbucket(credentials Credentials) Provider { - return bitbucket{OAuth2{ - Credentials: credentials, - Endpoint: endpoints.Bitbucket, - Scopes: []string{"email"}, - ProfileURL: "https://api.bitbucket.org/2.0/user", - Map: func(raw map[string]any) User { - return User{ - ID: String(raw, "uuid"), - Nickname: String(raw, "username"), - Name: String(raw, "display_name"), - Avatar: String(raw, "links.avatar.href"), - } - }, - }} -} - -type bitbucket struct{ OAuth2 } - -func (self bitbucket) User(ctx context.Context, client *http.Client, token *oauth2.Token) (*User, error) { - user, err := self.OAuth2.User(ctx, client, token) - if err != nil { - return nil, err - } - - var emails struct { - Values []map[string]any `json:"values"` - } - if err := GetJSON(ctx, client, "https://api.bitbucket.org/2.0/user/emails", &emails); err != nil { - return nil, err - } - - for _, candidate := range emails.Values { - if Bool(candidate, "is_primary") { - user.Email, user.EmailVerified = String(candidate, "email"), Bool(candidate, "is_confirmed") - - break - } - } - - return user, nil -} - -// Twitch reads the Helix users document, which needs the client id on the -// request as well as the token. -func Twitch(credentials Credentials) Provider { - return twitch{OAuth2{ - Credentials: credentials, - Endpoint: endpoints.Twitch, - Scopes: []string{"user:read:email"}, - ProfileURL: "https://api.twitch.tv/helix/users", - }} -} - -type twitch struct{ OAuth2 } - -func (self twitch) User(ctx context.Context, client *http.Client, _ *oauth2.Token) (*User, error) { - request, err := http.NewRequestWithContext(ctx, http.MethodGet, self.ProfileURL, nil) - if err != nil { - return nil, err - } - - request.Header.Set("Client-Id", self.Credentials.ClientID) - request.Header.Set("Accept", "application/json") - - response, err := client.Do(request) - if err != nil { - return nil, fmt.Errorf("get users: %w", err) - } - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - return nil, fmt.Errorf("get users: status %d", response.StatusCode) - } - - var users struct { - Data []map[string]any `json:"data"` - } - if err := json.NewDecoder(response.Body).Decode(&users); err != nil { - return nil, fmt.Errorf("decode users: %w", err) - } - - if len(users.Data) == 0 { - return nil, errors.New("twitch: empty users response") - } - - raw := users.Data[0] - - return &User{ - ID: String(raw, "id"), - Nickname: String(raw, "login"), - Name: String(raw, "display_name"), - Email: String(raw, "email"), - EmailVerified: String(raw, "email") != "", - Avatar: String(raw, "profile_image_url"), - Raw: raw, - }, nil -} - -// X reads the users/me document. X issues no email. -func X(credentials Credentials) Provider { - return OAuth2{ - Credentials: credentials, - Endpoint: endpoints.X, - Scopes: []string{"users.read", "tweet.read"}, - ProfileURL: "https://api.x.com/2/users/me?user.fields=profile_image_url", - Map: func(raw map[string]any) User { - return User{ - ID: String(raw, "data.id"), - Nickname: String(raw, "data.username"), - Name: String(raw, "data.name"), - Avatar: String(raw, "data.profile_image_url"), - } - }, - } -} diff --git a/providers_test.go b/providers_test.go deleted file mode 100644 index 645afde..0000000 --- a/providers_test.go +++ /dev/null @@ -1,166 +0,0 @@ -package sociable_test - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "github.com/gonstruct/sociable" -) - -func decode(response *http.Response, into any) error { - return json.NewDecoder(response.Body).Decode(into) -} - -func mustParse(raw string) *url.URL { - parsed, err := url.Parse(raw) - if err != nil { - panic(err) - } - - return parsed -} - -func TestStringReadsDottedPathsAndNumbers(t *testing.T) { - raw := map[string]any{ - "id": float64(1234567), - "picture": map[string]any{"data": map[string]any{"url": "https://example.test/p.png"}}, - "ok": true, - } - - if got := sociable.String(raw, "id"); got != "1234567" { - t.Errorf("id = %q", got) - } - if got := sociable.String(raw, "picture.data.url"); got != "https://example.test/p.png" { - t.Errorf("picture = %q", got) - } - if got := sociable.String(raw, "picture.missing.url"); got != "" { - t.Errorf("missing = %q", got) - } - if !sociable.Bool(raw, "ok") { - t.Error("ok = false") - } -} - -func TestBuiltInDriversAreConfigurable(t *testing.T) { - auth, err := sociable.New(sociable.Config{ - Key: "k", - URL: "https://app.test", - Drivers: sociable.Drivers{ - "google": {ClientID: "id", ClientSecret: "s", Redirect: "/cb"}, - "github": {ClientID: "id", ClientSecret: "s", Redirect: "/cb"}, - "gitlab": {ClientID: "id", ClientSecret: "s", Redirect: "/cb"}, - "facebook": {ClientID: "id", ClientSecret: "s", Redirect: "/cb"}, - "linkedin": {ClientID: "id", ClientSecret: "s", Redirect: "/cb"}, - "bitbucket": {ClientID: "id", ClientSecret: "s", Redirect: "/cb"}, - "slack": {ClientID: "id", ClientSecret: "s", Redirect: "/cb"}, - "twitch": {ClientID: "id", ClientSecret: "s", Redirect: "/cb"}, - "x": {ClientID: "id", ClientSecret: "s", Redirect: "/cb"}, - }, - }) - if err != nil { - t.Fatal(err) - } - - // The plain OAuth 2 drivers need no network to produce an authorization URL. - for _, name := range []string{"github", "gitlab", "facebook", "bitbucket", "twitch", "x"} { - recorder := httptest.NewRecorder() - - authURL, err := auth.Driver(name).AuthURL(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) - if err != nil { - t.Errorf("%s: %v", name, err) - - continue - } - - parsed := mustParse(authURL) - if parsed.Query().Get("client_id") != "id" || parsed.Query().Get("code_challenge") == "" { - t.Errorf("%s: %s", name, authURL) - } - } -} - -func TestGitHubFallsBackToThePrimaryEmail(t *testing.T) { - api := newAPI(t) - api.reply("/user", map[string]any{"id": 9, "login": "arjen", "name": "Arjen", "email": nil, "avatar_url": "https://a"}) - api.reply("/user/emails", []map[string]any{ - {"email": "old@example.test", "primary": false, "verified": true}, - {"email": "arjen@example.test", "primary": true, "verified": true}, - }) - - user, err := sociable.GitHub(sociable.Credentials{ClientID: "id"}).User(t.Context(), api.client(), nil) - if err != nil { - t.Fatal(err) - } - - if user.ID != "9" || user.Nickname != "arjen" || user.Email != "arjen@example.test" || !user.EmailVerified { - t.Errorf("user = %+v", user) - } -} - -func TestTwitchSendsTheClientID(t *testing.T) { - api := newAPI(t) - api.reply("/helix/users", map[string]any{ - "data": []map[string]any{{"id": "77", "login": "arjen", "display_name": "Arjen", "email": "arjen@example.test"}}, - }) - - user, err := sociable.Twitch(sociable.Credentials{ClientID: "twitch-client"}).User(t.Context(), api.client(), nil) - if err != nil { - t.Fatal(err) - } - - if user.ID != "77" || user.Email != "arjen@example.test" { - t.Errorf("user = %+v", user) - } - - if got := api.sent["/helix/users"].Get("Client-Id"); got != "twitch-client" { - t.Errorf("Client-Id = %q", got) - } -} - -// api is a fake provider API: canned JSON per path, the request headers -// recorded, and a client that sends every host to it. -type api struct { - *httptest.Server - - replies map[string]any - sent map[string]http.Header -} - -func newAPI(t *testing.T) *api { - t.Helper() - - a := &api{replies: map[string]any{}, sent: map[string]http.Header{}} - a.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - a.sent[r.URL.Path] = r.Header.Clone() - - reply, ok := a.replies[r.URL.Path] - if !ok { - http.NotFound(w, r) - - return - } - - _ = json.NewEncoder(w).Encode(reply) - })) - t.Cleanup(a.Close) - - return a -} - -func (a *api) reply(path string, body any) { a.replies[path] = body } - -func (a *api) client() *http.Client { - return &http.Client{Transport: rewrite{to: mustParse(a.URL)}} -} - -// rewrite sends every request to the test server, whatever host it named. -type rewrite struct{ to *url.URL } - -func (self rewrite) RoundTrip(request *http.Request) (*http.Response, error) { - request.URL.Scheme, request.URL.Host = self.to.Scheme, self.to.Host - - return http.DefaultTransport.RoundTrip(request) -} diff --git a/redirect_test.go b/redirect_test.go new file mode 100644 index 0000000..7e54046 --- /dev/null +++ b/redirect_test.go @@ -0,0 +1,118 @@ +package sociable + +import ( + "testing" + "time" +) + +func TestRedirectAsksForACode(t *testing.T) { + t.Parallel() + + m := manager[stub](newProviderServer(t)) + + query, cookies := redirected(t, m.Driver("stub")) + + for key, want := range map[string]string{ + "client_id": "id", + "redirect_uri": "https://app.example/cb", + "response_type": "code", + "scope": "a b", + "code_challenge_method": "S256", + } { + if got := query.Get(key); got != want { + t.Errorf("%s = %q, want %q", key, got, want) + } + } + + if query.Get("state") == "" || query.Get("code_challenge") == "" { + t.Errorf("no state or challenge: %v", query) + } + + if query.Has("nonce") { + t.Error("nonce on a plain OAuth 2 request") + } + + issued := handshakeFrom(t, cookies) + + if issued.State != query.Get("state") { + t.Error("stored state differs from the sent one") + } + + if issued.Verifier == "" || issued.Nonce != "" { + t.Errorf("handshake = %+v", issued) + } + + if until := time.Until(issued.ExpiresAt); until < 9*time.Minute || until > handshakeLifetime { + t.Errorf("expires in %s", until) + } +} + +func TestRedirectSendsANonceForOpenID(t *testing.T) { + t.Parallel() + + m := manager[openidStub](newProviderServer(t)) + + query, cookies := redirected(t, m.Driver("stub")) + + if query.Get("nonce") == "" { + t.Fatal("no nonce") + } + + if handshakeFrom(t, cookies).Nonce != query.Get("nonce") { + t.Error("stored nonce differs from the sent one") + } + + // Asking openid away makes it a plain request again. + query, _ = redirected(t, m.Driver("stub").SetScopes("a")) + if query.Has("nonce") { + t.Error("nonce without openid") + } +} + +func TestRedirectWithoutPKCE(t *testing.T) { + t.Parallel() + + m := manager[noPKCEStub](newProviderServer(t)) + + query, cookies := redirected(t, m.Driver("stub")) + + if query.Has("code_challenge") || query.Has("code_challenge_method") { + t.Errorf("challenge sent for a provider that cannot: %v", query) + } + + if handshakeFrom(t, cookies).Verifier != "" { + t.Error("verifier stored") + } +} + +func TestRedirectUsesTheProvidersSeparator(t *testing.T) { + t.Parallel() + + m := manager[commaStub](newProviderServer(t)) + + query, _ := redirected(t, m.Driver("stub").Scopes("c")) + + if query.Get("scope") != "a,b,c" { + t.Errorf("scope = %q", query.Get("scope")) + } +} + +func TestRedirectStateless(t *testing.T) { + t.Parallel() + + m := manager[stub](newProviderServer(t)) + + query, cookies := redirected(t, m.Driver("stub").Stateless()) + + if len(cookies) != 0 { + t.Errorf("cookie set: %v", cookies) + } + + if query.Has("code_challenge") { + t.Error("PKCE with nowhere to keep the verifier") + } + + if query.Get("state") == "" { + t.Error("no state sent") + } +} diff --git a/session.go b/session.go index 05e7572..91e28b5 100644 --- a/session.go +++ b/session.go @@ -6,74 +6,55 @@ import ( "crypto/rand" "crypto/sha256" "encoding/base64" - "errors" "net/http" - "time" ) -// Session keeps the handshake between the redirect and the callback. The -// default is an encrypted cookie; an application with a session of its own -// hands that over instead. +// Session keeps the handshake between the redirect and the callback, the way +// Socialite keeps it in Laravel's session. The default is an encrypted +// cookie; an application with a session of its own hands that over with +// WithSession. // -// The value is the handshake as plain JSON, PKCE verifier included, so a -// Session must keep it server-side or encrypt it. It must also be bound to -// the browser that started the flow, which is what makes the state check -// mean anything. +// The value holds the PKCE verifier, so a Session must keep it server-side +// or encrypted, and bound to the browser that started the flow. type Session interface { Put(w http.ResponseWriter, r *http.Request, key, value string) error Pull(w http.ResponseWriter, r *http.Request, key string) (string, error) } -// handshake is what the callback needs to trust what came back: the state it -// issued, the PKCE verifier whose challenge it sent, the nonce it asked the -// provider to echo into an ID token, and whatever the call site put in. -type handshake struct { - State string `json:"state"` - Verifier string `json:"verifier,omitempty"` - Nonce string `json:"nonce,omitempty"` - Custom map[string]string `json:"custom,omitempty"` - ExpiresAt time.Time `json:"expiresAt"` -} - -const ( - sessionKey = "sociable" - handshakeLifetime = 10 * time.Minute -) - -// ErrSealed means a cookie that was forged, truncated or issued under another -// key. The flow treats it as no handshake. -var ErrSealed = errors.New("sociable: the cookie cannot be opened") - +// cookieSession is the default Session: one cookie per key, AES-GCM under a +// key derived from Config.Key. type cookieSession struct { aead cipher.AEAD secure bool } -func newCookieSession(key string, secure bool) *cookieSession { +func newCookieSession(key string, secure bool) (*cookieSession, error) { + if key == "" { + return nil, ErrMissingKeyOrSession + } + derived := sha256.Sum256([]byte(key)) block, err := aes.NewCipher(derived[:]) if err != nil { - panic("sociable: " + err.Error()) + return nil, err } aead, err := cipher.NewGCM(block) if err != nil { - panic("sociable: " + err.Error()) + return nil, err } - return &cookieSession{aead: aead, secure: secure} + return &cookieSession{aead: aead, secure: secure}, nil } func (self *cookieSession) Put(w http.ResponseWriter, r *http.Request, key, value string) error { nonce := make([]byte, self.aead.NonceSize()) - if _, err := rand.Read(nonce); err != nil { - return err - } + _, _ = rand.Read(nonce) // cannot fail since Go 1.24 sealed := self.aead.Seal(nonce, nonce, []byte(value), nil) - self.write(w, r, key, base64.RawURLEncoding.EncodeToString(sealed), int(handshakeLifetime.Seconds())) + self.write(w, r, key, base64.RawURLEncoding.EncodeToString(sealed), 600) return nil } @@ -90,14 +71,14 @@ func (self *cookieSession) Pull(w http.ResponseWriter, r *http.Request, key stri data, err := base64.RawURLEncoding.DecodeString(cookie.Value) if err != nil || len(data) < self.aead.NonceSize() { - return "", ErrSealed + return "", ErrSessionSealed } size := self.aead.NonceSize() plain, err := self.aead.Open(nil, data[:size], data[size:], nil) if err != nil { - return "", ErrSealed + return "", ErrSessionSealed } return string(plain), nil @@ -114,14 +95,3 @@ func (self *cookieSession) write(w http.ResponseWriter, r *http.Request, key, va SameSite: http.SameSiteLaxMode, }) } - -func random(size int) string { - buffer := make([]byte, size) - if _, err := rand.Read(buffer); err != nil { - // A system that cannot produce randomness must not go on issuing - // values that are supposed to be unguessable. - panic("sociable: " + err.Error()) - } - - return base64.RawURLEncoding.EncodeToString(buffer) -} diff --git a/session_test.go b/session_test.go new file mode 100644 index 0000000..7d71876 --- /dev/null +++ b/session_test.go @@ -0,0 +1,119 @@ +package sociable + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestCookieSession(t *testing.T) { + t.Parallel() + + session, err := newCookieSession("key", false) + if err != nil { + t.Fatal(err) + } + + recorder := httptest.NewRecorder() + if err := session.Put(recorder, httptest.NewRequest(http.MethodGet, "/", nil), "name", "secret value"); err != nil { + t.Fatal(err) + } + + cookies := recorder.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("cookies = %v", cookies) + } + + cookie := cookies[0] + + if cookie.Name != "name" || !cookie.HttpOnly || cookie.SameSite != http.SameSiteLaxMode || cookie.Path != "/" || cookie.MaxAge != 600 || cookie.Secure { + t.Errorf("cookie = %+v", cookie) + } + + if strings.Contains(cookie.Value, "secret") { + t.Error("value readable") + } + + request := httptest.NewRequest(http.MethodGet, "/", nil) + request.AddCookie(cookie) + recorder = httptest.NewRecorder() + + value, err := session.Pull(recorder, request, "name") + if err != nil || value != "secret value" { + t.Errorf("pulled %q, %v", value, err) + } + + if cleared := recorder.Result().Cookies(); len(cleared) != 1 || cleared[0].MaxAge != -1 { + t.Errorf("not cleared: %v", cleared) + } +} + +func TestCookieSessionRefusesWhatItDidNotSeal(t *testing.T) { + t.Parallel() + + session, _ := newCookieSession("key", false) + otherKey, _ := newCookieSession("other", false) + + recorder := httptest.NewRecorder() + _ = otherKey.Put(recorder, httptest.NewRequest(http.MethodGet, "/", nil), "name", "value") + underOtherKey := recorder.Result().Cookies()[0].Value + + recorder = httptest.NewRecorder() + _ = session.Put(recorder, httptest.NewRequest(http.MethodGet, "/", nil), "name", "value") + genuine := recorder.Result().Cookies()[0].Value + + cases := map[string]string{ + "not base64": "***", + "too short": "YQ", + "tampered": genuine[:len(genuine)-2] + "zz", + "other key": underOtherKey, + } + + for name, value := range cases { + t.Run(name, func(t *testing.T) { + request := httptest.NewRequest(http.MethodGet, "/", nil) + request.AddCookie(&http.Cookie{Name: "name", Value: value}) + recorder := httptest.NewRecorder() + + if _, err := session.Pull(recorder, request, "name"); !errors.Is(err, ErrSessionSealed) { + t.Errorf("err = %v", err) + } + + if cleared := recorder.Result().Cookies(); len(cleared) != 1 || cleared[0].MaxAge != -1 { + t.Error("a failed pull must still clear the cookie") + } + }) + } + + if _, err := session.Pull(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil), "name"); !errors.Is(err, http.ErrNoCookie) { + t.Errorf("no cookie: %v", err) + } +} + +func TestCookieSessionNeedsAKey(t *testing.T) { + t.Parallel() + + if _, err := newCookieSession("", false); !errors.Is(err, ErrMissingKeyOrSession) { + t.Errorf("err = %v", err) + } + + secure, _ := newCookieSession("key", true) + recorder := httptest.NewRecorder() + _ = secure.Put(recorder, httptest.NewRequest(http.MethodGet, "/", nil), "name", "value") + + if !recorder.Result().Cookies()[0].Secure { + t.Error("not Secure") + } +} + +func TestRandom(t *testing.T) { + t.Parallel() + + a, b := random(32), random(32) + + if len(a) != 43 || a == b { + t.Errorf("%q %q", a, b) + } +} diff --git a/sociable.go b/sociable.go index 1517d94..2913bec 100644 --- a/sociable.go +++ b/sociable.go @@ -1,249 +1,72 @@ -// Package sociable authenticates people with Google, GitHub, GitLab, Facebook, -// LinkedIn, Bitbucket, Slack, Twitch, X, or any OAuth 2 or OpenID Connect -// provider, on net/http. It hands back who they are and a token to use. -// -// sociable.Configure(sociable.Config{ -// Key: os.Getenv("APP_KEY"), -// Drivers: sociable.Drivers{ -// "github": {ClientID: id, ClientSecret: secret, Redirect: "/auth/github/callback"}, -// }, -// }) -// -// sociable.Driver("github").Redirect(w, r) -// user, err := sociable.Driver("github").User(w, r) package sociable -import ( - "cmp" - "errors" - "fmt" - "maps" - "net/http" - "strings" - "sync" - "time" - - "golang.org/x/oauth2" -) +import "sync" // Credentials are what a provider issued the application. type Credentials struct { ClientID string ClientSecret string - // Redirect is the callback URL the provider sends the browser back to. A - // path is resolved against Config.URL. - Redirect string - - // Scopes replace the driver's defaults. - Scopes []string -} - -// Drivers maps a driver name to its credentials. The name picks the built-in -// provider of that name, or one registered with Extend. -type Drivers map[string]Credentials - -// Config is set once at boot. -type Config struct { - // Key encrypts the cookie that carries the handshake between the redirect - // and the callback. Any string; required unless Session is set. - Key string - - // URL is the application's own, for resolving a relative Redirect. - URL string - - Drivers Drivers - - // Session holds the handshake instead of the cookie, for an application - // that has a session already. - Session Session - - // Client talks to the providers. nil is http.DefaultClient. - Client *http.Client + // BaseURL is the provider's, for one that is self-hosted or an OpenID + // Connect issuer. A built-in provider has its own default. + BaseURL string + RedirectURL string } -// ErrNoKey is returned by New when there is nowhere to keep a handshake. -var ErrNoKey = errors.New("sociable: a Key or a Session is required") - -// Manager is a configured set of drivers. Configure sets up the default one; -// New makes another, for tests or a multi-tenant application. +// Manager is a configured set of drivers, Socialite's SocialiteManager. An +// application makes one with New at boot and hands it to its handlers; a +// test makes its own and fakes on it, so tests share nothing and run in +// parallel. type Manager struct { - mutex sync.RWMutex - config Config - session Session - factories map[string]Factory - providers map[string]Provider - fakes map[string]*Faked + mutex sync.RWMutex + config config } -var std = newManager() - -func newManager() *Manager { - return &Manager{factories: maps.Clone(builtin), providers: map[string]Provider{}, fakes: map[string]*Faked{}} -} - -// Configure sets up the default manager. It panics on a configuration that -// cannot work, because that is a mistake at boot rather than at runtime. -func Configure(config Config) { - if err := std.configure(config); err != nil { - panic(err) - } -} - -// Driver picks a configured driver on the default manager. -func Driver(name string) Flow { return std.Driver(name) } - -// Extend registers a provider under a name on the default manager. The factory -// receives the credentials configured under that name. -func Extend(name string, factory Factory) { std.Extend(name, factory) } - -// Fake replaces a driver on the default manager with one that returns the -// given user at the callback, for tests. Nothing needs configuring, and any -// field left blank gets a test value, so Fake("github", User{}) is a whole -// person. What comes back records every redirect, for asserting on. -func Fake(name string, user User) *Faked { return std.Fake(name, user) } - // New makes a manager of its own. -func New(config Config) (*Manager, error) { - manager := newManager() - - if err := manager.configure(config); err != nil { - return nil, err - } +func New(options ...option) *Manager { + manager := &Manager{} + manager.Configure(options...) - return manager, nil + return manager } -func (self *Manager) configure(config Config) error { - session := config.Session - if session == nil { - if config.Key == "" { - return ErrNoKey - } - - session = newCookieSession(config.Key, strings.HasPrefix(config.URL, "https://")) - } - - if config.Client == nil { - config.Client = http.DefaultClient - } - - config.Drivers = maps.Clone(config.Drivers) - if config.Drivers == nil { - config.Drivers = Drivers{} - } - +// Configure sets the manager up from scratch: the environment first, then +// the options over it. +func (self *Manager) Configure(options ...option) { self.mutex.Lock() defer self.mutex.Unlock() - self.config = config - self.session = session - clear(self.providers) - - return nil -} + self.config = configure() -// Driver picks a configured driver. An unknown name is not an error here but -// on every call that follows, so a handler has one place to check. -func (self *Manager) Driver(name string) Flow { - self.mutex.RLock() - faked, isFake := self.fakes[name] - credentials, configured := self.config.Drivers[name] - factory, known := self.factories[name] - session := self.session - provider, built := self.providers[name] - self.mutex.RUnlock() - - flow := Flow{manager: self, name: name} - - switch { - case isFake: - flow.fake = faked - case !configured || !known: - flow.err = fmt.Errorf("%w: %s", ErrUnknownDriver, name) - case session == nil: - flow.err = ErrNoKey - default: - if !built { - provider = self.build(name, factory, credentials) - } - - flow.credentials = credentials - flow.provider = provider + for _, option := range options { + option(self) } - - return flow } -// build makes the provider once. Two requests racing for the same driver -// both end up with the one that was cached first. -func (self *Manager) build(name string, factory Factory, credentials Credentials) Provider { - self.mutex.Lock() - defer self.mutex.Unlock() +// Driver picks a configured driver by name. +func (self *Manager) Driver(name string) DriverContract { + self.mutex.RLock() + defer self.mutex.RUnlock() - if provider, built := self.providers[name]; built { - return provider + if d, ok := self.config.Drivers[name]; ok { + return d } - provider := factory(credentials) - self.providers[name] = provider - - return provider -} - -// Extend registers a provider under a name. The factory receives the -// credentials configured under that name. -func (self *Manager) Extend(name string, factory Factory) { - self.mutex.Lock() - defer self.mutex.Unlock() - - self.factories[name] = factory - delete(self.providers, name) + return driver{} } -// Fake replaces a driver with one that returns the given user at the -// callback. The redirect goes to a URL that does not exist, and the callback -// checks nothing: a test calls it directly and gets the user. -func (self *Manager) Fake(name string, user User) *Faked { - self.mutex.Lock() - defer self.mutex.Unlock() +// Fake swaps the driver for one that redirects to a URL nobody serves and +// answers the callback with user, the way Socialite::fake does. Without a +// user, User falls through to the real driver. +func (self *Manager) Fake(name string, user ...*User) { + fake := &fakeDriver{name: name, driver: self.Driver(name)} - if self.fakes == nil { - self.fakes = map[string]*Faked{} + if len(user) > 0 { + fake.user = user[0] } - faked := &Faked{manager: self, driver: name, user: fakeUser(user)} - self.fakes[name] = faked - - return faked -} - -func (self *Manager) restore(name string, faked *Faked) { self.mutex.Lock() defer self.mutex.Unlock() - if self.fakes[name] == faked { - delete(self.fakes, name) - } -} - -// fakeUser fills the blanks with the values Socialite's fake user has, so a -// test names only what it cares about. -func fakeUser(user User) User { - user.ID = cmp.Or(user.ID, "123456789") - user.Nickname = cmp.Or(user.Nickname, "testuser") - user.Name = cmp.Or(user.Name, "Test User") - user.Email = cmp.Or(user.Email, "test@example.com") - user.EmailVerified = true - user.Avatar = cmp.Or(user.Avatar, "https://example.com/avatar.jpg") - - if user.Token == nil { - user.Token = &oauth2.Token{AccessToken: "fake-token", RefreshToken: "fake-refresh-token", Expiry: time.Now().Add(time.Hour)} - } - - if user.Raw == nil { - user.Raw = map[string]any{"id": user.ID, "nickname": user.Nickname, "name": user.Name, "email": user.Email} - } - - return user + self.config.Drivers[name] = fake } diff --git a/sociable_test.go b/sociable_test.go index 6c342da..3d0f4e0 100644 --- a/sociable_test.go +++ b/sociable_test.go @@ -1,137 +1,75 @@ -package sociable_test +package sociable import ( "errors" "net/http" "net/http/httptest" - "slices" - "sync" "testing" - - "github.com/gonstruct/sociable" ) -func TestTheDefaultManager(t *testing.T) { - sociable.Configure(sociable.Config{ - Key: "test", - URL: "https://app.test", - Drivers: sociable.Drivers{ - "github": {ClientID: "id", ClientSecret: "s", Redirect: "/auth/github/callback"}, - }, - }) - - recorder := httptest.NewRecorder() +func TestNewReadsTheEnvironment(t *testing.T) { + t.Setenv("APP_KEY", "from-env") + t.Setenv("API_URL", "https://env.example") - authURL, err := sociable.Driver("github").AuthURL(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) - if err != nil { - t.Fatal(err) - } + m := New() - parsed := mustParse(authURL) - if parsed.Host != "github.com" || parsed.Query().Get("redirect_uri") != "https://app.test/auth/github/callback" { - t.Errorf("url = %s", authURL) + if m.config.Key != "from-env" || m.config.APIURL != "https://env.example" { + t.Errorf("config = %+v", m.config) } - cookies := recorder.Result().Cookies() - if len(cookies) != 1 || cookies[0].Name != "sociable" || !cookies[0].HttpOnly || !cookies[0].Secure { - t.Errorf("cookies = %+v", cookies) - } + m = New(WithKey("from-option"), WithAPIURL("https://option.example")) - if err := sociable.Driver("nope").Redirect(recorder, httptest.NewRequest(http.MethodGet, "/", nil)); !errors.Is(err, sociable.ErrUnknownDriver) { - t.Errorf("err = %v", err) + if m.config.Key != "from-option" || m.config.APIURL != "https://option.example" { + t.Errorf("options did not win: %+v", m.config) } } -// A fake needs no configuration at all, the way Socialite::fake needs none. -func TestFakeNeedsNoConfiguration(t *testing.T) { - var auth sociable.Manager +func TestConfigureStartsOver(t *testing.T) { + t.Parallel() - fake := auth.Fake("google", sociable.User{ID: "1"}) + session := &memorySession{values: map[string]string{}} + m := New(WithKey("k"), WithSession(session), WithDriver[stub]("stub", Credentials{})) - recorder := httptest.NewRecorder() - err := auth.Driver("google"). - Scopes("https://www.googleapis.com/auth/drive.readonly"). - WithState(map[string]string{"invite": "abc"}). - Redirect(recorder, httptest.NewRequest(http.MethodGet, "/auth/google", nil)) - if err != nil { - t.Fatal(err) + if m.config.Session != session { + t.Error("session not set") } - fake.AssertRedirected(t, func(r sociable.Redirect) bool { - return slices.Contains(r.Scopes, "https://www.googleapis.com/auth/drive.readonly") && r.State["invite"] == "abc" - }) - fake.AssertNotRedirected(t, func(r sociable.Redirect) bool { return r.Params["prompt"] == "consent" }) - fake.AssertRedirectedCount(t, 1) - - user, err := auth.Driver("google").User(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/auth/google/callback", nil)) - if err != nil { - t.Fatal(err) + if _, ok := m.config.Drivers["stub"]; !ok { + t.Error("driver not registered") } - // What was given stays; what was not gets Socialite's fake user's values. - if user.ID != "1" || user.Name != "Test User" || user.Email != "test@example.com" || user.Token.AccessToken != "fake-token" { - t.Errorf("user = %+v", user) - } -} + m.Configure(WithKey("other")) -func TestDriversAreBuiltOnceUnderConcurrency(t *testing.T) { - auth, err := sociable.New(sociable.Config{ - Key: "k", - URL: "https://app.test", - Drivers: sociable.Drivers{"github": {ClientID: "id", ClientSecret: "s", Redirect: "/cb"}}, - }) - if err != nil { - t.Fatal(err) + if m.config.Key != "other" || m.config.Session != nil || len(m.config.Drivers) != 0 { + t.Errorf("not from scratch: %+v", m.config) } - - var wait sync.WaitGroup - for range 32 { - wait.Go(func() { - if _, err := auth.Driver("github").AuthURL(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)); err != nil { - t.Error(err) - } - }) - } - wait.Wait() } -func TestAFakeAnswersEveryCall(t *testing.T) { - var auth sociable.Manager - - fake := auth.Fake("google", sociable.User{State: map[string]string{"user_id": "7"}}) +func TestUnknownDriver(t *testing.T) { + t.Parallel() - user, err := auth.Driver("google").User(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/cb", nil)) - if err != nil || user.State["user_id"] != "7" { - t.Fatalf("user = %+v, err = %v", user, err) - } + m := New(WithKey("k")) + w, r := httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil) - token, err := auth.Driver("google").RefreshToken(t.Context(), "r") - if err != nil || token.AccessToken != "fake-token" { - t.Errorf("token = %+v, err = %v", token, err) + if err := m.Driver("nope").Redirect(w, r); !errors.Is(err, ErrUnknownDriver) { + t.Errorf("Redirect: %v", err) } - if client := auth.Driver("google").Client(t.Context(), token); client == nil { - t.Error("no client") + if _, err := m.Driver("nope").User(w, r); !errors.Is(err, ErrUnknownDriver) { + t.Errorf("User: %v", err) } - fake.Restore() - - if err := auth.Driver("google").Redirect(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)); !errors.Is(err, sociable.ErrUnknownDriver) { - t.Errorf("after restore err = %v", err) + if _, err := m.Driver("nope").UserFromToken(t.Context(), nil); !errors.Is(err, ErrUnknownDriver) { + t.Errorf("UserFromToken: %v", err) } -} -func TestARelativeRedirectNeedsTheApplicationURL(t *testing.T) { - auth, err := sociable.New(sociable.Config{ - Key: "k", - Drivers: sociable.Drivers{"github": {ClientID: "id", ClientSecret: "s", Redirect: "/cb"}}, - }) - if err != nil { - t.Fatal(err) + if _, err := m.Driver("nope").RefreshToken(t.Context(), "r"); !errors.Is(err, ErrUnknownDriver) { + t.Errorf("RefreshToken: %v", err) } - _, err = auth.Driver("github").AuthURL(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) - if !errors.Is(err, sociable.ErrNotConfigured) { - t.Errorf("err = %v", err) + // The chain must not panic on a driver that has no provider. + err := m.Driver("nope").Scopes("x").SetScopes("y").With(map[string]string{"a": "b"}).RedirectURL("/x").Stateless().Redirect(w, r) + if !errors.Is(err, ErrUnknownDriver) { + t.Errorf("chained Redirect: %v", err) } } diff --git a/token_test.go b/token_test.go new file mode 100644 index 0000000..55874da --- /dev/null +++ b/token_test.go @@ -0,0 +1,59 @@ +package sociable + +import ( + "errors" + "testing" + + "golang.org/x/oauth2" +) + +func TestUserFromToken(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + m := manager[stub](server) + + token := &oauth2.Token{AccessToken: "at"} + + user, err := m.Driver("stub").UserFromToken(t.Context(), token) + if err != nil { + t.Fatal(err) + } + + if user.ID != "42" || user.Token != token || server.auth != "Bearer at" { + t.Errorf("user = %+v, fetched with %q", user, server.auth) + } + + server.profile = nil + + if _, err := m.Driver("stub").UserFromToken(t.Context(), token); !errors.Is(err, ErrProfile) { + t.Errorf("failed profile: %v", err) + } +} + +func TestRefreshToken(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + server.token = map[string]any{"access_token": "fresh", "refresh_token": "next", "token_type": "bearer", "expires_in": 3600} + m := manager[stub](server) + + token, err := m.Driver("stub").RefreshToken(t.Context(), "old") + if err != nil { + t.Fatal(err) + } + + if token.AccessToken != "fresh" || token.RefreshToken != "next" || token.Expiry.IsZero() { + t.Errorf("token = %+v", token) + } + + if server.form.Get("grant_type") != "refresh_token" || server.form.Get("refresh_token") != "old" { + t.Errorf("posted %v", server.form) + } + + server.token = nil + + if _, err := m.Driver("stub").RefreshToken(t.Context(), "old"); !errors.Is(err, ErrExchange) { + t.Errorf("failed refresh: %v", err) + } +} diff --git a/user.go b/user.go deleted file mode 100644 index 9910dcc..0000000 --- a/user.go +++ /dev/null @@ -1,31 +0,0 @@ -package sociable - -import "golang.org/x/oauth2" - -// User is who the provider vouches for. -type User struct { - // ID is the provider's stable identifier for this person. Store this, - // not the email, which can change. - ID string - - Nickname string - Name string - Email string - EmailVerified bool - Avatar string - - // Raw is the provider's own document: the profile, or the ID token's - // claims. - Raw map[string]any - - // Token carries the access token, the refresh token when the provider - // issued one, and the expiry. - Token *oauth2.Token - - // ApprovedScopes are the scopes the provider granted, which need not be - // the ones that were asked for. - ApprovedScopes []string - - // State is what the call site put in with WithState. - State map[string]string -} diff --git a/user_test.go b/user_test.go new file mode 100644 index 0000000..fe5b148 --- /dev/null +++ b/user_test.go @@ -0,0 +1,365 @@ +package sociable + +import ( + "crypto/rand" + "crypto/rsa" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "slices" + "testing" + "time" + + "golang.org/x/oauth2" +) + +func TestUserSignsIn(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + m := manager[stub](server) + + user, err := signIn(t, m.Driver("stub")) + if err != nil { + t.Fatal(err) + } + + if user.ID != "42" || user.Name != "Test User" { + t.Errorf("user = %+v", user) + } + + if user.Token == nil || user.Token.AccessToken != "at" { + t.Errorf("token = %+v", user.Token) + } + + if !slices.Equal(user.ApprovedScopes, []string{"a", "b"}) { + t.Errorf("approved = %v", user.ApprovedScopes) + } + + if server.form.Get("code") != "c" || server.form.Get("grant_type") != "authorization_code" { + t.Errorf("exchange posted %v", server.form) + } + + if server.form.Get("redirect_uri") != "https://app.example/cb" { + t.Errorf("exchange redirect_uri = %q", server.form.Get("redirect_uri")) + } + + if server.form.Get("code_verifier") == "" { + t.Error("verifier not posted") + } + + if server.auth != "Bearer at" { + t.Errorf("profile fetched with %q", server.auth) + } +} + +func TestApprovedScopes(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + server.token = map[string]any{"access_token": "at", "token_type": "bearer", "scope": "a,b"} + + user, err := signIn(t, manager[commaStub](server).Driver("stub")) + if err != nil { + t.Fatal(err) + } + + if !slices.Equal(user.ApprovedScopes, []string{"a", "b"}) { + t.Errorf("comma separated: %v", user.ApprovedScopes) + } + + server.token = map[string]any{"access_token": "at", "token_type": "bearer"} + + user, err = signIn(t, manager[stub](server).Driver("stub")) + if err != nil { + t.Fatal(err) + } + + if user.ApprovedScopes != nil { + t.Errorf("no scope in the response: %v", user.ApprovedScopes) + } + + // A provider that names no separator is split on the space. + granted := (&oauth2.Token{}).WithExtra(map[string]any{"scope": "a b"}) + if got := approved(granted, ""); !slices.Equal(got, []string{"a", "b"}) { + t.Errorf("no separator: %v", got) + } +} + +func TestCallbackRejectsAnInvalidState(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + m := manager[stub](server) + + query, cookies := redirected(t, m.Driver("stub")) + state := query.Get("state") + + forged := []*http.Cookie{{Name: sessionKey, Value: "not-a-sealed-value"}} + + session, _ := newCookieSession("test-key", false) + + sealed := func(payload string) []*http.Cookie { + recorder := httptest.NewRecorder() + _ = session.Put(recorder, httptest.NewRequest(http.MethodGet, "/", nil), sessionKey, payload) + + return recorder.Result().Cookies() + } + + expired, _ := json.Marshal(handshake{State: state, ExpiresAt: time.Now().Add(-time.Second)}) + + cases := map[string]*http.Request{ + "no cookie": callback("code=c&state="+state, nil), + "forged cookie": callback("code=c&state="+state, forged), + "other state": callback("code=c&state=other", cookies), + "no state": callback("code=c", cookies), + "not json": callback("code=c&state="+state, sealed("{")), + "expired": callback("code=c&state="+state, sealed(string(expired))), + } + + for name, request := range cases { + t.Run(name, func(t *testing.T) { + recorder := httptest.NewRecorder() + + if _, err := m.Driver("stub").User(recorder, request); !errors.Is(err, ErrInvalidState) { + t.Errorf("err = %v", err) + } + + if server.form != nil { + t.Error("the code was exchanged") + } + }) + } +} + +func TestCallbackSpendsTheHandshake(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + m := manager[stub](server) + + query, cookies := redirected(t, m.Driver("stub")) + request := callback("code=c&state="+query.Get("state"), cookies) + + recorder := httptest.NewRecorder() + if _, err := m.Driver("stub").User(recorder, request); err != nil { + t.Fatal(err) + } + + // The cookie is cleared on the response, so the browser no longer has + // it and the same callback again has no handshake to check against. + cleared := recorder.Result().Cookies() + if len(cleared) != 1 || cleared[0].MaxAge != -1 || cleared[0].Value != "" { + t.Errorf("cookie not cleared: %v", cleared) + } + + server.form = nil + + if _, err := m.Driver("stub").User(httptest.NewRecorder(), callback("code=c&state="+query.Get("state"), nil)); !errors.Is(err, ErrInvalidState) { + t.Errorf("replay: %v", err) + } + + if server.form != nil { + t.Error("the code was exchanged again") + } +} + +func TestCallbackReportsARefusal(t *testing.T) { + t.Parallel() + + m := manager[stub](newProviderServer(t)) + + query, cookies := redirected(t, m.Driver("stub")) + + _, err := m.Driver("stub").User(httptest.NewRecorder(), + callback("error=access_denied&error_description=The+user+said+no&error_uri=https://x/e&state="+query.Get("state"), cookies)) + + if !errors.Is(err, ErrAccessDenied) || !errors.Is(err, ErrAuthorization) { + t.Errorf("err = %v", err) + } + + var refusal *AuthorizationError + if !errors.As(err, &refusal) || refusal.Code != "access_denied" || refusal.Description != "The user said no" || refusal.URI != "https://x/e" { + t.Errorf("refusal = %+v", refusal) + } + + query, cookies = redirected(t, m.Driver("stub")) + + _, err = m.Driver("stub").User(httptest.NewRecorder(), callback("error=server_error&state="+query.Get("state"), cookies)) + + if errors.Is(err, ErrAccessDenied) || !errors.Is(err, ErrAuthorization) { + t.Errorf("other refusal: %v", err) + } +} + +func TestCallbackReportsAFailedExchange(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + server.token = nil + + if _, err := signIn(t, manager[stub](server).Driver("stub")); !errors.Is(err, ErrExchange) { + t.Errorf("err = %v", err) + } +} + +func TestUserReportsAFailedProfile(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + server.profile = nil + + if _, err := signIn(t, manager[stub](server).Driver("stub")); !errors.Is(err, ErrProfile) { + t.Errorf("fetch failed: %v", err) + } + + server.profile = map[string]any{"id": "42"} + + if _, err := signIn(t, manager[badMapStub](server).Driver("stub")); !errors.Is(err, ErrProfile) { + t.Errorf("map failed: %v", err) + } +} + +func TestCallbackStateless(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + m := manager[stub](server) + + user, err := m.Driver("stub").Stateless().User(httptest.NewRecorder(), callback("code=c", nil)) + if err != nil || user.ID != "42" { + t.Fatalf("user = %+v, %v", user, err) + } + + if server.form.Has("code_verifier") { + t.Error("verifier posted with nothing to keep it") + } +} + +func TestCallbackHandsBackTheToken(t *testing.T) { + t.Parallel() + + server := newProviderServer(t) + m := manager[stub](server) + + query, cookies := redirected(t, m.Driver("stub")) + + token, err := m.Driver("stub").Callback(httptest.NewRecorder(), callback("code=c&state="+query.Get("state"), cookies)) + if err != nil || token.AccessToken != "at" { + t.Errorf("token = %+v, %v", token, err) + } + + if server.auth != "" { + t.Error("the profile was fetched") + } +} + +// The OpenID Connect tests share the issuer through oidcIssuer, so they run +// one after another. +func TestIDToken(t *testing.T) { + provider := newIssuer(t) + oidcIssuer = provider.URL + + other, _ := rsa.GenerateKey(rand.Reader, 2048) + + // begin redirects and returns the callback request and the nonce issued. + begin := func(t *testing.T, d DriverContract) (*http.Request, string) { + t.Helper() + + query, cookies := redirected(t, d) + + return callback("code=c&state="+query.Get("state"), cookies), query.Get("nonce") + } + + t.Run("verified", func(t *testing.T) { + server := newProviderServer(t) + m := manager[openidStub](server) + + request, nonce := begin(t, m.Driver("stub")) + server.token["id_token"] = provider.idToken(t, "id", nonce, nil) + + user, err := m.Driver("stub").User(httptest.NewRecorder(), request) + if err != nil || user.ID != "42" { + t.Errorf("user = %+v, %v", user, err) + } + }) + + t.Run("second sign-in uses the cached discovery", func(t *testing.T) { + server := newProviderServer(t) + m := manager[openidStub](server) + + request, nonce := begin(t, m.Driver("stub")) + server.token["id_token"] = provider.idToken(t, "id", nonce, nil) + + if _, ok := issuers.Load(provider.URL); !ok { + t.Fatal("discovery not cached") + } + + if _, err := m.Driver("stub").User(httptest.NewRecorder(), request); err != nil { + t.Error(err) + } + }) + + failures := map[string]func(t *testing.T, nonce string) any{ + "missing": func(*testing.T, string) any { return nil }, + "wrong nonce": func(t *testing.T, _ string) any { return provider.idToken(t, "id", "other", nil) }, + "wrong key": func(t *testing.T, nonce string) any { return provider.idToken(t, "id", nonce, other) }, + "wrong audience": func(t *testing.T, nonce string) any { return provider.idToken(t, "someone-else", nonce, nil) }, + "garbage": func(*testing.T, string) any { return "not.a.jwt" }, + } + + for name, idToken := range failures { + t.Run(name, func(t *testing.T) { + server := newProviderServer(t) + m := manager[openidStub](server) + + request, nonce := begin(t, m.Driver("stub")) + + if token := idToken(t, nonce); token != nil { + server.token["id_token"] = token + } + + if _, err := m.Driver("stub").User(httptest.NewRecorder(), request); !errors.Is(err, ErrIDToken) { + t.Errorf("err = %v", err) + } + }) + } + + t.Run("no verification without openid", func(t *testing.T) { + server := newProviderServer(t) + m := manager[openidStub](server) + + user, err := signIn(t, m.Driver("stub").SetScopes("a")) + if err != nil || user.ID != "42" { + t.Errorf("user = %+v, %v", user, err) + } + }) + + t.Run("stateless verifies without a nonce", func(t *testing.T) { + server := newProviderServer(t) + m := manager[openidStub](server) + server.token["id_token"] = provider.idToken(t, "id", "whatever", nil) + + user, err := m.Driver("stub").Stateless().User(httptest.NewRecorder(), callback("code=c", nil)) + if err != nil || user.ID != "42" { + t.Errorf("user = %+v, %v", user, err) + } + }) + + t.Run("discovery fails", func(t *testing.T) { + gone := newIssuer(t) + gone.Close() + oidcIssuer = gone.URL + + server := newProviderServer(t) + m := manager[openidStub](server) + + request, nonce := begin(t, m.Driver("stub")) + server.token["id_token"] = provider.idToken(t, "id", nonce, nil) + + if _, err := m.Driver("stub").User(httptest.NewRecorder(), request); !errors.Is(err, ErrIDToken) { + t.Errorf("err = %v", err) + } + }) +}