package cli import ( "path/filepath" "regexp" "strings" "testing" "time" "gitea.mynodes.xyz/ilker/llmgw/internal/store" ) func TestAKeyIsRotatedWithAnOverlapAndKeysLiveWithinTheirLimit(t *testing.T) { db := filepath.Join(t.TempDir(), "s.db") mustRun(t, db, "org", "add", "org", "Acme") mustRun(t, db, "org", "add", "team", "ml", "--in", "Acme") mustRun(t, db, "org", "add", "project", "train", "--in", "Acme/ml") mustRun(t, db, "keys", "ttl", "team:Acme/ml", "720h") if out := mustRun(t, db, "keys", "ttl"); !strings.Contains(out, "720h") { t.Errorf("listing: %s", out) } if _, err := run(t, db, "keys", "create", "ci", "--project", "train", "--expires-in", "2000h"); err == nil { t.Error("a key past the team's limit was made") } mustRun(t, db, "keys", "create", "ci", "--project", "train") list := mustRun(t, db, "keys", "list", "--all") if !strings.Contains(list, "service") || !strings.Contains(list, "in 29d") && !strings.Contains(list, "in 30d") { t.Errorf("a service key, given the team's longest life:\n%s", list) } id := regexp.MustCompile(`key-[a-z0-9]+`).FindString(list) out := mustRun(t, db, "keys", "rotate", id, "--overlap", "2h") if !strings.HasPrefix(strings.TrimSpace(out), store.KeyPrefix) { t.Errorf("the new key was not printed: %q", out) } s, err := store.Open(t.Context(), db) if err != nil { t.Fatal(err) } defer s.Close() old, _ := s.KeyByID(t.Context(), id) if d := time.Until(old.ExpiresAt); d > 2*time.Hour+time.Minute || d < time.Hour { t.Errorf("the old key stops in %s, expected about 2h", d) } rows, _ := s.AllKeys(t.Context()) if len(rows) != 2 { t.Errorf("%d keys after rotating", len(rows)) } }