secrets

package
v2.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: AGPL-3.0 Imports: 30 Imported by: 2 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

Index

Constants

View Source
const (
	// DataKeyPrefix starts every value sealed under a data key.
	DataKeyPrefix = "$DK1/"

	// DataKeySaltLength is the size of a database's salt, in bytes.
	DataKeySaltLength = 32
)

Data-key encryption, for values there are many of (App credentials).

EncryptValue derives a fresh key for every value: the operator's TYK_AI_SECRET_KEY through scrypt (PBKDF2 in FIPS mode) with a random per-value salt, about 100 ms each, and decrypting pays the same unless that value's key is in a small cache. That is right for a handful of values (a secret, an LLM's API key) and wrong for tens of thousands: a migration, a list, or a hub validating keys would spend its time deriving keys.

Here the key derivation runs once per process: TYK_AI_SECRET_KEY and a salt that belongs to the database (random, created once, stored in it, not secret) give one 256-bit data key, and each value is sealed under it with AES-256-GCM, a random 96-bit nonce, and the identity of the row it belongs to as additional authenticated data, so a ciphertext copied to another row does not open. Sealing or opening a value then costs microseconds, at any number of values.

The stored form is versioned and distinct from EncryptValue's "$ENC/":

"$DK1/s:"        + base64url(nonce || ciphertext)   data key derived with scrypt
"$DK1/p<iter>:"  + base64url(nonce || ciphertext)   data key derived with PBKDF2-HMAC-SHA256

The tag after the prefix names the key derivation, as v2 and v3 do for "$ENC/" values: FIPS-mode processes write the PBKDF2 form, every build reads both. Only approved primitives are used in FIPS mode.

View Source
const (
	// LookupHashKeyedPrefix starts a hash keyed with the encryption key;
	// what follows is a pkg/credhash hash.
	LookupHashKeyedPrefix = "k:"
	// LookupHashPlainPrefix starts an unkeyed SHA-256, in hexadecimal.
	LookupHashPlainPrefix = "u:"
	// LookupHashMaxLen bounds every form (a column size).
	LookupHashMaxLen = 80
)

A credential that is encrypted at rest cannot be found by its value: EncryptValue's output is different every time. It is found by a hash of the value, stored next to it.

LookupHash is that hash. With an encryption key (TYK_AI_SECRET_KEY) it is keyed: pkg/credhash's construction (HKDF-SHA-256, then HMAC-SHA-256) under the encryption key, so a copy of the database yields nothing that can be tested against a guessed credential without the key. Without a key, or with one shorter than the 14 bytes that construction needs, it is a plain SHA-256, as the value itself is then stored in plaintext beside it.

The two forms carry different prefixes, so a hash says which it is, and rows hashed before a key was set are found and rehashed (LookupHashIsCurrent). The hash depends on the key: with another key nothing is found, as nothing decrypts.

View Source
const (
	SecretRefPrefix = "$SECRET/"
	EnvRefPrefix    = "$ENV/"
)

Reference prefixes for values that name a secret or an environment variable instead of holding the value.

View Source
const EnvRefAllowlistVar = "AI_STUDIO_ENV_REF_ALLOWLIST"

EnvRefAllowlistVar is the one operator setting that lists, comma-separated, the environment variables a $ENV/NAME reference may resolve. It is empty by default, so no $ENV/ reference resolves until an operator lists the name. The process environment holds AI Studio's own secrets (encryption key, database URL, license), and whoever writes a reference usually chooses where its value is sent.

View Source
const RefusedCredential = "refused-credential-reference"

RefusedCredential is what an edge gets for a credential (an API key or token) whose reference the hub refused or could not resolve: a value that is neither empty nor a reference. Vendor clients fall back to their own environment when the key is empty (an OpenAI client reads OPENAI_API_KEY, AWS clients their default credential chain), and a released edge resolves the bare "$ENV/" ForEdge sends to empty; this value is sent instead, as a key, and the provider refuses it.

Variables

View Source
var ErrDataKeyUnavailable = errors.New("no data key: TYK_AI_SECRET_KEY or the database's salt is missing")

ErrDataKeyUnavailable: there is no encryption key, or no salt, to derive the data key from.

View Source
var ErrSecretNameAmbiguous = errors.New("secret name is held in more than one Workspace")

ErrSecretNameAmbiguous: live secrets in more than one Workspace share the name (grandfathered from before names were unique), so a reference to it resolves to none of them.

View Source
var ErrUnresolvedCredential = errors.New("credential is an unresolved reference (a $SECRET/ that cannot be found or decrypted, or an $ENV/ name not listed in " + EnvRefAllowlistVar + ")")

ErrUnresolvedCredential is CheckCredential's refusal. It names neither the reference nor the value.

Functions

func CheckCredential added in v2.3.0

func CheckCredential(v string) error

CheckCredential is called with a resolved credential (an API key or token) just before it is sent. It refuses one that did not resolve: still a $SECRET/ or $ENV/ reference, still encrypted ($ENC/), or the RefusedCredential an edge was sent for one. Such a value is never sent: it would hand the destination the reference text. Empty (no credential) is allowed.

func CreateSecret

func CreateSecret(db *gorm.DB, settings *Secret) error

CreateSecret creates a new Secret record in the database.

func CredentialRefForEdge added in v2.3.0

func CredentialRefForEdge(ref string) string

CredentialRefForEdge resolves a credential field for a snapshot sent to edges: a reference the policy refuses, that cannot be resolved, or that resolves to an empty value goes out as RefusedCredential. An empty credential is what a client fills from its own environment, and a secret stored empty is never what the writer of the reference meant. A field with no value at all (an Ollama LLM without a key) stays empty, and a literal value goes out as it is.

func DataKeyCurrentPrefix added in v2.3.0

func DataKeyCurrentPrefix() string

DataKeyCurrentPrefix is what every value this process seals starts with. A stored value that does not start with it is in an older or another form and is due to be sealed again.

func DecryptValue

func DecryptValue(value string) string

DecryptValue decrypts a value that was encrypted with EncryptValue. Returns the decrypted plaintext, or the original value if not encrypted.

func DeleteSecretByID

func DeleteSecretByID(db *gorm.DB, id uint) error

DeleteSecretByID deletes a Secret record from the database by ID.

func DisableEnvRefs added in v2.3.0

func DisableEnvRefs()

DisableEnvRefs makes ResolveRef refuse every $ENV/ reference in this process. Edge gateways call it at startup.

func EncryptValue

func EncryptValue(plaintext string) string

EncryptValue encrypts a plaintext string using the application's AES key. Returns the encrypted value or the original if encryption fails or is not configured.

func EncryptionKeyConfigured

func EncryptionKeyConfigured() bool

EncryptionKeyConfigured reports whether a secrets encryption key is set, through SetEncryptionKey or the environment.

func EnvRefAllowed added in v2.3.0

func EnvRefAllowed(name string) bool

EnvRefAllowed reports whether $ENV/name may be resolved: name is listed in AI_STUDIO_ENV_REF_ALLOWLIST (and is not that setting itself), and this process resolves $ENV/ at all. An empty name, or one containing "/" or whitespace, is never allowed, so a bare "$ENV/" (see ForEdge) stays unresolved.

func FilterSensitiveFields

func FilterSensitiveFields(obj interface{}) interface{}

func FilterSesitiveFieldsArr

func FilterSesitiveFieldsArr(in interface{}) interface{}

func ForEdge added in v2.3.0

func ForEdge(resolved string) string

ForEdge renders a resolved value for a configuration snapshot sent to edges. A value that is still a reference is sent as a bare "$ENV/": edges released before 2.3 resolve $ENV/ against their own environment, so a refused name sent as is would hand them their own variable (an encryption key, say) to send on. A bare "$ENV/" resolves to empty there, and current edges treat it as an unresolved reference.

func ForEdgeCredential added in v2.3.0

func ForEdgeCredential(resolved string) string

ForEdgeCredential is ForEdge for a credential field: a value that is still a reference, or still encrypted at rest ($ENC/, a value the hub could not decrypt), goes out as RefusedCredential. Use ForEdge for fields where an empty value has no fallback (endpoints, connection strings).

func ForceFIPSModeForTest added in v2.3.0

func ForceFIPSModeForTest(tb testing.TB)

ForceFIPSModeForTest makes this package write the FIPS formats (v3) until the test ends, so other packages' standard test runs can cover their FIPS paths. Not safe for parallel tests.

func GetOrCreateDefaultSecrets

func GetOrCreateDefaultSecrets(db *gorm.DB, skip ...func(name string) (bool, error)) error

GetOrCreateDefaultSecrets ensures default secrets exist in the database. This function creates OPENAI_KEY and ANTHROPIC_KEY secrets with empty values if they don't already exist, allowing users to fill in their API keys later. A name skip reports true for is left uncreated (the caller logs why): recreating a default name objects in another Workspace reference would let them resolve the Default's secret (midsommar-clean-oztk.47).

func GetSecretReference

func GetSecretReference(name string) string

GetSecretReference returns a secret reference string for a given name

func GetValue

func GetValue(reference string, preserveRef bool) string

GetValue resolves a $SECRET/NAME or $ENV/NAME reference; any other value is returned as is. With preserveRef, references are returned unchanged (for API responses, and for edits that save the value back). $ENV/NAME resolves only when EnvRefAllowed(NAME): the operator lists it in AI_STUDIO_ENV_REF_ALLOWLIST. Otherwise the reference is returned unchanged, so the variable's value never leaves the process.

func IsDataKeyValue added in v2.3.0

func IsDataKeyValue(stored string) bool

IsDataKeyValue reports whether stored is a value sealed under a data key.

func IsReference added in v2.3.0

func IsReference(v string) bool

IsReference reports whether v is (still) a $SECRET/ or $ENV/ reference, e.g. after resolution: an unknown secret or a refused $ENV/ name.

func IsSecretReference

func IsSecretReference(value string) bool

IsSecretReference checks if a string is in the format $SECRET/NAME

func KeyDerivations added in v2.3.0

func KeyDerivations() uint64

KeyDerivations returns how many key derivations (scrypt or PBKDF2, each about 100 ms at production cost) this process has computed.

func LookupHash added in v2.3.0

func LookupHash(value string) string

LookupHash returns the hash value is found by.

func LookupHashPrefix added in v2.3.0

func LookupHashPrefix() string

LookupHashPrefix is the prefix of the hashes this process writes.

func NewReferences added in v2.3.0

func NewReferences(old, updated map[string]string) []string

NewReferences lists the keys of updated whose value is a $SECRET/ or $ENV/ reference that old does not already hold under the same key (new, changed or moved). Writing those needs the right to read secrets, since the value is resolved and sent on for the writer.

func OpenWithDataKey added in v2.3.0

func OpenWithDataKey(salt []byte, stored, aad string) (string, error)

OpenWithDataKey decrypts a value SealWithDataKey wrote for the same salt and aad. It fails for another key, another salt, another row's aad, or a value that was altered.

func ReencryptEncJSON added in v2.3.0

func ReencryptEncJSON(doc string) (string, int)

ReencryptEncJSON is ReencryptEncValue for a JSON object column (LLM credential metadata, a submission's payload): it re-encrypts the top-level string values that are wholly a legacy or v2 EncryptValue output, which is where those writers put them, and re-marshals the object. Numbers keep their text. It returns the new document and how many values changed; anything that is not a JSON object comes back unchanged.

func ReencryptEncValue added in v2.3.0

func ReencryptEncValue(value string) (string, bool)

ReencryptEncValue re-encrypts, in the format this process writes, a column value that is wholly a legacy or v2 EncryptValue output. Anything else (a v3 value, plain text, text containing a token, a value that does not decrypt with the configured key) comes back unchanged, with ok false. Legacy AES-CFB values are read outside FIPS 140-only enforcement (decryptForMigration): this is a migration.

func ReencryptLegacySecrets

func ReencryptLegacySecrets(db *gorm.DB) (int, error)

ReencryptLegacySecrets rewrites stored Secret rows to the format this process writes. A standard build moves legacy AES-CFB rows to v2 (scrypt+AES-GCM) and leaves v2 and v3 rows alone; a FIPS-mode process moves legacy and v2 rows to v3 (PBKDF2+AES-GCM). Rows that are empty, already current, or fail to decrypt (e.g. written under a different key) are left untouched. Rows are processed in batches to bound memory usage, with each batch's updates applied in a single transaction. Returns the number of migrated rows.

func ResolveRef added in v2.3.0

func ResolveRef(v string) string

ResolveRef resolves v. It is GetValue(v, false), which applies the policy itself: an $ENV/ reference EnvRefAllowed refuses is returned unchanged (see IsReference), so the value never leaves the process.

func SealWithDataKey added in v2.3.0

func SealWithDataKey(salt []byte, plaintext, aad string) (string, error)

SealWithDataKey encrypts plaintext under the data key of salt, bound to aad (the identity of the row the value belongs to). Unlike EncryptValue it does not fall back to plaintext: without an encryption key or a salt it returns ErrDataKeyUnavailable, and the caller decides.

func SecretWorkspacesByVarNames added in v2.3.0

func SecretWorkspacesByVarNames(db *gorm.DB, names []string) (map[string]uint, error)

SecretWorkspacesByVarNames is FindSecretByVarName for several names in one query, returning only the stored workspace_id of the secret each name resolves to. A name that resolves to nothing (unknown or ambiguous) is absent.

func SetDBRef

func SetDBRef(db *gorm.DB)

func SetEncryptionKey

func SetEncryptionKey(key string)

SetEncryptionKey sets the key that encrypts secrets at rest, taking the place of the TYK_AI_SECRET_KEY environment variable. An embedding host calls it before any secret is read or written.

func UpdateSecret

func UpdateSecret(db *gorm.DB, settings *Secret, encryptValue bool) error

UpdateSecret updates an existing Secret record in the database. When encryptValue is true, the Value field is encrypted before saving. Pass false when the Value already contains the stored (encrypted) value and should not be re-encrypted.

func UseMinScryptCostForTests added in v2.3.0

func UseMinScryptCostForTests()

UseMinScryptCostForTests lowers the scrypt N to scryptTestN for the rest of the test binary. One derivation at scryptN takes ~0.5-1 s under -race, and every encrypt derives a fresh key (a new random salt). It panics outside a test binary. Call it from an init(), before anything is encrypted: values encrypted earlier, and fixtures encrypted at scryptN, no longer decrypt.

func WarnIfEncryptionUnconfigured

func WarnIfEncryptionUnconfigured() bool

WarnIfEncryptionUnconfigured emits a prominent startup warning when the encryption key is not configured, so operators know stored secrets will be persisted as plaintext. Returns true when the key is configured.

func WritesFIPSFormat added in v2.3.0

func WritesFIPSFormat() bool

WritesFIPSFormat reports whether this process writes the FIPS 140-3 formats (v3 secrets): crypto/fips140.Enabled.

Types

type Secret

type Secret struct {
	gorm.Model
	ID uint `gorm:"primaryKey" json:"id" access:"secrets"`

	// WorkspaceID is the Workspace that owns the secret (models.Workspace);
	// 0 reads as the Default workspace.
	WorkspaceID uint `json:"workspace_id" gorm:"not null;default:0;index"`

	VarName string `json:"name"`
	Value   string `json:"value"`
	// contains filtered or unexported fields
}

func FindSecretByVarName added in v2.3.0

func FindSecretByVarName(db *gorm.DB, name string) (*Secret, error)

FindSecretByVarName returns the live secret named name (exact match). Names are unique for new writes (midsommar-clean-oztk.47); of grandfathered duplicates it picks the lowest id when they are all in one Workspace (0 read as the Default) and refuses with ErrSecretNameAmbiguous when they span Workspaces. gorm.ErrRecordNotFound when there is none. The value is returned as stored (encrypted).

func GetSecretByID

func GetSecretByID(db *gorm.DB, id uint, preserveRef bool) (*Secret, error)

GetSecretByID retrieves a Secret record from the database by ID.

func GetSecretByVarName

func GetSecretByVarName(db *gorm.DB, name string, preserveRef bool) (*Secret, error)

GetSecretByVarName retrieves a Secret record from the database by its name (FindSecretByVarName). It is the one place a $SECRET/ reference is resolved (GetValue, ResolveRef, CredentialRefForEdge and so the edge snapshot; microgateways get the hub's resolved values).

func ListSecrets

func ListSecrets(db *gorm.DB, pageSize int, pageNumber int, all bool, scopes ...func(*gorm.DB) *gorm.DB) ([]Secret, int64, int, error)

func (*Secret) BeforeCreate added in v2.3.0

func (s *Secret) BeforeCreate(tx *gorm.DB) error

BeforeCreate stamps the secret's Workspace and locks it for the insert (wsstamp.OnCreate).

func (*Secret) BeforeUpdate added in v2.3.0

func (s *Secret) BeforeUpdate(tx *gorm.DB) error

BeforeUpdate keeps the Workspace stamp out of ordinary updates (wsstamp.KeepOnUpdate).

func (*Secret) GetValue

func (s *Secret) GetValue() string

GetValue returns either the decrypted value or the reference format

func (*Secret) HasValue

func (s *Secret) HasValue() bool

HasValue reports whether the secret holds a non-empty value, without exposing it. Works on a row as stored (encrypted) and on one that has already been decrypted: an encrypted empty string is a real ciphertext, so the stored form has to be decrypted to know it is empty, while a decrypted value is simply checked for emptiness.

func (*Secret) PreserveReference

func (s *Secret) PreserveReference()

PreserveReference sets the secret to return in reference format

Jump to

Keyboard shortcuts

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