store

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 31 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 store is remora's SQLite store: schema, migrations and repositories.

Index

Constants

View Source
const ScopeAdmin = "admin"

ScopeAdmin is the default scope for API tokens and the scope of admin sessions.

Variables

View Source
var (
	ErrNotFound  = errors.New("store: not found")
	ErrDuplicate = errors.New("store: duplicate")
)

Repository errors.

View Source
var ErrNoSealer = errors.New("store: no sealer configured")

ErrNoSealer means a repository needed to seal, open or MAC a secret but the store has no Sealer.

View Source
var ErrSchemaTooNew = errors.New("store: database schema is newer than this remora")

ErrSchemaTooNew means the database was written by a newer remora. Open never migrates down.

Functions

func GenerateKeyValue

func GenerateKeyValue() string

GenerateKeyValue returns a new client key value: "sk-" + base64url(32 random bytes), no padding.

func KeyPrefix

func KeyPrefix(value string) string

KeyPrefix returns the part of a key value kept to recognise it: its first 8 characters, but never more than half of it, so a short caller-chosen value is not given away.

func LoadMasterKey

func LoadMasterKey(dataDir, env string) ([]byte, error)

LoadMasterKey returns the master key. env (the value of REMORA_MASTER_KEY, base64 of 32 bytes) wins when set; otherwise the key is read from dataDir/master.key, which is created (mode 0600) with a random key if absent.

func WithTx added in v0.2.0

func WithTx(ctx context.Context, tx *Tx) context.Context

WithTx returns ctx carrying tx, for callers that join an open write transaction instead of opening their own.

Types

type APIToken

type APIToken struct {
	ID, Name, Prefix string
	Scope            string
	Hash             []byte
	CreatedAt        time.Time
	LastUsedAt       *time.Time
	ExpiresAt        *time.Time
}

APIToken is an API token for /api/*. Hash is the sha256 of its value; the value itself is never stored.

type Account

type Account struct {
	ID                          int64
	Provider, Label, Credential string
	Enabled                     bool
	Priority                    int // higher is tried first under the priority and fill-first strategies
	CreatedAt                   time.Time
}

Account is a subscription account: one OAuth engine credential remora adopted. Provider is the user-facing provider name ("grok", not the engine's "xai"); Credential is the engine's credential file name.

type AccountQuota added in v0.3.0

type AccountQuota struct {
	AccountID    int64
	Plan         string
	Windows      []QuotaWindow
	LimitReached bool
	Source       string // "poll" | "passive"
	FetchedAt    time.Time
	CheckedAt    time.Time
	Error        string
}

AccountQuota is an account's last quota snapshot. FetchedAt is when the windows were observed (zero = never); CheckedAt is the last poll attempt, successful or not.

type AuditEntry added in v0.7.0

type AuditEntry struct {
	ID                 int64
	At                 time.Time
	Principal          string
	TokenID, TokenName string
	OperationID        string
	Diff               map[string]any
}

AuditEntry records an authenticated management action. Diff contains only audit-safe fields.

type ClientKey

type ClientKey struct {
	ID, Name      string
	Prefix        string
	Allow         []string
	Enabled       bool
	VKID, VKValue string
	CreatedAt     time.Time
}

ClientKey is a remora key a client presents on /v1. Its value is never stored, only its MAC and a short Prefix to recognise it by. VKID and VKValue are the front door's virtual key for it (VKValue sealed at rest). Prefix and CreatedAt are set by the store; PutClientKey ignores them.

type PendingWrite added in v0.7.0

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

PendingWrite holds a committed change whose publication waits for engine acceptance or compensation. The caller must resolve it once, through either Commit or Undo.

func (*PendingWrite) Abandon added in v0.7.0

func (p *PendingWrite) Abandon(ctx context.Context)

Abandon ends a change whose compensation failed and will not be retried: the committed rows, unaccepted by the engine, are published so later writes and changes are not held back; the next full sync pushes them.

func (*PendingWrite) Commit added in v0.7.0

func (p *PendingWrite) Commit(ctx context.Context, fn func(tx *Tx) error) error

Commit writes the engine's output and publishes the change. On error the change stays pending.

func (*PendingWrite) Undo added in v0.7.0

func (p *PendingWrite) Undo(ctx context.Context) error

Undo compensates the write and publishes the restored state. On error the change stays pending.

type Provider

type Provider struct {
	Name                string
	Kind                ProviderKind
	Type                string // builtin only: the front door's provider, e.g. "openrouter"
	BaseURL             string
	AllowPrivateNetwork bool
}

Provider is an upstream remora routes to.

type ProviderKey

type ProviderKey struct {
	ID, Provider, Name, Secret string
	Enabled                    bool
}

ProviderKey is one credential of a provider. Secret is in clear in memory only; at rest it is sealed.

type ProviderKind

type ProviderKind string

ProviderKind is how remora drives a provider: "builtin" (a provider the front door ships, named by Type), "openai-compatible", "typesafe-compatible" (decision endpoints) or "soniox".

const (
	KindBuiltin            ProviderKind = "builtin"
	KindOpenAICompatible   ProviderKind = "openai-compatible"
	KindTypeSafeCompatible ProviderKind = "typesafe-compatible"
	KindSoniox             ProviderKind = "soniox"
)

Provider kinds.

type QuotaWindow added in v0.3.0

type QuotaWindow struct {
	Scope     string     `json:"scope"`
	Window    string     `json:"window"`
	Remaining *float64   `json:"remaining"`
	ResetsAt  *time.Time `json:"resets_at"`
}

QuotaWindow is one quota window of an account. Scope is a model family or model ("gemini", "claude-gpt", "opus", "" = the whole account); Window is "5h", "weekly" or the length in minutes. Remaining is 0..1, nil = unknown; ResetsAt nil = unknown or no reset.

type Sealer

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

Sealer encrypts secrets at rest with AES-256-GCM and computes lookup MACs with HMAC-SHA256. Both keys are derived from the master key with HKDF-SHA256, so the master key itself is never used directly.

func NewSealer

func NewSealer(master []byte) (*Sealer, error)

NewSealer derives the sealing and MAC keys from a 32-byte master key.

func (*Sealer) MAC

func (s *Sealer) MAC(data []byte) []byte

MAC returns HMAC-SHA256(macKey, data), used to look up client keys without storing them.

func (*Sealer) Open

func (s *Sealer) Open(sealed []byte, aad string) (string, error)

Open decrypts a value made by Seal with the same aad.

func (*Sealer) Seal

func (s *Sealer) Seal(plaintext, aad string) ([]byte, error)

Seal encrypts plaintext bound to aad (the row it belongs to, e.g. "provider_key:<id>"). The random nonce is prepended to the ciphertext.

type Store

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

Store is the SQLite store.

func Open

func Open(ctx context.Context, path string) (*Store, error)

Open opens (or creates) the database at path and applies the embedded migrations that are missing.

func (*Store) APITokenByHash

func (s *Store) APITokenByHash(ctx context.Context, hash []byte) (APIToken, error)

APITokenByHash finds the API token with this hash. ErrNotFound when there is none.

func (*Store) Account

func (s *Store) Account(ctx context.Context, id int64) (Account, error)

Account returns one account. ErrNotFound when it does not exist.

func (*Store) AccountQuotas added in v0.3.0

func (s *Store) AccountQuotas(ctx context.Context) (map[int64]AccountQuota, error)

AccountQuotas returns every stored snapshot by account id.

func (*Store) AccountStrategies added in v0.3.0

func (s *Store) AccountStrategies(ctx context.Context) (map[string]alias.Strategy, error)

AccountStrategies returns the stored strategy per subscription provider; a provider without one is not listed.

func (*Store) Accounts

func (s *Store) Accounts(ctx context.Context) ([]Account, error)

Accounts lists the accounts ordered by provider, then id.

func (*Store) Alias added in v0.2.1

func (s *Store) Alias(ctx context.Context, name string) (alias.Alias, bool, error)

Alias returns the alias named name, without copying the whole set.

func (*Store) AliasRuleIDs

func (s *Store) AliasRuleIDs(ctx context.Context) (map[string]string, error)

AliasRuleIDs maps alias name to the front door's routing rule id, for aliases that have one.

func (*Store) Aliases

func (s *Store) Aliases(ctx context.Context) (map[string]alias.Alias, error)

Aliases returns every alias by name, members in order.

func (*Store) ClientKeyByValue

func (s *Store) ClientKeyByValue(ctx context.Context, value string) (ClientKey, error)

ClientKeyByValue finds the client key whose value is value, enabled or not. ErrNotFound when none matches.

func (*Store) ClientKeyVKIDs

func (s *Store) ClientKeyVKIDs(ctx context.Context) (map[string]string, error)

ClientKeyVKIDs maps client key id to its virtual key id, for keys that have one.

func (*Store) Close

func (s *Store) Close() error

Close closes the database.

func (*Store) CreateAPIToken

func (s *Store) CreateAPIToken(ctx context.Context, t APIToken) error

CreateAPIToken stores t, defaulting an empty scope to admin. ErrDuplicate when its id or hash exists.

func (*Store) CreateAccount

func (s *Store) CreateAccount(ctx context.Context, a Account) (Account, error)

CreateAccount stores a new account and returns it with ID and CreatedAt set (a.ID and a.CreatedAt are ignored). ErrDuplicate when another account already has a.Credential.

func (*Store) CreateSession

func (s *Store) CreateSession(ctx context.Context, hash []byte, expires time.Time) error

CreateSession stores a session by its hash.

func (*Store) DB

func (s *Store) DB() *sql.DB

DB returns the underlying database, for tests and tools.

func (*Store) DeleteAPIToken

func (s *Store) DeleteAPIToken(ctx context.Context, id string) error

DeleteAPIToken deletes an API token. ErrNotFound when it does not exist.

func (*Store) DeleteAccount

func (s *Store) DeleteAccount(ctx context.Context, id int64) error

DeleteAccount deletes an account. ErrNotFound when it does not exist.

func (*Store) DeleteExpiredSessions added in v0.7.0

func (s *Store) DeleteExpiredSessions(ctx context.Context, now time.Time) error

DeleteExpiredSessions deletes sessions that have expired at or before now.

func (*Store) DeleteSession

func (s *Store) DeleteSession(ctx context.Context, hash []byte) error

DeleteSession deletes the session with this hash; deleting an absent session is not an error.

func (*Store) DeleteSessionsExcept

func (s *Store) DeleteSessionsExcept(ctx context.Context, keep []byte) error

DeleteSessionsExcept deletes every session but the one with hash keep (nil keeps none).

func (*Store) EngineValue

func (s *Store) EngineValue(ctx context.Context, engine, key string) (value string, ok bool, err error)

EngineValue returns the value stored for engine under key, sealing legacy plaintext on first read. ok is false when the value is absent.

func (*Store) ListAPITokens

func (s *Store) ListAPITokens(ctx context.Context) ([]APIToken, error)

ListAPITokens lists the API tokens, oldest first.

func (*Store) ListAudit added in v0.7.0

func (s *Store) ListAudit(ctx context.Context, operation string, limit, offset int) ([]AuditEntry, int, error)

ListAudit returns a newest-first page and the exact total for the operation filter (empty matches all).

func (*Store) LoadCooling added in v0.7.0

func (s *Store) LoadCooling(ctx context.Context, now time.Time) ([]cooling.Cooling, error)

LoadCooling deletes expired plain cooldowns but keeps breakers until a probe succeeds.

func (*Store) ProviderKeysByKind

func (s *Store) ProviderKeysByKind(ctx context.Context, kind ProviderKind) ([]string, error)

ProviderKeysByKind returns the plaintext secrets of the enabled keys of every provider of that kind, never nil.

func (*Store) PutAccountQuota added in v0.3.0

func (s *Store) PutAccountQuota(ctx context.Context, q AccountQuota) error

PutAccountQuota stores q as its account's snapshot, replacing the previous one. ErrNotFound when the account does not exist.

func (*Store) Read added in v0.7.0

func (s *Store) Read(ctx context.Context, fn func(tx *Tx) error) error

Read runs fn against one SQLite snapshot, without acquiring the write lock.

func (*Store) RecordAudit added in v0.7.0

func (s *Store) RecordAudit(ctx context.Context, e AuditEntry) error

RecordAudit appends an entry without changing the configuration generation.

func (*Store) RedactSecrets added in v0.7.0

func (s *Store) RedactSecrets(text string) string

RedactSecrets masks recoverable stored credentials in an unencoded engine log line. With no snapshot, omit the line rather than risk logging a credential.

func (*Store) Refresh added in v0.2.1

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

Refresh rebuilds the snapshot from the committed database, unless a reconcile write is still pending. On failure it drops the snapshot and returns the error; reads fall back to SQL. Without a sealer there is nothing to rebuild.

func (*Store) SaveCooling added in v0.7.0

func (s *Store) SaveCooling(ctx context.Context, rows []cooling.Cooling) error

SaveCooling atomically replaces the cooldowns without rebuilding the key and alias snapshot.

func (*Store) SessionExpiry

func (s *Store) SessionExpiry(ctx context.Context, hash []byte) (time.Time, error)

SessionExpiry returns when the session with this hash expires. ErrNotFound when there is none.

func (*Store) SetAccountEnabled

func (s *Store) SetAccountEnabled(ctx context.Context, id int64, enabled bool) error

SetAccountEnabled enables or disables an account. ErrNotFound when it does not exist.

func (*Store) SetAccountPriority added in v0.3.0

func (s *Store) SetAccountPriority(ctx context.Context, id int64, priority int) error

SetAccountPriority sets an account's priority. ErrNotFound when it does not exist.

func (*Store) SetAccountStrategy added in v0.3.0

func (s *Store) SetAccountStrategy(ctx context.Context, provider string, st alias.Strategy) error

SetAccountStrategy stores a subscription provider's strategy, replacing any earlier one.

func (*Store) SetEngineValue

func (s *Store) SetEngineValue(ctx context.Context, engine, key, value string) error

SetEngineValue seals and stores value for engine under key, replacing any previous value.

func (*Store) SetSealer

func (s *Store) SetSealer(sl *Sealer)

SetSealer sets the Sealer the repositories use for secrets.

func (*Store) SetSetting

func (s *Store) SetSetting(ctx context.Context, key, value string) error

SetSetting stores value under key, replacing any previous value.

func (*Store) Setting

func (s *Store) Setting(ctx context.Context, key string) (value string, ok bool, err error)

Setting returns the value stored under key. ok is false when the key is absent.

func (*Store) TouchAPIToken

func (s *Store) TouchAPIToken(ctx context.Context, id string, at time.Time) error

TouchAPIToken records that the token was used at at. ErrNotFound when it does not exist.

func (*Store) TouchAPITokens added in v0.7.0

func (s *Store) TouchAPITokens(ctx context.Context, batch map[string]time.Time) error

TouchAPITokens records last use in a single transaction. Deleted tokens are ignored.

func (*Store) Write

func (s *Store) Write(ctx context.Context, fn func(tx *Tx) error) error

Write runs fn in one BEGIN IMMEDIATE transaction and commits iff fn returns nil, then refreshes the snapshot unless a reconcile write is pending. Concurrent writers serialise on the database lock; Write waits up to 30 s.

func (*Store) WriteWithUndo added in v0.7.0

func (s *Store) WriteWithUndo(ctx context.Context, fn func(tx *Tx) error) (*PendingWrite, error)

WriteWithUndo commits fn without publishing it. The caller must resolve the returned PendingWrite.

type Tx

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

Tx is a store transaction. Store.Read supplies a read-only view.

func TxFrom added in v0.2.0

func TxFrom(ctx context.Context) (*Tx, bool)

TxFrom returns the transaction ctx carries (see WithTx).

func (*Tx) AliasRuleIDs

func (tx *Tx) AliasRuleIDs(ctx context.Context) (map[string]string, error)

AliasRuleIDs maps alias name to the front door's routing rule id, as this transaction sees it (its own uncommitted writes included).

func (*Tx) Aliases

func (tx *Tx) Aliases(ctx context.Context) (map[string]alias.Alias, error)

Aliases returns every alias by name, members in order.

func (*Tx) ClientKeys

func (tx *Tx) ClientKeys(ctx context.Context) ([]ClientKey, error)

ClientKeys lists the client keys by name, virtual key values opened.

func (*Tx) DeleteAlias

func (tx *Tx) DeleteAlias(ctx context.Context, name string) error

DeleteAlias deletes an alias and its members. ErrNotFound when it does not exist.

func (*Tx) DeleteClientKey

func (tx *Tx) DeleteClientKey(ctx context.Context, id string) error

DeleteClientKey deletes a client key. ErrNotFound when it does not exist.

func (*Tx) DeleteEngineMAC

func (tx *Tx) DeleteEngineMAC(ctx context.Context, object string) error

DeleteEngineMAC forgets an engine object. Deleting an unknown object is not an error.

func (*Tx) DeleteProvider

func (tx *Tx) DeleteProvider(ctx context.Context, name string) error

DeleteProvider deletes the provider and its keys. ErrNotFound when it does not exist.

func (*Tx) DeleteProviderKey

func (tx *Tx) DeleteProviderKey(ctx context.Context, id string) error

DeleteProviderKey deletes a provider key. ErrNotFound when it does not exist.

func (*Tx) EngineMACs

func (tx *Tx) EngineMACs(ctx context.Context) (map[string]string, error)

EngineMACs returns the MAC of every engine object as last pushed, keyed by object ("provider:<name>", "key:<id>", "vk:<client_key_id>", "rule:<alias>").

func (*Tx) Generation added in v0.7.0

func (tx *Tx) Generation(ctx context.Context) (int64, error)

Generation returns the reconcile-input generation in this transaction's snapshot.

func (*Tx) MAC

func (tx *Tx) MAC(data []byte) ([]byte, error)

MAC returns HMAC-SHA256(macKey, data) with the store's Sealer, for the engine_sync records of objects that carry a secret. ErrNoSealer when the store has none.

func (*Tx) ProviderKeys

func (tx *Tx) ProviderKeys(ctx context.Context) ([]ProviderKey, error)

ProviderKeys lists every provider key, secrets opened, by provider and name.

func (*Tx) Providers

func (tx *Tx) Providers(ctx context.Context) ([]Provider, error)

Providers lists the providers by name.

func (*Tx) PutAlias

func (tx *Tx) PutAlias(ctx context.Context, a alias.Alias) error

PutAlias creates or replaces the alias a.Name and replaces its members in order. The routing rule id is kept.

func (*Tx) PutClientKey

func (tx *Tx) PutClientKey(ctx context.Context, k ClientKey, value string) (ClientKey, error)

PutClientKey creates or updates the client key k.ID (an empty ID creates a key with a new UUID v4) and returns it as stored. value is caller-chosen and only its MAC and prefix are stored; value "" on an existing key keeps the stored MAC, and a new key needs a value. The virtual key fields are not changed here (see SetClientKeyVK).

func (*Tx) PutProvider

func (tx *Tx) PutProvider(ctx context.Context, p Provider) error

PutProvider creates or replaces the provider p.Name. Its keys are kept.

func (*Tx) PutProviderKey

func (tx *Tx) PutProviderKey(ctx context.Context, k ProviderKey) error

PutProviderKey creates or replaces the key k.ID; an empty ID creates a key with a new UUID v4.

func (*Tx) SetAccountStrategy added in v0.3.0

func (tx *Tx) SetAccountStrategy(ctx context.Context, provider string, st alias.Strategy) error

SetAccountStrategy stores a subscription provider's strategy on the transaction.

func (*Tx) SetAliasRuleID

func (tx *Tx) SetAliasRuleID(ctx context.Context, name, ruleID string) error

SetAliasRuleID records the front door's routing rule id for an alias. ErrNotFound when the alias does not exist.

func (*Tx) SetClientKeyVK

func (tx *Tx) SetClientKeyVK(ctx context.Context, id, vkID, vkValue string) error

SetClientKeyVK records the front door's virtual key for a client key; vkValue is sealed. ErrNotFound when the client key does not exist.

func (*Tx) SetEngineMAC

func (tx *Tx) SetEngineMAC(ctx context.Context, object, mac string) error

SetEngineMAC records the MAC of an engine object as pushed.

Jump to

Keyboard shortcuts

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