From 28d11977f71268e7d2b38e563611826009deb664 Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Thu, 17 Sep 2026 10:04:20 +0200 Subject: [PATCH] feat!: sociable, shaped after socialite The package is sociable, and its surface is Laravel Socialite's: Configure once at boot with a key and a map of driver credentials, Driver(name) with Scopes, SetScopes, RedirectURL, With, WithState and Stateless on the chain, then Redirect and User in the handlers. Nine drivers are built in and picked by name: google, github, gitlab, facebook, linkedin, bitbucket, slack, twitch and x. Extend registers a provider under a name; OpenID and OAuth2 describe one without a type of its own, and a provider that is not OAuth at all owns its Redirect and Callback. Fake swaps a driver for one that returns a test user and records every redirect, for asserting on. PKCE, the nonce, the verified ID token, the constant-time state check and the encrypted handshake cookie are on and unmentioned. Everything x/oauth2 already has is used from there: Config, endpoints, the PKCE helpers, the token and the client. Providers get an *http.Client that presents the token. --- README.md | 270 ++++++++++++++--------- e2e_test.go | 266 ----------------------- errors.go | 76 +++---- fake.go | 107 +++++++++ flow.go | 489 +++++++++++++++++++++++++++--------------- flow_test.go | 486 ++++++++++++++--------------------------- github/github.go | 123 ----------- github/github_test.go | 58 ----- go.mod | 5 +- google/google.go | 45 ---- google/google_test.go | 22 -- handshake.go | 175 --------------- helpers_test.go | 281 +++++++++++++++--------- oauth2.go | 130 ----------- oauth2_test.go | 76 ------- oidc.go | 186 ---------------- oidc_test.go | 213 ------------------ openid.go | 120 +++++++++++ openid_test.go | 133 ++++++++++++ options.go | 77 ------- provider.go | 192 ++++++++++++----- providers.go | 251 ++++++++++++++++++++++ providers_test.go | 166 ++++++++++++++ sealer.go | 61 ------ sealer_test.go | 57 ----- session.go | 127 +++++++++++ sociable.go | 249 +++++++++++++++++++++ sociable_test.go | 137 ++++++++++++ social.go | 205 ------------------ user.go | 45 ++-- 30 files changed, 2307 insertions(+), 2521 deletions(-) delete mode 100644 e2e_test.go create mode 100644 fake.go delete mode 100644 github/github.go delete mode 100644 github/github_test.go delete mode 100644 google/google.go delete mode 100644 google/google_test.go delete mode 100644 handshake.go delete mode 100644 oauth2.go delete mode 100644 oauth2_test.go delete mode 100644 oidc.go delete mode 100644 oidc_test.go create mode 100644 openid.go create mode 100644 openid_test.go delete mode 100644 options.go create mode 100644 providers.go create mode 100644 providers_test.go delete mode 100644 sealer.go delete mode 100644 sealer_test.go create mode 100644 session.go create mode 100644 sociable.go create mode 100644 sociable_test.go delete mode 100644 social.go diff --git a/README.md b/README.md index 3994d49..409573a 100644 --- a/README.md +++ b/README.md @@ -1,133 +1,203 @@ -# social +# sociable -Sign people in with somebody else's account. The OAuth 2.0 authorization code -flow with PKCE, and OpenID Connect on top of it, on plain `net/http`, for any -provider. +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. ```go -auth, err := social.New(social.Configuration{ - Sealer: sealer, // encrypts the handshake cookie; social.AESSealer(key) will do - Drivers: social.Drivers{ - "google": google.New(google.Options{ClientID: id, ClientSecret: secret, RedirectURL: "https://app/auth/google/callback"}), - "github": github.New(github.Options{ClientID: id, ClientSecret: secret, RedirectURL: "https://app/auth/github/callback"}), +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"}, }, }) +``` -// The handler that starts it. -err := auth.Redirect(w, r, "google", social.To("/dashboard")) +```go +http.HandleFunc("/auth/github", func(w http.ResponseWriter, r *http.Request) { + sociable.Driver("github").Redirect(w, r) +}) -// The handler the provider sends the browser back to. -result, err := auth.Callback(w, r, "google") -// result.User, result.RedirectTo +http.HandleFunc("/auth/github/callback", func(w http.ResponseWriter, r *http.Request) { + user, err := sociable.Driver("github").User(w, r) + if err != nil { + http.Error(w, "sign-in failed", http.StatusBadRequest) + return + } + + 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 +}) ``` -`result.User` carries the stable `ID`, `Email` and whether the provider -verified it, `Name`, `Nickname`, `Avatar`, the provider's `Raw` claims or -profile, the `Token`, and the scopes that were actually `ApprovedScopes`. -What to do with that person is the application's business; social stops at -the identity. - -## What it does that most clients do not - -- **PKCE is on** unless a provider says it cannot. OAuth 2.1 requires it of - every client; here opting out is the decision that has to be written down. -- **ID tokens are verified.** An OpenID Connect provider's token is checked - for its signature against the issuer's published keys, its issuer, its - audience, its expiry and the nonce this package sent. The identity comes - from those claims, with no profile request. -- **A refusal is an answer.** A provider that sends `error=access_denied` - back is `ErrAccessDenied`, so a cancelled sign-in is not reported as a - broken one. Every refusal matches `ErrAuthorization`. -- **The issuer parameter is checked** (RFC 9207) for a provider that asks - for it, which is what defeats a mix-up between two authorization servers. -- **State is compared in constant time**, the handshake carries its own - expiry, and any callback spends it whether it succeeds or not. -- **Granted scopes come back on the user**, because RFC 6749 lets them - differ from the ones requested. -- **Open redirects are refused**: the path to land on after sign-in must be - a path on this site. - -## Shaping a request - -Options trail the call and most calls have none: +## Configuration + +| Field | | +|---|---| +| `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. | + +`Redirect` is a full URL, or a path resolved against `URL`. + +## Shaping the redirect + +All optional, all chainable: ```go -auth.Redirect(w, r, "google", - social.To("/settings/integrations"), // where to land afterwards - social.Scopes("https://www.googleapis.com/auth/drive.readonly"), // add to the provider's - social.With(map[string]string{"login_hint": address}), // extra authorization parameters -) +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"}). + 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) ``` -`SetScopes` replaces instead of adds. `RedirectURL` overrides the callback. -`Stateless` runs a flow this server did not start, for a native app that -brings back its own code, and gives up state and PKCE with it. `UsingPKCE` -and `WithoutPKCE` override the provider for one request. +`WithState` carries values through the flow. They come back on `user.State` +at the callback and never travel through the provider: -`AuthorizationURL` is `Redirect` without the redirect, when the handler -sends the browser itself. `UserFromToken` reads an identity for a token the -application already holds. `Refresh` trades a refresh token for a live one. +```go +sociable.Driver("github").WithState(map[string]string{"invite": code}).Redirect(w, r) -## Providers +user, _ := sociable.Driver("github").User(w, r) +user.State["invite"] +``` -`google` (OpenID Connect through discovery) and `github` are included. Any -OpenID Connect provider is a `social.OpenIDConnect` with an issuer, and -endpoints and keys come from discovery: +`AuthURL(w, r)` is `Redirect` without the redirecting, for a handler that +sends the browser itself. + +## Tokens ```go -"okta": &social.OpenIDConnect{Driver: "okta", IssuerURL: "https://acme.okta.com", ClientID: id, ClientSecret: secret, RedirectURL: callback}, +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 ``` -Any plain OAuth 2 provider is a `social.OAuth2` described by its endpoints: +`Stateless()` runs a callback this server did not start, for a native app +that brings its own code. + +## Errors ```go -"acme": &social.OAuth2{ - Driver: "acme", ClientID: id, ClientSecret: secret, RedirectURL: callback, - AuthURL: "https://acme.example/oauth/authorize", - TokenURL: "https://acme.example/oauth/token", - ProfileURL: "https://acme.example/api/me", - Scopes: []string{"profile"}, - Profile: func(raw map[string]any) social.User { - return social.User{ID: social.String(raw, "id"), Email: social.String(raw, "email")} - }, -}, +user, err := sociable.Driver("github").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 +} ``` -A provider with more to say implements `social.Provider` itself, and the -optional `Parameterised`, `Unprotected` and `Issued` interfaces. +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`. -## Errors +## Your own provider -All typed, none to parse: +Any OpenID Connect provider is its issuer: -| Error | Meaning | -|---|---| -| `ErrUnknownDriver` | no provider registered under that name | -| `ErrNotConfigured` | the provider has no credentials, or discovery failed; refuse the route rather than redirect | -| `ErrNoHandshake` | the callback was never started here, was already used, or expired | -| `ErrStateMismatch` | the state is not the one issued | -| `ErrIssuerMismatch` | another authorization server answered | -| `ErrAuthorization`, `ErrAccessDenied` | the provider refused; `*AuthorizationError` carries its words | -| `ErrExchange` | the code could not be exchanged, or the token is not usable | -| `ErrIDToken` | the ID token failed verification: signature, issuer, audience, expiry or nonce | -| `ErrProfile` | the provider would not describe the user | +```go +sociable.Extend("okta", func(c sociable.Credentials) sociable.Provider { + return sociable.OpenID(c, "https://acme.okta.com") +}) +``` -## Configuration +Any OAuth 2 provider is its endpoints and a mapping: + +```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")} + }, + } +}) +``` -`Sealer` is required: it encrypts the handshake so the browser can hold it. -`AESSealer(key)` is one; an application with its own encryption hands that -over instead. `Cookie` mirrors the session cookie's attributes and defaults -to `social_handshake`, path `/`, `Lax`, ten minutes. `Client` is the HTTP -client used to talk to providers: discovery, keys, the exchange and the -profile; give it a traced transport to see them. +Then it is configured and used like a built-in: -One handshake lives in the browser at a time, so two sign-ins started in two -tabs resolve the later one. That is the cost of a cookie handshake and the -reason it needs no server-side store. +```go +"acme": {ClientID: id, ClientSecret: secret, Redirect: "/auth/acme/callback"}, +sociable.Driver("acme").Redirect(w, r) +``` + +A provider with more to read than one document implements `User` itself. +It gets an `*http.Client` that already presents the token: + +```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 + } + // ... +} +``` + +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 -The suite runs the whole flow through fake providers with a cookie-carrying -client: redirect, consent, callback, the code exchange with the verifier -checked, the profile fetch or the ID token verified, and the refusals, -replays, wrong audiences, wrong issuers and wrong nonces in between. +`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: + +```go +fake := sociable.Fake("github", sociable.User{Email: "arjen@example.test"}) +t.Cleanup(fake.Restore) + +recorder := httptest.NewRecorder() +app.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. + +## 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. + +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/e2e_test.go b/e2e_test.go deleted file mode 100644 index b80a748..0000000 --- a/e2e_test.go +++ /dev/null @@ -1,266 +0,0 @@ -package social_test - -import ( - "crypto/sha256" - "encoding/base64" - "encoding/json" - "errors" - "net/http" - "net/http/cookiejar" - "net/http/httptest" - "net/url" - "strings" - "testing" - - "github.com/gonstruct/social" -) - -// authorizationServer is a provider that behaves: it redirects back with a -// code, exchanges it only for the right verifier and client secret, and -// describes the user for the right bearer token. -type authorizationServer struct { - *httptest.Server - - deny bool - challenge string - scope string - tokenSeen url.Values -} - -func newAuthorizationServer(t *testing.T) *authorizationServer { - t.Helper() - - as := &authorizationServer{} - mux := http.NewServeMux() - - mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) { - query := r.URL.Query() - as.challenge = query.Get("code_challenge") - as.scope = query.Get("scope") - - back, _ := url.Parse(query.Get("redirect_uri")) - values := url.Values{"state": {query.Get("state")}, "iss": {as.URL}} - if as.deny { - values.Set("error", "access_denied") - values.Set("error_description", "The user declined") - } else { - values.Set("code", "the-code") - } - back.RawQuery = values.Encode() - http.Redirect(w, r, back.String(), http.StatusFound) - }) - - mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { - _ = r.ParseForm() - as.tokenSeen = r.PostForm - - id, secret, ok := r.BasicAuth() - if !ok { - id, secret = r.PostForm.Get("client_id"), r.PostForm.Get("client_secret") - } - sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier"))) - verifier := base64.RawURLEncoding.EncodeToString(sum[:]) - - switch { - case id != "app-id" || secret != "app-secret": - http.Error(w, `{"error":"invalid_client"}`, http.StatusUnauthorized) - case r.PostForm.Get("grant_type") != "authorization_code" || r.PostForm.Get("code") != "the-code": - http.Error(w, `{"error":"invalid_grant"}`, http.StatusBadRequest) - case verifier != as.challenge: - http.Error(w, `{"error":"invalid_grant","error_description":"verifier"}`, http.StatusBadRequest) - default: - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]any{ - "access_token": "the-token", "token_type": "Bearer", "expires_in": 3600, "scope": "profile email", - }) - } - }) - - mux.HandleFunc("/userinfo", func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Authorization") != "Bearer the-token" { - http.Error(w, "no", http.StatusUnauthorized) - return - } - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]any{ - "sub": "person-1", "email": "person@example.com", "email_verified": true, "name": "A Person", "picture": "https://cdn/p.png", - }) - }) - - as.Server = httptest.NewServer(mux) - t.Cleanup(as.Close) - - return as -} - -// application is the site signing people in: two handlers on social. -type application struct { - *httptest.Server - - auth *social.Social -} - -func newApplication(t *testing.T, provider func(app *application) social.Provider) *application { - t.Helper() - - app := &application{} - mux := http.NewServeMux() - app.Server = httptest.NewServer(mux) - t.Cleanup(app.Close) - - sealer, err := social.AESSealer([]byte("0123456789abcdef0123456789abcdef")) - if err != nil { - t.Fatal(err) - } - app.auth, err = social.New(social.Configuration{Sealer: sealer, Drivers: social.Drivers{"acme": provider(app)}}) - if err != nil { - t.Fatal(err) - } - - mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { - if err := app.auth.Redirect(w, r, "acme", social.To(r.URL.Query().Get("to"))); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { - result, err := app.auth.Callback(w, r, "acme") - if err != nil { - status := http.StatusBadGateway - if errors.Is(err, social.ErrAccessDenied) { - status = http.StatusForbidden - } - http.Error(w, err.Error(), status) - return - } - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]any{ - "id": result.User.ID, "email": result.User.Email, "verified": result.User.EmailVerified, "name": result.User.Name, - "scopes": result.User.ApprovedScopes, "redirectTo": result.RedirectTo, "token": result.User.Token.AccessToken, - }) - }) - - return app -} - -func oauth2Provider(as *authorizationServer, secret string) func(app *application) social.Provider { - return func(app *application) social.Provider { - return &social.OAuth2{ - Driver: "acme", ClientID: "app-id", ClientSecret: secret, RedirectURL: app.URL + "/callback", - AuthURL: as.URL + "/authorize", TokenURL: as.URL + "/token", ProfileURL: as.URL + "/userinfo", - IssuerURL: as.URL, Scopes: []string{"profile", "email"}, - Profile: func(raw map[string]any) social.User { - return social.User{ - ID: social.String(raw, "sub"), Email: social.String(raw, "email"), - EmailVerified: social.Bool(raw, "email_verified"), Name: social.String(raw, "name"), - } - }, - } - } -} - -// browser follows redirects and keeps cookies, like the real thing. -func browser(t *testing.T) *http.Client { - t.Helper() - - jar, err := cookiejar.New(nil) - if err != nil { - t.Fatal(err) - } - - return &http.Client{Jar: jar} -} - -type signedIn struct { - ID, Email, Name, RedirectTo, Token string - Verified bool - Scopes []string -} - -func signIn(t *testing.T, client *http.Client, app *application, path string) (signedIn, *http.Response) { - t.Helper() - - response, err := client.Get(app.URL + path) - if err != nil { - t.Fatal(err) - } - defer response.Body.Close() - - var result signedIn - if response.StatusCode == http.StatusOK { - if err := json.NewDecoder(response.Body).Decode(&result); err != nil { - t.Fatal(err) - } - } - - return result, response -} - -func TestEndToEndSignIn(t *testing.T) { - as := newAuthorizationServer(t) - app := newApplication(t, oauth2Provider(as, "app-secret")) - client := browser(t) - - result, response := signIn(t, client, app, "/login?to=/dashboard") - if response.StatusCode != http.StatusOK { - t.Fatalf("expected the callback to answer 200, got %d", response.StatusCode) - } - if result.ID != "person-1" || result.Email != "person@example.com" || !result.Verified || result.Name != "A Person" { - t.Errorf("wrong user: %+v", result) - } - if result.RedirectTo != "/dashboard" || result.Token != "the-token" || strings.Join(result.Scopes, " ") != "profile email" { - t.Errorf("result: %+v", result) - } - - // What the provider saw: PKCE with the matching verifier, the redirect - // URI and the scopes. - if as.tokenSeen.Get("code_verifier") == "" || as.tokenSeen.Get("redirect_uri") != app.URL+"/callback" || as.scope != "profile email" { - t.Errorf("token request: %v, scope %q", as.tokenSeen, as.scope) - } - - // The handshake is spent: the browser no longer holds the cookie. - appURL, _ := url.Parse(app.URL) - for _, cookie := range client.Jar.Cookies(appURL) { - if cookie.Name == "social_handshake" { - t.Error("the handshake cookie survived the callback") - } - } -} - -func TestEndToEndDenial(t *testing.T) { - as := newAuthorizationServer(t) - as.deny = true - app := newApplication(t, oauth2Provider(as, "app-secret")) - - if _, response := signIn(t, browser(t), app, "/login"); response.StatusCode != http.StatusForbidden { - t.Fatalf("a denial should reach the app as a denial, got %d", response.StatusCode) - } - if as.tokenSeen != nil { - t.Error("a denial must never be exchanged") - } -} - -func TestEndToEndReplayedCallbackIsRefused(t *testing.T) { - as := newAuthorizationServer(t) - app := newApplication(t, oauth2Provider(as, "app-secret")) - client := browser(t) - - _, first := signIn(t, client, app, "/login") - replayed, err := client.Get(first.Request.URL.String()) - if err != nil { - t.Fatal(err) - } - defer replayed.Body.Close() - - if replayed.StatusCode == http.StatusOK { - t.Fatal("a callback without a live handshake must not sign anyone in") - } -} - -func TestEndToEndWrongSecretFailsTheExchange(t *testing.T) { - as := newAuthorizationServer(t) - app := newApplication(t, oauth2Provider(as, "wrong")) - - if _, response := signIn(t, browser(t), app, "/login"); response.StatusCode != http.StatusBadGateway { - t.Fatalf("expected the exchange to fail, got %d", response.StatusCode) - } -} diff --git a/errors.go b/errors.go index a5439ec..08e6bdb 100644 --- a/errors.go +++ b/errors.go @@ -1,54 +1,42 @@ -package social +package sociable import ( "errors" "fmt" - "strings" ) var ( - // ErrNotConfigured means the driver has no credentials. Environments - // without them should refuse the route rather than redirect somewhere - // half-built. - ErrNotConfigured = errors.New("social: driver is not configured") + // ErrUnknownDriver means no driver is configured under that name. + ErrUnknownDriver = errors.New("sociable: unknown driver") - // ErrNoHandshake means this callback was never started here, was already - // used, or was started too long ago. All three are indistinguishable to the - // caller on purpose. - ErrNoHandshake = errors.New("social: no handshake for this callback") + // 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") - // ErrStateMismatch means the state did not match the one issued, which is - // what RFC 6749 section 10.12 asks a client to check. - ErrStateMismatch = errors.New("social: state does not match") + // ErrInvalidState means the callback was not started here, was already + // used, expired, or came back with another state. + ErrInvalidState = errors.New("sociable: invalid state") - // ErrIssuerMismatch means the authorization server that answered is not the - // one the browser was sent to. RFC 9207 adds the iss parameter for exactly - // this, and a client that expects it must reject a response without it. - ErrIssuerMismatch = errors.New("social: the response came from another issuer") + // ErrAuthorization is what every provider refusal matches. + ErrAuthorization = errors.New("sociable: the provider refused") - // ErrExchange means the authorization code could not be exchanged, or what - // came back was not a token this package can use. - ErrExchange = errors.New("social: failed to exchange the authorization code") + // ErrAccessDenied is the refusal that means the person said no. + ErrAccessDenied = fmt.Errorf("%w: access denied", ErrAuthorization) - // ErrProfile means the provider would not describe the user. - ErrProfile = errors.New("social: failed to read the profile") + // ErrExchange means the code could not be exchanged for a token, or the + // token is not usable. + ErrExchange = errors.New("sociable: token exchange failed") - // ErrUnknownDriver means no provider is registered under that name. - ErrUnknownDriver = errors.New("social: unknown driver") + // ErrIDToken means the ID token failed verification: signature, issuer, + // audience, expiry or nonce. + ErrIDToken = errors.New("sociable: the id token could not be verified") - // ErrAuthorization means the provider refused, and said so in the redirect - // rather than by failing. Match it to catch every refusal. - ErrAuthorization = errors.New("social: the provider refused the authorization request") - - // ErrAccessDenied is the refusal worth telling apart: the person said no, - // or the provider decided on their behalf. It is not a fault, and a - // sign-in page should say so differently than it says something broke. - ErrAccessDenied = fmt.Errorf("%w: access_denied", ErrAuthorization) + // ErrProfile means the provider would not describe the person. + ErrProfile = errors.New("sociable: could not read the profile") ) -// AuthorizationError is the provider refusing in the shape RFC 6749 section -// 4.1.2.1 requires: a code from a fixed set, and prose that may be aimed at a -// developer rather than at the person signing in. +// AuthorizationError is a refusal the provider sent back on the redirect, in +// the shape RFC 6749 section 4.1.2.1 defines. type AuthorizationError struct { Code string Description string @@ -56,21 +44,19 @@ type AuthorizationError struct { } func (self *AuthorizationError) Error() string { - message := "social: " + self.Code - - if self.Description != "" { - message += ": " + self.Description + if self.Description == "" { + return "sociable: the provider refused: " + self.Code } - return message + return "sociable: the provider refused: " + self.Code + ": " + self.Description } -// Is answers for the sentinels above, so a caller can match every refusal with -// ErrAuthorization or single out the one that is not a fault. +// Is makes every refusal match ErrAuthorization, and access_denied match +// ErrAccessDenied as well. func (self *AuthorizationError) Is(target error) bool { - if errors.Is(target, ErrAccessDenied) { - return strings.EqualFold(self.Code, "access_denied") + if target == ErrAccessDenied { + return self.Code == "access_denied" } - return errors.Is(target, ErrAuthorization) + return target == ErrAuthorization } diff --git a/fake.go b/fake.go new file mode 100644 index 0000000..a570909 --- /dev/null +++ b/fake.go @@ -0,0 +1,107 @@ +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 + + mutex sync.Mutex + redirects []Redirect +} + +// 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 +} + +// 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) +} + +// 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) +} + +// 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 + } + } + + 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 + } + } +} + +// 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 *Faked) record(redirect Redirect) { + self.mutex.Lock() + defer self.mutex.Unlock() + + self.redirects = append(self.redirects, redirect) +} + +func (self *Faked) describe() string { + redirects := self.Redirects() + if len(redirects) == 0 { + return "none" + } + + return fmt.Sprintf("%+v", redirects) +} + +func accepted(redirect Redirect, conditions []func(Redirect) bool) bool { + for _, condition := range conditions { + if !condition(redirect) { + return false + } + } + + return true +} diff --git a/flow.go b/flow.go index d9e843b..a5518c8 100644 --- a/flow.go +++ b/flow.go @@ -1,102 +1,234 @@ -package social +package sociable import ( "context" "crypto/subtle" + "encoding/json" + "errors" "fmt" + "maps" "net/http" "slices" "strings" + "time" "golang.org/x/oauth2" ) -// openIDScope turns an OAuth2 request into an OpenID Connect one. The flow -// watches for it because that is what decides whether a nonce is owed. -const openIDScope = "openid" - -// flow is one provider bound to one request, shaped by the call's options. -type flow struct { - writer http.ResponseWriter - request *http.Request - name string - provider Provider - sealer Sealer - cookie CookieOptions - client *http.Client - - to string - scopes []string - parameters []oauth2.AuthCodeOption - redirectURL string - stateless bool - pkce *bool +// 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 } -func (self *flow) authorizationURL() (string, error) { - if !self.provider.Configured() { - return "", ErrNotConfigured +// 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 + } } - handshake := Handshake{} + self.params = merged - if !self.stateless { - issued, err := self.cookie.begin(self.writer, self.sealer, self.to, self.usesPKCE(), self.usesNonce()) + 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 err } - handshake = issued + return redirector.Redirect(w, r, self.callback(), handshake.State) + } + + url, err := self.AuthURL(w, r) + if err != nil { + return err } - return self.config().AuthCodeURL(handshake.State, self.authorization(handshake)...), nil + http.Redirect(w, r, url, http.StatusFound) + + return nil } -func (self *flow) callback() (*Result, error) { - handshake, err := self.verified() +// 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 nil, err + return "", err } - // Only now, with the response tied to a handshake this server issued, is - // what it says worth reading. - if err := self.refusal(); err != nil { - return nil, 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])) } - if !self.provider.Configured() { - return nil, ErrNotConfigured + 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 } - token, err := self.exchange(handshake) + if self.fake != nil { + return self.faked(), nil + } + + handshake, err := self.end(w, r) if err != nil { return nil, err } - user, err := self.profile(token, handshake.Nonce) + 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 } - return &Result{User: user, RedirectTo: handshake.RedirectTo}, nil + user.State = handshake.Custom + + return user, nil } -func (self *flow) userFromToken(token *oauth2.Token) (*User, error) { - if err := usable(token); err != nil { - return nil, err +// 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.profile(token, "") + return self.userFor(self.context(ctx), self.config(), token, "") } -func (self *flow) refresh(refreshToken string) (*oauth2.Token, error) { - if !self.provider.Configured() { - return nil, ErrNotConfigured +// 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 } - source := self.config().TokenSource(self.context(), &oauth2.Token{RefreshToken: refreshToken}) + if self.fake != nil { + return self.faked().Token, nil + } - token, err := source.Token() + 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) } @@ -104,103 +236,131 @@ func (self *flow) refresh(refreshToken string) (*oauth2.Token, error) { return token, nil } -// context is the request's, carrying the configured HTTP client so the -// oauth2 library sends the exchange through it. -func (self *flow) context() context.Context { - return context.WithValue(self.request.Context(), oauth2.HTTPClient, self.client) +// 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) } -func (self *flow) query(name string) string { - if self.request.URL == nil { - return "" - } +// 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 self.request.URL.Query().Get(name) + return "https://sociable.fake/" + self.name + "/authorize" } -// verified reads back the handshake and checks the response against it: the -// state, and the issuer if the provider asks. A stateless flow has neither, -// which is what stateless means. -func (self *flow) verified() (Handshake, error) { +// 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 + return handshake{}, nil + } + + issued := handshake{ + State: random(32), + Custom: self.state, + ExpiresAt: time.Now().Add(handshakeLifetime), + } + + if self.usesPKCE() { + issued.Verifier = oauth2.GenerateVerifier() } - handshake, ok := self.cookie.end(self.writer, self.request, self.sealer) - if !ok { - return Handshake{}, ErrNoHandshake + if self.usesNonce() { + issued.Nonce = random(32) } - // A byte-by-byte comparison that stops early tells anyone who can time it - // how much of a guessed state was right. - if subtle.ConstantTimeCompare([]byte(handshake.State), []byte(self.query("state"))) != 1 { - return Handshake{}, ErrStateMismatch + payload, err := json.Marshal(issued) + if err != nil { + return handshake{}, err } - if err := self.issuer(); err != nil { - return Handshake{}, err + if err := self.manager.session.Put(w, r, sessionKey, string(payload)); err != nil { + return handshake{}, err } - return handshake, nil + return issued, nil } -// issuer applies RFC 9207. A provider that names itself must be the one that -// answered, and must have said so: an absent iss from a provider known to send -// one is the mix-up the extension exists to catch. -func (self *flow) issuer() error { - expected, ok := self.provider.(Issued) - if !ok || expected.Issuer() == "" { - return 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 } - if self.query("iss") != expected.Issuer() { - return ErrIssuerMismatch + payload, err := self.manager.session.Pull(w, r, sessionKey) + if err != nil || payload == "" { + return handshake{}, ErrInvalidState } - return nil -} + var issued handshake + if err := json.Unmarshal([]byte(payload), &issued); err != nil { + return handshake{}, ErrInvalidState + } -// refusal reads the error the provider may have redirected back with instead of -// a code, in the shape RFC 6749 section 4.1.2.1 defines. -func (self *flow) refusal() error { - code := self.query("error") - if code == "" { - return nil + if issued.State == "" || time.Now().After(issued.ExpiresAt) { + return handshake{}, ErrInvalidState } - return &AuthorizationError{ - Code: code, - Description: self.query("error_description"), - URI: self.query("error_uri"), + // 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(handshake Handshake) (*oauth2.Token, error) { - options := []oauth2.AuthCodeOption{} +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 + } - if handshake.CodeVerifier != "" { - options = append(options, oauth2.SetAuthURLParam("code_verifier", handshake.CodeVerifier)) + ctx := self.context(r.Context()) + + options := []oauth2.AuthCodeOption{} + if issued.Verifier != "" { + options = append(options, oauth2.VerifierOption(issued.Verifier)) } - token, err := self.config().Exchange(self.context(), self.query("code"), options...) + token, err := config.Exchange(ctx, r.URL.Query().Get("code"), options...) if err != nil { return nil, fmt.Errorf("%w: %w", ErrExchange, err) } - if err := usable(token); err != nil { - return nil, err + if token.AccessToken == "" { + return nil, fmt.Errorf("%w: the response carried no access token", ErrExchange) } - return token, nil + return self.userFor(ctx, config, token, issued.Nonce) } -func (self *flow) profile(token *oauth2.Token, nonce string) (*User, error) { - ctx := self.context() - grant := Grant{Token: token, Nonce: nonce, Client: self.config().Client(ctx, token)} +func (self Flow) userFor(ctx context.Context, config *oauth2.Config, token *oauth2.Token, nonce string) (*User, error) { + ctx = withNonce(ctx, nonce) - user, err := self.provider.User(ctx, grant) + // 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 isIDToken(err) { + if errors.Is(err, ErrIDToken) { return nil, err } @@ -208,106 +368,79 @@ func (self *flow) profile(token *oauth2.Token, nonce string) (*User, error) { } user.Token = token - user.ApprovedScopes = granted(token, self.scoped()) + user.ApprovedScopes = approved(token, config.Scopes) return user, nil } -// authorization is everything the flow itself puts on the authorization URL, -// followed by whatever the provider and the call site added. -func (self *flow) authorization(handshake Handshake) []oauth2.AuthCodeOption { - options := []oauth2.AuthCodeOption{} +// 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 handshake.CodeVerifier != "" { - options = append(options, - oauth2.SetAuthURLParam("code_challenge", handshake.Challenge()), - oauth2.SetAuthURLParam("code_challenge_method", "S256"), - ) + if self.scopes != nil { + config.Scopes = self.scopes } - if handshake.Nonce != "" { - options = append(options, oauth2.SetAuthURLParam("nonce", handshake.Nonce)) - } + return &config +} - if parameterised, ok := self.provider.(Parameterised); ok { - options = append(options, parameterised.Parameters()...) +// 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 } - return append(options, self.parameters...) -} + if !strings.HasPrefix(redirect, "/") { + return redirect + } -// scoped is what will be asked for: the provider's own scopes until an option -// changes them. -func (self *flow) scoped() []string { - if self.scopes != nil { - return slices.Clone(self.scopes) + if self.manager.config.URL == "" { + return "" } - return slices.Clone(self.provider.Config().Scopes) + return strings.TrimSuffix(self.manager.config.URL, "/") + redirect } -// config is the provider's, with this request's changes applied to a copy so -// one request cannot change what the next one asks for. -func (self *flow) config() *oauth2.Config { - config := *self.provider.Config() - - if self.scopes != nil { - config.Scopes = self.scopes - } +// 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) +} - if self.redirectURL != "" { - config.RedirectURL = self.redirectURL +func (self Flow) scoped() []string { + if self.scopes != nil || self.provider == nil { + return slices.Clone(self.scopes) } - return &config + return slices.Clone(self.provider.Config().Scopes) } -// usesPKCE reports whether this request takes part in PKCE. Silence is yes: -// OAuth 2.1 makes it mandatory for every client, so opting out is the decision -// that should have to be written down. -func (self *flow) usesPKCE() bool { - // The verifier has nowhere to live between the two requests. +// 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 } - if self.pkce != nil { - return *self.pkce - } - unprotected, ok := self.provider.(Unprotected) return !ok || unprotected.UsesPKCE() } -// usesNonce reports whether a nonce is owed. Asking for the openid scope is -// what makes this an OpenID Connect request, and section 3.1.2.1 of that spec -// is where the nonce comes from. -func (self *flow) usesNonce() bool { +// 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, openIDScope) + return strings.EqualFold(scope, "openid") }) } -// usable rejects a token this package cannot present. RFC 6750 covers bearer -// tokens, and a provider answering with anything else needs a client that knows -// what to do with it. -func usable(token *oauth2.Token) error { - if token == nil || token.AccessToken == "" { - return fmt.Errorf("%w: the response carried no access token", ErrExchange) - } - - if token.TokenType != "" && !strings.EqualFold(token.TokenType, "bearer") { - return fmt.Errorf("%w: unsupported token type %q", ErrExchange, token.TokenType) - } - - return nil -} - -// granted is what the provider actually approved. RFC 6749 section 5.1 lets the -// token response name a different set than was asked for, and says that leaving -// it out means the two are the same. -func granted(token *oauth2.Token, requested []string) []string { +// 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 { @@ -317,8 +450,8 @@ func granted(token *oauth2.Token, requested []string) []string { return requested } -// reserved names the parameters the flow decides. Letting a call site set them -// would let it disable the checks the callback depends on. +// 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": diff --git a/flow_test.go b/flow_test.go index f8ceb54..3c2676a 100644 --- a/flow_test.go +++ b/flow_test.go @@ -1,429 +1,269 @@ -package social_test +package sociable_test import ( - "context" - "crypto/sha256" - "encoding/base64" "errors" "net/http" "net/http/httptest" + "strings" "testing" - "github.com/gonstruct/social" - "golang.org/x/oauth2" + "github.com/gonstruct/sociable" ) -func TestRedirectCarriesAChallengeAndNotTheVerifier(t *testing.T) { - recorder := redirect(t, setup(t, configured()), social.To("/after")) +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()) }) - if recorder.Code != http.StatusFound { - t.Fatalf("expected a 302, got %d", recorder.Code) - } - query := issuedQuery(t, recorder) - if query.Get("code_challenge_method") != "S256" || query.Get("code_challenge") == "" { - t.Fatalf("expected an S256 challenge, got %s", query.Encode()) - } - if query.Get("state") == "" { - t.Fatal("no state was issued") - } - // The verifier is the secret half; only its hash may travel. - if query.Get("code_verifier") != "" { - t.Fatal("the verifier reached the provider") - } - if cookies := recorder.Result().Cookies(); len(cookies) != 1 || cookies[0].Name != "social_handshake" { - t.Fatalf("expected the handshake cookie, got %v", cookies) - } -} + result := signIn(t, browser(t), app, "acme") -func TestRedirectRefusesAnUnconfiguredProvider(t *testing.T) { - auth := setup(t, fakeProvider{configured: false}) - recorder := httptest.NewRecorder() - - err := auth.Redirect(recorder, httptest.NewRequest(http.MethodGet, "/login", nil), "fake") - if !errors.Is(err, social.ErrNotConfigured) { - t.Fatalf("expected ErrNotConfigured, got %v", err) - } - if recorder.Header().Get("Location") != "" || len(recorder.Result().Cookies()) != 0 { - t.Fatal("nothing should have been sent") + if result.Error != "" { + t.Fatalf("sign in failed: %s", result.Error) } -} - -func TestAnUnknownDriverIsAnErrorRatherThanAPanic(t *testing.T) { - auth := setup(t, configured()) - request := httptest.NewRequest(http.MethodGet, "/", nil) - - if err := auth.Redirect(httptest.NewRecorder(), request, "nope"); !errors.Is(err, social.ErrUnknownDriver) { - t.Fatalf("redirect: expected ErrUnknownDriver, got %v", err) + if result.User.ID != "42" || result.User.Nickname != "arjen" || result.User.Email != "arjen@example.test" { + t.Errorf("user = %+v", result.User) } - if _, err := auth.Callback(httptest.NewRecorder(), request, "nope"); !errors.Is(err, social.ErrUnknownDriver) { - t.Fatalf("callback: expected ErrUnknownDriver, got %v", err) + if result.User.Token.AccessToken != "t0ken" || result.User.Token.RefreshToken != "r3fresh" { + t.Errorf("token = %+v", result.User.Token) } - if _, err := auth.UserFromToken(context.Background(), "nope", &oauth2.Token{AccessToken: "a"}); !errors.Is(err, social.ErrUnknownDriver) { - t.Fatalf("user from token: expected ErrUnknownDriver, got %v", err) + if strings.Join(result.User.ApprovedScopes, " ") != "profile email" { + t.Errorf("approved scopes = %v", result.User.ApprovedScopes) } -} -func TestNewRequiresASealer(t *testing.T) { - if _, err := social.New(social.Configuration{}); !errors.Is(err, social.ErrNoSealer) { - t.Fatalf("expected ErrNoSealer, got %v", err) + sent := as.lastRequest() + if sent.Get("code_challenge") == "" || sent.Get("code_challenge_method") != "S256" { + t.Errorf("PKCE was not on: %v", sent) } -} - -func TestCallbackWithoutAHandshakeIsRefused(t *testing.T) { - _, err, _ := callback(t, setup(t, configured()), "/callback?code=c&state=s", nil) - if !errors.Is(err, social.ErrNoHandshake) { - t.Fatalf("expected ErrNoHandshake, got %v", err) + if sent.Get("redirect_uri") != app.URL+"/auth/acme/callback" { + t.Errorf("redirect_uri = %s", sent.Get("redirect_uri")) } -} - -func TestCallbackRefusesAForgedState(t *testing.T) { - auth := setup(t, configured()) - started := redirect(t, auth) - - _, err, _ := callback(t, auth, "/callback?code=c&state=forged", started) - if !errors.Is(err, social.ErrStateMismatch) { - t.Fatalf("expected ErrStateMismatch, got %v", err) + if sent.Get("scope") != "profile" { + t.Errorf("scope = %s", sent.Get("scope")) } } -func TestTheHandshakeIsSpentEvenByAFailedAttempt(t *testing.T) { - auth := setup(t, configured()) - started := redirect(t, auth) - - _, err, cleared := callback(t, auth, "/callback?code=c&state=forged", started) - if !errors.Is(err, social.ErrStateMismatch) { - t.Fatalf("expected the first attempt to fail on state, got %v", err) +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"}) } - // The failed attempt cleared the cookie; the retry carries that. - _, err, _ = callback(t, auth, "/callback?code=c&state=forged", cleared) - if !errors.Is(err, social.ErrNoHandshake) { - t.Fatalf("expected the handshake to be spent, got %v", err) - } -} - -func TestChallengeIsTheSha256OfTheVerifier(t *testing.T) { - handshake := social.Handshake{CodeVerifier: "a-known-verifier"} + signIn(t, browser(t), app, "acme") - sum := sha256.Sum256([]byte("a-known-verifier")) - if expected := base64.RawURLEncoding.EncodeToString(sum[:]); handshake.Challenge() != expected { - t.Fatalf("expected %q, got %q", expected, handshake.Challenge()) + sent := as.lastRequest() + if sent.Get("scope") != "profile email" { + t.Errorf("scope = %s", sent.Get("scope")) } -} - -func TestSafeRedirectKeepsOnlyLocalPaths(t *testing.T) { - cases := map[string]string{ - "/runs": "/runs", - "": "", - "https://evil.test/steal": "", - "//evil.test/steal": "", - "javascript:alert(1)": "", - " /spaced ": "/spaced", + if sent.Get("login_hint") != "arjen" { + t.Errorf("login_hint = %s", sent.Get("login_hint")) } - - for candidate, expected := range cases { - if got := social.SafeRedirect(candidate); got != expected { - t.Errorf("SafeRedirect(%q) = %q, want %q", candidate, got, expected) - } + if sent.Get("state") == "overridden" { + t.Error("a call site could override the state") } } -func TestAProviderCanAddItsOwnAuthorizationParameters(t *testing.T) { - query := issuedQuery(t, redirect(t, setup(t, parameterisedProvider{configured()}))) - - if query.Get("access_type") != "offline" || query.Get("prompt") != "consent" { - t.Fatalf("the provider's parameters did not reach the provider: %s", query.Encode()) - } - // PKCE is not an either/or with extra parameters. - if query.Get("code_challenge") == "" { - t.Fatal("adding parameters dropped the challenge") +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"}) } -} -func TestAProviderCanOptOutOfPKCE(t *testing.T) { - query := issuedQuery(t, redirect(t, setup(t, unprotectedProvider{configured()}))) + result := signIn(t, browser(t), app, "acme") - if query.Get("code_challenge") != "" || query.Get("code_challenge_method") != "" { - t.Fatalf("a provider that opted out was still sent a challenge: %s", query.Encode()) + 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) } - // State is not part of the opt-out: it is the only thing left tying the - // callback to this browser. - if query.Get("state") == "" { - t.Fatal("no state was issued") + if as.lastRequest().Has("user_id") { + t.Error("state leaked to the provider") } } -func TestACallSiteCanOverrideTheProviderOnPKCE(t *testing.T) { - on := issuedQuery(t, redirect(t, setup(t, unprotectedProvider{configured()}), social.UsingPKCE())) - if on.Get("code_challenge") == "" { - t.Fatal("UsingPKCE did not turn the challenge on") - } +func TestDenial(t *testing.T) { + as := newAuthorizationServer(t) + as.deny = true + app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - off := issuedQuery(t, redirect(t, setup(t, configured()), social.WithoutPKCE())) - if off.Get("code_challenge") != "" { - t.Fatal("WithoutPKCE did not turn the challenge off") + if result := signIn(t, browser(t), app, "acme"); result.Error != "denied" { + t.Errorf("error = %q, want denied", result.Error) } } -func TestARefusalIsReadRatherThanExchanged(t *testing.T) { - auth := setup(t, configured()) - started := redirect(t, auth) +func TestACallbackCannotBeReplayed(t *testing.T) { + as := newAuthorizationServer(t) + app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - _, err, _ := callback(t, auth, "/callback?error=access_denied&error_description=The+user+said+no&state="+issuedState(t, started), started) + 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() + } - // A cancelled sign-in is an answer, not a broken exchange. - if !errors.Is(err, social.ErrAccessDenied) { - t.Fatalf("expected ErrAccessDenied, got %v", err) - } - if !errors.Is(err, social.ErrAuthorization) { - t.Fatal("a denial should also match every refusal") + return nil } - var refusal *social.AuthorizationError - if !errors.As(err, &refusal) || refusal.Description != "The user said no" { - t.Fatalf("the provider's own words were lost: %v", err) + if result := signIn(t, client, app, "acme"); result.Error != "" { + t.Fatalf("first sign in failed: %s", result.Error) } -} - -func TestARefusalThatIsNotADenialStillMatchesAuthorization(t *testing.T) { - auth := setup(t, configured()) - started := redirect(t, auth) - - _, err, _ := callback(t, auth, "/callback?error=temporarily_unavailable&state="+issuedState(t, started), started) - if errors.Is(err, social.ErrAccessDenied) { - t.Fatal("an outage was reported as the person declining") - } - if !errors.Is(err, social.ErrAuthorization) { - t.Fatalf("expected ErrAuthorization, got %v", err) + response, err := client.Get(callback) + if err != nil { + t.Fatal(err) } -} - -func TestARefusalIsOnlyReadOnceTheStateMatches(t *testing.T) { - auth := setup(t, configured()) - started := redirect(t, auth) + defer response.Body.Close() - // Anyone can send the browser here carrying an error. Until the state - // ties the response to a handshake this server issued, what it says is - // not worth reading. - _, err, _ := callback(t, auth, "/callback?error=access_denied&state=forged", started) - if !errors.Is(err, social.ErrStateMismatch) { - t.Fatalf("expected ErrStateMismatch, got %v", err) + var result outcome + _ = decode(response, &result) + if result.Error != "state" { + t.Errorf("replay error = %q, want state", result.Error) } } -func TestAProviderThatAsksForTheIssuerMustBeTheOneThatAnswered(t *testing.T) { - auth := setup(t, issuedProvider{configured()}) - started := redirect(t, auth) +func TestACallbackNobodyStartedIsRefused(t *testing.T) { + as := newAuthorizationServer(t) + app := newApplication(t, nil, func(auth *sociable.Manager) { auth.Extend("acme", as.factory()) }) - _, err, _ := callback(t, auth, "/callback?code=c&iss=https://attacker.test&state="+issuedState(t, started), started) - if !errors.Is(err, social.ErrIssuerMismatch) { - t.Fatalf("expected ErrIssuerMismatch, got %v", err) + response, err := browser(t).Get(app.URL + "/auth/acme/callback?code=c0de&state=guess") + if err != nil { + t.Fatal(err) } -} - -func TestAMissingIssuerIsAMismatchForAProviderThatAsksForOne(t *testing.T) { - auth := setup(t, issuedProvider{configured()}) - started := redirect(t, auth) + defer response.Body.Close() - // RFC 9207 only defeats a mix-up if a client that expects an issuer - // refuses a response without one. - _, err, _ := callback(t, auth, "/callback?code=c&state="+issuedState(t, started), started) - if !errors.Is(err, social.ErrIssuerMismatch) { - t.Fatalf("expected ErrIssuerMismatch, got %v", err) + var result outcome + _ = decode(response, &result) + if result.Error != "state" { + t.Errorf("error = %q, want state", result.Error) } } -func TestScopesAddAndSetScopesReplace(t *testing.T) { - auth := setup(t, fakeProvider{configured: true, scopes: []string{"profile"}}) +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 scope := issuedQuery(t, redirect(t, auth, social.Scopes("email", "profile"))).Get("scope"); scope != "profile email" { - t.Fatalf("expected the provider's scope kept and one added, got %q", scope) - } - if scope := issuedQuery(t, redirect(t, auth, social.SetScopes("email"))).Get("scope"); scope != "email" { - t.Fatalf("expected only the scope set, got %q", scope) + if result := signIn(t, browser(t), app, "acme"); result.Error != "exchange" { + t.Errorf("error = %q, want exchange", result.Error) } } -func TestTheOpenIDScopeIsWhatIssuesANonce(t *testing.T) { - auth := setup(t, fakeProvider{configured: true, tokenURL: tokenEndpoint(t)}) +func TestAnUnknownDriverIsAnError(t *testing.T) { + app := newApplication(t, nil, func(*sociable.Manager) {}) - if issuedQuery(t, redirect(t, auth)).Get("nonce") != "" { - t.Fatal("a plain OAuth2 request was sent a nonce") + err := app.auth.Driver("nope").Redirect(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) + if !errors.Is(err, sociable.ErrUnknownDriver) { + t.Errorf("err = %v", err) } - started := redirect(t, auth, social.Scopes("openid")) - nonce := issuedQuery(t, started).Get("nonce") - if nonce == "" { - t.Fatal("an OpenID Connect request was not sent a nonce") - } + // Configured, but no provider of that name. + app2 := newApplication(t, func(config *sociable.Config) { + config.Drivers["mystery"] = sociable.Credentials{ClientID: "x"} + }, func(*sociable.Manager) {}) - // The provider has to be able to check the claim it gets back against it. - result, err, _ := callback(t, auth, "/callback?code=c&state="+issuedState(t, started), started, social.Scopes("openid")) - if err != nil { - t.Fatal(err) - } - grant, ok := result.User.Raw.(social.Grant) - if !ok || grant.Nonce != nonce { - t.Fatal("the nonce never reached the provider") - } - if grant.Client == nil { - t.Fatal("the provider was not given an authenticated client") + 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 TestWithCannotOverwriteWhatMakesTheCallbackTrustworthy(t *testing.T) { - query := issuedQuery(t, redirect(t, setup(t, configured()), social.With(map[string]string{"login_hint": "person@provider.test", "state": "chosen"}))) - - if query.Get("login_hint") != "person@provider.test" { - t.Fatal("an ordinary parameter was dropped") - } - if query.Get("state") == "chosen" { - t.Fatal("a call site was allowed to choose the state") - } -} +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()) }) -func TestRedirectURLOverridesTheProviders(t *testing.T) { - query := issuedQuery(t, redirect(t, setup(t, configured()), social.RedirectURL("http://localhost/other"))) - if query.Get("redirect_uri") != "http://localhost/other" { - t.Fatalf("redirect_uri: %q", query.Get("redirect_uri")) + client := browser(t) + if result := signIn(t, client, app, "acme"); result.Error != "" { + t.Fatalf("sign in failed: %s", result.Error) } -} - -func TestStatelessCarriesNoHandshakeAtAll(t *testing.T) { - recorder := redirect(t, setup(t, configured()), social.Stateless()) - if len(recorder.Result().Cookies()) != 0 { - t.Fatal("a stateless flow wrote a cookie") + if session.puts != 1 || session.pulls != 1 { + t.Errorf("session saw %d puts and %d pulls", session.puts, session.pulls) } - query := issuedQuery(t, recorder) - if query.Get("state") != "" || query.Get("code_challenge") != "" { - t.Fatalf("a stateless flow issued what it cannot check: %s", query.Encode()) - } -} - -func TestTheResultCarriesWhereToLand(t *testing.T) { - auth := setup(t, fakeProvider{configured: true, tokenURL: tokenEndpoint(t)}) - started := redirect(t, auth, social.To("/settings")) - result, err, recorder := callback(t, auth, "/callback?code=c&state="+issuedState(t, started), started) - if err != nil { - t.Fatal(err) - } - if result.RedirectTo != "/settings" || result.User.ID != "1" || result.User.Token.AccessToken != "granted" { - t.Fatalf("result: %+v", result) - } - // The callback clears the handshake for good. - for _, cookie := range recorder.Result().Cookies() { - if cookie.Name == "social_handshake" && cookie.MaxAge >= 0 { - t.Fatal("the handshake cookie was not cleared") + for _, cookie := range client.Jar.Cookies(mustParse(app.URL)) { + if cookie.Name == "sociable" { + t.Error("a cookie was set alongside the session") } } } -func TestApprovedScopesComeFromTheProviderWhenItNamesThem(t *testing.T) { - auth := setup(t, configured()) - ctx := context.Background() +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() } - granted := (&oauth2.Token{AccessToken: "granted"}).WithExtra(map[string]any{"scope": "profile email"}) - user, err := auth.UserFromToken(ctx, "fake", granted) + response, err := browser(t).Get(app.URL + "/auth/acme/callback?code=c0de") if err != nil { t.Fatal(err) } - if !user.HasScope("email") || len(user.ApprovedScopes) != 2 { - t.Fatalf("expected the granted scopes, got %v", user.ApprovedScopes) - } + defer response.Body.Close() - // RFC 6749 section 5.1: leaving the scope out means it is the one asked for. - silent, err := auth.UserFromToken(ctx, "fake", &oauth2.Token{AccessToken: "granted"}, social.Scopes("profile")) - if err != nil { - t.Fatal(err) - } - if len(silent.ApprovedScopes) != 1 || silent.ApprovedScopes[0] != "profile" { - t.Fatalf("expected the requested scope, got %v", silent.ApprovedScopes) + var result outcome + _ = decode(response, &result) + if result.Error != "" || result.User.ID != "42" { + t.Errorf("result = %+v", result) } } -func TestATokenThisPackageCannotPresentIsRefused(t *testing.T) { - auth := setup(t, configured()) - ctx := context.Background() +func TestFake(t *testing.T) { + app := newApplication(t, nil, func(auth *sociable.Manager) { + auth.Fake("github", sociable.User{ID: "1", Email: "arjen@example.test"}) + }) - if _, err := auth.UserFromToken(ctx, "fake", &oauth2.Token{}); !errors.Is(err, social.ErrExchange) { - t.Fatalf("an empty access token was accepted: %v", err) + // 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 _, err := auth.UserFromToken(ctx, "fake", &oauth2.Token{AccessToken: "a", TokenType: "mac"}); !errors.Is(err, social.ErrExchange) { - t.Fatalf("a token type this client cannot use was accepted: %v", err) + if location := recorder.Header().Get("Location"); location != "https://sociable.fake/github/authorize" { + t.Errorf("redirected to %s", location) } -} -func TestAnExpiredHandshakeIsNoHandshake(t *testing.T) { - auth, err := social.New(social.Configuration{Sealer: plainSealer{}, Cookie: expired(), Drivers: social.Drivers{"fake": configured()}}) + response, err := browser(t).Get(app.URL + "/auth/github/callback") if err != nil { t.Fatal(err) } - started := redirect(t, auth) + defer response.Body.Close() - // The cookie's own max-age is the browser's to honour. The expiry inside - // the sealed payload is not. - _, err, _ = callback(t, auth, "/callback?code=c&state="+issuedState(t, started), started) - if !errors.Is(err, social.ErrNoHandshake) { - t.Fatalf("expected ErrNoHandshake, got %v", err) + 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 TestATamperedHandshakeIsNoHandshake(t *testing.T) { - auth := setup(t, configured()) - started := redirect(t, auth) - - recorder := httptest.NewRecorder() - request := httptest.NewRequest(http.MethodGet, "/callback?code=c&state="+issuedState(t, started), nil) - for _, cookie := range started.Result().Cookies() { - cookie.Value = "not-" + cookie.Value - request.AddCookie(cookie) - } - if _, err := auth.Callback(recorder, request, "fake"); !errors.Is(err, social.ErrNoHandshake) { - t.Fatalf("expected ErrNoHandshake, got %v", err) +func TestConfigureRequiresSomewhereToKeepTheHandshake(t *testing.T) { + if _, err := sociable.New(sociable.Config{}); !errors.Is(err, sociable.ErrNoKey) { + t.Errorf("err = %v", err) } } -func TestExtendAddsADriverAtRuntime(t *testing.T) { - auth := setup(t, configured()) - auth.Extend("other", configured()) - - if err := auth.Redirect(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/login", nil), "other"); err != nil { - t.Fatalf("the extended driver should work: %v", err) - } +type memorySession struct { + values map[string]string + puts, pulls int } -func TestCookieOptionsAreMirrored(t *testing.T) { - auth, err := social.New(social.Configuration{ - Sealer: plainSealer{}, - Cookie: social.CookieOptions{Name: "hs", Path: "/auth", Domain: "example.test", Secure: true, SameSite: http.SameSiteStrictMode}, - Drivers: social.Drivers{"fake": configured()}, - }) - if err != nil { - t.Fatal(err) - } +func (self *memorySession) Put(_ http.ResponseWriter, _ *http.Request, key, value string) error { + self.puts++ + self.values[key] = value - cookie := redirect(t, auth).Result().Cookies()[0] - mirrored := cookie.Name == "hs" && cookie.Path == "/auth" && cookie.Domain == "example.test" && - cookie.Secure && cookie.HttpOnly && cookie.SameSite == http.SameSiteStrictMode - if !mirrored { - t.Fatalf("cookie attributes not honoured: %+v", cookie) - } - if cookie.MaxAge != 600 { - t.Fatalf("expected the default ten minutes, got %d", cookie.MaxAge) - } + return nil } -func TestRefreshGoesThroughTheProvider(t *testing.T) { - auth := setup(t, fakeProvider{configured: true, tokenURL: tokenEndpoint(t)}) +func (self *memorySession) Pull(_ http.ResponseWriter, _ *http.Request, key string) (string, error) { + self.pulls++ + value := self.values[key] + delete(self.values, key) - token, err := auth.Refresh(context.Background(), "fake", "refresh-me") - if err != nil || token.AccessToken != "granted" { - t.Fatalf("refresh: %+v %v", token, err) - } - if _, err := setup(t, fakeProvider{}).Refresh(context.Background(), "fake", "x"); !errors.Is(err, social.ErrNotConfigured) { - t.Fatalf("an unconfigured provider cannot refresh: %v", err) - } + return value, nil } diff --git a/github/github.go b/github/github.go deleted file mode 100644 index e1e5313..0000000 --- a/github/github.go +++ /dev/null @@ -1,123 +0,0 @@ -// Package github signs people in with GitHub. -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "strconv" - - "github.com/gonstruct/social" -) - -// Name is what the provider is registered and routed under. -const Name = "github" - -// Options are the application's credentials. Scopes default to read:user and -// user:email, which is what it takes to learn who somebody is. -type Options struct { - ClientID string - ClientSecret string - RedirectURL string - Scopes []string -} - -type provider struct { - *social.OAuth2 - - emailsURL string -} - -// New is a provider for a social.Drivers entry. -func New(options Options) social.Provider { - scopes := options.Scopes - if len(scopes) == 0 { - scopes = []string{"read:user", "user:email"} - } - - return &provider{emailsURL: "https://api.github.com/user/emails", OAuth2: &social.OAuth2{ - Driver: Name, - ClientID: options.ClientID, - ClientSecret: options.ClientSecret, - RedirectURL: options.RedirectURL, - AuthURL: "https://github.com/login/oauth/authorize", - TokenURL: "https://github.com/login/oauth/access_token", - ProfileURL: "https://api.github.com/user", - Scopes: scopes, - }} -} - -// User reads the profile and, when the profile hides the address, the -// primary verified one from the emails endpoint. -func (self *provider) User(_ context.Context, grant social.Grant) (*social.User, error) { - raw, err := social.FetchJSON(grant, self.ProfileURL) - if err != nil { - return nil, err - } - - user := Profile(raw) - user.Raw = raw - - if user.Email == "" { - email, verified, err := primaryEmail(grant, self.emailsURL) - if err != nil { - return nil, err - } - user.Email, user.EmailVerified = email, verified - } - - return &user, nil -} - -// Profile maps the user document. The numeric id is the stable identifier; -// the login is the nickname. An address on the profile is one GitHub shows -// publicly, which it only does once it is verified. -func Profile(raw map[string]any) social.User { - id := "" - if number, ok := raw["id"].(float64); ok { - id = strconv.FormatInt(int64(number), 10) - } - - email := social.String(raw, "email") - - return social.User{ - ID: id, - Nickname: social.String(raw, "login"), - Name: social.String(raw, "name"), - Email: email, - EmailVerified: email != "", - Avatar: social.String(raw, "avatar_url"), - } -} - -type email struct { - Email string `json:"email"` - Primary bool `json:"primary"` - Verified bool `json:"verified"` -} - -func primaryEmail(grant social.Grant, url string) (string, bool, error) { - response, err := grant.Client.Get(url) - if err != nil { - return "", false, fmt.Errorf("get emails: %w", err) - } - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - return "", false, fmt.Errorf("get emails: status %d", response.StatusCode) - } - - var emails []email - if err := json.NewDecoder(response.Body).Decode(&emails); err != nil { - return "", false, fmt.Errorf("decode emails: %w", err) - } - - for _, candidate := range emails { - if candidate.Primary { - return candidate.Email, candidate.Verified, nil - } - } - - return "", false, nil -} diff --git a/github/github_test.go b/github/github_test.go deleted file mode 100644 index 22f8098..0000000 --- a/github/github_test.go +++ /dev/null @@ -1,58 +0,0 @@ -//nolint:testpackage // the fallback reads an unexported endpoint field to point at the test server -package github - -import ( - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "testing" - - "github.com/gonstruct/social" - "golang.org/x/oauth2" -) - -func TestGitHubProviderDefaults(t *testing.T) { - provider := New(Options{ClientID: "id", ClientSecret: "secret", RedirectURL: "http://app/cb"}).(*provider) - - if provider.Name() != "github" || !provider.Configured() || len(provider.Scopes) != 2 { - t.Fatalf("basics: %+v", provider.OAuth2) - } -} - -func TestGitHubProfileAndEmailFallback(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - switch r.URL.Path { - case "/user": - _ = json.NewEncoder(w).Encode(map[string]any{"id": 42.0, "login": "octo", "name": "Octo Cat", "avatar_url": "https://a"}) - case "/user/emails": - _ = json.NewEncoder(w).Encode([]map[string]any{ - {"email": "old@example.com", "primary": false, "verified": true}, - {"email": "octo@example.com", "primary": true, "verified": true}, - }) - } - })) - t.Cleanup(server.Close) - - provider := New(Options{ClientID: "id"}).(*provider) - provider.ProfileURL = server.URL + "/user" - provider.emailsURL = server.URL + "/user/emails" - - grant := social.Grant{Client: (&oauth2.Config{}).Client(context.Background(), &oauth2.Token{AccessToken: "tok"})} - user, err := provider.User(context.Background(), grant) - if err != nil { - t.Fatal(err) - } - if user.ID != "42" || user.Nickname != "octo" || user.Name != "Octo Cat" || user.Avatar != "https://a" { - t.Fatalf("profile: %+v", user) - } - if user.Email != "octo@example.com" || !user.EmailVerified { - t.Fatalf("the primary verified address should be used: %+v", user) - } - - public := Profile(map[string]any{"id": 1.0, "login": "x", "email": "x@example.com"}) - if public.Email != "x@example.com" || !public.EmailVerified { - t.Fatalf("a public address is a verified one: %+v", public) - } -} diff --git a/go.mod b/go.mod index 0c5c474..e8cf6e2 100644 --- a/go.mod +++ b/go.mod @@ -1,10 +1,9 @@ -module github.com/gonstruct/social +module github.com/gonstruct/sociable go 1.26.0 -require golang.org/x/oauth2 v0.37.0 - require ( github.com/coreos/go-oidc/v3 v3.21.0 github.com/go-jose/go-jose/v4 v4.1.5 + golang.org/x/oauth2 v0.37.0 ) diff --git a/google/google.go b/google/google.go deleted file mode 100644 index 6f4aecd..0000000 --- a/google/google.go +++ /dev/null @@ -1,45 +0,0 @@ -// Package google signs people in with Google through OpenID Connect. -package google - -import ( - "net/http" - - "github.com/gonstruct/social" -) - -// Name is what the provider is registered and routed under. -const Name = "google" - -// Options are the application's credentials. Offline asks for a refresh -// token, which Google only issues with access_type=offline and prompt=consent. -type Options struct { - ClientID string - ClientSecret string - RedirectURL string - Scopes []string - Offline bool - - // Client fetches Google's discovery document and signing keys. - Client *http.Client -} - -// New is a provider for a social.Drivers entry. Endpoints and keys come from -// Google's discovery document, and the identity from a verified ID token. -func New(options Options) social.Provider { - extra := map[string]string{} - if options.Offline { - extra["access_type"] = "offline" - extra["prompt"] = "consent" - } - - return &social.OpenIDConnect{ - Driver: Name, - IssuerURL: "https://accounts.google.com", - ClientID: options.ClientID, - ClientSecret: options.ClientSecret, - RedirectURL: options.RedirectURL, - Scopes: options.Scopes, - Extra: extra, - Client: options.Client, - } -} diff --git a/google/google_test.go b/google/google_test.go deleted file mode 100644 index 61c8902..0000000 --- a/google/google_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package google_test - -import ( - "testing" - - "github.com/gonstruct/social" - "github.com/gonstruct/social/google" -) - -func TestGoogleIsOpenIDConnectThroughDiscovery(t *testing.T) { - provider := google.New(google.Options{ClientID: "id", ClientSecret: "secret", RedirectURL: "http://app/cb", Offline: true}).(*social.OpenIDConnect) - - if provider.Name() != "google" || provider.IssuerURL != "https://accounts.google.com" || provider.ClientID != "id" { - t.Fatalf("basics: %+v", provider) - } - if provider.Extra["access_type"] != "offline" || provider.Extra["prompt"] != "consent" { - t.Fatalf("offline: %v", provider.Extra) - } - if len(google.New(google.Options{}).(*social.OpenIDConnect).Extra) != 0 { - t.Error("online sign-in should send no extra parameters") - } -} diff --git a/handshake.go b/handshake.go deleted file mode 100644 index 2d04ba4..0000000 --- a/handshake.go +++ /dev/null @@ -1,175 +0,0 @@ -package social - -import ( - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "encoding/json" - "net/http" - "strings" - "time" -) - -// Sealer encrypts the handshake so it can be held by the browser between the -// redirect and the callback. The application supplies it, so choosing a cipher -// or a key store is not this package's business; AESSealer is the one to use -// when there is nothing to integrate with. -type Sealer interface { - Seal(plain []byte) (string, error) - Open(sealed string) ([]byte, error) -} - -// CookieOptions are the attributes the handshake cookie is written with. They -// should mirror the application's own session cookie so the two behave alike. -type CookieOptions struct { - Name string - Path string - Domain string - Secure bool - SameSite http.SameSite - Lifetime time.Duration -} - -const ( - defaultCookieName = "social_handshake" - defaultCookieLifetime = 10 * time.Minute -) - -func (self CookieOptions) withDefaults() CookieOptions { - if self.Name == "" { - self.Name = defaultCookieName - } - if self.Path == "" { - self.Path = "/" - } - if self.SameSite == 0 { - self.SameSite = http.SameSiteLaxMode - } - if self.Lifetime == 0 { - self.Lifetime = defaultCookieLifetime - } - - return self -} - -// Handshake is what the callback needs in order to trust what came back: the -// state it issued, the verifier whose challenge it sent, and the nonce it asked -// the provider to echo into an ID token. -// -// The verifier is empty for a provider that does not do PKCE, and the nonce is -// empty unless the openid scope was asked for. -type Handshake struct { - State string `json:"state"` - CodeVerifier string `json:"codeVerifier"` - Nonce string `json:"nonce"` - RedirectTo string `json:"redirectTo"` - ExpiresAt time.Time `json:"expiresAt"` -} - -// Challenge is the S256 hash of the verifier, the only transformation RFC 7636 -// section 4.2 allows a client that can compute it. Only this reaches the -// provider, so an intercepted authorization code cannot be exchanged without -// the cookie. -func (self Handshake) Challenge() string { - sum := sha256.Sum256([]byte(self.CodeVerifier)) - - return base64.RawURLEncoding.EncodeToString(sum[:]) -} - -func (self CookieOptions) write(writer http.ResponseWriter, value string, maxAge int) { - http.SetCookie(writer, &http.Cookie{ - Name: self.Name, - Value: value, - Path: self.Path, - Domain: self.Domain, - MaxAge: maxAge, - Secure: self.Secure, - HttpOnly: true, - SameSite: self.SameSite, - }) -} - -// begin issues a handshake and hands it to the browser sealed. What the -// handshake contains is decided here rather than by the caller, so a flow -// cannot accidentally be started without the halves that make it safe. -func (self CookieOptions) begin(writer http.ResponseWriter, sealer Sealer, redirectTo string, pkce, nonce bool) (Handshake, error) { - handshake := Handshake{ - State: randomToken(32), - RedirectTo: SafeRedirect(redirectTo), - ExpiresAt: time.Now().Add(self.Lifetime), - } - - if pkce { - handshake.CodeVerifier = randomToken(48) - } - - if nonce { - handshake.Nonce = randomToken(32) - } - - payload, err := json.Marshal(handshake) - if err != nil { - return Handshake{}, err - } - - sealed, err := sealer.Seal(payload) - if err != nil { - return Handshake{}, err - } - - self.write(writer, sealed, int(self.Lifetime.Seconds())) - - return handshake, nil -} - -// end reads and clears the handshake. It clears whether or not the value -// validates, so a failed attempt cannot be replayed, and it checks the expiry -// it carries rather than trusting the cookie's own: the browser decides when to -// stop sending a cookie, and this does not depend on that decision. -func (self CookieOptions) end(writer http.ResponseWriter, request *http.Request, sealer Sealer) (Handshake, bool) { - defer self.write(writer, "", -1) - - cookie, err := request.Cookie(self.Name) - if err != nil || cookie.Value == "" { - return Handshake{}, false - } - - payload, err := sealer.Open(cookie.Value) - if err != nil { - return Handshake{}, false - } - - var handshake Handshake - if err := json.Unmarshal(payload, &handshake); err != nil { - return Handshake{}, false - } - - if handshake.State == "" || time.Now().After(handshake.ExpiresAt) { - return Handshake{}, false - } - - return handshake, true -} - -// SafeRedirect keeps only a path on this site. An absolute or protocol-relative -// URL would turn the callback into an open redirect. -func SafeRedirect(candidate string) string { - candidate = strings.TrimSpace(candidate) - - if !strings.HasPrefix(candidate, "/") || strings.HasPrefix(candidate, "//") { - return "" - } - - return candidate -} - -func randomToken(size int) string { - buffer := make([]byte, size) - if _, err := rand.Read(buffer); err != nil { - // A system that cannot produce randomness must not carry on issuing - // tokens that are supposed to be unguessable. - panic("social: failed to read random bytes: " + err.Error()) - } - - return base64.RawURLEncoding.EncodeToString(buffer) -} diff --git a/helpers_test.go b/helpers_test.go index 09cf71f..089454b 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -1,161 +1,240 @@ -package social_test +package sociable_test import ( - "context" + "crypto/sha256" "encoding/base64" + "encoding/json" + "errors" "net/http" + "net/http/cookiejar" "net/http/httptest" "net/url" + "sync" "testing" - "time" - "github.com/gonstruct/social" + "github.com/gonstruct/sociable" "golang.org/x/oauth2" ) -// plainSealer stands in for the application's encryption. The flow only -// needs the round trip, so most tests do not depend on a cipher. -type plainSealer struct{} - -func (plainSealer) Seal(plain []byte) (string, error) { - return base64.RawURLEncoding.EncodeToString(plain), nil +// 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 { + *httptest.Server + + mutex sync.Mutex + secret string + challenge string + scope string + profile map[string]any + deny bool + requests []url.Values } -func (plainSealer) Open(sealed string) ([]byte, error) { - return base64.RawURLEncoding.DecodeString(sealed) -} +func newAuthorizationServer(t *testing.T) *authorizationServer { + t.Helper() -type fakeProvider struct { - configured bool - scopes []string - tokenURL string -} + as := &authorizationServer{ + secret: "s3cret", + profile: map[string]any{"id": float64(42), "login": "arjen", "email": "arjen@example.test"}, + } -func (fakeProvider) Name() string { return "fake" } -func (provider fakeProvider) Configured() bool { return provider.configured } + mux := http.NewServeMux() + mux.HandleFunc("/authorize", as.authorize) + mux.HandleFunc("/token", as.token) + mux.HandleFunc("/me", as.me) -func (provider fakeProvider) Config() *oauth2.Config { - tokenURL := provider.tokenURL - if tokenURL == "" { - tokenURL = "https://provider.test/token" - } + as.Server = httptest.NewServer(mux) + t.Cleanup(as.Close) - return &oauth2.Config{ - ClientID: "client", - RedirectURL: "http://localhost/callback", - Scopes: provider.scopes, - Endpoint: oauth2.Endpoint{AuthURL: "https://provider.test/authorize", TokenURL: tokenURL}, - } + return as } -func (fakeProvider) User(_ context.Context, grant social.Grant) (*social.User, error) { - return &social.User{ID: "1", Email: "person@provider.test", EmailVerified: true, Raw: grant}, nil -} +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() -// parameterisedProvider wants a Google-shaped refresh token, which only comes -// back when these two ride along on the authorization URL. -type parameterisedProvider struct{ fakeProvider } + back, _ := url.Parse(r.URL.Query().Get("redirect_uri")) + query := url.Values{"state": {r.URL.Query().Get("state")}} -func (parameterisedProvider) Parameters() []oauth2.AuthCodeOption { - return []oauth2.AuthCodeOption{oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent")} -} + if as.deny { + query.Set("error", "access_denied") + query.Set("error_description", "the person said no") + } else { + query.Set("code", "c0de") + } -// unprotectedProvider stands for the older providers that reject a challenge. -type unprotectedProvider struct{ fakeProvider } + back.RawQuery = query.Encode() + http.Redirect(w, r, back.String(), http.StatusFound) +} -func (unprotectedProvider) UsesPKCE() bool { return false } +func (as *authorizationServer) token(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() -// issuedProvider names itself, which is what makes RFC 9207's iss parameter -// required rather than merely checked. -type issuedProvider struct{ fakeProvider } + if r.PostForm.Get("code") != "c0de" || r.PostForm.Get("client_secret") != as.secret { + http.Error(w, `{"error":"invalid_grant"}`, http.StatusBadRequest) -func (issuedProvider) Issuer() string { return "https://provider.test" } + return + } -func configured() fakeProvider { return fakeProvider{configured: true} } + as.mutex.Lock() + challenge := as.challenge + as.mutex.Unlock() -// setup builds a registry with one provider under "fake". -func setup(t *testing.T, provider social.Provider) *social.Social { - t.Helper() + 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) - auth, err := social.New(social.Configuration{Sealer: plainSealer{}, Drivers: social.Drivers{"fake": provider}}) - if err != nil { - t.Fatal(err) + return + } } - return auth + 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, + }) } -// redirect runs Redirect through a handler and returns what the browser -// would have received: the Location and the handshake cookie. -func redirect(t *testing.T, auth *social.Social, options ...social.Option) *httptest.ResponseRecorder { - t.Helper() +func (as *authorizationServer) me(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer t0ken" { + http.Error(w, "unauthorized", http.StatusUnauthorized) - recorder := httptest.NewRecorder() - if err := auth.Redirect(recorder, httptest.NewRequest(http.MethodGet, "/login", nil), "fake", options...); err != nil { - t.Fatalf("redirect: %v", err) + return } - return recorder + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(as.profile) } -// callback runs Callback for a request, carrying the cookies a previous -// response set, and returns the recorder too because the handshake cookie -// must be cleared by it. -func callback( - t *testing.T, - auth *social.Social, - target string, - from *httptest.ResponseRecorder, - options ...social.Option, -) (*social.Result, error, *httptest.ResponseRecorder) { - t.Helper() +func (as *authorizationServer) lastRequest() url.Values { + as.mutex.Lock() + defer as.mutex.Unlock() - recorder := httptest.NewRecorder() - request := httptest.NewRequest(http.MethodGet, target, nil) - if from != nil { - for _, cookie := range from.Result().Cookies() { - request.AddCookie(cookie) + return as.requests[len(as.requests)-1] +} + +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")} + }, } } +} - result, err := auth.Callback(recorder, request, "fake", options...) +// 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 { + *httptest.Server - return result, err, recorder + auth *sociable.Manager + before func(sociable.Flow) sociable.Flow } -// issuedQuery is the authorization URL the driver sent the browser to, taken -// apart. -func issuedQuery(t *testing.T, recorder *httptest.ResponseRecorder) url.Values { +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 { t.Helper() - parsed, err := url.Parse(recorder.Header().Get("Location")) + app := &application{before: func(flow sociable.Flow) sociable.Flow { return flow }} + + 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) + + w.Header().Set("Content-Type", "application/json") + + if err != nil { + _ = json.NewEncoder(w).Encode(outcome{Error: classify(err)}) + + return + } + + _ = json.NewEncoder(w).Encode(outcome{User: user}) + }) + + app.Server = httptest.NewServer(mux) + t.Cleanup(app.Close) + + 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) + } + + auth, err := sociable.New(config) if err != nil { - t.Fatal(err) + t.Fatalf("New: %v", err) } - return parsed.Query() + 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() + } } -func issuedState(t *testing.T, recorder *httptest.ResponseRecorder) string { +func browser(t *testing.T) *http.Client { t.Helper() - return issuedQuery(t, recorder).Get("state") + jar, err := cookiejar.New(nil) + if err != nil { + t.Fatal(err) + } + + return &http.Client{Jar: jar} } -// tokenEndpoint answers an exchange with the smallest token RFC 6749 section -// 5.1 allows, so a test can reach what happens after one. -func tokenEndpoint(t *testing.T) string { +func signIn(t *testing.T, client *http.Client, app *application, driver string) outcome { t.Helper() - server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { - writer.Header().Set("Content-Type", "application/json") - _, _ = writer.Write([]byte(`{"access_token":"granted","token_type":"Bearer"}`)) - })) - t.Cleanup(server.Close) + response, err := client.Get(app.URL + "/auth/" + driver) + if err != nil { + t.Fatalf("sign in: %v", err) + } + defer response.Body.Close() - return server.URL -} + var result outcome + if err := json.NewDecoder(response.Body).Decode(&result); err != nil { + t.Fatalf("decode outcome: %v", err) + } -func expired() social.CookieOptions { - return social.CookieOptions{Lifetime: -time.Second} + return result } diff --git a/oauth2.go b/oauth2.go deleted file mode 100644 index cc83bf8..0000000 --- a/oauth2.go +++ /dev/null @@ -1,130 +0,0 @@ -package social - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "golang.org/x/oauth2" -) - -// OAuth2 is a provider described by its endpoints, for the many providers that -// need no code of their own: an authorization URL, a token URL, a profile URL -// and a function that reads the profile. It is what the google and github -// packages are built on, and what an application uses for a provider this -// module does not ship. -type OAuth2 struct { - // Driver is the name the provider is registered and routed under. - Driver string - - ClientID string - ClientSecret string - RedirectURL string - - AuthURL string - TokenURL string - ProfileURL string - - // Scopes are asked for unless the call site changes them. - Scopes []string - - // Extra parameters sent on every authorization request, such as - // access_type=offline for a Google refresh token. - Extra map[string]string - - // IssuerURL, when set, makes the iss parameter of RFC 9207 required on - // the callback. Only set it for a provider that sends the parameter. - IssuerURL string - - // WithoutPKCE opts out for a provider that rejects the challenge. - WithoutPKCE bool - - // Profile turns the decoded profile into a User. Raw is filled in by the - // provider; a Profile that leaves it empty keeps the decoded map. - Profile func(raw map[string]any) User -} - -func (self *OAuth2) Name() string { return self.Driver } - -func (self *OAuth2) Config() *oauth2.Config { - return &oauth2.Config{ - ClientID: self.ClientID, - ClientSecret: self.ClientSecret, - RedirectURL: self.RedirectURL, - Scopes: self.Scopes, - Endpoint: oauth2.Endpoint{AuthURL: self.AuthURL, TokenURL: self.TokenURL}, - } -} - -func (self *OAuth2) Configured() bool { - return self.ClientID != "" && self.AuthURL != "" && self.TokenURL != "" -} - -func (self *OAuth2) Parameters() []oauth2.AuthCodeOption { - options := make([]oauth2.AuthCodeOption, 0, len(self.Extra)) - for key, value := range self.Extra { - options = append(options, oauth2.SetAuthURLParam(key, value)) - } - - return options -} - -func (self *OAuth2) UsesPKCE() bool { return !self.WithoutPKCE } - -// Issuer is only consulted when IssuerURL is set; see Issued. -func (self *OAuth2) Issuer() string { return self.IssuerURL } - -// User fetches ProfileURL with the grant and hands the decoded JSON to Profile. -func (self *OAuth2) User(_ context.Context, grant Grant) (*User, error) { - raw, err := FetchJSON(grant, self.ProfileURL) - if err != nil { - return nil, err - } - - if self.Profile == nil { - return &User{Raw: raw}, nil - } - - user := self.Profile(raw) - if user.Raw == nil { - user.Raw = raw - } - - return &user, nil -} - -// FetchJSON reads a JSON document from the provider with the grant's client. -// Providers written by hand use it for their profile endpoints. -func FetchJSON(grant Grant, url string) (map[string]any, error) { - response, err := grant.Client.Get(url) - if err != nil { - return nil, fmt.Errorf("get %s: %w", url, err) - } - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - return nil, fmt.Errorf("get %s: status %d", url, response.StatusCode) - } - - var raw map[string]any - if err := json.NewDecoder(response.Body).Decode(&raw); err != nil { - return nil, fmt.Errorf("decode %s: %w", url, err) - } - - return raw, nil -} - -// String reads a string field of a decoded profile, "" when absent. -func String(raw map[string]any, key string) string { - value, _ := raw[key].(string) - - return value -} - -// Bool reads a boolean field of a decoded profile, false when absent. -func Bool(raw map[string]any, key string) bool { - value, _ := raw[key].(bool) - - return value -} diff --git a/oauth2_test.go b/oauth2_test.go deleted file mode 100644 index 12a5045..0000000 --- a/oauth2_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package social_test - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "testing" - - "github.com/gonstruct/social" - "golang.org/x/oauth2" -) - -func TestOAuth2ProviderFromEndpoints(t *testing.T) { - provider := &social.OAuth2{ - Driver: "acme", ClientID: "id", ClientSecret: "secret", RedirectURL: "http://app/cb", - AuthURL: "https://acme/authorize", TokenURL: "https://acme/token", - Scopes: []string{"a"}, Extra: map[string]string{"prompt": "consent"}, IssuerURL: "https://acme", - } - - if provider.Name() != "acme" || !provider.Configured() || !provider.UsesPKCE() || provider.Issuer() != "https://acme" { - t.Fatalf("basics: %+v", provider) - } - config := provider.Config() - if config.ClientID != "id" || config.Endpoint.AuthURL != "https://acme/authorize" || config.Scopes[0] != "a" { - t.Fatalf("config: %+v", config) - } - if len(provider.Parameters()) != 1 { - t.Fatalf("extra parameters: %v", provider.Parameters()) - } - - provider.WithoutPKCE = true - if provider.UsesPKCE() { - t.Error("WithoutPKCE ignored") - } - if (&social.OAuth2{Driver: "x", AuthURL: "a", TokenURL: "t"}).Configured() { - t.Error("a provider without a client id is not configured") - } -} - -func TestOAuth2ProviderReadsTheProfile(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Authorization") != "Bearer tok" { - http.Error(w, "no", http.StatusUnauthorized) - return - } - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]any{"id": "7", "handle": "person"}) - })) - t.Cleanup(server.Close) - - provider := &social.OAuth2{ProfileURL: server.URL + "/me", Profile: func(raw map[string]any) social.User { - return social.User{ID: social.String(raw, "id"), Nickname: social.String(raw, "handle")} - }} - grant := social.Grant{Token: &oauth2.Token{AccessToken: "tok"}, Client: (&oauth2.Config{}).Client(t.Context(), &oauth2.Token{AccessToken: "tok"})} - - user, err := provider.User(t.Context(), grant) - if err != nil || user.ID != "7" || user.Nickname != "person" { - t.Fatalf("user: %+v %v", user, err) - } - if raw, ok := user.Raw.(map[string]any); !ok || raw["id"] != "7" { - t.Error("Raw should keep the decoded profile") - } - - // Without a Profile function the raw document is all there is. - bare := &social.OAuth2{ProfileURL: server.URL + "/me"} - user, err = bare.User(t.Context(), grant) - if err != nil || user.ID != "" || user.Raw == nil { - t.Fatalf("bare: %+v %v", user, err) - } - - // A refused or broken profile endpoint is an error, not a user. - unauthorised := social.Grant{Client: (&oauth2.Config{}).Client(t.Context(), &oauth2.Token{AccessToken: "wrong"})} - if _, err := provider.User(t.Context(), unauthorised); err == nil { - t.Error("a 401 from the profile endpoint should be an error") - } -} diff --git a/oidc.go b/oidc.go deleted file mode 100644 index 59fdc74..0000000 --- a/oidc.go +++ /dev/null @@ -1,186 +0,0 @@ -package social - -import ( - "context" - "errors" - "fmt" - "net/http" - "sync" - - "github.com/coreos/go-oidc/v3/oidc" - "golang.org/x/oauth2" -) - -// ErrIDToken means the provider's ID token could not be verified: a bad -// signature, another issuer or audience, an expired token, or a nonce that is -// not the one this package issued. It is never wrapped as a profile failure, -// because it is the one error that must not be mistaken for one. -var ErrIDToken = errors.New("social: the id token could not be verified") - -// OpenIDConnect is a provider that supports OpenID Connect discovery. Its -// endpoints and signing keys are read from the issuer, and the identity comes -// from a verified ID token rather than a profile request. -type OpenIDConnect struct { - // Driver is the name the provider is registered and routed under. - Driver string - - // IssuerURL is where discovery starts: IssuerURL/.well-known/openid-configuration. - IssuerURL string - - ClientID string - ClientSecret string - RedirectURL string - - // Scopes default to openid, email and profile. - Scopes []string - - // Extra parameters sent on every authorization request, such as - // access_type=offline for a Google refresh token. - Extra map[string]string - - // RequireIssuerParameter makes the iss parameter of RFC 9207 required on - // the callback. Only turn it on for a provider that sends it. - RequireIssuerParameter bool - - // WithoutPKCE opts out for a provider that rejects the challenge. - WithoutPKCE bool - - // Client fetches the discovery document and the keys. nil is - // http.DefaultClient. - Client *http.Client - - // Profile overrides how the verified claims become a User. - Profile func(claims map[string]any) User - - once sync.Once - discovered *oidc.Provider - discovery error -} - -func (self *OpenIDConnect) Name() string { return self.Driver } - -// Config is the provider's endpoints from discovery. When discovery failed the -// endpoints are empty, and Configured says so. -func (self *OpenIDConnect) Config() *oauth2.Config { - config := &oauth2.Config{ - ClientID: self.ClientID, - ClientSecret: self.ClientSecret, - RedirectURL: self.RedirectURL, - Scopes: self.scopes(), - } - if provider := self.provider(); provider != nil { - config.Endpoint = provider.Endpoint() - } - - return config -} - -// Configured is true when the credentials are present and discovery -// succeeded. Discovery runs once, on first use. -func (self *OpenIDConnect) Configured() bool { - return self.ClientID != "" && self.IssuerURL != "" && self.provider() != nil -} - -func (self *OpenIDConnect) Parameters() []oauth2.AuthCodeOption { - options := make([]oauth2.AuthCodeOption, 0, len(self.Extra)) - for key, value := range self.Extra { - options = append(options, oauth2.SetAuthURLParam(key, value)) - } - - return options -} - -func (self *OpenIDConnect) UsesPKCE() bool { return !self.WithoutPKCE } - -func (self *OpenIDConnect) Issuer() string { - if !self.RequireIssuerParameter { - return "" - } - - return self.IssuerURL -} - -// User verifies the ID token and reads the identity from its claims. The -// token is checked for its signature against the issuer's keys, its issuer, -// its audience, its expiry, and the nonce this package sent. -func (self *OpenIDConnect) User(ctx context.Context, grant Grant) (*User, error) { - raw, _ := grant.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) - } - - verifier := provider.Verifier(&oidc.Config{ClientID: self.ClientID}) - token, err := verifier.Verify(oidc.ClientContext(ctx, self.httpClient()), raw) - if err != nil { - return nil, fmt.Errorf("%w: %w", ErrIDToken, err) - } - if grant.Nonce != "" && token.Nonce != grant.Nonce { - return nil, fmt.Errorf("%w: nonce does not match", ErrIDToken) - } - - var claims map[string]any - if err := token.Claims(&claims); err != nil { - return nil, fmt.Errorf("%w: %w", ErrIDToken, err) - } - - user := Claims(claims) - if self.Profile != nil { - user = self.Profile(claims) - } - if user.Raw == nil { - user.Raw = claims - } - - return &user, nil -} - -// 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"), - } -} - -func (self *OpenIDConnect) scopes() []string { - if len(self.Scopes) > 0 { - return self.Scopes - } - - return []string{openIDScope, "email", "profile"} -} - -func (self *OpenIDConnect) httpClient() *http.Client { - if self.Client != nil { - return self.Client - } - - return http.DefaultClient -} - -func (self *OpenIDConnect) provider() *oidc.Provider { - self.once.Do(func() { - ctx := oidc.ClientContext(context.Background(), self.httpClient()) - self.discovered, self.discovery = oidc.NewProvider(ctx, self.IssuerURL) - }) - - return self.discovered -} - -func isIDToken(err error) bool { - return errors.Is(err, ErrIDToken) -} diff --git a/oidc_test.go b/oidc_test.go deleted file mode 100644 index b370550..0000000 --- a/oidc_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package social_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/social" -) - -// openIDProvider is an OpenID Connect provider that behaves: discovery, keys, -// an authorization endpoint that redirects back, and a token endpoint that -// signs an ID token with the nonce it was given. -type openIDProvider struct { - *httptest.Server - - key *rsa.PrivateKey - nonce string - audience string - issuer string // what goes in the token; the real issuer unless a test lies - expired bool - noIDTok bool -} - -func newOpenIDProvider(t *testing.T) *openIDProvider { - t.Helper() - - key, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - t.Fatal(err) - } - op := &openIDProvider{key: key, audience: "app-id"} - mux := http.NewServeMux() - op.Server = httptest.NewServer(mux) - t.Cleanup(op.Close) - op.issuer = op.URL - - mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - _ = 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", - "userinfo_endpoint": op.URL + "/userinfo", - "id_token_signing_alg_values_supported": []string{"RS256"}, - }) - }) - mux.HandleFunc("/keys", func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - _ = 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) { - query := r.URL.Query() - op.nonce = query.Get("nonce") - back, _ := url.Parse(query.Get("redirect_uri")) - back.RawQuery = url.Values{"state": {query.Get("state")}, "code": {"the-code"}}.Encode() - http.Redirect(w, r, back.String(), http.StatusFound) - }) - mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { - _ = r.ParseForm() - token := map[string]any{"access_token": "the-token", "token_type": "Bearer", "expires_in": 3600} - if !op.noIDTok { - token["id_token"] = op.idToken(t) - } - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(token) - }) - - return op -} - -func (op *openIDProvider) 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) - } - now := time.Now() - expiry := now.Add(time.Hour) - if op.expired { - expiry = now.Add(-time.Hour) - } - claims := map[string]any{ - "iss": op.issuer, "sub": "person-1", "aud": op.audience, "nonce": op.nonce, - "iat": now.Unix(), "exp": expiry.Unix(), - "email": "person@example.com", "email_verified": true, "name": "A Person", "given_name": "A", "picture": "https://cdn/p.png", - } - raw, err := jwt.Signed(signer).Claims(claims).Serialize() - if err != nil { - t.Fatal(err) - } - - return raw -} - -func openIDConnectProvider(op *openIDProvider) func(app *application) social.Provider { - return func(app *application) social.Provider { - return &social.OpenIDConnect{ - Driver: "acme", IssuerURL: op.URL, ClientID: "app-id", ClientSecret: "app-secret", RedirectURL: app.URL + "/callback", - } - } -} - -func TestOpenIDConnectSignsInFromAVerifiedIDToken(t *testing.T) { - op := newOpenIDProvider(t) - app := newApplication(t, openIDConnectProvider(op)) - - result, response := signIn(t, browser(t), app, "/login?to=/home") - if response.StatusCode != http.StatusOK { - t.Fatalf("expected 200, got %d", response.StatusCode) - } - if result.ID != "person-1" || result.Email != "person@example.com" || !result.Verified || result.Name != "A Person" || result.RedirectTo != "/home" { - t.Fatalf("wrong user: %+v", result) - } - if op.nonce == "" { - t.Fatal("an openid request should carry a nonce") - } -} - -func TestOpenIDConnectRefusesAnIDTokenForAnotherAudience(t *testing.T) { - op := newOpenIDProvider(t) - op.audience = "someone-else" - app := newApplication(t, openIDConnectProvider(op)) - - if _, response := signIn(t, browser(t), app, "/login"); response.StatusCode == http.StatusOK { - t.Fatal("a token for another client must not sign anyone in") - } -} - -func TestOpenIDConnectRefusesAnExpiredIDToken(t *testing.T) { - op := newOpenIDProvider(t) - op.expired = true - app := newApplication(t, openIDConnectProvider(op)) - - if _, response := signIn(t, browser(t), app, "/login"); response.StatusCode == http.StatusOK { - t.Fatal("an expired token must not sign anyone in") - } -} - -func TestOpenIDConnectRefusesAnIDTokenFromAnotherIssuer(t *testing.T) { - op := newOpenIDProvider(t) - op.issuer = "https://attacker.test" - app := newApplication(t, openIDConnectProvider(op)) - - if _, response := signIn(t, browser(t), app, "/login"); response.StatusCode == http.StatusOK { - t.Fatal("a token from another issuer must not sign anyone in") - } -} - -func TestOpenIDConnectRefusesTheWrongNonce(t *testing.T) { - op := newOpenIDProvider(t) - app := newApplication(t, openIDConnectProvider(op)) - client := browser(t) - - // Start once so a handshake exists, then make the provider sign a token - // for a nonce nobody issued. - redirect := &http.Client{Jar: client.Jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} - first, err := redirect.Get(app.URL + "/login") - if err != nil { - t.Fatal(err) - } - first.Body.Close() - location, _ := url.Parse(first.Header.Get("Location")) - op.nonce = "not-the-one" - - callback := app.URL + "/callback?code=the-code&state=" + url.QueryEscape(location.Query().Get("state")) - response, err := client.Get(callback) - if err != nil { - t.Fatal(err) - } - defer response.Body.Close() - if response.StatusCode == http.StatusOK { - t.Fatal("a token with another nonce must not sign anyone in") - } -} - -func TestOpenIDConnectNeedsAnIDToken(t *testing.T) { - op := newOpenIDProvider(t) - op.noIDTok = true - app := newApplication(t, openIDConnectProvider(op)) - - if _, response := signIn(t, browser(t), app, "/login"); response.StatusCode == http.StatusOK { - t.Fatal("a token response without an id_token must not sign anyone in") - } -} - -func TestOpenIDConnectDiscoveryFailureIsNotConfigured(t *testing.T) { - provider := &social.OpenIDConnect{Driver: "acme", IssuerURL: "http://127.0.0.1:1", ClientID: "id"} - if provider.Configured() { - t.Fatal("a provider that cannot be discovered is not configured") - } -} - -func TestClaimsMapping(t *testing.T) { - user := social.Claims(map[string]any{ - "sub": "1", "email": "p@example.com", "email_verified": true, "name": "P", "preferred_username": "pee", "picture": "https://p", - }) - if user.ID != "1" || user.Email != "p@example.com" || !user.EmailVerified || user.Name != "P" || user.Nickname != "pee" || user.Avatar != "https://p" { - t.Fatalf("claims: %+v", user) - } - if social.Claims(map[string]any{"sub": "1", "given_name": "G"}).Nickname != "G" { - t.Error("given_name should be the fallback nickname") - } -} diff --git a/openid.go b/openid.go new file mode 100644 index 0000000..1057f9f --- /dev/null +++ b/openid.go @@ -0,0 +1,120 @@ +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 new file mode 100644 index 0000000..0303d63 --- /dev/null +++ b/openid_test.go @@ -0,0 +1,133 @@ +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/options.go b/options.go deleted file mode 100644 index 087c0a7..0000000 --- a/options.go +++ /dev/null @@ -1,77 +0,0 @@ -package social - -import "golang.org/x/oauth2" - -// Option shapes one request. Every one is optional: the defaults are what the -// provider registered, with PKCE on. -type Option func(*flow) - -// To is where the browser should land once the sign-in is complete. It must -// be a path on this site; anything else is dropped, see SafeRedirect. It -// comes back from Callback as Result.RedirectTo. -func To(path string) Option { - return func(f *flow) { f.to = path } -} - -// Scopes adds to what the provider already asks for. -func Scopes(scopes ...string) Option { - return func(f *flow) { f.scopes = dedupe(append(f.scoped(), scopes...)) } -} - -// SetScopes replaces them, for the caller who wants exactly these and no more. -func SetScopes(scopes ...string) Option { - return func(f *flow) { f.scopes = dedupe(scopes) } -} - -// With adds parameters to the authorization URL. Use it for the ones that -// belong to this request rather than to the provider, a login_hint, a prompt, -// and implement Parameterised for the ones that are always sent. -// -// The parameters the flow owns cannot be overwritten from here: state, -// code_challenge and nonce are what make the callback trustworthy, and a call -// site is not the place to decide otherwise. -func With(parameters map[string]string) Option { - return func(f *flow) { - for key, value := range parameters { - if reserved(key) { - continue - } - f.parameters = append(f.parameters, oauth2.SetAuthURLParam(key, value)) - } - } -} - -// RedirectURL overrides where the provider sends the browser back. It must -// still be one the provider has registered: RFC 6749 section 3.1.2.3 has the -// authorization server compare it exactly, so an unregistered value fails -// there rather than here. -func RedirectURL(url string) Option { - return func(f *flow) { f.redirectURL = url } -} - -// Stateless drops the handshake, for a flow this server did not start: a -// native app or a single-page client that runs the redirect itself and brings -// back what it got. -// -// It costs both defences at once: no state to compare, and nowhere to keep a -// verifier, so no PKCE either. Whatever uses it takes on the job of deciding -// that the callback belongs to the session it will be used for. -func Stateless() Option { - return func(f *flow) { f.stateless = true } -} - -// UsingPKCE turns PKCE on for a provider that opted out of it. -func UsingPKCE() Option { - enabled := true - - return func(f *flow) { f.pkce = &enabled } -} - -// WithoutPKCE turns it off for one request. Prefer implementing Unprotected: a -// provider that cannot do PKCE cannot do it on any request, and that belongs -// with the provider rather than at one call site. -func WithoutPKCE() Option { - disabled := false - - return func(f *flow) { f.pkce = &disabled } -} diff --git a/provider.go b/provider.go index ad1943d..a084824 100644 --- a/provider.go +++ b/provider.go @@ -1,69 +1,165 @@ -package social +package sociable import ( "context" + "encoding/json" + "fmt" "net/http" + "strconv" + "strings" "golang.org/x/oauth2" ) -// Provider is what a driver must supply: where to send the browser, and how to -// turn a grant into a user. Everything else about the flow is this package's, -// and everything a provider may change about it is an interface below. +// 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. type Provider interface { - // Name identifies the driver in routes and logs. - Name() string - - // Config carries the endpoints, credentials and default scopes. The flow - // copies it before changing anything, so returning the same pointer on - // every call is safe. Config() *oauth2.Config - - // Configured reports whether the credentials are present. - Configured() bool - - // User reads the provider's profile and normalises it. - User(context context.Context, grant Grant) (*User, error) + User(ctx context.Context, client *http.Client, token *oauth2.Token) (*User, error) } -// Grant is what the flow obtained, handed to the provider so it can read the -// profile and check anything the token carries. -// -// Client already presents the token, so a provider reads its profile with a -// plain Get. Nonce is the value that was sent on the authorization request -// when the provider was asked for the openid scope. A provider that reads an -// ID token must check the nonce claim against it: OpenID Connect Core section -// 3.1.3.7 makes that the client's job, and it is what stops a token issued for -// one sign-in being replayed into another. -type Grant struct { - Token *oauth2.Token - Nonce string - Client *http.Client +// Factory builds a Provider from the credentials configured under its name. +type Factory func(credentials Credentials) Provider + +// 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 } -// Parameterised is implemented by a provider that needs more on the -// authorization URL than the flow itself puts there: access_type and prompt for -// a Google refresh token, audience for an API-scoped token, a provider's own -// invention. A provider that stays silent sends none. -type Parameterised interface { - Parameters() []oauth2.AuthCodeOption +// 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) } -// Unprotected is implemented by a provider that cannot do PKCE. Some older -// providers reject the challenge outright, and a confidential client with a -// secret is not defenceless without it. -// -// PKCE is on for every provider that stays silent. OAuth 2.1 makes it mandatory -// for all clients, so opting out should be a decision somebody wrote down. +// Unprotected is a provider that cannot do PKCE. Every provider that stays +// silent does it. type Unprotected interface { UsesPKCE() bool } -// Issued is implemented by a provider whose authorization responses carry the -// iss parameter from RFC 9207. Implementing it makes the parameter required: -// the point of the extension is that a client which expects an issuer rejects a -// response without one, which is what defeats a mix-up attack between two -// authorization servers the same client talks to. -type Issued interface { - Issuer() 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, + } +} + +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 +} + +// 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 { + request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return err + } + + request.Header.Set("Accept", "application/json") + + response, err := client.Do(request) + if err != nil { + return fmt.Errorf("get %s: %w", url, 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 "" + } +} + +// 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] + } + + return current } diff --git a/providers.go b/providers.go new file mode 100644 index 0000000..d2554a6 --- /dev/null +++ b/providers.go @@ -0,0 +1,251 @@ +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 new file mode 100644 index 0000000..645afde --- /dev/null +++ b/providers_test.go @@ -0,0 +1,166 @@ +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/sealer.go b/sealer.go deleted file mode 100644 index e058a15..0000000 --- a/sealer.go +++ /dev/null @@ -1,61 +0,0 @@ -package social - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "encoding/base64" - "errors" - "fmt" -) - -// ErrSealed is returned by a sealer that cannot open what it was given: a -// forged, truncated or foreign value. The flow treats it as no handshake. -var ErrSealed = errors.New("social: the sealed value cannot be opened") - -type aesSealer struct { - aead cipher.AEAD -} - -// AESSealer seals with AES-GCM under a 16, 24 or 32 byte key. It is the -// sealer to use when the application has no encryption of its own to hand -// over; the key must be the same on every instance that handles a callback. -func AESSealer(key []byte) (Sealer, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, fmt.Errorf("social: %w", err) - } - - aead, err := cipher.NewGCM(block) - if err != nil { - return nil, fmt.Errorf("social: %w", err) - } - - return &aesSealer{aead: aead}, nil -} - -func (self *aesSealer) Seal(plain []byte) (string, error) { - nonce := make([]byte, self.aead.NonceSize()) - if _, err := rand.Read(nonce); err != nil { - return "", fmt.Errorf("social: %w", err) - } - - sealed := self.aead.Seal(nonce, nonce, plain, nil) - - return base64.RawURLEncoding.EncodeToString(sealed), nil -} - -func (self *aesSealer) Open(sealed string) ([]byte, error) { - data, err := base64.RawURLEncoding.DecodeString(sealed) - if err != nil || len(data) < self.aead.NonceSize() { - return nil, ErrSealed - } - - size := self.aead.NonceSize() - plain, err := self.aead.Open(nil, data[:size], data[size:], nil) - if err != nil { - return nil, ErrSealed - } - - return plain, nil -} diff --git a/sealer_test.go b/sealer_test.go deleted file mode 100644 index 57112f8..0000000 --- a/sealer_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package social_test - -import ( - "errors" - "testing" - - "github.com/gonstruct/social" -) - -func TestAESSealerRoundTrips(t *testing.T) { - sealer, err := social.AESSealer([]byte("0123456789abcdef0123456789abcdef")) - if err != nil { - t.Fatal(err) - } - - sealed, err := sealer.Seal([]byte(`{"state":"s"}`)) - if err != nil { - t.Fatal(err) - } - opened, err := sealer.Open(sealed) - if err != nil || string(opened) != `{"state":"s"}` { - t.Fatalf("round trip: %q %v", opened, err) - } - - // Every seal is different, so two handshakes never look alike on the wire. - again, _ := sealer.Seal([]byte(`{"state":"s"}`)) - if again == sealed { - t.Error("the nonce is not random") - } -} - -func TestAESSealerRejectsTamperingAndOtherKeys(t *testing.T) { - sealer, _ := social.AESSealer([]byte("0123456789abcdef0123456789abcdef")) - other, _ := social.AESSealer([]byte("fedcba9876543210fedcba9876543210")) - - sealed, _ := sealer.Seal([]byte("secret")) - - for name, value := range map[string]string{ - "tampered": sealed[:len(sealed)-2] + "zz", - "truncated": sealed[:4], - "garbage": "not base64 at all!", - "empty": "", - } { - if _, err := sealer.Open(value); !errors.Is(err, social.ErrSealed) { - t.Errorf("%s: expected ErrSealed, got %v", name, err) - } - } - if _, err := other.Open(sealed); !errors.Is(err, social.ErrSealed) { - t.Errorf("another key: expected ErrSealed, got %v", err) - } -} - -func TestAESSealerNeedsAValidKey(t *testing.T) { - if _, err := social.AESSealer([]byte("short")); err == nil { - t.Fatal("a five byte key should be refused") - } -} diff --git a/session.go b/session.go new file mode 100644 index 0000000..05e7572 --- /dev/null +++ b/session.go @@ -0,0 +1,127 @@ +package sociable + +import ( + "crypto/aes" + "crypto/cipher" + "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. +// +// 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. +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") + +type cookieSession struct { + aead cipher.AEAD + secure bool +} + +func newCookieSession(key string, secure bool) *cookieSession { + derived := sha256.Sum256([]byte(key)) + + block, err := aes.NewCipher(derived[:]) + if err != nil { + panic("sociable: " + err.Error()) + } + + aead, err := cipher.NewGCM(block) + if err != nil { + panic("sociable: " + err.Error()) + } + + return &cookieSession{aead: aead, secure: secure} +} + +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 + } + + sealed := self.aead.Seal(nonce, nonce, []byte(value), nil) + + self.write(w, r, key, base64.RawURLEncoding.EncodeToString(sealed), int(handshakeLifetime.Seconds())) + + return nil +} + +// Pull reads and clears the cookie. It clears whether or not the value opens, +// so a failed attempt cannot be replayed. +func (self *cookieSession) Pull(w http.ResponseWriter, r *http.Request, key string) (string, error) { + defer self.write(w, r, key, "", -1) + + cookie, err := r.Cookie(key) + if err != nil { + return "", err + } + + data, err := base64.RawURLEncoding.DecodeString(cookie.Value) + if err != nil || len(data) < self.aead.NonceSize() { + return "", ErrSealed + } + + size := self.aead.NonceSize() + + plain, err := self.aead.Open(nil, data[:size], data[size:], nil) + if err != nil { + return "", ErrSealed + } + + return string(plain), nil +} + +func (self *cookieSession) write(w http.ResponseWriter, r *http.Request, key, value string, maxAge int) { + http.SetCookie(w, &http.Cookie{ + Name: key, + Value: value, + Path: "/", + MaxAge: maxAge, + Secure: self.secure || r.TLS != nil, + HttpOnly: true, + 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/sociable.go b/sociable.go new file mode 100644 index 0000000..1517d94 --- /dev/null +++ b/sociable.go @@ -0,0 +1,249 @@ +// 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" +) + +// 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 +} + +// 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. +type Manager struct { + mutex sync.RWMutex + config Config + session Session + factories map[string]Factory + providers map[string]Provider + fakes map[string]*Faked +} + +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 + } + + return manager, nil +} + +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{} + } + + self.mutex.Lock() + defer self.mutex.Unlock() + + self.config = config + self.session = session + clear(self.providers) + + return nil +} + +// 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 + } + + 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() + + if provider, built := self.providers[name]; built { + return provider + } + + 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) +} + +// 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() + + if self.fakes == nil { + self.fakes = map[string]*Faked{} + } + + 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 +} diff --git a/sociable_test.go b/sociable_test.go new file mode 100644 index 0000000..6c342da --- /dev/null +++ b/sociable_test.go @@ -0,0 +1,137 @@ +package sociable_test + +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() + + authURL, err := sociable.Driver("github").AuthURL(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + if err != nil { + t.Fatal(err) + } + + parsed := mustParse(authURL) + if parsed.Host != "github.com" || parsed.Query().Get("redirect_uri") != "https://app.test/auth/github/callback" { + t.Errorf("url = %s", authURL) + } + + cookies := recorder.Result().Cookies() + if len(cookies) != 1 || cookies[0].Name != "sociable" || !cookies[0].HttpOnly || !cookies[0].Secure { + t.Errorf("cookies = %+v", cookies) + } + + if err := sociable.Driver("nope").Redirect(recorder, httptest.NewRequest(http.MethodGet, "/", nil)); !errors.Is(err, sociable.ErrUnknownDriver) { + t.Errorf("err = %v", err) + } +} + +// A fake needs no configuration at all, the way Socialite::fake needs none. +func TestFakeNeedsNoConfiguration(t *testing.T) { + var auth sociable.Manager + + fake := auth.Fake("google", sociable.User{ID: "1"}) + + 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) + } + + 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) + } + + // 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) + } +} + +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) + } + + 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"}}) + + 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) + } + + 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 client := auth.Driver("google").Client(t.Context(), token); client == nil { + t.Error("no client") + } + + 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) + } +} + +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) + } + + _, err = auth.Driver("github").AuthURL(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) + if !errors.Is(err, sociable.ErrNotConfigured) { + t.Errorf("err = %v", err) + } +} diff --git a/social.go b/social.go deleted file mode 100644 index e9435ae..0000000 --- a/social.go +++ /dev/null @@ -1,205 +0,0 @@ -// Package social signs people in with somebody else's account: the OAuth 2.0 -// authorization code flow with PKCE, and OpenID Connect on top of it, on -// plain net/http, for any provider. -// -// A handler does two things: -// -// err := auth.Redirect(w, r, "google", social.To("/dashboard")) -// result, err := auth.Callback(w, r, "google") -// -// and shapes the request with options when it needs to: -// -// auth.Redirect(w, r, "google", -// social.Scopes("https://www.googleapis.com/auth/drive.readonly"), -// social.With(map[string]string{"login_hint": address}), -// social.To("/settings/integrations")) -// -// What it does that most clients do not: -// -// - PKCE (RFC 7636) is on unless a provider says it cannot, rather than off -// unless somebody remembers. OAuth 2.1 requires it of every client. -// - A provider that refuses in the redirect (RFC 6749 section 4.1.2.1) is an -// AuthorizationError, so a cancelled sign-in is not reported as a broken -// one. -// - ID tokens are verified: signature against the provider's keys, issuer, -// audience, expiry, and the nonce this package issued. -// - The iss parameter (RFC 9207) is checked for a provider that asks for it, -// which is what defeats a mix-up between two authorization servers. -// - State is compared in constant time, the handshake carries its own -// expiry, and is spent by any callback whether it succeeds or not. -// - Granted scopes come back on the User, because RFC 6749 section 5.1 lets -// them differ from the ones requested. -// -// It deliberately stops at the identity. What an application does with the -// resolved user, sign them in, attach them to a workspace, refuse them, is the -// application's. -package social - -import ( - "context" - "errors" - "fmt" - "maps" - "net/http" - "sync" - - "golang.org/x/oauth2" -) - -// Drivers maps a name to a provider. The name is what routes and logs use. -type Drivers map[string]Provider - -// Configuration is what the application sets up once: how to seal a -// handshake, what the cookie looks like, which providers exist, and the HTTP -// client used to talk to them. -type Configuration struct { - // Sealer encrypts the handshake for the browser to hold. Required; see - // AESSealer for one that needs nothing but a key. - Sealer Sealer - - // Cookie is how the handshake travels between the redirect and the - // callback. Name defaults to "social_handshake", Path to "/", SameSite - // to Lax, and Lifetime to ten minutes. - Cookie CookieOptions - - Drivers Drivers - - // Client sends the token exchange, refresh, discovery, key and profile - // requests. Give it a traced transport to see them; nil is - // http.DefaultClient. - Client *http.Client -} - -// Social is a set of providers bound to one configuration. Build it once at -// boot and keep it. -type Social struct { - mutex sync.RWMutex - configuration Configuration -} - -// Result is what a finished callback gives back: who signed in, and where -// they asked to land afterwards. -type Result struct { - User *User - RedirectTo string -} - -// ErrNoSealer is returned by New when the configuration cannot seal a -// handshake, which would leave every flow stateless. -var ErrNoSealer = errors.New("social: a Sealer is required") - -// New validates the configuration and applies the cookie defaults. -func New(configuration Configuration) (*Social, error) { - if configuration.Sealer == nil { - return nil, ErrNoSealer - } - - configuration.Cookie = configuration.Cookie.withDefaults() - configuration.Drivers = maps.Clone(configuration.Drivers) - if configuration.Drivers == nil { - configuration.Drivers = Drivers{} - } - if configuration.Client == nil { - configuration.Client = http.DefaultClient - } - - return &Social{configuration: configuration}, nil -} - -// Extend adds one driver, for a provider that is not part of the -// application's own configuration. -func (self *Social) Extend(name string, provider Provider) { - self.mutex.Lock() - defer self.mutex.Unlock() - - self.configuration.Drivers[name] = provider -} - -// Redirect sends the browser to the provider, remembering the state, verifier -// and nonce on the way out. The error is ErrUnknownDriver or ErrNotConfigured -// when nothing was sent, so a handler can answer those itself. -func (self *Social) Redirect(writer http.ResponseWriter, request *http.Request, name string, options ...Option) error { - url, err := self.AuthorizationURL(writer, request, name, options...) - if err != nil { - return err - } - - http.Redirect(writer, request, url, http.StatusFound) - - return nil -} - -// AuthorizationURL is Redirect without the redirecting, for a handler that -// sends the browser itself. It still writes the handshake cookie, so -// whatever follows the URL must be the browser this was called for. -func (self *Social) AuthorizationURL(writer http.ResponseWriter, request *http.Request, name string, options ...Option) (string, error) { - flow, err := self.flow(writer, request, name, options) - if err != nil { - return "", err - } - - return flow.authorizationURL() -} - -// Callback finishes the flow and returns the identity the provider vouches -// for, with the path the sign-in asked to land on. -// -// The code, state, issuer and any refusal are read from the request rather -// than passed in, because they are the provider's half of a conversation -// this package started: the caller has nothing to add to them. -func (self *Social) Callback(writer http.ResponseWriter, request *http.Request, name string, options ...Option) (*Result, error) { - flow, err := self.flow(writer, request, name, options) - if err != nil { - return nil, err - } - - return flow.callback() -} - -// UserFromToken skips the flow and asks the provider about a token the caller -// already holds: one a native app obtained itself, or one stored earlier. -func (self *Social) UserFromToken(ctx context.Context, name string, token *oauth2.Token, options ...Option) (*User, error) { - flow, err := self.flow(nil, (&http.Request{}).WithContext(ctx), name, options) - if err != nil { - return nil, err - } - - return flow.userFromToken(token) -} - -// Refresh trades a refresh token for a live one. Nothing is stored: what comes -// back may carry a new refresh token, and RFC 6749 section 6 lets the provider -// retire the old one, so the caller persists the result. -func (self *Social) Refresh(ctx context.Context, name, refreshToken string, options ...Option) (*oauth2.Token, error) { - flow, err := self.flow(nil, (&http.Request{}).WithContext(ctx), name, options) - if err != nil { - return nil, err - } - - return flow.refresh(refreshToken) -} - -func (self *Social) flow(writer http.ResponseWriter, request *http.Request, name string, options []Option) (*flow, error) { - self.mutex.RLock() - provider, ok := self.configuration.Drivers[name] - self.mutex.RUnlock() - - if !ok { - return nil, fmt.Errorf("%w: %s", ErrUnknownDriver, name) - } - - bound := &flow{ - writer: writer, - request: request, - name: name, - provider: provider, - sealer: self.configuration.Sealer, - cookie: self.configuration.Cookie, - client: self.configuration.Client, - } - for _, option := range options { - option(bound) - } - - return bound, nil -} diff --git a/user.go b/user.go index 21fa2fc..9910dcc 100644 --- a/user.go +++ b/user.go @@ -1,44 +1,31 @@ -package social +package sociable -import ( - "strings" +import "golang.org/x/oauth2" - "golang.org/x/oauth2" -) - -// User is the identity a driver resolves, in the shape every driver must -// produce. It is deliberately small: the fields every provider has, plus the -// provider's own payload for everything else. +// User is who the provider vouches for. type User struct { - ID string + // 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 profile, as it arrived. - Raw any + // Raw is the provider's own document: the profile, or the ID token's + // claims. + Raw map[string]any - // Token is what the identity was read with, filled in by the flow rather - // than by the driver. A caller that wants to keep talking to the provider, - // or to store a refresh token, has it without running the exchange twice. + // Token carries the access token, the refresh token when the provider + // issued one, and the expiry. Token *oauth2.Token - // ApprovedScopes is what the provider actually granted, which RFC 6749 - // section 5.1 allows to differ from what was asked for. A feature that - // depends on a scope should check here rather than assume. + // ApprovedScopes are the scopes the provider granted, which need not be + // the ones that were asked for. ApprovedScopes []string -} - -// HasScope reports whether the provider granted a scope. It is the question -// worth asking before using one, since asking is not the same as receiving. -func (self *User) HasScope(scope string) bool { - for _, granted := range self.ApprovedScopes { - if strings.EqualFold(granted, scope) { - return true - } - } - return false + // State is what the call site put in with WithState. + State map[string]string }