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
This commit is contained in:
sam authored and GitHub committed 2026-10-12 03:24:04 +11:00
1 parent 8540c9f7c8
commit f34f60f9c7
60 files changed
+1695 -828

No files matched your search

+5 -2
View File
@@ -56,9 +56,12 @@ func textJSON(text string) []byte {
return out
}
// ListPolicies returns every stored policy across levels.
// ListPolicies returns the stored policies the request's scope may see:
// every policy across levels for an unscoped service.
func (s *Store) ListPolicies(ctx context.Context) ([]access.Policy, error) {
rows, err := s.queries().ListAccessPolicies(ctx)
rows, err := s.queries().ListAccessPolicies(ctx, postgresdb.ListAccessPoliciesParams{
ScopeOrg: scopeOrg(ctx), InstanceScope: org.InstanceScope(ctx),
})
if err != nil {
return nil, err
}
+17 -15
View File
@@ -215,6 +215,7 @@ func mappingValue(r postgresdb.Mapping, matches int64, lastMatched time.Time) (m
SourceHint: r.SourceHint,
EventTypeID: r.EventType,
Fields: fields,
WorkspaceID: org.WorkspaceID(r.WorkspaceID),
MatchCount: matches,
LastMatchedAt: lastMatched,
CreatedAt: r.CreatedAt,
@@ -330,21 +331,22 @@ func bindingValue(r postgresdb.GetBindingRow) (binding.Binding, error) {
return binding.Binding{}, fmt.Errorf("edastore: decode binding %s inputs: %w", r.ID, err)
}
return binding.Binding{
ID: r.ID,
Name: r.Name,
Matcher: binding.Matcher{Source: r.Source},
MappingID: r.Mapping,
Filter: r.Filter,
Workflow: r.Workflow,
Owner: r.Owner,
Repo: r.Repo,
RepoParam: r.RepoParam,
Inputs: inputs,
OrgID: org.OrgID(r.OrgID),
Version: int(r.Version),
Status: binding.Status(r.Status),
CreatedAt: r.CreatedAt,
UpdatedAt: r.UpdatedAt,
ID: r.ID,
Name: r.Name,
Matcher: binding.Matcher{Source: r.Source},
MappingID: r.Mapping,
Filter: r.Filter,
Workflow: r.Workflow,
Owner: r.Owner,
Repo: r.Repo,
RepoParam: r.RepoParam,
Inputs: inputs,
OrgID: org.OrgID(r.OrgID),
WorkspaceID: org.WorkspaceID(r.WorkspaceID),
Version: int(r.Version),
Status: binding.Status(r.Status),
CreatedAt: r.CreatedAt,
UpdatedAt: r.UpdatedAt,
}, nil
}
@@ -17,7 +17,10 @@ import (
var _ storecontract.EventTypeStore = (*EDA)(nil)
func eventTypeValue(r postgresdb.EventType) (eventtype.EventType, error) {
t := eventtype.EventType{ID: r.ID, Source: r.Source, Name: r.Name, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
t := eventtype.EventType{
ID: r.ID, Source: r.Source, Name: r.Name, WorkspaceID: org.WorkspaceID(r.WorkspaceID),
CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,
}
if err := json.Unmarshal([]byte(r.Rule), &t.Rule); err != nil {
return eventtype.EventType{}, fmt.Errorf("edastore: decode event type rule: %w", err)
}
+36 -8
View File
@@ -10,6 +10,7 @@ import (
"github.com/jackc/pgx/v5"
"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"
)
@@ -36,9 +37,9 @@ func insertIdentityEvent(ctx context.Context, q *postgresdb.Queries, id identity
})
}
// List returns every identity, oldest first.
// List returns every identity the request's scope may see, oldest first.
func (s *Store) List(ctx context.Context) ([]identity.Identity, error) {
rows, err := s.queries().ListIdentities(ctx)
rows, err := s.queries().ListIdentities(ctx, memberScope(ctx))
if err != nil {
return nil, err
}
@@ -49,9 +50,10 @@ func (s *Store) List(ctx context.Context) ([]identity.Identity, error) {
return out, nil
}
// Get returns one identity by id, or ErrNotFound.
// Get returns one identity by id, or ErrNotFound when there is none the
// request's scope may see.
func (s *Store) Get(ctx context.Context, id identity.IdentityID) (identity.Identity, error) {
i, err := s.queries().GetIdentity(ctx, string(id))
i, err := s.queries().GetVisibleIdentity(ctx, postgresdb.GetVisibleIdentityParams{ID: string(id), ScopeOrg: memberScope(ctx)})
if errors.Is(err, pgx.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
@@ -65,7 +67,7 @@ func (s *Store) Get(ctx context.Context, id identity.IdentityID) (identity.Ident
// Aliases match case-insensitively, mirroring the SQLite schema's COLLATE
// NOCASE.
func (s *Store) ResolveLegacyName(ctx context.Context, name string) (identity.Identity, error) {
i, err := s.queries().ResolveIdentityAlias(ctx, strings.TrimSpace(name))
i, err := s.queries().ResolveIdentityAlias(ctx, postgresdb.ResolveIdentityAliasParams{Alias: strings.TrimSpace(name), ScopeOrg: memberScope(ctx)})
if errors.Is(err, pgx.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
@@ -76,8 +78,17 @@ func (s *Store) ResolveLegacyName(ctx context.Context, name string) (identity.Id
}
// Create inserts a new identity, its display-name alias and its create audit
// event in one transaction.
// event in one transaction. An agent is assigned in the same transaction to
// the org the request acts in, with the shipped developer role, so it is
// authorized as soon as it exists.
func (s *Store) Create(ctx context.Context, value identity.Identity, audit identity.Audit) (identity.Identity, error) {
return s.create(ctx, value, audit, value.Kind.Agent())
}
// create inserts an identity, assigning an agent to the request's org when
// assign is set. Boot seeding does not assign: it runs before a fresh
// install's org exists, and the org upgrade assigns what it seeded.
func (s *Store) create(ctx context.Context, value identity.Identity, audit identity.Audit, assign bool) (identity.Identity, error) {
if err := value.Validate(); err != nil {
return identity.Identity{}, err
}
@@ -110,12 +121,29 @@ func (s *Store) Create(ctx context.Context, value identity.Identity, audit ident
}, audit, now); err != nil {
return identity.Identity{}, err
}
if assign {
if err := assignNewAgent(ctx, q, value.ID, org.OrgFromContext(ctx)); err != nil {
return identity.Identity{}, err
}
}
if err := tx.Commit(ctx); err != nil {
return identity.Identity{}, err
}
return value, nil
}
// assignNewAgent makes a new agent serve orgID with the developer role.
func assignNewAgent(ctx context.Context, q *postgresdb.Queries, id identity.IdentityID, orgID org.OrgID) error {
if err := q.UpsertAgentAssignment(ctx, postgresdb.UpsertAgentAssignmentParams{
IdentityID: string(id), OrgID: string(orgID),
}); err != nil {
return fmt.Errorf("assign agent to org %s: %w", orgID, err)
}
return q.EnsureMembership(ctx, postgresdb.EnsureMembershipParams{
IdentityID: string(id), OrgID: string(orgID), Role: string(org.RoleDeveloper),
})
}
// Apply mutates an identity under an optimistic version guard and records the
// lifecycle event.
func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersion int64, command identity.Command, audit identity.Audit) (identity.Identity, error) {
@@ -326,9 +354,9 @@ func (s *Store) BootstrapIdentities(ctx context.Context, legacyNames []string) e
values = append(values, value)
}
for _, value := range values {
_, err := s.Create(ctx, value, identity.Audit{
_, err := s.create(ctx, value, identity.Audit{
ActorID: identity.SystemID, Source: "legacy-config", RequestID: "identity-import:" + string(value.ID),
})
}, false)
if err != nil && !isUniqueViolation(err) {
return fmt.Errorf("bootstrap identity %q: %w", value.DisplayName, err)
}
+5 -1
View File
@@ -239,7 +239,11 @@ func (s *Store) PrincipalFor(ctx context.Context, id identity.IdentityID) (acces
Role: org.Role(r.Role),
})
}
return access.Principal{IdentityID: id, Org: resolved, Memberships: memberships}, nil
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
@@ -7,6 +7,8 @@ package postgresdb
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countShippedOrgPolicies = `-- name: CountShippedOrgPolicies :one
@@ -159,12 +161,23 @@ func (q *Queries) InsertAccessResetAudit(ctx context.Context, recordKey string)
const listAccessPolicies = `-- name: ListAccessPolicies :many
SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at
FROM access_policies ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id
FROM access_policies
WHERE $1::text IS NULL
OR (level = 'instance' AND $2::bool)
OR (level <> 'instance' AND org_id = $1)
ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id
`
type ListAccessPoliciesParams struct {
ScopeOrg pgtype.Text
InstanceScope bool
}
// Access policies and denial records (internal/domain/access)
func (q *Queries) ListAccessPolicies(ctx context.Context) ([]AccessPolicy, error) {
rows, err := q.db.Query(ctx, listAccessPolicies)
// A scoped read sees its own org's policies, and the instance policies only
// when it may read the instance.
func (q *Queries) ListAccessPolicies(ctx context.Context, arg ListAccessPoliciesParams) ([]AccessPolicy, error) {
rows, err := q.db.Query(ctx, listAccessPolicies, arg.ScopeOrg, arg.InstanceScope)
if err != nil {
return nil, err
}
@@ -13,7 +13,7 @@ import (
)
const armedBindingsForSource = `-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id, workspace_id
FROM bindings WHERE source = $1 AND status = 'armed' AND ($2::text IS NULL OR org_id = $2) ORDER BY created_at DESC
`
@@ -23,21 +23,22 @@ type ArmedBindingsForSourceParams struct {
}
type ArmedBindingsForSourceRow struct {
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
Inputs string
RepoParam string
OrgID string
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
Inputs string
RepoParam string
OrgID string
WorkspaceID string
}
func (q *Queries) ArmedBindingsForSource(ctx context.Context, arg ArmedBindingsForSourceParams) ([]ArmedBindingsForSourceRow, error) {
@@ -65,6 +66,7 @@ func (q *Queries) ArmedBindingsForSource(ctx context.Context, arg ArmedBindingsF
&i.Inputs,
&i.RepoParam,
&i.OrgID,
&i.WorkspaceID,
); err != nil {
return nil, err
}
@@ -303,7 +305,7 @@ func (q *Queries) EventTypesForSource(ctx context.Context, source string) ([]Eve
}
const getBinding = `-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id, workspace_id
FROM bindings WHERE id = $1 AND ($2::text IS NULL OR org_id = $2)
`
@@ -313,21 +315,22 @@ type GetBindingParams struct {
}
type GetBindingRow struct {
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
Inputs string
RepoParam string
OrgID string
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
Inputs string
RepoParam string
OrgID string
WorkspaceID string
}
func (q *Queries) GetBinding(ctx context.Context, arg GetBindingParams) (GetBindingRow, error) {
@@ -349,12 +352,13 @@ func (q *Queries) GetBinding(ctx context.Context, arg GetBindingParams) (GetBind
&i.Inputs,
&i.RepoParam,
&i.OrgID,
&i.WorkspaceID,
)
return i, err
}
const getEventType = `-- name: GetEventType :one
SELECT id, source, name, rule, schema, created_at, updated_at
SELECT id, source, name, rule, schema, created_at, updated_at, org_id, workspace_id
FROM event_types WHERE id = $1 AND ($2::text IS NULL OR org_id = $2)
`
@@ -363,19 +367,9 @@ type GetEventTypeParams struct {
ScopeOrg pgtype.Text
}
type GetEventTypeRow struct {
ID string
Source string
Name string
Rule string
Schema string
CreatedAt time.Time
UpdatedAt time.Time
}
func (q *Queries) GetEventType(ctx context.Context, arg GetEventTypeParams) (GetEventTypeRow, error) {
func (q *Queries) GetEventType(ctx context.Context, arg GetEventTypeParams) (EventType, error) {
row := q.db.QueryRow(ctx, getEventType, arg.ID, arg.ScopeOrg)
var i GetEventTypeRow
var i EventType
err := row.Scan(
&i.ID,
&i.Source,
@@ -384,6 +378,8 @@ func (q *Queries) GetEventType(ctx context.Context, arg GetEventTypeParams) (Get
&i.Schema,
&i.CreatedAt,
&i.UpdatedAt,
&i.OrgID,
&i.WorkspaceID,
)
return i, err
}
@@ -452,8 +448,10 @@ func (q *Queries) GetSource(ctx context.Context, arg GetSourceParams) (Source, e
}
const insertBinding = `-- name: InsertBinding :exec
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status, inputs, repo_param, org_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9, $10, $11, $12)
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status, inputs, repo_param, org_id, workspace_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1,
$9, $10, $11, $12,
COALESCE((SELECT s.workspace_id FROM sources s WHERE s.path = $3 AND s.org_id = $12), 'default'))
`
type InsertBindingParams struct {
@@ -471,6 +469,7 @@ type InsertBindingParams struct {
OrgID string
}
// A binding lives in its source's workspace.
func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) error {
_, err := q.db.Exec(ctx, insertBinding,
arg.ID,
@@ -577,8 +576,9 @@ func (q *Queries) InsertCaptureRefusal(ctx context.Context, arg InsertCaptureRef
}
const insertEventType = `-- name: InsertEventType :exec
INSERT INTO event_types (id, source, name, rule, schema, org_id)
VALUES ($1, $2, $3, $4, $5, $6)
INSERT INTO event_types (id, source, name, rule, schema, org_id, workspace_id)
VALUES ($1, $2, $3, $4, $5, $6,
COALESCE((SELECT s.workspace_id FROM sources s WHERE s.path = $2 AND s.org_id = $6), 'default'))
`
type InsertEventTypeParams struct {
@@ -590,6 +590,7 @@ type InsertEventTypeParams struct {
OrgID string
}
// An event type lives in its source's workspace.
func (q *Queries) InsertEventType(ctx context.Context, arg InsertEventTypeParams) error {
_, err := q.db.Exec(ctx, insertEventType,
arg.ID,
@@ -603,8 +604,9 @@ func (q *Queries) InsertEventType(ctx context.Context, arg InsertEventTypeParams
}
const insertMapping = `-- name: InsertMapping :exec
INSERT INTO mappings (id, name, source_hint, event_type, fields, org_id)
VALUES ($1, $2, $3, $4, $5, $6)
INSERT INTO mappings (id, name, source_hint, event_type, fields, org_id, workspace_id)
VALUES ($1, $2, $3, $4, $5, $6,
COALESCE((SELECT y.workspace_id FROM event_types y WHERE y.id = $4 AND y.org_id = $6), 'default'))
`
type InsertMappingParams struct {
@@ -616,6 +618,8 @@ type InsertMappingParams struct {
OrgID string
}
// A mapping lives in its event type's workspace; one with no event type in
// the org's default workspace.
func (q *Queries) InsertMapping(ctx context.Context, arg InsertMappingParams) error {
_, err := q.db.Exec(ctx, insertMapping,
arg.ID,
@@ -665,8 +669,10 @@ func (q *Queries) InsertPlaybookDispatch(ctx context.Context, arg InsertPlaybook
return err
}
const insertSource = `-- name: InsertSource :exec
INSERT INTO sources (path, signing, secret, org_id, workspace_id) VALUES ($1, $2, $3, $4, $5)
const insertSource = `-- name: InsertSource :execrows
INSERT INTO sources (path, signing, secret, org_id, workspace_id)
SELECT $1, $2, $3, w.org_id, w.id
FROM workspaces w WHERE w.org_id = $4 AND w.id = $5
`
type InsertSourceParams struct {
@@ -677,15 +683,19 @@ type InsertSourceParams struct {
WorkspaceID string
}
func (q *Queries) InsertSource(ctx context.Context, arg InsertSourceParams) error {
_, err := q.db.Exec(ctx, insertSource,
// Inserts nothing when the workspace is not one of the org's.
func (q *Queries) InsertSource(ctx context.Context, arg InsertSourceParams) (int64, error) {
result, err := q.db.Exec(ctx, insertSource,
arg.Path,
arg.Signing,
arg.Secret,
arg.OrgID,
arg.WorkspaceID,
)
return err
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const insertToolCall = `-- name: InsertToolCall :exec
@@ -779,26 +789,27 @@ func (q *Queries) ListBindingDispatches(ctx context.Context, arg ListBindingDisp
}
const listBindings = `-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id, workspace_id
FROM bindings WHERE ($1::text IS NULL OR org_id = $1) ORDER BY created_at DESC
`
type ListBindingsRow struct {
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
Inputs string
RepoParam string
OrgID string
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
Inputs string
RepoParam string
OrgID string
WorkspaceID string
}
func (q *Queries) ListBindings(ctx context.Context, scopeOrg pgtype.Text) ([]ListBindingsRow, error) {
@@ -826,6 +837,7 @@ func (q *Queries) ListBindings(ctx context.Context, scopeOrg pgtype.Text) ([]Lis
&i.Inputs,
&i.RepoParam,
&i.OrgID,
&i.WorkspaceID,
); err != nil {
return nil, err
}
@@ -1266,8 +1278,9 @@ const updateBinding = `-- name: UpdateBinding :execrows
UPDATE bindings
SET name = $1, source = $2, mapping = $3, filter = $4,
workflow = $5, owner = $6, repo = $7,
version = version + 1, status = $8, inputs = $9, repo_param = $10, updated_at = now()
WHERE id = $11 AND ($12::text IS NULL OR org_id = $12)
version = version + 1, status = $8, inputs = $9, repo_param = $10, updated_at = now(),
workspace_id = COALESCE((SELECT s.workspace_id FROM sources s WHERE s.path = $2 AND s.org_id = bindings.org_id), 'default')
WHERE bindings.id = $11 AND ($12::text IS NULL OR bindings.org_id = $12)
`
type UpdateBindingParams struct {
@@ -1333,8 +1346,9 @@ func (q *Queries) UpdateEventType(ctx context.Context, arg UpdateEventTypeParams
const updateMapping = `-- name: UpdateMapping :execrows
UPDATE mappings
SET name = $1, source_hint = $2, event_type = $3, fields = $4, updated_at = now()
WHERE id = $5 AND ($6::text IS NULL OR org_id = $6)
SET name = $1, source_hint = $2, event_type = $3, fields = $4, updated_at = now(),
workspace_id = COALESCE((SELECT y.workspace_id FROM event_types y WHERE y.id = $3 AND y.org_id = mappings.org_id), 'default')
WHERE mappings.id = $5 AND ($6::text IS NULL OR mappings.org_id = $6)
`
type UpdateMappingParams struct {
@@ -8,6 +8,8 @@ package postgresdb
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgtype"
)
const claimIdentitySubject = `-- name: ClaimIdentitySubject :one
@@ -75,6 +77,33 @@ func (q *Queries) GetIdentity(ctx context.Context, id string) (Identity, error)
return i, err
}
const getVisibleIdentity = `-- name: GetVisibleIdentity :one
SELECT id, kind, display_name, lifecycle, version, created_at, updated_at
FROM identities WHERE id = $1 AND ($2::text IS NULL
OR EXISTS (SELECT 1 FROM memberships m WHERE m.identity_id = identities.id AND m.org_id = $2)
OR EXISTS (SELECT 1 FROM org_agents a WHERE a.identity_id = identities.id AND a.org_id = $2))
`
type GetVisibleIdentityParams struct {
ID string
ScopeOrg pgtype.Text
}
func (q *Queries) GetVisibleIdentity(ctx context.Context, arg GetVisibleIdentityParams) (Identity, error) {
row := q.db.QueryRow(ctx, getVisibleIdentity, arg.ID, arg.ScopeOrg)
var i Identity
err := row.Scan(
&i.ID,
&i.Kind,
&i.DisplayName,
&i.Lifecycle,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertIdentity = `-- name: InsertIdentity :exec
INSERT INTO identities (id, kind, display_name, lifecycle, version, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
@@ -166,15 +195,21 @@ func (q *Queries) InsertIdentityEvent(ctx context.Context, arg InsertIdentityEve
const listIdentities = `-- name: ListIdentities :many
SELECT id, kind, display_name, lifecycle, version, created_at, updated_at
FROM identities ORDER BY created_at, id
FROM identities
WHERE ($1::text IS NULL
OR EXISTS (SELECT 1 FROM memberships m WHERE m.identity_id = identities.id AND m.org_id = $1)
OR EXISTS (SELECT 1 FROM org_agents a WHERE a.identity_id = identities.id AND a.org_id = $1))
ORDER BY created_at, id
`
// Identity persistence. The domain owns lifecycle semantics (internal/domain/
// identity); these queries are the durable half of that contract. Aliases are
// unique on lower(alias) rather than the case-sensitive PRIMARY KEY, matching
// the SQLite schema's COLLATE NOCASE.
func (q *Queries) ListIdentities(ctx context.Context) ([]Identity, error) {
rows, err := q.db.Query(ctx, listIdentities)
// A scoped read sees the identities that are members of, or agents assigned
// to, its org.
func (q *Queries) ListIdentities(ctx context.Context, scopeOrg pgtype.Text) ([]Identity, error) {
rows, err := q.db.Query(ctx, listIdentities, scopeOrg)
if err != nil {
return nil, err
}
@@ -240,11 +275,18 @@ func (q *Queries) ListIdentitySubjects(ctx context.Context, arg ListIdentitySubj
const resolveIdentityAlias = `-- name: ResolveIdentityAlias :one
SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at
FROM identities i JOIN identity_aliases a ON a.identity_id = i.id
WHERE lower(a.alias) = lower($1)
WHERE lower(a.alias) = lower($1) AND ($2::text IS NULL
OR EXISTS (SELECT 1 FROM memberships m WHERE m.identity_id = i.id AND m.org_id = $2)
OR EXISTS (SELECT 1 FROM org_agents a WHERE a.identity_id = i.id AND a.org_id = $2))
`
func (q *Queries) ResolveIdentityAlias(ctx context.Context, lower string) (Identity, error) {
row := q.db.QueryRow(ctx, resolveIdentityAlias, lower)
type ResolveIdentityAliasParams struct {
Alias string
ScopeOrg pgtype.Text
}
func (q *Queries) ResolveIdentityAlias(ctx context.Context, arg ResolveIdentityAliasParams) (Identity, error) {
row := q.db.QueryRow(ctx, resolveIdentityAlias, arg.Alias, arg.ScopeOrg)
var i Identity
err := row.Scan(
&i.ID,
@@ -526,7 +526,7 @@ func (q *Queries) InsertTransition(ctx context.Context, arg InsertTransitionPara
const listOpenPRs = `-- name: ListOpenPRs :many
SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt, review_cursor, watch_comment_id, outputs
FROM tasks WHERE status = 'pr_open'
FROM tasks WHERE status = 'pr_open' AND ($1::text IS NULL OR org_id = $1)
`
type ListOpenPRsRow struct {
@@ -544,8 +544,8 @@ type ListOpenPRsRow struct {
Outputs string
}
func (q *Queries) ListOpenPRs(ctx context.Context) ([]ListOpenPRsRow, error) {
rows, err := q.db.Query(ctx, listOpenPRs)
func (q *Queries) ListOpenPRs(ctx context.Context, scopeOrg pgtype.Text) ([]ListOpenPRsRow, error) {
rows, err := q.db.Query(ctx, listOpenPRs, scopeOrg)
if err != nil {
return nil, err
}
@@ -1,8 +1,14 @@
-- Access policies and denial records (internal/domain/access)
-- name: ListAccessPolicies :many
-- A scoped read sees its own org's policies, and the instance policies only
-- when it may read the instance.
SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at
FROM access_policies ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id;
FROM access_policies
WHERE sqlc.narg(scope_org)::text IS NULL
OR (level = 'instance' AND sqlc.arg(instance_scope)::bool)
OR (level <> 'instance' AND org_id = sqlc.narg(scope_org))
ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id;
-- name: UpsertAccessPolicy :exec
INSERT INTO access_policies (level, org_id, workspace_id, object_kind, object_id, policy_id, text)
@@ -55,8 +55,11 @@ WHERE c.org_id = (SELECT m.org_id FROM captures AS m WHERE m.id = sqlc.arg(captu
);
-- name: InsertMapping :exec
INSERT INTO mappings (id, name, source_hint, event_type, fields, org_id)
VALUES ($1, $2, $3, $4, $5, $6);
-- A mapping lives in its event type's workspace; one with no event type in
-- the org's default workspace.
INSERT INTO mappings (id, name, source_hint, event_type, fields, org_id, workspace_id)
VALUES (sqlc.arg(id), sqlc.arg(name), sqlc.arg(source_hint), sqlc.arg(event_type), sqlc.arg(fields), sqlc.arg(org_id),
COALESCE((SELECT y.workspace_id FROM event_types y WHERE y.id = sqlc.arg(event_type) AND y.org_id = sqlc.arg(org_id)), 'default'));
-- name: GetMapping :one
SELECT sqlc.embed(mappings),
@@ -72,8 +75,9 @@ FROM mappings WHERE (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(sc
-- name: UpdateMapping :execrows
UPDATE mappings
SET name = sqlc.arg(name), source_hint = sqlc.arg(source_hint), event_type = sqlc.arg(event_type), fields = sqlc.arg(fields), updated_at = now()
WHERE id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org));
SET name = sqlc.arg(name), source_hint = sqlc.arg(source_hint), event_type = sqlc.arg(event_type), fields = sqlc.arg(fields), updated_at = now(),
workspace_id = COALESCE((SELECT y.workspace_id FROM event_types y WHERE y.id = sqlc.arg(event_type) AND y.org_id = mappings.org_id), 'default')
WHERE mappings.id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text IS NULL OR mappings.org_id = sqlc.narg(scope_org));
-- name: InsertMappingMatch :exec
INSERT INTO mapping_matches (mapping, capture) VALUES ($1, $2)
@@ -83,27 +87,31 @@ ON CONFLICT DO NOTHING;
DELETE FROM mappings WHERE id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org));
-- name: InsertBinding :exec
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status, inputs, repo_param, org_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9, $10, $11, $12);
-- A binding lives in its source's workspace.
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status, inputs, repo_param, org_id, workspace_id)
VALUES (sqlc.arg(id), sqlc.arg(name), sqlc.arg(source), sqlc.arg(mapping), sqlc.arg(filter), sqlc.arg(workflow), sqlc.arg(owner), sqlc.arg(repo), 1,
sqlc.arg(status), sqlc.arg(inputs), sqlc.arg(repo_param), sqlc.arg(org_id),
COALESCE((SELECT s.workspace_id FROM sources s WHERE s.path = sqlc.arg(source) AND s.org_id = sqlc.arg(org_id)), 'default'));
-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id, workspace_id
FROM bindings WHERE id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org));
-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id, workspace_id
FROM bindings WHERE (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org)) ORDER BY created_at DESC;
-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id, workspace_id
FROM bindings WHERE source = sqlc.arg(source) AND status = 'armed' AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org)) ORDER BY created_at DESC;
-- name: UpdateBinding :execrows
UPDATE bindings
SET name = sqlc.arg(name), source = sqlc.arg(source), mapping = sqlc.arg(mapping), filter = sqlc.arg(filter),
workflow = sqlc.arg(workflow), owner = sqlc.arg(owner), repo = sqlc.arg(repo),
version = version + 1, status = sqlc.arg(status), inputs = sqlc.arg(inputs), repo_param = sqlc.arg(repo_param), updated_at = now()
WHERE id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org));
version = version + 1, status = sqlc.arg(status), inputs = sqlc.arg(inputs), repo_param = sqlc.arg(repo_param), updated_at = now(),
workspace_id = COALESCE((SELECT s.workspace_id FROM sources s WHERE s.path = sqlc.arg(source) AND s.org_id = bindings.org_id), 'default')
WHERE bindings.id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text IS NULL OR bindings.org_id = sqlc.narg(scope_org));
-- name: SetBindingArmed :execrows
UPDATE bindings SET status = 'armed', updated_at = now() WHERE id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org));
@@ -150,11 +158,13 @@ SELECT id, task_id, attempt, tool, result, error, called_at
FROM tool_calls WHERE task_id = sqlc.arg(task_id) AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org)) ORDER BY called_at ASC;
-- name: InsertEventType :exec
INSERT INTO event_types (id, source, name, rule, schema, org_id)
VALUES ($1, $2, $3, $4, $5, $6);
-- An event type lives in its source's workspace.
INSERT INTO event_types (id, source, name, rule, schema, org_id, workspace_id)
VALUES (sqlc.arg(id), sqlc.arg(source), sqlc.arg(name), sqlc.arg(rule), sqlc.arg(schema), sqlc.arg(org_id),
COALESCE((SELECT s.workspace_id FROM sources s WHERE s.path = sqlc.arg(source) AND s.org_id = sqlc.arg(org_id)), 'default'));
-- name: GetEventType :one
SELECT id, source, name, rule, schema, created_at, updated_at
SELECT id, source, name, rule, schema, created_at, updated_at, org_id, workspace_id
FROM event_types WHERE id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org));
-- name: ListEventTypes :many
@@ -176,8 +186,11 @@ DELETE FROM event_types WHERE id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text
-- Serialises saves per source so two concurrent saves cannot each pass the
-- overlap check against a set that excludes the other.
SELECT pg_advisory_xact_lock(hashtext('event_types:' || sqlc.arg(source)::text));
-- name: InsertSource :exec
INSERT INTO sources (path, signing, secret, org_id, workspace_id) VALUES ($1, $2, $3, $4, $5);
-- name: InsertSource :execrows
-- Inserts nothing when the workspace is not one of the org's.
INSERT INTO sources (path, signing, secret, org_id, workspace_id)
SELECT sqlc.arg(path), sqlc.arg(signing), sqlc.arg(secret), w.org_id, w.id
FROM workspaces w WHERE w.org_id = sqlc.arg(org_id) AND w.id = sqlc.arg(workspace_id);
-- name: GetSource :one
SELECT path, signing, secret, created_at, updated_at, org_id, workspace_id, name, delivery_header FROM sources WHERE path = sqlc.arg(path) AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org));
@@ -4,17 +4,31 @@
-- the SQLite schema's COLLATE NOCASE.
-- name: ListIdentities :many
-- A scoped read sees the identities that are members of, or agents assigned
-- to, its org.
SELECT id, kind, display_name, lifecycle, version, created_at, updated_at
FROM identities ORDER BY created_at, id;
FROM identities
WHERE (sqlc.narg(scope_org)::text IS NULL
OR EXISTS (SELECT 1 FROM memberships m WHERE m.identity_id = identities.id AND m.org_id = sqlc.narg(scope_org))
OR EXISTS (SELECT 1 FROM org_agents a WHERE a.identity_id = identities.id AND a.org_id = sqlc.narg(scope_org)))
ORDER BY created_at, id;
-- name: GetIdentity :one
SELECT id, kind, display_name, lifecycle, version, created_at, updated_at
FROM identities WHERE id = $1;
-- name: GetVisibleIdentity :one
SELECT id, kind, display_name, lifecycle, version, created_at, updated_at
FROM identities WHERE id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text IS NULL
OR EXISTS (SELECT 1 FROM memberships m WHERE m.identity_id = identities.id AND m.org_id = sqlc.narg(scope_org))
OR EXISTS (SELECT 1 FROM org_agents a WHERE a.identity_id = identities.id AND a.org_id = sqlc.narg(scope_org)));
-- name: ResolveIdentityAlias :one
SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at
FROM identities i JOIN identity_aliases a ON a.identity_id = i.id
WHERE lower(a.alias) = lower($1);
WHERE lower(a.alias) = lower(sqlc.arg(alias)) AND (sqlc.narg(scope_org)::text IS NULL
OR EXISTS (SELECT 1 FROM memberships m WHERE m.identity_id = i.id AND m.org_id = sqlc.narg(scope_org))
OR EXISTS (SELECT 1 FROM org_agents a WHERE a.identity_id = i.id AND a.org_id = sqlc.narg(scope_org)));
-- name: InsertIdentity :exec
INSERT INTO identities (id, kind, display_name, lifecycle, version, created_at, updated_at)
@@ -268,4 +268,4 @@ DELETE FROM tasks WHERE id = $1 AND status = $2;
-- name: ListOpenPRs :many
SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt, review_cursor, watch_comment_id, outputs
FROM tasks WHERE status = 'pr_open';
FROM tasks WHERE status = 'pr_open' AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org));
@@ -14,3 +14,12 @@ func scopeOrg(ctx context.Context) pgtype.Text {
id, ok := org.Scope(ctx)
return pgtype.Text{String: string(id), Valid: ok}
}
// memberScope is the org whose members and agents a read is confined to, or
// NULL when the request may read the whole instance.
func memberScope(ctx context.Context) pgtype.Text {
if org.InstanceScope(ctx) {
return pgtype.Text{}
}
return scopeOrg(ctx)
}
+13 -5
View File
@@ -15,17 +15,22 @@ import (
var _ storecontract.SourceStore = (*EDA)(nil)
// InsertSource stores a new source in the acting org's default workspace.
// The path is the primary key, so a taken
// path is refused by the database and surfaced as ErrSourcePathTaken.
// InsertSource stores a new source in one of the acting org's workspaces,
// its default one when src names none; a workspace the org does not have is
// ErrInvalidWorkspace. The path is the primary key, so a taken path is
// refused by the database and surfaced as ErrSourcePathTaken.
func (s *EDA) InsertSource(ctx context.Context, src source.Source) error {
secret, err := s.sealSecret(src.Secret)
if err != nil {
return err
}
err = s.q.InsertSource(ctx, postgresdb.InsertSourceParams{
workspace := src.WorkspaceID
if workspace == "" {
workspace = org.DefaultWorkspaceID
}
n, err := s.q.InsertSource(ctx, postgresdb.InsertSourceParams{
Path: src.Path, Signing: string(src.Signing), Secret: secret,
OrgID: string(org.OrgFromContext(ctx)), WorkspaceID: string(org.DefaultWorkspaceID),
OrgID: string(org.OrgFromContext(ctx)), WorkspaceID: string(workspace),
})
if isUniqueViolation(err) {
return storecontract.ErrSourcePathTaken
@@ -33,6 +38,9 @@ func (s *EDA) InsertSource(ctx context.Context, src source.Source) error {
if err != nil {
return fmt.Errorf("edastore: insert source: %w", err)
}
if n == 0 {
return fmt.Errorf("%w: %s is not a workspace of this org", org.ErrInvalidWorkspace, workspace)
}
return nil
}
+21 -4
View File
@@ -10,6 +10,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
@@ -29,8 +30,12 @@ func (s *Store) PutConfigSnapshot(ctx context.Context, snapshot storecontract.Co
}
// ConfigSnapshot returns the published snapshot. found is false, with a nil
// error, before anything has published one.
// error, before anything has published one or when the request may not read
// the instance.
func (s *Store) ConfigSnapshot(ctx context.Context) (storecontract.ConfigSnapshot, bool, error) {
if !org.InstanceScope(ctx) {
return storecontract.ConfigSnapshot{}, false, nil
}
row, err := s.queries().ConfigSnapshotByID(ctx)
if errors.Is(err, pgx.ErrNoRows) {
return storecontract.ConfigSnapshot{}, false, nil
@@ -78,8 +83,12 @@ func (s *Store) PutChannelStatus(ctx context.Context, channels []storecontract.C
return tx.Commit(ctx)
}
// ChannelStatus returns every reported channel, ordered by id.
// ChannelStatus returns every reported channel, ordered by id, or none when
// the request may not read the instance.
func (s *Store) ChannelStatus(ctx context.Context) ([]storecontract.ChannelStatus, error) {
if !org.InstanceScope(ctx) {
return []storecontract.ChannelStatus{}, nil
}
rows, err := s.queries().ListChannelStatus(ctx)
if err != nil {
return nil, fmt.Errorf("store: list channel status: %w", err)
@@ -110,8 +119,12 @@ func (s *Store) PutApplyStatus(ctx context.Context, status storecontract.ApplySt
return nil
}
// ListApplyStatus returns every process's report, ordered by (process, kind).
// ListApplyStatus returns every process's report, ordered by (process, kind),
// or none when the request may not read the instance.
func (s *Store) ListApplyStatus(ctx context.Context) ([]storecontract.ApplyStatus, error) {
if !org.InstanceScope(ctx) {
return []storecontract.ApplyStatus{}, nil
}
rows, err := s.queries().ListApplyStatus(ctx)
if err != nil {
return nil, fmt.Errorf("store: list apply status: %w", err)
@@ -158,8 +171,12 @@ func (s *Store) PutPresence(ctx context.Context, presence storecontract.Presence
// presenceRetention is how long a stopped instance stays listed as down.
const presenceRetention = 24 * time.Hour
// ListPresence returns every instance's record, ordered by (service, instance).
// ListPresence returns every instance's record, ordered by (service,
// instance), or none when the request may not read the instance.
func (s *Store) ListPresence(ctx context.Context) ([]storecontract.Presence, error) {
if !org.InstanceScope(ctx) {
return []storecontract.Presence{}, nil
}
rows, err := s.queries().ListPresence(ctx)
if err != nil {
return nil, fmt.Errorf("store: list presence: %w", err)
@@ -0,0 +1,37 @@
package postgres
import (
"context"
"testing"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// TestInstanceStatusHiddenFromOrgs pins that a caller confined to an org
// other than the system org reads none of the instance's status. The store
// has no database: a read that reached one would panic.
func TestInstanceStatusHiddenFromOrgs(t *testing.T) {
s := New(nil)
ctx := org.WithScope(context.Background(), "globex")
for _, tt := range []struct {
rpc string
read func() (int, error)
}{
{"ListPresence", func() (int, error) { v, err := s.ListPresence(ctx); return len(v), err }},
{"ListChannelStatus", func() (int, error) { v, err := s.ChannelStatus(ctx); return len(v), err }},
{"ListApplyStatus", func() (int, error) { v, err := s.ListApplyStatus(ctx); return len(v), err }},
{"GetConfigSnapshot", func() (int, error) {
_, found, err := s.ConfigSnapshot(ctx)
if found {
return 1, err
}
return 0, err
}},
} {
t.Run(tt.rpc, func(t *testing.T) {
if n, err := tt.read(); err != nil || n != 0 {
t.Fatalf("read %d rows, err %v; want none", n, err)
}
})
}
}
+2 -1
View File
@@ -109,6 +109,7 @@ func taskFromRow(t postgresdb.Task) *workflow.Task {
Source: t.Source,
Identity: t.Identity,
Org: org.OrgID(t.OrgID),
Workspace: org.WorkspaceID(t.WorkspaceID),
BindingID: t.BindingID,
BindingVersion: int(t.BindingVersion),
Inputs: inputs,
@@ -704,7 +705,7 @@ func (s *Store) RecoverStale(ctx context.Context) (int64, error) {
// carrying the attempt and the review/comment cursors the reconcile loop and
// poll backstop read.
func (s *Store) OpenPRs(ctx context.Context) ([]workflow.Task, error) {
rows, err := s.queries().ListOpenPRs(ctx)
rows, err := s.queries().ListOpenPRs(ctx, scopeOrg(ctx))
if err != nil {
return nil, err
}