package governance import ( "context" "crypto/rand" "crypto/sha256" "encoding/hex" "errors" "fmt" "net/mail" "net/url" "strings" "time" "github.com/google/uuid" ) type ( IdentityID string Kind string Lifecycle string CommandType string ) const ( SystemID IdentityID = "00000000-0000-5000-8000-000000000001" KindSystem Kind = "system" KindBot Kind = "bot" KindServiceAccount Kind = "service_account" KindUser Kind = "user" LifecycleActive Lifecycle = "active" LifecycleSuspended Lifecycle = "suspended" LifecycleRetired Lifecycle = "retired" CommandRename CommandType = "rename" CommandSuspend CommandType = "suspend" CommandReactivate CommandType = "reactivate" CommandRetire CommandType = "retire" ) var ( ErrInvalidIdentity = errors.New("invalid identity") ErrIdentityNotFound = errors.New("identity not found") ErrIdentityConflict = errors.New("identity version conflict") ErrSystemImmutable = errors.New("system identity is immutable") ErrIllegalTransition = errors.New("illegal identity lifecycle transition") ErrNoCredential = errors.New("no credential presented") ErrCredentialRejected = errors.New("credential rejected") ErrProviderUnavailable = errors.New("identity provider unavailable") ErrSubjectUnbound = errors.New("credential subject is not bound to an identity") ErrIdentityInactive = errors.New("identity may not act") ErrSetupComplete = errors.New("administrator has already been set up") ) // Identity is a persistent actor (user, bot, service account, or system) and // its lifecycle state. type Identity struct { ID IdentityID `json:"id"` Kind Kind `json:"kind"` DisplayName string `json:"display_name"` Lifecycle Lifecycle `json:"lifecycle"` Version int64 `json:"version"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } // IdentityCommand is a lifecycle or rename mutation applied to an Identity. type IdentityCommand struct { Type CommandType DisplayName string } // IdentityEvent records one applied IdentityCommand. type IdentityEvent struct { IdentityID IdentityID Type CommandType From Lifecycle To Lifecycle DisplayName string At time.Time } // IdentityAudit attributes an identity change to an actor and source. type IdentityAudit struct { ActorID IdentityID Source, RequestID string At time.Time } // IdentityRepository persists identities and their lifecycle events. type IdentityRepository interface { List(context.Context) ([]Identity, error) Get(context.Context, IdentityID) (Identity, error) ResolveLegacyName(context.Context, string) (Identity, error) Create(context.Context, Identity, IdentityAudit) (Identity, error) Apply(context.Context, IdentityID, int64, IdentityCommand, IdentityAudit) (Identity, error) } // SystemIdentity returns the singleton built-in system identity. func SystemIdentity() Identity { return Identity{ID: SystemID, Kind: KindSystem, DisplayName: "System", Lifecycle: LifecycleActive, Version: 1} } // StableID derives a version 5 UUID from legacyName using SHA-256 so fixed // identities resolve deterministically across restarts. func StableID(legacyName string) IdentityID { sum := sha256.Sum256([]byte("archie.identity.v1\x00" + strings.ToLower(strings.TrimSpace(legacyName)))) var id uuid.UUID copy(id[:], sum[:16]) id[6] = id[6]&0x0f | 0x50 id[8] = id[8]&0x3f | 0x80 return IdentityID(id.String()) } // OperatorID is the person identity used by an instance operator. func OperatorID() IdentityID { return StableID("operator") } // AgentID is the bot identity workflows run as. func AgentID() IdentityID { return StableID("agent") } // NewIdentity validates and constructs an active Identity at version 1. func NewIdentity(id IdentityID, kind Kind, displayName string) (Identity, error) { value := Identity{ ID: id, Kind: kind, DisplayName: strings.TrimSpace(displayName), Lifecycle: LifecycleActive, Version: 1, } if err := value.Validate(); err != nil { return Identity{}, err } return value, nil } // FromLegacyName builds the bot identity for a configured name. func FromLegacyName(legacyName string) (Identity, error) { return NewIdentity(StableID(legacyName), KindBot, legacyName) } // Agent reports whether k acts on its own rather than for a person: an agent // serves one organisation. func (k Kind) Agent() bool { return k == KindBot || k == KindServiceAccount } // ValidDisplayName reports whether name is non-empty after trimming. func ValidDisplayName(name string) bool { return strings.TrimSpace(name) != "" } // Validate checks that i has a valid id, display name, kind, and lifecycle. func (i Identity) Validate() error { if i.ID == "" || !ValidDisplayName(i.DisplayName) { return fmt.Errorf("%w: ID and display name are required", ErrInvalidIdentity) } switch i.Kind { case KindSystem, KindBot, KindServiceAccount, KindUser: default: return fmt.Errorf("%w: unknown kind %q", ErrInvalidIdentity, i.Kind) } switch i.Lifecycle { case LifecycleActive, LifecycleSuspended, LifecycleRetired: default: return fmt.Errorf("%w: unknown lifecycle %q", ErrInvalidIdentity, i.Lifecycle) } if i.Kind == KindSystem && (i.ID != SystemID || i.Lifecycle != LifecycleActive) { return ErrSystemImmutable } if i.ID == SystemID && i.Kind != KindSystem { return ErrSystemImmutable } return nil } // CanAct reports whether an identity may perform actions. func (i Identity) CanAct() bool { return i.Lifecycle == LifecycleActive } // ApplyIdentity applies command to i and returns the updated identity and event. func ApplyIdentity(i Identity, command IdentityCommand) (Identity, IdentityEvent, error) { if i.ID == SystemID || i.Kind == KindSystem { return Identity{}, IdentityEvent{}, ErrSystemImmutable } event := IdentityEvent{IdentityID: i.ID, Type: command.Type, From: i.Lifecycle, To: i.Lifecycle, At: time.Now().UTC()} switch command.Type { case CommandRename: name := strings.TrimSpace(command.DisplayName) if name == "" { return Identity{}, IdentityEvent{}, fmt.Errorf("%w: display name is required", ErrInvalidIdentity) } i.DisplayName, event.DisplayName = name, name case CommandSuspend: if i.Lifecycle != LifecycleActive { return Identity{}, IdentityEvent{}, ErrIllegalTransition } i.Lifecycle, event.To = LifecycleSuspended, LifecycleSuspended case CommandReactivate: if i.Lifecycle != LifecycleSuspended { return Identity{}, IdentityEvent{}, ErrIllegalTransition } i.Lifecycle, event.To = LifecycleActive, LifecycleActive case CommandRetire: if i.Lifecycle != LifecycleActive && i.Lifecycle != LifecycleSuspended { return Identity{}, IdentityEvent{}, ErrIllegalTransition } i.Lifecycle, event.To = LifecycleRetired, LifecycleRetired default: return Identity{}, IdentityEvent{}, fmt.Errorf("%w: unknown command %q", ErrInvalidIdentity, command.Type) } i.Version++ return i, event, nil } // Subject is what an identity provider asserts about a caller. Issuer is part // of the key because two providers can assert the same subject string for // different people. type Subject struct { Issuer string `json:"issuer"` Subject string `json:"subject"` } // EmailSubject is the placeholder binding of a person added by email until // their first sign-in claims it. func EmailSubject(issuer, email string) Subject { return Subject{Issuer: issuer, Subject: "email:" + strings.ToLower(strings.TrimSpace(email))} } // Validate checks that s names both an issuer and a subject. func (s Subject) Validate() error { if strings.TrimSpace(s.Issuer) == "" || strings.TrimSpace(s.Subject) == "" { return fmt.Errorf("%w: issuer and subject are required", ErrInvalidIdentity) } return nil } // Credential is what a provider-issued token proved. type Credential struct { Subject Subject Email string Scopes []string Expires time.Time } // Verifier checks a presented bearer token against an identity provider. type Verifier interface { Verify(ctx context.Context, rawToken string) (Credential, error) } // SubjectResolver resolves a provider subject to its bound identity. type SubjectResolver interface { ResolveSubject(context.Context, Subject) (Identity, error) ClaimSubject(ctx context.Context, placeholder, subject Subject) (Identity, error) } // SubjectBinding resolves and binds verified provider subjects to identities. type SubjectBinding interface { SubjectResolver BindSubject(context.Context, IdentityID, Subject, IdentityAudit) error } // LoginFlow is the browser authorization flow an identity provider requires. type LoginFlow interface { AuthCodeURL(ctx context.Context, state string) (string, string, error) Exchange(ctx context.Context, code, codeVerifier string) (ProviderSession, error) } // ProviderSession is what a completed provider authorization flow yields. type ProviderSession struct { Credential Credential Token string Expires time.Time } // AuthenticateCredential verifies rawToken and resolves it to an active identity. func AuthenticateCredential(ctx context.Context, subjects SubjectResolver, verifier Verifier, rawToken string) (Identity, Credential, error) { if strings.TrimSpace(rawToken) == "" { return Identity{}, Credential{}, ErrNoCredential } if verifier == nil { return Identity{}, Credential{}, fmt.Errorf("%w: no identity provider is configured", ErrCredentialRejected) } credential, err := verifier.Verify(ctx, rawToken) if err != nil { return Identity{}, Credential{}, fmt.Errorf("%w: %w", ErrCredentialRejected, err) } value, err := ResolveCredential(ctx, subjects, credential) if err != nil { return Identity{}, Credential{}, err } return value, credential, nil } // ResolveCredential maps a verified credential to its active identity. func ResolveCredential(ctx context.Context, subjects SubjectResolver, credential Credential) (Identity, error) { if err := credential.Subject.Validate(); err != nil { return Identity{}, fmt.Errorf("%w: %w", ErrCredentialRejected, err) } value, err := subjects.ResolveSubject(ctx, credential.Subject) if errors.Is(err, ErrIdentityNotFound) && credential.Email != "" { value, err = subjects.ClaimSubject(ctx, EmailSubject(credential.Subject.Issuer, credential.Email), credential.Subject) } if err != nil { if errors.Is(err, ErrIdentityNotFound) { return Identity{}, fmt.Errorf("%w: %s", ErrSubjectUnbound, credential.Subject.Subject) } return Identity{}, err } if !value.CanAct() { return Identity{}, fmt.Errorf("%w: %s is %s", ErrIdentityInactive, value.ID, value.Lifecycle) } return value, nil } // PersonalTokenIssuer is the subject issuer a personal API token binds under. // The subject is the token's SHA-256, so the store never holds the token. const PersonalTokenIssuer = "archie-token" const ( personalTokenPrefix = "archie_pat_" lastUsedGranularity = time.Minute ) // NewPersonalToken returns a fresh personal API token and the subject it binds as. func NewPersonalToken() (string, Subject, error) { var secret [32]byte if _, err := rand.Read(secret[:]); err != nil { return "", Subject{}, err } raw := personalTokenPrefix + hex.EncodeToString(secret[:]) subject, _ := PersonalTokenSubject(raw) return raw, subject, nil } // PersonalTokenSubject returns the subject a presented token binds as, or // false when the credential is not a personal token. func PersonalTokenSubject(raw string) (Subject, bool) { if !strings.HasPrefix(raw, personalTokenPrefix) { return Subject{}, false } sum := sha256.Sum256([]byte(raw)) return Subject{Issuer: PersonalTokenIssuer, Subject: hex.EncodeToString(sum[:])}, true } // PersonalToken is one personal API token as its owner sees it. type PersonalToken struct { ID string `json:"id"` Name string `json:"name"` CreatedAt time.Time `json:"created_at"` ExpiresAt *time.Time `json:"expires_at"` LastUsedAt *time.Time `json:"last_used_at"` } // PersonalTokenStore persists personal API tokens for an identity. type PersonalTokenStore interface { BindPersonalToken(ctx context.Context, id IdentityID, subject Subject, name string, expiresAt *time.Time, audit IdentityAudit) error SubjectsOf(ctx context.Context, id IdentityID, issuer string) ([]PersonalToken, error) UnbindSubject(context.Context, IdentityID, Subject, IdentityAudit) error PersonalTokenOf(context.Context, Subject) (PersonalToken, error) TouchPersonalToken(context.Context, Subject, time.Time) error } // UsePersonalToken admits a presented token, refusing expired tokens and // recording last use at most once per minute. 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 } if token.ExpiresAt != nil && !now.Before(*token.ExpiresAt) { return ErrIdentityNotFound } if token.LastUsedAt == nil || now.Sub(*token.LastUsedAt) >= lastUsedGranularity { return store.TouchPersonalToken(ctx, subject, now) } return nil } // PersonalTokens manages personal API tokens for the authenticated principal. type PersonalTokens interface { AddPersonalToken(ctx context.Context, subject Subject, name string, expiresAt *time.Time) error ListPersonalTokens(ctx context.Context) ([]PersonalToken, error) RevokePersonalToken(ctx context.Context, id string) error } // AccountSessionLifetime bounds a password or passkey account session. const AccountSessionLifetime = 7 * 24 * time.Hour // AccountRegistration carries the fields needed to register an account or // bootstrap the instance owner. type AccountRegistration struct { PublicURL string `json:"public_url"` WorkspaceName string `json:"workspace_name"` OrganisationName string `json:"organisation_name"` Email string `json:"email"` DisplayName string `json:"display_name"` Password string `json:"password"` Role string `json:"role"` } // Validate normalises email and display name and checks their bounds. func (r *AccountRegistration) Validate() error { r.Email = strings.ToLower(strings.TrimSpace(r.Email)) address, err := mail.ParseAddress(r.Email) r.DisplayName = strings.TrimSpace(r.DisplayName) if err != nil || address.Address != r.Email || len(r.Email) > 254 || r.DisplayName == "" || len(r.DisplayName) > 200 { return ErrInvalidIdentity } return nil } // AccountSession is an authenticated user session issued after sign-in. type AccountSession struct { Identity Identity Token string Expires time.Time } // Accounts manages local password accounts and sessions. type Accounts interface { AccountSetupRequired(context.Context) (bool, error) RegisterAccount(context.Context, AccountRegistration, bool) (Identity, error) SignInAccount(ctx context.Context, email, password string) (AccountSession, error) ResolveAccountSession(context.Context, string) (Identity, error) SignOutAccount(context.Context, string) error ChangeAccountPassword(ctx context.Context, current, next string) error } // AccountSecurity guards authenticator changes with recent authentication and // single-use recovery codes. type AccountSecurity interface { OpenAccountSession(context.Context, time.Time) (AccountSession, error) RequireFreshAccountSession(context.Context, string) error CreateAccountRecovery(context.Context) (string, error) RecoverAccount(ctx context.Context, email, code, password string) error } // AuthenticationSettings stores instance public origin and OIDC parameters. type AuthenticationSettings struct { PublicURL string `json:"public_url"` OIDCIssuer string `json:"oidc_issuer"` OIDCAudience string `json:"oidc_audience"` OIDCClientID string `json:"oidc_client_id"` } // Validate checks that PublicURL is a valid origin and OIDC fields are paired. func (s AuthenticationSettings) Validate() error { if !validInstanceOrigin(s.PublicURL) { return ErrInvalidIdentity } if s.OIDCIssuer == "" { if s.OIDCClientID != "" || s.OIDCAudience != "" { return ErrInvalidIdentity } return nil } if !validProviderIssuer(s.OIDCIssuer) || strings.TrimSpace(s.OIDCClientID) == "" || strings.TrimSpace(s.OIDCAudience) == "" { return ErrInvalidIdentity } return nil } func validInstanceOrigin(raw string) bool { u, err := url.Parse(raw) if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" { return false } return (u.Path == "" || u.Path == "/") && (u.Scheme == "https" || u.Scheme == "http") } func validProviderIssuer(raw string) bool { u, err := url.Parse(raw) if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" { return false } return u.Scheme == "https" || (u.Scheme == "http" && u.Hostname() == "localhost") } // AuthenticationSettingsStore reads and saves instance authentication settings. type AuthenticationSettingsStore interface { AuthenticationSettings(context.Context) (AuthenticationSettings, error) SaveAuthenticationSettings(context.Context, AuthenticationSettings) error } // Passkey is a registered WebAuthn credential. type Passkey struct { ID string `json:"id"` Name string `json:"name"` } // PasskeyCeremony is an in-flight WebAuthn registration or login ceremony. type PasskeyCeremony struct { Token string Options []byte } // Passkeys manages WebAuthn passkey registration and sign-in. type Passkeys interface { BeginPasskey(context.Context, bool) (PasskeyCeremony, error) FinishPasskey(ctx context.Context, token string, response []byte, registration bool, name string) (AccountSession, error) ListPasskeys(context.Context) ([]Passkey, error) DeletePasskey(context.Context, string) error }