fix(cloud): close the gaps the account-deletion review turned up

Eight findings from re-reading the erasure path, each one something that would
have shown up in production rather than in a test:

- The local purge missed two stores. SaaSShorts outputs (output/saas_<id>) and
  generated thumbnails record ownership in their own in-memory dicts, not in
  the .owner file, so neither was erased. Thumbnails are the serious half: the
  hourly sweep deliberately skips their directory, so a deleted user's
  generated images stayed on disk forever, publicly served at /thumbnails/.
- The purge ran on the event loop. rmtree over gigabytes of video stalled every
  other request on the process; it goes through asyncio.to_thread now.
- Paths from those dicts are now resolved through _safe_under, so a session id
  or output_dir containing ".." deletes nothing.
- Deleting a user made a webhook path reachable that never was: _apply_topup
  takes the user id from Stripe metadata, so a top-up completing around the
  deletion inserted a row pointing at a user that no longer exists. The FK
  violation 500s the webhook, and since the event is only recorded after
  handle_event returns, Stripe retries the same doomed insert for three days.
  It confirms the row exists first.
- The "why are you leaving" box was free text stored in a record that
  deliberately outlives the account, which is how personal data ends up in one
  by accident. It is a closed list now, which also makes twenty deletions a
  month countable instead of readable.
- Two concurrent deletes wrote two erasure records and sent two goodbye emails.
  The DELETE's rowcount now decides which call is the real one; the UI holds a
  ref so a double click doesn't fire a second Stripe cancel and R2 purge.
- The delete button armed itself when the confirm box was empty, if the page
  ever rendered before /api/me resolved.
- The goodbye email claimed we keep "a one-way hash of your email and nothing
  else", which was not true of the Stripe reference beside it. Fixed in the
  email and in the privacy policy, EN and ES.

Also: skip the Upload-Post call when no managed key is configured, and say
plainly in the in-flight comment that it covers metered work only.

tests/test_account_local_purge.py covers tenant isolation across all three
stores and both traversal attempts; test_account_erasure.py gains the
confirmation gate, the API-key refusal, and the already-cancelled-at-Stripe
case that would otherwise trap a user forever.
This commit is contained in:
juancarlos.cavero 2026-08-24 19:26:12 +02:00
parent 1d9fef7445
commit b4bf211b7b
10 changed files with 477 additions and 47 deletions

View file

@ -217,11 +217,22 @@ added after a table shipped exists in the models but not in production.
`tests/test_account_erasure.py` fails if a new table references `users.id`
without joining that list.
`app.py` registers a callback for the local working files, which record
ownership three different ways: the `.owner` file clip jobs write (so jobs
recovered from disk after a restart count too), `saas_jobs`, and
`thumbnail_sessions`. That last one is the only thing that ever deletes
generated thumbnails: the hourly sweep skips their directory and they are
served publicly at `/thumbnails/`.
What deliberately survives: the Stripe customer and its invoices (6-year
retention, Spanish commercial law) and one `account_deletions` row holding a
sha256 of the email as proof the erasure happened, itself purged after 5 years.
`app.py` registers a callback so the local `output/` and `uploads/` working
files go too, instead of waiting for the hourly sweep.
The "why are you leaving" answer is a closed list (`DELETION_REASONS`), never
free text — anything the user could type would land in a row designed to
outlive them. Deleting users also made one webhook path reachable that never
was before: `_apply_topup` reads the user id from Stripe metadata, so it now
confirms the row still exists before inserting, or the FK violation makes
Stripe retry the same doomed event for three days.
### Concurrency Model
Async job queue with semaphore-based concurrency control. Configure via `MAX_CONCURRENT_JOBS` env var (default: 5). Jobs auto-cleanup after 1 hour.

78
app.py
View file

@ -1218,35 +1218,66 @@ async def _settle_reservation(job_id):
except Exception as e:
print(f"⚠️ Reservation settle error for {job_id}: {e}")
def _owned_by(record, uid: str) -> bool:
owner = record.get('user_id') if isinstance(record, dict) else None
return owner is not None and str(owner) == uid
def _rm_under(base_dir: str, relative: str):
"""Remove a file or directory, refusing anything that escapes ``base_dir``."""
target = _safe_under(base_dir, relative)
if not target or target == os.path.realpath(base_dir):
return
if os.path.isdir(target):
shutil.rmtree(target, ignore_errors=True)
else:
try:
os.remove(target)
except OSError:
pass
def _purge_local_jobs_for_user(user_id) -> int:
"""Delete this user's job dirs, source uploads and in-memory job records.
"""Delete this user's working files and in-memory records from local disk.
Called by cloud/account.py when an account is erased. The durable copies
live on R2 and are deleted there; these are the working files on the API's
own disk, which would otherwise sit around until the one-hour cleanup sweep
— a long time to keep the videos of someone who just asked to be forgotten.
— and thumbnails not even then, because that sweep skips their directory.
Ownership comes from the ``.owner`` file each managed job writes, so jobs
recovered from disk after a restart (no in-memory record) are covered too.
Three stores, because each records ownership differently:
- clip jobs: the ``.owner`` file every managed job writes, so jobs
recovered from disk after a restart (no in-memory record) count too;
- SaaSShorts jobs (``output/saas_<id>``): ``saas_jobs`` only, no marker
file, so a restart loses the link and those age out on the sweep;
- thumbnail sessions (``output/thumbnails/<id>`` plus the source video in
``uploads/``): likewise in-memory only.
Blocking: rmtree over gigabytes of video. Callers must run it in a thread.
"""
uid = str(user_id)
job_ids = {jid for jid, job in list(jobs.items())
if job.get('user_id') is not None and str(job['user_id']) == uid}
removed = 0
job_ids = {jid for jid, job in list(jobs.items()) if _owned_by(job, uid)}
thumbs_dir_name = os.path.basename(THUMBNAILS_DIR)
try:
entries = os.listdir(OUTPUT_DIR)
except OSError:
entries = []
for job_id in entries:
owner_path = os.path.join(OUTPUT_DIR, job_id, ".owner")
# Never a job, and it backs a StaticFiles mount: deleting the directory
# itself 500s every /thumbnails request until the process restarts.
if job_id == thumbs_dir_name:
continue
try:
with open(owner_path) as f:
with open(os.path.join(OUTPUT_DIR, job_id, ".owner")) as f:
if f.read().strip() == uid:
job_ids.add(job_id)
except OSError:
continue
for job_id in job_ids:
shutil.rmtree(os.path.join(OUTPUT_DIR, job_id), ignore_errors=True)
_rm_under(OUTPUT_DIR, job_id)
jobs.pop(job_id, None)
# Source uploads are named "<job_id>_<filename>" (see /api/process).
for path in glob.glob(os.path.join(UPLOAD_DIR, f"{glob.escape(job_id)}_*")):
@ -1254,9 +1285,32 @@ def _purge_local_jobs_for_user(user_id) -> int:
os.remove(path)
except OSError:
pass
if job_ids:
print(f"🗑️ Purged {len(job_ids)} local job dir(s) for erased user {uid}.")
return len(job_ids)
removed += 1
for jid, job in list(saas_jobs.items()):
if not _owned_by(job, uid):
continue
out = job.get('output_dir')
if out:
_rm_under(OUTPUT_DIR, os.path.basename(out))
saas_jobs.pop(jid, None)
removed += 1
for sid, sess in list(thumbnail_sessions.items()):
if not _owned_by(sess, uid):
continue
# Generated thumbnails are served publicly at /thumbnails/<id>/... and
# nothing else ever deletes them.
_rm_under(THUMBNAILS_DIR, sid)
video_path = sess.get('video_path')
if video_path:
_rm_under(UPLOAD_DIR, os.path.basename(video_path))
thumbnail_sessions.pop(sid, None)
removed += 1
if removed:
print(f"🗑️ Purged {removed} local work item(s) for erased user {uid}.")
return removed
@asynccontextmanager

View file

@ -22,8 +22,10 @@ happens when a step fails halfway:
What deliberately survives: the Stripe customer and its invoices (six-year
retention under Spanish commercial law, privacy policy §5) and one
[AccountDeletion] row holding a sha256 of the email — proof the erasure
happened, with no readable identity in it.
[AccountDeletion] row proving the erasure happened — a sha256 of the email
rather than the address, and no free text anywhere in it. The confirmation
email tells the user both, because a record they were never told about is not
accountability, it is retention.
"""
import asyncio
import hashlib
@ -56,6 +58,17 @@ USER_OWNED_TABLES = (
Subscription, ApiKey, SignupAttribution, UploadPostProfile,
)
# The optional "why are you leaving" answer, as a closed list. It was a free
# text box first, and that was wrong: whatever the user types lands in a record
# that deliberately outlives their account, so a single "my name is X, please
# confirm" turns the one row meant to hold no readable identity into retained
# personal data. A fixed vocabulary cannot do that, and twenty deletions a month
# are far more legible counted than read.
DELETION_REASONS = (
"too_expensive", "not_using_it", "clip_quality", "missing_feature",
"found_alternative", "privacy", "other",
)
router = APIRouter()
# Job dirs on the API's own disk belong to app.py, which cannot be imported from
@ -141,6 +154,8 @@ async def _delete_upload_post_profile(user_id):
import httpx
from .social_profiles import API_BASE, _auth_headers
if not settings.managed_upload_post_key:
return
async with database.session() as session:
prof = await session.get(UploadPostProfile, user_id)
if prof is None:
@ -160,16 +175,31 @@ async def _delete_upload_post_profile(user_id):
print(f"⚠️ Upload-Post profile delete failed for {username}: {e}")
async def _erase_rows(user_id, email, stripe_customer_id, plan, r2_deleted, reason):
async def _erase_rows(user_id, email, stripe_customer_id, plan, r2_deleted, reason) -> bool:
"""Swap the account for its erasure record, in one transaction.
All-or-nothing on purpose: a half-erased account is worse than an un-erased
one, because the user is told they are gone while some of their rows are
not. Magic-link tokens are keyed by email rather than user id, so they need
their own statement on top of [USER_OWNED_TABLES].
Returns whether this call is the one that removed the account. Two requests
can race here — a double-click, or two tabs — and everything before this
point is idempotent, but the erasure record is not: writing it from the
loser would leave two rows for one deletion, possibly disagreeing about the
reason. Postgres serialises the two DELETEs, so the loser sees rowcount 0
and writes nothing.
"""
async with database.session() as session:
async with session.begin():
for model in USER_OWNED_TABLES:
await session.execute(
delete(model).where(model.user_id == user_id))
await session.execute(
delete(MagicLinkToken).where(MagicLinkToken.email == email))
result = await session.execute(delete(User).where(User.id == user_id))
if result.rowcount == 0:
return False
session.add(AccountDeletion(
former_user_id=str(user_id),
email_sha256=email_fingerprint(email),
@ -178,12 +208,7 @@ async def _erase_rows(user_id, email, stripe_customer_id, plan, r2_deleted, reas
r2_objects_deleted=r2_deleted,
reason=reason,
))
for model in USER_OWNED_TABLES:
await session.execute(
delete(model).where(model.user_id == user_id))
await session.execute(
delete(MagicLinkToken).where(MagicLinkToken.email == email))
await session.execute(delete(User).where(User.id == user_id))
return True
# --------------------------------------------------------------------------- #
@ -194,7 +219,7 @@ class DeleteAccountRequest(BaseModel):
# there is no password to re-enter, so this is the strongest thing we can
# ask for without mailing a second token to a user who is leaving anyway.
confirm_email: str
reason: Optional[str] = None
reason: Optional[str] = None # one of DELETION_REASONS, or ignored
@router.delete("/api/account")
@ -211,10 +236,15 @@ async def delete_account(payload: DeleteAccountRequest, request: Request):
if row is None:
raise HTTPException(status_code=404, detail="Account not found.")
email, stripe_customer_id = row.email, row.stripe_customer_id
# A reserved ledger row means a render is in flight. Erasing now would
# delete the output from under a job that is still writing it, and the
# A reserved ledger row means metered work is in flight. Erasing now
# would pull the output from under a job still writing it, and the
# reservation would never settle. Minutes are refunded on failure, so
# waiting costs the user nothing.
#
# This covers everything that costs minutes, which is everything long
# enough to matter. A free action (burning captions on an untranslated
# clip) writes no ledger row and so is not covered: worst case it fails
# on a missing file, in a tab whose session is about to end anyway.
in_flight = (await session.execute(
select(func.count(UsageLedger.id)).where(
UsageLedger.user_id == user.id, UsageLedger.status == "reserved")
@ -249,15 +279,20 @@ async def delete_account(payload: DeleteAccountRequest, request: Request):
if _local_purge is not None:
try:
_local_purge(user.id)
# rmtree over gigabytes of video: off the event loop, or every other
# request on the process waits for this user's disk to clear.
await asyncio.to_thread(_local_purge, user.id)
except Exception as e:
print(f"⚠️ Local job purge failed for {user.id}: {e}")
await _delete_upload_post_profile(user.id)
reason = (payload.reason or "").strip()[:500] or None
# Anything not in the closed list is dropped rather than rejected: a
# mismatched client must not be able to fail a deletion over a label.
reason = payload.reason if payload.reason in DELETION_REASONS else None
try:
await _erase_rows(user.id, email, stripe_customer_id, plan, r2_deleted, reason)
erased = await _erase_rows(
user.id, email, stripe_customer_id, plan, r2_deleted, reason)
except Exception as e:
# The content is already gone; only the account row survived. Say that
# rather than a bare 500 — the user needs to know a retry is safe and
@ -269,6 +304,10 @@ async def delete_account(payload: DeleteAccountRequest, request: Request):
# ``email`` was read before the delete on purpose: from here on the address
# exists nowhere in our systems, and the goodbye email still has to go out.
if not erased:
# A concurrent request got there first and has already sent the email.
return {"deleted": True, "r2_objects_deleted": r2_deleted}
print(f"🗑️ Account erased: {user.id} (plan={plan}, r2_objects={r2_deleted})")
# Everything below is after-the-fact and must never fail the deletion.

View file

@ -282,7 +282,20 @@ async def _apply_topup(session_obj: dict):
)).scalar_one_or_none()
if existing:
return
# The id rides in Stripe's metadata, so it can name an account that
# no longer exists: a checkout completed moments before the user
# erased themselves, or any webhook Stripe retries afterwards.
# Inserting it blind trips the foreign key, and because the event is
# only recorded after handle_event returns, the 500 makes Stripe
# retry the same doomed insert for three days.
user_id = (session_obj.get("metadata") or {}).get("user_id")
if user_id:
try:
user_id = (await s.execute(
select(User.id).where(User.id == user_id)
)).scalar_one_or_none()
except Exception:
user_id = None # not a uuid at all
if not user_id:
user_id = await _user_id_for_customer(s, session_obj.get("customer"))
if not user_id:

View file

@ -156,9 +156,11 @@ async def send_account_deleted_email(email: str):
<p>Two things we keep, and why:</p>
<ul style="line-height:1.7;padding-left:20px">
<li><strong>Your invoices</strong>, for six years &mdash; Spanish
commercial law requires it.</li>
<li><strong>A record that this deletion happened</strong>, holding a
one-way hash of your email address and nothing else.</li>
commercial law requires it, and the Stripe customer reference
that finds them goes with it.</li>
<li><strong>A record that this deletion happened</strong>, for five
years, holding a one-way hash of your email address instead of
the address itself.</li>
</ul>
<p>You can sign up again any time with the same address; it will be a
brand-new, empty account.</p>

View file

@ -228,9 +228,13 @@ class AccountDeletion(Base):
GDPR Art. 17 erasure has an accountability twin (Art. 5.2): if a former user
later claims we never deleted their account, the only way to answer is a
record that outlives the deletion. So this holds no readable identity — a
sha256 of the account email, which can confirm "yes, this address was
deleted on this date" without storing the address itself.
record that outlives the deletion. The identifying field is therefore a
sha256 of the account email, which confirms "yes, this address was deleted
on this date" without storing the address itself.
``reason`` is one label from ``account.DELETION_REASONS``, never free text:
anything the user could type would land in a row that deliberately outlives
their account, which is the opposite of what this row is for.
``stripe_customer_id`` is the one exception and it is deliberate: the
invoices behind it must be kept for six years under Spanish commercial law,
@ -249,5 +253,5 @@ class AccountDeletion(Base):
stripe_customer_id = Column(Text, nullable=True)
plan_at_deletion = Column(String(20), nullable=True)
r2_objects_deleted = Column(Integer, nullable=True)
reason = Column(Text, nullable=True) # optional free-text the user typed
reason = Column(String(32), nullable=True) # one of account.DELETION_REASONS
deleted_at = Column(DateTime(timezone=True), server_default=func.now())

View file

@ -613,7 +613,8 @@ Delete account</strong> in the dashboard does it yourself, immediately and
permanently, taking your projects, clips, transcripts, API keys and social
connections with it and cancelling any active subscription. Two things survive
it, both listed in section 5: your invoices, which tax law requires us to keep,
and a one-way hash of your email address recording that the deletion happened.
and a record that the deletion happened, which identifies you by a one-way hash
of your email address rather than by the address itself.
If you believe we are mishandling your data, you can complain to the Spanish
supervisory authority (AEPD, aepd.es) or to the authority of your own EU
country.</p>
@ -750,8 +751,9 @@ forma inmediata y permanente, y se lleva por delante tus proyectos, clips,
transcripciones, claves de API y conexiones con redes sociales, además de
cancelar cualquier suscripción activa. Solo sobreviven dos cosas, ambas
recogidas en el apartado 5: tus facturas, que la normativa fiscal nos obliga a
conservar, y un hash irreversible de tu dirección de email que acredita que la
eliminación se produjo. Si crees que tratamos mal tus datos, puedes reclamar
conservar, y un registro de que la eliminación se produjo, que te identifica
mediante un hash irreversible de tu dirección de email y no mediante la
dirección en sí. Si crees que tratamos mal tus datos, puedes reclamar
ante la Agencia Española de Protección de Datos (AEPD, aepd.es) o ante la
autoridad de tu país de la UE.</p>

View file

@ -1,8 +1,21 @@
import React, { useState, useCallback } from 'react';
import React, { useState, useRef, useCallback } from 'react';
import { Trash2, AlertTriangle, Loader2 } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
// Mirrors cloud/account.DELETION_REASONS. A closed list rather than a text
// box, because the answer is stored in a record that outlives the account and
// free text is how personal data gets into one by accident.
const REASONS = [
['too_expensive', 'Too expensive'],
['not_using_it', "I'm not using it"],
['clip_quality', "The clips weren't good enough"],
['missing_feature', 'Missing a feature I need'],
['found_alternative', 'I found something better'],
['privacy', 'Privacy concerns'],
['other', 'Something else'],
];
// GDPR Art. 17 erasure, self-service (backend: cloud/account.py). The privacy
// policy tells users they can delete their account from the dashboard, so this
// has to be findable — but it is also irreversible, hence: collapsed by
@ -16,18 +29,26 @@ export default function DeleteAccountCard() {
const [reason, setReason] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
// setBusy only disables the button on the next render, which a fast double
// click beats. The server survives a duplicate call, but each one re-runs a
// Stripe cancel and an R2 prefix delete for nothing.
const sending = useRef(false);
const email = me?.user?.email || '';
const matches = confirm.trim().toLowerCase() === email.toLowerCase();
// `!!email` matters: without it an account page rendered before /api/me
// resolves would treat an empty box as a match and arm the delete button.
const matches = !!email && confirm.trim().toLowerCase() === email.toLowerCase();
const remove = useCallback(async () => {
if (sending.current) return;
sending.current = true;
setBusy(true);
setError('');
try {
await apiJson('/api/account', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ confirm_email: confirm.trim(), reason: reason.trim() || undefined }),
body: JSON.stringify({ confirm_email: confirm.trim(), reason: reason || undefined }),
});
// The session token now points at nothing. Drop it before navigating, or
// the landing page spends a request discovering that for itself. The
@ -42,6 +63,7 @@ export default function DeleteAccountCard() {
window.location.reload();
} catch (e) {
setError(e?.detail || 'Could not delete your account. Please try again or email info@openshorts.app.');
sending.current = false;
setBusy(false);
}
}, [confirm, reason, logout]);
@ -77,19 +99,23 @@ export default function DeleteAccountCard() {
<p className="mt-2">
Any active subscription is cancelled as part of this. We keep your
invoices for six years because Spanish law requires it, plus a
one-way hash of your email as proof the deletion happened.
one-way hash of your email address, instead of the address, as
proof the deletion happened.
</p>
</div>
<label className="block">
<span className="text-sm text-muted lowercase">Why are you leaving? (optional)</span>
<input
<select
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder="It helps us fix what went wrong"
className="input-field w-full text-sm mt-1"
maxLength={500}
/>
>
<option value="">Prefer not to say</option>
{REASONS.map(([value, label]) => (
<option key={value} value={value}>{label}</option>
))}
</select>
</label>
<label className="block">

View file

@ -6,6 +6,7 @@ list forgets turns that sentence into a false statement — and a table added a
year from now is exactly the kind of thing nobody remembers to add here.
"""
import hashlib
import os
from cloud import account
from cloud.database import Base
@ -44,6 +45,23 @@ class TestCoverage:
assert AccountDeletion.__tablename__ not in _tables_referencing_users()
class TestDeletionReason:
"""The reason outlives the account, so it must never carry free text."""
def test_the_ui_offers_exactly_the_reasons_the_server_accepts(self):
repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
card = open(os.path.join(
repo, "dashboard/src/components/DeleteAccountCard.jsx")).read()
for value in account.DELETION_REASONS:
assert f"'{value}'" in card, f"{value} is accepted but never offered"
def test_the_column_cannot_hold_a_typed_sentence(self):
# 32 chars is under every label in the list and far under anything a
# user could write, so a free-text regression fails loudly at the DB.
assert AccountDeletion.reason.type.length == 32
assert max(len(r) for r in account.DELETION_REASONS) <= 32
class TestEmailFingerprint:
def test_is_a_plain_sha256_of_the_normalised_address(self):
assert account.email_fingerprint("user@example.com") == \
@ -62,3 +80,121 @@ class TestEmailFingerprint:
def test_different_addresses_differ(self):
assert account.email_fingerprint("a@example.com") != \
account.email_fingerprint("b@example.com")
# --------------------------------------------------------------------------- #
# The endpoint's gates
# --------------------------------------------------------------------------- #
import asyncio # noqa: E402
import pytest # noqa: E402
from fastapi import FastAPI # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
class _FakeUser:
id = "11111111-1111-1111-1111-111111111111"
email = "owner@example.com"
@pytest.fixture
def client(monkeypatch):
"""The endpoint with authentication stubbed out.
Everything past the confirmation gate needs Postgres, so these cover only
what happens before it — which is the part that decides whether an account
gets destroyed.
"""
async def _fake_session_user(request):
return _FakeUser()
monkeypatch.setattr(account, "_session_user", _fake_session_user)
app = FastAPI()
app.include_router(account.router)
return TestClient(app, raise_server_exceptions=False)
def _delete(client, **body):
return client.request("DELETE", "/api/account", json=body)
class TestConfirmationGate:
def test_a_wrong_email_deletes_nothing(self, client):
r = _delete(client, confirm_email="someone.else@example.com")
assert r.status_code == 400
def test_an_empty_confirmation_deletes_nothing(self, client):
# The UI can render before /api/me resolves; an empty box must never
# read as agreement.
assert _delete(client, confirm_email="").status_code == 400
def test_a_missing_confirmation_deletes_nothing(self, client):
assert client.request("DELETE", "/api/account").status_code == 422
def test_the_right_email_gets_past_the_gate(self, client):
# No database here, so "past the gate" is anything but the 400/422 the
# cases above return. What matters is that it stopped rejecting.
assert _delete(client, confirm_email="owner@example.com").status_code \
not in (400, 422)
def test_the_gate_ignores_case_and_gmail_aliasing(self, client, monkeypatch):
# Sign-up normalises the address, so the stored one may not be what the
# user remembers typing.
class _Gmail(_FakeUser):
email = "foobar@gmail.com"
async def _fake(request):
return _Gmail()
monkeypatch.setattr(account, "_session_user", _fake)
assert _delete(client, confirm_email="Foo.Bar+news@GMAIL.com").status_code \
not in (400, 422)
class TestApiKeyAuth:
def test_an_api_key_cannot_delete_the_account_it_belongs_to(self):
# Not the stubbed fixture: this must be the real _session_user.
app = FastAPI()
app.include_router(account.router)
c = TestClient(app, raise_server_exceptions=False)
for headers in ({"Authorization": "Bearer osk_abc123"},
{"X-API-Key": "osk_abc123"}):
r = c.request("DELETE", "/api/account",
json={"confirm_email": "owner@example.com"},
headers=headers)
assert r.status_code == 403
class TestStripeCancel:
def test_an_already_cancelled_subscription_does_not_trap_the_user(self, monkeypatch):
"""Our row can say "active" long after Stripe stopped billing — a
cancellation made in the portal whose webhook never landed. If that
raised, the one account impossible to delete would be the one Stripe
already stopped charging."""
import stripe
class _Row:
stripe_subscription_id = "sub_gone"
status = "active"
plan = "starter"
class _Result:
def scalars(self):
return [_Row()]
class _Session:
async def execute(self, _stmt):
return _Result()
async def __aenter__(self):
return self
async def __aexit__(self, *_a):
return False
def _boom(_sid):
raise stripe.InvalidRequestError("No such subscription", None)
monkeypatch.setattr(account.database, "session", lambda: _Session())
monkeypatch.setattr(stripe.Subscription, "cancel", staticmethod(_boom))
assert asyncio.run(account._cancel_subscriptions("uid")) == "starter"

View file

@ -0,0 +1,143 @@
"""Local-disk purge on account erasure (app._purge_local_jobs_for_user).
Two failure modes matter here and neither shows up in a unit-free reading of
the code: erasing one user's files must not touch another's (the API is
multi-tenant, and the three stores record ownership three different ways), and
a session id or output_dir that walks out of the working directories must not
delete anything at all.
"""
import os
import pytest
import app
MINE = "aaaa-1111"
THEIRS = "bbbb-2222"
def _write(path, body="x"):
parent = os.path.dirname(path)
if parent:
os.makedirs(parent, exist_ok=True)
with open(path, "w") as f:
f.write(body)
@pytest.fixture
def workdir(tmp_path, monkeypatch):
"""A throwaway output/ + uploads/ tree, with the in-memory stores emptied.
app.py holds OUTPUT_DIR / UPLOAD_DIR as relative paths, so chdir is enough
to redirect every write the purge can make.
"""
monkeypatch.chdir(tmp_path)
os.makedirs("output/thumbnails", exist_ok=True)
os.makedirs("uploads", exist_ok=True)
monkeypatch.setattr(app, "jobs", {})
monkeypatch.setattr(app, "saas_jobs", {})
monkeypatch.setattr(app, "thumbnail_sessions", {})
return tmp_path
class TestClipJobs:
def test_erases_jobs_marked_with_an_owner_file(self, workdir):
# No in-memory record: this is a job recovered from disk after a restart.
_write("output/job1/.owner", MINE)
_write("output/job1/clip.mp4")
_write("uploads/job1_source.mp4")
app._purge_local_jobs_for_user(MINE)
assert not os.path.exists("output/job1")
assert not os.path.exists("uploads/job1_source.mp4")
def test_erases_in_memory_jobs_with_no_owner_file(self, workdir):
_write("output/job2/clip.mp4")
app.jobs["job2"] = {"user_id": MINE, "status": "completed"}
app._purge_local_jobs_for_user(MINE)
assert not os.path.exists("output/job2")
assert "job2" not in app.jobs
def test_leaves_another_users_jobs_alone(self, workdir):
_write("output/theirs/.owner", THEIRS)
_write("output/theirs/clip.mp4")
_write("uploads/theirs_source.mp4")
app._purge_local_jobs_for_user(MINE)
assert os.path.exists("output/theirs/clip.mp4")
assert os.path.exists("uploads/theirs_source.mp4")
def test_leaves_unowned_self_host_jobs_alone(self, workdir):
# BYOK jobs carry user_id=None; a str() comparison would match "None".
_write("output/anon/clip.mp4")
app.jobs["anon"] = {"user_id": None, "status": "completed"}
app._purge_local_jobs_for_user(MINE)
assert os.path.exists("output/anon/clip.mp4")
class TestOtherStores:
def test_erases_saasshorts_output(self, workdir):
_write("output/saas_s1/final.mp4")
app.saas_jobs["s1"] = {"user_id": MINE, "output_dir": "output/saas_s1"}
app._purge_local_jobs_for_user(MINE)
assert not os.path.exists("output/saas_s1")
assert "s1" not in app.saas_jobs
def test_erases_generated_thumbnails_and_their_source(self, workdir):
# Nothing else ever deletes these: the hourly sweep skips the whole
# thumbnails directory, and they are served publicly at /thumbnails/.
_write("output/thumbnails/t1/thumb.png")
_write("uploads/thumb_t1_video.mp4")
app.thumbnail_sessions["t1"] = {
"user_id": MINE, "video_path": "uploads/thumb_t1_video.mp4"}
app._purge_local_jobs_for_user(MINE)
assert not os.path.exists("output/thumbnails/t1")
assert not os.path.exists("uploads/thumb_t1_video.mp4")
assert "t1" not in app.thumbnail_sessions
def test_leaves_another_users_thumbnails_alone(self, workdir):
_write("output/thumbnails/t2/thumb.png")
app.thumbnail_sessions["t2"] = {"user_id": THEIRS}
app._purge_local_jobs_for_user(MINE)
assert os.path.exists("output/thumbnails/t2/thumb.png")
def test_keeps_the_thumbnails_directory_itself(self, workdir):
# It backs a StaticFiles mount; removing it 500s every /thumbnails
# request until the process restarts.
_write("output/thumbnails/t1/thumb.png")
app.thumbnail_sessions["t1"] = {"user_id": MINE}
app._purge_local_jobs_for_user(MINE)
assert os.path.isdir("output/thumbnails")
class TestPathTraversal:
def test_a_poisoned_session_id_deletes_nothing(self, workdir):
_write("secret.txt", "keep me")
app.thumbnail_sessions["../../secret.txt"] = {"user_id": MINE}
app._purge_local_jobs_for_user(MINE)
assert os.path.exists("secret.txt")
def test_a_poisoned_output_dir_deletes_nothing(self, workdir):
_write("secret.txt", "keep me")
app.saas_jobs["evil"] = {
"user_id": MINE, "output_dir": "output/../../secret.txt"}
app._purge_local_jobs_for_user(MINE)
assert os.path.exists("secret.txt")