videogen/docs/reelforge/SECURITY_AUDIT.md
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

17 KiB
Raw Permalink Blame History

ReelForge Security Audit

Historical audit: findings and verification totals are anchored to the 2026-08-13 review. Use CURRENT_STATE.md for current gates; security conclusions here remain point-in-time evidence.

Scope: the ReelForge slice of the MoneyPrinterTurbo codebase — billing/credits, async job pipeline, R2 object storage, and the FFmpeg compositor. This is an adversarial audit anchored on the money path, tenant isolation, and untrusted input reaching the shell/filtergraph.

Audit date: 2026-08-13 Anchor: security-audit pass over app/, tests/reelforge/, migrations/.

Verification snapshot

Reproduce with the SQLite-backed DB, dummy R2 env, and a token-encryption key set (the growth-phase OAuth surface requires SOCIAL_TOKEN_KEY):

NEON_DATABASE_URL='sqlite:///:memory:' R2_ACCOUNT_ID=x R2_ACCESS_KEY_ID=x \
  R2_SECRET_ACCESS_KEY=x R2_BUCKET=x SOCIAL_TOKEN_KEY=test-token-key \
  python -m pytest tests/reelforge
  • pytest (tests/reelforge): 1709 passed, 3 skipped (warnings are pre-existing Pydantic v2 class Config deprecations — no failures).
  • ruff --select F,E9 on app tests/reelforge migrations: All checks passed! (no unfixable findings; no --fix changes required).
  • Migrations: 22 files in migrations/versions, single head d4e8c1b9f6a2, the chain applies cleanly on a fresh DB, and alembic check reports "No new upgrade operations detected" (no model/migration drift).
  • Import smoke (app.controllers.v1.jobs, app.controllers.v1.billing, app.services.billing.service): IMPORT OK.

Quality gates run locally, not in CI (GitHub Actions is intentionally omitted this phase as a cost constraint): ruff --select F,E9 + pytest + alembic upgrade head / alembic check + the golden acceptance run.

Dimensions audited

  1. Money integrity — credit debit/grant/refund correctness and atomicity, no double-spend, no double-refund, no cross-account or cross-pool balance leakage.
  2. Payment webhooks — signature authenticity, replay/idempotency, and fail-closed behaviour on the credit-granting endpoint.
  3. IDOR / BOLA — object- and function-level authorization on jobs, brand assets, and user-supplied R2 keys; owner-scoping of every enumerable resource.
  4. SSRF / path traversal / injection — untrusted keys, filenames, and paths flowing into R2 presign/download and the FFmpeg -filter_complex graph.
  5. Secrets & input handling — provider keys/webhook secrets sourced only from config/env, boundary validation of external payloads.
  6. Concurrency — row-level locking and compare-and-swap on the balance and job-state transitions that gate the money path.

Confirmed defects and their fixes

D1 — Billing-attribution bug on job retry (MEDIUM, money)

Where: app/controllers/v1/jobs.py (retry_job).

Defect: The Job model has no workspace_id column, and retry_job performed no ledger lookup, so it unconditionally re-charged and refunded the user's personal balance — even for jobs whose original debit was funded by a workspace SHARED pool. Two concrete failures: (A) a workspace member with 0 personal credits got a false 402 when retrying a pool-funded job; (B) when a member did have personal credits, the retry debit and any enqueue-failure refund landed on the personal balance instead of the pool, silently draining the wrong account.

Fix (controller-only, no schema change):

  • Added CreditLedger to the guarded persistence import block.
  • Added _job_funding_workspace(session, job_id): recovers the funding pool by selecting the earliest CreditLedger row for that job_id where workspace_id IS NOT NULL — the only durable record of which pool funded the original debit. Returns None for the classic per-user path.
  • retry_job now binds workspace_id outside the transaction (mirroring create_job), routes the retry debit to CreditRepository.workspace_debit(...) when a pool funded the job and to debit(...) otherwise, and threads workspace_id into both reconcile paths (_refund_and_fail_job on enqueue failure and _reconcile_failed_enqueue on task-id-persist failure), which route refunds via workspace_grant vs grant accordingly.

Regression tests (tests/reelforge/test_workspace_credits_api.py):

  • test_retry_workspace_job_debits_pool_not_personal: member with 0 personal credits retries a failed workspace job → 200 (not 402), pool re-debited 4→3, personal untouched at 0.
  • test_retry_workspace_job_refunds_pool_on_enqueue_failure: failed retry enqueue → 502, pool refunded back to 4, personal never touched.

Debit-before-enqueue ordering, isolated refund sessions, and the FAILED→PROCESSING compare-and-swap were all preserved.

D2 — R2 IDOR / BOLA on user-supplied object keys (HIGH, tenant isolation)

Where: app/services/reelforge.py (stage_compose, _prepare_watermark).

Defect: Two stages accepted user-supplied R2 keys (screen_recording_key, and the per-job watermark_key / brand logo_key) and presigned/downloaded them with no ownership check. A caller could reference jobs/<other-tenant-job-id>/... and have another tenant's object fetched into their render — a cross-tenant object read (BOLA).

Fix (mirrors the brand controller's existing _verify_logo_ownership):

  • _key_job_ref(key): returns the <job_id> for a jobs/<job_id>/... key, else None. Non-jobs/ prefixes (e.g. uploads/<uuid4>) are already user-scoped, non-enumerable namespaces and short-circuit as allowed with zero DB hits.
  • _assert_owned_r2_key(job_id, key): raises PermissionError when a jobs/<ref>/ key references a different tenant. A ref is allowed only when it is this job or another job owned by the same user (resolved via JobRepository). Fails closed — any unresolved cross-job reference (no DB, missing rows, or error) is rejected.
  • Wiring: in stage_compose the guard runs before _download_from_r2, so the victim object is never presigned/downloaded; a violation becomes a typed ReelForgeStageError("compose", ...) (screen recording is required → hard fail). In _prepare_watermark the guard runs inside the existing best-effort block, so a violating logo/watermark is caught by the surrounding except Exception and the reel simply composes without the overlay.

Regression coverage added in tests/reelforge/test_reelforge_stages.py.

Residual posture (guards confirmed present)

Money / credits — row-locked, atomic, idempotent. app/models/db/repositories.py performs balance mutations under SELECT ... FOR UPDATE (with_for_update() in debit/grant/workspace_debit/ workspace_grant and the balance/job lookups, lines ~270, ~439, ~511, ~560); app/services/billing/service.py acquires the User/Workspace row lock before granting (lines ~238, ~370). Debit happens before enqueue and refunds run in isolated sessions, so a failed enqueue cannot leave credits spent.

Payment webhooks — signature-verified, fail-closed, idempotent. app/services/billing/creem_client.py::verify_and_parse_webhook requires the creem-signature header, recomputes HMAC-SHA256 over the raw body with config.creem.webhook_secret, and compares with hmac.compare_digest (constant-time; _signature_matches, lines 342–356). A missing/invalid signature raises ValueError → caller responds 400 and grants nothing (fail-closed). Replay is blocked by Redis SETNX billing:evt:<provider>:<event_id> (TTL 30d) and a durable reason-encoded ledger idempotency key, so a duplicate event is a no-op even if Redis is unavailable (app/services/billing/service.py, _idempotent_grant).

IDOR / BOLA — owner-scoped resources. Jobs and brand assets are resolved through owner-scoped repository lookups; brand logos are guarded by _verify_logo_ownership, and after D2 all user-supplied R2 keys in the compositor are guarded by _assert_owned_r2_key, both failing closed on any unresolved cross-tenant reference.

SSRF / traversal / injection — escaped filtergraph paths, scoped keys. The FFmpeg compositor never interpolates untrusted strings into a shell (uses subprocess argv lists) and escapes every path handed to -filter_complex: app/services/compose/compose_ffmpeg.py::_escape_ass_filter_path (lines 466–484) absolutizes, normalizes backslashes to forward slashes, then backslash-escapes the filtergraph metacharacters [ ] ; , : ' so a crafted filename cannot break out of the ass= argument or inject extra filters; app/services/video.py:: _escape_ffmpeg_concat_path does the same for concat lists. Object access is by tenant-scoped R2 key (no user-controlled URL is fetched server-side), and upload filenames are basename-stripped (app/services/bgm.py, line 92) before use.

Secrets & input — env/config only, validated at the boundary. Provider API keys, webhook secrets, and bucket/R2 credentials are read only from config.* / environment (_require_webhook_secret, _creem_config, R2_*/NEON_DATABASE_URL env) and are never hardcoded; a missing webhook secret raises rather than silently accepting unsigned events. Webhook bodies are treated as untrusted: signature is checked before JSON is parsed, and malformed JSON is rejected with a 400-mapped ValueError.

Growth-phase security posture (Direct-Publish, Sharing, Creator graph)

This phase shipped several new surfaces beyond the original build plan — OAuth Direct-Publish account-connect, public watermarked share pages, the template marketplace with win-score ranking + remix trees, per-API-key quotas, and creator profiles + follow graph + leaderboards. Each was audited on the same money-path / tenant-isolation / untrusted-input axes; the posture below is what the code enforces today (see the cross-linked planning docs ROADMAP_V2.md, ARCHITECTURE_NEXT.md).

OAuth token secrecy — Fernet, key-at-use, never plaintext, never serialised. app/services/crypto_tokens.py is the single boundary where a plaintext OAuth access/refresh token becomes the opaque blob persisted in SocialAccount (access_token_enc / refresh_token_enc). It uses cryptography.fernet.Fernet (AES-128-CBC + HMAC-SHA256 authenticated encryption) — no hand-rolled crypto — with the key derived from the SOCIAL_TOKEN_KEY env var (falling back to config.app['social_token_key']), stretched to Fernet's required shape via urlsafe_b64encode(sha256(secret)). The key is validated at use (lazily) in _fernet(): with no secret configured, encrypt/decrypt raise the typed MissingTokenKeyError rather than persisting a plaintext token or crashing at import. A plaintext token is never written to a row (oauth_connect.store_account encrypts before the UPSERT; load_tokens/_decrypt_account decrypt in-memory only), and never serialised to a response — connections._connection_public_data returns only provider / external account id / status / expiry / scopes, and the module docstring's "never serialise a token" invariant is upheld across authorize, callback, list, and publish. decrypt maps a tampered / wrong-key blob to a typed TokenDecryptError (never a partial plaintext), and rotating the secret invalidates prior blobs — the intended fail-closed behaviour for a compromised key.

OAuth CSRF state — opaque, single-use (in-memory today = known debt). oauth_connect.generate_state mints an unguessable token via secrets.token_urlsafe (CSPRNG). SingleUseStateStore.consume returns True exactly once per issued state and False for an unknown / already-used / blank value. In controllers/v1/connections.py the authorize endpoint mints via _STATE_STORE.issue(), and callback consumes the state FIRST — a missing, unknown, or replayed state is a clean 400 before any exchange_code network call or token write. Known debt: _STATE_STORE is a process-local in-memory store, so the single-use guarantee holds within one worker but not across a multi-worker deployment (a state issued on worker A is unknown to worker B). Production must back the same SingleUseStateStore contract with a shared, expiring store (Redis / signed cookie / DB) — tracked in ARCHITECTURE_NEXT.md.

Per-API-key quota — 429 enforced on the live resolve path. jobs._resolve_user falls through to resolve_user_by_api_key (app/controllers/v1/base.py) for a UserApiKey, which enforces the key's per-minute rate limit + monthly quota via app/services/apikey_quota.py (enforce_rate_limit + check_and_consume, usage tracked in the api_key_usage table). A breach raises HttpException(429) that propagates — it is deliberately not caught and degraded to a 401, so a runaway key is rejected with a real, caller-facing 429 on the same path that authenticates every request. The enforcement is import-safe and degrade-OPEN: if the quota service is unavailable the request is allowed through (mirroring the rate limiter's fail-open stance) rather than blocking the whole API.

Public share / profile / leaderboard DTOs — STRICT and token-free. The unauthenticated read surfaces expose only allowlisted safe fields and never touch a token, the clean result_key, the owning user_id, or any financial:

  • share.public_view returns exactly share.SAFE_PUBLIC_FIELDS (title, watermarked_preview_url, created_at, sharer_referral_code). _safe_preview_key considers only the watermarked preview_key / poster_key / cover_key — the clean result_key is never a candidate, so the un-watermarked master can never leak. A revoked/unknown token is a 404 and never increments a view. GET /public/r/{token} skips _resolve_user (no auth) but is bounded by the strict SharePublicModel response contract.
  • creators.public_profile / leaderboard return only SAFE_PROFILE_FIELDS plus the score/rank/addressing keys; the controllers/v1/creators.py response models are STRICT pydantic (no extra="allow"), so credits/email/cost/revenue can never leak even if an aggregate accidentally carried one. The public profile DTO does not even include user_id.

Remix-parent spoof — blocked at the preset-create boundary, no update path. source_marketplace_id is the server-only provenance key the trusted clone path (marketplace.clone_to_user) writes to record a preset's genuine marketplace ancestor. controllers/v1/me.py defines _RESERVED_PROVENANCE_KEY = "source_marketplace_id" and strips it from every POST /me/presets body by rebuilding a fresh, sanitised config dict (immutable — the input is not mutated), so a hand-crafted preset can never forge remix-tree parentage (a fake parent link / inflated remix_count) or spoof a win-score cohort. There is no preset-update endpoint (/me/presets exposes only GET / POST / DELETE), so there is no second path through which a caller could later inject the key.

Self-clone reputation inflation — provenance + k-anonymity guard. The gaming-resistant anchor of the reputation score is downstream_win_score, sourced from marketplace.listing_win_scores, which is STRICTLY per-user provenance: a reel only counts toward a listing when the reel's OWNER genuinely cloned that listing, defeating a spoofed source_marketplace_id job param. On top of that it applies a k-anonymity cohort floor (creators.LEADERBOARD_WINSCORE_MIN_COHORT = 2 distinct downstream cloners), so a lone creator cloning THEIR OWN listing and logging fake metrics can never manufacture a win score. The weaker denormalised signals (clones, rating) are weighted modestly against that anchor, and each marketplace rating is one row per distinct (template, user) — so a single actor cannot inflate a rating either. Follows are idempotent (no self-follow, no duplicate edge), so the follower signal cannot be padded from one account.

Honest limitations

  • The audit is scoped to the ReelForge surface (app/, tests/reelforge/, migrations/); it does not re-certify unrelated MoneyPrinterTurbo legacy paths.
  • The OAuth CSRF state store is in-memory and process-local today; its single-use guarantee does not span a multi-worker deployment until it is backed by a shared, expiring store (Redis / signed cookie / DB). Tracked as known debt above.
  • Webhook replay protection's fast path depends on Redis; the durable reason-encoded ledger key is the backstop when Redis is degraded — correct, but it means a duplicate during a Redis outage costs one extra DB round-trip rather than a cache hit.
  • FOR UPDATE row locking is a no-op under SQLite (used only in tests); the atomicity guarantee holds on the production Neon/Postgres backend. Tests assert the logical invariants, not the lock's DB-level enforcement.
  • The jobs/<job_id>/... ownership guard assumes job IDs are the sole tenancy key embedded in R2 keys; non-jobs/ prefixes are trusted as user-scoped by construction (uploads/<uuid4>), which is safe only as long as that namespace stays non-enumerable and per-user.