oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package provider
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "os"
9 "os/user"
10 "path/filepath"
11 "strconv"
12 "strings"
13 "testing"
14
15 "golang.org/x/sys/unix"
16)
17
18func accountFixture(t *testing.T) (Binding, HomeRules) {
19 t.Helper()
20 root := t.TempDir()
21 home := filepath.Join(root, "dedicated")
22 if e := os.Mkdir(home, 0700); e != nil {
23 t.Fatal(e)
24 }
25 identity := Identity{AccountID: "account", HomeID: "enrolled-home", ProviderVersion: "0.165.0"}
26 b := Binding{ID: "binding", Home: home, AccountID: "account", Provider: "codex", Expected: identity, RuntimeRoot: filepath.Join(root, "homes")}
27 writeMetadata(t, home, identity)
28 writeFake(t, filepath.Join(home, "auth.json"), `{"token":"fake-one"}`)
29 return b, HomeRules{InteractiveHomes: []string{filepath.Join(root, "interactive")}}
30}
31func writeFake(t *testing.T, path, s string) {
32 t.Helper()
33 if e := os.WriteFile(path, []byte(s), 0600); e != nil {
34 t.Fatal(e)
35 }
36}
37func writeMetadata(t *testing.T, home string, id Identity) {
38 t.Helper()
39 raw, _ := json.Marshal(id)
40 writeFake(t, filepath.Join(home, IdentityFile), string(raw))
41}
42func openFixture(t *testing.T, b Binding, r HomeRules) *AccountLease {
43 t.Helper()
44 l, e := openAccount(context.Background(), b, r)
45 if e != nil {
46 t.Fatal(e)
47 }
48 t.Cleanup(func() { l.Close() })
49 return l
50}
51func preflightFixture(t *testing.T, l *AccountLease) {
52 t.Helper()
53 if e := l.Preflight(context.Background(), func(context.Context, Binding) (Identity, error) { return l.Identity(), nil }); e != nil {
54 t.Fatal(e)
55 }
56}
57
58func TestAccountHomeBinding(t *testing.T) {
59 t.Run("dedicated provenance", func(t *testing.T) {
60 b, r := accountFixture(t)
61 b.DedicatedHome = true
62 if b.VerifiedDedicatedHome() {
63 t.Fatal("input boolean granted authority")
64 }
65 l := openFixture(t, b, r)
66 if !l.Binding().VerifiedDedicatedHome() {
67 t.Fatal("verified lease lost provenance")
68 }
69 wire, _ := json.Marshal(l.Binding())
70 var forged Binding
71 json.Unmarshal(wire, &forged)
72 if forged.VerifiedDedicatedHome() {
73 t.Fatal("wire input granted authority")
74 }
75 altered := l.Binding()
76 altered.AccountID = "other"
77 if altered.VerifiedDedicatedHome() {
78 t.Fatal("altered binding retained authority")
79 }
80 if e := l.Validate(context.Background()); !errors.Is(e, ErrPreflightRequired) {
81 t.Fatalf("unobserved identity accepted: %v", e)
82 }
83 preflightFixture(t, l)
84 if e := l.Validate(context.Background()); e != nil {
85 t.Fatal(e)
86 }
87 l.Close()
88 if l.Binding().VerifiedDedicatedHome() {
89 t.Fatal("closed lease retained authority")
90 }
91 })
92 t.Run("identity", func(t *testing.T) {
93 b, r := accountFixture(t)
94 b.Expected.AccountID = "other"
95 if l, e := openAccount(context.Background(), b, r); e == nil {
96 l.Close()
97 t.Fatal("wrong expected identity accepted")
98 }
99 })
100 t.Run("missing metadata", func(t *testing.T) {
101 b, r := accountFixture(t)
102 os.Remove(filepath.Join(b.Home, IdentityFile))
103 if l, e := openAccount(context.Background(), b, r); e == nil {
104 l.Close()
105 t.Fatal("missing metadata accepted")
106 }
107 })
108 t.Run("shared and aliases", func(t *testing.T) {
109 b, r := accountFixture(t)
110 r.InteractiveHomes = []string{b.Home}
111 for _, name := range []string{b.Home, filepath.Join(filepath.Dir(b.Home), "alias")} {
112 if name != b.Home {
113 if e := os.Symlink(b.Home, name); e != nil {
114 t.Fatal(e)
115 }
116 }
117 candidate := b
118 candidate.Home = name
119 if l, e := openAccount(context.Background(), candidate, r); e == nil {
120 l.Close()
121 t.Fatal("shared home accepted")
122 }
123 }
124 // Inode comparison is exercised independently of path spelling (bind alias semantics).
125 f, e := os.Open(b.Home)
126 if e != nil {
127 t.Fatal(e)
128 }
129 defer f.Close()
130 info, _ := f.Stat()
131 if !r.refusedInode(info) {
132 t.Fatal("shared inode accepted")
133 }
134 })
135 t.Run("real defaults path only", func(t *testing.T) {
136 r := DefaultHomeRules()
137 for _, p := range r.InteractiveHomes {
138 if !r.RefusesPath(p) {
139 t.Fatal("default shared home accepted")
140 }
141 }
142 if !r.RefusesPath("/home/example/.paseo/zerosub/homes/fake") {
143 t.Fatal("ZeroSub accepted")
144 }
145 })
146 t.Run("private modes", func(t *testing.T) {
147 b, r := accountFixture(t)
148 os.Chmod(filepath.Join(b.Home, "auth.json"), 0644)
149 if l, e := openAccount(context.Background(), b, r); e == nil {
150 l.Close()
151 t.Fatal("public credentials accepted")
152 }
153 })
154}
155func TestAccountUnavailableDoesNotFailover(t *testing.T) {
156 for _, failure := range []error{ErrAccountMaintenance, ErrIdentity, Error("quota")} {
157 t.Run(failure.Error(), func(t *testing.T) {
158 b, r := accountFixture(t)
159 l := openFixture(t, b, r)
160 preflightFixture(t, l)
161 calls, prompts := 0, 0
162 e := l.Preflight(context.Background(), func(_ context.Context, got Binding) (Identity, error) {
163 calls++
164 if got.AccountID != b.AccountID {
165 t.Fatal("fallback account")
166 }
167 return Identity{}, failure
168 })
169 if e == nil {
170 t.Fatal("failure accepted")
171 }
172 if l.BeginTurn(context.Background()) == nil {
173 prompts++
174 }
175 if calls != 1 || prompts != 0 {
176 t.Fatalf("calls=%d prompts=%d", calls, prompts)
177 }
178 })
179 }
180}
181func TestAccountHomeMutation(t *testing.T) {
182 t.Run("replacement", func(t *testing.T) {
183 b, r := accountFixture(t)
184 l := openFixture(t, b, r)
185 preflightFixture(t, l)
186 os.Rename(b.Home, b.Home+"-old")
187 os.Symlink(b.Home+"-old", b.Home)
188 if e := l.Validate(context.Background()); !errors.Is(e, ErrContainment) {
189 t.Fatalf("replacement accepted: %v", e)
190 }
191 })
192 t.Run("lock", func(t *testing.T) {
193 b, r := accountFixture(t)
194 l := openFixture(t, b, r)
195 if other, e := openAccount(context.Background(), b, r); !errors.Is(e, ErrAccountBusy) {
196 if other != nil {
197 other.Close()
198 }
199 t.Fatalf("concurrent lease accepted: %v", e)
200 }
201 l.Close()
202 openFixture(t, b, r)
203 })
204 t.Run("lock release with inherited descriptor", func(t *testing.T) {
205 b, r := accountFixture(t)
206 l := openFixture(t, b, r)
207 inherited, err := unix.FcntlInt(l.dir.Fd(), unix.F_DUPFD_CLOEXEC, 0)
208 if err != nil {
209 t.Fatal(err)
210 }
211 defer unix.Close(inherited)
212 if err := l.Close(); err != nil {
213 t.Fatal(err)
214 }
215 openFixture(t, b, r)
216 })
217 for _, kind := range []string{"successful refresh", "failed refresh", "identity change", "active change"} {
218 t.Run(kind, func(t *testing.T) {
219 b, r := accountFixture(t)
220 l := openFixture(t, b, r)
221 preflightFixture(t, l)
222 if kind == "active change" {
223 if e := l.BeginTurn(context.Background()); e != nil {
224 t.Fatal(e)
225 }
226 }
227 writeFake(t, filepath.Join(b.Home, "replacement"), `{"token":"fake-two"}`)
228 os.Rename(filepath.Join(b.Home, "replacement"), filepath.Join(b.Home, "auth.json"))
229 if kind == "identity change" {
230 id := b.Expected
231 id.AccountID = "different"
232 writeMetadata(t, b.Home, id)
233 }
234 want := ErrPreflightRequired
235 if kind == "identity change" {
236 want = ErrIdentity
237 }
238 if kind == "active change" {
239 want = ErrContainment
240 }
241 if e := l.Validate(context.Background()); !errors.Is(e, want) {
242 t.Fatalf("got %v want %v", e, want)
243 }
244 if kind == "successful refresh" {
245 preflightFixture(t, l)
246 if e := l.BeginTurn(context.Background()); e != nil {
247 t.Fatal(e)
248 }
249 if e := l.EndTurn(context.Background()); e != nil {
250 t.Fatal(e)
251 }
252 }
253 if kind == "failed refresh" {
254 e := l.Preflight(context.Background(), func(context.Context, Binding) (Identity, error) { return Identity{}, ErrAccountMaintenance })
255 if !errors.Is(e, ErrAccountMaintenance) {
256 t.Fatal(e)
257 }
258 if l.BeginTurn(context.Background()) == nil {
259 t.Fatal("failed refresh dispatched")
260 }
261 }
262 })
263 }
264}
265func TestPrivateHomeDoesNotTouchInteractiveConfig(t *testing.T) {
266 b, r := accountFixture(t)
267 interactive := r.InteractiveHomes[0]
268 os.Mkdir(interactive, 0700)
269 path := filepath.Join(interactive, "config.toml")
270 writeFake(t, path, "original untrusted config")
271 l := openFixture(t, b, r)
272 preflightFixture(t, l)
273 home := l.Binding().Home
274 raw, e := os.ReadFile(filepath.Join(home, "auth.json"))
275 if e != nil || string(raw) != `{"token":"fake-one"}` {
276 t.Fatal("login not staged", e)
277 }
278 for _, p := range []string{home, filepath.Join(home, "auth.json")} {
279 info, e := os.Stat(p)
280 if e != nil {
281 t.Fatal(e)
282 }
283 want := os.FileMode(0600)
284 if info.IsDir() {
285 want = 0700
286 }
287 if info.Mode().Perm() != want {
288 t.Fatal("nonprivate runtime")
289 }
290 }
291 got, _ := os.ReadFile(path)
292 entries, _ := os.ReadDir(interactive)
293 if string(got) != "original untrusted config" || len(entries) != 1 {
294 t.Fatal("interactive config changed")
295 }
296 l.Close()
297 if _, e = os.Stat(home); !os.IsNotExist(e) {
298 t.Fatal("runtime leaked")
299 }
300}
301
302func TestAccountHomeRuntimeGuards(t *testing.T) {
303 t.Run("runtime symlink", func(t *testing.T) {
304 b, r := accountFixture(t)
305 l := openFixture(t, b, r)
306 preflightFixture(t, l)
307 target := filepath.Join(l.Binding().Home, "auth.json")
308 os.Remove(target)
309 os.Symlink(filepath.Join(b.Home, "auth.json"), target)
310 if l.Preflight(context.Background(), func(context.Context, Binding) (Identity, error) { return b.Expected, nil }) == nil {
311 t.Fatal("runtime symlink accepted")
312 }
313 })
314 t.Run("same bytes new generation", func(t *testing.T) {
315 b, r := accountFixture(t)
316 l := openFixture(t, b, r)
317 preflightFixture(t, l)
318 writeFake(t, filepath.Join(b.Home, "new"), `{"token":"fake-one"}`)
319 os.Rename(filepath.Join(b.Home, "new"), filepath.Join(b.Home, "auth.json"))
320 if l.Validate(context.Background()) == nil {
321 t.Fatal("atomic generation not detected")
322 }
323 })
324 t.Run("runtime active mutation", func(t *testing.T) {
325 b, r := accountFixture(t)
326 l := openFixture(t, b, r)
327 preflightFixture(t, l)
328 l.BeginTurn(context.Background())
329 writeFake(t, filepath.Join(l.Binding().Home, "auth.json"), `{"token":"fake-new"}`)
330 if !errors.Is(l.EndTurn(context.Background()), Error("provider_refresh_pending")) {
331 t.Fatal("active runtime mutation accepted")
332 }
333 })
334 t.Run("controlled refresh", func(t *testing.T) {
335 b, r := accountFixture(t)
336 l := openFixture(t, b, r)
337 preflightFixture(t, l)
338 writeFake(t, filepath.Join(l.Binding().Home, "auth.json"), `{"token":"fake-refreshed"}`)
339 if e := l.CommitRefresh(context.Background(), func(_ context.Context, got Binding) (Identity, error) {
340 if !got.VerifiedDedicatedHome() {
341 t.Fatal("probe lost provenance")
342 }
343 return b.Expected, nil
344 }); e != nil {
345 t.Fatal(e)
346 }
347 if !errors.Is(l.Validate(context.Background()), ErrPreflightRequired) {
348 t.Fatal("refresh skipped preflight")
349 }
350 preflightFixture(t, l)
351 raw, _ := os.ReadFile(filepath.Join(b.Home, "auth.json"))
352 if string(raw) != `{"token":"fake-refreshed"}` {
353 t.Fatal("refresh not committed")
354 }
355 })
356}
357
358func TestAccountHomeRuntimeAliasNoSideEffects(t *testing.T) {
359 b, r := accountFixture(t)
360 interactive := r.InteractiveHomes[0]
361 if e := os.Mkdir(interactive, 0700); e != nil {
362 t.Fatal(e)
363 }
364 alias := filepath.Join(filepath.Dir(b.Home), "runtime-alias")
365 if e := os.Symlink(interactive, alias); e != nil {
366 t.Fatal(e)
367 }
368 b.RuntimeRoot = filepath.Join(alias, "new")
369 if l, e := openAccount(context.Background(), b, r); e == nil {
370 l.Close()
371 t.Fatal("runtime alias accepted")
372 }
373 entries, e := os.ReadDir(interactive)
374 if e != nil || len(entries) != 0 {
375 t.Fatal("interactive directory changed", e)
376 }
377}
378func TestAccountHomeFileGuards(t *testing.T) {
379 for _, kind := range []string{"directory mode", "credential hardlink", "metadata trailing", "metadata duplicate", "metadata missing home"} {
380 t.Run(kind, func(t *testing.T) {
381 b, r := accountFixture(t)
382 switch kind {
383 case "directory mode":
384 os.Chmod(b.Home, 0755)
385 case "credential hardlink":
386 os.Link(filepath.Join(b.Home, "auth.json"), filepath.Join(filepath.Dir(b.Home), "linked"))
387 case "metadata trailing":
388 raw, _ := json.Marshal(b.Expected)
389 writeFake(t, filepath.Join(b.Home, IdentityFile), string(raw)+`{}`)
390 case "metadata duplicate":
391 writeFake(t, filepath.Join(b.Home, IdentityFile), `{"account_id":"account","account_id":"account","home_id":"enrolled-home","provider_version":"0.165.0"}`)
392 case "metadata missing home":
393 id := b.Expected
394 id.HomeID = ""
395 writeMetadata(t, b.Home, id)
396 }
397 if l, e := openAccount(context.Background(), b, r); e == nil {
398 l.Close()
399 t.Fatal("unsafe account input accepted")
400 }
401 })
402 }
403}
404
405func TestAccountHomePreflightGuards(t *testing.T) {
406 t.Run("observed identity", func(t *testing.T) {
407 b, r := accountFixture(t)
408 l := openFixture(t, b, r)
409 id := b.Expected
410 id.AccountID = "other"
411 if e := l.Preflight(context.Background(), func(context.Context, Binding) (Identity, error) { return id, nil }); !errors.Is(e, ErrIdentity) {
412 t.Fatal("wrong CLI identity accepted", e)
413 }
414 })
415 t.Run("generation during probe", func(t *testing.T) {
416 b, r := accountFixture(t)
417 l := openFixture(t, b, r)
418 if e := l.Preflight(context.Background(), func(context.Context, Binding) (Identity, error) {
419 writeFake(t, filepath.Join(b.Home, "auth.json"), `{"token":"changed-during-probe"}`)
420 return b.Expected, nil
421 }); !errors.Is(e, ErrPreflightRequired) {
422 t.Fatal("unstable probe accepted", e)
423 }
424 })
425 t.Run("refresh identity", func(t *testing.T) {
426 b, r := accountFixture(t)
427 l := openFixture(t, b, r)
428 preflightFixture(t, l)
429 writeFake(t, filepath.Join(l.Binding().Home, "auth.json"), `{"token":"wrong-account"}`)
430 id := b.Expected
431 id.AccountID = "other"
432 if e := l.CommitRefresh(context.Background(), func(context.Context, Binding) (Identity, error) { return id, nil }); !errors.Is(e, ErrIdentity) {
433 t.Fatal("wrong refresh accepted", e)
434 }
435 raw, _ := os.ReadFile(filepath.Join(b.Home, "auth.json"))
436 if string(raw) != `{"token":"fake-one"}` {
437 t.Fatal("failed refresh modified dedicated home")
438 }
439 })
440 t.Run("claude", func(t *testing.T) {
441 b, r := accountFixture(t)
442 b.Provider = "claude"
443 b.Expected.ProviderVersion = "2.1.312"
444 writeMetadata(t, b.Home, b.Expected)
445 writeFake(t, filepath.Join(b.Home, ".credentials.json"), `{"token":"fake-claude"}`)
446 l := openFixture(t, b, r)
447 preflightFixture(t, l)
448 if _, e := os.Stat(filepath.Join(l.Binding().Home, "auth.json")); !os.IsNotExist(e) {
449 t.Fatal("other provider login copied")
450 }
451 })
452}
453
454func TestAccountRefreshPending(t *testing.T) {
455 for _, active := range []bool{false, true} {
456 t.Run(fmt.Sprint(active), func(t *testing.T) {
457 b, r := accountFixture(t)
458 l := openFixture(t, b, r)
459 preflightFixture(t, l)
460 ctx := context.Background()
461 if active {
462 if e := l.BeginTurn(ctx); e != nil {
463 t.Fatal(e)
464 }
465 }
466 path := filepath.Join(l.Binding().Home, "auth.json")
467 refreshed := `{"token":"rotated"}`
468 writeFake(t, path, refreshed)
469 var e error
470 if active {
471 e = l.EndTurn(ctx)
472 } else {
473 e = l.Validate(ctx)
474 }
475 if !errors.Is(e, Error("provider_refresh_pending")) {
476 t.Fatalf("refresh must be pending: %v", e)
477 }
478 calls := 0
479 probe := func(context.Context, Binding) (Identity, error) { calls++; return b.Expected, nil }
480 if e = l.Preflight(ctx, probe); !errors.Is(e, Error("provider_refresh_pending")) {
481 t.Errorf("preflight must preserve pending refresh: %v", e)
482 }
483 raw, _ := os.ReadFile(path)
484 if string(raw) != refreshed || calls != 0 {
485 t.Fatal("preflight overwrote rotated login or probed stale login")
486 }
487 if e = l.CommitRefresh(ctx, probe); e != nil {
488 t.Fatal(e)
489 }
490 if e = l.BeginTurn(ctx); !errors.Is(e, ErrPreflightRequired) {
491 t.Fatalf("refresh skipped preflight: %v", e)
492 }
493 preflightFixture(t, l)
494 if e = l.BeginTurn(ctx); e != nil {
495 t.Fatal(e)
496 }
497 if e = l.EndTurn(ctx); e != nil {
498 t.Fatal(e)
499 }
500 raw, _ = os.ReadFile(filepath.Join(b.Home, "auth.json"))
501 if string(raw) != refreshed {
502 t.Fatal("rotated login lost")
503 }
504 })
505 }
506}
507func TestAccountContainmentLatched(t *testing.T) {
508 for _, kind := range []string{"source", "identity", "runtime-identity", "symlink", "nonregular"} {
509 t.Run(kind, func(t *testing.T) {
510 b, r := accountFixture(t)
511 l := openFixture(t, b, r)
512 preflightFixture(t, l)
513 ctx := context.Background()
514 if e := l.BeginTurn(ctx); e != nil {
515 t.Fatal(e)
516 }
517 runtime := l.Binding().Home
518 switch kind {
519 case "source":
520 writeFake(t, filepath.Join(b.Home, "auth.json"), `{"token":"external"}`)
521 case "identity", "runtime-identity":
522 home := b.Home
523 if kind == "runtime-identity" {
524 home = runtime
525 }
526 id := b.Expected
527 id.AccountID = "changed"
528 writeMetadata(t, home, id)
529 case "symlink", "nonregular":
530 path := filepath.Join(runtime, "auth.json")
531 if e := os.Remove(path); e != nil {
532 t.Fatal(e)
533 }
534 if kind == "symlink" {
535 if e := os.Symlink(filepath.Join(b.Home, "auth.json"), path); e != nil {
536 t.Fatal(e)
537 }
538 } else {
539 if e := os.Mkdir(path, 0700); e != nil {
540 t.Fatal(e)
541 }
542 }
543 }
544 if e := l.EndTurn(ctx); !errors.Is(e, ErrContainment) {
545 t.Errorf("active tampering not contained: %v", e)
546 }
547 // Restore the inputs: a contained lease still cannot recover authority.
548 writeMetadata(t, b.Home, b.Expected)
549 writeMetadata(t, runtime, b.Expected)
550 if kind == "symlink" || kind == "nonregular" {
551 if e := os.Remove(filepath.Join(runtime, "auth.json")); e != nil {
552 t.Fatal(e)
553 }
554 }
555 writeFake(t, filepath.Join(runtime, "auth.json"), `{"token":"fake-one"}`)
556 if e := l.Preflight(ctx, func(context.Context, Binding) (Identity, error) { return b.Expected, nil }); !errors.Is(e, ErrContainment) {
557 t.Fatalf("containment not latched: %v", e)
558 }
559 if l.Binding().VerifiedDedicatedHome() {
560 t.Fatal("contained lease retained provenance")
561 }
562 if e := l.BeginTurn(ctx); !errors.Is(e, ErrContainment) {
563 t.Fatalf("contained lease admitted turn: %v", e)
564 }
565
566 })
567 }
568}
569func TestAccountHomeDefaultsIgnoreEnvironment(t *testing.T) {
570 u, e := user.LookupId(strconv.Itoa(os.Geteuid()))
571 if e != nil {
572 t.Fatal(e)
573 }
574 for _, home := range []string{"", t.TempDir()} {
575 t.Setenv("HOME", home)
576 r := DefaultHomeRules()
577 for _, name := range []string{".claude", ".codex"} {
578 if !r.RefusesPath(filepath.Join(u.HomeDir, name)) {
579 t.Fatal("passwd home accepted with changed HOME")
580 }
581 }
582 }
583 for _, key := range []string{"CODEX_HOME", "CLAUDE_CONFIG_DIR"} {
584 path := filepath.Join(t.TempDir(), "interactive")
585 t.Setenv(key, path)
586 if !DefaultHomeRules().RefusesPath(path) {
587 t.Fatalf("inherited %s accepted", key)
588 }
589 }
590}
591
592func TestAccountHomeLookupFailClosed(t *testing.T) {
593 for _, u := range []*user.User{nil, {}, {HomeDir: "relative"}, {HomeDir: "/"}} {
594 rules := homeRules(func(string) (*user.User, error) { return u, nil }, func(string) string { return "" })
595 if !rules.RefusesPath("/owned/fake-home") {
596 t.Fatal("missing passwd home accepted")
597 }
598 }
599 rules := homeRules(func(string) (*user.User, error) { return nil, errors.New("lookup failed") }, func(string) string { return "" })
600 if !rules.RefusesPath("/owned/fake-home") {
601 t.Fatal("failed passwd lookup accepted")
602 }
603}
604func TestAccountRefreshPreflightPreservesLogin(t *testing.T) {
605 b, r := accountFixture(t)
606 l := openFixture(t, b, r)
607 preflightFixture(t, l)
608 path := filepath.Join(l.Binding().Home, "auth.json")
609 writeFake(t, path, `{"token":"rotated"}`)
610 e := l.Preflight(context.Background(), func(context.Context, Binding) (Identity, error) {
611 t.Error("pending refresh probed")
612 return b.Expected, nil
613 })
614 raw, _ := os.ReadFile(path)
615 if string(raw) != `{"token":"rotated"}` {
616 t.Fatal("pending refresh overwritten")
617 }
618 if !errors.Is(e, Error("provider_refresh_pending")) {
619 t.Fatalf("not refresh pending: %v", e)
620 }
621}
622
623func TestAccountContainmentPreflightLatched(t *testing.T) {
624 for _, kind := range []string{"source", "identity", "runtime"} {
625 t.Run(kind, func(t *testing.T) {
626 b, r := accountFixture(t)
627 l := openFixture(t, b, r)
628 preflightFixture(t, l)
629 home := b.Home
630 if kind == "runtime" {
631 home = l.Binding().Home
632 }
633 if kind == "identity" {
634 id := b.Expected
635 id.AccountID = "changed"
636 writeMetadata(t, home, id)
637 } else {
638 if e := os.Rename(home, home+"-old"); e != nil {
639 t.Fatal(e)
640 }
641 if e := os.Symlink(home+"-old", home); e != nil {
642 t.Fatal(e)
643 }
644 }
645 probe := func(context.Context, Binding) (Identity, error) { return b.Expected, nil }
646 if e := l.Preflight(context.Background(), probe); e == nil {
647 t.Fatal("tampered preflight accepted")
648 }
649 if kind == "identity" {
650 writeMetadata(t, home, b.Expected)
651 } else {
652 if e := os.Remove(home); e != nil {
653 t.Fatal(e)
654 }
655 if e := os.Rename(home+"-old", home); e != nil {
656 t.Fatal(e)
657 }
658 }
659 if e := l.Preflight(context.Background(), probe); !errors.Is(e, ErrContainment) {
660 t.Fatalf("preflight containment not latched: %v", e)
661 }
662 })
663 }
664}
665
666func TestAccountContainmentSourceFile(t *testing.T) {
667 for _, kind := range []string{"symlink", "directory"} {
668 t.Run(kind, func(t *testing.T) {
669 b, r := accountFixture(t)
670 l := openFixture(t, b, r)
671 preflightFixture(t, l)
672 path := filepath.Join(b.Home, "auth.json")
673 if e := os.Remove(path); e != nil {
674 t.Fatal(e)
675 }
676 if kind == "symlink" {
677 if e := os.Symlink(filepath.Join(l.Binding().Home, "auth.json"), path); e != nil {
678 t.Fatal(e)
679 }
680 } else {
681 if e := os.Mkdir(path, 0700); e != nil {
682 t.Fatal(e)
683 }
684 }
685 if e := l.Validate(context.Background()); !errors.Is(e, ErrContainment) {
686 t.Errorf("unsafe source not contained: %v", e)
687 }
688 if e := os.Remove(path); e != nil {
689 t.Fatal(e)
690 }
691 writeFake(t, path, `{"token":"fake-one"}`)
692 if e := l.Preflight(context.Background(), func(context.Context, Binding) (Identity, error) { return b.Expected, nil }); !errors.Is(e, ErrContainment) {
693 t.Fatalf("unsafe source containment not latched: %v", e)
694 }
695 })
696 }
697}
698
699func TestAccountRefreshFailure(t *testing.T) {
700 for _, kind := range []string{"maintenance", "identity"} {
701 t.Run(kind, func(t *testing.T) {
702 b, r := accountFixture(t)
703 l := openFixture(t, b, r)
704 preflightFixture(t, l)
705 path := filepath.Join(l.Binding().Home, "auth.json")
706 writeFake(t, path, `{"token":"rotated"}`)
707 e := l.CommitRefresh(context.Background(), func(context.Context, Binding) (Identity, error) {
708 if kind == "maintenance" {
709 return Identity{}, ErrAccountMaintenance
710 }
711 id := b.Expected
712 id.AccountID = "different"
713 return id, nil
714 })
715 want := ErrAccountMaintenance
716 if kind == "identity" {
717 want = ErrIdentity
718 }
719 if !errors.Is(e, want) {
720 t.Fatalf("refresh failure lost: %v", e)
721 }
722 raw, _ := os.ReadFile(filepath.Join(b.Home, "auth.json"))
723 if string(raw) != `{"token":"fake-one"}` {
724 t.Fatal("failed refresh committed")
725 }
726 writeFake(t, path, `{"token":"fake-one"}`)
727 e = l.Preflight(context.Background(), func(context.Context, Binding) (Identity, error) { return b.Expected, nil })
728 if kind == "identity" && !errors.Is(e, ErrContainment) {
729 t.Fatalf("wrong refresh identity not latched: %v", e)
730 }
731 })
732 }
733}
734
735func TestRuntimeHomeRejectsPolicyInjection(t *testing.T) {
736 for _, name := range []string{"config.toml", "AGENTS.md", "CLAUDE.md", "settings.json", "hooks", "sessions/AGENTS.md"} {
737 for _, resume := range []bool{false, true} {
738 t.Run(fmt.Sprint(name, resume), func(t *testing.T) {
739 b, r := accountFixture(t)
740 l := openFixture(t, b, r)
741 preflightFixture(t, l)
742 path := filepath.Join(l.Binding().Home, name)
743 if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
744 t.Fatal(err)
745 }
746 writeFake(t, path, "injected policy")
747 var err error
748 if resume {
749 err = l.ValidatePolicy(context.Background())
750 } else {
751 err = l.BeginTurn(context.Background())
752 }
753 if err == nil {
754 t.Fatal("runtime policy injection accepted")
755 }
756 })
757 }
758 }
759}
760func TestRefreshDoesNotOverwriteNewerSource(t *testing.T) {
761 b, r := accountFixture(t)
762 l := openFixture(t, b, r)
763 preflightFixture(t, l)
764 writeFake(t, filepath.Join(l.Binding().Home, "auth.json"), `{"token":"refreshed"}`)
765 writeFake(t, filepath.Join(b.Home, "auth.json"), `{"token":"newer-source"}`)
766 if err := l.CommitRefresh(context.Background(), func(context.Context, Binding) (Identity, error) { return b.Expected, nil }); err == nil {
767 t.Fatal("new source overwritten by older refresh")
768 }
769 raw, _ := os.ReadFile(filepath.Join(b.Home, "auth.json"))
770 if !strings.Contains(string(raw), "newer-source") {
771 t.Fatal("newer login lost")
772 }
773}
774
775func TestPreflightFingerprintTracksSource(t *testing.T) {
776 b, r := accountFixture(t)
777 l := openFixture(t, b, r)
778 first, err := l.PreflightFingerprint(context.Background())
779 if err != nil {
780 t.Fatal(err)
781 }
782 again, err := l.PreflightFingerprint(context.Background())
783 if err != nil || again != first {
784 t.Fatal("unchanged source invalidated cache", err)
785 }
786 writeFake(t, filepath.Join(b.Home, "auth.json"), `{"token":"different"}`)
787 changed, err := l.PreflightFingerprint(context.Background())
788 if err != nil || changed == first {
789 t.Fatal("source generation omitted from cache key", err)
790 }
791}
792