Key lifecycle: lifetime limits by scope, rotation with overlap, kinds and expiry in the listing
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
178964cf6a
commit
8866a1ea0f
14 files changed
+463
-5
No files matched your search
+175
-3
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
@@ -37,6 +38,8 @@ func newTenancyCmd() *cobra.Command {
|
||||
newKeyCreateCmd(open),
|
||||
newKeyListCmd(open),
|
||||
newKeyRevokeCmd(open),
|
||||
newKeyRotateCmd(open),
|
||||
newKeyTTLCmd(open),
|
||||
newLimitsCmd(open),
|
||||
newThreadsCmd(open),
|
||||
newMemoryCmd(open),
|
||||
@@ -220,15 +223,20 @@ func newKeyListCmd(open opener) *cobra.Command {
|
||||
return err
|
||||
}
|
||||
w := tabwriter.NewWriter(cmd.OutOrStdout(), 0, 0, 2, ' ', 0)
|
||||
fmt.Fprintln(w, "ID\tNAME\tKEY\tPROJECT\tOWNER\tSTATE\tLAST USED")
|
||||
fmt.Fprintln(w, "ID\tNAME\tKIND\tKEY\tPROJECT\tOWNER\tSTATE\tEXPIRES\tLAST USED")
|
||||
now := time.Now()
|
||||
// Service keys — a project's, nobody's own — first: they are
|
||||
// the ones nobody leaving the company takes with them.
|
||||
slices.SortStableFunc(rows, func(a, b store.KeyRow) int {
|
||||
return strings.Compare(keyKind(a.Key), keyKind(b.Key))
|
||||
})
|
||||
for _, r := range rows {
|
||||
where := r.ProjectPath
|
||||
if where == "" {
|
||||
where = "personal"
|
||||
}
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", r.ID, r.Name, r.Prefix,
|
||||
where, dash(r.OwnerEmail), keyState(r.Key, now), ago(r.LastUsedAt, now))
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", r.ID, r.Name, keyKind(r.Key), r.Prefix,
|
||||
where, dash(r.OwnerEmail), keyState(r.Key, now), until(r.ExpiresAt, now), ago(r.LastUsedAt, now))
|
||||
}
|
||||
return w.Flush()
|
||||
}
|
||||
@@ -387,6 +395,33 @@ func newLimitsCmd(open opener) *cobra.Command {
|
||||
return cmd
|
||||
}
|
||||
|
||||
// keyKind says whose a key is: a project's (service), a person's in a
|
||||
// project (member), or a person's own (personal).
|
||||
func keyKind(k store.Key) string {
|
||||
switch {
|
||||
case k.UserID == "":
|
||||
return "service"
|
||||
case k.ProjectID == "":
|
||||
return "personal"
|
||||
}
|
||||
return "member"
|
||||
}
|
||||
|
||||
// until is how long a key has left, or "never".
|
||||
func until(t, now time.Time) string {
|
||||
if t.IsZero() {
|
||||
return "never"
|
||||
}
|
||||
if !t.After(now) {
|
||||
return "-"
|
||||
}
|
||||
d := t.Sub(now)
|
||||
if d > 48*time.Hour {
|
||||
return fmt.Sprintf("in %dd", int(d.Hours()/24))
|
||||
}
|
||||
return "in " + d.Round(time.Minute).String()
|
||||
}
|
||||
|
||||
func keyState(k store.Key, now time.Time) string {
|
||||
switch {
|
||||
case !k.RevokedAt.IsZero():
|
||||
@@ -427,3 +462,140 @@ func randomID(prefix string) string {
|
||||
_, _ = rand.Read(buf[:])
|
||||
return prefix + "-" + strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(buf[:]))
|
||||
}
|
||||
|
||||
func newKeyRotateCmd(open opener) *cobra.Command {
|
||||
var overlap time.Duration
|
||||
cmd := &cobra.Command{
|
||||
Use: "rotate <key-id>",
|
||||
Short: "Replace a key with a new one, the old one working on for a while",
|
||||
Long: "The new key belongs where the old one did — the same project, owner, band\n" +
|
||||
"and routing profile, and as long a life — and is printed once. The old\n" +
|
||||
"one stops working after --overlap, so whatever uses it can be moved over\n" +
|
||||
"without an outage.",
|
||||
Example: " llmgw keys rotate key-7f3a --overlap 48h",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
s, err := open(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.Close()
|
||||
old, err := s.KeyByID(cmd.Context(), args[0])
|
||||
if err != nil {
|
||||
return fmt.Errorf("no key %s: %w", args[0], err)
|
||||
}
|
||||
if !old.RevokedAt.IsZero() {
|
||||
return fmt.Errorf("%s is revoked; make a new key instead", old.ID)
|
||||
}
|
||||
secret, k, err := store.NewKey(randomID("key"), old.Name, old.ProjectID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
k.CreatedAt = time.Now()
|
||||
k.Band, k.RoutingProfile, k.UserID = old.Band, old.RoutingProfile, old.UserID
|
||||
if !old.ExpiresAt.IsZero() {
|
||||
k.ExpiresAt = k.CreatedAt.Add(old.ExpiresAt.Sub(old.CreatedAt))
|
||||
}
|
||||
if err := s.CreateKey(cmd.Context(), k); err != nil {
|
||||
return err
|
||||
}
|
||||
retire := time.Now().Add(overlap)
|
||||
if err := s.ExpireKeyBy(cmd.Context(), old.ID, retire); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintln(cmd.OutOrStdout(), secret)
|
||||
cmd.PrintErrf("\nid %s (replaces %s)\nold key stops working at %s\n", k.ID, old.ID,
|
||||
retire.UTC().Format(time.RFC3339))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Flags().DurationVar(&overlap, "overlap", 24*time.Hour, "how long the old key keeps working")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newKeyTTLCmd(open opener) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "ttl [<org|team|project>:<name> <duration|off>]",
|
||||
Short: "How long a key may live at most, in a part of the tree",
|
||||
Long: "A key is made within the shortest limit that applies to it — its\n" +
|
||||
"project's, its team's, its organization's, and auth.max_key_ttl in\n" +
|
||||
"server.yaml for every key. A key asked for with no expiry is given the\n" +
|
||||
"longest allowed. Existing keys are not changed. Without arguments, lists\n" +
|
||||
"the limits.",
|
||||
Example: " llmgw keys ttl team:Acme/ml 720h\n llmgw keys ttl team:Acme/ml off",
|
||||
Args: cobra.RangeArgs(0, 2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
s, err := open(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.Close()
|
||||
if len(args) == 0 {
|
||||
limits, err := s.KeyTTLs(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(limits) == 0 {
|
||||
fmt.Fprintln(cmd.OutOrStdout(), "No limit: keys may live for ever.")
|
||||
return nil
|
||||
}
|
||||
names := make([]string, 0, len(limits))
|
||||
for k := range limits {
|
||||
names = append(names, k)
|
||||
}
|
||||
slices.Sort(names)
|
||||
w := tabwriter.NewWriter(cmd.OutOrStdout(), 0, 0, 2, ' ', 0)
|
||||
fmt.Fprintln(w, "SCOPE\tLONGEST")
|
||||
for _, n := range names {
|
||||
fmt.Fprintf(w, "%s\t%s\n", strings.TrimSuffix(n, ":"), limits[n])
|
||||
}
|
||||
return w.Flush()
|
||||
}
|
||||
if len(args) != 2 {
|
||||
return errors.New("give a scope and a duration, or off")
|
||||
}
|
||||
kind, name, ok := strings.Cut(args[0], ":")
|
||||
if !ok {
|
||||
return fmt.Errorf("%q is not org:NAME, team:NAME or project:NAME", args[0])
|
||||
}
|
||||
var id string
|
||||
switch store.Scope(kind) {
|
||||
case store.ScopeOrg:
|
||||
o, err := resolveOrg(cmd.Context(), s, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id = o.ID
|
||||
case store.ScopeTeam:
|
||||
t, err := resolveTeam(cmd.Context(), s, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id = t.ID
|
||||
case store.ScopeProject:
|
||||
p, err := resolveProject(cmd.Context(), s, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id = p.ID
|
||||
default:
|
||||
return fmt.Errorf("%q: org, team or project — the gateway's is auth.max_key_ttl in server.yaml", kind)
|
||||
}
|
||||
var d time.Duration
|
||||
if args[1] != "off" {
|
||||
if d, err = time.ParseDuration(args[1]); err != nil || d <= 0 {
|
||||
return fmt.Errorf("%q is not a duration like 720h, or off", args[1])
|
||||
}
|
||||
}
|
||||
if err := s.SetMaxKeyTTL(cmd.Context(), store.Scope(kind), id, d); err != nil {
|
||||
return err
|
||||
}
|
||||
if d == 0 {
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "%s: no limit of its own\n", args[0])
|
||||
} else {
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "%s: keys live %s at most\n", args[0], d)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -119,6 +119,13 @@ func newServerCmd() *cobra.Command {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// The longest any key may live, where every way of making one
|
||||
// reads it: the store.
|
||||
if st := rt.Store(); st != nil {
|
||||
if err := st.SetMaxKeyTTL(cmd.Context(), storepkg.ScopeGateway, "", cfg.Auth.MaxKeyTTL); err != nil {
|
||||
log.Warn("could not record auth.max_key_ttl", "err", err)
|
||||
}
|
||||
}
|
||||
// Guardrails, when server.yaml defines any. Attachments to
|
||||
// parts of the tenancy tree live in the store; without one, only
|
||||
// guard.default applies.
|
||||
|
||||
Reference in new issue
Block a user