# Single Sign-On

Source: https://keyringauth.com/docs/0.x/go/sso

## Introduction

Single sign-on lets users sign in with Google, Microsoft, GitHub, or any OpenID Connect provider, as in the PHP package. A sign in goes through the same [pipeline](https://keyringauth.com/docs/0.x/go/sign-in-flow#the-verification-pipeline) as the login form, so rate limits, your policy and risk checks all apply, and a user with a second factor is still asked for it. Accounts are matched by the issuer and subject the provider vouches for, never by email address, and stored as the PHP package stores them, so a link either side made signs in on the other.

All four of the PHP package's drivers are ported: `oidc`, `google`, `microsoft` and `github`.

## Setting Up

Turn on `Factors.SingleSignOn` and list the providers in `SSO.Providers`, built with `keyring.OIDCProvider`, `GoogleProvider`, `MicrosoftProvider` or `GitHubProvider`:

```go
k := keyring.New[models.User](func(cfg *keyring.Config) {
	cfg.Factors.SingleSignOn = true
	// Linking, with the other sign-in methods.
	cfg.Features.ManageAuthenticators = true

	okta := keyring.OIDCProvider("okta", "https://example.okta.com", os.Getenv("OKTA_CLIENT_ID"), os.Getenv("OKTA_CLIENT_SECRET"))
	okta.Label = "Okta"
	okta.Freshness = keyring.RoundTrip

	cfg.SSO.Providers = []keyring.SSOProvider{
		keyring.GoogleProvider("google", os.Getenv("GOOGLE_CLIENT_ID"), os.Getenv("GOOGLE_CLIENT_SECRET")),
		okta,
	}
})
```

There's no factor to register: `Factors.SingleSignOn` with at least one provider is the PHP package's `SingleSignOn` in `Keyring::factors()`. It starts off, since it needs a provider. With it off, a user with a link, one a PHP application made say, is refused at sign in, as one with any factor Keyring can't check is. [More Identity Providers](https://keyringauth.com/docs/0.x/go/sso-providers) has settings for other providers, and drivers of your own.

A provider's name is given once: the same name twice stops `Register`.

### The Callback URL

Every provider sends the user back to the same URL, whether they're signing in, linking or confirming: `/auth/{name}/callback` after `Config.Prefix`, on `Config.LinkRoot` when you set it, or else `APP_URL`, such as `https://example.com/auth/google/callback`, whatever host a request names. Register it exactly as written, and add your local one too, such as `http://localhost:8000/auth/google/callback`.

| Method | URI | Does |
|---|---|---|
| `GET` | `/auth/{provider}/redirect` | Sends a guest to the provider, under the `Limits.LoginOptions` limit. |
| `GET` | `/auth/{provider}/callback` | Where the provider sends the user back, to sign in, link or confirm. |
| `GET` | `/confirm/sso/redirect` | Sends a signed-in user to the provider of a link on the confirm page. See [Step-Up](https://keyringauth.com/docs/0.x/go/sso#step-up). |
| `POST` | `/user/authenticators/sso` | Begins a link, with `provider`. See [Linking and Unlinking](https://keyringauth.com/docs/0.x/go/sso#linking-and-unlinking). |

The routes are only registered while `Factors.SingleSignOn` is on and a provider is configured, so an application without providers keeps any `/auth/...` routes of its own. They answer `404` for a provider that isn't configured. A request your own code started with [`StartSSO`](https://keyringauth.com/docs/0.x/go/sso#signing-up-with-a-provider) for another purpose is spent at Keyring's callback and answered with a `404`.

The callback is outside the guest and signed-in groups. It looks at the request its state names, then runs the middleware a route for that purpose would: `Guest` and the login options' limit for a sign in, `Authenticate`, `Config.ChangesMiddleware` and the forms' limit for a link, and `Authenticate` and the forms' limit for a confirm, as the PHP controller's `through()` does.

### Google

Create a "Web application" OAuth client ID in the Google Cloud console, with the callback URL as a redirect URI, and use `keyring.GoogleProvider`, as above. The scopes, `hd` claim and freshness are the PHP package's, as its [docs](https://keyringauth.com/docs/0.x/sso#google) describe: freshness is `Never` by default, and `Reauthenticate` only once your app has Google's session age claims.

### Microsoft

Register an application in the Microsoft Entra admin center, with the callback URL as a "Web" redirect URI, and a client secret:

```go
keyring.MicrosoftProvider("microsoft", os.Getenv("MICROSOFT_TENANT"), os.Getenv("MICROSOFT_CLIENT_ID"), os.Getenv("MICROSOFT_CLIENT_SECRET"))
```

The tenant is `""` for `common`, or `organizations`, `consumers`, or a tenant ID or domain, as the [PHP docs](https://keyringauth.com/docs/0.x/sso#microsoft) describe. Freshness is `Reauthenticate`, which needs the `auth_time` optional claim on the app registration. Microsoft's `email` is only verified with the `xms_edov` claim.

### GitHub

Create an OAuth app in GitHub's developer settings, with the callback URL as its "Authorization callback URL", and use `keyring.GitHubProvider`. Keyring reads who signed in from GitHub's API: the numeric ID, and the primary address when `user:email` was granted, verified as GitHub says. GitHub can't be asked for a new sign in, so its freshness is `Never`, and `Reauthenticate` is refused.

### Any OpenID Connect Provider

Any provider with a discovery document works with `keyring.OIDCProvider`, given the issuer. The issuer must match the discovery document exactly, and the issuer and every endpoint must be HTTPS, except on this machine. Keyring refuses a token endpoint or key set on a private, local or reserved address, IPv4-mapped, -compatible and -translated IPv6 included, unless it's on the issuer's own host and port, or `PrivateEndpoints` is on. The `oidc` driver defaults to `Reauthenticate`. See the [PHP docs](https://keyringauth.com/docs/0.x/sso#any-openid-connect-provider).

## Configuration

| Setting | Default | Notes |
|---|---|---|
| `SSO.Providers` | Empty | The providers, in the order the login page lists them. |
| `SSO.RequestFor` | 10 minutes | How long a user sent to a provider has to come back. Each browser keeps up to five at once. |
| `SSO.CacheFor` | One hour | How long discovery documents and signing keys are cached. A key ID the cache doesn't know reads the keys again at most once a minute. |
| `SSO.Store` | The default store | The cache store for them, by name. |
| `SSO.ResolveHosts` | DNS | Every address a host name has, for the private-address check. A test gives one of its own, as the PHP package's `HostResolver::fake()`. The token and key requests also check the address they actually connect to, through the system's DNS, so a name `ResolveHosts` calls public that really resolves to a private address is refused: set `PrivateEndpoints` for that provider instead. |

Each `SSOProvider` has the PHP package's options as fields:

| Field | |
|---|---|
| `Name` | The key, as the routes name it: letters, digits, `-` and `_`. |
| `Driver` | `oidc`, `google`, `microsoft`, `github`, or one given to [`SSO.Extend`](https://keyringauth.com/docs/0.x/go/sso#custom-drivers). The constructors set it. |
| `ClientID`, `ClientSecret` | `ClientSecret` is `""` for a public client. Every request uses PKCE either way. |
| `Issuer` | The `oidc` driver's issuer. |
| `Tenant` | The `microsoft` driver's tenant. `""` is `common`. |
| `Label` | The button's text, the PHP package's `name`. `""` is the driver's own: for `oidc`, the name as Laravel's `Str::headline()` writes it, so `my_idp` is `My Idp` and `AzureAD` is `Azure A D`. |
| `Scopes` | Replaces the driver's. Nil keeps the driver's. |
| `Parameters` | More to send the user with, in order, as `[]keyring.SSOParameter`, such as `{Name: "prompt", Value: "select_account"}`. Keyring's own can't be set. |
| `Freshness` | `keyring.Reauthenticate`, `RoundTrip` or `Never`, or `""` for the driver's own, which has to be one of the three too. |
| `TokenEndpointAuthMethod` | `client_secret_basic` (the default), `client_secret_post` or `none`. |
| `PrivateEndpoints` | Lets an OpenID Connect provider's endpoints be on a private address. Only for an issuer you run or trust. |
| `Options` | Anything else a driver of your own reads. Keyring's drivers read none of it. |

A provider is checked when a request builds it, as the PHP package's drivers are: one that can't work, an empty `ClientID` say, fails its routes with a server error and is left off the login page. Printing an `SSOProvider` with `%v` or `%#v` leaves the secret out.

### Freshness

Each provider's `Freshness` says how much a sign in counts toward a [fresh verification](https://keyringauth.com/docs/0.x/go/step-up#fresh-verification), exactly as in the PHP package:

| `Freshness` | A sign in counts as fresh | A confirm |
|---|---|---|
| `Reauthenticate` | From when the provider says the user signed in (`auth_time`). Never without one. | Asks the provider for a new sign in, with `max_age=0` and `prompt=login`. |
| `RoundTrip` | From when the user comes back. | A plain round trip. |
| `Never` | Never. | A plain round trip that counts toward the session's level, never as fresh. |

The defaults are the PHP package's: `Reauthenticate` for `oidc` and `microsoft`, `Never` for `google` and `github`. The provider's `Freshness` wins over the driver's, and `Reauthenticate` for a provider that can't reauthenticate is refused.

> [!WARNING]
> `RoundTrip` lets anyone at a browser still signed in to the provider get a fresh verification without typing anything. Opt in only where you accept that.

## Login Buttons

The `login` page gets a `providers` prop, with each provider's `name`, `label` and `url`, leaving out one that can't be built, which is reported. A plain link works best, and an Inertia visit gets a `409` with `X-Inertia-Location`. Add `?remember=1` for "remember me", which Keyring keeps for the callback.

Failures go back to the login page as in the PHP package: an account nobody linked gets the wrong-password message, a failed check gets "We couldn't sign you in", and a user who said no gets `sso-cancelled`.

## Linking and Unlinking

Users link accounts from your settings page, with `Features.ManageAuthenticators` on. A link is an enrollment like any other sign-in method's: it needs a fresh verification, and the password when the account has one and no established second factor. `POST /user/authenticators/sso` `{ "provider", "password" }` answers `enrollment-started` with `{ "enrollment": { "provider", "url" } }`, and the provider's callback finishes it, answering `authenticator-added`, or `authenticator-updated` for an account the user had already linked, or a `422` on `provider` for one someone else has. The browser package's `linkProvider()` does both steps. What the [PHP docs](https://keyringauth.com/docs/0.x/sso#linking-and-unlinking) say about the answers, unlinking and the freeze holds here.

`GET /user/authenticators` lists the user's links with `provider` and `email`, and `k.SignInMethods(ctx, user)` offers `sso` among what can be added once a provider is configured. Unlink with `DELETE /user/authenticators/{authenticator}`.

Linking refuses an account any row has already, confirmed or not, before inserting. The PHP package inserts and turns the unique violation away, so only the order differs.

## How It Fits With the Rest

### Second Factors and Policies

As in the PHP package: a sign in with a provider is one knowledge proof, like a password. A link is never a second factor, never the default, never offered on the challenge page, and never comes with recovery codes. A provider's `amr` and `acr` are kept on the [`Verification`](https://keyringauth.com/docs/0.x/go/step-up#verification-properties) as `ProviderAMR` and `ProviderACR`, and never count toward the level.

### Hearing About Accepted Identities

`keyring.ProviderIdentityAccepted[U]` fires each time a provider's account is accepted as one of the user's links, for a sign in, a confirm or a link, as in the PHP package. It carries the `User`, the `AuthenticatorID`, the `Purpose` and the `Identity`, with the request's state, nonce and code verifier, and the ID token's `nonce`, `at_hash` and `c_hash`, already left out, so a listener can keep it.

It fires as the provider's proof is accepted, before the rest of the sign in: a second factor may still be asked for. `Authenticated` or `Confirmed` says the whole attempt is done.

### Step-Up

A link answers the [confirm page](https://keyringauth.com/docs/0.x/go/step-up#the-confirm-flow) while its provider is configured, with `challenge` `{ "provider", "label", "url" }`: `GET /confirm/sso/redirect?authenticator=` sends the user back to the provider, with `max_age=0` and `prompt=login` for one that reauthenticates (only `max_age` at Google, only `prompt=login` at Microsoft), and the callback has to bring the link's account with an `auth_time` from no more than a minute before the user was sent there. The rest is the [PHP package's](https://keyringauth.com/docs/0.x/sso#step-up).

### Users Whose Only Way In Is Never Fresh

As in the [PHP docs](https://keyringauth.com/docs/0.x/sso#users-whose-only-way-in-is-never-fresh): a user whose only sign-in method is a link at a `Never` provider can sign in but can't pass a fresh verification, so they get `enroll-first` at once. The way out is a password reset. Have a user who [signs up with such a provider](https://keyringauth.com/docs/0.x/go/sso#signing-up-with-a-provider) set a password or add a passkey while the sign up is still fresh.

### Password Resets and Email Changes

A completed password reset unlinks every identity provider on the account, with `AuthenticatorRemoved` for each, as in the PHP package, whether or not `Factors.SingleSignOn` is on. An undone email change removes the links added since the change.

### Failures and the Security Log

Failures are logged and dispatched as in the PHP package (`factor_failed`, `second_factor_failed`, `enrollment_refused`), apart from Laravel's `Failed` event, which Laravel Go doesn't have. A refused callback dispatches `FactorFailed` with no user. A failure is a `*keyring.SSOFailed`, found with `errors.As`, whose `Reason` is an `SSOFailure`. Its message never carries a code, token or secret.

## No Sign Up, and No Linking by Email

As in the PHP package, Keyring never creates an account for someone who signs in with a provider, and never links an account to a user because they share an address. To let people sign up with a provider, build the routes yourself, as below.

### Signing Up With a Provider

`k.StartSSO` and `k.CompleteSSO` send users to a provider and take them back at routes of your own, as `Keyring::sso()->start()` and `complete()` do. Give the request a purpose other than `login`, `link` or `confirm`, give it the URL the provider sends users back to, built from `APP_URL` as Keyring's own callback is and never from the request's host, and check the purpose when the identity comes back:

```go
// GET /sign-up/google, for guests.
func signUpWithGoogle(r *web.Request) *web.Response {
	k := keyring.From[models.User](r)

	to, err := k.StartSSO(r, "google", "sign-up", appURL+"/sign-up/google/callback", keyring.SSOStart{})
	if err != nil {
		return web.Fail(err)
	}

	return web.Redirect(to)
}

// GET /sign-up/google/callback, for guests.
func signedUpWithGoogle(r *web.Request) *web.Response {
	identity, err := keyring.From[models.User](r).CompleteSSO(r, "google")
	if failed := (*keyring.SSOFailed)(nil); errors.As(err, &failed) {
		return web.Redirect("/register")
	}
	if err != nil {
		return web.Fail(err)
	}
	if identity.Request.Purpose != "sign-up" {
		return web.Abort(http.StatusNotFound)
	}

	// Sign in someone who signed up already, or create the user, link the
	// account and sign them in: see below.
	return signUpOrSignIn(r, identity)
}
```

`appURL` is your `APP_URL`. The callback's request is spent whether or not the rest succeeds. `SSOStart` takes `Data`, which comes back on `identity.Request.Data` and stays on the server, such as "remember me", `MaxAge` and `LoginHint`.

`k.LinkedSSO(ctx, identity)` is the ID of the sign-in method the provider's account is linked as, whoever it belongs to, or `""`, as `SingleSignOn::linked()`. `k.AttemptSSO(r, identity, remember)` signs in whoever linked it, through Keyring's pipeline, as `Keyring::attempt()` with the identity on the request. `k.LinkNewAccount(ctx, &user, identity)` links the provider's account to a user you just created with it, as the PHP example creates the row: stored under the issuer and subject, so Keyring's own button signs them in, with no `AuthenticatorAdded`, and its ID returned. It refuses a user who already has any sign-in method, a password included, and an account someone already linked. `k.SignInAs(r, &user, []keyring.Proved{keyring.ProvedAuthenticator(link)}, remember)` signs in the new account with what creating it proved, as `SignIn::as()`. The rest of the PHP example translates like this:

```go
func signUpOrSignIn(r *web.Request, identity *keyring.Identity) *web.Response {
	k := keyring.From[models.User](r)

	// Someone who already signed up: an ordinary sign in. A refusal goes to
	// the login page, as Keyring's own callback sends it: back would be
	// Google.
	linked, err := k.LinkedSSO(r, identity)
	if err != nil {
		return web.Fail(err)
	}
	if linked != "" {
		res, err := k.AttemptSSO(r, identity, false)

		return toLogin(r, res, err)
	}

	// Google only vouches for who owns a Gmail address, or one in a Google
	// Workspace domain (the "hd" claim). Any other address was verified
	// once, when the Google account was made, and may have changed hands
	// since.
	hd, _ := identity.Claims["hd"].(string)
	email := ""
	if identity.Email != nil {
		email = strings.ToLower(strings.TrimSpace(*identity.Email))
	}
	if !identity.EmailVerified || email == "" || (!strings.HasSuffix(email, "@gmail.com") && hd == "") {
		return web.Redirect("/register").WithError("email", "Sign up with your email address, then link Google from your settings.")
	}

	taken, err := addressTaken(r, email)
	if err != nil {
		return web.Fail(err)
	}
	if taken {
		return web.Redirect("/register").WithError("email", "Sign up with your email address, then link Google from your settings.")
	}

	// Your own: a user with this address, verified, and no password.
	user, err := createUserWithoutPassword(r, identity, email)
	if err != nil {
		return web.Fail(err)
	}
	link, err := k.LinkNewAccount(r, user, identity)
	if err != nil {
		return web.Fail(err)
	}

	// The account didn't exist until this request, so this sign in counts
	// as fresh: long enough to choose a password or add a passkey.
	if _, err := k.SignInAs(r, user, []keyring.Proved{keyring.ProvedAuthenticator(link)}, false); err != nil {
		return toLogin(r, nil, err)
	}

	return web.Redirect("/settings/security")
}

// toLogin is a sign in's answer, or the refusal Keyring gave, as the PHP
// example catches its ValidationException: to the login page with the
// errors, or the 422 for JSON.
func toLogin(r *web.Request, res *web.Response, err error) *web.Response {
	if invalid, ok := errors.AsType[*web.InputError](err); ok && !r.ExpectsJSON() {
		return web.Redirect("/login").WithErrors(invalid)
	}
	if err != nil {
		return web.Fail(err)
	}

	return res
}
```

`addressTaken` and `createUserWithoutPassword` are yours. Put both routes behind `keyring.Guest` and `keyring.BlockSession`, as Keyring's own are.

The [PHP example's notes](https://keyringauth.com/docs/0.x/sso#signing-up-with-a-provider) hold: Google only vouches for a Gmail address or one in a Workspace domain (the `hd` claim, in `identity.Claims`), check the address as registration does, counting `k.AddressReserved(ctx, address, nil)` too, and put a rate limit on the callback, as each call may create an account.

## Frontends Laravel Doesn't Serve

A [headless frontend](https://keyringauth.com/docs/0.x/go/headless) can offer providers as with the PHP package: a JSON request to the redirect route answers `{ "url" }`, and the browser package's `signInWithProvider()` does both steps. Start the callback URL at the frontend with `Config.LinkRoot`, and have the frontend pass the callback's path and query to Keyring as JSON. `LinkRoot` is one setting for every provider and every emailed link, where the PHP package can set it per provider. The answers are the PHP package's, as its [docs](https://keyringauth.com/docs/0.x/sso#frontends-laravel-doesnt-serve) list.

## Security Notes

The PHP package's [notes](https://keyringauth.com/docs/0.x/sso#security-notes) hold: `PrivateEndpoints` is only for an issuer you run or trust, keep `SESSION_SAME_SITE` at `lax`, `Reauthenticate` behind a broker only means something when users type their credentials at the broker, Google and Microsoft sign with RS256, and Keyring's session carries on after the provider's ends.

Keyring only fetches HTTPS endpoints, or plain HTTP to an issuer on this machine, never follows a redirect, and gives up after 5 seconds connecting and 10 in all. It only takes a `2xx` answer, reads at most 1 MiB of one, and sends a provider only what it writes itself: the headers, tokens, query, retries and transport your application gives its HTTP client in `laravel.Options.HTTP` stay behind. Its requests still go through that client, so `httpclienttest` fakes answer them, and its `BeforeSending` and `AfterResponse` hooks and its log see them. Host names are resolved through the system's resolver. A token endpoint or key set let through only because its name resolved to a public address is connected to only at a public address, so a name that resolves somewhere private or local by the time Keyring connects (DNS rebinding) is refused, where the PHP package resolves it again and connects. One on the issuer's own host and port, one allowed by `PrivateEndpoints`, and any endpoint of an issuer on this machine connect wherever their names resolve, and a request through a proxy (`HTTPS_PROXY`) leaves the name to the proxy.

## Custom Drivers

A driver of your own, as `Keyring::sso()->extend()` registers one, implements `keyring.IdentityProvider`:

- `Name()` returns the name it's configured under, and `Label()` the button's text.
- `SupportsReauthentication()` says whether it can be asked for a new sign in, and `Freshness()` how much a sign in through it counts by default. A plain OAuth 2.0 driver answers `false` and `keyring.Never`.
- `AuthorizationURL(ctx, request)` builds the URL from the `AuthorizationRequest` Keyring made and keeps in the session: its `State`, `CodeChallenge()` and `RedirectURI`.
- `Identify(ctx, request, query)` turns the callback's query string, a `keyring.CallbackQuery`, into an `*Identity`, or fails with a `*keyring.SSOFailed` from `keyring.NewSSOFailed`.

Keyring holds the identity to the provider and request it knows, whatever the driver says, and refuses one with no issuer or subject. Register it with `SSO.Extend` under a driver name, or under one of Keyring's (`oidc`, `google`, `microsoft`, `github`) to replace that, and configure providers with that `Driver`. Whatever else it reads goes in the provider's `Options`:

```go
cfg.SSO.Extend("discord", func(provider keyring.SSOProvider) (keyring.IdentityProvider, error) {
	return NewDiscord(provider)
})
cfg.SSO.Providers = append(cfg.SSO.Providers, keyring.SSOProvider{
	Name:         "discord",
	Driver:       "discord",
	ClientID:     os.Getenv("DISCORD_CLIENT_ID"),
	ClientSecret: os.Getenv("DISCORD_CLIENT_SECRET"),
})
```

[More Identity Providers](https://keyringauth.com/docs/0.x/go/sso-providers#discord) has the Discord driver, and a [checklist](https://keyringauth.com/docs/0.x/go/sso-providers#writing-your-own).

### Building on Keyring's Drivers

Keyring for Go doesn't export the pieces its own drivers are built on, the PHP package's `OAuth2Provider` and `OidcProvider`, so a driver of your own does the authorization code flow itself: the query it sends the user with, checking the callback, and exchanging the code with the request's `CodeVerifier`. The [Discord driver](https://keyringauth.com/docs/0.x/go/sso-providers#discord) shows each step. A driver can't extend Google's or Microsoft's either: one that changes them, such as the PHP docs' Workspace driver, isn't possible without writing the OpenID Connect side as well.

Two leaf packages do what Keyring's drivers do, for drivers that need it:

- `keyringauth.com/go/jose` checks an ID token as Keyring does (`jose.Parse`, then the token's `SignedBy` against a provider's key).
- `keyringauth.com/go/hosts` makes Keyring's address checks: `hosts.IsSecure`, `IsLocal`, `SameHost`, `IsInward` and `IsPublic`, for requests your driver makes itself. `IsInward` looks a name up once, so give your client's `net.Dialer` a `Control` that refuses an address `IsPublic` doesn't take, as Keyring's own requests do, or a name that resolves elsewhere when it's connected to gets through.

See [Differences From PHP](https://keyringauth.com/docs/0.x/go/differences#single-sign-on).

## Testing

`keyringtest.FakeIdentityProvider` stands in for a provider, as the PHP package's `FakeIdentityProvider`. It answers Keyring's requests through Laravel Go's HTTP client fake (`httpclienttest`) as the real one would: discovery, signing keys, the token endpoint and GitHub's API. Its ID tokens are really signed, with keys it makes, so every check Keyring runs on them runs in your tests.

Its `Register(name)` goes in Keyring's settings, as the PHP package's `register()`: it adds the provider under that name, turns `Factors.SingleSignOn` on, and, unless you set `SSO.ResolveHosts` yourself, has no host resolve to anything, as the PHP package's `register()` calls `HostResolver::fake()` with no hosts: Keyring never asks DNS, and a host with a dot in its name that has no address counts as outside your network. `Serve(t, client)` answers the application's requests from then on:

```go
func TestSignsInWithGoogle(t *testing.T) {
    google := keyringtest.GoogleIdentityProvider("")
    options := bootstrap.Options()
    // Your Keyring, with the provider added to its settings.
    options.Packages = []laravel.Package{keyring.New[models.User](bootstrap.Keyring, google.Register("google"))}
    client := laraveltest.New(t, options, laraveltest.RefreshDatabase)
    google.Serve(t, client)
    kt := keyringtest.New[models.User](t, client)
    user := client.Create(factories.User)
    kt.Add(&user, keyringtest.SSO("google", "42", "https://accounts.google.com", ""))

    b := client.NewBrowser().WithHeader("Accept", "application/json")
    authorize := b.GetJSON("/auth/google/redirect").JSON[map[string]any]()["url"].(string)
    b.Get(google.SignIn(map[string]any{"sub": "42"}).Approve(authorize))

    b.GetJSON("/user/sessions").AssertOK()
}
```

`NewFakeIdentityProvider(issuer, algorithm)` is any OpenID Connect provider (`https://idp.test` and ES256 when they're empty), `GoogleIdentityProvider`, `MicrosoftIdentityProvider(tenant, tenantID)` and `GitHubIdentityProvider` the drivers'. `Serve` makes a new `httpclienttest` fake, as a client takes one: a test that fakes the HTTP client itself, or has two providers, passes its fake to `Answer` instead.

`Approve(url)` checks the authorization URL the way the provider would and gives the callback URL, and `Deny(url, error)` the callback for a user who said no. `SignIn`, `WithEmails`, `SignedInAt`, `IgnoringReauthentication` and `WithAuthTimeClaim` say who signs in and when, and `WithClaims`, `WithHeader`, `WithDiscovery`, `Expired`, `Unsigned`, `SignedWithPublicKeyAsSecret`, `SignedWithUnpublishedKey`, `RotateKeys`, `WithKeyIssuer`, `SendsIssuer`, `AuthMethods`, `FailExchange` and `Down` what Keyring refuses, as the PHP package's methods of those names. `DiscoveryFetches` and `KeyFetches` count Keyring's reads.

`SSO.ResolveHosts` stands in for DNS, so a test never asks it.

## Migrating From the Socialite Recipe

The Socialite recipe was for PHP, so there's no Go version of it to migrate from. A PHP application that migrated already has links Keyring for Go reads, since the rows are the same.

If your Go application stored GitHub IDs of its own, turn on `Factors.SingleSignOn` with a `github` provider, and move each ID into a `keyring_authenticators` row as the [PHP migration](https://keyringauth.com/docs/0.x/sso#migrating-from-the-socialite-recipe) does: factor `sso`, `credential_id` of `sso:` and the lowercase hex SHA-256 of `https://github.com`, a NUL byte and the ID, and `meta` `{ "provider", "issuer", "subject", "email" }`.

## Reference

### The Factor

The `sso` factor is the PHP package's `SingleSignOn`, as its [reference](https://keyringauth.com/docs/0.x/sso#the-factor) describes. It has no type of its own: `Factors.SingleSignOn` turns it on, and `SSO.Providers` is what it offers. The purposes are the strings `login`, `link` and `confirm`.

### Failure Reasons

`keyring.SSOFailure` has the PHP package's reasons, as its [list](https://keyringauth.com/docs/0.x/sso#failure-reasons) describes: `SSODenied`, `SSOInvalidState`, `SSOProviderError`, `SSOInvalidResponse`, `SSOExchangeFailed`, `SSOInvalidToken`, `SSOUnavailable` and `SSOStaleAuthentication`. `keyring.NewSSOFailed(reason, detail)` builds one, and `Expected()` says whether it's one users cause, such as `SSODenied` and `SSOInvalidState`, which aren't reported.

## How It Works

The flow is the PHP package's, as its [How It Works](https://keyringauth.com/docs/0.x/sso#how-it-works) describes. Every request carries PKCE (S256), a 43-character `state` kept encrypted in the session (five at most, the oldest making way) and claimed in the cache so it works once, even from a copy of the session, and for OpenID Connect a `nonce`, `login_hint` where there's one, and the `claims` parameter asking for `auth_time` where discovery says it's taken. The ID token has to be a compact JWS of at most 64 KiB with no `crit`, signed with RS256, PS256, ES256 or EdDSA by one of the provider's published keys that allows it, from the issuer, for this client, current within a minute, with this sign in's nonce and a subject of at most 255 bytes. ID tokens are checked by Keyring's own `jose` package, which takes and refuses what the PHP package does.

Accounts are matched on issuer and subject, stored as the PHP package's `credential_id` (`sso:` and the SHA-256 of issuer, NUL, subject) with `meta` `{ "provider", "issuer", "subject", "email" }`, so a link either side made signs in on the other.

A few things differ:

- Go's `crypto/rsa` refuses an RSA public exponent over 2³¹−1, which OpenSSL takes. Every provider uses 65537.
- Discovery documents are cached as their checked body and read again from the cache each time they're needed, where the PHP package keeps one per provider object for the request.
- A callback's `amr` given as an object is read in key order.

See [Single Sign-On](https://keyringauth.com/docs/0.x/go/differences#single-sign-on) for the rest.
