feat(access): the dashboard operator is a person owning org-sys

This commit is contained in:
sam committed 2026-10-05 20:33:22 +11:00
1 parent c1fd42f575
commit 0920be65e3
12 files changed
+320 -17

No files matched your search

+5
View File
@@ -87,6 +87,11 @@ func StableID(legacyName string) IdentityID {
return IdentityID(fmt.Sprintf("%08x-%04x-5%03x-%04x-%012x", sum[:4], sum[4:6], sum[6:8], uint16(sum[8])<<8|uint16(sum[9])&0x3fff|0x8000, sum[10:16]))
}
// OperatorID is the person identity the dashboard acts as when no provider
// signs anyone in. Deriving it from a name lets the upgrade that creates it
// and the request path that resolves it agree without a lookup.
func OperatorID() IdentityID { return StableID("operator") }
func New(id IdentityID, kind Kind, displayName string) (Identity, error) {
value := Identity{ID: id, Kind: kind, DisplayName: strings.TrimSpace(displayName), Lifecycle: LifecycleActive, Version: 1}
if err := value.Validate(); err != nil {
@@ -0,0 +1,15 @@
-- The dashboard acts as a person who owns org-sys. That person is created by
-- a new resumable upgrade phase, so the ledger's phase vocabulary grows by
-- one.
-- +goose Up
ALTER TABLE org_upgrades DROP CONSTRAINT org_upgrades_phase_check;
ALTER TABLE org_upgrades ADD CONSTRAINT org_upgrades_phase_check
CHECK (phase IN ('state_store', 'edastore', 'operator'));
-- +goose Down
ALTER TABLE org_upgrades DROP CONSTRAINT org_upgrades_phase_check;
ALTER TABLE org_upgrades ADD CONSTRAINT org_upgrades_phase_check
CHECK (phase IN ('state_store', 'edastore'));
@@ -11,7 +11,9 @@ import (
"github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
)
@@ -101,6 +103,63 @@ func TestOrgSysMigrationMovesExistingDefaultRows(t *testing.T) {
assertNoOrg(t, pool, "org-sys")
}
// TestOrgOperatorUpgrade pins the operator phase: a fresh install and an
// existing one each end with exactly one person owner of org-sys, and running
// the upgrade again adds no second.
func TestOrgOperatorUpgrade(t *testing.T) {
ctx := t.Context()
db := pgstore.Open(t)
if err := db.UpgradeDefaultOrg(ctx); err != nil {
t.Fatalf("fresh upgrade: %v", err)
}
assertOneOperator(t, db.Pool)
if err := db.UpgradeDefaultOrg(ctx); err != nil {
t.Fatalf("second upgrade: %v", err)
}
assertOneOperator(t, db.Pool)
// An existing install that ran the first two phases but never the operator
// phase: drop the phase's ledger row and what it wrote, then upgrade again.
if _, err := db.Pool.Exec(ctx, `DELETE FROM org_upgrades WHERE phase = 'operator'`); err != nil {
t.Fatalf("reset operator phase: %v", err)
}
for _, sql := range []string{
`DELETE FROM memberships WHERE identity_id = $1`,
`DELETE FROM identities WHERE id = $1`,
} {
if _, err := db.Pool.Exec(ctx, sql, string(identity.OperatorID())); err != nil {
t.Fatalf("reset operator phase: %v", err)
}
}
if err := db.UpgradeDefaultOrg(ctx); err != nil {
t.Fatalf("upgrade on an existing install: %v", err)
}
assertOneOperator(t, db.Pool)
}
func assertOneOperator(t *testing.T, pool *pgxpool.Pool) {
t.Helper()
var owners int
if err := pool.QueryRow(t.Context(), `
SELECT count(*) FROM memberships m
JOIN identities i ON i.id = m.identity_id
WHERE m.org_id = 'org-sys' AND m.workspace_id IS NULL AND m.role = 'owner' AND i.kind = 'user'
`).Scan(&owners); err != nil {
t.Fatal(err)
}
if owners != 1 {
t.Fatalf("person owners of org-sys = %d, want 1", owners)
}
var kind string
if err := pool.QueryRow(t.Context(), `SELECT kind FROM identities WHERE id = $1`, string(identity.OperatorID())).Scan(&kind); err != nil {
t.Fatalf("operator identity: %v", err)
}
if kind != string(identity.KindUser) {
t.Fatalf("operator kind = %q, want %q", kind, identity.KindUser)
}
}
func seedDefaultOrg(t *testing.T, pool *pgxpool.Pool) {
t.Helper()
ctx := t.Context()
+20
View File
@@ -221,6 +221,11 @@ func (s *Store) UpgradeDefaultOrg(ctx context.Context) error {
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreEventTypes(ctx) },
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreToolCalls(ctx) },
}},
// The operator phase runs last: it needs the org the state_store phase
// creates, and gives the dashboard a person to act as where none exists.
{name: "operator", stamps: []func(context.Context, *postgresdb.Queries) (int64, error){
ensureOrgOperator,
}},
}
for _, p := range phases {
if _, err := s.queries().GetOrgUpgradePhase(ctx, p.name); err == nil {
@@ -235,6 +240,21 @@ func (s *Store) UpgradeDefaultOrg(ctx context.Context) error {
return nil
}
// ensureOrgOperator creates the dashboard's operator person as org-sys's owner
// when no person owns it yet. Both writes re-check that condition, so a
// re-run leaves an existing person owner alone and never adds a second.
func ensureOrgOperator(ctx context.Context, q *postgresdb.Queries) (int64, error) {
params := postgresdb.EnsureOrgOperatorIdentityParams{
ID: string(identity.OperatorID()), OrgID: string(org.DefaultOrgID),
}
if _, err := q.EnsureOrgOperatorIdentity(ctx, params); err != nil {
return 0, err
}
return q.EnsureOrgOperatorMembership(ctx, postgresdb.EnsureOrgOperatorMembershipParams{
IdentityID: params.ID, OrgID: params.OrgID,
})
}
// runUpgradePhase stamps one phase's tables and records its ledger row in one
// transaction. An interrupted phase reruns from the start.
func (s *Store) runUpgradePhase(ctx context.Context, name string, stamps []func(context.Context, *postgresdb.Queries) (int64, error)) error {
@@ -42,6 +42,59 @@ func (q *Queries) EnsureDefaultWorkspace(ctx context.Context) error {
return err
}
const ensureOrgOperatorIdentity = `-- name: EnsureOrgOperatorIdentity :execrows
INSERT INTO identities (id, kind, display_name, lifecycle, version, created_at, updated_at)
SELECT $1, 'user', 'Operator', 'active', 1, now(), now()
WHERE NOT EXISTS (
SELECT 1 FROM memberships m
JOIN identities i ON i.id = m.identity_id
WHERE m.org_id = $2 AND m.workspace_id IS NULL AND m.role = 'owner' AND i.kind = 'user'
)
ON CONFLICT (id) DO NOTHING
`
type EnsureOrgOperatorIdentityParams struct {
ID string
OrgID string
}
// The operator phase: if org-sys has no person member with the owner role,
// create the dashboard's operator person and make it that owner. Both writes
// re-check the condition, so a re-run on an install that already has a person
// owner (or already has the operator) changes nothing.
func (q *Queries) EnsureOrgOperatorIdentity(ctx context.Context, arg EnsureOrgOperatorIdentityParams) (int64, error) {
result, err := q.db.Exec(ctx, ensureOrgOperatorIdentity, arg.ID, arg.OrgID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const ensureOrgOperatorMembership = `-- name: EnsureOrgOperatorMembership :execrows
INSERT INTO memberships (identity_id, org_id, workspace_id, role)
SELECT $1, $2, NULL, 'owner'
WHERE NOT EXISTS (
SELECT 1 FROM memberships m
JOIN identities i ON i.id = m.identity_id
WHERE m.org_id = $2 AND m.workspace_id IS NULL AND m.role = 'owner' AND i.kind = 'user'
)
ON CONFLICT DO NOTHING
`
type EnsureOrgOperatorMembershipParams struct {
IdentityID string
OrgID string
}
func (q *Queries) EnsureOrgOperatorMembership(ctx context.Context, arg EnsureOrgOperatorMembershipParams) (int64, error) {
result, err := q.db.Exec(ctx, ensureOrgOperatorMembership, arg.IdentityID, arg.OrgID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getOrgUpgradePhase = `-- name: GetOrgUpgradePhase :one
SELECT completed_at FROM org_upgrades WHERE phase = $1
@@ -58,4 +58,29 @@ UPDATE sources SET org_id = 'org-sys', workspace_id = 'default' WHERE org_id = '
UPDATE event_types SET org_id = 'org-sys', workspace_id = 'default' WHERE org_id = '';
-- name: StampEdastoreToolCalls :execrows
UPDATE tool_calls SET org_id = 'org-sys', workspace_id = 'default' WHERE org_id = '';
UPDATE tool_calls SET org_id = 'org-sys', workspace_id = 'default' WHERE org_id = '';
-- The operator phase: if org-sys has no person member with the owner role,
-- create the dashboard's operator person and make it that owner. Both writes
-- re-check the condition, so a re-run on an install that already has a person
-- owner (or already has the operator) changes nothing.
-- name: EnsureOrgOperatorIdentity :execrows
INSERT INTO identities (id, kind, display_name, lifecycle, version, created_at, updated_at)
SELECT $1, 'user', 'Operator', 'active', 1, now(), now()
WHERE NOT EXISTS (
SELECT 1 FROM memberships m
JOIN identities i ON i.id = m.identity_id
WHERE m.org_id = $2 AND m.workspace_id IS NULL AND m.role = 'owner' AND i.kind = 'user'
)
ON CONFLICT (id) DO NOTHING;
-- name: EnsureOrgOperatorMembership :execrows
INSERT INTO memberships (identity_id, org_id, workspace_id, role)
SELECT $1, $2, NULL, 'owner'
WHERE NOT EXISTS (
SELECT 1 FROM memberships m
JOIN identities i ON i.id = m.identity_id
WHERE m.org_id = $2 AND m.workspace_id IS NULL AND m.role = 'owner' AND i.kind = 'user'
)
ON CONFLICT DO NOTHING;
+1 -1
View File
@@ -106,7 +106,7 @@ func (s *Server) handleControlPlaneCommand(w http.ResponseWriter, r *http.Reques
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
audit, err := webAudit()
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
+1 -1
View File
@@ -93,7 +93,7 @@ func (s *Server) putExtensionSettings(ctx context.Context, doc controlplanerpc.E
if err != nil {
return err
}
audit, err := webAudit()
audit, err := webAudit(ctx)
if err != nil {
return err
}
+14 -8
View File
@@ -1,6 +1,7 @@
package webui
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
@@ -8,6 +9,7 @@ import (
"net/http"
"strings"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
@@ -44,7 +46,7 @@ func (s *Server) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
http.Error(w, "cannot create identity ID", http.StatusInternalServerError)
return
}
audit, err := webAudit()
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
@@ -67,7 +69,7 @@ func (s *Server) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
audit, err := webAudit()
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
@@ -81,16 +83,20 @@ func (s *Server) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
writeJSON(w, value)
}
// webAudit attributes a dashboard write. The dashboard authenticates with one
// shared token and carries no per-user session, so the actor is the System
// identity: a real identity the repository resolves, never a name the request
// could claim for itself.
func webAudit() (identity.Audit, error) {
// webAudit attributes a dashboard write to the request's own principal: the
// person the dashboard acts as. Only a request with no principal at all falls
// back to the System identity, which is a real identity the repository
// resolves, never a name the request could claim for itself.
func webAudit(ctx context.Context) (identity.Audit, error) {
id, err := newControlPlaneRequestID()
if err != nil {
return identity.Audit{}, err
}
return identity.Audit{ActorID: identity.SystemID, Source: "archie-ui", RequestID: id}, nil
actor := identity.SystemID
if p, ok := access.PrincipalFromContext(ctx); ok && p.IdentityID != "" {
actor = p.IdentityID
}
return identity.Audit{ActorID: actor, Source: "archie-ui", RequestID: id}, nil
}
func randomIdentityID() (identity.IdentityID, error) {
+1 -1
View File
@@ -72,7 +72,7 @@ func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) {
http.Error(w, "encode workflow enablement", http.StatusInternalServerError)
return
}
audit, err := webAudit()
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
+11 -2
View File
@@ -7,6 +7,7 @@ import (
"strings"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
@@ -53,8 +54,10 @@ func (s *Server) authorize(h http.Handler) http.Handler {
}
// requestPrincipal assembles the principal a request acts as. With no acting
// identity (the shared token), it is the token owner; with one, it is the
// identity's org and memberships, read over the wire.
// identity (the shared token), it is the org-sys owner person when the upgrade
// created one; with an acting identity, it is the identity's org and
// memberships, read over the wire. The system owner remains the fallback for an
// install that has not run the operator phase.
func (s *Server) requestPrincipal(ctx context.Context) (access.Principal, error) {
if acting, ok := ActingIdentity(ctx); ok {
if s.Principals == nil {
@@ -62,6 +65,12 @@ func (s *Server) requestPrincipal(ctx context.Context) (access.Principal, error)
}
return s.Principals.PrincipalFor(ctx, acting.ID)
}
if s.Principals != nil {
if operator, err := s.Principals.PrincipalFor(ctx, identity.OperatorID()); err == nil &&
operator.Org == org.DefaultOrgID && operator.Role("") == org.RoleOwner {
return operator, nil
}
}
return access.SharedTokenOwner(), nil
}
+114 -3
View File
@@ -1,16 +1,127 @@
package webui
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// Installing, accepting, enabling or removing an extension runs or stops a
// process on the host, and editing a policy changes who may do anything, so
// every write on these routes is policy administration, not a dashboard read.
// operator is the person owner the upgrade creates and the shared-token
// session acts as.
func operator() access.Principal {
return access.Principal{
IdentityID: identity.OperatorID(),
Org: org.DefaultOrgID,
Memberships: []org.Membership{
{IdentityID: identity.OperatorID(), OrgID: org.DefaultOrgID, Role: org.RoleOwner},
},
}
}
// stubPrincipals answers the operator's own principal and a bare one for
// anyone else.
func stubPrincipals(haveOperator bool) access.PrincipalSource {
return operatorPrincipals{haveOperator: haveOperator}
}
type operatorPrincipals struct{ haveOperator bool }
func (s operatorPrincipals) PrincipalFor(_ context.Context, id identity.IdentityID) (access.Principal, error) {
if s.haveOperator && id == identity.OperatorID() {
return operator(), nil
}
return access.Principal{IdentityID: id, Org: org.DefaultOrgID}, nil
}
type allowAll struct{}
func (allowAll) Authorize(access.Principal, access.Action, access.Resource, access.Context) access.Decision {
return access.Allowed()
}
type recordingTokens struct{ owner identity.IdentityID }
// AddPersonalToken mirrors the State Store's rule: only a signed-in person's
// principal may own a personal token.
func (t *recordingTokens) AddPersonalToken(ctx context.Context, _ identity.Subject) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok || p.IdentityID == identity.SystemID || p.Role("") != org.RoleOwner {
return identity.ErrInvalid
}
t.owner = p.IdentityID
return nil
}
func (*recordingTokens) ListPersonalTokens(context.Context) ([]identity.PersonalToken, error) {
return nil, nil
}
func (*recordingTokens) RevokePersonalToken(context.Context, string) error { return nil }
// TestSharedTokenPrincipal pins who the dashboard acts as when no provider
// signed anyone in: the org-sys owner person when the upgrade made one, the
// system owner otherwise.
func TestSharedTokenPrincipal(t *testing.T) {
tests := []struct {
name string
principals access.PrincipalSource
want identity.IdentityID
}{
{"the operator person owns the shared session", stubPrincipals(true), identity.OperatorID()},
{"with no operator the system owner remains", stubPrincipals(false), identity.SystemID},
{"with no principal source the system owner remains", nil, identity.SystemID},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &Server{Principals: tt.principals}
p, err := s.requestPrincipal(t.Context())
if err != nil {
t.Fatal(err)
}
if p.IdentityID != tt.want {
t.Fatalf("principal = %q, want %q", p.IdentityID, tt.want)
}
})
}
}
// TestSharedTokenOperatorPostsPersonalToken drives the whole dashboard path:
// the shared token resolves to the operator, the token route accepts it where
// the system principal was refused, and a write's audit names the operator.
func TestSharedTokenOperatorPostsPersonalToken(t *testing.T) {
tokens := &recordingTokens{}
s := &Server{
Token: "shared",
Access: allowAll{},
Principals: stubPrincipals(true),
PersonalTokens: tokens,
}
handler := s.requireToken(s.authorize(http.HandlerFunc(s.handlePersonalTokenCreate)))
rec := httptest.NewRecorder()
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/tokens", nil)
req.Header.Set("Authorization", "Bearer shared")
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("POST /api/tokens = %d, body %s", rec.Code, rec.Body.String())
}
if tokens.owner != identity.OperatorID() {
t.Fatalf("token owner = %q, want the operator", tokens.owner)
}
audit, err := webAudit(access.WithPrincipal(t.Context(), operator()))
if err != nil {
t.Fatal(err)
}
if audit.ActorID != identity.OperatorID() {
t.Fatalf("audit actor = %q, want the operator", audit.ActorID)
}
}
func TestAdministrationRoutes(t *testing.T) {
tests := []struct {
method, path string