Documentation
¶
Index ¶
- Constants
- Variables
- func CheckCredential(v string) error
- func CreateSecret(db *gorm.DB, settings *Secret) error
- func CredentialRefForEdge(ref string) string
- func DataKeyCurrentPrefix() string
- func DecryptValue(value string) string
- func DeleteSecretByID(db *gorm.DB, id uint) error
- func DisableEnvRefs()
- func EncryptValue(plaintext string) string
- func EncryptionKeyConfigured() bool
- func EnvRefAllowed(name string) bool
- func FilterSensitiveFields(obj interface{}) interface{}
- func FilterSesitiveFieldsArr(in interface{}) interface{}
- func ForEdge(resolved string) string
- func ForEdgeCredential(resolved string) string
- func ForceFIPSModeForTest(tb testing.TB)
- func GetOrCreateDefaultSecrets(db *gorm.DB, skip ...func(name string) (bool, error)) error
- func GetSecretReference(name string) string
- func GetValue(reference string, preserveRef bool) string
- func IsDataKeyValue(stored string) bool
- func IsReference(v string) bool
- func IsSecretReference(value string) bool
- func KeyDerivations() uint64
- func LookupHash(value string) string
- func LookupHashPrefix() string
- func NewReferences(old, updated map[string]string) []string
- func OpenWithDataKey(salt []byte, stored, aad string) (string, error)
- func ReencryptEncJSON(doc string) (string, int)
- func ReencryptEncValue(value string) (string, bool)
- func ReencryptLegacySecrets(db *gorm.DB) (int, error)
- func ResolveRef(v string) string
- func SealWithDataKey(salt []byte, plaintext, aad string) (string, error)
- func SecretWorkspacesByVarNames(db *gorm.DB, names []string) (map[string]uint, error)
- func SetDBRef(db *gorm.DB)
- func SetEncryptionKey(key string)
- func UpdateSecret(db *gorm.DB, settings *Secret, encryptValue bool) error
- func UseMinScryptCostForTests()
- func WarnIfEncryptionUnconfigured() bool
- func WritesFIPSFormat() bool
- type Secret
- func FindSecretByVarName(db *gorm.DB, name string) (*Secret, error)
- func GetSecretByID(db *gorm.DB, id uint, preserveRef bool) (*Secret, error)
- func GetSecretByVarName(db *gorm.DB, name string, preserveRef bool) (*Secret, error)
- func ListSecrets(db *gorm.DB, pageSize int, pageNumber int, all bool, ...) ([]Secret, int64, int, error)
Constants ¶
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.
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.
const ( SecretRefPrefix = "$SECRET/" EnvRefPrefix = "$ENV/" )
Reference prefixes for values that name a secret or an environment variable instead of holding the value.
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.
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 ¶
ErrDataKeyUnavailable: there is no encryption key, or no salt, to derive the data key from.
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.
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
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 ¶
CreateSecret creates a new Secret record in the database.
func CredentialRefForEdge ¶ added in v2.3.0
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 ¶
DecryptValue decrypts a value that was encrypted with EncryptValue. Returns the decrypted plaintext, or the original value if not encrypted.
func DeleteSecretByID ¶
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 ¶
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
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
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
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
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 ¶
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 ¶
GetSecretReference returns a secret reference string for a given name
func GetValue ¶
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
IsDataKeyValue reports whether stored is a value sealed under a data key.
func IsReference ¶ added in v2.3.0
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 ¶
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
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
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
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
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
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 ¶
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
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
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
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 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 ¶
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
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 ¶
GetSecretByID retrieves a Secret record from the database by ID.
func GetSecretByVarName ¶
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 (*Secret) BeforeCreate ¶ added in v2.3.0
BeforeCreate stamps the secret's Workspace and locks it for the insert (wsstamp.OnCreate).
func (*Secret) BeforeUpdate ¶ added in v2.3.0
BeforeUpdate keeps the Workspace stamp out of ordinary updates (wsstamp.KeepOnUpdate).
func (*Secret) HasValue ¶
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