apikeys

package
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 15 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 apikeys mints and verifies the caller credentials stored in the api_key table. A key is stored as a sha256 hash, never in plain — the plain value exists only in the response that mints it.

Deliberately not bcrypt: these keys are 32 bytes from crypto/rand, so there is nothing to guess and bcrypt's cost would buy only latency.

Index

Constants

View Source
const (
	// ScopeGenerate allows the data-plane RPCs (GenerateText, ListModels).
	ScopeGenerate = "generate"
	ScopeAdmin    = "admin"
	// ScopeAdminRead allows the Admin API reads and nothing that changes state.
	ScopeAdminRead = "admin:read"
	ScopeNode      = "node"
)

Scopes. A key carries a subset; admin implies all of them.

View Source
const (
	KeyPrefix           = "ktms_"
	NodeKeyPrefix       = "ktms_node_"
	LegacyKeyPrefix     = "llm_"
	LegacyNodeKeyPrefix = "llm_node_"
)

KeyPrefix marks our keys so a leaked string is recognisable in a log scan.

Variables

View Source
var (
	ErrUnauthenticated = errors.New("apikeys: unauthenticated")
	ErrForbidden       = errors.New("apikeys: insufficient scope")
)

ValidScopes is the closed set the admin endpoint accepts.

Functions

func Generate

func Generate(name string, scopes []string) (plain string, row *proxydb.APIKey, err error)

Generate mints a key, returning the plain value (shown to the operator once) alongside the row to store.

func GenerateNodeKey

func GenerateNodeKey(name, nodeID string, allowedCIDRs, allowedModels []string, maxBaseWeight float64, maxConcurrency int32) (plain string, row *proxydb.NodeKey, err error)

GenerateNodeKey mints a node key (prefixed with llm_node_), returning the plain secret alongside the database row to store.

func LookupHash

func LookupHash(plain string) string

LookupHash is the indexed sha256 hex of a plain key.

func NormalizeScopes

func NormalizeScopes(in []string) ([]string, error)

NormalizeScopes rejects unknown scopes and drops duplicates.

func ParseBearer

func ParseBearer(header string) (string, error)

ParseBearer extracts the key from an "Authorization: Bearer <key>" value.

func VerifyHash

func VerifyHash(plain string) string

VerifyHash is what key_hash holds. Same digest as LookupHash on purpose: the lookup column finds the row and the hash column authenticates it; a future change to how rows are found must not quietly change authentication.

func WithIdentity

func WithIdentity(ctx context.Context, id *Identity) context.Context

WithIdentity stores the authenticated caller for handlers downstream of the auth interceptor.

Types

type Identity

type Identity struct {
	KeyID             string
	Name              string
	Scopes            []string
	NodeID            string
	AllowedCIDRs      []string
	AllowedModels     []string
	MaxBaseWeight     float64
	MaxConcurrent     int32
	OrgID             string
	TeamID            string
	TeamAllowedModels []string
	// The client key's own policy; empty and 0 mean no limit.
	KeyAllowedModels []string
	RPMLimit         int32
	TPMLimit         int64
}

Identity is the authenticated caller.

func IdentityFor added in v1.2.0

func IdentityFor(row *proxydb.APIKey) *Identity

IdentityFor is the caller a client key's row stands for, as Verify builds it; ExplainRoute uses it to route as that key would.

func IdentityFrom

func IdentityFrom(ctx context.Context) *Identity

IdentityFrom returns the authenticated caller, or nil outside an authenticated RPC (exempt methods, tests).

func (*Identity) CanAccessModel added in v0.14.0

func (i *Identity) CanAccessModel(modelID string) bool

CanAccessModel reports whether both the key's and its team's allowlists (empty = any model) permit modelID.

func (*Identity) DeniedBy added in v1.0.0

func (i *Identity) DeniedBy(modelID string) string

DeniedBy names the allowlist that refuses modelID: "team" when the team's does, else "key". Refusal messages name it so the operator knows which to edit.

func (*Identity) HasScope

func (i *Identity) HasScope(want string) bool

HasScope reports whether the caller may perform an action needing want.

func (*Identity) RestrictsModels added in v1.0.0

func (i *Identity) RestrictsModels() bool

RestrictsModels reports whether an allowlist narrows the models it may call.

type Store

type Store interface {
	GetAPIKeyByLookup(ctx context.Context, lookup string) (*proxydb.APIKey, error)
	GetNodeKeyByLookup(ctx context.Context, lookup string) (*proxydb.NodeKey, error)
}

Store is the slice of proxydb the verifier needs, so tests can fake it.

type Verifier

type Verifier struct {
	// contains filtered or unexported fields
}

Verifier authenticates bearer keys for the gRPC interceptor.

func NewVerifier

func NewVerifier(store Store, bootstrapKey string) *Verifier

NewVerifier builds a verifier. bootstrapKey, when non-empty, is accepted as an implicit admin key — it exists only to mint the first real key, and can be unset afterwards.

func (*Verifier) Verify

func (v *Verifier) Verify(ctx context.Context, plain string) (*Identity, error)

Verify authenticates a plain key. Auth is never dormant here: no key means no access, because this service holds LLM vendor keys.

func (*Verifier) VerifyScope

func (v *Verifier) VerifyScope(ctx context.Context, plain, scope string) (*Identity, error)

VerifyScope authenticates and authorises in one step.

func (*Verifier) WithQueryTimeout added in v0.13.1

func (v *Verifier) WithQueryTimeout(d time.Duration) *Verifier

WithQueryTimeout bounds each key lookup, so a hung database fails calls instead of stalling them until every pool connection is stuck.

func (*Verifier) WithStaleIfError added in v0.13.1

func (v *Verifier) WithStaleIfError(maxAge time.Duration) *Verifier

WithStaleIfError lets a key verified within maxAge keep working while the store is unreachable; revocation applies whenever the store answers, so only one made just before an outage can lag, by at most maxAge. 0 disables it.

Jump to

Keyboard shortcuts

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