Files
archie/internal/daemon/kit_task.go
T
sam 416df69b00 feat(egress): credential resolver backed by declared-and-granted run credentials
docs/prds/external-agent-harness.md (Credentials) and orgs-and-access.md:
egress.Resolver had no production implementation, and no run carried a
credential naming the org secrets its identity is granted, so a Kit's
required credential@1 was refused at the proxy and no harness run
authenticated (archie-core-egkf.11).

Two things, as scoped (this does not attempt #1026's full run-credential
consolidation replacing WorktreeGrantIssuer/StateStoreGrantIssuer -- that
PRD item is real, separate, and still open; this is deliberately narrower):

1. A run credential naming granted secrets: config.CredentialBinding maps a
   Kit credential@1 service to a secret; config.Config/IdentityConfig gain
   Org and GrantedCredentials (a per-identity allowlist of service names,
   reusing the existing per-identity config-override pattern DiffCapLines
   already uses, not a new Cedar/Authorizer integration -- KindSecret policy
   objects exist in internal/domain/access but assembling a full Principal
   is #1026's job, not a two-line addition here). config.ContainerConfig.
   BoundCredentials computes the declared (Kit) ∩ granted (identity) ∩
   org-matched intersection Sam's own rule requires: neither side widens
   the other, proven by a mutation-checked test flipping each of the three
   independently.

2. egress.GrantResolver: the production Resolver, holding only what a
   caller explicitly Grant-ed one run, replaced wholesale (not merged) on
   a repeated Grant, gone entirely on RevokeGrant. kitrun.Launcher.Launch
   computes the intersection per launch and resolves real values through
   the existing secret registry (SecretResolver), Grants it before the
   proxy session opens, and Release/error-path rollback (a new shared
   Launcher.release) always revokes it.

Course-corrected mid-implementation (flagged by Sam): credential bindings
first landed as a boot-time config.ContainerConfig.Credentials field
captured once into Launcher.Bindings -- exactly the "parses but is not a
resource" trap CLAUDE.md warns about, and inconsistent with agent-profiles
(#1207) making a Kit profile apply without a restart. Rebuilt as its own
live control-plane resource, CredentialBindingsKind ("credential-bindings"),
following the agent-profiles/container-runtime-policies split precisely:
config.ContainerConfig.Credentials is json:"-", [containers].credentials
is only its seed, and kitrun.Launcher now holds *config.Holder (not a
captured slice) and reads Containers.Credentials fresh on every Launch.
Org/GrantedCredentials were already read fresh per dispatch (d.configFor
inside runKitTask, never cached), so no equivalent fix was needed there.

Deliberately not built: identities and grants as their own State Store
resource (orgs-and-access.md's "Org owns ... identities and their grants").
Identities are entirely config.toml-defined today with no control-plane
resource at all; moving GrantedCredentials alone into one would put half
an identity in two places. That migration is identities' own scope, not
credential bindings'.
2026-09-27 06:14:22 +10:00

113 lines
4.1 KiB
Go

package daemon
import (
"context"
"fmt"
"os"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/infrastructure/kit"
"github.com/samcharles93/archie-core/internal/infrastructure/kitrun"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// KitLauncher starts and ends the container of a task whose agent profile
// is a Kit.
type KitLauncher interface {
Launch(ctx context.Context, req kitrun.Request) (*kitrun.Run, error)
Release(ctx context.Context, run *kitrun.Run) error
RemoveVolumes(ctx context.Context, volumes []kit.Volume) error
}
// runKitTask runs a task in its Kit's container, every agent stage on the
// Kit's harness. The worker reaches NATS and the State Store only through
// the egress relay, and its environment carries no model provider key.
func (d *Daemon) runKitTask(ctx context.Context, task *workflow.Task, repo config.Repo, workDir string, profile config.AgentProfile) {
park := func(reason string, err error) {
d.Log.Error(reason, "task", task.ID, "err", err)
d.parkRunningTask(ctx, task.ID, reason+": "+err.Error(), taskstate.ParkTransient)
}
if d.KitLauncher == nil {
park("kit profile", fmt.Errorf("kit harness runs are unavailable on this daemon"))
return
}
if err := writeTaskBrief(workDir, task); err != nil {
park("task.json write failed", err)
return
}
stateStoreToken, revokeStateStoreGrant, err := d.stateStoreGrantToken(task)
if err != nil {
park("state store grant failed", err)
return
}
defer revokeStateStoreGrant()
env, err := kitrun.WorkerEnv(kitrun.Endpoints{
NATS: d.ConnectedNATS.URL, NATSToken: d.ConnectedNATS.Token,
StateStore: d.ConnectedStateStore.URL, StateStoreToken: stateStoreToken,
}, os.Getuid(), os.Getgid())
if err != nil {
park("kit worker environment", err)
return
}
// The interface is reparsed rather than threaded through pinTaskProfile's
// return: task.WorkflowDefinitionYAML is already pinned by the time this
// runs, parsing it is pure and cheap, and pinTaskProfile's signature stays
// unchanged for its other callers.
iface, err := workflowtask.ParseWorkflowInterface(task.WorkflowDefinitionYAML)
if err != nil {
park("kit workflow interface", err)
return
}
// Org and GrantedServices are the dispatching identity's own facts, read
// fresh here rather than cached anywhere: the same per-task
// config.Config d.configFor already resolves for every other identity
// override (Forge, Budgets, ...).
taskCfg := d.configFor(task)
run, err := d.KitLauncher.Launch(ctx, kitrun.Request{
Execution: fmt.Sprintf("task-%d", task.ID),
Kit: profile.Kit,
Adapter: profile.Adapter,
WorkDir: workDir,
WorkerEnv: env,
GateRetries: iface.Needs.GateRetries,
Org: taskCfg.Org,
GrantedServices: taskCfg.GrantedCredentials,
})
if err != nil {
park("kit launch failed", err)
return
}
limitCtx, stopLimit := withTaskTimeLimit(ctx, d.configFor(task).Budgets.TaskWallClock.Std())
runCtx, stopWatch := withContainerExit(limitCtx, run.Container.Exited())
d.runViaAgent(runCtx, task, repo, profile, &run.Harness)
stopWatch()
stopLimit()
if err := d.KitLauncher.Release(ctx, run); err != nil {
d.Log.Warn("kit release failed", "task", task.ID, "err", err)
}
d.removeEndedKitVolumes(ctx, task.ID, run.Volumes)
}
// removeEndedKitVolumes removes the execution's Kit volumes unless the task
// parked: a retry of a parked task is the same execution and resumes from
// them.
func (d *Daemon) removeEndedKitVolumes(ctx context.Context, taskID int64, volumes []kit.Volume) {
if len(volumes) == 0 || d.Store == nil {
return
}
lookupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
latest, err := d.Store.TaskByID(lookupCtx, taskID)
if err != nil || latest == nil || latest.Status == workflow.StatusParked {
return
}
if err := d.KitLauncher.RemoveVolumes(lookupCtx, volumes); err != nil {
d.Log.Warn("kit volume removal failed", "task", taskID, "err", err)
}
}