package governance import ( "context" "crypto/rand" "encoding/base64" "encoding/json/jsontext" "errors" "fmt" "net/http" "strings" "time" "unicode/utf8" "github.com/danielgtaylor/huma/v2" "github.com/samcharles93/archie-core/internal/platform/httpapi" ) // Cookie names beside httpapi.SessionCookie. The sign-in flow's cookies are // scoped to the paths that read them. const ( passkeyLoginCookie = "archie_passkey_login" passkeyRegistrationCookie = "archie_passkey_registration" loginStateCookie = "archie_login_state" loginVerifierCookie = "archie_login_verifier" passkeyCookiePath = "/api/" loginCookiePath = "/oauth2" passkeyCookieAge = 300 loginCookieAge = 600 maxTokenNameLength = 40 // personalTokenBindTimeout is under the dashboard's own request timeout. personalTokenBindTimeout = 10 * time.Second ) // client is the host a request reached, which decides whether a cookie must // be Secure. type client struct{ host string } // Resolve reads the request's host. Huma calls it for every input that // carries a client. func (c *client) Resolve(ctx huma.Context) []error { c.host = ctx.Host() return nil } // cookie returns an HttpOnly, SameSite=Lax cookie, Secure unless the browser // reached this host over loopback. A negative maxAge deletes it. func (c *client) cookie(name, value, path string, maxAge int) http.Cookie { return http.Cookie{ //nolint:gosec // G124: a fixed Secure would stop a browser on localhost signing in. Name: name, Value: value, Path: path, MaxAge: maxAge, HttpOnly: true, Secure: !loopback(c.host), SameSite: http.SameSiteLaxMode, } } func (c *client) session(s AccountSession) http.Cookie { return c.cookie(httpapi.SessionCookie, s.Token, "/", int(time.Until(s.Expires).Seconds())) } func (c *client) clear(name, path string) http.Cookie { return c.cookie(name, "", path, -1) } type sessionInput struct { Client client Session string `cookie:"archie_session"` } type cookieReply struct { SetCookie []http.Cookie `header:"Set-Cookie"` CacheControl string `header:"Cache-Control"` } type userBody struct { User Identity `json:"user"` } type userReply struct { SetCookie []http.Cookie `header:"Set-Cookie"` CacheControl string `header:"Cache-Control"` Body userBody } // RegisterAccounts adds sign-in and the signed-in person's account: password // accounts, passkeys, recovery, OIDC, personal API tokens, the instance's // authentication settings and what the dashboard can show. func (m *Module) RegisterAccounts(api huma.API) { tags := []string{"Accounts"} op := func(id, method, path, summary string, status int) huma.Operation { return huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags, DefaultStatus: status} } httpapi.Register(api, httpapi.Public(), op("get-auth-status", http.MethodGet, "/api/auth/status", "Report setup and who is signed in", 0), m.authStatus) httpapi.Register(api, httpapi.Public(), op("set-up-account", http.MethodPost, "/api/auth/setup", "Create the instance owner and sign in", 0), m.setUpAccount) httpapi.Register(api, httpapi.Public(), op("sign-in", http.MethodPost, "/api/auth/login", "Sign in with email and password", 0), m.signIn) httpapi.Register(api, httpapi.Public(), op("sign-out", http.MethodPost, "/api/auth/logout", "Sign out", http.StatusNoContent), m.signOut) httpapi.Register(api, httpapi.Public(), op("recover-account", http.MethodPost, "/api/auth/recover", "Reset a password with a recovery code", http.StatusNoContent), m.recoverAccount) httpapi.Register(api, httpapi.Public(), op("begin-passkey-sign-in", http.MethodPost, "/api/auth/passkey/begin", "Start signing in with a passkey", 0), m.beginPasskeySignIn) httpapi.Register(api, httpapi.Public(), op("finish-passkey-sign-in", http.MethodPost, "/api/auth/passkey/finish", "Finish signing in with a passkey", 0), m.finishPasskeySignIn) httpapi.Register(api, httpapi.Public(), op("begin-oidc-sign-in", http.MethodGet, "/oauth2/login", "Send the browser to the identity provider", http.StatusSeeOther), m.beginOIDC) httpapi.Register(api, httpapi.Public(), op("finish-oidc-sign-in", http.MethodGet, oidcCallbackPath, "Complete the identity provider's sign-in", http.StatusSeeOther), m.finishOIDC) httpapi.Register(api, httpapi.Authorized(ActionUpdate, KindAccount), op("change-password", http.MethodPost, "/api/account/password", "Change your password", http.StatusNoContent), m.changePassword) httpapi.Register(api, httpapi.Authorized(ActionCreate, KindAccount), op("create-recovery-code", http.MethodPost, "/api/account/recovery", "Create a recovery code", 0), m.createRecoveryCode) httpapi.Register(api, httpapi.Authorized(ActionRead, KindAccount), op("list-passkeys", http.MethodGet, "/api/account/passkeys", "List your passkeys", 0), m.listPasskeys) httpapi.Register(api, httpapi.Authorized(ActionCreate, KindAccount), op("begin-passkey-registration", http.MethodPost, "/api/account/passkeys/begin", "Start adding a passkey", 0), m.beginPasskeyRegistration) httpapi.Register(api, httpapi.Authorized(ActionCreate, KindAccount), op("finish-passkey-registration", http.MethodPost, "/api/account/passkeys/finish", "Finish adding a passkey", 0), m.finishPasskeyRegistration) httpapi.Register(api, httpapi.Authorized(ActionDelete, KindAccount), op("delete-passkey", http.MethodDelete, "/api/account/passkeys/{id}", "Remove a passkey", http.StatusNoContent), m.deletePasskey) httpapi.Register(api, httpapi.Authorized(ActionRead, KindAccount), op("list-personal-tokens", http.MethodGet, "/api/tokens", "List your personal API tokens", 0), m.listTokens) httpapi.Register(api, httpapi.Authorized(ActionCreate, KindAccount), op("create-personal-token", http.MethodPost, "/api/tokens", "Create a personal API token", http.StatusCreated), m.createToken) httpapi.Register(api, httpapi.Authorized(ActionDelete, KindAccount), op("revoke-personal-token", http.MethodDelete, "/api/tokens/{id}", "Revoke a personal API token", http.StatusNoContent), m.revokeToken) m.registerLinks(api, op) httpapi.Register(api, httpapi.Authorized(ActionRead, KindAccount), op("get-capabilities", http.MethodGet, "/api/capabilities", "Report which dashboard sections this binary serves", 0), m.capabilities) httpapi.Register(api, httpapi.AdminAuthorized(ActionManageIdentities, KindIdentity), op("create-account", http.MethodPost, "/api/accounts", "Create an account", http.StatusCreated), m.createAccount) httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), op("get-authentication", http.MethodGet, "/api/authentication", "Get the authentication settings", 0), m.getAuthentication) httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), op("put-authentication", http.MethodPut, "/api/authentication", "Change the authentication settings", http.StatusNoContent), m.putAuthentication) } // accountError turns an account failure into the status a person can act on. func (m *Module) accountError(ctx context.Context, err error) error { switch { case refused(err): return huma.Error401Unauthorized(httpapi.ErrUnauthenticated.Error()) case errors.Is(err, ErrSetupComplete): return huma.Error409Conflict(ErrSetupComplete.Error()) case errors.Is(err, ErrIdentityConflict): return huma.Error409Conflict("An account already uses that email.") case errors.Is(err, ErrInvalidIdentity): return huma.Error400BadRequest("Enter a name, valid email, organisation name for setup, and an uncommon password of at least 15 characters (at most 1024 bytes).") case errors.Is(err, ErrProviderUnavailable): return huma.Error503ServiceUnavailable("The sign-in provider is unavailable. Try again shortly.") default: m.log.ErrorContext(ctx, "account operation failed", "err", err) return huma.Error503ServiceUnavailable("Account service unavailable.") } } // person refuses a caller that is not a signed-in person: account security // belongs to people, not to tokens acting for the system. func person(ctx context.Context) error { if p, ok := PrincipalFromContext(ctx); ok && p.Kind == KindUser { return nil } return huma.Error401Unauthorized("sign-in required") } // requireFresh refuses an authenticator change unless the caller signed in // within the last few minutes. func (m *Module) requireFresh(ctx context.Context, session string) error { if session == "" || m.RequireFreshAccountSession(ctx, session) != nil { return huma.Error403Forbidden("Sign in again before changing account security.") } return nil } type authStatusBody struct { SetupRequired bool `json:"setup_required"` User *Identity `json:"user"` OIDC bool `json:"oidc"` PublicURL string `json:"public_url"` Instance string `json:"instance"` } type authStatusReply struct { CacheControl string `header:"Cache-Control"` Body authStatusBody } func (m *Module) authStatus(ctx context.Context, in *sessionInput) (*authStatusReply, error) { required, err := m.AccountSetupRequired(ctx) if err != nil { return nil, m.accountError(ctx, err) } out := authStatusBody{SetupRequired: required, Instance: "archie"} if in.Session != "" { value, err := m.ResolveAccountSession(ctx, in.Session) switch { case err == nil && value.Kind == KindUser && value.CanAct(): out.User = &value case err != nil && !refused(err): return nil, m.accountError(ctx, err) } } settings, err := m.AuthenticationSettings(ctx) if err != nil { return nil, m.accountError(ctx, err) } out.PublicURL = settings.PublicURL out.OIDC = settings.PublicURL != "" && settings.OIDCIssuer != "" return &authStatusReply{CacheControl: "no-store", Body: out}, nil } type registration struct { Email string `json:"email"` DisplayName string `json:"display_name"` Password string `json:"password"` Role string `json:"role,omitempty"` } func (r registration) account() AccountRegistration { return AccountRegistration{Email: r.Email, DisplayName: r.DisplayName, Password: r.Password, Role: r.Role} } type setUpInput struct { Client client Body struct { PublicURL string `json:"public_url" doc:"The public origin of this Archie instance"` Email string `json:"email"` DisplayName string `json:"display_name"` Password string `json:"password"` } } func (m *Module) setUpAccount(ctx context.Context, in *setUpInput) (*userReply, error) { r := in.Body if _, err := m.RegisterAccount(ctx, AccountRegistration{PublicURL: r.PublicURL, Email: r.Email, DisplayName: r.DisplayName, Password: r.Password}, true); err != nil { return nil, m.accountError(ctx, err) } return m.openSession(ctx, &in.Client, in.Body.Email, in.Body.Password) } type signInInput struct { Client client Body struct { Email string `json:"email"` Password string `json:"password"` } } func (m *Module) signIn(ctx context.Context, in *signInInput) (*userReply, error) { return m.openSession(ctx, &in.Client, in.Body.Email, in.Body.Password) } func (m *Module) openSession(ctx context.Context, c *client, email, password string) (*userReply, error) { value, err := m.SignInAccount(ctx, email, password) if err != nil { m.log.InfoContext(ctx, "account sign-in refused") return nil, m.accountError(ctx, err) } m.log.InfoContext(ctx, "account signed in", "identity", value.Identity.ID) return &userReply{SetCookie: []http.Cookie{c.session(value)}, CacheControl: "no-store", Body: userBody{User: value.Identity}}, nil } func (m *Module) signOut(ctx context.Context, in *sessionInput) (*cookieReply, error) { if in.Session != "" { if err := m.SignOutAccount(ctx, in.Session); err != nil { return nil, m.accountError(ctx, err) } } return &cookieReply{SetCookie: []http.Cookie{in.Client.clear(httpapi.SessionCookie, "/")}, CacheControl: "no-store"}, nil } type recoverInput struct { Body struct { Email string `json:"email"` Code string `json:"code"` Password string `json:"password"` } } func (m *Module) recoverAccount(ctx context.Context, in *recoverInput) (*struct{}, error) { if err := m.RecoverAccount(ctx, in.Body.Email, in.Body.Code, in.Body.Password); err != nil { return nil, m.accountError(ctx, err) } return nil, nil } type changePasswordInput struct { Client client Body struct { Current string `json:"current_password"` New string `json:"new_password"` } } // changePassword revokes every session, so the browser's cookie goes too. func (m *Module) changePassword(ctx context.Context, in *changePasswordInput) (*cookieReply, error) { if err := person(ctx); err != nil { return nil, err } if err := m.ChangeAccountPassword(ctx, in.Body.Current, in.Body.New); err != nil { return nil, m.accountError(ctx, err) } return &cookieReply{SetCookie: []http.Cookie{in.Client.clear(httpapi.SessionCookie, "/")}, CacheControl: "no-store"}, nil } type recoveryCodeReply struct { CacheControl string `header:"Cache-Control"` Body struct { Code string `json:"code"` } } func (m *Module) createRecoveryCode(ctx context.Context, in *sessionInput) (*recoveryCodeReply, error) { if err := person(ctx); err != nil { return nil, err } if err := m.requireFresh(ctx, in.Session); err != nil { return nil, err } code, err := m.CreateAccountRecovery(ctx) if err != nil { return nil, m.accountError(ctx, err) } out := &recoveryCodeReply{CacheControl: "no-store"} out.Body.Code = code return out, nil } type createAccountInput struct { Session string `cookie:"archie_session"` Body registration } func (m *Module) createAccount(ctx context.Context, in *createAccountInput) (*httpapi.Reply[userBody], error) { if err := m.requireFresh(ctx, in.Session); err != nil { return nil, err } value, err := m.RegisterAccount(ctx, in.Body.account(), false) if err != nil { return nil, m.accountError(ctx, err) } return httpapi.OK(userBody{User: value}), nil } func (m *Module) getAuthentication(ctx context.Context, _ *struct{}) (*httpapi.Reply[AuthenticationSettings], error) { value, err := m.AuthenticationSettings(ctx) if err != nil { return nil, m.accountError(ctx, err) } return httpapi.OK(value), nil } type authenticationInput struct { Session string `cookie:"archie_session"` Body struct { PublicURL string `json:"public_url"` OIDCIssuer string `json:"oidc_issuer,omitempty"` OIDCAudience string `json:"oidc_audience,omitempty"` OIDCClientID string `json:"oidc_client_id,omitempty"` TrustedProxies []string `json:"trusted_proxies,omitempty"` } } func (m *Module) putAuthentication(ctx context.Context, in *authenticationInput) (*struct{}, error) { if err := m.requireFresh(ctx, in.Session); err != nil { return nil, err } err := m.SaveAuthenticationSettings(ctx, AuthenticationSettings(in.Body)) if errors.Is(err, ErrInvalidIdentity) { return nil, huma.Error400BadRequest("Use a valid instance origin, trusted proxies that are addresses or CIDR ranges, and complete OIDC settings. Remove enrolled passkeys before changing the instance URL.") } if err != nil { return nil, m.accountError(ctx, err) } return nil, nil } type passkeyOptionsReply struct { SetCookie []http.Cookie `header:"Set-Cookie"` CacheControl string `header:"Cache-Control"` Body jsontext.Value } func (m *Module) beginPasskeySignIn(ctx context.Context, in *sessionInput) (*passkeyOptionsReply, error) { return m.beginPasskey(ctx, &in.Client, false) } func (m *Module) beginPasskeyRegistration(ctx context.Context, in *sessionInput) (*passkeyOptionsReply, error) { if err := person(ctx); err != nil { return nil, err } if err := m.requireFresh(ctx, in.Session); err != nil { return nil, err } return m.beginPasskey(ctx, &in.Client, true) } func passkeyCookie(registration bool) string { if registration { return passkeyRegistrationCookie } return passkeyLoginCookie } func (m *Module) beginPasskey(ctx context.Context, c *client, registration bool) (*passkeyOptionsReply, error) { value, err := m.BeginPasskey(ctx, registration) if err != nil { return nil, m.accountError(ctx, err) } return &passkeyOptionsReply{ SetCookie: []http.Cookie{c.cookie(passkeyCookie(registration), value.Token, passkeyCookiePath, passkeyCookieAge)}, CacheControl: "no-store", Body: jsontext.Value(value.Options), }, nil } type passkeyFinishBody struct { Credential jsontext.Value `json:"credential"` Name string `json:"name,omitempty"` } type passkeySignInInput struct { Client client Ceremony string `cookie:"archie_passkey_login"` Body passkeyFinishBody } func (m *Module) finishPasskeySignIn(ctx context.Context, in *passkeySignInInput) (*userReply, error) { value, err := m.finishPasskey(ctx, in.Ceremony, in.Body, false) if err != nil { return nil, err } return &userReply{ SetCookie: []http.Cookie{in.Client.clear(passkeyLoginCookie, passkeyCookiePath), in.Client.session(value)}, CacheControl: "no-store", Body: userBody{User: value.Identity}, }, nil } type passkeyRegistrationInput struct { Client client Session string `cookie:"archie_session"` Ceremony string `cookie:"archie_passkey_registration"` Body passkeyFinishBody } func (m *Module) finishPasskeyRegistration(ctx context.Context, in *passkeyRegistrationInput) (*userReply, error) { if err := person(ctx); err != nil { return nil, err } if err := m.requireFresh(ctx, in.Session); err != nil { return nil, err } value, err := m.finishPasskey(ctx, in.Ceremony, in.Body, true) if err != nil { return nil, err } return &userReply{ SetCookie: []http.Cookie{in.Client.clear(passkeyRegistrationCookie, passkeyCookiePath)}, CacheControl: "no-store", Body: userBody{User: value.Identity}, }, nil } func (m *Module) finishPasskey(ctx context.Context, ceremony string, body passkeyFinishBody, registration bool) (AccountSession, error) { if ceremony == "" { return AccountSession{}, huma.Error401Unauthorized("passkey request expired") } value, err := m.FinishPasskey(ctx, ceremony, body.Credential, registration, body.Name) if err != nil { return AccountSession{}, m.accountError(ctx, err) } return value, nil } type passkeysBody struct { Passkeys []Passkey `json:"passkeys"` } func (m *Module) listPasskeys(ctx context.Context, _ *struct{}) (*httpapi.Reply[passkeysBody], error) { if err := person(ctx); err != nil { return nil, err } values, err := m.ListPasskeys(ctx) if err != nil { return nil, m.accountError(ctx, err) } if values == nil { values = []Passkey{} } return httpapi.OK(passkeysBody{Passkeys: values}), nil } type deletePasskeyInput struct { Session string `cookie:"archie_session"` ID string `path:"id"` } func (m *Module) deletePasskey(ctx context.Context, in *deletePasskeyInput) (*struct{}, error) { if err := person(ctx); err != nil { return nil, err } if err := m.requireFresh(ctx, in.Session); err != nil { return nil, err } if err := m.DeletePasskey(ctx, in.ID); err != nil { return nil, m.accountError(ctx, err) } return nil, nil } // tokenOwner reports whether the caller is a person who can hold personal // tokens; the bootstrap admin token acts as the system and cannot. func tokenOwner(ctx context.Context) bool { p, ok := PrincipalFromContext(ctx) return ok && p.IdentityID != "" && p.IdentityID != SystemID } type tokensBody struct { Tokens []PersonalToken `json:"tokens"` Available bool `json:"available"` } func (m *Module) listTokens(ctx context.Context, _ *struct{}) (*httpapi.Reply[tokensBody], error) { if !tokenOwner(ctx) { return httpapi.OK(tokensBody{Tokens: []PersonalToken{}}), nil } tokens, err := m.ListPersonalTokens(ctx) if err != nil { return nil, m.accountError(ctx, err) } if tokens == nil { tokens = []PersonalToken{} } return httpapi.OK(tokensBody{Tokens: tokens, Available: true}), nil } type createTokenInput struct { Body struct { Name string `json:"name"` Days int `json:"days,omitempty"` } } type createdToken struct { ID string `json:"id"` Token string `json:"token"` } type createTokenReply struct { CacheControl string `header:"Cache-Control"` Body createdToken } // createToken makes the token here and stores only its hash; the response is // the one time the token is shown. func (m *Module) createToken(ctx context.Context, in *createTokenInput) (*createTokenReply, error) { if !tokenOwner(ctx) { return nil, huma.Error403Forbidden("Personal tokens need a signed-in person.") } name := strings.TrimSpace(in.Body.Name) if name == "" || utf8.RuneCountInString(name) > maxTokenNameLength { return nil, huma.Error400BadRequest("Name a token in up to 40 characters.") } var expiresAt *time.Time switch in.Body.Days { case 0: case 7, 30, 90: t := time.Now().UTC().AddDate(0, 0, in.Body.Days) expiresAt = &t default: return nil, huma.Error400BadRequest("Lifetime is 7, 30 or 90 days, or none.") } raw, subject, err := NewPersonalToken() if err != nil { return nil, m.accountError(ctx, err) } if err := m.addPersonalToken(ctx, subject, name, expiresAt); err != nil { return nil, m.accountError(ctx, err) } return &createTokenReply{CacheControl: "no-store", Body: createdToken{ID: subject.Subject, Token: raw}}, nil } // addPersonalToken binds the token under its own deadline. The token is // shown only once, so a bind that fails may still have committed: revoke it, // detached from the request that is over, rather than leave a token nobody // holds. func (m *Module) addPersonalToken(ctx context.Context, subject Subject, name string, expiresAt *time.Time) error { bindCtx, cancel := context.WithTimeout(ctx, personalTokenBindTimeout) defer cancel() err := m.AddPersonalToken(bindCtx, subject, name, expiresAt) if err == nil { return nil } revokeCtx, revokeCancel := context.WithTimeout(context.WithoutCancel(ctx), personalTokenBindTimeout) defer revokeCancel() if revokeErr := m.RevokePersonalToken(revokeCtx, subject.Subject); revokeErr != nil && !errors.Is(revokeErr, ErrIdentityNotFound) { return errors.Join(err, fmt.Errorf("revoke unconfirmed token: %w", revokeErr)) } return err } type revokeTokenInput struct { ID string `path:"id"` } func (m *Module) revokeToken(ctx context.Context, in *revokeTokenInput) (*struct{}, error) { if !tokenOwner(ctx) { return nil, huma.Error403Forbidden("Personal tokens need a signed-in person.") } if err := m.RevokePersonalToken(ctx, in.ID); err != nil { return nil, m.accountError(ctx, err) } return nil, nil } type capabilitiesBody struct { Sections map[string]bool `json:"sections"` } // capabilities reports the dashboard sections this binary serves. Chat and a // person's own memory are every signed-in person's, acting with their own // access; every other served section's operations need an instance // administrator, so each is reported as the caller's administrator standing. // The dashboard hides the rest, whose pages call operations this binary does // not have. func (m *Module) capabilities(ctx context.Context, _ *struct{}) (*httpapi.Reply[capabilitiesBody], error) { p, signedIn := PrincipalFromContext(ctx) sections := map[string]bool{"chat": signedIn, "memory": signedIn} for _, name := range []string{ "settings", "events", "workflows", "runs", "credentials", "secret_engines", "controls", "memory_admin", "home", "system_status", "org_config", "captures", "mappings", "extension_catalogue", "model_aliases", "workflow_editor", } { sections[name] = p.InstanceAdmin() } // An organisation is created through the API alone here, so its page is // offered but its writes are not. sections["organisations"] = false // The access pages are offered to those the policy chain lets use them. sections["org_members"] = m.mayUse(ctx, p, ActionManageMembers, KindMember) sections["org_policies"] = m.mayUse(ctx, p, ActionManagePolicies, KindPolicy) sections["org_decisions"] = m.mayUse(ctx, p, ActionReadAudit, KindAudit) // Every member reads the organisation they belong to and its workspaces. sections["org"] = signedIn sections["org_workspaces"] = signedIn return httpapi.OK(capabilitiesBody{Sections: sections}), nil } type redirectReply struct { Location string `header:"Location"` SetCookie []http.Cookie `header:"Set-Cookie"` CacheControl string `header:"Cache-Control"` } // beginOIDC sends a browser to the provider, keeping the state and PKCE // verifier the callback needs in cookies scoped to the callback path. func (m *Module) beginOIDC(ctx context.Context, in *sessionInput) (*redirectReply, error) { flow, err := m.oidc.flow(ctx, m) if errors.Is(err, ErrNoCredential) { return nil, huma.Error404NotFound("no identity provider is configured") } if err != nil { return nil, m.accountError(ctx, err) } state, err := randomState() if err != nil { return nil, m.accountError(ctx, err) } target, verifier, err := flow.AuthCodeURL(ctx, state) if err != nil { return nil, m.accountError(ctx, err) } return &redirectReply{ Location: target, SetCookie: []http.Cookie{ in.Client.cookie(loginStateCookie, state, loginCookiePath, loginCookieAge), in.Client.cookie(loginVerifierCookie, verifier, loginCookiePath, loginCookieAge), }, CacheControl: "no-store", }, nil } type oidcCallbackInput struct { Client client Code string `query:"code"` State string `query:"state"` ProviderError string `query:"error"` WantState string `cookie:"archie_login_state"` Verifier string `cookie:"archie_login_verifier"` } // finishOIDC checks the state it issued, exchanges the code with the PKCE // verifier it issued, and opens a local session no longer than the // provider's. func (m *Module) finishOIDC(ctx context.Context, in *oidcCallbackInput) (*redirectReply, error) { if in.ProviderError != "" { return nil, m.accountError(ctx, fmt.Errorf("%w: provider returned %s", ErrCredentialRejected, in.ProviderError)) } if in.WantState == "" || !sameToken(in.WantState, in.State) || in.Verifier == "" { return nil, m.accountError(ctx, fmt.Errorf("%w: sign-in state did not match", ErrCredentialRejected)) } flow, err := m.oidc.flow(ctx, m) if err != nil { return nil, m.accountError(ctx, err) } session, err := flow.Exchange(ctx, in.Code, in.Verifier) if err != nil { return nil, m.accountError(ctx, err) } value, err := ResolveCredential(ctx, m, session.Credential) if err != nil { return nil, m.accountError(ctx, err) } p, err := m.PrincipalFor(ctx, value.ID) if err != nil { return nil, m.accountError(ctx, err) } local, err := m.OpenAccountSession(WithPrincipal(ctx, p), session.Expires) if err != nil { return nil, m.accountError(ctx, err) } m.log.InfoContext(ctx, "account signed in through the identity provider", "identity", value.ID) return &redirectReply{ Location: "/", SetCookie: []http.Cookie{ in.Client.clear(loginStateCookie, loginCookiePath), in.Client.clear(loginVerifierCookie, loginCookiePath), in.Client.session(local), }, CacheControl: "no-store", }, nil } func randomState() (string, error) { raw := make([]byte, 32) if _, err := rand.Read(raw); err != nil { return "", err } return base64.RawURLEncoding.EncodeToString(raw), nil }