Django ORM

Secret models.

class smarter.apps.secret.models.Secret(*args, **kwargs)[source]

Bases: MetaDataWithOwnershipModel

Secret model for securely storing and managing sensitive account-level information.

Usage:

# Encrypt a secret value before saving it
secret_value = Secret.encrypt("my-sensitive-api-key")

# Create a new secret
secret = Secret(
    name="API Key",
    user_profile=user_profile_instance,
    encrypted_value=secret_value
)
secret.save()

# Retrieve and decrypt a secret
retrieved_secret = Secret.objects.get(id=secret.id)
decrypted_value = retrieved_secret.get_secret()

Note

The value field is transient and only used during runtime. It is not stored in the database to ensure sensitive data is only saved in encrypted form.

Parameters:
  • id (Unknown) – Primary key: ID

  • created_at (Unknown) – Created at

  • updated_at (Unknown) – Updated at

  • name (Unknown) – Name. Name in camelCase, e.g., ‘apiKey’, no special characters.

  • description (Unknown) – Description. A brief description of this resource. Be verbose, but not too verbose.

  • version (Unknown) – Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.

  • last_accessed (Unknown) – Last accessed. Timestamp of the last time the secret was accessed.

  • expires_at (Unknown) – Expires at. Timestamp indicating when the secret expires. If null, the secret does not expire.

  • encrypted_value (Unknown) – Encrypted value. Read-only encrypted representation of the secret’s value.

Relationship fields:

Parameters:
  • user_profile (Unknown) – User profile. Reference to the UserProfile associated with this secret. (related name: secrets)

  • tags (Unknown) – Tags. Tags for categorizing and organizing this resource. (related name: secret)

  • tagged_items (Unknown) – Tagged items (related name: +)

Reverse relationships:

Parameters:
  • api_connections_api_key (Unknown) – All api connections api key of this Secret (related name of api_key)

  • api_connections_proxy_password (Unknown) – All api connections proxy password of this Secret (related name of proxy_password)

  • sql_connections_password (Unknown) – All sql connections password of this Secret (related name of password)

  • sql_connections_proxy_password (Unknown) – All sql connections proxy password of this Secret (related name of proxy_password)

  • llmhosts (Unknown) – All llmhosts of this Secret (related name of api_key_secret)

  • mcpclient (Unknown) – All MCPClients of this Secret (related name of credentials)

  • plugin_data_websearch_api_key (Unknown) – All plugin data websearch api key of this Secret (related name of search_api_key)

  • provider_api_key (Unknown) – All provider api key of this Secret (related name of api_key)

  • proxies (Unknown) – All proxies of this Secret (related name of api_key_secret)

  • vectorsearches (Unknown) – All vectorsearches of this Secret (related name of auth_secret)

  • vectorstores (Unknown) – All vectorstores of this Secret (related name of api_key_secret)

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

exception NotUpdated

Bases: ObjectNotUpdated, DatabaseError

api_connections_api_key

Reverse ForeignKey from ApiConnection

All api connections api key of this Secret (related name of api_key)

Type:

Type

api_connections_proxy_password

Reverse ForeignKey from ApiConnection

All api connections proxy password of this Secret (related name of proxy_password)

Type:

Type

created_at

DateTimeField

Created at

Timestamp indicating when the model instance was created.

This field is automatically set to the current date and time when the instance is first created. It is indexed in the database for efficient querying.

Type:

Type

description

TextField

Description. A brief description of this resource. Be verbose, but not too verbose.

Type:

Type

classmethod encrypt(value)[source]

Encrypt a string value using Fernet symmetric encryption.

Parameters:

value (str) – str The plaintext string to encrypt.

Return type:

bytes

Returns:

bytes The encrypted value as bytes.

Raises:

SmarterValueError If the input value is not a non-empty string.

Attention

The original plaintext value is not stored or persisted; only the encrypted bytes are returned.

Caution

Always clear or avoid storing the plaintext value after encryption to prevent accidental exposure.

Example usage:

encrypted = Secret.encrypt("my-api-key")
# Store `encrypted` in the database, never the plaintext

See also

get_fernet() – Returns the Fernet encryption object.

encrypted_value

BinaryField

Encrypted value. Read-only encrypted representation of the secret’s value.

Type:

Type

expires_at

DateTimeField

Expires at. Timestamp indicating when the secret expires. If null, the secret does not expire.

Type:

Type

classmethod get_cached_object(*args, invalidate=False, pk=None, name=None, user=None, user_profile=None, account=None, **kwargs)[source]

Retrieve a model instance using caching to optimize performance.

Examples of retrieval patterns:

# By primary key
instance = MyModel.get_cached_object(pk=123)

# By name and user profile
instance = MyModel.get_cached_object(name="Resource Name", user_profile=user_profile)

# By name and account
instance = MyModel.get_cached_object(name="Resource Name", account=account)
Parameters:
  • pk (int | None) – The primary key of the model instance to retrieve.

  • name (str | None) – The name of the model instance to retrieve.

  • user (User | None) – The user associated with the model instance.

  • user_profile (UserProfile | None) – The user profile associated with the model instance.

  • account (Account | None) – The account associated with the model instance.

Returns:

The model instance if found, otherwise None.

Return type:

Secret

classmethod get_fernet()[source]

Return a Fernet encryption object for secure value encryption and decryption.

Return type:

Fernet

Returns:

cryptography.fernet.Fernet A Fernet instance initialized with the configured encryption key.

Raises:

SmarterConfigurationError If the encryption key is missing from settings.

Important

The encryption key must be set in smarter.common.conf.settings.fernet_encryption_key. Without a valid key, secrets cannot be encrypted or decrypted.

Example usage:

fernet = Secret.get_fernet()
encrypted = fernet.encrypt(b"my-value")
decrypted = fernet.decrypt(encrypted)

See also

encrypt() – Uses the Fernet object to encrypt values.

get_secret(update_last_accessed=True)[source]

Decrypt and return the original secret value.

Optionally updates the last_accessed timestamp and emits an access signal. If decryption fails, raises a SmarterValueError.

Parameters:

update_last_accessed – Boolean. If True, updates the last_accessed timestamp. Defaults to True.

Return type:

str | None

Returns:

Optional[str] The decrypted secret value, or None if not set.

Raises:

SmarterValueError if decryption fails.

Note

Accessing the secret updates its last accessed time for audit purposes.

Example usage:

secret_value = secret.get_secret(update_last_accessed=True)
id: int

BigAutoField

Primary key: ID

The row’s primary key, which Django adds to every concrete model. Declared, without a value, only so that type checkers know it: Django ignores a bare annotation.

Type:

Type

is_expired()[source]

Determine whether the secret has expired based on its expires_at timestamp.

Return type:

bool

Returns:

bool True if the current time is past the expiration timestamp; False otherwise.

Note

If expires_at is not set, the secret is considered non-expiring.

Example usage:

if secret.is_expired():
    print("This secret is no longer valid.")
last_accessed

DateTimeField

Last accessed. Timestamp of the last time the secret was accessed.

Type:

Type

llmhosts

Reverse ForeignKey from LLMHost

All llmhosts of this Secret (related name of api_key_secret)

Type:

Type

property manifest_url: str | None

Returns the URL to the plugin’s manifest.

This property constructs the URL to the plugin’s manifest based on its kind and RFC 1034-compliant name. The URL follows the pattern: /plugins/{kind}/{name}/manifest/, where {kind} is the RFC 1034-compliant kind of the plugin, and {name} is the RFC 1034-compliant name of the plugin.

Example:

self.rfc1034_compliant_kind  # 'static'
self.rfc1034_compliant_name  # 'example-plugin
self.manifest_url  # '/plugins/static/example-plugin/manifest/'
mcpclient_set

Reverse ForeignKey from MCPClient

All MCPClients of this Secret (related name of credentials)

Type:

Type

name

CharField

Name. Name in camelCase, e.g., ‘apiKey’, no special characters.

Type:

Type

objects: SecretManager = <smarter.apps.secret.models.SecretManager object>
plugin_data_websearch_api_key

Reverse ForeignKey from PluginDataWebsearch

All plugin data websearch api key of this Secret (related name of search_api_key)

Type:

Type

provider_api_key

Reverse ForeignKey from Provider

All provider api key of this Secret (related name of api_key)

Type:

Type

proxies

Reverse ForeignKey from Proxy

All proxies of this Secret (related name of api_key_secret)

Type:

Type

property ready: bool

the parent’s check passes, and it has an encrypted value.

Type:

Whether the Secret is ready

save(*args, **kwargs)[source]

Encrypt and persist the secret value for this instance.

This method encrypts the transient value field and stores the result in encrypted_value. It validates that both name and encrypted_value are present and that the value is a string.

Parameters:
  • args – Positional arguments passed to the parent save method.

  • kwargs – Keyword arguments passed to the parent save method.

Raises:

SmarterValueError if name or encrypted_value is missing.

Important

Only the encrypted value is stored in the database; the plaintext value is never persisted.

Note

Emits a signal on creation or edit for audit and notification purposes.

Example usage:

secret = Secret(
    name="apiKey",
    user_profile=user_profile,
    encrypted_value=Secret.encrypt("my-api-key")
)
secret.save()
sql_connections_password

Reverse ForeignKey from SqlConnection

All sql connections password of this Secret (related name of password)

Type:

Type

sql_connections_proxy_password

Reverse ForeignKey from SqlConnection

All sql connections proxy password of this Secret (related name of proxy_password)

Type:

Type

tagged_items

Reverse GenericRelation from Secret

All + of this tagged item (related name of tagged_items)

Type:

Type

tags = <taggit.managers._TaggableManager object>
updated_at

DateTimeField

Updated at

Timestamp indicating when the model instance was last updated.

This field is automatically updated to the current date and time whenever the instance is saved. It is indexed in the database for efficient querying.

Type:

Type

user_profile

ForeignKey to UserProfile

User profile. Reference to the UserProfile associated with this secret. (related name: secrets)

Type:

Type

user_profile_id

Internal field, use user_profile instead.

vectorsearches

Reverse ForeignKey from Vectorsearch

All vectorsearches of this Secret (related name of auth_secret)

Type:

Type

vectorstores

Reverse ForeignKey from VectorstoreMeta

All vectorstores of this Secret (related name of api_key_secret)

Type:

Type

version

CharField

Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.

Type:

Type

class smarter.apps.secret.models.SecretManager(*args, **kwargs)[source]

Bases: MetaDataWithOwnershipModelManager

The manager of Secret, which returns a SecretQuerySet.

get_queryset()[source]

Returns a SecretQuerySet for the model.

Return type:

SecretQuerySet

with_use_permission_for(user)[source]

Returns the Secrets that a resource of user may use.

See SecretQuerySet.with_use_permission_for().

Return type:

SecretQuerySet

class smarter.apps.secret.models.SecretQuerySet(model=None, query=None, using=None, hints=None)[source]

Bases: SmarterQuerySetWithPermissions

The permission-aware queryset of Secret.

Other resources that the platform account owns, such as its Providers and example Plugins, are shared built-ins that every account may read. A Secret holds a credential, so its read permission is its ownership permission instead: a superuser reads every Secret, a staff user the Secrets of their own account, and any other user only their own. No account but the platform’s reads the platform’s Secrets, e.g. the provider api keys that manage.py initialize_providers stores. Whatever a caller does with a Secret that it reads, whether it clones it, describes it, or attaches it to a resource that sends it to a url of its owner’s choosing, it can’t reach another account’s credential.

Platform code that needs a platform Secret looks it up by its owner, e.g. Secret.get_cached_object(name=..., user_profile=smarter_cached_objects.smarter_admin_user_profile), rather than through a user’s permissions.

with_read_permission_for(user)[source]

Returns the Secrets that user may read: the same Secrets that they may manage.

Parameters:

user (User) – django.contrib.auth.models.User The user to check.

Return type:

SecretQuerySet

Returns:

SecretQuerySet The Secrets that the user owns, or, for a staff user, that their account owns, or, for a superuser, every Secret.

with_use_permission_for(user)[source]

Returns the Secrets that a resource of user may use without revealing their value.

These are the Secrets of the user’s accounts and of the platform account, which is the read permission that the platform’s other shared resources have. Use it only where Smarter itself fixes the endpoint that receives the credential, e.g. the web search and image search api keys of WebsearchPlugins and ImageSearchPlugins, which every account’s copy of the example plugins shares, and never to return a Secret’s value to the user, to copy a Secret, or to attach it to a resource whose url its owner chooses.

Parameters:

user (User) – django.contrib.auth.models.User The user to check.

Return type:

SecretQuerySet

Returns:

SecretQuerySet The Secrets that a resource of the user may use.