fix(identity): use System as the one root identity and record who created every task (#1851)
Drop the bot_user-derived root identity and the empty-identity sentinel. System polls forge connections and owns instance-level work; a polled task stores the polling identity, task_queued and work_request_submitted carry task id, actor and principal, and an empty task identity is refused. Migration 0072 moves empty tasks.identity, the identity-grants root key and the old root's connection permits to System so a re-poll dedups.
This commit is contained in:
36 files changed
+283
-189
No files matched your search
@@ -20,6 +20,7 @@ release's per-component sections are labelled beneath its heading.
|
|||||||
- Execution budgets set in the dashboard are no longer reverted when the model catalogue loads.
|
- Execution budgets set in the dashboard are no longer reverted when the model catalogue loads.
|
||||||
- A full volume is reported as an environment failure, and an unreachable secret engine as unavailable, rather than as a bad or missing credential.
|
- A full volume is reported as an environment failure, and an unreachable secret engine as unavailable, rather than as a bad or missing credential.
|
||||||
- A park from the workflow identity check now appears in the task log.
|
- A park from the workflow identity check now appears in the task log.
|
||||||
|
- Every task records the identity that created it, and its queued event names the task, actor and principal. System is the one instance identity: it polls forge connections and owns the root grants and connection permits the bot-named identity used to hold, which existing tasks, grants and permits move to on upgrade.
|
||||||
|
|
||||||
### archie-ui
|
### archie-ui
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/config"
|
"github.com/samcharles93/archie-core/internal/config"
|
||||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||||
"github.com/samcharles93/archie-core/internal/infrastructure/alertwebhook"
|
"github.com/samcharles93/archie-core/internal/infrastructure/alertwebhook"
|
||||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||||
@@ -173,7 +174,7 @@ func providerAlerts(providers map[string]config.Provider) []alert.Input {
|
|||||||
// instance org always among them.
|
// instance org always among them.
|
||||||
func credentialOrgs(cfg config.Config) []org.OrgID {
|
func credentialOrgs(cfg config.Config) []org.OrgID {
|
||||||
orgs := []org.OrgID{org.DefaultOrgID}
|
orgs := []org.OrgID{org.DefaultOrgID}
|
||||||
for _, name := range append([]string{""}, identityNames(cfg)...) {
|
for _, name := range append([]string{string(identity.SystemID)}, identityNames(cfg)...) {
|
||||||
orgName, _ := cfg.CredentialAccess(name)
|
orgName, _ := cfg.CredentialAccess(name)
|
||||||
if id := org.OrgID(credentialOrg(orgName)); !slices.Contains(orgs, id) {
|
if id := org.OrgID(credentialOrg(orgName)); !slices.Contains(orgs, id) {
|
||||||
orgs = append(orgs, id)
|
orgs = append(orgs, id)
|
||||||
@@ -203,7 +204,7 @@ func credentialOrg(name string) string {
|
|||||||
func unboundAlerts(cfg config.Config) map[org.OrgID][]alert.Input {
|
func unboundAlerts(cfg config.Config) map[org.OrgID][]alert.Input {
|
||||||
out := map[org.OrgID][]alert.Input{}
|
out := map[org.OrgID][]alert.Input{}
|
||||||
seen := map[alert.Key]bool{}
|
seen := map[alert.Key]bool{}
|
||||||
for _, name := range append([]string{""}, identityNames(cfg)...) {
|
for _, name := range append([]string{string(identity.SystemID)}, identityNames(cfg)...) {
|
||||||
orgName, granted := cfg.CredentialAccess(name)
|
orgName, granted := cfg.CredentialAccess(name)
|
||||||
orgID := org.OrgID(credentialOrg(orgName))
|
orgID := org.OrgID(credentialOrg(orgName))
|
||||||
bound := cfg.Containers.BoundCredentials(orgName, granted, granted)
|
bound := cfg.Containers.BoundCredentials(orgName, granted, granted)
|
||||||
|
|||||||
@@ -619,7 +619,6 @@ func (b *boot) buildDaemon() {
|
|||||||
TaskInstructions: b.taskInstructions,
|
TaskInstructions: b.taskInstructions,
|
||||||
IssueSources: b.issueSources,
|
IssueSources: b.issueSources,
|
||||||
OrgPrincipals: b.orgPrincipals,
|
OrgPrincipals: b.orgPrincipals,
|
||||||
RootIdentityID: identity.StableID(servicekit.IdentityNames(b.cfg)[0]),
|
|
||||||
TaskLogs: b.taskLogs,
|
TaskLogs: b.taskLogs,
|
||||||
AgentStatus: b.agentStatus,
|
AgentStatus: b.agentStatus,
|
||||||
WorkflowDefinitions: b.workflowDefinitions,
|
WorkflowDefinitions: b.workflowDefinitions,
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
|
||||||
"github.com/samcharles93/archie-core/internal/config"
|
"github.com/samcharles93/archie-core/internal/config"
|
||||||
"github.com/samcharles93/archie-core/internal/daemon"
|
"github.com/samcharles93/archie-core/internal/daemon"
|
||||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||||
@@ -14,7 +13,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// orgAgents is every organisation with the principals that may act in it,
|
// orgAgents is every organisation with the principals that may act in it,
|
||||||
// system org first. The system org's own root identity leads its list.
|
// system org first. System leads the system org's list.
|
||||||
type orgAgents struct {
|
type orgAgents struct {
|
||||||
owner org.OrgID
|
owner org.OrgID
|
||||||
principals []access.Principal
|
principals []access.Principal
|
||||||
@@ -63,8 +62,7 @@ func (b *boot) organisations(ctx context.Context) []orgAgents {
|
|||||||
for _, owner := range b.owners(ctx, directory) {
|
for _, owner := range b.owners(ctx, directory) {
|
||||||
entry := orgAgents{owner: owner}
|
entry := orgAgents{owner: owner}
|
||||||
if owner == org.DefaultOrgID && directory != nil {
|
if owner == org.DefaultOrgID && directory != nil {
|
||||||
root := identity.StableID(servicekit.IdentityNames(b.cfgHolder.Get())[0])
|
if principal, err := directory.PrincipalFor(ctx, identity.SystemID); err == nil {
|
||||||
if principal, err := directory.PrincipalFor(ctx, root); err == nil {
|
|
||||||
entry.principals = append(entry.principals, principal)
|
entry.principals = append(entry.principals, principal)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -348,20 +348,8 @@ func registerTaskRPCServers(nc *natsio.Conn, resolve func(context.Context, *work
|
|||||||
return resolved.Trees, err
|
return resolved.Trees, err
|
||||||
}}
|
}}
|
||||||
messages := &messagerpc.Server{Runs: runs, Deliver: deliver, Log: log}
|
messages := &messagerpc.Server{Runs: runs, Deliver: deliver, Log: log}
|
||||||
for _, identity := range []string{"", "*"} {
|
for _, register := range []func(*natsio.Conn, string) (func(), error){messages.RegisterFor, fg.RegisterFor, trees.RegisterFor} {
|
||||||
stop, err := messages.RegisterFor(nc, identity)
|
stop, err := register(nc, "*")
|
||||||
if err != nil {
|
|
||||||
unsubscribe()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
unsubs = append(unsubs, stop)
|
|
||||||
stop, err = fg.RegisterFor(nc, identity)
|
|
||||||
if err != nil {
|
|
||||||
unsubscribe()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
unsubs = append(unsubs, stop)
|
|
||||||
stop, err = trees.RegisterFor(nc, identity)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
unsubscribe()
|
unsubscribe()
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/config"
|
"github.com/samcharles93/archie-core/internal/config"
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||||
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
||||||
)
|
)
|
||||||
@@ -41,7 +42,7 @@ func TestEgressResolvesOnlyGrantedCredentials(t *testing.T) {
|
|||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
r := runCredentialResolver{
|
r := runCredentialResolver{
|
||||||
runs: runsByToken{"dashboard-run": {ID: 9, Identity: "new-agent"}, "root-run": {ID: 1}, "acme-run": {ID: 2, Identity: "acme-bot", Org: "acme"}, "acme-row-run": {ID: 3, Org: "acme"}},
|
runs: runsByToken{"dashboard-run": {ID: 9, Identity: "new-agent"}, "root-run": {ID: 1, Identity: string(identity.SystemID)}, "acme-run": {ID: 2, Identity: "acme-bot", Org: "acme"}, "acme-row-run": {ID: 3, Org: "acme"}},
|
||||||
config: config.NewHolder(cfg),
|
config: config.NewHolder(cfg),
|
||||||
secrets: secretValues{"GH": "gh-secret", "ROOT_AI": "root-ai", "ACME_AI": "acme-ai", "ROOT_OPENAI": "root-openai", "ACME_OPENAI": "acme-openai", "ROOT_DEEPSEEK": "root-deepseek"},
|
secrets: secretValues{"GH": "gh-secret", "ROOT_AI": "root-ai", "ACME_AI": "acme-ai", "ROOT_OPENAI": "root-openai", "ACME_OPENAI": "acme-openai", "ROOT_DEEPSEEK": "root-deepseek"},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,16 +2,8 @@ package servicekit
|
|||||||
|
|
||||||
import "github.com/samcharles93/archie-core/internal/config"
|
import "github.com/samcharles93/archie-core/internal/config"
|
||||||
|
|
||||||
// IdentityNames is the agent identities the config names, or the bot user
|
// IdentityNames is the agent identities the config names.
|
||||||
// alone when it names none.
|
|
||||||
func IdentityNames(cfg config.Config) []string {
|
func IdentityNames(cfg config.Config) []string {
|
||||||
if len(cfg.Identities) == 0 {
|
|
||||||
name := cfg.BotUser
|
|
||||||
if name == "" {
|
|
||||||
name = "archie"
|
|
||||||
}
|
|
||||||
return []string{name}
|
|
||||||
}
|
|
||||||
names := make([]string, 0, len(cfg.Identities))
|
names := make([]string, 0, len(cfg.Identities))
|
||||||
for _, value := range cfg.Identities {
|
for _, value := range cfg.Identities {
|
||||||
names = append(names, value.Name)
|
names = append(names, value.Name)
|
||||||
|
|||||||
@@ -267,8 +267,6 @@ func (b *server) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
|
|||||||
deps := staterpc.Deps{
|
deps := staterpc.Deps{
|
||||||
LogFeed: b.logFeed,
|
LogFeed: b.logFeed,
|
||||||
Tasks: b.st, Log: b.log, Grants: grants,
|
Tasks: b.st, Log: b.log, Grants: grants,
|
||||||
// The same root archied dispatches as (servicekit.IdentityNames).
|
|
||||||
RootIdentity: identity.StableID(servicekit.IdentityNames(b.cfg)[0]),
|
|
||||||
}
|
}
|
||||||
if b.pg != nil {
|
if b.pg != nil {
|
||||||
packages := storepkg.Service{
|
packages := storepkg.Service{
|
||||||
|
|||||||
@@ -752,11 +752,11 @@ func (c ContainerConfig) BoundCredentials(org string, granted, declared []string
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CredentialAccess returns the org and granted credential services of the
|
// CredentialAccess returns the org and granted credential services of the
|
||||||
// identity named name: the root's, each overridden by the identity's own when
|
// identity named name: System's, each overridden by the identity's own when
|
||||||
// it sets one. Unknown identities receive no grants.
|
// it sets one. Unknown identities receive no grants.
|
||||||
func (c Config) CredentialAccess(name string) (org string, granted []string) {
|
func (c Config) CredentialAccess(name string) (org string, granted []string) {
|
||||||
org, granted = c.Org, c.GrantedCredentials
|
org, granted = c.Org, c.GrantedCredentials
|
||||||
if name == "" {
|
if name == string(identity.SystemID) {
|
||||||
return credentialOrg(org), granted
|
return credentialOrg(org), granted
|
||||||
}
|
}
|
||||||
for _, id := range c.Identities {
|
for _, id := range c.Identities {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"slices"
|
"slices"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -52,7 +53,7 @@ func TestCredentialAccessGrants(t *testing.T) {
|
|||||||
name, identity string
|
name, identity string
|
||||||
want []string
|
want []string
|
||||||
}{
|
}{
|
||||||
{name: "root identity", want: []string{"root-service"}},
|
{name: "System", identity: string(identity.SystemID), want: []string{"root-service"}},
|
||||||
{name: "configured identity without its own grant inherits the root's", identity: "bot", want: []string{"root-service"}},
|
{name: "configured identity without its own grant inherits the root's", identity: "bot", want: []string{"root-service"}},
|
||||||
{name: "dashboard identity gets its grant", identity: "6f129e29-0e26-5246-99bd-74cb4496203b", want: []string{"github"}},
|
{name: "dashboard identity gets its grant", identity: "6f129e29-0e26-5246-99bd-74cb4496203b", want: []string{"github"}},
|
||||||
{name: "unknown identity gets none", identity: "11111111-1111-5111-8111-111111111111", want: nil},
|
{name: "unknown identity gets none", identity: "11111111-1111-5111-8111-111111111111", want: nil},
|
||||||
|
|||||||
+38
-38
@@ -200,7 +200,6 @@ type Daemon struct {
|
|||||||
// every cycle so suspend/reactivate commands do not require a restart.
|
// every cycle so suspend/reactivate commands do not require a restart.
|
||||||
IdentityRepository identity.Repository
|
IdentityRepository identity.Repository
|
||||||
AgentAssignments org.AgentAssignments
|
AgentAssignments org.AgentAssignments
|
||||||
RootIdentityID identity.IdentityID
|
|
||||||
|
|
||||||
// PackageAuthorities bounds the tools a package workflow's run is offered.
|
// PackageAuthorities bounds the tools a package workflow's run is offered.
|
||||||
PackageAuthorities PackageAuthorities
|
PackageAuthorities PackageAuthorities
|
||||||
@@ -267,14 +266,6 @@ func (d *Daemon) issueSources(ctx context.Context) []IssueSource {
|
|||||||
return d.IssueSources(ctx)
|
return d.IssueSources(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
// sourceTag is the identity a source's tasks carry: empty for the root.
|
|
||||||
func (d *Daemon) sourceTag(source IssueSource) string {
|
|
||||||
if source.Identity == d.RootIdentityID {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return string(source.Identity)
|
|
||||||
}
|
|
||||||
|
|
||||||
// emit publishes an observability event; safe on a nil bus.
|
// emit publishes an observability event; safe on a nil bus.
|
||||||
func (d *Daemon) emit(ctx context.Context, e events.Event) {
|
func (d *Daemon) emit(ctx context.Context, e events.Event) {
|
||||||
if d.Bus != nil {
|
if d.Bus != nil {
|
||||||
@@ -593,9 +584,9 @@ func (d *Daemon) dispatchBindings(ctx context.Context) {
|
|||||||
if d.OrgPrincipals != nil {
|
if d.OrgPrincipals != nil {
|
||||||
principals = d.OrgPrincipals(ctx)
|
principals = d.OrgPrincipals(ctx)
|
||||||
} else {
|
} else {
|
||||||
principal, err := d.Principals.PrincipalFor(ctx, d.RootIdentityID)
|
principal, err := d.Principals.PrincipalFor(ctx, identity.SystemID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
d.Log.WarnContext(ctx, "binding dispatch: principal unavailable", "identity", d.RootIdentityID, "err", err)
|
d.Log.WarnContext(ctx, "binding dispatch: principal unavailable", "identity", identity.SystemID, "err", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
principals = []access.Principal{principal}
|
principals = []access.Principal{principal}
|
||||||
@@ -734,8 +725,8 @@ func (d *Daemon) claimAndEnqueue(ctx context.Context, b binding.Binding, c store
|
|||||||
if target.declared {
|
if target.declared {
|
||||||
body = fmt.Sprintf("Started by binding %q from capture %q; the workflow's inputs travel with the task.", b.Name, c.ID)
|
body = fmt.Sprintf("Started by binding %q from capture %q; the workflow's inputs travel with the task.", b.Name, c.ID)
|
||||||
}
|
}
|
||||||
taskIdentity := ""
|
taskIdentity := string(identity.SystemID)
|
||||||
if principal, ok := access.PrincipalFromContext(ctx); ok && (principal.IdentityID != d.RootIdentityID || principal.Org != org.DefaultOrgID) {
|
if principal, ok := access.PrincipalFromContext(ctx); ok {
|
||||||
taskIdentity = string(principal.IdentityID)
|
taskIdentity = string(principal.IdentityID)
|
||||||
}
|
}
|
||||||
task, err := d.BindingTaskCreator.EnqueueBindingTask(ctx, target.owner, target.repo, title, body, b.Workflow, taskIdentity, b.ID, b.Version, c.ID, target.inputs)
|
task, err := d.BindingTaskCreator.EnqueueBindingTask(ctx, target.owner, target.repo, title, body, b.Workflow, taskIdentity, b.ID, b.Version, c.ID, target.inputs)
|
||||||
@@ -1306,7 +1297,7 @@ func (d *Daemon) poll(ctx context.Context) error {
|
|||||||
if source.Dispatch.Trigger != "" {
|
if source.Dispatch.Trigger != "" {
|
||||||
cfg.Dispatch, cfg.Label = source.Dispatch, source.Label
|
cfg.Dispatch, cfg.Label = source.Dispatch, source.Label
|
||||||
}
|
}
|
||||||
tag := d.sourceTag(source)
|
tag := string(source.Identity)
|
||||||
for _, repo := range source.Repos {
|
for _, repo := range source.Repos {
|
||||||
issues, complete := d.pollIssuesWithConfig(ctx, source.Forge, cfg, repo)
|
issues, complete := d.pollIssuesWithConfig(ctx, source.Forge, cfg, repo)
|
||||||
if complete {
|
if complete {
|
||||||
@@ -1451,7 +1442,10 @@ func (d *Daemon) PublishTask(ctx context.Context, task workintake.TaskEnvelope)
|
|||||||
if err := task.Kind.Validate(); err != nil {
|
if err := task.Kind.Validate(); err != nil {
|
||||||
return fmt.Errorf("publish task %s: %w", task.Ref(), err)
|
return fmt.Errorf("publish task %s: %w", task.Ref(), err)
|
||||||
}
|
}
|
||||||
resolved, err := d.identityOrg(ctx, d.publisherIdentity(task.Identity))
|
if task.Identity == "" {
|
||||||
|
return fmt.Errorf("publish task %s: no identity", task.Ref())
|
||||||
|
}
|
||||||
|
resolved, err := d.identityOrg(ctx, identity.IdentityID(task.Identity))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("publish task %s: resolve org: %w", task.Ref(), err)
|
return fmt.Errorf("publish task %s: resolve org: %w", task.Ref(), err)
|
||||||
}
|
}
|
||||||
@@ -1470,7 +1464,7 @@ func (d *Daemon) PublishReaction(ctx context.Context, reaction workintake.Review
|
|||||||
return fmt.Errorf("publish reaction %s: no task bus configured", reaction.Ref())
|
return fmt.Errorf("publish reaction %s: no task bus configured", reaction.Ref())
|
||||||
}
|
}
|
||||||
if reaction.Org == "" {
|
if reaction.Org == "" {
|
||||||
resolved, err := d.identityOrg(ctx, d.RootIdentityID)
|
resolved, err := d.identityOrg(ctx, identity.SystemID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("publish reaction %s: resolve org: %w", reaction.Ref(), err)
|
return fmt.Errorf("publish reaction %s: resolve org: %w", reaction.Ref(), err)
|
||||||
}
|
}
|
||||||
@@ -1483,15 +1477,6 @@ func (d *Daemon) PublishReaction(ctx context.Context, reaction workintake.Review
|
|||||||
return d.Tasks.PublishUnique(ctx, reaction.Subject(), reaction.IdempotencyKey(), payload)
|
return d.Tasks.PublishUnique(ctx, reaction.Subject(), reaction.IdempotencyKey(), payload)
|
||||||
}
|
}
|
||||||
|
|
||||||
// publisherIdentity is the identity a producer publishes as: the envelope's
|
|
||||||
// identity when it names one, otherwise the root identity.
|
|
||||||
func (d *Daemon) publisherIdentity(ref string) identity.IdentityID {
|
|
||||||
if ref == "" || identity.IdentityID(ref) == d.RootIdentityID || identity.StableID(ref) == d.RootIdentityID {
|
|
||||||
return d.RootIdentityID
|
|
||||||
}
|
|
||||||
return identity.IdentityID(ref)
|
|
||||||
}
|
|
||||||
|
|
||||||
// identityOrg resolves an identity's org. No PrincipalSource means the
|
// identityOrg resolves an identity's org. No PrincipalSource means the
|
||||||
// default org; a store error is returned.
|
// default org; a store error is returned.
|
||||||
func (d *Daemon) identityOrg(ctx context.Context, id identity.IdentityID) (org.OrgID, error) {
|
func (d *Daemon) identityOrg(ctx context.Context, id identity.IdentityID) (org.OrgID, error) {
|
||||||
@@ -1505,7 +1490,7 @@ func (d *Daemon) identityOrg(ctx context.Context, id identity.IdentityID) (org.O
|
|||||||
return principal.Org, nil
|
return principal.Org, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// acknowledge posts the pickup reaction and queued event
|
// acknowledge posts the pickup reaction
|
||||||
// using fg -- the forge client that owns repo (identity-scoped or root) --
|
// using fg -- the forge client that owns repo (identity-scoped or root) --
|
||||||
// and the ack reaction from cfg, the dispatch config that owns this poll.
|
// and the ack reaction from cfg, the dispatch config that owns this poll.
|
||||||
func (d *Daemon) acknowledge(ctx context.Context, fg forge.Forge, cfg config.Config, repo config.Repo, is forge.Issue) {
|
func (d *Daemon) acknowledge(ctx context.Context, fg forge.Forge, cfg config.Config, repo config.Repo, is forge.Issue) {
|
||||||
@@ -1515,10 +1500,22 @@ func (d *Daemon) acknowledge(ctx context.Context, fg forge.Forge, cfg config.Con
|
|||||||
d.Log.WarnContext(ctx, "ack reaction failed", "issue", is.Number, "err", err)
|
d.Log.WarnContext(ctx, "ack reaction failed", "issue", is.Number, "err", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
d.emit(ctx, events.Event{
|
}
|
||||||
Kind: events.KindTaskQueued, Repo: repo.FullName(),
|
|
||||||
Issue: is.Number, Detail: is.Title,
|
// emitTaskQueued records the queued task under the identity that polled it,
|
||||||
})
|
// which is both the actor and the authority the task was created with.
|
||||||
|
func (d *Daemon) emitTaskQueued(ctx context.Context, task *workflow.Task) {
|
||||||
|
e := events.Event{
|
||||||
|
Kind: events.KindTaskQueued, TaskID: task.ID, Repo: task.Owner + "/" + task.Repo,
|
||||||
|
Issue: task.IssueNumber, Detail: task.Title, Attempt: task.Attempt,
|
||||||
|
ActorID: task.Identity, PrincipalID: task.Identity,
|
||||||
|
}
|
||||||
|
if d.IdentityRepository != nil {
|
||||||
|
if value, err := d.IdentityRepository.Get(ctx, identity.IdentityID(task.Identity)); err == nil {
|
||||||
|
e.ActorKind = string(value.Kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d.emit(ctx, e)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Daemon) acceptTaskPublisher(ctx context.Context, msg eventbus.Message, name string) bool {
|
func (d *Daemon) acceptTaskPublisher(ctx context.Context, msg eventbus.Message, name string) bool {
|
||||||
@@ -1591,6 +1588,7 @@ func (d *Daemon) processNATSTask(ctx context.Context, msg eventbus.Message, hold
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
d.emitTaskQueued(ctx, task)
|
||||||
d.process(ctx, task, hold)
|
d.process(ctx, task, hold)
|
||||||
if err := msg.Ack(); err != nil {
|
if err := msg.Ack(); err != nil {
|
||||||
d.Log.WarnContext(ctx, "ack failed", "err", err)
|
d.Log.WarnContext(ctx, "ack failed", "err", err)
|
||||||
@@ -2632,10 +2630,13 @@ func (d *Daemon) captureAttemptConfig(ctx context.Context, task *workflow.Task,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// identityMayAct reports whether a task's identity may act, and the park
|
// identityMayAct reports whether a task's identity may act, and the park
|
||||||
// class if not. Empty is the root identity. An unknown or inactive identity
|
// class if not. An empty, unknown or inactive identity never falls back to
|
||||||
// never falls back to the root forge.
|
// the System forge.
|
||||||
func (d *Daemon) identityMayAct(ctx context.Context, name string) (bool, string, taskstate.ParkClass) {
|
func (d *Daemon) identityMayAct(ctx context.Context, name string) (bool, string, taskstate.ParkClass) {
|
||||||
id := d.publisherIdentity(name)
|
if name == "" {
|
||||||
|
return false, "task has no identity", taskstate.ParkNeedsDecision
|
||||||
|
}
|
||||||
|
id := identity.IdentityID(name)
|
||||||
if d.IdentityRepository != nil {
|
if d.IdentityRepository != nil {
|
||||||
value, err := d.IdentityRepository.Get(ctx, id)
|
value, err := d.IdentityRepository.Get(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -2646,15 +2647,14 @@ func (d *Daemon) identityMayAct(ctx context.Context, name string) (bool, string,
|
|||||||
}
|
}
|
||||||
return true, "", ""
|
return true, "", ""
|
||||||
}
|
}
|
||||||
if name == "" || name == string(d.RootIdentityID) {
|
if name == string(identity.SystemID) {
|
||||||
return true, "", ""
|
return true, "", ""
|
||||||
}
|
}
|
||||||
return false, "identity " + name + " no longer resolves", taskstate.ParkTransient
|
return false, "identity " + name + " no longer resolves", taskstate.ParkTransient
|
||||||
}
|
}
|
||||||
|
|
||||||
// parkIfIdentityUnresolvable parks task when its non-empty identity cannot be
|
// parkIfIdentityUnresolvable parks task when its identity cannot be acted on,
|
||||||
// acted on, reporting whether it did. An empty identity is the root
|
// reporting whether it did.
|
||||||
// single-identity path and never parks here.
|
|
||||||
func (d *Daemon) parkIfIdentityUnresolvable(ctx context.Context, task *workflow.Task) bool {
|
func (d *Daemon) parkIfIdentityUnresolvable(ctx context.Context, task *workflow.Task) bool {
|
||||||
ok, reason, class := d.identityMayAct(ctx, task.Identity)
|
ok, reason, class := d.identityMayAct(ctx, task.Identity)
|
||||||
if ok {
|
if ok {
|
||||||
@@ -2711,7 +2711,7 @@ func (d *Daemon) treesFor(task *workflow.Task) *worktree.Manager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *Daemon) rootTask(task *workflow.Task) bool {
|
func (d *Daemon) rootTask(task *workflow.Task) bool {
|
||||||
return task.Identity == "" || identity.IdentityID(task.Identity) == d.RootIdentityID
|
return identity.IdentityID(task.Identity) == identity.SystemID
|
||||||
}
|
}
|
||||||
|
|
||||||
// repoFor resolves a root task's repo config from Cfg.Repos.
|
// repoFor resolves a root task's repo config from Cfg.Repos.
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ func TestPublishDiscoveredCap(t *testing.T) {
|
|||||||
}
|
}
|
||||||
room := tt.cap
|
room := tt.cap
|
||||||
repo := config.Repo{Owner: "acme", Name: "widget"}
|
repo := config.Repo{Owner: "acme", Name: "widget"}
|
||||||
d.publishDiscovered(t.Context(), nil, config.Config{}, repo, issues, "", &room)
|
d.publishDiscovered(t.Context(), nil, config.Config{}, repo, issues, string(sys), &room)
|
||||||
if bus.published != tt.want {
|
if bus.published != tt.want {
|
||||||
t.Fatalf("published %d tasks, want %d", bus.published, tt.want)
|
t.Fatalf("published %d tasks, want %d", bus.published, tt.want)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/config"
|
"github.com/samcharles93/archie-core/internal/config"
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||||
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||||
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
||||||
@@ -68,7 +69,7 @@ func (d *Daemon) runKitTask(ctx context.Context, task *workflow.Task, repo confi
|
|||||||
// config.Config d.configFor already resolves for every other identity
|
// config.Config d.configFor already resolves for every other identity
|
||||||
// override (Forge, Budgets, ...).
|
// override (Forge, Budgets, ...).
|
||||||
taskCfg := d.configFor(task)
|
taskCfg := d.configFor(task)
|
||||||
credentialOrg, grantedServices := taskCfg.CredentialAccess("")
|
credentialOrg, grantedServices := taskCfg.CredentialAccess(string(identity.SystemID))
|
||||||
var record *egress.RecordOptions
|
var record *egress.RecordOptions
|
||||||
if task.IsTestRun() {
|
if task.IsTestRun() {
|
||||||
record = &egress.RecordOptions{TaskID: task.ID, ModelHosts: modelHosts(d.Cfg.Get().Providers)}
|
record = &egress.RecordOptions{TaskID: task.ID, ModelHosts: modelHosts(d.Cfg.Get().Providers)}
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ func TestOpenModelEgressCarriesOnlyReferencedProviders(t *testing.T) {
|
|||||||
}),
|
}),
|
||||||
ModelEgress: egressProxy,
|
ModelEgress: egressProxy,
|
||||||
}
|
}
|
||||||
task := &workflow.Task{ID: 7, WorkflowDefinitionYAML: "id: w\nsteps:\n - type: agent.run\n"}
|
task := &workflow.Task{ID: 7, Identity: string(sys), WorkflowDefinitionYAML: "id: w\nsteps:\n - type: agent.run\n"}
|
||||||
|
|
||||||
if _, _, err := d.openModelEgress(t.Context(), task, "run-credential"); err != nil {
|
if _, _, err := d.openModelEgress(t.Context(), task, "run-credential"); err != nil {
|
||||||
t.Fatalf("open model egress: %v", err)
|
t.Fatalf("open model egress: %v", err)
|
||||||
@@ -99,7 +99,7 @@ func TestRunViaAgentCarriesProviderCredentialVariable(t *testing.T) {
|
|||||||
Tasks: bus,
|
Tasks: bus,
|
||||||
Log: slog.New(slog.DiscardHandler),
|
Log: slog.New(slog.DiscardHandler),
|
||||||
}
|
}
|
||||||
task := &workflow.Task{ID: 7, Attempt: 1, Workflow: "implement", WorkflowDefinitionYAML: "id: w\nsteps:\n - type: agent.run\n"}
|
task := &workflow.Task{ID: 7, Identity: string(sys), Attempt: 1, Workflow: "implement", WorkflowDefinitionYAML: "id: w\nsteps:\n - type: agent.run\n"}
|
||||||
|
|
||||||
d.runViaAgent(t.Context(), task, config.Repo{}, config.AgentProfile{}, nil, "run-credential")
|
d.runViaAgent(t.Context(), task, config.Repo{}, config.AgentProfile{}, nil, "run-credential")
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package daemon
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log/slog"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/config"
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||||
|
"github.com/samcharles93/archie-core/internal/forge"
|
||||||
|
)
|
||||||
|
|
||||||
|
type labelledIssues struct {
|
||||||
|
forge.Forge
|
||||||
|
issues []forge.Issue
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f labelledIssues) IssuesWithLabel(context.Context, string, string, string) ([]forge.Issue, error) {
|
||||||
|
return f.issues, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (labelledIssues) React(context.Context, string, string, int, string) error { return nil }
|
||||||
|
|
||||||
|
type publishedKeys struct {
|
||||||
|
stubTasks
|
||||||
|
payloads [][]byte
|
||||||
|
keys []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *publishedKeys) PublishUnique(_ context.Context, _, key string, payload []byte) error {
|
||||||
|
p.keys = append(p.keys, key)
|
||||||
|
p.payloads = append(p.payloads, payload)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// migratedRootIdentity is what migration 0072 writes over the empty identity
|
||||||
|
// the root's tasks used to carry. The poller must publish under the same
|
||||||
|
// value, or a re-poll after the migration no longer dedups against the rows.
|
||||||
|
const migratedRootIdentity = "00000000-0000-5000-8000-000000000001"
|
||||||
|
|
||||||
|
// TestPolledTaskKeepsItsCreatingIdentity pins that a polled task is published
|
||||||
|
// under the identity that polled it, never empty, and that System's key is the
|
||||||
|
// one a migrated row carries.
|
||||||
|
func TestPolledTaskKeepsItsCreatingIdentity(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
source identity.IdentityID
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"System poll matches the migrated root", identity.SystemID, migratedRootIdentity},
|
||||||
|
{"named identity poll keeps its identity", "bot-7", "bot-7"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
bus := &publishedKeys{}
|
||||||
|
d := &Daemon{
|
||||||
|
Log: slog.New(slog.DiscardHandler), Store: taskLookup{}, Tasks: bus,
|
||||||
|
Cfg: config.NewHolder(config.Config{}),
|
||||||
|
IssueSources: func(context.Context) []IssueSource {
|
||||||
|
return []IssueSource{{
|
||||||
|
Identity: tt.source,
|
||||||
|
Forge: labelledIssues{issues: []forge.Issue{{Number: 12, Title: "t"}}},
|
||||||
|
Dispatch: config.Dispatch{Trigger: "label"}, Label: "archie",
|
||||||
|
Repos: []config.Repo{{Owner: "acme", Name: "widget"}},
|
||||||
|
}}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if err := d.poll(t.Context()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(bus.payloads) != 1 {
|
||||||
|
t.Fatalf("published %d tasks, want 1", len(bus.payloads))
|
||||||
|
}
|
||||||
|
envelope, err := workintake.DecodeTask(bus.payloads[0])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if envelope.Identity != tt.want {
|
||||||
|
t.Fatalf("published identity %q, want %q", envelope.Identity, tt.want)
|
||||||
|
}
|
||||||
|
want := workintake.TaskEnvelope{Org: "org-sys", Identity: tt.want, Owner: "acme", Repo: "widget", Number: 12}.IdempotencyKey()
|
||||||
|
if bus.keys[0] != want {
|
||||||
|
t.Fatalf("idempotency key %q, want %q", bus.keys[0], want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/config"
|
"github.com/samcharles93/archie-core/internal/config"
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||||
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||||
"github.com/samcharles93/archie-core/internal/forge"
|
"github.com/samcharles93/archie-core/internal/forge"
|
||||||
@@ -42,7 +43,7 @@ func (d *Daemon) Repository(ctx context.Context, task *workflow.Task, operation
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return RepositoryAccess{}, err
|
return RepositoryAccess{}, err
|
||||||
}
|
}
|
||||||
if _, err := d.databaseExecutionIdentity(ctx, &run, d.publisherIdentity(run.Identity)); err != nil {
|
if _, err := d.databaseExecutionIdentity(ctx, &run, identity.IdentityID(run.Identity)); err != nil {
|
||||||
return RepositoryAccess{}, err
|
return RepositoryAccess{}, err
|
||||||
}
|
}
|
||||||
return d.ResolveRepository(ctx, &run, operation)
|
return d.ResolveRepository(ctx, &run, operation)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||||
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||||
"github.com/samcharles93/archie-core/internal/forge"
|
"github.com/samcharles93/archie-core/internal/forge"
|
||||||
@@ -154,7 +155,7 @@ func (d *Daemon) scanPRReviews(ctx context.Context) error {
|
|||||||
func (d *Daemon) scanOnePR(ctx context.Context, reader forge.PullRequestReviewReader, checker forge.WriteAccessChecker, t *workflowtask.Task) bool {
|
func (d *Daemon) scanOnePR(ctx context.Context, reader forge.PullRequestReviewReader, checker forge.WriteAccessChecker, t *workflowtask.Task) bool {
|
||||||
// Resolve the org; on failure skip this task for now.
|
// Resolve the org; on failure skip this task for now.
|
||||||
if t.Org == "" {
|
if t.Org == "" {
|
||||||
resolved, err := d.identityOrg(ctx, d.publisherIdentity(t.Identity))
|
resolved, err := d.identityOrg(ctx, identity.IdentityID(t.Identity))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
d.Log.WarnContext(ctx, "review scan org resolve failed", "task", t.ID, "err", err)
|
d.Log.WarnContext(ctx, "review scan org resolve failed", "task", t.ID, "err", err)
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ import (
|
|||||||
// a poller, or a calling workflow's declared identity) must be permitted run
|
// a poller, or a calling workflow's declared identity) must be permitted run
|
||||||
// on the workflow, and so must the identity the run acts as. A workflow that
|
// on the workflow, and so must the identity the run acts as. A workflow that
|
||||||
// declares no identity is refused: it neither inherits its starter's nor
|
// declares no identity is refused: it neither inherits its starter's nor
|
||||||
// falls back to the root's. It runs before anything that depends on the
|
// falls back to System's. It runs before anything that depends on the
|
||||||
// identity, and reports whether processing may continue; a refusal parks the
|
// identity, and reports whether processing may continue; a refusal parks the
|
||||||
// task.
|
// task.
|
||||||
func (d *Daemon) adoptWorkflowIdentity(ctx context.Context, task *workflow.Task) bool {
|
func (d *Daemon) adoptWorkflowIdentity(ctx context.Context, task *workflow.Task) bool {
|
||||||
@@ -43,7 +43,7 @@ func (d *Daemon) adoptWorkflowIdentity(ctx context.Context, task *workflow.Task)
|
|||||||
d.parkBlockedTask(ctx, task, "workflow "+task.Workflow+": "+err.Error(), pinParkClass(err), parkBlocker(err))
|
d.parkBlockedTask(ctx, task, "workflow "+task.Workflow+": "+err.Error(), pinParkClass(err), parkBlocker(err))
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if allowed, err := d.mayRunWorkflow(ctx, task, d.publisherIdentity(task.Identity)); !allowed {
|
if allowed, err := d.mayRunWorkflow(ctx, task, identity.IdentityID(task.Identity)); !allowed {
|
||||||
d.parkRefusedRun(ctx, task, "the identity that started it may not run workflow "+task.Workflow, err)
|
d.parkRefusedRun(ctx, task, "the identity that started it may not run workflow "+task.Workflow, err)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -58,32 +58,16 @@ func (d *Daemon) adoptWorkflowIdentity(ctx context.Context, task *workflow.Task)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// declaredIdentity resolves a workflow's declared identity to the ID it is
|
// declaredIdentity resolves a workflow's declared identity to the ID it is
|
||||||
// authorized as and the name the task carries while it runs: a configured
|
// authorized as and the name the task carries while it runs.
|
||||||
// identity's name, or empty for the root identity of a single-identity
|
|
||||||
// install.
|
|
||||||
func (d *Daemon) declaredIdentity(ctx context.Context, task *workflow.Task, ref string) (identity.IdentityID, string, error) {
|
func (d *Daemon) declaredIdentity(ctx context.Context, task *workflow.Task, ref string) (identity.IdentityID, string, error) {
|
||||||
var id identity.IdentityID
|
|
||||||
var name string
|
|
||||||
if identity.IdentityID(ref) == d.RootIdentityID || identity.StableID(ref) == d.RootIdentityID {
|
|
||||||
id = d.RootIdentityID
|
|
||||||
} else {
|
|
||||||
id, name = identity.IdentityID(ref), ref
|
|
||||||
}
|
|
||||||
if d.IdentityRepository == nil {
|
if d.IdentityRepository == nil {
|
||||||
if id == d.RootIdentityID {
|
|
||||||
return id, name, nil
|
|
||||||
}
|
|
||||||
return "", "", pinFailure{taskstate.ParkTransient, fmt.Errorf("identity authority unavailable for %s", ref)}
|
return "", "", pinFailure{taskstate.ParkTransient, fmt.Errorf("identity authority unavailable for %s", ref)}
|
||||||
}
|
}
|
||||||
value, err := d.databaseExecutionIdentity(ctx, task, id)
|
value, err := d.databaseExecutionIdentity(ctx, task, identity.IdentityID(ref))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", "", err
|
return "", "", err
|
||||||
}
|
}
|
||||||
|
return value.ID, string(value.ID), nil
|
||||||
if name != "" {
|
|
||||||
name = string(value.ID)
|
|
||||||
}
|
|
||||||
return value.ID, name, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Daemon) databaseExecutionIdentity(ctx context.Context, task *workflow.Task, id identity.IdentityID) (identity.Identity, error) {
|
func (d *Daemon) databaseExecutionIdentity(ctx context.Context, task *workflow.Task, id identity.IdentityID) (identity.Identity, error) {
|
||||||
|
|||||||
@@ -37,12 +37,14 @@ func (principalOf) PrincipalFor(_ context.Context, id identity.IdentityID) (acce
|
|||||||
return access.Principal{IdentityID: id, Org: org.DefaultOrgID}, nil
|
return access.Principal{IdentityID: id, Org: org.DefaultOrgID}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sys = identity.SystemID
|
||||||
|
|
||||||
// agentDirectory knows each agent by name and by ID, all assigned to the
|
// agentDirectory knows each agent by name and by ID, all assigned to the
|
||||||
// system org.
|
// system org.
|
||||||
type agentDirectory struct{ identity.Repository }
|
type agentDirectory struct{ identity.Repository }
|
||||||
|
|
||||||
var directoryAgents = map[identity.IdentityID]identity.IdentityID{
|
var directoryAgents = map[identity.IdentityID]identity.IdentityID{
|
||||||
"root": "root", "deployer": "id-deployer", "id-deployer": "id-deployer", "bot": "id-bot", "id-bot": "id-bot",
|
"deployer": "id-deployer", "id-deployer": "id-deployer", "bot": "id-bot", "id-bot": "id-bot",
|
||||||
}
|
}
|
||||||
|
|
||||||
func (agentDirectory) Get(_ context.Context, ref identity.IdentityID) (identity.Identity, error) {
|
func (agentDirectory) Get(_ context.Context, ref identity.IdentityID) (identity.Identity, error) {
|
||||||
@@ -113,14 +115,14 @@ func TestWorkflowIdentity(t *testing.T) {
|
|||||||
wantDenied []identity.IdentityID
|
wantDenied []identity.IdentityID
|
||||||
disabled bool
|
disabled bool
|
||||||
}{
|
}{
|
||||||
{"allowed dispatch runs as the workflow's identity", deploy, "", runAllowed{"root": true, "id-deployer": true}, "id-deployer", false, "", nil, false},
|
{"allowed dispatch runs as the workflow's identity", deploy, string(sys), runAllowed{sys: true, "id-deployer": true}, "id-deployer", false, "", nil, false},
|
||||||
{"refused invocation is parked", deploy, "", runAllowed{"id-deployer": true}, "", true, taskstate.ParkNeedsDecision, []identity.IdentityID{"root"}, false},
|
{"refused invocation is parked", deploy, string(sys), runAllowed{"id-deployer": true}, "", true, taskstate.ParkNeedsDecision, []identity.IdentityID{sys}, false},
|
||||||
{"refused execution is parked", deploy, "", runAllowed{"root": true}, "", true, taskstate.ParkNeedsDecision, []identity.IdentityID{"id-deployer"}, false},
|
{"refused execution is parked", deploy, string(sys), runAllowed{sys: true}, "", true, taskstate.ParkNeedsDecision, []identity.IdentityID{"id-deployer"}, false},
|
||||||
{"a chain that cannot be read parks transient, not as a denial", deploy, "", unavailableChain{}, "", true, taskstate.ParkTransient, nil, false},
|
{"a chain that cannot be read parks transient, not as a denial", deploy, "", unavailableChain{}, "", true, taskstate.ParkTransient, nil, false},
|
||||||
{"called workflow runs as its own identity, not its caller's", callee, "id-deployer", runAllowed{"id-deployer": true, "id-bot": true}, "id-bot", false, "", nil, false},
|
{"called workflow runs as its own identity, not its caller's", callee, "id-deployer", runAllowed{"id-deployer": true, "id-bot": true}, "id-bot", false, "", nil, false},
|
||||||
{"caller refused the called workflow is parked", callee, "id-deployer", runAllowed{"id-bot": true}, "", true, taskstate.ParkNeedsDecision, []identity.IdentityID{"id-deployer"}, false},
|
{"caller refused the called workflow is parked", callee, "id-deployer", runAllowed{"id-bot": true}, "", true, taskstate.ParkNeedsDecision, []identity.IdentityID{"id-deployer"}, false},
|
||||||
{"no declared identity is refused", "id: deploy\n", "id-bot", runAllowed{"root": true, "id-bot": true}, "", true, taskstate.ParkNeedsDecision, nil, false},
|
{"no declared identity is refused", "id: deploy\n", "id-bot", runAllowed{sys: true, "id-bot": true}, "", true, taskstate.ParkNeedsDecision, nil, false},
|
||||||
{"unconfigured identity is parked", "id: deploy\nidentity: ghost\n", "", runAllowed{"root": true}, "", true, taskstate.ParkNeedsDecision, nil, false},
|
{"unconfigured identity is parked", "id: deploy\nidentity: ghost\n", string(sys), runAllowed{sys: true}, "", true, taskstate.ParkNeedsDecision, nil, false},
|
||||||
{"disabled workflow is parked", deploy, "id-bot", runAllowed{"id-bot": true, "id-deployer": true}, "", true, taskstate.ParkNeedsDecision, nil, true},
|
{"disabled workflow is parked", deploy, "id-bot", runAllowed{"id-bot": true, "id-deployer": true}, "", true, taskstate.ParkNeedsDecision, nil, true},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
@@ -128,7 +130,7 @@ func TestWorkflowIdentity(t *testing.T) {
|
|||||||
store := &identityStore{}
|
store := &identityStore{}
|
||||||
var denied denials
|
var denied denials
|
||||||
d := &Daemon{
|
d := &Daemon{
|
||||||
Store: store, Log: slog.New(slog.DiscardHandler), RootIdentityID: "root",
|
Store: store, Log: slog.New(slog.DiscardHandler),
|
||||||
Access: tt.allowed, Principals: principalOf{}, Denials: &denied,
|
Access: tt.allowed, Principals: principalOf{}, Denials: &denied,
|
||||||
IdentityRepository: agentDirectory{}, AgentAssignments: agentDirectory{},
|
IdentityRepository: agentDirectory{}, AgentAssignments: agentDirectory{},
|
||||||
}
|
}
|
||||||
@@ -176,12 +178,12 @@ func TestWorkflowRunCarriesEventContext(t *testing.T) {
|
|||||||
}{{"valid", true}, {"unsigned", false}, {"", false}} {
|
}{{"valid", true}, {"unsigned", false}, {"", false}} {
|
||||||
t.Run(tt.signature, func(t *testing.T) {
|
t.Run(tt.signature, func(t *testing.T) {
|
||||||
d := &Daemon{
|
d := &Daemon{
|
||||||
Store: &identityStore{}, Log: slog.New(slog.DiscardHandler), RootIdentityID: "root",
|
Store: &identityStore{}, Log: slog.New(slog.DiscardHandler),
|
||||||
Access: signedOnly{runAllowed{"root": true, "id-deployer": true}},
|
Access: signedOnly{runAllowed{sys: true, "id-deployer": true}},
|
||||||
Principals: principalOf{}, IdentityRepository: agentDirectory{}, AgentAssignments: agentDirectory{},
|
Principals: principalOf{}, IdentityRepository: agentDirectory{}, AgentAssignments: agentDirectory{},
|
||||||
}
|
}
|
||||||
task := &workflow.Task{
|
task := &workflow.Task{
|
||||||
ID: 1, Workflow: "deploy", BindingSignature: tt.signature,
|
ID: 1, Identity: string(sys), Workflow: "deploy", BindingSignature: tt.signature,
|
||||||
WorkflowDefinitionYAML: deploy, WorkflowDefinitionDigest: workflow.DigestDefinition(deploy),
|
WorkflowDefinitionYAML: deploy, WorkflowDefinitionDigest: workflow.DigestDefinition(deploy),
|
||||||
}
|
}
|
||||||
if got := d.adoptWorkflowIdentity(context.Background(), task); got != tt.want {
|
if got := d.adoptWorkflowIdentity(context.Background(), task); got != tt.want {
|
||||||
@@ -235,13 +237,13 @@ func TestDashboardExecutionIdentity(t *testing.T) {
|
|||||||
store := &identityStore{}
|
store := &identityStore{}
|
||||||
cfg := config.Config{BotUser: "root-bot", GrantedCredentials: []string{"root-secret"}, Forge: config.Forge{Token: config.SecretRef{Engine: "env", Key: "ROOT"}}, Repos: []config.Repo{{Owner: "acme", Name: "app"}}}
|
cfg := config.Config{BotUser: "root-bot", GrantedCredentials: []string{"root-secret"}, Forge: config.Forge{Token: config.SecretRef{Engine: "env", Key: "ROOT"}}, Repos: []config.Repo{{Owner: "acme", Name: "app"}}}
|
||||||
d := &Daemon{
|
d := &Daemon{
|
||||||
Store: store, Log: slog.New(slog.DiscardHandler), Cfg: config.NewHolder(cfg), RootIdentityID: "root",
|
Store: store, Log: slog.New(slog.DiscardHandler), Cfg: config.NewHolder(cfg),
|
||||||
IdentityRepository: repository, AgentAssignments: assignedAgents{{IdentityID: value.ID, OrgID: tt.assigned}},
|
IdentityRepository: repository, AgentAssignments: assignedAgents{{IdentityID: value.ID, OrgID: tt.assigned}},
|
||||||
Principals: workflowPrincipals{"root": "org-sys", "dashboard-agent": "org-sys"}, Access: runAllowed{"root": true, "dashboard-agent": true},
|
Principals: workflowPrincipals{sys: "org-sys", "dashboard-agent": "org-sys"}, Access: runAllowed{sys: true, "dashboard-agent": true},
|
||||||
}
|
}
|
||||||
definition := "id: deploy\nidentity: dashboard-agent\nrepository: none\n"
|
definition := "id: deploy\nidentity: dashboard-agent\nrepository: none\n"
|
||||||
newTask := func() *workflow.Task {
|
newTask := func() *workflow.Task {
|
||||||
return &workflow.Task{ID: 1, Workflow: "deploy", WorkflowDefinitionYAML: definition, WorkflowDefinitionDigest: workflow.DigestDefinition(definition)}
|
return &workflow.Task{ID: 1, Identity: string(sys), Workflow: "deploy", WorkflowDefinitionYAML: definition, WorkflowDefinitionDigest: workflow.DigestDefinition(definition)}
|
||||||
}
|
}
|
||||||
task := newTask()
|
task := newTask()
|
||||||
ok := d.adoptWorkflowIdentity(context.Background(), task)
|
ok := d.adoptWorkflowIdentity(context.Background(), task)
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ func (d *Daemon) workflowContext(ctx context.Context, task *workflow.Task) (cont
|
|||||||
}
|
}
|
||||||
return ctx, nil
|
return ctx, nil
|
||||||
}
|
}
|
||||||
principal, err := d.principalIn(ctx, d.publisherIdentity(task.Identity), owner)
|
principal, err := d.principalIn(ctx, identity.IdentityID(task.Identity), owner)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, pinFailure{taskstate.ParkTransient, fmt.Errorf("workflow principal: %w", err)}
|
return nil, pinFailure{taskstate.ParkTransient, fmt.Errorf("workflow principal: %w", err)}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -88,9 +88,9 @@ func TestDispatchOrgWorkflows(t *testing.T) {
|
|||||||
{ID: "root", MappingID: "root", Matcher: binding.Matcher{Source: "root"}, OrgID: org.DefaultOrgID, Workflow: "deploy", Status: binding.StatusArmed, Owner: "owner", Repo: "repo"},
|
{ID: "root", MappingID: "root", Matcher: binding.Matcher{Source: "root"}, OrgID: org.DefaultOrgID, Workflow: "deploy", Status: binding.StatusArmed, Owner: "owner", Repo: "repo"},
|
||||||
{ID: "acme", MappingID: "acme", Matcher: binding.Matcher{Source: "acme"}, OrgID: "acme", Workflow: "deploy", Status: binding.StatusArmed},
|
{ID: "acme", MappingID: "acme", Matcher: binding.Matcher{Source: "acme"}, OrgID: "acme", Workflow: "deploy", Status: binding.StatusArmed},
|
||||||
}}
|
}}
|
||||||
d := &Daemon{Cfg: config.NewHolder(config.Config{}), Store: store, Log: slog.New(slog.DiscardHandler), Bindings: store, BindingDispatcher: store, BindingTaskCreator: store, Mappings: store, RootIdentityID: "root", OrgPrincipals: func(context.Context) []access.Principal {
|
d := &Daemon{Cfg: config.NewHolder(config.Config{}), Store: store, Log: slog.New(slog.DiscardHandler), Bindings: store, BindingDispatcher: store, BindingTaskCreator: store, Mappings: store, OrgPrincipals: func(context.Context) []access.Principal {
|
||||||
return []access.Principal{{IdentityID: "root", Org: org.DefaultOrgID}, {IdentityID: "acme-bot", Org: "acme"}}
|
return []access.Principal{{IdentityID: identity.SystemID, Org: org.DefaultOrgID}, {IdentityID: "acme-bot", Org: "acme"}}
|
||||||
}, Principals: workflowPrincipals{"root": org.DefaultOrgID, "acme-bot": "acme"}, WorkflowDefinitions: orgDefinitions{
|
}, Principals: workflowPrincipals{sys: org.DefaultOrgID, "acme-bot": "acme"}, WorkflowDefinitions: orgDefinitions{
|
||||||
org.DefaultOrgID: "id: deploy\nrepository: required\nsteps:\n - type: workflow.finish\n",
|
org.DefaultOrgID: "id: deploy\nrepository: required\nsteps:\n - type: workflow.finish\n",
|
||||||
"acme": "id: deploy\nrepository: none\nsteps:\n - type: workflow.finish\n",
|
"acme": "id: deploy\nrepository: none\nsteps:\n - type: workflow.finish\n",
|
||||||
}}
|
}}
|
||||||
@@ -99,7 +99,7 @@ func TestDispatchOrgWorkflows(t *testing.T) {
|
|||||||
}
|
}
|
||||||
d.dispatchBindings(t.Context())
|
d.dispatchBindings(t.Context())
|
||||||
root := store.started[org.DefaultOrgID]
|
root := store.started[org.DefaultOrgID]
|
||||||
if root == nil || root.Repo != "repo" || root.Identity != "" {
|
if root == nil || root.Repo != "repo" || root.Identity != string(sys) {
|
||||||
t.Fatalf("root dispatch %#v", root)
|
t.Fatalf("root dispatch %#v", root)
|
||||||
}
|
}
|
||||||
acme := store.started["acme"]
|
acme := store.started["acme"]
|
||||||
@@ -146,11 +146,11 @@ func TestPinWorkflowInTaskOrg(t *testing.T) {
|
|||||||
{"unresolved context cannot select another org", "", nil, "", true, "acme"},
|
{"unresolved context cannot select another org", "", nil, "", true, "acme"},
|
||||||
} {
|
} {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
d := &Daemon{Store: listsWorkspaces{&identityStore{}}, RootIdentityID: "bot", WorkflowDefinitions: orgDefinitions{org.DefaultOrgID: shared, "acme": custom}}
|
d := &Daemon{Store: listsWorkspaces{&identityStore{}}, WorkflowDefinitions: orgDefinitions{org.DefaultOrgID: shared, "acme": custom}}
|
||||||
if tc.principals != nil {
|
if tc.principals != nil {
|
||||||
d.Principals = tc.principals
|
d.Principals = tc.principals
|
||||||
}
|
}
|
||||||
task := &workflow.Task{ID: 1, Org: tc.owner, Workflow: "deploy"}
|
task := &workflow.Task{ID: 1, Identity: "bot", Org: tc.owner, Workflow: "deploy"}
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
if tc.contextOrg != "" {
|
if tc.contextOrg != "" {
|
||||||
ctx = org.WithOrg(access.WithPrincipal(ctx, access.Principal{IdentityID: "foreign", Org: tc.contextOrg}), tc.contextOrg)
|
ctx = org.WithOrg(access.WithPrincipal(ctx, access.Principal{IdentityID: "foreign", Org: tc.contextOrg}), tc.contextOrg)
|
||||||
|
|||||||
@@ -87,9 +87,9 @@ type Task struct {
|
|||||||
// Source is "forge", "chat" or "test". Chat tasks have a synthetic IssueNumber and
|
// Source is "forge", "chat" or "test". Chat tasks have a synthetic IssueNumber and
|
||||||
// skip forge operations.
|
// skip forge operations.
|
||||||
Source string `json:"source"`
|
Source string `json:"source"`
|
||||||
// Identity is the identity that started this task: a chat user, a
|
// Identity is the identity that created this task: a chat user, the
|
||||||
// binding's or poller's identity, or a calling workflow's declared
|
// polling identity, a calling workflow's declared identity, or System for
|
||||||
// identity; empty is the root identity. Used to scope /approve and
|
// instance-level work. Never empty. Used to scope /approve and
|
||||||
// /cancel authorization so one identity cannot control another's
|
// /cancel authorization so one identity cannot control another's
|
||||||
// chat-spawned tasks. While the daemon processes the task it holds the
|
// chat-spawned tasks. While the daemon processes the task it holds the
|
||||||
// identity the workflow declares, which is never stored here.
|
// identity the workflow declares, which is never stored here.
|
||||||
|
|||||||
@@ -35,10 +35,9 @@ type TaskEnvelope struct {
|
|||||||
// methods. Callers should use Labels.
|
// methods. Callers should use Labels.
|
||||||
LabelsRaw string `json:"labels"`
|
LabelsRaw string `json:"labels"`
|
||||||
|
|
||||||
// Identity is the archie identity whose forge poll discovered the issue,
|
// Identity is the archie identity whose forge poll discovered the issue.
|
||||||
// empty for single-identity deployments. Carried so the consuming daemon
|
// Carried so the consuming daemon enqueues the task under the right owner.
|
||||||
// enqueues the task under the right owner.
|
Identity string `json:"identity"`
|
||||||
Identity string `json:"identity,omitempty"`
|
|
||||||
|
|
||||||
// Org is the org the identity serves, resolved by the producer before
|
// Org is the org the identity serves, resolved by the producer before
|
||||||
// publishing.
|
// publishing.
|
||||||
|
|||||||
@@ -47,12 +47,8 @@ func Subjects(identity string) []string {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// SubjectFor returns base scoped to identity, or base when identity is
|
// SubjectFor returns base scoped to identity.
|
||||||
// empty.
|
|
||||||
func SubjectFor(identity, base string) string {
|
func SubjectFor(identity, base string) string {
|
||||||
if identity == "" {
|
|
||||||
return base
|
|
||||||
}
|
|
||||||
// Keyed by the identity's ID, not its name: a name may hold characters a
|
// Keyed by the identity's ID, not its name: a name may hold characters a
|
||||||
// subject cannot, and both ends derive the same ID from the name.
|
// subject cannot, and both ends derive the same ID from the name.
|
||||||
return "archie.forge." + string(domainidentity.StableID(identity)) + "." + strings.TrimPrefix(base, "archie.forge.")
|
return "archie.forge." + string(domainidentity.StableID(identity)) + "." + strings.TrimPrefix(base, "archie.forge.")
|
||||||
@@ -395,7 +391,6 @@ type Client struct {
|
|||||||
// Timeout bounds each call when ctx has no deadline of its own.
|
// Timeout bounds each call when ctx has no deadline of its own.
|
||||||
Timeout time.Duration
|
Timeout time.Duration
|
||||||
// Identity scopes this client's calls to one identity's RPC server.
|
// Identity scopes this client's calls to one identity's RPC server.
|
||||||
// Empty uses the root subjects (single-identity deployments).
|
|
||||||
Identity string
|
Identity string
|
||||||
// Credential is the task's run credential, presented on every call.
|
// Credential is the task's run credential, presented on every call.
|
||||||
Credential string
|
Credential string
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/config"
|
"github.com/samcharles93/archie-core/internal/config"
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -13,11 +14,10 @@ import (
|
|||||||
// identity may use. Applied live on each launch.
|
// identity may use. Applied live on each launch.
|
||||||
const IdentityGrantsKind = "identity-grants"
|
const IdentityGrantsKind = "identity-grants"
|
||||||
|
|
||||||
// identityGrants is the document: the root identity's services, and per named
|
// identityGrants is the document: per identity ID the credential services it
|
||||||
// identity a list that replaces the root's. An identity with no entry
|
// may use. System's entry is the default a configured identity with none of
|
||||||
// inherits the root's; an empty list grants none.
|
// its own inherits; an empty list grants none.
|
||||||
type identityGrants struct {
|
type identityGrants struct {
|
||||||
Root []string `json:"root"`
|
|
||||||
Identities map[string][]string `json:"identities,omitempty"`
|
Identities map[string][]string `json:"identities,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ func identityGrantsDefinition() Definition {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func seedIdentityGrants(cfg config.Config) any {
|
func seedIdentityGrants(cfg config.Config) any {
|
||||||
doc := identityGrants{Root: cfg.GrantedCredentials, Identities: map[string][]string{}}
|
doc := identityGrants{Identities: map[string][]string{string(identity.SystemID): cfg.GrantedCredentials}}
|
||||||
for _, id := range cfg.Identities {
|
for _, id := range cfg.Identities {
|
||||||
if id.GrantedCredentials != nil {
|
if id.GrantedCredentials != nil {
|
||||||
doc.Identities[id.Name] = *id.GrantedCredentials
|
doc.Identities[id.Name] = *id.GrantedCredentials
|
||||||
@@ -44,9 +44,6 @@ func seedIdentityGrants(cfg config.Config) any {
|
|||||||
|
|
||||||
func validateIdentityGrants(input []byte) error {
|
func validateIdentityGrants(input []byte) error {
|
||||||
return validateAs(input, func(doc identityGrants) error {
|
return validateAs(input, func(doc identityGrants) error {
|
||||||
if err := validServices("root", doc.Root); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for name, services := range doc.Identities {
|
for name, services := range doc.Identities {
|
||||||
if strings.TrimSpace(name) == "" {
|
if strings.TrimSpace(name) == "" {
|
||||||
return fmt.Errorf("identity grants: an identity name is empty")
|
return fmt.Errorf("identity grants: an identity name is empty")
|
||||||
@@ -88,7 +85,7 @@ func layerCredentials(ctx context.Context, reader controlplanerpc.ResourceReader
|
|||||||
|
|
||||||
// applyIdentityGrants replaces every identity's grants with the document's.
|
// applyIdentityGrants replaces every identity's grants with the document's.
|
||||||
func applyIdentityGrants(out *config.Config, doc identityGrants) {
|
func applyIdentityGrants(out *config.Config, doc identityGrants) {
|
||||||
out.GrantedCredentials = doc.Root
|
out.GrantedCredentials = doc.Identities[string(identity.SystemID)]
|
||||||
out.IdentityGrants = doc.Identities
|
out.IdentityGrants = doc.Identities
|
||||||
for i := range out.Identities {
|
for i := range out.Identities {
|
||||||
if services, ok := doc.Identities[out.Identities[i].Name]; ok {
|
if services, ok := doc.Identities[out.Identities[i].Name]; ok {
|
||||||
|
|||||||
@@ -5,11 +5,12 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/config"
|
"github.com/samcharles93/archie-core/internal/config"
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestIdentityGrantsReplaceTheFiles pins that the stored grants replace the
|
// TestIdentityGrantsReplaceTheFiles pins that the stored grants replace the
|
||||||
// file's: a listed identity gets exactly its list, an unlisted one is left to
|
// file's: a listed identity gets exactly its list, an unlisted one is left to
|
||||||
// inherit the root's (nil), and an empty list grants nothing.
|
// inherit System's (nil), and an empty list grants nothing.
|
||||||
func TestIdentityGrantsReplaceTheFiles(t *testing.T) {
|
func TestIdentityGrantsReplaceTheFiles(t *testing.T) {
|
||||||
fileList := []string{"from-file"}
|
fileList := []string{"from-file"}
|
||||||
cfg := config.Config{
|
cfg := config.Config{
|
||||||
@@ -21,15 +22,14 @@ func TestIdentityGrantsReplaceTheFiles(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
applyIdentityGrants(&cfg, identityGrants{
|
applyIdentityGrants(&cfg, identityGrants{
|
||||||
Root: []string{"github"},
|
Identities: map[string][]string{string(identity.SystemID): {"github"}, "listed": {"anthropic"}, "none": {}},
|
||||||
Identities: map[string][]string{"listed": {"anthropic"}, "none": {}},
|
|
||||||
})
|
})
|
||||||
if !slices.Equal(cfg.GrantedCredentials, []string{"github"}) {
|
if !slices.Equal(cfg.GrantedCredentials, []string{"github"}) {
|
||||||
t.Fatalf("root granted %v", cfg.GrantedCredentials)
|
t.Fatalf("System granted %v", cfg.GrantedCredentials)
|
||||||
}
|
}
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
identity string
|
identity string
|
||||||
want []string // nil means inherit the root
|
want []string // nil means inherit System
|
||||||
}{
|
}{
|
||||||
{"listed", []string{"anthropic"}},
|
{"listed", []string{"anthropic"}},
|
||||||
{"unlisted", nil},
|
{"unlisted", nil},
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
-- System is the one root identity. Tasks that stored '' for the root, the
|
||||||
|
-- identity-grants "root" key and the connection permits of the identity the
|
||||||
|
-- config's bot_user used to seed all move to System, so the poller's new
|
||||||
|
-- identity matches the stored rows and a re-poll dedups.
|
||||||
|
-- The old root is the first identity imported from the config.
|
||||||
|
|
||||||
|
-- +goose Up
|
||||||
|
|
||||||
|
UPDATE tasks SET identity = '00000000-0000-5000-8000-000000000001' WHERE identity = '';
|
||||||
|
ALTER TABLE tasks ADD CONSTRAINT tasks_identity_set CHECK (identity <> '');
|
||||||
|
|
||||||
|
UPDATE resources r
|
||||||
|
SET value = convert_to(m.doc::text, 'UTF8')
|
||||||
|
FROM (
|
||||||
|
SELECT g.org_id, g.kind, (g.v - 'root') || jsonb_build_object('identities',
|
||||||
|
CASE WHEN jsonb_typeof(g.v -> 'identities') = 'object' THEN g.v -> 'identities' ELSE '{}'::jsonb END
|
||||||
|
|| jsonb_build_object('00000000-0000-5000-8000-000000000001',
|
||||||
|
CASE WHEN jsonb_typeof(g.v -> 'root') = 'array' THEN g.v -> 'root' ELSE '[]'::jsonb END)) AS doc
|
||||||
|
FROM (
|
||||||
|
SELECT org_id, kind, convert_from(value, 'UTF8')::jsonb AS v FROM resources WHERE kind = 'identity-grants'
|
||||||
|
) g
|
||||||
|
WHERE g.v ? 'root'
|
||||||
|
) m
|
||||||
|
WHERE r.org_id = m.org_id AND r.kind = m.kind;
|
||||||
|
|
||||||
|
UPDATE resources r
|
||||||
|
SET value = convert_to(m.doc::text, 'UTF8')
|
||||||
|
FROM (
|
||||||
|
SELECT f.org_id, f.kind, (
|
||||||
|
SELECT COALESCE(jsonb_agg(
|
||||||
|
CASE WHEN c -> 'permits' ? old.id THEN jsonb_set(c, '{permits}',
|
||||||
|
((c -> 'permits') - old.id) || jsonb_build_object('00000000-0000-5000-8000-000000000001',
|
||||||
|
(SELECT jsonb_agg(DISTINCT op) FROM jsonb_array_elements_text(
|
||||||
|
COALESCE(c -> 'permits' -> '00000000-0000-5000-8000-000000000001', '[]'::jsonb) || (c -> 'permits' -> old.id)) op)))
|
||||||
|
ELSE c END), '[]'::jsonb)
|
||||||
|
FROM jsonb_array_elements(f.v) c
|
||||||
|
) AS doc
|
||||||
|
FROM (
|
||||||
|
SELECT org_id, kind, convert_from(value, 'UTF8')::jsonb AS v FROM resources WHERE kind = 'forge-connections'
|
||||||
|
) f,
|
||||||
|
(
|
||||||
|
SELECT identity_id AS id FROM identity_events
|
||||||
|
WHERE request_id LIKE 'identity-import:%' AND identity_id <> '00000000-0000-5000-8000-000000000001'
|
||||||
|
ORDER BY id LIMIT 1
|
||||||
|
) old
|
||||||
|
WHERE jsonb_typeof(f.v) = 'array'
|
||||||
|
) m
|
||||||
|
WHERE r.org_id = m.org_id AND r.kind = m.kind;
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
|
||||||
|
ALTER TABLE tasks DROP CONSTRAINT tasks_identity_set;
|
||||||
@@ -358,7 +358,7 @@ func (s *Store) EnsureAgentOrgMembership(ctx context.Context) error {
|
|||||||
// PrincipalFor assembles the access principal for one identity: the org it
|
// PrincipalFor assembles the access principal for one identity: the org it
|
||||||
// serves and its memberships (internal/domain/access). An identity in no org
|
// serves and its memberships (internal/domain/access). An identity in no org
|
||||||
// is the default org with no role, which the shipped role policies never
|
// is the default org with no role, which the shipped role policies never
|
||||||
// permit.
|
// permit. System owns the default org without a membership row.
|
||||||
func (s *Store) PrincipalFor(ctx context.Context, id identity.IdentityID) (access.Principal, error) {
|
func (s *Store) PrincipalFor(ctx context.Context, id identity.IdentityID) (access.Principal, error) {
|
||||||
resolved, err := s.OrgForIdentity(ctx, id)
|
resolved, err := s.OrgForIdentity(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -385,6 +385,9 @@ func (s *Store) PrincipalFor(ctx context.Context, id identity.IdentityID) (acces
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return access.Principal{}, err
|
return access.Principal{}, err
|
||||||
}
|
}
|
||||||
|
if id == identity.SystemID {
|
||||||
|
memberships = access.SharedTokenOwner().Memberships
|
||||||
|
}
|
||||||
return access.Principal{IdentityID: id, Org: resolved, Memberships: memberships, Workspaces: workspaces}, nil
|
return access.Principal{IdentityID: id, Org: resolved, Memberships: memberships, Workspaces: workspaces}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -159,9 +159,16 @@ var (
|
|||||||
_ workflow.Store = (*Store)(nil)
|
_ workflow.Store = (*Store)(nil)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// errTaskIdentity refuses a task nobody created: every task records the
|
||||||
|
// identity that created it.
|
||||||
|
var errTaskIdentity = errors.New("task identity is required")
|
||||||
|
|
||||||
// EnqueueIssue inserts a new queued task for the issue; returns false if the
|
// EnqueueIssue inserts a new queued task for the issue; returns false if the
|
||||||
// issue is already tracked (the idempotency key is owner/repo/number).
|
// issue is already tracked (the idempotency key is owner/repo/number).
|
||||||
func (s *Store) EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels, identity string) (bool, error) {
|
func (s *Store) EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels, identity string) (bool, error) {
|
||||||
|
if identity == "" {
|
||||||
|
return false, errTaskIdentity
|
||||||
|
}
|
||||||
n, err := s.queries().EnqueueIssue(ctx, postgresdb.EnqueueIssueParams{
|
n, err := s.queries().EnqueueIssue(ctx, postgresdb.EnqueueIssueParams{
|
||||||
Owner: owner, Repo: repo, IssueNumber: int64(number),
|
Owner: owner, Repo: repo, IssueNumber: int64(number),
|
||||||
Title: title, Body: body, Labels: labels, Identity: identity,
|
Title: title, Body: body, Labels: labels, Identity: identity,
|
||||||
@@ -179,6 +186,9 @@ func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, w
|
|||||||
}
|
}
|
||||||
|
|
||||||
func insertChatTask(ctx context.Context, q *postgresdb.Queries, owner, repo, title, body, wf, identity, origin, draft string, inputs map[string]any) (*workflow.Task, error) {
|
func insertChatTask(ctx context.Context, q *postgresdb.Queries, owner, repo, title, body, wf, identity, origin, draft string, inputs map[string]any) (*workflow.Task, error) {
|
||||||
|
if identity == "" {
|
||||||
|
return nil, errTaskIdentity
|
||||||
|
}
|
||||||
encoded, err := task.EncodeInputs(inputs)
|
encoded, err := task.EncodeInputs(inputs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ func TestIdentityStartIsAudited(t *testing.T) {
|
|||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
tasks := &auditTasks{failInsert: tt.failInsert}
|
tasks := &auditTasks{failInsert: tt.failInsert}
|
||||||
grants := &TaskGrants{Store: credentials{}}
|
grants := &TaskGrants{Store: credentials{}}
|
||||||
s := &taskGrantServer{server: &server{deps: Deps{Tasks: tasks, Grants: grants, RootIdentity: "root", Identities: executionIdentityRepo{}}}}
|
s := &taskGrantServer{server: &server{deps: Deps{Tasks: tasks, Grants: grants, Identities: executionIdentityRepo{}}}}
|
||||||
ctx := access.WithActor(context.Background(), "archied")
|
ctx := access.WithActor(context.Background(), "archied")
|
||||||
_, err := s.RegisterTaskGrant(ctx, &pb.RegisterTaskGrantRequest{TaskId: 7, Token: token, LifetimeSeconds: 60})
|
_, err := s.RegisterTaskGrant(ctx, &pb.RegisterTaskGrantRequest{TaskId: 7, Token: token, LifetimeSeconds: 60})
|
||||||
live, _ := grants.taskFor(ctx, token)
|
live, _ := grants.taskFor(ctx, token)
|
||||||
|
|||||||
@@ -133,8 +133,6 @@ type Deps struct {
|
|||||||
// serves and its memberships. Optional: nil answers GetPrincipal with
|
// serves and its memberships. Optional: nil answers GetPrincipal with
|
||||||
// codes.Unavailable.
|
// codes.Unavailable.
|
||||||
Principals access.PrincipalSource
|
Principals access.PrincipalSource
|
||||||
// RootIdentity is the identity a task with no identity name runs as.
|
|
||||||
RootIdentity identity.IdentityID
|
|
||||||
// Policies is the stored policy chain.
|
// Policies is the stored policy chain.
|
||||||
// Optional: nil answers the access RPCs with codes.Unavailable. The reset
|
// Optional: nil answers the access RPCs with codes.Unavailable. The reset
|
||||||
// surface is deliberately not an RPC: `archie-state-store access reset` runs on the
|
// surface is deliberately not an RPC: `archie-state-store access reset` runs on the
|
||||||
|
|||||||
@@ -275,11 +275,7 @@ func (s *taskGrantServer) ResolveTaskGrant(ctx context.Context, r *pb.ResolveTas
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, status.Error(codes.Unavailable, "execution identity unavailable")
|
return nil, status.Error(codes.Unavailable, "execution identity unavailable")
|
||||||
}
|
}
|
||||||
route := string(principal)
|
return &pb.ResolveTaskGrantResponse{TaskId: id, ExecutionIdentity: string(principal), PrincipalId: string(principal)}, nil
|
||||||
if principal == s.deps.RootIdentity {
|
|
||||||
route = ""
|
|
||||||
}
|
|
||||||
return &pb.ResolveTaskGrantResponse{TaskId: id, ExecutionIdentity: route, PrincipalId: string(principal)}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// RegisterTaskGrant creates fresh random material at the daemon and registers
|
// RegisterTaskGrant creates fresh random material at the daemon and registers
|
||||||
@@ -402,9 +398,6 @@ func (s *server) executionPrincipal(ctx context.Context, t *task.Task) (identity
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
id := identity.IdentityID(ref)
|
id := identity.IdentityID(ref)
|
||||||
if ref == "" {
|
|
||||||
id = s.deps.RootIdentity
|
|
||||||
}
|
|
||||||
if s.deps.Identities == nil {
|
if s.deps.Identities == nil {
|
||||||
return "", fmt.Errorf("identity authority unavailable")
|
return "", fmt.Errorf("identity authority unavailable")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,15 +18,9 @@ import (
|
|||||||
"github.com/samcharles93/archie-core/internal/natsrpc"
|
"github.com/samcharles93/archie-core/internal/natsrpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SubjectDeliver is the root subject a task's message.send publishes to.
|
// SubjectFor returns the subject a task's message.send publishes to, keyed by
|
||||||
const SubjectDeliver = "archie.message.deliver"
|
// the identity's ID as forgerpc.SubjectFor is.
|
||||||
|
|
||||||
// SubjectFor returns SubjectDeliver scoped to identity, or the root subject
|
|
||||||
// when identity is empty. Keyed by the identity's ID, as forgerpc.SubjectFor is.
|
|
||||||
func SubjectFor(identity string) string {
|
func SubjectFor(identity string) string {
|
||||||
if identity == "" {
|
|
||||||
return SubjectDeliver
|
|
||||||
}
|
|
||||||
return "archie.message." + string(domainidentity.StableID(identity)) + ".deliver"
|
return "archie.message." + string(domainidentity.StableID(identity)) + ".deliver"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -108,7 +102,7 @@ func (s *Server) authorize(ctx context.Context, identity, credential string) (*w
|
|||||||
return nil, fmt.Errorf("message request credential is invalid: %w", err)
|
return nil, fmt.Errorf("message request credential is invalid: %w", err)
|
||||||
}
|
}
|
||||||
switch {
|
switch {
|
||||||
case identity != "" && task.Identity != identity && domainidentity.StableID(task.Identity) != domainidentity.IdentityID(identity):
|
case task.Identity != identity && domainidentity.StableID(task.Identity) != domainidentity.IdentityID(identity):
|
||||||
return nil, errors.New("message request is outside its run's identity")
|
return nil, errors.New("message request is outside its run's identity")
|
||||||
case task.IsTestRun():
|
case task.IsTestRun():
|
||||||
return nil, errors.New("a test run records deliveries instead of performing them")
|
return nil, errors.New("a test run records deliveries instead of performing them")
|
||||||
|
|||||||
@@ -150,7 +150,10 @@ func (a *workflowsAPI) handleWorkRequest(w http.ResponseWriter, r *http.Request)
|
|||||||
http.Error(w, "work request rejected", http.StatusBadRequest)
|
http.Error(w, "work request rejected", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
a.emit(r.Context(), events.Event{Kind: events.KindWorkRequestSubmitted, TaskID: created.ID, Repo: request.Repository, Workflow: request.Workflow, Detail: request.Title})
|
a.emit(r.Context(), events.Event{
|
||||||
|
Kind: events.KindWorkRequestSubmitted, TaskID: created.ID, Repo: request.Repository, Workflow: request.Workflow, Detail: request.Title,
|
||||||
|
ActorID: string(principal.IdentityID), ActorKind: string(principal.Kind), PrincipalID: string(principal.IdentityID),
|
||||||
|
})
|
||||||
w.WriteHeader(http.StatusCreated)
|
w.WriteHeader(http.StatusCreated)
|
||||||
writeJSON(w, map[string]any{"ok": true, "task_id": created.ID})
|
writeJSON(w, map[string]any{"ok": true, "task_id": created.ID})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,12 +23,8 @@ const (
|
|||||||
SubjectPush = "archie.worktree.push"
|
SubjectPush = "archie.worktree.push"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SubjectFor returns base scoped to identity, or base when identity is
|
// SubjectFor returns base scoped to identity.
|
||||||
// empty.
|
|
||||||
func SubjectFor(identity, base string) string {
|
func SubjectFor(identity, base string) string {
|
||||||
if identity == "" {
|
|
||||||
return base
|
|
||||||
}
|
|
||||||
// Keyed by the identity's ID, as forgerpc.SubjectFor is.
|
// Keyed by the identity's ID, as forgerpc.SubjectFor is.
|
||||||
return "archie.worktree." + string(domainidentity.StableID(identity)) + "." + strings.TrimPrefix(base, "archie.worktree.")
|
return "archie.worktree." + string(domainidentity.StableID(identity)) + "." + strings.TrimPrefix(base, "archie.worktree.")
|
||||||
}
|
}
|
||||||
@@ -146,7 +142,6 @@ type Client struct {
|
|||||||
// Timeout bounds each call when ctx has no deadline of its own.
|
// Timeout bounds each call when ctx has no deadline of its own.
|
||||||
Timeout time.Duration
|
Timeout time.Duration
|
||||||
// Identity scopes this client's calls to one identity's RPC server.
|
// Identity scopes this client's calls to one identity's RPC server.
|
||||||
// Empty uses the root subjects (single-identity deployments).
|
|
||||||
Identity string
|
Identity string
|
||||||
Grant string
|
Grant string
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,13 +13,13 @@ import { useSettingsStore } from "@/stores/settings";
|
|||||||
import DraftHint from "./DraftHint.vue";
|
import DraftHint from "./DraftHint.vue";
|
||||||
import KindGate from "./KindGate.vue";
|
import KindGate from "./KindGate.vue";
|
||||||
|
|
||||||
/** The identity-grants document: the default credential services,
|
/** The identity-grants document: credential services per identity ID. The
|
||||||
* and per identity a list that replaces the default. */
|
* System entry is the default; another identity's list replaces it. */
|
||||||
interface IdentityGrants {
|
interface IdentityGrants {
|
||||||
root: string[] | null;
|
identities?: Record<string, string[] | null>;
|
||||||
identities?: Record<string, string[]>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const SYSTEM_ID = "00000000-0000-5000-8000-000000000001";
|
||||||
const KIND = "identity-grants";
|
const KIND = "identity-grants";
|
||||||
const store = useSettingsStore();
|
const store = useSettingsStore();
|
||||||
const org = useOrgStore();
|
const org = useOrgStore();
|
||||||
@@ -35,16 +35,15 @@ const addable = computed(() =>
|
|||||||
org.activeIdentities.filter((a) => a.kind !== "user" && a.kind !== "system" && !(a.id in (grants.value?.identities ?? {}))),
|
org.activeIdentities.filter((a) => a.kind !== "user" && a.kind !== "system" && !(a.id in (grants.value?.identities ?? {}))),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const others = computed(() => Object.entries(grants.value?.identities ?? {}).filter(([id]) => id !== SYSTEM_ID));
|
||||||
|
|
||||||
// Identity ids are free text, so identities are written as whole maps rather
|
// Identity ids are free text, so identities are written as whole maps rather
|
||||||
// than by a dotted per-id path.
|
// than by a dotted per-id path.
|
||||||
function setRoot(services: string[]) {
|
|
||||||
form.value?.api.setFieldValue("root", services);
|
|
||||||
}
|
|
||||||
function setIdentity(id: string, services: string[]) {
|
function setIdentity(id: string, services: string[]) {
|
||||||
form.value?.api.setFieldValue("identities", (prev: Record<string, string[]> | undefined) => ({ ...prev, [id]: services }));
|
form.value?.api.setFieldValue("identities", (prev: Record<string, string[] | null> | undefined) => ({ ...prev, [id]: services }));
|
||||||
}
|
}
|
||||||
function removeIdentity(id: string) {
|
function removeIdentity(id: string) {
|
||||||
form.value?.api.setFieldValue("identities", (prev: Record<string, string[]> | undefined) => {
|
form.value?.api.setFieldValue("identities", (prev: Record<string, string[] | null> | undefined) => {
|
||||||
const { [id]: _, ...rest } = prev ?? {};
|
const { [id]: _, ...rest } = prev ?? {};
|
||||||
return rest;
|
return rest;
|
||||||
});
|
});
|
||||||
@@ -58,14 +57,14 @@ function removeIdentity(id: string) {
|
|||||||
<ItemGroup v-if="grants">
|
<ItemGroup v-if="grants">
|
||||||
<Item as="div" role="listitem" variant="outline" size="sm" class="flex-wrap">
|
<Item as="div" role="listitem" variant="outline" size="sm" class="flex-wrap">
|
||||||
<span class="w-40 shrink-0 text-label max-sm:w-24 max-sm:truncate">Default</span>
|
<span class="w-40 shrink-0 text-label max-sm:w-24 max-sm:truncate">Default</span>
|
||||||
<ToggleGroup class="flex-wrap" type="multiple" variant="outline" size="sm" :model-value="grants.root ?? []" aria-label="Default grants" @update:model-value="(v) => setRoot(v as string[])">
|
<ToggleGroup class="flex-wrap" type="multiple" variant="outline" size="sm" :model-value="grants.identities?.[SYSTEM_ID] ?? []" aria-label="Default grants" @update:model-value="(v) => setIdentity(SYSTEM_ID, v as string[])">
|
||||||
<ToggleGroupItem v-for="service in store.credentialServices" :key="service" :value="service" class="font-mono text-caption">{{ service }}</ToggleGroupItem>
|
<ToggleGroupItem v-for="service in store.credentialServices" :key="service" :value="service" class="font-mono text-caption">{{ service }}</ToggleGroupItem>
|
||||||
</ToggleGroup>
|
</ToggleGroup>
|
||||||
<DraftHint :kind="KIND" path="root" />
|
<DraftHint :kind="KIND" path="identities" />
|
||||||
</Item>
|
</Item>
|
||||||
<Item v-for="(services, id) in grants.identities" :key="id" as="div" role="listitem" variant="outline" size="sm">
|
<Item v-for="[id, services] in others" :key="id" as="div" role="listitem" variant="outline" size="sm">
|
||||||
<span class="w-40 shrink-0 truncate text-label max-sm:w-24">{{ org.identityName(String(id)) }}</span>
|
<span class="w-40 shrink-0 truncate text-label max-sm:w-24">{{ org.identityName(String(id)) }}</span>
|
||||||
<ToggleGroup class="flex-wrap" type="multiple" variant="outline" size="sm" :model-value="services" :aria-label="`${org.identityName(String(id))} grants`" @update:model-value="(v) => setIdentity(String(id), v as string[])">
|
<ToggleGroup class="flex-wrap" type="multiple" variant="outline" size="sm" :model-value="services ?? []" :aria-label="`${org.identityName(String(id))} grants`" @update:model-value="(v) => setIdentity(String(id), v as string[])">
|
||||||
<ToggleGroupItem v-for="service in store.credentialServices" :key="service" :value="service" class="font-mono text-caption">{{ service }}</ToggleGroupItem>
|
<ToggleGroupItem v-for="service in store.credentialServices" :key="service" :value="service" class="font-mono text-caption">{{ service }}</ToggleGroupItem>
|
||||||
</ToggleGroup>
|
</ToggleGroup>
|
||||||
<Button variant="ghost" size="sm" class="ml-auto" :aria-label="`Remove ${org.identityName(String(id))}`" @click="removeIdentity(String(id))"><X /></Button>
|
<Button variant="ghost" size="sm" class="ml-auto" :aria-label="`Remove ${org.identityName(String(id))}`" @click="removeIdentity(String(id))"><X /></Button>
|
||||||
|
|||||||
Reference in new issue
Block a user