feat(identity): add browser setup and user accounts
This commit is contained in:
1 parent
cf3455ef2e
commit
aa012a7c6e
91 files changed
+6823
-636
No files matched your search
@@ -7,17 +7,14 @@ import (
|
||||
|
||||
// carriesPersonIdentity reports whether a platform's SenderID names a person.
|
||||
//
|
||||
// Telegram and email carry a native per-person sender id (a Telegram numeric
|
||||
// user id, an SMTP from address). The dashboard ("web") has one bearer token,
|
||||
// not users. Treating a shared token as an identity
|
||||
// would give it the same standing as a real user, which the read path's
|
||||
// isolation guarantee depends on never happening.
|
||||
// Web sender IDs are supplied by the authenticated UI service.
|
||||
// Telegram and email carry native person identifiers.
|
||||
//
|
||||
// An unknown platform fails closed, so a channel added later gets global and
|
||||
// agent scopes only until someone decides deliberately that it carries people.
|
||||
func carriesPersonIdentity(platform string) bool {
|
||||
switch platform {
|
||||
case "telegram", "email":
|
||||
case "telegram", "email", "web":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package archieui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/oidc"
|
||||
)
|
||||
|
||||
// accountOIDC reloads browser-managed provider settings without restarting UI.
|
||||
// The provider retains its discovery and signing-key cache until settings change.
|
||||
type accountOIDC struct {
|
||||
fallbackFlow identity.LoginFlow
|
||||
fallbackProvider *oidc.Provider
|
||||
settings identity.AuthenticationSettingsStore
|
||||
subjects identity.SubjectResolver
|
||||
fallback identity.AuthenticationSettings
|
||||
mu sync.Mutex
|
||||
current identity.AuthenticationSettings
|
||||
provider *oidc.Provider
|
||||
}
|
||||
|
||||
func (a *accountOIDC) flow(ctx context.Context) (identity.LoginFlow, *oidc.Verifier, error) {
|
||||
settings, err := a.settings.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if settings.PublicURL == "" {
|
||||
settings = a.fallback
|
||||
if a.fallbackFlow != nil {
|
||||
return a.fallbackFlow, oidc.NewVerifierForAudience(a.fallbackProvider, a.fallback.OIDCClientID), nil
|
||||
}
|
||||
}
|
||||
if settings.OIDCIssuer == "" {
|
||||
return nil, nil, identity.ErrNoCredential
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.provider == nil || a.current != settings {
|
||||
provider, err := oidc.NewProvider(oidc.Config{Issuer: settings.OIDCIssuer, Audience: settings.OIDCAudience})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
a.provider, a.current = provider, settings
|
||||
}
|
||||
flow, err := oidc.NewFlow(a.provider, settings.OIDCClientID, "", settings.PublicURL+"/oauth2/callback")
|
||||
return flow, oidc.NewVerifierForAudience(a.provider, settings.OIDCClientID), err
|
||||
}
|
||||
|
||||
func (a *accountOIDC) AuthenticateBrowser(ctx context.Context, credential string) (identity.Identity, error) {
|
||||
_, verifier, err := a.flow(ctx)
|
||||
if err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
value, _, err := identity.Authenticate(ctx, a.subjects, verifier, credential)
|
||||
return value, err
|
||||
}
|
||||
|
||||
func (a *accountOIDC) AuthCodeURL(ctx context.Context, state string) (string, string, error) {
|
||||
flow, _, err := a.flow(ctx)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return flow.AuthCodeURL(ctx, state)
|
||||
}
|
||||
|
||||
func (a *accountOIDC) Exchange(ctx context.Context, code, verifier string) (identity.ProviderSession, error) {
|
||||
flow, _, err := a.flow(ctx)
|
||||
if err != nil {
|
||||
return identity.ProviderSession{}, err
|
||||
}
|
||||
return flow.Exchange(ctx, code, verifier)
|
||||
}
|
||||
|
||||
func (a *accountOIDC) Authenticate(ctx context.Context, credential string) (identity.Identity, error) {
|
||||
if subject, ok := identity.PersonalTokenSubject(credential); ok {
|
||||
return identity.Resolve(ctx, a.subjects, identity.Credential{Subject: subject})
|
||||
}
|
||||
if _, _, err := a.flow(ctx); err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
provider := a.provider
|
||||
if provider == nil {
|
||||
provider = a.fallbackProvider
|
||||
}
|
||||
a.mu.Unlock()
|
||||
value, _, err := identity.Authenticate(ctx, a.subjects, oidc.NewVerifier(provider), credential)
|
||||
return value, err
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
package archieui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
@@ -20,25 +18,6 @@ func signInProvider(opts Options) (*oidc.Provider, error) {
|
||||
return oidc.NewProvider(oidc.Config{Issuer: opts.OidcIssuer, Audience: opts.OidcAudience})
|
||||
}
|
||||
|
||||
// dashboardAuthenticator builds the credential check, or nil when no provider
|
||||
// is configured.
|
||||
func dashboardAuthenticator(provider *oidc.Provider, opts Options, subjects identity.SubjectResolver, log *slog.Logger) func(context.Context, string) (identity.Identity, error) {
|
||||
if provider == nil {
|
||||
return nil
|
||||
}
|
||||
verifier := oidc.NewVerifier(provider)
|
||||
log.Info("dashboard authenticates provider credentials", "issuer", opts.OidcIssuer, "audience", opts.OidcAudience)
|
||||
return func(ctx context.Context, credential string) (identity.Identity, error) {
|
||||
// A personal token is bound in the State Store, not issued by the
|
||||
// provider, so it resolves without the provider's verifier.
|
||||
if subject, ok := identity.PersonalTokenSubject(credential); ok {
|
||||
return identity.Resolve(ctx, subjects, identity.Credential{Subject: subject})
|
||||
}
|
||||
value, _, err := identity.Authenticate(ctx, subjects, verifier, credential)
|
||||
return value, err
|
||||
}
|
||||
}
|
||||
|
||||
// dashboardLoginFlow builds the browser sign-in flow, or nil when not
|
||||
// configured. The client secret is read from the named env var.
|
||||
func dashboardLoginFlow(provider *oidc.Provider, opts Options) (identity.LoginFlow, error) {
|
||||
|
||||
@@ -38,7 +38,8 @@ type deps struct {
|
||||
Identities identity.Repository
|
||||
// Authenticate resolves a presented credential to the identity that may
|
||||
// act. Nil when no provider is configured, which keeps the shared token.
|
||||
Authenticate func(context.Context, string) (identity.Identity, error)
|
||||
Authenticate func(context.Context, string) (identity.Identity, error)
|
||||
AuthenticateBrowser func(context.Context, string) (identity.Identity, error)
|
||||
// Login drives the browser sign-in flow, or nil when no provider is
|
||||
// configured for it.
|
||||
Login identity.LoginFlow
|
||||
@@ -56,8 +57,8 @@ func compose(ctx context.Context, d deps) *webui.Server {
|
||||
srv := &webui.Server{
|
||||
Store: d.Store,
|
||||
Log: d.Log,
|
||||
Token: d.Options.Token,
|
||||
Authenticate: d.Authenticate,
|
||||
AuthenticateBrowser: d.AuthenticateBrowser,
|
||||
Login: d.Login,
|
||||
TrustForwardedHeaders: d.Options.trustForwardedHeaders(),
|
||||
Health: d.Health,
|
||||
@@ -134,6 +135,9 @@ func compose(ctx context.Context, d deps) *webui.Server {
|
||||
// wireOrgSurface attaches the dashboard's org surface when the state client
|
||||
// carries it.
|
||||
func wireOrgSurface(srv *webui.Server, store storecontract.TaskStore) {
|
||||
if accounts, ok := store.(identity.Accounts); ok {
|
||||
srv.Accounts = accounts
|
||||
}
|
||||
if orgs, ok := store.(org.API); ok {
|
||||
srv.Orgs = orgs
|
||||
}
|
||||
|
||||
@@ -34,11 +34,6 @@ func Resolve(o Options, log *slog.Logger) (Options, error) {
|
||||
return Options{}, err
|
||||
}
|
||||
o.identity = id
|
||||
token, err := resolveToken(o)
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
o.Token = token
|
||||
if err := o.validate(); err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
@@ -146,20 +141,7 @@ func withDefaults(o Options) Options {
|
||||
return o
|
||||
}
|
||||
|
||||
// resolveToken returns the dashboard token, minting and persisting one when
|
||||
// the operator named a token file and gave no token directly. Naming the file
|
||||
// is how a non-loopback listener opts in to a generated token instead of
|
||||
// being refused.
|
||||
func resolveToken(o Options) (string, error) {
|
||||
if o.Token != "" || o.TokenFile == "" {
|
||||
return o.Token, nil
|
||||
}
|
||||
return webui.LoadOrCreateToken(o.TokenFile)
|
||||
}
|
||||
|
||||
// Unlike the daemon, which mints a token silently, this process refuses to
|
||||
// start -- an operator who exposed the dashboard by accident learns about it
|
||||
// here rather than from the log.
|
||||
// Browser access is gated by accounts; service endpoints must still be configured.
|
||||
func (o Options) validate() error {
|
||||
if o.Gateway.Target == "" {
|
||||
return fmt.Errorf("gateway target is required (-gateway-target or [services.gateway].target)")
|
||||
@@ -167,12 +149,7 @@ func (o Options) validate() error {
|
||||
if o.State.Target == "" {
|
||||
return fmt.Errorf("state store target is required (-state-target or [services.state].target)")
|
||||
}
|
||||
if !webui.IsLoopback(o.Listen) && o.Token == "" {
|
||||
return fmt.Errorf(
|
||||
"ui listen address %q is non-loopback; a reachable dashboard requires a token (-token) or a token file to mint one (-token-file) (deployments/README.md, running the dashboard)",
|
||||
o.Listen,
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -37,15 +37,8 @@ type Options struct {
|
||||
|
||||
// Listen is the dashboard HTTP bind address.
|
||||
Listen string
|
||||
// Token gates browser access. Empty is permitted only for a loopback
|
||||
// listener; see Options.validate.
|
||||
Token string
|
||||
// TokenFile is where the dashboard token is persisted, minted on first
|
||||
// use. It is the explicit opt-in to a non-loopback listener: without it
|
||||
// a reachable bind must be given a token.
|
||||
TokenFile string
|
||||
// OidcIssuer and OidcAudience configure the identity provider. Both empty
|
||||
// keeps the shared token; an issuer without an audience is refused.
|
||||
// OidcIssuer and OidcAudience configure the identity provider. Local accounts remain available;
|
||||
// an issuer without an audience is refused.
|
||||
OidcIssuer string
|
||||
OidcAudience string
|
||||
// OidcClientID and OidcClientSecretEnv register the browser sign-in; the
|
||||
|
||||
@@ -10,11 +10,13 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/applystatus"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/presence"
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
@@ -73,25 +75,27 @@ func Run(ctx context.Context, options Options) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
authenticate := dashboardAuthenticator(provider, opts, tasks, log)
|
||||
|
||||
login, err := dashboardLoginFlow(provider, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
runtimeOIDC := &accountOIDC{settings: tasks, subjects: tasks, fallbackFlow: login, fallbackProvider: provider, fallback: identity.AuthenticationSettings{PublicURL: strings.TrimSuffix(opts.OidcRedirectURL, "/oauth2/callback"), OIDCIssuer: opts.OidcIssuer, OIDCAudience: opts.OidcAudience, OIDCClientID: opts.OidcClientID}}
|
||||
srv := compose(ctx, deps{
|
||||
Options: opts,
|
||||
Log: log,
|
||||
Store: tasks,
|
||||
Chat: chat,
|
||||
Updates: controlplanerpc.UpdateService(controlplanerpc.NewRPCClient(tasks.ControlPlane()), filepath.Join(configuration.DefaultWorkDir(), "ui-update-deferrals.json")),
|
||||
Health: newReadinessRegistry(opts, tasks, chat, chain, provider),
|
||||
ControlPlane: tasks.ControlPlane(),
|
||||
Identities: tasks,
|
||||
Authenticate: authenticate,
|
||||
Login: login,
|
||||
Access: chain,
|
||||
Principals: tasks,
|
||||
Denials: tasks,
|
||||
Options: opts,
|
||||
Log: log,
|
||||
Store: tasks,
|
||||
Chat: chat,
|
||||
Updates: controlplanerpc.UpdateService(controlplanerpc.NewRPCClient(tasks.ControlPlane()), filepath.Join(configuration.DefaultWorkDir(), "ui-update-deferrals.json")),
|
||||
Health: newReadinessRegistry(opts, tasks, chat, chain, provider),
|
||||
ControlPlane: tasks.ControlPlane(),
|
||||
Identities: tasks,
|
||||
Authenticate: runtimeOIDC.Authenticate,
|
||||
AuthenticateBrowser: runtimeOIDC.AuthenticateBrowser,
|
||||
Login: runtimeOIDC,
|
||||
Access: chain,
|
||||
Principals: tasks,
|
||||
Denials: tasks,
|
||||
})
|
||||
stopLogs, err := wireServiceLogs(opts, srv, tasks, chat, feed)
|
||||
if err != nil {
|
||||
@@ -118,11 +122,6 @@ func Run(ctx context.Context, options Options) error {
|
||||
"gateway", opts.Gateway.Target,
|
||||
"state", opts.State.Target,
|
||||
}
|
||||
// Name the file holding the token, never the token itself: this line
|
||||
// reaches the journal and any log an operator pastes.
|
||||
if opts.TokenFile != "" {
|
||||
attrs = append(attrs, "token_file", opts.TokenFile)
|
||||
}
|
||||
log.Info("archie-ui running", attrs...)
|
||||
return serve(ctx, listener, srv.Handler(), opts)
|
||||
}
|
||||
|
||||
@@ -403,6 +403,9 @@ func (b *server) callers() rpcidentity.Callers {
|
||||
// no tenant boundary yet -- degrades the access RPCs rather than failing the
|
||||
// boot, the same pattern the other optional surfaces use.
|
||||
func (b *server) accessDeps(deps *staterpc.Deps) {
|
||||
if accounts, ok := b.st.(identity.Accounts); ok {
|
||||
deps.Accounts = accounts
|
||||
}
|
||||
if ps, ok := b.st.(access.PrincipalSource); ok {
|
||||
deps.Principals = ps
|
||||
}
|
||||
|
||||
+2144
-342
File diff suppressed because it is too large.
Load diff
@@ -35,6 +35,22 @@ const (
|
||||
StateStoreService_RevokeTaskGrant_FullMethodName = "/state.v1.StateStoreService/RevokeTaskGrant"
|
||||
StateStoreService_ResolveTaskGrant_FullMethodName = "/state.v1.StateStoreService/ResolveTaskGrant"
|
||||
StateStoreService_ListIdentities_FullMethodName = "/state.v1.StateStoreService/ListIdentities"
|
||||
StateStoreService_GetAuthenticationSettings_FullMethodName = "/state.v1.StateStoreService/GetAuthenticationSettings"
|
||||
StateStoreService_SaveAuthenticationSettings_FullMethodName = "/state.v1.StateStoreService/SaveAuthenticationSettings"
|
||||
StateStoreService_BeginPasskey_FullMethodName = "/state.v1.StateStoreService/BeginPasskey"
|
||||
StateStoreService_FinishPasskey_FullMethodName = "/state.v1.StateStoreService/FinishPasskey"
|
||||
StateStoreService_ListPasskeys_FullMethodName = "/state.v1.StateStoreService/ListPasskeys"
|
||||
StateStoreService_DeletePasskey_FullMethodName = "/state.v1.StateStoreService/DeletePasskey"
|
||||
StateStoreService_OpenAccountSession_FullMethodName = "/state.v1.StateStoreService/OpenAccountSession"
|
||||
StateStoreService_RequireFreshAccountSession_FullMethodName = "/state.v1.StateStoreService/RequireFreshAccountSession"
|
||||
StateStoreService_CreateAccountRecovery_FullMethodName = "/state.v1.StateStoreService/CreateAccountRecovery"
|
||||
StateStoreService_RecoverAccount_FullMethodName = "/state.v1.StateStoreService/RecoverAccount"
|
||||
StateStoreService_AccountSetup_FullMethodName = "/state.v1.StateStoreService/AccountSetup"
|
||||
StateStoreService_RegisterAccount_FullMethodName = "/state.v1.StateStoreService/RegisterAccount"
|
||||
StateStoreService_SignInAccount_FullMethodName = "/state.v1.StateStoreService/SignInAccount"
|
||||
StateStoreService_ResolveAccountSession_FullMethodName = "/state.v1.StateStoreService/ResolveAccountSession"
|
||||
StateStoreService_SignOutAccount_FullMethodName = "/state.v1.StateStoreService/SignOutAccount"
|
||||
StateStoreService_ChangeAccountPassword_FullMethodName = "/state.v1.StateStoreService/ChangeAccountPassword"
|
||||
StateStoreService_GetIdentity_FullMethodName = "/state.v1.StateStoreService/GetIdentity"
|
||||
StateStoreService_CreateIdentity_FullMethodName = "/state.v1.StateStoreService/CreateIdentity"
|
||||
StateStoreService_RenameIdentity_FullMethodName = "/state.v1.StateStoreService/RenameIdentity"
|
||||
@@ -202,6 +218,22 @@ type StateStoreServiceClient interface {
|
||||
ResolveTaskGrant(ctx context.Context, in *ResolveTaskGrantRequest, opts ...grpc.CallOption) (*ResolveTaskGrantResponse, error)
|
||||
// Identity domain. Task-scoped grants cannot call these administrative RPCs.
|
||||
ListIdentities(ctx context.Context, in *ListIdentitiesRequest, opts ...grpc.CallOption) (*ListIdentitiesResponse, error)
|
||||
GetAuthenticationSettings(ctx context.Context, in *GetAuthenticationSettingsRequest, opts ...grpc.CallOption) (*GetAuthenticationSettingsResponse, error)
|
||||
SaveAuthenticationSettings(ctx context.Context, in *SaveAuthenticationSettingsRequest, opts ...grpc.CallOption) (*SaveAuthenticationSettingsResponse, error)
|
||||
BeginPasskey(ctx context.Context, in *BeginPasskeyRequest, opts ...grpc.CallOption) (*BeginPasskeyResponse, error)
|
||||
FinishPasskey(ctx context.Context, in *FinishPasskeyRequest, opts ...grpc.CallOption) (*FinishPasskeyResponse, error)
|
||||
ListPasskeys(ctx context.Context, in *ListPasskeysRequest, opts ...grpc.CallOption) (*ListPasskeysResponse, error)
|
||||
DeletePasskey(ctx context.Context, in *DeletePasskeyRequest, opts ...grpc.CallOption) (*DeletePasskeyResponse, error)
|
||||
OpenAccountSession(ctx context.Context, in *OpenAccountSessionRequest, opts ...grpc.CallOption) (*OpenAccountSessionResponse, error)
|
||||
RequireFreshAccountSession(ctx context.Context, in *RequireFreshAccountSessionRequest, opts ...grpc.CallOption) (*RequireFreshAccountSessionResponse, error)
|
||||
CreateAccountRecovery(ctx context.Context, in *CreateAccountRecoveryRequest, opts ...grpc.CallOption) (*CreateAccountRecoveryResponse, error)
|
||||
RecoverAccount(ctx context.Context, in *RecoverAccountRequest, opts ...grpc.CallOption) (*RecoverAccountResponse, error)
|
||||
AccountSetup(ctx context.Context, in *AccountSetupRequest, opts ...grpc.CallOption) (*AccountSetupResponse, error)
|
||||
RegisterAccount(ctx context.Context, in *RegisterAccountRequest, opts ...grpc.CallOption) (*RegisterAccountResponse, error)
|
||||
SignInAccount(ctx context.Context, in *SignInAccountRequest, opts ...grpc.CallOption) (*SignInAccountResponse, error)
|
||||
ResolveAccountSession(ctx context.Context, in *ResolveAccountSessionRequest, opts ...grpc.CallOption) (*ResolveAccountSessionResponse, error)
|
||||
SignOutAccount(ctx context.Context, in *SignOutAccountRequest, opts ...grpc.CallOption) (*SignOutAccountResponse, error)
|
||||
ChangeAccountPassword(ctx context.Context, in *ChangeAccountPasswordRequest, opts ...grpc.CallOption) (*ChangeAccountPasswordResponse, error)
|
||||
GetIdentity(ctx context.Context, in *GetIdentityRequest, opts ...grpc.CallOption) (*GetIdentityResponse, error)
|
||||
CreateIdentity(ctx context.Context, in *CreateIdentityRequest, opts ...grpc.CallOption) (*CreateIdentityResponse, error)
|
||||
RenameIdentity(ctx context.Context, in *RenameIdentityRequest, opts ...grpc.CallOption) (*RenameIdentityResponse, error)
|
||||
@@ -601,6 +633,166 @@ func (c *stateStoreServiceClient) ListIdentities(ctx context.Context, in *ListId
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) GetAuthenticationSettings(ctx context.Context, in *GetAuthenticationSettingsRequest, opts ...grpc.CallOption) (*GetAuthenticationSettingsResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetAuthenticationSettingsResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_GetAuthenticationSettings_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) SaveAuthenticationSettings(ctx context.Context, in *SaveAuthenticationSettingsRequest, opts ...grpc.CallOption) (*SaveAuthenticationSettingsResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(SaveAuthenticationSettingsResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_SaveAuthenticationSettings_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) BeginPasskey(ctx context.Context, in *BeginPasskeyRequest, opts ...grpc.CallOption) (*BeginPasskeyResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(BeginPasskeyResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_BeginPasskey_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) FinishPasskey(ctx context.Context, in *FinishPasskeyRequest, opts ...grpc.CallOption) (*FinishPasskeyResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(FinishPasskeyResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_FinishPasskey_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ListPasskeys(ctx context.Context, in *ListPasskeysRequest, opts ...grpc.CallOption) (*ListPasskeysResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ListPasskeysResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ListPasskeys_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) DeletePasskey(ctx context.Context, in *DeletePasskeyRequest, opts ...grpc.CallOption) (*DeletePasskeyResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(DeletePasskeyResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_DeletePasskey_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) OpenAccountSession(ctx context.Context, in *OpenAccountSessionRequest, opts ...grpc.CallOption) (*OpenAccountSessionResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(OpenAccountSessionResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_OpenAccountSession_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) RequireFreshAccountSession(ctx context.Context, in *RequireFreshAccountSessionRequest, opts ...grpc.CallOption) (*RequireFreshAccountSessionResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(RequireFreshAccountSessionResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_RequireFreshAccountSession_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) CreateAccountRecovery(ctx context.Context, in *CreateAccountRecoveryRequest, opts ...grpc.CallOption) (*CreateAccountRecoveryResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(CreateAccountRecoveryResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_CreateAccountRecovery_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) RecoverAccount(ctx context.Context, in *RecoverAccountRequest, opts ...grpc.CallOption) (*RecoverAccountResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(RecoverAccountResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_RecoverAccount_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) AccountSetup(ctx context.Context, in *AccountSetupRequest, opts ...grpc.CallOption) (*AccountSetupResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(AccountSetupResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_AccountSetup_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) RegisterAccount(ctx context.Context, in *RegisterAccountRequest, opts ...grpc.CallOption) (*RegisterAccountResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(RegisterAccountResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_RegisterAccount_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) SignInAccount(ctx context.Context, in *SignInAccountRequest, opts ...grpc.CallOption) (*SignInAccountResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(SignInAccountResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_SignInAccount_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ResolveAccountSession(ctx context.Context, in *ResolveAccountSessionRequest, opts ...grpc.CallOption) (*ResolveAccountSessionResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ResolveAccountSessionResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ResolveAccountSession_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) SignOutAccount(ctx context.Context, in *SignOutAccountRequest, opts ...grpc.CallOption) (*SignOutAccountResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(SignOutAccountResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_SignOutAccount_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ChangeAccountPassword(ctx context.Context, in *ChangeAccountPasswordRequest, opts ...grpc.CallOption) (*ChangeAccountPasswordResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ChangeAccountPasswordResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ChangeAccountPassword_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) GetIdentity(ctx context.Context, in *GetIdentityRequest, opts ...grpc.CallOption) (*GetIdentityResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetIdentityResponse)
|
||||
@@ -1900,6 +2092,22 @@ type StateStoreServiceServer interface {
|
||||
ResolveTaskGrant(context.Context, *ResolveTaskGrantRequest) (*ResolveTaskGrantResponse, error)
|
||||
// Identity domain. Task-scoped grants cannot call these administrative RPCs.
|
||||
ListIdentities(context.Context, *ListIdentitiesRequest) (*ListIdentitiesResponse, error)
|
||||
GetAuthenticationSettings(context.Context, *GetAuthenticationSettingsRequest) (*GetAuthenticationSettingsResponse, error)
|
||||
SaveAuthenticationSettings(context.Context, *SaveAuthenticationSettingsRequest) (*SaveAuthenticationSettingsResponse, error)
|
||||
BeginPasskey(context.Context, *BeginPasskeyRequest) (*BeginPasskeyResponse, error)
|
||||
FinishPasskey(context.Context, *FinishPasskeyRequest) (*FinishPasskeyResponse, error)
|
||||
ListPasskeys(context.Context, *ListPasskeysRequest) (*ListPasskeysResponse, error)
|
||||
DeletePasskey(context.Context, *DeletePasskeyRequest) (*DeletePasskeyResponse, error)
|
||||
OpenAccountSession(context.Context, *OpenAccountSessionRequest) (*OpenAccountSessionResponse, error)
|
||||
RequireFreshAccountSession(context.Context, *RequireFreshAccountSessionRequest) (*RequireFreshAccountSessionResponse, error)
|
||||
CreateAccountRecovery(context.Context, *CreateAccountRecoveryRequest) (*CreateAccountRecoveryResponse, error)
|
||||
RecoverAccount(context.Context, *RecoverAccountRequest) (*RecoverAccountResponse, error)
|
||||
AccountSetup(context.Context, *AccountSetupRequest) (*AccountSetupResponse, error)
|
||||
RegisterAccount(context.Context, *RegisterAccountRequest) (*RegisterAccountResponse, error)
|
||||
SignInAccount(context.Context, *SignInAccountRequest) (*SignInAccountResponse, error)
|
||||
ResolveAccountSession(context.Context, *ResolveAccountSessionRequest) (*ResolveAccountSessionResponse, error)
|
||||
SignOutAccount(context.Context, *SignOutAccountRequest) (*SignOutAccountResponse, error)
|
||||
ChangeAccountPassword(context.Context, *ChangeAccountPasswordRequest) (*ChangeAccountPasswordResponse, error)
|
||||
GetIdentity(context.Context, *GetIdentityRequest) (*GetIdentityResponse, error)
|
||||
CreateIdentity(context.Context, *CreateIdentityRequest) (*CreateIdentityResponse, error)
|
||||
RenameIdentity(context.Context, *RenameIdentityRequest) (*RenameIdentityResponse, error)
|
||||
@@ -2187,6 +2395,54 @@ func (UnimplementedStateStoreServiceServer) ResolveTaskGrant(context.Context, *R
|
||||
func (UnimplementedStateStoreServiceServer) ListIdentities(context.Context, *ListIdentitiesRequest) (*ListIdentitiesResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ListIdentities not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) GetAuthenticationSettings(context.Context, *GetAuthenticationSettingsRequest) (*GetAuthenticationSettingsResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method GetAuthenticationSettings not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) SaveAuthenticationSettings(context.Context, *SaveAuthenticationSettingsRequest) (*SaveAuthenticationSettingsResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method SaveAuthenticationSettings not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) BeginPasskey(context.Context, *BeginPasskeyRequest) (*BeginPasskeyResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method BeginPasskey not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) FinishPasskey(context.Context, *FinishPasskeyRequest) (*FinishPasskeyResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method FinishPasskey not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ListPasskeys(context.Context, *ListPasskeysRequest) (*ListPasskeysResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ListPasskeys not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) DeletePasskey(context.Context, *DeletePasskeyRequest) (*DeletePasskeyResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method DeletePasskey not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) OpenAccountSession(context.Context, *OpenAccountSessionRequest) (*OpenAccountSessionResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method OpenAccountSession not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) RequireFreshAccountSession(context.Context, *RequireFreshAccountSessionRequest) (*RequireFreshAccountSessionResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method RequireFreshAccountSession not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) CreateAccountRecovery(context.Context, *CreateAccountRecoveryRequest) (*CreateAccountRecoveryResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method CreateAccountRecovery not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) RecoverAccount(context.Context, *RecoverAccountRequest) (*RecoverAccountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method RecoverAccount not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) AccountSetup(context.Context, *AccountSetupRequest) (*AccountSetupResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method AccountSetup not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) RegisterAccount(context.Context, *RegisterAccountRequest) (*RegisterAccountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method RegisterAccount not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) SignInAccount(context.Context, *SignInAccountRequest) (*SignInAccountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method SignInAccount not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ResolveAccountSession(context.Context, *ResolveAccountSessionRequest) (*ResolveAccountSessionResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ResolveAccountSession not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) SignOutAccount(context.Context, *SignOutAccountRequest) (*SignOutAccountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method SignOutAccount not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ChangeAccountPassword(context.Context, *ChangeAccountPasswordRequest) (*ChangeAccountPasswordResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ChangeAccountPassword not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) GetIdentity(context.Context, *GetIdentityRequest) (*GetIdentityResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method GetIdentity not implemented")
|
||||
}
|
||||
@@ -2865,6 +3121,294 @@ func _StateStoreService_ListIdentities_Handler(srv interface{}, ctx context.Cont
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_GetAuthenticationSettings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetAuthenticationSettingsRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).GetAuthenticationSettings(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_GetAuthenticationSettings_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).GetAuthenticationSettings(ctx, req.(*GetAuthenticationSettingsRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_SaveAuthenticationSettings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SaveAuthenticationSettingsRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).SaveAuthenticationSettings(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_SaveAuthenticationSettings_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).SaveAuthenticationSettings(ctx, req.(*SaveAuthenticationSettingsRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_BeginPasskey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(BeginPasskeyRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).BeginPasskey(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_BeginPasskey_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).BeginPasskey(ctx, req.(*BeginPasskeyRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_FinishPasskey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(FinishPasskeyRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).FinishPasskey(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_FinishPasskey_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).FinishPasskey(ctx, req.(*FinishPasskeyRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ListPasskeys_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ListPasskeysRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ListPasskeys(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ListPasskeys_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ListPasskeys(ctx, req.(*ListPasskeysRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_DeletePasskey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(DeletePasskeyRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).DeletePasskey(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_DeletePasskey_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).DeletePasskey(ctx, req.(*DeletePasskeyRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_OpenAccountSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(OpenAccountSessionRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).OpenAccountSession(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_OpenAccountSession_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).OpenAccountSession(ctx, req.(*OpenAccountSessionRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_RequireFreshAccountSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(RequireFreshAccountSessionRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).RequireFreshAccountSession(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_RequireFreshAccountSession_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).RequireFreshAccountSession(ctx, req.(*RequireFreshAccountSessionRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_CreateAccountRecovery_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(CreateAccountRecoveryRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).CreateAccountRecovery(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_CreateAccountRecovery_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).CreateAccountRecovery(ctx, req.(*CreateAccountRecoveryRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_RecoverAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(RecoverAccountRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).RecoverAccount(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_RecoverAccount_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).RecoverAccount(ctx, req.(*RecoverAccountRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_AccountSetup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(AccountSetupRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).AccountSetup(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_AccountSetup_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).AccountSetup(ctx, req.(*AccountSetupRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_RegisterAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(RegisterAccountRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).RegisterAccount(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_RegisterAccount_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).RegisterAccount(ctx, req.(*RegisterAccountRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_SignInAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SignInAccountRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).SignInAccount(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_SignInAccount_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).SignInAccount(ctx, req.(*SignInAccountRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ResolveAccountSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ResolveAccountSessionRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ResolveAccountSession(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ResolveAccountSession_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ResolveAccountSession(ctx, req.(*ResolveAccountSessionRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_SignOutAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SignOutAccountRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).SignOutAccount(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_SignOutAccount_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).SignOutAccount(ctx, req.(*SignOutAccountRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ChangeAccountPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ChangeAccountPasswordRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ChangeAccountPassword(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ChangeAccountPassword_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ChangeAccountPassword(ctx, req.(*ChangeAccountPasswordRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_GetIdentity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetIdentityRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -5129,6 +5673,70 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "ListIdentities",
|
||||
Handler: _StateStoreService_ListIdentities_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetAuthenticationSettings",
|
||||
Handler: _StateStoreService_GetAuthenticationSettings_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SaveAuthenticationSettings",
|
||||
Handler: _StateStoreService_SaveAuthenticationSettings_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "BeginPasskey",
|
||||
Handler: _StateStoreService_BeginPasskey_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "FinishPasskey",
|
||||
Handler: _StateStoreService_FinishPasskey_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ListPasskeys",
|
||||
Handler: _StateStoreService_ListPasskeys_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "DeletePasskey",
|
||||
Handler: _StateStoreService_DeletePasskey_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "OpenAccountSession",
|
||||
Handler: _StateStoreService_OpenAccountSession_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "RequireFreshAccountSession",
|
||||
Handler: _StateStoreService_RequireFreshAccountSession_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "CreateAccountRecovery",
|
||||
Handler: _StateStoreService_CreateAccountRecovery_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "RecoverAccount",
|
||||
Handler: _StateStoreService_RecoverAccount_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "AccountSetup",
|
||||
Handler: _StateStoreService_AccountSetup_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "RegisterAccount",
|
||||
Handler: _StateStoreService_RegisterAccount_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SignInAccount",
|
||||
Handler: _StateStoreService_SignInAccount_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ResolveAccountSession",
|
||||
Handler: _StateStoreService_ResolveAccountSession_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SignOutAccount",
|
||||
Handler: _StateStoreService_SignOutAccount_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ChangeAccountPassword",
|
||||
Handler: _StateStoreService_ChangeAccountPassword_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetIdentity",
|
||||
Handler: _StateStoreService_GetIdentity_Handler,
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrSetupComplete = errors.New("administrator has already been set up")
|
||||
|
||||
const AccountSessionLifetime = 7 * 24 * time.Hour
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
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 ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type AccountSession struct {
|
||||
Identity Identity
|
||||
Token string
|
||||
Expires time.Time
|
||||
}
|
||||
|
||||
// Accounts is served by the State Store. Account creation after bootstrap is
|
||||
// administrative; password changes always address the caller's own identity.
|
||||
type Accounts interface {
|
||||
AccountSetupRequired(context.Context) (bool, error)
|
||||
RegisterAccount(context.Context, AccountRegistration, bool) (Identity, error)
|
||||
SignInAccount(context.Context, string, string) (AccountSession, error)
|
||||
ResolveAccountSession(context.Context, string) (Identity, error)
|
||||
SignOutAccount(context.Context, string) error
|
||||
ChangeAccountPassword(context.Context, string, string) error
|
||||
}
|
||||
|
||||
// AccountSecurity guards authenticator changes with recent authentication and
|
||||
// provides a one-use recovery secret without relying on outbound email.
|
||||
type AccountSecurity interface {
|
||||
OpenAccountSession(context.Context, time.Time) (AccountSession, error)
|
||||
RequireFreshAccountSession(context.Context, string) error
|
||||
CreateAccountRecovery(context.Context) (string, error)
|
||||
RecoverAccount(context.Context, string, string, string) error
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type AuthenticationSettings struct {
|
||||
PublicURL string `json:"public_url"`
|
||||
OIDCIssuer string `json:"oidc_issuer"`
|
||||
OIDCAudience string `json:"oidc_audience"`
|
||||
OIDCClientID string `json:"oidc_client_id"`
|
||||
}
|
||||
|
||||
func (s AuthenticationSettings) Validate() error {
|
||||
if !validInstanceOrigin(s.PublicURL) {
|
||||
return ErrInvalid
|
||||
}
|
||||
if s.OIDCIssuer == "" {
|
||||
if s.OIDCClientID != "" || s.OIDCAudience != "" {
|
||||
return ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !validProviderIssuer(s.OIDCIssuer) || strings.TrimSpace(s.OIDCClientID) == "" || strings.TrimSpace(s.OIDCAudience) == "" {
|
||||
return ErrInvalid
|
||||
}
|
||||
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")
|
||||
}
|
||||
|
||||
type AuthenticationSettingsStore interface {
|
||||
AuthenticationSettings(context.Context) (AuthenticationSettings, error)
|
||||
SaveAuthenticationSettings(context.Context, AuthenticationSettings) error
|
||||
}
|
||||
|
||||
type Passkey struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type PasskeyCeremony struct {
|
||||
Token string
|
||||
Options []byte
|
||||
}
|
||||
|
||||
type Passkeys interface {
|
||||
BeginPasskey(context.Context, bool) (PasskeyCeremony, error)
|
||||
FinishPasskey(context.Context, string, []byte, bool, string) (AccountSession, error)
|
||||
ListPasskeys(context.Context) ([]Passkey, error)
|
||||
DeletePasskey(context.Context, string) error
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package identity
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAuthenticationSettingsRejectUntrustedOrigins(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, url, issuer, client, audience string
|
||||
want bool
|
||||
}{
|
||||
{name: "public TLS", url: "https://archie.example", want: true},
|
||||
{name: "localhost", url: "http://localhost:8484", want: true},
|
||||
{name: "userinfo is not an origin", url: "https://user:password@archie.example", want: false},
|
||||
{name: "URL path cannot change the RP origin", url: "https://archie.example/subpath", want: false},
|
||||
{name: "query is not an origin", url: "https://archie.example?token=1", want: false},
|
||||
{name: "complete provider", url: "https://archie.example", issuer: "https://identity.example", client: "archie", audience: "archie", want: true},
|
||||
{name: "remote insecure provider", url: "https://archie.example", issuer: "http://identity.example", client: "archie", audience: "archie", want: false},
|
||||
{name: "issuer without client", url: "https://archie.example", issuer: "https://identity.example", audience: "archie", want: false},
|
||||
{name: "audience without provider", url: "https://archie.example", audience: "archie", want: false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := (AuthenticationSettings{PublicURL: tc.url, OIDCIssuer: tc.issuer, OIDCClientID: tc.client, OIDCAudience: tc.audience}).Validate()
|
||||
if (err == nil) != tc.want {
|
||||
t.Fatalf("validation err=%v, allowed=%v", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
package identity
|
||||
|
||||
// Known common passwords at or above the minimum length, from the NCSC
|
||||
// list in SecLists. Shorter entries are rejected by the length rule.
|
||||
// Source: https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/100k-most-used-passwords-NCSC.txt
|
||||
//
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2018 Daniel Miessler
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
const commonPasswords = `
|
||||
$hex[687474703a2f2f616473]
|
||||
$hex[687474703a2f2f777777]
|
||||
000000000000000
|
||||
00000000000000000000
|
||||
010203040506070809
|
||||
102030405060708090
|
||||
111111111111111
|
||||
11111111111111111111
|
||||
111111prof_root2.sql.txt:,
|
||||
111111prof_root3.sql.txt:,
|
||||
111222333444555
|
||||
1122334455667788
|
||||
112233445566778899
|
||||
11223344556677889900
|
||||
1213141516171819
|
||||
122333444455555
|
||||
123123123123123
|
||||
123451234512345
|
||||
1234567812345678
|
||||
1234567887654321
|
||||
12345678900987654321
|
||||
123456789012345
|
||||
1234567890123456
|
||||
12345678901234567890
|
||||
1234567890987654321
|
||||
1234567890qwert
|
||||
1234567890qwerty
|
||||
1234567890qwertyuiop
|
||||
123456789101112
|
||||
123456789123456
|
||||
1234567891234567
|
||||
123456789123456789
|
||||
12345678987654321
|
||||
123456789987654
|
||||
1234567899876543
|
||||
123456789987654321
|
||||
123456789qwerty
|
||||
123456789qwertyuio
|
||||
123456789qwertyuiop
|
||||
123456789zxcvbnm
|
||||
12345678qwertyui
|
||||
123456prof_root2.sql.txt:,
|
||||
123456prof_root3.sql.txt:,
|
||||
12345qwertasdfg
|
||||
1234qwerasdfzxcv
|
||||
1324354657687980
|
||||
1q2w3e4r5t6y7u8
|
||||
1q2w3e4r5t6y7u8i
|
||||
1q2w3e4r5t6y7u8i9o
|
||||
1q2w3e4r5t6y7u8i9o0p
|
||||
1qa2ws3ed4rf5tg
|
||||
1qaz2wsx3edc4rfv
|
||||
1qaz2wsx3edc4rfv5tgb
|
||||
1qazxsw23edcvfr4
|
||||
30secondstomars
|
||||
5.254.105.20:test
|
||||
5.254.105.20:test1
|
||||
555555555555555
|
||||
6666666666empulgara
|
||||
79621601378.kirill
|
||||
827ccb0eea8a706c4c
|
||||
9121318barssuki
|
||||
987654321123456789
|
||||
???????????????
|
||||
@elit-centr.com.ua
|
||||
aaaaaaaaaaaaaaa
|
||||
aaaaaaaaaaaaaaaa
|
||||
abuse_123456_abuse
|
||||
aleksandr.ustinov.2012
|
||||
aleksej.shorin.86
|
||||
alena_plotnikova_1995
|
||||
aliya.mutallapova
|
||||
andrey.shalanov
|
||||
andreyka.gorshkov.98
|
||||
andreyka.zhilin.1981
|
||||
anna.savickaya.1986
|
||||
antsiferova1973
|
||||
antusenok_zhekonya
|
||||
apalkova.tatiana
|
||||
aqwleeb_6e0pk59
|
||||
arina-sharapova-80
|
||||
arividerchi_shatalov
|
||||
armyach-aleksandra
|
||||
arsik-di-noxcho95
|
||||
asdfghjkl:':
|
||||
asdfghjkl;'
|
||||
asdfghjklzxcvbnm
|
||||
asil.dovlatov.1982
|
||||
avengedsevenfold
|
||||
azefirov.inno1987.r
|
||||
bad_boys_adience
|
||||
bakuman.manga.drawing
|
||||
beloved_a_devil
|
||||
blackangel09021
|
||||
blckd_sa_unpaidfee_oct06
|
||||
californication
|
||||
ceckbrcerfkbxyjcnm2
|
||||
cod12qw75rqyi59n
|
||||
constance626boilard1987
|
||||
cristianoronaldo
|
||||
d1bd6bc58c1d74df41a957489c9942f5
|
||||
d41d8cd98f00b204e980
|
||||
damira.shagabutdinova
|
||||
default_password
|
||||
demon1q2w3e4r5t
|
||||
denis_nazarenko
|
||||
dimulya.vasilenko
|
||||
dmitrij.mironov2014
|
||||
doomsayer.2.7mords.v
|
||||
doomsayer.2.7mords.vv
|
||||
dovbeshkosushova.1972
|
||||
drm199019902323
|
||||
e10adc3949ba59abbe56
|
||||
eremei_vasechkin
|
||||
etravelmoleoptin
|
||||
evgenii-shenderovich
|
||||
familiyafamiliya
|
||||
fiammalex1@hotmail.it
|
||||
fjodorova-natashenka
|
||||
friendofarriane
|
||||
friendofearning$1
|
||||
friendofeveryemailyouproc
|
||||
friendofthenext18peoplew
|
||||
friendofyoucanmake$200-
|
||||
gadjieva.gulmira
|
||||
galatasaray1905
|
||||
galina-davidyuk
|
||||
galinka_korneeva
|
||||
gayassfagpastebinleaks
|
||||
goderdzikarxjxv
|
||||
golovizina_elena
|
||||
guldaniya.galina
|
||||
gygypyfyyyposhy
|
||||
hallucinationse
|
||||
hd764nw5d7e1vb1
|
||||
hermina617berno1990f6i
|
||||
holidaysecure123
|
||||
holidaysecure123$
|
||||
htt//members.cumfiesta.com/
|
||||
hugo854lataille1988
|
||||
ignatova_1978_09
|
||||
ijfrnhf7yhcy54bhy0cd
|
||||
inactive1996aug
|
||||
ivankaterinchenko
|
||||
jafjkshf7y6w34rjd
|
||||
john!20130605at1753
|
||||
julia_eduardovna
|
||||
juliadronina1996
|
||||
kamazist.tsobenko
|
||||
kartoffelpuffer
|
||||
kikugalanetroot
|
||||
kinyabuzova.eleonora
|
||||
kirienko_svetlana
|
||||
kirik26trimyasov
|
||||
kirill.kirillov.2013
|
||||
korostelev_3333
|
||||
kotovichvalentina
|
||||
ksyusha.kulagina.91
|
||||
kudryavcevavalya
|
||||
kurmangazieva_gulmira
|
||||
kuznecovviktorr
|
||||
lady.procenko71
|
||||
len_rin_kagamine_02
|
||||
lexaafanasiev84
|
||||
lhbjkjubz2957704
|
||||
lightpower12345
|
||||
linkedinlinkedin
|
||||
linkedinpassword
|
||||
listopad.iuliia
|
||||
macegorova.mariya
|
||||
maitland571ka1994
|
||||
maks.abramov.99.99
|
||||
maksim.bychkov.1986
|
||||
maksimilian_nasirov
|
||||
malhotra493ozzy1991282151
|
||||
manchesterunited
|
||||
mandds1mg6bv8re
|
||||
maria-demidchik
|
||||
mariagoncharenko
|
||||
marina.shapovalo
|
||||
marina.ushakovaznuv
|
||||
marina_stryazhkova
|
||||
marinadeduxinaa
|
||||
marinaorlova1991
|
||||
marinochka.zhelannaya
|
||||
masloboinikova1987
|
||||
maximova_elena77
|
||||
migrationsandeep
|
||||
migrationschool
|
||||
mihail_alekseevskiy406
|
||||
mihailpezhemskii
|
||||
milankasanakoeva
|
||||
mirellabroersma1987570
|
||||
miss-evgeniya-93
|
||||
miss.marina.nikolaeva.2013
|
||||
mknaxhxeh8yp3tf
|
||||
morozovavalya28
|
||||
mozellbranou81e
|
||||
mutalim.gusenov
|
||||
mychemicalromance
|
||||
narashchivaiunoghti
|
||||
nastyaanciferova
|
||||
natalya.dmitrieva.1978
|
||||
nati.beridze.92
|
||||
never_desponding
|
||||
neworleans12345
|
||||
nikolay_thebest
|
||||
oksanaorgadykova
|
||||
olesya.kolchina
|
||||
olga.kazakova_85
|
||||
olga.ponomarenko.2012
|
||||
olga.rumyanceva.1985
|
||||
olgha.pietrova.1979
|
||||
password1234567
|
||||
password12345678
|
||||
password123456789
|
||||
passwordpassword
|
||||
pletnevakaterina
|
||||
polniypizdec0211
|
||||
polniypizdec1102
|
||||
polniypizdec110211
|
||||
professionaltools
|
||||
prosto_chelkynchik
|
||||
q1w2e3r4t5y6u7i8
|
||||
q1w2e3r4t5y6u7i8o9
|
||||
q1w2e3r4t5y6u7i8o9p0
|
||||
qazwsxedcrfvtgb
|
||||
qwertasdfgzxcvb
|
||||
qwerty123456789
|
||||
qwerty1234567890
|
||||
qwertyuiop12345
|
||||
qwertyuiop123456
|
||||
qwertyuiop123456789
|
||||
qwertyuiop1234567890
|
||||
qwertyuiopasdfg
|
||||
qwertyuiopasdfghjkl
|
||||
qwertyuiopasdfghjkl151515
|
||||
qwertyuiopasdfghjklzxcvbnm
|
||||
r6a50de3ujwtog4
|
||||
rachelle289ariyoshi5251987
|
||||
rashaun966krager1993
|
||||
raymonde336schwegel7331987
|
||||
regawf7ss1dm7rn
|
||||
rendakova_sveta
|
||||
riwr2hky4w3tjgg
|
||||
rkamkin.karoli1988mp
|
||||
romanova.natalya.96
|
||||
rtertuy77ijyhu7i
|
||||
sataieva.elinka
|
||||
sdf7asdf6asdg8df
|
||||
sdf7asdf6asdg8df1
|
||||
sergeevna_10.10.91
|
||||
sergey-personal
|
||||
sergey.lushnikoff
|
||||
sergey.melnik-1996
|
||||
sergio-emperior
|
||||
shakmakovataisiya1992
|
||||
shaquillesecx10
|
||||
sharmaine005foskett6071988
|
||||
shea019bernabei1992
|
||||
sheba417yorck1986vxm7
|
||||
shukurova-ismigu
|
||||
siiifonjiknalivai
|
||||
silakova.nadezhda.2012
|
||||
simonova_lyudmila_73
|
||||
simonovskiy1970
|
||||
sirazhdinov.shamil
|
||||
slava_kulbidyuk
|
||||
sofya.kulikova.87
|
||||
soloveibormalei
|
||||
somanypickles27
|
||||
sorokina-999-01
|
||||
spiridonmarkin1982
|
||||
spring938burston0001990
|
||||
srcuqq1_2j1h3rbf
|
||||
stalker_lemurrr
|
||||
stas.gorodissky
|
||||
stas_the_best.ru
|
||||
stefangreil1983
|
||||
stepanov_georgij
|
||||
sulamifcherenchikova1979
|
||||
svetik_kryuchkov
|
||||
svetlana-mironova-13
|
||||
tagesgruppe2010
|
||||
thisismypassword
|
||||
travelmoleoptin
|
||||
vadyusha.isaev.83
|
||||
valentina.victoria
|
||||
valya-valya-1982
|
||||
valya.klimenko.87
|
||||
valya.korobeynik
|
||||
valya.kryuchkova.1990
|
||||
valya.lantux.83
|
||||
varfolomeeva0990
|
||||
varida.alibaeva
|
||||
veralipatnikova
|
||||
victor_evdokimov
|
||||
victor_sakhalin1990-20
|
||||
victoria-berkat-energo
|
||||
victoria-dyatlova
|
||||
victoria392eliezrie1992frp
|
||||
victoria_shkurco
|
||||
vika.krivonos.1995
|
||||
vkovshut_annab1988fg
|
||||
vks1zz9v_7ceu69
|
||||
vladcherktecktonik
|
||||
volfram.kozlov123633
|
||||
volfram.kozlov173902
|
||||
volgograd.orlovka
|
||||
volkova.elena.13
|
||||
volkova.ksyusha.89
|
||||
volodina.elena66
|
||||
volodya-ivanov-63
|
||||
volokitina.olga
|
||||
voroshilova.liliya
|
||||
worldofwarcraft
|
||||
wwwksenechkawww
|
||||
yegbpltw2012lol
|
||||
yfdbufnjh10305070
|
||||
yulia-dubrovina
|
||||
yushinazena2009
|
||||
zabloczkaya2012
|
||||
zabolotneva_ira
|
||||
zabolotnova31337
|
||||
zarina_sabirova
|
||||
zarinaismailova
|
||||
zxcvbnm123456789
|
||||
zxcvbnmasdfghjkl
|
||||
пїѕпїѕпїѕпїѕпїѕпїѕ@mail.ru
|
||||
`
|
||||
@@ -0,0 +1,47 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// HashPassword uses the OWASP Argon2id minimum with a fresh salt.
|
||||
func HashPassword(password string) (string, error) {
|
||||
if utf8.RuneCountInString(password) < 15 || len(password) > 1024 {
|
||||
return "", fmt.Errorf("%w: password must have at least 15 characters and at most 1024 bytes", ErrInvalid)
|
||||
}
|
||||
if strings.Contains(commonPasswords, "\n"+strings.ToLower(password)+"\n") {
|
||||
return "", fmt.Errorf("%w: choose a password that is not commonly used", ErrInvalid)
|
||||
}
|
||||
var salt [16]byte
|
||||
if _, err := rand.Read(salt[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
key := argon2.IDKey([]byte(password), salt[:], 2, 19*1024, 1, 32)
|
||||
return "$argon2id$v=19$m=19456,t=2,p=1$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
// VerifyPassword accepts only parameters this application produces, bounding
|
||||
// the work even if a stored hash is corrupted.
|
||||
func VerifyPassword(password, hash string) bool {
|
||||
parts := strings.Split(hash, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" || parts[3] != "m=19456,t=2,p=1" || len(password) > 1024 {
|
||||
return false
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) != 16 {
|
||||
return false
|
||||
}
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(expected) != 32 {
|
||||
return false
|
||||
}
|
||||
key := argon2.IDKey([]byte(password), salt, 2, 19*1024, 1, 32)
|
||||
return subtle.ConstantTimeCompare(key, expected) == 1
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPasswordVerification(t *testing.T) {
|
||||
hash, err := HashPassword("a sufficiently long password")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, password, hash string
|
||||
want bool
|
||||
}{
|
||||
{"correct", "a sufficiently long password", hash, true},
|
||||
{"wrong", "a different long password", hash, false},
|
||||
{"malformed", "a sufficiently long password", "bad", false},
|
||||
{"unbounded parameters", "password", "$argon2id$v=19$m=999999999,t=2,p=1$c2FsdA$aGFzaA", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := VerifyPassword(tc.password, tc.hash); got != tc.want {
|
||||
t.Fatalf("verification = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, password := range []string{"short", strings.Repeat("a", 1025), "123456789012345", "passwordpassword"} {
|
||||
if _, err := HashPassword(password); err == nil {
|
||||
t.Fatal("accepted invalid password length")
|
||||
}
|
||||
}
|
||||
second, err := HashPassword("a sufficiently long password")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if hash == second {
|
||||
t.Fatal("password hashes reuse salts")
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,10 @@ type DashboardPage struct {
|
||||
var dashboardPages = []DashboardPage{
|
||||
{Path: "/", Label: "Dashboard", Description: "Running work, work needing attention, token spend."},
|
||||
{Path: "/tasks", Label: "Tasks", Description: "Picked-up issues and their status."},
|
||||
{Path: "/account", Label: "Your account", Description: "Password, recovery code and passkeys."},
|
||||
{Path: "/org", Label: "Organisation", Description: "Members, local accounts and organization roles."},
|
||||
{Path: "/settings/authentication", Label: "Authentication", Description: "Instance URL and OIDC sign-in."},
|
||||
{Path: "/settings/playbooks", Label: "Playbooks", Description: "Edit event-driven automation rules."},
|
||||
{Path: "/workflows", Label: "Workflows", Description: "Workflows and run history."},
|
||||
{Path: "/settings/skills", Label: "Skills", Description: "Skills Archie can activate."},
|
||||
{Path: "/settings/curators", Label: "Curators", Description: "Scheduled memory and capture curation."},
|
||||
@@ -60,7 +64,8 @@ func DashboardPages() []DashboardPage {
|
||||
// PageIndexResult is what page_index returns: the full list of dashboard pages
|
||||
// and what each one shows, so the agent can answer where to go.
|
||||
type PageIndexResult struct {
|
||||
Pages []DashboardPage `json:"pages"`
|
||||
Pages []DashboardPage `json:"pages"`
|
||||
ProductGuide string `json:"product_guide"`
|
||||
}
|
||||
|
||||
// pageIndexTool returns the tool that lists every dashboard page. It is only
|
||||
@@ -70,10 +75,10 @@ func pageIndexTool() (tools.ToolEntry, bool) {
|
||||
entry := tools.ToolEntry{
|
||||
Name: "page_index",
|
||||
Toolset: "dashboard",
|
||||
Description: "List every dashboard page and, in one line, what it shows. Use it to tell the operator where to go for something rather than guessing.",
|
||||
Description: "List every dashboard page, what it shows, and built-in guidance for creating workflows and using Archie. Use it to tell the operator where to go for something rather than guessing.",
|
||||
Classification: tools.ClassIdempotent,
|
||||
Handler: func(_ context.Context, _ map[string]any) (any, error) {
|
||||
return PageIndexResult{Pages: DashboardPages()}, nil
|
||||
return PageIndexResult{Pages: DashboardPages(), ProductGuide: productGuide}, nil
|
||||
},
|
||||
}
|
||||
return entry, true
|
||||
|
||||
+18
-13
@@ -10,6 +10,9 @@ import (
|
||||
//go:embed templates/archie.md.tpl
|
||||
var archiePromptTpl string
|
||||
|
||||
//go:embed templates/product-guide.md
|
||||
var productGuide string
|
||||
|
||||
// ToolSummary is the capability metadata for one registered tool, as it is
|
||||
// advertised to the model.
|
||||
type ToolSummary struct {
|
||||
@@ -66,7 +69,8 @@ type SystemPromptConfig struct {
|
||||
// calling methods during rendering.
|
||||
type promptData struct {
|
||||
SystemPromptConfig
|
||||
Date string
|
||||
Date string
|
||||
ProductGuide string
|
||||
}
|
||||
|
||||
// escapeXML replaces the three bytes that would otherwise be read as markup
|
||||
@@ -95,18 +99,19 @@ func BuildSystemPrompt(cfg SystemPromptConfig) string {
|
||||
}
|
||||
}
|
||||
data := promptData{
|
||||
Soul: cfg.Soul,
|
||||
Tools: tools,
|
||||
Channel: cfg.Channel,
|
||||
Model: cfg.Model,
|
||||
SessionID: cfg.SessionID,
|
||||
Page: cfg.Page,
|
||||
Now: cfg.Now,
|
||||
Date: cfg.Now.Format("2006-01-02"),
|
||||
Workspace: cfg.Workspace,
|
||||
Repos: cfg.Repos,
|
||||
Operator: cfg.Operator,
|
||||
Memory: cfg.Memory,
|
||||
Soul: cfg.Soul,
|
||||
Tools: tools,
|
||||
Channel: cfg.Channel,
|
||||
Model: cfg.Model,
|
||||
SessionID: cfg.SessionID,
|
||||
Page: cfg.Page,
|
||||
Now: cfg.Now,
|
||||
Date: cfg.Now.Format("2006-01-02"),
|
||||
Workspace: cfg.Workspace,
|
||||
Repos: cfg.Repos,
|
||||
Operator: cfg.Operator,
|
||||
Memory: cfg.Memory,
|
||||
ProductGuide: productGuide,
|
||||
}
|
||||
var buf strings.Builder
|
||||
if err := archiePromptTemplate.Execute(&buf, data); err != nil {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
@@ -40,6 +41,9 @@ func (s *postgresSessionStore) Close() error {
|
||||
// ── Sessions ────────────────────────────────────────────────────────────────
|
||||
|
||||
func (s *postgresSessionStore) Save(ctx context.Context, sc SessionContext) error {
|
||||
if !sessionVisible(ctx, sc) {
|
||||
return ErrSessionNotFound
|
||||
}
|
||||
q := postgresdb.New(s.pool)
|
||||
saved, err := q.SaveSession(ctx, postgresdb.SaveSessionParams{
|
||||
SessionID: sc.SessionID,
|
||||
@@ -73,6 +77,9 @@ func (s *postgresSessionStore) Get(ctx context.Context, sessionID string) (*Sess
|
||||
return nil, fmt.Errorf("sessionstore: get: %w", err)
|
||||
}
|
||||
sc := sessionFromRow(row)
|
||||
if !sessionVisible(ctx, sc) {
|
||||
return nil, nil
|
||||
}
|
||||
return &sc, nil
|
||||
}
|
||||
|
||||
@@ -84,7 +91,7 @@ func (s *postgresSessionStore) GetByChannel(ctx context.Context, platform, chann
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sessionstore: get by channel: %w", err)
|
||||
}
|
||||
return sessionsFromRows(rows), nil
|
||||
return visibleSessions(ctx, sessionsFromRows(rows)), nil
|
||||
}
|
||||
|
||||
func (s *postgresSessionStore) Delete(ctx context.Context, sessionID string) error {
|
||||
@@ -133,7 +140,7 @@ func (s *postgresSessionStore) List(ctx context.Context) ([]SessionContext, erro
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sessionstore: list: %w", err)
|
||||
}
|
||||
return sessionsFromRows(rows), nil
|
||||
return visibleSessions(ctx, sessionsFromRows(rows)), nil
|
||||
}
|
||||
|
||||
func sessionFromRow(row postgresdb.Session) SessionContext {
|
||||
@@ -846,6 +853,15 @@ func (s *postgresSessionStore) mayRead(ctx context.Context, sessionID string) er
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("sessionstore: session org: %w", err)
|
||||
}
|
||||
if _, ok := access.PrincipalFromContext(ctx); ok {
|
||||
session, err := s.Get(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if session == nil {
|
||||
return ErrSessionNotFound
|
||||
}
|
||||
}
|
||||
if owner != callerOrg(ctx) {
|
||||
return ErrSessionNotFound
|
||||
}
|
||||
@@ -861,3 +877,14 @@ func (s *postgresSessionStore) mayWrite(ctx context.Context, sessionID string) e
|
||||
}
|
||||
return s.mayRead(ctx, sessionID)
|
||||
}
|
||||
|
||||
// Service-owned curation has no person principal. Signed-in callers only
|
||||
// see their own web conversations, including through tools and slash commands.
|
||||
func sessionVisible(ctx context.Context, session SessionContext) bool {
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
return !ok || (session.Source.Platform == "web" && session.Source.ThreadID == string(p.IdentityID))
|
||||
}
|
||||
|
||||
func visibleSessions(ctx context.Context, sessions []SessionContext) []SessionContext {
|
||||
return slices.DeleteFunc(sessions, func(session SessionContext) bool { return !sessionVisible(ctx, session) })
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
func TestSessionVisibility(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
service bool
|
||||
platform, owner string
|
||||
want bool
|
||||
}{
|
||||
{"own history", false, "web", "alice", true},
|
||||
{"another user in the same org", false, "web", "bob", false},
|
||||
{"anonymous history is not assigned to a person", false, "web", "", false},
|
||||
{"other channel history", false, "telegram", "alice", false},
|
||||
{"curator service", true, "web", "bob", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
if !tc.service {
|
||||
ctx = access.WithPrincipal(ctx, access.Principal{IdentityID: "alice"})
|
||||
}
|
||||
session := SessionContext{Source: messaging.SessionSource{Platform: tc.platform, ThreadID: tc.owner}}
|
||||
if got := sessionVisible(ctx, session); got != tc.want {
|
||||
t.Fatalf("visible=%v want=%v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ The `<soul>` block above, when present, supplies identity and communication styl
|
||||
</instruction_precedence>
|
||||
|
||||
<core_rules>
|
||||
1. Never claim a capability beyond the tools listed below, and never assert that a file, memory, action, result or specific system detail (a file path, subsystem name, count or config value) exists, succeeded, or is accurate unless you checked it with a tool this turn -- a detail from earlier in the conversation, from memory, or from your own training data is unconfirmed, however specific or familiar it sounds. If you are unsure whether you can do something, say so plainly rather than guessing, and do not wait for the user to challenge you before correcting an unchecked claim.
|
||||
1. Never claim a capability beyond the tools listed below, and never assert that a file, memory, action, result or specific system detail (a file path, subsystem name, count or config value) exists, succeeded, or is accurate unless it is supplied in the runtime metadata or built-in product guide, or you checked it with a tool this turn -- a detail from earlier in the conversation, from memory, or from your own training data is unconfirmed, however specific or familiar it sounds. If you are unsure whether you can do something, say so plainly rather than guessing, and do not wait for the user to challenge you before correcting an unchecked claim.
|
||||
2. The tools listed below are the complete set available to you. You have no others. Do not offer to run commands, read files, install software or reach the network unless a listed tool actually does it.
|
||||
3. When you cannot do something, say what you cannot do and what you can do instead, in one or two sentences. Do not offer a numbered menu of questions.
|
||||
4. Prefer acting with a tool over asking the user for information a tool could retrieve.
|
||||
@@ -25,6 +25,10 @@ The `<soul>` block above, when present, supplies identity and communication styl
|
||||
7. Never ask to be given shell access, credentials, a connection or a path into a system. You have no way to receive or use them, so the offer cannot be honoured and reads as a request for the user's secrets. Say what a listed tool can do instead.
|
||||
</core_rules>
|
||||
|
||||
<product_guide purpose="product_reference" trust="data">
|
||||
{{xml .ProductGuide}}
|
||||
</product_guide>
|
||||
|
||||
<communication>
|
||||
- Replies are delivered over a chat channel: lead with the answer, keep it short, and skip preamble.
|
||||
- Brevity means not padding an answer; it does not mean being cold. A short reply can still be warm, and a clipped transactional one reads as rude.
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
Archie is event-driven automation: events start workflows, workflows run agent/tool steps, and results can require human review. A repository is optional. Use this built-in guide for product questions; the public GitHub repository is not a required source and may be private. Source-code details still require a file/tool lookup in an authorized workspace. Never invent a checkout or assume public repository access.
|
||||
|
||||
Accounts and organization:
|
||||
- First visit creates the organization, first workspace, instance URL, and first admin account. Organization members are managed at /org. Local accounts and OIDC identities are distinct; an identity must have membership before it can act.
|
||||
- Your account (/account) manages passwords, one-use recovery codes and passkeys. Passkeys need the configured HTTPS domain or localhost and a supported browser. Instance admins configure OIDC at /settings/authentication. Never request passwords, tokens or recovery codes in chat.
|
||||
|
||||
Creating a workflow:
|
||||
1. Open /workflows and choose New workflow. The new definition is an unsaved draft with an id and empty steps.
|
||||
2. Use YAML to edit its id, or the canvas to add and select steps. Select Starts when on the canvas to open Workflow settings. Set Runs as to an existing active agent identity. Works on selects Repository, If given, or None.
|
||||
3. Read an existing workflow and the served step/settings catalog before constructing YAML. A repository planning workflow normally prepares the repository, then uses agent.run with read_only: true and a mission asking it to inspect the code and return a plan. Keep forge writes, commits, implementation steps and automatic implementation handoffs out of a planning-only workflow. The shipped feasibility workflow also closes issues or hands off after approval: it is not a planning-only template unchanged.
|
||||
4. Save the definition. Test runs the draft once with forge writes/pushes skipped; commands and tools still run, so a test is not a side-effect-free simulation. Run starts the saved version. History, Performance and Runs show revisions and execution evidence.
|
||||
5. Manual workflows need no automatic trigger. Bind an event creates an event binding from a captured example and maps payload fields to declared inputs. Existing bindings can be paused or removed. Playbooks are edited at /settings/playbooks; workflow calls/handoffs are edited in the workflow that invokes them. Built-in issue-label routes are marked Built-in; they cannot be removed in the event-binding editor. Disable the workflow to prevent automatic execution.
|
||||
|
||||
Other product operations:
|
||||
- /tasks lists work and opens task details. Available actions depend on task state and permissions; read the served action vocabulary rather than guessing an action.
|
||||
- /events covers captured events, event types, field mappings and bindings. A source, mapping and binding are different records. Removing a binding does not remove its source or mapping.
|
||||
- /settings/status reports service health/configuration. For a status request, use the available status/health tool; a page listing does not check service health.
|
||||
- Settings and workflow changes must go through the available control-plane tools or the dashboard. Navigation tools only open pages; they do not click controls or save changes. If no listed tool can perform a requested operation, explain the concrete UI steps without claiming to have changed anything.
|
||||
@@ -17,7 +17,6 @@ import (
|
||||
// the code exchange, PKCE and token verification are the libraries'.
|
||||
type Flow struct {
|
||||
provider *Provider
|
||||
verifier *Verifier
|
||||
clientID string
|
||||
clientSecret string
|
||||
redirectURL string
|
||||
@@ -34,7 +33,7 @@ func NewFlow(provider *Provider, clientID, clientSecret, redirectURL string) (*F
|
||||
return nil, fmt.Errorf("oidc: redirect URL is required for the browser flow")
|
||||
}
|
||||
return &Flow{
|
||||
provider: provider, verifier: NewVerifier(provider),
|
||||
provider: provider,
|
||||
clientID: clientID, clientSecret: clientSecret, redirectURL: redirectURL,
|
||||
}, nil
|
||||
}
|
||||
@@ -65,15 +64,15 @@ func (f *Flow) AuthCodeURL(ctx context.Context, state string) (string, string, e
|
||||
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 completes the flow: it trades the code for the provider's tokens and
|
||||
// verifies the access token through the same Verifier a presented token goes
|
||||
// through. There is no second verification path here, so a token obtained by the
|
||||
// browser cannot be accepted on terms a presented token would be refused on.
|
||||
// verifies the ID token against the browser client and binds its nonce to the
|
||||
// PKCE verifier. Access tokens are not proof of a browser login.
|
||||
func (f *Flow) Exchange(ctx context.Context, code, codeVerifier string) (identity.ProviderSession, error) {
|
||||
config, err := f.oauth(ctx)
|
||||
if err != nil {
|
||||
@@ -83,7 +82,22 @@ func (f *Flow) Exchange(ctx context.Context, code, codeVerifier string) (identit
|
||||
if err != nil {
|
||||
return identity.ProviderSession{}, fmt.Errorf("oidc: exchange code: %w", err)
|
||||
}
|
||||
credential, err := f.verifier.Verify(ctx, token.AccessToken)
|
||||
rawIDToken, ok := token.Extra("id_token").(string)
|
||||
if !ok || rawIDToken == "" {
|
||||
return identity.ProviderSession{}, fmt.Errorf("oidc: provider returned no ID token")
|
||||
}
|
||||
discovered, err := f.provider.get(ctx)
|
||||
if err != nil {
|
||||
return identity.ProviderSession{}, err
|
||||
}
|
||||
verified, err := discovered.Verifier(&gooidc.Config{ClientID: f.clientID}).Verify(ctx, rawIDToken)
|
||||
if err != nil {
|
||||
return identity.ProviderSession{}, fmt.Errorf("oidc: verify ID token: %w", err)
|
||||
}
|
||||
if verified.Nonce != oauth2.S256ChallengeFromVerifier(codeVerifier) {
|
||||
return identity.ProviderSession{}, fmt.Errorf("oidc: ID token nonce mismatch")
|
||||
}
|
||||
credential, err := NewVerifierForAudience(f.provider, f.clientID).Verify(ctx, rawIDToken)
|
||||
if err != nil {
|
||||
return identity.ProviderSession{}, err
|
||||
}
|
||||
@@ -91,5 +105,5 @@ func (f *Flow) Exchange(ctx context.Context, code, codeVerifier string) (identit
|
||||
if credential.Expires.Before(expires) || expires.IsZero() {
|
||||
expires = credential.Expires
|
||||
}
|
||||
return identity.ProviderSession{Credential: credential, Token: token.AccessToken, Expires: expires}, nil
|
||||
return identity.ProviderSession{Credential: credential, Token: rawIDToken, Expires: expires}, nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-jose/go-jose/v4"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
func TestBrowserFlowVerifiesIDToken(t *testing.T) {
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, nonce, audience string
|
||||
omit, expired bool
|
||||
want bool
|
||||
}{
|
||||
{name: "verified ID token", nonce: oauth2.S256ChallengeFromVerifier("verifier"), audience: "browser-client", want: true},
|
||||
{name: "nonce mismatch", nonce: "different", audience: "browser-client"},
|
||||
{name: "wrong audience", nonce: oauth2.S256ChallengeFromVerifier("verifier"), audience: "other-client"},
|
||||
{name: "missing ID token", omit: true},
|
||||
{name: "expired ID token", nonce: oauth2.S256ChallengeFromVerifier("verifier"), audience: "browser-client", expired: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var provider *httptest.Server
|
||||
provider = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/.well-known/openid-configuration":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"issuer": provider.URL, "authorization_endpoint": provider.URL + "/auth", "token_endpoint": provider.URL + "/token", "jwks_uri": provider.URL + "/keys", "id_token_signing_alg_values_supported": []string{"RS256"}})
|
||||
case "/keys":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []jose.JSONWebKey{{Key: &key.PublicKey, KeyID: "test", Algorithm: "RS256", Use: "sig"}}})
|
||||
case "/token":
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if r.Form.Get("code_verifier") != "verifier" {
|
||||
t.Error("token exchange omitted PKCE verifier")
|
||||
}
|
||||
expires := time.Now().Add(time.Hour).Unix()
|
||||
if tc.expired {
|
||||
expires = time.Now().Add(-time.Hour).Unix()
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{"iss": provider.URL, "aud": tc.audience, "sub": "alice", "nonce": tc.nonce, "iat": time.Now().Unix(), "exp": expires, "email": "alice@example.com", "email_verified": true})
|
||||
token.Header["kid"] = "test"
|
||||
raw, signErr := token.SignedString(key)
|
||||
if signErr != nil {
|
||||
t.Error(signErr)
|
||||
return
|
||||
}
|
||||
body := map[string]any{"access_token": "opaque-access-token", "token_type": "Bearer", "expires_in": 3600}
|
||||
if !tc.omit {
|
||||
body["id_token"] = raw
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer provider.Close()
|
||||
configured, err := NewProvider(Config{Issuer: provider.URL, Audience: "resource-audience"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
flow, err := NewFlow(configured, "browser-client", "", "https://archie.example/oauth2/callback")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := flow.Exchange(t.Context(), "code", "verifier")
|
||||
if (err == nil) != tc.want {
|
||||
t.Fatalf("accepted=%v want=%v err=%v", err == nil, tc.want, err)
|
||||
}
|
||||
if tc.want && (result.Credential.Subject.Subject != "alice" || result.Credential.Email != "alice@example.com" || result.Token == "opaque-access-token") {
|
||||
t.Fatalf("unverified/wrong token became browser identity: %+v", result.Credential)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,7 @@ func (p *Provider) Check(ctx context.Context) error {
|
||||
// Verifier validates tokens against the provider's published signing keys.
|
||||
type Verifier struct {
|
||||
provider *Provider
|
||||
audience string
|
||||
}
|
||||
|
||||
// NewVerifier returns a verifier for provider's tokens.
|
||||
@@ -91,7 +92,11 @@ func (v *Verifier) Verify(ctx context.Context, rawToken string) (identity.Creden
|
||||
if err != nil {
|
||||
return identity.Credential{}, err
|
||||
}
|
||||
verifier := discovered.Verifier(&gooidc.Config{ClientID: v.provider.audience})
|
||||
audience := v.audience
|
||||
if audience == "" {
|
||||
audience = v.provider.audience
|
||||
}
|
||||
verifier := discovered.Verifier(&gooidc.Config{ClientID: audience})
|
||||
token, err := verifier.Verify(ctx, strings.TrimSpace(rawToken))
|
||||
if err != nil {
|
||||
return identity.Credential{}, fmt.Errorf("oidc: verify: %w", err)
|
||||
@@ -146,3 +151,9 @@ func scopesFor(scope string, scopes []string) []string {
|
||||
}
|
||||
return strings.Fields(scope)
|
||||
}
|
||||
|
||||
// NewVerifierForAudience shares discovery and signing-key caches while checking
|
||||
// the browser client's audience instead of a resource-server audience.
|
||||
func NewVerifierForAudience(provider *Provider, audience string) *Verifier {
|
||||
return &Verifier{provider: provider, audience: audience}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
func (s *Store) OpenAccountSession(ctx context.Context, expires time.Time) (identity.AccountSession, error) {
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return identity.AccountSession{}, identity.ErrCredentialRejected
|
||||
}
|
||||
row, err := s.queries().GetIdentity(ctx, string(p.IdentityID))
|
||||
if err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
value := identityFromRow(row)
|
||||
if value.Kind != identity.KindUser || !value.CanAct() {
|
||||
return identity.AccountSession{}, identity.ErrCredentialRejected
|
||||
}
|
||||
result := identity.AccountSession{Identity: value, Token: rand.Text(), Expires: time.Now().UTC().Add(identity.AccountSessionLifetime)}
|
||||
if expires.IsZero() || !expires.After(time.Now()) {
|
||||
return identity.AccountSession{}, identity.ErrCredentialRejected
|
||||
}
|
||||
if expires.Before(result.Expires) {
|
||||
result.Expires = expires
|
||||
}
|
||||
_, err = s.pool.Exec(ctx, `INSERT INTO account_sessions (token_hash,identity_id,expires_at) VALUES ($1,$2,$3)`, sessionHash(result.Token), string(p.IdentityID), result.Expires)
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (s *Store) RequireFreshAccountSession(ctx context.Context, token string) error {
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
var fresh bool
|
||||
err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM account_sessions WHERE token_hash=$1 AND identity_id=$2 AND expires_at>now() AND issued_at>now()-interval '10 minutes')`, sessionHash(token), string(p.IdentityID)).Scan(&fresh)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !fresh {
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateAccountRecovery(ctx context.Context) (string, error) {
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return "", identity.ErrCredentialRejected
|
||||
}
|
||||
code := rand.Text() + rand.Text()
|
||||
result, err := s.pool.Exec(ctx, `UPDATE accounts SET recovery_hash=$2 WHERE identity_id=$1`, string(p.IdentityID), sessionHash(code))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if result.RowsAffected() != 1 {
|
||||
return "", identity.ErrNotFound
|
||||
}
|
||||
return code, nil
|
||||
}
|
||||
|
||||
func (s *Store) RecoverAccount(ctx context.Context, email, code, password string) error {
|
||||
if len(code) < 52 || len(code) > 128 {
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
hash, err := identity.HashPassword(password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
var id string
|
||||
err = tx.QueryRow(ctx, `UPDATE accounts a SET password_hash=$3,recovery_hash=NULL,failed_attempts=0,locked_until=NULL FROM identities i WHERE a.identity_id=i.id AND i.lifecycle='active' AND a.email=$1 AND a.recovery_hash=$2 RETURNING a.identity_id`, strings.ToLower(strings.TrimSpace(email)), sessionHash(code), hash).Scan(&id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
func (s *Store) AccountSetupRequired(ctx context.Context) (bool, error) {
|
||||
var required bool
|
||||
err := s.pool.QueryRow(ctx, `SELECT NOT EXISTS (SELECT 1 FROM accounts)`).Scan(&required)
|
||||
return required, err
|
||||
}
|
||||
|
||||
func (s *Store) RegisterAccount(ctx context.Context, r identity.AccountRegistration, bootstrap bool) (identity.Identity, error) {
|
||||
role, orgID, err := accountRegistrationScope(ctx, &r, bootstrap)
|
||||
if err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
hash, err := identity.HashPassword(r.Password)
|
||||
if err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
// Every registration shares this lock so only one transaction can bootstrap.
|
||||
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(484726231)`); err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
var anyAccounts bool
|
||||
if err = tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM accounts)`).Scan(&anyAccounts); err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
if bootstrap && anyAccounts {
|
||||
return identity.Identity{}, identity.ErrSetupComplete
|
||||
}
|
||||
if !bootstrap && !anyAccounts {
|
||||
return identity.Identity{}, identity.ErrCredentialRejected
|
||||
}
|
||||
value, err := writeAccount(ctx, tx, r, bootstrap, orgID, role, hash)
|
||||
if err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func writeAccount(ctx context.Context, tx pgx.Tx, r identity.AccountRegistration, bootstrap bool, orgID org.OrgID, role org.Role, hash string) (identity.Identity, error) {
|
||||
id := identity.IdentityID(rand.Text())
|
||||
if bootstrap {
|
||||
id = identity.OperatorID()
|
||||
}
|
||||
value, err := identity.New(id, identity.KindUser, r.DisplayName)
|
||||
if err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
value.CreatedAt, value.UpdatedAt = now, now
|
||||
if bootstrap {
|
||||
if err := setupAccountOrganisation(ctx, tx, r, orgID, now); err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `INSERT INTO identities (id,kind,display_name,lifecycle,version,created_at,updated_at) VALUES ($1,'user',$2,'active',1,$3,$3)
|
||||
ON CONFLICT (id) DO UPDATE SET display_name=EXCLUDED.display_name, lifecycle='active',version=identities.version+1,updated_at=EXCLUDED.updated_at`, string(id), r.DisplayName, now)
|
||||
if err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO accounts (identity_id,email,password_hash) VALUES ($1,$2,$3)`, string(id), r.Email, hash)
|
||||
if err != nil {
|
||||
var pgerr *pgconn.PgError
|
||||
if errors.As(err, &pgerr) && pgerr.Code == "23505" {
|
||||
return identity.Identity{}, identity.ErrConflict
|
||||
}
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO memberships (identity_id,org_id,role) VALUES ($1,$2,$3) ON CONFLICT (identity_id,org_id,(COALESCE(workspace_id,''))) DO UPDATE SET role=EXCLUDED.role`, string(id), string(orgID), string(role))
|
||||
if err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
actor := id
|
||||
if p, ok := access.PrincipalFromContext(ctx); ok {
|
||||
actor = p.IdentityID
|
||||
}
|
||||
err = insertIdentityEvent(ctx, postgresdb.New(tx), id, identity.Event{Type: "create", To: identity.LifecycleActive, DisplayName: r.DisplayName}, identity.Audit{ActorID: actor, Source: "accounts", RequestID: "account:" + rand.Text()}, now)
|
||||
if err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func sessionHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *Store) SignInAccount(ctx context.Context, email, password string) (identity.AccountSession, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
var id, hash string
|
||||
var attempts int
|
||||
var locked *time.Time
|
||||
err = tx.QueryRow(ctx, `SELECT identity_id,password_hash,failed_attempts,locked_until FROM accounts WHERE email=$1 FOR UPDATE`, strings.ToLower(strings.TrimSpace(email))).Scan(&id, &hash, &attempts, &locked)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
// An unknown email still pays the password hashing cost.
|
||||
_, hashErr := identity.HashPassword("unknown account dummy password")
|
||||
if hashErr != nil {
|
||||
return identity.AccountSession{}, hashErr
|
||||
}
|
||||
return identity.AccountSession{}, identity.ErrCredentialRejected
|
||||
}
|
||||
if err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
valid := identity.VerifyPassword(password, hash)
|
||||
if locked != nil && time.Now().Before(*locked) {
|
||||
return identity.AccountSession{}, identity.ErrCredentialRejected
|
||||
}
|
||||
if !valid {
|
||||
return identity.AccountSession{}, recordFailedAccountLogin(ctx, tx, id, attempts, locked)
|
||||
}
|
||||
|
||||
row, err := postgresdb.New(tx).GetIdentity(ctx, id)
|
||||
if err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
value := identityFromRow(row)
|
||||
if !value.CanAct() {
|
||||
return identity.AccountSession{}, identity.ErrCredentialRejected
|
||||
}
|
||||
token := rand.Text()
|
||||
expires := time.Now().UTC().Add(identity.AccountSessionLifetime)
|
||||
if _, err = tx.Exec(ctx, `UPDATE accounts SET failed_attempts=0,locked_until=NULL WHERE identity_id=$1`, id); err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `DELETE FROM account_sessions WHERE expires_at<=now()`); err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO account_sessions (token_hash,identity_id,expires_at) VALUES ($1,$2,$3)`, sessionHash(token), id, expires); err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
return identity.AccountSession{Identity: value, Token: token, Expires: expires}, nil
|
||||
}
|
||||
|
||||
func (s *Store) ResolveAccountSession(ctx context.Context, token string) (identity.Identity, error) {
|
||||
if len(token) < 26 || len(token) > 128 {
|
||||
return identity.Identity{}, identity.ErrCredentialRejected
|
||||
}
|
||||
var id string
|
||||
err := s.pool.QueryRow(ctx, `SELECT s.identity_id FROM account_sessions s JOIN identities i ON i.id=s.identity_id WHERE s.token_hash=$1 AND s.expires_at>now() AND i.lifecycle='active'`, sessionHash(token)).Scan(&id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return identity.Identity{}, identity.ErrCredentialRejected
|
||||
}
|
||||
if err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
row, err := s.queries().GetIdentity(ctx, id)
|
||||
return identityFromRow(row), err
|
||||
}
|
||||
|
||||
func (s *Store) SignOutAccount(ctx context.Context, token string) error {
|
||||
_, err := s.pool.Exec(ctx, `DELETE FROM account_sessions WHERE token_hash=$1`, sessionHash(token))
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) ChangeAccountPassword(ctx context.Context, current, next string) error {
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
hash, err := identity.HashPassword(next)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
var old string
|
||||
err = tx.QueryRow(ctx, `SELECT password_hash FROM accounts WHERE identity_id=$1 FOR UPDATE`, string(p.IdentityID)).Scan(&old)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !identity.VerifyPassword(current, old) {
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE accounts SET password_hash=$2,failed_attempts=0,locked_until=NULL WHERE identity_id=$1`, string(p.IdentityID), hash); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, string(p.IdentityID)); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func accountRegistrationScope(ctx context.Context, r *identity.AccountRegistration, bootstrap bool) (org.Role, org.OrgID, error) {
|
||||
if err := r.Validate(); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
role := org.Role(r.Role)
|
||||
orgID := org.OrgFromContext(ctx)
|
||||
if bootstrap {
|
||||
if err := validateAccountSetup(r); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return org.RoleOwner, org.DefaultOrgID, nil
|
||||
}
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok || p.Org != orgID {
|
||||
return "", "", identity.ErrCredentialRejected
|
||||
}
|
||||
if role != org.RoleAdmin && role != org.RoleDeveloper && role != org.RoleViewer {
|
||||
return "", "", identity.ErrInvalid
|
||||
}
|
||||
|
||||
return role, orgID, nil
|
||||
}
|
||||
|
||||
func recordFailedAccountLogin(ctx context.Context, tx pgx.Tx, id string, attempts int, locked *time.Time) error {
|
||||
if locked != nil {
|
||||
attempts = 0
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE accounts SET failed_attempts=$2,locked_until=CASE WHEN $2>=5 THEN now()+interval '15 minutes' ELSE NULL END WHERE identity_id=$1`, id, attempts+1); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
|
||||
func setupAccountOrganisation(ctx context.Context, tx pgx.Tx, r identity.AccountRegistration, orgID org.OrgID, now time.Time) error {
|
||||
_, err := tx.Exec(ctx, `UPDATE orgs SET name=$1, updated_at=$2 WHERE id=$3`, r.OrganisationName, now, string(orgID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE workspaces SET name=$1,updated_at=$2 WHERE org_id=$3 AND id=$4`, r.WorkspaceName, now, string(orgID), string(org.DefaultWorkspaceID)); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO authentication_settings (public_url) VALUES ($1)`, r.PublicURL); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAccountSetup(r *identity.AccountRegistration) error {
|
||||
r.OrganisationName = strings.TrimSpace(r.OrganisationName)
|
||||
r.WorkspaceName = strings.TrimSpace(r.WorkspaceName)
|
||||
r.PublicURL = strings.TrimRight(r.PublicURL, "/")
|
||||
if r.WorkspaceName == "" || len(r.WorkspaceName) > 200 {
|
||||
return identity.ErrInvalid
|
||||
}
|
||||
if r.OrganisationName == "" || len(r.OrganisationName) > 200 {
|
||||
return fmt.Errorf("%w: organisation name is required", identity.ErrInvalid)
|
||||
}
|
||||
return (identity.AuthenticationSettings{PublicURL: r.PublicURL}).Validate()
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
func (s *Store) AuthenticationSettings(ctx context.Context) (identity.AuthenticationSettings, error) {
|
||||
var value identity.AuthenticationSettings
|
||||
err := s.pool.QueryRow(ctx, `SELECT public_url,oidc_issuer,oidc_audience,oidc_client_id FROM authentication_settings WHERE singleton`).Scan(&value.PublicURL, &value.OIDCIssuer, &value.OIDCAudience, &value.OIDCClientID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return value, nil
|
||||
}
|
||||
return value, err
|
||||
}
|
||||
|
||||
func (s *Store) SaveAuthenticationSettings(ctx context.Context, value identity.AuthenticationSettings) error {
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok || !p.InstanceAdmin() {
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
value.PublicURL = strings.TrimRight(value.PublicURL, "/")
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
// The relying-party origin cannot silently change and orphan enrolled keys.
|
||||
command, err := s.pool.Exec(ctx, `UPDATE authentication_settings SET public_url=$1,oidc_issuer=$2,oidc_audience=$3,oidc_client_id=$4 WHERE singleton AND (public_url=$1 OR NOT EXISTS (SELECT 1 FROM passkeys))`, value.PublicURL, value.OIDCIssuer, value.OIDCAudience, value.OIDCClientID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if command.RowsAffected() != 1 {
|
||||
return identity.ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -185,6 +185,11 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi
|
||||
if n != 1 {
|
||||
return identity.Identity{}, identity.ErrConflict
|
||||
}
|
||||
if next.Lifecycle != identity.LifecycleActive {
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, string(id)); err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
}
|
||||
if command.Type == identity.CommandRename {
|
||||
if err := q.InsertIdentityAliasIgnoreConflict(ctx, postgresdb.InsertIdentityAliasIgnoreConflictParams{
|
||||
Alias: next.DisplayName, IdentityID: string(id),
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE accounts (
|
||||
identity_id text PRIMARY KEY REFERENCES identities(id),
|
||||
email text NOT NULL UNIQUE CHECK (email = lower(email)),
|
||||
password_hash text NOT NULL,
|
||||
recovery_hash text,
|
||||
failed_attempts integer NOT NULL DEFAULT 0,
|
||||
locked_until timestamptz
|
||||
);
|
||||
CREATE TABLE account_sessions (
|
||||
token_hash text PRIMARY KEY,
|
||||
identity_id text NOT NULL REFERENCES identities(id) ON DELETE CASCADE,
|
||||
expires_at timestamptz NOT NULL,
|
||||
issued_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX account_sessions_identity ON account_sessions(identity_id);
|
||||
CREATE INDEX account_sessions_expiry ON account_sessions(expires_at);
|
||||
|
||||
CREATE TABLE authentication_settings (
|
||||
singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
|
||||
public_url text NOT NULL,
|
||||
oidc_issuer text NOT NULL DEFAULT '',
|
||||
oidc_audience text NOT NULL DEFAULT '',
|
||||
oidc_client_id text NOT NULL DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE passkeys (
|
||||
credential_id text PRIMARY KEY,
|
||||
identity_id text NOT NULL REFERENCES identities(id),
|
||||
name text NOT NULL,
|
||||
credential jsonb NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX passkeys_identity ON passkeys(identity_id);
|
||||
CREATE TABLE passkey_ceremonies (
|
||||
token_hash text PRIMARY KEY,
|
||||
identity_id text NOT NULL,
|
||||
registration boolean NOT NULL,
|
||||
session_data jsonb NOT NULL,
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX passkey_ceremonies_expiry ON passkey_ceremonies(expires_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE passkey_ceremonies;
|
||||
DROP TABLE passkeys;
|
||||
DROP TABLE authentication_settings;
|
||||
DROP TABLE account_sessions;
|
||||
DROP TABLE accounts;
|
||||
@@ -0,0 +1,264 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-webauthn/webauthn/protocol"
|
||||
"github.com/go-webauthn/webauthn/webauthn"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
type passkeyUser struct {
|
||||
value identity.Identity
|
||||
credentials []webauthn.Credential
|
||||
}
|
||||
|
||||
func (u passkeyUser) WebAuthnID() []byte { return []byte(u.value.ID) }
|
||||
func (u passkeyUser) WebAuthnName() string { return u.value.DisplayName }
|
||||
func (u passkeyUser) WebAuthnDisplayName() string { return u.value.DisplayName }
|
||||
func (u passkeyUser) WebAuthnCredentials() []webauthn.Credential { return u.credentials }
|
||||
|
||||
func (s *Store) webAuthn(ctx context.Context) (*webauthn.WebAuthn, error) {
|
||||
settings, err := s.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u, err := url.Parse(settings.PublicURL)
|
||||
secure := err == nil && (u.Scheme == "https" || (u.Scheme == "http" && u.Hostname() == "localhost"))
|
||||
if !secure || u.Hostname() == "" || net.ParseIP(u.Hostname()) != nil {
|
||||
return nil, identity.ErrInvalid
|
||||
}
|
||||
return webauthn.New(&webauthn.Config{RPDisplayName: "Archie", RPID: u.Hostname(), RPOrigins: []string{strings.TrimRight(settings.PublicURL, "/")}, AuthenticatorSelection: protocol.AuthenticatorSelection{UserVerification: protocol.VerificationRequired, ResidentKey: protocol.ResidentKeyRequirementRequired}})
|
||||
}
|
||||
|
||||
func loadPasskeyUser(ctx context.Context, q *postgresdb.Queries, db interface {
|
||||
Query(context.Context, string, ...any) (pgx.Rows, error)
|
||||
}, id string,
|
||||
) (passkeyUser, error) {
|
||||
row, err := q.GetIdentity(ctx, id)
|
||||
if err != nil {
|
||||
return passkeyUser{}, err
|
||||
}
|
||||
user := passkeyUser{value: identityFromRow(row)}
|
||||
if user.value.Kind != identity.KindUser || !user.value.CanAct() {
|
||||
return passkeyUser{}, identity.ErrCredentialRejected
|
||||
}
|
||||
rows, err := db.Query(ctx, `SELECT credential FROM passkeys WHERE identity_id=$1`, id)
|
||||
if err != nil {
|
||||
return passkeyUser{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var data []byte
|
||||
if err = rows.Scan(&data); err != nil {
|
||||
return passkeyUser{}, err
|
||||
}
|
||||
var credential webauthn.Credential
|
||||
if err = json.Unmarshal(data, &credential); err != nil {
|
||||
return passkeyUser{}, err
|
||||
}
|
||||
user.credentials = append(user.credentials, credential)
|
||||
}
|
||||
return user, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) BeginPasskey(ctx context.Context, registration bool) (identity.PasskeyCeremony, error) {
|
||||
wa, err := s.webAuthn(ctx)
|
||||
if err != nil {
|
||||
return identity.PasskeyCeremony{}, err
|
||||
}
|
||||
var options any
|
||||
var session *webauthn.SessionData
|
||||
var owner string
|
||||
if registration {
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return identity.PasskeyCeremony{}, identity.ErrCredentialRejected
|
||||
}
|
||||
owner = string(p.IdentityID)
|
||||
user, loadErr := loadPasskeyUser(ctx, s.queries(), s.pool, owner)
|
||||
if loadErr != nil {
|
||||
return identity.PasskeyCeremony{}, loadErr
|
||||
}
|
||||
options, session, err = wa.BeginRegistration(user)
|
||||
} else {
|
||||
options, session, err = wa.BeginDiscoverableLogin(webauthn.WithUserVerification(protocol.VerificationRequired))
|
||||
}
|
||||
if err != nil {
|
||||
return identity.PasskeyCeremony{}, err
|
||||
}
|
||||
data, err := json.Marshal(session)
|
||||
if err != nil {
|
||||
return identity.PasskeyCeremony{}, err
|
||||
}
|
||||
encoded, err := json.Marshal(options)
|
||||
if err != nil {
|
||||
return identity.PasskeyCeremony{}, err
|
||||
}
|
||||
token := rand.Text()
|
||||
if _, err = s.pool.Exec(ctx, `DELETE FROM passkey_ceremonies WHERE expires_at<=now()`); err != nil {
|
||||
return identity.PasskeyCeremony{}, err
|
||||
}
|
||||
_, err = s.pool.Exec(ctx, `INSERT INTO passkey_ceremonies (token_hash,identity_id,registration,session_data,expires_at) VALUES ($1,$2,$3,$4,now()+interval '5 minutes')`, sessionHash(token), owner, registration, data)
|
||||
return identity.PasskeyCeremony{Token: token, Options: encoded}, err
|
||||
}
|
||||
|
||||
func (s *Store) FinishPasskey(ctx context.Context, token string, response []byte, registration bool, name string) (identity.AccountSession, error) {
|
||||
wa, err := s.webAuthn(ctx)
|
||||
if err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
var owner string
|
||||
var data []byte
|
||||
// Consume before verification: failed and successful attempts are single-use.
|
||||
err = s.pool.QueryRow(ctx, `DELETE FROM passkey_ceremonies WHERE token_hash=$1 AND registration=$2 AND expires_at>now() RETURNING identity_id,session_data`, sessionHash(token), registration).Scan(&owner, &data)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return identity.AccountSession{}, identity.ErrCredentialRejected
|
||||
}
|
||||
if err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
var session webauthn.SessionData
|
||||
if err = json.Unmarshal(data, &session); err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
credential, user, err := verifyPasskey(ctx, tx, wa, owner, session, response, registration)
|
||||
|
||||
if err != nil || credential == nil || credential.Authenticator.CloneWarning {
|
||||
return identity.AccountSession{}, identity.ErrCredentialRejected
|
||||
}
|
||||
owner = string(user.value.ID)
|
||||
if err := persistPasskey(ctx, tx, credential, owner, name, registration); err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
|
||||
result := identity.AccountSession{Identity: user.value}
|
||||
if !registration {
|
||||
result.Token = rand.Text()
|
||||
result.Expires = time.Now().UTC().Add(identity.AccountSessionLifetime)
|
||||
_, err = tx.Exec(ctx, `INSERT INTO account_sessions (token_hash,identity_id,expires_at) VALUES ($1,$2,$3)`, sessionHash(result.Token), owner, result.Expires)
|
||||
if err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return identity.AccountSession{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListPasskeys(ctx context.Context) ([]identity.Passkey, error) {
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return nil, identity.ErrCredentialRejected
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `SELECT credential_id,name FROM passkeys WHERE identity_id=$1 ORDER BY created_at`, string(p.IdentityID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []identity.Passkey{}
|
||||
for rows.Next() {
|
||||
var value identity.Passkey
|
||||
if err = rows.Scan(&value.ID, &value.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, value)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) DeletePasskey(ctx context.Context, id string) error {
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
result, err := s.pool.Exec(ctx, `DELETE FROM passkeys WHERE credential_id=$1 AND identity_id=$2`, id, string(p.IdentityID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result.RowsAffected() != 1 {
|
||||
return identity.ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func verifyPasskey(ctx context.Context, tx pgx.Tx, wa *webauthn.WebAuthn, owner string, session webauthn.SessionData, response []byte, registration bool) (*webauthn.Credential, passkeyUser, error) {
|
||||
if registration {
|
||||
return verifyPasskeyRegistration(ctx, tx, wa, owner, session, response)
|
||||
}
|
||||
var user passkeyUser
|
||||
parsed, err := protocol.ParseCredentialRequestResponseBytes(response)
|
||||
if err != nil {
|
||||
return nil, user, identity.ErrCredentialRejected
|
||||
}
|
||||
credential, err := wa.ValidateDiscoverableLogin(func(rawID, userHandle []byte) (webauthn.User, error) {
|
||||
if err = tx.QueryRow(ctx, `SELECT identity_id FROM passkeys WHERE credential_id=$1 FOR UPDATE`, base64.RawURLEncoding.EncodeToString(rawID)).Scan(&owner); err != nil {
|
||||
return nil, identity.ErrCredentialRejected
|
||||
}
|
||||
if owner != string(userHandle) {
|
||||
return nil, identity.ErrCredentialRejected
|
||||
}
|
||||
user, err = loadPasskeyUser(ctx, postgresdb.New(tx), tx, owner)
|
||||
return user, err
|
||||
}, session, parsed)
|
||||
return credential, user, err
|
||||
}
|
||||
|
||||
func verifyPasskeyRegistration(ctx context.Context, tx pgx.Tx, wa *webauthn.WebAuthn, owner string, session webauthn.SessionData, response []byte) (*webauthn.Credential, passkeyUser, error) {
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok || string(p.IdentityID) != owner {
|
||||
return nil, passkeyUser{}, identity.ErrCredentialRejected
|
||||
}
|
||||
user, err := loadPasskeyUser(ctx, postgresdb.New(tx), tx, owner)
|
||||
if err != nil {
|
||||
return nil, user, err
|
||||
}
|
||||
parsed, err := protocol.ParseCredentialCreationResponseBytes(response)
|
||||
if err != nil {
|
||||
return nil, user, identity.ErrCredentialRejected
|
||||
}
|
||||
credential, err := wa.CreateCredential(user, session, parsed)
|
||||
return credential, user, err
|
||||
}
|
||||
|
||||
func persistPasskey(ctx context.Context, tx pgx.Tx, credential *webauthn.Credential, owner, name string, registration bool) error {
|
||||
encoded, err := json.Marshal(credential)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
credentialID := base64.RawURLEncoding.EncodeToString(credential.ID)
|
||||
if registration {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
name = "Passkey"
|
||||
}
|
||||
if len(name) > 200 {
|
||||
return identity.ErrInvalid
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO passkeys (credential_id,identity_id,name,credential) VALUES ($1,$2,$3,$4)`, credentialID, owner, name, encoded)
|
||||
} else {
|
||||
_, err = tx.Exec(ctx, `UPDATE passkeys SET credential=$2 WHERE credential_id=$1`, credentialID, encoded)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -558,6 +558,11 @@ ON CONFLICT (session_id) DO UPDATE SET
|
||||
created_at = EXCLUDED.created_at,
|
||||
last_active_at = EXCLUDED.last_active_at
|
||||
WHERE sessions.org_id = EXCLUDED.org_id
|
||||
AND (
|
||||
(sessions.platform = '' AND sessions.bot_user = '' AND sessions.channel_id = '' AND sessions.thread_id = '')
|
||||
OR (sessions.platform = EXCLUDED.platform AND sessions.bot_user = EXCLUDED.bot_user
|
||||
AND sessions.channel_id = EXCLUDED.channel_id AND sessions.thread_id = EXCLUDED.thread_id)
|
||||
)
|
||||
`
|
||||
|
||||
type SaveSessionParams struct {
|
||||
@@ -577,8 +582,9 @@ type SaveSessionParams struct {
|
||||
// Gateway conversation queries: sessions, messages, turns, full-text search.
|
||||
// These back internal/gateway's PostgreSQL SessionStore.
|
||||
// ── Sessions ────────────────────────────────────────────────────────────────
|
||||
// Updates only a session the writing org owns: another org's session of the
|
||||
// same id is left untouched and the zero row count refuses the write.
|
||||
// A saved session keeps its organization and conversation identity. Empty
|
||||
// placeholder rows may be completed; an existing conversation cannot be claimed
|
||||
// by overwriting its source with another person's thread.
|
||||
func (q *Queries) SaveSession(ctx context.Context, arg SaveSessionParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, saveSession,
|
||||
arg.SessionID,
|
||||
|
||||
@@ -44,6 +44,22 @@ type AccessPolicyVersion struct {
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type Account struct {
|
||||
IdentityID string
|
||||
Email string
|
||||
PasswordHash string
|
||||
RecoveryHash pgtype.Text
|
||||
FailedAttempts int32
|
||||
LockedUntil pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AccountSession struct {
|
||||
TokenHash string
|
||||
IdentityID string
|
||||
ExpiresAt time.Time
|
||||
IssuedAt time.Time
|
||||
}
|
||||
|
||||
type Alert struct {
|
||||
ID int64
|
||||
OrgID string
|
||||
@@ -89,6 +105,14 @@ type ApplyStatus struct {
|
||||
ReportedAt time.Time
|
||||
}
|
||||
|
||||
type AuthenticationSetting struct {
|
||||
Singleton bool
|
||||
PublicUrl string
|
||||
OidcIssuer string
|
||||
OidcAudience string
|
||||
OidcClientID string
|
||||
}
|
||||
|
||||
type Binding struct {
|
||||
ID string
|
||||
Name string
|
||||
@@ -344,6 +368,22 @@ type OrgUpgrade struct {
|
||||
CompletedAt time.Time
|
||||
}
|
||||
|
||||
type Passkey struct {
|
||||
CredentialID string
|
||||
IdentityID string
|
||||
Name string
|
||||
Credential []byte
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type PasskeyCeremony struct {
|
||||
TokenHash string
|
||||
IdentityID string
|
||||
Registration bool
|
||||
SessionData []byte
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type PlaybookDispatch struct {
|
||||
PlaybookID string
|
||||
PlaybookVersion string
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
-- ── Sessions ────────────────────────────────────────────────────────────────
|
||||
|
||||
-- name: SaveSession :execrows
|
||||
-- Updates only a session the writing org owns: another org's session of the
|
||||
-- same id is left untouched and the zero row count refuses the write.
|
||||
-- A saved session keeps its organization and conversation identity. Empty
|
||||
-- placeholder rows may be completed; an existing conversation cannot be claimed
|
||||
-- by overwriting its source with another person's thread.
|
||||
INSERT INTO sessions (session_id, platform, bot_user, channel_id, thread_id,
|
||||
title, parent_session_id, branch_name, created_at, last_active_at, org_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||
@@ -19,7 +20,12 @@ ON CONFLICT (session_id) DO UPDATE SET
|
||||
branch_name = EXCLUDED.branch_name,
|
||||
created_at = EXCLUDED.created_at,
|
||||
last_active_at = EXCLUDED.last_active_at
|
||||
WHERE sessions.org_id = EXCLUDED.org_id;
|
||||
WHERE sessions.org_id = EXCLUDED.org_id
|
||||
AND (
|
||||
(sessions.platform = '' AND sessions.bot_user = '' AND sessions.channel_id = '' AND sessions.thread_id = '')
|
||||
OR (sessions.platform = EXCLUDED.platform AND sessions.bot_user = EXCLUDED.bot_user
|
||||
AND sessions.channel_id = EXCLUDED.channel_id AND sessions.thread_id = EXCLUDED.thread_id)
|
||||
);
|
||||
|
||||
-- name: ClaimSession :exec
|
||||
-- A write to a session no row names yet makes the writing org its owner.
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
func (s *server) accountSecurity() (identity.AccountSecurity, error) {
|
||||
store, ok := s.deps.Accounts.(identity.AccountSecurity)
|
||||
if !ok {
|
||||
return nil, status.Error(codes.Unavailable, "account security unavailable")
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
func (s *server) OpenAccountSession(ctx context.Context, r *pb.OpenAccountSessionRequest) (*pb.OpenAccountSessionResponse, error) {
|
||||
store, err := s.accountSecurity()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value, err := store.OpenAccountSession(ctx, timeValue(r.ExpiresAt))
|
||||
if err != nil {
|
||||
return nil, accountStatus(err)
|
||||
}
|
||||
return &pb.OpenAccountSessionResponse{Identity: identityProto(value.Identity), Token: value.Token, ExpiresAt: timestamp(value.Expires)}, nil
|
||||
}
|
||||
|
||||
func (s *server) RequireFreshAccountSession(ctx context.Context, r *pb.RequireFreshAccountSessionRequest) (*pb.RequireFreshAccountSessionResponse, error) {
|
||||
store, err := s.accountSecurity()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pb.RequireFreshAccountSessionResponse{}, accountStatus(store.RequireFreshAccountSession(ctx, r.Token))
|
||||
}
|
||||
|
||||
func (s *server) CreateAccountRecovery(ctx context.Context, _ *pb.CreateAccountRecoveryRequest) (*pb.CreateAccountRecoveryResponse, error) {
|
||||
store, err := s.accountSecurity()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
code, err := store.CreateAccountRecovery(ctx)
|
||||
if err != nil {
|
||||
return nil, accountStatus(err)
|
||||
}
|
||||
return &pb.CreateAccountRecoveryResponse{Code: code}, nil
|
||||
}
|
||||
|
||||
func (s *server) RecoverAccount(ctx context.Context, r *pb.RecoverAccountRequest) (*pb.RecoverAccountResponse, error) {
|
||||
store, err := s.accountSecurity()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pb.RecoverAccountResponse{}, accountStatus(store.RecoverAccount(ctx, r.Email, r.Code, r.Password))
|
||||
}
|
||||
|
||||
func (c *Client) OpenAccountSession(ctx context.Context, expires time.Time) (identity.AccountSession, error) {
|
||||
r, err := c.client.OpenAccountSession(ctx, &pb.OpenAccountSessionRequest{ExpiresAt: timestamp(expires)})
|
||||
if err != nil {
|
||||
return identity.AccountSession{}, accountClientError(err)
|
||||
}
|
||||
return identity.AccountSession{Identity: identityValue(r.Identity), Token: r.Token, Expires: timeValue(r.ExpiresAt)}, nil
|
||||
}
|
||||
|
||||
func (c *Client) RequireFreshAccountSession(ctx context.Context, token string) error {
|
||||
_, err := c.client.RequireFreshAccountSession(ctx, &pb.RequireFreshAccountSessionRequest{Token: token})
|
||||
return accountClientError(err)
|
||||
}
|
||||
|
||||
func (c *Client) CreateAccountRecovery(ctx context.Context) (string, error) {
|
||||
r, err := c.client.CreateAccountRecovery(ctx, &pb.CreateAccountRecoveryRequest{})
|
||||
if err != nil {
|
||||
return "", accountClientError(err)
|
||||
}
|
||||
return r.Code, nil
|
||||
}
|
||||
|
||||
func (c *Client) RecoverAccount(ctx context.Context, email, code, password string) error {
|
||||
_, err := c.client.RecoverAccount(ctx, &pb.RecoverAccountRequest{Email: email, Code: code, Password: password})
|
||||
return accountClientError(err)
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
)
|
||||
|
||||
func accountStatus(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, identity.ErrSetupComplete):
|
||||
return status.Error(codes.AlreadyExists, identity.ErrSetupComplete.Error())
|
||||
case errors.Is(err, identity.ErrCredentialRejected):
|
||||
return status.Error(codes.Unauthenticated, "credentials not accepted")
|
||||
default:
|
||||
return identityStatus(err)
|
||||
}
|
||||
}
|
||||
|
||||
func accountClientError(err error) error {
|
||||
switch status.Code(err) {
|
||||
case codes.AlreadyExists:
|
||||
return identity.ErrSetupComplete
|
||||
case codes.Unauthenticated:
|
||||
return identity.ErrCredentialRejected
|
||||
default:
|
||||
return identityClientError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) accountStore() (identity.Accounts, error) {
|
||||
if s.deps.Accounts == nil {
|
||||
return nil, status.Error(codes.Unavailable, "accounts unavailable")
|
||||
}
|
||||
return s.deps.Accounts, nil
|
||||
}
|
||||
|
||||
func (s *server) AccountSetup(ctx context.Context, _ *pb.AccountSetupRequest) (*pb.AccountSetupResponse, error) {
|
||||
store, err := s.accountStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
required, err := store.AccountSetupRequired(ctx)
|
||||
return &pb.AccountSetupResponse{Required: required}, accountStatus(err)
|
||||
}
|
||||
|
||||
func (s *server) RegisterAccount(ctx context.Context, r *pb.RegisterAccountRequest) (*pb.RegisterAccountResponse, error) {
|
||||
store, err := s.accountStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !r.Bootstrap {
|
||||
if err := s.authorizeAccountManagement(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
value, err := store.RegisterAccount(ctx, identity.AccountRegistration{Email: r.Email, DisplayName: r.DisplayName, Password: r.Password, Role: r.Role, OrganisationName: r.OrganisationName, WorkspaceName: r.WorkspaceName, PublicURL: r.PublicUrl}, r.Bootstrap)
|
||||
if err != nil {
|
||||
return nil, accountStatus(err)
|
||||
}
|
||||
return &pb.RegisterAccountResponse{Identity: identityProto(value)}, nil
|
||||
}
|
||||
|
||||
func (s *server) SignInAccount(ctx context.Context, r *pb.SignInAccountRequest) (*pb.SignInAccountResponse, error) {
|
||||
store, err := s.accountStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value, err := store.SignInAccount(ctx, r.Email, r.Password)
|
||||
if err != nil {
|
||||
return nil, accountStatus(err)
|
||||
}
|
||||
return &pb.SignInAccountResponse{Identity: identityProto(value.Identity), Token: value.Token, ExpiresAt: timestamp(value.Expires)}, nil
|
||||
}
|
||||
|
||||
func (s *server) ResolveAccountSession(ctx context.Context, r *pb.ResolveAccountSessionRequest) (*pb.ResolveAccountSessionResponse, error) {
|
||||
store, err := s.accountStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value, err := store.ResolveAccountSession(ctx, r.Token)
|
||||
if err != nil {
|
||||
return nil, accountStatus(err)
|
||||
}
|
||||
return &pb.ResolveAccountSessionResponse{Identity: identityProto(value)}, nil
|
||||
}
|
||||
|
||||
func (s *server) SignOutAccount(ctx context.Context, r *pb.SignOutAccountRequest) (*pb.SignOutAccountResponse, error) {
|
||||
store, err := s.accountStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pb.SignOutAccountResponse{}, accountStatus(store.SignOutAccount(ctx, r.Token))
|
||||
}
|
||||
|
||||
func (s *server) ChangeAccountPassword(ctx context.Context, r *pb.ChangeAccountPasswordRequest) (*pb.ChangeAccountPasswordResponse, error) {
|
||||
store, err := s.accountStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pb.ChangeAccountPasswordResponse{}, accountStatus(store.ChangeAccountPassword(ctx, r.CurrentPassword, r.NewPassword))
|
||||
}
|
||||
|
||||
func (c *Client) AccountSetupRequired(ctx context.Context) (bool, error) {
|
||||
r, err := c.client.AccountSetup(ctx, &pb.AccountSetupRequest{})
|
||||
return r.GetRequired(), accountClientError(err)
|
||||
}
|
||||
|
||||
func (c *Client) RegisterAccount(ctx context.Context, r identity.AccountRegistration, bootstrap bool) (identity.Identity, error) {
|
||||
out, err := c.client.RegisterAccount(ctx, &pb.RegisterAccountRequest{Email: r.Email, DisplayName: r.DisplayName, Password: r.Password, Role: r.Role, Bootstrap: bootstrap, OrganisationName: r.OrganisationName, WorkspaceName: r.WorkspaceName, PublicUrl: r.PublicURL})
|
||||
if err != nil {
|
||||
return identity.Identity{}, accountClientError(err)
|
||||
}
|
||||
return identityValue(out.Identity), nil
|
||||
}
|
||||
|
||||
func (c *Client) SignInAccount(ctx context.Context, email, password string) (identity.AccountSession, error) {
|
||||
r, err := c.client.SignInAccount(ctx, &pb.SignInAccountRequest{Email: email, Password: password})
|
||||
if err != nil {
|
||||
return identity.AccountSession{}, accountClientError(err)
|
||||
}
|
||||
return identity.AccountSession{Identity: identityValue(r.Identity), Token: r.Token, Expires: timeValue(r.ExpiresAt)}, nil
|
||||
}
|
||||
|
||||
func (c *Client) ResolveAccountSession(ctx context.Context, token string) (identity.Identity, error) {
|
||||
r, err := c.client.ResolveAccountSession(ctx, &pb.ResolveAccountSessionRequest{Token: token})
|
||||
if err != nil {
|
||||
return identity.Identity{}, accountClientError(err)
|
||||
}
|
||||
return identityValue(r.Identity), nil
|
||||
}
|
||||
|
||||
func (c *Client) SignOutAccount(ctx context.Context, token string) error {
|
||||
_, err := c.client.SignOutAccount(ctx, &pb.SignOutAccountRequest{Token: token})
|
||||
return accountClientError(err)
|
||||
}
|
||||
|
||||
func (c *Client) ChangeAccountPassword(ctx context.Context, current, next string) error {
|
||||
_, err := c.client.ChangeAccountPassword(ctx, &pb.ChangeAccountPasswordRequest{CurrentPassword: current, NewPassword: next})
|
||||
return accountClientError(err)
|
||||
}
|
||||
|
||||
func (s *server) authorizeAccountManagement(ctx context.Context) error {
|
||||
p, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return status.Error(codes.PermissionDenied, "account management requires a principal")
|
||||
}
|
||||
if s.deps.Policies == nil {
|
||||
return status.Error(codes.Unavailable, "access policies unavailable")
|
||||
}
|
||||
policies, err := s.deps.Policies.ListPolicies(access.WithoutPrincipal(ctx))
|
||||
if err != nil {
|
||||
return status.Error(codes.Unavailable, "access policies unavailable")
|
||||
}
|
||||
decision := infraaccess.New(policies).Authorize(p, access.ActionManageMembers, access.Resource{Kind: access.KindMember, Org: p.Org}, access.Context{})
|
||||
if !decision.Allowed {
|
||||
return status.Error(codes.PermissionDenied, "account management refused")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
type accountPolicyStore struct {
|
||||
access.PolicyStore
|
||||
policies []access.Policy
|
||||
}
|
||||
|
||||
func (s accountPolicyStore) ListPolicies(context.Context) ([]access.Policy, error) {
|
||||
return s.policies, nil
|
||||
}
|
||||
|
||||
type accountRegistrationStore struct{ identity.Accounts }
|
||||
|
||||
func (accountRegistrationStore) RegisterAccount(context.Context, identity.AccountRegistration, bool) (identity.Identity, error) {
|
||||
return identity.Identity{ID: "created"}, nil
|
||||
}
|
||||
|
||||
func TestAccountManagementUsesPolicy(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
role org.Role
|
||||
extra string
|
||||
anonymous bool
|
||||
want codes.Code
|
||||
}{
|
||||
{name: "administrator relationship permits", role: org.RoleAdmin, want: codes.OK},
|
||||
{name: "developer has no grant", role: org.RoleDeveloper, want: codes.PermissionDenied},
|
||||
{name: "explicit identity policy permits without admin role", role: org.RoleDeveloper, extra: `permit(principal == Archie::Identity::"alice", action == Archie::Action::"manage_members", resource);`, want: codes.OK},
|
||||
{name: "explicit forbid wins over admin role", role: org.RoleAdmin, extra: `forbid(principal,action == Archie::Action::"manage_members",resource);`, want: codes.PermissionDenied},
|
||||
{name: "unauthenticated service has no user grant", anonymous: true, want: codes.PermissionDenied},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
if !tc.anonymous {
|
||||
ctx = access.WithPrincipal(ctx, access.Principal{IdentityID: "alice", Org: "acme", Memberships: []org.Membership{{IdentityID: "alice", OrgID: "acme", Role: tc.role}}})
|
||||
}
|
||||
policies := access.ShippedOrgPolicies("acme")
|
||||
if tc.extra != "" {
|
||||
policies = append(policies, access.Policy{ID: "custom-members", Level: access.LevelOrg, OrgID: "acme", Text: tc.extra})
|
||||
}
|
||||
srv := &server{deps: Deps{Accounts: accountRegistrationStore{}, Policies: accountPolicyStore{policies: policies}}}
|
||||
_, err := srv.RegisterAccount(ctx, &pb.RegisterAccountRequest{Email: "new@example.com", Role: "viewer"})
|
||||
if got := status.Code(err); got != tc.want {
|
||||
t.Fatalf("code=%s want=%s err=%v", got, tc.want, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskCredentialsCannotManageAccounts(t *testing.T) {
|
||||
for _, method := range []string{
|
||||
pb.StateStoreService_AccountSetup_FullMethodName,
|
||||
pb.StateStoreService_RegisterAccount_FullMethodName,
|
||||
pb.StateStoreService_SignInAccount_FullMethodName,
|
||||
pb.StateStoreService_ResolveAccountSession_FullMethodName,
|
||||
pb.StateStoreService_SignOutAccount_FullMethodName,
|
||||
pb.StateStoreService_ChangeAccountPassword_FullMethodName,
|
||||
pb.StateStoreService_GetAuthenticationSettings_FullMethodName,
|
||||
pb.StateStoreService_SaveAuthenticationSettings_FullMethodName,
|
||||
pb.StateStoreService_BeginPasskey_FullMethodName,
|
||||
pb.StateStoreService_FinishPasskey_FullMethodName,
|
||||
pb.StateStoreService_ListPasskeys_FullMethodName,
|
||||
pb.StateStoreService_DeletePasskey_FullMethodName,
|
||||
pb.StateStoreService_OpenAccountSession_FullMethodName,
|
||||
pb.StateStoreService_RequireFreshAccountSession_FullMethodName,
|
||||
pb.StateStoreService_CreateAccountRecovery_FullMethodName,
|
||||
pb.StateStoreService_RecoverAccount_FullMethodName,
|
||||
} {
|
||||
t.Run(method, func(t *testing.T) {
|
||||
if authorizesTaskScopedCall(method, nil, 7) {
|
||||
t.Fatal("task credential authorizes account operation")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
func authenticationProto(v identity.AuthenticationSettings) *pb.AuthenticationSettings {
|
||||
return &pb.AuthenticationSettings{PublicUrl: v.PublicURL, OidcIssuer: v.OIDCIssuer, OidcAudience: v.OIDCAudience, OidcClientId: v.OIDCClientID}
|
||||
}
|
||||
|
||||
func authenticationValue(v *pb.AuthenticationSettings) identity.AuthenticationSettings {
|
||||
return identity.AuthenticationSettings{PublicURL: v.GetPublicUrl(), OIDCIssuer: v.GetOidcIssuer(), OIDCAudience: v.GetOidcAudience(), OIDCClientID: v.GetOidcClientId()}
|
||||
}
|
||||
|
||||
func (s *server) GetAuthenticationSettings(ctx context.Context, _ *pb.GetAuthenticationSettingsRequest) (*pb.GetAuthenticationSettingsResponse, error) {
|
||||
store, ok := s.deps.Accounts.(identity.AuthenticationSettingsStore)
|
||||
if !ok {
|
||||
return nil, status.Error(codes.Unavailable, "authentication settings unavailable")
|
||||
}
|
||||
value, err := store.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return nil, accountStatus(err)
|
||||
}
|
||||
return &pb.GetAuthenticationSettingsResponse{Settings: authenticationProto(value)}, nil
|
||||
}
|
||||
|
||||
func (s *server) SaveAuthenticationSettings(ctx context.Context, r *pb.SaveAuthenticationSettingsRequest) (*pb.SaveAuthenticationSettingsResponse, error) {
|
||||
store, ok := s.deps.Accounts.(identity.AuthenticationSettingsStore)
|
||||
if !ok {
|
||||
return nil, status.Error(codes.Unavailable, "authentication settings unavailable")
|
||||
}
|
||||
return &pb.SaveAuthenticationSettingsResponse{}, accountStatus(store.SaveAuthenticationSettings(ctx, authenticationValue(r.Settings)))
|
||||
}
|
||||
|
||||
func (c *Client) AuthenticationSettings(ctx context.Context) (identity.AuthenticationSettings, error) {
|
||||
r, err := c.client.GetAuthenticationSettings(ctx, &pb.GetAuthenticationSettingsRequest{})
|
||||
if err != nil {
|
||||
return identity.AuthenticationSettings{}, accountClientError(err)
|
||||
}
|
||||
return authenticationValue(r.Settings), nil
|
||||
}
|
||||
|
||||
func (c *Client) SaveAuthenticationSettings(ctx context.Context, v identity.AuthenticationSettings) error {
|
||||
_, err := c.client.SaveAuthenticationSettings(ctx, &pb.SaveAuthenticationSettingsRequest{Settings: authenticationProto(v)})
|
||||
return accountClientError(err)
|
||||
}
|
||||
|
||||
func (s *server) passkeyStore() (identity.Passkeys, error) {
|
||||
v, ok := s.deps.Accounts.(identity.Passkeys)
|
||||
if !ok {
|
||||
return nil, status.Error(codes.Unavailable, "passkeys unavailable")
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (s *server) BeginPasskey(ctx context.Context, r *pb.BeginPasskeyRequest) (*pb.BeginPasskeyResponse, error) {
|
||||
store, err := s.passkeyStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value, err := store.BeginPasskey(ctx, r.Registration)
|
||||
if err != nil {
|
||||
return nil, accountStatus(err)
|
||||
}
|
||||
return &pb.BeginPasskeyResponse{Token: value.Token, Options: value.Options}, nil
|
||||
}
|
||||
|
||||
func (s *server) FinishPasskey(ctx context.Context, r *pb.FinishPasskeyRequest) (*pb.FinishPasskeyResponse, error) {
|
||||
store, err := s.passkeyStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value, err := store.FinishPasskey(ctx, r.Token, r.Credential, r.Registration, r.Name)
|
||||
if err != nil {
|
||||
return nil, accountStatus(err)
|
||||
}
|
||||
return &pb.FinishPasskeyResponse{Identity: identityProto(value.Identity), Token: value.Token, ExpiresAt: timestamp(value.Expires)}, nil
|
||||
}
|
||||
|
||||
func (s *server) ListPasskeys(ctx context.Context, _ *pb.ListPasskeysRequest) (*pb.ListPasskeysResponse, error) {
|
||||
store, err := s.passkeyStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values, err := store.ListPasskeys(ctx)
|
||||
if err != nil {
|
||||
return nil, accountStatus(err)
|
||||
}
|
||||
out := &pb.ListPasskeysResponse{}
|
||||
for _, value := range values {
|
||||
out.Passkeys = append(out.Passkeys, &pb.Passkey{Id: value.ID, Name: value.Name})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *server) DeletePasskey(ctx context.Context, r *pb.DeletePasskeyRequest) (*pb.DeletePasskeyResponse, error) {
|
||||
store, err := s.passkeyStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pb.DeletePasskeyResponse{}, accountStatus(store.DeletePasskey(ctx, r.Id))
|
||||
}
|
||||
|
||||
func (c *Client) BeginPasskey(ctx context.Context, registration bool) (identity.PasskeyCeremony, error) {
|
||||
r, err := c.client.BeginPasskey(ctx, &pb.BeginPasskeyRequest{Registration: registration})
|
||||
if err != nil {
|
||||
return identity.PasskeyCeremony{}, accountClientError(err)
|
||||
}
|
||||
return identity.PasskeyCeremony{Token: r.Token, Options: r.Options}, nil
|
||||
}
|
||||
|
||||
func (c *Client) FinishPasskey(ctx context.Context, token string, credential []byte, registration bool, name string) (identity.AccountSession, error) {
|
||||
r, err := c.client.FinishPasskey(ctx, &pb.FinishPasskeyRequest{Token: token, Credential: credential, Registration: registration, Name: name})
|
||||
if err != nil {
|
||||
return identity.AccountSession{}, accountClientError(err)
|
||||
}
|
||||
return identity.AccountSession{Identity: identityValue(r.Identity), Token: r.Token, Expires: timeValue(r.ExpiresAt)}, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListPasskeys(ctx context.Context) ([]identity.Passkey, error) {
|
||||
r, err := c.client.ListPasskeys(ctx, &pb.ListPasskeysRequest{})
|
||||
if err != nil {
|
||||
return nil, accountClientError(err)
|
||||
}
|
||||
out := []identity.Passkey{}
|
||||
for _, v := range r.Passkeys {
|
||||
out = append(out, identity.Passkey{ID: v.Id, Name: v.Name})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *Client) DeletePasskey(ctx context.Context, id string) error {
|
||||
_, err := c.client.DeletePasskey(ctx, &pb.DeletePasskeyRequest{Id: id})
|
||||
return accountClientError(err)
|
||||
}
|
||||
@@ -69,6 +69,7 @@ const taskLogChunkBytes = 256 << 10
|
||||
type Deps struct {
|
||||
ControlPlane controlpb.ControlPlaneServiceServer
|
||||
Identities identity.Repository
|
||||
Accounts identity.Accounts
|
||||
// SubjectBindings fronts the subject-binding surface, which only the
|
||||
// authenticating path needs. Unset means this process cannot resolve a
|
||||
// verified subject, and the RPCs answer Unavailable rather than pretending.
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/ratelimit"
|
||||
)
|
||||
|
||||
const accountCookie = "archie_session"
|
||||
|
||||
func (s *Server) registerAccountRoutes(public, protected *http.ServeMux) {
|
||||
if s.Accounts == nil {
|
||||
return
|
||||
}
|
||||
s.accountRateLimit = ratelimit.New(time.Minute, 20)
|
||||
public.HandleFunc("GET /api/auth/status", s.handleAccountStatus)
|
||||
public.HandleFunc("POST /api/auth/setup", s.handleAccountSetup)
|
||||
public.HandleFunc("POST /api/auth/login", s.handleAccountLogin)
|
||||
public.HandleFunc("POST /api/auth/logout", s.handleAccountLogout)
|
||||
public.HandleFunc("POST /api/auth/recover", s.handleAccountRecover)
|
||||
protected.HandleFunc("POST /api/accounts", s.handleAccountCreate)
|
||||
personal := http.NewServeMux()
|
||||
personal.HandleFunc("POST /api/account/password", s.handleAccountPassword)
|
||||
personal.HandleFunc("POST /api/account/recovery", s.handleAccountRecovery)
|
||||
public.Handle("/api/account/", s.requireAccount(s.authorizeAccountSelf(personal)))
|
||||
protected.HandleFunc("GET /api/authentication", s.handleAuthenticationSettings)
|
||||
protected.HandleFunc("PUT /api/authentication", s.handleAuthenticationSettings)
|
||||
s.registerPasskeyRoutes(public, personal)
|
||||
}
|
||||
|
||||
func (s *Server) accountIdentity(r *http.Request) (identity.Identity, error) {
|
||||
if c, err := r.Cookie(accountCookie); err == nil {
|
||||
value, err := s.Accounts.ResolveAccountSession(r.Context(), c.Value)
|
||||
if err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
if err := s.verifyAccountProvider(r, value); err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
if s.Authenticate != nil && strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
|
||||
return s.Authenticate(r.Context(), strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
|
||||
}
|
||||
if cookie, err := r.Cookie(providerTokenCookie); err == nil {
|
||||
return s.authenticateBrowser(r.Context(), cookie.Value)
|
||||
}
|
||||
|
||||
return identity.Identity{}, identity.ErrNoCredential
|
||||
}
|
||||
|
||||
func (s *Server) requireAccount(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
value, err := s.accountIdentity(r)
|
||||
if err != nil || value.Kind != identity.KindUser || !value.CanAct() {
|
||||
if err == nil {
|
||||
err = identity.ErrCredentialRejected
|
||||
}
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
h.ServeHTTP(w, r.WithContext(WithActingIdentity(r.Context(), value)))
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAccountStatus(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
required, err := s.Accounts.AccountSetupRequired(r.Context())
|
||||
if err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
var user *identity.Identity
|
||||
value, err := s.accountIdentity(r)
|
||||
if err == nil && value.Kind == identity.KindUser && value.CanAct() {
|
||||
user = &value
|
||||
} else if err != nil && !errors.Is(err, identity.ErrNoCredential) && !errors.Is(err, identity.ErrCredentialRejected) && !errors.Is(err, identity.ErrIdentityInactive) && !errors.Is(err, identity.ErrSubjectUnbound) {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
oidcEnabled := s.Login != nil
|
||||
publicURL := ""
|
||||
if store, ok := s.authenticationSettings(); ok {
|
||||
settings, settingsErr := store.AuthenticationSettings(r.Context())
|
||||
if settingsErr != nil {
|
||||
s.writeAccountError(w, settingsErr)
|
||||
return
|
||||
}
|
||||
publicURL = settings.PublicURL
|
||||
if settings.PublicURL != "" {
|
||||
oidcEnabled = settings.OIDCIssuer != ""
|
||||
}
|
||||
}
|
||||
writeJSON(w, map[string]any{"setup_required": required, "user": user, "oidc": oidcEnabled, "public_url": publicURL})
|
||||
}
|
||||
|
||||
func decodeAccountRequest(w http.ResponseWriter, r *http.Request, value any) bool {
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(value); err != nil {
|
||||
http.Error(w, "invalid account request", http.StatusBadRequest)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) handleAccountSetup(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeAuthenticationMutation(w, r) {
|
||||
return
|
||||
}
|
||||
var request identity.AccountRegistration
|
||||
if !decodeAccountRequest(w, r, &request) {
|
||||
return
|
||||
}
|
||||
if _, err := s.Accounts.RegisterAccount(r.Context(), request, true); err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
s.signInAccount(w, r, request.Email, request.Password)
|
||||
}
|
||||
|
||||
func (s *Server) handleAccountLogin(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeAuthenticationMutation(w, r) {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if !decodeAccountRequest(w, r, &request) {
|
||||
return
|
||||
}
|
||||
s.signInAccount(w, r, request.Email, request.Password)
|
||||
}
|
||||
|
||||
func (s *Server) signInAccount(w http.ResponseWriter, r *http.Request, email, password string) {
|
||||
value, err := s.Accounts.SignInAccount(r.Context(), email, password)
|
||||
if err != nil {
|
||||
s.logf("account sign-in refused", "peer", r.RemoteAddr)
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
if s.Log != nil {
|
||||
s.Log.Info("account signed in", "identity", value.Identity.ID)
|
||||
}
|
||||
s.clearProviderCookie(w)
|
||||
s.setAccountCookie(w, r, value)
|
||||
writeJSON(w, map[string]any{"user": value.Identity})
|
||||
}
|
||||
|
||||
func (s *Server) setAccountCookie(w http.ResponseWriter, r *http.Request, value identity.AccountSession) {
|
||||
scheme, _ := s.expectedOrigin(r)
|
||||
http.SetCookie(w, &http.Cookie{Name: accountCookie, Value: value.Token, Path: "/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, Expires: value.Expires, MaxAge: int(time.Until(value.Expires).Seconds())})
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
}
|
||||
|
||||
func (s *Server) handleAccountLogout(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeAuthenticationMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if c, err := r.Cookie(accountCookie); err == nil {
|
||||
if err = s.Accounts.SignOutAccount(r.Context(), c.Value); err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
for _, name := range []string{accountCookie, providerTokenCookie} {
|
||||
http.SetCookie(w, &http.Cookie{Name: name, Path: "/", HttpOnly: true, MaxAge: -1, SameSite: http.SameSiteStrictMode})
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) handleAccountCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeAuthenticationMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if !s.requireFreshAccount(w, r) {
|
||||
return
|
||||
}
|
||||
var request identity.AccountRegistration
|
||||
if !decodeAccountRequest(w, r, &request) {
|
||||
return
|
||||
}
|
||||
value, err := s.Accounts.RegisterAccount(r.Context(), request, false)
|
||||
if err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, map[string]any{"user": value})
|
||||
}
|
||||
|
||||
func (s *Server) handleAccountPassword(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeAuthenticationMutation(w, r) {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Current string `json:"current_password"`
|
||||
New string `json:"new_password"`
|
||||
}
|
||||
if !decodeAccountRequest(w, r, &request) {
|
||||
return
|
||||
}
|
||||
if err := s.Accounts.ChangeAccountPassword(r.Context(), request.Current, request.New); err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: accountCookie, Path: "/", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteStrictMode})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) writeAccountError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, identity.ErrNoCredential), errors.Is(err, identity.ErrCredentialRejected), errors.Is(err, identity.ErrIdentityInactive), errors.Is(err, identity.ErrSubjectUnbound):
|
||||
http.Error(w, "Sign-in required or credentials not accepted.", http.StatusUnauthorized)
|
||||
case errors.Is(err, identity.ErrSetupComplete):
|
||||
http.Error(w, identity.ErrSetupComplete.Error(), http.StatusConflict)
|
||||
case errors.Is(err, identity.ErrNotFound):
|
||||
http.Error(w, "Record not found.", http.StatusNotFound)
|
||||
case errors.Is(err, identity.ErrConflict):
|
||||
http.Error(w, "An account already uses that email.", http.StatusConflict)
|
||||
case errors.Is(err, identity.ErrInvalid):
|
||||
http.Error(w, "Enter a name, valid email, organisation name for setup, and an uncommon password of at least 15 characters (at most 1024 bytes).", http.StatusBadRequest)
|
||||
default:
|
||||
s.logf("account operation failed", "err", err)
|
||||
http.Error(w, "Account service unavailable.", http.StatusServiceUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) authenticationSettings() (identity.AuthenticationSettingsStore, bool) {
|
||||
value, ok := s.Accounts.(identity.AuthenticationSettingsStore)
|
||||
return value, ok
|
||||
}
|
||||
|
||||
func (s *Server) handleAuthenticationSettings(w http.ResponseWriter, r *http.Request) {
|
||||
if !instanceOwner(r) {
|
||||
http.Error(w, "instance administrator required", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
store, ok := s.authenticationSettings()
|
||||
if !ok {
|
||||
http.Error(w, "authentication settings unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
value, err := store.AuthenticationSettings(r.Context())
|
||||
if err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, value)
|
||||
return
|
||||
}
|
||||
if !s.requireFreshAccount(w, r) {
|
||||
return
|
||||
}
|
||||
if !s.authorizeAuthenticationMutation(w, r) {
|
||||
return
|
||||
}
|
||||
var value identity.AuthenticationSettings
|
||||
if !decodeAccountRequest(w, r, &value) {
|
||||
return
|
||||
}
|
||||
if err := store.SaveAuthenticationSettings(r.Context(), value); err != nil {
|
||||
if errors.Is(err, identity.ErrInvalid) {
|
||||
http.Error(w, "Use a valid instance origin and complete OIDC settings. Remove enrolled passkeys before changing the instance URL.", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) authorizeAccountSelf(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
acting, ok := ActingIdentity(r.Context())
|
||||
if !ok || acting.Kind != identity.KindUser || !acting.CanAct() {
|
||||
http.Error(w, "sign-in required", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
principal, err := s.requestPrincipal(r.Context())
|
||||
if err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
h.ServeHTTP(w, r.WithContext(org.WithOrg(access.WithPrincipal(r.Context(), principal), principal.Org)))
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) requireFreshAccount(w http.ResponseWriter, r *http.Request) bool {
|
||||
store, ok := s.Accounts.(identity.AccountSecurity)
|
||||
if !ok {
|
||||
http.Error(w, "account security unavailable", http.StatusServiceUnavailable)
|
||||
return false
|
||||
}
|
||||
cookie, err := r.Cookie(accountCookie)
|
||||
if err == nil {
|
||||
err = store.RequireFreshAccountSession(r.Context(), cookie.Value)
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "Sign in again before changing account security.", http.StatusForbidden)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) handleAccountRecovery(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) || !s.requireFreshAccount(w, r) {
|
||||
return
|
||||
}
|
||||
store, ok := s.Accounts.(identity.AccountSecurity)
|
||||
if !ok {
|
||||
http.Error(w, "account security unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
code, err := store.CreateAccountRecovery(r.Context())
|
||||
if err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, map[string]string{"code": code})
|
||||
}
|
||||
|
||||
func (s *Server) handleAccountRecover(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeAuthenticationMutation(w, r) {
|
||||
return
|
||||
}
|
||||
store, ok := s.Accounts.(identity.AccountSecurity)
|
||||
if !ok {
|
||||
http.Error(w, "account security unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Email string `json:"email"`
|
||||
Code string `json:"code"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if !decodeAccountRequest(w, r, &request) {
|
||||
return
|
||||
}
|
||||
if err := store.RecoverAccount(r.Context(), request.Email, request.Code, request.Password); err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) clearProviderCookie(w http.ResponseWriter) {
|
||||
http.SetCookie(w, &http.Cookie{Name: providerTokenCookie, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
|
||||
}
|
||||
|
||||
func (s *Server) authorizeAuthenticationMutation(w http.ResponseWriter, r *http.Request) bool {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return false
|
||||
}
|
||||
scheme, host := s.expectedOrigin(r)
|
||||
hostname := host
|
||||
if name, _, err := net.SplitHostPort(host); err == nil {
|
||||
hostname = name
|
||||
}
|
||||
local := strings.EqualFold(hostname, "localhost") || (net.ParseIP(hostname) != nil && net.ParseIP(hostname).IsLoopback())
|
||||
if scheme != "https" && !local {
|
||||
http.Error(w, "Account credentials require HTTPS. Use a TLS proxy, or localhost for development.", http.StatusForbidden)
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/api/auth/") && s.accountRateLimit != nil {
|
||||
peer, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
peer = r.RemoteAddr
|
||||
}
|
||||
s.accountRateLimit.EvictStale()
|
||||
if !s.accountRateLimit.Allow("authentication", peer) {
|
||||
w.Header().Set("Retry-After", "60")
|
||||
http.Error(w, "Too many sign-in attempts. Try again shortly.", http.StatusTooManyRequests)
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) verifyAccountProvider(r *http.Request, value identity.Identity) error {
|
||||
cookie, err := r.Cookie(providerTokenCookie)
|
||||
if errors.Is(err, http.ErrNoCookie) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
providerValue, err := s.authenticateBrowser(r.Context(), cookie.Value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if providerValue.ID != value.ID {
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) authenticateBrowser(ctx context.Context, credential string) (identity.Identity, error) {
|
||||
verify := s.AuthenticateBrowser
|
||||
if verify == nil {
|
||||
verify = s.Authenticate
|
||||
}
|
||||
if verify == nil {
|
||||
return identity.Identity{}, identity.ErrCredentialRejected
|
||||
}
|
||||
return verify(ctx, credential)
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
)
|
||||
|
||||
type accountBoundaryStore struct {
|
||||
identity.Accounts
|
||||
identity.AccountSecurity
|
||||
fresh bool
|
||||
}
|
||||
|
||||
func (accountBoundaryStore) AccountSetupRequired(context.Context) (bool, error) { return false, nil }
|
||||
|
||||
func (accountBoundaryStore) ResolveAccountSession(_ context.Context, token string) (identity.Identity, error) {
|
||||
if token != "valid" {
|
||||
return identity.Identity{}, identity.ErrCredentialRejected
|
||||
}
|
||||
return identity.Identity{ID: "alice", Kind: identity.KindUser, DisplayName: "Alice", Lifecycle: identity.LifecycleActive}, nil
|
||||
}
|
||||
|
||||
func (accountBoundaryStore) SignInAccount(_ context.Context, email, password string) (identity.AccountSession, error) {
|
||||
if email != "alice@example.com" || password != "a sufficiently long password" {
|
||||
return identity.AccountSession{}, identity.ErrCredentialRejected
|
||||
}
|
||||
return identity.AccountSession{Identity: identity.Identity{ID: "alice", Kind: identity.KindUser, Lifecycle: identity.LifecycleActive}, Token: "new-session", Expires: time.Now().Add(time.Hour)}, nil
|
||||
}
|
||||
|
||||
func (s accountBoundaryStore) RequireFreshAccountSession(context.Context, string) error {
|
||||
if !s.fresh {
|
||||
return identity.ErrCredentialRejected
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (accountBoundaryStore) CreateAccountRecovery(context.Context) (string, error) {
|
||||
return "one-use-recovery-code", nil
|
||||
}
|
||||
|
||||
func TestAccountBoundary(t *testing.T) {
|
||||
principal := access.Principal{IdentityID: "alice", Org: "acme", Memberships: []org.Membership{{IdentityID: "alice", OrgID: "acme", Role: org.RoleViewer}}}
|
||||
for _, tc := range []struct {
|
||||
name, method, path, body, cookie, csrf string
|
||||
fresh bool
|
||||
want int
|
||||
}{
|
||||
{name: "shared token cannot authenticate", method: "GET", path: "/api/summary", cookie: "legacy", want: 401},
|
||||
{name: "API reads reach authentication", method: "GET", path: "/api/chat/sessions", want: 401},
|
||||
{name: "valid cookie reaches protected API", method: "GET", path: "/api/chat/sessions", cookie: "valid", want: 501},
|
||||
{name: "login requires CSRF", method: "POST", path: "/api/auth/login", body: `{"email":"alice@example.com","password":"a sufficiently long password"}`, want: 403},
|
||||
{name: "incorrect credentials use generic refusal", method: "POST", path: "/api/auth/login", csrf: "1", body: `{"email":"unknown@example.com","password":"wrong"}`, want: 401},
|
||||
{name: "successful login", method: "POST", path: "/api/auth/login", csrf: "1", body: `{"email":"alice@example.com","password":"a sufficiently long password"}`, want: 200},
|
||||
{name: "anonymous cannot manage personal security", method: "POST", path: "/api/account/recovery", csrf: "1", body: `{}`, want: 401},
|
||||
{name: "viewer manages own security after recent sign in", method: "POST", path: "/api/account/recovery", csrf: "1", body: `{}`, cookie: "valid", fresh: true, want: 200},
|
||||
{name: "stale session cannot replace recovery", method: "POST", path: "/api/account/recovery", csrf: "1", body: `{}`, cookie: "valid", want: 403},
|
||||
{name: "viewer cannot create accounts", method: "POST", path: "/api/accounts", csrf: "1", body: `{}`, cookie: "valid", fresh: true, want: 403},
|
||||
{name: "viewer cannot edit instance authentication", method: "PUT", path: "/api/authentication", csrf: "1", body: `{}`, cookie: "valid", fresh: true, want: 403},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := &Server{Accounts: accountBoundaryStore{fresh: tc.fresh}, Access: infraaccess.New(access.ShippedOrgPolicies("acme")), Principals: principalOf(principal)}
|
||||
req := httptest.NewRequestWithContext(t.Context(), tc.method, "https://archie.example"+tc.path, strings.NewReader(tc.body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", tc.csrf)
|
||||
if tc.cookie != "" {
|
||||
req.AddCookie(&http.Cookie{Name: accountCookie, Value: tc.cookie})
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(recorder, req)
|
||||
if recorder.Code != tc.want {
|
||||
t.Fatalf("status=%d want=%d body=%s", recorder.Code, tc.want, recorder.Body.String())
|
||||
}
|
||||
if tc.name == "successful login" {
|
||||
var found bool
|
||||
for _, cookie := range recorder.Result().Cookies() {
|
||||
if cookie.Name == accountCookie {
|
||||
found = true
|
||||
if !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteStrictMode || cookie.Value != "new-session" {
|
||||
t.Fatalf("unsafe session cookie: %+v", cookie)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("login did not set a session")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticationTransport(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, url, origin, csrf string
|
||||
want bool
|
||||
}{
|
||||
{"TLS", "https://archie.example/api/auth/login", "https://archie.example", "1", true},
|
||||
{"localhost development", "http://localhost:8484/api/auth/login", "http://localhost:8484", "1", true},
|
||||
{"network cleartext", "http://archie.example/api/auth/login", "http://archie.example", "1", false},
|
||||
{"cross origin", "https://archie.example/api/auth/login", "https://attacker.example", "1", false},
|
||||
{"missing CSRF", "https://archie.example/api/auth/login", "https://archie.example", "", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequestWithContext(t.Context(), "POST", tc.url, strings.NewReader(`{}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", tc.csrf)
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
if got := (&Server{}).authorizeAuthenticationMutation(httptest.NewRecorder(), req); got != tc.want {
|
||||
t.Fatalf("allowed=%v want=%v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountSessionFailureIsClosed(t *testing.T) {
|
||||
srv := &Server{Accounts: unavailableAccounts{}}
|
||||
req := httptest.NewRequestWithContext(t.Context(), "GET", "https://archie.example/api/auth/status", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
srv.handleAccountStatus(rec, req)
|
||||
if rec.Code != 503 {
|
||||
t.Fatalf("account outage status=%d, want 503", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
type unavailableAccounts struct{ identity.Accounts }
|
||||
|
||||
func (unavailableAccounts) AccountSetupRequired(context.Context) (bool, error) {
|
||||
return false, errors.New("store unavailable")
|
||||
}
|
||||
@@ -163,7 +163,7 @@ func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
out := make([]messaging.SessionContext, 0, len(snapshot.Sessions))
|
||||
active := make(map[string]string)
|
||||
for _, session := range snapshot.Sessions {
|
||||
if session.Source.Platform == "web" {
|
||||
if s.ownsChatSession(r.Context(), session) {
|
||||
out = append(out, session)
|
||||
if name, ok := snapshot.ActivePersonas[session.SessionID]; ok {
|
||||
active[session.SessionID] = name
|
||||
@@ -200,7 +200,7 @@ func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found || session.Source.Platform != "web" {
|
||||
if !found || !s.ownsChatSession(r.Context(), session) {
|
||||
http.Error(w, "session not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
@@ -231,7 +231,7 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found || session.Source.Platform != "web" {
|
||||
if !found || !s.ownsChatSession(r.Context(), session) {
|
||||
http.Error(w, "session not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
@@ -290,7 +290,8 @@ func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (mess
|
||||
return messaging.Inbound{
|
||||
Message: messaging.Message{
|
||||
SourceID: req.SourceID,
|
||||
ConversationID: messaging.ConversationID{ChannelID: req.ChannelID},
|
||||
ConversationID: messaging.ConversationID{ChannelID: req.ChannelID, ThreadID: chatUser(r.Context())},
|
||||
SenderID: chatUser(r.Context()),
|
||||
Sender: "web",
|
||||
Role: messaging.RoleUser,
|
||||
Text: req.Text,
|
||||
@@ -345,6 +346,7 @@ type chatStreamSink struct {
|
||||
showToolCalls bool
|
||||
// files hands out downloads for the local files a turn sends.
|
||||
files *chatFiles
|
||||
owner string
|
||||
}
|
||||
|
||||
func (s chatStreamSink) Delta(text string) {
|
||||
@@ -394,7 +396,7 @@ func (s chatStreamSink) Media(event messaging.MediaEvent) {
|
||||
if name == "" {
|
||||
name = filepath.Base(att.Path)
|
||||
}
|
||||
s.write(chatStreamEvent{Type: "delta", Text: "\n\n📎 [" + name + "](" + chatFileURL(s.files.offer(att.Path, att.FileName)) + ")"})
|
||||
s.write(chatStreamEvent{Type: "delta", Text: "\n\n📎 [" + name + "](" + chatFileURL(s.files.offerFor(att.Path, att.FileName, s.owner)) + ")"})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -442,7 +444,7 @@ func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
|
||||
writeChatEvent(chatStreamEvent{Type: "error", Text: err.Error()}, "")
|
||||
return
|
||||
}
|
||||
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls(r.Context()), files: &s.chatFiles}
|
||||
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls(r.Context()), files: &s.chatFiles, owner: chatUser(r.Context())}
|
||||
for event := range events {
|
||||
sink.write = func(frame chatStreamEvent) { writeChatEvent(frame, event.SessionID) }
|
||||
switch event.Kind {
|
||||
@@ -480,7 +482,7 @@ func (s *Server) handleChatCancel(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found || session.Source.Platform != "web" {
|
||||
if !found || !s.ownsChatSession(r.Context(), session) {
|
||||
http.Error(w, "session not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
@@ -514,7 +516,7 @@ func (s *Server) handleChatPersona(w http.ResponseWriter, r *http.Request) {
|
||||
if session, found, err := chat.Contract.GetSession(r.Context(), req.SessionID); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
} else if !found || session.Source.Platform != "web" {
|
||||
} else if !found || !s.ownsChatSession(r.Context(), session) {
|
||||
http.Error(w, "session not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
@@ -641,3 +643,16 @@ func newChatSourceID() string {
|
||||
}
|
||||
return "web-" + id.String()
|
||||
}
|
||||
|
||||
// The server supplies the person thread; browser-supplied conversation IDs
|
||||
// cannot select another person's history.
|
||||
func chatUser(ctx context.Context) string {
|
||||
if value, ok := ActingIdentity(ctx); ok {
|
||||
return string(value.ID)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) ownsChatSession(ctx context.Context, session messaging.SessionContext) bool {
|
||||
return session.Source.Platform == "web" && session.Source.ThreadID == chatUser(ctx)
|
||||
}
|
||||
@@ -31,9 +31,10 @@ type chatAskChoice struct {
|
||||
type chatAsks struct {
|
||||
mu sync.Mutex
|
||||
waiting map[string]chan string
|
||||
owners map[string]string
|
||||
}
|
||||
|
||||
func (a *chatAsks) open() (string, chan string) {
|
||||
func (a *chatAsks) open(owner string) (string, chan string) {
|
||||
var b [12]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
id := hex.EncodeToString(b[:])
|
||||
@@ -41,8 +42,10 @@ func (a *chatAsks) open() (string, chan string) {
|
||||
a.mu.Lock()
|
||||
if a.waiting == nil {
|
||||
a.waiting = make(map[string]chan string)
|
||||
a.owners = make(map[string]string)
|
||||
}
|
||||
a.waiting[id] = ch
|
||||
a.owners[id] = owner
|
||||
a.mu.Unlock()
|
||||
return id, ch
|
||||
}
|
||||
@@ -50,12 +53,14 @@ func (a *chatAsks) open() (string, chan string) {
|
||||
func (a *chatAsks) close(id string) {
|
||||
a.mu.Lock()
|
||||
delete(a.waiting, id)
|
||||
delete(a.owners, id)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *chatAsks) answer(id, answer string) bool {
|
||||
func (a *chatAsks) answer(id, answer, owner string) bool {
|
||||
a.mu.Lock()
|
||||
ch, ok := a.waiting[id]
|
||||
ok = ok && a.owners[id] == owner
|
||||
a.mu.Unlock()
|
||||
if ok {
|
||||
select {
|
||||
@@ -74,7 +79,7 @@ type dashboardAsker struct {
|
||||
}
|
||||
|
||||
func (d dashboardAsker) ask(ctx context.Context, q chatAsk) (string, error) {
|
||||
id, ch := d.asks.open()
|
||||
id, ch := d.asks.open(chatUser(ctx))
|
||||
defer d.asks.close(id)
|
||||
q.ID = id
|
||||
d.write(chatStreamEvent{Type: "ask", Ask: &q})
|
||||
@@ -152,7 +157,7 @@ func (s *Server) handleChatAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "id is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !s.chatAsks.answer(req.ID, req.Answer) {
|
||||
if !s.chatAsks.answer(req.ID, req.Answer, chatUser(r.Context())) {
|
||||
http.Error(w, "that question is no longer waiting", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ type chatFiles struct {
|
||||
type chatFile struct {
|
||||
path string
|
||||
name string
|
||||
owner string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
@@ -37,7 +38,9 @@ func (c *chatFiles) clock() time.Time {
|
||||
}
|
||||
|
||||
// offer registers path and returns the token that downloads it.
|
||||
func (c *chatFiles) offer(path, name string) string {
|
||||
func (c *chatFiles) offer(path, name string) string { return c.offerFor(path, name, "") }
|
||||
|
||||
func (c *chatFiles) offerFor(path, name, owner string) string {
|
||||
var b [16]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
token := hex.EncodeToString(b[:])
|
||||
@@ -55,7 +58,7 @@ func (c *chatFiles) offer(path, name string) string {
|
||||
delete(c.files, t)
|
||||
}
|
||||
}
|
||||
c.files[token] = chatFile{path: path, name: name, expires: now.Add(chatFileTTL)}
|
||||
c.files[token] = chatFile{path: path, name: name, owner: owner, expires: now.Add(chatFileTTL)}
|
||||
return token
|
||||
}
|
||||
|
||||
@@ -71,7 +74,7 @@ func (c *chatFiles) lookup(token string) (chatFile, bool) {
|
||||
|
||||
func (s *Server) handleChatFile(w http.ResponseWriter, r *http.Request) {
|
||||
f, ok := s.chatFiles.lookup(r.PathValue("token"))
|
||||
if !ok {
|
||||
if !ok || f.owner != chatUser(r.Context()) {
|
||||
http.Error(w, "that file is no longer available", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
// TestChatFileDownload: only a file a turn offered is served, and only until
|
||||
@@ -20,9 +22,11 @@ func TestChatFileDownload(t *testing.T) {
|
||||
srv := &Server{}
|
||||
srv.chatFiles.now = func() time.Time { return now }
|
||||
token := srv.chatFiles.offer(path, "")
|
||||
private := srv.chatFiles.offerFor(path, "", "alice")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
user string
|
||||
token string
|
||||
after time.Duration
|
||||
want int
|
||||
@@ -30,12 +34,19 @@ func TestChatFileDownload(t *testing.T) {
|
||||
{name: "an offered file is served", token: token, want: http.StatusOK},
|
||||
{name: "a token nobody was given is refused", token: "0123456789abcdef0123456789abcdef", want: http.StatusNotFound},
|
||||
{name: "a path is not a token", token: "..%2f..%2fetc%2fpasswd", want: http.StatusNotFound},
|
||||
{name: "owner downloads private file", user: "alice", token: private, want: http.StatusOK},
|
||||
{name: "another person cannot download", user: "bob", token: private, want: http.StatusNotFound},
|
||||
{name: "unidentified caller cannot download private file", token: private, want: http.StatusNotFound},
|
||||
{name: "an expired token is refused", token: token, after: chatFileTTL + time.Second, want: http.StatusNotFound},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv.chatFiles.now = func() time.Time { return now.Add(tt.after) }
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/chat/file/x", nil)
|
||||
ctx := t.Context()
|
||||
if tt.user != "" {
|
||||
ctx = WithActingIdentity(ctx, identity.Identity{ID: identity.IdentityID(tt.user)})
|
||||
}
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/chat/file/x", nil)
|
||||
req.SetPathValue("token", tt.token)
|
||||
rec := httptest.NewRecorder()
|
||||
srv.handleChatFile(rec, req)
|
||||
|
||||
@@ -220,7 +220,7 @@ func (s *Server) handleOrgMemberAdd(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if s.Subjects == nil || s.Identities == nil || s.Issuer == "" {
|
||||
if s.Subjects == nil || s.Identities == nil || s.memberIssuer(r) == "" {
|
||||
http.Error(w, "adding a person needs a configured identity provider", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -281,9 +281,9 @@ func (s *Server) decodeMemberAdd(w http.ResponseWriter, r *http.Request) (reques
|
||||
http.Error(w, "give either a subject or an email", http.StatusBadRequest)
|
||||
return request, bound, name, false
|
||||
case subject != "":
|
||||
bound, name = identity.Subject{Issuer: s.Issuer, Subject: subject}, cmp.Or(name, subject)
|
||||
bound, name = identity.Subject{Issuer: s.memberIssuer(r), Subject: subject}, cmp.Or(name, subject)
|
||||
default:
|
||||
bound, name = identity.EmailSubject(s.Issuer, email), cmp.Or(name, email)
|
||||
bound, name = identity.EmailSubject(s.memberIssuer(r), email), cmp.Or(name, email)
|
||||
}
|
||||
if err := org.Role(request.Role).Validate(); err != nil {
|
||||
writeOrgError(w, err)
|
||||
@@ -405,3 +405,16 @@ func writeOrgError(w http.ResponseWriter, err error) {
|
||||
writeControlPlaneError(w, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) memberIssuer(r *http.Request) string {
|
||||
if store, ok := s.authenticationSettings(); ok {
|
||||
value, err := store.AuthenticationSettings(r.Context())
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if value.PublicURL != "" {
|
||||
return value.OIDCIssuer
|
||||
}
|
||||
}
|
||||
return s.Issuer
|
||||
}
|
||||
+19
-1
@@ -15,6 +15,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
@@ -105,6 +106,9 @@ func LoadOrCreateToken(path string) (string, error) {
|
||||
// token when an identity provider is configured, else the shared token. A
|
||||
// ?t= token is moved into a cookie and the request redirected.
|
||||
func (s *Server) requireToken(h http.Handler) http.Handler {
|
||||
if s.Accounts != nil {
|
||||
return s.requireAccount(h)
|
||||
}
|
||||
if s.Authenticate != nil {
|
||||
return s.requireIdentity(h)
|
||||
}
|
||||
@@ -244,12 +248,26 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
|
||||
s.refuseUnidentified(w, r, err)
|
||||
return
|
||||
}
|
||||
if _, err := s.Authenticate(r.Context(), session.Token); err != nil {
|
||||
value, err := s.authenticateBrowser(r.Context(), session.Token)
|
||||
if err != nil {
|
||||
s.refuseUnidentified(w, r, err)
|
||||
return
|
||||
}
|
||||
clearFlowCookie(w, r, loginStateCookie)
|
||||
clearFlowCookie(w, r, loginVerifierCookie)
|
||||
if security, ok := s.Accounts.(identity.AccountSecurity); ok {
|
||||
principal, resolveErr := s.Principals.PrincipalFor(r.Context(), value.ID)
|
||||
if resolveErr != nil {
|
||||
s.writeAccountError(w, resolveErr)
|
||||
return
|
||||
}
|
||||
local, openErr := security.OpenAccountSession(access.WithPrincipal(r.Context(), principal), session.Expires)
|
||||
if openErr != nil {
|
||||
s.writeAccountError(w, openErr)
|
||||
return
|
||||
}
|
||||
s.setAccountCookie(w, r, local)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: providerTokenCookie, Value: session.Token, Path: "/",
|
||||
HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil,
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
)
|
||||
|
||||
type authorizationTasks struct{ storecontract.TaskStore }
|
||||
|
||||
func (authorizationTasks) TaskByID(context.Context, int64) (*task.Task, error) {
|
||||
return &task.Task{ID: 7}, nil
|
||||
}
|
||||
|
||||
// These are the policy-governed HTTP surfaces. Protocol entry points and
|
||||
// private account resources have separate credential/ownership behavior tests.
|
||||
func TestHTTPPolicyCannotBeBypassed(t *testing.T) {
|
||||
routes := []struct{ method, path string }{
|
||||
{"DELETE", "/api/access/policies"},
|
||||
{"DELETE", "/api/bindings/7"},
|
||||
{"DELETE", "/api/event-types/7"},
|
||||
{"DELETE", "/api/extensions/sample"},
|
||||
{"DELETE", "/api/mappings/7"},
|
||||
{"DELETE", "/api/orgs/7/members/sample"},
|
||||
{"DELETE", "/api/sources/sample"},
|
||||
{"DELETE", "/api/tokens/7"},
|
||||
{"GET", "/api/access/policies"},
|
||||
{"GET", "/api/alerts"},
|
||||
{"GET", "/api/authentication"},
|
||||
{"GET", "/api/bindings"},
|
||||
{"GET", "/api/bindings/7"},
|
||||
{"GET", "/api/bindings/7/dispatches"},
|
||||
{"GET", "/api/capabilities"},
|
||||
{"GET", "/api/captures"},
|
||||
{"GET", "/api/captures/7/dispatches"},
|
||||
{"GET", "/api/channels"},
|
||||
{"GET", "/api/chat/file/sample"},
|
||||
{"GET", "/api/chat/sessions"},
|
||||
{"GET", "/api/chat/sessions/7/messages"},
|
||||
{"GET", "/api/chat/sessions/7/turns"},
|
||||
{"GET", "/api/chat/update"},
|
||||
{"GET", "/api/config"},
|
||||
{"GET", "/api/control-plane/apply-status"},
|
||||
{"GET", "/api/control-plane/audit"},
|
||||
{"GET", "/api/control-plane/catalog"},
|
||||
{"GET", "/api/control-plane/resources/sample"},
|
||||
{"GET", "/api/control-plane/resources/sample/history"},
|
||||
{"GET", "/api/curators"},
|
||||
{"GET", "/api/event-types"},
|
||||
{"GET", "/api/extensions"},
|
||||
{"GET", "/api/extensions/catalogue"},
|
||||
{"GET", "/api/harness/bindings"},
|
||||
{"GET", "/api/harness/terminal"},
|
||||
{"GET", "/api/identities"},
|
||||
{"GET", "/api/logs"},
|
||||
{"GET", "/api/mappings"},
|
||||
{"GET", "/api/mappings/7"},
|
||||
{"GET", "/api/orgs"},
|
||||
{"GET", "/api/orgs/7"},
|
||||
{"GET", "/api/orgs/7/members"},
|
||||
{"GET", "/api/orgs/7/workspaces"},
|
||||
{"GET", "/api/secret-engines"},
|
||||
{"GET", "/api/services"},
|
||||
{"GET", "/api/setup"},
|
||||
{"GET", "/api/skills"},
|
||||
{"GET", "/api/sources"},
|
||||
{"GET", "/api/stream"},
|
||||
{"GET", "/api/summary"},
|
||||
{"GET", "/api/task-meta"},
|
||||
{"GET", "/api/tasks"},
|
||||
{"GET", "/api/tasks/7"},
|
||||
{"GET", "/api/tasks/7/attempts"},
|
||||
{"GET", "/api/tasks/7/changes"},
|
||||
{"GET", "/api/tasks/7/debug"},
|
||||
{"GET", "/api/tasks/7/dispatches"},
|
||||
{"GET", "/api/tasks/7/logs"},
|
||||
{"GET", "/api/tasks/7/logs/download"},
|
||||
{"GET", "/api/tasks/7/sandbox"},
|
||||
{"GET", "/api/tokens"},
|
||||
{"GET", "/api/version"},
|
||||
{"GET", "/api/workflows"},
|
||||
{"PATCH", "/api/bindings/7"},
|
||||
{"PATCH", "/api/mappings/7"},
|
||||
{"POST", "/api/accounts"},
|
||||
{"POST", "/api/alerts/7/dismiss"},
|
||||
{"POST", "/api/bindings"},
|
||||
{"POST", "/api/bindings/7/approve"},
|
||||
{"POST", "/api/bindings/7/pause"},
|
||||
{"POST", "/api/bindings/7/resume"},
|
||||
{"POST", "/api/channels/7/reload"},
|
||||
{"POST", "/api/chat/answer"},
|
||||
{"POST", "/api/chat/cancel"},
|
||||
{"POST", "/api/chat/message"},
|
||||
{"POST", "/api/chat/persona"},
|
||||
{"POST", "/api/chat/stream"},
|
||||
{"POST", "/api/chat/update/defer"},
|
||||
{"POST", "/api/chat/update/install"},
|
||||
{"POST", "/api/control-plane/resources/sample/commands/sample"},
|
||||
{"POST", "/api/event-types"},
|
||||
{"POST", "/api/extensions"},
|
||||
{"POST", "/api/extensions/catalogue/sample/install"},
|
||||
{"POST", "/api/extensions/sample/accept"},
|
||||
{"POST", "/api/extensions/sample/approve-update"},
|
||||
{"POST", "/api/extensions/sample/rollback"},
|
||||
{"POST", "/api/extensions/sample/update"},
|
||||
{"POST", "/api/identities"},
|
||||
{"POST", "/api/identities/7/sample"},
|
||||
{"POST", "/api/mappings"},
|
||||
{"POST", "/api/mappings/preview"},
|
||||
{"POST", "/api/orgs"},
|
||||
{"POST", "/api/orgs/7/members"},
|
||||
{"POST", "/api/orgs/7/workspaces"},
|
||||
{"POST", "/api/secret-references/check"},
|
||||
{"POST", "/api/sources"},
|
||||
{"POST", "/api/sources/sample/approve-unsigned"},
|
||||
{"POST", "/api/sources/sample/secret"},
|
||||
{"POST", "/api/sources/sample/signing"},
|
||||
{"POST", "/api/tasks/7/action"},
|
||||
{"POST", "/api/tokens"},
|
||||
{"POST", "/api/work-requests"},
|
||||
{"PUT", "/api/access/policies"},
|
||||
{"PUT", "/api/authentication"},
|
||||
{"PUT", "/api/event-types/7"},
|
||||
{"PUT", "/api/extensions/sample/enabled"},
|
||||
{"PUT", "/api/extensions/sample/update-policy"},
|
||||
{"PUT", "/api/orgs/7/agents/sample"},
|
||||
{"PUT", "/api/orgs/7/members/sample"},
|
||||
{"PUT", "/api/sources/sample/delivery-header"},
|
||||
{"PUT", "/api/sources/sample/name"},
|
||||
{"PUT", "/api/workflows/7/enabled"},
|
||||
}
|
||||
principal := access.Principal{IdentityID: "alice", Org: "acme", Memberships: []org.Membership{{IdentityID: "alice", OrgID: "acme", Role: org.RoleAdmin}}}
|
||||
policy := access.Policy{ID: "deny-all", Level: access.LevelInstance, Text: `forbid(principal,action,resource);`}
|
||||
for _, route := range routes {
|
||||
t.Run(route.method+" "+route.path, func(t *testing.T) {
|
||||
for _, signedIn := range []bool{false, true} {
|
||||
srv := &Server{Store: authorizationTasks{}, Accounts: accountBoundaryStore{}, Access: infraaccess.New(append(access.ShippedOrgPolicies("acme"), policy)), Principals: principalOf(principal)}
|
||||
req := httptest.NewRequestWithContext(t.Context(), route.method, "https://archie.example"+route.path, strings.NewReader(`{}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
want := http.StatusUnauthorized
|
||||
if signedIn {
|
||||
req.AddCookie(&http.Cookie{Name: accountCookie, Value: "valid"})
|
||||
want = http.StatusForbidden
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != want {
|
||||
t.Fatalf("signedIn=%v status=%d want=%d body=%s", signedIn, rec.Code, want, rec.Body.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+46
-31
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -41,15 +42,15 @@ func (s *Server) authorize(h http.Handler) http.Handler {
|
||||
// The record's org is not loaded here: org-filtered lookups keep a
|
||||
// record of another org from ever being fetched, and this request's
|
||||
// record (when it has an ID) belongs to the caller's org. The
|
||||
// workspace is the record's, not the route's, so it is read.
|
||||
workspace, err := s.recordWorkspace(ctx, kind, id)
|
||||
// workspace, owner and state are read from the record, never the body.
|
||||
resource, err := s.recordResource(ctx, kind, id)
|
||||
if err != nil {
|
||||
s.logf("record workspace unavailable", "kind", kind, "id", id, "err", err)
|
||||
http.Error(w, "record unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
resource := access.Resource{Kind: kind, ID: id, Org: principal.Org, Workspace: workspace}
|
||||
decision := s.Access.Authorize(principal, action, resource, access.Context{})
|
||||
peer, _, _ := net.SplitHostPort(r.RemoteAddr)
|
||||
decision := s.Access.Authorize(principal, action, resource, access.Context{Addr: peer})
|
||||
if !decision.Allowed {
|
||||
if errors.Is(decision.Err, access.ErrChainUnavailable) {
|
||||
// Nothing was evaluated: the chain has not loaded. This is an
|
||||
@@ -91,27 +92,26 @@ func (s *Server) authorizeCreateIn(w http.ResponseWriter, r *http.Request, kind
|
||||
return false
|
||||
}
|
||||
|
||||
// recordWorkspace returns the workspace of the record a request names, so
|
||||
// workspace policies and per-workspace roles decide for it. A request naming
|
||||
// no record, or one the caller's org does not hold, has none: the handler's
|
||||
// own lookup answers not found.
|
||||
func (s *Server) recordWorkspace(ctx context.Context, kind access.ResourceKind, id string) (org.WorkspaceID, error) {
|
||||
// recordResource reads policy attributes from the stored record, never the body.
|
||||
func (s *Server) recordResource(ctx context.Context, kind access.ResourceKind, id string) (access.Resource, error) {
|
||||
resource := access.Resource{Kind: kind, ID: id, Org: org.OrgFromContext(ctx)}
|
||||
if id == "" {
|
||||
return "", nil
|
||||
return resource, nil
|
||||
}
|
||||
var err error
|
||||
switch kind {
|
||||
case access.KindSource:
|
||||
return s.sourceWorkspace(ctx, id)
|
||||
case access.KindBinding:
|
||||
return s.bindingWorkspace(ctx, id)
|
||||
case access.KindMapping:
|
||||
return s.mappingWorkspace(ctx, id)
|
||||
case access.KindEventType:
|
||||
return s.eventTypeWorkspace(ctx, id)
|
||||
case access.KindTask:
|
||||
return s.taskWorkspace(ctx, id)
|
||||
return s.taskResource(ctx, resource)
|
||||
case access.KindBinding:
|
||||
return s.bindingResource(ctx, resource)
|
||||
case access.KindSource:
|
||||
resource.Workspace, err = s.sourceWorkspace(ctx, id)
|
||||
case access.KindMapping:
|
||||
resource.Workspace, err = s.mappingWorkspace(ctx, id)
|
||||
case access.KindEventType:
|
||||
resource.Workspace, err = s.eventTypeWorkspace(ctx, id)
|
||||
}
|
||||
return "", nil
|
||||
return resource, err
|
||||
}
|
||||
|
||||
func (s *Server) sourceWorkspace(ctx context.Context, path string) (org.WorkspaceID, error) {
|
||||
@@ -125,15 +125,16 @@ func (s *Server) sourceWorkspace(ctx context.Context, path string) (org.Workspac
|
||||
return src.WorkspaceID, nil
|
||||
}
|
||||
|
||||
func (s *Server) bindingWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
|
||||
func (s *Server) bindingResource(ctx context.Context, resource access.Resource) (access.Resource, error) {
|
||||
if s.Bindings == nil {
|
||||
return "", nil
|
||||
return resource, nil
|
||||
}
|
||||
b, err := s.Bindings.GetBinding(ctx, id)
|
||||
b, err := s.Bindings.GetBinding(ctx, resource.ID)
|
||||
if b == nil || err != nil {
|
||||
return "", ignoreNotFound(err, storecontract.ErrBindingNotFound)
|
||||
return resource, ignoreNotFound(err, storecontract.ErrBindingNotFound)
|
||||
}
|
||||
return b.WorkspaceID, nil
|
||||
resource.Workspace, resource.State = b.WorkspaceID, string(b.Status)
|
||||
return resource, nil
|
||||
}
|
||||
|
||||
func (s *Server) mappingWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
|
||||
@@ -163,16 +164,17 @@ func (s *Server) eventTypeWorkspace(ctx context.Context, id string) (org.Workspa
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (s *Server) taskWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
|
||||
taskID, ok := numericID(id)
|
||||
if s.Store == nil || !ok {
|
||||
return "", nil
|
||||
func (s *Server) taskResource(ctx context.Context, resource access.Resource) (access.Resource, error) {
|
||||
taskID, ok := numericID(resource.ID)
|
||||
if !ok {
|
||||
return resource, nil
|
||||
}
|
||||
t, err := s.Store.TaskByID(ctx, taskID)
|
||||
if t == nil || err != nil {
|
||||
return "", err
|
||||
return resource, err
|
||||
}
|
||||
return t.Workspace, nil
|
||||
resource.Workspace, resource.Owner, resource.State = t.Workspace, identity.IdentityID(t.Identity), t.Status
|
||||
return resource, nil
|
||||
}
|
||||
|
||||
// numericID parses a task route's ID; any other segment names no task.
|
||||
@@ -285,6 +287,9 @@ func actionOf(method string) access.Action {
|
||||
// routeOverride returns the action, kind and record key a specific route
|
||||
// shape carries, or ok=false when the method-and-kind fallback applies.
|
||||
func routeOverride(action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
|
||||
if a, kind, ok := accountRoute(path); ok {
|
||||
return a, kind, "", true
|
||||
}
|
||||
if command, ok := bindingCommand(action, path); ok {
|
||||
return command, access.KindBinding, segmentValue(path, 2), true
|
||||
}
|
||||
@@ -427,3 +432,13 @@ func matchPrefix(path, prefix string) bool {
|
||||
func matchSegment(path, prefix, suffix string) bool {
|
||||
return strings.HasPrefix(path, prefix) && strings.HasSuffix(path, suffix)
|
||||
}
|
||||
|
||||
func accountRoute(path string) (access.Action, access.ResourceKind, bool) {
|
||||
switch path {
|
||||
case "/api/accounts":
|
||||
return access.ActionManageMembers, access.KindMember, true
|
||||
case "/api/authentication":
|
||||
return access.ActionManageIdentities, access.KindIdentity, true
|
||||
}
|
||||
return "", "", false
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
)
|
||||
|
||||
@@ -350,3 +351,35 @@ func TestAuthorizeCreateIn(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type taskAttributesStore struct {
|
||||
storecontract.TaskStore
|
||||
owner, status string
|
||||
}
|
||||
|
||||
func (s taskAttributesStore) TaskByID(context.Context, int64) (*task.Task, error) {
|
||||
return &task.Task{ID: 7, Identity: s.owner, Status: s.status, Workspace: "default"}, nil
|
||||
}
|
||||
|
||||
func TestTaskAuthorizationUsesStoredAttributes(t *testing.T) {
|
||||
policy := access.Policy{ID: "owned-queued", Level: access.LevelObject, OrgID: "acme", ObjectKind: access.KindTask, ObjectID: "7", Text: `permit(principal,action,resource) when {resource.owner == "alice" && resource.state == "queued"};`}
|
||||
p := access.Principal{IdentityID: "alice", Org: "acme", Memberships: []org.Membership{{IdentityID: "alice", OrgID: "acme", Role: org.RoleDeveloper}}}
|
||||
for _, tc := range []struct {
|
||||
name, owner, state string
|
||||
want int
|
||||
}{
|
||||
{"owned queued task", "alice", "queued", 200},
|
||||
{"other owner", "bob", "queued", 403},
|
||||
{"different state", "alice", "running", 403},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := &Server{Store: taskAttributesStore{owner: tc.owner, status: tc.state}, Access: infraaccess.New(append(access.ShippedOrgPolicies("acme"), policy)), Principals: principalOf(p)}
|
||||
req := httptest.NewRequestWithContext(WithActingIdentity(t.Context(), identity.Identity{ID: "alice"}), "PUT", "https://archie.example/api/tasks/7", strings.NewReader(`{"owner":"alice","state":"queued"}`))
|
||||
rec := httptest.NewRecorder()
|
||||
srv.authorize(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})).ServeHTTP(rec, req)
|
||||
if rec.Code != tc.want {
|
||||
t.Fatalf("status=%d want=%d body=%s", rec.Code, tc.want, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
type ownedChat struct{ messaging.ChatContract }
|
||||
|
||||
func (ownedChat) Snapshot(context.Context) (messaging.ChatSnapshot, error) {
|
||||
return messaging.ChatSnapshot{CancellationAvailable: true, PersonasAvailable: true}, nil
|
||||
}
|
||||
|
||||
func (ownedChat) GetSession(context.Context, string) (messaging.SessionContext, bool, error) {
|
||||
return messaging.SessionContext{SessionID: "private", Source: messaging.SessionSource{Platform: "web", ThreadID: "alice"}}, true, nil
|
||||
}
|
||||
|
||||
func (ownedChat) RecentMessages(context.Context, string, int) ([]messaging.Message, error) {
|
||||
return []messaging.Message{}, nil
|
||||
}
|
||||
|
||||
func (ownedChat) RecentTurns(context.Context, string, int) ([]messaging.TurnRecord, error) {
|
||||
return []messaging.TurnRecord{}, nil
|
||||
}
|
||||
|
||||
func (ownedChat) Cancel(context.Context, string) (messaging.ChatCancellation, error) {
|
||||
return messaging.ChatCancellation{Cancelled: true}, nil
|
||||
}
|
||||
func (ownedChat) SetPersona(context.Context, string, string) (bool, error) { return true, nil }
|
||||
|
||||
func TestWebChatOwnership(t *testing.T) {
|
||||
for _, route := range []struct {
|
||||
name, body string
|
||||
handler func(*Server, http.ResponseWriter, *http.Request)
|
||||
}{
|
||||
{"messages", "", (*Server).handleChatMessages},
|
||||
{"turns", "", (*Server).handleChatTurns},
|
||||
{"cancel", `{"session_id":"private"}`, (*Server).handleChatCancel},
|
||||
{"persona", `{"session_id":"private","name":"archie"}`, (*Server).handleChatPersona},
|
||||
} {
|
||||
for _, user := range []string{"alice", "bob"} {
|
||||
t.Run(route.name+"/"+user, func(t *testing.T) {
|
||||
ctx := WithActingIdentity(t.Context(), identity.Identity{ID: identity.IdentityID(user)})
|
||||
req := httptest.NewRequestWithContext(ctx, "POST", "https://archie.example/api/chat/test", strings.NewReader(route.body))
|
||||
req.SetPathValue("id", "private")
|
||||
rec := httptest.NewRecorder()
|
||||
srv := &Server{Chat: &ChatService{Contract: ownedChat{}}}
|
||||
route.handler(srv, rec, req)
|
||||
want := 200
|
||||
if user != "alice" {
|
||||
want = 404
|
||||
}
|
||||
if rec.Code != want {
|
||||
t.Fatalf("status=%d want=%d body=%s", rec.Code, want, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebChatSenderCannotBeSuppliedByBrowser(t *testing.T) {
|
||||
ctx := WithActingIdentity(t.Context(), identity.Identity{ID: "alice"})
|
||||
req := httptest.NewRequestWithContext(ctx, "POST", "https://archie.example/api/chat/message", strings.NewReader(`{"channel_id":"browser-channel","text":"hello","sender_id":"bob","thread_id":"bob"}`))
|
||||
value, ok := (&Server{}).decodeChatMessage(httptest.NewRecorder(), req)
|
||||
if !ok {
|
||||
t.Fatal("message refused")
|
||||
}
|
||||
if value.Message.SenderID != "alice" || value.Message.ConversationID.ThreadID != "alice" {
|
||||
t.Fatalf("browser selected sender: %+v", value.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatQuestionBelongsToInitiatingPerson(t *testing.T) {
|
||||
var asks chatAsks
|
||||
id, answers := asks.open("alice")
|
||||
defer asks.close(id)
|
||||
if asks.answer(id, "approve", "bob") {
|
||||
t.Fatal("another person answered the question")
|
||||
}
|
||||
select {
|
||||
case <-answers:
|
||||
t.Fatal("unauthorized answer delivered")
|
||||
default:
|
||||
}
|
||||
if !asks.answer(id, "approve", "alice") {
|
||||
t.Fatal("owner could not answer")
|
||||
}
|
||||
if answer := <-answers; answer != "approve" {
|
||||
t.Fatalf("answer=%s", answer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
func (s *Server) registerPasskeyRoutes(public, protected *http.ServeMux) {
|
||||
public.HandleFunc("POST /api/auth/passkey/begin", func(w http.ResponseWriter, r *http.Request) { s.handlePasskeyBegin(w, r, false) })
|
||||
public.HandleFunc("POST /api/auth/passkey/finish", func(w http.ResponseWriter, r *http.Request) { s.handlePasskeyFinish(w, r, false) })
|
||||
protected.HandleFunc("POST /api/account/passkeys/begin", func(w http.ResponseWriter, r *http.Request) { s.handlePasskeyBegin(w, r, true) })
|
||||
protected.HandleFunc("POST /api/account/passkeys/finish", func(w http.ResponseWriter, r *http.Request) { s.handlePasskeyFinish(w, r, true) })
|
||||
protected.HandleFunc("GET /api/account/passkeys", s.handlePasskeyList)
|
||||
protected.HandleFunc("DELETE /api/account/passkeys/{id}", s.handlePasskeyDelete)
|
||||
}
|
||||
|
||||
func passkeyCookie(registration bool) string {
|
||||
if registration {
|
||||
return "archie_passkey_registration"
|
||||
}
|
||||
return "archie_passkey_login"
|
||||
}
|
||||
|
||||
func (s *Server) handlePasskeyBegin(w http.ResponseWriter, r *http.Request, registration bool) {
|
||||
if !s.authorizeAuthenticationMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if registration && !s.requireFreshAccount(w, r) {
|
||||
return
|
||||
}
|
||||
store, ok := s.Accounts.(identity.Passkeys)
|
||||
if !ok {
|
||||
http.Error(w, "passkeys unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
value, err := store.BeginPasskey(r.Context(), registration)
|
||||
if err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
scheme, _ := s.expectedOrigin(r)
|
||||
http.SetCookie(w, &http.Cookie{Name: passkeyCookie(registration), Value: value.Token, Path: "/api/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, MaxAge: 300})
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, json.RawMessage(value.Options))
|
||||
}
|
||||
|
||||
func (s *Server) handlePasskeyFinish(w http.ResponseWriter, r *http.Request, registration bool) {
|
||||
if !s.authorizeAuthenticationMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if registration && !s.requireFreshAccount(w, r) {
|
||||
return
|
||||
}
|
||||
store, ok := s.Accounts.(identity.Passkeys)
|
||||
if !ok {
|
||||
http.Error(w, "passkeys unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
cookie, err := r.Cookie(passkeyCookie(registration))
|
||||
if err != nil {
|
||||
http.Error(w, "passkey request expired", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: passkeyCookie(registration), Path: "/api/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
|
||||
var request struct {
|
||||
Credential json.RawMessage `json:"credential"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if !decodeAccountRequest(w, r, &request) {
|
||||
return
|
||||
}
|
||||
value, err := store.FinishPasskey(r.Context(), cookie.Value, request.Credential, registration, request.Name)
|
||||
if err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
if !registration {
|
||||
s.clearProviderCookie(w)
|
||||
s.setAccountCookie(w, r, value)
|
||||
}
|
||||
writeJSON(w, map[string]any{"user": value.Identity})
|
||||
}
|
||||
|
||||
func (s *Server) handlePasskeyList(w http.ResponseWriter, r *http.Request) {
|
||||
store, ok := s.Accounts.(identity.Passkeys)
|
||||
if !ok {
|
||||
http.Error(w, "passkeys unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
values, err := store.ListPasskeys(r.Context())
|
||||
if err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{"passkeys": values})
|
||||
}
|
||||
|
||||
func (s *Server) handlePasskeyDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.requireFreshAccount(w, r) {
|
||||
return
|
||||
}
|
||||
if !s.authorizeAuthenticationMutation(w, r) {
|
||||
return
|
||||
}
|
||||
store, ok := s.Accounts.(identity.Passkeys)
|
||||
if !ok {
|
||||
http.Error(w, "passkeys unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if err := store.DeletePasskey(r.Context(), r.PathValue("id")); err != nil {
|
||||
s.writeAccountError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -22,11 +22,15 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/captureintake"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/ratelimit"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/ui"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
Accounts identity.Accounts
|
||||
accountRateLimit *ratelimit.Limiter
|
||||
|
||||
// chatAsks holds the chat questions waiting for the operator's answer.
|
||||
chatAsks chatAsks
|
||||
// chatFiles holds the downloads for files chat turns sent.
|
||||
@@ -123,7 +127,8 @@ type Server struct {
|
||||
|
||||
// Authenticate resolves a presented credential to an identity. Non-nil
|
||||
// replaces the shared token.
|
||||
Authenticate func(context.Context, string) (identity.Identity, error)
|
||||
Authenticate func(context.Context, string) (identity.Identity, error)
|
||||
AuthenticateBrowser func(context.Context, string) (identity.Identity, error)
|
||||
|
||||
// PersonalTokens manages the signed-in person's API tokens. Nil answers
|
||||
// Unavailable.
|
||||
@@ -398,6 +403,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.Handle("GET /", s.assets())
|
||||
|
||||
top := http.NewServeMux()
|
||||
s.registerAccountRoutes(top, mux)
|
||||
top.HandleFunc("GET /healthz", s.handleHealthz)
|
||||
top.HandleFunc("GET /health", s.handleHealth)
|
||||
// The sign-in routes sit on the bypass mux because they are how a caller
|
||||
@@ -415,7 +421,14 @@ func (s *Server) Handler() http.Handler {
|
||||
}
|
||||
// The chain runs after the credential check and before any handler: the
|
||||
// principal exists only once the credential resolved
|
||||
top.Handle("/", s.requireToken(s.authorize(mux)))
|
||||
authenticated := s.requireToken(s.authorize(mux))
|
||||
top.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Accounts != nil && r.Method == http.MethodGet && !strings.HasPrefix(r.URL.Path, "/api/") && r.URL.Path != healthDetailedRoute {
|
||||
s.assets().ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
authenticated.ServeHTTP(w, r)
|
||||
}))
|
||||
return top
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user