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
This commit is contained in:
sam committed 2026-11-23 00:38:54 +11:00
1 parent 8c267b6edd
commit e1ada94d78
13 files changed
+358 -17

No files matched your search

+1 -1
View File
@@ -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:
@@ -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;
+4 -1
View File
@@ -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 {
+9
View File
@@ -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) {
+64
View File
@@ -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)
}
+65
View File
@@ -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)
}
})
}
}
+1
View File
@@ -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")
)
+6 -1
View File
@@ -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):
+57 -4
View File
@@ -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)
}
})
}
}
+14 -2
View File
@@ -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.
+89
View File
@@ -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)
}
}
+26 -6
View File
@@ -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)
+6 -2
View File
@@ -148,6 +148,10 @@ async function save(): Promise<void> {
}
const pending = ref<Policy | null>(null);
function isShipped(p: Policy): boolean {
return p.level === "org" && shipped.value.includes(p.id);
}
async function remove(p: Policy): Promise<void> {
try {
await api.deletePolicy(p);
@@ -181,13 +185,13 @@ onMounted(load);
<span class="font-mono font-medium">{{ p.id }}</span>
<Badge variant="default">{{ p.level }}</Badge>
<span v-if="scope(p)" class="font-mono text-fg-muted">{{ scope(p) }}</span>
<Badge v-if="shipped.includes(p.id)" variant="ok">shipped</Badge>
<Badge v-if="isShipped(p)" variant="ok">shipped</Badge>
</div>
<pre class="mt-1 overflow-x-auto text-caption text-fg-muted">{{ p.text }}</pre>
</div>
<div class="flex shrink-0 gap-2">
<Button size="sm" variant="outline" @click="edit(p)">Edit</Button>
<Button size="sm" variant="outline" @click="pending = p">Delete</Button>
<Button v-if="!isShipped(p)" size="sm" variant="outline" @click="pending = p">Delete</Button>
</div>
</div>
</div>