build: package the outbound runner and wire guarded startup
35 files changed,
+2,026
−48
.rastrillo/budgets.txt+1 −0AGENTS.md+2 −2Makefile+18 −2cmd/equipo-runner/main.go+54 −9cmd/equipo-runner/main_test.go+13 −0cmd/equipo/main.go+8 −1internal/equipo/app.go+32 −1internal/equipo/config.go+13 −9internal/equipo/connections.go+4 −1internal/equipo/copy.go+6 −0internal/equipo/execution.go+1 −1internal/equipo/execution_startup.go+113 −0internal/equipotest/runner_release_test.go+128 −0internal/equipotest/runner_startup_test.go+159 −0internal/release/manifest.go+33 −0internal/release/manifest.json+14 −0internal/runner/config.go+114 −0internal/runner/config_test.go+134 −0internal/runner/connections.go+136 −0internal/runner/connections_test.go+90 −0internal/runner/enrol.go+149 −0internal/runner/forge/no_effect_test.go+30 −1internal/runner/forge/publisher.go+12 −2internal/runner/http.go+14 −1internal/runner/paseo/client.go+8 −0internal/runner/paseo/client_test.go+10 −0internal/runner/paseo/types.go+19 −15internal/runner/runtime.go+219 −0internal/runner/runtime_test.go+236 −0internal/runner/runtime_workflow.go+190 −0internal/runner/service.go+4 −0internal/runner/workflow.go+2 −1internal/runner/workflow_integration_test.go+33 −1internal/runner/workflow_turn.go+9 −1packaging/equipo-runner.service+18 −0
CI cancelled — superseded by a newer push — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index fe12ec42..43c44f14 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -21,3 +21,4 @@ time internal/runner 75s Task 15 keeps local Git workflow, real sandbox checks, |
| perf GET /live skip Authorized notification stream, bounded to 30 seconds; not a GET screen. |
| perf GET /api/runner/v1/artifacts/{assignment}/{artifact} skip Authenticated runner artifact download, not a browser GET screen. Runner long-poll and blob downloads use POST and are outside the screen inventory. |
| +size internal/runner 5600 - Task 17 keeps the mandated service configuration, enrolment, discovery and production workflow wiring beside the Task 15 supervisor (5221 source lines before final formatting). |
diff --git a/AGENTS.md b/AGENTS.md| index c5cc9742..c5813d75 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -18,8 +18,8 @@ precedence over generic workflows. |
| - Keep migrations additive. App tables belong in `Models` and `Schema`; |
| framework sessions, auth and proof tables belong only in `BootSchema`. |
| - An unknown count must remain unknown. Never turn a query error into zero. |
| -- `NewStore` grants no authority. The execution library remains unopened in |
| - Foundation. No runners, provider calls, repository fetches or dispatch. |
| +- `NewStore` grants no authority. Execution is off unless |
| + `EQUIPO_EXECUTION_ENABLED=1`; runner dispatch uses only the gated paths. |
| ## Boot and interface |
diff --git a/Makefile b/Makefile| index 020b85a9..3e5e3209 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -132,12 +132,17 @@ gitleaks: |
| migration-check: |
| CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$$' -count=1 |
| -runner-adapter-test: |
| +runner-prerequisites: |
| + @test "$$(node --version)" = "v24.19.0" |
| + @test "$$(codex --version)" = "codex-cli 0.165.0" |
| + |
| +runner-adapter-test: runner-prerequisites |
| command -v node |
| command -v npm |
| npm ci --prefix runner/paseo --ignore-scripts --no-audit --no-fund --registry=https://registry.npmjs.org |
| node --test runner/paseo/bridge.test.mjs |
| CGO_ENABLED=0 go test ./internal/runner/paseo -run 'TestPaseo|TestSubscriptionReady' -count=1 |
| + CGO_ENABLED=0 go test ./internal/runner/checks -run '^TestCheckSandbox' -count=1 |
| # ci is the one gate: what a runner executes and what you run before |
| # pushing are the same definition. amadan's runner falls back to this |
| @@ -148,8 +153,19 @@ runner-adapter-test: |
| # declares manifest resources, also add: rastrillo generate --check |
| ci: build vet fmt-check staticcheck govulncheck gitleaks budget test runner-adapter-test migration-check perf |
| -.PHONY: copy-release-check release-runner |
| +.PHONY: copy-release-check release-runner runner-prerequisites |
| copy-release-check: |
| EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$$' -count=1 |
| release-runner: copy-release-check |
| + @test -z "$$(git ls-files --others --exclude-standard)" |
| + @git diff --quiet && git diff --cached --quiet || exit 1 |
| + @$(MAKE) --no-print-directory runner-prerequisites |
| + @mkdir -p releases/equipo-runner-linux-amd64/paseo |
| + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath \ |
| + -ldflags "-s -w -X amadan.net/rastrillo/rastrillo.BuildVersion=$$(git rev-parse --short HEAD)" \ |
| + -o releases/equipo-runner-linux-amd64/equipo-runner ./cmd/equipo-runner |
| + cp runner/paseo/bridge.mjs runner/paseo/package.json runner/paseo/package-lock.json releases/equipo-runner-linux-amd64/paseo/ |
| + npm ci --prefix releases/equipo-runner-linux-amd64/paseo --omit=dev --ignore-scripts --no-audit --no-fund --registry=https://registry.npmjs.org |
| + cp packaging/equipo-runner.service internal/release/manifest.json releases/equipo-runner-linux-amd64/ |
| + @git rev-parse HEAD > releases/equipo-runner-linux-amd64/COMMIT |
diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go| index cc7ad6d3..b52a2545 100644 |
| --- a/cmd/equipo-runner/main.go |
| +++ b/cmd/equipo-runner/main.go |
| @@ -1,24 +1,69 @@ |
| package main |
| import ( |
| - "amadan.net/oficina/equipo/internal/equipo" |
| - "amadan.net/oficina/equipo/internal/runner" |
| "context" |
| + "encoding/json" |
| + "errors" |
| "io" |
| "os" |
| + "os/signal" |
| + "syscall" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/rastrillo/rastrillo" |
| ) |
| func run(ctx context.Context, args []string, input io.Reader, output, errorOutput io.Writer, getenv func(string) string) int { |
| - if len(args) != 1 || args[0] != "tool" { |
| - _, _ = io.WriteString(errorOutput, equipo.CopyToolRejected+"\n") |
| - return 1 |
| + fail := func() int { _, _ = io.WriteString(errorOutput, equipo.CopyRunnerUnavailable+"\n"); return 1 } |
| + if len(args) != 1 { |
| + return fail() |
| + } |
| + if args[0] == "version" { |
| + if json.NewEncoder(output).Encode(struct { |
| + Version string `json:"version"` |
| + Manifest release.Manifest `json:"manifest"` |
| + }{rastrillo.BuildVersion, release.BuildManifest()}) != nil { |
| + return fail() |
| + } |
| + return 0 |
| + } |
| + if args[0] == "tool" { |
| + if runner.ServeTools(ctx, input, output, getenv("EQUIPO_TOOL_SOCKET"), getenv("EQUIPO_TOOL_CAPABILITY_FILE")) != nil { |
| + _, _ = io.WriteString(errorOutput, equipo.CopyToolRejected+"\n") |
| + return 1 |
| + } |
| + return 0 |
| + } |
| + if args[0] != "run" && args[0] != "enrol" && args[0] != "preflight" { |
| + return fail() |
| + } |
| + cfg, err := runner.LoadConfig(getenv) |
| + if err != nil { |
| + return fail() |
| + } |
| + cfg.Copy = equipo.RunnerToolCopy() |
| + switch args[0] { |
| + case "enrol": |
| + err = runner.Enrol(ctx, cfg, output) |
| + case "run": |
| + err = runner.Run(ctx, cfg) |
| + case "preflight": |
| + var reports any |
| + reports, err = runner.Preflight(ctx, cfg) |
| + if err == nil { |
| + err = json.NewEncoder(output).Encode(reports) |
| + } |
| } |
| - if runner.ServeTools(ctx, input, output, getenv("EQUIPO_TOOL_SOCKET"), getenv("EQUIPO_TOOL_CAPABILITY_FILE")) != nil { |
| - _, _ = io.WriteString(errorOutput, equipo.CopyToolRejected+"\n") |
| - return 1 |
| + if err != nil && !errors.Is(err, context.Canceled) { |
| + return fail() |
| } |
| return 0 |
| } |
| func main() { |
| - os.Exit(run(context.Background(), os.Args[1:], os.Stdin, os.Stdout, os.Stderr, os.Getenv)) |
| + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| + code := run(ctx, os.Args[1:], os.Stdin, os.Stdout, os.Stderr, os.Getenv) |
| + stop() |
| + os.Exit(code) |
| } |
diff --git a/cmd/equipo-runner/main_test.go b/cmd/equipo-runner/main_test.go| index bcdf7c24..c144f282 100644 |
| --- a/cmd/equipo-runner/main_test.go |
| +++ b/cmd/equipo-runner/main_test.go |
| @@ -15,3 +15,16 @@ func TestToolVerbClosed(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestRunnerServiceVerbs(t *testing.T) { |
| + for _, verb := range []string{"run", "preflight", "enrol"} { |
| + var out, log bytes.Buffer |
| + if run(context.Background(), []string{verb}, strings.NewReader(""), &out, &log, func(string) string { return "" }) != 1 { |
| + t.Fatal("missing config accepted", verb) |
| + } |
| + } |
| + var out, log bytes.Buffer |
| + if run(context.Background(), []string{"version"}, strings.NewReader(""), &out, &log, func(string) string { return "" }) != 0 || out.Len() == 0 { |
| + t.Fatal("version unavailable") |
| + } |
| +} |
diff --git a/cmd/equipo/main.go b/cmd/equipo/main.go| index f1cef656..0b6c604e 100644 |
| --- a/cmd/equipo/main.go |
| +++ b/cmd/equipo/main.go |
| @@ -1,6 +1,7 @@ |
| package main |
| import ( |
| + "context" |
| "log/slog" |
| "os" |
| "time" |
| @@ -36,7 +37,13 @@ func run(logger *slog.Logger, started time.Time) error { |
| return err |
| } |
| defer d.Close() |
| - mux, err := equipo.App(d, cfg, mail.FromEnv("CARLOS", logger), logger) |
| + store := equipo.NewStore(d) |
| + execution, err := equipo.OpenExecution(context.Background(), d, opts.DBPath, cfg, store) |
| + if err != nil { |
| + return err |
| + } |
| + defer execution.Close() |
| + mux, err := equipo.AppWithExecution(d, cfg, mail.FromEnv("CARLOS", logger), logger, execution) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index a9f6a81d..261301ca 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -25,6 +25,7 @@ import ( |
| ) |
| type application struct { |
| + executionEnabled bool |
| chi.Router |
| live *live.Hub |
| origin string |
| @@ -38,6 +39,16 @@ type application struct { |
| func (a *application) startBackground() *background.Group { |
| a.start.Do(func() { |
| + if a.executionEnabled && a.store.execution != nil { |
| + execution := a.store.execution |
| + a.background.Loop(context.Background(), 5*time.Second, func() { |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + if err := execution.Reconcile(ctx); err != nil { |
| + a.logger.Error(CopyExecutionReconcile, "err", err) |
| + } |
| + }) |
| + } |
| a.background.Loop(context.Background(), time.Hour, func() { |
| if err := a.auth.Sweep(time.Now()); err != nil { |
| a.logger.Error(copyAuthSweep, "err", err) |
| @@ -59,6 +70,26 @@ func App(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (*http.S |
| return Mux(r), nil |
| } |
| +func AppWithExecution(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger, execution *Execution) (*http.ServeMux, error) { |
| + r, err := RouterWithExecution(d, cfg, mailer, logger, execution) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return Mux(r), nil |
| +} |
| +func RouterWithExecution(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger, execution *Execution) (chi.Router, error) { |
| + if !cfg.ExecutionEnabled { |
| + if execution != nil { |
| + return nil, ErrInvalid |
| + } |
| + return Router(d, cfg, mailer, logger) |
| + } |
| + if execution == nil || execution.db != d || execution.store.execution != execution { |
| + return nil, ErrInvalid |
| + } |
| + return RouterWithStore(d, cfg, mailer, logger, execution.store) |
| +} |
| + |
| // Router applies the schema and builds the routes. |
| func Router(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (chi.Router, error) { |
| return RouterWithStore(d, cfg, mailer, logger, NewStore(d)) |
| @@ -98,7 +129,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| if err != nil { |
| return nil, err |
| } |
| - a := &application{Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin} |
| + a := &application{executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin} |
| if cfg.AlwaysOn { |
| a.live, err = live.New(live.Config{Path: "/live", Topics: map[string]live.Allow{"jobs": a.allowJob}, Lifetime: 30 * time.Second}) |
| if err != nil { |
diff --git a/internal/equipo/config.go b/internal/equipo/config.go| index dc58b7b9..e4f24495 100644 |
| --- a/internal/equipo/config.go |
| +++ b/internal/equipo/config.go |
| @@ -9,19 +9,23 @@ import ( |
| ) |
| type Config struct { |
| - AlwaysOn bool |
| - Origin string |
| - InstanceKey string |
| - Owners []string |
| - AllowLoggedMail bool |
| + ExecutionEnabled bool |
| + ExecutionMarkerPath string |
| + AlwaysOn bool |
| + Origin string |
| + InstanceKey string |
| + Owners []string |
| + AllowLoggedMail bool |
| } |
| func LoadConfig(getenv func(string) string) (Config, error) { |
| cfg := Config{ |
| - AlwaysOn: getenv("EQUIPO_ALWAYS_ON") == "1", |
| - Origin: strings.TrimSpace(getenv("EQUIPO_ORIGIN")), |
| - InstanceKey: strings.TrimSpace(getenv("EQUIPO_INSTANCE_KEY")), |
| - AllowLoggedMail: getenv("EQUIPO_ALLOW_LOGGED_MAIL") == "1", |
| + ExecutionEnabled: getenv("EQUIPO_EXECUTION_ENABLED") == "1", |
| + ExecutionMarkerPath: getenv("EQUIPO_EXECUTION_MARKER_PATH"), |
| + AlwaysOn: getenv("EQUIPO_ALWAYS_ON") == "1", |
| + Origin: strings.TrimSpace(getenv("EQUIPO_ORIGIN")), |
| + InstanceKey: strings.TrimSpace(getenv("EQUIPO_INSTANCE_KEY")), |
| + AllowLoggedMail: getenv("EQUIPO_ALLOW_LOGGED_MAIL") == "1", |
| } |
| for _, address := range strings.Split(getenv("EQUIPO_OWNERS"), ",") { |
| if address = strings.ToLower(strings.TrimSpace(address)); address != "" { |
diff --git a/internal/equipo/connections.go b/internal/equipo/connections.go| index 93cd2499..991ce8c7 100644 |
| --- a/internal/equipo/connections.go |
| +++ b/internal/equipo/connections.go |
| @@ -35,7 +35,7 @@ func reportValid(r ConnectionReport) bool { |
| if !((r.Provider == "claude" && r.Family == "claude") || (r.Provider == "codex" && r.Family == "gpt")) { |
| return false |
| } |
| - if r.LocalID == "" || r.Provider == "" || r.ProviderVersion == "" || r.PaseoVersion == "" || r.Family == "" || r.Model == "" || !hexHash(r.IsolationConfigHash) || (r.Kind != "subscription" && r.Kind != "api") || r.AllowanceRemaining < 0 { |
| + if r.LocalID == "" || r.Provider == "" || (r.Available && (r.ProviderVersion == "" || r.PaseoVersion == "")) || r.Family == "" || r.Model == "" || !hexHash(r.IsolationConfigHash) || (r.Kind != "subscription" && r.Kind != "api") || r.AllowanceRemaining < 0 { |
| return false |
| } |
| for _, v := range []string{r.LocalID, r.Provider, r.ProviderVersion, r.PaseoVersion, r.Family, r.Model, r.AccountLabel, r.UnavailableReason, r.Routing.BindingID, r.Routing.AccountID, r.Routing.ObservedAccountID} { |
| @@ -43,6 +43,9 @@ func reportValid(r ConnectionReport) bool { |
| return false |
| } |
| } |
| + if !r.Available { |
| + return routingValid(r) || r.UnavailableReason != "" && r.Routing.BindingID != "" && r.Routing.AccountID != "" && hexHash(r.Routing.CredentialHomeHash) |
| + } |
| return routingValid(r) |
| } |
| func sameProfile(a, b ConnectionReport) bool { |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 3f0125a9..be5fe7e6 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -388,3 +388,9 @@ func PendingRunnerCopy() []string { |
| sort.Strings(keys) |
| return keys |
| } |
| + |
| +// COPY REVIEW REQUIRED: Task 17 runner startup diagnostic. |
| +const CopyRunnerUnavailable = "The runner could not start. Check its local configuration, credentials and capabilities." |
| + |
| +// COPY REVIEW REQUIRED: Task 17 execution reconciliation diagnostic. |
| +const CopyExecutionReconcile = "Execution recovery could not finish." |
diff --git a/internal/equipo/execution.go b/internal/equipo/execution.go| index 8f617ea1..94bbcc7b 100644 |
| --- a/internal/equipo/execution.go |
| +++ b/internal/equipo/execution.go |
| @@ -11,6 +11,7 @@ import ( |
| ) |
| type Execution struct { |
| + lifetime *executionLifetime |
| Core *team.Store |
| store *Store |
| validators RunnerValidators |
| @@ -18,7 +19,6 @@ type Execution struct { |
| } |
| // AttachExecution is a startup operation, before serving requests. |
| -// Production boot stays unattached until runner recovery is wired. |
| func (s *Store) AttachExecution(ctx context.Context, path string, options team.Options) (*Execution, error) { |
| if s == nil || s.db == nil { |
| return nil, ErrUnavailable |
diff --git a/internal/equipo/execution_startup.go b/internal/equipo/execution_startup.go| new file mode 100644 |
| index 00000000..cf8adce5 |
| --- /dev/null |
| +++ b/internal/equipo/execution_startup.go |
| @@ -0,0 +1,113 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "sync" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +type executionLifetime struct { |
| + once sync.Once |
| + lock *os.File |
| + err error |
| +} |
| + |
| +func OpenExecution(ctx context.Context, d *db.DB, path string, cfg Config, store *Store) (*Execution, error) { |
| + if !cfg.ExecutionEnabled { |
| + return nil, nil |
| + } |
| + if d == nil || store == nil || store.db != d || store.execution != nil || !filepath.IsAbs(cfg.ExecutionMarkerPath) || filepath.Clean(cfg.ExecutionMarkerPath) != cfg.ExecutionMarkerPath { |
| + return nil, ErrInvalid |
| + } |
| + database, err := filepath.Abs(path) |
| + if err != nil { |
| + return nil, err |
| + } |
| + // A different directory is the minimum enforceable separation. Deployment |
| + // must preserve this storage independently of database backup and restore. |
| + if filepath.Dir(database) == filepath.Dir(cfg.ExecutionMarkerPath) { |
| + return nil, ErrInvalid |
| + } |
| + dir := filepath.Dir(cfg.ExecutionMarkerPath) |
| + if err = os.MkdirAll(dir, 0700); err != nil { |
| + return nil, err |
| + } |
| + actual, err := filepath.EvalSymlinks(dir) |
| + if err != nil || actual != dir { |
| + return nil, ErrInvalid |
| + } |
| + info, err := os.Stat(dir) |
| + if err != nil || info.Mode().Perm()&0077 != 0 { |
| + return nil, ErrInvalid |
| + } |
| + fd, err := unix.Open(cfg.ExecutionMarkerPath+".startup.lock", unix.O_CREAT|unix.O_RDWR|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600) |
| + if err != nil { |
| + return nil, err |
| + } |
| + lock := os.NewFile(uintptr(fd), cfg.ExecutionMarkerPath+".startup.lock") |
| + if err = unix.Flock(fd, unix.LOCK_EX|unix.LOCK_NB); err != nil { |
| + lock.Close() |
| + return nil, ErrConflict |
| + } |
| + ok := false |
| + defer func() { |
| + if !ok { |
| + lock.Close() |
| + } |
| + }() |
| + if _, err = migrate.Apply(ctx, d, BootSchema); err != nil { |
| + return nil, err |
| + } |
| + if err = store.Bootstrap(ctx, cfg.Owners); err != nil { |
| + return nil, err |
| + } |
| + store.verifiedIsolation = release.BuildManifest().VerifiedIsolationTuples |
| + x, err := store.AttachSupervisedExecution(ctx, path, team.Options{Marker: cfg.ExecutionMarkerPath, Clock: team.RealClock{}, Authority: NewAuthority(store, team.RealClock{})}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + x.lifetime = &executionLifetime{lock: lock} |
| + if _, err = x.Core.Resume(ctx); err != nil { |
| + _ = x.Close() |
| + return nil, err |
| + } |
| + ok = true |
| + return x, nil |
| +} |
| +func (e *Execution) Close() error { |
| + if e == nil { |
| + return nil |
| + } |
| + if e.lifetime == nil { |
| + return e.Core.Close() |
| + } |
| + e.lifetime.once.Do(func() { e.lifetime.err = errors.Join(e.Core.Close(), e.lifetime.lock.Close()); e.store.execution = nil }) |
| + return e.lifetime.err |
| +} |
| + |
| +func (e *Execution) Reconcile(ctx context.Context) error { |
| + if e == nil || e.Core == nil { |
| + return ErrUnavailable |
| + } |
| + status, err := e.Core.Status(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + if status.Quarantine { |
| + return nil |
| + } |
| + if status.AdmissionPaused { |
| + if _, err = e.Core.Resume(ctx); err != nil { |
| + return err |
| + } |
| + } |
| + return e.Sync(ctx) |
| +} |
diff --git a/internal/equipotest/runner_release_test.go b/internal/equipotest/runner_release_test.go| new file mode 100644 |
| index 00000000..e38adbed |
| --- /dev/null |
| +++ b/internal/equipotest/runner_release_test.go |
| @@ -0,0 +1,128 @@ |
| +package equipotest |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/release" |
| + "encoding/json" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestRunnerReleaseContract(t *testing.T) { |
| + raw, err := os.ReadFile("../release/manifest.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var manifest release.Manifest |
| + if err = json.Unmarshal(raw, &manifest); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(manifest, release.BuildManifest()) { |
| + t.Fatal("manifest differs from embedded build") |
| + } |
| + if len(manifest.VerifiedIsolationTuples) != 0 { |
| + t.Fatal("Task 18 has not passed: tuple list must be empty") |
| + } |
| + if manifest.Node != "v24.19.0" || manifest.Codex != "0.165.0" || manifest.PaseoServer != "0.14.0" { |
| + t.Fatal("unpinned dependencies") |
| + } |
| + unit, err := os.ReadFile("../../packaging/equipo-runner.service") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, value := range []string{"Type=simple", "Restart=on-failure", "TimeoutStopSec=45", "KillMode=control-group", "EnvironmentFile=%h/.config/equipo-runner/runner.env", "ExecStart=%h/.local/lib/equipo-runner/equipo-runner run"} { |
| + if !strings.Contains(string(unit), value) { |
| + t.Fatalf("missing service contract: %s", value) |
| + } |
| + } |
| + for _, value := range []string{"0.0.0.0", "sudo ", "ExecStartPost=", "enrol"} { |
| + if strings.Contains(string(unit), value) { |
| + t.Fatalf("unsafe unit %s", value) |
| + } |
| + } |
| +} |
| + |
| +func TestRunnerReleaseContractPackaging(t *testing.T) { |
| + for _, scenario := range []string{"clean", "dirty", "untracked", "node", "codex", "copy"} { |
| + t.Run(scenario, func(t *testing.T) { |
| + root := t.TempDir() |
| + bin := filepath.Join(root, "bin") |
| + executionMust(t, os.Mkdir(bin, 0700)) |
| + for _, name := range []string{"Makefile", "packaging/equipo-runner.service", "internal/release/manifest.json", "runner/paseo/bridge.mjs", "runner/paseo/package.json", "runner/paseo/package-lock.json"} { |
| + raw, err := os.ReadFile("../../" + name) |
| + executionMust(t, err) |
| + executionMust(t, os.MkdirAll(filepath.Dir(filepath.Join(root, name)), 0700)) |
| + executionMust(t, os.WriteFile(filepath.Join(root, name), raw, 0600)) |
| + } |
| + scripts := map[string]string{ |
| + "git": "#!/bin/sh\ncase \"$1\" in diff) [ \"$SCENARIO\" != dirty ];; rev-parse) echo abc1234;; ls-files) if [ \"$SCENARIO\" = untracked ]; then echo unsafe.go; fi;; esac\n", |
| + "go": "#!/bin/sh\ncase \"$1\" in test) [ \"$SCENARIO\" != copy ];; build) printf '%s\\n' \"$GOOS/$GOARCH\" \"$@\" > \"$CAPTURE\"; while [ $# -gt 0 ]; do if [ \"$1\" = -o ]; then shift; touch \"$1\"; fi; shift; done;; esac\n", |
| + "node": "#!/bin/sh\n[ \"$SCENARIO\" != node ] && echo v24.19.0\n", |
| + "codex": "#!/bin/sh\n[ \"$SCENARIO\" != codex ] && echo 'codex-cli 0.165.0'\n", |
| + "npm": "#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$NPM_CAPTURE\"\n", |
| + "systemctl": "#!/bin/sh\nexit 98\n", |
| + "carlos": "#!/bin/sh\nexit 99\n", |
| + } |
| + for name, script := range scripts { |
| + executionMust(t, os.WriteFile(filepath.Join(bin, name), []byte(script), 0700)) |
| + } |
| + capture := filepath.Join(root, "build.args") |
| + cmd := exec.Command("make", "--no-print-directory", "release-runner") |
| + cmd.Dir = root |
| + cmd.Env = []string{"PATH=" + bin + ":/usr/bin:/bin", "SCENARIO=" + scenario, "CAPTURE=" + capture, "NPM_CAPTURE=" + filepath.Join(root, "npm.args")} |
| + out, err := cmd.CombinedOutput() |
| + if scenario != "clean" { |
| + if err == nil { |
| + t.Fatalf("unsafe release accepted %s: %s", scenario, out) |
| + } |
| + if _, err = os.Stat(capture); !os.IsNotExist(err) { |
| + t.Fatal("built before release guards") |
| + } |
| + return |
| + } |
| + if err != nil { |
| + t.Fatalf("release: %v %s", err, out) |
| + } |
| + raw, err := os.ReadFile(capture) |
| + executionMust(t, err) |
| + if !strings.Contains(string(raw), "linux/amd64") || !strings.Contains(string(raw), "BuildVersion=abc1234") { |
| + t.Fatalf("wrong stamped build: %s", raw) |
| + } |
| + npm, err := os.ReadFile(filepath.Join(root, "npm.args")) |
| + executionMust(t, err) |
| + for _, flag := range []string{"ci", "--omit=dev", "--ignore-scripts"} { |
| + if !strings.Contains(string(npm), flag) { |
| + t.Fatal("unlocked package install", string(npm)) |
| + } |
| + } |
| + shipped, err := os.ReadFile(filepath.Join(root, "releases/equipo-runner-linux-amd64/manifest.json")) |
| + executionMust(t, err) |
| + source, err := os.ReadFile(filepath.Join(root, "internal/release/manifest.json")) |
| + executionMust(t, err) |
| + if string(shipped) != string(source) { |
| + t.Fatal("packaged manifest mismatch") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRunnerReleaseContractUnlistedReport(t *testing.T) { |
| + f := connectionStore(t) |
| + f.s = equipo.NewStore(f.d, equipo.WithRunnerClock(f.clock), equipo.WithVerifiedIsolationTuples(release.BuildManifest().VerifiedIsolationTuples)) |
| + executionMust(t, f.s.ReportConnections(connectionContext, f.principal, f.reports)) |
| + rows, err := f.s.Connections(connectionContext, ownerActor) |
| + executionMust(t, err) |
| + for _, row := range rows { |
| + for _, r := range row.Reports { |
| + if r.ReadIsolation { |
| + t.Fatal("unlisted report changed build eligibility") |
| + } |
| + } |
| + } |
| + f.choice(t, "") |
| + f.denied(t, "engineering", "") |
| +} |
diff --git a/internal/equipotest/runner_startup_test.go b/internal/equipotest/runner_startup_test.go| new file mode 100644 |
| index 00000000..72a6db4a |
| --- /dev/null |
| +++ b/internal/equipotest/runner_startup_test.go |
| @@ -0,0 +1,159 @@ |
| +package equipotest |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "context" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestExecutionStartupClosed(t *testing.T) { |
| + d, path := executionDB(t) |
| + executionMust(t, os.Chmod(filepath.Dir(path), 0700)) |
| + s := equipo.NewStore(d) |
| + cfg := testConfig(testOrigin) |
| + marker := filepath.Join(t.TempDir(), "external", "witness") |
| + cfg.ExecutionMarkerPath = marker |
| + x, err := equipo.OpenExecution(context.Background(), d, path, cfg, s) |
| + if err != nil || x != nil { |
| + t.Fatal("disabled execution opened", err) |
| + } |
| + if _, err = os.Stat(filepath.Dir(marker)); !os.IsNotExist(err) { |
| + t.Fatal("disabled execution touched witness") |
| + } |
| + cfg.ExecutionEnabled = true |
| + cfg.ExecutionMarkerPath = "" |
| + if x, err = equipo.OpenExecution(context.Background(), d, path, cfg, s); err == nil || x != nil { |
| + t.Fatal("enabled without external witness") |
| + } |
| + cfg.ExecutionMarkerPath = filepath.Join(filepath.Dir(path), "witness") |
| + if x, err = equipo.OpenExecution(context.Background(), d, path, cfg, s); err == nil || x != nil { |
| + t.Fatal("witness shares database history directory") |
| + } |
| + cfg.ExecutionMarkerPath = marker |
| + x, err = equipo.OpenExecution(context.Background(), d, path, cfg, s) |
| + executionMust(t, err) |
| + defer x.Close() |
| + st, err := x.Core.Status(context.Background()) |
| + executionMust(t, err) |
| + if st.AdmissionPaused || st.Quarantine { |
| + t.Fatalf("fresh enabled startup did not resume: %+v", st) |
| + } |
| + if _, err = equipo.AppWithExecution(d, cfg, &capturingMailer{}, nil, x); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = x.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if scalar(t, d, "SELECT admission_paused FROM service WHERE id=1") != 1 { |
| + t.Fatal("core not closed before database") |
| + } |
| + if err = d.Writer().Ping(); err != nil { |
| + t.Fatal("core closed shared database", err) |
| + } |
| +} |
| +func TestExecutionHibernateWitness(t *testing.T) { |
| + d, path := executionDB(t) |
| + cfg := testConfig(testOrigin) |
| + cfg.ExecutionEnabled = true |
| + cfg.ExecutionMarkerPath = filepath.Join(t.TempDir(), "external", "witness") |
| + open := func() *equipo.Execution { |
| + x, err := equipo.OpenExecution(context.Background(), d, path, cfg, equipo.NewStore(d)) |
| + executionMust(t, err) |
| + return x |
| + } |
| + x := open() |
| + executionMust(t, x.Close()) |
| + oldWitness, err := os.ReadFile(cfg.ExecutionMarkerPath) |
| + executionMust(t, err) |
| + x = open() |
| + st, err := x.Core.Status(context.Background()) |
| + executionMust(t, err) |
| + if st.Quarantine { |
| + t.Fatal("preserved witness quarantined") |
| + } |
| + executionMust(t, x.Close()) |
| + executionMust(t, os.WriteFile(cfg.ExecutionMarkerPath, oldWitness, 0600)) |
| + x = open() |
| + st, err = x.Core.Status(context.Background()) |
| + executionMust(t, err) |
| + if !st.Quarantine || !st.AdmissionPaused { |
| + t.Fatal("mismatched witness admitted dispatch") |
| + } |
| + executionMust(t, x.Close()) |
| + executionMust(t, os.Remove(cfg.ExecutionMarkerPath)) |
| + x = open() |
| + defer x.Close() |
| + st, err = x.Core.Status(context.Background()) |
| + executionMust(t, err) |
| + if !st.Quarantine || !st.AdmissionPaused { |
| + t.Fatal("lost witness admitted dispatch") |
| + } |
| +} |
| + |
| +func TestIsolationAcknowledgementLapsesCreateAndTurn(t *testing.T) { |
| + for _, change := range []string{"removed", "demoted", "provider", "paseo", "configuration"} { |
| + t.Run(change, func(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + q := f.request() |
| + q.RequestID = "before-create" |
| + if _, err := f.x.Mutate(connectionContext, f.principal, "validate", q); err != nil { |
| + t.Fatal(err) |
| + } |
| + switch change { |
| + case "removed": |
| + mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", ownerAddress) |
| + case "demoted": |
| + mustSQL(t, f.d, "UPDATE members SET role='member' WHERE address=?", ownerAddress) |
| + default: |
| + reports := append([]equipo.ConnectionReport(nil), f.reports...) |
| + switch change { |
| + case "provider": |
| + reports[1].ProviderVersion = "next" |
| + case "paseo": |
| + reports[1].PaseoVersion = "next" |
| + case "configuration": |
| + reports[1].IsolationConfigHash = strings.Repeat("c", 64) |
| + } |
| + executionMust(t, f.s.ReportConnections(connectionContext, f.principal, reports)) |
| + } |
| + for _, phase := range []string{"before-create", "before-turn"} { |
| + q.RequestID = phase |
| + if _, err := f.x.Mutate(connectionContext, f.principal, "validate", q); err == nil { |
| + t.Fatal("stale acknowledgement authorized", phase) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestExecutionStartupReconciliation(t *testing.T) { |
| + d, path := executionDB(t) |
| + s := equipo.NewStore(d) |
| + cfg := testConfig(testOrigin) |
| + cfg.ExecutionEnabled = true |
| + cfg.ExecutionMarkerPath = filepath.Join(t.TempDir(), "external/witness") |
| + x, err := equipo.OpenExecution(context.Background(), d, path, cfg, s) |
| + executionMust(t, err) |
| + defer x.Close() |
| + executionMust(t, x.Core.Pause(context.Background(), "test recovery")) |
| + executionMust(t, x.Reconcile(context.Background())) |
| + status, err := x.Core.Status(context.Background()) |
| + executionMust(t, err) |
| + if !status.Quarantine { |
| + t.Fatal("reconciler released quarantine") |
| + } |
| + _, err = x.Core.Resume(context.Background()) |
| + executionMust(t, err) |
| + snapshot, err := x.Core.RecoverySnapshot(context.Background()) |
| + executionMust(t, err) |
| + executionMust(t, s.ReleaseExecution(context.Background(), ownerActor, snapshot.Revision, "reviewed", snapshot.Hash)) |
| + executionMust(t, x.Reconcile(context.Background())) |
| + status, err = x.Core.Status(context.Background()) |
| + executionMust(t, err) |
| + if status.AdmissionPaused || status.Quarantine { |
| + t.Fatal("owner release was not revalidated") |
| + } |
| +} |
diff --git a/internal/release/manifest.go b/internal/release/manifest.go| new file mode 100644 |
| index 00000000..e7802b07 |
| --- /dev/null |
| +++ b/internal/release/manifest.go |
| @@ -0,0 +1,33 @@ |
| +package release |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + _ "embed" |
| + "encoding/json" |
| +) |
| + |
| +//go:embed manifest.json |
| +var manifest string |
| + |
| +type Manifest struct { |
| + Schema int `json:"schema"` |
| + RunnerTarget string `json:"runner_target"` |
| + InstanceTarget string `json:"instance_target"` |
| + Go string `json:"go"` |
| + Node string `json:"node"` |
| + Codex string `json:"codex"` |
| + Claude string `json:"claude"` |
| + PaseoClient string `json:"paseo_client"` |
| + PaseoProtocol string `json:"paseo_protocol"` |
| + PaseoServer string `json:"paseo_server"` |
| + VerifiedIsolationTuples []team.IsolationTuple `json:"verified_isolation_tuples"` |
| + GateEvidence []string `json:"gate_evidence"` |
| +} |
| + |
| +func BuildManifest() Manifest { |
| + var value Manifest |
| + if err := json.Unmarshal([]byte(manifest), &value); err != nil { |
| + panic(err) |
| + } |
| + return value |
| +} |
diff --git a/internal/release/manifest.json b/internal/release/manifest.json| new file mode 100644 |
| index 00000000..004eacc8 |
| --- /dev/null |
| +++ b/internal/release/manifest.json |
| @@ -0,0 +1,14 @@ |
| +{ |
| + "schema": 1, |
| + "runner_target": "linux/amd64", |
| + "instance_target": "linux/arm64", |
| + "go": "go1.26.10", |
| + "node": "v24.19.0", |
| + "codex": "0.165.0", |
| + "claude": "2.1.312", |
| + "paseo_client": "0.14.0", |
| + "paseo_protocol": "0.14.0", |
| + "paseo_server": "0.14.0", |
| + "verified_isolation_tuples": [], |
| + "gate_evidence": [] |
| +} |
diff --git a/internal/runner/config.go b/internal/runner/config.go| new file mode 100644 |
| index 00000000..917ef82c |
| --- /dev/null |
| +++ b/internal/runner/config.go |
| @@ -0,0 +1,114 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "net" |
| + "net/url" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +type Config struct { |
| + Origin, StateDir, PaseoHome, NodePath, BridgePath, AmadanCredentialPath, AccountBindingsPath, CodexPath string |
| + GoRoot, GoBinary, WorkspaceRoot, ScratchRoot, GitPath, Executable string |
| + PaseoEndpoint, PaseoServerID, InstanceID string |
| + Copy ToolCopy |
| +} |
| + |
| +func LoadConfig(getenv func(string) string) (Config, error) { |
| + c := Config{Origin: getenv("EQUIPO_ORIGIN"), StateDir: getenv("EQUIPO_RUNNER_STATE_DIR"), PaseoHome: getenv("EQUIPO_PASEO_HOME"), NodePath: getenv("EQUIPO_NODE_PATH"), BridgePath: getenv("EQUIPO_BRIDGE_PATH"), AmadanCredentialPath: getenv("EQUIPO_AMADAN_CREDENTIAL_PATH"), AccountBindingsPath: getenv("EQUIPO_ACCOUNT_BINDINGS_PATH"), CodexPath: getenv("EQUIPO_CODEX_PATH"), GoRoot: getenv("EQUIPO_GO_ROOT"), GoBinary: getenv("EQUIPO_GO_BINARY"), WorkspaceRoot: getenv("EQUIPO_WORKSPACE_ROOT"), ScratchRoot: getenv("EQUIPO_SCRATCH_ROOT"), GitPath: getenv("EQUIPO_GIT_PATH"), Executable: getenv("EQUIPO_RUNNER_EXECUTABLE"), PaseoEndpoint: getenv("EQUIPO_PASEO_ENDPOINT"), PaseoServerID: getenv("EQUIPO_PASEO_SERVER_ID"), InstanceID: getenv("EQUIPO_INSTANCE_ID")} |
| + return c, c.validate() |
| +} |
| +func validOrigin(origin string) bool { |
| + u, err := url.Parse(origin) |
| + return err == nil && u.Host != "" && u.User == nil && u.Path == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && !strings.Contains(origin, "#") && (u.Scheme == "https" || (u.Scheme == "http" && u.Hostname() == "127.0.0.1")) |
| +} |
| +func (c Config) validate() error { |
| + if !validOrigin(c.Origin) || c.InstanceID == "" || c.PaseoServerID == "" { |
| + return paseo.ErrContract |
| + } |
| + host, port, err := net.SplitHostPort(c.PaseoEndpoint) |
| + if err != nil || host != "127.0.0.1" || port == "" { |
| + return paseo.ErrContract |
| + } |
| + for _, p := range []string{c.StateDir, c.PaseoHome, c.NodePath, c.BridgePath, c.AmadanCredentialPath, c.AccountBindingsPath, c.CodexPath, c.GoRoot, c.GoBinary, c.WorkspaceRoot, c.ScratchRoot, c.GitPath, c.Executable} { |
| + if !filepath.IsAbs(p) || filepath.Clean(p) != p || p == "/" { |
| + return paseo.ErrContract |
| + } |
| + } |
| + for _, p := range []string{c.WorkspaceRoot, c.ScratchRoot, c.PaseoHome} { |
| + if containsPath(c.StateDir, p) || containsPath(p, c.StateDir) { |
| + return paseo.ErrPolicy |
| + } |
| + } |
| + return nil |
| +} |
| +func containsPath(root, path string) bool { |
| + r, err := filepath.Rel(root, path) |
| + return err == nil && (r == "." || r != ".." && !strings.HasPrefix(r, "../")) |
| +} |
| +func lockState(dir string) (*os.File, error) { |
| + if !filepath.IsAbs(dir) || filepath.Clean(dir) != dir { |
| + return nil, paseo.ErrPolicy |
| + } |
| + if err := os.MkdirAll(dir, 0700); err != nil { |
| + return nil, err |
| + } |
| + real, err := filepath.EvalSymlinks(dir) |
| + if err != nil || real != dir { |
| + return nil, paseo.ErrPolicy |
| + } |
| + info, err := os.Stat(dir) |
| + if err != nil || info.Mode().Perm() != 0700 { |
| + return nil, paseo.ErrPolicy |
| + } |
| + fd, err := unix.Open(filepath.Join(dir, "runner.lock"), unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0600) |
| + if err != nil { |
| + return nil, err |
| + } |
| + f := os.NewFile(uintptr(fd), "runner.lock") |
| + if err = unix.Flock(fd, unix.LOCK_EX|unix.LOCK_NB); err != nil { |
| + f.Close() |
| + return nil, paseo.ErrUncertain |
| + } |
| + return f, nil |
| +} |
| +func privateJSON(path string, out any) error { |
| + info, err := os.Lstat(path) |
| + if err != nil { |
| + return err |
| + } |
| + if !info.Mode().IsRegular() || info.Mode().Perm() != 0600 || info.Size() > 1<<20 { |
| + return paseo.ErrPolicy |
| + } |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return err |
| + } |
| + defer f.Close() |
| + return runnerproto.DecodeLimit(f, out, 1<<20) |
| +} |
| +func readCredentials(path string) (runnerproto.CredentialRotation, error) { |
| + var value runnerproto.CredentialRotation |
| + err := privateJSON(path, &value) |
| + if err == nil && value.Bearer.Token == "" { |
| + err = paseo.ErrIdentity |
| + } |
| + return value, err |
| +} |
| +func checkNode(ctx context.Context, path string) error { |
| + cmd := exec.CommandContext(ctx, path, "--version") |
| + cmd.Env = []string{"PATH=/usr/bin:/bin"} |
| + raw, err := cmd.Output() |
| + if err != nil || strings.TrimSpace(string(raw)) != release.BuildManifest().Node { |
| + return paseo.ErrContract |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/config_test.go b/internal/runner/config_test.go| new file mode 100644 |
| index 00000000..6221073e |
| --- /dev/null |
| +++ b/internal/runner/config_test.go |
| @@ -0,0 +1,134 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "crypto/x509" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func configFixture(t *testing.T) Config { |
| + t.Helper() |
| + root := t.TempDir() |
| + return Config{Origin: "https://equipo.example", StateDir: filepath.Join(root, "state"), PaseoHome: filepath.Join(root, "paseo"), NodePath: "/usr/local/bin/node", BridgePath: filepath.Join(root, "bridge.mjs"), AmadanCredentialPath: filepath.Join(root, "forge.json"), AccountBindingsPath: filepath.Join(root, "bindings.json"), CodexPath: "/usr/bin/codex", GoRoot: "/opt/go", GoBinary: "/opt/go/bin/go", WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", Executable: "/usr/bin/equipo-runner", PaseoEndpoint: "127.0.0.1:1234", PaseoServerID: "server", InstanceID: "instance"} |
| +} |
| +func TestRunnerConfig(t *testing.T) { |
| + c := configFixture(t) |
| + if err := c.validate(); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, origin := range []string{"http://example.com", "https://user:pass@example.com", "https://example.com/path", "https://example.com?x=y", "https://example.com/#x"} { |
| + bad := c |
| + bad.Origin = origin |
| + if bad.validate() == nil { |
| + t.Fatalf("accepted unsafe origin %s", origin) |
| + } |
| + } |
| + bad := c |
| + bad.StateDir = "relative" |
| + if bad.validate() == nil { |
| + t.Fatal("accepted relative state") |
| + } |
| + bad = c |
| + bad.PaseoEndpoint = "0.0.0.0:1234" |
| + if bad.validate() == nil { |
| + t.Fatal("accepted public daemon endpoint") |
| + } |
| + if _, err := LoadConfig(func(string) string { return "" }); err == nil { |
| + t.Fatal("accepted missing config") |
| + } |
| +} |
| +func TestRunnerServiceLifecycle(t *testing.T) { |
| + c := configFixture(t) |
| + lock, err := lockState(c.StateDir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if second, err := lockState(c.StateDir); err == nil { |
| + second.Close() |
| + t.Fatal("second process acquired lock") |
| + } |
| + st, err := os.Stat(c.StateDir) |
| + if err != nil || st.Mode().Perm() != 0700 { |
| + t.Fatal("state is not private", err) |
| + } |
| + lock.Close() |
| + lock, err = lockState(c.StateDir) |
| + if err != nil { |
| + t.Fatal("lock not released", err) |
| + } |
| + lock.Close() |
| + path := filepath.Join(c.StateDir, "credentials.json") |
| + credential := runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Version: 1, Token: "secret", ExpiresAt: time.Now().Add(time.Hour)}} |
| + if err := runnerproto.JournalCredentials(path, credential); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := readCredentials(path) |
| + if err != nil || got.Bearer.Token != "secret" { |
| + t.Fatal("credentials not restored", err) |
| + } |
| + st, _ = os.Stat(path) |
| + if st.Mode().Perm() != 0600 { |
| + t.Fatal("credential mode") |
| + } |
| + if err := os.Chmod(path, 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = readCredentials(path); err == nil { |
| + t.Fatal("accepted exposed credentials") |
| + } |
| +} |
| + |
| +type transportFunc func(*http.Request) (*http.Response, error) |
| + |
| +func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| +func TestRunnerHTTPClient(t *testing.T) { |
| + j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "j.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer j.Close() |
| + c, err := NewHTTPInstance("https://equipo.example/api/runner/v1", j, runnerproto.RunnerCredential{Token: "secret", ExpiresAt: time.Now().Add(time.Hour)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + calls := 0 |
| + c.client.Transport = transportFunc(func(r *http.Request) (*http.Response, error) { |
| + calls++ |
| + if r.URL.Host != "equipo.example" || r.Header.Get("Authorization") != "Bearer secret" { |
| + t.Fatal("bearer escaped origin") |
| + } |
| + return &http.Response{StatusCode: 302, Header: http.Header{"Location": []string{"https://evil.example/"}}, Body: io.NopCloser(strings.NewReader("")), Request: r}, nil |
| + }) |
| + if _, err = c.Poll(context.Background()); err == nil || calls != 1 { |
| + t.Fatal("followed redirect", err, calls) |
| + } |
| + c.bearer.ExpiresAt = time.Now().Add(-time.Second) |
| + if _, err = c.Poll(context.Background()); err == nil || calls != 1 { |
| + t.Fatal("expired credential reused") |
| + } |
| +} |
| + |
| +func TestRunnerHTTPClientTLSFailure(t *testing.T) { |
| + j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private/j.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer j.Close() |
| + c, err := NewHTTPInstance("https://equipo.example/api/runner/v1", j, runnerproto.RunnerCredential{Token: "secret", ExpiresAt: time.Now().Add(time.Hour)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + calls := 0 |
| + c.client.Transport = transportFunc(func(*http.Request) (*http.Response, error) { calls++; return nil, x509.UnknownAuthorityError{} }) |
| + if _, err = c.Poll(context.Background()); err == nil || calls != 1 { |
| + t.Fatal("TLS failure bypassed", err, calls) |
| + } |
| +} |
diff --git a/internal/runner/connections.go b/internal/runner/connections.go| new file mode 100644 |
| index 00000000..b6206794 |
| --- /dev/null |
| +++ b/internal/runner/connections.go |
| @@ -0,0 +1,136 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "sort" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type AccountBinding struct { |
| + ID string `json:"id"` |
| + LocalID string `json:"local_id"` |
| + Provider string `json:"provider"` |
| + Family string `json:"family"` |
| + Model string `json:"model"` |
| + AccountID string `json:"account_id"` |
| + CredentialHome string `json:"credential_home"` |
| + Kind string `json:"kind"` |
| +} |
| + |
| +func loadBindings(path string) ([]AccountBinding, error) { |
| + var bs []AccountBinding |
| + if err := privateJSON(path, &bs); err != nil { |
| + return nil, err |
| + } |
| + if len(bs) == 0 || len(bs) > 256 { |
| + return nil, paseo.ErrContract |
| + } |
| + seen := map[string]bool{} |
| + for _, b := range bs { |
| + if b.ID == "" || b.LocalID == "" || b.AccountID == "" || b.Model == "" || !(b.Provider == "claude" && b.Family == "claude" || b.Provider == "codex" && b.Family == "gpt") || !(b.Kind == "subscription" || b.Kind == "api") || !filepath.IsAbs(b.CredentialHome) || seen[b.LocalID+"/"+b.Model] { |
| + return nil, paseo.ErrIdentity |
| + } |
| + actual, err := filepath.EvalSymlinks(b.CredentialHome) |
| + if err != nil || actual != b.CredentialHome { |
| + return nil, paseo.ErrPolicy |
| + } |
| + seen[b.LocalID+"/"+b.Model] = true |
| + } |
| + return bs, nil |
| +} |
| +func (c Config) securityPaths(bs []AccountBinding) workspace.SecurityPaths { |
| + home, _ := os.UserHomeDir() |
| + homes := []string{filepath.Join(home, ".claude"), filepath.Join(home, ".codex")} |
| + for _, b := range bs { |
| + homes = append(homes, b.CredentialHome) |
| + } |
| + return workspace.SecurityPaths{RunnerState: c.StateDir, RunnerConfig: c.AccountBindingsPath, Journal: filepath.Join(c.StateDir, "journal.db"), Bearer: filepath.Join(c.StateDir, "credentials.json"), Cleanup: filepath.Join(c.StateDir, "credentials.json"), ForgeCredential: c.AmadanCredentialPath, PaseoHome: c.PaseoHome, SSH: filepath.Join(home, ".ssh"), ProviderHomes: homes} |
| +} |
| +func canonicalSecurityPath(path string) (string, error) { |
| + tail := "" |
| + for parent := path; ; parent = filepath.Dir(parent) { |
| + real, err := filepath.EvalSymlinks(parent) |
| + if err == nil { |
| + return filepath.Join(real, tail), nil |
| + } |
| + if !os.IsNotExist(err) || parent == filepath.Dir(parent) { |
| + return "", paseo.ErrPolicy |
| + } |
| + tail = filepath.Join(filepath.Base(parent), tail) |
| + } |
| +} |
| +func bindingPolicy(c Config, bs []AccountBinding, b AccountBinding) (paseo.ReadPolicy, error) { |
| + s := c.securityPaths(bs) |
| + paths := append([]string{s.RunnerState, s.RunnerConfig, s.Journal, s.Bearer, s.Cleanup, s.ForgeCredential, s.PaseoHome, s.SSH}, s.ProviderHomes...) |
| + paths = append(paths, filepath.Join(c.StateDir, "private")) |
| + var denied []string |
| + for _, p := range paths { |
| + real, err := canonicalSecurityPath(p) |
| + if err != nil { |
| + return paseo.ReadPolicy{}, err |
| + } |
| + denied = append(denied, p, real) |
| + } |
| + sort.Strings(denied) |
| + denied = slices.Compact(denied) |
| + for _, root := range []string{c.WorkspaceRoot, c.ScratchRoot} { |
| + for _, p := range denied { |
| + if containsPath(p, root) { |
| + return paseo.ReadPolicy{}, paseo.ErrPolicy |
| + } |
| + } |
| + } |
| + b.Model = "" |
| + raw, _ := json.Marshal(struct { |
| + Binding AccountBinding |
| + Mode, Home, Endpoint, Server string |
| + Denied []string |
| + }{b, "default", c.PaseoHome, c.PaseoEndpoint, c.PaseoServerID, denied}) |
| + sum := sha256.Sum256(raw) |
| + return paseo.ReadPolicy{DeniedPaths: denied, ConfigHash: hex.EncodeToString(sum[:])}, nil |
| +} |
| +func connectionReport(b AccountBinding, p paseo.ReadPolicy, c paseo.Capabilities, err error) runnerproto.ConnectionReport { |
| + hash := sha256.Sum256([]byte(b.CredentialHome)) |
| + tuple := team.IsolationTuple{Provider: b.Provider, ProviderVersion: c.ProviderVersion, PaseoVersion: c.PaseoVersion, IsolationConfigHash: c.IsolationConfigHash} |
| + confined := c.ReadIsolation && slices.Contains(release.BuildManifest().VerifiedIsolationTuples, tuple) |
| + routingObserved := c.ObservedCredentialHome == b.CredentialHome && c.ObservedBindingID == b.ID && c.ObservedFamily == b.Family |
| + ready := routingObserved && c.AccountPinning && c.NoFailover && c.ObservedAccount == b.AccountID && c.RecoverableTimeline && c.ProcessOwnership && c.MCPAtCreate && c.IsolationConfigHash == p.ConfigHash && c.PaseoVersion == "0.14.0" && (b.Provider == "codex" && c.ProviderVersion == "0.165.0" || b.Provider == "claude" && c.ProviderVersion == "2.1.312" && confined) |
| + if err != nil && err != paseo.ErrIsolation { |
| + ready = false |
| + } |
| + reason := c.UnavailableReason |
| + if !ready && reason == "" { |
| + reason = "capability_unverified" |
| + } |
| + return runnerproto.ConnectionReport{LocalID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, Kind: b.Kind, ProviderVersion: c.ProviderVersion, PaseoVersion: c.PaseoVersion, IsolationConfigHash: p.ConfigHash, Available: ready, ReadIsolation: confined, UnavailableReason: reason, Routing: runnerproto.ConnectionRouting{BindingID: b.ID, AccountID: b.AccountID, ObservedAccountID: c.ObservedAccount, CredentialHomeHash: hex.EncodeToString(hash[:]), AccountPinned: c.AccountPinning && routingObserved, NoFailover: c.NoFailover, TimelineRecovery: c.RecoverableTimeline, ProcessOwnership: c.ProcessOwnership}} |
| +} |
| +func discover(ctx context.Context, c Config, client *paseo.Client) ([]runnerproto.ConnectionReport, error) { |
| + bs, err := loadBindings(c.AccountBindingsPath) |
| + if err != nil { |
| + return nil, err |
| + } |
| + reports := make([]runnerproto.ConnectionReport, 0, len(bs)) |
| + for _, b := range bs { |
| + policy, err := bindingPolicy(c, bs, b) |
| + if err != nil { |
| + return nil, err |
| + } |
| + caps, e := client.Preflight(ctx, paseo.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID}, policy) |
| + reports = append(reports, connectionReport(b, policy, caps, e)) |
| + } |
| + return reports, nil |
| +} |
| +func serviceInspector(client TerminalClient, j *Journal) (*LinuxProcessInspector, error) { |
| + return NewLinuxProcessInspector("/proc", client, j) |
| +} |
diff --git a/internal/runner/connections_test.go b/internal/runner/connections_test.go| new file mode 100644 |
| index 00000000..7491c1f0 |
| --- /dev/null |
| +++ b/internal/runner/connections_test.go |
| @@ -0,0 +1,90 @@ |
| +package runner |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "context" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| +) |
| + |
| +func TestConnectionsBindings(t *testing.T) { |
| + c := configFixture(t) |
| + b := AccountBinding{ID: "binding", LocalID: "local", Provider: "codex", Family: "gpt", Model: "model", AccountID: "account", CredentialHome: filepath.Join(t.TempDir(), "provider"), Kind: "subscription"} |
| + if err := os.MkdirAll(b.CredentialHome, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _ := json.Marshal([]AccountBinding{b}) |
| + if err := os.WriteFile(c.AccountBindingsPath, raw, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + bs, err := loadBindings(c.AccountBindingsPath) |
| + if err != nil || len(bs) != 1 { |
| + t.Fatal(err) |
| + } |
| + p, err := bindingPolicy(c, bs, b) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + caps := paseo.Capabilities{ObservedBindingID: b.ID, ObservedCredentialHome: b.CredentialHome, ObservedFamily: b.Family, ProviderVersion: "0.165.0", PaseoVersion: "0.14.0", ObservedAccount: "account", AccountPinning: true, NoFailover: true, RecoverableTimeline: true, ProcessOwnership: true, MCPAtCreate: true, ReadIsolation: true, IsolationConfigHash: p.ConfigHash} |
| + r := connectionReport(b, p, caps, nil) |
| + if r.ReadIsolation { |
| + t.Fatal("unlisted report became confined") |
| + } |
| + if r.Routing.AccountID != "account" || r.Routing.CredentialHomeHash == "" || r.Routing.ObservedAccountID != "account" { |
| + t.Fatal("missing observed binding") |
| + } |
| + caps.ObservedCredentialHome = "" |
| + if connectionReport(b, p, caps, nil).Available { |
| + t.Fatal("unobserved credential home accepted") |
| + } |
| + caps.ObservedCredentialHome = b.CredentialHome |
| + caps.NoFailover = false |
| + if connectionReport(b, p, caps, nil).Available { |
| + t.Fatal("failover-capable binding accepted") |
| + } |
| + caps.NoFailover = true |
| + caps.ObservedAccount = "other" |
| + r = connectionReport(b, p, caps, nil) |
| + if r.Available { |
| + t.Fatal("account failover accepted") |
| + } |
| + b.Family = "claude" |
| + raw, _ = json.Marshal([]AccountBinding{b}) |
| + os.WriteFile(c.AccountBindingsPath, raw, 0600) |
| + if _, err = loadBindings(c.AccountBindingsPath); err == nil { |
| + t.Fatal("unsupported provider family") |
| + } |
| +} |
| +func TestRunnerServiceUsesLinuxInspector(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| + actual, err := serviceInspector(p.client, p.journal) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if actual.root != "/proc" { |
| + t.Fatal("service does not use Linux /proc") |
| + } |
| + if err = actual.Track(context.Background(), o); err != nil { |
| + t.Fatal(err) |
| + } |
| + pid := escapedChild(t, o) |
| + inv, err := actual.Remaining(context.Background(), o) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if inv.CoverageKnown { |
| + t.Fatal("surviving escaped child allowed service containment") |
| + } |
| + id, err := actual.identity(pid) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if actual.Stop(context.Background(), id) == nil { |
| + t.Fatal("signalled unattributed child") |
| + } |
| +} |
diff --git a/internal/runner/enrol.go b/internal/runner/enrol.go| new file mode 100644 |
| index 00000000..8a618a94 |
| --- /dev/null |
| +++ b/internal/runner/enrol.go |
| @@ -0,0 +1,149 @@ |
| +package runner |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func outboundClient() *http.Client { |
| + return &http.Client{Timeout: 35 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| +} |
| +func Enrol(ctx context.Context, c Config, output io.Writer) error { |
| + if err := c.validate(); err != nil { |
| + return err |
| + } |
| + lock, err := lockState(c.StateDir) |
| + if err != nil { |
| + return err |
| + } |
| + defer lock.Close() |
| + credentialPath := filepath.Join(c.StateDir, "credentials.json") |
| + if _, err := os.Lstat(credentialPath); err == nil { |
| + old, err := readCredentials(credentialPath) |
| + if err != nil { |
| + return err |
| + } |
| + if time.Now().Before(old.Bearer.ExpiresAt) { |
| + return paseo.ErrIdentity |
| + } |
| + journalPath := filepath.Join(c.StateDir, "journal.db") |
| + if _, err = os.Stat(journalPath); err == nil { |
| + j, err := OpenJournal(ctx, journalPath) |
| + if err != nil { |
| + return err |
| + } |
| + var attempts []attemptState |
| + err = j.readStates(ctx, "attempt", &attempts) |
| + closeErr := j.Close() |
| + if err != nil { |
| + return err |
| + } |
| + if closeErr != nil { |
| + return closeErr |
| + } |
| + for _, a := range attempts { |
| + if a.Phase != "contained" { |
| + return paseo.ErrUncertain |
| + } |
| + } |
| + } else if !os.IsNotExist(err) { |
| + return err |
| + } |
| + } else if !os.IsNotExist(err) { |
| + return err |
| + } |
| + keyPath := filepath.Join(c.StateDir, "machine-key.json") |
| + var encoded string |
| + if err = privateJSON(keyPath, &encoded); os.IsNotExist(err) { |
| + _, key, e := ed25519.GenerateKey(rand.Reader) |
| + if e != nil { |
| + return e |
| + } |
| + encoded = base64.RawURLEncoding.EncodeToString(key) |
| + err = runnerproto.JournalCredentials(keyPath, encoded) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + key, err := base64.RawURLEncoding.DecodeString(encoded) |
| + if err != nil || len(key) != ed25519.PrivateKeySize { |
| + return paseo.ErrIdentity |
| + } |
| + client := outboundClient() |
| + post := func(path string, in, out any) (int, error) { |
| + raw, err := runnerproto.Marshal(in) |
| + if err != nil { |
| + return 0, err |
| + } |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.Origin+path, bytes.NewReader(raw)) |
| + if err != nil { |
| + return 0, err |
| + } |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := client.Do(req) |
| + if err != nil { |
| + return 0, paseo.ErrUncertain |
| + } |
| + defer resp.Body.Close() |
| + if resp.StatusCode != 200 && resp.StatusCode != 201 { |
| + return resp.StatusCode, paseo.ErrIdentity |
| + } |
| + return resp.StatusCode, runnerproto.DecodeLimit(resp.Body, out, 64<<10) |
| + } |
| + var code runnerproto.DeviceCode |
| + _, err = post("/api/enrolments", runnerproto.BeginEnrolmentRequest{Version: 1, MachinePublicKey: base64.RawURLEncoding.EncodeToString(ed25519.PrivateKey(key).Public().(ed25519.PublicKey)), Label: "equipo-runner"}, &code) |
| + if err != nil { |
| + return err |
| + } |
| + u, err := url.Parse(code.VerificationURI) |
| + origin, _ := url.Parse(c.Origin) |
| + if err != nil || u.Scheme != origin.Scheme || u.Host != origin.Host || u.User != nil || code.InstanceID != c.InstanceID || code.PollIntervalSeconds < 5 || code.PollIntervalSeconds > 60 || !time.Now().Before(code.ExpiresAt) { |
| + return paseo.ErrIdentity |
| + } |
| + if _, err = io.WriteString(output, "["+code.VerificationURI+"]("+code.VerificationURI+")\n"+code.UserCode+"\n"); err != nil { |
| + return err |
| + } |
| + proof := runnerproto.ExchangeProof{EnrolmentID: code.EnrolmentID, Challenge: code.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(randomBytes(32))} |
| + proof.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(ed25519.PrivateKey(key), runnerproto.EnrolmentProofMessage(code.InstanceID, proof))) |
| + for time.Now().Before(code.ExpiresAt) { |
| + timer := time.NewTimer(time.Duration(code.PollIntervalSeconds) * time.Second) |
| + select { |
| + case <-ctx.Done(): |
| + timer.Stop() |
| + return ctx.Err() |
| + case <-timer.C: |
| + } |
| + var cred runnerproto.RunnerCredential |
| + status, err := post("/api/enrolments/token", runnerproto.ExchangeEnrolmentRequest{Version: 1, DeviceSecret: code.DeviceSecret, Proof: proof}, &cred) |
| + if status == 409 { |
| + continue |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if cred.Version != 1 || cred.Token == "" || cred.RunnerID == "" || !time.Now().Before(cred.ExpiresAt) { |
| + return paseo.ErrIdentity |
| + } |
| + return runnerproto.JournalCredentials(credentialPath, runnerproto.CredentialRotation{Bearer: cred}) |
| + } |
| + return paseo.ErrIdentity |
| +} |
| +func randomBytes(n int) []byte { |
| + b := make([]byte, n) |
| + if _, err := rand.Read(b); err != nil { |
| + panic(err) |
| + } |
| + return b |
| +} |
diff --git a/internal/runner/forge/no_effect_test.go b/internal/runner/forge/no_effect_test.go| index a108dcfd..13bc96bc 100644 |
| --- a/internal/runner/forge/no_effect_test.go |
| +++ b/internal/runner/forge/no_effect_test.go |
| @@ -118,12 +118,21 @@ func TestPublishNoEffect(t *testing.T) { |
| } |
| _, err := f.p.Execute(callCtx, f.auth.Ticket.Dispatch) |
| cleanup() |
| - assertNoEffect(t, f, err) |
| + if name == "description" || name == "cancel_description" || name == "push_marker" { |
| + if !errors.Is(err, team.ErrUncertain) { |
| + t.Fatal("post-description failure claimed no effect", err) |
| + } |
| + if _, e := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch); !errors.Is(e, team.ErrUncertain) { |
| + t.Fatal("description uncertainty lost", e) |
| + } |
| + return |
| + } |
| if name == "expired_export" { |
| if _, e := os.Stat(f.p.path(f.auth.Ticket.Dispatch)); !os.IsNotExist(e) { |
| t.Fatal("expired export wrote a journal") |
| } |
| } |
| + assertNoEffect(t, f, err) |
| if name == "final_authority" || name == "final_validate" || name == "final_objects" { |
| if f.desc.calls != 0 { |
| t.Fatal("description changed before final authority and object checks") |
| @@ -272,3 +281,23 @@ func TestPublishJournalRecoveryClasses(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +func TestPublishReconcileTombstone(t *testing.T) { |
| + f := newFixture(t) |
| + _, err := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch) |
| + if !errors.Is(err, team.ErrNotDispatched) { |
| + t.Fatal(err) |
| + } |
| + _, err = f.p.Execute(ctx, f.auth.Ticket.Dispatch) |
| + if !errors.Is(err, team.ErrNotDispatched) || f.pushes != 0 { |
| + t.Fatal("reconciled absence was dispatched", err, f.pushes) |
| + } |
| +} |
| +func TestPublishDescriptionFailureUncertain(t *testing.T) { |
| + f := newFixture(t) |
| + f.desc.fail = true |
| + _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch) |
| + if !errors.Is(err, team.ErrUncertain) { |
| + t.Fatal("description Set may have succeeded", err) |
| + } |
| +} |
diff --git a/internal/runner/forge/publisher.go b/internal/runner/forge/publisher.go| index 344ac669..b574981c 100644 |
| --- a/internal/runner/forge/publisher.go |
| +++ b/internal/runner/forge/publisher.go |
| @@ -194,6 +194,8 @@ func (p *Publisher) Execute(ctx context.Context, d team.Dispatch) (receipt team. |
| defer func() { |
| if resultErr != nil && !mayPublish && !errors.Is(resultErr, team.ErrConflict) { |
| resultErr = team.ErrNotDispatched |
| + } else if resultErr != nil && mayPublish && !errors.Is(resultErr, team.ErrConflict) { |
| + resultErr = team.ErrUncertain |
| } |
| }() |
| a, e := p.cfg.Authorize(ctx, d) |
| @@ -258,9 +260,14 @@ func (p *Publisher) Execute(ctx context.Context, d team.Dispatch) (receipt team. |
| return p.reconcile(ctx, r) |
| } |
| if p.cfg.Description.BeforePush() { |
| - if e = p.confirmDescription(ctx, cred, desc); e != nil { |
| + r.Phase = "description_started" |
| + if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { |
| return team.Receipt{}, e |
| } |
| + mayPublish = true |
| + if e = p.confirmDescription(ctx, cred, desc); e != nil { |
| + return team.Receipt{}, team.ErrUncertain |
| + } |
| } |
| if e = ready(); e != nil { |
| return team.Receipt{}, e |
| @@ -300,7 +307,7 @@ func (p *Publisher) confirmDescription(ctx context.Context, cred Credential, des |
| return nil |
| } |
| func (p *Publisher) reconcile(ctx context.Context, r record) (team.Receipt, error) { |
| - if r.Phase == "prepared" { |
| + if r.Phase == "prepared" || r.Phase == "not_dispatched" { |
| return team.Receipt{}, team.ErrNotDispatched |
| } |
| if r.Phase != "" && r.Phase != "push_started" && r.Phase != "observed" { |
| @@ -342,6 +349,9 @@ func (p *Publisher) Reconcile(ctx context.Context, d team.Dispatch) (team.Reconc |
| defer unlock() |
| r, e := p.load(d) |
| if os.IsNotExist(e) { |
| + if err := runnerproto.JournalCredentials(p.path(d), record{Phase: "not_dispatched", Authorization: Authorization{Ticket: team.AdmissionTicket{Dispatch: d}}}); err != nil { |
| + return team.ReconcileResult{}, team.ErrUncertain |
| + } |
| return team.ReconcileResult{}, team.ErrNotDispatched |
| } |
| if e != nil { |
diff --git a/internal/runner/http.go b/internal/runner/http.go| index 7156be75..92fbdf6f 100644 |
| --- a/internal/runner/http.go |
| +++ b/internal/runner/http.go |
| @@ -3,6 +3,7 @@ package runner |
| import ( |
| "bytes" |
| "context" |
| + "crypto/rand" |
| "encoding/json" |
| "io" |
| "net/http" |
| @@ -29,7 +30,7 @@ func NewHTTPInstance(origin string, j *Journal, credential runnerproto.RunnerCre |
| if err != nil || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Host == "" || u.Scheme != "https" && (u.Scheme != "http" || u.Hostname() != "127.0.0.1") || j == nil || credential.Token == "" { |
| return nil, paseo.ErrContract |
| } |
| - return &HTTPInstance{origin: strings.TrimRight(origin, "/"), journal: j, bearer: credential, cleanup: map[string]string{}, client: &http.Client{Timeout: 35 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil |
| + return &HTTPInstance{origin: strings.TrimRight(origin, "/"), journal: j, bearer: credential, cleanup: map[string]string{}, client: outboundClient()}, nil |
| } |
| func (c *HTTPInstance) post(ctx context.Context, op string, body any, token string, out any) error { |
| raw, err := runnerproto.Marshal(body) |
| @@ -168,3 +169,15 @@ func (c *HTTPInstance) RestoreClaim(claim RunClaim) error { |
| c.cleanup[claim.Assignment.ID] = token |
| return nil |
| } |
| + |
| +func (c *HTTPInstance) Heartbeat(ctx context.Context, reports []runnerproto.ConnectionReport) error { |
| + token, err := c.token("", false) |
| + if err != nil { |
| + return err |
| + } |
| + raw, err := json.Marshal(reports) |
| + if err != nil { |
| + return err |
| + } |
| + return c.post(ctx, "heartbeat", runnerproto.HeartbeatRequest{Version: 1, RequestID: rand.Text(), Reports: raw}, token, nil) |
| +} |
diff --git a/internal/runner/paseo/client.go b/internal/runner/paseo/client.go| index de8bce9c..e04e29dd 100644 |
| --- a/internal/runner/paseo/client.go |
| +++ b/internal/runner/paseo/client.go |
| @@ -303,6 +303,9 @@ func evaluate(s Selection, p ReadPolicy, c Capabilities, tuples []VerifiedTuple, |
| c.IsolationStatus = "unconfined" |
| return deny("unsupported_provider_version", ErrCapability) |
| } |
| + if c.ObservedFamily != "" && c.ObservedFamily != s.Family { |
| + return deny("family_changed", ErrIdentity) |
| + } |
| if c.IsolationConfigHash != p.ConfigHash || p.ConfigHash == "" { |
| return deny("effective_policy_unobserved", ErrPolicy) |
| } |
| @@ -374,6 +377,11 @@ func (c *Client) Preflight(ctx context.Context, s Selection, p ReadPolicy) (Capa |
| if caps.ServerID != c.cfg.ServerID { |
| return caps, ErrIdentity |
| } |
| + if c.cfg.VerifyRouting != nil { |
| + if err := c.cfg.VerifyRouting(ctx, s, caps); err != nil { |
| + return caps, err |
| + } |
| + } |
| inspected := false |
| if c.cfg.InspectProcesses != nil { |
| var err error |
diff --git a/internal/runner/paseo/client_test.go b/internal/runner/paseo/client_test.go| index 57f1ae8e..d9b1e2e2 100644 |
| --- a/internal/runner/paseo/client_test.go |
| +++ b/internal/runner/paseo/client_test.go |
| @@ -424,3 +424,13 @@ func TestPaseoSendDurableIntent(t *testing.T) { |
| t.Fatal("send bypassed durable intent", err, recorded) |
| } |
| } |
| + |
| +func TestPaseoRoutingCallback(t *testing.T) { |
| + calls := 0 |
| + c := testClient(t, "normal", func(cfg *Config) { |
| + cfg.VerifyRouting = func(context.Context, Selection, Capabilities) error { calls++; return ErrIdentity } |
| + }) |
| + if _, err := c.Preflight(context.Background(), fixtureSelection(), fixturePolicy()); err != ErrIdentity || calls != 1 { |
| + t.Fatal("routing refusal bypassed", err, calls) |
| + } |
| +} |
diff --git a/internal/runner/paseo/types.go b/internal/runner/paseo/types.go| index 19c4a753..7b944228 100644 |
| --- a/internal/runner/paseo/types.go |
| +++ b/internal/runner/paseo/types.go |
| @@ -44,21 +44,24 @@ type VerifiedTuple struct { |
| ConfigHash string |
| } |
| type Capabilities struct { |
| - Version string `json:"version"` |
| - ServerID string `json:"server_id"` |
| - ProviderVersion string `json:"provider_version"` |
| - PaseoVersion string `json:"paseo_version"` |
| - AccountPinning bool `json:"account_pinning"` |
| - ObservedAccount string `json:"observed_account"` |
| - NoFailover bool `json:"no_failover"` |
| - RecoverableTimeline bool `json:"recoverable_timeline"` |
| - ProcessOwnership bool `json:"process_ownership"` |
| - MCPAtCreate bool `json:"mcp_at_create"` |
| - ReadIsolation bool `json:"read_isolation"` |
| - ReadIsolationReason string `json:"read_isolation_reason"` |
| - IsolationConfigHash string `json:"isolation_config_hash"` |
| - IsolationStatus string `json:"isolation_status"` |
| - UnavailableReason string `json:"unavailable_reason"` |
| + ObservedFamily string `json:"observed_family,omitempty"` |
| + ObservedCredentialHome string `json:"observed_credential_home,omitempty"` |
| + ObservedBindingID string `json:"observed_binding_id,omitempty"` |
| + Version string `json:"version"` |
| + ServerID string `json:"server_id"` |
| + ProviderVersion string `json:"provider_version"` |
| + PaseoVersion string `json:"paseo_version"` |
| + AccountPinning bool `json:"account_pinning"` |
| + ObservedAccount string `json:"observed_account"` |
| + NoFailover bool `json:"no_failover"` |
| + RecoverableTimeline bool `json:"recoverable_timeline"` |
| + ProcessOwnership bool `json:"process_ownership"` |
| + MCPAtCreate bool `json:"mcp_at_create"` |
| + ReadIsolation bool `json:"read_isolation"` |
| + ReadIsolationReason string `json:"read_isolation_reason"` |
| + IsolationConfigHash string `json:"isolation_config_hash"` |
| + IsolationStatus string `json:"isolation_status"` |
| + UnavailableReason string `json:"unavailable_reason"` |
| } |
| type Workspace struct { |
| ServerID string `json:"server_id"` |
| @@ -131,6 +134,7 @@ type Intent struct { |
| Request json.RawMessage |
| } |
| type Config struct { |
| + VerifyRouting func(context.Context, Selection, Capabilities) error |
| NodePath string |
| BridgePath string |
| DaemonHome string |
diff --git a/internal/runner/runtime.go b/internal/runner/runtime.go| new file mode 100644 |
| index 00000000..818dc2be |
| --- /dev/null |
| +++ b/internal/runner/runtime.go |
| @@ -0,0 +1,219 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "sync" |
| + |
| + "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type Runtime struct { |
| + cfg Config |
| + lock *os.File |
| + journal *Journal |
| + client *paseo.Client |
| + inspector *LinuxProcessInspector |
| + api *HTTPInstance |
| + service *Service |
| + sandbox *checks.CodexSandbox |
| + mu sync.Mutex |
| + current *RunClaim |
| +} |
| + |
| +func openRuntime(ctx context.Context, c Config) (r *Runtime, err error) { |
| + if err = c.validate(); err != nil { |
| + return nil, err |
| + } |
| + r = &Runtime{cfg: c} |
| + defer func() { |
| + if err != nil { |
| + r.Close() |
| + } |
| + }() |
| + r.lock, err = lockState(c.StateDir) |
| + if err != nil { |
| + return r, err |
| + } |
| + credentials, err := readCredentials(filepath.Join(c.StateDir, "credentials.json")) |
| + if err != nil { |
| + return r, err |
| + } |
| + bs, err := loadBindings(c.AccountBindingsPath) |
| + if err != nil { |
| + return r, err |
| + } |
| + if err = checkNode(ctx, c.NodePath); err != nil { |
| + return r, err |
| + } |
| + for _, path := range []string{c.ScratchRoot, c.WorkspaceRoot} { |
| + if err = os.MkdirAll(path, 0700); err != nil { |
| + return r, err |
| + } |
| + } |
| + r.sandbox, err = checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: c.CodexPath, ScratchRoot: c.ScratchRoot, GoRoot: c.GoRoot, GoBinary: c.GoBinary, Protected: c.securityPaths(bs)}) |
| + if err != nil { |
| + return r, err |
| + } |
| + r.journal, err = OpenJournal(ctx, filepath.Join(c.StateDir, "journal.db")) |
| + if err != nil { |
| + return r, err |
| + } |
| + r.api, err = NewHTTPInstance(c.Origin+"/api/runner/v1", r.journal, credentials.Bearer) |
| + if err != nil { |
| + return r, err |
| + } |
| + for id, token := range credentials.CleanupTokens { |
| + r.api.cleanup[id] = token |
| + } |
| + tuples := []paseo.VerifiedTuple{} |
| + for _, v := range release.BuildManifest().VerifiedIsolationTuples { |
| + tuples = append(tuples, paseo.VerifiedTuple{Provider: v.Provider, ProviderVersion: v.ProviderVersion, PaseoVersion: v.PaseoVersion, ConfigHash: v.IsolationConfigHash}) |
| + } |
| + r.client, err = paseo.Start(ctx, paseo.Config{VerifyRouting: r.verifyRouting, VerifiedTuples: tuples, NodePath: c.NodePath, BridgePath: c.BridgePath, DaemonHome: c.PaseoHome, Endpoint: c.PaseoEndpoint, ServerID: c.PaseoServerID, RecordIntent: r.journal.RecordIntent, InspectProcesses: r.coverage, AuthorizeUnconfined: r.authorizeUnconfined}) |
| + if err != nil { |
| + return r, err |
| + } |
| + r.inspector, err = serviceInspector(r.client, r.journal) |
| + if err != nil { |
| + return r, err |
| + } |
| + return r, nil |
| +} |
| +func (r *Runtime) Close() error { |
| + if r == nil { |
| + return nil |
| + } |
| + var err error |
| + if r.client != nil { |
| + err = errors.Join(err, r.client.Close()) |
| + r.client = nil |
| + } |
| + if r.journal != nil { |
| + err = errors.Join(err, r.journal.Close()) |
| + r.journal = nil |
| + } |
| + if r.lock != nil { |
| + err = errors.Join(err, r.lock.Close()) |
| + r.lock = nil |
| + } |
| + return err |
| +} |
| +func (r *Runtime) coverage(ctx context.Context, _ paseo.Selection) (bool, error) { |
| + if r.inspector == nil { |
| + return false, paseo.ErrUncertain |
| + } |
| + return r.inspector.InspectProcesses(ctx, paseo.Selection{}) |
| +} |
| +func (r *Runtime) authorizeUnconfined(ctx context.Context, s paseo.Selection, caps paseo.Capabilities) error { |
| + r.mu.Lock() |
| + claim := r.current |
| + r.mu.Unlock() |
| + if claim == nil || selection(claim.Assignment) != s || s.Provider != "codex" { |
| + return paseo.ErrIsolation |
| + } |
| + iso := claim.Assignment.Selection.Isolation |
| + if iso.Status != "unconfined" || !iso.RunnerTainted || len(iso.AcknowledgementIDs) == 0 { |
| + return paseo.ErrIsolation |
| + } |
| + matched := false |
| + for _, tuple := range iso.ObservedTuples { |
| + if tuple.Provider == s.Provider && tuple.ProviderVersion == caps.ProviderVersion && tuple.PaseoVersion == caps.PaseoVersion && tuple.IsolationConfigHash == caps.IsolationConfigHash { |
| + matched = true |
| + } |
| + } |
| + if !matched { |
| + return paseo.ErrIsolation |
| + } |
| + return r.api.Call(ctx, "validate", runnerproto.RunnerRequest{Version: 1, AssignmentID: claim.Assignment.ID, Scope: claim.Scope, Handle: claim.Handle, RequestID: "preflight"}, nil) |
| +} |
| +func (r *Runtime) binding(s paseo.Selection) (AccountBinding, []AccountBinding, error) { |
| + bs, err := loadBindings(r.cfg.AccountBindingsPath) |
| + if err != nil { |
| + return AccountBinding{}, nil, err |
| + } |
| + var selected *AccountBinding |
| + for i, b := range bs { |
| + if b.Provider == s.Provider && b.Family == s.Family && b.Model == s.Model && b.AccountID == s.AccountID { |
| + if selected != nil { |
| + return AccountBinding{}, nil, paseo.ErrIdentity |
| + } |
| + selected = &bs[i] |
| + } |
| + } |
| + if selected == nil { |
| + return AccountBinding{}, nil, paseo.ErrIdentity |
| + } |
| + return *selected, bs, nil |
| +} |
| +func (r *Runtime) policy(_ context.Context, s paseo.Selection) (paseo.ReadPolicy, error) { |
| + b, bs, err := r.binding(s) |
| + if err != nil { |
| + return paseo.ReadPolicy{}, err |
| + } |
| + return bindingPolicy(r.cfg, bs, b) |
| +} |
| +func (r *Runtime) verifyRouting(_ context.Context, s paseo.Selection, c paseo.Capabilities) error { |
| + b, _, err := r.binding(s) |
| + if err != nil { |
| + return err |
| + } |
| + if c.ObservedBindingID != b.ID || c.ObservedCredentialHome != b.CredentialHome || c.ObservedFamily != b.Family { |
| + return paseo.ErrIdentity |
| + } |
| + return nil |
| +} |
| + |
| +func Preflight(ctx context.Context, c Config) ([]runnerproto.ConnectionReport, error) { |
| + r, err := openRuntime(ctx, c) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer r.Close() |
| + return discover(ctx, c, r.client) |
| +} |
| +func Run(ctx context.Context, c Config) error { |
| + r, err := openRuntime(ctx, c) |
| + if err != nil { |
| + return err |
| + } |
| + defer r.Close() |
| + if err = r.wire(ctx); err != nil { |
| + return err |
| + } |
| + return r.service.Run(ctx) |
| +} |
| +func (r *Runtime) Poll(ctx context.Context) ([]runnerproto.Assignment, error) { |
| + reports, err := discover(ctx, r.cfg, r.client) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if err = r.api.Heartbeat(ctx, reports); err != nil { |
| + return nil, err |
| + } |
| + return r.api.Poll(ctx) |
| +} |
| +func (r *Runtime) Claim(ctx context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| + return r.api.Claim(ctx, q) |
| +} |
| +func (r *Runtime) RecoverClaim(ctx context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| + return r.api.RecoverClaim(ctx, q) |
| +} |
| + |
| +func (r *Runtime) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error { |
| + if op == "renew" { |
| + reports, err := discover(ctx, r.cfg, r.client) |
| + if err != nil { |
| + return err |
| + } |
| + if err = r.api.Heartbeat(ctx, reports); err != nil { |
| + return err |
| + } |
| + } |
| + return r.api.Call(ctx, op, q, out) |
| +} |
diff --git a/internal/runner/runtime_test.go b/internal/runner/runtime_test.go| new file mode 100644 |
| index 00000000..b99d0b9f |
| --- /dev/null |
| +++ b/internal/runner/runtime_test.go |
| @@ -0,0 +1,236 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func runtimeFixture(t *testing.T) Config { |
| + t.Helper() |
| + c := configFixture(t) |
| + c.GoRoot = filepath.Join(t.TempDir(), "go") |
| + c.GoBinary = filepath.Join(c.GoRoot, "bin/go") |
| + c.CodexPath = filepath.Join(t.TempDir(), "codex") |
| + c.Copy = ToolCopy{Accepted: "accepted", Rejected: "rejected"} |
| + for _, p := range []string{c.StateDir, c.PaseoHome, filepath.Dir(c.GoBinary)} { |
| + if err := os.MkdirAll(p, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := os.WriteFile(c.GoBinary, []byte(fmt.Sprintf("#!/bin/sh\necho 'go version go1.26.10 %s/%s'\n", runtime.GOOS, runtime.GOARCH)), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(c.CodexPath, []byte("#!/bin/sh\necho 'codex-cli 0.165.0'\n"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + c.BridgePath = filepath.Join(t.TempDir(), "bridge.mjs") |
| + if err := os.WriteFile(c.BridgePath, []byte(`import readline from 'node:readline';readline.createInterface({input:process.stdin}).on('line',line=>{const q=JSON.parse(line);let result={};if(q.op==='preflight')result={version:'0.14.0',server_id:'server',paseo_version:'0.14.0',provider_version:'0.165.0',account_pinning:false,observed_account:'',no_failover:false};process.stdout.write(JSON.stringify({version:1,type:'result',id:q.id,result})+'\n')});`), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + home := filepath.Join(t.TempDir(), "home") |
| + os.Mkdir(home, 0700) |
| + raw, _ := json.Marshal([]AccountBinding{{ID: "b", LocalID: "local", Provider: "codex", Family: "gpt", Model: "model", AccountID: "account", CredentialHome: home, Kind: "subscription"}}) |
| + if err := os.WriteFile(c.AccountBindingsPath, raw, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := runnerproto.JournalCredentials(filepath.Join(c.StateDir, "credentials.json"), runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Version: 1, RunnerID: "runner", Token: "test", ExpiresAt: time.Now().Add(time.Hour)}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + return c |
| +} |
| +func TestRunnerServiceLifecycleWiring(t *testing.T) { |
| + c := runtimeFixture(t) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + r, err := openRuntime(ctx, c) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer r.Close() |
| + if err = r.wire(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r.service.Supervisor.inspector != r.inspector || r.inspector.root != "/proc" || r.service.Supervisor.client != r.client { |
| + t.Fatal("service bypassed real inspector/client") |
| + } |
| + calls := 0 |
| + r.api.client.Transport = transportFunc(func(q *http.Request) (*http.Response, error) { |
| + calls++ |
| + if strings.HasSuffix(q.URL.Path, "/poll") { |
| + cancel() |
| + return nil, context.Canceled |
| + } |
| + return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"version":1,"result":null}`))}, nil |
| + }) |
| + if err = r.service.Run(ctx); err == nil { |
| + t.Fatal("cancelled run succeeded") |
| + } |
| + if calls != 2 { |
| + t.Fatal("service did not heartbeat before polling", calls) |
| + } |
| + if err = r.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + lock, err := lockState(c.StateDir) |
| + if err != nil { |
| + t.Fatal("lock leaked", err) |
| + } |
| + lock.Close() |
| +} |
| +func TestRunnerServiceVersions(t *testing.T) { |
| + c := runtimeFixture(t) |
| + c.NodePath = filepath.Join(t.TempDir(), "node") |
| + nodeLog := filepath.Join(t.TempDir(), "node.calls") |
| + os.WriteFile(c.NodePath, []byte(fmt.Sprintf("#!/bin/sh\nprintf '%%s\\n' \"$*\" >> %q\necho v24.0.0\n", nodeLog)), 0700) |
| + if r, err := openRuntime(context.Background(), c); err == nil { |
| + r.Close() |
| + t.Fatal("unverified Node started") |
| + } |
| + calls, _ := os.ReadFile(nodeLog) |
| + if string(calls) != "--version\n" { |
| + t.Fatal("unverified Node reached bridge startup", string(calls)) |
| + } |
| + lock, err := lockState(c.StateDir) |
| + if err != nil { |
| + t.Fatal("failed boot leaked lock") |
| + } |
| + lock.Close() |
| + c = runtimeFixture(t) |
| + os.WriteFile(c.CodexPath, []byte("#!/bin/sh\necho 'codex-cli 9.0.0'\n"), 0700) |
| + if r, err := openRuntime(context.Background(), c); err == nil { |
| + r.Close() |
| + t.Fatal("unverified Codex started") |
| + } |
| +} |
| +func TestConnectionsUnavailable(t *testing.T) { |
| + c := runtimeFixture(t) |
| + reports, err := Preflight(context.Background(), c) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(reports) != 1 || reports[0].Available || reports[0].ReadIsolation || reports[0].Routing.AccountPinned { |
| + t.Fatal("missing capability became available", reports) |
| + } |
| +} |
| +func TestUnconfinedContainmentRotatesTokensService(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + ctx := context.Background() |
| + c := runtimeFixture(t) |
| + r, err := openRuntime(ctx, c) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer r.Close() |
| + if err = r.wire(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + s := r.service.Supervisor |
| + owner := ProcessOwner{LocalOnly: true, Attempt: 1, Fence: 1, Marker: "rotation", Workspace: paseo.Workspace{Path: c.WorkspaceRoot}} |
| + if err = r.inspector.Track(ctx, owner); err != nil { |
| + t.Fatal(err) |
| + } |
| + record := &attemptState{Claim: RunClaim{Assignment: runnerproto.Assignment{ID: "assignment"}, ClaimResponse: runnerproto.ClaimResponse{Scope: runnerproto.Scope{Account: "team", Job: 1}, Handle: team.Handle{Attempt: 1, Fence: 1, Runner: "runner"}}}, Owner: owner, Phase: "completed"} |
| + if err = s.save(ctx, record); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.api.cleanup["assignment"] = "old-cleanup" |
| + rotation := runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Token: "new-bearer", ExpiresAt: time.Now().Add(time.Hour)}, CleanupTokens: map[string]string{"assignment": "new-cleanup"}} |
| + failAck := true |
| + polls := 0 |
| + containments := 0 |
| + r.api.client.Transport = transportFunc(func(q *http.Request) (*http.Response, error) { |
| + var value any |
| + switch filepath.Base(q.URL.Path) { |
| + case "contained": |
| + containments++ |
| + value = rotation |
| + case "heartbeat": |
| + saved, e := readCredentials(filepath.Join(c.StateDir, "credentials.json")) |
| + if e != nil || saved.Bearer.Token != "new-bearer" { |
| + t.Fatal("ack before durable credentials") |
| + } |
| + if failAck { |
| + return nil, io.ErrUnexpectedEOF |
| + } |
| + case "poll": |
| + polls++ |
| + return nil, context.Canceled |
| + } |
| + raw, _ := json.Marshal(map[string]any{"version": 1, "result": value}) |
| + return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(string(raw)))}, nil |
| + }) |
| + if _, err = s.cleanup(ctx, record); err == nil || record.Phase == "contained" { |
| + t.Fatal("failed rotation reopened admission") |
| + } |
| + if err = r.service.Run(ctx); err == nil || polls != 0 { |
| + t.Fatal("restart polled before rotation acknowledgement") |
| + } |
| + failAck = false |
| + if err = s.Recover(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !s.ready || containments != 1 { |
| + t.Fatal("recovery repeated containment or stayed blocked", containments) |
| + } |
| +} |
| + |
| +func TestConnectionsRoutingAtTurn(t *testing.T) { |
| + c := runtimeFixture(t) |
| + r := &Runtime{cfg: c} |
| + bs, err := loadBindings(c.AccountBindingsPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b := bs[0] |
| + sel := paseo.Selection{ConnectionID: "instance-connection", Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID} |
| + caps := paseo.Capabilities{ObservedBindingID: b.ID, ObservedCredentialHome: b.CredentialHome, ObservedFamily: b.Family} |
| + if err = r.verifyRouting(context.Background(), sel, caps); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, field := range []string{"binding", "home", "family"} { |
| + bad := caps |
| + switch field { |
| + case "binding": |
| + bad.ObservedBindingID = "other" |
| + case "home": |
| + bad.ObservedCredentialHome = "/other" |
| + case "family": |
| + bad.ObservedFamily = "claude" |
| + } |
| + if r.verifyRouting(context.Background(), sel, bad) == nil { |
| + t.Fatal("changed routing accepted", field) |
| + } |
| + } |
| +} |
| + |
| +func TestExecutionHibernateWitnessLeaseDeadline(t *testing.T) { |
| + before := ClockReading{Wall: time.Now(), Elapsed: time.Hour, BootID: "boot"} |
| + after := before |
| + after.Wall = before.Wall.Add(2 * time.Minute) |
| + after.Elapsed += 2 * time.Minute |
| + if _, err := newLease(after, before.Wall.Add(time.Minute), before.Wall.Add(20*time.Minute)); err == nil { |
| + t.Fatal("startup extended expired authority") |
| + } |
| + lease, err := newLease(before, before.Wall.Add(time.Minute), before.Wall.Add(20*time.Minute)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if lease.check(after) == nil { |
| + t.Fatal("hibernation retained authority") |
| + } |
| +} |
diff --git a/internal/runner/runtime_workflow.go b/internal/runner/runtime_workflow.go| new file mode 100644 |
| index 00000000..1a3fcf9d |
| --- /dev/null |
| +++ b/internal/runner/runtime_workflow.go |
| @@ -0,0 +1,190 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "path/filepath" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| + "amadan.net/oficina/equipo/internal/runner/forge" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type forgeCredentials struct{ path string } |
| +type forgeCredentialFile struct { |
| + Agent string `json:"agent"` |
| + Repositories map[string]string `json:"repositories"` |
| +} |
| + |
| +func (f forgeCredentials) credential(_ context.Context, repo string) (forge.Credential, error) { |
| + var file forgeCredentialFile |
| + if err := privateJSON(f.path, &file); err != nil { |
| + return forge.Credential{}, err |
| + } |
| + token := file.Repositories[repo] |
| + if !strings.HasPrefix(repo, "amadan.net/") || strings.ContainsAny(repo+token, "\r\n\x00") || token == "" || file.Agent == "" { |
| + return forge.Credential{}, paseo.ErrIdentity |
| + } |
| + return forge.Credential{Remote: "https://" + repo, Agent: file.Agent, Bearer: token}, nil |
| +} |
| +func (f forgeCredentials) Resolve(ctx context.Context, repo string) (workspace.Remote, error) { |
| + c, err := f.credential(ctx, repo) |
| + return workspace.Remote{URL: c.Remote, Bearer: c.Bearer}, err |
| +} |
| + |
| +// The pinned Amadan interface has no authenticated description readback. |
| +// Keep publication unavailable until that interface exists. |
| +type unavailableDescription struct{} |
| + |
| +func (unavailableDescription) BeforePush() bool { return true } |
| +func (unavailableDescription) Set(context.Context, forge.Credential, forge.Description) error { |
| + return paseo.ErrCapability |
| +} |
| +func (unavailableDescription) Read(context.Context, forge.Credential, string, string) (forge.Description, error) { |
| + return forge.Description{}, paseo.ErrCapability |
| +} |
| + |
| +func (r *Runtime) active() (RunClaim, error) { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + if r.current == nil { |
| + return RunClaim{}, paseo.ErrIdentity |
| + } |
| + return *r.current, nil |
| +} |
| +func claimRequest(c RunClaim, op string) runnerproto.RunnerRequest { |
| + return runnerproto.RunnerRequest{Version: 1, AssignmentID: c.Assignment.ID, Scope: c.Scope, Handle: c.Handle, RequestID: attemptKey(c.Scope, c.Handle) + "/" + op} |
| +} |
| +func (r *Runtime) artifacts(ctx context.Context, c RunClaim) ([]team.Artifact, error) { |
| + var list []team.Artifact |
| + if err := r.api.Call(ctx, "evidence", claimRequest(c, "evidence"), &list); err != nil { |
| + return nil, err |
| + } |
| + for i, item := range list { |
| + q := claimRequest(c, "evidence") |
| + q.ArtifactID = item.ID |
| + var full team.Artifact |
| + if err := r.api.Call(ctx, "evidence", q, &full); err != nil { |
| + return nil, err |
| + } |
| + if full.ID != item.ID || full.Hash != item.Hash || team.ContentDigest(full.Payload) != item.Hash { |
| + return nil, paseo.ErrIdentity |
| + } |
| + list[i] = full |
| + } |
| + return list, nil |
| +} |
| +func (r *Runtime) wire(ctx context.Context) error { |
| + w, err := NewWitness(r.journal) |
| + if err != nil { |
| + return err |
| + } |
| + bs, err := loadBindings(r.cfg.AccountBindingsPath) |
| + if err != nil { |
| + return err |
| + } |
| + var manager *workspace.Manager |
| + executor := func(ctx context.Context, c RunClaim, d checks.Definition, repro checks.Reproduction, deadline time.Time) (*checks.Executor, error) { |
| + policy, err := r.policy(ctx, selection(c.Assignment)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + baseRepo := filepath.Join(r.cfg.StateDir, "private", "project-"+runnerproto.EventHash(d.Repository)) |
| + candidate := func(ctx context.Context, hash string) (team.GitCandidate, error) { |
| + arts, err := r.artifacts(ctx, c) |
| + if err != nil { |
| + return team.GitCandidate{}, err |
| + } |
| + for _, art := range arts { |
| + if art.Role == team.RoleCandidate { |
| + var v team.GitCandidate |
| + if json.Unmarshal(art.Payload, &v) == nil && checks.CandidateHash(v) == hash { |
| + return v, nil |
| + } |
| + } |
| + } |
| + return team.GitCandidate{}, paseo.ErrIdentity |
| + } |
| + return checks.New(checks.Config{ScratchRoot: r.cfg.ScratchRoot, Scope: c.Scope, Handle: c.Handle, Deadline: deadline, Policy: policy, DefinitionHash: checks.Digest(marshal(d)), ReproductionHash: checks.Digest(marshal(repro)), Reproduction: func(_ context.Context, hash string) (checks.Reproduction, error) { |
| + if hash != checks.Digest(marshal(repro)) { |
| + return checks.Reproduction{}, paseo.ErrIdentity |
| + } |
| + return repro, nil |
| + }, ResolveCandidate: candidate, Isolation: func(ctx context.Context) (team.IsolationSnapshot, error) { |
| + // Refresh the authenticated assignment, including runner-wide taint. |
| + var selected runnerproto.Selection |
| + if err := r.api.Call(ctx, "validate", claimRequest(c, "isolation"), &selected); err != nil { |
| + return team.IsolationSnapshot{}, err |
| + } |
| + return selected.Isolation, nil |
| + }, Export: func(ctx context.Context, commit, dest string) error { |
| + if commit == d.Base { |
| + return checks.ExportBase(ctx, baseRepo, commit, dest) |
| + } |
| + arts, err := r.artifacts(ctx, c) |
| + if err != nil { |
| + return err |
| + } |
| + for _, art := range arts { |
| + if art.Role == team.RoleCandidate { |
| + var v team.GitCandidate |
| + if json.Unmarshal(art.Payload, &v) == nil && v.Commit == commit { |
| + return manager.ExportCandidate(ctx, v, dest) |
| + } |
| + } |
| + } |
| + return paseo.ErrIdentity |
| + }}, r.sandbox) |
| + } |
| + credentials := forgeCredentials{r.cfg.AmadanCredentialPath} |
| + manager, err = workspace.New(workspace.Config{Protected: r.cfg.securityPaths(bs), PrivateRoot: filepath.Join(r.cfg.StateDir, "private"), WorkspaceRoot: r.cfg.WorkspaceRoot, GitPath: r.cfg.GitPath, Forge: credentials, Policy: r.policy, Definitions: func(ctx context.Context, target team.TargetBinding, repo string) (runnerproto.PreparedBug, error) { |
| + c, err := r.active() |
| + if err != nil { |
| + return runnerproto.PreparedBug{}, err |
| + } |
| + d, err := checks.LoadBaseDefinition(ctx, repo, target.Repository, target.BaseRevision, r.cfg.ScratchRoot) |
| + if err != nil { |
| + return runnerproto.PreparedBug{}, err |
| + } |
| + e, err := executor(ctx, c, d, checks.Reproduction{}, c.AttemptDeadline) |
| + if err != nil { |
| + return runnerproto.PreparedBug{}, err |
| + } |
| + d.Baseline, err = e.CaptureBaseline(ctx, d) |
| + if err != nil { |
| + return runnerproto.PreparedBug{}, err |
| + } |
| + raw := marshal(d) |
| + return runnerproto.PreparedBug{CheckDefinition: raw, CheckDefinitionHash: checks.Digest(raw), BaselineTestSetHash: d.Baseline.Hash}, nil |
| + }}, r.client) |
| + if err != nil { |
| + return err |
| + } |
| + publisherFor := func(ctx context.Context, auth runnerproto.PublicationAuthorization) (*forge.Publisher, error) { |
| + return forge.New(forge.Config{Root: filepath.Join(r.cfg.StateDir, "publish"), GitPath: r.cfg.GitPath, Runner: r.api.bearer.RunnerID, Incarnation: auth.Ticket.Incarnation, Clock: time.Now, Authorize: w.PublicationAuthorization, Revalidate: func(ctx context.Context, a forge.Authorization) error { |
| + c, err := r.active() |
| + if err != nil { |
| + return err |
| + } |
| + if c.Scope != a.Ticket.Scope || c.Handle != a.Ticket.Handle { |
| + return paseo.ErrIdentity |
| + } |
| + return r.api.Call(ctx, "validate", claimRequest(c, "publish-validate"), nil) |
| + }, Export: manager.ExportCandidate, Credential: credentials.credential, Description: unavailableDescription{}}) |
| + } |
| + workflow, err := NewBugWorkflow(BugWorkflowConfig{Workspaces: manager, Client: r.client, Witness: w, Policy: r.policy, Executor: executor, PublisherFor: publisherFor, StateDir: r.cfg.StateDir, Executable: r.cfg.Executable, InstanceID: r.cfg.InstanceID, Copy: r.cfg.Copy}) |
| + if err != nil { |
| + return err |
| + } |
| + supervisor, err := NewSupervisor(SupervisorConfig{Journal: r.journal, Client: r.client, Inspector: r.inspector, API: r, Workflow: workflow, CredentialsPath: filepath.Join(r.cfg.StateDir, "credentials.json"), InstallCredentials: r.api.InstallCredentials}) |
| + if err != nil { |
| + return err |
| + } |
| + r.service = &Service{Supervisor: supervisor, Source: r, BeforeRun: func(c RunClaim) { r.mu.Lock(); r.current = &c; r.mu.Unlock() }} |
| + return nil |
| +} |
diff --git a/internal/runner/service.go b/internal/runner/service.go| index 8ce1a190..10a38977 100644 |
| --- a/internal/runner/service.go |
| +++ b/internal/runner/service.go |
| @@ -16,6 +16,7 @@ type AssignmentSource interface { |
| type Service struct { |
| Supervisor *Supervisor |
| Source AssignmentSource |
| + BeforeRun func(RunClaim) |
| } |
| func (s *Service) Run(ctx context.Context) error { |
| @@ -55,6 +56,9 @@ func (s *Service) Run(ctx context.Context) error { |
| if err != nil { |
| return err |
| } |
| + if s.BeforeRun != nil { |
| + s.BeforeRun(RunClaim{Assignment: a, ClaimResponse: claim}) |
| + } |
| if err = s.Supervisor.Run(ctx, RunClaim{Assignment: a, ClaimResponse: claim}); err != nil { |
| return err |
| } |
diff --git a/internal/runner/workflow.go b/internal/runner/workflow.go| index 5fdf3f73..565a3709 100644 |
| --- a/internal/runner/workflow.go |
| +++ b/internal/runner/workflow.go |
| @@ -23,13 +23,14 @@ type BugWorkflowConfig struct { |
| Policy func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) |
| Executor func(context.Context, RunClaim, checks.Definition, checks.Reproduction, time.Time) (*checks.Executor, error) |
| Publisher *forge.Publisher |
| + PublisherFor func(context.Context, runnerproto.PublicationAuthorization) (*forge.Publisher, error) |
| StateDir, Executable, InstanceID string |
| Copy ToolCopy |
| } |
| type BugWorkflow struct{ cfg BugWorkflowConfig } |
| func NewBugWorkflow(c BugWorkflowConfig) (*BugWorkflow, error) { |
| - if c.Workspaces == nil || c.Client == nil || c.Witness == nil || c.Policy == nil || c.Executor == nil || c.Publisher == nil || !filepath.IsAbs(c.StateDir) || filepath.Clean(c.StateDir) != c.StateDir || !filepath.IsAbs(c.Executable) || filepath.Clean(c.Executable) != c.Executable || c.InstanceID == "" { |
| + if c.Workspaces == nil || c.Client == nil || c.Witness == nil || c.Policy == nil || c.Executor == nil || (c.Publisher == nil && c.PublisherFor == nil) || !filepath.IsAbs(c.StateDir) || filepath.Clean(c.StateDir) != c.StateDir || !filepath.IsAbs(c.Executable) || filepath.Clean(c.Executable) != c.Executable || c.InstanceID == "" { |
| return nil, paseo.ErrContract |
| } |
| return &BugWorkflow{cfg: c}, nil |
diff --git a/internal/runner/workflow_integration_test.go b/internal/runner/workflow_integration_test.go| index 04b8c730..6bb0af87 100644 |
| --- a/internal/runner/workflow_integration_test.go |
| +++ b/internal/runner/workflow_integration_test.go |
| @@ -156,7 +156,13 @@ func (a *coreWorkflowAPI) Call(ctx context.Context, op string, q runnerproto.Run |
| } |
| func TestRunnerBugWorkflow(t *testing.T) { runBugWorkflow(t, false) } |
| func TestRunnerBugWorkflowRejectedTools(t *testing.T) { runBugWorkflow(t, true) } |
| -func runBugWorkflow(t *testing.T, reject bool) { |
| +func runBugWorkflow(t *testing.T, reject bool) { runBugWorkflowMode(t, reject, "") } |
| +func TestAccountFailoverStops(t *testing.T) { |
| + for _, mode := range []string{"before", "during", "family_before", "family_during"} { |
| + t.Run(mode, func(t *testing.T) { runBugWorkflowMode(t, false, mode) }) |
| + } |
| +} |
| +func runBugWorkflowMode(t *testing.T, reject bool, failover string) { |
| ctx := context.Background() |
| root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e15-") |
| wfMust(t, err) |
| @@ -177,6 +183,14 @@ func runBugWorkflow(t *testing.T, reject bool) { |
| proc := isolatedProc(t) |
| bridge := filepath.Join(root, "bridge.mjs") |
| script := fmt.Sprintf(workflowBridge, proc) |
| + if failover != "" { |
| + if strings.HasPrefix(failover, "family_") { |
| + script = strings.Replace(script, "observed_account:'account'", "observed_account:'account',observed_family:"+map[string]string{"family_before": "'gpt'", "family_during": "turn>0?'gpt':p.selection.family"}[failover], 1) |
| + } else { |
| + script = strings.Replace(script, "observed_account:'account'", "observed_account:"+map[string]string{"before": "'other'", "during": "turn>0?'other':'account'"}[failover], 1) |
| + } |
| + script = strings.Replace(script, "++turn;", "++turn;fs.writeFileSync(proc+'/prompts',String(turn));", 1) |
| + } |
| if reject { |
| script = strings.Replace(script, "decision:'approve'", "decision:'changes_requested'", 1) |
| } |
| @@ -349,6 +363,21 @@ func runBugWorkflow(t *testing.T, reject bool) { |
| } |
| claim := RunClaim{Assignment: a, ClaimResponse: runnerproto.ClaimResponse{Scope: scope, Handle: h, Brief: runnerproto.RunnerBrief{Target: target, Selection: sel, Policy: pol, CheckDefinition: marshal(pinned), ArtifactHashes: hashes}, AttemptDeadline: time.Now().Add(20 * time.Minute), LeaseDeadline: time.Now().Add(60 * time.Second)}} |
| if err = s.Run(ctx, claim); err != nil { |
| + if failover != "" { |
| + raw, _ := os.ReadFile(filepath.Join(proc, "prompts")) |
| + want := "" |
| + if failover == "during" || failover == "family_during" { |
| + want = "1" |
| + } |
| + if string(raw) != want { |
| + t.Fatalf("failover prompt count %q want %q", raw, want) |
| + } |
| + state := s.states[attemptKey(scope, h)] |
| + if state.Phase != "contained" || state.Proof == nil || !state.Proof.Empty { |
| + t.Fatalf("failover was not contained: %s %v", state.Phase, err) |
| + } |
| + return |
| + } |
| if reject && step == "review" && errors.Is(err, team.ErrEvidence) { |
| pending, e := j.ToolSubmissions(ctx, 128) |
| wfMust(t, e) |
| @@ -369,6 +398,9 @@ func runBugWorkflow(t *testing.T, reject bool) { |
| t.Fatalf("%s (%s): %v %s", step, s.states[attemptKey(scope, h)].FailurePhase, err, b) |
| } |
| } |
| + if failover != "" { |
| + t.Fatal("account failover completed workflow") |
| + } |
| if reject { |
| t.Fatal("rejected review published") |
| } |
diff --git a/internal/runner/workflow_turn.go b/internal/runner/workflow_turn.go| index 04a119e5..48f444a9 100644 |
| --- a/internal/runner/workflow_turn.go |
| +++ b/internal/runner/workflow_turn.go |
| @@ -274,7 +274,15 @@ func (w *BugWorkflow) publish(ctx context.Context, s *Supervisor, r *attemptStat |
| if err := w.cfg.Witness.record(ctx, "publication", runnerproto.EventHash(auth.Ticket.Dispatch), auth); err != nil { |
| return err |
| } |
| - receipt, err := w.cfg.Publisher.Execute(ctx, auth.Ticket.Dispatch) |
| + publisher := w.cfg.Publisher |
| + if w.cfg.PublisherFor != nil { |
| + var err error |
| + publisher, err = w.cfg.PublisherFor(ctx, auth) |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + receipt, err := publisher.Execute(ctx, auth.Ticket.Dispatch) |
| if err != nil { |
| return err |
| } |
diff --git a/packaging/equipo-runner.service b/packaging/equipo-runner.service| new file mode 100644 |
| index 00000000..b3ab3280 |
| --- /dev/null |
| +++ b/packaging/equipo-runner.service |
| @@ -0,0 +1,18 @@ |
| +[Unit] |
| +Description=equipo-runner |
| +After=network-online.target |
| +Wants=network-online.target |
| + |
| +[Service] |
| +Type=simple |
| +EnvironmentFile=%h/.config/equipo-runner/runner.env |
| +ExecStart=%h/.local/lib/equipo-runner/equipo-runner run |
| +Restart=on-failure |
| +RestartSec=5 |
| +TimeoutStopSec=45 |
| +KillMode=control-group |
| +UMask=0077 |
| +NoNewPrivileges=yes |
| + |
| +[Install] |
| +WantedBy=default.target |