package main import ( "context" "strings" "testing" "time" . "claude-licence-manager/internal/licences" ) // design 39 bus-and-switch ยง10: an adoption whose key another licence has is refused, in the audit and as an event. func TestAnAdoptionWhoseKeyIsTakenIsRefused(t *testing.T) { ctx := context.Background() t.Run("an API key", func(t *testing.T) { mm := newMesh(t) _ = mm.store.SaveLicence(ctx, Licence{Name: "Ops-Key", Kind: "api-key"}) _, err := mm.m.adoptKey(ctx, "ops-key", "sk-ant-"+strings.Repeat("a", 40), "a test") if err == nil || !strings.Contains(err.Error(), "Ops-Key") { t.Fatalf("adopted a key whose key form is taken: %v", err) } if l, _ := mm.store.Licence(ctx, "ops-key"); l != nil { t.Fatal("the clashing licence was kept") } assertRefused(t, mm) }) t.Run("a login", func(t *testing.T) { mm := newMesh(t) _ = mm.store.SaveLicence(ctx, Licence{Name: "ACCT-1@example.org", Kind: "api-key"}) r := mm.login("laptop", "rt-laptop", true, t0.Add(-time.Minute)) adopted, err := mm.m.Consider(ctx, []Holdings{r}) if err != nil || len(adopted) != 0 { t.Fatalf("adopted %v (%v), want none", adopted, err) } if len(mm.vendor.exchanged) != 0 { t.Fatalf("a refused login was exchanged: %v", mm.vendor.exchanged) } if o, _ := mm.store.Outcome(ctx, Fingerprint("rt-laptop")); o != Refused { t.Fatalf("outcome %q, want refused", o) } assertRefused(t, mm) }) } func assertRefused(t *testing.T, mm *miniMesh) { t.Helper() said := false for _, e := range mm.events { said = said || strings.HasPrefix(e, "licence.refused ") } audited := false for _, a := range mm.audit.under("") { audited = audited || a["what"] == "refused" } if !said || !audited { t.Fatalf("refusal said %v, audited %v: %v", said, audited, mm.events) } }