Merge branch 'worktree-agent-a82ec64b6cc1a2809'

# Conflicts:
#	internal/app/archie/operations.go
#	modules/events/events.go
#	modules/governance/accounts_api.go
#	modules/governance/governance.go
This commit is contained in:
sam committed 2026-11-22 02:16:56 +11:00
commit e3130d53e7
44 files changed
+1462 -266

No files matched your search

+3
View File
@@ -107,6 +107,9 @@ const (
KindMemory ResourceKind = "memory"
KindSettings ResourceKind = "settings"
KindInstance ResourceKind = "instance"
KindAccount ResourceKind = "account"
KindChatSession ResourceKind = "chat_session"
KindNote ResourceKind = "note"
)
// Policy is one stored Cedar policy.
+19 -6
View File
@@ -449,17 +449,24 @@ type fakePolicySeed struct {
ids []string
rows []store.PolicyRow
err error
// later holds the policy IDs of every seed after the first.
later []string
}
func (f *fakePolicySeed) SeedOrgPolicies(_ context.Context, _ string, shippedIDs []string, rows []store.PolicyRow) error {
f.calls++
f.ids, f.rows = shippedIDs, rows
if f.calls == 1 {
f.ids, f.rows = shippedIDs, rows
} else {
f.later = append(f.later, shippedIDs...)
}
return f.err
}
// TestSeedShippedPolicies guards that the shipped set is written in one call
// TestSeedShippedPolicies guards that the role policies are written in one call
// rather than one policy at a time, which is what left an org holding only some
// of its role policies. The transaction, the zero-count check under the lock and
// of them, and that each later shipped policy is seeded on its own so an org
// seeded before it existed still receives it. The transaction, the zero-count check under the lock and
// how deletions and edits survive are proven against Postgres in the binary's
// smoke test.
func TestSeedShippedPolicies(t *testing.T) {
@@ -467,9 +474,15 @@ func TestSeedShippedPolicies(t *testing.T) {
if err := seedShippedPolicies(t.Context(), seeder, DefaultOrgID); err != nil {
t.Fatalf("seed: %v", err)
}
shipped := ShippedOrgPolicies(DefaultOrgID)
if seeder.calls != 1 {
t.Fatalf("seed calls = %d, want 1", seeder.calls)
shipped := ShippedRolePolicies(DefaultOrgID)
extras := shippedExtraPolicies(DefaultOrgID)
if seeder.calls != 1+len(extras) {
t.Fatalf("seed calls = %d, want the role policies in one call and %d more", seeder.calls, len(extras))
}
for i, p := range extras {
if seeder.later[i] != p.ID {
t.Fatalf("later seed %d = %s, want %s", i, seeder.later[i], p.ID)
}
}
if len(seeder.rows) != len(shipped) || len(seeder.ids) != len(shipped) {
t.Fatalf("seeded %d rows and %d ids, want %d of each", len(seeder.rows), len(seeder.ids), len(shipped))
+24 -30
View File
@@ -88,40 +88,34 @@ type userReply struct {
// authentication settings and what the dashboard can show.
func (m *Module) RegisterAccounts(api huma.API) {
tags := []string{"Accounts"}
public := func(id, method, path, summary string, status int) huma.Operation {
return httpapi.Public(huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags, DefaultStatus: status})
}
signedIn := func(id, method, path, summary string, status int) huma.Operation {
return httpapi.SignedIn(huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags, DefaultStatus: status})
}
admin := func(id, method, path, summary string, status int) huma.Operation {
op := func(id, method, path, summary string, status int) huma.Operation {
return huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags, DefaultStatus: status}
}
huma.Register(api, public("get-auth-status", http.MethodGet, "/api/auth/status", "Report setup and who is signed in", 0), m.authStatus)
huma.Register(api, public("set-up-account", http.MethodPost, "/api/auth/setup", "Create the instance owner and sign in", 0), m.setUpAccount)
huma.Register(api, public("sign-in", http.MethodPost, "/api/auth/login", "Sign in with email and password", 0), m.signIn)
huma.Register(api, public("sign-out", http.MethodPost, "/api/auth/logout", "Sign out", http.StatusNoContent), m.signOut)
huma.Register(api, public("recover-account", http.MethodPost, "/api/auth/recover", "Reset a password with a recovery code", http.StatusNoContent), m.recoverAccount)
huma.Register(api, public("begin-passkey-sign-in", http.MethodPost, "/api/auth/passkey/begin", "Start signing in with a passkey", 0), m.beginPasskeySignIn)
huma.Register(api, public("finish-passkey-sign-in", http.MethodPost, "/api/auth/passkey/finish", "Finish signing in with a passkey", 0), m.finishPasskeySignIn)
huma.Register(api, public("begin-oidc-sign-in", http.MethodGet, "/oauth2/login", "Send the browser to the identity provider", http.StatusSeeOther), m.beginOIDC)
huma.Register(api, public("finish-oidc-sign-in", http.MethodGet, oidcCallbackPath, "Complete the identity provider's sign-in", http.StatusSeeOther), m.finishOIDC)
httpapi.Register(api, httpapi.Public(), op("get-auth-status", http.MethodGet, "/api/auth/status", "Report setup and who is signed in", 0), m.authStatus)
httpapi.Register(api, httpapi.Public(), op("set-up-account", http.MethodPost, "/api/auth/setup", "Create the instance owner and sign in", 0), m.setUpAccount)
httpapi.Register(api, httpapi.Public(), op("sign-in", http.MethodPost, "/api/auth/login", "Sign in with email and password", 0), m.signIn)
httpapi.Register(api, httpapi.Public(), op("sign-out", http.MethodPost, "/api/auth/logout", "Sign out", http.StatusNoContent), m.signOut)
httpapi.Register(api, httpapi.Public(), op("recover-account", http.MethodPost, "/api/auth/recover", "Reset a password with a recovery code", http.StatusNoContent), m.recoverAccount)
httpapi.Register(api, httpapi.Public(), op("begin-passkey-sign-in", http.MethodPost, "/api/auth/passkey/begin", "Start signing in with a passkey", 0), m.beginPasskeySignIn)
httpapi.Register(api, httpapi.Public(), op("finish-passkey-sign-in", http.MethodPost, "/api/auth/passkey/finish", "Finish signing in with a passkey", 0), m.finishPasskeySignIn)
httpapi.Register(api, httpapi.Public(), op("begin-oidc-sign-in", http.MethodGet, "/oauth2/login", "Send the browser to the identity provider", http.StatusSeeOther), m.beginOIDC)
httpapi.Register(api, httpapi.Public(), op("finish-oidc-sign-in", http.MethodGet, oidcCallbackPath, "Complete the identity provider's sign-in", http.StatusSeeOther), m.finishOIDC)
huma.Register(api, signedIn("change-password", http.MethodPost, "/api/account/password", "Change your password", http.StatusNoContent), m.changePassword)
huma.Register(api, signedIn("create-recovery-code", http.MethodPost, "/api/account/recovery", "Create a recovery code", 0), m.createRecoveryCode)
huma.Register(api, signedIn("list-passkeys", http.MethodGet, "/api/account/passkeys", "List your passkeys", 0), m.listPasskeys)
huma.Register(api, signedIn("begin-passkey-registration", http.MethodPost, "/api/account/passkeys/begin", "Start adding a passkey", 0), m.beginPasskeyRegistration)
huma.Register(api, signedIn("finish-passkey-registration", http.MethodPost, "/api/account/passkeys/finish", "Finish adding a passkey", 0), m.finishPasskeyRegistration)
huma.Register(api, signedIn("delete-passkey", http.MethodDelete, "/api/account/passkeys/{id}", "Remove a passkey", http.StatusNoContent), m.deletePasskey)
huma.Register(api, signedIn("list-personal-tokens", http.MethodGet, "/api/tokens", "List your personal API tokens", 0), m.listTokens)
huma.Register(api, signedIn("create-personal-token", http.MethodPost, "/api/tokens", "Create a personal API token", http.StatusCreated), m.createToken)
huma.Register(api, signedIn("revoke-personal-token", http.MethodDelete, "/api/tokens/{id}", "Revoke a personal API token", http.StatusNoContent), m.revokeToken)
m.registerLinks(api, signedIn)
huma.Register(api, signedIn("get-capabilities", http.MethodGet, "/api/capabilities", "Report which dashboard sections this binary serves", 0), m.capabilities)
httpapi.Register(api, httpapi.Authorized(ActionUpdate, KindAccount), op("change-password", http.MethodPost, "/api/account/password", "Change your password", http.StatusNoContent), m.changePassword)
httpapi.Register(api, httpapi.Authorized(ActionCreate, KindAccount), op("create-recovery-code", http.MethodPost, "/api/account/recovery", "Create a recovery code", 0), m.createRecoveryCode)
httpapi.Register(api, httpapi.Authorized(ActionRead, KindAccount), op("list-passkeys", http.MethodGet, "/api/account/passkeys", "List your passkeys", 0), m.listPasskeys)
httpapi.Register(api, httpapi.Authorized(ActionCreate, KindAccount), op("begin-passkey-registration", http.MethodPost, "/api/account/passkeys/begin", "Start adding a passkey", 0), m.beginPasskeyRegistration)
httpapi.Register(api, httpapi.Authorized(ActionCreate, KindAccount), op("finish-passkey-registration", http.MethodPost, "/api/account/passkeys/finish", "Finish adding a passkey", 0), m.finishPasskeyRegistration)
httpapi.Register(api, httpapi.Authorized(ActionDelete, KindAccount), op("delete-passkey", http.MethodDelete, "/api/account/passkeys/{id}", "Remove a passkey", http.StatusNoContent), m.deletePasskey)
httpapi.Register(api, httpapi.Authorized(ActionRead, KindAccount), op("list-personal-tokens", http.MethodGet, "/api/tokens", "List your personal API tokens", 0), m.listTokens)
httpapi.Register(api, httpapi.Authorized(ActionCreate, KindAccount), op("create-personal-token", http.MethodPost, "/api/tokens", "Create a personal API token", http.StatusCreated), m.createToken)
httpapi.Register(api, httpapi.Authorized(ActionDelete, KindAccount), op("revoke-personal-token", http.MethodDelete, "/api/tokens/{id}", "Revoke a personal API token", http.StatusNoContent), m.revokeToken)
m.registerLinks(api, op)
httpapi.Register(api, httpapi.Authorized(ActionRead, KindAccount), op("get-capabilities", http.MethodGet, "/api/capabilities", "Report which dashboard sections this binary serves", 0), m.capabilities)
huma.Register(api, admin("create-account", http.MethodPost, "/api/accounts", "Create an account", http.StatusCreated), m.createAccount)
huma.Register(api, admin("get-authentication", http.MethodGet, "/api/authentication", "Get the authentication settings", 0), m.getAuthentication)
huma.Register(api, admin("put-authentication", http.MethodPut, "/api/authentication", "Change the authentication settings", http.StatusNoContent), m.putAuthentication)
httpapi.Register(api, httpapi.AdminAuthorized(ActionManageIdentities, KindIdentity), op("create-account", http.MethodPost, "/api/accounts", "Create an account", http.StatusCreated), m.createAccount)
httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), op("get-authentication", http.MethodGet, "/api/authentication", "Get the authentication settings", 0), m.getAuthentication)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), op("put-authentication", http.MethodPut, "/api/authentication", "Change the authentication settings", http.StatusNoContent), m.putAuthentication)
}
// accountError turns an account failure into the status a person can act on.
+99
View File
@@ -0,0 +1,99 @@
package governance
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
)
// ErrDenied is returned when the policy chain refuses an action.
var ErrDenied = errors.New("access: not permitted")
// WorkloadID is the identity background work acts as.
const WorkloadID IdentityID = "workload"
// WorkloadPrincipal returns the principal queued work acts as in org: trigger
// dispatch, run workers and delivery workers. It holds only the workload role,
// which the shipped workload policy grants a narrow set of actions, so
// background work is decided by the same chain as any other caller.
func WorkloadPrincipal(org OrgID) Principal {
return Principal{
IdentityID: WorkloadID,
Kind: KindSystem,
Org: org,
Memberships: []Membership{{IdentityID: WorkloadID, OrgID: org, Role: RoleWorkload}},
}
}
// Require asks a whether p may take action on r. It returns nil when allowed,
// ErrChainUnavailable when a cannot decide, and an error wrapping ErrDenied
// otherwise. A nil a cannot decide, so the action is refused.
func Require(ctx context.Context, a Authorizer, p Principal, action Action, r Resource) error {
if a == nil {
return ErrChainUnavailable
}
d := a.Authorize(ctx, p, action, r, AccessContext{Time: time.Now()})
switch {
case d.Allowed:
return nil
case errors.Is(d.Err, ErrChainUnavailable):
return ErrChainUnavailable
}
return fmt.Errorf("%w: %s %s %s", ErrDenied, action, r.Kind, r.ID)
}
// RequireWorkload is Require for the workload principal of the operating
// organisation, whose policies govern the work every module queues.
func RequireWorkload(ctx context.Context, a Authorizer, action Action, r Resource) error {
r.Org = DefaultOrgID
return Require(ctx, a, WorkloadPrincipal(DefaultOrgID), action, r)
}
type recording struct {
Authorizer
denials DenialRecorder
log *slog.Logger
}
// Recording wraps a so every refusal is stored as a denial, whichever entry
// point asked. A decision that could not be made is not a denial and is not
// stored.
func Recording(a Authorizer, denials DenialRecorder, log *slog.Logger) Authorizer {
return recording{Authorizer: a, denials: denials, log: log}
}
func (r recording) Authorize(ctx context.Context, p Principal, action Action, res Resource, c AccessContext) Decision {
d := r.Authorizer.Authorize(ctx, p, action, res, c)
if d.Allowed || errors.Is(d.Err, ErrChainUnavailable) {
return d
}
err := r.denials.RecordDenial(context.WithoutCancel(ctx), Denial{
Principal: p.IdentityID, Org: p.Org, Action: action, Kind: res.Kind, ResourceID: res.ID,
Level: d.Level, Policies: d.Policies, At: time.Now(), Count: 1,
})
if err != nil {
r.log.ErrorContext(ctx, "record access denial", "principal", p.IdentityID, "action", action, "kind", res.Kind, "error", err)
}
return d
}
// Allow decides a request for the HTTP API's guard: the caller acting in ctx
// against the live policy chain.
func (m *Module) Allow(ctx context.Context, action, kind string) error {
p, ok := PrincipalFromContext(ctx)
if !ok {
return httpapi.ErrDenied
}
err := Require(ctx, m.authz(), p, Action(action), Resource{Kind: ResourceKind(kind), Org: p.Org})
switch {
case err == nil:
return nil
case errors.Is(err, ErrDenied):
return httpapi.ErrDenied
}
return httpapi.ErrUnavailable
}
+111
View File
@@ -0,0 +1,111 @@
package governance
import (
"context"
"errors"
"log/slog"
"testing"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
)
// TestShippedPoliciesLetTheWorkloadWork guards that a fresh install runs its
// workflows: the workload principal may run workflows, deliver messages and
// read, and may do nothing that changes configuration or reads secrets. Members
// reach their own account, conversations and notes whatever their role.
func TestShippedPoliciesLetTheWorkloadWork(t *testing.T) {
engine := NewEngine(ShippedOrgPolicies(DefaultOrgID))
member := func(role Role) Principal {
return Principal{IdentityID: "alice", Org: DefaultOrgID, Memberships: []Membership{{IdentityID: "alice", OrgID: DefaultOrgID, Role: role}}}
}
tests := []struct {
name string
who Principal
action Action
kind ResourceKind
want bool
}{
{"workload runs a workflow", WorkloadPrincipal(DefaultOrgID), ActionRun, KindWorkflow, true},
{"workload delivers", WorkloadPrincipal(DefaultOrgID), ActionDeliver, KindDelivery, true},
{"workload reads", WorkloadPrincipal(DefaultOrgID), ActionRead, KindRun, true},
{"workload does not change a workflow", WorkloadPrincipal(DefaultOrgID), ActionUpdate, KindWorkflow, false},
{"workload does not read secrets", WorkloadPrincipal(DefaultOrgID), ActionReadSecret, KindSecret, false},
{"workload does not manage policies", WorkloadPrincipal(DefaultOrgID), ActionManagePolicies, KindPolicy, false},
{"a viewer changes their account", member(RoleViewer), ActionUpdate, KindAccount, true},
{"a viewer sends a chat turn", member(RoleViewer), ActionCreate, KindChatSession, true},
{"a viewer keeps a note", member(RoleViewer), ActionCreate, KindNote, true},
{"a viewer does not update a workflow", member(RoleViewer), ActionUpdate, KindWorkflow, false},
{"a viewer does not publish a shared note", member(RoleViewer), ActionCreate, KindMemory, false},
{"a developer runs a workflow", member(RoleDeveloper), ActionRun, KindWorkflow, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := Require(t.Context(), engine, tt.who, tt.action, Resource{Kind: tt.kind, Org: tt.who.Org})
if (err == nil) != tt.want {
t.Fatalf("Require = %v, want allowed %v", err, tt.want)
}
if err != nil && !errors.Is(err, ErrDenied) {
t.Fatalf("a refusal is %v, want %v", err, ErrDenied)
}
})
}
}
type denialLog struct{ recorded []Denial }
func (d *denialLog) RecordDenial(_ context.Context, denial Denial) error {
d.recorded = append(d.recorded, denial)
return nil
}
// TestEnforcementFailsClosedAndRecordsRefusals guards the single seam every
// entry point shares: a chain that is not loaded refuses with
// ErrChainUnavailable, as does one with no authorizer at all, a refusal is
// recorded as a denial, and an undecidable request is not.
func TestEnforcementFailsClosedAndRecordsRefusals(t *testing.T) {
failing := func(context.Context) (int64, error) { return 0, errors.New("database down") }
nothing := func(context.Context) ([]Policy, error) { return nil, nil }
pending := NewPending(failing, nothing, slog.New(slog.DiscardHandler))
loaded := NewEngine(ShippedOrgPolicies(DefaultOrgID))
admin := SharedTokenOwner()
viewer := Principal{IdentityID: "bob", Org: DefaultOrgID, Memberships: []Membership{{IdentityID: "bob", OrgID: DefaultOrgID, Role: RoleViewer}}}
resource := Resource{Kind: KindWorkflow, ID: "triage", Org: DefaultOrgID}
tests := []struct {
name string
authorizer Authorizer
who Principal
wantErr error
wantDenials int
wantHTTPDeny error
}{
{name: "a chain that is not loaded", authorizer: pending, who: admin, wantErr: ErrChainUnavailable, wantHTTPDeny: httpapi.ErrUnavailable},
{name: "no authorizer", authorizer: nil, who: admin, wantErr: ErrChainUnavailable, wantHTTPDeny: httpapi.ErrUnavailable},
{name: "a refusal", authorizer: loaded, who: viewer, wantErr: ErrDenied, wantDenials: 1, wantHTTPDeny: httpapi.ErrDenied},
{name: "a grant", authorizer: loaded, who: admin},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
denials := &denialLog{}
var a Authorizer
if tt.authorizer != nil {
a = Recording(tt.authorizer, denials, slog.New(slog.DiscardHandler))
}
if err := Require(t.Context(), a, tt.who, ActionRun, resource); !errors.Is(err, tt.wantErr) {
t.Fatalf("Require = %v, want %v", err, tt.wantErr)
}
if len(denials.recorded) != tt.wantDenials {
t.Fatalf("denials recorded = %d, want %d", len(denials.recorded), tt.wantDenials)
}
m := &Module{}
if a != nil {
m.UseAuthorizer(a)
}
ctx := WithPrincipal(t.Context(), tt.who)
if err := m.Allow(ctx, string(ActionRun), string(KindWorkflow)); !errors.Is(err, tt.wantHTTPDeny) {
t.Fatalf("Allow = %v, want %v", err, tt.wantHTTPDeny)
}
})
}
}
+18 -9
View File
@@ -15,6 +15,7 @@ import (
"net/url"
"regexp"
"strings"
"sync/atomic"
"time"
"github.com/danielgtaylor/huma/v2"
@@ -255,7 +256,7 @@ type Module struct {
store *store.Store
log *slog.Logger
credentials Credentials
authorizer Authorizer
authorizer atomic.Pointer[Authorizer]
oidc *oidcLogin
setup *SetupSignal
channels ChannelLinks
@@ -273,7 +274,15 @@ func (m *Module) UseCredentials(c Credentials) { m.credentials = c }
// UseAuthorizer gives the module the live policy chain that administrative
// writes are checked against.
func (m *Module) UseAuthorizer(a Authorizer) { m.authorizer = a }
func (m *Module) UseAuthorizer(a Authorizer) { m.authorizer.Store(&a) }
// authz returns the policy chain, or nil before UseAuthorizer.
func (m *Module) authz() Authorizer {
if a := m.authorizer.Load(); a != nil {
return *a
}
return nil
}
// AgentModel returns the organisation's agent model.
func (m *Module) AgentModel(ctx context.Context) (Model, error) {
@@ -388,31 +397,31 @@ func (m *Module) ApprovalDeadline(ctx context.Context) (time.Duration, error) {
// Register adds the settings API: organisation settings and the agent model.
func (m *Module) Register(api huma.API) {
tags := []string{"Governance"}
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{
OperationID: "get-settings", Method: http.MethodGet, Path: "/api/settings",
Summary: "Get the organisation settings", Tags: tags,
}, m.getSettings)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "put-settings", Method: http.MethodPut, Path: "/api/settings",
Summary: "Change the organisation settings", Tags: tags,
}, m.putSettings)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{
OperationID: "list-agent-models", Method: http.MethodGet, Path: "/api/settings/agent-models",
Summary: "List agent models by alias", Tags: tags,
}, m.listAgentModels)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{
OperationID: "get-agent-model", Method: http.MethodGet, Path: "/api/settings/agent-model",
Summary: "Get the agent model", Tags: tags,
}, m.getAgentModel)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "put-agent-model", Method: http.MethodPut, Path: "/api/settings/agent-model",
Summary: "Set the agent model", Tags: tags,
}, m.putAgentModel)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "delete-agent-model", Method: http.MethodDelete, Path: "/api/settings/agent-model",
Summary: "Delete an agent model", Tags: tags, DefaultStatus: http.StatusNoContent,
}, m.deleteAgentModel)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "test-agent-model", Method: http.MethodPost, Path: "/api/settings/agent-model/test",
Summary: "Ask a model one question before saving it", Tags: tags,
}, m.testAgentModel)
+4 -4
View File
@@ -245,10 +245,10 @@ func (m *Module) linkError(ctx context.Context, err error) error {
return m.accountError(ctx, err)
}
func (m *Module) registerLinks(api huma.API, signedIn func(id, method, path, summary string, status int) huma.Operation) {
huma.Register(api, signedIn("list-channel-links", http.MethodGet, "/api/account/channels", "List the channels you can link and your linked accounts", 0), m.listChannels)
huma.Register(api, signedIn("begin-channel-link", http.MethodPost, "/api/account/channels/{connector}/link", "Start linking a channel account", 0), m.beginChannelLink)
huma.Register(api, signedIn("unlink-channel", http.MethodDelete, "/api/account/channels/{connector}/{subject}", "Unlink a channel account", http.StatusNoContent), m.unlinkChannel)
func (m *Module) registerLinks(api huma.API, op func(id, method, path, summary string, status int) huma.Operation) {
httpapi.Register(api, httpapi.Authorized(ActionRead, KindAccount), op("list-channel-links", http.MethodGet, "/api/account/channels", "List the channels you can link and your linked accounts", 0), m.listChannels)
httpapi.Register(api, httpapi.Authorized(ActionUpdate, KindAccount), op("begin-channel-link", http.MethodPost, "/api/account/channels/{connector}/link", "Start linking a channel account", 0), m.beginChannelLink)
httpapi.Register(api, httpapi.Authorized(ActionUpdate, KindAccount), op("unlink-channel", http.MethodDelete, "/api/account/channels/{connector}/{subject}", "Unlink a channel account", http.StatusNoContent), m.unlinkChannel)
}
// AccountOf returns the id of the account that holds identity, written as
+3
View File
@@ -72,6 +72,9 @@ const (
RoleAdmin Role = "admin"
RoleDeveloper Role = "developer"
RoleViewer Role = "viewer"
// RoleWorkload is the role of the principal background work acts as. No
// member holds it.
RoleWorkload Role = "workload"
)
// Validate reports whether r is a valid role identifier.
+12 -12
View File
@@ -88,19 +88,19 @@ type listEventsInput struct {
// organisation the caller's request acts in.
func (m *Module) RegisterOrganisations(api huma.API) {
tags := []string{"Organisations"}
signedIn := func(id, method, path, summary string, status int) huma.Operation {
return httpapi.SignedIn(huma.Operation{
op := func(id, method, path, summary string, status int) huma.Operation {
return huma.Operation{
OperationID: id, Method: method, Path: path, Summary: summary,
Tags: tags, DefaultStatus: status, MaxBodyBytes: 16 << 10,
})
}
}
huma.Register(api, signedIn("list-orgs", http.MethodGet, "/api/orgs", "List the organisation the caller acts in", 0), m.listOrgs)
huma.Register(api, signedIn("get-org", http.MethodGet, "/api/orgs/{id}", "Get an organisation", 0), m.getOrg)
huma.Register(api, signedIn("rename-org", http.MethodPatch, "/api/orgs/{id}", "Rename an organisation", 0), m.renameOrg)
huma.Register(api, signedIn("list-org-workspaces", http.MethodGet, "/api/orgs/{id}/workspaces", "List an organisation's workspaces", 0), m.listOrgWorkspaces)
huma.Register(api, signedIn("create-org-workspace", http.MethodPost, "/api/orgs/{id}/workspaces", "Create a workspace", http.StatusCreated), m.createOrgWorkspace)
huma.Register(api, signedIn("rename-org-workspace", http.MethodPatch, "/api/orgs/{id}/workspaces/{workspace}", "Rename a workspace", 0), m.renameOrgWorkspace)
huma.Register(api, signedIn("list-org-events", http.MethodGet, "/api/orgs/{id}/history", "List the organisation's name changes", 0), m.listOrgEvents)
httpapi.Register(api, httpapi.Authorized(ActionRead, KindOrg), op("list-orgs", http.MethodGet, "/api/orgs", "List the organisation the caller acts in", 0), m.listOrgs)
httpapi.Register(api, httpapi.Authorized(ActionRead, KindOrg), op("get-org", http.MethodGet, "/api/orgs/{id}", "Get an organisation", 0), m.getOrg)
httpapi.Register(api, httpapi.Authorized(ActionUpdate, KindOrg), op("rename-org", http.MethodPatch, "/api/orgs/{id}", "Rename an organisation", 0), m.renameOrg)
httpapi.Register(api, httpapi.Authorized(ActionRead, KindWorkspace), op("list-org-workspaces", http.MethodGet, "/api/orgs/{id}/workspaces", "List an organisation's workspaces", 0), m.listOrgWorkspaces)
httpapi.Register(api, httpapi.Authorized(ActionCreate, KindWorkspace), op("create-org-workspace", http.MethodPost, "/api/orgs/{id}/workspaces", "Create a workspace", http.StatusCreated), m.createOrgWorkspace)
httpapi.Register(api, httpapi.Authorized(ActionUpdate, KindWorkspace), op("rename-org-workspace", http.MethodPatch, "/api/orgs/{id}/workspaces/{workspace}", "Rename a workspace", 0), m.renameOrgWorkspace)
httpapi.Register(api, httpapi.Authorized(ActionRead, KindOrg), op("list-org-events", http.MethodGet, "/api/orgs/{id}/history", "List the organisation's name changes", 0), m.listOrgEvents)
}
// caller returns the principal a request acts as. Every organisation route is
@@ -146,12 +146,12 @@ func (m *Module) ownerOf(ctx context.Context, kind ResourceKind, resourceID stri
// policyAllows evaluates the live chain for one write, so a forbid an operator
// wrote refuses it even when the caller's role would otherwise permit it.
func (m *Module) policyAllows(ctx context.Context, p Principal, action Action, kind ResourceKind, resourceID string, org OrgID, workspace WorkspaceID) error {
if m.authorizer == nil {
if m.authz() == nil {
return huma.Error503ServiceUnavailable("Access policies are unavailable.")
}
scoped := p
scoped.Org = org
decision := m.authorizer.Authorize(ctx, scoped, action, Resource{
decision := m.authz().Authorize(ctx, scoped, action, Resource{
Kind: kind, ID: resourceID, Org: org, Workspace: workspace,
}, AccessContext{Time: time.Now()})
switch {
+3 -2
View File
@@ -99,7 +99,8 @@ func (s Settings) path(eligible map[string]string, owner string) []PathStep {
// Holds reports whether the account is allowed every one of actions on r by
// the live access policies. It is false while no policy chain is attached.
func (m *Module) Holds(ctx context.Context, account IdentityID, r Resource, actions ...Action) (bool, error) {
if m.authorizer == nil {
authz := m.authz()
if authz == nil {
return false, nil
}
p, err := m.PrincipalFor(ctx, account)
@@ -107,7 +108,7 @@ func (m *Module) Holds(ctx context.Context, account IdentityID, r Resource, acti
return false, err
}
for _, a := range actions {
d := m.authorizer.Authorize(ctx, p, a, r, AccessContext{})
d := authz.Authorize(ctx, p, a, r, AccessContext{})
if d.Err != nil {
return false, d.Err
}
+54 -7
View File
@@ -1,19 +1,27 @@
package governance
import "slices"
const (
roleOwner = string(RoleOwner)
roleAdmin = string(RoleAdmin)
roleDeveloper = string(RoleDeveloper)
roleViewer = string(RoleViewer)
roleWorkload = string(RoleWorkload)
)
// Shipped policy IDs overwritten by seeding and org policy resets.
const (
PolicyOrgRead = "org-role-read"
PolicyOrgEdit = "org-role-edit"
PolicyOrgAdmin = "org-role-admin"
PolicyOrgOwner = "org-role-owner"
PolicyCrossOrgID = "instance-cross-org"
PolicyOrgRead = "org-role-read"
PolicyOrgEdit = "org-role-edit"
PolicyOrgAdmin = "org-role-admin"
PolicyOrgOwner = "org-role-owner"
// PolicyOrgWorkload grants the principal background work acts as.
PolicyOrgWorkload = "org-workload"
// PolicyOrgSelfService lets every member manage their own account,
// conversations and notes.
PolicyOrgSelfService = "org-self-service"
PolicyCrossOrgID = "instance-cross-org"
)
const orgReadPolicy = `permit(principal, action, resource) when {
@@ -40,8 +48,25 @@ const orgOwnerPolicy = `permit(principal, action, resource) when {
principal.role == "` + roleOwner + `"
};`
// ShippedOrgPolicies returns the four shipped role policies for one org.
func ShippedOrgPolicies(orgID OrgID) []Policy {
// orgWorkloadPolicy lets trigger dispatch, run workers and delivery workers do
// the work they were queued to do and nothing else.
const orgWorkloadPolicy = `permit(principal, action, resource) when {
resource.org == principal.org &&
principal.role == "` + roleWorkload + `" &&
action in [Archie::Action::"read", Archie::Action::"run", Archie::Action::"deliver"]
};`
// orgSelfServicePolicy lets any member use the account, conversation and note
// routes, whose handlers scope every row to the caller.
const orgSelfServicePolicy = `permit(principal, action, resource) when {
resource.org == principal.org &&
["` + roleViewer + `", "` + roleDeveloper + `", "` + roleAdmin + `", "` + roleOwner + `"].contains(principal.role) &&
["` + string(KindAccount) + `", "` + string(KindChatSession) + `", "` + string(KindNote) + `"].contains(resource.kind) &&
action in [Archie::Action::"read", Archie::Action::"create", Archie::Action::"update", Archie::Action::"delete"]
};`
// ShippedRolePolicies returns the four shipped role policies for one org.
func ShippedRolePolicies(orgID OrgID) []Policy {
return []Policy{
{ID: PolicyOrgRead, Level: LevelOrg, OrgID: orgID, Text: orgReadPolicy},
{ID: PolicyOrgEdit, Level: LevelOrg, OrgID: orgID, Text: orgEditPolicy},
@@ -50,6 +75,28 @@ func ShippedOrgPolicies(orgID OrgID) []Policy {
}
}
// ShippedWorkloadPolicy returns the shipped policy for the workload principal.
func ShippedWorkloadPolicy(orgID OrgID) Policy {
return Policy{ID: PolicyOrgWorkload, Level: LevelOrg, OrgID: orgID, Text: orgWorkloadPolicy}
}
// ShippedSelfServicePolicy returns the shipped policy for self-service routes.
func ShippedSelfServicePolicy(orgID OrgID) Policy {
return Policy{ID: PolicyOrgSelfService, Level: LevelOrg, OrgID: orgID, Text: orgSelfServicePolicy}
}
// shippedExtraPolicies are the shipped policies added after the role
// policies. Each is seeded on its own, so an org seeded before it existed
// still receives it.
func shippedExtraPolicies(orgID OrgID) []Policy {
return []Policy{ShippedWorkloadPolicy(orgID), ShippedSelfServicePolicy(orgID)}
}
// ShippedOrgPolicies returns every policy shipped for one org.
func ShippedOrgPolicies(orgID OrgID) []Policy {
return slices.Clip(append(ShippedRolePolicies(orgID), shippedExtraPolicies(orgID)...))
}
// CrossOrgForbidID is the ID reported in denial records for cross-org refusals.
const CrossOrgForbidID = PolicyCrossOrgID
+17 -4
View File
@@ -128,13 +128,26 @@ type policySeedStore interface {
// 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.
//
// The later shipped policies are seeded one by one, so an org that was seeded
// before they existed still receives them.
func seedShippedPolicies(ctx context.Context, s policySeedStore, orgID OrgID) error {
shipped := ShippedOrgPolicies(orgID)
rows := make([]store.PolicyRow, 0, len(shipped))
for _, p := range shipped {
roles := ShippedRolePolicies(orgID)
rows := make([]store.PolicyRow, 0, len(roles))
ids := make([]string, 0, len(roles))
for _, p := range roles {
rows = append(rows, policyToRow(p))
ids = append(ids, p.ID)
}
return s.SeedOrgPolicies(ctx, string(orgID), shippedOrgPolicyIDs(), rows)
if err := s.SeedOrgPolicies(ctx, string(orgID), ids, rows); err != nil {
return err
}
for _, p := range shippedExtraPolicies(orgID) {
if err := s.SeedOrgPolicies(ctx, string(orgID), []string{p.ID}, []store.PolicyRow{policyToRow(p)}); err != nil {
return err
}
}
return nil
}
// ResetOrgPolicies removes non-shipped org policies and restores the shipped role policies.