diff --git a/api/openapi.yaml b/api/openapi.yaml index c33ad9e4e..e1bfe9fde 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -374,6 +374,8 @@ components: type: - array - "null" + links_accounts: + type: boolean listens: type: boolean lookups: @@ -391,6 +393,7 @@ components: - lookups - listens - target_facts + - links_accounts type: object ConnectorsCapability: additionalProperties: false @@ -1235,6 +1238,43 @@ components: required: - sections type: object + GovernanceChannelLink: + additionalProperties: false + properties: + connector: + type: string + linked_at: + format: date-time + type: string + name: + type: string + subject: + type: string + required: + - connector + - subject + - name + - linked_at + type: object + GovernanceChannelsBody: + additionalProperties: false + properties: + connectors: + items: + type: string + type: + - array + - "null" + linked: + items: + $ref: "#/components/schemas/GovernanceChannelLink" + type: + - array + - "null" + required: + - connectors + - linked + type: object GovernanceCreatedToken: additionalProperties: false properties: @@ -1275,6 +1315,18 @@ components: - created_at - updated_at type: object + GovernanceLinkStart: + additionalProperties: false + properties: + expires_at: + format: date-time + type: string + url: + type: string + required: + - url + - expires_at + type: object GovernanceModel: additionalProperties: false properties: @@ -1426,27 +1478,6 @@ components: required: - passkeys type: object - GovernancePersonRequest: - additionalProperties: false - properties: - authority: - type: boolean - id: - description: Empty for a new person - type: string - identities: - items: - type: string - type: - - array - - "null" - name: - type: string - required: - - name - - authority - - identities - type: object GovernancePersonalToken: additionalProperties: false properties: @@ -1543,12 +1574,12 @@ components: GovernanceStepRequest: additionalProperties: false properties: + account: + type: string deadline: type: string - person: - type: string required: - - person + - account - deadline type: object GovernanceTiming: @@ -2915,6 +2946,80 @@ info: version: dev openapi: 3.1.0 paths: + /api/account/channels: + get: + operationId: list-channel-links + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceChannelsBody" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: List the channels you can link and your linked accounts + tags: + - Accounts + /api/account/channels/{connector}/link: + post: + operationId: begin-channel-link + parameters: + - in: path + name: connector + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceLinkStart" + description: OK + headers: + Cache-Control: + schema: + type: string + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Start linking a channel account + tags: + - Accounts + /api/account/channels/{connector}/{subject}: + delete: + operationId: unlink-channel + parameters: + - in: path + name: connector + required: true + schema: + type: string + - in: path + name: subject + required: true + schema: + type: string + responses: + "204": + description: No Content + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Unlink a channel account + tags: + - Accounts /api/account/passkeys: get: operationId: list-passkeys @@ -5078,61 +5183,6 @@ paths: summary: Rename a workspace tags: - Organisations - /api/people: - get: - operationId: list-people - responses: - "200": - content: - application/json: - schema: - items: - $ref: "#/components/schemas/GovernancePersonRequest" - type: - - array - - "null" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: List the people - tags: - - Governance - put: - operationId: put-people - requestBody: - content: - application/json: - schema: - items: - $ref: "#/components/schemas/GovernancePersonRequest" - type: - - array - - "null" - required: true - responses: - "200": - content: - application/json: - schema: - items: - $ref: "#/components/schemas/GovernancePersonRequest" - type: - - array - - "null" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Replace the people - tags: - - Governance /api/policies/change-request: get: operationId: get-change-request-rules diff --git a/internal/app/archie/operations.go b/internal/app/archie/operations.go index 6bb080635..a53e09fb0 100644 --- a/internal/app/archie/operations.go +++ b/internal/app/archie/operations.go @@ -79,6 +79,7 @@ func (o *operations) Start(ctx context.Context) error { // Administrative writes are checked against the same live policy chain as // every other request. o.settings.UseAuthorizer(access) + o.allow.UseAuthorizer(access) o.talk.Use(chat.Deps{ People: o.settings, Access: access, Settings: o.settings, Toolbox: o.conns, Judge: o.judge, Approver: o.allow, Memory: o.remember, Runs: o.engine, Notifier: o.tell, diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index 6c41b40f6..2a58620f8 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -161,6 +161,8 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary } // A model's key is a credential name resolved through the sealed store. settings.UseCredentials(conns) + // An account links a channel account on the connectors that can link. + settings.UseChannels(conns) sys := system.New(system.Bootstrap{ Listen: cfg.Listen, Database: DatabaseHost(cfg.Database.URL), Schemas: len(schemas), @@ -189,7 +191,7 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary if err != nil { return nil, err } - hear := events.NewModule(db, log.With("module", "events"), orgID, sealer, conns, engine, allow, tell) + hear := events.NewModule(db, log.With("module", "events"), orgID, sealer, conns, engine, allow, settings, tell) hear.Routes(mux) judge := newJudgement(db, log, conns, classes, policies, settings, hear) // The record of deletions outlives this process and its database, so the @@ -250,7 +252,7 @@ func (a answers) Signal(ctx context.Context, id uuid.UUID, key string, payload j // and change-request rules. A failed action tightens its class. func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, classes *judgement.Classes, policies *judgement.Policies, settings *governance.Module, heard judgement.Events) *judgement.Module { guards := []judgement.Guard{ - judgement.Impact{Lookup: judgement.RecordedFacts{Source: conns, People: settings}, Defaults: settings}, + judgement.Impact{Lookup: judgement.RecordedFacts{Source: conns, Accounts: settings}, Defaults: settings}, judgement.Reversibility{}, judgement.Precedent{Classes: classes}, judgement.Provenance{Events: heard}, diff --git a/internal/platform/pg/migrations/00049_governance_approvers_are_accounts.sql b/internal/platform/pg/migrations/00049_governance_approvers_are_accounts.sql new file mode 100644 index 000000000..b5c8c9a12 --- /dev/null +++ b/internal/platform/pg/migrations/00049_governance_approvers_are_accounts.sql @@ -0,0 +1,93 @@ +-- +goose Up +-- Who may approve is decided by role, and a channel identity is a credential of +-- an account, so the people records go. A channel identity moves to the account +-- its person maps to without doubt: the account the person already answered +-- from on the dashboard, or the operating org's only owner when that owner +-- and the person are the only ones. Any other identity is dropped and linked +-- again from the account page. The default owner and escalation steps follow +-- the same mapping, and a step that maps nowhere is cleared. +CREATE TABLE governance.link_codes ( + code_hash text PRIMARY KEY, + identity_id text NOT NULL REFERENCES governance.identities (id), + issuer text NOT NULL, + expires_at timestamptz NOT NULL, + used_at timestamptz +); +CREATE INDEX idx_governance_link_codes_identity + ON governance.link_codes (identity_id); + +CREATE TEMPORARY TABLE person_account ( + person_id uuid PRIMARY KEY, + account text NOT NULL +); + +INSERT INTO person_account (person_id, account) +SELECT pi.person_id, min(substr(pi.identity, 9)) +FROM governance.person_identities pi +JOIN governance.memberships m + ON m.identity_id = substr(pi.identity, 9) AND m.org_id = 'org-sys' AND m.workspace_id IS NULL +WHERE pi.identity LIKE 'account:%' +GROUP BY pi.person_id +HAVING count(*) = 1; + +INSERT INTO person_account (person_id, account) +SELECT p.id, sole.identity_id +FROM governance.people p +CROSS JOIN LATERAL ( + SELECT min(m.identity_id) AS identity_id, count(*) AS owners + FROM governance.memberships m + JOIN governance.identities i ON i.id = m.identity_id + WHERE m.org_id = 'org-sys' AND m.workspace_id IS NULL AND m.role = 'owner' AND i.kind = 'user' +) sole +WHERE sole.owners = 1 + AND (SELECT count(*) FROM governance.people) = 1 + AND p.id NOT IN (SELECT person_id FROM person_account); + +INSERT INTO governance.identity_subjects (issuer, subject, identity_id, bound_at, name) +SELECT split_part(pi.identity, ':', 1), substr(pi.identity, strpos(pi.identity, ':') + 1), pa.account, now(), '' +FROM governance.person_identities pi +JOIN person_account pa ON pa.person_id = pi.person_id +WHERE pi.identity NOT LIKE 'account:%' AND strpos(pi.identity, ':') > 1 +ON CONFLICT (issuer, subject) DO NOTHING; + +UPDATE governance.settings s +SET default_owner = COALESCE(( + SELECT pa.account FROM person_account pa WHERE pa.person_id::text = s.default_owner + ), ''), + escalation = COALESCE(( + SELECT jsonb_agg(jsonb_build_object('account', d.account, 'deadline_ms', d.deadline_ms) ORDER BY d.n) + FROM ( + SELECT DISTINCT ON (pa.account) pa.account, e.step -> 'deadline_ms' AS deadline_ms, e.n + FROM jsonb_array_elements(s.escalation) WITH ORDINALITY AS e (step, n) + JOIN person_account pa ON pa.person_id::text = e.step ->> 'person' + ORDER BY pa.account, e.n + ) d + ), '[]'::jsonb); + +DROP TABLE person_account; +DROP TABLE governance.person_identities; +DROP TABLE governance.people; + +ALTER TABLE approvals.requests DROP COLUMN asked; + +-- +goose Down +ALTER TABLE approvals.requests ADD COLUMN asked jsonb NOT NULL DEFAULT '[]'; + +CREATE TABLE governance.people ( + id uuid PRIMARY KEY, + org_id text NOT NULL, + name text NOT NULL, + authority boolean NOT NULL DEFAULT false, + created_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (org_id, name) +); +CREATE TABLE governance.person_identities ( + org_id text NOT NULL, + identity text NOT NULL, + person_id uuid NOT NULL REFERENCES governance.people (id) ON DELETE CASCADE, + CONSTRAINT person_identities_pkey PRIMARY KEY (org_id, identity) +); + +UPDATE governance.settings SET default_owner = '', escalation = '[]'::jsonb; + +DROP TABLE governance.link_codes; diff --git a/internal/platform/prompts/product_guide.md b/internal/platform/prompts/product_guide.md index 97b4e0705..62819987c 100644 --- a/internal/platform/prompts/product_guide.md +++ b/internal/platform/prompts/product_guide.md @@ -6,7 +6,7 @@ Dashboard pages: - Unmatched (/unmatched): event groups no trigger matched; a draft workflow can be made from one, dry-run, and published. - Events (/events): the events sources delivered, with the run each started. - Classes (/classes, /classes/ID): action classes and the autonomy each has earned; approvals count towards a raise a person must approve, and a denial or failure lowers it. -- People (/people): the people approvals go to, with their channel identities. +- Account (/account): passkeys, tokens and the channel accounts (such as Telegram) linked to the signed-in account. Any member whose role allows approve can answer an approval, from the dashboard or from a linked channel account. - Controls (/controls): hard rules and change-request policy, and the judges that weigh actions. - Extensions (/extensions): connectors, secret engines, guards and MCP servers, each accepted before it runs. - Sources (/sources) and Triggers (/triggers): where events come from and which workflow each kind starts. diff --git a/modules/approvals/approvals.go b/modules/approvals/approvals.go index 7210ed416..0ee50b99e 100644 --- a/modules/approvals/approvals.go +++ b/modules/approvals/approvals.go @@ -43,25 +43,18 @@ var ( ErrAnswered = errors.New("that request was already answered") // ErrExpired means the answer arrived after the request's deadline. ErrExpired = errors.New("that request has expired") - // ErrUnverified means the answer came from an identity no person holds. - ErrUnverified = errors.New("that identity isn't held by any person, so its answer is refused") - // ErrNotApprover means the person may not answer approvals for actions. - ErrNotApprover = errors.New("that person isn't the default owner, on the escalation path or an authority, so their answer is refused") - // ErrNotAsked means the request hasn't yet reached that person on its - // escalation path. - ErrNotAsked = errors.New("that person hasn't been asked yet, so their answer is refused") - // ErrNeedsAuthority means the action needs a person with authority, and - // the answer came from one without. - ErrNeedsAuthority = errors.New("that action needs a person with authority, so their answer is refused") + // ErrUnlinked means the answer came from a channel account that no + // account has linked. + ErrUnlinked = errors.New("that channel account isn't linked to an account, so its answer is refused") + // ErrNotApprover means the account's role doesn't let it answer this + // request. + ErrNotApprover = errors.New("that account isn't allowed to approve this request, so its answer is refused") // ErrNeedsFreshAuthentication means approving this action needs a passkey // assertion made for this request, and the answer carried none. ErrNeedsFreshAuthentication = errors.New("that action can't be undone, so approving it needs a fresh passkey confirmation") // ErrNotSignedIn means the answer came from no signed-in person: the // bootstrap admin token is not a person who may approve. ErrNotSignedIn = errors.New("only a signed-in person can answer an approval") - // ErrNoAuthority means the answer to a raise came from a person without - // authority over policy and ceilings. - ErrNoAuthority = errors.New("that person holds no authority over policy and ceilings, so their answer to a raise is refused") ) // The kinds of request. A raise asks whether an action class may act with one @@ -179,30 +172,34 @@ type Policy interface { RaiseAfter(ctx context.Context) (int, error) } -// People resolves verified channel identities to people. -type People interface { - Verify(ctx context.Context, identity string) (governance.Verified, bool, error) +// Accounts resolves who answered: the account a channel credential is linked +// to, and the principal the access policies judge. +type Accounts interface { + ResolveSubject(ctx context.Context, s governance.Subject) (governance.Identity, error) + PrincipalFor(ctx context.Context, id governance.IdentityID) (governance.Principal, error) + Get(ctx context.Context, id governance.IdentityID) (governance.Identity, error) } // Module owns one organisation's approval requests. type Module struct { - orgID string - store *store.Store - tell Delivery - wake Signaller - classes Classes - policy Policy - people People - confirm Confirmer - changes ChangeRequests - log *slog.Logger - now func() time.Time + orgID string + store *store.Store + tell Delivery + wake Signaller + classes Classes + policy Policy + accounts Accounts + authz governance.Authorizer + confirm Confirmer + changes ChangeRequests + log *slog.Logger + now func() time.Time } // NewModule creates the approvals module for orgID. -func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller, classes Classes, policy Policy, people People) *Module { +func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller, classes Classes, policy Policy, accounts Accounts) *Module { return &Module{ - orgID: orgID, store: store.New(db), tell: tell, wake: wake, classes: classes, policy: policy, people: people, + orgID: orgID, store: store.New(db), tell: tell, wake: wake, classes: classes, policy: policy, accounts: accounts, log: log, now: time.Now, } } @@ -221,21 +218,13 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme for _, st := range path { total += st.Deadline() } - asked := []string{} - if path[0].Person != "" { - asked = append(asked, path[0].Person) - } - askedJSON, err := json.Marshal(asked) - if err != nil { - return Request{}, fmt.Errorf("encode asked: %w", err) - } row, err := m.store.Put(ctx, store.Request{ ID: uuid.New(), OrgID: m.orgID, RunID: runID, Key: key, DecisionID: d.ID, Kind: KindAction, Digest: d.Action.Digest, Level: d.Level.String(), Connector: d.Action.Connector, Action: d.Action.Name, TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID, Irreversible: irreversible(d.Action), Summary: Summary(d), State: StatePending, Deadline: now.Add(total), - StepDeadline: sql.NullTime{Time: now.Add(path[0].Deadline()), Valid: true}, Asked: string(askedJSON), + StepDeadline: sql.NullTime{Time: now.Add(path[0].Deadline()), Valid: true}, ChangeRequest: changeRequest, }) if err != nil { @@ -364,11 +353,13 @@ func raiseSummary(r *judgement.Raise) string { return s.String() } -// Settle processes a response from a channel identity such as "telegram:1001". -// It records why it rejected an unverified or unauthorized response. It returns -// false without an error for recorded rejections and for requests that are -// missing, expired or already answered, since retrying won't help. -func (m *Module) Settle(ctx context.Context, id uuid.UUID, identity, via string, approved bool) (bool, error) { +// Settle processes a response from a channel account, such as the Telegram +// user 1001 on the "telegram" connector. It records why it rejected an +// unlinked or unauthorized response. It returns false without an error for +// recorded rejections and for requests that are missing, expired or already +// answered, since retrying won't help. An unlinked account returns +// ErrUnlinked so the caller can tell it how to link. +func (m *Module) Settle(ctx context.Context, id uuid.UUID, who governance.Subject, via string, approved bool) (bool, error) { row, err := m.store.ByID(ctx, m.orgID, id) if errors.Is(err, ErrNotFound) { return false, nil @@ -376,17 +367,24 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, identity, via string, if err != nil { return false, err } - who, err := m.verify(ctx, identity, row) + name, err := m.channelAnswerer(ctx, who, row) if refusal(err) { + identity := who.Issuer + ":" + who.Subject m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", err.Error()) - return false, m.store.Refuse(ctx, store.Refusal{ + if rerr := m.store.Refuse(ctx, store.Refusal{ ID: uuid.New(), OrgID: m.orgID, RequestID: id, Identity: identity, Via: via, Reason: err.Error(), At: m.now().UTC(), - }) + }); rerr != nil { + return false, rerr + } + if errors.Is(err, ErrUnlinked) { + return false, err + } + return false, nil } if err != nil { return false, err } - _, err = m.answerAs(ctx, id, who.Name+" ("+identity+")", via, approved) + _, err = m.answerAs(ctx, id, name, via, approved) switch { case err == nil: return true, nil @@ -396,46 +394,59 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, identity, via string, return false, err } -func (m *Module) verify(ctx context.Context, identity string, row store.Request) (governance.Verified, error) { - who, ok, err := m.people.Verify(ctx, identity) +// channelAnswerer returns the name of the account who holds the channel +// credential when that account may answer row. +func (m *Module) channelAnswerer(ctx context.Context, who governance.Subject, row store.Request) (string, error) { + account, err := m.accounts.ResolveSubject(ctx, who) + if errors.Is(err, governance.ErrIdentityNotFound) { + return "", ErrUnlinked + } if err != nil { - return governance.Verified{}, fmt.Errorf("verify %s: %w", identity, err) + return "", fmt.Errorf("resolve %s:%s: %w", who.Issuer, who.Subject, err) } - if !ok { - return governance.Verified{}, ErrUnverified + if account.Kind != governance.KindUser || !account.CanAct() { + return "", ErrNotApprover } - return who, mayAnswer(who, row) + p, err := m.accounts.PrincipalFor(ctx, account.ID) + if err != nil { + return "", fmt.Errorf("read access of %s: %w", account.ID, err) + } + p.Kind = account.Kind + if err := m.mayAnswer(ctx, p, row); err != nil { + return "", err + } + return account.DisplayName, nil } -func mayAnswer(who governance.Verified, row store.Request) error { - switch { - case row.Kind == KindRaise && !who.Authority: - return ErrNoAuthority - case row.Kind == KindRaise: - return nil - case !who.Approver && !slices.Contains(askedOf(row), who.ID): +// mayAnswer applies the access policies to an answer, as to any other +// permission: approving needs the approve action on the request, and a raise +// or an escalated action, which change what the organisation lets Archie do, +// also need the policy-management action. +func (m *Module) mayAnswer(ctx context.Context, p governance.Principal, row store.Request) error { + if m.authz == nil { return ErrNotApprover - case row.Level == judgement.Escalate.String() && !who.Authority: - return ErrNeedsAuthority - case !who.Authority && !slices.Contains(askedOf(row), who.ID): - return ErrNotAsked + } + actions := []governance.Action{governance.ActionApprove} + if row.Kind == KindRaise || row.Level == judgement.Escalate.String() { + actions = append(actions, governance.ActionManagePolicies) + } + res := governance.Resource{Kind: governance.KindApproval, ID: row.ID.String(), Org: governance.DefaultOrgID, State: row.State} + for _, a := range actions { + d := m.authz.Authorize(ctx, p, a, res, governance.AccessContext{}) + if d.Err != nil { + return fmt.Errorf("check access: %w", d.Err) + } + if !d.Allowed { + return ErrNotApprover + } } return nil } -func askedOf(row store.Request) []string { - var ids []string - if err := json.Unmarshal([]byte(row.Asked), &ids); err != nil { - return nil - } - return ids -} - // refusal distinguishes a rejected response from an operational error. func refusal(err error) bool { - return errors.Is(err, ErrUnverified) || errors.Is(err, ErrNotApprover) || errors.Is(err, ErrNoAuthority) || - errors.Is(err, ErrNotAsked) || errors.Is(err, ErrNeedsAuthority) || errors.Is(err, ErrNeedsFreshAuthentication) || - errors.Is(err, ErrNotSignedIn) + return errors.Is(err, ErrUnlinked) || errors.Is(err, ErrNotApprover) || + errors.Is(err, ErrNeedsFreshAuthentication) || errors.Is(err, ErrNotSignedIn) } // Expire records a timeout without reducing the action class's autonomy: diff --git a/modules/approvals/approvals_test.go b/modules/approvals/approvals_test.go index cefc07314..e54c53519 100644 --- a/modules/approvals/approvals_test.go +++ b/modules/approvals/approvals_test.go @@ -3,62 +3,129 @@ package approvals import ( "context" "errors" - "strings" "testing" "time" + "github.com/google/uuid" + "github.com/samcharles93/archie-core/modules/approvals/internal/store" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" ) -type fakePeople map[string]governance.Verified - -func (f fakePeople) Verify(_ context.Context, identity string) (governance.Verified, bool, error) { - p, ok := f[identity] - return p, ok, nil +// fakeAccounts holds accounts by id, each with the role the shipped policies +// read, and the channel credentials linked to them. +type fakeAccounts struct { + accounts map[governance.IdentityID]governance.Identity + roles map[governance.IdentityID]governance.Role + linked map[governance.Subject]governance.IdentityID } -// TestVerifyAcceptsAnAnswerOnlyFromAPersonWhoMayGiveIt checks that a verified -// identity alone is not enough: the request kind, escalation step and required -// authority also determine who can respond. -func TestVerifyAcceptsAnAnswerOnlyFromAPersonWhoMayGiveIt(t *testing.T) { - people := fakePeople{ - "telegram:1001": {ID: "owner", Name: "Owner", Approver: true}, - "telegram:1002": {ID: "lead", Name: "Authority", Approver: true, Authority: true}, - "telegram:1003": {ID: "bystander", Name: "Bystander"}, - "telegram:1004": {ID: "second", Name: "Second", Approver: true}, +func (f fakeAccounts) ResolveSubject(_ context.Context, s governance.Subject) (governance.Identity, error) { + id, ok := f.linked[s] + if !ok { + return governance.Identity{}, governance.ErrIdentityNotFound } - action := func(level string, asked ...string) store.Request { - return store.Request{Kind: KindAction, Level: level, Asked: `["` + strings.Join(asked, `","`) + `"]`} + return f.accounts[id], nil +} + +func (f fakeAccounts) Get(_ context.Context, id governance.IdentityID) (governance.Identity, error) { + account, ok := f.accounts[id] + if !ok { + return governance.Identity{}, governance.ErrIdentityNotFound + } + return account, nil +} + +func (f fakeAccounts) PrincipalFor(_ context.Context, id governance.IdentityID) (governance.Principal, error) { + return governance.Principal{ + IdentityID: id, + Org: governance.DefaultOrgID, + Memberships: []governance.Membership{{IdentityID: id, OrgID: governance.DefaultOrgID, Role: f.roles[id]}}, + }, nil +} + +func newAccounts() fakeAccounts { + f := fakeAccounts{ + accounts: map[governance.IdentityID]governance.Identity{}, + roles: map[governance.IdentityID]governance.Role{}, + linked: map[governance.Subject]governance.IdentityID{}, + } + for id, role := range map[governance.IdentityID]governance.Role{ + "admin": governance.RoleAdmin, "owner": governance.RoleOwner, + "developer": governance.RoleDeveloper, "viewer": governance.RoleViewer, + } { + f.accounts[id] = governance.Identity{ID: id, Kind: governance.KindUser, DisplayName: string(id), Lifecycle: governance.LifecycleActive} + f.roles[id] = role + f.linked[governance.Subject{Issuer: "telegram", Subject: "tg-" + string(id)}] = id + } + return f +} + +// shipped is the access chain an install starts with: admin and owner may +// approve, a developer or viewer may not. +func shipped() governance.Authorizer { + return governance.NewEngine(governance.ShippedOrgPolicies(governance.DefaultOrgID)) +} + +// approveOnlyForDevelopers grants approve, and nothing about policy, to the +// developer role. +func approveOnlyForDevelopers() governance.Authorizer { + return governance.NewEngine([]governance.Policy{{ + ID: "developers-approve", Level: governance.LevelOrg, OrgID: governance.DefaultOrgID, + Text: `permit(principal, action == Archie::Action::"approve", resource) when { + resource.org == principal.org && principal.role == "developer" +};`, + }}) +} + +// TestChannelAnswerComesFromALinkedAccountWhoseRoleMayApprove guards the +// channel answer path: the channel credential resolves to an account, and +// role alone decides whether that account may answer, as for any other +// permission. A credential no account has linked is refused. +func TestChannelAnswerComesFromALinkedAccountWhoseRoleMayApprove(t *testing.T) { + action := func(level string) store.Request { + return store.Request{ID: uuid.New(), Kind: KindAction, Level: level} } propose, escalate := judgement.ProposeAndWait.String(), judgement.Escalate.String() + suspended := newAccounts() + suspended.accounts["admin"] = governance.Identity{ID: "admin", Kind: governance.KindUser, DisplayName: "admin", Lifecycle: governance.LifecycleSuspended} + bot := newAccounts() + bot.accounts["admin"] = governance.Identity{ID: "admin", Kind: governance.KindBot, DisplayName: "admin", Lifecycle: governance.LifecycleActive} tests := []struct { name string - identity string + accounts fakeAccounts + authz governance.Authorizer + who string row store.Request + wantName string wantErr error }{ - {name: "an approver can respond once notified", identity: "telegram:1001", row: action(propose, "owner")}, - {name: "an unmapped identity is refused", identity: "telegram:9999", row: action(propose, "owner"), wantErr: ErrUnverified}, - {name: "an unmapped identity can't answer a raise", identity: "telegram:9999", row: store.Request{Kind: KindRaise}, wantErr: ErrUnverified}, - {name: "an unlisted person who isn't an approver cannot respond", identity: "telegram:1003", row: action(propose, "owner"), wantErr: ErrNotApprover}, - {name: "the target owner can respond when explicitly asked", identity: "telegram:1003", row: action(propose, "bystander")}, - {name: "an approver without authority cannot respond to a raise", identity: "telegram:1001", row: store.Request{Kind: KindRaise}, wantErr: ErrNoAuthority}, - {name: "a person with authority can respond to a raise", identity: "telegram:1002", row: store.Request{Kind: KindRaise}}, - {name: "a later approver cannot respond before escalation", identity: "telegram:1004", row: action(propose, "owner"), wantErr: ErrNotAsked}, - {name: "a later approver can respond after escalation", identity: "telegram:1004", row: action(propose, "owner", "second")}, - {name: "a person with authority can respond without being asked", identity: "telegram:1002", row: action(propose, "owner")}, - {name: "the escalate level requires authority even when the approver was asked", identity: "telegram:1001", row: action(escalate, "owner"), wantErr: ErrNeedsAuthority}, - {name: "a person with authority can respond at the escalate level", identity: "telegram:1002", row: action(escalate, "owner")}, + {name: "an admin may approve", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: action(propose), wantName: "admin"}, + {name: "an owner may approve", accounts: newAccounts(), authz: shipped(), who: "tg-owner", row: action(propose), wantName: "owner"}, + {name: "an admin may answer an escalated action", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: action(escalate), wantName: "admin"}, + {name: "an admin may answer a raise", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: store.Request{ID: uuid.New(), Kind: KindRaise}, wantName: "admin"}, + {name: "a developer may not approve", accounts: newAccounts(), authz: shipped(), who: "tg-developer", row: action(propose), wantErr: ErrNotApprover}, + {name: "a viewer may not approve", accounts: newAccounts(), authz: shipped(), who: "tg-viewer", row: action(propose), wantErr: ErrNotApprover}, + {name: "a channel account no account has linked is refused", accounts: newAccounts(), authz: shipped(), who: "tg-stranger", row: action(propose), wantErr: ErrUnlinked}, + {name: "an unlinked channel account can't answer a raise", accounts: newAccounts(), authz: shipped(), who: "tg-stranger", row: store.Request{Kind: KindRaise}, wantErr: ErrUnlinked}, + {name: "a suspended account is refused", accounts: suspended, authz: shipped(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover}, + {name: "a bot is refused", accounts: bot, authz: shipped(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover}, + {name: "nobody may approve before access policies are attached", accounts: newAccounts(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover}, + {name: "a policy can grant approve to a role", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: action(propose), wantName: "developer"}, + {name: "approve alone does not answer an escalated action", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: action(escalate), wantErr: ErrNotApprover}, + {name: "approve alone does not answer a raise", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: store.Request{ID: uuid.New(), Kind: KindRaise}, wantErr: ErrNotApprover}, } - m := &Module{people: people} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - _, err := m.verify(context.Background(), tt.identity, tt.row) + m := &Module{accounts: tt.accounts, authz: tt.authz} + name, err := m.channelAnswerer(context.Background(), governance.Subject{Issuer: "telegram", Subject: tt.who}, tt.row) if !errors.Is(err, tt.wantErr) { t.Fatalf("err = %v, want %v", err, tt.wantErr) } + if name != tt.wantName { + t.Fatalf("name = %q, want %q", name, tt.wantName) + } if tt.wantErr != nil && !refusal(err) { t.Fatalf("%v isn't recorded as a refusal", err) } diff --git a/modules/approvals/dashboard.go b/modules/approvals/dashboard.go index 65c2d319b..b9d5af13c 100644 --- a/modules/approvals/dashboard.go +++ b/modules/approvals/dashboard.go @@ -61,19 +61,27 @@ type Assertion struct { Credential jsontext.Value `json:"credential"` } -// caller returns the person the signed-in caller is, checked as a channel -// identity is. The bootstrap token is no person, so it can't answer. +// UseAuthorizer attaches the access policies an answer is judged against. +// Until one is attached, no answer is accepted. +func (m *Module) UseAuthorizer(a governance.Authorizer) { m.authz = a } + +// caller returns the signed-in person, checked as a channel account is: their +// role must let them answer. The bootstrap token is no person, so it can't +// answer. func (m *Module) caller(ctx context.Context, row store.Request) (name, identity string, err error) { p, ok := governance.PrincipalFromContext(ctx) - if !ok || p.IdentityID == governance.SystemID || p.Kind == governance.KindSystem { + if !ok || p.IdentityID == governance.SystemID || p.Kind != governance.KindUser { return "", "", ErrNotSignedIn } - identity = governance.AccountIdentity(p.IdentityID) - who, err := m.verify(ctx, identity, row) - if err != nil { + identity = string(p.IdentityID) + if err := m.mayAnswer(ctx, p, row); err != nil { return "", identity, err } - return who.Name + " (" + identity + ")", identity, nil + account, err := m.accounts.Get(ctx, p.IdentityID) + if err != nil { + return "", identity, fmt.Errorf("read account %s: %w", identity, err) + } + return account.DisplayName, identity, nil } // authorise accepts an answer from the dashboard only from a person who may diff --git a/modules/approvals/dashboard_test.go b/modules/approvals/dashboard_test.go index cbeed45cf..4cf8159ef 100644 --- a/modules/approvals/dashboard_test.go +++ b/modules/approvals/dashboard_test.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json/jsontext" "errors" - "strings" "testing" "github.com/google/uuid" @@ -31,23 +30,22 @@ func (f *fakeConfirmer) Confirm(_ context.Context, _ string, _ []byte, subject s return f.err } -// TestDashboardAnswerComesFromAPersonWhoMayGiveIt guards the dashboard answer -// path: the signed-in caller is checked as a channel identity is, so the -// bootstrap token or an account no person holds can't approve, and approving -// an action that can't be undone also needs a passkey assertion that the -// confirmer accepts for this request. -func TestDashboardAnswerComesFromAPersonWhoMayGiveIt(t *testing.T) { - people := fakePeople{ - "account:owner": {ID: "owner", Name: "Owner", Approver: true}, - "account:bystander": {ID: "bystander", Name: "Bystander"}, - } +// TestDashboardAnswerComesFromAnAccountWhoseRoleMayApprove guards the +// dashboard answer path: the signed-in caller is judged by role as a channel +// account is, so the bootstrap token or a member without approve can't answer, +// and approving an action that can't be undone also needs a passkey assertion +// that the confirmer accepts for this request. +func TestDashboardAnswerComesFromAnAccountWhoseRoleMayApprove(t *testing.T) { signedIn := func(id string) *governance.Principal { - return &governance.Principal{IdentityID: governance.IdentityID(id), Kind: governance.KindUser} + p, _ := newAccounts().PrincipalFor(context.Background(), governance.IdentityID(id)) + p.Kind = governance.KindUser + return &p } shared := governance.SharedTokenOwner() + bot := &governance.Principal{IdentityID: "admin", Kind: governance.KindBot} request := uuid.New() row := func(irreversible bool) store.Request { - return store.Request{ID: request, Kind: KindAction, Level: judgement.ProposeAndWait.String(), Asked: `["owner"]`, Irreversible: irreversible} + return store.Request{ID: request, Kind: KindAction, Level: judgement.ProposeAndWait.String(), Irreversible: irreversible} } assertion := &Assertion{Token: "t", Credential: jsontext.Value(`{}`)} tests := []struct { @@ -59,22 +57,24 @@ func TestDashboardAnswerComesFromAPersonWhoMayGiveIt(t *testing.T) { confirmer *fakeConfirmer wantErr error }{ - {name: "a person on the path may approve", as: signedIn("owner"), row: row(false), approved: true}, + {name: "an admin may approve", as: signedIn("admin"), row: row(false), approved: true}, + {name: "an owner may approve", as: signedIn("owner"), row: row(false), approved: true}, {name: "the bootstrap token is no person", as: &shared, row: row(false), approved: true, wantErr: ErrNotSignedIn}, + {name: "a bot is no person", as: bot, row: row(false), approved: true, wantErr: ErrNotSignedIn}, {name: "a request with no one signed in is refused", as: nil, row: row(false), approved: true, wantErr: ErrNotSignedIn}, - {name: "an account no person holds is refused", as: signedIn("stranger"), row: row(false), approved: true, wantErr: ErrUnverified}, - {name: "a person who isn't an approver is refused", as: signedIn("bystander"), row: row(false), approved: true, wantErr: ErrNotApprover}, - {name: "a person who isn't an approver may not deny either", as: signedIn("bystander"), row: row(false), approved: false, wantErr: ErrNotApprover}, - {name: "an irreversible action needs an assertion", as: signedIn("owner"), row: row(true), approved: true, confirmer: &fakeConfirmer{}, wantErr: ErrNeedsFreshAuthentication}, - {name: "an irreversible action with no confirmer can't be approved", as: signedIn("owner"), row: row(true), approved: true, assertion: assertion, wantErr: ErrNeedsFreshAuthentication}, - {name: "a rejected assertion is refused", as: signedIn("owner"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{err: governance.ErrCredentialRejected}, wantErr: ErrFreshAuthenticationFailed}, - {name: "an accepted assertion approves", as: signedIn("owner"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{}}, - {name: "a denial needs no assertion", as: signedIn("owner"), row: row(true), approved: false, confirmer: &fakeConfirmer{}}, - {name: "a person who isn't an approver can't approve with an assertion", as: signedIn("bystander"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{}, wantErr: ErrNotApprover}, + {name: "a developer is refused", as: signedIn("developer"), row: row(false), approved: true, wantErr: ErrNotApprover}, + {name: "a viewer is refused", as: signedIn("viewer"), row: row(false), approved: true, wantErr: ErrNotApprover}, + {name: "a developer may not deny either", as: signedIn("developer"), row: row(false), approved: false, wantErr: ErrNotApprover}, + {name: "an irreversible action needs an assertion", as: signedIn("admin"), row: row(true), approved: true, confirmer: &fakeConfirmer{}, wantErr: ErrNeedsFreshAuthentication}, + {name: "an irreversible action with no confirmer can't be approved", as: signedIn("admin"), row: row(true), approved: true, assertion: assertion, wantErr: ErrNeedsFreshAuthentication}, + {name: "a rejected assertion is refused", as: signedIn("admin"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{err: governance.ErrCredentialRejected}, wantErr: ErrFreshAuthenticationFailed}, + {name: "an accepted assertion approves", as: signedIn("admin"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{}}, + {name: "a denial needs no assertion", as: signedIn("admin"), row: row(true), approved: false, confirmer: &fakeConfirmer{}}, + {name: "a developer can't approve with an assertion", as: signedIn("developer"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{}, wantErr: ErrNotApprover}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - m := &Module{people: people} + m := &Module{accounts: newAccounts(), authz: shipped()} if tt.confirmer != nil { m.UseConfirmer(tt.confirmer) } @@ -86,8 +86,8 @@ func TestDashboardAnswerComesFromAPersonWhoMayGiveIt(t *testing.T) { if !errors.Is(err, tt.wantErr) { t.Fatalf("err = %v, want %v", err, tt.wantErr) } - if err == nil && !strings.Contains(by, "account:") { - t.Fatalf("answered by %q, want the account's identity recorded", by) + if err == nil && by != string(tt.as.IdentityID) { + t.Fatalf("answered by %q, want the account's name recorded", by) } if tt.confirmer != nil && len(tt.confirmer.subjects) == 1 && tt.confirmer.subjects[0] != confirmationSubject(request) { t.Fatalf("confirmed %q, want the assertion confirmed for this request", tt.confirmer.subjects[0]) diff --git a/modules/approvals/escalation.go b/modules/approvals/escalation.go index dfba7bb44..a2adc6cbd 100644 --- a/modules/approvals/escalation.go +++ b/modules/approvals/escalation.go @@ -48,7 +48,7 @@ func (m *Module) Escalate(ctx context.Context, id uuid.UUID, n int, to governanc }); err != nil { return err } - if _, _, err := m.store.Escalate(ctx, m.orgID, id, n, to.Person, until); err != nil { + if _, _, err := m.store.Escalate(ctx, m.orgID, id, n, until); err != nil { return err } m.log.InfoContext(ctx, "approval request escalated", "request", id, "step", n) diff --git a/modules/approvals/internal/store/store.go b/modules/approvals/internal/store/store.go index 6aeedb258..4ad04fcba 100644 --- a/modules/approvals/internal/store/store.go +++ b/modules/approvals/internal/store/store.go @@ -37,11 +37,8 @@ type Request struct { AnsweredAt sql.NullTime `db:"answered_at"` AnsweredBy sql.NullString `db:"answered_by"` AnsweredVia sql.NullString `db:"answered_via"` - // Asked is a JSON array of person IDs reached so far, not just the - // person assigned to the current step. - Step int `db:"step"` - StepDeadline sql.NullTime `db:"step_deadline"` - Asked string `db:"asked"` + Step int `db:"step"` + StepDeadline sql.NullTime `db:"step_deadline"` // ChangeRequest is whether the request went through a change request // rather than the approvers' channels. ChangeRequest bool `db:"change_request"` @@ -60,7 +57,7 @@ func New(db *sqlx.DB) *Store { return &Store{db: db} } const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, connector, action, target_kind, target_id, level, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_via, - step, step_deadline, asked::text AS asked, change_request, counted, discarded_because` + step, step_deadline, change_request, counted, discarded_because` // Put inserts r or returns the existing request for the same organisation, // run and key. @@ -68,12 +65,12 @@ func (s *Store) Put(ctx context.Context, r Request) (Request, error) { var out Request err := s.db.GetContext(ctx, &out, ` INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, kind, digest, connector, action, - target_kind, target_id, level, irreversible, summary, state, deadline, step_deadline, asked, change_request) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, CAST($18 AS jsonb), $19) + target_kind, target_id, level, irreversible, summary, state, deadline, step_deadline, change_request) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) ON CONFLICT (org_id, run_id, key) DO NOTHING RETURNING `+requestColumns, r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.Kind, r.Digest, r.Connector, r.Action, r.TargetKind, - r.TargetID, r.Level, r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.askedOrEmpty(), r.ChangeRequest) + r.TargetID, r.Level, r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.ChangeRequest) if errors.Is(err, sql.ErrNoRows) { return s.Get(ctx, r.OrgID, r.RunID, r.Key) } @@ -83,13 +80,6 @@ func (s *Store) Put(ctx context.Context, r Request) (Request, error) { return out, nil } -func (r Request) askedOrEmpty() string { - if r.Asked == "" { - return "[]" - } - return r.Asked -} - // Get returns the request for one run's key. func (s *Store) Get(ctx context.Context, orgID string, runID uuid.UUID, key string) (Request, error) { var out Request @@ -122,17 +112,16 @@ func (s *Store) Answer(ctx context.Context, orgID string, id uuid.UUID, state, b return out, nil } -// Escalate advances a pending request to step, sets the deadline to until and -// records person if supplied. It returns false if the request has already -// reached that step or is no longer pending. -func (s *Store) Escalate(ctx context.Context, orgID string, id uuid.UUID, step int, person string, until time.Time) (Request, bool, error) { +// Escalate advances a pending request to step and sets the deadline to until. +// It returns false if the request has already reached that step or is no +// longer pending. +func (s *Store) Escalate(ctx context.Context, orgID string, id uuid.UUID, step int, until time.Time) (Request, bool, error) { var out Request err := s.db.GetContext(ctx, &out, ` UPDATE approvals.requests - SET step = $3, step_deadline = $4, - asked = CASE WHEN $5::text = '' OR asked @> to_jsonb($5::text) THEN asked ELSE asked || to_jsonb($5::text) END + SET step = $3, step_deadline = $4 WHERE org_id = $1 AND id = $2 AND state = 'pending' AND step < $3 - RETURNING `+requestColumns, orgID, id, step, until, person) + RETURNING `+requestColumns, orgID, id, step, until) if errors.Is(err, sql.ErrNoRows) { return Request{}, false, nil } diff --git a/modules/chat/binding.go b/modules/chat/binding.go index d48412f6c..8874f159c 100644 --- a/modules/chat/binding.go +++ b/modules/chat/binding.go @@ -117,8 +117,8 @@ func bindingFor(orgID string, id, request uuid.UUID, t store.Turn, d judgement.D func approverIDs(path []governance.PathStep) []string { out := make([]string, 0, len(path)) for _, st := range path { - if st.Person != "" { - out = append(out, st.Person) + if st.Account != "" { + out = append(out, st.Account) } } return out diff --git a/modules/chat/binding_test.go b/modules/chat/binding_test.go index b1c72c684..1833ebfef 100644 --- a/modules/chat/binding_test.go +++ b/modules/chat/binding_test.go @@ -230,7 +230,7 @@ func newApprovalFixture(t *testing.T) *approvalFixture { f.d = Deps{ People: fakePeople{alice: person(alice, governance.RoleAdmin)}, Access: governance.NewEngine(governance.ShippedOrgPolicies(governance.DefaultOrgID)), - Settings: runSettings{path: []governance.PathStep{{Person: alice}}}, + Settings: runSettings{path: []governance.PathStep{{Account: alice}}}, Judge: f.judge, Approver: f.approver, Notifier: runNotifier{}, } return f @@ -289,7 +289,7 @@ func TestRunApprovedRunsOnlyWhatWasApprovedAndOnlyOnce(t *testing.T) { { name: "the approvers changed while pending", change: func(f *approvalFixture) { - f.d.Settings = runSettings{path: []governance.PathStep{{Person: bob}}} + f.d.Settings = runSettings{path: []governance.PathStep{{Account: bob}}} }, wantDiscard: "the people who may approve it changed", }, diff --git a/modules/chat/taint_test.go b/modules/chat/taint_test.go index 3beaba6e8..b520cb35d 100644 --- a/modules/chat/taint_test.go +++ b/modules/chat/taint_test.go @@ -66,7 +66,7 @@ func (fakeApprover) Ask(_ context.Context, _ uuid.UUID, key string, _ judgement. type fakeSettings struct{ Settings } func (fakeSettings) EscalationPath(context.Context, string, bool) ([]governance.PathStep, error) { - return []governance.PathStep{{Person: alice}}, nil + return []governance.PathStep{{Account: alice}}, nil } // taintDeps builds the module dependencies around a store holding one diff --git a/modules/events/events.go b/modules/events/events.go index 834cfb11f..b78c52b2a 100644 --- a/modules/events/events.go +++ b/modules/events/events.go @@ -18,6 +18,7 @@ import ( "log/slog" "net/http" "regexp" + "strings" "sync" "time" @@ -25,9 +26,11 @@ import ( "github.com/jmoiron/sqlx" "github.com/samcharles93/archie-core/internal/platform/httpjson" + "github.com/samcharles93/archie-core/modules/approvals" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/events/internal/match" "github.com/samcharles93/archie-core/modules/events/internal/store" + "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/runs" ) @@ -52,16 +55,31 @@ type Runs interface { // belonged to no run. type Deliveries interface { SentBy(ctx context.Context, channel string, ids ...string) (run uuid.UUID, found bool, err error) + // Send writes text to one chat on a channel. + Send(ctx context.Context, channel, chatID, text, key string) error } // Answers settles the approval requests answer events name. type Answers interface { - Settle(ctx context.Context, id uuid.UUID, identity, via string, approved bool) (bool, error) + Settle(ctx context.Context, id uuid.UUID, who governance.Subject, via string, approved bool) (bool, error) } -// answerType is the event a channel emits when a person answers an approval -// request. -const answerType = "approval.answer" +// Links binds the channel accounts that account.link events name to the +// accounts that issued their codes. +type Links interface { + CompleteLink(ctx context.Context, issuer, subject, name, code string) (governance.Identity, error) + // LinkingURL is the dashboard page where a person links a channel account. + LinkingURL(ctx context.Context) (string, error) +} + +// The events a channel emits. An answer carries the approval request and the +// person's decision; a link carries the code the person sent to the channel. +// Both name the sender as ":" in by, and may name +// the chat to reply to in chat_id. +const ( + answerType = "approval.answer" + linkType = "account.link" +) // listenRetry is how long a listener waits after its stream breaks. const listenRetry = 5 * time.Second @@ -76,15 +94,16 @@ type Module struct { connectors Connectors runs Runs answers Answers + links Links deliveries Deliveries log *slog.Logger poll time.Duration } // NewModule returns the events module for orgID. -func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealer Sealer, c Connectors, r Runs, a Answers, d Deliveries) *Module { +func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealer Sealer, c Connectors, r Runs, a Answers, l Links, d Deliveries) *Module { st := store.New(db) - m := &Module{orgID: orgID, store: st, reader: st, sealer: sealer, connectors: c, runs: r, answers: a, deliveries: d, log: log, poll: time.Second} + m := &Module{orgID: orgID, store: st, reader: st, sealer: sealer, connectors: c, runs: r, answers: a, links: l, deliveries: d, log: log, poll: time.Second} m.parse = m.parseWith return m } @@ -291,18 +310,27 @@ func (m *Module) listen(ctx context.Context, src store.Source) { // answer settles the approval request an answer event names. An answer that // can't settle it is logged and done with: the request's own record already -// says why. +// says why. A channel account no account has linked is told how to link it. func (m *Module) answer(ctx context.Context, e store.Event) error { var a struct { RequestID uuid.UUID `json:"request_id"` Approved bool `json:"approved"` By string `json:"by"` + ChatID string `json:"chat_id"` } if err := json.Unmarshal(e.Fields, &a); err != nil { m.log.WarnContext(ctx, "unreadable approval answer", "event", e.ID, "error", err) return nil } - settled, err := m.answers.Settle(ctx, a.RequestID, a.By, e.Source, a.Approved) + src, who, ok := m.sender(ctx, e, a.By) + if !ok { + return nil + } + settled, err := m.answers.Settle(ctx, a.RequestID, who, e.Source, a.Approved) + if errors.Is(err, approvals.ErrUnlinked) { + m.replyUnlinked(ctx, e, src, a.ChatID) + return nil + } if err != nil { return fmt.Errorf("settle approval %s: %w", a.RequestID, err) } @@ -312,6 +340,77 @@ func (m *Module) answer(ctx context.Context, e store.Event) error { return nil } +// link binds the channel account that sent a link code to the account that +// issued the code, and tells the sender how it went. A code that doesn't work +// is not retried. +func (m *Module) link(ctx context.Context, e store.Event) error { + var l struct { + By string `json:"by"` + Code string `json:"code"` + Name string `json:"name"` + ChatID string `json:"chat_id"` + } + if err := json.Unmarshal(e.Fields, &l); err != nil { + m.log.WarnContext(ctx, "unreadable link request", "event", e.ID, "error", err) + return nil + } + src, who, ok := m.sender(ctx, e, l.By) + if !ok { + return nil + } + account, err := m.links.CompleteLink(ctx, who.Issuer, who.Subject, l.Name, l.Code) + switch { + case errors.Is(err, governance.ErrLinkCode): + m.reply(ctx, e, src, l.ChatID, "That link code didn't work. Start again from your account page in the dashboard.") + case errors.Is(err, governance.ErrLinkTaken): + m.reply(ctx, e, src, l.ChatID, "That "+src.Connector+" account is already linked to another account.") + case err != nil: + return fmt.Errorf("link %s account: %w", src.Connector, err) + default: + m.log.InfoContext(ctx, "channel account linked", "event", e.ID, "connector", src.Connector, "account", account.ID) + m.reply(ctx, e, src, l.ChatID, "Linked to "+account.DisplayName+".") + } + return nil +} + +// sender reads who sent a channel event. The connector comes from the event's +// source, so a connector can only speak for its own accounts: by must name the +// source's connector. +func (m *Module) sender(ctx context.Context, e store.Event, by string) (store.Source, governance.Subject, bool) { + src, err := m.reader.Source(ctx, e.OrgID, e.Source) + if err != nil { + m.log.WarnContext(ctx, "channel event from an unknown source", "event", e.ID, "source", e.Source, "error", err) + return store.Source{}, governance.Subject{}, false + } + prefix, subject, found := strings.Cut(by, ":") + if !found || prefix != src.Connector || subject == "" { + m.log.WarnContext(ctx, "channel event names a sender outside its connector", "event", e.ID, "source", e.Source) + return store.Source{}, governance.Subject{}, false + } + return src, governance.Subject{Issuer: src.Connector, Subject: subject}, true +} + +// replyUnlinked tells an unlinked channel account where to link it. +func (m *Module) replyUnlinked(ctx context.Context, e store.Event, src store.Source, chatID string) { + url, err := m.links.LinkingURL(ctx) + if err != nil { + m.log.WarnContext(ctx, "read the linking URL", "event", e.ID, "error", err) + return + } + m.reply(ctx, e, src, chatID, "That "+src.Connector+" account isn't linked to an account, so your answer wasn't counted. Link it at "+url+" and answer again.") +} + +// reply sends text to the chat an event came from. A reply that fails is +// logged and dropped: the event itself is already handled. +func (m *Module) reply(ctx context.Context, e store.Event, src store.Source, chatID, text string) { + if chatID == "" { + return + } + if err := m.deliveries.Send(ctx, src.Connector, chatID, text, "reply:"+e.ID.String()); err != nil { + m.log.WarnContext(ctx, "reply to a channel event", "event", e.ID, "error", err) + } +} + // dispatch links a resolve to the event it resolves and starts no work for // it. Any other event starts one run per matching trigger, keyed so a retried // dispatch never starts a second run. @@ -321,8 +420,11 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) { // Archie's own message coming back starts nothing and proposes nothing. return false, nil } - if e.Type == answerType { + switch e.Type { + case answerType: return false, m.answer(ctx, e) + case linkType: + return false, m.link(ctx, e) } linked, err := store.Link(ctx, tx, e) if err != nil || linked { diff --git a/modules/events/sender_test.go b/modules/events/sender_test.go new file mode 100644 index 000000000..e91eb51cd --- /dev/null +++ b/modules/events/sender_test.go @@ -0,0 +1,43 @@ +package events + +import ( + "context" + "log/slog" + "testing" + + "github.com/samcharles93/archie-core/modules/events/internal/store" + "github.com/samcharles93/archie-core/modules/governance" +) + +type connectorSource struct{ src store.Source } + +func (o connectorSource) Source(context.Context, string, string) (store.Source, error) { + return o.src, nil +} + +// TestSenderMustBelongToTheSourcesConnector guards channel identities: the +// issuer of a linked credential comes from the source's connector, so a +// connector can't answer or link as an account of another connector. +func TestSenderMustBelongToTheSourcesConnector(t *testing.T) { + tests := []struct { + name string + by string + want governance.Subject + ok bool + }{ + {name: "its own account", by: "telegram:1001", want: governance.Subject{Issuer: "telegram", Subject: "1001"}, ok: true}, + {name: "an account with a colon in its id", by: "telegram:a:b", want: governance.Subject{Issuer: "telegram", Subject: "a:b"}, ok: true}, + {name: "another connector's account", by: "slack:1001"}, + {name: "no connector", by: "1001"}, + {name: "no account", by: "telegram:"}, + } + m := &Module{reader: connectorSource{store.Source{Connector: "telegram"}}, log: slog.New(slog.DiscardHandler)} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, got, ok := m.sender(t.Context(), store.Event{Source: "chat"}, tt.by) + if ok != tt.ok || got != tt.want { + t.Fatalf("sender = %v %v, want %v %v", got, ok, tt.want, tt.ok) + } + }) + } +} diff --git a/modules/governance/accounts_api.go b/modules/governance/accounts_api.go index 1fffed28e..27b560317 100644 --- a/modules/governance/accounts_api.go +++ b/modules/governance/accounts_api.go @@ -116,6 +116,7 @@ func (m *Module) RegisterAccounts(api huma.API) { huma.Register(api, signedIn("list-personal-tokens", http.MethodGet, "/api/tokens", "List your personal API tokens", 0), m.listTokens) huma.Register(api, signedIn("create-personal-token", http.MethodPost, "/api/tokens", "Create a personal API token", http.StatusCreated), m.createToken) huma.Register(api, signedIn("revoke-personal-token", http.MethodDelete, "/api/tokens/{id}", "Revoke a personal API token", http.StatusNoContent), m.revokeToken) + m.registerLinks(api, signedIn) huma.Register(api, signedIn("get-capabilities", http.MethodGet, "/api/capabilities", "Report which dashboard sections this binary serves", 0), m.capabilities) huma.Register(api, admin("create-account", http.MethodPost, "/api/accounts", "Create an account", http.StatusCreated), m.createAccount) @@ -612,7 +613,7 @@ func (m *Module) capabilities(ctx context.Context, _ *struct{}) (*httpapi.Reply[ p, signedIn := PrincipalFromContext(ctx) sections := map[string]bool{"chat": signedIn, "memory": signedIn} for _, name := range []string{ - "settings", "org_people", "events", "workflows", "runs", "credentials", "extensions", "secret_engines", "models", "controls", "memory_admin", + "settings", "events", "workflows", "runs", "credentials", "extensions", "secret_engines", "models", "controls", "memory_admin", } { sections[name] = p.InstanceAdmin() } diff --git a/modules/governance/confirmation.go b/modules/governance/confirmation.go index 24424f6a6..ad924265c 100644 --- a/modules/governance/confirmation.go +++ b/modules/governance/confirmation.go @@ -15,10 +15,6 @@ import ( // ErrNoPasskey means the signed-in person has no passkey to confirm with. var ErrNoPasskey = errors.New("no passkey is registered for this account") -// AccountIdentity is the channel identity a signed-in account answers as, so -// a person is linked to an account in the same list as their channels. -func AccountIdentity(id IdentityID) string { return "account:" + string(id) } - // BeginConfirmation starts a passkey assertion for the signed-in person. It // can be finished only by Confirm with the same subject, and only by that // person: a sign-in ceremony can't stand in for it, nor it for a sign-in. diff --git a/modules/governance/governance.go b/modules/governance/governance.go index 45d900a59..c4d0a9731 100644 --- a/modules/governance/governance.go +++ b/modules/governance/governance.go @@ -14,7 +14,6 @@ import ( "net/http" "net/url" "regexp" - "slices" "strings" "time" @@ -117,10 +116,10 @@ type Settings struct { RecurrenceThreshold int // AttemptsPerRun is how many steps an agent may take in one run. AttemptsPerRun int - // DefaultOwner is the id of the person who answers for what has no other + // DefaultOwner is the id of the member who answers for what has no other // owner, or empty. DefaultOwner string - // Escalation is the people an unanswered request moves through, in order, + // Escalation is the members an unanswered request moves through, in order, // each with how long the request waits on them. Escalation []Step // Timing is when changing actions may run without asking. @@ -131,24 +130,24 @@ type Settings struct { ActionsPerDay int } -// Step is one stop on the escalation path: a person and how long an unanswered +// Step is one stop on the escalation path: a member and how long an unanswered // request waits on them before it moves to the next. type Step struct { - // Person is the id of the person the request is passed to. - Person string + // Account is the id of the member the request is passed to. + Account string Deadline time.Duration } // stepRow is a step as stored. type stepRow struct { - Person string `json:"person"` + Account string `json:"account"` DeadlineMS int64 `json:"deadline_ms"` } // stepRequest is a step as the API shows and sets it. Its deadline travels as // a Go duration string, like the approval deadline. type stepRequest struct { - Person string `json:"person"` + Account string `json:"account"` Deadline string `json:"deadline"` } @@ -180,7 +179,7 @@ func (s Settings) request() settingsRequest { func stepRequests(steps []Step) []stepRequest { out := make([]stepRequest, 0, len(steps)) for _, st := range steps { - out = append(out, stepRequest{Person: st.Person, Deadline: st.Deadline.String()}) + out = append(out, stepRequest{Account: st.Account, Deadline: st.Deadline.String()}) } return out } @@ -194,7 +193,7 @@ func stepsOf(req []stepRequest) ([]Step, error) { if err != nil { return nil, errors.New("each escalation deadline is a duration, such as 4h") } - out = append(out, Step{Person: r.Person, Deadline: d}) + out = append(out, Step{Account: r.Account, Deadline: d}) } return out, nil } @@ -259,6 +258,7 @@ type Module struct { authorizer Authorizer oidc *oidcLogin setup *SetupSignal + channels ChannelLinks } // NewModule returns the governance module for orgID. The ai-sdk provider @@ -320,7 +320,7 @@ func (m *Module) Settings(ctx context.Context) (Settings, error) { } escalation := make([]Step, 0, len(rows)) for _, r := range rows { - escalation = append(escalation, Step{Person: r.Person, Deadline: time.Duration(r.DeadlineMS) * time.Millisecond}) + escalation = append(escalation, Step{Account: r.Account, Deadline: time.Duration(r.DeadlineMS) * time.Millisecond}) } var timing Timing if err := json.Unmarshal(jsontext.Value(row.Timing), &timing); err != nil { @@ -385,8 +385,7 @@ func (m *Module) ApprovalDeadline(ctx context.Context) (time.Duration, error) { return set.ApprovalDeadline, nil } -// Register adds the settings API: organisation settings, the agent model and -// people. +// Register adds the settings API: organisation settings and the agent model. func (m *Module) Register(api huma.API) { tags := []string{"Governance"} huma.Register(api, huma.Operation{ @@ -413,14 +412,6 @@ func (m *Module) Register(api huma.API) { OperationID: "test-agent-model", Method: http.MethodPost, Path: "/api/settings/agent-model/test", Summary: "Ask a model one question before saving it", Tags: tags, }, m.testAgentModel) - huma.Register(api, huma.Operation{ - OperationID: "list-people", Method: http.MethodGet, Path: "/api/people", - Summary: "List the people", Tags: tags, - }, m.getPeople) - huma.Register(api, huma.Operation{ - OperationID: "put-people", Method: http.MethodPut, Path: "/api/people", - Summary: "Replace the people", Tags: tags, - }, m.putPeople) } func (m *Module) getSettings(ctx context.Context, _ *struct{}) (*httpapi.Reply[settingsRequest], error) { @@ -451,17 +442,17 @@ func (m *Module) putSettings(ctx context.Context, in *struct{ Body settingsReque if err := set.validate(); err != nil { return nil, huma.NewError(http.StatusBadRequest, err.Error()) } - people, err := m.store.People(ctx, m.orgID) + members, err := m.memberNames(ctx) if err != nil { - m.log.ErrorContext(ctx, "read people", "error", err) + m.log.ErrorContext(ctx, "read members", "error", err) return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the settings") } - if err := set.knows(people); err != nil { + if err := set.knows(members); err != nil { return nil, huma.NewError(http.StatusBadRequest, err.Error()) } rows := make([]stepRow, 0, len(set.Escalation)) for _, st := range set.Escalation { - rows = append(rows, stepRow{Person: st.Person, DeadlineMS: st.Deadline.Milliseconds()}) + rows = append(rows, stepRow{Account: st.Account, DeadlineMS: st.Deadline.Milliseconds()}) } escalation, err := json.Marshal(rows) if err != nil { @@ -519,28 +510,41 @@ func validDeadlines(path []Step) error { return nil } -// knows checks that the default owner and every person on the escalation path -// is one of people, and that no one is on the path twice. -func (s Settings) knows(people []store.Person) error { - known := func(id string) bool { - return slices.ContainsFunc(people, func(p store.Person) bool { return p.ID.String() == id }) - } - if s.DefaultOwner != "" && !known(s.DefaultOwner) { - return errors.New("the default owner must be one of the people") +// knows checks that the default owner and every account on the escalation +// path is one of members, and that no one is on the path twice. +func (s Settings) knows(members map[string]string) error { + if _, ok := members[s.DefaultOwner]; s.DefaultOwner != "" && !ok { + return errors.New("the default owner must be a member") } seen := map[string]bool{} for _, st := range s.Escalation { - if !known(st.Person) { - return errors.New("everyone on the escalation path must be one of the people") + if _, ok := members[st.Account]; !ok { + return errors.New("everyone on the escalation path must be a member") } - if seen[st.Person] { - return errors.New("a person can be on the escalation path once") + if seen[st.Account] { + return errors.New("a member can be on the escalation path once") } - seen[st.Person] = true + seen[st.Account] = true } return nil } +// memberNames returns the display name of each person who holds an org-wide +// membership, by account id. Agents and service accounts never answer. +func (m *Module) memberNames(ctx context.Context) (map[string]string, error) { + members, err := m.ListMembers(ctx, DefaultOrgID) + if err != nil { + return nil, err + } + out := make(map[string]string, len(members)) + for _, member := range members { + if member.Kind == KindUser && member.WorkspaceID == "" { + out[string(member.IdentityID)] = member.DisplayName + } + } + return out, nil +} + func (m *Module) listAgentModels(ctx context.Context, _ *struct{}) (*httpapi.Reply[map[string]Model], error) { rows, err := m.store.AgentModelRoles(ctx, m.orgID) if err != nil { diff --git a/modules/governance/internal/store/links.go b/modules/governance/internal/store/links.go new file mode 100644 index 000000000..119e96377 --- /dev/null +++ b/modules/governance/internal/store/links.go @@ -0,0 +1,94 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" + + "github.com/jmoiron/sqlx" +) + +// LinkCode is a stored single-use code that links a channel credential to the +// account that issued it. +type LinkCode struct { + IdentityID string `db:"identity_id"` + Issuer string `db:"issuer"` + ExpiresAt time.Time `db:"expires_at"` + UsedAt sql.NullTime `db:"used_at"` + Lifecycle string `db:"lifecycle"` +} + +// PutLinkCode stores the hash of a code issued by an account for one channel +// connector, and drops that account's codes that have run out. +func (s *Store) PutLinkCode(ctx context.Context, hash, identityID, issuer string, now, expires time.Time) error { + return s.withTx(ctx, func(tx *sqlx.Tx) error { + if _, err := tx.ExecContext(ctx, ` + DELETE FROM governance.link_codes WHERE identity_id = $1 AND (expires_at <= $2 OR used_at IS NOT NULL)`, + identityID, now); err != nil { + return fmt.Errorf("drop spent link codes: %w", err) + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.link_codes (code_hash, identity_id, issuer, expires_at) VALUES ($1, $2, $3, $4)`, + hash, identityID, issuer, expires); err != nil { + return fmt.Errorf("store link code: %w", err) + } + return nil + }) +} + +// RedeemLinkCode links the channel credential (issuer, subject) to the account +// that issued the code, once. The code row is locked while check judges it, so +// two redemptions of one code can't both pass. check also gets the account the +// credential is already linked to, empty when none; a refusal leaves the code +// unspent. +func (s *Store) RedeemLinkCode(ctx context.Context, hash, subject, name string, now time.Time, check func(code LinkCode, linkedTo string) error) (string, error) { + var account string + err := s.withTx(ctx, func(tx *sqlx.Tx) error { + var code LinkCode + err := tx.GetContext(ctx, &code, ` + SELECT c.identity_id, c.issuer, c.expires_at, c.used_at, i.lifecycle + FROM governance.link_codes c JOIN governance.identities i ON i.id = c.identity_id + WHERE c.code_hash = $1 + FOR UPDATE OF c`, hash) + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + if err != nil { + return fmt.Errorf("read link code: %w", err) + } + var bound string + err = tx.GetContext(ctx, &bound, ` + SELECT identity_id FROM governance.identity_subjects WHERE issuer = $1 AND subject = $2 FOR UPDATE`, + code.Issuer, subject) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return fmt.Errorf("read channel credential: %w", err) + } + if err := check(code, bound); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `UPDATE governance.link_codes SET used_at = $2 WHERE code_hash = $1`, hash, now); err != nil { + return fmt.Errorf("spend link code: %w", err) + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.identity_subjects (issuer, subject, identity_id, bound_at, name) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (issuer, subject) DO UPDATE SET name = EXCLUDED.name`, + code.Issuer, subject, code.IdentityID, now, name); err != nil { + return fmt.Errorf("link channel credential: %w", err) + } + orgID, err := auditSubjectOrg(ctx, tx, "", code.IdentityID) + if err != nil { + return err + } + account = code.IdentityID + return insertIdentityEvent(ctx, tx, IdentityEventRow{ + IdentityID: account, EventType: "bind_subject", + FromLifecycle: code.Lifecycle, ToLifecycle: code.Lifecycle, + DisplayName: code.Issuer + ":" + subject, ActorID: account, Source: "channel link", + RequestID: "link:" + hash, At: now, OrgID: orgID, + }) + }) + return account, err +} diff --git a/modules/governance/links.go b/modules/governance/links.go new file mode 100644 index 000000000..bf15ffeea --- /dev/null +++ b/modules/governance/links.go @@ -0,0 +1,270 @@ +package governance + +import ( + "context" + "crypto/rand" + "errors" + "fmt" + "net/http" + "slices" + "strings" + "time" + + "github.com/danielgtaylor/huma/v2" + + "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/modules/governance/internal/store" +) + +// linkCodeLifetime is how long a link code can be used after it is issued. +const linkCodeLifetime = 10 * time.Minute + +var ( + // ErrLinkCode means the link code is unknown, already used, expired or + // was issued for another channel. The cases are not told apart, so a + // guess learns nothing. + ErrLinkCode = errors.New("that link code isn't valid") + // ErrLinkTaken means the channel account is already linked to another + // Archie account. + ErrLinkTaken = errors.New("that channel account is already linked to another account") + // ErrNoChannel means no installed connector can link accounts under that + // name. + ErrNoChannel = errors.New("no installed channel links accounts under that name") +) + +// ChannelLinks is what linking an account needs from the installed +// connectors: which of them can link, and the URL a person opens to send a +// code to the connector's bot. +type ChannelLinks interface { + // LinkableChannels returns the names of the connectors that can link. + LinkableChannels(ctx context.Context) ([]string, error) + // LinkURL asks the named connector for the URL that delivers code to it. + LinkURL(ctx context.Context, connector, code string) (string, error) +} + +// UseChannels gives the module the connectors an account links channels on. +func (m *Module) UseChannels(c ChannelLinks) { m.channels = c } + +// linkCode is a stored link code, as redeeming judges it. +type linkCode struct { + account string + issuer string + expiresAt time.Time + used bool + active bool +} + +// redeem says whether the code may link a credential from the connector issuer +// at now. linkedTo is the account that already holds the credential, empty +// when none does: a credential is never moved from one account to another. +func (c linkCode) redeem(issuer, linkedTo string, now time.Time) error { + if c.used || !c.active || c.issuer != issuer || !now.Before(c.expiresAt) { + return ErrLinkCode + } + if linkedTo != "" && linkedTo != c.account { + return ErrLinkTaken + } + return nil +} + +// LinkStart is a link code ready to be opened in a channel. +type LinkStart struct { + URL string `json:"url"` + ExpiresAt time.Time `json:"expires_at"` +} + +// BeginLink issues the signed-in account a single-use code for the named +// connector and returns the URL that delivers it. +func (m *Module) BeginLink(ctx context.Context, connector string) (LinkStart, error) { + p, ok := PrincipalFromContext(ctx) + if !ok || p.Kind != KindUser { + return LinkStart{}, ErrCredentialRejected + } + if err := m.linkable(ctx, connector); err != nil { + return LinkStart{}, err + } + code := rand.Text() + now := time.Now().UTC() + expires := now.Add(linkCodeLifetime) + if err := m.store.PutLinkCode(ctx, sessionHash(code), string(p.IdentityID), connector, now, expires); err != nil { + return LinkStart{}, err + } + url, err := m.channels.LinkURL(ctx, connector, code) + if err != nil { + return LinkStart{}, fmt.Errorf("ask %s for the link URL: %w", connector, err) + } + return LinkStart{URL: url, ExpiresAt: expires}, nil +} + +func (m *Module) linkable(ctx context.Context, connector string) error { + if m.channels == nil { + return ErrNoChannel + } + names, err := m.channels.LinkableChannels(ctx) + if err != nil { + return err + } + if !slices.Contains(names, connector) { + return ErrNoChannel + } + return nil +} + +// CompleteLink links the channel account subject on the connector issuer to +// the account that issued code, and returns that account. The credential +// comes from the connector's own event, so the person never proves it here. +func (m *Module) CompleteLink(ctx context.Context, issuer, subject, name, code string) (Identity, error) { + subj := Subject{Issuer: issuer, Subject: subject} + if err := subj.Validate(); err != nil || code == "" { + return Identity{}, ErrLinkCode + } + now := time.Now().UTC() + account, err := m.store.RedeemLinkCode(ctx, sessionHash(code), subject, strings.TrimSpace(name), now, func(row store.LinkCode, linkedTo string) error { + return linkCode{ + account: row.IdentityID, issuer: row.Issuer, expiresAt: row.ExpiresAt, + used: row.UsedAt.Valid, active: row.Lifecycle == string(LifecycleActive), + }.redeem(issuer, linkedTo, now) + }) + if errors.Is(err, store.ErrNotFound) { + return Identity{}, ErrLinkCode + } + if err != nil { + return Identity{}, err + } + return m.Get(ctx, IdentityID(account)) +} + +// ChannelLink is one channel account linked to the signed-in account. +type ChannelLink struct { + Connector string `json:"connector"` + Subject string `json:"subject"` + Name string `json:"name"` + LinkedAt time.Time `json:"linked_at"` +} + +// ChannelsBody is what the account page shows: the connectors that can link, +// and the channel accounts already linked. +type ChannelsBody struct { + Connectors []string `json:"connectors"` + Linked []ChannelLink `json:"linked"` +} + +// Channels returns the connectors that can link and the signed-in account's +// links on them. +func (m *Module) Channels(ctx context.Context) (ChannelsBody, error) { + body := ChannelsBody{Connectors: []string{}, Linked: []ChannelLink{}} + p, ok := PrincipalFromContext(ctx) + if !ok || p.Kind != KindUser || m.channels == nil { + return body, nil + } + names, err := m.channels.LinkableChannels(ctx) + if err != nil { + return ChannelsBody{}, err + } + for _, name := range names { + rows, err := m.store.ListIdentitySubjects(ctx, string(p.IdentityID), name) + if err != nil { + return ChannelsBody{}, err + } + body.Connectors = append(body.Connectors, name) + for _, r := range rows { + body.Linked = append(body.Linked, ChannelLink{Connector: name, Subject: r.Subject, Name: r.Name, LinkedAt: r.BoundAt}) + } + } + return body, nil +} + +// Unlink removes one of the signed-in account's channel links. +func (m *Module) Unlink(ctx context.Context, connector, subject string) error { + p, ok := PrincipalFromContext(ctx) + if !ok || p.Kind != KindUser { + return ErrCredentialRejected + } + if err := m.linkable(ctx, connector); err != nil { + return err + } + return m.UnbindSubject(ctx, p.IdentityID, Subject{Issuer: connector, Subject: subject}, IdentityAudit{ + ActorID: p.IdentityID, Source: "channel link", RequestID: newRequestID("unlink"), + }) +} + +// LinkingURL is the dashboard page where a person links their channel +// accounts, which a channel tells an unlinked person to open. +func (m *Module) LinkingURL(ctx context.Context) (string, error) { + settings, err := m.AuthenticationSettings(ctx) + if err != nil { + return "", err + } + return strings.TrimRight(settings.PublicURL, "/") + "/account", nil +} + +type channelPath struct { + Connector string `path:"connector"` +} + +type unlinkInput struct { + Connector string `path:"connector"` + Subject string `path:"subject"` +} + +func (m *Module) listChannels(ctx context.Context, _ *struct{}) (*httpapi.Reply[ChannelsBody], error) { + body, err := m.Channels(ctx) + if err != nil { + return nil, m.accountError(ctx, err) + } + return httpapi.OK(body), nil +} + +type linkReply struct { + CacheControl string `header:"Cache-Control"` + Body LinkStart +} + +func (m *Module) beginChannelLink(ctx context.Context, in *channelPath) (*linkReply, error) { + start, err := m.BeginLink(ctx, in.Connector) + if err != nil { + return nil, m.linkError(ctx, err) + } + return &linkReply{CacheControl: "no-store", Body: start}, nil +} + +func (m *Module) unlinkChannel(ctx context.Context, in *unlinkInput) (*struct{}, error) { + if err := m.Unlink(ctx, in.Connector, in.Subject); err != nil { + return nil, m.linkError(ctx, err) + } + return nil, nil +} + +func (m *Module) linkError(ctx context.Context, err error) error { + switch { + case errors.Is(err, ErrNoChannel): + return huma.Error404NotFound(ErrNoChannel.Error()) + case errors.Is(err, ErrIdentityNotFound): + return huma.Error404NotFound("That channel account isn't linked.") + } + return m.accountError(ctx, err) +} + +func (m *Module) registerLinks(api huma.API, signedIn func(id, method, path, summary string, status int) huma.Operation) { + huma.Register(api, signedIn("list-channel-links", http.MethodGet, "/api/account/channels", "List the channels you can link and your linked accounts", 0), m.listChannels) + huma.Register(api, signedIn("begin-channel-link", http.MethodPost, "/api/account/channels/{connector}/link", "Start linking a channel account", 0), m.beginChannelLink) + huma.Register(api, signedIn("unlink-channel", http.MethodDelete, "/api/account/channels/{connector}/{subject}", "Unlink a channel account", http.StatusNoContent), m.unlinkChannel) +} + +// AccountOf returns the id of the account that holds identity, written as +// the connector and the account on it, such as "servicenow:jdoe"; ok is false +// when no account holds it. +func (m *Module) AccountOf(ctx context.Context, identity string) (string, bool, error) { + issuer, subject, found := strings.Cut(identity, ":") + if !found { + return "", false, nil + } + account, err := m.ResolveSubject(ctx, Subject{Issuer: issuer, Subject: subject}) + if errors.Is(err, ErrIdentityNotFound) { + return "", false, nil + } + if err != nil { + return "", false, err + } + return string(account.ID), true, nil +} diff --git a/modules/governance/links_test.go b/modules/governance/links_test.go new file mode 100644 index 000000000..bcac96e27 --- /dev/null +++ b/modules/governance/links_test.go @@ -0,0 +1,38 @@ +package governance + +import ( + "errors" + "testing" + "time" +) + +// TestLinkCodeLinksOnlyOnceToItsIssuer guards linking a channel account: a +// code works once, before it expires, for the connector it was issued for and +// for an active account, and a channel account that another account already +// holds is never moved to the issuer. +func TestLinkCodeLinksOnlyOnceToItsIssuer(t *testing.T) { + now := time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC) + fresh := linkCode{account: "alice", issuer: "telegram", expiresAt: now.Add(time.Minute), active: true} + tests := []struct { + name string + code linkCode + issuer string + linkedTo string + want error + }{ + {name: "a fresh code links", code: fresh, issuer: "telegram"}, + {name: "a channel account already linked to the issuer links again", code: fresh, issuer: "telegram", linkedTo: "alice"}, + {name: "a used code is refused", code: func() linkCode { c := fresh; c.used = true; return c }(), issuer: "telegram", want: ErrLinkCode}, + {name: "an expired code is refused", code: func() linkCode { c := fresh; c.expiresAt = now; return c }(), issuer: "telegram", want: ErrLinkCode}, + {name: "a code for another connector is refused", code: fresh, issuer: "slack", want: ErrLinkCode}, + {name: "a suspended account's code is refused", code: func() linkCode { c := fresh; c.active = false; return c }(), issuer: "telegram", want: ErrLinkCode}, + {name: "a channel account held by another account is refused", code: fresh, issuer: "telegram", linkedTo: "bob", want: ErrLinkTaken}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := tt.code.redeem(tt.issuer, tt.linkedTo, now); !errors.Is(err, tt.want) { + t.Fatalf("redeem = %v, want %v", err, tt.want) + } + }) + } +} diff --git a/modules/governance/path.go b/modules/governance/path.go index 1dab1d9b6..d31938297 100644 --- a/modules/governance/path.go +++ b/modules/governance/path.go @@ -4,17 +4,15 @@ import ( "context" "slices" "time" - - "github.com/samcharles93/archie-core/modules/governance/internal/store" ) // PathStep is one stop on the route an unanswered approval request takes: who // it is passed to, and how long it waits there. The first step is the target's // owner when there is one, otherwise the default owner, who may be nobody, and -// then anyone with authority. +// then each member on the escalation path who may answer it. type PathStep struct { - // Person is the id of the person asked at this step, or empty. - Person string `json:"person"` + // Account is the id of the member asked at this step, or empty. + Account string `json:"account"` Name string `json:"name"` DeadlineMS int64 `json:"deadline_ms"` } @@ -32,51 +30,90 @@ func (m *Module) HasDefaultOwner(ctx context.Context) (bool, error) { } // EscalationPath returns the route an approval request takes. owner is the -// person who answers for the action's target, or empty when none is known. A -// known owner is asked first and the default owner is the next step; an unknown -// owner leaves the default owner first. Every later step is a person on the -// escalation path. When the action needs authority, a step held by someone -// without it is left out, so the request never moves to a person who could not -// answer it. +// account that answers for the action's target, or empty when none is known. +// A known owner is asked first and the default owner is the next step; an +// unknown owner leaves the default owner first. Every later step is a member +// on the escalation path. A member the access policies don't let approve is +// left out, so the request never moves to someone who could not answer it. +// When the action needs authority over policy as well, so must they be allowed +// to manage policies. func (m *Module) EscalationPath(ctx context.Context, owner string, needAuthority bool) ([]PathStep, error) { set, err := m.Settings(ctx) if err != nil { return nil, err } - people, err := m.store.People(ctx, m.orgID) + names, err := m.memberNames(ctx) if err != nil { return nil, err } - return set.path(people, owner, needAuthority), nil + actions := []Action{ActionApprove} + if needAuthority { + actions = append(actions, ActionManagePolicies) + } + candidates := []string{owner, set.DefaultOwner} + for _, st := range set.Escalation { + candidates = append(candidates, st.Account) + } + eligible := map[string]string{} + for _, id := range candidates { + name, member := names[id] + if id == "" || !member { + continue + } + may, err := m.Holds(ctx, IdentityID(id), Resource{Kind: KindApproval, ID: "path", Org: DefaultOrgID}, actions...) + if err != nil { + return nil, err + } + if may { + eligible[id] = name + } + } + return set.path(eligible, owner), nil } -func (s Settings) path(people []store.Person, owner string, needAuthority bool) []PathStep { - find := func(id string) (store.Person, bool) { - i := slices.IndexFunc(people, func(p store.Person) bool { return p.ID.String() == id }) - if i < 0 { - return store.Person{}, false - } - return people[i], true - } - defaultOwner := PathStep{Person: s.DefaultOwner, DeadlineMS: s.ApprovalDeadline.Milliseconds()} - if p, ok := find(s.DefaultOwner); ok { - defaultOwner.Name = p.Name +// path lays the route out over eligible, the members who may answer by id. +func (s Settings) path(eligible map[string]string, owner string) []PathStep { + defaultOwner := PathStep{DeadlineMS: s.ApprovalDeadline.Milliseconds()} + if name, ok := eligible[s.DefaultOwner]; ok { + defaultOwner.Account, defaultOwner.Name = s.DefaultOwner, name } var out []PathStep - if p, ok := find(owner); ok && owner != "" && (p.Authority || !needAuthority) { - out = append(out, PathStep{Person: owner, Name: p.Name, DeadlineMS: s.ApprovalDeadline.Milliseconds()}) + if name, ok := eligible[owner]; ok && owner != "" { + out = append(out, PathStep{Account: owner, Name: name, DeadlineMS: s.ApprovalDeadline.Milliseconds()}) } // With no owner to ask, the default owner leads even when nobody is set, // so the request still goes to anyone who may answer it. - if len(out) == 0 || (s.DefaultOwner != "" && s.DefaultOwner != owner) { + if len(out) == 0 || (defaultOwner.Account != "" && defaultOwner.Account != owner) { out = append(out, defaultOwner) } for _, st := range s.Escalation { - p, ok := find(st.Person) - if !ok || (needAuthority && !p.Authority) || slices.ContainsFunc(out, func(o PathStep) bool { return o.Person == st.Person }) { + name, ok := eligible[st.Account] + if !ok || slices.ContainsFunc(out, func(o PathStep) bool { return o.Account == st.Account }) { continue } - out = append(out, PathStep{Person: st.Person, Name: p.Name, DeadlineMS: st.Deadline.Milliseconds()}) + out = append(out, PathStep{Account: st.Account, Name: name, DeadlineMS: st.Deadline.Milliseconds()}) } return out } + +// Holds reports whether the account is allowed every one of actions on r by +// the live access policies. It is false while no policy chain is attached. +func (m *Module) Holds(ctx context.Context, account IdentityID, r Resource, actions ...Action) (bool, error) { + if m.authorizer == nil { + return false, nil + } + p, err := m.PrincipalFor(ctx, account) + if err != nil { + return false, err + } + for _, a := range actions { + d := m.authorizer.Authorize(ctx, p, a, r, AccessContext{}) + if d.Err != nil { + return false, d.Err + } + if !d.Allowed { + return false, nil + } + } + return true, nil +} diff --git a/modules/governance/path_test.go b/modules/governance/path_test.go index 22bc3356e..abc1fe02b 100644 --- a/modules/governance/path_test.go +++ b/modules/governance/path_test.go @@ -4,62 +4,60 @@ import ( "slices" "testing" "time" - - "github.com/google/uuid" - - "github.com/samcharles93/archie-core/modules/governance/internal/store" ) -// TestPathNeverDropsBelowTheAuthorityTheActionNeeds guards the escalation -// path: an action that needs authority is never passed to a person without -// it, however the path is set, every step keeps its own deadline, and a target's -// known owner is asked before the default owner, which an unknown owner leaves first. -func TestPathNeverDropsBelowTheAuthorityTheActionNeeds(t *testing.T) { - owner := store.Person{ID: uuid.New(), Name: "Owner"} - peer := store.Person{ID: uuid.New(), Name: "Peer"} - lead := store.Person{ID: uuid.New(), Name: "Lead", Authority: true} +// TestPathAsksOnlyMembersWhoMayAnswer guards the escalation path: it never +// passes a request to an account that was left out as unable to answer, every +// step keeps its own deadline, and a target's known owner is asked before the +// default owner, which an unknown owner leaves first. +func TestPathAsksOnlyMembersWhoMayAnswer(t *testing.T) { set := Settings{ - ApprovalDeadline: time.Hour, DefaultOwner: owner.ID.String(), + ApprovalDeadline: time.Hour, DefaultOwner: "owner", Escalation: []Step{ - {Person: peer.ID.String(), Deadline: 2 * time.Hour}, - {Person: lead.ID.String(), Deadline: 3 * time.Hour}, + {Account: "peer", Deadline: 2 * time.Hour}, + {Account: "lead", Deadline: 3 * time.Hour}, }, } - people := []store.Person{owner, peer, lead} + everyone := map[string]string{"owner": "Owner", "peer": "Peer", "lead": "Lead"} + leadOnly := map[string]string{"owner": "Owner", "lead": "Lead"} tests := []struct { - name string - needAuthority bool - // target is the person who answers for the action's target. + name string + eligible map[string]string + // target is the account that answers for the action's target. target string want []string wantDeadlines []time.Duration }{ { - name: "an ordinary action goes through every step", want: []string{"Owner", "Peer", "Lead"}, + name: "an ordinary action goes through every step", eligible: everyone, want: []string{"Owner", "Peer", "Lead"}, wantDeadlines: []time.Duration{time.Hour, 2 * time.Hour, 3 * time.Hour}, }, { - name: "an action that needs authority skips a step without it", needAuthority: true, + name: "a step that may not answer is skipped", eligible: leadOnly, want: []string{"Owner", "Lead"}, wantDeadlines: []time.Duration{time.Hour, 3 * time.Hour}, }, { - name: "the target's owner is asked first, then the default owner and the path", target: peer.ID.String(), + name: "the target's owner is asked first, then the default owner and the path", eligible: everyone, target: "peer", want: []string{"Peer", "Owner", "Lead"}, wantDeadlines: []time.Duration{time.Hour, time.Hour, 3 * time.Hour}, }, { - name: "a target owner without the authority an action needs is not asked", target: peer.ID.String(), needAuthority: true, + name: "a target owner who may not answer is not asked", eligible: leadOnly, target: "peer", want: []string{"Owner", "Lead"}, wantDeadlines: []time.Duration{time.Hour, 3 * time.Hour}, }, { - name: "a target owner nobody knows leaves the default owner first", target: uuid.NewString(), + name: "a target owner nobody knows leaves the default owner first", eligible: everyone, target: "stranger", want: []string{"Owner", "Peer", "Lead"}, wantDeadlines: []time.Duration{time.Hour, 2 * time.Hour, 3 * time.Hour}, }, + { + name: "a default owner who may not answer leaves the first step open", eligible: map[string]string{"lead": "Lead"}, + want: []string{"", "Lead"}, wantDeadlines: []time.Duration{time.Hour, 3 * time.Hour}, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var names []string var deadlines []time.Duration - for _, st := range set.path(people, tt.target, tt.needAuthority) { + for _, st := range set.path(tt.eligible, tt.target) { names = append(names, st.Name) deadlines = append(deadlines, st.Deadline()) } diff --git a/modules/judgement/facts.go b/modules/judgement/facts.go index 9f1c15f5d..7d489a0f5 100644 --- a/modules/judgement/facts.go +++ b/modules/judgement/facts.go @@ -13,20 +13,20 @@ type FactsSource interface { TargetFacts(ctx context.Context, t connectors.Target) (connectors.TargetFacts, error) } -// Identities says which person holds an identity, such as "servicenow:jdoe". +// Identities says which account holds an identity, such as "servicenow:jdoe". type Identities interface { - PersonID(ctx context.Context, identity string) (id string, ok bool, err error) + AccountOf(ctx context.Context, identity string) (id string, ok bool, err error) } // RecordedFacts looks a target's facts up in the connectors each time and -// keeps none. The owner a connector names counts only when the identity is a -// person Archie knows, so the request can be put to them. +// keeps none. The owner a connector names counts only when the identity is +// linked to an account, so the request can be put to them. type RecordedFacts struct { - Source FactsSource - People Identities + Source FactsSource + Accounts Identities } -// Facts asks the connectors about t and maps the owner they name to a person. +// Facts asks the connectors about t and maps the owner they name to an account. func (r RecordedFacts) Facts(ctx context.Context, t connectors.Target) (TargetFacts, error) { got, err := r.Source.TargetFacts(ctx, t) if err != nil { @@ -36,7 +36,7 @@ func (r RecordedFacts) Facts(ctx context.Context, t connectors.Target) (TargetFa if got.OwnerIdentity == "" { return facts, nil } - id, ok, err := r.People.PersonID(ctx, got.OwnerIdentity) + id, ok, err := r.Accounts.AccountOf(ctx, got.OwnerIdentity) if err != nil { return TargetFacts{}, fmt.Errorf("match owner %s: %w", got.OwnerIdentity, err) } diff --git a/modules/runs/dry.go b/modules/runs/dry.go index 7b3ae3559..e7aa311f3 100644 --- a/modules/runs/dry.go +++ b/modules/runs/dry.go @@ -206,7 +206,7 @@ func dryAction(d judgement.Decision, ask []string) DryAction { func pathNames(path []governance.PathStep) []string { names := make([]string, 0, len(path)) for _, s := range path { - names = append(names, firstText(s.Name, s.Person)) + names = append(names, firstText(s.Name, s.Account)) } return names } diff --git a/modules/runs/escalation_test.go b/modules/runs/escalation_test.go index d4537559f..65c4e06a4 100644 --- a/modules/runs/escalation_test.go +++ b/modules/runs/escalation_test.go @@ -104,7 +104,7 @@ func (e *escalations) Discard(context.Context, uuid.UUID, string) error { return // answer at any step stops the escalation there. func TestWaitThroughPathMovesOnAtEachDeadlineAndExpiresAtTheEnd(t *testing.T) { // A zero deadline has passed by the time it is waited on. - step := func(person string) governance.PathStep { return governance.PathStep{Person: person} } + step := func(person string) governance.PathStep { return governance.PathStep{Account: person} } tests := []struct { name string path []governance.PathStep diff --git a/modules/runs/investigate_test.go b/modules/runs/investigate_test.go index 1b02b254d..73ad6ba46 100644 --- a/modules/runs/investigate_test.go +++ b/modules/runs/investigate_test.go @@ -99,7 +99,7 @@ func (investigateSettings) AttemptsPerRun(context.Context) (int, error) { return // EscalationPath waits long enough that the first attempt suspends, as a // person who has not answered yet does. func (investigateSettings) EscalationPath(context.Context, string, bool) ([]governance.PathStep, error) { - return []governance.PathStep{{Person: "p", DeadlineMS: time.Hour.Milliseconds()}}, nil + return []governance.PathStep{{Account: "p", DeadlineMS: time.Hour.Milliseconds()}}, nil } // investigateBox declares one action so the model has something to call. The diff --git a/modules/runs/steps_test.go b/modules/runs/steps_test.go index 4d2f152d4..e420a4d88 100644 --- a/modules/runs/steps_test.go +++ b/modules/runs/steps_test.go @@ -97,7 +97,7 @@ func (onePersonPath) AgentProvider(context.Context, governance.Model) (chat.Prov } func (onePersonPath) EscalationPath(context.Context, string, bool) ([]governance.PathStep, error) { - return []governance.PathStep{{Person: "p"}}, nil + return []governance.PathStep{{Account: "p"}}, nil } func (onePersonPath) RecurrenceThreshold(context.Context) (int, error) { return 0, nil }