Files
archie/modules/governance/accounts_api.go
T
sam 073959b4f9 feat(memory): scope chat notes and preserve deletions on restore (#2069)
Keep personal notes private by default and require review before publishing shared notes. Restore backups and replay forgotten notes in one transaction, and retain the installed release when an unattended rollback could bring back forgotten notes.
2026-11-21 13:20:31 +11:00

725 lines
26 KiB
Go

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"}
public := func(id, method, path, summary string, status int) huma.Operation {
return httpapi.Public(huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags, DefaultStatus: status})
}
signedIn := func(id, method, path, summary string, status int) huma.Operation {
return httpapi.SignedIn(huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags, DefaultStatus: status})
}
admin := 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}
}
huma.Register(api, public("get-auth-status", http.MethodGet, "/api/auth/status", "Report setup and who is signed in", 0), m.authStatus)
huma.Register(api, public("set-up-account", http.MethodPost, "/api/auth/setup", "Create the instance owner and sign in", 0), m.setUpAccount)
huma.Register(api, public("sign-in", http.MethodPost, "/api/auth/login", "Sign in with email and password", 0), m.signIn)
huma.Register(api, public("sign-out", http.MethodPost, "/api/auth/logout", "Sign out", http.StatusNoContent), m.signOut)
huma.Register(api, public("recover-account", http.MethodPost, "/api/auth/recover", "Reset a password with a recovery code", http.StatusNoContent), m.recoverAccount)
huma.Register(api, public("begin-passkey-sign-in", http.MethodPost, "/api/auth/passkey/begin", "Start signing in with a passkey", 0), m.beginPasskeySignIn)
huma.Register(api, public("finish-passkey-sign-in", http.MethodPost, "/api/auth/passkey/finish", "Finish signing in with a passkey", 0), m.finishPasskeySignIn)
huma.Register(api, public("begin-oidc-sign-in", http.MethodGet, "/oauth2/login", "Send the browser to the identity provider", http.StatusSeeOther), m.beginOIDC)
huma.Register(api, public("finish-oidc-sign-in", http.MethodGet, oidcCallbackPath, "Complete the identity provider's sign-in", http.StatusSeeOther), m.finishOIDC)
huma.Register(api, signedIn("change-password", http.MethodPost, "/api/account/password", "Change your password", http.StatusNoContent), m.changePassword)
huma.Register(api, signedIn("create-recovery-code", http.MethodPost, "/api/account/recovery", "Create a recovery code", 0), m.createRecoveryCode)
huma.Register(api, signedIn("list-passkeys", http.MethodGet, "/api/account/passkeys", "List your passkeys", 0), m.listPasskeys)
huma.Register(api, signedIn("begin-passkey-registration", http.MethodPost, "/api/account/passkeys/begin", "Start adding a passkey", 0), m.beginPasskeyRegistration)
huma.Register(api, signedIn("finish-passkey-registration", http.MethodPost, "/api/account/passkeys/finish", "Finish adding a passkey", 0), m.finishPasskeyRegistration)
huma.Register(api, signedIn("delete-passkey", http.MethodDelete, "/api/account/passkeys/{id}", "Remove a passkey", http.StatusNoContent), m.deletePasskey)
huma.Register(api, signedIn("list-personal-tokens", http.MethodGet, "/api/tokens", "List your personal API tokens", 0), m.listTokens)
huma.Register(api, signedIn("create-personal-token", http.MethodPost, "/api/tokens", "Create a personal API token", http.StatusCreated), m.createToken)
huma.Register(api, signedIn("revoke-personal-token", http.MethodDelete, "/api/tokens/{id}", "Revoke a personal API token", http.StatusNoContent), m.revokeToken)
huma.Register(api, signedIn("get-capabilities", http.MethodGet, "/api/capabilities", "Report which dashboard sections this binary serves", 0), m.capabilities)
huma.Register(api, admin("create-account", http.MethodPost, "/api/accounts", "Create an account", http.StatusCreated), m.createAccount)
huma.Register(api, admin("get-authentication", http.MethodGet, "/api/authentication", "Get the authentication settings", 0), m.getAuthentication)
huma.Register(api, admin("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 {
PublicURL string `json:"public_url,omitempty"`
WorkspaceName string `json:"workspace_name,omitempty"`
OrganisationName string `json:"organisation_name,omitempty"`
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(r)
}
type setUpInput struct {
Client client
Body registration
}
func (m *Module) setUpAccount(ctx context.Context, in *setUpInput) (*userReply, error) {
if _, err := m.RegisterAccount(ctx, in.Body.account(), 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"`
}
}
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 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", "extensions", "secret_engines", "models", "controls", "memory_admin",
} {
sections[name] = p.InstanceAdmin()
}
for _, name := range []string{
"home", "tasks", "work_requests", "logs", "skills", "curators", "channels",
"captures", "mappings", "bindings", "workflow_editor", "extension_catalogue", "model_aliases",
"system_status", "task_execution", "organisations", "tools", "plugins", "container_runtime", "agent_profiles",
"org_members", "org_agents", "org_policies", "org_denials", "org_audit", "org_usage", "org_config",
} {
sections[name] = false
}
// 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
}