authkeys

package
v0.1.100 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// TokenPrefix is the managed API key prefix returned to clients.
	TokenPrefix = "sk_gom_"

	// ImportedFromLiteLLM marks a key imported from a LiteLLM proxy. Its
	// SecretHash is the SHA-256 of the whole "sk-..." token, as LiteLLM stores
	// it, so the old token keeps working without GoModel ever seeing it.
	ImportedFromLiteLLM = "litellm"
)

Variables

View Source
var (
	// ErrNotFound indicates a requested auth key record does not exist.
	ErrNotFound = errors.New("auth key not found")
	// ErrInvalidToken indicates the presented token does not match a known key.
	ErrInvalidToken = errors.New("invalid API key")
	// ErrInactive indicates the presented token belongs to an inactive key.
	ErrInactive = errors.New("API key is inactive")
	// ErrExpired indicates the presented token belongs to an expired key.
	ErrExpired = errors.New("API key expired")
	// ErrSecretHashExists indicates a key with the same secret hash is
	// already stored. Store.Create returns it for a duplicate hash.
	ErrSecretHashExists = errors.New("an auth key with this secret_hash already exists")
)

Functions

func IsValidationError

func IsValidationError(err error) bool

IsValidationError reports whether err is a validation error.

func NormalizeAllowedModels added in v0.1.84

func NormalizeAllowedModels(values []string) []string

NormalizeAllowedModels trims, drops empty entries, and de-duplicates model selectors while preserving order. Selector syntax is validated by the caller that owns the provider catalog.

Types

type AuthKey

type AuthKey struct {
	ID          string   `json:"id" bson:"_id"`
	Name        string   `json:"name" bson:"name"`
	Description string   `json:"description,omitempty" bson:"description,omitempty"`
	UserPath    string   `json:"user_path,omitempty" bson:"user_path,omitempty"`
	Labels      []string `json:"labels,omitempty" bson:"labels,omitempty"`
	// AllowedModels restricts the key to the listed model selectors (exact
	// "provider/model", provider-wide "provider/", or model-wide "model").
	// Empty means the key alone imposes no model restriction.
	AllowedModels []string `json:"allowed_models,omitempty" bson:"allowed_models,omitempty"`
	// DashboardAccess grants the key access to the admin API and dashboard.
	// Keys without it can still call every model endpoint and /v1/usage.
	DashboardAccess bool       `json:"dashboard_access" bson:"dashboard_access,omitempty"`
	RedactedValue   string     `json:"redacted_value" bson:"redacted_value"`
	SecretHash      string     `json:"-" bson:"secret_hash"`
	Enabled         bool       `json:"enabled" bson:"enabled"`
	ExpiresAt       *time.Time `json:"expires_at,omitempty" bson:"expires_at,omitempty"`
	DeactivatedAt   *time.Time `json:"deactivated_at,omitempty" bson:"deactivated_at,omitempty"`
	CreatedAt       time.Time  `json:"created_at" bson:"created_at"`
	UpdatedAt       time.Time  `json:"updated_at" bson:"updated_at"`
	// ImportedFrom names the gateway an imported key came from, such as
	// ImportedFromLiteLLM. Empty for keys GoModel issued.
	ImportedFrom string `json:"imported_from,omitempty" bson:"imported_from,omitempty"`
}

AuthKey is the persisted auth key record.

func (AuthKey) Active

func (k AuthKey) Active(now time.Time) bool

Active reports whether the key can currently authenticate requests.

type AuthenticationResult

type AuthenticationResult struct {
	ID              string
	UserPath        string
	Labels          []string
	AllowedModels   []string
	DashboardAccess bool
}

AuthenticationResult describes one successful managed auth key lookup.

type CreateInput

type CreateInput struct {
	Name            string
	Description     string
	UserPath        string
	Labels          []string
	AllowedModels   []string
	DashboardAccess bool
	ExpiresAt       *time.Time
}

CreateInput captures the admin request for issuing a new auth key.

type ImportInput added in v0.1.100

type ImportInput struct {
	CreateInput
	ImportedFrom  string
	SecretHash    string
	RedactedValue string
	// Disabled marks a key the source gateway blocked or expired: an
	// existing import is deactivated, and a missing one is not created.
	Disabled bool
}

ImportInput captures the admin request for importing a key another gateway issued. Only the token's hash is imported, never the token.

type ImportOutcome added in v0.1.100

type ImportOutcome int

ImportOutcome reports what Import did with a key.

const (
	// ImportCreated means the key was new and is now stored.
	ImportCreated ImportOutcome = iota
	// ImportUpdated means an earlier import of the key was brought up to date.
	ImportUpdated
	// ImportSkipped means a disabled key had never been imported, so nothing
	// was stored.
	ImportSkipped
)

type IssuedKey

type IssuedKey struct {
	View
	Value string `json:"value"`
}

IssuedKey is returned once on create and includes the plaintext token value.

type MongoDBStore

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

MongoDBStore stores auth keys in MongoDB.

func NewMongoDBStore

func NewMongoDBStore(database *mongo.Database) (*MongoDBStore, error)

NewMongoDBStore creates collection indexes if needed.

func (*MongoDBStore) Close

func (s *MongoDBStore) Close() error

func (*MongoDBStore) Create

func (s *MongoDBStore) Create(ctx context.Context, key AuthKey) error

func (*MongoDBStore) Deactivate

func (s *MongoDBStore) Deactivate(ctx context.Context, id string, now time.Time) error

func (*MongoDBStore) List

func (s *MongoDBStore) List(ctx context.Context) ([]AuthKey, error)

func (*MongoDBStore) UpdateAllowedModels added in v0.1.84

func (s *MongoDBStore) UpdateAllowedModels(ctx context.Context, id string, allowedModels []string, now time.Time) error

func (*MongoDBStore) UpdateDashboardAccess added in v0.1.59

func (s *MongoDBStore) UpdateDashboardAccess(ctx context.Context, id string, allowed bool, now time.Time) error

func (*MongoDBStore) UpdateImported added in v0.1.100

func (s *MongoDBStore) UpdateImported(ctx context.Context, key AuthKey) error

func (*MongoDBStore) UpdateLabels

func (s *MongoDBStore) UpdateLabels(ctx context.Context, id string, labels []string, now time.Time) error

type Result

type Result struct {
	Service *Service
	Store   Store
	// contains filtered or unexported fields
}

Result holds the initialized auth key service and any owned resources.

func New

func New(ctx context.Context, shared storage.Storage) (*Result, error)

New creates an auth key subsystem using an existing storage connection.

func (*Result) Close

func (r *Result) Close() error

Close releases resources held by the auth key subsystem.

type SQLStore added in v0.1.60

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

SQLStore stores auth keys in a SQL database.

func NewSQLStore added in v0.1.60

func NewSQLStore(ctx context.Context, db sqlx.DB) (*SQLStore, error)

NewSQLStore creates the auth_keys table and indexes if needed.

func (*SQLStore) Close added in v0.1.60

func (s *SQLStore) Close() error

func (*SQLStore) Create added in v0.1.60

func (s *SQLStore) Create(ctx context.Context, key AuthKey) error

func (*SQLStore) Deactivate added in v0.1.60

func (s *SQLStore) Deactivate(ctx context.Context, id string, now time.Time) error

func (*SQLStore) List added in v0.1.60

func (s *SQLStore) List(ctx context.Context) ([]AuthKey, error)

func (*SQLStore) UpdateAllowedModels added in v0.1.84

func (s *SQLStore) UpdateAllowedModels(ctx context.Context, id string, allowedModels []string, now time.Time) error

func (*SQLStore) UpdateDashboardAccess added in v0.1.60

func (s *SQLStore) UpdateDashboardAccess(ctx context.Context, id string, allowed bool, now time.Time) error

func (*SQLStore) UpdateImported added in v0.1.100

func (s *SQLStore) UpdateImported(ctx context.Context, key AuthKey) error

func (*SQLStore) UpdateLabels added in v0.1.60

func (s *SQLStore) UpdateLabels(ctx context.Context, id string, labels []string, now time.Time) error

type Service

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

Service keeps managed auth keys cached in memory for request authentication.

func NewService

func NewService(store Store) (*Service, error)

NewService creates a managed auth key service backed by storage.

func (*Service) ActiveCount

func (s *Service) ActiveCount() int

ActiveCount returns the number of currently active auth keys.

func (*Service) Authenticate

func (s *Service) Authenticate(_ context.Context, token string) (AuthenticationResult, error)

Authenticate validates a presented bearer token against the in-memory snapshot and returns the matched auth key metadata on success.

func (*Service) Create

func (s *Service) Create(ctx context.Context, input CreateInput) (*IssuedKey, error)

Create issues a new managed auth key, persists it, updates the in-memory snapshot immediately, and then best-effort reconciles from storage.

func (*Service) Deactivate

func (s *Service) Deactivate(ctx context.Context, id string) error

Deactivate marks a managed auth key inactive while preserving its record and best-effort reconciles the snapshot from storage afterward.

func (*Service) Enabled

func (s *Service) Enabled() bool

Enabled reports whether managed auth keys should be enforced.

func (*Service) Import added in v0.1.100

func (s *Service) Import(ctx context.Context, input ImportInput) (*View, ImportOutcome, error)

Import stores a key another gateway issued, by the hash of its token, so clients keep using that token. Importing the same token again updates the earlier import, so re-running a migration carries over later changes; a Disabled input only deactivates it. It returns ErrSecretHashExists only when the hash belongs to a key from another source.

func (*Service) ListViews

func (s *Service) ListViews() []View

ListViews returns all cached keys in admin-facing form.

func (*Service) Refresh

func (s *Service) Refresh(ctx context.Context) error

Refresh reloads keys from storage and atomically swaps the in-memory snapshot.

func (*Service) StartBackgroundRefresh

func (s *Service) StartBackgroundRefresh(interval time.Duration) func()

StartBackgroundRefresh periodically reloads auth keys from storage until stopped.

func (*Service) Total

func (s *Service) Total() int

Total returns the number of persisted managed auth keys in the current snapshot.

func (*Service) UpdateAllowedModels added in v0.1.84

func (s *Service) UpdateAllowedModels(ctx context.Context, id string, allowedModels []string) (*View, error)

UpdateAllowedModels replaces a managed auth key's model allowlist, updates the in-memory snapshot immediately, best-effort reconciles from storage, and returns the updated admin-facing view. Passing no selectors lifts the key-level restriction.

func (*Service) UpdateDashboardAccess added in v0.1.59

func (s *Service) UpdateDashboardAccess(ctx context.Context, id string, allowed bool) (*View, error)

UpdateDashboardAccess grants or revokes a managed auth key's admin API and dashboard access, updates the in-memory snapshot immediately, best-effort reconciles from storage, and returns the updated admin-facing view.

func (*Service) UpdateLabels

func (s *Service) UpdateLabels(ctx context.Context, id string, labels []string) (*View, error)

UpdateLabels replaces a managed auth key's labels, updates the in-memory snapshot immediately, best-effort reconciles from storage, and returns the updated admin-facing view. Passing no labels clears them.

func (*Service) View added in v0.1.87

func (s *Service) View(id string) (*View, error)

View returns the admin-facing view of one cached key, or ErrNotFound.

type Store

type Store interface {
	List(ctx context.Context) ([]AuthKey, error)
	// Create returns ErrSecretHashExists when a key with key.SecretHash exists.
	Create(ctx context.Context, key AuthKey) error
	// UpdateImported replaces the fields an import sets on the key with
	// key.ID: name, description, user path, labels, allowed models, redacted
	// value, and expiry.
	UpdateImported(ctx context.Context, key AuthKey) error
	UpdateLabels(ctx context.Context, id string, labels []string, now time.Time) error
	UpdateAllowedModels(ctx context.Context, id string, allowedModels []string, now time.Time) error
	UpdateDashboardAccess(ctx context.Context, id string, allowed bool, now time.Time) error
	Deactivate(ctx context.Context, id string, now time.Time) error
	Close() error
}

Store defines persistence operations for managed auth keys.

type ValidationError

type ValidationError = validation.Error

ValidationError indicates invalid auth key input or state.

type View

type View struct {
	AuthKey
	Active bool `json:"active"`
	// LastUsedAt is the key's newest audit-log activity, overlaid by the admin
	// list handler; presentation-only and never persisted.
	LastUsedAt *time.Time `json:"last_used_at,omitempty"`
}

View is the admin-facing representation of a managed auth key.

Jump to

Keyboard shortcuts

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