harden(social): fail closed when the server cannot resolve the caller's profile

Cloud keeps every user's connected accounts as profiles inside one
Upload-Post account, so the profile string is the only thing separating
'schedule to my TikTok' from 'schedule to a stranger's'. All three call
sites read `forced_profile or <client-supplied profile>`, which honours
the client's value whenever the server fails to resolve its own — one
resolver bug away from a cross-tenant write, and invisible in review
because the happy path looks identical.

resolve_post_profile() now refuses in cloud mode instead of falling
back, and never consults the client value there; self-host keeps
picking its own profile, since it owns the account behind the key.
Tests pin both behaviours and the profile filter on the scheduled-post
list, which is what stops one tenant reading or cancelling another's
queue.
This commit is contained in:
juancarlos.cavero 2026-08-21 21:19:44 +02:00
parent a245f14ec5
commit 36cf2e43ef
2 changed files with 116 additions and 10 deletions

38
app.py
View file

@ -139,6 +139,31 @@ async def resolve_upload_post(request: Request, body_key: Optional[str] = None):
return key, None return key, None
def resolve_post_profile(forced_profile: Optional[str], client_profile: Optional[str]) -> str:
"""The Upload-Post profile to act as, for posting/scheduling/analytics.
Fails closed on purpose. Every call site used to read
``forced_profile or client_profile``, which quietly honours whatever
profile the *client* asked for if the server ever failed to resolve its
own — one refactor of ``resolve_upload_post`` away from letting a cloud
user schedule into someone else's connected accounts. In cloud mode the
client value is never consulted: either the server knows the caller's
profile or the request is refused.
"""
if BILLING_ENABLED:
if not forced_profile:
raise HTTPException(
status_code=503,
detail="Could not resolve your social profile. Please try again.")
return forced_profile
# Self-host: no user model, the caller owns the Upload-Post account whose
# key resolved above, so it picks its own profile.
profile = forced_profile or client_profile
if not profile:
raise HTTPException(status_code=400, detail="Missing Upload-Post user profile")
return profile
def gemini_missing_error(): def gemini_missing_error():
"""The right 4xx when no Gemini key could be resolved. """The right 4xx when no Gemini key could be resolved.
@ -3664,9 +3689,7 @@ async def post_to_socials(req: SocialPostRequest, request: Request):
upload_key, forced_profile = await resolve_upload_post(request, req.api_key) upload_key, forced_profile = await resolve_upload_post(request, req.api_key)
if not upload_key: if not upload_key:
raise HTTPException(status_code=400, detail="Missing Upload-Post API key") raise HTTPException(status_code=400, detail="Missing Upload-Post API key")
post_user = forced_profile or req.user_id post_user = resolve_post_profile(forced_profile, req.user_id)
if not post_user:
raise HTTPException(status_code=400, detail="Missing Upload-Post user profile")
job = jobs[req.job_id] job = jobs[req.job_id]
await _assert_job_owner(request, job) await _assert_job_owner(request, job)
@ -3852,10 +3875,7 @@ async def _social_analytics_auth(request: Request, byok_profile: Optional[str]):
user = await _user_from_request(request) user = await _user_from_request(request)
if user: if user:
_check_analytics_rate(user.id) _check_analytics_rate(user.id)
profile = forced_profile or byok_profile return api_key, resolve_post_profile(forced_profile, byok_profile)
if not profile:
raise HTTPException(status_code=400, detail="Missing Upload-Post user profile (pass ?user= with BYOK)")
return api_key, profile
async def _upload_post_get(api_key: str, url: str, params: dict): async def _upload_post_get(api_key: str, url: str, params: dict):
@ -4757,9 +4777,7 @@ async def saasshorts_post_to_socials(req: SaaSPostRequest, request: Request):
upload_key, forced_profile = await resolve_upload_post(request, req.api_key) upload_key, forced_profile = await resolve_upload_post(request, req.api_key)
if not upload_key: if not upload_key:
raise HTTPException(status_code=400, detail="Missing Upload-Post API key") raise HTTPException(status_code=400, detail="Missing Upload-Post API key")
post_user = forced_profile or req.user_id post_user = resolve_post_profile(forced_profile, req.user_id)
if not post_user:
raise HTTPException(status_code=400, detail="Missing Upload-Post user profile")
job = saas_jobs[req.job_id] job = saas_jobs[req.job_id]
await _assert_job_owner(request, job) await _assert_job_owner(request, job)

View file

@ -0,0 +1,88 @@
"""Multi-tenant isolation for the social surface (posting, scheduling, analytics).
Cloud runs every user's connected accounts inside ONE Upload-Post account, as
profiles named ``os_<hex>``. That means the profile string is the only thing
standing between "schedule to my TikTok" and "schedule to a stranger's", and it
must never come from the request body.
Two things are pinned here:
1. ``resolve_post_profile`` ignores the client-supplied profile in cloud mode
and refuses when the server cannot resolve one, rather than falling back to
the client's value. The call sites used to read ``forced_profile or
req.user_id``; that is the exact shape that turns a resolver bug into a
cross-tenant write.
2. The vendor-facing list helper filters by profile. Upload-Post's schedule
endpoint takes no profile filter and returns the whole account, so dropping
this filter would expose (and let anyone cancel) every other user's queue.
"""
import asyncio
import pytest
from fastapi import HTTPException
import app as app_module
OTHER_TENANT = "os_deadbeefcafe"
class TestResolvePostProfileInCloud:
@pytest.fixture(autouse=True)
def _cloud(self, monkeypatch):
monkeypatch.setattr(app_module, "BILLING_ENABLED", True)
def test_uses_the_server_resolved_profile(self):
assert app_module.resolve_post_profile("os_mine", None) == "os_mine"
def test_ignores_a_profile_supplied_by_the_caller(self):
assert app_module.resolve_post_profile("os_mine", OTHER_TENANT) == "os_mine"
def test_refuses_instead_of_falling_back_to_the_caller_value(self):
# The whole point: no server profile must NOT mean "use theirs".
with pytest.raises(HTTPException) as exc:
app_module.resolve_post_profile(None, OTHER_TENANT)
assert exc.value.status_code == 503
@pytest.mark.parametrize("empty", [None, ""])
def test_empty_server_profile_is_also_refused(self, empty):
with pytest.raises(HTTPException):
app_module.resolve_post_profile(empty, OTHER_TENANT)
class TestResolvePostProfileSelfHosted:
"""Self-host has no user model: the caller owns the Upload-Post account
whose key resolved the request, so it may name its own profile."""
@pytest.fixture(autouse=True)
def _self_host(self, monkeypatch):
monkeypatch.setattr(app_module, "BILLING_ENABLED", False)
def test_client_profile_is_honoured(self):
assert app_module.resolve_post_profile(None, "my-profile") == "my-profile"
def test_missing_profile_is_a_client_error(self):
with pytest.raises(HTTPException) as exc:
app_module.resolve_post_profile(None, None)
assert exc.value.status_code == 400
class TestScheduledPostsAreFilteredByProfile:
def test_other_tenants_rows_are_dropped(self, monkeypatch):
vendor_rows = {
"scheduled_posts": [
{"job_id": "mine-1", "profile_username": "os_mine"},
{"job_id": "theirs", "profile_username": OTHER_TENANT},
{"job_id": "mine-2", "profile_username": "os_mine"},
{"job_id": "nameless"}, # no profile at all: not ours
]
}
async def fake_get(api_key, url, params):
return vendor_rows
monkeypatch.setattr(app_module, "_upload_post_get", fake_get)
rows = asyncio.run(app_module._scheduled_posts_for("key", "os_mine"))
assert [r["job_id"] for r in rows] == ["mine-1", "mine-2"]
assert all(r.get("profile_username") == "os_mine" for r in rows)