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"` } // UseAuthorizer attaches the access policies an answer is judged against. // Until one is attached, no answer is accepted. func (m *Module) UseAuthorizer(a governance.Authorizer) { m.authz = a } // caller returns the signed-in person, checked as a channel account is: their // role must let them answer. The bootstrap token is no person, so it can't // answer. func (m *Module) caller(ctx context.Context, row store.Request) (name, identity string, err error) { p, ok := governance.PrincipalFromContext(ctx) if !ok || p.IdentityID == governance.SystemID || p.Kind != governance.KindUser { return "", "", ErrNotSignedIn } identity = string(p.IdentityID) if err := m.mayAnswer(ctx, p, row); err != nil { return "", identity, err } account, err := m.accounts.Get(ctx, p.IdentityID) if err != nil { return "", identity, fmt.Errorf("read account %s: %w", identity, err) } return account.DisplayName, identity, nil } // authorise accepts an answer from the dashboard only from a person who may // 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"} httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindApproval), huma.Operation{ OperationID: "list-approvals", Method: http.MethodGet, Path: "/api/approvals", Summary: "List approval requests waiting for an answer", Tags: tags, }, m.list) httpapi.Register(api, httpapi.Authorized(governance.ActionApprove, governance.KindApproval), 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) httpapi.Register(api, httpapi.Authorized(governance.ActionApprove, governance.KindApproval), 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 }