package runner import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "io" "net/http" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) func directRuntimeFixture(t *testing.T) Config { c := runtimeFixture(t) c.Executable, _ = os.Executable() c.ClaudePath = c.CodexPath c.ModuleCache = t.TempDir() // No credential file or account lease is needed to open and wire the runtime. b := AccountBinding{ID: "binding", LocalID: "local", Provider: "codex", Family: "gpt", Model: "model", AccountID: "account", ProviderHome: filepath.Join(t.TempDir(), "unopened"), Kind: "subscription", ExpectedIdentity: provider.Identity{AccountID: "account", HomeID: "home", ProviderVersion: "0.165.0"}} mustJournal(t, os.WriteFile(c.AccountBindingsPath, marshal([]AccountBinding{b}), 0600)) return c } func TestDirectBugRuntime(t *testing.T) { c := directRuntimeFixture(t) r, err := openRuntime(context.Background(), c) mustJournal(t, err) defer r.Close() mustJournal(t, r.wire(context.Background())) if r.namespaces == nil || len(r.launchers) != 2 || r.service.Supervisor.namespaces != r.namespaces { t.Fatal("runtime did not construct direct services") } host, ok := r.host.(*directHost) if !ok || host.journal != r.journal || host.manager != r.namespaces { t.Fatal("namespace launches bypass durable host") } legacy := r.service.Supervisor.workflow.cfg legacy.Launchers = nil if _, err := NewBugWorkflow(legacy); err == nil { t.Fatal("missing launcher registry authorized new workflow") } } func TestDirectBugRuntimeRecoveryBeforeStart(t *testing.T) { c := directRuntimeFixture(t) mustJournal(t, os.Mkdir(c.ScratchRoot, 0700)) record := containment.Record{ID: strings.Repeat("a", 32), AttemptKey: "orphan"} mustJournal(t, os.WriteFile(filepath.Join(c.ScratchRoot, record.ID+".json"), marshal(record), 0600)) if r, err := openRuntime(context.Background(), c); err == nil { r.Close() t.Fatal("admitted launchers before reconciling unknown namespace") } } func TestDirectBugRuntimeClosesNamespaces(t *testing.T) { s, r, m, host, l := directNamespaceFixture(t) var manifest struct{ Argv []string } mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest)) p, err := host.Start(s.namespaceContext(context.Background(), r), l, manifest.Argv) mustJournal(t, err) t.Cleanup(func() { m.Stop(context.Background(), p.ID()) p.Stdout().Close() p.Stderr().Close() p.Stdin().Close() }) b := make([]byte, 6) _, err = io.ReadFull(p.Stdout(), b) mustJournal(t, err) runtime := &Runtime{namespaces: m} released := false runtime.service = &Service{Supervisor: &Supervisor{activeRelease: func() error { ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() if _, err := p.Wait(ctx); err != nil { return err } released = true return nil }}} mustJournal(t, runtime.Close()) if !released { t.Fatal("runtime shutdown retained account lease after containment") } ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() if _, err = p.Wait(ctx); err != nil { t.Fatal("runtime shutdown left namespace alive") } } func TestDirectCancelRetainsCheckUntilEveryProof(t *testing.T) { c := directRuntimeFixture(t) runtime, err := openRuntime(context.Background(), c) mustJournal(t, err) defer runtime.Close() mustJournal(t, runtime.wire(context.Background())) s := runtime.service.Supervisor _, r, _, _ := cleanupFixture(t) r.Direct = true r.Proof = nil s.api = &supervisorAPI{order: new([]string)} root, err := os.MkdirTemp(c.WorkspaceRoot, "checks-") mustJournal(t, err) work := filepath.Join(root, "work") mustJournal(t, os.Mkdir(work, 0700)) raw := []byte(`{"Version":"checks-v1"}`) hash := sha256.Sum256(raw) l := provider.Launch{AttemptKey: "check-recorded", Workspace: work, Policy: provider.Policy{Manifest: raw, ManifestHash: hex.EncodeToString(hash[:]), Hash: strings.Repeat("c", 64)}} record := containment.Record{ID: strings.Repeat("a", 32), AttemptKey: l.AttemptKey, BootID: "old-boot", ManifestHash: strings.Repeat("b", 64), PolicyHash: l.Policy.Hash} mustJournal(t, s.journal.recordDirectLaunch(context.Background(), l, record)) owner := attemptKey(r.Claim.Scope, r.Claim.Handle) mustJournal(t, s.journal.saveState(context.Background(), "namespace", record.ID, namespaceState{Owner: owner, Record: record})) mustJournal(t, s.journal.saveState(context.Background(), "namespace", "zz-missing", namespaceState{Owner: owner, Record: containment.Record{ID: "missing", AttemptKey: "missing"}})) if _, err = s.cleanup(context.Background(), r); err == nil { t.Fatal("missing namespace proof accepted") } if _, err = os.Stat(work); err != nil { t.Fatal("removed check checkout before every namespace was contained") } } func TestDirectBugRuntimeRenewHeartbeat(t *testing.T) { c := directRuntimeFixture(t) r, err := openRuntime(context.Background(), c) mustJournal(t, err) defer r.Close() r.lastReports = []runnerproto.ConnectionReport{{LocalID: "cached"}} var paths []string r.api.client.Transport = transportFunc(func(q *http.Request) (*http.Response, error) { paths = append(paths, q.URL.Path) return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"version":2,"result":null}`))}, nil }) mustJournal(t, r.Call(context.Background(), "renew", runnerproto.RunnerRequest{Version: 2, AssignmentID: "assignment", RequestID: "renew"}, nil)) if len(paths) != 2 || !strings.HasSuffix(paths[0], "/heartbeat") || !strings.HasSuffix(paths[1], "/renew") { t.Fatalf("active connection liveness was not renewed: %v", paths) } } func TestDirectLegacyJournalCannotResume(t *testing.T) { s, r, _, order := cleanupFixture(t) r.Phase = "turn" mustJournal(t, s.save(context.Background(), r)) if err := s.Recover(context.Background()); err == nil { t.Fatal("unfinished historical work was resumed") } if s.ready { t.Fatal("admission opened before historical containment") } if len(*order) != 1 || (*order)[0] != "stop" { t.Fatal("legacy attempt was not fenced without claiming containment", *order) } var records []attemptState mustJournal(t, s.journal.readStates(context.Background(), "attempt", &records)) if len(records) != 1 || records[0].Proof != nil || records[0].Phase != "turn" { t.Fatal("fabricated historical containment", records) } } func TestDirectClaimRevalidates(t *testing.T) { c := directRuntimeFixture(t) r, err := openRuntime(context.Background(), c) mustJournal(t, err) defer r.Close() var paths []string r.api.client.Transport = transportFunc(func(q *http.Request) (*http.Response, error) { paths = append(paths, q.URL.Path) if strings.HasSuffix(q.URL.Path, "/heartbeat") { var heartbeat runnerproto.HeartbeatRequest mustJournal(t, runnerproto.DecodeLimit(q.Body, &heartbeat, 1<<20)) var reports []runnerproto.ConnectionReport mustJournal(t, json.Unmarshal(heartbeat.Reports, &reports)) if len(reports) != 1 || reports[0].Available { t.Fatal("stale account remained available", reports) } return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"version":2,"result":null}`))}, nil } return &http.Response{StatusCode: 403, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"version":2,"error":"form.forbidden"}`))}, nil }) if _, err = r.Claim(context.Background(), runnerproto.ClaimRequest{Version: 2, AssignmentID: "assignment", Revision: 1, RequestID: "claim"}); err == nil { t.Fatal("refused claim accepted") } if len(paths) != 2 || !strings.HasSuffix(paths[0], "/heartbeat") || !strings.HasSuffix(paths[1], "/claim") { t.Fatal("claim skipped fresh discovery", paths) } binding, err := c.DirectBinding(AccountBinding{ID: "id", ProviderHome: "/unopened", Provider: "codex", AccountID: "account"}) mustJournal(t, err) if binding.DedicatedHome || binding.VerifiedDedicatedHome() { t.Fatal("configuration granted home provenance") } } func TestRunnerSweepsStaleDescriptionTokens(t *testing.T) { c := directRuntimeFixture(t) mustJournal(t, os.MkdirAll(c.ScratchRoot, 0700)) stale := filepath.Join(c.ScratchRoot, "describe-stale") mustJournal(t, os.Mkdir(stale, 0700)) mustJournal(t, os.WriteFile(filepath.Join(stale, "credentials"), []byte("fake-old-token"), 0600)) keep := filepath.Join(c.ScratchRoot, "keep") mustJournal(t, os.WriteFile(keep, []byte("keep"), 0600)) r, err := openRuntime(context.Background(), c) mustJournal(t, err) defer r.Close() if _, err = os.Stat(stale); !os.IsNotExist(err) { t.Fatal("stale token directory survived startup") } if _, err = os.Stat(keep); err != nil { t.Fatal("unrelated scratch removed") } }