Welcome to VaultAPI’s documentation!¶
VaultAPI - Server¶
Server module includes the starter function for the Vault API.
It creates the default table in the database.
Instantiates the database and uvicorn config with customizations to host, port, workers, and log_config.
Initializes the uvicorn server with the custom configurations.
- vaultapi.server.start() None¶
Starter function for the API, which uses uvicorn server as trigger.
Application module that wires together the FastAPI instance, CORS policy, and all routes.
Defines the FastAPI application instance and the lifespan context manager.
Registers the custom Swagger UI docs endpoint.
Attaches API routes and, when the UI is enabled, UI routes.
- async vaultapi.api.delete_ui_session(event: str) None¶
Delete the active UI session during application startup or shutdown.
- Parameters:
event – Lifecycle event name (e.g.
"startup"or"shutdown"), used only for log messages.
- vaultapi.api.lifespan(_: FastAPI)¶
Lifespan context manager that handles startup and shutdown events.
- async vaultapi.api.docs() HTMLResponse¶
Render the custom Swagger UI docs page.
- Returns:
HTML page with the customized Swagger UI.
- Return type:
HTMLResponse
- vaultapi.api.startup() None¶
Configure CORS middleware and register all API and UI routes on the application.
See also
When
enable_uiisTrue, auth tables are created and UI routes are registered. When disabled, the root path redirects to/docsinstead.
Authenticator¶
Authenticator module contains functions that handle authentication requests from individual API/UI endpoints.
- vaultapi.auth.UI_BASIC(session, auth, host)¶
- vaultapi.auth.API_BASIC(auth)¶
- vaultapi.auth.API_ADVANCED(auth)¶
- vaultapi.auth.unauthorized(host: str) NoReturn¶
Increment the failed auth counter for a host and raise a 401 response.
- Parameters:
host – Hostname or IP address of the client.
- Raises:
- 401 – Always raised after incrementing the failure counter.
- async vaultapi.auth.blocked(host: str) Union[None, NoReturn]¶
Raise a 403 response if the host is within an active cool-off window.
- Parameters:
host – Hostname or IP address of the client.
- Raises:
- 403 – If the host has a non-expired
blocked_untilentry.
- async vaultapi.auth.validate_totp(totp_code: str) Union[bool, NoReturn]¶
Verify a TOTP code against the configured authenticator token.
- Parameters:
totp_code – TOTP code received from the client.
- Returns:
Trueif the code is valid,Falseotherwise.- Return type:
bool
- async vaultapi.auth.validate(request: Request, authorization: HTTPAuthorizationCredentials, auth_type: AuthType) Union[None, NoReturn]¶
Validate an incoming request’s credentials against the requested auth type.
See also
Auth type dispatch: -
ui_login: API key (HMAC) + TOTP code. -ui_basic: Active session token bound to the client host. -ui_advanced: Active session token + TOTP code. -api_basic: HMAC-signed API key. -api_advanced: HMAC-signed combined API key and secret.- Parameters:
request – Incoming FastAPI request object.
authorization – Credential extracted from the
Authorization: Bearerheader.auth_type – Determines which validation path to follow.
- Raises:
- 401 – If the provided credentials are invalid.
- 403 – If the host is blocked after repeated failed attempts.
Core¶
Core module is the common layer for Vault API that includes functionalities used by both API and UI endpoints.
- async vaultapi.core.retrieve_secret(key: str, table_name: str) Optional[str]¶
Return the raw encrypted value for a single key, or
Noneif not found.- Parameters:
key – Key to look up.
table_name – Table name where the secret is stored.
- Returns:
Raw encrypted value, or
Noneif the key does not exist.- Return type:
str
- Raises:
- 400 – On SQLite operational error.
- 404 –
keydoes not exist.
- async vaultapi.core.retrieve_secrets(table_name: str, keys: Optional[List[str]] = None) Dict[str, Optional[str]]¶
Return a mapping of key → encrypted value for the given table.
When
keysis provided only those keys are fetched; otherwise all rows in the table are returned.- Parameters:
table_name – Table name where the secrets are stored.
keys – Optional subset of keys to retrieve. Omit to return the full table.
- Returns:
Mapping of key names to their raw encrypted values.
- Return type:
Dict[str, bytes]
- Raises:
- 400 – On SQLite operational error.
- vaultapi.core.create_table(table_name: str) None¶
Create a table, raising 409 if it already exists or 400 on a DB error.
- Parameters:
table_name – Name of the table to create.
- Raises:
- 409 – A table with that name already exists.
- 400 – On SQLite operational error.
- vaultapi.core.drop_table(table_name: str) None¶
Drop a table, raising 404 if it does not exist or 400 on a DB error.
- Parameters:
table_name – Name of the table to drop.
- Raises:
- 404 – Table not found.
- 400 – On SQLite operational error.
- vaultapi.core.rename_table(table_name: str, new_name: str) None¶
Rename a table after validating the old and new names.
- Parameters:
table_name – Current name of the table.
new_name – Desired new name.
- Raises:
- 400 –
new_nameis empty.- 404 –
table_namedoes not exist.- 409 – A table named
new_namealready exists.- 400 – On SQLite operational error.
- async vaultapi.core.remove_secret(key: str, table_name: str) None¶
Delete a secret from a table after validating its existence.
- Parameters:
key – Key of the secret to remove.
table_name – Name of the table that contains the secret.
- Raises:
- 400 –
keyis empty.- 404 – The secret does not exist.
- 400 – On SQLite operational error.
- vaultapi.core.parse_import_payload(payload: str, payload_type: str) Dict[str, str]¶
Parse a JSON, YAML, or
.envstring into a flat key-value dict.See also
Supported
payload_typevalues: -"json": Must be a flat JSON object. -"yaml": Must be a flat YAML mapping. -"env": Standard dotenv format; comments and blank lines are skipped.- Parameters:
payload – Raw payload string to parse.
payload_type – Format indicator — one of
"json","yaml", or"env".
- Returns:
Flat mapping of string keys to string values extracted from the payload.
- Return type:
Dict[str, str]
- Raises:
- 400 – Unsupported
payload_type, malformed payload, non-dict structure, or empty result.
Database¶
Database module that provides all SQLite read/write operations for secrets, sessions, and auth tracking.
Manages the UI session table (single active session stored as a Fernet-encrypted blob).
Manages the blocked-hosts table for failed authentication rate-limiting.
Provides CRUD helpers for user-defined secret tables.
- vaultapi.database.create_auth_tables() None¶
Create the UI session and blocked-hosts tables if they do not already exist.
- vaultapi.database.upsert_ui_session(token: str, hostname: str, expires: int, fernet: Fernet) None¶
Persist an active UI session, replacing any previous one.
The stored blob is
fernet.encrypt(json({"token": ..., "host": ..., "exp": ...})). Fernet provides authenticated encryption — tampering with the blob is detected on decrypt and raises an exception, whichget_ui_sessiontreats as “no valid session”.- Parameters:
token – Opaque session token returned to the browser.
hostname –
request.client.hostcaptured at login time.expires – Unix timestamp after which the session is considered invalid.
fernet – Fernet instance from
models.session.fernet.
- vaultapi.database.get_ui_session(fernet: Fernet) dict | None¶
Return the decrypted session record, or
Noneif absent or tampered.- Parameters:
fernet – Fernet instance from
models.session.fernet.- Returns:
{"token": str, "host": str, "exp": int}on success,Noneotherwise.- Return type:
dict
- vaultapi.database.delete_ui_session() None¶
Remove all rows from the UI session table, invalidating any active session.
- vaultapi.database.get_blocked_until(host: str) vaultapi.models.AuthCounter | None¶
Return the auth counter for a blocked host, or
Noneif the host is not blocked.If a cooloff entry exists but has already expired it is cleared and
Noneis returned.- Parameters:
host – Client IP address to check.
- Returns:
AuthCounterwithcountandblocked_untilif the host is currently blocked,Noneotherwise.- Return type:
models.AuthCounter | None
- vaultapi.database.is_host_blocked(host: str) bool¶
Return
Trueif the host is currently within an active cooloff window.- Parameters:
host – Client IP address to check.
- Returns:
Trueif blocked,Falseotherwise.- Return type:
bool
- vaultapi.database.remove_blocked_host(host: str) None¶
Delete a host’s entry from the blocked-hosts table entirely.
- Parameters:
host – Client IP address to remove.
- vaultapi.database.increment_failed_auth(host: str) None¶
Increment the failed-authentication counter for a host and apply a cooloff if a threshold is crossed.
Inserts the host with
failed_auth = 1if it does not yet exist. Setsblocked_untilwhen the cumulative count reaches a threshold defined inCOOLOFF_THRESHOLDS.- Parameters:
host – Client IP address that failed authentication.
- vaultapi.database.reset_failed_auth(host: str) None¶
Reset the failed-authentication counter to zero after a successful login.
- Parameters:
host – Client IP address to reset.
- vaultapi.database.table_exists(table_name: str) bool¶
Check whether a user-defined table exists in the secrets database.
- Parameters:
table_name – Name of the table to check.
- Returns:
Trueif the table exists,Falseotherwise.- Return type:
bool
- vaultapi.database.list_tables() List[str]¶
Return the names of all user-defined tables in the secrets database.
- Returns:
List of table names.
- Return type:
List[str]
- vaultapi.database.create_table(table_name: str, columns: Union[List[str], Tuple[str]]) None¶
Create a table with the specified columns (no-op if it already exists).
- Parameters:
table_name – Name of the table to create.
columns – Column definitions (e.g.
["key", "value"]).
- vaultapi.database.get_secret(key: str, table_name: str) str | None¶
Retrieve a single encrypted secret value by key.
- Parameters:
key – Name of the secret to retrieve.
table_name – Name of the table where the secret is stored.
- Returns:
Encrypted secret value, or
Noneif the key does not exist.- Return type:
str
- vaultapi.database.get_table(table_name: str) List[Tuple[str, str]]¶
Retrieve all key-value pairs from a table.
- Parameters:
table_name – Name of the table to read.
- Returns:
List of
(key, encrypted_value)tuples.- Return type:
List[Tuple[str, str]]
- vaultapi.database.put_secret(key: str, value: str, table_name: str) None¶
Insert or overwrite a secret in the database.
- Parameters:
key – Name of the secret.
value – Encrypted value to store.
table_name – Name of the table where the secret is stored.
- vaultapi.database.remove_secret(key: str, table_name: str) None¶
Delete a secret from a table.
- Parameters:
key – Name of the secret to remove.
table_name – Name of the table where the secret is stored.
- vaultapi.database.drop_table(table_name: str) None¶
Drop a table from the database.
- Parameters:
table_name – Name of the table to drop.
- vaultapi.database.rename_table(old_name: str, new_name: str) None¶
Rename a table in the database.
- Parameters:
old_name – Current name of the table.
new_name – New name for the table.
Endpoints¶
API endpoints module that implements all authenticated REST operations for the Vault API.
Read-only endpoints (apikey based bearer token): get-secret, get-table, list-tables, create-table.
Write/Modify endpoints (apikey+secret based bearer token): put-secret, delete-secret, rename-table, delete-table.
Provides unauthenticated utility endpoints: health, version.
- async vaultapi.api_endpoints.get_secret(request: ~starlette.requests.Request, key: str, table_name: str = 'default', apikey: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
API function to retrieve one or more secret(s) - transit encrypted.
Args:
key: Single key or comma-separated list of keys to retrieve. table_name: Name of the table where the secrets are stored.
Raises:
APIResponse: - 200: Secrets found and returned (transit-encrypted). - 206: Partial content — some keys were not found. - 400: No valid keys provided. - 404: None of the requested keys were found.
- async vaultapi.api_endpoints.list_tables(request: ~starlette.requests.Request, apikey: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
API function to get ALL table names.
Raises:
APIResponse: - 200: Table list returned successfully.
- async vaultapi.api_endpoints.get_table(request: ~starlette.requests.Request, table_name: str = 'default', apikey: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
API function to get ALL secrets in a table - transit encrypted.
Args:
table_name: Name of the table where the secrets are stored.
Raises:
APIResponse: - 200: All secrets returned (transit-encrypted).
- async vaultapi.api_endpoints.put_secret(request: ~starlette.requests.Request, data: ~vaultapi.payload.PutSecret, apikey: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
API function to add or update secrets in a table, accepting plain or transit-encrypted payloads.
Args:
data: Request body containing
secrets(plain dict or transit-encrypted string) andtable_name.Raises:
APIResponse: - 200: Secrets stored successfully. - 404: Table not found.
- async vaultapi.api_endpoints.delete_secret(request: ~starlette.requests.Request, data: ~vaultapi.payload.DeleteSecret, apikey: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
API function to delete a secret key from a table in the database.
Args:
data: Request body containing
keyandtable_name.Raises:
APIResponse: - 200: Secret deleted successfully. - 404: Secret or table not found.
- async vaultapi.api_endpoints.create_table(request: ~starlette.requests.Request, table_name: str, apikey: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
API function to create a new table in the database.
Args:
table_name: Name of the table to be created.
Raises:
APIResponse: - 200: Table created successfully. - 409: Table already exists.
- async vaultapi.api_endpoints.rename_table(request: ~starlette.requests.Request, table_name: str, data: ~vaultapi.payload.RenameTable, apikey: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
API function to rename an existing table in the database.
Args:
table_name: Current name of the table to rename. data: Request body containing
new_name.Raises:
APIResponse: - 200: Table renamed successfully. - 400: New name is empty. - 404: Table not found. - 409: A table with the new name already exists.
- async vaultapi.api_endpoints.delete_table(request: ~starlette.requests.Request, table_name: str, apikey: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
API function to delete a table in the database.
Args:
table_name: Name of the table to delete.
Raises:
APIResponse: - 200: Table deleted successfully. - 404: Table not found.
- async vaultapi.api_endpoints.health() Dict[str, str]¶
Return a simple health check response.
- Returns:
Always returns
{"STATUS": "OK"}.- Return type:
Dict[str, str]
- async vaultapi.api_endpoints.get_version() str¶
Return the current version of the Vault API.
- Returns:
Version string of the Vault API.
- Return type:
str
UI endpoints module that implements the browser-facing routes for the VaultAPI web interface.
Serves the index and playground HTML pages.
Handles UI authentication (login/logout) and session management.
Provides session-authenticated CRUD operations for tables and secrets.
- async vaultapi.ui_endpoints.index(request: Request)¶
Serve the UI landing page.
- Parameters:
request – Incoming FastAPI request object.
- Returns:
Rendered
index.htmltemplate.- Return type:
HTMLResponse
- async vaultapi.ui_endpoints.playground(request: Request)¶
Serve the playground page.
- Parameters:
request – Incoming FastAPI request object.
See also
This endpoint is registered as part of API routes and available even when
enable_uiis set toFalse.- Returns:
Rendered
playground.htmltemplate withenable_uicontext variable.- Return type:
HTMLResponse
- async vaultapi.ui_endpoints.ui_login(request: ~starlette.requests.Request, apikey: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
Validate login credentials and issue a session token.
- Parameters:
request – Incoming FastAPI request object.
apikey – HMAC-signed API key credential.
- Returns:
{"token": str, "expires": int}on success.- Return type:
JSONResponse
- Raises:
- 401 – Invalid API key or TOTP code.
- 403 – Host is blocked after repeated failures.
- async vaultapi.ui_endpoints.ui_logout(request: ~starlette.requests.Request, session_token: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
Invalidate the active UI session.
- Parameters:
request – Incoming FastAPI request object.
session_token – Active session token.
- Returns:
{"detail": "OK"}on success.- Return type:
JSONResponse
- Raises:
- 401 – Token is invalid or already expired.
- 403 – Host is blocked.
- async vaultapi.ui_endpoints.ui_list_tables(request: ~starlette.requests.Request, session_token: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
Return a list of all table names for the UI.
- Parameters:
request – Incoming FastAPI request object.
session_token – Active session token.
- Returns:
{"tables": List[str]}on success.- Return type:
JSONResponse
- Raises:
- 401 – Invalid or expired session token.
- 403 – Host is blocked.
- async vaultapi.ui_endpoints.ui_get_table(request: ~starlette.requests.Request, table_name: str, session_token: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
Return all Fernet-encrypted key-value pairs from a table (no transit encryption).
- Parameters:
request – Incoming FastAPI request object.
table_name – Name of the table to retrieve.
session_token – Active session token.
- Returns:
{"encrypted_secrets": Dict[str, str]}mapping keys to Fernet-encoded values.- Return type:
JSONResponse
- Raises:
- 401 – Invalid or expired session token.
- 403 – Host is blocked.
- 404 – Table not found.
- async vaultapi.ui_endpoints.ui_rename_table(request: ~starlette.requests.Request, table_name: str, session_token: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
Rename a table.
- Parameters:
request – Incoming FastAPI request object.
table_name – Current name of the table to rename.
session_token – Active session token.
- Returns:
{"detail": "OK"}on success.- Return type:
JSONResponse
- Raises:
- 400 – New name is empty.
- 401 – Invalid session token or TOTP.
- 403 – Host is blocked.
- 404 – Table not found.
- 409 – Target name already exists.
- async vaultapi.ui_endpoints.ui_create_table(request: ~starlette.requests.Request, table_name: str, session_token=Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
Create a new table.
- Parameters:
request – Incoming FastAPI request object.
table_name – Name of the table to create.
session_token – Active session token.
- Returns:
{"detail": "OK"}on success.- Return type:
JSONResponse
- Raises:
- 401 – Invalid or expired session token.
- 403 – Host is blocked.
- 409 – Table already exists.
- async vaultapi.ui_endpoints.ui_delete_table(request: ~starlette.requests.Request, table_name: str, session_token: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
Delete a table and all its secrets.
- Parameters:
request – Incoming FastAPI request object.
table_name – Name of the table to delete.
session_token – Active session token.
- Returns:
{"detail": "OK"}on success.- Return type:
JSONResponse
- Raises:
- 401 – Invalid session token or TOTP.
- 403 – Host is blocked.
- 404 – Table not found.
- async vaultapi.ui_endpoints.ui_put_secret(request: ~starlette.requests.Request, session_token: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
Add or update a single secret in a table.
- Parameters:
request – Incoming FastAPI request object. Body must contain
table_name,key, andvalue.session_token – Active session token.
- Returns:
{"detail": "OK"}on success.- Return type:
JSONResponse
- Raises:
- 400 – Key is empty.
- 401 – Invalid session token or TOTP.
- 403 – Host is blocked.
- 404 – Table not found.
- async vaultapi.ui_endpoints.ui_import_secrets(request: ~starlette.requests.Request, session_token: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
Import multiple secrets into a table from a JSON, YAML, or
.envpayload.- Parameters:
request – Incoming FastAPI request object. Body must contain
table_name,payload, andpayload_type.session_token – Active session token.
- Returns:
{"imported": int, "skipped": int}with counts of processed entries.- Return type:
JSONResponse
- Raises:
- 400 – Invalid or empty payload.
- 401 – Invalid session token or TOTP.
- 403 – Host is blocked.
- 404 – Table not found.
- async vaultapi.ui_endpoints.ui_delete_secret(request: ~starlette.requests.Request, session_token: ~fastapi.security.http.HTTPAuthorizationCredentials = Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))¶
Delete a single secret from a table.
- Parameters:
request – Incoming FastAPI request object. Body must contain
table_nameandkey.session_token – Active session token.
- Returns:
{"detail": "OK"}on success.- Return type:
JSONResponse
- Raises:
- 400 – Key is empty.
- 401 – Invalid session token or TOTP.
- 403 – Host is blocked.
- 404 – Secret not found.
Enums¶
Enumerations module that defines string enums for API routes, UI routes, and authentication types.
- class vaultapi.enums.APIRoutes(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
Enums for API routes.
>>> APIRoutes
- root = '/'¶
- docs = '/docs'¶
- redoc = '/redoc'¶
- health = '/health'¶
- version = '/version'¶
- get_secret = '/get-secret'¶
- get_table = '/get-table'¶
- list_tables = '/list-tables'¶
- create_table = '/create-table'¶
- put_secret = '/put-secret'¶
- delete_secret = '/delete-secret'¶
- rename_table = '/rename-table'¶
- delete_table = '/delete-table'¶
- class vaultapi.enums.UIRoutes(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
Enums for UI routes.
>>> UIRoutes
- root = '/'¶
- playground = '/playground'¶
- ui_login = '/ui/login'¶
- ui_logout = '/ui/logout'¶
- ui_tables = '/ui/tables'¶
- ui_table = '/ui/table/{table_name}'¶
- ui_secret = '/ui/secret'¶
- ui_import = '/ui/import'¶
Exceptions¶
Exceptions module that defines custom exception classes used across the Vault API.
- exception vaultapi.exceptions.APIResponse(status_code: int, detail: Any = None, headers: collections.abc.Mapping[str, str] | None = None)¶
Custom
HTTPExceptionfromFastAPIto wrap an API response.>>> APIResponse
- exception vaultapi.exceptions.StartupError¶
Custom
StartupErrorto indicate an error during application startup.>>> StartupError
Header¶
Header module that generates and validates HMAC-SHA512 signed authentication headers.
- vaultapi.header.generate(token: str) str¶
Generate an HMAC-SHA512 signed authentication header value.
The header encodes a Unix timestamp and a signature so the server can verify both the token and the request’s age, reducing replay attack risk.
See also
Header format:
Signature=<hex_digest>,timestamp=<unix_seconds>- Parameters:
token – Shared API token used as the HMAC secret key.
- Returns:
Authentication header value containing the signature and timestamp.
- Return type:
str
- vaultapi.header.validate(auth_header: str, token: str, validity: int) bool¶
Validate an authentication header generated by
generate.See also
Validation steps: 1. Parse the signature and timestamp from the header. 2. Reject timestamps too far in the future (clock skew tolerance =
validity // 5). 3. Reject timestamps that have expired beyond the validity window. 4. Recompute the expected HMAC-SHA512 signature. 5. Compare signatures with a constant-time digest to prevent timing attacks.- Parameters:
auth_header – Raw authentication header value received from the client.
token – Shared API token used as the HMAC secret key.
validity – Accepted age of the header in seconds.
- Returns:
Trueif the header is structurally valid, unexpired, and the signature matches;Falseotherwise.- Return type:
bool
Models¶
- class vaultapi.models.RateLimit(BaseModel)¶
Object to store the rate limit settings.
>>> RateLimit
- max_requests: int¶
- seconds: int¶
- class vaultapi.models.Session(BaseModel)¶
Object to store session information.
>>> Session
- fernet: cryptography.fernet.Fernet | None¶
- info: Dict[str, str]¶
- rps: Dict[str, int]¶
- class vaultapi.models.EnvConfig(BaseSettings)¶
Object to load environment variables.
>>> EnvConfig
- Parameters:
apikey – API key to authenticate the
GETandPOSTrequestssecret – Shared secret used for DB encryption (Fernet) and transit encryption (AES)
transit_key_length – Length of the transit key (AES) - first N bytes of SHA-256 hash.
transit_time_bucket – Duration in seconds for ciphertext to be keyed.
authorization_validity – Duration in seconds for a HMAC-signed auth header to be accepted after it was generated.
database – Path to the main SQLite database file.
auth_database – Path to the auth SQLite database file.
host – Host to run the API server.
port – Port to run the API server.
workers – Number of worker processes.
enable_ui – Boolean to indicate whether to enable UI.
totp_token – Authenticator token for TOTP-based authentication.
ui_lifetime – Lifetime of the UI
session_tokenin seconds.log_config – File path to the logging configuration file [OR] the log configuration dictionary itself.
allowed_origins – List of allowed origins for CORS.
rate_limit – Rate limit for API calls.
- apikey: str¶
- secret: str¶
- transit_key_length: int¶
- transit_time_bucket: int¶
- authorization_validity: int¶
- database: Union[Path, Path, str]¶
- auth_database: Union[Path, Path, str]¶
- host: str¶
- port: int¶
- workers: int¶
- enable_ui: bool¶
- totp_token: str | None¶
- ui_lifetime: int¶
- log_config: Optional[Union[Path, Dict[str, Any]]]¶
- allowed_origins: Union[HttpUrl, List[HttpUrl]]¶
- classmethod validate_transit_key_length(value: int) Union[int, NoReturn]¶
Validate that the transit key length is an AES-compatible size.
- Parameters:
value – Proposed key length in bytes.
- Returns:
The validated key length if it is 16, 24, or 32.
- Return type:
PositiveInt
- Raises:
ValueError – If the value is not one of the accepted AES key sizes.
- classmethod validate_apikey(value: str) str | None¶
Validate the API key against minimum complexity requirements.
- Parameters:
value – Proposed API key string.
- Returns:
The validated API key.
- Return type:
str
- Raises:
ValueError – If the key does not meet complexity requirements.
- classmethod validate_api_secret(value: str) str¶
Validate that the secret is a valid Fernet key.
- Parameters:
value – Proposed secret string.
- Returns:
The validated secret.
- Return type:
str
- Raises:
ValueError – If the value cannot be used to construct a Fernet instance.
Models module that defines configuration, session, and database connection objects for the Vault API.
Provides
EnvConfigfor loading and validating all environment variables.Provides
Databasefor managing SQLite connections.Provides
Sessionfor holding runtime state (Fernet instance, etc.).Bootstraps the global
env,database,auth_database, andsessionsingletons.
- vaultapi.models.complexity_checker(secret: str, max_len: int = 32) None¶
Verify that a secret meets minimum complexity requirements.
See also
A secret is considered strong if it has at least:
32 characters
1 digit
1 symbol
1 uppercase letter
1 lowercase letter
- Parameters:
secret – The secret string to validate.
max_len – Minimum required character length. Defaults to
32.
- Raises:
AssertionError – When any complexity condition fails.
- vaultapi.models.validate_totp_secret(token) Union[None, NoReturn]¶
Validate the provided TOTP secret by generating and verifying a sample code.
- Parameters:
token – Base32-encoded TOTP secret to validate.
- Raises:
AssertionError – If the TOTP secret fails self-verification.
- class vaultapi.models.Database(filepath: Union[Path, str], timeout: int = 10)¶
Creates a connection and instantiates the cursor.
>>> Database
- Parameters:
filepath – Name of the database file.
timeout – Timeout for the connection to database.
- class vaultapi.models.AuthCounter(*, count: int, blocked_until: int)¶
Base model for auth counters.
>>> AuthCounter
- count: int¶
- blocked_until: int¶
- _abc_impl = <_abc._abc_data object>¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- vaultapi.models.envfile_loader(filename: str | os.PathLike) EnvConfig¶
Load environment variables from a file, dispatching by extension.
- Parameters:
filename – Path to the environment file (
.json,.yaml/.yml, or.env/.txt).- Returns:
Populated
EnvConfiginstance.- Return type:
- Raises:
ValueError – If the file extension is not supported.
- vaultapi.models.load_env() EnvConfig¶
Load environment configuration from a file if present, otherwise from environment variables.
See also
Checks
env_file/ENV_FILEenvironment variable first; falls back to.envin the working directory; finally falls back to reading variables directly from the environment.- Returns:
Populated
EnvConfiginstance.- Return type:
OTP¶
OTP module that handles TOTP secret generation, QR code creation, and secret display.
- class vaultapi.otp.OTPConfig(qr_filename: str, authenticator_user: str, authenticator_app: str, secret: str = '')¶
Data class to hold OTP configuration.
>>> OTPConfig
- qr_filename: str¶
- authenticator_user: str¶
- authenticator_app: str¶
- secret: str = ''¶
- vaultapi.otp.display_secret(config: OTPConfig) None¶
Print the TOTP secret key and QR code filename to the terminal.
- Parameters:
config – OTP configuration containing the secret and QR filename to display.
- vaultapi.otp.generate_qr(show_qr: bool, config: OTPConfig) None¶
Generate a TOTP secret, create a QR code, and optionally display it.
See also
Steps performed: 1. Generate a new Base32 TOTP secret. 2. Build a
otpauth://provisioning URI for authenticator apps. 3. Render the URI as a QR code and save it toconfig.qr_filename. 4. Updateconfig.secretwith the generated secret. 5. Print the secret to the terminal viadisplay_secret.- Parameters:
show_qr – If
True, opens the QR code image with the default viewer.config – OTP configuration updated in-place with the generated secret and filename.
Payload¶
- class vaultapi.payload.DeleteSecret(BaseModel)¶
Payload for delete-secret API call.
>>> DeleteSecret
- key: str¶
- table_name: str¶
RateLimit¶
Rate limiter module that enforces per-client request limits using a sliding-window algorithm.
- vaultapi.rate_limit._get_identifier(request: Request) str¶
Build a unique string key for a request based on the client IP and path.
- Parameters:
request – Incoming FastAPI request object.
- Returns:
"<ip>:<path>"string, using the first IP fromX-Forwarded-Forwhen present.- Return type:
str
- class vaultapi.rate_limit.RateLimiter(rps: RateLimit)¶
Rate limiter for incoming requests.
>>> RateLimiter
- init(request: Request) None¶
Check whether the request exceeds the rate limit for its identifier.
- Parameters:
request – Incoming FastAPI request object.
- Raises:
HTTPException –
- 429 – Too many requests within the configured window.
Routes¶
Routes module that constructs and returns the FastAPI APIRoute lists for API and UI endpoints.
- vaultapi.routes.ui_routes() List[APIRoute]¶
Build the list of UI routes for the FastAPI application.
- Returns:
All UI
APIRouteobjects to be registered on the application.- Return type:
List[APIRoute]
- vaultapi.routes.api_routes() List[APIRoute]¶
Build the list of API routes for the FastAPI application.
- Returns:
All API
APIRouteobjects to be registered on the application.- Return type:
List[APIRoute]
SwaggerUI¶
Swagger UI module that customizes the docs endpoint and generates the API description.
- async vaultapi.swagger_ui.get_swagger_html(app: FastAPI) HTMLResponse¶
Render the customized Swagger UI HTML page.
See also
Injects a custom JavaScript snippet (
swagger_ui.js) before</body>to enable smooth scrolling to an operation when a hyperlink from the description block is clicked.- Parameters:
app – FastAPI application instance used to extract the title and OpenAPI URL.
- Returns:
HTML page with the customized Swagger UI and injected JavaScript.
- Return type:
HTMLResponse
- async vaultapi.swagger_ui.docs_redirect() RedirectResponse¶
Redirect the root path to the
/docspage.- Returns:
302 redirect to
/docs.- Return type:
RedirectResponse
- vaultapi.swagger_ui.docs_handler(api: FastAPI, func: Callable) None¶
Replace the default Swagger UI route with the custom docs endpoint.
- Parameters:
api – FastAPI application instance whose route list is modified in-place.
func – Callable to register as the new
/docsendpoint handler.
- vaultapi.swagger_ui.generate_hyperlink(route: APIRoute) str¶
Generate a Swagger UI deep-link anchor tag for an API route.
- Parameters:
route – The
APIRouteobject to generate the hyperlink for.- Returns:
HTML anchor tag string pointing to the route’s Swagger UI operation.
- Return type:
str
- vaultapi.swagger_ui.get_desc(api_routes: List[APIRoute]) str¶
Build the full API description string for the Swagger UI overview.
- Parameters:
api_routes – List of registered API routes used to generate the feature links.
- Returns:
Markdown/HTML description string assigned to the FastAPI application.
- Return type:
str
Transit¶
Module that performs transit encryption/decryption.
This allows the server to securely transmit retrieved secrets to be decrypted at the client side using the API key.
- vaultapi.transit.string_to_aes_key(input_string: str, key_length: int) ByteString¶
Derive an AES key from a string by SHA-256 hashing and truncating.
See also
- AES supports three key lengths:
128 bits (16 bytes)
192 bits (24 bytes)
256 bits (32 bytes)
- Parameters:
input_string – Input string to hash.
key_length – Number of bytes to take from the SHA-256 digest.
- Returns:
First
key_lengthbytes of the SHA-256 digest ofinput_string.- Return type:
ByteString
- vaultapi.transit.encrypt(payload: Dict[str, Any], url_safe: bool = True) Union[ByteString, str]¶
Encrypt a payload dict using AES-GCM with a time-bucketed derived key.
- Parameters:
payload – Dictionary to encrypt.
url_safe – When
True, returns a Base64-encoded string; otherwise returns raw bytes.
- Returns:
Ciphertext as a URL-safe Base64 string when
url_safeisTrue, or raw bytes otherwise.- Return type:
ByteString | str
- vaultapi.transit.decrypt(ciphertext: Union[ByteString, str]) Dict[str, Any]¶
Decrypt AES-GCM ciphertext produced by
encrypt.- Parameters:
ciphertext – Base64-encoded string or raw bytes produced by
encrypt.- Returns:
Deserialized JSON payload.
- Return type:
Dict[str, Any]
- Raises:
InvalidTag – If the ciphertext was produced with a different key or is corrupted.
Util¶
Utility module that provides helper functions for bulk secret import and transit decryption.
- vaultapi.util.dotenv_to_table(table_name: str, dotenv_file: str, drop_existing: bool = False) None¶
Load all key-value pairs from a
.envfile into a database table.When
drop_existingisTruethe table is dropped and recreated before loading. Otherwise, existing secrets in the table are overwritten in-place.- Parameters:
table_name – Name of the destination table.
dotenv_file – Path to the
.envfile to load.drop_existing – If
True, drop and recreate the table before importing.
- vaultapi.util.transit_decrypt(ciphertext: Union[str, ByteString]) Dict[str, Any]¶
Decrypt an AES-GCM transit-encrypted ciphertext using the API key and current time bucket.
- Parameters:
ciphertext – Base64-encoded string or raw bytes to decrypt.
- Returns:
Deserialized JSON payload from the decrypted ciphertext.
- Return type:
Dict[str, Any]