feat(governance): sign in to the archie binary from the Vue dashboard (#2017)

The binary serves the account routes the Vue client already calls: status,
setup, password and passkey sign-in, recovery, sign-out, OIDC, account
passkeys, password and recovery codes, personal tokens and capabilities.
The API authenticates a session cookie, a personal token or the bootstrap
admin token, and unsafe requests pass cross-origin protection. The
dashboard serves the Vue app at /.

Copied from internal/webui/{accounts,passkeys,personal_tokens,
api_capabilities,auth}.go, internal/infrastructure/oidc/{flow,oidc}.go and
internal/app/archieui/account_oidc.go, which archie-ui still imports.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
samandCopilot committed 2026-11-20 00:30:11 +11:00
1 parent 7673e3a135
commit c12f6b7947
14 files changed
+2241 -53

No files matched your search

+3 -3
View File
@@ -1,4 +1,4 @@
// Package dashboard serves the single binary's SPA: archie.html and its
// Package dashboard serves the single binary's SPA: index.html and its
// assets from the embedded build. Every other route belongs to a module.
package dashboard
@@ -10,7 +10,7 @@ import (
"github.com/samcharles93/archie-core/internal/platform/httpjson"
)
const page = "archie.html"
const page = "index.html"
// Routes serves the SPA from dist on mux. A path under /api/ that no module
// claimed is a JSON 404, never the page. With no build embedded, the page
@@ -45,7 +45,7 @@ func handler(dist fs.FS) http.Handler {
return
}
name := strings.TrimPrefix(r.URL.Path, "/")
if name != "" && name != "index.html" && name != page {
if name != "" && name != page {
if info, err := fs.Stat(dist, name); err == nil && !info.IsDir() {
if strings.HasPrefix(name, "assets/") {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
+712
View File
@@ -0,0 +1,712 @@
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. The
// sections below have no backend here yet, so the dashboard hides them;
// settings is the instance area, which only an instance administrator
// operates.
func (m *Module) capabilities(ctx context.Context, _ *struct{}) (*httpapi.Reply[capabilitiesBody], error) {
p, _ := PrincipalFromContext(ctx)
sections := map[string]bool{"settings": p.InstanceAdmin()}
for _, name := range []string{
"chat", "logs", "skills", "curators", "channels", "captures", "mappings", "bindings", "workflows",
"org_members", "org_agents", "org_policies", "org_denials", "org_audit", "org_usage", "org_config",
} {
sections[name] = false
}
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
}
+122
View File
@@ -0,0 +1,122 @@
package governance
import (
"context"
"crypto/subtle"
"errors"
"net"
"net/http"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
)
// credentials is what authenticating a request reads.
type credentials interface {
ResolveAccountSession(context.Context, string) (Identity, error)
ResolveSubject(context.Context, Subject) (Identity, error)
PersonalTokenOf(context.Context, Subject) (PersonalToken, error)
TouchPersonalToken(context.Context, Subject, time.Time) error
PrincipalFor(context.Context, IdentityID) (Principal, error)
}
// authenticator admits, in order, a browser session cookie, a personal API
// token, or the bootstrap admin token, which is held only as its hash.
type authenticator struct {
creds credentials
adminHash string
now func() time.Time
}
// Authenticator returns the API's authenticator over the module's accounts
// and personal tokens, with adminHash the bootstrap admin token's hash.
func (m *Module) Authenticator(adminHash string) httpapi.Authenticator {
return authenticator{creds: m, adminHash: adminHash, now: time.Now}
}
func (a authenticator) Authenticate(ctx context.Context, r *http.Request) (context.Context, bool, error) {
if c, err := r.Cookie(httpapi.SessionCookie); err == nil {
value, err := a.creds.ResolveAccountSession(ctx, c.Value)
return a.acting(ctx, value, err)
}
token, ok := bearer(r)
if !ok {
return nil, false, httpapi.ErrUnauthenticated
}
if subject, ok := PersonalTokenSubject(token); ok {
if err := UsePersonalToken(ctx, a.creds, subject, a.now()); err != nil {
return a.acting(ctx, Identity{}, err)
}
value, err := a.creds.ResolveSubject(ctx, subject)
return a.acting(ctx, value, err)
}
if httpjson.TokenMatches(token, a.adminHash) {
return actingAs(ctx, SharedTokenOwner()), true, nil
}
return nil, false, httpapi.ErrUnauthenticated
}
// acting is the principal an identity resolved from a credential acts as.
func (a authenticator) acting(ctx context.Context, value Identity, err error) (context.Context, bool, error) {
if err == nil && !value.CanAct() {
err = ErrIdentityInactive
}
if err != nil {
if refused(err) {
return nil, false, httpapi.ErrUnauthenticated
}
return nil, false, err
}
p, err := a.creds.PrincipalFor(ctx, value.ID)
if err != nil {
return nil, false, err
}
p.Kind = value.Kind
return actingAs(ctx, p), p.InstanceAdmin(), nil
}
func actingAs(ctx context.Context, p Principal) context.Context {
return WithOrg(WithPrincipal(ctx, p), p.Org)
}
// refused reports whether err says the credential was not accepted, as
// opposed to the lookup failing.
func refused(err error) bool {
for _, target := range []error{ErrNoCredential, ErrCredentialRejected, ErrIdentityNotFound, ErrIdentityInactive, ErrSubjectUnbound} {
if errors.Is(err, target) {
return true
}
}
return false
}
func bearer(r *http.Request) (string, bool) {
const prefix = "Bearer "
header := r.Header.Get("Authorization")
if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) {
return "", false
}
token := strings.TrimSpace(header[len(prefix):])
return token, token != ""
}
// loopback reports whether host, as a request's Host header gives it, names
// this machine. Browsers send a Secure cookie only over HTTPS, except to
// localhost.
func loopback(host string) bool {
if name, _, err := net.SplitHostPort(host); err == nil {
host = name
}
host = strings.Trim(host, "[]")
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
func sameToken(got, want string) bool {
return subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1
}
+138
View File
@@ -0,0 +1,138 @@
package governance
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
)
// fakeCredentials holds sessions and personal tokens by their raw value.
type fakeCredentials struct {
sessions map[string]Identity
tokens map[Subject]PersonalToken
subjects map[Subject]Identity
principals map[IdentityID]Principal
}
func (f fakeCredentials) ResolveAccountSession(_ context.Context, token string) (Identity, error) {
if token == "broken" {
return Identity{}, errors.New("database down")
}
if v, ok := f.sessions[token]; ok {
return v, nil
}
return Identity{}, ErrIdentityNotFound
}
func (f fakeCredentials) ResolveSubject(_ context.Context, s Subject) (Identity, error) {
if v, ok := f.subjects[s]; ok {
return v, nil
}
return Identity{}, ErrIdentityNotFound
}
func (f fakeCredentials) PersonalTokenOf(_ context.Context, s Subject) (PersonalToken, error) {
if v, ok := f.tokens[s]; ok {
return v, nil
}
return PersonalToken{}, ErrIdentityNotFound
}
func (fakeCredentials) TouchPersonalToken(context.Context, Subject, time.Time) error { return nil }
func (f fakeCredentials) PrincipalFor(_ context.Context, id IdentityID) (Principal, error) {
return f.principals[id], nil
}
// TestAuthenticateRequest guards the API's credential check: a session
// cookie or personal token acts as its own identity with that identity's
// role, the bootstrap admin token acts as the instance owner, and a
// tampered, expired or inactive credential is refused rather than acting as
// anyone.
func TestAuthenticateRequest(t *testing.T) {
const admin = "a-plainly-fake-admin-token" //nolint:gosec // test fixture, not a credential
now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
past := now.Add(-time.Hour)
owner := Identity{ID: "owner", Kind: KindUser, Lifecycle: LifecycleActive}
viewer := Identity{ID: "viewer", Kind: KindUser, Lifecycle: LifecycleActive}
suspended := Identity{ID: "suspended", Kind: KindUser, Lifecycle: LifecycleSuspended}
ownerToken, ownerSubject := personalToken(t)
viewerToken, viewerSubject := personalToken(t)
expiredToken, expiredSubject := personalToken(t)
creds := fakeCredentials{
sessions: map[string]Identity{"owner-session": owner, "viewer-session": viewer, "suspended-session": suspended},
tokens: map[Subject]PersonalToken{
ownerSubject: {}, viewerSubject: {}, expiredSubject: {ExpiresAt: &past},
},
subjects: map[Subject]Identity{ownerSubject: owner, viewerSubject: viewer, expiredSubject: owner},
principals: map[IdentityID]Principal{
"owner": {IdentityID: "owner", Org: DefaultOrgID, Memberships: []Membership{{IdentityID: "owner", OrgID: DefaultOrgID, Role: RoleOwner}}},
"viewer": {IdentityID: "viewer", Org: DefaultOrgID, Memberships: []Membership{{IdentityID: "viewer", OrgID: DefaultOrgID, Role: RoleViewer}}},
},
}
tests := []struct {
name, cookie, bearer, adminHash string
wantErr error
wantID IdentityID
wantRole Role
wantAdmin bool
}{
{name: "no credential", wantErr: httpapi.ErrUnauthenticated},
{name: "owner session", cookie: "owner-session", wantID: "owner", wantRole: RoleOwner, wantAdmin: true},
{name: "viewer session", cookie: "viewer-session", wantID: "viewer", wantRole: RoleViewer},
{name: "tampered session", cookie: "owner-sessiom", wantErr: httpapi.ErrUnauthenticated},
{name: "suspended identity's session", cookie: "suspended-session", wantErr: httpapi.ErrUnauthenticated},
{name: "a failed session lookup is not a refusal", cookie: "broken", wantErr: errors.New("any")},
{name: "owner's personal token", bearer: ownerToken, wantID: "owner", wantRole: RoleOwner, wantAdmin: true},
{name: "viewer's personal token keeps the viewer role", bearer: viewerToken, wantID: "viewer", wantRole: RoleViewer},
{name: "expired personal token", bearer: expiredToken, wantErr: httpapi.ErrUnauthenticated},
{name: "unknown personal token", bearer: "archie_pat_00", wantErr: httpapi.ErrUnauthenticated}, //nolint:gosec // G101: a token no store holds, which must be refused.
{name: "admin token", bearer: admin, adminHash: httpjson.TokenHash(admin), wantID: SystemID, wantRole: RoleOwner, wantAdmin: true},
{name: "wrong admin token", bearer: "other", adminHash: httpjson.TokenHash(admin), wantErr: httpapi.ErrUnauthenticated},
{name: "no admin hash locks the admin token out", bearer: admin, wantErr: httpapi.ErrUnauthenticated},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
auth := authenticator{creds: creds, adminHash: tt.adminHash, now: func() time.Time { return now }}
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/thing", nil)
if tt.cookie != "" {
req.AddCookie(&http.Cookie{Name: httpapi.SessionCookie, Value: tt.cookie}) //nolint:gosec // G124: a request cookie; attributes are the server's to set.
}
if tt.bearer != "" {
req.Header.Set("Authorization", "Bearer "+tt.bearer)
}
acting, admin, err := auth.Authenticate(req.Context(), req)
if tt.wantErr != nil {
if err == nil {
t.Fatal("authenticated, want refused")
}
if errors.Is(tt.wantErr, httpapi.ErrUnauthenticated) != errors.Is(err, httpapi.ErrUnauthenticated) {
t.Fatalf("err = %v, want %v", err, tt.wantErr)
}
return
}
if err != nil {
t.Fatalf("Authenticate: %v", err)
}
p, ok := PrincipalFromContext(acting)
if !ok || p.IdentityID != tt.wantID || p.Role("") != tt.wantRole || admin != tt.wantAdmin {
t.Fatalf("acts as %s role %q admin %v, want %s role %q admin %v", p.IdentityID, p.Role(""), admin, tt.wantID, tt.wantRole, tt.wantAdmin)
}
})
}
}
func personalToken(t *testing.T) (string, Subject) {
t.Helper()
raw, subject, err := NewPersonalToken()
if err != nil {
t.Fatal(err)
}
return raw, subject
}
+2 -1
View File
@@ -255,12 +255,13 @@ type Module struct {
store *store.Store
log *slog.Logger
credentials Credentials
oidc *oidcLogin
}
// NewModule returns the governance module for orgID. The ai-sdk provider
// classes must already be registered.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module {
return &Module{orgID: orgID, store: store.New(db), log: log}
return &Module{orgID: orgID, store: store.New(db), log: log, oidc: &oidcLogin{}}
}
// UseCredentials gives the module the sealed store a model's key reference
+5 -1
View File
@@ -356,7 +356,11 @@ type PersonalTokenStore interface {
// UsePersonalToken admits a presented token, refusing expired tokens and
// recording last use at most once per minute.
func UsePersonalToken(ctx context.Context, store PersonalTokenStore, subject Subject, now time.Time) error {
func UsePersonalToken(ctx context.Context, store interface {
PersonalTokenOf(context.Context, Subject) (PersonalToken, error)
TouchPersonalToken(context.Context, Subject, time.Time) error
}, subject Subject, now time.Time,
) error {
token, err := store.PersonalTokenOf(ctx, subject)
if err != nil {
return err
+198
View File
@@ -0,0 +1,198 @@
package governance
import (
"context"
"fmt"
"strings"
"sync"
gooidc "github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
// oidcCallbackPath must match the redirect URI registered at the provider:
// the provider returns the browser to the path it was given.
const oidcCallbackPath = "/oauth2/callback"
// oidcLogin runs the browser sign-in against the provider the authentication
// settings name. It keeps the provider's discovery and signing-key cache
// until the settings change, so a change applies without a restart.
type oidcLogin struct {
mu sync.Mutex
current AuthenticationSettings
provider *oidcProvider
}
// flow returns the authorization code flow for the saved settings, or
// ErrNoCredential when no provider is configured.
func (o *oidcLogin) flow(ctx context.Context, settings AuthenticationSettingsStore) (*oidcFlow, error) {
value, err := settings.AuthenticationSettings(ctx)
if err != nil {
return nil, err
}
if value.PublicURL == "" || value.OIDCIssuer == "" {
return nil, ErrNoCredential
}
o.mu.Lock()
defer o.mu.Unlock()
if o.provider == nil || o.current != value {
provider, err := newOIDCProvider(value.OIDCIssuer, value.OIDCAudience)
if err != nil {
return nil, err
}
o.provider, o.current = provider, value
}
return newOIDCFlow(o.provider, value.OIDCClientID, value.PublicURL+oidcCallbackPath)
}
// oidcProvider discovers the identity provider on first use and keeps the
// result. A provider that is down does not stop the binary: discovery is
// retried on the next sign-in.
type oidcProvider struct {
issuer string
audience string
mu sync.Mutex
discovered *gooidc.Provider
}
func newOIDCProvider(issuer, audience string) (*oidcProvider, error) {
issuer, audience = strings.TrimSpace(issuer), strings.TrimSpace(audience)
if issuer == "" {
return nil, fmt.Errorf("oidc: issuer is required")
}
// Without an audience a token the provider minted for a different
// service would authenticate here.
if audience == "" {
return nil, fmt.Errorf("oidc: audience is required")
}
return &oidcProvider{issuer: issuer, audience: audience}, nil
}
func (p *oidcProvider) get(ctx context.Context) (*gooidc.Provider, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.discovered != nil {
return p.discovered, nil
}
discovered, err := gooidc.NewProvider(ctx, p.issuer)
if err != nil {
return nil, fmt.Errorf("%w: discover %q: %w", ErrProviderUnavailable, p.issuer, err)
}
p.discovered = discovered
return discovered, nil
}
// oidcFlow runs the authorization code flow with PKCE. Discovery, the code
// exchange, PKCE and token verification are the libraries'.
type oidcFlow struct {
provider *oidcProvider
clientID string
redirectURL string
}
func newOIDCFlow(provider *oidcProvider, clientID, redirectURL string) (*oidcFlow, error) {
if strings.TrimSpace(clientID) == "" {
return nil, fmt.Errorf("oidc: client id is required for the browser flow")
}
return &oidcFlow{provider: provider, clientID: clientID, redirectURL: redirectURL}, nil
}
func (f *oidcFlow) oauth(ctx context.Context) (oauth2.Config, error) {
discovered, err := f.provider.get(ctx)
if err != nil {
return oauth2.Config{}, err
}
return oauth2.Config{
ClientID: f.clientID,
Endpoint: discovered.Endpoint(),
RedirectURL: f.redirectURL,
// openid makes the provider return a subject at all; profile and
// email make a name available for display.
Scopes: []string{gooidc.ScopeOpenID, "profile", "email"},
}, nil
}
// AuthCodeURL returns the provider URL to send a browser to, with the
// audience requested, and the PKCE verifier.
func (f *oidcFlow) AuthCodeURL(ctx context.Context, state string) (string, string, error) {
config, err := f.oauth(ctx)
if err != nil {
return "", "", err
}
codeVerifier := oauth2.GenerateVerifier()
url := config.AuthCodeURL(state,
oauth2.S256ChallengeOption(codeVerifier),
oauth2.SetAuthURLParam("nonce", oauth2.S256ChallengeFromVerifier(codeVerifier)),
oauth2.SetAuthURLParam("audience", f.provider.audience),
)
return url, codeVerifier, nil
}
// Exchange trades the code for the provider's tokens, verifies the ID token
// against the browser client and binds its nonce to the PKCE verifier. An
// access token is not proof of a browser sign-in.
func (f *oidcFlow) Exchange(ctx context.Context, code, codeVerifier string) (ProviderSession, error) {
config, err := f.oauth(ctx)
if err != nil {
return ProviderSession{}, err
}
token, err := config.Exchange(ctx, strings.TrimSpace(code), oauth2.VerifierOption(codeVerifier))
if err != nil {
return ProviderSession{}, fmt.Errorf("%w: exchange code: %w", ErrCredentialRejected, err)
}
rawIDToken, ok := token.Extra("id_token").(string)
if !ok || rawIDToken == "" {
return ProviderSession{}, fmt.Errorf("%w: provider returned no ID token", ErrCredentialRejected)
}
discovered, err := f.provider.get(ctx)
if err != nil {
return ProviderSession{}, err
}
verified, err := discovered.Verifier(&gooidc.Config{ClientID: f.clientID}).Verify(ctx, rawIDToken)
if err != nil {
return ProviderSession{}, fmt.Errorf("%w: verify ID token: %w", ErrCredentialRejected, err)
}
if verified.Nonce != oauth2.S256ChallengeFromVerifier(codeVerifier) {
return ProviderSession{}, fmt.Errorf("%w: ID token nonce mismatch", ErrCredentialRejected)
}
credential, err := credentialOf(verified)
if err != nil {
return ProviderSession{}, err
}
expires := token.Expiry
if credential.Expires.Before(expires) || expires.IsZero() {
expires = credential.Expires
}
return ProviderSession{Credential: credential, Token: rawIDToken, Expires: expires}, nil
}
// credentialOf reads what a verified token proved. Claims are read only after
// verification: an unverified token selects nothing.
func credentialOf(token *gooidc.IDToken) (Credential, error) {
var claims struct {
Subject string `json:"sub"`
ClientID string `json:"client_id"`
Scope string `json:"scope"`
Scopes []string `json:"scp"`
Email string `json:"email"`
Verified bool `json:"email_verified"`
}
_ = token.Claims(&claims)
subject := Subject{Issuer: token.Issuer, Subject: strings.TrimSpace(claims.Subject)}
if subject.Subject == "" {
subject.Subject = strings.TrimSpace(claims.ClientID)
}
if subject.Subject == "" {
return Credential{}, fmt.Errorf("%w: token asserts neither sub nor client_id", ErrCredentialRejected)
}
email := ""
if claims.Verified {
email = strings.TrimSpace(claims.Email)
}
scopes := claims.Scopes
if len(scopes) == 0 {
scopes = strings.Fields(claims.Scope)
}
return Credential{Subject: subject, Email: email, Scopes: scopes, Expires: token.Expiry}, nil
}