Documentation
¶
Overview ¶
Package store is remora's SQLite store: schema, migrations and repositories.
Index ¶
- Constants
- Variables
- func GenerateKeyValue() string
- func KeyPrefix(value string) string
- func LoadMasterKey(dataDir, env string) ([]byte, error)
- func WithTx(ctx context.Context, tx *Tx) context.Context
- type APIToken
- type Account
- type AccountQuota
- type AuditEntry
- type ClientKey
- type PendingWrite
- type Provider
- type ProviderKey
- type ProviderKind
- type QuotaWindow
- type Sealer
- type Store
- func (s *Store) APITokenByHash(ctx context.Context, hash []byte) (APIToken, error)
- func (s *Store) Account(ctx context.Context, id int64) (Account, error)
- func (s *Store) AccountQuotas(ctx context.Context) (map[int64]AccountQuota, error)
- func (s *Store) AccountStrategies(ctx context.Context) (map[string]alias.Strategy, error)
- func (s *Store) Accounts(ctx context.Context) ([]Account, error)
- func (s *Store) Alias(ctx context.Context, name string) (alias.Alias, bool, error)
- func (s *Store) AliasRuleIDs(ctx context.Context) (map[string]string, error)
- func (s *Store) Aliases(ctx context.Context) (map[string]alias.Alias, error)
- func (s *Store) ClientKeyByValue(ctx context.Context, value string) (ClientKey, error)
- func (s *Store) ClientKeyVKIDs(ctx context.Context) (map[string]string, error)
- func (s *Store) Close() error
- func (s *Store) CreateAPIToken(ctx context.Context, t APIToken) error
- func (s *Store) CreateAccount(ctx context.Context, a Account) (Account, error)
- func (s *Store) CreateSession(ctx context.Context, hash []byte, expires time.Time) error
- func (s *Store) DB() *sql.DB
- func (s *Store) DeleteAPIToken(ctx context.Context, id string) error
- func (s *Store) DeleteAccount(ctx context.Context, id int64) error
- func (s *Store) DeleteExpiredSessions(ctx context.Context, now time.Time) error
- func (s *Store) DeleteSession(ctx context.Context, hash []byte) error
- func (s *Store) DeleteSessionsExcept(ctx context.Context, keep []byte) error
- func (s *Store) EngineValue(ctx context.Context, engine, key string) (value string, ok bool, err error)
- func (s *Store) ListAPITokens(ctx context.Context) ([]APIToken, error)
- func (s *Store) ListAudit(ctx context.Context, operation string, limit, offset int) ([]AuditEntry, int, error)
- func (s *Store) LoadCooling(ctx context.Context, now time.Time) ([]cooling.Cooling, error)
- func (s *Store) ProviderKeysByKind(ctx context.Context, kind ProviderKind) ([]string, error)
- func (s *Store) PutAccountQuota(ctx context.Context, q AccountQuota) error
- func (s *Store) Read(ctx context.Context, fn func(tx *Tx) error) error
- func (s *Store) RecordAudit(ctx context.Context, e AuditEntry) error
- func (s *Store) RedactSecrets(text string) string
- func (s *Store) Refresh(ctx context.Context) error
- func (s *Store) SaveCooling(ctx context.Context, rows []cooling.Cooling) error
- func (s *Store) SessionExpiry(ctx context.Context, hash []byte) (time.Time, error)
- func (s *Store) SetAccountEnabled(ctx context.Context, id int64, enabled bool) error
- func (s *Store) SetAccountPriority(ctx context.Context, id int64, priority int) error
- func (s *Store) SetAccountStrategy(ctx context.Context, provider string, st alias.Strategy) error
- func (s *Store) SetEngineValue(ctx context.Context, engine, key, value string) error
- func (s *Store) SetSealer(sl *Sealer)
- func (s *Store) SetSetting(ctx context.Context, key, value string) error
- func (s *Store) Setting(ctx context.Context, key string) (value string, ok bool, err error)
- func (s *Store) TouchAPIToken(ctx context.Context, id string, at time.Time) error
- func (s *Store) TouchAPITokens(ctx context.Context, batch map[string]time.Time) error
- func (s *Store) Write(ctx context.Context, fn func(tx *Tx) error) error
- func (s *Store) WriteWithUndo(ctx context.Context, fn func(tx *Tx) error) (*PendingWrite, error)
- type Tx
- func (tx *Tx) AliasRuleIDs(ctx context.Context) (map[string]string, error)
- func (tx *Tx) Aliases(ctx context.Context) (map[string]alias.Alias, error)
- func (tx *Tx) ClientKeys(ctx context.Context) ([]ClientKey, error)
- func (tx *Tx) DeleteAlias(ctx context.Context, name string) error
- func (tx *Tx) DeleteClientKey(ctx context.Context, id string) error
- func (tx *Tx) DeleteEngineMAC(ctx context.Context, object string) error
- func (tx *Tx) DeleteProvider(ctx context.Context, name string) error
- func (tx *Tx) DeleteProviderKey(ctx context.Context, id string) error
- func (tx *Tx) EngineMACs(ctx context.Context) (map[string]string, error)
- func (tx *Tx) Generation(ctx context.Context) (int64, error)
- func (tx *Tx) MAC(data []byte) ([]byte, error)
- func (tx *Tx) ProviderKeys(ctx context.Context) ([]ProviderKey, error)
- func (tx *Tx) Providers(ctx context.Context) ([]Provider, error)
- func (tx *Tx) PutAlias(ctx context.Context, a alias.Alias) error
- func (tx *Tx) PutClientKey(ctx context.Context, k ClientKey, value string) (ClientKey, error)
- func (tx *Tx) PutProvider(ctx context.Context, p Provider) error
- func (tx *Tx) PutProviderKey(ctx context.Context, k ProviderKey) error
- func (tx *Tx) SetAccountStrategy(ctx context.Context, provider string, st alias.Strategy) error
- func (tx *Tx) SetAliasRuleID(ctx context.Context, name, ruleID string) error
- func (tx *Tx) SetClientKeyVK(ctx context.Context, id, vkID, vkValue string) error
- func (tx *Tx) SetEngineMAC(ctx context.Context, object, mac string) error
Constants ¶
const ScopeAdmin = "admin"
ScopeAdmin is the default scope for API tokens and the scope of admin sessions.
Variables ¶
var ( ErrNotFound = errors.New("store: not found") ErrDuplicate = errors.New("store: duplicate") )
Repository errors.
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.
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 ¶
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 ¶
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.
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.
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 ¶
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 (*Sealer) MAC ¶
MAC returns HMAC-SHA256(macKey, data), used to look up client keys without storing them.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the SQLite store.
func Open ¶
Open opens (or creates) the database at path and applies the embedded migrations that are missing.
func (*Store) APITokenByHash ¶
APITokenByHash finds the API token with this hash. ErrNotFound when there is none.
func (*Store) AccountQuotas ¶ added in v0.3.0
AccountQuotas returns every stored snapshot by account id.
func (*Store) AccountStrategies ¶ added in v0.3.0
AccountStrategies returns the stored strategy per subscription provider; a provider without one is not listed.
func (*Store) Alias ¶ added in v0.2.1
Alias returns the alias named name, without copying the whole set.
func (*Store) AliasRuleIDs ¶
AliasRuleIDs maps alias name to the front door's routing rule id, for aliases that have one.
func (*Store) ClientKeyByValue ¶
ClientKeyByValue finds the client key whose value is value, enabled or not. ErrNotFound when none matches.
func (*Store) ClientKeyVKIDs ¶
ClientKeyVKIDs maps client key id to its virtual key id, for keys that have one.
func (*Store) CreateAPIToken ¶
CreateAPIToken stores t, defaulting an empty scope to admin. ErrDuplicate when its id or hash exists.
func (*Store) CreateAccount ¶
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 ¶
CreateSession stores a session by its hash.
func (*Store) DeleteAPIToken ¶
DeleteAPIToken deletes an API token. ErrNotFound when it does not exist.
func (*Store) DeleteAccount ¶
DeleteAccount deletes an account. ErrNotFound when it does not exist.
func (*Store) DeleteExpiredSessions ¶ added in v0.7.0
DeleteExpiredSessions deletes sessions that have expired at or before now.
func (*Store) DeleteSession ¶
DeleteSession deletes the session with this hash; deleting an absent session is not an error.
func (*Store) DeleteSessionsExcept ¶
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 ¶
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
LoadCooling deletes expired plain cooldowns but keeps breakers until a probe succeeds.
func (*Store) ProviderKeysByKind ¶
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
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
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
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
SaveCooling atomically replaces the cooldowns without rebuilding the key and alias snapshot.
func (*Store) SessionExpiry ¶
SessionExpiry returns when the session with this hash expires. ErrNotFound when there is none.
func (*Store) SetAccountEnabled ¶
SetAccountEnabled enables or disables an account. ErrNotFound when it does not exist.
func (*Store) SetAccountPriority ¶ added in v0.3.0
SetAccountPriority sets an account's priority. ErrNotFound when it does not exist.
func (*Store) SetAccountStrategy ¶ added in v0.3.0
SetAccountStrategy stores a subscription provider's strategy, replacing any earlier one.
func (*Store) SetEngineValue ¶
SetEngineValue seals and stores value for engine under key, replacing any previous value.
func (*Store) SetSetting ¶
SetSetting stores value under key, replacing any previous value.
func (*Store) Setting ¶
Setting returns the value stored under key. ok is false when the key is absent.
func (*Store) TouchAPIToken ¶
TouchAPIToken records that the token was used at at. ErrNotFound when it does not exist.
func (*Store) TouchAPITokens ¶ added in v0.7.0
TouchAPITokens records last use in a single transaction. Deleted tokens are ignored.
func (*Store) Write ¶
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
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 (*Tx) AliasRuleIDs ¶
AliasRuleIDs maps alias name to the front door's routing rule id, as this transaction sees it (its own uncommitted writes included).
func (*Tx) ClientKeys ¶
ClientKeys lists the client keys by name, virtual key values opened.
func (*Tx) DeleteAlias ¶
DeleteAlias deletes an alias and its members. ErrNotFound when it does not exist.
func (*Tx) DeleteClientKey ¶
DeleteClientKey deletes a client key. ErrNotFound when it does not exist.
func (*Tx) DeleteEngineMAC ¶
DeleteEngineMAC forgets an engine object. Deleting an unknown object is not an error.
func (*Tx) DeleteProvider ¶
DeleteProvider deletes the provider and its keys. ErrNotFound when it does not exist.
func (*Tx) DeleteProviderKey ¶
DeleteProviderKey deletes a provider key. ErrNotFound when it does not exist.
func (*Tx) EngineMACs ¶
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
Generation returns the reconcile-input generation in this transaction's snapshot.
func (*Tx) MAC ¶
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) PutAlias ¶
PutAlias creates or replaces the alias a.Name and replaces its members in order. The routing rule id is kept.
func (*Tx) PutClientKey ¶
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 ¶
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
SetAccountStrategy stores a subscription provider's strategy on the transaction.
func (*Tx) SetAliasRuleID ¶
SetAliasRuleID records the front door's routing rule id for an alias. ErrNotFound when the alias does not exist.
func (*Tx) SetClientKeyVK ¶
SetClientKeyVK records the front door's virtual key for a client key; vkValue is sealed. ErrNotFound when the client key does not exist.