| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 17 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 18 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 19 | ) |
| 20 | |
| 21 | func directRuntimeFixture(t *testing.T) Config { |
| 22 | c := runtimeFixture(t) |
| 23 | c.Executable, _ = os.Executable() |
| 24 | c.ClaudePath = c.CodexPath |
| 25 | c.ModuleCache = t.TempDir() |
| 26 | // No credential file or account lease is needed to open and wire the runtime. |
| 27 | 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"}} |
| 28 | mustJournal(t, os.WriteFile(c.AccountBindingsPath, marshal([]AccountBinding{b}), 0600)) |
| 29 | return c |
| 30 | } |
| 31 | |
| 32 | func TestDirectBugRuntime(t *testing.T) { |
| 33 | c := directRuntimeFixture(t) |
| 34 | r, err := openRuntime(context.Background(), c) |
| 35 | mustJournal(t, err) |
| 36 | defer r.Close() |
| 37 | mustJournal(t, r.wire(context.Background())) |
| 38 | if r.namespaces == nil || len(r.launchers) != 2 || r.service.Supervisor.namespaces != r.namespaces { |
| 39 | t.Fatal("runtime did not construct direct services") |
| 40 | } |
| 41 | host, ok := r.host.(*directHost) |
| 42 | if !ok || host.journal != r.journal || host.manager != r.namespaces { |
| 43 | t.Fatal("namespace launches bypass durable host") |
| 44 | } |
| 45 | legacy := r.service.Supervisor.workflow.cfg |
| 46 | legacy.Launchers = nil |
| 47 | if _, err := NewBugWorkflow(legacy); err == nil { |
| 48 | t.Fatal("missing launcher registry authorized new workflow") |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | func TestDirectBugRuntimeRecoveryBeforeStart(t *testing.T) { |
| 53 | c := directRuntimeFixture(t) |
| 54 | mustJournal(t, os.Mkdir(c.ScratchRoot, 0700)) |
| 55 | record := containment.Record{ID: strings.Repeat("a", 32), AttemptKey: "orphan"} |
| 56 | mustJournal(t, os.WriteFile(filepath.Join(c.ScratchRoot, record.ID+".json"), marshal(record), 0600)) |
| 57 | if r, err := openRuntime(context.Background(), c); err == nil { |
| 58 | r.Close() |
| 59 | t.Fatal("admitted launchers before reconciling unknown namespace") |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | func TestDirectBugRuntimeClosesNamespaces(t *testing.T) { |
| 64 | s, r, m, host, l := directNamespaceFixture(t) |
| 65 | var manifest struct{ Argv []string } |
| 66 | mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest)) |
| 67 | p, err := host.Start(s.namespaceContext(context.Background(), r), l, manifest.Argv) |
| 68 | mustJournal(t, err) |
| 69 | t.Cleanup(func() { |
| 70 | m.Stop(context.Background(), p.ID()) |
| 71 | p.Stdout().Close() |
| 72 | p.Stderr().Close() |
| 73 | p.Stdin().Close() |
| 74 | }) |
| 75 | b := make([]byte, 6) |
| 76 | _, err = io.ReadFull(p.Stdout(), b) |
| 77 | mustJournal(t, err) |
| 78 | runtime := &Runtime{namespaces: m} |
| 79 | released := false |
| 80 | runtime.service = &Service{Supervisor: &Supervisor{activeRelease: func() error { |
| 81 | ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| 82 | defer cancel() |
| 83 | if _, err := p.Wait(ctx); err != nil { |
| 84 | return err |
| 85 | } |
| 86 | released = true |
| 87 | return nil |
| 88 | }}} |
| 89 | mustJournal(t, runtime.Close()) |
| 90 | if !released { |
| 91 | t.Fatal("runtime shutdown retained account lease after containment") |
| 92 | } |
| 93 | ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| 94 | defer cancel() |
| 95 | if _, err = p.Wait(ctx); err != nil { |
| 96 | t.Fatal("runtime shutdown left namespace alive") |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | func TestDirectCancelRetainsCheckUntilEveryProof(t *testing.T) { |
| 101 | c := directRuntimeFixture(t) |
| 102 | runtime, err := openRuntime(context.Background(), c) |
| 103 | mustJournal(t, err) |
| 104 | defer runtime.Close() |
| 105 | mustJournal(t, runtime.wire(context.Background())) |
| 106 | s := runtime.service.Supervisor |
| 107 | _, r, _, _ := cleanupFixture(t) |
| 108 | r.Direct = true |
| 109 | r.Proof = nil |
| 110 | s.api = &supervisorAPI{order: new([]string)} |
| 111 | root, err := os.MkdirTemp(c.WorkspaceRoot, "checks-") |
| 112 | mustJournal(t, err) |
| 113 | work := filepath.Join(root, "work") |
| 114 | mustJournal(t, os.Mkdir(work, 0700)) |
| 115 | raw := []byte(`{"Version":"checks-v1"}`) |
| 116 | hash := sha256.Sum256(raw) |
| 117 | l := provider.Launch{AttemptKey: "check-recorded", Workspace: work, Policy: provider.Policy{Manifest: raw, ManifestHash: hex.EncodeToString(hash[:]), Hash: strings.Repeat("c", 64)}} |
| 118 | record := containment.Record{ID: strings.Repeat("a", 32), AttemptKey: l.AttemptKey, BootID: "old-boot", ManifestHash: strings.Repeat("b", 64), PolicyHash: l.Policy.Hash} |
| 119 | mustJournal(t, s.journal.recordDirectLaunch(context.Background(), l, record)) |
| 120 | owner := attemptKey(r.Claim.Scope, r.Claim.Handle) |
| 121 | mustJournal(t, s.journal.saveState(context.Background(), "namespace", record.ID, namespaceState{Owner: owner, Record: record})) |
| 122 | mustJournal(t, s.journal.saveState(context.Background(), "namespace", "zz-missing", namespaceState{Owner: owner, Record: containment.Record{ID: "missing", AttemptKey: "missing"}})) |
| 123 | if _, err = s.cleanup(context.Background(), r); err == nil { |
| 124 | t.Fatal("missing namespace proof accepted") |
| 125 | } |
| 126 | if _, err = os.Stat(work); err != nil { |
| 127 | t.Fatal("removed check checkout before every namespace was contained") |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | func TestDirectBugRuntimeRenewHeartbeat(t *testing.T) { |
| 132 | c := directRuntimeFixture(t) |
| 133 | r, err := openRuntime(context.Background(), c) |
| 134 | mustJournal(t, err) |
| 135 | defer r.Close() |
| 136 | r.lastReports = []runnerproto.ConnectionReport{{LocalID: "cached"}} |
| 137 | var paths []string |
| 138 | r.api.client.Transport = transportFunc(func(q *http.Request) (*http.Response, error) { |
| 139 | paths = append(paths, q.URL.Path) |
| 140 | return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"version":2,"result":null}`))}, nil |
| 141 | }) |
| 142 | mustJournal(t, r.Call(context.Background(), "renew", runnerproto.RunnerRequest{Version: 2, AssignmentID: "assignment", RequestID: "renew"}, nil)) |
| 143 | if len(paths) != 2 || !strings.HasSuffix(paths[0], "/heartbeat") || !strings.HasSuffix(paths[1], "/renew") { |
| 144 | t.Fatalf("active connection liveness was not renewed: %v", paths) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | func TestDirectLegacyJournalCannotResume(t *testing.T) { |
| 149 | s, r, _, order := cleanupFixture(t) |
| 150 | r.Phase = "turn" |
| 151 | mustJournal(t, s.save(context.Background(), r)) |
| 152 | if err := s.Recover(context.Background()); err == nil { |
| 153 | t.Fatal("unfinished historical work was resumed") |
| 154 | } |
| 155 | if s.ready { |
| 156 | t.Fatal("admission opened before historical containment") |
| 157 | } |
| 158 | if len(*order) != 1 || (*order)[0] != "stop" { |
| 159 | t.Fatal("legacy attempt was not fenced without claiming containment", *order) |
| 160 | } |
| 161 | var records []attemptState |
| 162 | mustJournal(t, s.journal.readStates(context.Background(), "attempt", &records)) |
| 163 | if len(records) != 1 || records[0].Proof != nil || records[0].Phase != "turn" { |
| 164 | t.Fatal("fabricated historical containment", records) |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | func TestDirectClaimRevalidates(t *testing.T) { |
| 169 | c := directRuntimeFixture(t) |
| 170 | r, err := openRuntime(context.Background(), c) |
| 171 | mustJournal(t, err) |
| 172 | defer r.Close() |
| 173 | var paths []string |
| 174 | r.api.client.Transport = transportFunc(func(q *http.Request) (*http.Response, error) { |
| 175 | paths = append(paths, q.URL.Path) |
| 176 | if strings.HasSuffix(q.URL.Path, "/heartbeat") { |
| 177 | var heartbeat runnerproto.HeartbeatRequest |
| 178 | mustJournal(t, runnerproto.DecodeLimit(q.Body, &heartbeat, 1<<20)) |
| 179 | var reports []runnerproto.ConnectionReport |
| 180 | mustJournal(t, json.Unmarshal(heartbeat.Reports, &reports)) |
| 181 | if len(reports) != 1 || reports[0].Available { |
| 182 | t.Fatal("stale account remained available", reports) |
| 183 | } |
| 184 | return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"version":2,"result":null}`))}, nil |
| 185 | } |
| 186 | return &http.Response{StatusCode: 403, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"version":2,"error":"form.forbidden"}`))}, nil |
| 187 | }) |
| 188 | if _, err = r.Claim(context.Background(), runnerproto.ClaimRequest{Version: 2, AssignmentID: "assignment", Revision: 1, RequestID: "claim"}); err == nil { |
| 189 | t.Fatal("refused claim accepted") |
| 190 | } |
| 191 | if len(paths) != 2 || !strings.HasSuffix(paths[0], "/heartbeat") || !strings.HasSuffix(paths[1], "/claim") { |
| 192 | t.Fatal("claim skipped fresh discovery", paths) |
| 193 | } |
| 194 | binding, err := c.DirectBinding(AccountBinding{ID: "id", ProviderHome: "/unopened", Provider: "codex", AccountID: "account"}) |
| 195 | mustJournal(t, err) |
| 196 | if binding.DedicatedHome || binding.VerifiedDedicatedHome() { |
| 197 | t.Fatal("configuration granted home provenance") |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | func TestRunnerSweepsStaleDescriptionTokens(t *testing.T) { |
| 202 | c := directRuntimeFixture(t) |
| 203 | mustJournal(t, os.MkdirAll(c.ScratchRoot, 0700)) |
| 204 | stale := filepath.Join(c.ScratchRoot, "describe-stale") |
| 205 | mustJournal(t, os.Mkdir(stale, 0700)) |
| 206 | mustJournal(t, os.WriteFile(filepath.Join(stale, "credentials"), []byte("fake-old-token"), 0600)) |
| 207 | keep := filepath.Join(c.ScratchRoot, "keep") |
| 208 | mustJournal(t, os.WriteFile(keep, []byte("keep"), 0600)) |
| 209 | r, err := openRuntime(context.Background(), c) |
| 210 | mustJournal(t, err) |
| 211 | defer r.Close() |
| 212 | if _, err = os.Stat(stale); !os.IsNotExist(err) { |
| 213 | t.Fatal("stale token directory survived startup") |
| 214 | } |
| 215 | if _, err = os.Stat(keep); err != nil { |
| 216 | t.Fatal("unrelated scratch removed") |
| 217 | } |
| 218 | } |
| 219 | |