gateway

package
v1.0.0-alpha.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package gateway gives one CI run its own key on a LiteLLM proxy. The agent's job draws the key and seals it to the gateway's sealing key; a job that holds the sealing key's private half and the proxy's admin key opens it and registers it with the run's budget; the agent runs on it; a last job deletes it. No key crosses a job in the clear.

Index

Constants

View Source
const (
	MetaRepository       = "costroid_repository"
	MetaPullRequest      = "costroid_pull_request"
	MetaHead             = "costroid_head"
	MetaRun              = "costroid_run_id"
	MetaAttempt          = "costroid_run_attempt"
	MetaMaxRequestTokens = "costroid_max_request_tokens"
)

The metadata keys a run's key carries.

View Source
const RequestFile = "costroid-gateway-request.json"

RequestFile is the name of the sealed request inside its artifact.

View Source
const (

	// SealingKeyPrefix starts the sealing key's private half, so it is never
	// taken for the public half.
	SealingKeyPrefix = "costroid-sealing-key-v1-"
)

Variables

View Source
var ErrDerivedSealingKey = errors.New("gateway: the request is sealed to a public key derived from the admin key, which anyone who reads it can test guesses at the admin key against. " +
	"Run costroid gateway keygen, store the private half as the environment secret COSTROID_GATEWAY_SEALING_KEY and the public half as the variable COSTROID_GATEWAY_PUBLIC_KEY, and rotate the admin key")

ErrDerivedSealingKey is a request sealed to a public key derived from the admin key, as versions before keygen made it. Anyone who reads that public key can test guesses at the admin key offline.

View Source
var ErrNotFound = errors.New("gateway: not found")

ErrNotFound is a gateway's answer that the key, team or user is absent.

View Source
var ErrUnsettled = errors.New("may not have settled")

ErrUnsettled marks a figure that was still moving when the wait for it ended. The figure is answered beside it.

Functions

func ActionsToken

func ActionsToken(ctx context.Context, client *http.Client, getenv func(string) string, audience string) (string, error)

ActionsToken asks GitHub Actions for the job's OIDC token, as the ingest job does. It needs id-token: write, which sets the two variables it reads.

func Attest

func Attest(ctx context.Context, client *http.Client, credentialsURL, token string, attestation Attestation) error

Attest sends an attestation to the ledger under the job's OIDC token.

func AttestSpend

func AttestSpend(ctx context.Context, client *http.Client, spendURL, token string, attestation SpendAttestation) error

AttestSpend sends a key's spend to the ledger under the job's OIDC token.

func CheckURL

func CheckURL(base string) error

CheckURL refuses a gateway URL a key would cross the network in the clear to. Every call sends the admin key or the run's key in its Authorization header, so the URL must be https, except on localhost and 127.0.0.1.

func Close

func Close(ctx context.Context, client *Client, adminKey string, run Binding) (bool, error)

Close deletes the run's key. It reports whether a key was there to delete.

func CredentialsURL

func CredentialsURL(ingest string) (string, error)

CredentialsURL is where the ledger behind an ingest URL takes attestations. The URL must be https, because the request carries the job's OIDC token.

func KeyID

func KeyID(key string) string

KeyID is the key's identifier: the SHA-256 of the key in hex, which is what LiteLLM stores in place of the key and writes on its spend logs.

func NewKey

func NewKey() string

NewKey draws a key for one run: 128 random bits after LiteLLM's prefix.

func NewSealingKey

func NewSealingKey() (private, public string, err error)

NewSealingKey draws a sealing key pair at random. It returns the private half, for an environment secret, and the public half, for a repository variable. Nothing about the pair depends on the admin key.

func PublicKey

func PublicKey(sealingKey string) (string, error)

PublicKey is the public half of a sealing key's private half.

func SameSpend

func SameSpend(counted, total decimal.Decimal) bool

SameSpend reports whether the gateway's count and the rows' total are the same figure within spendTolerance.

func SpendURL

func SpendURL(ingest, keyID string) (string, error)

SpendURL is where the ledger behind an ingest URL takes a key's spend.

Types

type Artifacts

type Artifacts struct {
	API        string
	Repository string
	Run        string
	Token      string
	HTTP       *http.Client
	Every      time.Duration
}

Artifacts reads one artifact of the current run through GitHub's REST API, with a token that holds actions: read.

func (Artifacts) Wait

func (a Artifacts) Wait(ctx context.Context, name string) (Request, error)

Wait polls until the artifact named holds the request, or ctx ends.

type Attestation

type Attestation struct {
	KeyID      string `json:"key_id"`
	Repository string `json:"repository"`
	RunID      string `json:"run_id"`
	RunAttempt string `json:"run_attempt"`
}

Attestation tells the ledger that a key was minted for one run. KeyID is the value the run's rows carry in SubAccountId. It holds no secret.

func AttestationFor

func AttestationFor(keyID string, run Binding) Attestation

AttestationFor names the run a binding is for.

type Binding

type Binding struct {
	Repository string `json:"repository"`
	Run        string `json:"run_id"`
	Attempt    string `json:"run_attempt"`
}

Binding names the run a key is for. A key sealed for one binding opens for no other.

func ReadBinding

func ReadBinding(getenv func(string) string) (Binding, error)

ReadBinding reads the run from GitHub Actions' variables.

func (Binding) Alias

func (b Binding) Alias() string

Alias is the key's alias on the gateway. It names the run and the attempt, so the job that deletes the key needs nothing from the jobs before it.

type Client

type Client struct {
	URL  string
	HTTP *http.Client
}

Client speaks LiteLLM's proxy API. It never logs a key: errors name the route and the status, and quote no request.

func NewClient

func NewClient(base string) *Client

NewClient trims the URL and sets a timeout per call.

func (*Client) Count

func (c *Client) Count(ctx context.Context, adminKey, alias string) (Count, bool, error)

Count reads the key with the alias, as the gateway's admin. It answers false when no key has the alias. LiteLLM keeps aliases unique, so a second key with the alias is an error.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, adminKey, alias string) (bool, error)

Delete deletes the keys with the alias. A key already gone is not an error.

func (*Client) EnsureDailyBudget

func (c *Client) EnsureDailyBudget(ctx context.Context, adminKey, kind, id string, budget decimal.Decimal) error

EnsureDailyBudget creates a team or a user with a daily budget, or sets the budget of one that exists. Kind is team or user.

func (*Client) Generate

func (c *Client) Generate(ctx context.Context, adminKey string, spec KeySpec) error

Generate registers a key the caller drew.

func (*Client) Info

func (c *Client) Info(ctx context.Context, bearer, id string) (KeyInfo, error)

Info reads a key. Bearer is the key itself, or the admin key with id naming the key by its id.

func (*Client) Readiness

func (c *Client) Readiness(ctx context.Context) (Readiness, error)

Readiness asks the gateway's public health route, which needs no key.

type Count

type Count struct {
	KeyID string
	Spend decimal.Decimal
}

Count is what the gateway counted on a run's key: the key's id and its spend, in USD at the gateway's own prices.

type Counter

type Counter struct {
	Client   *Client
	AdminKey string
	Run      Binding
	// Poll is how often the key is read. Stable is how long a figure that has
	// moved must then hold to count as settled, and Settle bounds the whole
	// wait. settle says why.
	Poll, Stable, Settle time.Duration
}

Counter reads what the gateway counted on a run's key once the figure has settled. LiteLLM writes spend to its store in batches, so a key read once can still lack its last request.

func (Counter) Settled

func (c Counter) Settled(ctx context.Context) (Count, bool, error)

Settled reads the run's key until its spend has settled as settle reads it, with no figure accepted early, since close has no rows to compare with. It answers false when no key has the run's alias. A figure still moving when Settle passes is answered with an error wrapping ErrUnsettled.

type DailyCaps

type DailyCaps struct {
	Repository *decimal.Decimal
	Author     *decimal.Decimal
}

DailyCaps are the caps a key's team and user carry. A nil cap sets nothing.

type Expect

type Expect struct {
	Budget decimal.Decimal
	Run    string
	Now    time.Time
}

Expect is what the key must say about itself for the run to hold.

type Grant

type Grant struct {
	KeyID            string
	MaxBudget        decimal.Decimal
	MaxParallel      int64
	MaxRequestTokens int64
	// Problems name each fact the key lacks. A grant with any reads none.
	Problems []string
}

Grant is what the gateway holds the run to.

func Inspect

func Inspect(key string, info KeyInfo, expect Expect) Grant

Inspect holds the key the gateway returned to what the run needs.

type KeyInfo

type KeyInfo struct {
	MaxBudget *json.Number `json:"max_budget"`
	Spend     json.Number  `json:"spend"`
	// Expires is read as it came, so a form other than RFC 3339 is named
	// rather than failing the whole answer.
	Expires     json.RawMessage `json:"expires"`
	MaxParallel *int            `json:"max_parallel_requests"`
	Metadata    map[string]any  `json:"metadata"`
	Team        *string         `json:"team_id"`
	User        *string         `json:"user_id"`
	Status      string          `json:"status"`
}

KeyInfo is what the gateway says about a key.

func (KeyInfo) ExpiresAt

func (k KeyInfo) ExpiresAt() (time.Time, bool, error)

ExpiresAt reads the key's expiry. A key with none reads false. An expiry that is not an RFC 3339 time with a zone offset is an error naming the field.

type KeySpec

type KeySpec struct {
	Key         string
	Alias       string
	MaxBudget   decimal.Decimal
	Lifetime    time.Duration
	MaxParallel int
	Metadata    map[string]string
	Team        string
	User        string
}

KeySpec is one run's key as the gateway registers it.

type Mint

type Mint struct {
	Client   *Client
	AdminKey string
	// SealingKey is the private half the request was sealed to.
	SealingKey       string
	Run              Binding
	Request          Request
	Budget           decimal.Decimal
	Lifetime         time.Duration
	MaxParallel      int
	MaxRequestTokens int64
	PullRequest      string
	Head             string
	Author           string
	Caps             DailyCaps
}

Mint is one key to register for one run.

func (Mint) Register

func (m Mint) Register(ctx context.Context) (string, error)

Register opens the request and registers its key with the run's budget, expiry and metadata. It returns the key's id. A request sealed to the public key earlier versions derived from the admin key is refused.

type Readiness

type Readiness struct {
	HTTPStatus int
	Store      string
}

Readiness is the gateway's public health answer.

type Request

type Request struct {
	Format string `json:"format"`
	Binding
	// SealingKey is the public key the key was sealed to.
	SealingKey string `json:"sealing_key"`
	KeyID      string `json:"key_id"`
	Sealed     string `json:"sealed"`
}

Request is the sealed key and the run it is for. It holds no secret: only a holder of the sealing key's private half can open it.

func NewRequest

func NewRequest(publicKey string, binding Binding) (Request, string, error)

NewRequest draws a key for the run and seals it to the gateway's public key. The key is returned to be kept on the runner, and never written to the request.

func ReadRequest

func ReadRequest(source io.Reader) (Request, error)

ReadRequest parses a request file.

func (Request) Open

func (r Request) Open(sealingKey string, run Binding) (string, error)

Open checks that the request names the run the caller is in and was sealed to this sealing key, then opens it. A request copied from another run is refused before it is opened.

type Session

type Session struct {
	Client *Client
	Key    string
	// Wait is how long to wait for the key to be registered.
	Wait time.Duration
	// Every is how often the store is probed while the agent runs.
	Every time.Duration
	// Poll is how often the key is asked for while it is awaited or while
	// its spend settles.
	Poll time.Duration
	// Settle bounds the wait for the key's spend to reach the gateway's store,
	// and must outlast one of LiteLLM's batch writes. Stable is how long a
	// figure that has moved must then hold to count as settled. settle says
	// why.
	Settle, Stable time.Duration
}

Session is one run's key on one gateway, as the agent's job holds it.

func (Session) Await

func (s Session) Await(ctx context.Context) (KeyInfo, error)

Await waits until the key authenticates, then reads it back. A URL the key would cross the network in the clear to is refused before any wait.

func (Session) Env

func (s Session) Env(base []string, agent adapter.Gatewayed) []string

Env is the agent's environment: the base given, with the agent's own variables for the gateway's URL and the run's key in place of any it held, and without each credential the agent names to be removed.

func (Session) Spend

func (s Session) Spend(ctx context.Context, want decimal.Decimal) (decimal.Decimal, error)

Spend reads what the gateway counted on the key, in its own prices, once the agent has ended and the figure has settled. It answers as soon as the figure is the same as want, and otherwise waits as settle does. A figure still moving when Settle passes is answered with an error wrapping ErrUnsettled.

func (Session) Watch

func (s Session) Watch(ctx context.Context) (stop func() string)

Watch probes the gateway's store until stop is called, and once more then. It returns the first reason the store did not hold, or empty.

type SpendAttestation

type SpendAttestation struct {
	Repository string `json:"repository"`
	RunID      string `json:"run_id"`
	RunAttempt string `json:"run_attempt"`
	Currency   string `json:"currency"`
	Spend      string `json:"spend"`
}

SpendAttestation tells the ledger what the gateway counted on a key minted for one run. The key's id is in the URL.

func SpendFor

func SpendFor(count Count, run Binding) SpendAttestation

SpendFor states a count for the run. The ledger keeps 12 fractional digits, so a figure with more is rounded up, and the ledger's figure is never below the gateway's.

Directories

Path Synopsis
Package gatewaytest serves the LiteLLM proxy routes costroid gateway calls, as LiteLLM v1.108.1 answered them on 2026-11-07, for tests.
Package gatewaytest serves the LiteLLM proxy routes costroid gateway calls, as LiteLLM v1.108.1 answered them on 2026-11-07, for tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL