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’.

  • annotations (Unknown) – Annotations. Key-value pairs for annotating this resource.

  • 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)

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

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

exception NotUpdated

Bases: ObjectNotUpdated, DatabaseError

annotations

JSONField

Annotations. Key-value pairs for annotating this resource.

Type:

Type

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 (Optional[int]) – The primary key of the model instance to retrieve.

  • name (Optional[str]) – The name of the model instance to retrieve.

  • user (Optional[User]) – The user associated with the model instance.

  • user_profile (Optional[UserProfile]) – The user profile associated with the model instance.

  • account (Optional[Account]) – The account associated with the model instance.

Returns:

The model instance if found, otherwise None.

Return type:

Optional[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:

Optional[str]

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

BigAutoField

Primary key: ID

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

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/'
name

CharField

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

Type:

Type

objects: MetaDataWithOwnershipModelManager = <smarter.apps.account.models.metadata_with_ownership.MetaDataWithOwnershipModelManager object>
provider_api_key

Reverse ForeignKey from Provider

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

Type:

Type

property ready: bool

Indicates whether the object is ready for use.

This is a placeholder that should be overridden in subclasses.

Returns:

True if ready, False otherwise.

Return type:

bool

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.

version

CharField

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

Type:

Type