Skip to content
SEUNGWOO CHOI edited this page Oct 23, 2026 · 4 revisions

API operations, deletion, backup, and recovery

English · 한국어

Default storage is PostgreSQL plus a local blob volume. Commands run from the API checkout with .env.production and compose.production.yaml; replace the Compose filename with compose.api.yaml for API-only deployment. See deployment.

Account deletion contract

  1. While signed in, request a fresh code with POST /api/v1/auth/code/request. Consumed sign-in codes cannot be reused; existing email/IP limits and the sixty-second resend interval apply.
  2. Send DELETE /api/v1/account with JSON {"code":"123456"}, exact Origin, session cookie, and X-CSRF-Token. Multi-account clients also send X-Miroven-User-ID. Code lifetime/attempt limits match login; an additional per-account hourly deletion-attempt limit applies.
  3. A 202 immediately revokes all sessions. Deletion state and the job are created in one transaction. Uploads recheck sessions before storage, preventing new files after deletion acceptance.
  4. Use the returned deletion_token in Authorization: Bearer … to query GET /api/v1/account/deletion. Cookies/URL parameters cannot authorize it. The token grants no other API access, is not stored plaintext in the DB, and is valid for thirty days.
  5. The worker deletes files, then cascades users, sessions, vault, entries, operation results, change history, and snapshots, also removing email codes/mail jobs. For more than 100 files, remove references first and process batches of 100. Repeating an external file deletion after a pre-commit crash is safe. Empty local directories can remain.

Storage deletion failures retry with exponential delay up to one hour. Ten consecutive failures mark a job failed while access remains blocked. Unfinished jobs are not removed merely because receipts expire; completed receipts are cleaned one day after expiry. Receipt IDs equal user UUIDs so old backups can reapply deletions. Completion retains no user FK, email, or file list, but UUIDs still require restricted access.

After correcting the failure, retry a failed job:

docker compose --env-file .env.production -f compose.production.yaml run --rm --no-deps worker python -m app.worker --retry-deletion DELETION_UUID

DB errors/process termination roll back and release jobs for another worker; jobs are not permanently held in a processing state. Workers separate claims with SKIP LOCKED. SMTP acceptance before commit may duplicate a single-use code email. Request a new code when the old one expires or is exhausted.

Usage, logging, and monitoring

GET /api/v1/account/usage returns storage_bytes, storage_limit_bytes, entries, entry_limit, blob_max_bytes, effective plan, subscription_status, current_period_end, and cancel_at_period_end. Limits are the effective per-account values, including active overrides. Reserved/unlinked uploads and old photos retained by history/snapshots count toward bytes. Entry counts include tombstones. Lowering quotas never deletes existing data; user locks serialize reservations/new entries, and idempotent retries do not double-charge. Vault/authentication data and DB size are not blob usage.

Use the image's python -m app.server entry point, which logs only request ID, HTTP method, route template, and status. It excludes raw URL/query, blob UUID, bodies, email, codes, cookies, headers, exception messages, tracebacks, and raw SQLAlchemy/SMTP errors. Worker errors expose class names only. Direct uvicorn execution bypasses this setup. Production nginx/Caddy raw access/error logs are disabled. Development Mailpit retains plaintext emails and must not ship in production.

Monitor container state/restarts, readiness, HTTP 5xx/429, free disk, oldest pending job available_at, failed deletion jobs, last successful backup, and restore drills. Do not expose DB/API ports outside the proxy or print personal information during manual diagnosis.

Subscriptions and administrator operations

Current default limits in app/config.py are:

Effective plan Blob storage Journal entries, including tombstones Per encrypted file
Free 100 MiB 10,000 4 MiB
Pro 5 GiB 100,000 16 MiB

Operators can configure Free limits with MIROVEN_STORAGE_QUOTA_BYTES, MIROVEN_MAX_ENTRIES, MIROVEN_BLOB_MAX_BYTES, and Pro limits with the corresponding MIROVEN_PRO_... settings. Pro uses at least the configured Free limits. Per-account storage/entry overrides apply only while entitlement is active; there is no per-account file-size override. Use the returned limits rather than inferring quotas from the plan name. The profile is excluded from entry counts; encrypted document payloads are not blob usage. Lower limits never delete existing content.

app/subscriptions.py evaluates entitlements at request time. active, trialing, and past_due retain entitlement until a supplied period end; canceled retains it only with a future period end. An elapsed period end or explicit expired status removes entitlement, returns Free limits, and stops applying overrides. cancel_at_period_end alone does not end entitlement early. No payment checkout, provider billing integration or automatic charge collection is implemented.

Set MIROVEN_ADMIN_EMAILS to a comma-separated administrator allowlist and restart the API to apply configuration. An empty list disables GET /admin with 404. Open /admin on the API origin and authenticate using the ordinary email-code/session flow; initial signup still obeys the domain/local-part policy. The HTML page itself grants no privilege: each administrator API requires an allowlisted signed-in account, and mutations also require Origin and CSRF checks. Keep the website and preview origins outside credential CORS.

Operation Route
Metadata/usage/subscription statistics GET /api/v1/admin/stats
Search/filter/paginate accounts GET /api/v1/admin/users
Account metadata and effective limits GET /api/v1/admin/users/{user_id}
Set subscription and quota overrides PUT /api/v1/admin/users/{user_id}/subscription
Retry a failed account deletion POST /api/v1/admin/deletions/{deletion_id}/retry

The subscription PUT sets plan, status, optional period boundaries, cancel_at_period_end, storage/entry overrides, provider and note. It replaces those fields: omitted optional values reset to null/defaults rather than preserving old values. Read the existing account detail before editing; use contracts/openapi.json for exact constraints. Deletion retry accepts only a failed task, resetting its attempts and schedule; it does not restore the account. Statistics and user search expose emails and operational metadata to administrators, never decrypted journal/profile content or photos. Restrict access and keep those responses out of shared logs.

Paired DB and local-blob backup

The host needs Python 3.12 and Docker Compose. API/workers must belong only to this project. Stop external writers, replicas, and migrations first. The script stops running API/workers, creates pg_dump and a blob tar, then restarts only services previously running. The API is unavailable during backup; the DB container must stay running.

python scripts/backup_restore.py backup backups/2026-10-17 --env-file .env.production -f compose.production.yaml
python scripts/backup_restore.py verify backups/2026-10-17

Only new destination folders are allowed. Success requires db.dump, blobs.tar, and a SHA-256 manifest. Hashes detect integrity damage, not malicious tampering with a signed guarantee. Encrypt/restrict the full backup: even with encrypted blobs, the DB includes email, session verifiers, and mail jobs. Separately encrypt/store SECRET_KEY, environment, and image digests. Without the server secret, sessions, deletion receipts, and unsent jobs cannot be restored intact. On Windows, apply ACLs rather than relying on directory mode.

The script rejects S3. For S3, stop all writers and capture the DB dump plus a complete same-point-in-time copy of the dedicated bucket/prefix as one set. Verify each DB storage_key against size/SHA-256. Versioning, replication, and Object Lock may leave older versions behind delete markers; account for them in deletion/retention procedures. Actual provider backup/restore remains unverified; the validated default layout uses local blobs.

Backup retention and deletion ledger

Default operating policy: daily backups, at most seven days retention, no extra long-term archive. Online deletion completes with the worker; old backups can retain isolated ciphertext/email for up to seven days. Operators must remove expired backups daily and enforce the same policy for external copies/S3 versions. Configure expiration schedules on the host; this repository does not automatically delete unrelated host files.

Keep a current deletion ledger independently of backups. Export receipt UUIDs after deletion requests and at regular backups; automated export should replace it at least every five minutes. Requests after the last export may be absent after failure: collect/merge their receipts too. If that gap cannot be established, do not expose an old restored backup to users. The ledger must be newer than all retained backups and kept for thirty days.

# UUIDs only, no emails; encrypt and restrict the output separately.
docker compose --env-file .env.production -f compose.production.yaml run --rm --no-deps -T worker python scripts/deletion_ledger.py export > deletion-ledger.json

Restore and reapply deletions

Restore only to a new Compose project, empty DB, and empty blob volume. Never overwrite existing data. Verify project name, environment, domain, and volumes; start only the DB first. Use the same SECRET_KEY and compatible images.

docker compose --env-file .env.production -f compose.production.yaml -p miroven-restore up -d --wait db
python scripts/backup_restore.py restore backups/2026-10-17 --env-file .env.production -f compose.production.yaml -p miroven-restore
# Feed the latest ledger on stdin with the API still stopped.
docker compose --env-file .env.production -f compose.production.yaml -p miroven-restore run --rm --no-deps -T worker python scripts/deletion_ledger.py apply < deletion-ledger.json
docker compose --env-file .env.production -f compose.production.yaml -p miroven-restore run --rm --no-deps worker python scripts/check_integrity.py

The stdin example uses a POSIX shell. In PowerShell, use Get-Content -Raw deletion-ledger.json | docker compose ... run --rm --no-deps -T worker python scripts/deletion_ledger.py apply, substituting the full Compose options above for ....

Ledger application blocks restored accounts, revokes sessions, and recreates deletion jobs. Start the worker and confirm every ledger deletion is complete before checking migrations/readiness, email, login, and decryption on two devices, then connecting external traffic. Failed restoration does not auto-start services. Isolate partial volumes for diagnosis and retry in another empty project.

Upgrade and rollback

  1. Record image digests, schema revision, and environment. Export the latest deletion ledger, create a stopped-service backup, and verify it.
  2. Stop traffic and API/workers. Set new image tags in the environment; retain the DB.
  3. Run docker compose --env-file .env.production -f compose.production.yaml run --rm --no-deps migrate to apply the selected API source's full Alembic head, require exit zero, then up -d --wait with the same configuration. Attachment support alone is not the complete current schema; account/limit queries also require 0005_subscriptions.
  4. Check internal readiness/integrity, login, entry/photo decryption, and deletion status before opening traffic. Stop new-version writers on failure.
  5. Return to old images only if schema compatibility is confirmed. Never automatically perform destructive downgrades. Otherwise restore the old image/backup pair to a new project and reapply the latest deletion ledger. Ordinary writes after the backup can be lost; communicate the recovery point.

docker compose down preserves volumes. Do not attempt production recovery with down --volumes. Attachment v2 entries/history/snapshots block downgrading migration 0004_attachments; reverting requires the pre-deployment backup. See launch checks.

Encrypted profile

The per-account reserved UUID 00000000-0000-4000-8000-000000000001 is included in current encrypted documents, change history, snapshots, DB backup/restore, and account deletion. Its image is inside the payload, with no separate blob. No separate table/data migration is needed. It is excluded from journal entry limits/counts and blob usage. See profile contract.

Clone this wiki locally