Storage
The Storage Module provides unified file and image uploads with automatic validation, image resizing and compression, deterministic thumbnail generation, per-user path scoping, and a pluggable storage architecture.
Kirak currently launches with an initial set of 10 supported storage backends (Local disk, AWS S3, Cloudflare R2, Google Cloud Storage, Azure Blob Storage, Wasabi, DigitalOcean Spaces, Backblaze B2, Cubbit, and OVHcloud), with more storage adapters continuously being added by the core team and community contributors. Custom backends can also be added easily using Kirak’s modular provider architecture.
Installation & Setup
Section titled “Installation & Setup”Install provider-specific extras as needed:
pip install "kirak[storage]" # Local, AWS S3, Wasabi, R2, Spaces, Cubbit, OVH, B2pip install "kirak[storage-gcs]" # Google Cloud Storagepip install "kirak[storage-azure]" # Azure Blob Storagepip install "kirak[all-storage]" # All storage backendsEnable the module in kirak.json:
{ "modules": ["storage"]}Architectural Lifecycle & Ingestion Pipeline
Section titled “Architectural Lifecycle & Ingestion Pipeline”When an asset is uploaded through the Storage module, Kirak runs it through an automated security and processing pipeline before persisting it to the designated provider instance.
flowchart TD Start["Call upload_image() or upload_file()"] --> AuthCheck{"Is caller<br/>authenticated?"} AuthCheck -- "Guest" --> Refuse401["Refuse with 401<br/>AuthenticationError"] AuthCheck -- "Authenticated" --> ScopeCheck{"Caller Role"}
ScopeCheck -- "admin / system" --> UseRawPath["Use Path as Provided"] ScopeCheck -- "regular user" --> PrependPrefix["Confine to User Scope<br/>Prefix with {user_id}/"]
PrependPrefix --> CheckTraversal{"Contains '..' segment?"} UseRawPath --> CheckTraversal CheckTraversal -- "Yes" --> TraversalErr["Raise 400 ValidationError<br/>(path traversal forbidden)"] CheckTraversal -- "No" --> ValidateFile["Validate MIME Type & File Size<br/>(magic bytes + allowed extensions)"]
ValidateFile --> IsImage{"Is image upload?"}
IsImage -- "No (upload_file)" --> ProviderUpload["Dispatch to Storage Provider<br/>(Local / S3 / R2 / GCS / Azure)"] IsImage -- "Yes (upload_image)" --> PillowProcess["Pillow Processing<br/>- Compress quality (e.g. 85)<br/>- Resize to max width/height<br/>- Keep aspect ratio"]
PillowProcess --> ProviderUpload ProviderUpload --> ThumbCheck{"Thumbnails<br/>requested?"}
ThumbCheck -- "No" --> FinalizeResult["Return Success Envelope<br/>(path, provider, original URL)"] ThumbCheck -- "Yes (Sync Mode)" --> GenSyncThumbs["Generate & Upload Thumbnails<br/>(thumbnails/name/sm.jpg, thumbnails/name/md.jpg)"] ThumbCheck -- "Yes (Background Mode)" --> GenAsyncThumbs["Add FastAPI BackgroundTask<br/>Mint deterministic signed URLs immediately"]
GenSyncThumbs --> FinalizeResult GenAsyncThumbs --> FinalizeResultThe Path vs. URL Architectural Contract
Section titled “The Path vs. URL Architectural Contract”[!IMPORTANT] Golden Rule for Private Storage: Always persist the canonical
pathin your database (users.avatar_path), never the temporary presignedurl.On private storage instances (the default),
urlis a time-limited signed link that expires aftersigned_url_ttl(default 3600 seconds). Saving an ephemeral signed URL into your database results in dead links once the signature expires. Persist thepathandprovider, then callget_urlon read to mint fresh access URLs.
sequenceDiagram autonumber actor Client as Frontend / Client participant API as Kirak API Server participant DB as App Database participant S3 as Storage Bucket (S3/R2/GCS)
Note over Client,S3: 1. Upload Phase (Write Path) Client->>API: POST /storage/upload/image (photo.jpg) API->>API: Enforce user scoping: 42/avatars/photo.jpg API->>S3: Upload binary & thumbnails S3-->>API: 200 OK API-->>Client: Return envelope {path: "42/avatars/photo.jpg", provider: "main"} Client->>API: PATCH /users/me {avatar_path: "42/avatars/photo.jpg"} API->>DB: UPDATE users SET avatar_path = '42/avatars/photo.jpg'
Note over Client,S3: 2. Retrieval Phase (Read Path) Client->>API: GET /users/me API->>DB: SELECT avatar_path FROM users WHERE id = 42 DB-->>API: "42/avatars/photo.jpg" API->>API: kirak.storage.get_url({path: "42/avatars/photo.jpg", expires: 3600}) API-->>Client: Return fresh signed URL (valid for 1 hour) Client->>S3: GET https://bucket.s3.amazonaws.com/42/avatars/photo.jpg?X-Amz-Signature=... S3-->>Client: 200 OK (Image Rendered)Configuring Providers
Section titled “Configuring Providers”kirak.json declares the active storage provider instances and specifies the default. Secrets are never committed to kirak.json; they come from environment variables matching KIRAK_STORAGE_<INSTANCE>_<FIELD>.
{ "storage": { "default_provider": "main", "thumbnail_mode": "sync", "default_thumbnails": "sm:100x100,md:300x300,lg:600x600", "image_max_size": "5mb", "file_max_size": "15mb", "signed_url_ttl": 3600,
"providers": { "main": { "type": "aws", "aws_bucket": "app-media-private", "aws_region": "us-east-1", "visibility": "private" }, "cdn_public": { "type": "r2", "account_id": "abc123xyz456", "aws_bucket": "public-assets", "public_url": "https://cdn.example.com", "visibility": "public" }, "local": { "type": "local", "upload_dir": "assets/media", "visibility": "private" } } }}View All Supported Storage Provider Types & Settings
storage key |
Type | Description |
|---|---|---|
default_provider |
string | Instance name used when a call names no provider. Must be one of the instances under providers. |
providers |
object | Storage provider instances (types local, aws, wasabi, r2, spaces, cubbit, ovh, b2, gcs, azure, or a custom type), by instance name. |
image_allowed_types |
string | Allowed image extensions, comma-separated. Default “jpg,jpeg,png,webp,gif”. svg is refused: store vector files with upload_file. |
image_max_size |
string | Maximum image upload size, e.g. “5mb”. Default “5mb”. |
image_compress_quality |
integer | JPEG/WebP compression quality. Default 85. |
image_max_width |
integer | Maximum stored image width in pixels; larger images are scaled down. Default 2000. |
image_max_height |
integer | Maximum stored image height in pixels; larger images are scaled down. Default 2000. |
file_allowed_types |
string | Allowed non-image extensions, comma-separated. Default “pdf,doc,docx,xls,xlsx,csv,txt,zip”. |
file_max_size |
string | Maximum file upload size, e.g. “25mb”. Default “10mb”. |
default_thumbnails |
string or null | Thumbnails generated for every image upload, e.g. “sm:100x100,md:300x300”. Default none. |
thumbnail_mode |
string | sync makes thumbnails before responding; background responds first. Default sync. |
signed_url_ttl |
integer | Lifetime in seconds of a signed URL for a private instance when get_url is called without expires. Default 3600 (1 hour). |
<INSTANCE> is the provider instance’s name in kirak.json, upper-cased: an instance
named main reads ..._MAIN_....
local (no extra install) – Files on the app’s own disk, served at /media/
Credential check (check()): upload_dir is (or can be created) readable and writable where the check runs.
| Name | Where | Required / default | Description |
|---|---|---|---|
upload_dir |
kirak.json | default assets/media |
Directory uploads are written to. Two local instances need different ones. |
visibility |
kirak.json | default private |
public or private. private (the default): get_url returns a signed URL that expires after storage.signed_url_ttl, and a local instance serves files only through a signature-checked route; nobody can read a file by guessing its path. public: get_url returns a permanent, unauthenticated URL, and a local instance serves its directory as static files. Choose public deliberately for assets meant to be world-readable. |
aws (pip install "kirak[storage]") – Amazon S3, or any S3-compatible service through endpoint_url.
Credential check (check()): ListObjectsV2 (MaxKeys=1); with write, PutObject and DeleteObject of one object.
| Name | Where | Required / default | Description |
|---|---|---|---|
aws_bucket |
kirak.json | required | Bucket name. |
aws_region |
kirak.json | default us-east-1 |
Bucket region. |
endpoint_url |
kirak.json | Custom S3 endpoint; leave unset for AWS. | |
public_url |
kirak.json | Base URL of returned file URLs, e.g. a CDN or custom domain in front of the bucket. Unset: the bucket’s own URL. | |
acl |
kirak.json | Canned ACL set on each upload: private or public-read. Unset: none is sent, as buckets with ACLs disabled (the AWS default) require. | |
visibility |
kirak.json | default private |
public or private. private (the default): get_url returns a signed URL that expires after storage.signed_url_ttl, and a local instance serves files only through a signature-checked route; nobody can read a file by guessing its path. public: get_url returns a permanent, unauthenticated URL, and a local instance serves its directory as static files. Choose public deliberately for assets meant to be world-readable. |
KIRAK_STORAGE_<INSTANCE>_ACCESS_KEY |
environment | Access key ID. Optional: boto3’s default credential chain is used when unset. | |
KIRAK_STORAGE_<INSTANCE>_SECRET_KEY |
environment | Secret access key. Set together with the access key. |
wasabi (pip install "kirak[storage]") – Wasabi object storage (S3-compatible).
Credential check (check()): ListObjectsV2 (MaxKeys=1); with write, PutObject and DeleteObject of one object.
| Name | Where | Required / default | Description |
|---|---|---|---|
aws_bucket |
kirak.json | required | Bucket name. |
aws_region |
kirak.json | default us-east-1 |
Bucket region. |
endpoint_url |
kirak.json | default https://s3.wasabisys.com |
Wasabi endpoint. |
public_url |
kirak.json | Base URL of returned file URLs, e.g. a CDN or custom domain in front of the bucket. Unset: the bucket’s own URL. | |
acl |
kirak.json | Canned ACL set on each upload: private or public-read. Unset: none is sent, as buckets with ACLs disabled (the AWS default) require. | |
visibility |
kirak.json | default private |
public or private. private (the default): get_url returns a signed URL that expires after storage.signed_url_ttl, and a local instance serves files only through a signature-checked route; nobody can read a file by guessing its path. public: get_url returns a permanent, unauthenticated URL, and a local instance serves its directory as static files. Choose public deliberately for assets meant to be world-readable. |
KIRAK_STORAGE_<INSTANCE>_ACCESS_KEY |
environment | Access key ID. Optional: boto3’s default credential chain is used when unset. | |
KIRAK_STORAGE_<INSTANCE>_SECRET_KEY |
environment | Secret access key. Set together with the access key. |
r2 (pip install "kirak[storage]") – Cloudflare R2 (S3-compatible). Returned URLs are public only through public_url.
Credential check (check()): ListObjectsV2 (MaxKeys=1); with write, PutObject and DeleteObject of one object.
| Name | Where | Required / default | Description |
|---|---|---|---|
account_id |
kirak.json | required | Cloudflare account id (32 hex characters); sets the endpoint. |
aws_bucket |
kirak.json | required | Bucket name. |
jurisdiction |
kirak.json | default default |
Where the bucket’s data is kept: default, eu or fedramp. Must match the bucket. |
aws_region |
kirak.json | default auto |
Leave unset: R2 ignores it. |
endpoint_url |
kirak.json | Leave unset: built from account_id and jurisdiction. | |
public_url |
kirak.json | Base URL of returned file URLs: the bucket’s r2.dev subdomain or a custom domain bound to it. Unset: URLs point at the S3 endpoint, which is never public; use get_url with expires. | |
acl |
kirak.json | Leave unset: R2 has no object ACLs, so setting it is an error. | |
visibility |
kirak.json | default private |
public or private. private (the default): get_url returns a signed URL that expires after storage.signed_url_ttl, and a local instance serves files only through a signature-checked route; nobody can read a file by guessing its path. public: get_url returns a permanent, unauthenticated URL, and a local instance serves its directory as static files. Choose public deliberately for assets meant to be world-readable. |
KIRAK_STORAGE_<INSTANCE>_ACCESS_KEY |
environment | required | Access key ID. |
KIRAK_STORAGE_<INSTANCE>_SECRET_KEY |
environment | required | Secret access key. |
spaces (pip install "kirak[storage]") – DigitalOcean Spaces (S3-compatible).
Credential check (check()): ListObjectsV2 (MaxKeys=1); with write, PutObject and DeleteObject of one object.
| Name | Where | Required / default | Description |
|---|---|---|---|
aws_bucket |
kirak.json | required | Space (bucket) name. |
aws_region |
kirak.json | required | Datacenter region of the Space, e.g. nyc3 or fra1; sets the endpoint. |
endpoint_url |
kirak.json | Leave unset: https://<aws_region>.digitaloceanspaces.com. | |
public_url |
kirak.json | Base URL of returned file URLs, e.g. the Spaces CDN https:// |
|
acl |
kirak.json | default public-read |
Canned ACL set on each upload: public-read (files readable by URL) or private. |
visibility |
kirak.json | default private |
public or private. private (the default): get_url returns a signed URL that expires after storage.signed_url_ttl, and a local instance serves files only through a signature-checked route; nobody can read a file by guessing its path. public: get_url returns a permanent, unauthenticated URL, and a local instance serves its directory as static files. Choose public deliberately for assets meant to be world-readable. |
KIRAK_STORAGE_<INSTANCE>_ACCESS_KEY |
environment | required | Access key ID. |
KIRAK_STORAGE_<INSTANCE>_SECRET_KEY |
environment | required | Secret access key. |
cubbit (pip install "kirak[storage]") – Cubbit DS3, European geo-distributed object storage (S3-compatible).
Credential check (check()): ListObjectsV2 (MaxKeys=1); with write, PutObject and DeleteObject of one object.
| Name | Where | Required / default | Description |
|---|---|---|---|
aws_bucket |
kirak.json | required | Bucket name. |
aws_region |
kirak.json | default eu-west-1 |
Signing region. |
endpoint_url |
kirak.json | default https://s3.cubbit.eu |
Cubbit endpoint; https://s3. |
public_url |
kirak.json | Base URL of returned file URLs, e.g. a CDN or custom domain in front of the bucket. Unset: the bucket’s own URL. | |
acl |
kirak.json | Canned ACL set on each upload: private or public-read. Unset: none is sent, as buckets with ACLs disabled (the AWS default) require. | |
visibility |
kirak.json | default private |
public or private. private (the default): get_url returns a signed URL that expires after storage.signed_url_ttl, and a local instance serves files only through a signature-checked route; nobody can read a file by guessing its path. public: get_url returns a permanent, unauthenticated URL, and a local instance serves its directory as static files. Choose public deliberately for assets meant to be world-readable. |
KIRAK_STORAGE_<INSTANCE>_ACCESS_KEY |
environment | required | Access key ID. |
KIRAK_STORAGE_<INSTANCE>_SECRET_KEY |
environment | required | Secret access key. |
ovh (pip install "kirak[storage]") – OVHcloud Object Storage (S3-compatible).
Credential check (check()): ListObjectsV2 (MaxKeys=1); with write, PutObject and DeleteObject of one object.
| Name | Where | Required / default | Description |
|---|---|---|---|
aws_bucket |
kirak.json | required | Bucket name. |
aws_region |
kirak.json | required | Region code in lower case, e.g. gra, sbg, de, uk or eu-west-par; sets the endpoint. |
endpoint_url |
kirak.json | Leave unset: https://s3.<aws_region>.io.cloud.ovh.net. | |
public_url |
kirak.json | Base URL of returned file URLs, e.g. a CDN or custom domain. Unset: https:// |
|
acl |
kirak.json | Canned ACL set on each upload: private or public-read. Unset: none is sent (files are private unless a bucket policy makes them public). | |
visibility |
kirak.json | default private |
public or private. private (the default): get_url returns a signed URL that expires after storage.signed_url_ttl, and a local instance serves files only through a signature-checked route; nobody can read a file by guessing its path. public: get_url returns a permanent, unauthenticated URL, and a local instance serves its directory as static files. Choose public deliberately for assets meant to be world-readable. |
KIRAK_STORAGE_<INSTANCE>_ACCESS_KEY |
environment | required | Access key ID. |
KIRAK_STORAGE_<INSTANCE>_SECRET_KEY |
environment | required | Secret access key. |
b2 (pip install "kirak[storage]") – Backblaze B2 (S3-compatible).
Credential check (check()): ListObjectsV2 (MaxKeys=1); with write, PutObject and DeleteObject of one object.
| Name | Where | Required / default | Description |
|---|---|---|---|
aws_bucket |
kirak.json | required | Bucket name. |
aws_region |
kirak.json | required | Region of the bucket’s S3 endpoint, e.g. us-west-004; sets the endpoint. |
endpoint_url |
kirak.json | Leave unset: https://s3.<aws_region>.backblazeb2.com. | |
public_url |
kirak.json | Base URL of returned file URLs, e.g. a CDN or the bucket’s friendly URL https://f004.backblazeb2.com/file/ |
|
acl |
kirak.json | Leave unset: B2 sets ACLs per bucket, so setting it is an error. | |
visibility |
kirak.json | default private |
public or private. private (the default): get_url returns a signed URL that expires after storage.signed_url_ttl, and a local instance serves files only through a signature-checked route; nobody can read a file by guessing its path. public: get_url returns a permanent, unauthenticated URL, and a local instance serves its directory as static files. Choose public deliberately for assets meant to be world-readable. |
KIRAK_STORAGE_<INSTANCE>_ACCESS_KEY |
environment | required | Application key ID (keyID). |
KIRAK_STORAGE_<INSTANCE>_SECRET_KEY |
environment | required | Application key (applicationKey). |
gcs (pip install "kirak[storage-gcs]") – Google Cloud Storage, with a service account key or Application Default Credentials.
Credential check (check()): objects.list (maxResults=1); with write, objects.insert and objects.delete of one object; under ADC with signing_service_account, IAM signBlob of one URL.
| Name | Where | Required / default | Description |
|---|---|---|---|
bucket |
kirak.json | required | Bucket name. |
project_id |
kirak.json | Project id. Unset: the key’s project, or the ADC project. | |
public_url |
kirak.json | Base URL of returned file URLs, e.g. a Cloud CDN or load balancer domain. Unset: https://storage.googleapis.com/ |
|
signing_service_account |
kirak.json | Service account email that signs URLs (get_url with expires) under Application Default Credentials; the app’s identity needs iam.serviceAccounts.signBlob on it. Not needed with credentials_json. | |
visibility |
kirak.json | default private |
public or private. private (the default): get_url returns a signed URL that expires after storage.signed_url_ttl, and a local instance serves files only through a signature-checked route; nobody can read a file by guessing its path. public: get_url returns a permanent, unauthenticated URL, and a local instance serves its directory as static files. Choose public deliberately for assets meant to be world-readable. |
KIRAK_STORAGE_<INSTANCE>_CREDENTIALS_JSON |
environment | Service account key file contents (JSON). Optional: Application Default Credentials are used when unset. |
azure (pip install "kirak[storage-azure]") – Azure Blob Storage, with a connection string, an account key or the app’s Azure identity.
Credential check (check()): List Blobs (maxresults=1); with write, Put Blob and Delete Blob of one blob; under an Azure identity, Get User Delegation Key.
| Name | Where | Required / default | Description |
|---|---|---|---|
container |
kirak.json | required | Container name. |
account_name |
kirak.json | Storage account name. Required unless connection_string is set. | |
account_url |
kirak.json | Blob endpoint, for sovereign clouds or Azurite. Unset: https://<account_name>.blob.core.windows.net. | |
public_url |
kirak.json | Base URL of returned file URLs, e.g. an Azure Front Door or CDN domain. Unset: the blob’s own URL, readable only if the container allows anonymous blob access. | |
visibility |
kirak.json | default private |
public or private. private (the default): get_url returns a signed URL that expires after storage.signed_url_ttl, and a local instance serves files only through a signature-checked route; nobody can read a file by guessing its path. public: get_url returns a permanent, unauthenticated URL, and a local instance serves its directory as static files. Choose public deliberately for assets meant to be world-readable. |
KIRAK_STORAGE_<INSTANCE>_CONNECTION_STRING |
environment | Storage account connection string. Optional: account_name with account_key, or the app’s Azure identity, is used when unset. | |
KIRAK_STORAGE_<INSTANCE>_ACCOUNT_KEY |
environment | Storage account access key, used with account_name. Optional: without it the app’s Azure identity (DefaultAzureCredential) is used. |
Visibility: Public vs. Private
Section titled “Visibility: Public vs. Private”Every instance is configured as either public or private. private is the default.
| Attribute | private (Default) |
public |
|---|---|---|
| Security Model | Access requires a valid, time-limited cryptographic signature. | World-readable without authentication. |
get_url Response |
Returns a signed URL that expires after expires (or signed_url_ttl). |
Returns a permanent, unauthenticated URL. |
| Local Serving | Served at /media/<instance> via a route that verifies HMAC exp and sig query tokens. |
Mounted as a FastAPI StaticFiles endpoint. |
| Served Headers (both) | Every file has Content-Security-Policy: sandbox. Only PNG, JPEG, GIF, WebP and PDF show inline; any other type is sent with Content-Disposition: attachment. |
The same headers. |
| Cloud Serving | Generates an S3 Signature V4 Presigned URL, GCS Signed URL, or Azure SAS URL. | Returns direct bucket URL or <public_url>/<path> (CDN endpoint). |
| Database Storage | Store the relative path only (path). Mint signed URLs on read. |
Storing the static url directly is permissible. |
Per-Caller Path Scoping & Security Boundaries
Section titled “Per-Caller Path Scoping & Security Boundaries”Storage operations enforce strict isolation between users:
- Authentication Required: All 5 operations (
upload_image,upload_file,delete,get_url,list) refuse guest callers with401 AuthenticationError. In background tasks or system scripts, wrap calls withwith as_system():orwith user_context(caller):. - Per-User Directory Confinement: For any caller who is not an
adminorsystem, Kirak prefixes the path with{user_id}/. A regular user uploading toavatars/me.jpgis automatically scoped to42/avatars/me.jpg. A user can never read, list, delete, or overwrite files belonging to other users. - Directory Traversal Prevention: Any path containing
..segments is rejected immediately with400 ValidationError. - Stored Path Matches the File Type: The
pathmust end in the uploaded file’s extension (compared without case), so a file is served as the type it was validated as. A path with no extension takes the filename’s extension:reports/q3withq3.pdfis stored asreports/q3.pdf. A different extension, or a path that names no file, is400 ValidationError.upload_fileandupload_imageboth apply this. - Automated Account Purge: When an account is deleted via
kirak.auth, Kirak automatically wipes all files and thumbnails stored under{user_id}/across all storage providers.
upload_image
Section titled “upload_image”Uploads an image, applies compression and resizing, and deterministically generates thumbnail variants.
result = await kirak.storage.upload_image({ "file": file_bytes, # Raw image bytes from form upload "path": "avatars/photo.jpg", # Logical path (scoped to {user_id}/avatars/photo.jpg) "filename": "my_photo.jpg", # Used for extension & format detection "thumbnails": [ {"name": "sm", "width": 100, "height": 100}, {"name": "md", "width": 300, "height": 300}, {"name": "lg", "width": 600, "height": 600}, ], "background_tasks": background_tasks, # Required for thumbnail_mode="background" "provider": "main", # Optional provider instance override})Parameters
Section titled “Parameters”| Parameter | Type | Default | Description |
|---|---|---|---|
file |
bytes |
Required | Raw image binary content. |
path |
str |
Required | Logical storage key (e.g. "images/blog/cover.jpg"). |
filename |
str |
"image.jpg" |
Original filename used for format validation. |
thumbnails |
list / bool / None |
None |
None for no thumbnails, True to use default_thumbnails from kirak.json, or a custom list of size dicts. |
background_tasks |
BackgroundTasks |
None |
FastAPI BackgroundTasks instance (required for async background thumbnail processing). |
provider |
str |
default_provider |
Named provider instance from kirak.json. |
Sync vs. Background Thumbnail Modes
Section titled “Sync vs. Background Thumbnail Modes”syncMode (Default): All thumbnails are generated and uploaded to the storage bucket before the API responds.backgroundMode: The original image is processed and uploaded immediately. Thumbnail URLs are mathematically pre-computed (e.g.thumbnails/filename/sm.jpg) and returned in the initial response with"processing": true. Actual thumbnail generation runs as a background task. Thumbnail URLs return 404 until background processing completes.
{ "statusCode": 200, "status": "success", "message": "Image uploaded successfully", "data": { "original": "https://storage.googleapis.com/app-media/42/avatars/photo.jpg?Signature=...", "path": "42/avatars/photo.jpg", "thumbnails": { "sm": "https://storage.googleapis.com/app-media/42/avatars/thumbnails/photo/sm.jpg?Signature=...", "md": "https://storage.googleapis.com/app-media/42/avatars/thumbnails/photo/md.jpg?Signature=...", "lg": "https://storage.googleapis.com/app-media/42/avatars/thumbnails/photo/lg.jpg?Signature=..." }, "provider": "main" }}Where thumbnails are stored
Section titled “Where thumbnails are stored”Each thumbnail sits in a thumbnails folder beside the original, inside a subfolder named after the original without its extension, and is named after its size. For an upload to images/avatars/user_42.jpg by user 42:
| Item | Stored key |
|---|---|
| Original | 42/images/avatars/user_42.jpg |
Size sm |
42/images/avatars/thumbnails/user_42/sm.jpg |
Custom size banner_custom |
42/images/avatars/thumbnails/user_42/banner_custom.jpg |
All thumbnails of one image share that folder, so delete with with_thumbnails=True removes every one, including custom sizes and sizes no longer in default_thumbnails. Each thumbnail name may use only letters, digits, _ and -; any other name is refused with a ValidationError before anything is stored.
upload_file
Section titled “upload_file”Uploads documents or arbitrary binary files (PDFs, spreadsheets, ZIP archives) without image compression:
result = await kirak.storage.upload_file({ "file": file_bytes, "path": "reports/quarterly_q3.pdf", "filename": "quarterly_q3.pdf", "provider": "main",})Response:
{ "statusCode": 200, "status": "success", "data": { "url": "https://bucket.s3.amazonaws.com/42/reports/quarterly_q3.pdf?...", "path": "42/reports/quarterly_q3.pdf", "filename": "quarterly_q3.pdf", "size": 1048576, "mime_type": "application/pdf", "provider": "main" }}delete
Section titled “delete”Deletes a stored object and optionally its associated thumbnail variants:
result = await kirak.storage.delete({ "path": "avatars/photo.jpg", "with_thumbnails": True, "provider": "main",})Deleting a file that does not exist succeeds on every provider: the file is gone either way.
Note on Thumbnail Deletion: When
with_thumbnails=Trueis passed, Kirak deletes every file in the image’s thumbnail folder (avatars/thumbnails/photo/here), whatever sizes they were made at, including custom sizes. Thumbnails are stored there by upload; see Where thumbnails are stored.
get_url
Section titled “get_url”Generates an accessible URL for a stored asset:
# Default signed URL using signed_url_ttl from kirak.json (default 3600s)result = await kirak.storage.get_url({ "path": "reports/quarterly_q3.pdf", "provider": "main",})url = result["data"]["url"]
# Custom short-lived URL (e.g. 15 minutes)result = await kirak.storage.get_url({ "path": "kyc/passport.pdf", "expires": 900,})Lists all stored files matching a given prefix:
result = await kirak.storage.list({ "prefix": "reports/", "provider": "main",})# result["data"]["files"] -> [{"path": "42/reports/q1.pdf", "size": 20480, "url": "...",# "last_modified": "2026-11-24T10:00:00+00:00"}, ...]# The same keys on every provider (local storage also adds "mime_type").HTTP REST Endpoints
Section titled “HTTP REST Endpoints”All endpoints require a valid credential (Bearer JWT, session cookie, or API key) and are rate-limited to 60 uploads per minute per user to protect against resource exhaustion:
| Method | Path | Query / Form Parameters | Description |
|---|---|---|---|
POST |
/storage/upload/image |
Form: file (multipart), path, thumbnails, provider |
Upload & process image |
POST |
/storage/upload/file |
Form: file (multipart), path, provider |
Upload binary document |
DELETE |
/storage/delete |
Query: path, with_thumbnails, provider |
Delete file & all its thumbnails |
GET |
/storage/url |
Query: path, expires, provider |
Generate fresh signed URL |
GET |
/storage/list |
Query: prefix, provider |
List files under prefix |
Adding a Custom Storage Provider
Section titled “Adding a Custom Storage Provider”Subclass StorageProvider from kirak.storage.providers.base and implement the 4 core methods:
from kirak.storage.providers.base import StorageProvider
class MinioProvider(StorageProvider): TYPE_NAME = "minio" SECRET_FIELDS = ("access_key", "secret_key")
def __init__(self, config, storage=None): super().__init__(config, storage) self._require("endpoint_url", "bucket")
async def upload(self, file_bytes: bytes, path: str, content_type: str = "application/octet-stream") -> str: # Upload binary to MinIO... return f"{self.config['endpoint_url']}/{self.config['bucket']}/{path}"
async def delete(self, path: str) -> bool: # Delete object from MinIO... return True
async def get_url(self, path: str, expires: int = None) -> str: # Generate presigned URL... return f"{self.config['endpoint_url']}/{self.config['bucket']}/{path}?token=..."
async def list_files(self, prefix: str = "") -> list: # List objects under prefix... return [{"path": f"{prefix}example.jpg", "size": 1024, "url": "...", "last_modified": None}]Register the provider in your application’s on_kirak_ready hook:
def on_kirak_ready(kirak): kirak.storage.register_provider("minio", MinioProvider)