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:
1 parent
8540c9f7c8
commit
f34f60f9c7
60 files changed
+1695
-828
No files matched your search
@@ -13,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/applystatus"
|
||||
"github.com/samcharles93/archie-core/internal/domain/presence"
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
@@ -29,7 +30,12 @@ import (
|
||||
// retrying, so a State Store or database that is down or slow at start
|
||||
// closes the dashboard rather than opening it or stopping it.
|
||||
func buildAccessChain(ctx context.Context, store *staterpc.Client, log *slog.Logger) *infraaccess.Live {
|
||||
live := infraaccess.NewPending(store.ListPolicies, log)
|
||||
// The chain decides for every org, so it loads as the dashboard service,
|
||||
// never as the person whose policy edit triggered a reload.
|
||||
load := func(ctx context.Context) ([]access.Policy, error) {
|
||||
return store.ListPolicies(access.WithoutPrincipal(ctx))
|
||||
}
|
||||
live := infraaccess.NewPending(load, log)
|
||||
go live.Run(ctx, applystatus.RestampInterval)
|
||||
return live
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package statestore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// tasksByOrg answers TaskByID the way the store does: a scoped read sees only
|
||||
// its own org's tasks.
|
||||
type tasksByOrg map[int64]org.OrgID
|
||||
|
||||
func (t tasksByOrg) TaskByID(ctx context.Context, id int64) (*task.Task, error) {
|
||||
owner, ok := t[id]
|
||||
if scope, scoped := org.Scope(ctx); !ok || (scoped && scope != owner) {
|
||||
return nil, nil
|
||||
}
|
||||
return &task.Task{ID: id}, nil
|
||||
}
|
||||
|
||||
// everyLog has a log for every task.
|
||||
type everyLog struct{}
|
||||
|
||||
func (everyLog) TaskLog(context.Context, int64, int, logging.Query) (logging.TaskLogPage, error) {
|
||||
return logging.TaskLogPage{Found: true}, nil
|
||||
}
|
||||
|
||||
func (everyLog) TaskLogContent(context.Context, int64, int, io.Writer) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// TestOrgScopedReads pins that a caller scoped to one org reads nothing of
|
||||
// another org's, while an unscoped internal service reads everything.
|
||||
func TestOrgScopedReads(t *testing.T) {
|
||||
logs := orgTaskLogs{TaskLogStore: everyLog{}, tasks: tasksByOrg{1: "acme"}}
|
||||
reads := map[string]func(ctx context.Context) bool{
|
||||
"ReadTaskLog": func(ctx context.Context) bool {
|
||||
page, err := logs.TaskLog(ctx, 1, 0, logging.Query{})
|
||||
return err == nil && page.Found
|
||||
},
|
||||
"StreamTaskLogContent": func(ctx context.Context) bool {
|
||||
found, err := logs.TaskLogContent(ctx, 1, 0, io.Discard)
|
||||
return err == nil && found
|
||||
},
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
scope org.OrgID
|
||||
want bool
|
||||
}{
|
||||
{"unscoped service", "", true},
|
||||
{"owning org", "acme", true},
|
||||
{"another org", "globex", false},
|
||||
} {
|
||||
for rpc, read := range reads {
|
||||
t.Run(rpc+"/"+tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
if tt.scope != "" {
|
||||
ctx = org.WithScope(ctx, tt.scope)
|
||||
}
|
||||
if got := read(ctx); got != tt.want {
|
||||
t.Fatalf("read = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,8 @@ func (g guardedPolicies) DeletePolicy(ctx context.Context, p access.Policy) erro
|
||||
}
|
||||
|
||||
func (g guardedPolicies) checkLockout(ctx context.Context, change func([]access.Policy) []access.Policy) error {
|
||||
current, err := g.ListPolicies(ctx)
|
||||
// The change is checked against every org's chain, not just the caller's.
|
||||
current, err := g.ListPolicies(org.WithoutScope(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -312,7 +312,7 @@ func (b *server) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
|
||||
// what makes the RPC answer Unavailable -- the honest "this process cannot
|
||||
// read logs" -- instead of depending on nil-receiver behaviour to notice.
|
||||
if b.taskLogs != nil {
|
||||
deps.TaskLogs = b.taskLogs
|
||||
deps.TaskLogs = orgTaskLogs{TaskLogStore: b.taskLogs, tasks: b.st}
|
||||
}
|
||||
// The event-capture contracts are served by the event-capture store, not
|
||||
// the task store. BindingTaskCreator stays below on the
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package statestore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// orgTaskLogs serves a task's log only to a caller whose org holds the task.
|
||||
// Log files carry no org; the task row does, so a scoped read asks the task
|
||||
// store, which applies the caller's scope, and answers "no log" for a task the
|
||||
// caller cannot see.
|
||||
type orgTaskLogs struct {
|
||||
storecontract.TaskLogStore
|
||||
tasks interface {
|
||||
TaskByID(ctx context.Context, taskID int64) (*task.Task, error)
|
||||
}
|
||||
}
|
||||
|
||||
func (l orgTaskLogs) visible(ctx context.Context, taskID int64) (bool, error) {
|
||||
if _, scoped := org.Scope(ctx); !scoped {
|
||||
return true, nil
|
||||
}
|
||||
t, err := l.tasks.TaskByID(ctx, taskID)
|
||||
return t != nil, err
|
||||
}
|
||||
|
||||
func (l orgTaskLogs) TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error) {
|
||||
if ok, err := l.visible(ctx, taskID); !ok || err != nil {
|
||||
return logging.TaskLogPage{}, err
|
||||
}
|
||||
return l.TaskLogStore.TaskLog(ctx, taskID, attempt, q)
|
||||
}
|
||||
|
||||
func (l orgTaskLogs) TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (bool, error) {
|
||||
if ok, err := l.visible(ctx, taskID); !ok || err != nil {
|
||||
return false, err
|
||||
}
|
||||
return l.TaskLogStore.TaskLogContent(ctx, taskID, attempt, w)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -752,7 +752,7 @@ func (d *Daemon) authorizeDispatch(ctx context.Context, b binding.Binding, c sto
|
||||
return false
|
||||
}
|
||||
resource := access.Resource{
|
||||
Kind: access.KindWorkflow, ID: b.Workflow, Org: principal.Org,
|
||||
Kind: access.KindWorkflow, ID: b.Workflow, Org: principal.Org, Workspace: b.WorkspaceID,
|
||||
}
|
||||
contextValue := access.Context{Signature: signatureOf(c), Addr: c.RemoteAddr}
|
||||
decision := d.Access.Authorize(principal, access.ActionRun, resource, contextValue)
|
||||
|
||||
@@ -80,7 +80,7 @@ func (d *Daemon) mayRunWorkflow(ctx context.Context, task *workflow.Task, id ide
|
||||
d.Log.Warn("workflow identity: principal unavailable", "task", task.ID, "identity", id, "err", err)
|
||||
return false
|
||||
}
|
||||
resource := access.Resource{Kind: access.KindWorkflow, ID: task.Workflow, Org: task.Org}
|
||||
resource := access.Resource{Kind: access.KindWorkflow, ID: task.Workflow, Org: task.Org, Workspace: task.Workspace}
|
||||
if resource.Org == "" {
|
||||
resource.Org = principal.Org
|
||||
}
|
||||
|
||||
@@ -40,6 +40,12 @@ func WithPrincipal(ctx context.Context, p Principal) context.Context {
|
||||
return context.WithValue(ctx, principalContextKey{}, p)
|
||||
}
|
||||
|
||||
// WithoutPrincipal drops the principal from ctx, so a call made with it acts
|
||||
// as the calling service rather than for the person behind the request.
|
||||
func WithoutPrincipal(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, principalContextKey{}, nil)
|
||||
}
|
||||
|
||||
// PrincipalFromContext returns the principal WithPrincipal attached.
|
||||
func PrincipalFromContext(ctx context.Context) (Principal, bool) {
|
||||
p, ok := ctx.Value(principalContextKey{}).(Principal)
|
||||
|
||||
@@ -51,6 +51,20 @@ type Principal struct {
|
||||
Kind identity.Kind
|
||||
Org org.OrgID
|
||||
Memberships []org.Membership
|
||||
// Workspaces are the workspaces of Org. A principal acts only in its own
|
||||
// org, so these describe the workspace of any resource it may reach.
|
||||
Workspaces []org.Workspace
|
||||
}
|
||||
|
||||
// Environment returns the environment of ws in the principal's org, empty
|
||||
// when it names none.
|
||||
func (p Principal) Environment(ws org.WorkspaceID) string {
|
||||
for _, w := range p.Workspaces {
|
||||
if w.ID == ws {
|
||||
return w.Environment
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Role returns the principal's effective role for a resource: the role of
|
||||
|
||||
@@ -52,11 +52,13 @@ type Binding struct {
|
||||
Inputs map[string]InputSource `json:"inputs,omitempty"`
|
||||
// OrgID is the org that owns the binding; the store sets it and a
|
||||
// binding may target only a workflow that org has enabled.
|
||||
OrgID org.OrgID `json:"org_id"`
|
||||
Version int `json:"version"`
|
||||
Status Status `json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
OrgID org.OrgID `json:"org_id"`
|
||||
// WorkspaceID is its source's workspace; the store sets it.
|
||||
WorkspaceID org.WorkspaceID `json:"workspace_id"`
|
||||
Version int `json:"version"`
|
||||
Status Status `json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// Validate checks a binding is well-formed before it is persisted: a
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -52,13 +54,15 @@ type Rule struct {
|
||||
// EventType is a named kind of event from one source. Schema is the inferred
|
||||
// structure (path to type) of the payload it was created from.
|
||||
type EventType struct {
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"`
|
||||
Name string `json:"name"`
|
||||
Rule Rule `json:"rule"`
|
||||
Schema map[string]ValueType `json:"schema"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"`
|
||||
Name string `json:"name"`
|
||||
Rule Rule `json:"rule"`
|
||||
Schema map[string]ValueType `json:"schema"`
|
||||
// WorkspaceID is its source's workspace; the store sets it.
|
||||
WorkspaceID org.WorkspaceID `json:"workspace_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// Validate refuses an event type that has no name or source or carries a
|
||||
|
||||
@@ -105,6 +105,10 @@ func FromLegacyName(legacyName string) (Identity, error) {
|
||||
return New(StableID(legacyName), KindBot, legacyName)
|
||||
}
|
||||
|
||||
// Agent reports whether the kind acts on its own rather than for a person: an
|
||||
// agent serves exactly one org.
|
||||
func (k Kind) Agent() bool { return k == KindBot || k == KindServiceAccount }
|
||||
|
||||
// ValidDisplayName reports whether name is non-empty after trimming.
|
||||
func ValidDisplayName(name string) bool { return strings.TrimSpace(name) != "" }
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// FieldType is the expected JSON shape of a mapped field, checked at
|
||||
@@ -53,15 +54,17 @@ type Field struct {
|
||||
// it. MatchCount and LastMatchedAt are read-only: the store counts each
|
||||
// capture the mapping resolved at dispatch.
|
||||
type Mapping struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
SourceHint string `json:"source_hint"`
|
||||
EventTypeID string `json:"event_type_id"`
|
||||
Fields []Field `json:"fields"`
|
||||
MatchCount int64 `json:"match_count"`
|
||||
LastMatchedAt time.Time `json:"last_matched_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
SourceHint string `json:"source_hint"`
|
||||
EventTypeID string `json:"event_type_id"`
|
||||
Fields []Field `json:"fields"`
|
||||
// WorkspaceID is its event type's workspace; the store sets it.
|
||||
WorkspaceID org.WorkspaceID `json:"workspace_id"`
|
||||
MatchCount int64 `json:"match_count"`
|
||||
LastMatchedAt time.Time `json:"last_matched_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// validTypes is the set of FieldType values Validate accepts.
|
||||
|
||||
@@ -32,6 +32,21 @@ func WithScope(ctx context.Context, id OrgID) context.Context {
|
||||
return context.WithValue(ctx, scopeContextKey{}, id)
|
||||
}
|
||||
|
||||
// WithoutScope lifts a request's org confinement, for a read that serves the
|
||||
// whole instance rather than the caller, such as checking a policy change
|
||||
// against every org's chain.
|
||||
func WithoutScope(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, scopeContextKey{}, OrgID(""))
|
||||
}
|
||||
|
||||
// InstanceScope reports whether ctx may read instance-wide records: it is an
|
||||
// internal service acting across orgs, or it is confined to the system org,
|
||||
// which operates the instance.
|
||||
func InstanceScope(ctx context.Context) bool {
|
||||
id, ok := Scope(ctx)
|
||||
return !ok || id == DefaultOrgID
|
||||
}
|
||||
|
||||
// Scope returns the org WithScope confined ctx to.
|
||||
func Scope(ctx context.Context) (OrgID, bool) {
|
||||
id, ok := ctx.Value(scopeContextKey{}).(OrgID)
|
||||
|
||||
@@ -33,10 +33,6 @@ var (
|
||||
ErrOrgExists = errors.New("org: org already exists")
|
||||
ErrWorkspaceExists = errors.New("org: workspace already exists")
|
||||
ErrMembershipExists = errors.New("org: membership already exists")
|
||||
// ErrUpgradeIncomplete reports that the resumable default org/workspace
|
||||
// upgrade has not finished: the store refuses scoped calls rather than
|
||||
// serving records with no org.
|
||||
ErrUpgradeIncomplete = errors.New("org: default org upgrade incomplete")
|
||||
)
|
||||
|
||||
// Role is a member's role in an org or one of its workspaces.
|
||||
|
||||
@@ -98,6 +98,9 @@ type Task struct {
|
||||
// a task
|
||||
// of a single-operator install belongs to the default org.
|
||||
Org org.OrgID `json:"org,omitempty"`
|
||||
// Workspace is the workspace of Org the task belongs to; the store sets
|
||||
// it.
|
||||
Workspace org.WorkspaceID `json:"workspace,omitempty"`
|
||||
// BindingID and BindingVersion are stamped when a task was created from a
|
||||
// playbook binding dispatch. They record provenance: which binding fired
|
||||
// this task and at what version, so later edits to the binding cannot
|
||||
|
||||
@@ -20,8 +20,8 @@ import (
|
||||
const schemaText = `namespace Archie {
|
||||
entity Identity in [Org] = {"org": String, "role": String};
|
||||
entity Org;
|
||||
entity Workspace in [Org] = {"org": String};
|
||||
entity Object in [Org, Workspace] = {"org": String, "workspace": String, "kind": String, "owner": String, "state": String};
|
||||
entity Workspace in [Org] = {"org": String, "environment": String};
|
||||
entity Object in [Org, Workspace] = {"org": String, "workspace": Workspace, "kind": String, "owner": String, "state": String};
|
||||
action read appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
|
||||
action create appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
|
||||
action update appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
|
||||
|
||||
@@ -45,3 +45,41 @@ func TestInvalidInstancePolicy(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestWorkspaceEnvironment pins that a policy can read the environment of
|
||||
// the workspace a resource is in: it validates on save and decides runs in
|
||||
// that workspace only.
|
||||
func TestWorkspaceEnvironment(t *testing.T) {
|
||||
frozen := access.Policy{
|
||||
ID: "no-prod-runs", Level: access.LevelOrg, OrgID: "acme",
|
||||
Text: `forbid(principal, action == Archie::Action::"run", resource) when { resource.workspace.environment == "production" };`,
|
||||
}
|
||||
engine := New(append(access.ShippedOrgPolicies("acme"), frozen))
|
||||
if err := engine.Validate(frozen); err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
dev := access.Principal{
|
||||
IdentityID: "dev", Org: "acme",
|
||||
Memberships: []org.Membership{{IdentityID: "dev", OrgID: "acme", Role: org.RoleDeveloper}},
|
||||
Workspaces: []org.Workspace{{ID: "live", OrgID: "acme", Environment: "production"}, {ID: "stage", OrgID: "acme", Environment: "staging"}},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
action access.Action
|
||||
workspace org.WorkspaceID
|
||||
allowed bool
|
||||
}{
|
||||
{"run in a production workspace", access.ActionRun, "live", false},
|
||||
{"other actions in it", access.ActionUpdate, "live", true},
|
||||
{"run in another environment", access.ActionRun, "stage", true},
|
||||
{"run on a record with no workspace", access.ActionRun, "", true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
resource := access.Resource{Kind: access.KindWorkflow, ID: "triage", Org: "acme", Workspace: tt.workspace}
|
||||
if got := engine.Authorize(dev, tt.action, resource, access.Context{}); got.Allowed != tt.allowed {
|
||||
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -68,21 +68,25 @@ func buildEntities(p access.Principal, r access.Resource) cedar.EntityMap {
|
||||
}
|
||||
|
||||
parents := []types.EntityUID{orgUID}
|
||||
resUID := types.NewEntityUID(access.EntityTypeObject, types.String(r.ID))
|
||||
attrs := types.RecordMap{
|
||||
"org": types.String(resOrg),
|
||||
"kind": types.String(string(r.Kind)),
|
||||
}
|
||||
// An org-level record has no workspace, so a policy reading
|
||||
// resource.workspace does not apply to it.
|
||||
if r.Workspace != "" {
|
||||
wsUID := types.NewEntityUID(access.EntityTypeWorkspace, types.String(r.Workspace))
|
||||
entities[wsUID] = cedar.Entity{
|
||||
UID: wsUID,
|
||||
Parents: cedar.NewEntityUIDSet(orgUID),
|
||||
Attributes: types.NewRecord(types.RecordMap{"org": types.String(resOrg)}),
|
||||
UID: wsUID,
|
||||
Parents: cedar.NewEntityUIDSet(orgUID),
|
||||
Attributes: types.NewRecord(types.RecordMap{
|
||||
"org": types.String(resOrg),
|
||||
"environment": types.String(p.Environment(r.Workspace)),
|
||||
}),
|
||||
}
|
||||
parents = append(parents, wsUID)
|
||||
}
|
||||
|
||||
resUID := types.NewEntityUID(access.EntityTypeObject, types.String(r.ID))
|
||||
attrs := types.RecordMap{
|
||||
"org": types.String(resOrg),
|
||||
"workspace": types.String(string(r.Workspace)),
|
||||
"kind": types.String(string(r.Kind)),
|
||||
attrs["workspace"] = wsUID
|
||||
}
|
||||
if r.Owner != "" {
|
||||
attrs["owner"] = types.String(string(r.Owner))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -87,6 +87,9 @@ func (s *server) GetPrincipal(ctx context.Context, request *pb.GetPrincipalReque
|
||||
IdentityId: string(value.IdentityID),
|
||||
OrgId: string(value.Org),
|
||||
Memberships: memberships,
|
||||
Workspaces: mapValues(value.Workspaces, func(w org.Workspace) *pb.PrincipalWorkspace {
|
||||
return &pb.PrincipalWorkspace{WorkspaceId: string(w.ID), Environment: w.Environment}
|
||||
}),
|
||||
}}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -33,10 +33,14 @@ func (c *Client) PrincipalFor(ctx context.Context, id identity.IdentityID) (acce
|
||||
Role: org.Role(m.GetRole()),
|
||||
}
|
||||
})
|
||||
orgID := org.OrgID(value.GetOrgId())
|
||||
return access.Principal{
|
||||
IdentityID: identity.IdentityID(value.GetIdentityId()),
|
||||
Org: org.OrgID(value.GetOrgId()),
|
||||
Org: orgID,
|
||||
Memberships: memberships,
|
||||
Workspaces: mapValues(value.GetWorkspaces(), func(w *pb.PrincipalWorkspace) org.Workspace {
|
||||
return org.Workspace{ID: org.WorkspaceID(w.GetWorkspaceId()), OrgID: orgID, Environment: w.GetEnvironment()}
|
||||
}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
@@ -19,7 +20,7 @@ var (
|
||||
|
||||
func eventTypeProto(t eventtype.EventType) *pb.EventType {
|
||||
out := &pb.EventType{
|
||||
Id: t.ID, Source: t.Source, Name: t.Name,
|
||||
Id: t.ID, Source: t.Source, Name: t.Name, WorkspaceId: string(t.WorkspaceID),
|
||||
CreatedAt: timestamp(t.CreatedAt), UpdatedAt: timestamp(t.UpdatedAt),
|
||||
}
|
||||
for _, h := range t.Rule.Headers {
|
||||
@@ -42,7 +43,7 @@ func eventTypeValue(t *pb.EventType) eventtype.EventType {
|
||||
return eventtype.EventType{}
|
||||
}
|
||||
out := eventtype.EventType{
|
||||
ID: t.Id, Source: t.Source, Name: t.Name,
|
||||
ID: t.Id, Source: t.Source, Name: t.Name, WorkspaceID: org.WorkspaceID(t.WorkspaceId),
|
||||
CreatedAt: timeValue(t.CreatedAt), UpdatedAt: timeValue(t.UpdatedAt),
|
||||
}
|
||||
for _, h := range t.HeaderConditions {
|
||||
|
||||
@@ -27,7 +27,7 @@ func orgStatus(err error) error {
|
||||
return status.Error(codes.Aborted, err.Error())
|
||||
case errors.Is(err, org.ErrInvalidRole), errors.Is(err, org.ErrInvalidOrg),
|
||||
errors.Is(err, org.ErrInvalidMembership), errors.Is(err, org.ErrInvalidWorkspace),
|
||||
errors.Is(err, org.ErrInvalidAssignment), errors.Is(err, org.ErrUpgradeIncomplete):
|
||||
errors.Is(err, org.ErrInvalidAssignment):
|
||||
return status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
return mapError(err)
|
||||
|
||||
@@ -82,6 +82,7 @@ func taskProto(t *task.Task) *pb.Task { // mirror-image field-by-field proto<->d
|
||||
WorkflowDefinitionDigest: t.WorkflowDefinitionDigest,
|
||||
WorkflowDefinitionYaml: t.WorkflowDefinitionYAML,
|
||||
Org: string(t.Org),
|
||||
Workspace: string(t.Workspace),
|
||||
CallParentTaskId: t.CallParentTaskID,
|
||||
CallDepth: int32(t.CallDepth),
|
||||
Origin: t.Origin,
|
||||
@@ -115,6 +116,7 @@ func taskValue(t *pb.Task) *task.Task { // see taskProto above
|
||||
WorkflowDefinitionDigest: t.WorkflowDefinitionDigest,
|
||||
WorkflowDefinitionYAML: t.WorkflowDefinitionYaml,
|
||||
Org: org.OrgID(t.Org),
|
||||
Workspace: org.WorkspaceID(t.Workspace),
|
||||
CallParentTaskID: t.CallParentTaskId,
|
||||
CallDepth: int(t.CallDepth),
|
||||
Origin: t.Origin,
|
||||
@@ -245,8 +247,9 @@ func mappingFieldValue(f *pb.MappingField) mapping.Field {
|
||||
func mappingProto(m mapping.Mapping) *pb.Mapping {
|
||||
return &pb.Mapping{
|
||||
Id: m.ID, Name: m.Name, SourceHint: m.SourceHint, EventTypeId: m.EventTypeID,
|
||||
Fields: mapValues(m.Fields, mappingFieldProto),
|
||||
MatchCount: m.MatchCount, LastMatchedAt: timestamp(m.LastMatchedAt),
|
||||
WorkspaceId: string(m.WorkspaceID),
|
||||
Fields: mapValues(m.Fields, mappingFieldProto),
|
||||
MatchCount: m.MatchCount, LastMatchedAt: timestamp(m.LastMatchedAt),
|
||||
CreatedAt: timestamp(m.CreatedAt), UpdatedAt: timestamp(m.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -257,8 +260,9 @@ func mappingValue(m *pb.Mapping) mapping.Mapping {
|
||||
}
|
||||
return mapping.Mapping{
|
||||
ID: m.Id, Name: m.Name, SourceHint: m.SourceHint, EventTypeID: m.EventTypeId,
|
||||
Fields: mapValues(m.Fields, mappingFieldValue),
|
||||
MatchCount: m.MatchCount, LastMatchedAt: timeValue(m.LastMatchedAt),
|
||||
WorkspaceID: org.WorkspaceID(m.WorkspaceId),
|
||||
Fields: mapValues(m.Fields, mappingFieldValue),
|
||||
MatchCount: m.MatchCount, LastMatchedAt: timeValue(m.LastMatchedAt),
|
||||
CreatedAt: timeValue(m.CreatedAt), UpdatedAt: timeValue(m.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -268,7 +272,7 @@ func bindingProto(b binding.Binding) *pb.Binding {
|
||||
Id: b.ID, Name: b.Name, Matcher: &pb.BindingMatcher{Source: b.Matcher.Source},
|
||||
MappingId: b.MappingID, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
|
||||
RepoParam: b.RepoParam, InputsJson: bindingInputsJSON(b.Inputs), OrgId: string(b.OrgID),
|
||||
Version: int64(b.Version), Status: string(b.Status),
|
||||
WorkspaceId: string(b.WorkspaceID), Version: int64(b.Version), Status: string(b.Status),
|
||||
CreatedAt: timestamp(b.CreatedAt), UpdatedAt: timestamp(b.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -285,7 +289,7 @@ func bindingValue(b *pb.Binding) binding.Binding {
|
||||
ID: b.Id, Name: b.Name, Matcher: binding.Matcher{Source: source},
|
||||
MappingID: b.MappingId, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
|
||||
RepoParam: b.RepoParam, Inputs: bindingInputsValue(b.InputsJson), OrgID: org.OrgID(b.OrgId),
|
||||
Version: int(b.Version), Status: binding.Status(b.Status),
|
||||
WorkspaceID: org.WorkspaceID(b.WorkspaceId), Version: int(b.Version), Status: binding.Status(b.Status),
|
||||
CreatedAt: timeValue(b.CreatedAt), UpdatedAt: timeValue(b.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -512,6 +516,7 @@ var wireErrors = []struct {
|
||||
{storecontract.ErrCallCallerNotRunning, codes.FailedPrecondition, storecontract.ErrCallCallerNotRunning.Error()},
|
||||
{storecontract.ErrCallDepthExceeded, codes.FailedPrecondition, storecontract.ErrCallDepthExceeded.Error()},
|
||||
{storecontract.ErrSourcePathTaken, codes.AlreadyExists, msgSourcePathTaken},
|
||||
{org.ErrInvalidWorkspace, codes.InvalidArgument, org.ErrInvalidWorkspace.Error()},
|
||||
{storecontract.ErrHarnessSecretNotFound, codes.NotFound, msgHarnessSecretNotFound},
|
||||
{storecontract.ErrRereviewCapReached, codes.FailedPrecondition, msgRereviewCapReached},
|
||||
{storepkg.ErrNotFound, codes.NotFound, storepkg.ErrNotFound.Error()},
|
||||
|
||||
@@ -69,6 +69,9 @@ func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
views := make([]bindingView, 0, len(bindings))
|
||||
for _, b := range bindings {
|
||||
if !listedIn(r, b.WorkspaceID) {
|
||||
continue
|
||||
}
|
||||
views = append(views, bindingView{
|
||||
Binding: b, Unsigned: unsigned[b.Matcher.Source], WorkflowDisabled: !enablement.Enabled(b.OrgID, b.Workflow),
|
||||
LastOutcome: s.lastOutcome(r.Context(), b.ID),
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
)
|
||||
@@ -289,7 +290,9 @@ func (r remoteChannelStatus) Snapshot() []status.Status {
|
||||
|
||||
func RemoteConfigView(snapshots storecontract.ConfigSnapshotStore) ConfigViewSource {
|
||||
return func(ctx context.Context) (ConfigView, bool, error) {
|
||||
snapshot, found, err := snapshots.ConfigSnapshot(ctx)
|
||||
// The published config is instance state: the dashboard reads it as
|
||||
// itself, and each handler decides what of it a caller may see.
|
||||
snapshot, found, err := snapshots.ConfigSnapshot(access.WithoutPrincipal(ctx))
|
||||
if err != nil || !found {
|
||||
return ConfigView{}, false, err
|
||||
}
|
||||
|
||||
@@ -58,10 +58,13 @@ func (s *Server) handleEventTypes(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
proposals = append(proposals, eventtype.Propose(unmatchedCaptures(types, captures))...)
|
||||
}
|
||||
if types == nil {
|
||||
types = []eventtype.EventType{}
|
||||
listed := []eventtype.EventType{}
|
||||
for _, t := range types {
|
||||
if listedIn(r, t.WorkspaceID) {
|
||||
listed = append(listed, t)
|
||||
}
|
||||
}
|
||||
writeJSON(w, map[string]any{"enabled": true, "event_types": types, "proposals": proposals})
|
||||
writeJSON(w, map[string]any{"enabled": true, "event_types": listed, "proposals": proposals})
|
||||
}
|
||||
|
||||
// unmatchedCaptures keeps the captures that were unidentified on arrival and
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
@@ -60,6 +61,7 @@ func (s *Server) handleMappingsList(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "list mappings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
mappings = slices.DeleteFunc(mappings, func(m mapping.Mapping) bool { return !listedIn(r, m.WorkspaceID) })
|
||||
writeJSON(w, map[string]any{"mappings": mappings})
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +5,11 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
@@ -28,6 +30,7 @@ func (s *Server) handleSourcesList(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "list sources failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
list = slices.DeleteFunc(list, func(src source.Source) bool { return !listedIn(r, src.WorkspaceID) })
|
||||
for i := range list {
|
||||
list[i].Secret = ""
|
||||
}
|
||||
@@ -44,6 +47,9 @@ func (s *Server) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
var req struct {
|
||||
Path string `json:"path"`
|
||||
// Workspace is the caller's org workspace to create it in; empty is
|
||||
// the default one.
|
||||
Workspace org.WorkspaceID `json:"workspace"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
@@ -55,6 +61,7 @@ func (s *Server) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
src.WorkspaceID = req.Workspace
|
||||
err = s.Sources.InsertSource(r.Context(), src)
|
||||
}
|
||||
if err != nil {
|
||||
@@ -229,6 +236,8 @@ func (s *Server) sourceError(w http.ResponseWriter, what string, err error) {
|
||||
http.Error(w, "source signing changed; reload and retry", http.StatusConflict)
|
||||
case errors.Is(err, storecontract.ErrSourceNotFound):
|
||||
http.Error(w, "source not found", http.StatusNotFound)
|
||||
case errors.Is(err, org.ErrInvalidWorkspace):
|
||||
http.Error(w, "that workspace is not one of this org's", http.StatusBadRequest)
|
||||
case errors.Is(err, storecontract.ErrSourceInUse):
|
||||
http.Error(w, "an armed binding fires on this source; pause or delete it first", http.StatusConflict)
|
||||
default:
|
||||
@@ -273,3 +282,10 @@ func (s *Server) recentRefusals(r *http.Request) map[string]storecontract.Captur
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// listedIn reports whether a record in ws belongs in a list the request
|
||||
// narrowed with ?workspace=; with none, every record does.
|
||||
func listedIn(r *http.Request, ws org.WorkspaceID) bool {
|
||||
want := r.URL.Query().Get("workspace")
|
||||
return want == "" || org.WorkspaceID(want) == ws
|
||||
}
|
||||
+113
-4
@@ -5,12 +5,14 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// authorize wraps h with the policy chain. A chain that is absent or has not
|
||||
@@ -35,11 +37,18 @@ func (s *Server) authorize(h http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
action, kind, id := accessRequest(r)
|
||||
ctx := org.WithOrg(access.WithPrincipal(r.Context(), principal), principal.Org)
|
||||
// The record's org is not loaded here: org-filtered lookups keep a
|
||||
// record of another org from ever being fetched, and this request's
|
||||
// record (when it has an ID) belongs to the caller's org. The
|
||||
// workspace is likewise the record's, not the route's.
|
||||
resource := access.Resource{Kind: kind, ID: id, Org: principal.Org}
|
||||
// workspace is the record's, not the route's, so it is read.
|
||||
workspace, err := s.recordWorkspace(ctx, kind, id)
|
||||
if err != nil {
|
||||
s.logf("record workspace unavailable", "kind", kind, "id", id, "err", err)
|
||||
http.Error(w, "record unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
resource := access.Resource{Kind: kind, ID: id, Org: principal.Org, Workspace: workspace}
|
||||
decision := s.Access.Authorize(principal, action, resource, access.Context{})
|
||||
if !decision.Allowed {
|
||||
if errors.Is(decision.Err, access.ErrChainUnavailable) {
|
||||
@@ -60,10 +69,109 @@ func (s *Server) authorize(h http.Handler) http.Handler {
|
||||
}
|
||||
// The principal rides the context into every State Store call, which
|
||||
// derives the org it acts in from it.
|
||||
h.ServeHTTP(w, r.WithContext(org.WithOrg(access.WithPrincipal(r.Context(), principal), principal.Org)))
|
||||
h.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// recordWorkspace returns the workspace of the record a request names, so
|
||||
// workspace policies and per-workspace roles decide for it. A request naming
|
||||
// no record, or one the caller's org does not hold, has none: the handler's
|
||||
// own lookup answers not found.
|
||||
func (s *Server) recordWorkspace(ctx context.Context, kind access.ResourceKind, id string) (org.WorkspaceID, error) {
|
||||
if id == "" {
|
||||
return "", nil
|
||||
}
|
||||
switch kind {
|
||||
case access.KindSource:
|
||||
return s.sourceWorkspace(ctx, id)
|
||||
case access.KindBinding:
|
||||
return s.bindingWorkspace(ctx, id)
|
||||
case access.KindMapping:
|
||||
return s.mappingWorkspace(ctx, id)
|
||||
case access.KindEventType:
|
||||
return s.eventTypeWorkspace(ctx, id)
|
||||
case access.KindTask:
|
||||
return s.taskWorkspace(ctx, id)
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (s *Server) sourceWorkspace(ctx context.Context, path string) (org.WorkspaceID, error) {
|
||||
if s.Sources == nil {
|
||||
return "", nil
|
||||
}
|
||||
src, err := s.Sources.GetSource(ctx, path)
|
||||
if src == nil || err != nil {
|
||||
return "", err
|
||||
}
|
||||
return src.WorkspaceID, nil
|
||||
}
|
||||
|
||||
func (s *Server) bindingWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
|
||||
if s.Bindings == nil {
|
||||
return "", nil
|
||||
}
|
||||
b, err := s.Bindings.GetBinding(ctx, id)
|
||||
if b == nil || err != nil {
|
||||
return "", ignoreNotFound(err, storecontract.ErrBindingNotFound)
|
||||
}
|
||||
return b.WorkspaceID, nil
|
||||
}
|
||||
|
||||
func (s *Server) mappingWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
|
||||
if s.Mappings == nil {
|
||||
return "", nil
|
||||
}
|
||||
m, err := s.Mappings.GetMapping(ctx, id)
|
||||
if m == nil || err != nil {
|
||||
return "", ignoreNotFound(err, storecontract.ErrMappingNotFound)
|
||||
}
|
||||
return m.WorkspaceID, nil
|
||||
}
|
||||
|
||||
func (s *Server) eventTypeWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
|
||||
if s.EventTypes == nil {
|
||||
return "", nil
|
||||
}
|
||||
types, err := s.EventTypes.ListEventTypes(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, t := range types {
|
||||
if t.ID == id {
|
||||
return t.WorkspaceID, nil
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (s *Server) taskWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
|
||||
taskID, ok := numericID(id)
|
||||
if s.Store == nil || !ok {
|
||||
return "", nil
|
||||
}
|
||||
t, err := s.Store.TaskByID(ctx, taskID)
|
||||
if t == nil || err != nil {
|
||||
return "", err
|
||||
}
|
||||
return t.Workspace, nil
|
||||
}
|
||||
|
||||
// numericID parses a task route's ID; any other segment names no task.
|
||||
func numericID(id string) (int64, bool) {
|
||||
n, err := strconv.ParseInt(id, 10, 64)
|
||||
return n, err == nil
|
||||
}
|
||||
|
||||
// ignoreNotFound drops the store's not-found answer: a missing record has no
|
||||
// workspace, and the handler reports it.
|
||||
func ignoreNotFound(err, notFound error) error {
|
||||
if errors.Is(err, notFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// refuseUngated answers a request the dashboard cannot authorize because no
|
||||
// policy chain is available. It serves nothing ungated: without a chain the
|
||||
// credential check would be the whole gate and every call would act as the
|
||||
@@ -180,7 +288,8 @@ func routeOverride(action access.Action, path string) (access.Action, access.Res
|
||||
case matchPrefix(path, "/api/chat"):
|
||||
return chatRoute(action)
|
||||
case matchSegment(path, "/api/sources/", "/secret"):
|
||||
return access.ActionUpdate, access.KindSecret, segmentValue(path, 2), true
|
||||
// Rotating a source's secret hands back its value.
|
||||
return access.ActionReadSecret, access.KindSecret, segmentValue(path, 2), true
|
||||
case matchPrefix(path, "/api/harness/terminal"):
|
||||
// Opening the setup terminal updates the binding's secret.
|
||||
return access.ActionUpdate, access.KindSecret, "", true
|
||||
|
||||
@@ -10,6 +10,9 @@ import (
|
||||
"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/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
)
|
||||
|
||||
// operator is the person owner the upgrade creates and the shared-token
|
||||
@@ -230,3 +233,81 @@ func TestPersonalTokensWithoutPerson(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// sourcesIn serves GetSource, the one read authorization makes: one source
|
||||
// per path, in the workspace it names.
|
||||
type sourcesIn struct {
|
||||
storecontract.SourceStore
|
||||
workspaces map[string]org.WorkspaceID
|
||||
}
|
||||
|
||||
func (s sourcesIn) GetSource(_ context.Context, path string) (*source.Source, error) {
|
||||
ws, ok := s.workspaces[path]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &source.Source{Path: path, OrgID: org.DefaultOrgID, WorkspaceID: ws}, nil
|
||||
}
|
||||
|
||||
type principalOf access.Principal
|
||||
|
||||
func (p principalOf) PrincipalFor(context.Context, identity.IdentityID) (access.Principal, error) {
|
||||
return access.Principal(p), nil
|
||||
}
|
||||
|
||||
// TestAuthorizeRecord pins that a request for a record is decided in that
|
||||
// record's scope: its workspace's policies and the role held there, and the
|
||||
// record's own object policies.
|
||||
func TestAuthorizeRecord(t *testing.T) {
|
||||
member := func(id identity.IdentityID, role org.Role, workspaces ...org.Membership) access.Principal {
|
||||
return access.Principal{IdentityID: id, Org: org.DefaultOrgID, Memberships: append([]org.Membership{
|
||||
{IdentityID: id, OrgID: org.DefaultOrgID, Role: role},
|
||||
}, workspaces...)}
|
||||
}
|
||||
dev := member("dev", org.RoleDeveloper, org.Membership{IdentityID: "dev", OrgID: org.DefaultOrgID, WorkspaceID: "locked", Role: org.RoleViewer})
|
||||
ops, admin := member("ops", org.RoleAdmin), member("admin", org.RoleAdmin)
|
||||
policies := append(access.ShippedOrgPolicies(org.DefaultOrgID),
|
||||
access.Policy{
|
||||
ID: "prod-open", Level: access.LevelWorkspace, OrgID: org.DefaultOrgID, WorkspaceID: "prod",
|
||||
Text: `permit(principal, action, resource);`,
|
||||
},
|
||||
access.Policy{
|
||||
ID: "prod-frozen", Level: access.LevelWorkspace, OrgID: org.DefaultOrgID, WorkspaceID: "prod",
|
||||
Text: `forbid(principal, action == Archie::Action::"update", resource);`,
|
||||
},
|
||||
access.Policy{
|
||||
ID: "ops-reads-it", Level: access.LevelObject, OrgID: org.DefaultOrgID, ObjectKind: access.KindSecret, ObjectID: "in-default",
|
||||
Text: `permit(principal, action, resource) when { principal == Archie::Identity::"ops" };`,
|
||||
},
|
||||
)
|
||||
sources := sourcesIn{workspaces: map[string]org.WorkspaceID{
|
||||
"in-default": org.DefaultWorkspaceID, "in-prod": "prod", "in-locked": "locked",
|
||||
}}
|
||||
tests := []struct {
|
||||
name, method, path string
|
||||
principal access.Principal
|
||||
want int
|
||||
}{
|
||||
{"the org role edits a default-workspace record", http.MethodPut, "/api/sources/in-default/name", dev, http.StatusOK},
|
||||
{"a workspace forbid denies the edit there", http.MethodPut, "/api/sources/in-prod/name", dev, http.StatusForbidden},
|
||||
{"the forbid leaves reads alone", http.MethodGet, "/api/sources/in-prod", dev, http.StatusOK},
|
||||
{"a workspace viewer role replaces the org developer role", http.MethodPut, "/api/sources/in-locked/name", dev, http.StatusForbidden},
|
||||
{"the workspace role still reads", http.MethodGet, "/api/sources/in-locked", dev, http.StatusOK},
|
||||
{"a developer does not read a secret", http.MethodPost, "/api/sources/in-prod/secret", dev, http.StatusForbidden},
|
||||
{"an admin reads a secret", http.MethodPost, "/api/sources/in-prod/secret", admin, http.StatusOK},
|
||||
{"an object policy narrows who reads it", http.MethodPost, "/api/sources/in-default/secret", admin, http.StatusForbidden},
|
||||
{"the reader it names still does", http.MethodPost, "/api/sources/in-default/secret", ops, http.StatusOK},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := &Server{Access: infraaccess.New(policies), Principals: principalOf(tt.principal), Sources: sources}
|
||||
handler := s.authorize(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
req := httptest.NewRequestWithContext(WithActingIdentity(t.Context(), identity.Identity{ID: tt.principal.IdentityID}), tt.method, tt.path, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
if rec.Code != tt.want {
|
||||
t.Fatalf("%s %s = %d, want %d", tt.method, tt.path, rec.Code, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user