From e1ada94d78a7c105f509d6dc64a20af056c0ef96 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 23 Nov 2026 00:38:54 +1100 Subject: [PATCH] fix: redact link codes and guard shipped policies - redact single-use link codes from stored account.link events after handling, with a migration to scrub existing rows - refuse deletion of shipped org policies and hide the delete action in the UI - validate agent step models against the workflow model policy at save time, including the default model --- api/openapi.yaml | 2 +- .../00059_events_redact_link_codes.sql | 16 ++++ modules/events/events.go | 5 +- modules/events/internal/store/store.go | 9 ++ modules/events/linkcode.go | 64 +++++++++++++ modules/events/linkcode_test.go | 65 ++++++++++++++ modules/governance/access.go | 1 + modules/governance/access_api.go | 7 +- modules/governance/access_api_test.go | 61 ++++++++++++- modules/governance/store_access.go | 16 +++- modules/runs/model_policy_test.go | 89 +++++++++++++++++++ modules/runs/runs.go | 32 +++++-- ui/src/org/OrgAccessPage.vue | 8 +- 13 files changed, 358 insertions(+), 17 deletions(-) create mode 100644 internal/platform/pg/migrations/00059_events_redact_link_codes.sql create mode 100644 modules/events/linkcode.go create mode 100644 modules/events/linkcode_test.go create mode 100644 modules/runs/model_policy_test.go diff --git a/api/openapi.yaml b/api/openapi.yaml index 6d0eb21f7..f2a4b80c1 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -2342,7 +2342,7 @@ components: - array - "null" shipped: - description: IDs of the policies Archie ships, which a reset restores + description: IDs of the org policies Archie ships. They can be edited but not deleted, and a reset restores them items: type: string type: diff --git a/internal/platform/pg/migrations/00059_events_redact_link_codes.sql b/internal/platform/pg/migrations/00059_events_redact_link_codes.sql new file mode 100644 index 000000000..8abe93404 --- /dev/null +++ b/internal/platform/pg/migrations/00059_events_redact_link_codes.sql @@ -0,0 +1,16 @@ +-- +goose Up +-- Redact single-use link codes already stored in account.link events, in the +-- fields and in the raw body. Issued codes are ASCII, and LATIN1 maps every +-- byte to one character, so the body is edited without changing other bytes. +UPDATE events.events +SET body = CASE + WHEN body IS NOT NULL AND length(fields->>'code') >= 16 + THEN convert_to(replace(convert_from(body, 'LATIN1'), fields->>'code', '[redacted]'), 'LATIN1') + ELSE body + END, + fields = jsonb_set(fields, '{code}', '"[redacted]"') +WHERE type = 'account.link' AND fields ? 'code' AND fields->>'code' <> '[redacted]'; + +-- +goose Down +-- Redacted codes can't be restored. +SELECT 1; diff --git a/modules/events/events.go b/modules/events/events.go index a81d18402..1e5b9913a 100644 --- a/modules/events/events.go +++ b/modules/events/events.go @@ -595,7 +595,10 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) { case answerType: return false, m.answer(ctx, e) case linkType: - return false, m.link(ctx, e) + if err := m.link(ctx, e); err != nil { + return false, err + } + return false, m.redactHandledLink(ctx, tx, e) } linked, err := store.Link(ctx, tx, e) if err != nil || linked { diff --git a/modules/events/internal/store/store.go b/modules/events/internal/store/store.go index 3779ab8d2..e6af97ab8 100644 --- a/modules/events/internal/store/store.go +++ b/modules/events/internal/store/store.go @@ -263,6 +263,15 @@ func Link(ctx context.Context, tx *sqlx.Tx, e Event) (bool, error) { return n == 1, err } +// SetEventPayload replaces the stored fields and body of e inside tx. +func SetEventPayload(ctx context.Context, tx *sqlx.Tx, e Event) error { + if _, err := tx.ExecContext(ctx, ` + UPDATE events.events SET fields = $2, body = $3 WHERE id = $1`, e.ID, e.Fields, e.Body); err != nil { + return fmt.Errorf("redact event payload: %w", err) + } + return nil +} + // Triggers returns the armed triggers that fire for one source and event type, // and for the custom type the event was identified as, if any. func Triggers(ctx context.Context, tx *sqlx.Tx, orgID, source, eventType string, typeID uuid.NullUUID) ([]Trigger, error) { diff --git a/modules/events/linkcode.go b/modules/events/linkcode.go new file mode 100644 index 000000000..5ba056d88 --- /dev/null +++ b/modules/events/linkcode.go @@ -0,0 +1,64 @@ +package events + +import ( + "bytes" + "context" + "encoding/json/jsontext" + json "encoding/json/v2" + "fmt" + + "github.com/jmoiron/sqlx" + + "github.com/samcharles93/archie-core/modules/events/internal/store" +) + +// redactedCode replaces a link code in a stored event, so the record still +// shows that a code was presented. +const redactedCode = "[redacted]" + +// minBodyCodeLen is the shortest code redacted from the stored body. Issued +// codes are longer, and replacing a shorter value could rewrite unrelated +// text in the payload. +const minBodyCodeLen = 16 + +// redactLinkCode returns e with the link code replaced by redactedCode in its +// fields and in its stored body. The sender, name and chat stay, so the event +// still records which channel account asked to link. +func redactLinkCode(e store.Event) (store.Event, error) { + var fields map[string]jsontext.Value + if err := json.Unmarshal(e.Fields, &fields); err != nil { + return e, fmt.Errorf("read link fields: %w", err) + } + var code string + if raw, ok := fields["code"]; ok { + if err := json.Unmarshal(raw, &code); err != nil { + return e, fmt.Errorf("read link code: %w", err) + } + } + if code == "" { + return e, nil + } + fields["code"] = jsontext.Value(`"` + redactedCode + `"`) + redacted, err := json.Marshal(fields) + if err != nil { + return e, fmt.Errorf("write link fields: %w", err) + } + e.Fields = redacted + if len(code) >= minBodyCodeLen { + e.Body = bytes.ReplaceAll(e.Body, []byte(code), []byte(redactedCode)) + } + return e, nil +} + +// redactHandledLink removes the link code from a handled account.link event +// in the transaction that marks the event dispatched. Every code an event +// presents is redacted, whether it linked the account, had expired or was +// refused, so no event keeps a code past its handling. +func (m *Module) redactHandledLink(ctx context.Context, tx *sqlx.Tx, e store.Event) error { + redacted, err := redactLinkCode(e) + if err != nil { + m.log.WarnContext(ctx, "unreadable link request", "event", e.ID, "error", err) + return nil + } + return store.SetEventPayload(ctx, tx, redacted) +} diff --git a/modules/events/linkcode_test.go b/modules/events/linkcode_test.go new file mode 100644 index 000000000..cd21d7a2d --- /dev/null +++ b/modules/events/linkcode_test.go @@ -0,0 +1,65 @@ +package events + +import ( + json "encoding/json/v2" + "strings" + "testing" + + "github.com/samcharles93/archie-core/modules/events/internal/store" +) + +// TestRedactLinkCode guards the credential in an account.link event: once the +// event is handled, whether the code linked the account, expired or was +// refused, neither the parsed fields nor the stored body may hold it, and the +// event must still say which channel account sent it. +func TestRedactLinkCode(t *testing.T) { + const code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" //nolint:gosec // plainly fake link code the redaction must remove + tests := []struct { + name string + fields string + body string + }{ + { + name: "webhook body", + fields: `{"by":"telegram:1001","code":"` + code + `","name":"Jo","chat_id":"55"}`, + body: `{"message":{"from":{"id":1001},"text":"/link ` + code + `"}}`, + }, + { + name: "streamed batch", + fields: `{"by":"telegram:1001","code":"` + code + `","name":"Jo","chat_id":"55"}`, + body: `[{"type":"account.link","fields":{"by":"telegram:1001","code":"` + code + `"}}]`, + }, + { + name: "no stored body", + fields: `{"by":"telegram:1001","code":"` + code + `"}`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + e := store.Event{Type: linkType, Fields: []byte(tt.fields)} + if tt.body != "" { + e.Body = []byte(tt.body) + } + got, err := redactLinkCode(e) + if err != nil { + t.Fatalf("redactLinkCode: %v", err) + } + if strings.Contains(string(got.Fields), code) || strings.Contains(string(got.Body), code) { + t.Fatalf("code still stored: fields %s body %s", got.Fields, got.Body) + } + var f struct { + By string `json:"by"` + Code string `json:"code"` + } + if err := json.Unmarshal(got.Fields, &f); err != nil { + t.Fatalf("fields are not valid JSON: %v", err) + } + if f.By != "telegram:1001" || f.Code != redactedCode { + t.Fatalf("fields = %s, want the sender and a marker in place of the code", got.Fields) + } + if tt.body != "" && !strings.Contains(string(got.Body), redactedCode) { + t.Fatalf("body = %s, want the marker in place of the code", got.Body) + } + }) + } +} diff --git a/modules/governance/access.go b/modules/governance/access.go index 2ba6447df..7cf1e7b99 100644 --- a/modules/governance/access.go +++ b/modules/governance/access.go @@ -186,6 +186,7 @@ var ( ErrPolicyNotFound = errors.New("access: policy not found") ErrPolicyInvalidText = errors.New("access: policy text does not parse") ErrPolicyLockout = errors.New("access: change leaves no owner able to manage policies") + ErrPolicyShipped = errors.New("access: shipped policy cannot be deleted") ErrChainUnavailable = errors.New("access: policy chain not loaded") ErrNotMember = errors.New("not a member of that org") ) diff --git a/modules/governance/access_api.go b/modules/governance/access_api.go index 8ed2c4aba..48d9c9a12 100644 --- a/modules/governance/access_api.go +++ b/modules/governance/access_api.go @@ -39,7 +39,7 @@ func (m *Module) access() *accessAPI { type policiesBody struct { Policies []Policy `json:"policies"` - Shipped []string `json:"shipped" doc:"IDs of the policies Archie ships, which a reset restores"` + Shipped []string `json:"shipped" doc:"IDs of the org policies Archie ships. They can be edited but not deleted, and a reset restores them"` } type policyVersionBody struct { @@ -115,6 +115,9 @@ func (a *accessAPI) deletePolicy(ctx context.Context, in *policyInput) (*struct{ if err != nil { return nil, err } + if IsShippedPolicy(value) { + return nil, a.failed(ctx, "delete the policy", ErrPolicyShipped) + } if err := a.policies.DeletePolicy(ctx, value); err != nil { return nil, a.failed(ctx, "delete the policy", err) } @@ -163,6 +166,8 @@ func (a *accessAPI) failed(ctx context.Context, what string, err error) error { switch { case errors.Is(err, ErrPolicyLockout): return huma.Error409Conflict("That change would leave no owner able to manage policies.") + case errors.Is(err, ErrPolicyShipped): + return huma.Error409Conflict("Shipped policies can't be deleted. Edit the policy instead.") case errors.Is(err, ErrPolicyNotFound): return huma.Error404NotFound("That policy does not exist.") case errors.Is(err, ErrInvalidPolicy), errors.Is(err, ErrInvalidLevel), errors.Is(err, ErrPolicyInvalidText): diff --git a/modules/governance/access_api_test.go b/modules/governance/access_api_test.go index 8bdc3b222..d7da1aa12 100644 --- a/modules/governance/access_api_test.go +++ b/modules/governance/access_api_test.go @@ -12,9 +12,10 @@ import ( // fakePolicies applies the same validation and lockout rule as the module's // store-backed methods, against policies held in memory. type fakePolicies struct { - stored []Policy - puts []Policy - org []Principal + stored []Policy + puts []Policy + deletes []Policy + org []Principal } func (f *fakePolicies) ListPolicies(context.Context) ([]Policy, error) { return f.stored, nil } @@ -30,7 +31,10 @@ func (f *fakePolicies) PutPolicy(ctx context.Context, p Policy) (int64, error) { return 1, nil } -func (f *fakePolicies) DeletePolicy(context.Context, Policy) error { return nil } +func (f *fakePolicies) DeletePolicy(_ context.Context, p Policy) error { + f.deletes = append(f.deletes, p) + return nil +} func policyRoutes(f *fakePolicies) *accessAPI { return &accessAPI{policies: f, log: slog.New(slog.DiscardHandler)} @@ -89,3 +93,52 @@ func TestPolicyEdits(t *testing.T) { }) } } + +// TestShippedPolicyDeletion guards that a shipped org policy is edited and +// never deleted, because an org without an active org policy denies every +// request. A policy an operator created is deleted as usual. +func TestShippedPolicyDeletion(t *testing.T) { + owner := actor("root", RoleOwner) + const harmless = `permit(principal, action == Archie::Action::"read", resource);` + shipped := ShippedRolePolicies(DefaultOrgID)[0] + custom := Policy{ID: "custom", Level: LevelOrg, OrgID: DefaultOrgID, Text: harmless} + sameIDInstance := Policy{ID: shipped.ID, Level: LevelInstance, Text: harmless} + edited := shipped + edited.Text = harmless + + tests := []struct { + name string + delete *Policy + put *Policy + want int + wantDeleted bool + wantPut bool + }{ + {name: "delete a shipped policy", delete: &shipped, want: http.StatusConflict}, + {name: "delete an operator policy", delete: &custom, want: http.StatusOK, wantDeleted: true}, + {name: "delete an instance policy that reuses a shipped ID", delete: &sameIDInstance, want: http.StatusOK, wantDeleted: true}, + {name: "edit a shipped policy", put: &edited, want: http.StatusOK, wantPut: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := &fakePolicies{stored: ShippedOrgPolicies(DefaultOrgID), org: []Principal{owner}} + routes := policyRoutes(f) + ctx := WithPrincipal(t.Context(), owner) + var err error + if tt.delete != nil { + _, err = routes.deletePolicy(ctx, &policyInput{Body: *tt.delete}) + } else { + _, err = routes.putPolicy(ctx, &policyInput{Body: *tt.put}) + } + if got := status(t, err); got != tt.want { + t.Fatalf("status = %d (%v), want %d", got, err, tt.want) + } + if deleted := len(f.deletes) > 0; deleted != tt.wantDeleted { + t.Fatalf("deleted = %v, want %v", deleted, tt.wantDeleted) + } + if put := len(f.puts) > 0; put != tt.wantPut { + t.Fatalf("put = %v, want %v", put, tt.wantPut) + } + }) + } +} diff --git a/modules/governance/store_access.go b/modules/governance/store_access.go index 12a2ae15e..99f7cbd43 100644 --- a/modules/governance/store_access.go +++ b/modules/governance/store_access.go @@ -32,6 +32,13 @@ func shippedOrgPolicyIDs() []string { return ids } +// IsShippedPolicy reports whether p is one of the org policies Archie ships. +// Shipped policies are the base the system runs on, and an org with no active +// org policy denies every request, so they are edited and never deleted. +func IsShippedPolicy(p Policy) bool { + return p.Level == LevelOrg && slices.Contains(shippedOrgPolicyIDs(), p.ID) +} + func policyToRow(p Policy) store.PolicyRow { return store.PolicyRow{ Level: string(p.Level), @@ -94,10 +101,14 @@ func (m *Module) PutPolicy(ctx context.Context, p Policy) (int64, error) { } // DeletePolicy removes one stored policy after verifying no org is locked out. +// A shipped policy is refused with ErrPolicyShipped. func (m *Module) DeletePolicy(ctx context.Context, p Policy) error { if err := p.Validate(); err != nil { return err } + if IsShippedPolicy(p) { + return ErrPolicyShipped + } if err := m.checkLockout(ctx, func(current []Policy) []Policy { return slices.DeleteFunc(current, func(c Policy) bool { return samePolicy(c, p) }) }); err != nil { @@ -126,8 +137,9 @@ type policySeedStore interface { // seedShippedPolicies writes the whole shipped set in one call, so a failure // leaves none of it behind and the next attempt writes all of it. The store -// decides whether the seed already ran; an org that has any shipped policy is -// left alone, so a deletion or an edit an admin made stands across restarts. +// decides whether the seed already ran; a shipped policy that is present is +// never rewritten, so an admin's edits persist across restarts. Shipped +// policies cannot be deleted, so seeding only fills in policies the org lacks. // // The later shipped policies are seeded one by one, so an org that was seeded // before they existed still receives them. diff --git a/modules/runs/model_policy_test.go b/modules/runs/model_policy_test.go new file mode 100644 index 000000000..9bac1c32f --- /dev/null +++ b/modules/runs/model_policy_test.go @@ -0,0 +1,89 @@ +package runs + +import ( + "context" + "fmt" + "log/slog" + "slices" + "strings" + "testing" + + "github.com/samcharles93/archie-core/modules/governance" +) + +// policyModels resolves aliases as the workflow model policy does: an alias +// outside allowed is refused, a nil allowed list lets every alias through, and +// an alias the policy allows resolves. With noDefault set, the organisation has +// not chosen a default agent model yet. +type policyModels struct { + onePersonPath + allowed []string + noDefault bool +} + +func (p policyModels) WorkflowModelForAlias(_ context.Context, alias string) (governance.Model, error) { + name := alias + if name == "" { + name = "default" + } + if p.allowed != nil && !slices.Contains(p.allowed, name) { + return governance.Model{}, fmt.Errorf("model alias %q: %w", name, governance.ErrModelNotAllowed) + } + if alias == "" && p.noDefault { + return governance.Model{}, governance.ErrNoAgentModel + } + if alias != "" && alias != "fast" { + return governance.Model{}, fmt.Errorf("agent model alias %q: %w", alias, governance.ErrNoAgentModel) + } + return governance.Model{Model: name}, nil +} + +// TestSavingChecksAgentModelAgainstPolicy guards the workflow step contract at +// save time: an agent step whose model the workflow model policy refuses, the +// default included, is refused when the workflow is saved, not when its run +// starts. +func TestSavingChecksAgentModelAgainstPolicy(t *testing.T) { + tests := []struct { + name string + model string + allowed []string + // noDefault means no default agent model is configured yet. + noDefault bool + want string + }{ + {name: "default is refused when the policy leaves it out", model: "model: default, ", allowed: []string{"fast"}, want: `steps[0].settings.model: model alias "default"`}, + {name: "no model is checked as the default", model: "", allowed: []string{"fast"}, want: `steps[0].settings.model: model alias "default"`}, + {name: "default is accepted when the policy allows it", model: "model: default, ", allowed: []string{"default"}}, + {name: "a named alias the policy allows is accepted", model: "model: fast, ", allowed: []string{"fast"}}, + {name: "no model saves while no default model is configured", model: "", noDefault: true}, + {name: "default saves while no default model is configured", model: "model: default, ", allowed: []string{"default"}, noDefault: true}, + {name: "default is still refused by the policy while no default model is configured", model: "model: default, ", allowed: []string{"fast"}, noDefault: true, want: `steps[0].settings.model: model alias "default"`}, + {name: "an unknown named alias is refused", model: "model: ghost, ", want: `steps[0].settings.model: unknown agent model alias "ghost"`}, + {name: "a named alias the policy leaves out is refused", model: "model: slow, ", allowed: []string{"fast"}, want: `steps[0].settings.model: model alias "slow"`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + engine := newEngine(nil, &fakeWork{}, slog.New(slog.DiscardHandler), Options{}) + engine.Use(Deps{Settings: policyModels{allowed: tt.allowed, noDefault: tt.noDefault}}) + step := "{type: agent.run, settings: {" + tt.model + "mission: look}}" + _, err := engine.validateDocument(t.Context(), "steps:\n - "+step+"\n") + switch { + case tt.want == "" && err != nil: + t.Fatalf("validateDocument: %v", err) + case tt.want != "" && (err == nil || !strings.Contains(err.Error(), tt.want)): + t.Fatalf("validateDocument error = %v, want %q", err, tt.want) + } + }) + } +} + +// TestStarterWorkflowSavesWithoutModels guards a fresh install: the workflow +// that ships with the binary is saved at start, before an operator has +// configured any model, so saving it must not need one. +func TestStarterWorkflowSavesWithoutModels(t *testing.T) { + engine := newEngine(nil, &fakeWork{}, slog.New(slog.DiscardHandler), Options{}) + engine.Use(Deps{Settings: policyModels{noDefault: true}}) + if _, err := engine.validateDocument(t.Context(), InvestigateDocument()); err != nil { + t.Fatalf("validateDocument: %v", err) + } +} diff --git a/modules/runs/runs.go b/modules/runs/runs.go index 8858e5dc5..54248287f 100644 --- a/modules/runs/runs.go +++ b/modules/runs/runs.go @@ -152,18 +152,25 @@ func (e *Engine) validateDocument(ctx context.Context, body string) (Document, e if err := decodeSettings(step.Settings, &s); err != nil { return Document{}, err } - if modelAlias(s.Model) == "" { - continue - } deps, err := e.steps() if err != nil { return Document{}, err } - if _, err := deps.Settings.WorkflowModelForAlias(ctx, s.Model); err != nil { - if !errors.Is(err, governance.ErrNoAgentModel) { + // Ask what the run start asks, with the alias it would use. A step + // that names no model runs on the default, so it is checked the same + // way as "model: default". + if _, err := deps.Settings.WorkflowModelForAlias(ctx, modelAlias(s.Model)); err != nil { + switch message, ok := modelProblem(err, s.Model); { + case ok: + problems = append(problems, Problem{Path: fmt.Sprintf("steps[%d].settings.model", i), Message: message}) + case errors.Is(err, governance.ErrNoAgentModel): + // The default isn't configured yet. The operator can set it + // later and the run start checks it again, so it doesn't block + // saving. A fresh install saves its starter workflow + // before any model exists. + default: return Document{}, err } - problems = append(problems, Problem{Path: fmt.Sprintf("steps[%d].settings.model", i), Message: fmt.Sprintf("unknown agent model alias %q", s.Model)}) } } if len(problems) > 0 { @@ -172,6 +179,19 @@ func (e *Engine) validateDocument(ctx context.Context, body string) (Document, e return doc, nil } +// modelProblem describes a model the organisation can't provide as a problem +// with the step. It reports false for an unconfigured default and for any +// other error. +func modelProblem(err error, alias string) (string, bool) { + switch { + case errors.Is(err, governance.ErrModelNotAllowed): + return err.Error(), true + case errors.Is(err, governance.ErrNoAgentModel) && modelAlias(alias) != "": + return fmt.Sprintf("unknown agent model alias %q", alias), true + } + return "", false +} + // Has reports whether a workflow is stored under name. func (e *Engine) Has(ctx context.Context, orgID, name string) (bool, error) { _, err := e.db.Workflow(ctx, orgID, name, 0) diff --git a/ui/src/org/OrgAccessPage.vue b/ui/src/org/OrgAccessPage.vue index 66d82300b..b45e47ac4 100644 --- a/ui/src/org/OrgAccessPage.vue +++ b/ui/src/org/OrgAccessPage.vue @@ -148,6 +148,10 @@ async function save(): Promise { } const pending = ref(null); +function isShipped(p: Policy): boolean { + return p.level === "org" && shipped.value.includes(p.id); +} + async function remove(p: Policy): Promise { try { await api.deletePolicy(p); @@ -181,13 +185,13 @@ onMounted(load); {{ p.id }} {{ p.level }} {{ scope(p) }} - shipped + shipped
{{ p.text }}
- +