runner: metered slot, sign-out, binding and probe transport fixes
Security round findings 1 to 6: an attempt is registered as running before its admission commits; a holder already claiming the slot is never let in again; sign-out retires the connection and waits for its slot, so a running probe's charge commits first; API-key homes take names never reused, and budget and Resume frames must name the connection's instance id, consumed frames changing nothing; the probe uses its own transport (public addresses pinned after resolution, no proxy, no redirects, a size cap); another model answering proves nothing and its usage is priced as that model.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+665
−84
internal/runner/connect/apikey.go+94 −9internal/runner/connect/apikey_test.go+81 −3internal/runner/egress/policy.go+5 −0internal/runner/metered/ledger.go+49 −20internal/runner/metered/meter.go+41 −8internal/runner/metered/meter_test.go+149 −7internal/runner/thin/apikey.go+75 −30internal/runner/thin/apikey_test.go+143 −2internal/runner/thin/askmetered_test.go+4 −4internal/runner/thin/login.go+17 −0internal/runner/thin/token.go+7 −1
diff --git a/internal/runner/connect/apikey.go b/internal/runner/connect/apikey.go| index 88773cc4..1ffa6296 100644 |
| --- a/internal/runner/connect/apikey.go |
| +++ b/internal/runner/connect/apikey.go |
| @@ -3,15 +3,19 @@ package connect |
| import ( |
| "bytes" |
| "context" |
| + "crypto/tls" |
| "encoding/json" |
| "errors" |
| "fmt" |
| "io" |
| + "net" |
| "net/http" |
| + "net/netip" |
| "slices" |
| "strings" |
| "time" |
| + "amadan.net/oficina/equipo/internal/runner/egress" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -46,7 +50,71 @@ func (c APIClient) client() *http.Client { |
| if c.HTTP != nil { |
| return c.HTTP |
| } |
| - return &http.Client{Timeout: time.Minute, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + return SafeClient(nil, nil, nil) |
| +} |
| + |
| +// errUnsafeAddress: the provider's host resolved to an address the |
| +// runner does not dial (not public), or to none. |
| +var errUnsafeAddress = errors.New("the provider's host did not resolve to public addresses only") |
| + |
| +// SafeClient is the client an API key's requests use (security round, |
| +// finding 5): no ambient proxy; the host resolved once, every answer |
| +// required to be public (allow; egress.PublicAddress by default) and the |
| +// connection made to an address resolved, never resolved again; TLS |
| +// verified for the provider's host name; no redirect followed; a minute |
| +// at most. lookup, allow and dial are the tests' seams (nil: the |
| +// system's). |
| +func SafeClient(lookup func(ctx context.Context, host string) ([]netip.Addr, error), allow func(netip.Addr) bool, dial func(ctx context.Context, network, addr string) (net.Conn, error)) *http.Client { |
| + if lookup == nil { |
| + lookup = func(ctx context.Context, host string) ([]netip.Addr, error) { |
| + return net.DefaultResolver.LookupNetIP(ctx, "ip", host) |
| + } |
| + } |
| + if allow == nil { |
| + allow = egress.PublicAddress |
| + } |
| + if dial == nil { |
| + dial = (&net.Dialer{Timeout: 15 * time.Second}).DialContext |
| + } |
| + pinned := func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + host, port, err := net.SplitHostPort(addr) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var addrs []netip.Addr |
| + if a, err := netip.ParseAddr(host); err == nil { |
| + addrs = []netip.Addr{a} |
| + } else if addrs, err = lookup(ctx, host); err != nil { |
| + return nil, errProviderUnreachable |
| + } |
| + if len(addrs) == 0 || slices.ContainsFunc(addrs, func(a netip.Addr) bool { return !allow(a.Unmap()) }) { |
| + return nil, errUnsafeAddress |
| + } |
| + var last error |
| + for _, a := range addrs { |
| + conn, err := dial(ctx, network, net.JoinHostPort(a.Unmap().String(), port)) |
| + if err == nil { |
| + return conn, nil |
| + } |
| + last = err |
| + } |
| + return nil, last |
| + } |
| + return &http.Client{ |
| + Timeout: time.Minute, |
| + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| + Transport: &http.Transport{ |
| + Proxy: nil, |
| + DialContext: pinned, |
| + TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}, |
| + TLSHandshakeTimeout: 15 * time.Second, |
| + ResponseHeaderTimeout: 45 * time.Second, |
| + MaxResponseHeaderBytes: 64 << 10, |
| + MaxIdleConns: 2, |
| + IdleConnTimeout: 30 * time.Second, |
| + DisableCompression: true, |
| + }, |
| + } |
| } |
| func (c APIClient) do(ctx context.Context, method, path string, key []byte, body any) ([]byte, error) { |
| @@ -116,13 +184,19 @@ func (c APIClient) Models(ctx context.Context, key []byte) ([]string, error) { |
| // ProbeUsage is a one-token completion's usage as the provider reported |
| // it, normalised: input is the uncached part (an OpenAI-compatible |
| // prompt_tokens counts cached tokens inside it); reasoning is part of |
| -// output. Reported is false when the answer carried no usage. |
| +// output. Reported is false when the answer carried no usage. Model is |
| +// the model the provider says answered: the usage is that model's. |
| type ProbeUsage struct { |
| Input, Cached, Output int64 |
| Reasoning *int64 |
| Reported bool |
| + Model string |
| } |
| +// ErrModelMismatch: another model answered than the one selected, so the |
| +// probe proves nothing about the selected model. |
| +var ErrModelMismatch = errors.New("another model answered the probe") |
| + |
| // probePrompt is the probe's whole request: one word back, one token. |
| const probePrompt = "Reply with the word ok." |
| @@ -150,11 +224,18 @@ func (c APIClient) Probe(ctx context.Context, key []byte, model string) (ProbeUs |
| if err := json.Unmarshal(raw, &answer); err != nil { |
| return ProbeUsage{}, ErrProviderAnswer |
| } |
| + if len(answer.Model) > wire.MaxModelName { |
| + answer.Model = "" |
| + } |
| + mismatch := error(nil) |
| + if answer.Model != model { |
| + mismatch = ErrModelMismatch |
| + } |
| u := answer.Usage |
| if u == nil || u.Prompt == nil || u.Completion == nil { |
| - return ProbeUsage{}, nil |
| + return ProbeUsage{Model: answer.Model}, mismatch |
| } |
| - out := ProbeUsage{Input: *u.Prompt, Output: *u.Completion, Reported: true} |
| + out := ProbeUsage{Input: *u.Prompt, Output: *u.Completion, Reported: true, Model: answer.Model} |
| if u.Prompt2 != nil && u.Prompt2.Cached != nil { |
| out.Cached = *u.Prompt2.Cached |
| out.Input -= out.Cached |
| @@ -163,15 +244,19 @@ func (c APIClient) Probe(ctx context.Context, key []byte, model string) (ProbeUs |
| out.Reasoning = u.Completion2.Reasoning |
| } |
| if out.Input < 0 || out.Cached < 0 || out.Output < 0 { |
| - return ProbeUsage{}, nil |
| + return ProbeUsage{Model: answer.Model}, mismatch |
| } |
| - return out, nil |
| + return out, mismatch |
| } |
| -// Row is the probe's usage row on connection local: complete only when |
| -// the provider reported the usage. |
| +// Row is the probe's usage row on connection local, under the model that |
| +// answered (priced as that model): complete only when the provider |
| +// reported the usage and named the model. |
| func (u ProbeUsage) Row(provider, local, model string, attempt int64, ok bool) wire.Usage { |
| - row := wire.Usage{Provider: provider, Connection: local, Model: model, Attempt: attempt, Outcome: wire.OutcomeReplied, Complete: u.Reported} |
| + if u.Model != "" { |
| + model = u.Model |
| + } |
| + row := wire.Usage{Provider: provider, Connection: local, Model: model, Attempt: attempt, Outcome: wire.OutcomeReplied, Complete: u.Reported && u.Model != ""} |
| if !ok { |
| row.Outcome = wire.OutcomeFailed |
| } |
diff --git a/internal/runner/connect/apikey_test.go b/internal/runner/connect/apikey_test.go| index c30c793b..77654868 100644 |
| --- a/internal/runner/connect/apikey_test.go |
| +++ b/internal/runner/connect/apikey_test.go |
| @@ -4,9 +4,12 @@ import ( |
| "context" |
| "encoding/json" |
| "errors" |
| + "net" |
| "net/http" |
| "net/http/httptest" |
| + "net/netip" |
| "strings" |
| + "sync/atomic" |
| "testing" |
| ) |
| @@ -30,7 +33,11 @@ func fakeProvider(t *testing.T, key string) *httptest.Server { |
| w.WriteHeader(http.StatusBadRequest) |
| return |
| } |
| - w.Write([]byte(`{"model":"` + in.Model + `","choices":[{"message":{"content":"ok"}}],"usage":{"prompt_tokens":12,"completion_tokens":1,"prompt_tokens_details":{"cached_tokens":2}}}`)) |
| + model := in.Model |
| + if model == "z-ai/glm-5.3-swap" { |
| + model = "vendor/other" |
| + } |
| + w.Write([]byte(`{"model":"` + model + `","choices":[{"message":{"content":"ok"}}],"usage":{"prompt_tokens":12,"completion_tokens":1,"prompt_tokens_details":{"cached_tokens":2}}}`)) |
| default: |
| w.WriteHeader(http.StatusNotFound) |
| } |
| @@ -44,15 +51,22 @@ func fakeProvider(t *testing.T, key string) *httptest.Server { |
| func TestAPIClientModelsAndProbe(t *testing.T) { |
| s := fakeProvider(t, "tx-key-1") |
| - c := APIClient{Origin: s.URL, Path: "/v1"} |
| + // The production transport, with the fake's loopback address allowed. |
| + c := APIClient{HTTP: SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), Origin: s.URL, Path: "/v1"} |
| models, err := c.Models(context.Background(), []byte("tx-key-1")) |
| if err != nil || strings.Join(models, ",") != "vendor/other,z-ai/glm-5.3" { |
| t.Fatalf("models %v %v", models, err) |
| } |
| u, err := c.Probe(context.Background(), []byte("tx-key-1"), "z-ai/glm-5.3") |
| - if err != nil || !u.Reported || u.Input != 10 || u.Cached != 2 || u.Output != 1 { |
| + if err != nil || !u.Reported || u.Input != 10 || u.Cached != 2 || u.Output != 1 || u.Model != "z-ai/glm-5.3" { |
| t.Fatalf("probe %+v %v", u, err) |
| } |
| + // Security round finding 6: another model answering is no proof of |
| + // the selected one, and its row is that model's, priced as it. |
| + swap, err := c.Probe(context.Background(), []byte("tx-key-1"), "z-ai/glm-5.3-swap") |
| + if !errors.Is(err, ErrModelMismatch) || swap.Model != "vendor/other" || swap.Row("tensorx", "tensorx-1", "z-ai/glm-5.3-swap", 1, false).Model != "vendor/other" { |
| + t.Fatalf("another model answered: %+v %v", swap, err) |
| + } |
| row := u.Row("tensorx", "tensorx-1", "z-ai/glm-5.3", 1, true) |
| if !row.Complete || *row.InputTokens != 10 || *row.CachedInputTokens != 2 || *row.OutputTokens != 1 || row.Outcome != "replied" { |
| t.Fatalf("row %+v", row) |
| @@ -68,3 +82,67 @@ func TestAPIClientModelsAndProbe(t *testing.T) { |
| t.Fatalf("no usage reported: %+v", row) |
| } |
| } |
| + |
| +// Security round finding 5: the probe's client reaches public addresses |
| +// only, pinned to what it resolved, through no ambient proxy, follows no |
| +// redirect and reads no answer over its cap. |
| +func TestAPIClientTransport(t *testing.T) { |
| + ctx := context.Background() |
| + for name, answer := range map[string][]netip.Addr{ |
| + "loopback": {netip.MustParseAddr("127.0.0.1")}, |
| + "private": {netip.MustParseAddr("10.0.0.7")}, |
| + "link-local": {netip.MustParseAddr("169.254.169.254")}, |
| + "public and local": {netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("192.168.1.2")}, |
| + "none": {}, |
| + } { |
| + dialed := false |
| + c := APIClient{HTTP: SafeClient(func(context.Context, string) ([]netip.Addr, error) { return answer, nil }, nil, func(context.Context, string, string) (net.Conn, error) { |
| + dialed = true |
| + return nil, errors.New("dialed") |
| + }), Origin: "https://api.provider.example", Path: "/v1"} |
| + if _, err := c.Models(ctx, []byte("k")); err == nil || dialed { |
| + t.Fatalf("%s: dialed %v, %v", name, dialed, err) |
| + } |
| + } |
| + // A public answer is dialed at the address resolved, not resolved |
| + // again; the TLS name stays the provider's host. |
| + var dialedTo string |
| + c := APIClient{HTTP: SafeClient(func(context.Context, string) ([]netip.Addr, error) { |
| + return []netip.Addr{netip.MustParseAddr("8.8.4.4")}, nil |
| + }, nil, func(_ context.Context, _, addr string) (net.Conn, error) { |
| + dialedTo = addr |
| + return nil, errors.New("stop") |
| + }), Origin: "https://api.provider.example", Path: "/v1"} |
| + c.Models(ctx, []byte("k")) |
| + if dialedTo != "8.8.4.4:443" { |
| + t.Fatalf("dialed %q", dialedTo) |
| + } |
| + tr := c.HTTP.Transport.(*http.Transport) |
| + if tr.Proxy != nil || tr.TLSClientConfig == nil || tr.TLSClientConfig.InsecureSkipVerify { |
| + t.Fatal("the transport takes an ambient proxy or skips TLS verification") |
| + } |
| + // Redirects are refused (the target is never asked); an answer over |
| + // the cap is not read. |
| + var reached atomic.Bool |
| + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached.Store(true) })) |
| + t.Cleanup(target.Close) |
| + src := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch r.URL.Path { |
| + case "/v1/models": |
| + http.Redirect(w, r, target.URL+"/v1/models", http.StatusFound) |
| + default: |
| + w.Write([]byte(`{"usage":{"prompt_tokens":1,"completion_tokens":1},"pad":"` + strings.Repeat("x", 2<<20) + `"}`)) |
| + } |
| + })) |
| + t.Cleanup(src.Close) |
| + loopback := APIClient{HTTP: SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), Origin: src.URL, Path: "/v1"} |
| + if _, err := loopback.Models(ctx, []byte("k")); err == nil || reached.Load() { |
| + t.Fatalf("a redirect was followed: %v", err) |
| + } |
| + if _, err := loopback.Probe(ctx, []byte("k"), "m"); !errors.Is(err, ErrProviderAnswer) { |
| + t.Fatalf("an oversized answer: %v", err) |
| + } |
| + if (APIClient{}).client().Transport == nil { |
| + t.Fatal("the default client uses the default transport") |
| + } |
| +} |
diff --git a/internal/runner/egress/policy.go b/internal/runner/egress/policy.go| index 941813ad..3386b519 100644 |
| --- a/internal/runner/egress/policy.go |
| +++ b/internal/runner/egress/policy.go |
| @@ -142,6 +142,11 @@ var blocked = func() []netip.Prefix { |
| }() |
| var publicV6 = netip.MustParsePrefix("2000::/3") |
| +// PublicAddress reports whether a is a public unicast address the relay |
| +// would dial: never loopback, private, link-local or a reserved range. |
| +// The runner's own provider requests (an API key's probe) use it too. |
| +func PublicAddress(a netip.Addr) bool { return publicAddress(a) } |
| + |
| func publicAddress(a netip.Addr) bool { |
| a = a.Unmap() |
| if !a.IsValid() || a.Zone() != "" || !a.IsGlobalUnicast() || a.IsPrivate() || a.IsLoopback() || a.IsLinkLocalUnicast() { |
diff --git a/internal/runner/metered/ledger.go b/internal/runner/metered/ledger.go| index 065e6498..a5004621 100644 |
| --- a/internal/runner/metered/ledger.go |
| +++ b/internal/runner/metered/ledger.go |
| @@ -16,7 +16,7 @@ import ( |
| // claims in the transaction that admits it; budget_charge the ledger, |
| // keyed by the usage row's key so a resent row charges once. |
| const Schema = ` |
| -CREATE TABLE IF NOT EXISTS metered_connections (local_id TEXT PRIMARY KEY, person TEXT NOT NULL, provider TEXT NOT NULL, harness TEXT NOT NULL, upstream TEXT NOT NULL, billing TEXT NOT NULL, model TEXT NOT NULL DEFAULT '', home TEXT NOT NULL, currency TEXT NOT NULL, price_version TEXT NOT NULL, budget_day INTEGER NOT NULL, budget_month INTEGER NOT NULL, budget_revision INTEGER NOT NULL DEFAULT 0, spend_unknown INTEGER NOT NULL DEFAULT 0, pause_revision INTEGER NOT NULL DEFAULT 0, validated INTEGER NOT NULL DEFAULT 0, refused INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL); |
| +CREATE TABLE IF NOT EXISTS metered_connections (local_id TEXT PRIMARY KEY, connection TEXT NOT NULL DEFAULT '', retiring INTEGER NOT NULL DEFAULT 0, person TEXT NOT NULL, provider TEXT NOT NULL, harness TEXT NOT NULL, upstream TEXT NOT NULL, billing TEXT NOT NULL, model TEXT NOT NULL DEFAULT '', home TEXT NOT NULL, currency TEXT NOT NULL, price_version TEXT NOT NULL, budget_day INTEGER NOT NULL, budget_month INTEGER NOT NULL, budget_revision INTEGER NOT NULL DEFAULT 0, spend_unknown INTEGER NOT NULL DEFAULT 0, pause_revision INTEGER NOT NULL DEFAULT 0, validated INTEGER NOT NULL DEFAULT 0, refused INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL); |
| CREATE TABLE IF NOT EXISTS metered_slot (local_id TEXT PRIMARY KEY, holder TEXT NOT NULL DEFAULT '', role TEXT NOT NULL DEFAULT '', namespace TEXT NOT NULL DEFAULT '', claimed_at TEXT NOT NULL DEFAULT ''); |
| CREATE TABLE IF NOT EXISTS budget_charge (turn TEXT NOT NULL, step TEXT NOT NULL, attempt INTEGER NOT NULL, connection TEXT NOT NULL, model TEXT NOT NULL, holder TEXT NOT NULL, cost_micros INTEGER, reported_micros INTEGER, currency TEXT NOT NULL, price_version TEXT NOT NULL, day TEXT NOT NULL, month TEXT NOT NULL, recorded_at TEXT NOT NULL, PRIMARY KEY (turn, step, attempt, connection, model)); |
| CREATE INDEX IF NOT EXISTS budget_charge_period ON budget_charge(connection, day, month); |
| @@ -44,8 +44,12 @@ var ErrNotMetered = errors.New("metered: not a metered connection") |
| // proof. |
| var ErrNotProven = errors.New("metered: the attempt's exit is not proven") |
| -// Conn is one metered connection as the runner holds it. |
| +// Conn is one metered connection as the runner holds it. Connection is |
| +// the instance's id for it: every budget and Resume frame must name it. |
| +// Retiring: its sign-out has begun; nothing more is admitted. |
| type Conn struct { |
| + Connection string |
| + Retiring bool |
| LocalID, Person, Provider, Harness, Upstream, Billing, Model, Home string |
| Currency, PriceVersion string |
| Budget wire.Budget |
| @@ -69,9 +73,12 @@ type Holder struct { |
| func (h Holder) Key() string { return fmt.Sprintf("%s|%s|%s|%d", h.Role, h.Turn, h.Step, h.Attempt) } |
| // Admission is Admit's answer: admitted, or held with why and, for the |
| -// budget, when a new day or month starts. |
| +// budget, when a new day or month starts. Claimed: the holder already |
| +// claims the slot (an attempt of it is running, or awaits its proof); |
| +// that never gives leave to launch again. |
| type Admission struct { |
| Admitted bool |
| + Claimed bool |
| Hold string |
| WakeAt time.Time |
| } |
| @@ -81,20 +88,20 @@ type querier interface { |
| QueryContext(context.Context, string, ...any) (*sql.Rows, error) |
| } |
| -const connColumns = "local_id, person, provider, harness, upstream, billing, model, home, currency, price_version, budget_day, budget_month, budget_revision, spend_unknown, pause_revision, validated, refused" |
| +const connColumns = "connection, retiring, local_id, person, provider, harness, upstream, billing, model, home, currency, price_version, budget_day, budget_month, budget_revision, spend_unknown, pause_revision, validated, refused" |
| func scanConn(scan func(...any) error) (Conn, error) { |
| var c Conn |
| - var unknown, validated, refused int |
| - err := scan(&c.LocalID, &c.Person, &c.Provider, &c.Harness, &c.Upstream, &c.Billing, &c.Model, &c.Home, &c.Currency, &c.PriceVersion, &c.Budget.Day, &c.Budget.Month, &c.Budget.Revision, &unknown, &c.PauseRevision, &validated, &refused) |
| + var unknown, validated, refused, retiring int |
| + err := scan(&c.Connection, &retiring, &c.LocalID, &c.Person, &c.Provider, &c.Harness, &c.Upstream, &c.Billing, &c.Model, &c.Home, &c.Currency, &c.PriceVersion, &c.Budget.Day, &c.Budget.Month, &c.Budget.Revision, &unknown, &c.PauseRevision, &validated, &refused) |
| c.Budget.Currency = c.Currency |
| - c.SpendUnknown, c.Validated, c.Refused = unknown == 1, validated == 1, refused == 1 |
| + c.SpendUnknown, c.Validated, c.Refused, c.Retiring = unknown == 1, validated == 1, refused == 1, retiring == 1 |
| return c, err |
| } |
| // Add records a new metered connection and its free slot. |
| func Add(ctx context.Context, tx *sql.Tx, c Conn, now time.Time) error { |
| - if _, err := tx.ExecContext(ctx, "INSERT INTO metered_connections("+connColumns+", created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,0,0,?)", c.LocalID, c.Person, c.Provider, c.Harness, c.Upstream, c.Billing, c.Model, c.Home, c.Currency, c.PriceVersion, c.Budget.Day, c.Budget.Month, c.Budget.Revision, stamp(now)); err != nil { |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO metered_connections("+connColumns+", created_at) VALUES(?,0,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,0,0,?)", c.Connection, c.LocalID, c.Person, c.Provider, c.Harness, c.Upstream, c.Billing, c.Model, c.Home, c.Currency, c.PriceVersion, c.Budget.Day, c.Budget.Month, c.Budget.Revision, stamp(now)); err != nil { |
| return err |
| } |
| _, err := tx.ExecContext(ctx, "INSERT INTO metered_slot(local_id) VALUES(?) ON CONFLICT DO NOTHING", c.LocalID) |
| @@ -128,9 +135,28 @@ func List(ctx context.Context, q querier) ([]Conn, error) { |
| return out, rows.Err() |
| } |
| -// Remove forgets a signed-out connection: its record and slot. Its |
| -// charges stay until they age out with the day's and month's sums. |
| +// ErrSlotHeld: the connection cannot go while an attempt holds its slot. |
| +var ErrSlotHeld = errors.New("metered: an attempt holds the slot") |
| + |
| +// Retire starts a connection's sign-out: from this transaction on, |
| +// nothing more is admitted to it. |
| +func Retire(ctx context.Context, tx *sql.Tx, local string) error { |
| + _, err := tx.ExecContext(ctx, "UPDATE metered_connections SET retiring=1 WHERE local_id=?", local) |
| + return err |
| +} |
| + |
| +// Remove forgets a signed-out connection, its record and slot, only once |
| +// its slot is free: an attempt still running is charged (or its spend |
| +// made unknown) first (ErrSlotHeld until then). Its charges stay until |
| +// they age out with the day's and month's sums. |
| func Remove(ctx context.Context, tx *sql.Tx, local string) error { |
| + var holder string |
| + if err := tx.QueryRowContext(ctx, "SELECT holder FROM metered_slot WHERE local_id=?", local).Scan(&holder); err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return err |
| + } |
| + if holder != "" { |
| + return ErrSlotHeld |
| + } |
| if _, err := tx.ExecContext(ctx, "DELETE FROM metered_connections WHERE local_id=?", local); err != nil { |
| return err |
| } |
| @@ -176,7 +202,9 @@ func spent(ctx context.Context, q querier, local string, now time.Time) (day, mo |
| // free, the spend is known, and the reported spend is under both the |
| // day's and the month's budget. The same holder asking again is |
| // admitted (its claim stands). Every attempt on a metered connection |
| -// passes here: an Engineering or Review step, a question, a probe. |
| +// passes here: an Engineering or Review step, a question, a probe. A |
| +// holder that already claims the slot is not admitted again, and a |
| +// retiring connection admits nothing. |
| func Admit(ctx context.Context, tx *sql.Tx, local string, h Holder, now time.Time) (Admission, error) { |
| c, ok, err := Get(ctx, tx, local) |
| if err != nil || !ok { |
| @@ -187,9 +215,9 @@ func Admit(ctx context.Context, tx *sql.Tx, local string, h Holder, now time.Tim |
| return Admission{}, err |
| } |
| if holder == h.Key() { |
| - return Admission{Admitted: true}, nil |
| + return Admission{Claimed: true, Hold: HoldBusy}, nil |
| } |
| - if holder != "" { |
| + if holder != "" || c.Retiring { |
| return Admission{Hold: HoldBusy}, nil |
| } |
| if c.SpendUnknown { |
| @@ -318,12 +346,13 @@ func pause(ctx context.Context, tx *sql.Tx, local string) error { |
| return err |
| } |
| -// Resume consumes the person's Resume bound to the pause they saw: it |
| +// Resume consumes the person's Resume for connection (the instance's |
| +// id), bound to the pause they saw: it |
| // clears the unknown spend once, and only while pauseRevision is still |
| // the connection's pause. A stale or repeated Resume changes nothing, |
| // so a newer pause stays. It reports whether it cleared one. |
| -func Resume(ctx context.Context, tx *sql.Tx, local string, pauseRevision int64) (bool, error) { |
| - res, err := tx.ExecContext(ctx, "UPDATE metered_connections SET spend_unknown=0 WHERE local_id=? AND spend_unknown=1 AND pause_revision=?", local, pauseRevision) |
| +func Resume(ctx context.Context, tx *sql.Tx, local, connection string, pauseRevision int64) (bool, error) { |
| + res, err := tx.ExecContext(ctx, "UPDATE metered_connections SET spend_unknown=0 WHERE local_id=? AND connection=? AND spend_unknown=1 AND pause_revision=?", local, connection, pauseRevision) |
| if err != nil { |
| return false, err |
| } |
| @@ -331,14 +360,14 @@ func Resume(ctx context.Context, tx *sql.Tx, local string, pauseRevision int64) |
| return n == 1, err |
| } |
| -// ApplyBudget applies a budget change above the revision the runner |
| -// holds; an older or equal revision changes nothing. A running attempt |
| +// ApplyBudget applies a budget change for connection (the instance's |
| +// id) above the revision the runner holds; an older or equal revision changes nothing. A running attempt |
| // is not stopped: the budget is read at the next admission. |
| -func ApplyBudget(ctx context.Context, tx *sql.Tx, local string, b wire.Budget) (bool, error) { |
| +func ApplyBudget(ctx context.Context, tx *sql.Tx, local, connection string, b wire.Budget) (bool, error) { |
| if !wire.ValidBudget(b) { |
| return false, errors.New("metered: budget out of bounds") |
| } |
| - res, err := tx.ExecContext(ctx, "UPDATE metered_connections SET budget_day=?, budget_month=?, budget_revision=? WHERE local_id=? AND budget_revision<?", b.Day, b.Month, b.Revision, local, b.Revision) |
| + res, err := tx.ExecContext(ctx, "UPDATE metered_connections SET budget_day=?, budget_month=?, budget_revision=? WHERE local_id=? AND connection=? AND budget_revision<?", b.Day, b.Month, b.Revision, local, connection, b.Revision) |
| if err != nil { |
| return false, err |
| } |
diff --git a/internal/runner/metered/meter.go b/internal/runner/metered/meter.go| index 3d352297..b19336d6 100644 |
| --- a/internal/runner/metered/meter.go |
| +++ b/internal/runner/metered/meter.go |
| @@ -102,7 +102,15 @@ func (m *Meter) changed() { |
| // Admit claims the slot for h when the guard allows it, in its own |
| // transaction plus whatever admit adds to it (the caller's admission |
| // record), so the claim and the admission commit together. |
| +// |
| +// The attempt is registered as running here before its admission |
| +// commits, so a Recover never sees its claim without it and never |
| +// releases it unproven; a holder running here already is held, never |
| +// launched twice. |
| func (m *Meter) Admit(ctx context.Context, local string, h Holder, admit func(*sql.Tx) error) (Admission, error) { |
| + if !m.reserve(local, h) { |
| + return Admission{Claimed: true, Hold: HoldBusy}, nil |
| + } |
| var a Admission |
| err := m.tx(ctx, func(t *sql.Tx) error { |
| var err error |
| @@ -111,13 +119,38 @@ func (m *Meter) Admit(ctx context.Context, local string, h Holder, admit func(*s |
| } |
| return admit(t) |
| }) |
| - if err == nil && a.Admitted { |
| - m.setRunning(local, h, true) |
| - m.changed() |
| + if err != nil || !a.Admitted { |
| + m.setRunning(local, h, false) |
| + return a, err |
| + } |
| + if m.Fault != nil { |
| + if err := m.Fault("admitted"); err != nil { |
| + return a, err |
| + } |
| } |
| - return a, err |
| + m.changed() |
| + return a, nil |
| } |
| +// reserve registers h as running on local unless it is already. |
| +func (m *Meter) reserve(local string, h Holder) bool { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if m.running == nil { |
| + m.running = map[string]bool{} |
| + } |
| + key := local + "\x00" + h.Key() |
| + if m.running[key] { |
| + return false |
| + } |
| + m.running[key] = true |
| + return true |
| +} |
| + |
| +// Notify tells the runner a metered connection's standing changed (a |
| +// budget applied, a pause resumed) outside the Meter's own calls. |
| +func (m *Meter) Notify() { m.changed() } |
| + |
| // Run admits h on the connection, runs the attempt and settles it. |
| // Held, it returns the hold and runs nothing. report, in the charge's |
| // transaction, records the priced rows (the attempt's report or usage |
| @@ -213,11 +246,11 @@ func (m *Meter) Recover(ctx context.Context) error { |
| } |
| // Resume consumes a Resume for the pause it names (Resume). |
| -func (m *Meter) Resume(ctx context.Context, local string, pauseRevision int64, record func(*sql.Tx) error) (bool, error) { |
| +func (m *Meter) Resume(ctx context.Context, local, connection string, pauseRevision int64, record func(*sql.Tx) error) (bool, error) { |
| var cleared bool |
| err := m.tx(ctx, func(t *sql.Tx) error { |
| var err error |
| - if cleared, err = Resume(ctx, t, local, pauseRevision); err != nil { |
| + if cleared, err = Resume(ctx, t, local, connection, pauseRevision); err != nil { |
| return err |
| } |
| if record != nil { |
| @@ -233,11 +266,11 @@ func (m *Meter) Resume(ctx context.Context, local string, pauseRevision int64, r |
| // ApplyBudget applies a budget frame (ApplyBudget) with record, the |
| // frame's own bookkeeping, in one transaction. |
| -func (m *Meter) ApplyBudget(ctx context.Context, local string, b wire.Budget, record func(*sql.Tx) error) (bool, error) { |
| +func (m *Meter) ApplyBudget(ctx context.Context, local, connection string, b wire.Budget, record func(*sql.Tx) error) (bool, error) { |
| var applied bool |
| err := m.tx(ctx, func(t *sql.Tx) error { |
| var err error |
| - if applied, err = ApplyBudget(ctx, t, local, b); err != nil { |
| + if applied, err = ApplyBudget(ctx, t, local, connection, b); err != nil { |
| return err |
| } |
| if record != nil { |
diff --git a/internal/runner/metered/meter_test.go b/internal/runner/metered/meter_test.go| index c815275f..29ce6a1f 100644 |
| --- a/internal/runner/metered/meter_test.go |
| +++ b/internal/runner/metered/meter_test.go |
| @@ -45,7 +45,7 @@ func newRig(t *testing.T, day, month int64) *rig { |
| r.db = open(t, r.dir) |
| r.m = r.meter() |
| err := r.m.tx(context.Background(), func(tx *sql.Tx) error { |
| - return Add(context.Background(), tx, Conn{LocalID: tx1, Person: "p", Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: "/h", Currency: "USD", PriceVersion: Current[wire.ProviderTensorX], Budget: wire.Budget{Day: day, Month: month, Revision: 1}}, r.clock) |
| + return Add(context.Background(), tx, Conn{LocalID: tx1, Connection: "cn_1", Person: "p", Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: "/h", Currency: "USD", PriceVersion: Current[wire.ProviderTensorX], Budget: wire.Budget{Day: day, Month: month, Revision: 1}}, r.clock) |
| }) |
| if err != nil { |
| t.Fatal(err) |
| @@ -136,10 +136,10 @@ func TestMeteredBudgetHoldsTheNextAttempt(t *testing.T) { |
| t.Fatalf("month: %+v", a) |
| } |
| // A raised budget, applied, admits; an older revision changes nothing. |
| - if ok, err := r.m.ApplyBudget(context.Background(), tx1, wire.Budget{Day: 900_000, Month: 9_000_000, Revision: 1}, nil); err != nil || ok { |
| + if ok, err := r.m.ApplyBudget(context.Background(), tx1, "cn_1", wire.Budget{Day: 900_000, Month: 9_000_000, Revision: 1}, nil); err != nil || ok { |
| t.Fatalf("same revision applied: %v %v", ok, err) |
| } |
| - if ok, err := r2.m.ApplyBudget(context.Background(), tx1, wire.Budget{Day: 2_000_000, Month: 5_000_000, Revision: 2}, nil); err != nil || !ok { |
| + if ok, err := r2.m.ApplyBudget(context.Background(), tx1, "cn_1", wire.Budget{Day: 2_000_000, Month: 5_000_000, Revision: 2}, nil); err != nil || !ok { |
| t.Fatalf("raise: %v %v", ok, err) |
| } |
| if a := r2.run(step("s3", RoleEngineering)); a.Hold == HoldBudget { |
| @@ -291,7 +291,7 @@ func TestMeteredStaleResumeLeavesTheNewerPause(t *testing.T) { |
| if s := r.spend(); !s.Unknown || s.PauseRevision != 1 { |
| t.Fatalf("pause 1: %+v", s) |
| } |
| - if ok, err := r.m.Resume(ctx, tx1, 1, nil); err != nil || !ok { |
| + if ok, err := r.m.Resume(ctx, tx1, "cn_1", 1, nil); err != nil || !ok { |
| t.Fatalf("resume 1: %v %v", ok, err) |
| } |
| // Another unknown spend: pause 2. |
| @@ -300,16 +300,16 @@ func TestMeteredStaleResumeLeavesTheNewerPause(t *testing.T) { |
| t.Fatalf("pause 2: %+v", s) |
| } |
| // The first Resume again, replayed or stale, changes nothing. |
| - if ok, err := r.m.Resume(ctx, tx1, 1, nil); err != nil || ok { |
| + if ok, err := r.m.Resume(ctx, tx1, "cn_1", 1, nil); err != nil || ok { |
| t.Fatalf("stale resume cleared: %v %v", ok, err) |
| } |
| if a := r.run(step("s3", RoleEngineering)); a.Hold != HoldSpendUnknown { |
| t.Fatalf("admitted after a stale resume: %+v", a) |
| } |
| - if ok, _ := r.m.Resume(ctx, tx1, 2, nil); !ok { |
| + if ok, _ := r.m.Resume(ctx, tx1, "cn_1", 2, nil); !ok { |
| t.Fatal("the current resume did nothing") |
| } |
| - if ok, _ := r.m.Resume(ctx, tx1, 2, nil); ok { |
| + if ok, _ := r.m.Resume(ctx, tx1, "cn_1", 2, nil); ok { |
| t.Fatal("a resume was consumed twice") |
| } |
| if a := r.run(step("s3", RoleEngineering), usage("z-ai/glm-5.3", 1, 1, 1)); !a.Admitted { |
| @@ -391,3 +391,145 @@ func TestMeteredUnpricedModelIsSpendUnknown(t *testing.T) { |
| t.Fatalf("not started: %+v", s) |
| } |
| } |
| + |
| +// Security round finding 1: an attempt is registered as running before |
| +// its admission commits, so a Recover in between (here, in the window |
| +// right after the commit) never releases its slot unproven, and nothing |
| +// else is admitted while it runs. |
| +func TestMeteredRecoverBetweenAdmissionAndLaunch(t *testing.T) { |
| + r := newRig(t, 1_000_000, 10_000_000) |
| + recovered := false |
| + r.m.Fault = func(stage string) error { |
| + if stage == "admitted" && !recovered { |
| + recovered = true |
| + if err := r.m.Recover(context.Background()); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + return nil |
| + } |
| + ran := false |
| + _, _, err := r.m.Run(context.Background(), tx1, step("s1", RoleEngineering), func(ctx context.Context, l Launch) Result { |
| + ran = true |
| + if s := r.spend(); !s.Running { |
| + t.Error("the slot was released between the admission and the launch") |
| + } |
| + if a, _ := r.m.Admit(ctx, tx1, step("s2", RoleReview), nil); a.Admitted { |
| + t.Error("a second attempt was admitted while the first ran") |
| + } |
| + return harness(usage("z-ai/glm-5.3", 1, 1, 1))(ctx, l) |
| + }, nil) |
| + if err != nil || !ran || !recovered { |
| + t.Fatalf("ran %v recovered %v %v", ran, recovered, err) |
| + } |
| +} |
| + |
| +// Security round finding 2: a holder already claiming the slot is not |
| +// let in again. Two runs with the same holder at once start one harness; |
| +// a second process (another Meter) finding the claim does not launch. |
| +func TestMeteredDuplicateHolderRunsOnce(t *testing.T) { |
| + r := newRig(t, 1_000_000, 10_000_000) |
| + h := step("s1", RoleEngineering) |
| + release := make(chan struct{}) |
| + var mu sync.Mutex |
| + runs := 0 |
| + var wg sync.WaitGroup |
| + for i := 0; i < 2; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + r.m.Run(context.Background(), tx1, h, func(ctx context.Context, l Launch) Result { |
| + mu.Lock() |
| + runs++ |
| + mu.Unlock() |
| + <-release |
| + return harness(usage("z-ai/glm-5.3", 1, 1, 1))(ctx, l) |
| + }, nil) |
| + }() |
| + } |
| + time.Sleep(200 * time.Millisecond) |
| + close(release) |
| + wg.Wait() |
| + if runs != 1 { |
| + t.Fatalf("the same holder ran %d times", runs) |
| + } |
| + // The claim, seen from a transaction of its own (another process): |
| + // claimed, not admitted. |
| + h2 := step("s2", RoleEngineering) |
| + if a, err := r.m.Admit(context.Background(), tx1, h2, nil); err != nil || !a.Admitted { |
| + t.Fatal(a, err) |
| + } |
| + other := r.meter() |
| + err := other.tx(context.Background(), func(tx *sql.Tx) error { |
| + a, err := Admit(context.Background(), tx, tx1, h2, r.clock) |
| + if err == nil && (a.Admitted || !a.Claimed) { |
| + t.Errorf("a claimed holder admitted again: %+v", a) |
| + } |
| + return err |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// Security round finding 3: a retiring connection admits nothing, and |
| +// is removed only once its slot is free (its attempt charged or its |
| +// spend unknown). |
| +func TestMeteredRetireWaitsForTheSlot(t *testing.T) { |
| + r := newRig(t, 1_000_000, 10_000_000) |
| + ctx := context.Background() |
| + h := step("s1", RoleEngineering) |
| + if a, _ := r.m.Admit(ctx, tx1, h, nil); !a.Admitted { |
| + t.Fatal("not admitted") |
| + } |
| + if err := r.m.tx(ctx, func(tx *sql.Tx) error { return Retire(ctx, tx, tx1) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if a, _ := r.m.Admit(ctx, tx1, step("s2", RoleReview), nil); a.Admitted { |
| + t.Fatal("a retiring connection admitted an attempt") |
| + } |
| + if err := r.m.tx(ctx, func(tx *sql.Tx) error { return Remove(ctx, tx, tx1) }); !errors.Is(err, ErrSlotHeld) { |
| + t.Fatalf("removed with its slot held: %v", err) |
| + } |
| + if err := r.m.Finish(ctx, tx1, h, Result{Usage: []wire.Usage{usage("z-ai/glm-5.3", 1, 10, 1)}, Ending: Ending{Proven: true}}, nil); err != nil { |
| + t.Fatalf("the attempt's charge after retiring: %v", err) |
| + } |
| + if a, _ := r.m.Admit(ctx, tx1, step("s3", RoleReview), nil); a.Admitted { |
| + t.Fatal("a retiring connection with a free slot admitted an attempt") |
| + } |
| + if err := r.m.tx(ctx, func(tx *sql.Tx) error { return Remove(ctx, tx, tx1) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + var charged int |
| + r.db.QueryRow("SELECT count(*) FROM budget_charge WHERE connection=?", tx1).Scan(&charged) |
| + if charged != 1 { |
| + t.Fatalf("charges %d", charged) |
| + } |
| +} |
| + |
| +// Security round finding 4: a budget or a Resume names the connection |
| +// it is for; one for another connection (an earlier one under the same |
| +// runner name) changes nothing. |
| +func TestMeteredBindingNamesTheConnection(t *testing.T) { |
| + r := newRig(t, 1_000_000, 10_000_000) |
| + ctx := context.Background() |
| + r.run(step("s1", RoleEngineering)) // spend unknown, pause 1 |
| + err := r.m.tx(ctx, func(tx *sql.Tx) error { |
| + if ok, err := ApplyBudget(ctx, tx, tx1, "cn_old", wire.Budget{Day: 5, Month: 9, Revision: 9}); err != nil || ok { |
| + t.Errorf("another connection's budget applied: %v %v", ok, err) |
| + } |
| + if ok, err := Resume(ctx, tx, tx1, "cn_old", 1); err != nil || ok { |
| + t.Errorf("another connection's resume consumed: %v %v", ok, err) |
| + } |
| + if ok, err := ApplyBudget(ctx, tx, tx1, "cn_1", wire.Budget{Day: 5, Month: 9, Revision: 9}); err != nil || !ok { |
| + t.Errorf("its own budget: %v %v", ok, err) |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if s := r.spend(); !s.Unknown { |
| + t.Fatal("resumed by another connection's frame") |
| + } |
| +} |
diff --git a/internal/runner/thin/apikey.go b/internal/runner/thin/apikey.go| index 191c0e6a..015e4c1b 100644 |
| --- a/internal/runner/thin/apikey.go |
| +++ b/internal/runner/thin/apikey.go |
| @@ -170,7 +170,7 @@ func (c *Connector) runAPIKey(ctx context.Context, cmd wire.ConnectCommand, base |
| failed(home, reasonOf(firstErr(ctx.Err(), context.Canceled))) |
| return |
| } |
| - conn := metered.Conn{LocalID: local, Person: cmd.Person, Provider: cmd.Provider, Harness: kp.Harness, Upstream: kp.Upstream, Billing: billing, Model: model, Home: home, Currency: table.Currency, PriceVersion: table.Version, Budget: wire.Budget{Day: budget.Day, Month: budget.Month, Currency: table.Currency, Revision: budget.Revision}} |
| + conn := metered.Conn{Connection: cmd.Connection, LocalID: local, Person: cmd.Person, Provider: cmd.Provider, Harness: kp.Harness, Upstream: kp.Upstream, Billing: billing, Model: model, Home: home, Currency: table.Currency, PriceVersion: table.Version, Budget: wire.Budget{Day: budget.Day, Month: budget.Month, Currency: table.Currency, Revision: budget.Revision}} |
| err = c.State.tx(ctx, func(t *sql.Tx) error { |
| if _, ok, err := metered.Get(ctx, t, local); err != nil || ok { |
| if ok { |
| @@ -264,6 +264,9 @@ func (c *Connector) probe(ctx context.Context, conn metered.Conn, id string) err |
| defer clear(key) |
| u, err := api.Probe(ctx, key, conn.Model) |
| perr = err |
| + // Another model answering proves nothing about the selected one; |
| + // its usage is that model's, priced as it (security round, |
| + // finding 6). |
| if errors.Is(err, connect.ErrKeyRefused) { |
| // Refused at sign-in: nothing was billed. |
| return metered.Result{Ending: metered.Ending{Proven: true, NotStarted: true}} |
| @@ -309,48 +312,66 @@ func (c *Connector) Model(ctx context.Context, frameID string, cmd wire.ModelCom |
| } |
| // Budget applies a budget frame for one of the person's metered |
| -// connections, with the frame's record in the same transaction; the |
| -// link acks it after, which is when the instance shows it applied. A |
| -// frame for no such connection, or out of bounds, is acked unapplied. |
| +// connections. In one transaction: a frame already consumed changes |
| +// nothing; the command must name the connection's own instance id, |
| +// person and runner name, and a budget in bounds; then it is applied |
| +// (security round, finding 4). The link acks it after, which is when the |
| +// instance shows it applied. A frame that does not bind is acked |
| +// unapplied. |
| func (c *Connector) Budget(ctx context.Context, frameID string, cmd wire.BudgetCommand) error { |
| m := c.meter() |
| if m == nil { |
| return nil |
| } |
| - if conn, ok, err := metered.Get(ctx, c.State.db, cmd.LocalID); err != nil { |
| - return err |
| - } else if !ok || conn.Person != cmd.Person || !wire.ValidBudget(cmd.Budget) { |
| - return nil |
| - } |
| - _, err := m.ApplyBudget(ctx, cmd.LocalID, cmd.Budget, func(t *sql.Tx) error { |
| - _, err := seen(t, frameID) |
| + applied := false |
| + err := c.State.tx(ctx, func(t *sql.Tx) error { |
| + fresh, err := seen(t, frameID) |
| + if err != nil || !fresh || !wire.ValidBudget(cmd.Budget) { |
| + return err |
| + } |
| + if ok, err := bound(ctx, t, cmd.LocalID, cmd.Connection, cmd.Person); err != nil || !ok { |
| + return err |
| + } |
| + applied, err = metered.ApplyBudget(ctx, t, cmd.LocalID, cmd.Connection, cmd.Budget) |
| return err |
| }) |
| - if err == nil { |
| - c.Conns.changed() |
| + if err == nil && applied { |
| + m.Notify() |
| } |
| return err |
| } |
| -// ResumeSpend consumes the person's Resume for the pause it names. |
| +// bound reports whether a frame's binding is the metered connection's |
| +// own: its runner name, the instance's id for it and its person. |
| +func bound(ctx context.Context, t *sql.Tx, local, connection, person string) (bool, error) { |
| + conn, ok, err := metered.Get(ctx, t, local) |
| + if err != nil || !ok { |
| + return false, err |
| + } |
| + return conn.Connection != "" && conn.Connection == connection && conn.Person == person, nil |
| +} |
| + |
| +// ResumeSpend consumes the person's Resume for the pause it names, under |
| +// the same binding and freshness rules as Budget. |
| func (c *Connector) ResumeSpend(ctx context.Context, frameID string, cmd wire.ResumeSpendCommand) error { |
| m := c.meter() |
| if m == nil { |
| return nil |
| } |
| - if conn, ok, err := metered.Get(ctx, c.State.db, cmd.LocalID); err != nil { |
| - return err |
| - } else if !ok || conn.Person != cmd.Person { |
| - return nil |
| - } |
| - fresh := true |
| - _, err := m.Resume(ctx, cmd.LocalID, cmd.PauseRevision, func(t *sql.Tx) error { |
| - var err error |
| - fresh, err = seen(t, frameID) |
| + cleared := false |
| + err := c.State.tx(ctx, func(t *sql.Tx) error { |
| + fresh, err := seen(t, frameID) |
| + if err != nil || !fresh { |
| + return err |
| + } |
| + if ok, err := bound(ctx, t, cmd.LocalID, cmd.Connection, cmd.Person); err != nil || !ok { |
| + return err |
| + } |
| + cleared, err = metered.Resume(ctx, t, cmd.LocalID, cmd.Connection, cmd.PauseRevision) |
| return err |
| }) |
| - if err == nil && fresh { |
| - c.Conns.changed() |
| + if err == nil && cleared { |
| + m.Notify() |
| } |
| return err |
| } |
| @@ -370,15 +391,39 @@ func (c *Connector) checkMetered(conn metered.Conn) { |
| }) |
| } |
| -// removeMetered is a metered connection's part of its sign-out: its |
| -// record goes before its home; a stop between them leaves the home in |
| -// the cleanup record, which deletes it on the next start. |
| +// removeMetered is a metered connection's part of its sign-out |
| +// (security round, finding 3): it retires first, so nothing more is |
| +// admitted; an attempt still holding its slot (a Check again's probe) is |
| +// awaited, and its charge or spend_unknown commits before the record |
| +// goes; then the record goes before its home (a stop between them leaves |
| +// the home in the cleanup record, deleted on the next start). An attempt |
| +// that does not end in time leaves the sign-out owed, retired. |
| func (c *Connector) removeMetered(k cleanup) bool { |
| - err := c.State.tx(context.Background(), func(t *sql.Tx) error { return metered.Remove(context.Background(), t, k.local) }) |
| - if err != nil { |
| + ctx := context.Background() |
| + if err := c.State.tx(ctx, func(t *sql.Tx) error { return metered.Retire(ctx, t, k.local) }); err != nil { |
| c.log("disconnect metered", err) |
| return false |
| } |
| + deadline := time.Now().Add(removeWait) |
| + for { |
| + err := c.State.tx(ctx, func(t *sql.Tx) error { return metered.Remove(ctx, t, k.local) }) |
| + if err == nil { |
| + break |
| + } |
| + if !errors.Is(err, metered.ErrSlotHeld) || time.Now().After(deadline) { |
| + c.log("disconnect metered", err) |
| + return false |
| + } |
| + // An attempt that ended unproven is proven here, if it can be. |
| + if m := c.meter(); m != nil { |
| + _ = m.Recover(ctx) |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| c.Conns.changed() |
| return true |
| } |
| + |
| +// removeWait bounds how long a sign-out waits for a running attempt: a |
| +// probe's own limit and a little more. |
| +const removeWait = 3 * time.Minute |
diff --git a/internal/runner/thin/apikey_test.go b/internal/runner/thin/apikey_test.go| index f62fc455..1e623c5a 100644 |
| --- a/internal/runner/thin/apikey_test.go |
| +++ b/internal/runner/thin/apikey_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "encoding/json" |
| "net/http" |
| "net/http/httptest" |
| + "net/netip" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -12,6 +13,7 @@ import ( |
| "testing" |
| "time" |
| + "amadan.net/oficina/equipo/internal/runner/connect" |
| "amadan.net/oficina/equipo/internal/runner/metered" |
| "amadan.net/oficina/equipo/internal/sealbox" |
| "amadan.net/oficina/equipo/internal/wire" |
| @@ -26,6 +28,11 @@ type fakeTensorX struct { |
| key string |
| probes []string |
| usage string |
| + // answered, when set, is the model the provider says answered; |
| + // hold, when set, keeps a completion open until it is closed. |
| + answered string |
| + hold chan struct{} |
| + started chan struct{} |
| } |
| func newFakeTensorX(t *testing.T, key string) *fakeTensorX { |
| @@ -52,8 +59,16 @@ func newFakeTensorX(t *testing.T, key string) *fakeTensorX { |
| } |
| f.mu.Lock() |
| f.probes = append(f.probes, in.Model) |
| + model, hold, started := in.Model, f.hold, f.started |
| + if f.answered != "" { |
| + model = f.answered |
| + } |
| f.mu.Unlock() |
| - w.Write([]byte(`{"choices":[{"message":{"content":"ok"}}],"usage":` + usage + `}`)) |
| + if hold != nil { |
| + started <- struct{}{} |
| + <-hold |
| + } |
| + w.Write([]byte(`{"model":"` + model + `","choices":[{"message":{"content":"ok"}}],"usage":` + usage + `}`)) |
| default: |
| w.WriteHeader(http.StatusNotFound) |
| } |
| @@ -89,7 +104,8 @@ func (r *tokenRig) meteredConnector(fake *fakeTensorX) *Connector { |
| r.conns.Meter = &metered.Meter{DB: r.state.db} |
| } |
| c := r.connector() |
| - c.http, c.origin = fake.Client(), func(string) string { return fake.URL } |
| + // The production transport, with the fake's loopback address allowed. |
| + c.http, c.origin = connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), func(string) string { return fake.URL } |
| return c |
| } |
| @@ -240,6 +256,17 @@ func TestAPIKeyConnectionRoundTrip(t *testing.T) { |
| if err := c.Budget(r.ctx, "f-budget-0", wire.BudgetCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Budget: wire.Budget{Day: 1, Month: 1, Revision: 1}}); err != nil { |
| t.Fatal(err) |
| } |
| + // Security round finding 4: a frame for another connection under the |
| + // same runner name changes nothing, and a frame already consumed is |
| + // not applied again whatever it now says. |
| + for frame, cmd := range map[string]wire.BudgetCommand{ |
| + "f-budget-other": {Connection: "cn_earlier", Person: connPerson, LocalID: local, Budget: wire.Budget{Day: 3, Month: 3, Revision: 7}}, |
| + "f-budget-1": {Connection: "cn_tx", Person: connPerson, LocalID: local, Budget: wire.Budget{Day: 4, Month: 4, Revision: 8}}, |
| + } { |
| + if err := c.Budget(r.ctx, frame, cmd); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| if h, _ := r.held(local); h.Budget.Day != 2_000_000 || h.Budget.Month != 20_000_000 || h.Budget.Revision != 2 { |
| t.Fatalf("budget %+v", h.Budget) |
| } |
| @@ -271,6 +298,120 @@ func TestAPIKeyConnectionRoundTrip(t *testing.T) { |
| if _, ok := r.held(local); ok { |
| t.Fatal("still held") |
| } |
| + // Security round finding 4: a later connection never takes the same |
| + // runner name, so no frame for this one can reach it. |
| + again := r.startAPIKey(c, "cn_tx2") |
| + if filepath.Base(again) == local || filepath.Base(home) == "tensorx-1" { |
| + t.Fatalf("the runner name %q was reused (%q)", filepath.Base(again), local) |
| + } |
| +} |
| + |
| +// TestAPIKeySignOutDuringAProbe (security round, finding 3): a sign-out |
| +// while a Check again's probe runs admits nothing more, waits for the |
| +// probe, commits its charge, and only then deletes the connection. |
| +func TestAPIKeySignOutDuringAProbe(t *testing.T) { |
| + const key = "tx-fake-key-fake-key" |
| + r := newTokenRig(t) |
| + fake := newFakeTensorX(t, key) |
| + c := r.meteredConnector(fake) |
| + home := r.startAPIKey(c, "cn_tx") |
| + local := filepath.Base(home) |
| + r.deliver(c, "f-secret-1", r.sealedKey("cn_tx", key, nil)) |
| + r.card("cn_tx", wire.PromptModel) |
| + c.Model(r.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"}) |
| + if end := r.ended("cn_tx"); end.State != wire.ConnHealthy { |
| + t.Fatalf("end %+v", end) |
| + } |
| + fake.mu.Lock() |
| + fake.hold, fake.started = make(chan struct{}), make(chan struct{}, 8) |
| + fake.mu.Unlock() |
| + var release sync.Once |
| + t.Cleanup(func() { release.Do(func() { close(fake.hold) }) }) |
| + checked := make(chan error, 1) |
| + go func() { |
| + checked <- c.Check(r.ctx, "f-check-1", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}) |
| + }() |
| + <-fake.started |
| + out := make(chan error, 1) |
| + go func() { |
| + out <- c.Disconnect(r.ctx, "f-disconnect", wire.DisconnectCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}) |
| + }() |
| + r.waitFor(func() bool { |
| + conn, ok, _ := metered.Get(r.ctx, r.state.db, local) |
| + return ok && conn.Retiring |
| + }, "the connection retiring") |
| + if a, err := r.conns.Meter.Admit(r.ctx, local, metered.Holder{Step: "s-late", Attempt: 1, Role: metered.RoleEngineering}, nil); err != nil || a.Admitted { |
| + t.Fatalf("admitted while signing out: %+v %v", a, err) |
| + } |
| + if _, ok, _ := metered.Get(r.ctx, r.state.db, local); !ok { |
| + t.Fatal("deleted while its probe ran") |
| + } |
| + release.Do(func() { close(fake.hold) }) |
| + if err := <-out; err != nil { |
| + t.Fatal(err) |
| + } |
| + <-checked |
| + r.waitFor(func() bool { |
| + _, ok, _ := metered.Get(r.ctx, r.state.db, local) |
| + return !ok |
| + }, "the connection removed") |
| + var charged int |
| + r.state.db.QueryRow("SELECT count(*) FROM budget_charge WHERE connection=? AND step LIKE 'pr_tensorx%'", local).Scan(&charged) |
| + probes := 0 |
| + for _, u := range r.usageFrames() { |
| + if strings.HasPrefix(u.ProbeID, "pr_"+local) { |
| + probes++ |
| + } |
| + } |
| + if charged != 1 || probes != 1 { |
| + t.Fatalf("the running probe's charge: %d rows, %d usage frames", charged, probes) |
| + } |
| +} |
| + |
| +// TestAPIKeyProbeAnsweredByAnotherModel (security round, finding 6): |
| +// a probe answered by another model proves nothing; its usage is that |
| +// model's, and an unpriced one leaves the spend unknown. |
| +func TestAPIKeyProbeAnsweredByAnotherModel(t *testing.T) { |
| + const key = "tx-fake-key-fake-key" |
| + r := newTokenRig(t) |
| + fake := newFakeTensorX(t, key) |
| + c := r.meteredConnector(fake) |
| + home := r.startAPIKey(c, "cn_tx") |
| + local := filepath.Base(home) |
| + r.deliver(c, "f-secret-1", r.sealedKey("cn_tx", key, nil)) |
| + r.card("cn_tx", wire.PromptModel) |
| + c.Model(r.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"}) |
| + if end := r.ended("cn_tx"); end.State != wire.ConnHealthy { |
| + t.Fatalf("end %+v", end) |
| + } |
| + fake.mu.Lock() |
| + fake.answered = "vendor/unpriced" |
| + fake.mu.Unlock() |
| + if err := c.Check(r.ctx, "f-check-1", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.waitFor(func() bool { h, _ := r.held(local); return h.Spend != nil && h.Spend.Unknown }, "spend unknown") |
| + var row *wire.Usage |
| + for _, u := range r.usageFrames() { |
| + if strings.HasPrefix(u.ProbeID, "pr_"+local) { |
| + row = &u.Rows[0] |
| + } |
| + } |
| + if row == nil || row.Model != "vendor/unpriced" || row.CostMicros != nil { |
| + t.Fatalf("the probe's row %+v", row) |
| + } |
| + // A new attempt answered by another model is not made a connection. |
| + r2 := newTokenRig(t) |
| + fake2 := newFakeTensorX(t, key) |
| + fake2.answered = "z-ai/glm-5.3-flash" |
| + c2 := r2.meteredConnector(fake2) |
| + r2.startAPIKey(c2, "cn_tx") |
| + r2.deliver(c2, "f-secret-1", r2.sealedKey("cn_tx", key, nil)) |
| + r2.card("cn_tx", wire.PromptModel) |
| + c2.Model(r2.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"}) |
| + if end := r2.ended("cn_tx"); end.State == wire.ConnHealthy { |
| + t.Fatalf("made a connection on another model's answer: %+v", end) |
| + } |
| } |
| // TestAPIKeyBoxBoundToTheProvider: a box for an API-key attempt bound to |
diff --git a/internal/runner/thin/askmetered_test.go b/internal/runner/thin/askmetered_test.go| index 17e90f01..f87ed6e8 100644 |
| --- a/internal/runner/thin/askmetered_test.go |
| +++ b/internal/runner/thin/askmetered_test.go |
| @@ -35,7 +35,7 @@ func newAskRig(t *testing.T, harness bool) *askRig { |
| t.Cleanup(func() { s.Close() }) |
| r := &askRig{t: t, ctx: ctx, s: s, m: &metered.Meter{DB: s.db}} |
| err = s.tx(ctx, func(tx *sql.Tx) error { |
| - if err := metered.Add(ctx, tx, metered.Conn{LocalID: meteredLocal, Person: connPerson, Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: "/nowhere", Currency: "USD", PriceVersion: metered.Current[wire.ProviderTensorX], Budget: wire.Budget{Day: 1_000_000, Month: 10_000_000, Revision: 1}}, time.Now()); err != nil { |
| + if err := metered.Add(ctx, tx, metered.Conn{Connection: "cn_q", LocalID: meteredLocal, Person: connPerson, Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: "/nowhere", Currency: "USD", PriceVersion: metered.Current[wire.ProviderTensorX], Budget: wire.Budget{Day: 1_000_000, Month: 10_000_000, Revision: 1}}, time.Now()); err != nil { |
| return err |
| } |
| return metered.Checked(ctx, tx, meteredLocal, true) |
| @@ -156,7 +156,7 @@ func TestMeteredGuardHoldsQuestions(t *testing.T) { |
| } |
| // The budget is spent: the next question waits for the next day. |
| if err := r.s.tx(r.ctx, func(tx *sql.Tx) error { |
| - _, err := metered.ApplyBudget(r.ctx, tx, meteredLocal, wire.Budget{Day: 2200, Month: 10_000_000, Revision: 2}) |
| + _, err := metered.ApplyBudget(r.ctx, tx, meteredLocal, "cn_q", wire.Budget{Day: 2200, Month: 10_000_000, Revision: 2}) |
| return err |
| }); err != nil { |
| t.Fatal(err) |
| @@ -178,7 +178,7 @@ func TestMeteredGuardHoldsQuestions(t *testing.T) { |
| t.Fatalf("reports %d calls %d", n, r.calls.Load()) |
| } |
| // Raised and applied: it runs. |
| - if _, err := r.m.ApplyBudget(r.ctx, meteredLocal, wire.Budget{Day: 5_000_000, Month: 10_000_000, Revision: 3}, nil); err != nil { |
| + if _, err := r.m.ApplyBudget(r.ctx, meteredLocal, "cn_q", wire.Budget{Day: 5_000_000, Month: 10_000_000, Revision: 3}, nil); err != nil { |
| t.Fatal(err) |
| } |
| r.e.MeteredChanged() |
| @@ -195,7 +195,7 @@ func TestMeteredGuardHoldsQuestions(t *testing.T) { |
| if a := r.waitAnswer("q3", wire.QuestionQueued); a.Reason != wire.HoldSpendUnknown { |
| t.Fatalf("held %+v", a) |
| } |
| - if ok, err := r.m.Resume(r.ctx, meteredLocal, 7, nil); err != nil || !ok { |
| + if ok, err := r.m.Resume(r.ctx, meteredLocal, "cn_q", 7, nil); err != nil || !ok { |
| t.Fatal(ok, err) |
| } |
| r.e.MeteredChanged() |
diff --git a/internal/runner/thin/login.go b/internal/runner/thin/login.go| index ca07d657..19f2d2d5 100644 |
| --- a/internal/runner/thin/login.go |
| +++ b/internal/runner/thin/login.go |
| @@ -137,6 +137,23 @@ func finishLogin(ctx context.Context, c runner.Config, person, name, id, home st |
| } |
| // nextHome creates the first free <provider>-<n> directory. |
| +// uniqueHome makes a home whose name is never reused: name and a random |
| +// suffix. |
| +func uniqueHome(root, name string) (string, string, error) { |
| + for n := 0; n < 10; n++ { |
| + id := name + "-" + strings.ToLower(rand.Text()[:12]) |
| + home := filepath.Join(root, id) |
| + err := os.Mkdir(home, 0700) |
| + if err == nil { |
| + return id, home, nil |
| + } |
| + if !errors.Is(err, os.ErrExist) { |
| + return "", "", err |
| + } |
| + } |
| + return "", "", provider.ErrAccountMaintenance |
| +} |
| + |
| func nextHome(root, name string) (string, string, error) { |
| for n := 1; n < 1000; n++ { |
| id := fmt.Sprintf("%s-%d", name, n) |
diff --git a/internal/runner/thin/token.go b/internal/runner/thin/token.go| index 6f69e8ad..52d19c93 100644 |
| --- a/internal/runner/thin/token.go |
| +++ b/internal/runner/thin/token.go |
| @@ -123,7 +123,13 @@ func (c *Connector) tokenHome(ctx context.Context, id string) (string, error) { |
| } |
| name = a.provider |
| } |
| - _, home, err := nextHome(c.Root, name) |
| + next := nextHome |
| + if a.kind == wire.KindAPIKey { |
| + // Never reused: a frame for an earlier connection can never name |
| + // a later one (security round, finding 4). |
| + next = uniqueHome |
| + } |
| + _, home, err := next(c.Root, name) |
| if err == nil { |
| err = provider.CheckLoginHome(home) |
| } |