mesh/merge-gate head a72eb3dbb28d merged into trunk 19ecad261cf2 — pass: builds claude-code, claude-licence-manager → ace, g14, novox, shanks; no bus step;…
mesh/repo-check head a72eb3dbb28d merged into trunk 19ecad261cf2 — fail: its merge-check.sh failed: --- FAIL: TestAManagerWithNoLicenceAdoptsTheNewestLogin…
mesh/delivery superseded: a newer head of the same pull request
A switch of g14 back to another licence on 2026-10-13 left no trace: the manager logged no line and sent no event for bind, switch or release, and its audit kept only the verb's name. Every change of what a consumer holds now goes to the journal, the audit and a licence.<what> event with the same fields: consumer, licence before and after, generation, why (the verb or the rule) and by (the caller the runtime proved, or the manager itself). The node is told why in the bindings state and says it when it applies. The audit and binding tables become readable through the store's reader. The SDK moves to the version that proves the caller (issue 365).
803 lines
30 KiB
Go
803 lines
30 KiB
Go
package main
|
|
|
|
// The Anthropic licence manager's rules (novox/hq ADR 0183, ADR 0206, design 39), written against what it
|
|
// is handed — a store, the vendor, a way to ask a node, its own state, a way to emit — so every rule is
|
|
// tested without a bus, a database or the vendor.
|
|
//
|
|
// - A licence is an account, learned from what the nodes report (`holdings`, the agent module's state).
|
|
// A report with a refresh token the manager does not hold is a candidate.
|
|
// - The secret is asked for, sealed to this module's key, never published.
|
|
// - Adopting is refreshing: newest login first, once per account; a failure adopts nothing.
|
|
// - What each consumer should hold is this module's `bindings` state, with a generation that grows with
|
|
// every rotation and switch; the consumer fetches its token by asking `current`.
|
|
// - One rotation source: every exchange with the vendor runs under a lease.
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Fingerprint names a token without being one: the agent module's own fingerprint, so the two compare.
|
|
func Fingerprint(s string) string {
|
|
sum := sha256.Sum256([]byte(s))
|
|
return "sha256:" + hex.EncodeToString(sum[:])[:16]
|
|
}
|
|
|
|
// Identity is the account a grant belongs to, as the agent's own state file names it.
|
|
type Identity struct {
|
|
AccountUUID string `json:"accountUuid"`
|
|
EmailAddress string `json:"emailAddress,omitempty"`
|
|
OrganizationUUID string `json:"organizationUuid,omitempty"`
|
|
}
|
|
|
|
// Holdings is one node's report, as the agent module writes it to its `holdings` state (ADR 0206).
|
|
type Holdings struct {
|
|
Node string `json:"node"`
|
|
Identity *Identity `json:"identity"`
|
|
Kind string `json:"kind"`
|
|
Refresh struct {
|
|
Present bool `json:"present"`
|
|
Fingerprint string `json:"fingerprint"`
|
|
} `json:"refresh"`
|
|
ChangedAt string `json:"changedAt"`
|
|
// Generation is the binding generation the node last applied (novox/hq issue 243).
|
|
Generation int64 `json:"generation"`
|
|
}
|
|
|
|
// BindingState is what `bindings` holds for one consumer: no secret, only what it should hold and which
|
|
// generation.
|
|
type BindingState struct {
|
|
Licence string `json:"licence"`
|
|
Kind string `json:"kind"`
|
|
Generation int64 `json:"generation"`
|
|
// Why and By are what moved it and who asked (novox/hq issue 625), so the node can say so when it applies it.
|
|
Why string `json:"why,omitempty"`
|
|
By string `json:"by,omitempty"`
|
|
}
|
|
|
|
// Cause is why a consumer's binding changed and who or what asked for it (novox/hq issue 625): Why is the verb
|
|
// called or the rule that fired, By the caller the runtime proved (stdio.CallerOf) or this module itself.
|
|
type Cause struct {
|
|
Why string
|
|
By string
|
|
}
|
|
|
|
// Itself names this module where it moved a binding by a rule of its own, with no caller.
|
|
const Itself = "claude-licence-manager"
|
|
|
|
type causeKey struct{}
|
|
|
|
// WithCause is ctx carrying why what runs in it changes a binding, and who asked.
|
|
func WithCause(ctx context.Context, c Cause) context.Context {
|
|
return context.WithValue(ctx, causeKey{}, c)
|
|
}
|
|
|
|
// CauseOf is the cause ctx carries, or "a rule of this module's own" when none: never empty, so a record always
|
|
// says something, and a change nobody named a cause for reads as this module's own.
|
|
func CauseOf(ctx context.Context) Cause {
|
|
if c, ok := ctx.Value(causeKey{}).(Cause); ok && c.By != "" {
|
|
return c
|
|
}
|
|
return Cause{Why: "a rule of this module's own", By: Itself}
|
|
}
|
|
|
|
// record says one change of what a consumer holds, the same fields in three places (novox/hq issue 625): a line
|
|
// in the journal, a row in the audit table, and the event `licence.<what>` on the bus. Never a token.
|
|
func (m *Manager) record(ctx context.Context, what, line string, detail map[string]any) {
|
|
_ = m.Store.Audit(ctx, what, detail)
|
|
m.Log("%s", line)
|
|
_ = m.Emit("licence."+what, detail)
|
|
}
|
|
|
|
// moved records a consumer bound or switched: from which licence to which, at which generation, why and by whom.
|
|
func (m *Manager) moved(ctx context.Context, consumer, from, licence string, generation int64, c Cause) {
|
|
what, line := "bound", fmt.Sprintf("bound %s to %s", consumer, licence)
|
|
if from != "" {
|
|
what, line = "switched", fmt.Sprintf("switched %s from %s to %s", consumer, from, licence)
|
|
}
|
|
m.record(ctx, what, fmt.Sprintf("%s (generation %d): %s; asked by %s", line, generation, c.Why, c.By),
|
|
map[string]any{"consumer": consumer, "licence": licence, "from": from, "generation": generation,
|
|
"why": c.Why, "by": c.By})
|
|
}
|
|
|
|
// Settings are the manager's own, declared with defaults (design 39 §8).
|
|
type Settings struct {
|
|
Cadence time.Duration // rotate a grant once older than this
|
|
Floor time.Duration // refresh in any case with less than this left
|
|
FailuresToNotify int
|
|
Cooldown time.Duration // at most one notification per licence in this window
|
|
RefreshWarn time.Duration // warn this long before a refresh token itself expires
|
|
}
|
|
|
|
// Defaults are the settings a fresh mesh runs with.
|
|
var Defaults = Settings{Cadence: 4 * time.Hour, Floor: time.Hour, FailuresToNotify: 3, Cooldown: 24 * time.Hour, RefreshWarn: 72 * time.Hour}
|
|
|
|
// SettingsFrom reads the settings file, keeping a default for anything absent or not positive.
|
|
func SettingsFrom(path string) Settings {
|
|
s := Defaults
|
|
raw, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return s
|
|
}
|
|
var f map[string]float64
|
|
if json.Unmarshal(raw, &f) != nil {
|
|
return s
|
|
}
|
|
set := func(k string, unit time.Duration, into *time.Duration) {
|
|
if v := f[k]; v > 0 {
|
|
*into = time.Duration(v * float64(unit))
|
|
}
|
|
}
|
|
set("cadence_minutes", time.Minute, &s.Cadence)
|
|
set("floor_minutes", time.Minute, &s.Floor)
|
|
set("cooldown_hours", time.Hour, &s.Cooldown)
|
|
if v := f["refresh_warn_days"]; v > 0 {
|
|
s.RefreshWarn = time.Duration(v * float64(24*time.Hour))
|
|
}
|
|
if v := f["failures_to_notify"]; v > 0 {
|
|
s.FailuresToNotify = int(v)
|
|
}
|
|
return s
|
|
}
|
|
|
|
// GrantAnswer is what a node's `claude_code_grant` answers: a login sealed to the key given, or nothing.
|
|
type GrantAnswer struct {
|
|
Sealed *SealedBox `json:"sealed"`
|
|
Identity *Identity `json:"identity"`
|
|
Fingerprint string `json:"fingerprint"`
|
|
}
|
|
|
|
// Manager is the rules and what they are handed.
|
|
type Manager struct {
|
|
Store Store
|
|
Vendor Vendor
|
|
Crypt *Crypt
|
|
Keys KeyPair
|
|
// AskGrant asks a node's agent module for the grant a login left there, sealed to publicKey. An error
|
|
// is the node not answering; a nil Sealed is no login waiting.
|
|
AskGrant func(ctx context.Context, node, publicKey string) (GrantAnswer, error)
|
|
// PutBinding and DeleteBinding are this module's `bindings` state.
|
|
PutBinding func(ctx context.Context, consumer string, b BindingState) error
|
|
DeleteBinding func(ctx context.Context, consumer string) error
|
|
Emit func(event string, body map[string]any) error
|
|
Now func() time.Time
|
|
Log func(format string, args ...any)
|
|
// Holder names this process in a lease, so a second run is told apart.
|
|
Holder string
|
|
Settings Settings
|
|
}
|
|
|
|
const leaseFor = 2 * time.Minute
|
|
|
|
// NameFor is a licence's name: the account's address where it has one, else its id.
|
|
func NameFor(id Identity) string {
|
|
if e := strings.TrimSpace(id.EmailAddress); e != "" {
|
|
return e
|
|
}
|
|
return id.AccountUUID
|
|
}
|
|
|
|
// ---- learning licences from what the nodes hold ------------------------------------------------------
|
|
|
|
// Candidate is a report the manager should try.
|
|
type Candidate struct {
|
|
Node string
|
|
Identity Identity
|
|
Fingerprint string
|
|
ChangedAt int64
|
|
}
|
|
|
|
// CandidatesIn is the candidates in a set of reports by account, newest login first (ADR 0206 §2, §4). A
|
|
// report without an identity is not one: a grant is filed under its account or not at all.
|
|
func (m *Manager) CandidatesIn(ctx context.Context, reports []Holdings) (map[string][]Candidate, error) {
|
|
out := map[string][]Candidate{}
|
|
for _, r := range reports {
|
|
if !r.Refresh.Present || r.Refresh.Fingerprint == "" || r.Identity == nil || r.Identity.AccountUUID == "" {
|
|
continue
|
|
}
|
|
settled, err := m.Store.Outcome(ctx, r.Refresh.Fingerprint)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if settled != "" {
|
|
continue // adopted, dead, skipped, refused or gone: settled once
|
|
}
|
|
held, err := m.Store.LicenceForAccount(ctx, r.Identity.AccountUUID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if held != nil && held.RefreshFingerprint == r.Refresh.Fingerprint {
|
|
continue
|
|
}
|
|
var changed int64
|
|
if t, err := time.Parse(time.RFC3339Nano, r.ChangedAt); err == nil {
|
|
changed = t.UnixMilli()
|
|
}
|
|
// The latest login wins: one no newer than the grant held is not a newer login.
|
|
if held != nil && changed <= held.AdoptedAt {
|
|
continue
|
|
}
|
|
out[r.Identity.AccountUUID] = append(out[r.Identity.AccountUUID],
|
|
Candidate{Node: r.Node, Identity: *r.Identity, Fingerprint: r.Refresh.Fingerprint, ChangedAt: changed})
|
|
}
|
|
for _, list := range out {
|
|
sort.SliceStable(list, func(i, j int) bool { return list[i].ChangedAt > list[j].ChangedAt })
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// Consider every report (ADR 0206): for each account with candidates, under that account's lease, try them
|
|
// newest first; the first that refreshes is adopted and the rest are settled as skipped without being
|
|
// exchanged. Answers what was adopted.
|
|
func (m *Manager) Consider(ctx context.Context, reports []Holdings) ([]string, error) {
|
|
// **Never a generation a node has already passed** (novox/hq issue 243). A store rebuilt after a loss
|
|
// counts from one again, while every node still holds the number it last applied. The nodes no longer
|
|
// wait for a higher number, but a binding numbered exactly as the one a node applied would still be
|
|
// skipped. So the count is moved past every number reported, before anything here binds.
|
|
var highest int64
|
|
for _, r := range reports {
|
|
highest = max(highest, r.Generation)
|
|
}
|
|
if err := m.Store.GenerationsAbove(ctx, highest); err != nil {
|
|
return nil, err
|
|
}
|
|
byAccount, err := m.CandidatesIn(ctx, reports)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
accounts := make([]string, 0, len(byAccount))
|
|
for a := range byAccount {
|
|
accounts = append(accounts, a)
|
|
}
|
|
sort.Strings(accounts)
|
|
// A node reporting an account the manager already holds, and bound to nothing, is bound to it
|
|
// (ADR 0206 §7) — whenever its report arrives, not only when the licence is adopted: a node whose own
|
|
// login is older than the one adopted is never a candidate, and would otherwise never be bound.
|
|
if err := m.bindReporters(ctx, reports); err != nil {
|
|
return nil, err
|
|
}
|
|
var adopted []string
|
|
for _, account := range accounts {
|
|
list := byAccount[account]
|
|
key := "account:" + account
|
|
ok, err := m.Store.Lease(ctx, key, m.Holder, leaseFor)
|
|
if err != nil || !ok {
|
|
continue
|
|
}
|
|
for i, c := range list {
|
|
name, err := m.adoptOne(ctx, c, reports)
|
|
if err != nil {
|
|
m.Log("adopting %s's login failed: %v", c.Node, err)
|
|
continue
|
|
}
|
|
if name != "" {
|
|
adopted = append(adopted, name)
|
|
for _, rest := range list[i+1:] {
|
|
_ = m.Store.RecordOutcome(ctx, rest.Fingerprint, rest.Node, account, Skipped, c.Node+"'s newer login was adopted first")
|
|
}
|
|
break
|
|
}
|
|
}
|
|
_ = m.Store.Unlease(ctx, key, m.Holder)
|
|
}
|
|
return adopted, nil
|
|
}
|
|
|
|
// bindReporters binds each reporting node that is bound to nothing to the licence its account already has.
|
|
func (m *Manager) bindReporters(ctx context.Context, reports []Holdings) error {
|
|
for _, rep := range reports {
|
|
if rep.Identity == nil || rep.Identity.AccountUUID == "" {
|
|
continue
|
|
}
|
|
if b, err := m.Store.Binding(ctx, rep.Node); err != nil || b != nil {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
continue
|
|
}
|
|
l, err := m.Store.LicenceForAccount(ctx, rep.Identity.AccountUUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if l == nil {
|
|
continue
|
|
}
|
|
b, err := m.Store.Bind(ctx, rep.Node, l.Name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c := Cause{Why: rep.Node + " reported the account of " + l.Name + " and was bound to nothing", By: Itself}
|
|
m.moved(ctx, rep.Node, "", l.Name, b.Generation, c)
|
|
if err := m.PutBinding(ctx, rep.Node, BindingState{Licence: l.Name, Kind: l.Kind, Generation: b.Generation,
|
|
Why: c.Why, By: c.By}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (m *Manager) adoptOne(ctx context.Context, c Candidate, reports []Holdings) (string, error) {
|
|
answer, err := m.AskGrant(ctx, c.Node, m.Keys.PublicKey)
|
|
if err != nil {
|
|
// Not answering is not an answer: asked again on the next pass.
|
|
m.Log("%s did not hand over its login: %v", c.Node, err)
|
|
return "", nil
|
|
}
|
|
if answer.Sealed == nil {
|
|
return "", m.Store.RecordOutcome(ctx, c.Fingerprint, c.Node, c.Identity.AccountUUID, Gone, "no login was waiting when asked")
|
|
}
|
|
plain, err := Open(*answer.Sealed, m.Keys.PrivateKey)
|
|
if err != nil {
|
|
return "", m.Store.RecordOutcome(ctx, c.Fingerprint, c.Node, c.Identity.AccountUUID, Refused, "the grant did not open with this module's key")
|
|
}
|
|
var offered FullGrant
|
|
if err := json.Unmarshal([]byte(plain), &offered); err != nil || offered.RefreshToken == "" {
|
|
return "", m.Store.RecordOutcome(ctx, c.Fingerprint, c.Node, c.Identity.AccountUUID, Refused, "the grant holds no refresh token")
|
|
}
|
|
if Fingerprint(offered.RefreshToken) != c.Fingerprint {
|
|
m.Log("%s's login changed while it was asked for; waiting for its next report", c.Node)
|
|
return "", nil
|
|
}
|
|
|
|
// Adopting is refreshing (ADR 0206 §4): the exchange is the check, and from here this module is the
|
|
// only holder of a live refresh token for the account.
|
|
r := m.Vendor.Refresh(ctx, offered)
|
|
if !r.OK {
|
|
_ = m.Store.RecordOutcome(ctx, c.Fingerprint, c.Node, c.Identity.AccountUUID, Dead, fmt.Sprintf("%d %s", r.Status, r.Reason))
|
|
_ = m.Store.Audit(ctx, "refused", map[string]any{"node": c.Node, "account": c.Identity.AccountUUID, "status": r.Status, "reason": r.Reason})
|
|
_ = m.Emit("licence.refused", map[string]any{"node": c.Node, "account": NameFor(c.Identity),
|
|
"reason": fmt.Sprintf("the login's refresh token did not refresh (%d)", r.Status)})
|
|
m.Log("%s's login for %s did not refresh: %d %s", c.Node, NameFor(c.Identity), r.Status, r.Reason)
|
|
return "", nil
|
|
}
|
|
// The identity guard, on two sources (ADR 0206 §8).
|
|
if r.Account != "" && r.Account != c.Identity.AccountUUID {
|
|
_ = m.Store.RecordOutcome(ctx, c.Fingerprint, c.Node, c.Identity.AccountUUID, Refused,
|
|
"the node says "+c.Identity.AccountUUID+", the vendor says "+r.Account)
|
|
_ = m.Store.Audit(ctx, "refused", map[string]any{"node": c.Node, "reported": c.Identity.AccountUUID, "vendor": r.Account})
|
|
_ = m.Emit("licence.refused", map[string]any{"node": c.Node, "account": NameFor(c.Identity),
|
|
"reason": "the account the node reported is not the one the vendor answered for"})
|
|
return "", nil
|
|
}
|
|
|
|
held, err := m.Store.LicenceForAccount(ctx, c.Identity.AccountUUID)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
now := m.Now().UnixMilli()
|
|
l := Licence{Name: NameFor(c.Identity), Kind: "subscription", AccountUUID: c.Identity.AccountUUID,
|
|
Email: c.Identity.EmailAddress, OrganizationUUID: c.Identity.OrganizationUUID}
|
|
if held != nil {
|
|
l.Name, l.NotifiedAt = held.Name, held.NotifiedAt
|
|
if l.Email == "" {
|
|
l.Email = held.Email
|
|
}
|
|
if l.OrganizationUUID == "" {
|
|
l.OrganizationUUID = held.OrganizationUUID
|
|
}
|
|
}
|
|
m.keep(&l, r.Grant)
|
|
l.AdoptedAt = max(now, c.ChangedAt)
|
|
if err := m.Store.SaveLicence(ctx, l); err != nil {
|
|
return "", err
|
|
}
|
|
why := "a new licence"
|
|
if held != nil {
|
|
why = "a newer login"
|
|
}
|
|
_ = m.Store.RecordOutcome(ctx, c.Fingerprint, c.Node, c.Identity.AccountUUID, Adopted, why)
|
|
_ = m.Store.Audit(ctx, "adopted", map[string]any{"licence": l.Name, "node": c.Node, "account": c.Identity.AccountUUID,
|
|
"vendorNamedAccount": r.Account != ""})
|
|
|
|
// A login moves its node (ADR 0209): the node this login came from is bound to its licence —
|
|
// switched, if it was bound to another. Then every node reporting this account and bound to nothing.
|
|
// Who asked is the person who logged in there; the mesh knows them only as that login (novox/hq issue 625).
|
|
cause := Cause{Why: "a login to " + l.Name + " on " + c.Node + " (ADR 0209)", By: Itself}
|
|
ctx = WithCause(ctx, cause)
|
|
if b, err := m.Store.Binding(ctx, c.Node); err != nil {
|
|
return "", err
|
|
} else if b == nil || b.Licence != l.Name {
|
|
moved, err := m.Store.Bind(ctx, c.Node, l.Name)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
from := ""
|
|
if b != nil {
|
|
from = b.Licence
|
|
}
|
|
m.moved(ctx, c.Node, from, l.Name, moved.Generation, cause)
|
|
}
|
|
for _, rep := range reports {
|
|
if rep.Identity == nil || rep.Identity.AccountUUID != c.Identity.AccountUUID {
|
|
continue
|
|
}
|
|
if b, err := m.Store.Binding(ctx, rep.Node); err != nil || b != nil {
|
|
continue
|
|
}
|
|
if b, err := m.Store.Bind(ctx, rep.Node, l.Name); err == nil {
|
|
m.moved(ctx, rep.Node, "", l.Name, b.Generation,
|
|
Cause{Why: rep.Node + " reports the account of " + l.Name + ", logged in on " + c.Node + ", and was bound to nothing", By: Itself})
|
|
}
|
|
}
|
|
if err := m.publishAdvance(ctx, l); err != nil {
|
|
return "", err
|
|
}
|
|
_ = m.Emit("licence.adopted", map[string]any{"licence": l.Name, "from": c.Node, "replaced": held != nil})
|
|
m.Log("adopted %s from %s (%s)", l.Name, c.Node, why)
|
|
return l.Name, nil
|
|
}
|
|
|
|
// keep stores a grant on its licence: encrypted, fingerprinted, its expiries, fresh.
|
|
func (m *Manager) keep(l *Licence, g FullGrant) {
|
|
raw, _ := json.Marshal(g)
|
|
l.Sealed = m.Crypt.Seal(string(raw))
|
|
l.RefreshFingerprint = Fingerprint(g.RefreshToken)
|
|
l.AccessExpiresAt = g.ExpiresAt
|
|
if g.RefreshTokenExpiresAt != nil {
|
|
l.RefreshExpiresAt = *g.RefreshTokenExpiresAt
|
|
}
|
|
l.Failures = 0
|
|
l.RotatedAt = m.Now().UnixMilli()
|
|
}
|
|
|
|
// publishAdvance gives every consumer of a licence a new generation, and tells each in the state with the
|
|
// cause ctx carries, so the node says why it fetched again (novox/hq issue 625).
|
|
func (m *Manager) publishAdvance(ctx context.Context, l Licence) error {
|
|
bindings, err := m.Store.Advance(ctx, l.Name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c := CauseOf(ctx)
|
|
for _, b := range bindings {
|
|
if err := m.PutBinding(ctx, b.Consumer, BindingState{Licence: b.Licence, Kind: l.Kind, Generation: b.Generation,
|
|
Why: c.Why, By: c.By}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ---- keeping grants alive ----------------------------------------------------------------------------
|
|
|
|
// Due says whether a licence needs a refresh now: near expiry, or older than the cadence.
|
|
func Due(l Licence, now time.Time, s Settings) bool {
|
|
if l.Kind != "subscription" || l.Sealed == "" {
|
|
return false
|
|
}
|
|
ms := now.UnixMilli()
|
|
if l.AccessExpiresAt != 0 && l.AccessExpiresAt-ms < s.Floor.Milliseconds() {
|
|
return true
|
|
}
|
|
return l.RotatedAt == 0 || ms-l.RotatedAt >= s.Cadence.Milliseconds()
|
|
}
|
|
|
|
// Rotate refreshes one licence under its lease (design 39 §3). A second run started together finds the
|
|
// lease live and does nothing; one started just after finds a fresh grant and is not due. force refreshes
|
|
// whatever the age — the seat's `refresh` verb.
|
|
func (m *Manager) Rotate(ctx context.Context, name string, force bool) (map[string]any, error) {
|
|
key := "licence:" + name
|
|
ok, err := m.Store.Lease(ctx, key, m.Holder, leaseFor)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !ok {
|
|
return map[string]any{"licence": name, "refreshed": false, "reason": "another run holds its lease"}, nil
|
|
}
|
|
defer func() { _ = m.Store.Unlease(ctx, key, m.Holder) }()
|
|
l, err := m.Store.Licence(ctx, name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if l == nil {
|
|
return map[string]any{"licence": name, "refreshed": false, "reason": "no such licence"}, nil
|
|
}
|
|
if l.Kind != "subscription" || l.Sealed == "" {
|
|
return map[string]any{"licence": name, "refreshed": false, "reason": "an API key does not refresh"}, nil
|
|
}
|
|
now := m.Now()
|
|
if !force && !Due(*l, now, m.Settings) {
|
|
return map[string]any{"licence": name, "refreshed": false, "reason": "not due"}, nil
|
|
}
|
|
plain, err := m.Crypt.Open(l.Sealed)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var g FullGrant
|
|
if err := json.Unmarshal([]byte(plain), &g); err != nil {
|
|
return nil, err
|
|
}
|
|
r := m.Vendor.Refresh(ctx, g)
|
|
if !r.OK {
|
|
l.Failures++
|
|
m.Log("%s did not refresh (%d in a row): %d %s", name, l.Failures, r.Status, r.Reason)
|
|
_ = m.Store.Audit(ctx, "failed", map[string]any{"licence": name, "status": r.Status, "reason": r.Reason, "failures": l.Failures})
|
|
m.notify(l, fmt.Sprintf("refresh failed %d time(s) in a row: %d", l.Failures, r.Status), l.Failures >= m.Settings.FailuresToNotify)
|
|
if err := m.Store.SaveLicence(ctx, *l); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"licence": name, "refreshed": false, "reason": fmt.Sprintf("%d %s", r.Status, r.Reason), "failures": l.Failures}, nil
|
|
}
|
|
m.keep(l, r.Grant)
|
|
if l.RefreshExpiresAt != 0 {
|
|
left := time.Duration(l.RefreshExpiresAt-now.UnixMilli()) * time.Millisecond
|
|
m.notify(l, fmt.Sprintf("its refresh token expires in %.1f day(s): a person must log in again", left.Hours()/24),
|
|
left < m.Settings.RefreshWarn)
|
|
}
|
|
if err := m.Store.SaveLicence(ctx, *l); err != nil {
|
|
return nil, err
|
|
}
|
|
c := CauseOf(ctx)
|
|
if force {
|
|
c.Why = "a refresh asked for: " + c.Why
|
|
} else {
|
|
c = Cause{Why: "due: older than its cadence or near its expiry", By: Itself}
|
|
if by := CauseOf(ctx); by.By != Itself {
|
|
c.By = by.By
|
|
}
|
|
}
|
|
ctx = WithCause(ctx, Cause{Why: "a rotation of " + name + " (" + c.Why + ")", By: c.By})
|
|
m.record(ctx, "rotated", fmt.Sprintf("rotated %s, its token now expiring %s: %s; asked by %s", name,
|
|
time.UnixMilli(l.AccessExpiresAt).UTC().Format(time.RFC3339), c.Why, c.By),
|
|
map[string]any{"licence": name, "expiresAt": l.AccessExpiresAt, "why": c.Why, "by": c.By})
|
|
if err := m.publishAdvance(ctx, *l); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"licence": name, "refreshed": true, "expiresAt": time.UnixMilli(l.AccessExpiresAt).UTC().Format(time.RFC3339)}, nil
|
|
}
|
|
|
|
// notify emits `licence.failing` at most once per cooldown (design 39 §3); it carries no secret.
|
|
func (m *Manager) notify(l *Licence, why string, when bool) {
|
|
if !when {
|
|
return
|
|
}
|
|
now := m.Now().UnixMilli()
|
|
if l.NotifiedAt != 0 && now-l.NotifiedAt < m.Settings.Cooldown.Milliseconds() {
|
|
return
|
|
}
|
|
l.NotifiedAt = now
|
|
_ = m.Emit("licence.failing", map[string]any{"licence": l.Name, "why": why})
|
|
}
|
|
|
|
// RotateDue refreshes every licence that is due.
|
|
func (m *Manager) RotateDue(ctx context.Context) ([]map[string]any, error) {
|
|
all, err := m.Store.Licences(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var out []map[string]any
|
|
for _, l := range all {
|
|
if Due(l, m.Now(), m.Settings) {
|
|
r, err := m.Rotate(ctx, l.Name, false)
|
|
if err != nil {
|
|
return out, err
|
|
}
|
|
out = append(out, r)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// ReadUsage reads and records each subscription's usage (ADR 0054); the event names the licence and numbers.
|
|
func (m *Manager) ReadUsage(ctx context.Context) error {
|
|
all, err := m.Store.Licences(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, l := range all {
|
|
if l.Kind != "subscription" || l.Sealed == "" {
|
|
continue
|
|
}
|
|
plain, err := m.Crypt.Open(l.Sealed)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var g FullGrant
|
|
_ = json.Unmarshal([]byte(plain), &g)
|
|
raw, err := m.Vendor.Usage(ctx, g.AccessToken)
|
|
if err != nil || raw == nil {
|
|
continue
|
|
}
|
|
reading := FlattenUsage(raw)
|
|
if err := m.Store.RecordUsage(ctx, l.Name, m.Now().UnixMilli(), reading, raw); err != nil {
|
|
return err
|
|
}
|
|
_ = m.Emit("usage.read", map[string]any{"licence": l.Name, "sessionPct": reading.SessionPct,
|
|
"weeklyPct": reading.WeeklyPct, "sonnetPct": reading.SonnetPct})
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ---- the seat's verbs --------------------------------------------------------------------------------
|
|
|
|
// Current is a consumer's token sealed to the key it sent (ADR 0206 §6): for a subscription the access
|
|
// token and its expiries only — never the refresh token, which no node holds. Nil when it is bound to
|
|
// nothing.
|
|
func (m *Manager) Current(ctx context.Context, consumer, publicKey string) (map[string]any, error) {
|
|
if !strings.Contains(publicKey, "PUBLIC KEY") {
|
|
return nil, errors.New("current seals to the consumer's public key, and none was given")
|
|
}
|
|
b, err := m.Store.Binding(ctx, consumer)
|
|
if err != nil || b == nil {
|
|
return nil, err
|
|
}
|
|
l, err := m.Store.Licence(ctx, b.Licence)
|
|
if err != nil || l == nil || l.Sealed == "" {
|
|
return nil, err
|
|
}
|
|
plain, err := m.Crypt.Open(l.Sealed)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
handed := plain
|
|
if l.Kind == "subscription" {
|
|
var g FullGrant
|
|
if err := json.Unmarshal([]byte(plain), &g); err != nil {
|
|
return nil, err
|
|
}
|
|
access, _ := json.Marshal(map[string]any{"accessToken": g.AccessToken, "expiresAt": g.ExpiresAt,
|
|
"refreshTokenExpiresAt": g.RefreshTokenExpiresAt, "scopes": g.Scopes,
|
|
"subscriptionType": g.SubscriptionType, "rateLimitTier": g.RateLimitTier})
|
|
handed = string(access)
|
|
}
|
|
box, err := Seal(handed, publicKey)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := map[string]any{"licence": l.Name, "kind": l.Kind, "generation": b.Generation, "sealed": box}
|
|
if l.AccountUUID != "" {
|
|
out["identity"] = Identity{AccountUUID: l.AccountUUID, EmailAddress: l.Email, OrganizationUUID: l.OrganizationUUID}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// Bind binds or switches a consumer: a person's act (ADR 0183), told to the consumer as a new generation, and
|
|
// recorded with the cause ctx carries — the verb and its proven caller (novox/hq issue 625).
|
|
func (m *Manager) Bind(ctx context.Context, consumer, licence string) (map[string]any, error) {
|
|
l, err := m.Store.Licence(ctx, licence)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if l == nil {
|
|
return nil, fmt.Errorf("there is no licence %s; `licences` lists them", licence)
|
|
}
|
|
before, err := m.Store.Binding(ctx, consumer)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
b, err := m.Store.Bind(ctx, consumer, licence)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
from := ""
|
|
if before != nil {
|
|
from = before.Licence
|
|
}
|
|
c := CauseOf(ctx)
|
|
m.moved(ctx, consumer, from, licence, b.Generation, c)
|
|
if err := m.PutBinding(ctx, consumer, BindingState{Licence: licence, Kind: l.Kind, Generation: b.Generation,
|
|
Why: c.Why, By: c.By}); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"consumer": consumer, "licence": licence, "generation": b.Generation, "from": from}, nil
|
|
}
|
|
|
|
// Release unbinds a consumer; its node keeps its last token, which expires within hours.
|
|
func (m *Manager) Release(ctx context.Context, consumer string) (map[string]any, error) {
|
|
was, err := m.Store.Binding(ctx, consumer)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if ok, err := m.Store.Unbind(ctx, consumer); err != nil || !ok {
|
|
return map[string]any{"consumer": consumer, "released": false, "reason": "it was bound to nothing"}, err
|
|
}
|
|
if err := m.DeleteBinding(ctx, consumer); err != nil {
|
|
return nil, err
|
|
}
|
|
c := CauseOf(ctx)
|
|
m.record(ctx, "released", fmt.Sprintf("released %s from %s: %s; asked by %s", consumer, was.Licence, c.Why, c.By),
|
|
map[string]any{"consumer": consumer, "licence": was.Licence, "generation": was.Generation, "why": c.Why, "by": c.By})
|
|
return map[string]any{"consumer": consumer, "released": true, "was": was.Licence}, nil
|
|
}
|
|
|
|
var licenceName = regexp.MustCompile(`^[A-Za-z0-9@._-]+$`)
|
|
|
|
// apiKeyShape is what an Anthropic API key looks like. A key of another shape is refused before it is kept,
|
|
// so a file that is not a key (a credential, a private key) is never adopted as one (novox/hq ADR 0266).
|
|
var apiKeyShape = regexp.MustCompile(`^sk-ant-[A-Za-z0-9_-]{20,300}$`)
|
|
|
|
// AdoptKey adopts an API key from a file on this node — never an argument (design 39 §6).
|
|
func (m *Manager) AdoptKey(ctx context.Context, name, file string) (map[string]any, error) {
|
|
raw, err := os.ReadFile(file)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return m.adoptKey(ctx, name, strings.TrimSpace(string(raw)), "a file on "+m.Holder)
|
|
}
|
|
|
|
// AdoptSealedKey adopts an API key sealed to this module's public key by a node's agent module (ADR 0209):
|
|
// the key crosses the bus only sealed, on request/reply.
|
|
func (m *Manager) AdoptSealedKey(ctx context.Context, name string, box SealedBox, from string) (map[string]any, error) {
|
|
key, err := Open(box, m.Keys.PrivateKey)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return m.adoptKey(ctx, name, strings.TrimSpace(key), from)
|
|
}
|
|
|
|
func (m *Manager) adoptKey(ctx context.Context, name, key, from string) (map[string]any, error) {
|
|
if !licenceName.MatchString(name) {
|
|
return nil, fmt.Errorf("%q is not a licence name: letters, digits and @._-", name)
|
|
}
|
|
if key == "" {
|
|
return nil, errors.New("the key is empty")
|
|
}
|
|
if !apiKeyShape.MatchString(key) {
|
|
// Never the content: what was handed may be a secret of another kind.
|
|
return nil, errors.New("what was handed over is not an Anthropic API key (sk-ant-…): nothing adopted")
|
|
}
|
|
held, err := m.Store.Licence(ctx, name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if held != nil && held.Kind != "api-key" {
|
|
return nil, fmt.Errorf("%s is a subscription; an API key needs a name of its own", name)
|
|
}
|
|
l := Licence{Name: name, Kind: "api-key", Sealed: m.Crypt.Seal(key), AdoptedAt: m.Now().UnixMilli()}
|
|
if err := m.Store.SaveLicence(ctx, l); err != nil {
|
|
return nil, err
|
|
}
|
|
c := CauseOf(ctx)
|
|
_ = m.Store.Audit(ctx, "adopted", map[string]any{"licence": name, "kind": "api-key", "from": from, "why": c.Why, "by": c.By})
|
|
m.Log("adopted the API key %s from %s; asked by %s", name, from, c.By)
|
|
ctx = WithCause(ctx, Cause{Why: "the API key " + name + " adopted from " + from, By: c.By})
|
|
if err := m.publishAdvance(ctx, l); err != nil {
|
|
return nil, err
|
|
}
|
|
_ = m.Emit("licence.adopted", map[string]any{"licence": name, "from": from, "replaced": held != nil})
|
|
return map[string]any{"licence": name, "kind": "api-key", "adopted": true, "fingerprint": Fingerprint(key)}, nil
|
|
}
|
|
|
|
// Licences is each licence as a person reads it: health and who is bound, never a token.
|
|
func (m *Manager) Licences(ctx context.Context) ([]map[string]any, error) {
|
|
all, err := m.Store.Licences(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
bindings, err := m.Store.Bindings(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
stamp := func(ms int64) any {
|
|
if ms == 0 {
|
|
return nil
|
|
}
|
|
return time.UnixMilli(ms).UTC().Format(time.RFC3339)
|
|
}
|
|
out := []map[string]any{}
|
|
for _, l := range all {
|
|
bound := []string{}
|
|
for _, b := range bindings {
|
|
if b.Licence == l.Name {
|
|
bound = append(bound, b.Consumer)
|
|
}
|
|
}
|
|
account := l.Email
|
|
if account == "" {
|
|
account = l.AccountUUID
|
|
}
|
|
out = append(out, map[string]any{"name": l.Name, "kind": l.Kind, "account": account,
|
|
"accessExpiresAt": stamp(l.AccessExpiresAt), "refreshExpiresAt": stamp(l.RefreshExpiresAt),
|
|
"rotatedAt": stamp(l.RotatedAt), "failures": l.Failures, "bound": bound})
|
|
}
|
|
return out, nil
|
|
}
|