Files
archie/internal/infrastructure/postgres/orgs.go
T
sam 03b43fc07b Feat/org epic (#1634)
* fix(postgres): scope OpenPRs to the caller's org

A principal-carrying caller read every org's pr_open tasks. The query now
honours the request scope; the daemon's unscoped review scan still sees all
orgs.

Issue: archie-core-kgxw.23

* fix(statestore): serve task logs only to the task's org

ReadTaskLog and StreamTaskLogContent took a task ID and read the file with
no org check. The State Store's task-log reader now confirms the task is
visible under the caller's scope first; unscoped services read as before.

Issue: archie-core-kgxw.24

* fix(postgres): scope ListPolicies to the caller's org

Every org's policy text reached any principal-carrying caller. A scoped read
now sees its own org's policies, plus instance policies when scoped to the
system org. The engines and the lockout guard decide for every org, so they
read the full chain unscoped: the dashboard engine loads without the
request's principal and the guard lifts the caller's scope.

Issue: archie-core-kgxw.25

* fix(postgres): scope identity reads to the caller's org

ListIdentities and GetIdentity (and its alias fallback) returned every
identity to any caller. A caller scoped to an org now sees only that org's
members and assigned agents; the system org and unscoped services still see
the whole instance.

Issue: archie-core-kgxw.26

* fix(postgres): hide instance status from other orgs

ListPresence, ListChannelStatus, ListApplyStatus and GetConfigSnapshot
answered any org principal with instance-wide state. They now return nothing
unless the request is unscoped or scoped to the system org. The dashboard
reads the published config as itself, since its handlers project it for
callers of every org.

Issue: archie-core-kgxw.27

* feat(postgres): assign new agents an org and role at creation

A bot or service account created through the API served no org until the
next State Store boot granted it one. Create now assigns it to the org the
request acts in with the developer role in the same transaction, so it is
authorized immediately.

Issue: archie-core-kgxw.14

* feat(edastore): create event records in a chosen workspace

Sources are created in a workspace of the caller's org, the default one when
none is named; event types and bindings take their source's workspace and
mappings their event type's, the same rule the org backfill applied. The
binding, mapping and event type contracts carry the workspace, the four list
endpoints accept ?workspace=, and the Events page has a workspace selector
that filters every step and picks where a new source goes.

Issue: archie-core-kgxw.11

* feat(webui): authorize a record in its workspace

The API built every access request with no workspace, so workspace
policies and per-workspace roles never applied. A request naming a source,
binding, mapping, event type or task now reads the record's workspace under
the caller's scope and authorizes in it; tasks carry their workspace on the
State Store contract for this.

Issue: archie-core-kgxw.9

* feat(access): expose workspace environment to policies

Policies can test resource.workspace.environment. The workspace attribute
is the workspace entity, which carries its environment; the principal
brings its org's workspaces from the State Store, so the dashboard and the
daemon's run checks describe a resource's workspace without another lookup,
and the daemon now authorizes runs in the task's or binding's workspace.

Issue: archie-core-kgxw.10

* fix(webui): ask read_secret when a source secret is read

Rotating a source's secret returns its value, but the route asked update,
which every developer holds, so no policy could narrow who reads a secret.
It now asks read_secret on the secret, which the shipped roles give admins
and an object policy can narrow further.

Issue: archie-core-kgxw.17

* refactor(org): delete the unused upgrade-incomplete sentinel

Nothing returns org.ErrUpgradeIncomplete: the State Store finishes the org
upgrade before it serves.

Issue: archie-core-kgxw.18
2026-10-12 03:24:04 +11:00

367 lines
13 KiB
Go

package postgres
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
var (
_ org.Repository = (*Store)(nil)
_ org.Upgrader = (*Store)(nil)
)
// orgFromRow maps the generated org row to the domain org.
func orgFromRow(o postgresdb.Org) org.Org {
return org.Org{ID: org.OrgID(o.ID), Name: o.Name}
}
// CreateOrg inserts a new org, its default workspace and its owner in one
// transaction, so an org never exists without someone who can act in it.
// Re-creating an existing ID is ErrOrgExists.
func (s *Store) CreateOrg(ctx context.Context, value org.Org, owner identity.IdentityID) (org.Org, error) {
if err := value.Validate(); err != nil {
return org.Org{}, err
}
membership := org.Membership{IdentityID: owner, OrgID: value.ID, Role: org.RoleOwner}
if err := membership.Validate(); err != nil {
return org.Org{}, err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return org.Org{}, err
}
defer func() { _ = tx.Rollback(ctx) }()
q := postgresdb.New(tx)
if err := q.InsertOrg(ctx, postgresdb.InsertOrgParams{ID: string(value.ID), Name: value.Name}); err != nil {
if isUniqueViolation(err) {
return org.Org{}, fmt.Errorf("%w: %s", org.ErrOrgExists, value.ID)
}
return org.Org{}, err
}
if err := q.InsertWorkspace(ctx, postgresdb.InsertWorkspaceParams{
ID: string(org.DefaultWorkspaceID), OrgID: string(value.ID), Name: "Default",
}); err != nil {
return org.Org{}, err
}
if err := q.EnsureMembership(ctx, postgresdb.EnsureMembershipParams{
IdentityID: string(owner), OrgID: string(value.ID), Role: string(org.RoleOwner),
}); err != nil {
return org.Org{}, err
}
return value, tx.Commit(ctx)
}
// GetOrg returns one org by ID, or ErrOrgNotFound.
func (s *Store) GetOrg(ctx context.Context, id org.OrgID) (org.Org, error) {
o, err := s.queries().GetOrg(ctx, string(id))
if errors.Is(err, pgx.ErrNoRows) {
return org.Org{}, org.ErrOrgNotFound
}
if err != nil {
return org.Org{}, err
}
return orgFromRow(o), nil
}
// ListOrgs returns every org, oldest first.
func (s *Store) ListOrgs(ctx context.Context) ([]org.Org, error) {
rows, err := s.queries().ListOrgs(ctx)
if err != nil {
return nil, err
}
out := make([]org.Org, 0, len(rows))
for _, r := range rows {
out = append(out, orgFromRow(r))
}
return out, nil
}
// CreateWorkspace inserts a workspace into an existing org; an unknown org is
// ErrOrgNotFound.
func (s *Store) CreateWorkspace(ctx context.Context, value org.Workspace) (org.Workspace, error) {
if err := value.Validate(); err != nil {
return org.Workspace{}, err
}
if _, err := s.GetOrg(ctx, value.OrgID); err != nil {
return org.Workspace{}, err
}
if err := s.queries().InsertWorkspace(ctx, postgresdb.InsertWorkspaceParams{
ID: string(value.ID), OrgID: string(value.OrgID),
Name: value.Name, Environment: value.Environment,
}); err != nil {
if isUniqueViolation(err) {
return org.Workspace{}, fmt.Errorf("%w: %s/%s", org.ErrWorkspaceExists, value.OrgID, value.ID)
}
return org.Workspace{}, err
}
return value, nil
}
// workspaceFromRow maps the generated workspace row to the domain workspace.
func workspaceFromRow(w postgresdb.Workspace) org.Workspace {
return org.Workspace{
ID: org.WorkspaceID(w.ID), OrgID: org.OrgID(w.OrgID),
Name: w.Name, Environment: w.Environment,
}
}
// ListWorkspaces returns an org's workspaces, oldest first.
func (s *Store) ListWorkspaces(ctx context.Context, id org.OrgID) ([]org.Workspace, error) {
rows, err := s.queries().ListWorkspaces(ctx, string(id))
if err != nil {
return nil, err
}
out := make([]org.Workspace, 0, len(rows))
for _, r := range rows {
out = append(out, workspaceFromRow(r))
}
return out, nil
}
// EnsureMembership grants an identity a role in an org, or in one workspace
// of it; an identical existing membership is not an error.
func (s *Store) EnsureMembership(ctx context.Context, value org.Membership) error {
if err := value.Validate(); err != nil {
return err
}
var workspace pgtype.Text
if value.WorkspaceID != "" {
workspace = pgtype.Text{String: string(value.WorkspaceID), Valid: true}
}
if _, err := s.GetOrg(ctx, value.OrgID); err != nil {
return err
}
return s.queries().EnsureMembership(ctx, postgresdb.EnsureMembershipParams{
IdentityID: string(value.IdentityID),
OrgID: string(value.OrgID),
WorkspaceID: workspace,
Role: string(value.Role),
})
}
// AssignAgent records the one org an agent or service identity serves,
// replacing any prior assignment for that identity.
func (s *Store) AssignAgent(ctx context.Context, value org.AgentAssignment) error {
if err := value.Validate(); err != nil {
return err
}
if _, err := s.GetOrg(ctx, value.OrgID); err != nil {
return err
}
return s.queries().UpsertAgentAssignment(ctx, postgresdb.UpsertAgentAssignmentParams{
IdentityID: string(value.IdentityID), OrgID: string(value.OrgID),
})
}
// ListMembers returns an org's memberships with the identity each names.
func (s *Store) ListMembers(ctx context.Context, id org.OrgID) ([]org.Member, error) {
rows, err := s.queries().ListMembers(ctx, string(id))
if err != nil {
return nil, err
}
out := make([]org.Member, 0, len(rows))
for _, r := range rows {
var ws org.WorkspaceID
if r.WorkspaceID.Valid {
ws = org.WorkspaceID(r.WorkspaceID.String)
}
out = append(out, org.Member{
IdentityID: identity.IdentityID(r.IdentityID), Kind: identity.Kind(r.Kind),
DisplayName: r.DisplayName, WorkspaceID: ws, Role: org.Role(r.Role),
})
}
return out, nil
}
// RemoveMembership revokes one membership; a missing one is not an error.
func (s *Store) RemoveMembership(ctx context.Context, value org.Membership) error {
if value.IdentityID == "" || value.OrgID == "" {
return fmt.Errorf("%w: identity and org are required", org.ErrInvalidMembership)
}
return s.queries().RemoveMembership(ctx, postgresdb.RemoveMembershipParams{
IdentityID: string(value.IdentityID), OrgID: string(value.OrgID), WorkspaceID: string(value.WorkspaceID),
})
}
// ListOrgAgents returns the agent and service identities assigned to an org.
func (s *Store) ListOrgAgents(ctx context.Context, id org.OrgID) ([]org.AgentAssignment, error) {
rows, err := s.queries().ListOrgAgents(ctx, string(id))
if err != nil {
return nil, err
}
out := make([]org.AgentAssignment, 0, len(rows))
for _, r := range rows {
out = append(out, org.AgentAssignment{IdentityID: identity.IdentityID(r.IdentityID), OrgID: org.OrgID(r.OrgID)})
}
return out, nil
}
// EnsureAgentOrgMembership grants every agent identity the shipped developer
// role in the org it serves. It runs at the State Store's boot, after the
// default-org upgrade, so dispatch's chain has a principal to evaluate.
// Idempotent: an existing membership (any role) is left alone.
func (s *Store) EnsureAgentOrgMembership(ctx context.Context) error {
return s.queries().EnsureAgentOrgMembership(ctx)
}
// PrincipalFor assembles the access principal for one identity: the org it
// serves and its memberships (internal/domain/access). An identity in no org
// is the default org with no role, which the shipped role policies never
// permit.
func (s *Store) PrincipalFor(ctx context.Context, id identity.IdentityID) (access.Principal, error) {
resolved, err := s.OrgForIdentity(ctx, id)
if err != nil {
return access.Principal{}, err
}
rows, err := s.queries().ListMembershipsByIdentity(ctx, string(id))
if err != nil {
return access.Principal{}, err
}
memberships := make([]org.Membership, 0, len(rows))
for _, r := range rows {
var ws org.WorkspaceID
if r.WorkspaceID.Valid {
ws = org.WorkspaceID(r.WorkspaceID.String)
}
memberships = append(memberships, org.Membership{
IdentityID: id,
OrgID: org.OrgID(r.OrgID),
WorkspaceID: ws,
Role: org.Role(r.Role),
})
}
workspaces, err := s.ListWorkspaces(ctx, resolved)
if err != nil {
return access.Principal{}, err
}
return access.Principal{IdentityID: id, Org: resolved, Memberships: memberships, Workspaces: workspaces}, nil
}
// OrgForIdentity returns the org an identity serves: the assigned org for an
// agent, the org of one of its memberships for a person, and the default org
// for an identity in no org.
func (s *Store) OrgForIdentity(ctx context.Context, id identity.IdentityID) (org.OrgID, error) {
resolved, err := s.queries().ResolveIdentityOrg(ctx, string(id))
if err != nil {
return "", err
}
return org.OrgID(resolved), nil
}
// UpgradeDefaultOrg runs the resumable default org/workspace upgrade: the
// State Store phase first, the event-capture phase second, each in one
// transaction with its ledger row so a phase is either recorded or entirely
// absent, and each skipped on a later start once recorded.
func (s *Store) UpgradeDefaultOrg(ctx context.Context) error {
type phase struct {
name string
stamps []func(context.Context, *postgresdb.Queries) (int64, error)
}
phases := []phase{
{name: "state_store", stamps: []func(context.Context, *postgresdb.Queries) (int64, error){
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampStateStoreTasks(ctx) },
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampStateStoreEvents(ctx) },
func(ctx context.Context, q *postgresdb.Queries) (int64, error) {
return q.StampStateStoreTransitions(ctx)
},
func(ctx context.Context, q *postgresdb.Queries) (int64, error) {
return q.StampStateStoreResources(ctx)
},
func(ctx context.Context, q *postgresdb.Queries) (int64, error) {
return q.StampStateStoreResourceHistory(ctx)
},
}},
{name: "edastore", stamps: []func(context.Context, *postgresdb.Queries) (int64, error){
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreBindings(ctx) },
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreMappings(ctx) },
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreCaptures(ctx) },
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreSources(ctx) },
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 {
continue // recorded: the phase committed on an earlier start
} else if !errors.Is(err, pgx.ErrNoRows) {
return err
}
if err := s.runUpgradePhase(ctx, p.name, p.stamps); err != nil {
return fmt.Errorf("org upgrade phase %s: %w", p.name, err)
}
}
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 {
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
q := postgresdb.New(tx)
if err := q.EnsureDefaultOrg(ctx); err != nil {
return err
}
if err := q.EnsureDefaultWorkspace(ctx); err != nil {
return err
}
if err := q.AssignDefaultOrgIdentities(ctx); err != nil {
return err
}
for _, stamp := range stamps {
if _, err := stamp(ctx, q); err != nil {
return err
}
}
if err := q.InsertOrgUpgradePhase(ctx, name); err != nil {
return err
}
return tx.Commit(ctx)
}
// OrgOwners returns the identities holding the org-wide owner role.
func (s *Store) OrgOwners(ctx context.Context, orgID org.OrgID) ([]identity.IdentityID, error) {
rows, err := s.queries().ListOrgOwners(ctx, string(orgID))
if err != nil {
return nil, fmt.Errorf("store: list org owners: %w", err)
}
out := make([]identity.IdentityID, 0, len(rows))
for _, id := range rows {
out = append(out, identity.IdentityID(id))
}
return out, nil
}