feat(chat): bind held-action approvals to the whole action and require fresh passkey confirmation for irreversible ones (#2072)
This commit is contained in:
23 files changed
+1288
-119
No files matched your search
+49
-1
@@ -5,9 +5,31 @@ components:
|
|||||||
properties:
|
properties:
|
||||||
approved:
|
approved:
|
||||||
type: boolean
|
type: boolean
|
||||||
|
assertion:
|
||||||
|
$ref: "#/components/schemas/ApprovalsAssertion"
|
||||||
required:
|
required:
|
||||||
- approved
|
- approved
|
||||||
type: object
|
type: object
|
||||||
|
ApprovalsAssertion:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
credential: {}
|
||||||
|
token:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- token
|
||||||
|
- credential
|
||||||
|
type: object
|
||||||
|
ApprovalsConfirmation:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
options: {}
|
||||||
|
token:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- token
|
||||||
|
- options
|
||||||
|
type: object
|
||||||
ApprovalsView:
|
ApprovalsView:
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
properties:
|
properties:
|
||||||
@@ -3165,7 +3187,33 @@ paths:
|
|||||||
schema:
|
schema:
|
||||||
$ref: "#/components/schemas/ErrorModel"
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
description: Error
|
description: Error
|
||||||
summary: Approve or refuse an action as the bootstrap admin
|
summary: Approve or refuse an action as the signed-in person
|
||||||
|
tags:
|
||||||
|
- Approvals
|
||||||
|
/api/approvals/{id}/confirmation:
|
||||||
|
post:
|
||||||
|
operationId: begin-approval-confirmation
|
||||||
|
parameters:
|
||||||
|
- in: path
|
||||||
|
name: id
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
format: uuid
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ApprovalsConfirmation"
|
||||||
|
description: OK
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Start the passkey confirmation that approving an irreversible action needs
|
||||||
tags:
|
tags:
|
||||||
- Approvals
|
- Approvals
|
||||||
/api/auth/login:
|
/api/auth/login:
|
||||||
|
|||||||
@@ -181,6 +181,8 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
|
|||||||
// An approval request is carried by deliveries, and its answer wakes the run
|
// An approval request is carried by deliveries, and its answer wakes the run
|
||||||
// that is waiting on it.
|
// that is waiting on it.
|
||||||
allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, answers{chat: talk, runs: engine}, classes, settings, settings)
|
allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, answers{chat: talk, runs: engine}, classes, settings, settings)
|
||||||
|
// Approving an action that can't be undone needs a fresh passkey assertion.
|
||||||
|
allow.UseConfirmer(settings)
|
||||||
policies := judgement.NewPolicies(db, log.With("module", "judgement"), orgID)
|
policies := judgement.NewPolicies(db, log.With("module", "judgement"), orgID)
|
||||||
// An answer a channel delivers is an event, and settles its request.
|
// An answer a channel delivers is an event, and settles its request.
|
||||||
sealer, err := seal.New(cfg.AgeIdentity, cfg.AgeBackupRecipients)
|
sealer, err := seal.New(cfg.AgeIdentity, cfg.AgeBackupRecipients)
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
-- +goose Up
|
||||||
|
-- A held chat action's approval is bound to the whole record of the action, not
|
||||||
|
-- only its name and arguments. Actions held before the binding existed carry
|
||||||
|
-- the narrow digest alone, so they are discarded rather than bound afterwards:
|
||||||
|
-- the person asks again. An approval already given is discarded, a pending
|
||||||
|
-- one expires, and the action stops.
|
||||||
|
UPDATE approvals.requests SET state = 'discarded',
|
||||||
|
discarded_because = 'it was approved before approvals were bound to the whole action'
|
||||||
|
WHERE state = 'approved' AND NOT counted
|
||||||
|
AND id IN (SELECT request_id FROM chat.actions WHERE state = 'approved');
|
||||||
|
UPDATE approvals.requests SET state = 'expired'
|
||||||
|
WHERE state = 'pending' AND id IN (SELECT request_id FROM chat.actions WHERE state = 'waiting');
|
||||||
|
UPDATE chat.actions SET state = 'expired',
|
||||||
|
result = 'It was held before approvals were bound to the whole action, so it didn''t run. Ask again.'
|
||||||
|
WHERE state = 'waiting';
|
||||||
|
UPDATE chat.actions SET state = 'failed',
|
||||||
|
result = 'It was held before approvals were bound to the whole action, so it didn''t run. Ask again.'
|
||||||
|
WHERE state = 'approved';
|
||||||
|
|
||||||
|
ALTER TABLE chat.actions ADD COLUMN binding jsonb, ADD COLUMN binding_digest text NOT NULL DEFAULT '';
|
||||||
|
|
||||||
|
-- Approving an action that can't be undone needs a fresh passkey assertion.
|
||||||
|
ALTER TABLE approvals.requests ADD COLUMN irreversible boolean NOT NULL DEFAULT false;
|
||||||
|
|
||||||
|
-- A confirmation ceremony is for one subject, such as an approval request. A
|
||||||
|
-- sign-in or registration ceremony has none.
|
||||||
|
ALTER TABLE governance.passkey_ceremonies ADD COLUMN subject text NOT NULL DEFAULT '';
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
ALTER TABLE governance.passkey_ceremonies DROP COLUMN subject;
|
||||||
|
ALTER TABLE approvals.requests DROP COLUMN irreversible;
|
||||||
|
ALTER TABLE chat.actions DROP COLUMN binding_digest, DROP COLUMN binding;
|
||||||
@@ -13,16 +13,13 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"maps"
|
"maps"
|
||||||
"net/http"
|
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/danielgtaylor/huma/v2"
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/jmoiron/sqlx"
|
"github.com/jmoiron/sqlx"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
|
||||||
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
|
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
|
||||||
"github.com/samcharles93/archie-core/modules/deliveries"
|
"github.com/samcharles93/archie-core/modules/deliveries"
|
||||||
"github.com/samcharles93/archie-core/modules/governance"
|
"github.com/samcharles93/archie-core/modules/governance"
|
||||||
@@ -56,6 +53,12 @@ var (
|
|||||||
// ErrNeedsAuthority means the action needs a person with authority, and
|
// ErrNeedsAuthority means the action needs a person with authority, and
|
||||||
// the answer came from one without.
|
// the answer came from one without.
|
||||||
ErrNeedsAuthority = errors.New("that action needs a person with authority, so their answer is refused")
|
ErrNeedsAuthority = errors.New("that action needs a person with authority, so their 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
|
// ErrNoAuthority means the answer to a raise came from a person without
|
||||||
// authority over policy and ceilings.
|
// 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")
|
ErrNoAuthority = errors.New("that person holds no authority over policy and ceilings, so their answer to a raise is refused")
|
||||||
@@ -83,8 +86,11 @@ type Request struct {
|
|||||||
TargetKind string
|
TargetKind string
|
||||||
TargetID string
|
TargetID string
|
||||||
Level string
|
Level string
|
||||||
Summary string
|
// Irreversible is whether the action can't be undone. Approving it needs
|
||||||
State string
|
// a fresh passkey assertion from the dashboard.
|
||||||
|
Irreversible bool
|
||||||
|
Summary string
|
||||||
|
State string
|
||||||
// Deadline applies to the whole request, not just the current escalation step.
|
// Deadline applies to the whole request, not just the current escalation step.
|
||||||
Deadline time.Time
|
Deadline time.Time
|
||||||
// Step and StepDeadline track the current escalation step and its deadline.
|
// Step and StepDeadline track the current escalation step and its deadline.
|
||||||
@@ -187,6 +193,7 @@ type Module struct {
|
|||||||
classes Classes
|
classes Classes
|
||||||
policy Policy
|
policy Policy
|
||||||
people People
|
people People
|
||||||
|
confirm Confirmer
|
||||||
changes ChangeRequests
|
changes ChangeRequests
|
||||||
log *slog.Logger
|
log *slog.Logger
|
||||||
now func() time.Time
|
now func() time.Time
|
||||||
@@ -226,7 +233,7 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme
|
|||||||
ID: uuid.New(), OrgID: m.orgID, RunID: runID, Key: key,
|
ID: uuid.New(), OrgID: m.orgID, RunID: runID, Key: key,
|
||||||
DecisionID: d.ID, Kind: KindAction, Digest: d.Action.Digest, Level: d.Level.String(),
|
DecisionID: d.ID, Kind: KindAction, Digest: d.Action.Digest, Level: d.Level.String(),
|
||||||
Connector: d.Action.Connector, Action: d.Action.Name,
|
Connector: d.Action.Connector, Action: d.Action.Name,
|
||||||
TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID,
|
TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID, Irreversible: irreversible(d.Action),
|
||||||
Summary: Summary(d), State: StatePending, Deadline: now.Add(total),
|
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}, Asked: string(askedJSON),
|
||||||
ChangeRequest: changeRequest,
|
ChangeRequest: changeRequest,
|
||||||
@@ -370,6 +377,10 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, identity, via string,
|
|||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
who, err := m.verify(ctx, identity, row)
|
who, err := m.verify(ctx, identity, row)
|
||||||
|
if err == nil && approved && row.Irreversible {
|
||||||
|
// A channel message can't carry a passkey assertion.
|
||||||
|
err = ErrNeedsFreshAuthentication
|
||||||
|
}
|
||||||
if refusal(err) {
|
if refusal(err) {
|
||||||
m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", err.Error())
|
m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", err.Error())
|
||||||
return false, m.store.Refuse(ctx, store.Refusal{
|
return false, m.store.Refuse(ctx, store.Refusal{
|
||||||
@@ -427,7 +438,8 @@ func askedOf(row store.Request) []string {
|
|||||||
// refusal distinguishes a rejected response from an operational error.
|
// refusal distinguishes a rejected response from an operational error.
|
||||||
func refusal(err error) bool {
|
func refusal(err error) bool {
|
||||||
return errors.Is(err, ErrUnverified) || errors.Is(err, ErrNotApprover) || errors.Is(err, ErrNoAuthority) ||
|
return errors.Is(err, ErrUnverified) || errors.Is(err, ErrNotApprover) || errors.Is(err, ErrNoAuthority) ||
|
||||||
errors.Is(err, ErrNotAsked) || errors.Is(err, ErrNeedsAuthority)
|
errors.Is(err, ErrNotAsked) || errors.Is(err, ErrNeedsAuthority) || errors.Is(err, ErrNeedsFreshAuthentication) ||
|
||||||
|
errors.Is(err, ErrNotSignedIn)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Expire records a timeout without reducing the action class's autonomy:
|
// Expire records a timeout without reducing the action class's autonomy:
|
||||||
@@ -512,62 +524,6 @@ func (m *Module) Outcomes(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]j
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Register adds the approvals API.
|
|
||||||
func (m *Module) Register(api huma.API) {
|
|
||||||
tags := []string{"Approvals"}
|
|
||||||
huma.Register(api, huma.Operation{
|
|
||||||
OperationID: "list-approvals", Method: http.MethodGet, Path: "/api/approvals",
|
|
||||||
Summary: "List approval requests waiting for an answer", Tags: tags,
|
|
||||||
}, m.list)
|
|
||||||
huma.Register(api, huma.Operation{
|
|
||||||
OperationID: "answer-approval", Method: http.MethodPost, Path: "/api/approvals/{id}/answer",
|
|
||||||
Summary: "Approve or refuse an action as the bootstrap admin", Tags: tags,
|
|
||||||
}, m.answer)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The token guard authenticates the bootstrap admin before the API handler,
|
|
||||||
// so the handler does not look up a channel identity.
|
|
||||||
const bootstrapAdmin = "admin"
|
|
||||||
|
|
||||||
type answerInput struct {
|
|
||||||
ID string `path:"id" format:"uuid"`
|
|
||||||
Body struct {
|
|
||||||
Approved bool `json:"approved"`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Module) list(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]View], error) {
|
|
||||||
pending, err := m.Pending(ctx)
|
|
||||||
if err != nil {
|
|
||||||
m.log.ErrorContext(ctx, "list approvals", "error", err)
|
|
||||||
return nil, huma.NewError(http.StatusInternalServerError, "couldn't list approvals")
|
|
||||||
}
|
|
||||||
out := make([]View, 0, len(pending))
|
|
||||||
for _, p := range pending {
|
|
||||||
out = append(out, p.View())
|
|
||||||
}
|
|
||||||
return httpapi.OK(out), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Module) answer(ctx context.Context, in *answerInput) (*httpapi.Reply[View], error) {
|
|
||||||
id, err := uuid.Parse(in.ID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, huma.NewError(http.StatusBadRequest, "id is a request id")
|
|
||||||
}
|
|
||||||
req := in.Body
|
|
||||||
out, err := m.answerAs(ctx, id, bootstrapAdmin, "composer", req.Approved)
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, ErrNotFound):
|
|
||||||
return nil, huma.NewError(http.StatusNotFound, "no such approval request")
|
|
||||||
case errors.Is(err, ErrAnswered), errors.Is(err, ErrExpired):
|
|
||||||
return nil, huma.NewError(http.StatusConflict, err.Error())
|
|
||||||
case err != nil:
|
|
||||||
m.log.ErrorContext(ctx, "answer approval", "request", id, "error", err)
|
|
||||||
return nil, huma.NewError(http.StatusInternalServerError, "couldn't record the answer")
|
|
||||||
}
|
|
||||||
return httpapi.OK(out.View()), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Module) pending(ctx context.Context, id uuid.UUID, now time.Time) (store.Request, error) {
|
func (m *Module) pending(ctx context.Context, id uuid.UUID, now time.Time) (store.Request, error) {
|
||||||
row, err := m.store.ByID(ctx, m.orgID, id)
|
row, err := m.store.ByID(ctx, m.orgID, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -662,7 +618,7 @@ func requestOf(row store.Request, d judgement.Decision) Request {
|
|||||||
r := Request{
|
r := Request{
|
||||||
ID: row.ID, Kind: row.Kind, RunID: row.RunID, Key: row.Key, Decision: d, DecisionID: row.DecisionID, RequestedAt: row.CreatedAt,
|
ID: row.ID, Kind: row.Kind, RunID: row.RunID, Key: row.Key, Decision: d, DecisionID: row.DecisionID, RequestedAt: row.CreatedAt,
|
||||||
Connector: row.Connector, Action: row.Action, TargetKind: row.TargetKind, TargetID: row.TargetID,
|
Connector: row.Connector, Action: row.Action, TargetKind: row.TargetKind, TargetID: row.TargetID,
|
||||||
Level: row.Level, Summary: row.Summary, State: row.State, Deadline: row.Deadline,
|
Level: row.Level, Irreversible: row.Irreversible, Summary: row.Summary, State: row.State, Deadline: row.Deadline,
|
||||||
Step: row.Step, ChangeRequest: row.ChangeRequest,
|
Step: row.Step, ChangeRequest: row.ChangeRequest,
|
||||||
}
|
}
|
||||||
if row.StepDeadline.Valid {
|
if row.StepDeadline.Valid {
|
||||||
|
|||||||
@@ -0,0 +1,247 @@
|
|||||||
|
package approvals
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json/jsontext"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/danielgtaylor/huma/v2"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||||
|
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
|
||||||
|
"github.com/samcharles93/archie-core/modules/connectors"
|
||||||
|
"github.com/samcharles93/archie-core/modules/governance"
|
||||||
|
"github.com/samcharles93/archie-core/modules/judgement"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrFreshAuthenticationFailed means the passkey assertion sent with an
|
||||||
|
// approval wasn't accepted for this person and request.
|
||||||
|
var ErrFreshAuthenticationFailed = errors.New("that passkey confirmation wasn't accepted")
|
||||||
|
|
||||||
|
// Confirmer checks that a signed-in person is at their authenticator now.
|
||||||
|
type Confirmer interface {
|
||||||
|
// BeginConfirmation starts a passkey assertion for the signed-in person,
|
||||||
|
// valid only for subject.
|
||||||
|
BeginConfirmation(ctx context.Context, subject string) (governance.PasskeyCeremony, error)
|
||||||
|
// Confirm verifies the person's assertion for subject and uses up the
|
||||||
|
// ceremony, so one assertion confirms one answer.
|
||||||
|
Confirm(ctx context.Context, token string, credential []byte, subject string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// UseConfirmer configures the passkey check behind approvals of actions that
|
||||||
|
// can't be undone. Without one, such an action can't be approved.
|
||||||
|
func (m *Module) UseConfirmer(c Confirmer) { m.confirm = c }
|
||||||
|
|
||||||
|
// viaDashboard is the channel recorded for an answer from the dashboard API.
|
||||||
|
const viaDashboard = "dashboard"
|
||||||
|
|
||||||
|
// confirmationSubject ties a passkey ceremony to one approval request.
|
||||||
|
func confirmationSubject(id uuid.UUID) string { return "approval:" + id.String() }
|
||||||
|
|
||||||
|
// irreversible reports whether approving the action needs a fresh passkey
|
||||||
|
// assertion: an action that changes something and isn't declared undoable.
|
||||||
|
// A missing declaration counts as irreversible.
|
||||||
|
func irreversible(a judgement.Action) bool {
|
||||||
|
if a.Effect.ReadOnly || a.Target.Disposable {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
switch a.Effect.Reversibility {
|
||||||
|
case connectors.UndoneAutomatically, connectors.Recoverable:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assertion is a passkey assertion made for one approval request.
|
||||||
|
type Assertion struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
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.
|
||||||
|
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 {
|
||||||
|
return "", "", ErrNotSignedIn
|
||||||
|
}
|
||||||
|
identity = governance.AccountIdentity(p.IdentityID)
|
||||||
|
who, err := m.verify(ctx, identity, row)
|
||||||
|
if err != nil {
|
||||||
|
return "", identity, err
|
||||||
|
}
|
||||||
|
return who.Name + " (" + identity + ")", identity, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// authorise accepts an answer from the dashboard only from a person who may
|
||||||
|
// give it. Approving an action that can't be undone also needs a passkey
|
||||||
|
// assertion made for this request.
|
||||||
|
func (m *Module) authorise(ctx context.Context, row store.Request, approved bool, assertion *Assertion) (by, identity string, err error) {
|
||||||
|
by, identity, err = m.caller(ctx, row)
|
||||||
|
if err != nil {
|
||||||
|
return "", identity, err
|
||||||
|
}
|
||||||
|
if approved && row.Irreversible {
|
||||||
|
if err := m.confirmed(ctx, row, assertion); err != nil {
|
||||||
|
return "", identity, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return by, identity, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) confirmed(ctx context.Context, row store.Request, a *Assertion) error {
|
||||||
|
if m.confirm == nil || a == nil || a.Token == "" || len(a.Credential) == 0 {
|
||||||
|
return ErrNeedsFreshAuthentication
|
||||||
|
}
|
||||||
|
err := m.confirm.Confirm(ctx, a.Token, a.Credential, confirmationSubject(row.ID))
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, governance.ErrCredentialRejected):
|
||||||
|
return ErrFreshAuthenticationFailed
|
||||||
|
case err != nil:
|
||||||
|
return fmt.Errorf("check passkey confirmation: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register adds the approvals API.
|
||||||
|
func (m *Module) Register(api huma.API) {
|
||||||
|
tags := []string{"Approvals"}
|
||||||
|
huma.Register(api, huma.Operation{
|
||||||
|
OperationID: "list-approvals", Method: http.MethodGet, Path: "/api/approvals",
|
||||||
|
Summary: "List approval requests waiting for an answer", Tags: tags,
|
||||||
|
}, m.list)
|
||||||
|
huma.Register(api, httpapi.SignedIn(huma.Operation{
|
||||||
|
OperationID: "answer-approval", Method: http.MethodPost, Path: "/api/approvals/{id}/answer",
|
||||||
|
Summary: "Approve or refuse an action as the signed-in person", Tags: tags,
|
||||||
|
}), m.answer)
|
||||||
|
huma.Register(api, httpapi.SignedIn(huma.Operation{
|
||||||
|
OperationID: "begin-approval-confirmation", Method: http.MethodPost, Path: "/api/approvals/{id}/confirmation",
|
||||||
|
Summary: "Start the passkey confirmation that approving an irreversible action needs", Tags: tags,
|
||||||
|
}), m.beginConfirmation)
|
||||||
|
}
|
||||||
|
|
||||||
|
type answerInput struct {
|
||||||
|
ID string `path:"id" format:"uuid"`
|
||||||
|
Body struct {
|
||||||
|
Approved bool `json:"approved"`
|
||||||
|
// Assertion is the passkey assertion that approving an action that
|
||||||
|
// can't be undone needs.
|
||||||
|
Assertion *Assertion `json:"assertion,omitempty"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) list(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]View], error) {
|
||||||
|
pending, err := m.Pending(ctx)
|
||||||
|
if err != nil {
|
||||||
|
m.log.ErrorContext(ctx, "list approvals", "error", err)
|
||||||
|
return nil, huma.NewError(http.StatusInternalServerError, "couldn't list approvals")
|
||||||
|
}
|
||||||
|
out := make([]View, 0, len(pending))
|
||||||
|
for _, p := range pending {
|
||||||
|
out = append(out, p.View())
|
||||||
|
}
|
||||||
|
return httpapi.OK(out), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) answer(ctx context.Context, in *answerInput) (*httpapi.Reply[View], error) {
|
||||||
|
id, err := uuid.Parse(in.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, huma.NewError(http.StatusBadRequest, "id is a request id")
|
||||||
|
}
|
||||||
|
row, err := m.openRequest(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.answerError(ctx, id, err)
|
||||||
|
}
|
||||||
|
req := in.Body
|
||||||
|
by, identity, err := m.authorise(ctx, row, req.Approved, req.Assertion)
|
||||||
|
if err != nil {
|
||||||
|
if refusal(err) || errors.Is(err, ErrFreshAuthenticationFailed) {
|
||||||
|
m.refuse(ctx, id, identity, err)
|
||||||
|
}
|
||||||
|
return nil, m.answerError(ctx, id, err)
|
||||||
|
}
|
||||||
|
out, err := m.answerAs(ctx, id, by, viaDashboard, req.Approved)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.answerError(ctx, id, err)
|
||||||
|
}
|
||||||
|
return httpapi.OK(out.View()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// openRequest returns the request when it can still be answered.
|
||||||
|
func (m *Module) openRequest(ctx context.Context, id uuid.UUID) (store.Request, error) {
|
||||||
|
row, err := m.store.ByID(ctx, m.orgID, id)
|
||||||
|
if err != nil {
|
||||||
|
return store.Request{}, err
|
||||||
|
}
|
||||||
|
return row, settleable(row, m.now().UTC())
|
||||||
|
}
|
||||||
|
|
||||||
|
// refuse records an answer that was turned away.
|
||||||
|
func (m *Module) refuse(ctx context.Context, id uuid.UUID, identity string, reason error) {
|
||||||
|
if identity == "" {
|
||||||
|
identity = "shared-token"
|
||||||
|
}
|
||||||
|
m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", reason.Error())
|
||||||
|
if err := m.store.Refuse(ctx, store.Refusal{
|
||||||
|
ID: uuid.New(), OrgID: m.orgID, RequestID: id, Identity: identity, Via: viaDashboard, Reason: reason.Error(), At: m.now().UTC(),
|
||||||
|
}); err != nil {
|
||||||
|
m.log.ErrorContext(ctx, "record approval refusal", "request", id, "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) answerError(ctx context.Context, id uuid.UUID, err error) error {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, ErrNotFound):
|
||||||
|
return huma.NewError(http.StatusNotFound, "no such approval request")
|
||||||
|
case errors.Is(err, ErrAnswered), errors.Is(err, ErrExpired):
|
||||||
|
return huma.NewError(http.StatusConflict, err.Error())
|
||||||
|
case errors.Is(err, ErrNeedsFreshAuthentication):
|
||||||
|
return huma.NewError(http.StatusPreconditionRequired, err.Error())
|
||||||
|
case refusal(err), errors.Is(err, ErrFreshAuthenticationFailed):
|
||||||
|
return huma.NewError(http.StatusForbidden, err.Error())
|
||||||
|
}
|
||||||
|
m.log.ErrorContext(ctx, "answer approval", "request", id, "error", err)
|
||||||
|
return huma.NewError(http.StatusInternalServerError, "couldn't record the answer")
|
||||||
|
}
|
||||||
|
|
||||||
|
type confirmationInput struct {
|
||||||
|
ID string `path:"id" format:"uuid"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Confirmation is the passkey request a person answers to approve an action
|
||||||
|
// that can't be undone.
|
||||||
|
type Confirmation struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
Options jsontext.Value `json:"options"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) beginConfirmation(ctx context.Context, in *confirmationInput) (*httpapi.Reply[Confirmation], error) {
|
||||||
|
id, err := uuid.Parse(in.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, huma.NewError(http.StatusBadRequest, "id is a request id")
|
||||||
|
}
|
||||||
|
row, err := m.openRequest(ctx, id)
|
||||||
|
if err == nil {
|
||||||
|
_, _, err = m.caller(ctx, row)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.answerError(ctx, id, err)
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case !row.Irreversible:
|
||||||
|
return nil, huma.NewError(http.StatusConflict, "that request needs no passkey confirmation")
|
||||||
|
case m.confirm == nil:
|
||||||
|
return nil, huma.NewError(http.StatusServiceUnavailable, "passkey confirmation isn't available")
|
||||||
|
}
|
||||||
|
ceremony, err := m.confirm.BeginConfirmation(ctx, confirmationSubject(id))
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, governance.ErrNoPasskey):
|
||||||
|
return nil, huma.NewError(http.StatusConflict, "Add a passkey to your account to approve this action.")
|
||||||
|
case err != nil:
|
||||||
|
return nil, m.answerError(ctx, id, err)
|
||||||
|
}
|
||||||
|
return httpapi.OK(Confirmation{Token: ceremony.Token, Options: jsontext.Value(ceremony.Options)}), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package approvals
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json/jsontext"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
|
||||||
|
"github.com/samcharles93/archie-core/modules/connectors"
|
||||||
|
"github.com/samcharles93/archie-core/modules/governance"
|
||||||
|
"github.com/samcharles93/archie-core/modules/judgement"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeConfirmer records the subject it was asked to confirm and answers with
|
||||||
|
// err.
|
||||||
|
type fakeConfirmer struct {
|
||||||
|
err error
|
||||||
|
subjects []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeConfirmer) BeginConfirmation(context.Context, string) (governance.PasskeyCeremony, error) {
|
||||||
|
return governance.PasskeyCeremony{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeConfirmer) Confirm(_ context.Context, _ string, _ []byte, subject string) error {
|
||||||
|
f.subjects = append(f.subjects, subject)
|
||||||
|
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"},
|
||||||
|
}
|
||||||
|
signedIn := func(id string) *governance.Principal {
|
||||||
|
return &governance.Principal{IdentityID: governance.IdentityID(id), Kind: governance.KindUser}
|
||||||
|
}
|
||||||
|
shared := governance.SharedTokenOwner()
|
||||||
|
request := uuid.New()
|
||||||
|
row := func(irreversible bool) store.Request {
|
||||||
|
return store.Request{ID: request, Kind: KindAction, Level: judgement.ProposeAndWait.String(), Asked: `["owner"]`, Irreversible: irreversible}
|
||||||
|
}
|
||||||
|
assertion := &Assertion{Token: "t", Credential: jsontext.Value(`{}`)}
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
as *governance.Principal
|
||||||
|
row store.Request
|
||||||
|
approved bool
|
||||||
|
assertion *Assertion
|
||||||
|
confirmer *fakeConfirmer
|
||||||
|
wantErr error
|
||||||
|
}{
|
||||||
|
{name: "a person on the path 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 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},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
m := &Module{people: people}
|
||||||
|
if tt.confirmer != nil {
|
||||||
|
m.UseConfirmer(tt.confirmer)
|
||||||
|
}
|
||||||
|
ctx := t.Context()
|
||||||
|
if tt.as != nil {
|
||||||
|
ctx = governance.WithPrincipal(ctx, *tt.as)
|
||||||
|
}
|
||||||
|
by, _, err := m.authorise(ctx, tt.row, tt.approved, tt.assertion)
|
||||||
|
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 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])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIrreversibleActionsNeedFreshAuthentication guards the risk threshold:
|
||||||
|
// anything that changes something and isn't declared undoable needs a passkey
|
||||||
|
// assertion to approve, including an action that declares nothing.
|
||||||
|
func TestIrreversibleActionsNeedFreshAuthentication(t *testing.T) {
|
||||||
|
action := func(effect connectors.Effect, disposable bool) judgement.Action {
|
||||||
|
return judgement.Action{Effect: effect, Target: connectors.Target{Disposable: disposable}}
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
in judgement.Action
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"an irreversible action", action(connectors.Effect{Reversibility: connectors.Irreversible}, false), true},
|
||||||
|
{"an action that declares no reversibility", action(connectors.Effect{}, false), true},
|
||||||
|
{"a recoverable action", action(connectors.Effect{Reversibility: connectors.Recoverable}, false), false},
|
||||||
|
{"an action undone automatically", action(connectors.Effect{Reversibility: connectors.UndoneAutomatically}, false), false},
|
||||||
|
{"a read-only action", action(connectors.Effect{ReadOnly: true}, false), false},
|
||||||
|
{"an irreversible action on a disposable target", action(connectors.Effect{Reversibility: connectors.Irreversible}, true), false},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := irreversible(tt.in); got != tt.want {
|
||||||
|
t.Fatalf("irreversible = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,18 +23,20 @@ type Request struct {
|
|||||||
Kind string `db:"kind"`
|
Kind string `db:"kind"`
|
||||||
Digest string `db:"digest"`
|
Digest string `db:"digest"`
|
||||||
// Copy the action details so the request can be read without loading the decision.
|
// Copy the action details so the request can be read without loading the decision.
|
||||||
Connector string `db:"connector"`
|
Connector string `db:"connector"`
|
||||||
Action string `db:"action"`
|
Action string `db:"action"`
|
||||||
TargetKind string `db:"target_kind"`
|
TargetKind string `db:"target_kind"`
|
||||||
TargetID string `db:"target_id"`
|
TargetID string `db:"target_id"`
|
||||||
Level string `db:"level"`
|
Level string `db:"level"`
|
||||||
Summary string `db:"summary"`
|
// Irreversible is whether approving needs a fresh passkey assertion.
|
||||||
State string `db:"state"`
|
Irreversible bool `db:"irreversible"`
|
||||||
Deadline time.Time `db:"deadline"`
|
Summary string `db:"summary"`
|
||||||
CreatedAt time.Time `db:"created_at"`
|
State string `db:"state"`
|
||||||
AnsweredAt sql.NullTime `db:"answered_at"`
|
Deadline time.Time `db:"deadline"`
|
||||||
AnsweredBy sql.NullString `db:"answered_by"`
|
CreatedAt time.Time `db:"created_at"`
|
||||||
AnsweredVia sql.NullString `db:"answered_via"`
|
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
|
// Asked is a JSON array of person IDs reached so far, not just the
|
||||||
// person assigned to the current step.
|
// person assigned to the current step.
|
||||||
Step int `db:"step"`
|
Step int `db:"step"`
|
||||||
@@ -57,7 +59,7 @@ type Store struct {
|
|||||||
func New(db *sqlx.DB) *Store { return &Store{db: db} }
|
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,
|
const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, connector, action, target_kind,
|
||||||
target_id, level, summary, state, deadline, created_at, answered_at, answered_by, answered_via,
|
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, asked::text AS asked, change_request, counted, discarded_because`
|
||||||
|
|
||||||
// Put inserts r or returns the existing request for the same organisation,
|
// Put inserts r or returns the existing request for the same organisation,
|
||||||
@@ -66,12 +68,12 @@ func (s *Store) Put(ctx context.Context, r Request) (Request, error) {
|
|||||||
var out Request
|
var out Request
|
||||||
err := s.db.GetContext(ctx, &out, `
|
err := s.db.GetContext(ctx, &out, `
|
||||||
INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, kind, digest, connector, action,
|
INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, kind, digest, connector, action,
|
||||||
target_kind, target_id, level, summary, state, deadline, step_deadline, asked, change_request)
|
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, CAST($17 AS jsonb), $18)
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, CAST($18 AS jsonb), $19)
|
||||||
ON CONFLICT (org_id, run_id, key) DO NOTHING
|
ON CONFLICT (org_id, run_id, key) DO NOTHING
|
||||||
RETURNING `+requestColumns,
|
RETURNING `+requestColumns,
|
||||||
r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.Kind, r.Digest, r.Connector, r.Action, r.TargetKind,
|
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.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.askedOrEmpty(), r.ChangeRequest)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return s.Get(ctx, r.OrgID, r.RunID, r.Key)
|
return s.Get(ctx, r.OrgID, r.RunID, r.Key)
|
||||||
}
|
}
|
||||||
|
|||||||
+31
-15
@@ -115,8 +115,9 @@ func (m *Module) escalate(ctx context.Context, d Deps, a store.Action) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// runApproved judges an approved action again and runs it once. An approval
|
// runApproved judges an approved action again and runs it once. An approval
|
||||||
// for an action that has since changed or become stricter is discarded, and
|
// whose binding no longer matches the action, or for an action that has become
|
||||||
// the operator asks again.
|
// stricter, is discarded, and the operator asks again. Whatever can't be
|
||||||
|
// checked stops the action.
|
||||||
func (m *Module) runApproved(ctx context.Context, d Deps, a store.Action) error {
|
func (m *Module) runApproved(ctx context.Context, d Deps, a store.Action) error {
|
||||||
var (
|
var (
|
||||||
held judgement.Decision
|
held judgement.Decision
|
||||||
@@ -138,15 +139,12 @@ func (m *Module) runApproved(ctx context.Context, d Deps, a store.Action) error
|
|||||||
}
|
}
|
||||||
return m.settled(ctx, d, a, actionApproved, actionFailed, err.Error())
|
return m.settled(ctx, d, a, actionApproved, actionFailed, err.Error())
|
||||||
}
|
}
|
||||||
fresh, err := d.Judge.Assess(ctx, judgement.Request{
|
fresh, why, err := m.recheck(ctx, d, a, held, answer)
|
||||||
RunID: a.TurnID, Key: held.Key + ":again", Connector: held.Action.Connector, Action: held.Action.Name,
|
|
||||||
Input: held.Action.Input, Workflow: principal,
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Nothing runs that wasn't judged again; the operator asks again.
|
// Nothing runs that couldn't be checked again; the operator asks again.
|
||||||
return m.settled(ctx, d, a, actionApproved, actionFailed, "It couldn't be judged again before running: "+err.Error())
|
return m.settled(ctx, d, a, actionApproved, actionFailed, "It couldn't be checked again before running: "+err.Error())
|
||||||
}
|
}
|
||||||
if why := invalidated(held, fresh); why != "" {
|
if why != "" {
|
||||||
if err := d.Approver.Discard(ctx, a.RequestID, why); err != nil {
|
if err := d.Approver.Discard(ctx, a.RequestID, why); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -174,18 +172,36 @@ func (m *Module) runApproved(ctx context.Context, d Deps, a store.Action) error
|
|||||||
return m.settled(ctx, d, a, actionRunning, actionSucceeded, out)
|
return m.settled(ctx, d, a, actionRunning, actionSucceeded, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
// invalidated says why an approval no longer covers the action as judged now,
|
// recheck judges an approved action again and says why its approval no longer
|
||||||
// or nothing when it still does.
|
// holds, or nothing when it still does. An error means it couldn't be checked.
|
||||||
|
func (m *Module) recheck(ctx context.Context, d Deps, a store.Action, held judgement.Decision, answer approvals.Answer) (judgement.Decision, string, error) {
|
||||||
|
fresh, err := d.Judge.Assess(ctx, judgement.Request{
|
||||||
|
RunID: a.TurnID, Key: held.Key + ":again", Connector: held.Action.Connector, Action: held.Action.Name,
|
||||||
|
Input: held.Action.Input, Workflow: principal,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fresh, "", fmt.Errorf("judge it: %w", err)
|
||||||
|
}
|
||||||
|
path, err := d.Settings.EscalationPath(ctx, held.Owner(), held.Level == judgement.Escalate)
|
||||||
|
if err != nil {
|
||||||
|
return fresh, "", fmt.Errorf("find who may approve it: %w", err)
|
||||||
|
}
|
||||||
|
why := stale(a, answer, held, fresh, approverIDs(path), time.Now())
|
||||||
|
if why == "" {
|
||||||
|
why = invalidated(held, fresh)
|
||||||
|
}
|
||||||
|
return fresh, why, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// invalidated says why an approval no longer covers the action's level as
|
||||||
|
// judged now, or nothing when it still does. What the action is and acts on
|
||||||
|
// is checked against its binding.
|
||||||
func invalidated(approved, fresh judgement.Decision) string {
|
func invalidated(approved, fresh judgement.Decision) string {
|
||||||
switch {
|
switch {
|
||||||
case fresh.Level == judgement.Never:
|
case fresh.Level == judgement.Never:
|
||||||
return "it is now refused: " + fresh.Reason
|
return "it is now refused: " + fresh.Reason
|
||||||
case fresh.Level.Runs():
|
case fresh.Level.Runs():
|
||||||
return ""
|
return ""
|
||||||
case fresh.Action.Target != approved.Action.Target:
|
|
||||||
return "its target changed since it was approved"
|
|
||||||
case fresh.Action.Effect != approved.Action.Effect:
|
|
||||||
return "its effect changed since it was approved"
|
|
||||||
case fresh.Level > approved.Level:
|
case fresh.Level > approved.Level:
|
||||||
return "judgement is stricter than when it was approved: now " + fresh.Level.String()
|
return "judgement is stricter than when it was approved: now " + fresh.Level.String()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json/jsontext"
|
||||||
|
json "encoding/json/v2"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"slices"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/modules/approvals"
|
||||||
|
"github.com/samcharles93/archie-core/modules/chat/internal/store"
|
||||||
|
"github.com/samcharles93/archie-core/modules/connectors"
|
||||||
|
"github.com/samcharles93/archie-core/modules/governance"
|
||||||
|
"github.com/samcharles93/archie-core/modules/judgement"
|
||||||
|
)
|
||||||
|
|
||||||
|
// bindingDomain separates a binding digest from every other SHA-256 the
|
||||||
|
// binary computes, so a digest can't be replayed as another kind of record.
|
||||||
|
const bindingDomain = "archie.chat.binding.v1\x00"
|
||||||
|
|
||||||
|
// Binding is the immutable record a held chat action's approval is bound to.
|
||||||
|
// The approver's answer covers this whole record, not only the action name and
|
||||||
|
// input, so an approval can't be moved to another organisation, conversation,
|
||||||
|
// turn, target or approver set, or run after any of them changed.
|
||||||
|
//
|
||||||
|
// Level is not part of it: a stricter level than the one held at is refused
|
||||||
|
// when the action is judged again, and a lower one is not a risk.
|
||||||
|
type Binding struct {
|
||||||
|
// ID is the held action's single-use id.
|
||||||
|
ID uuid.UUID `json:"id"`
|
||||||
|
Org string `json:"org"`
|
||||||
|
Session uuid.UUID `json:"session"`
|
||||||
|
Turn uuid.UUID `json:"turn"`
|
||||||
|
// Owner is the person whose conversation the action belongs to.
|
||||||
|
Owner string `json:"owner"`
|
||||||
|
// Request is the approval request put to the approvers.
|
||||||
|
Request uuid.UUID `json:"request"`
|
||||||
|
Connector string `json:"connector"`
|
||||||
|
Action string `json:"action"`
|
||||||
|
// Input is the action's arguments in connectors.Canonical form.
|
||||||
|
Input jsontext.Value `json:"input"`
|
||||||
|
Target connectors.Target `json:"target"`
|
||||||
|
Effect connectors.Effect `json:"effect"`
|
||||||
|
// Approvers are the people the request is put to, in escalation order. It
|
||||||
|
// is empty, not nil, when only people with authority may answer.
|
||||||
|
Approvers []string `json:"approvers"`
|
||||||
|
Expires time.Time `json:"expires"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var errUnbound = errors.New("the action's binding is incomplete")
|
||||||
|
|
||||||
|
// Digest returns the hex SHA-256 of the binding's canonical JSON (RFC 8785)
|
||||||
|
// under a domain prefix. It refuses a binding with a missing field: an
|
||||||
|
// approval that doesn't name everything it covers covers nothing.
|
||||||
|
func (b Binding) Digest() (string, error) {
|
||||||
|
if err := b.complete(); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(b)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("encode binding: %w", err)
|
||||||
|
}
|
||||||
|
value := jsontext.Value(raw)
|
||||||
|
if err := value.Canonicalize(jsontext.CanonicalizeRawInts(false)); err != nil {
|
||||||
|
return "", fmt.Errorf("canonicalise binding: %w", err)
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256(append([]byte(bindingDomain), value...))
|
||||||
|
return hex.EncodeToString(sum[:]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b Binding) complete() error {
|
||||||
|
missing := ""
|
||||||
|
switch {
|
||||||
|
case b.ID == uuid.Nil:
|
||||||
|
missing = "id"
|
||||||
|
case b.Org == "":
|
||||||
|
missing = "organisation"
|
||||||
|
case b.Session == uuid.Nil:
|
||||||
|
missing = "conversation"
|
||||||
|
case b.Turn == uuid.Nil:
|
||||||
|
missing = "turn"
|
||||||
|
case b.Owner == "":
|
||||||
|
missing = "owner"
|
||||||
|
case b.Request == uuid.Nil:
|
||||||
|
missing = "approval request"
|
||||||
|
case b.Connector == "" || b.Action == "":
|
||||||
|
missing = "action"
|
||||||
|
case len(bytes.TrimSpace(b.Input)) == 0:
|
||||||
|
missing = "arguments"
|
||||||
|
case b.Target.Kind == "" || b.Target.ID == "":
|
||||||
|
missing = "target"
|
||||||
|
case b.Approvers == nil:
|
||||||
|
missing = "approvers"
|
||||||
|
case b.Expires.IsZero():
|
||||||
|
missing = "expiry"
|
||||||
|
}
|
||||||
|
if missing != "" {
|
||||||
|
return fmt.Errorf("%w: no %s", errUnbound, missing)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// bindingFor describes a decision held for a turn.
|
||||||
|
func bindingFor(orgID string, id, request uuid.UUID, t store.Turn, d judgement.Decision, approvers []string, expires time.Time) Binding {
|
||||||
|
return Binding{
|
||||||
|
ID: id, Org: orgID, Session: t.SessionID, Turn: t.ID, Owner: t.Owner, Request: request,
|
||||||
|
Connector: d.Action.Connector, Action: d.Action.Name, Input: connectors.Canonical(d.Action.Input),
|
||||||
|
Target: d.Action.Target, Effect: d.Action.Effect, Approvers: approvers, Expires: expires.UTC(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// approverIDs are the people an escalation path asks, in order.
|
||||||
|
func approverIDs(path []governance.PathStep) []string {
|
||||||
|
out := make([]string, 0, len(path))
|
||||||
|
for _, st := range path {
|
||||||
|
if st.Person != "" {
|
||||||
|
out = append(out, st.Person)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// stale says why a held action's approval no longer covers what would run, or
|
||||||
|
// returns nothing when it still does. The action carries the binding recorded
|
||||||
|
// when it was held and its digest; fresh is the decision judged again now and
|
||||||
|
// approvers the people the request would be put to now. Anything that can't
|
||||||
|
// be checked counts as stale.
|
||||||
|
func stale(a store.Action, answer approvals.Answer, held, fresh judgement.Decision, approvers []string, now time.Time) string {
|
||||||
|
stored, why := recorded(a)
|
||||||
|
if why != "" {
|
||||||
|
return why
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case stored.ID != a.ID || stored.Turn != a.TurnID || stored.Owner != a.Owner || stored.Request != a.RequestID:
|
||||||
|
return "its binding belongs to another action"
|
||||||
|
case !answer.Approved || answer.RequestID != a.RequestID:
|
||||||
|
return "the answer was given for another request"
|
||||||
|
case !now.Before(stored.Expires):
|
||||||
|
return "it expired before it ran"
|
||||||
|
case stored.Connector != held.Action.Connector || stored.Action != held.Action.Name ||
|
||||||
|
!bytes.Equal(stored.Input, connectors.Canonical(held.Action.Input)):
|
||||||
|
return "the held action differs from the one approved"
|
||||||
|
}
|
||||||
|
return changed(stored, fresh, approvers)
|
||||||
|
}
|
||||||
|
|
||||||
|
// recorded reads the binding stored with an action and checks it against its
|
||||||
|
// digest.
|
||||||
|
func recorded(a store.Action) (Binding, string) {
|
||||||
|
var stored Binding
|
||||||
|
if len(a.Binding) == 0 || a.BindingDigest == "" || json.Unmarshal(a.Binding, &stored) != nil {
|
||||||
|
return Binding{}, "it carries no binding to check the approval against"
|
||||||
|
}
|
||||||
|
if sum, err := stored.Digest(); err != nil || sum != a.BindingDigest {
|
||||||
|
return Binding{}, "its binding is incomplete or was altered"
|
||||||
|
}
|
||||||
|
return stored, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// changed names the first thing in the action as it stands now that differs
|
||||||
|
// from what was approved.
|
||||||
|
func changed(stored Binding, fresh judgement.Decision, approvers []string) string {
|
||||||
|
switch {
|
||||||
|
case stored.Connector != fresh.Action.Connector || stored.Action != fresh.Action.Name:
|
||||||
|
return "its connector or action changed since it was approved"
|
||||||
|
case !bytes.Equal(stored.Input, connectors.Canonical(fresh.Action.Input)):
|
||||||
|
return "its arguments changed since it was approved"
|
||||||
|
case stored.Target != fresh.Action.Target:
|
||||||
|
return "its target changed since it was approved"
|
||||||
|
case stored.Effect != fresh.Action.Effect:
|
||||||
|
return "its effect changed since it was approved"
|
||||||
|
case !slices.Equal(stored.Approvers, approvers):
|
||||||
|
return "the people who may approve it changed since it was approved"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/json/jsontext"
|
||||||
|
"errors"
|
||||||
|
"log/slog"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/platform/hub"
|
||||||
|
"github.com/samcharles93/archie-core/modules/approvals"
|
||||||
|
"github.com/samcharles93/archie-core/modules/chat/internal/store"
|
||||||
|
"github.com/samcharles93/archie-core/modules/connectors"
|
||||||
|
"github.com/samcharles93/archie-core/modules/deliveries"
|
||||||
|
"github.com/samcharles93/archie-core/modules/governance"
|
||||||
|
"github.com/samcharles93/archie-core/modules/judgement"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
bindTurn = uuid.MustParse("11111111-1111-1111-1111-111111111111")
|
||||||
|
bindSession = uuid.MustParse("22222222-2222-2222-2222-222222222222")
|
||||||
|
bindAction = uuid.MustParse("33333333-3333-3333-3333-333333333333")
|
||||||
|
bindRequest = uuid.MustParse("44444444-4444-4444-4444-444444444444")
|
||||||
|
bindExpiry = time.Date(2100, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
)
|
||||||
|
|
||||||
|
func baseBinding() Binding {
|
||||||
|
return Binding{
|
||||||
|
ID: bindAction, Org: "default", Session: bindSession, Turn: bindTurn, Owner: alice, Request: bindRequest,
|
||||||
|
Connector: "mail", Action: "send", Input: connectors.Canonical(jsontext.Value(`{"to":"a@example.com","body":"hi"}`)),
|
||||||
|
Target: connectors.Target{Kind: "mailbox", ID: "inbox", Environment: "prod"},
|
||||||
|
Effect: connectors.Effect{Reversibility: connectors.Irreversible, Summary: "sends mail"},
|
||||||
|
Approvers: []string{alice}, Expires: bindExpiry,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBindingDigestCoversTheWholeAction guards the time-of-check to
|
||||||
|
// time-of-use gap: an approval is bound to everything that decides what runs
|
||||||
|
// and for whom, so a change to any part gives a different digest, a respelling
|
||||||
|
// of the same arguments does not, and a binding with a part missing has no
|
||||||
|
// digest at all.
|
||||||
|
func TestBindingDigestCoversTheWholeAction(t *testing.T) {
|
||||||
|
base, err := baseBinding().Digest()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
other := uuid.MustParse("99999999-9999-9999-9999-999999999999")
|
||||||
|
changes := []struct {
|
||||||
|
name string
|
||||||
|
change func(*Binding)
|
||||||
|
}{
|
||||||
|
{"the action's id", func(b *Binding) { b.ID = other }},
|
||||||
|
{"the organisation", func(b *Binding) { b.Org = "other" }},
|
||||||
|
{"the conversation", func(b *Binding) { b.Session = other }},
|
||||||
|
{"the turn", func(b *Binding) { b.Turn = other }},
|
||||||
|
{"the owner", func(b *Binding) { b.Owner = bob }},
|
||||||
|
{"the approval request", func(b *Binding) { b.Request = other }},
|
||||||
|
{"the connector", func(b *Binding) { b.Connector = "chat" }},
|
||||||
|
{"the action", func(b *Binding) { b.Action = "forward" }},
|
||||||
|
{"the arguments", func(b *Binding) { b.Input = jsontext.Value(`{"to":"b@example.com","body":"hi"}`) }},
|
||||||
|
{"the target's id", func(b *Binding) { b.Target.ID = "outbox" }},
|
||||||
|
{"the target's environment", func(b *Binding) { b.Target.Environment = "dev" }},
|
||||||
|
{"the effect", func(b *Binding) { b.Effect.Reversibility = connectors.Recoverable }},
|
||||||
|
{"the approvers", func(b *Binding) { b.Approvers = []string{bob} }},
|
||||||
|
{"the expiry", func(b *Binding) { b.Expires = bindExpiry.Add(time.Hour) }},
|
||||||
|
}
|
||||||
|
for _, tt := range changes {
|
||||||
|
t.Run("a change to "+tt.name+" changes the digest", func(t *testing.T) {
|
||||||
|
b := baseBinding()
|
||||||
|
tt.change(&b)
|
||||||
|
got, err := b.Digest()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got == base {
|
||||||
|
t.Fatalf("digest is unchanged by a change to %s", tt.name)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
t.Run("respelled arguments keep the digest", func(t *testing.T) {
|
||||||
|
b := baseBinding()
|
||||||
|
b.Input = connectors.Canonical(jsontext.Value(`{ "body": "hi", "to": "a@example.com" }`))
|
||||||
|
got, err := b.Digest()
|
||||||
|
if err != nil || got != base {
|
||||||
|
t.Fatalf("digest = %q, %v; want %q", got, err, base)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
missing := []struct {
|
||||||
|
name string
|
||||||
|
remove func(*Binding)
|
||||||
|
}{
|
||||||
|
{"id", func(b *Binding) { b.ID = uuid.Nil }},
|
||||||
|
{"organisation", func(b *Binding) { b.Org = "" }},
|
||||||
|
{"conversation", func(b *Binding) { b.Session = uuid.Nil }},
|
||||||
|
{"turn", func(b *Binding) { b.Turn = uuid.Nil }},
|
||||||
|
{"owner", func(b *Binding) { b.Owner = "" }},
|
||||||
|
{"approval request", func(b *Binding) { b.Request = uuid.Nil }},
|
||||||
|
{"connector", func(b *Binding) { b.Connector = "" }},
|
||||||
|
{"action", func(b *Binding) { b.Action = "" }},
|
||||||
|
{"arguments", func(b *Binding) { b.Input = nil }},
|
||||||
|
{"target kind", func(b *Binding) { b.Target.Kind = "" }},
|
||||||
|
{"target id", func(b *Binding) { b.Target.ID = "" }},
|
||||||
|
{"approvers", func(b *Binding) { b.Approvers = nil }},
|
||||||
|
{"expiry", func(b *Binding) { b.Expires = time.Time{} }},
|
||||||
|
}
|
||||||
|
for _, tt := range missing {
|
||||||
|
t.Run("a missing "+tt.name+" has no digest", func(t *testing.T) {
|
||||||
|
b := baseBinding()
|
||||||
|
tt.remove(&b)
|
||||||
|
if got, err := b.Digest(); !errors.Is(err, errUnbound) || got != "" {
|
||||||
|
t.Fatalf("digest = %q, %v; want errUnbound", got, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// approvalFixture is one approved chat action waiting to run, with the judge,
|
||||||
|
// approver and store fakes that record what happens to it.
|
||||||
|
type approvalFixture struct {
|
||||||
|
m *Module
|
||||||
|
d Deps
|
||||||
|
action store.Action
|
||||||
|
judge *runJudge
|
||||||
|
approver *runApprover
|
||||||
|
store *runStore
|
||||||
|
}
|
||||||
|
|
||||||
|
type runJudge struct {
|
||||||
|
Judge
|
||||||
|
fresh judgement.Decision
|
||||||
|
assessed int
|
||||||
|
executed []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *runJudge) Assess(context.Context, judgement.Request) (judgement.Decision, error) {
|
||||||
|
j.assessed++
|
||||||
|
return j.fresh, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *runJudge) Execute(_ context.Context, _ judgement.Decision, _ jsontext.Value, _ string) (string, error) {
|
||||||
|
j.executed = append(j.executed, "execute")
|
||||||
|
return "ran", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *runJudge) ExecuteApproved(_ context.Context, _ judgement.Decision, _ judgement.Approval, _ jsontext.Value, _ string) (string, error) {
|
||||||
|
j.executed = append(j.executed, "execute approved")
|
||||||
|
return "ran", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type runApprover struct {
|
||||||
|
Approver
|
||||||
|
discarded []string
|
||||||
|
accepted int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *runApprover) Discard(_ context.Context, _ uuid.UUID, because string) error {
|
||||||
|
a.discarded = append(a.discarded, because)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *runApprover) Accept(context.Context, uuid.UUID) error { a.accepted++; return nil }
|
||||||
|
|
||||||
|
type runSettings struct {
|
||||||
|
Settings
|
||||||
|
path []governance.PathStep
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s runSettings) EscalationPath(context.Context, string, bool) ([]governance.PathStep, error) {
|
||||||
|
return s.path, s.err
|
||||||
|
}
|
||||||
|
|
||||||
|
type runNotifier struct{}
|
||||||
|
|
||||||
|
func (runNotifier) Notify(context.Context, deliveries.Notification) error { return nil }
|
||||||
|
|
||||||
|
// runStore moves an action only from the state it is in, as the SQL does.
|
||||||
|
type runStore struct {
|
||||||
|
*fakeStore
|
||||||
|
state string
|
||||||
|
moves []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *runStore) Move(_ context.Context, _ uuid.UUID, from, to, _ string) (bool, error) {
|
||||||
|
if s.state != from {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
s.state = to
|
||||||
|
s.moves = append(s.moves, to)
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func heldDecision() judgement.Decision {
|
||||||
|
input := jsontext.Value(`{"to":"a@example.com","body":"hi"}`)
|
||||||
|
return judgement.Decision{
|
||||||
|
ID: uuid.New(), Key: "k", Level: judgement.ProposeAndWait,
|
||||||
|
Action: judgement.Action{
|
||||||
|
Connector: "mail", Name: "send", Input: input, Digest: connectors.Digest("send", input),
|
||||||
|
Target: connectors.Target{Kind: "mailbox", ID: "inbox", Environment: "prod"},
|
||||||
|
Effect: connectors.Effect{Reversibility: connectors.Irreversible, Summary: "sends mail"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newApprovalFixture(t *testing.T) *approvalFixture {
|
||||||
|
t.Helper()
|
||||||
|
held := heldDecision()
|
||||||
|
binding := baseBinding()
|
||||||
|
digest, err := binding.Digest()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rawBinding, _ := json.Marshal(binding)
|
||||||
|
rawDecision, _ := json.Marshal(held)
|
||||||
|
rawAnswer, _ := json.Marshal(approvals.Answer{RequestID: bindRequest, Approved: true, By: "alice", At: bindExpiry.Add(-time.Hour)})
|
||||||
|
f := &approvalFixture{
|
||||||
|
action: store.Action{
|
||||||
|
ID: bindAction, TurnID: bindTurn, Owner: alice, Key: "approval:k", Decision: rawDecision, RequestID: bindRequest,
|
||||||
|
State: actionApproved, Answer: rawAnswer, Binding: rawBinding, BindingDigest: digest,
|
||||||
|
},
|
||||||
|
judge: &runJudge{fresh: held},
|
||||||
|
approver: &runApprover{},
|
||||||
|
}
|
||||||
|
f.store = &runStore{fakeStore: &fakeStore{}, state: actionApproved}
|
||||||
|
f.m = &Module{orgID: "default", store: f.store, log: slog.New(slog.DiscardHandler), hub: hub.New()}
|
||||||
|
f.d = Deps{
|
||||||
|
People: fakePeople{alice: person(alice, governance.RoleAdmin)},
|
||||||
|
Access: governance.NewEngine(governance.ShippedOrgPolicies(governance.DefaultOrgID)),
|
||||||
|
Settings: runSettings{path: []governance.PathStep{{Person: alice}}},
|
||||||
|
Judge: f.judge, Approver: f.approver, Notifier: runNotifier{},
|
||||||
|
}
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRunApprovedRunsOnlyWhatWasApprovedAndOnlyOnce guards the dispatch-time
|
||||||
|
// recheck: an approval is discarded, and nothing runs, when the owner has lost
|
||||||
|
// access, when the target, effect, arguments or approvers changed, when the
|
||||||
|
// binding is missing, altered or expired, or when the answer belongs to
|
||||||
|
// another request. An action that still matches runs exactly once.
|
||||||
|
func TestRunApprovedRunsOnlyWhatWasApprovedAndOnlyOnce(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
change func(*approvalFixture)
|
||||||
|
wantRuns int
|
||||||
|
wantDiscard string
|
||||||
|
}{
|
||||||
|
{name: "an action that still matches runs", wantRuns: 1},
|
||||||
|
{
|
||||||
|
name: "the owner's access revoked while pending",
|
||||||
|
change: func(f *approvalFixture) { f.d.People = fakePeople{alice: person(alice, governance.RoleViewer)} },
|
||||||
|
wantDiscard: "you may not run connector mail",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "the target changed while pending",
|
||||||
|
change: func(f *approvalFixture) {
|
||||||
|
f.judge.fresh.Action.Target = connectors.Target{Kind: "mailbox", ID: "outbox", Environment: "prod"}
|
||||||
|
},
|
||||||
|
wantDiscard: "its target changed",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "the target changed and would now run unattended",
|
||||||
|
change: func(f *approvalFixture) {
|
||||||
|
f.judge.fresh.Action.Target.ID = "outbox"
|
||||||
|
f.judge.fresh.Level = judgement.ActQuietly
|
||||||
|
},
|
||||||
|
wantDiscard: "its target changed",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "the effect changed while pending",
|
||||||
|
change: func(f *approvalFixture) {
|
||||||
|
f.judge.fresh.Action.Effect.Summary = "deletes the mailbox"
|
||||||
|
},
|
||||||
|
wantDiscard: "its effect changed",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "the approvers changed while pending",
|
||||||
|
change: func(f *approvalFixture) {
|
||||||
|
f.d.Settings = runSettings{path: []governance.PathStep{{Person: bob}}}
|
||||||
|
},
|
||||||
|
wantDiscard: "the people who may approve it changed",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "the action is now refused",
|
||||||
|
change: func(f *approvalFixture) { f.judge.fresh.Level, f.judge.fresh.Reason = judgement.Never, "blackout" },
|
||||||
|
wantDiscard: "it is now refused",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "judgement is now stricter",
|
||||||
|
change: func(f *approvalFixture) { f.judge.fresh.Level = judgement.Escalate },
|
||||||
|
wantDiscard: "judgement is stricter",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "the stored binding was altered",
|
||||||
|
change: func(f *approvalFixture) { f.action.BindingDigest = strings.Repeat("0", 64) },
|
||||||
|
wantDiscard: "binding is incomplete or was altered",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "an action held before bindings existed",
|
||||||
|
change: func(f *approvalFixture) {
|
||||||
|
f.action.Binding, f.action.BindingDigest = nil, ""
|
||||||
|
},
|
||||||
|
wantDiscard: "carries no binding",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "the answer belongs to another request",
|
||||||
|
change: func(f *approvalFixture) {
|
||||||
|
f.action.Answer, _ = json.Marshal(approvals.Answer{RequestID: uuid.New(), Approved: true})
|
||||||
|
},
|
||||||
|
wantDiscard: "another request",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "the binding expired",
|
||||||
|
change: func(f *approvalFixture) {
|
||||||
|
b := baseBinding()
|
||||||
|
b.Expires = time.Now().Add(-time.Minute)
|
||||||
|
f.action.Binding, _ = json.Marshal(b)
|
||||||
|
f.action.BindingDigest, _ = b.Digest()
|
||||||
|
},
|
||||||
|
wantDiscard: "it expired",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
f := newApprovalFixture(t)
|
||||||
|
if tt.change != nil {
|
||||||
|
tt.change(f)
|
||||||
|
}
|
||||||
|
if err := f.m.runApproved(t.Context(), f.d, f.action); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := len(f.judge.executed); got != tt.wantRuns {
|
||||||
|
t.Fatalf("ran %d times (%v), want %d", got, f.judge.executed, tt.wantRuns)
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case tt.wantDiscard == "" && len(f.approver.discarded) != 0:
|
||||||
|
t.Fatalf("discarded %v, want the approval kept", f.approver.discarded)
|
||||||
|
case tt.wantDiscard != "" && (len(f.approver.discarded) != 1 || !strings.Contains(f.approver.discarded[0], tt.wantDiscard)):
|
||||||
|
t.Fatalf("discarded %v, want one containing %q", f.approver.discarded, tt.wantDiscard)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
t.Run("a second pass over the same action runs nothing", func(t *testing.T) {
|
||||||
|
f := newApprovalFixture(t)
|
||||||
|
for range 2 {
|
||||||
|
if err := f.m.runApproved(t.Context(), f.d, f.action); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(f.judge.executed) != 1 {
|
||||||
|
t.Fatalf("ran %d times, want once", len(f.judge.executed))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("who may approve can't be read", func(t *testing.T) {
|
||||||
|
f := newApprovalFixture(t)
|
||||||
|
f.d.Settings = runSettings{err: errors.New("settings unavailable")}
|
||||||
|
if err := f.m.runApproved(t.Context(), f.d, f.action); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(f.judge.executed) != 0 || len(f.approver.discarded) != 0 {
|
||||||
|
t.Fatalf("ran %v and discarded %v, want nothing to run and the approval kept", f.judge.executed, f.approver.discarded)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -69,6 +69,10 @@ type Action struct {
|
|||||||
State string `db:"state"`
|
State string `db:"state"`
|
||||||
Answer []byte `db:"answer"`
|
Answer []byte `db:"answer"`
|
||||||
Result string `db:"result"`
|
Result string `db:"result"`
|
||||||
|
// Binding is the record the approval is bound to, and BindingDigest its
|
||||||
|
// digest. An action stored without them can't be run.
|
||||||
|
Binding jsontext.Value `db:"binding"`
|
||||||
|
BindingDigest string `db:"binding_digest"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Store is the chat module's Postgres store.
|
// Store is the chat module's Postgres store.
|
||||||
@@ -354,16 +358,16 @@ func (s *Store) EventsOf(ctx context.Context, sessionID uuid.UUID, kinds []strin
|
|||||||
// one under its key, and returns the stored one either way.
|
// one under its key, and returns the stored one either way.
|
||||||
func (s *Store) PutAction(ctx context.Context, orgID string, a Action) (Action, error) {
|
func (s *Store) PutAction(ctx context.Context, orgID string, a Action) (Action, error) {
|
||||||
if _, err := s.db.ExecContext(ctx, `
|
if _, err := s.db.ExecContext(ctx, `
|
||||||
INSERT INTO chat.actions (id, org_id, turn_id, key, decision, request_id, path, step_due, state)
|
INSERT INTO chat.actions (id, org_id, turn_id, key, decision, request_id, path, step_due, state, binding, binding_digest)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'waiting')
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'waiting', $9, $10)
|
||||||
ON CONFLICT (turn_id, key) DO NOTHING`,
|
ON CONFLICT (turn_id, key) DO NOTHING`,
|
||||||
a.ID, orgID, a.TurnID, a.Key, a.Decision, a.RequestID, a.Path, a.StepDue); err != nil {
|
a.ID, orgID, a.TurnID, a.Key, a.Decision, a.RequestID, a.Path, a.StepDue, a.Binding, a.BindingDigest); err != nil {
|
||||||
return Action{}, fmt.Errorf("record held action: %w", err)
|
return Action{}, fmt.Errorf("record held action: %w", err)
|
||||||
}
|
}
|
||||||
return s.actionBy(ctx, `turn_id = $1 AND key = $2`, a.TurnID, a.Key)
|
return s.actionBy(ctx, `turn_id = $1 AND key = $2`, a.TurnID, a.Key)
|
||||||
}
|
}
|
||||||
|
|
||||||
const actionColumns = `id, turn_id, key, decision, request_id, path, step, step_due, state, answer, result,
|
const actionColumns = `id, turn_id, key, decision, request_id, path, step, step_due, state, answer, result, binding, binding_digest,
|
||||||
(SELECT s.owner_id FROM chat.turns t JOIN chat.sessions s ON s.id = t.session_id WHERE t.id = chat.actions.turn_id) AS owner_id`
|
(SELECT s.owner_id FROM chat.turns t JOIN chat.sessions s ON s.id = t.session_id WHERE t.id = chat.actions.turn_id) AS owner_id`
|
||||||
|
|
||||||
func (s *Store) actionBy(ctx context.Context, where string, args ...any) (Action, error) {
|
func (s *Store) actionBy(ctx context.Context, where string, args ...any) (Action, error) {
|
||||||
|
|||||||
@@ -35,7 +35,13 @@ type taintJudge struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (j *taintJudge) Assess(_ context.Context, req judgement.Request) (judgement.Decision, error) {
|
func (j *taintJudge) Assess(_ context.Context, req judgement.Request) (judgement.Decision, error) {
|
||||||
return judgement.Decision{Key: req.Key, RunID: req.RunID, Level: j.level}, nil
|
return judgement.Decision{
|
||||||
|
Key: req.Key, RunID: req.RunID, Level: j.level,
|
||||||
|
Action: judgement.Action{
|
||||||
|
Connector: req.Connector, Name: req.Action, Input: req.Input,
|
||||||
|
Target: connectors.Target{Kind: "mailbox", ID: "inbox"},
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *taintJudge) Execute(_ context.Context, d judgement.Decision, _ jsontext.Value, _ string) (string, error) {
|
func (j *taintJudge) Execute(_ context.Context, d judgement.Decision, _ jsontext.Value, _ string) (string, error) {
|
||||||
@@ -53,7 +59,7 @@ func (j *taintJudge) Execute(_ context.Context, d judgement.Decision, _ jsontext
|
|||||||
type fakeApprover struct{ Approver }
|
type fakeApprover struct{ Approver }
|
||||||
|
|
||||||
func (fakeApprover) Ask(_ context.Context, _ uuid.UUID, key string, _ judgement.Decision, _ []governance.PathStep) (approvals.Request, error) {
|
func (fakeApprover) Ask(_ context.Context, _ uuid.UUID, key string, _ judgement.Decision, _ []governance.PathStep) (approvals.Request, error) {
|
||||||
return approvals.Request{ID: uuid.New(), Key: key, Summary: "approve this", StepDeadline: time.Now().Add(time.Hour)}, nil
|
return approvals.Request{ID: uuid.New(), Key: key, Summary: "approve this", StepDeadline: time.Now().Add(time.Hour), Deadline: time.Now().Add(time.Hour)}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// fakeSettings gives every held action a one-step escalation path.
|
// fakeSettings gives every held action a one-step escalation path.
|
||||||
|
|||||||
+18
-2
@@ -9,6 +9,7 @@ import (
|
|||||||
"regexp"
|
"regexp"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/samcharles93/ai-sdk/core"
|
"github.com/samcharles93/ai-sdk/core"
|
||||||
@@ -288,11 +289,26 @@ func (m *Module) hold(ctx context.Context, d Deps, t store.Turn, decision judgem
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("find who approves %s %s: %w", decision.Action.Connector, decision.Action.Name, err)
|
return "", fmt.Errorf("find who approves %s %s: %w", decision.Action.Connector, decision.Action.Name, err)
|
||||||
}
|
}
|
||||||
|
// A decision that can't be bound completely is never put to anyone.
|
||||||
|
approvers := approverIDs(path)
|
||||||
|
actionID := uuid.New()
|
||||||
|
if err := bindingFor(m.orgID, actionID, uuid.New(), t, decision, approvers, time.Now()).complete(); err != nil {
|
||||||
|
return "", fmt.Errorf("hold %s %s: %w", decision.Action.Connector, decision.Action.Name, err)
|
||||||
|
}
|
||||||
key := waitKey(decision.Key)
|
key := waitKey(decision.Key)
|
||||||
request, err := d.Approver.Ask(ctx, t.ID, key, decision, path)
|
request, err := d.Approver.Ask(ctx, t.ID, key, decision, path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("ask for approval: %w", err)
|
return "", fmt.Errorf("ask for approval: %w", err)
|
||||||
}
|
}
|
||||||
|
binding := bindingFor(m.orgID, actionID, request.ID, t, decision, approvers, request.Deadline)
|
||||||
|
digest, err := binding.Digest()
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("hold %s %s: %w", decision.Action.Connector, decision.Action.Name, err)
|
||||||
|
}
|
||||||
|
rawBinding, err := json.Marshal(binding)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
rawDecision, err := json.Marshal(decision)
|
rawDecision, err := json.Marshal(decision)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@@ -302,8 +318,8 @@ func (m *Module) hold(ctx context.Context, d Deps, t store.Turn, decision judgem
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if _, err := m.store.PutAction(ctx, m.orgID, store.Action{
|
if _, err := m.store.PutAction(ctx, m.orgID, store.Action{
|
||||||
ID: uuid.New(), TurnID: t.ID, Key: key, Decision: rawDecision, RequestID: request.ID,
|
ID: actionID, TurnID: t.ID, Key: key, Decision: rawDecision, RequestID: request.ID,
|
||||||
Path: rawPath, StepDue: request.StepDeadline,
|
Path: rawPath, StepDue: request.StepDeadline, Binding: rawBinding, BindingDigest: digest,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
package governance
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/go-webauthn/webauthn/protocol"
|
||||||
|
"github.com/go-webauthn/webauthn/webauthn"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/modules/governance/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
func (m *Module) BeginConfirmation(ctx context.Context, subject string) (PasskeyCeremony, error) {
|
||||||
|
p, ok := PrincipalFromContext(ctx)
|
||||||
|
if !ok || subject == "" {
|
||||||
|
return PasskeyCeremony{}, ErrCredentialRejected
|
||||||
|
}
|
||||||
|
wa, err := m.webAuthn(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return PasskeyCeremony{}, err
|
||||||
|
}
|
||||||
|
owner := string(p.IdentityID)
|
||||||
|
row, creds, err := m.store.LoadPasskeyUser(ctx, owner)
|
||||||
|
if err != nil {
|
||||||
|
return PasskeyCeremony{}, mapIdentityErr(err)
|
||||||
|
}
|
||||||
|
user, err := decodePasskeyUser(row, creds)
|
||||||
|
if err != nil {
|
||||||
|
return PasskeyCeremony{}, err
|
||||||
|
}
|
||||||
|
if len(user.credentials) == 0 {
|
||||||
|
return PasskeyCeremony{}, ErrNoPasskey
|
||||||
|
}
|
||||||
|
options, session, err := wa.BeginLogin(user, webauthn.WithUserVerification(protocol.VerificationRequired))
|
||||||
|
if err != nil {
|
||||||
|
return PasskeyCeremony{}, err
|
||||||
|
}
|
||||||
|
data, err := json.Marshal(session)
|
||||||
|
if err != nil {
|
||||||
|
return PasskeyCeremony{}, err
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(options)
|
||||||
|
if err != nil {
|
||||||
|
return PasskeyCeremony{}, err
|
||||||
|
}
|
||||||
|
token := rand.Text()
|
||||||
|
if err := m.store.InsertPasskeyCeremony(ctx, sessionHash(token), owner, false, subject, data); err != nil {
|
||||||
|
return PasskeyCeremony{}, err
|
||||||
|
}
|
||||||
|
return PasskeyCeremony{Token: token, Options: encoded}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Confirm verifies the signed-in person's passkey assertion for subject and
|
||||||
|
// uses up its ceremony. A missing, expired or used ceremony, another person's
|
||||||
|
// assertion or a cloned authenticator is ErrCredentialRejected.
|
||||||
|
func (m *Module) Confirm(ctx context.Context, token string, response []byte, subject string) error {
|
||||||
|
p, ok := PrincipalFromContext(ctx)
|
||||||
|
if !ok || subject == "" {
|
||||||
|
return ErrCredentialRejected
|
||||||
|
}
|
||||||
|
wa, err := m.webAuthn(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ceremony, err := m.store.TakePasskeyCeremony(ctx, sessionHash(token), false, subject)
|
||||||
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
|
return ErrCredentialRejected
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
owner := string(p.IdentityID)
|
||||||
|
if ceremony.IdentityID != owner {
|
||||||
|
return ErrCredentialRejected
|
||||||
|
}
|
||||||
|
var session webauthn.SessionData
|
||||||
|
if err := json.Unmarshal(ceremony.SessionData, &session); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
parsed, err := protocol.ParseCredentialRequestResponseBytes(response)
|
||||||
|
if err != nil {
|
||||||
|
return ErrCredentialRejected
|
||||||
|
}
|
||||||
|
err = m.store.WithPasskeyTx(ctx, func(pt *store.PasskeyTx) error {
|
||||||
|
row, creds, err := pt.LoadUser(ctx, owner)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
user, err := decodePasskeyUser(row, creds)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
cred, err := wa.ValidateLogin(user, session, parsed)
|
||||||
|
if err != nil || cred.Authenticator.CloneWarning {
|
||||||
|
return ErrCredentialRejected
|
||||||
|
}
|
||||||
|
return persistPasskeyTx(ctx, pt, cred, owner, "", false)
|
||||||
|
})
|
||||||
|
return mapIdentityErr(err)
|
||||||
|
}
|
||||||
@@ -105,27 +105,29 @@ func (s *Store) LoadPasskeyUser(ctx context.Context, identityID string) (Identit
|
|||||||
}
|
}
|
||||||
|
|
||||||
// InsertPasskeyCeremony sweeps expired ceremonies and stores a new 5-minute ceremony.
|
// InsertPasskeyCeremony sweeps expired ceremonies and stores a new 5-minute ceremony.
|
||||||
func (s *Store) InsertPasskeyCeremony(ctx context.Context, tokenHash, identityID string, registration bool, sessionData []byte) error {
|
// subject is empty for a sign-in or registration, and names what a
|
||||||
|
// confirmation is for otherwise.
|
||||||
|
func (s *Store) InsertPasskeyCeremony(ctx context.Context, tokenHash, identityID string, registration bool, subject string, sessionData []byte) error {
|
||||||
if _, err := s.db.ExecContext(ctx, `DELETE FROM governance.passkey_ceremonies WHERE expires_at <= now()`); err != nil {
|
if _, err := s.db.ExecContext(ctx, `DELETE FROM governance.passkey_ceremonies WHERE expires_at <= now()`); err != nil {
|
||||||
return fmt.Errorf("sweep passkey ceremonies: %w", err)
|
return fmt.Errorf("sweep passkey ceremonies: %w", err)
|
||||||
}
|
}
|
||||||
if _, err := s.db.ExecContext(ctx, `
|
if _, err := s.db.ExecContext(ctx, `
|
||||||
INSERT INTO governance.passkey_ceremonies (token_hash, identity_id, registration, session_data, expires_at)
|
INSERT INTO governance.passkey_ceremonies (token_hash, identity_id, registration, subject, session_data, expires_at)
|
||||||
VALUES ($1, $2, $3, $4, now() + interval '5 minutes')`,
|
VALUES ($1, $2, $3, $4, $5, now() + interval '5 minutes')`,
|
||||||
tokenHash, identityID, registration, sessionData); err != nil {
|
tokenHash, identityID, registration, subject, sessionData); err != nil {
|
||||||
return fmt.Errorf("insert passkey ceremony: %w", err)
|
return fmt.Errorf("insert passkey ceremony: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TakePasskeyCeremony consumes a live single-use ceremony.
|
// TakePasskeyCeremony consumes a live single-use ceremony started for subject.
|
||||||
func (s *Store) TakePasskeyCeremony(ctx context.Context, tokenHash string, registration bool) (CeremonyRow, error) {
|
func (s *Store) TakePasskeyCeremony(ctx context.Context, tokenHash string, registration bool, subject string) (CeremonyRow, error) {
|
||||||
var out CeremonyRow
|
var out CeremonyRow
|
||||||
err := s.db.GetContext(ctx, &out, `
|
err := s.db.GetContext(ctx, &out, `
|
||||||
DELETE FROM governance.passkey_ceremonies
|
DELETE FROM governance.passkey_ceremonies
|
||||||
WHERE token_hash = $1 AND registration = $2 AND expires_at > now()
|
WHERE token_hash = $1 AND registration = $2 AND subject = $3 AND expires_at > now()
|
||||||
RETURNING token_hash, identity_id, registration, session_data, expires_at`,
|
RETURNING token_hash, identity_id, registration, session_data, expires_at`,
|
||||||
tokenHash, registration)
|
tokenHash, registration, subject)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return CeremonyRow{}, ErrNotFound
|
return CeremonyRow{}, ErrNotFound
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -651,7 +651,7 @@ func (m *Module) BeginPasskey(ctx context.Context, registration bool) (PasskeyCe
|
|||||||
return PasskeyCeremony{}, err
|
return PasskeyCeremony{}, err
|
||||||
}
|
}
|
||||||
token := rand.Text()
|
token := rand.Text()
|
||||||
if err := m.store.InsertPasskeyCeremony(ctx, sessionHash(token), owner, registration, data); err != nil {
|
if err := m.store.InsertPasskeyCeremony(ctx, sessionHash(token), owner, registration, "", data); err != nil {
|
||||||
return PasskeyCeremony{}, err
|
return PasskeyCeremony{}, err
|
||||||
}
|
}
|
||||||
return PasskeyCeremony{Token: token, Options: encoded}, nil
|
return PasskeyCeremony{Token: token, Options: encoded}, nil
|
||||||
@@ -663,7 +663,7 @@ func (m *Module) FinishPasskey(ctx context.Context, token string, response []byt
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return AccountSession{}, err
|
return AccountSession{}, err
|
||||||
}
|
}
|
||||||
ceremony, err := m.store.TakePasskeyCeremony(ctx, sessionHash(token), registration)
|
ceremony, err := m.store.TakePasskeyCeremony(ctx, sessionHash(token), registration, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return AccountSession{}, mapIdentityErr(err)
|
return AccountSession{}, mapIdentityErr(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -241,6 +241,10 @@ func TestExecuteApprovedRunsOnlyWhatThePersonSaw(t *testing.T) {
|
|||||||
},
|
},
|
||||||
wantErr: ErrUnapproved,
|
wantErr: ErrUnapproved,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "the same arguments spelled differently still run",
|
||||||
|
d: decided, a: approval, input: jsontext.Value(`{ "path" : "/tmp/runner" }`),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "input that differs from the judged action is refused",
|
name: "input that differs from the judged action is refused",
|
||||||
d: decided, a: approval, input: jsontext.Value(`{"path":"/"}`),
|
d: decided, a: approval, input: jsontext.Value(`{"path":"/"}`),
|
||||||
|
|||||||
@@ -37,8 +37,22 @@ export async function usePasskey(registration:boolean,name=""):Promise<void>{
|
|||||||
for(const list of ["excludeCredentials","allowCredentials"]){for(const entry of (key[list] as {id:string|ArrayBuffer}[]|undefined)??[]){entry.id=decode(entry.id as string)}}
|
for(const list of ["excludeCredentials","allowCredentials"]){for(const entry of (key[list] as {id:string|ArrayBuffer}[]|undefined)??[]){entry.id=decode(entry.id as string)}}
|
||||||
const credential=(registration?await navigator.credentials.create({publicKey:key as unknown as PublicKeyCredentialCreationOptions}):await navigator.credentials.get({publicKey:key as unknown as PublicKeyCredentialRequestOptions})) as PublicKeyCredential|null;
|
const credential=(registration?await navigator.credentials.create({publicKey:key as unknown as PublicKeyCredentialCreationOptions}):await navigator.credentials.get({publicKey:key as unknown as PublicKeyCredentialRequestOptions})) as PublicKeyCredential|null;
|
||||||
if(!credential)throw new Error(errors.accounts.passkey.noneSelected);
|
if(!credential)throw new Error(errors.accounts.passkey.noneSelected);
|
||||||
|
await api.finishPasskey(registration,credentialJSON(credential),name);
|
||||||
|
}
|
||||||
|
|
||||||
|
function credentialJSON(credential:PublicKeyCredential){
|
||||||
const response=credential.response;
|
const response=credential.response;
|
||||||
const common={clientDataJSON:encode(response.clientDataJSON)};
|
const common={clientDataJSON:encode(response.clientDataJSON)};
|
||||||
const data=response instanceof AuthenticatorAttestationResponse?{...common,attestationObject:encode(response.attestationObject),transports:response.getTransports()}:{...common,authenticatorData:encode((response as AuthenticatorAssertionResponse).authenticatorData),signature:encode((response as AuthenticatorAssertionResponse).signature),userHandle:encode((response as AuthenticatorAssertionResponse).userHandle)};
|
const data=response instanceof AuthenticatorAttestationResponse?{...common,attestationObject:encode(response.attestationObject),transports:response.getTransports()}:{...common,authenticatorData:encode((response as AuthenticatorAssertionResponse).authenticatorData),signature:encode((response as AuthenticatorAssertionResponse).signature),userHandle:encode((response as AuthenticatorAssertionResponse).userHandle)};
|
||||||
await api.finishPasskey(registration,{id:credential.id,rawId:encode(credential.rawId),type:credential.type,response:data,clientExtensionResults:credential.getClientExtensionResults(),authenticatorAttachment:credential.authenticatorAttachment},name);
|
return {id:credential.id,rawId:encode(credential.rawId),type:credential.type,response:data,clientExtensionResults:credential.getClientExtensionResults(),authenticatorAttachment:credential.authenticatorAttachment};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Has the signed-in person's authenticator sign the challenge in options, and returns the assertion as the server reads it. */
|
||||||
|
export async function getAssertion(options:{publicKey:Record<string,unknown>}):Promise<unknown>{
|
||||||
|
const key=options.publicKey;
|
||||||
|
key.challenge=decode(key.challenge as string);
|
||||||
|
for(const entry of (key.allowCredentials as {id:string|ArrayBuffer}[]|undefined)??[]){entry.id=decode(entry.id as string)}
|
||||||
|
const credential=await navigator.credentials.get({publicKey:key as unknown as PublicKeyCredentialRequestOptions}) as PublicKeyCredential|null;
|
||||||
|
if(!credential)throw new Error(errors.accounts.passkey.noneSelected);
|
||||||
|
return credentialJSON(credential);
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ import { computed, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
|
|||||||
import { errors } from "@/copy/errors";
|
import { errors } from "@/copy/errors";
|
||||||
import { api, describeError, type ChatTurnRecord } from "@/lib/api";
|
import { api, describeError, type ChatTurnRecord } from "@/lib/api";
|
||||||
import { router } from "@/router";
|
import { router } from "@/router";
|
||||||
|
import { answerApproval } from "@/runs/answer";
|
||||||
import { useSessionStore } from "@/stores/session";
|
import { useSessionStore } from "@/stores/session";
|
||||||
import { commandCompletions, detectTrigger, taskCompletions, type Completion, type Trigger } from "./commands";
|
import { commandCompletions, detectTrigger, taskCompletions, type Completion, type Trigger } from "./commands";
|
||||||
import {
|
import {
|
||||||
@@ -206,7 +207,7 @@ export async function answerAsk(answer: string, ask = streamingTurn.value?.ask):
|
|||||||
if (!ask) return false;
|
if (!ask) return false;
|
||||||
try {
|
try {
|
||||||
if (ask.via !== "approvals") throw new Error(errors.chat.ask.unsupported);
|
if (ask.via !== "approvals") throw new Error(errors.chat.ask.unsupported);
|
||||||
await api.answerApproval(ask.id, answer === "approve");
|
await answerApproval(ask.id, answer === "approve");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
askError.value = describeError(err, errors.chat.ask.answer);
|
askError.value = describeError(err, errors.chat.ask.answer);
|
||||||
askErrorID.value = ask.id;
|
askErrorID.value = ask.id;
|
||||||
|
|||||||
+16
-2
@@ -193,8 +193,11 @@ export const api = {
|
|||||||
/** Asks a run that has not ended to stop, along with the runs it called. */
|
/** Asks a run that has not ended to stop, along with the runs it called. */
|
||||||
cancelRun: (id: string) => request<Run>(`/api/runs/${encodeURIComponent(id)}/cancel`, { method: "POST", body: {} }),
|
cancelRun: (id: string) => request<Run>(`/api/runs/${encodeURIComponent(id)}/cancel`, { method: "POST", body: {} }),
|
||||||
approvals: () => request<Approval[]>("/api/approvals"),
|
approvals: () => request<Approval[]>("/api/approvals"),
|
||||||
answerApproval: (id: string, approved: boolean) =>
|
answerApproval: (id: string, approved: boolean, assertion?: ApprovalAssertion) =>
|
||||||
request<Approval>(`/api/approvals/${encodeURIComponent(id)}/answer`, { method: "POST", body: { approved } }),
|
request<Approval>(`/api/approvals/${encodeURIComponent(id)}/answer`, { method: "POST", body: { approved, assertion } }),
|
||||||
|
/** Starts the passkey confirmation that approving an irreversible action needs. */
|
||||||
|
beginApprovalConfirmation: (id: string) =>
|
||||||
|
request<ApprovalConfirmation>(`/api/approvals/${encodeURIComponent(id)}/confirmation`, { method: "POST", body: {} }),
|
||||||
events: (params: { limit?: number; source?: string; type?: string; matched?: string } = {}) =>
|
events: (params: { limit?: number; source?: string; type?: string; matched?: string } = {}) =>
|
||||||
request<EventRecord[]>("/api/events" + qs(params)),
|
request<EventRecord[]>("/api/events" + qs(params)),
|
||||||
event: (id: string) => request<EventDetail>(`/api/events/${encodeURIComponent(id)}`),
|
event: (id: string) => request<EventDetail>(`/api/events/${encodeURIComponent(id)}`),
|
||||||
@@ -675,6 +678,17 @@ export interface Run {
|
|||||||
result?: unknown;
|
result?: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A passkey assertion made for one approval request. */
|
||||||
|
export interface ApprovalAssertion {
|
||||||
|
token: string;
|
||||||
|
credential: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApprovalConfirmation {
|
||||||
|
token: string;
|
||||||
|
options: { publicKey: Record<string, unknown> };
|
||||||
|
}
|
||||||
|
|
||||||
export interface Approval {
|
export interface Approval {
|
||||||
id: string;
|
id: string;
|
||||||
run_id: string;
|
run_id: string;
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { Timestamp } from "@/components/ui/timestamp";
|
|||||||
import { errors } from "@/copy/errors";
|
import { errors } from "@/copy/errors";
|
||||||
import { api, describeError } from "@/lib/api";
|
import { api, describeError } from "@/lib/api";
|
||||||
import { usePoll, useRead } from "@/lib/use-read";
|
import { usePoll, useRead } from "@/lib/use-read";
|
||||||
|
import { answerApproval } from "@/runs/answer";
|
||||||
import { useLiveResource } from "@/stores/session";
|
import { useLiveResource } from "@/stores/session";
|
||||||
|
|
||||||
/** Waiting approvals are a filter on runs: each asks a person to allow one
|
/** Waiting approvals are a filter on runs: each asks a person to allow one
|
||||||
@@ -31,7 +32,7 @@ async function answer(id: string, approved: boolean): Promise<void> {
|
|||||||
busy.value = id;
|
busy.value = id;
|
||||||
answerError.value = "";
|
answerError.value = "";
|
||||||
try {
|
try {
|
||||||
await api.answerApproval(id, approved);
|
await answerApproval(id, approved);
|
||||||
emit("answered");
|
emit("answered");
|
||||||
} catch (cause) {
|
} catch (cause) {
|
||||||
answerError.value = describeError(cause, errors.common.unknown);
|
answerError.value = describeError(cause, errors.common.unknown);
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { getAssertion } from "@/accounts/accounts";
|
||||||
|
import { api, ApiError, type Approval } from "@/lib/api";
|
||||||
|
|
||||||
|
/** Answers an approval. The server asks for a fresh passkey assertion
|
||||||
|
* (428) when approving an action that can't be undone; the person confirms
|
||||||
|
* with their passkey and the answer is sent again with it. */
|
||||||
|
export async function answerApproval(id: string, approved: boolean): Promise<Approval> {
|
||||||
|
try {
|
||||||
|
return await api.answerApproval(id, approved);
|
||||||
|
} catch (cause) {
|
||||||
|
if (!(cause instanceof ApiError) || cause.status !== 428) throw cause;
|
||||||
|
}
|
||||||
|
const confirmation = await api.beginApprovalConfirmation(id);
|
||||||
|
const credential = await getAssertion(confirmation.options);
|
||||||
|
return api.answerApproval(id, approved, { token: confirmation.token, credential });
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ const apiStub =
|
|||||||
"data:text/javascript," +
|
"data:text/javascript," +
|
||||||
encodeURIComponent(
|
encodeURIComponent(
|
||||||
"export const api = new Proxy({}, { get: (_, p) => globalThis.__archieChatTestApi[p] });" +
|
"export const api = new Proxy({}, { get: (_, p) => globalThis.__archieChatTestApi[p] });" +
|
||||||
|
"export class ApiError extends Error { constructor(message, status) { super(message); this.status = status; } }" +
|
||||||
"export function describeError(err, fallback) { return err instanceof Error && err.message ? err.message : fallback; }",
|
"export function describeError(err, fallback) { return err instanceof Error && err.message ? err.message : fallback; }",
|
||||||
);
|
);
|
||||||
const sessionStub =
|
const sessionStub =
|
||||||
|
|||||||
Reference in new issue
Block a user