Spaces:
Running
Running
github-actions[bot] commited on
Commit Β·
ecebbf4
1
Parent(s): a440819
Deploy fd25b77
Browse filesA shared library was authorized, then hidden by the database (#409)
Source: https://github.com/WINTER4000/turingDNA/commit/fd25b77468ab6368bb1562ead495fcb6e3cc17d4
Files changed (3)
39 unmodified lines4041424344451980 unmodified lines20262027202820292030203111 unmodified lines204320442045204620472048204920502051205220532054205539 unmodified linesfrom __future__ import annotationsimport hashlibimport hmacimport json1980 unmodified linesreturn hdef _user_pgrst_headers(extra: Optional[Dict[str, str]] = None) -> Dict[str, str]:"""Headers for a per-user PostgREST call made AS THE USER.11 unmodified linesof defence, and makes rollout reversible (unset SUPABASE_ANON_KEY torevert). Only ever call this from a synchronous request-context handler;background threads have no ``g`` and must use ``_supabase_headers``."""h: Dict[str, str]try:auth = get_auth()except Exception: # noqa: BLE001 β defensive: no request contextauth = AuthContext()if SUPABASE_ANON_KEY and auth.token and not auth.anonymous:h = {"apikey": SUPABASE_ANON_KEY,"Authorization": f"Bearer {auth.token}",39 unmodified lines40414243444546471980 unmodified lines202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208811 unmodified lines21002101210221032104210521062107210821092110211121122113211421152116211739 unmodified linesfrom __future__ import annotationsimport contextlibimport contextvarsimport hashlibimport hmacimport json1980 unmodified linesreturn h# Set ONLY while project_workspaces.shared_artifact runs one owner-scoped# loader for a read the membership RPC has just authorized. See# reading_for_a_member below for why, and why it is this narrow._READING_FOR_A_MEMBER: "contextvars.ContextVar[Optional[str]]" = \contextvars.ContextVar("dee_reading_for_a_member", default=None)@contextlib.contextmanagerdef reading_for_a_member(owner_id: str):"""Run ONE owner-scoped loader as the owner, for a read 0068 authorized.THE BUG THIS CLOSES. A variant library shared into a project opened forits owner and answered "Library not found." to every collaborator, andthree changes in a row fixed something adjacent to it: the bench pointerand the link diverging (2026-11-23), the link never being made (#406),the id's two spellings (#408). Each was real. None was this.shared_artifact's order is the whole security property: the RPCauthorizes with the CALLER's JWT and returns the owner and the id, then"the owner-scoped loader runs with exactly those". But every loaderbuilds its PostgREST call with _user_pgrst_headers, which sends theREQUESTER's JWT β so the owner-scoped query ran as the collaborator, andRow-Level Security answered it as the collaborator. For plasmids, CRISPRdesigns and primer sets that happened to work: 0056 gave each table a`*_select_shared` policy for a member reading the owner's linked rows.`libraries` never got one. It has `libraries_select_own` and nothingelse, so the row came back empty, load_library returned None, andshared_artifact said "Result no longer available." β after the RPC hadsaid yes. It is also why an EDITOR's contributed plasmid could not beopened by anybody else: those `_select_shared` policies only cover rowsthe project's owner authored, and the RPC names the author.WHY THIS IS SAFE, AND WHY IT IS THIS SHAPE. The loader still filters on`id=eq.` and `user_id=eq.`, and both values come from the RPC, never theclient; the RPC is asked again after the fetch, so a membership revokedmeanwhile still receives nothing. That was always the design β the RLSbackstop was added under it later and silently overruled it for the onetable without a shared policy. A database policy for libraries wouldhave fixed owner-authored libraries only, and only once a migration wasapplied by hand; an editor's round-2 library would still be refused.A context variable rather than a parameter, so the four loaders andevery other caller of them stay exactly as they are. Reset in `finally`,and per-thread by construction: a request on another thread, or thenext request on this one, sees the default and is sent as its user."""if not owner_id:raise ValueError("reading_for_a_member needs the owner the RPC named")token = _READING_FOR_A_MEMBER.set(str(owner_id))try:yieldfinally:_READING_FOR_A_MEMBER.reset(token)def _user_pgrst_headers(extra: Optional[Dict[str, str]] = None) -> Dict[str, str]:"""Headers for a per-user PostgREST call made AS THE USER.11 unmodified linesof defence, and makes rollout reversible (unset SUPABASE_ANON_KEY torevert). Only ever call this from a synchronous request-context handler;background threads have no ``g`` and must use ``_supabase_headers``.The one exception is reading_for_a_member above: a loader run for a readthe membership RPC already authorized is sent as the server, because therequester it would otherwise be sent as is, by definition, not the owner."""h: Dict[str, str]try:auth = get_auth()except Exception: # noqa: BLE001 β defensive: no request contextauth = AuthContext()if SUPABASE_ANON_KEY and auth.token and not auth.anonymous \and _READING_FOR_A_MEMBER.get() is None:h = {"apikey": SUPABASE_ANON_KEY,"Authorization": f"Bearer {auth.token}",
170 unmodified lines171172173174175176177170 unmodified linesloader = loaders.get(result.get('kind'))if not loader or not result.get('owner_id') or not result.get('artifact_id'):raise WorkspaceError('Result unavailable.', 404)artifact = loader(result['owner_id'], result['artifact_id'])if not artifact:raise WorkspaceError('Result no longer available.', 404)# Recheck after a potentially slow storage fetch; a revoked membership170 unmodified lines171172173174175176177178179180181182183184170 unmodified linesloader = loaders.get(result.get('kind'))if not loader or not result.get('owner_id') or not result.get('artifact_id'):raise WorkspaceError('Result unavailable.', 404)# AS THE OWNER, because the RPC just said so. Without this the loader's# query carried the requester's JWT, Row-Level Security answered it as# the requester, and `libraries` β the one artifact table with no# `_select_shared` policy β returned nothing to every collaborator: a# shared library said "Library not found." after the membership check# had authorized it. See auth.reading_for_a_member.with auth_module.reading_for_a_member(result['owner_id']):artifact = loader(result['owner_id'], result['artifact_id'])if not artifact:raise WorkspaceError('Result no longer available.', 404)# Recheck after a potentially slow storage fetch; a revoked membership
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291"""A variant library shared into a project opens for the collaborator.
Reported again 2026-11-27, after three fixes in a row: a library generated onone account, the project shared to a second, and the second account's Librarytab said "Library not found." Each earlier fix was real and adjacent β thebench pointer and the link diverging, the link never being made (#406), theid's two spellings (#408). None of them was this.
The membership RPC authorized the read and named the owner. The owner-scopedloader then ran its PostgREST query with the REQUESTER's JWT(_user_pgrst_headers), so Row-Level Security answered as the collaborator.`libraries` has `libraries_select_own` and no `_select_shared` policy β theother three artifact tables got one in 0056 β so the row came back empty.
Every earlier test of this path replaced load_library with a lambda, which iswhy it survived: the bug lived in the headers the real loader sends. Thesetests run the REAL loaders against a fake PostgREST that enforces the realpolicies, keyed on the bearer token, exactly as the database does."""import jsonimport urllib.parseimport urllib.requestfrom types import SimpleNamespace
import pytest
from dee import auth as Afrom dee import serverfrom dee.core import project_workspaces as ws
OWNER = '00000000-0000-4000-8000-0000000000a1'EDITOR = '00000000-0000-4000-8000-0000000000a2'RECIPIENT = '00000000-0000-4000-8000-0000000000a3'PROJECT = '00000000-0000-4000-8000-000000000010'LIB32 = '3f2a9c1e5b7d4e6fa1b2c3d4e5f60718' # minted by the engine: uuid4().hexLIB = '3f2a9c1e-5b7d-4e6f-a1b2-c3d4e5f60718' # what Postgres hands backPLASMID = '00000000-0000-4000-8000-000000000020' # an EDITOR's contribution
SERVICE = 'service-key'ANON = 'anon-key'
def _jwt(uid): return 'jwt-of-' + uid
class _Resp: def __init__(self, body, status=200): self._body = body.encode('utf-8') if isinstance(body, str) else body self.status = status
def read(self): return self._body
def __enter__(self): return self
def __exit__(self, *exc): return False
class FakeSupabase: """PostgREST + Storage with the policies the real tables carry.
libraries: libraries_select_own (0014) plasmids: select_own + plasmids_select_shared, which only admits rows the PROJECT OWNER authored and linked (0056) The service key bypasses RLS, as it does in Supabase. """
def __init__(self): self.libraries = [{ 'id': LIB, 'user_id': OWNER, 'name': 'MSTN round 1', 'created_at': '2026-11-27T00:00:00Z', 'wt_identifier': 'MSTN', 'wt_protein': 'MQKLQLCVYI', 'host_organism': 'E. coli', 'n_variants': 2, 'top_fitness': 1.5, # The CSV lives at the 32-hex path the engine minted (#408). 'storage_path': f'{OWNER}/{LIB32}.csv', 'expires_at': None, }] self.plasmids = [{ 'id': PLASMID, 'user_id': EDITOR, 'name': 'pMSTN-opt', 'sequence': 'ACGTACGT', 'features': [], 'topology': 'circular', 'created_at': '2026-11-27T00:00:00Z', 'meta': {}, }] self.project = {'id': PROJECT, 'user_id': OWNER, 'members': {RECIPIENT, EDITOR}, 'plasmid_ids': [PLASMID]} self.csv = ('Rank,Mutations,Fitness_Score,Optimized_DNA_Seq\n' '1,A12G,1.5,ATGGCC\n2,L40V,1.2,ATGCTG\n') self.seen = [] # (table, bearer)
def _who(self, req): auth = req.get_header('Authorization') or '' bearer = auth.split(' ', 1)[1] if ' ' in auth else '' if bearer == SERVICE: return 'service' if bearer.startswith('jwt-of-'): return bearer[len('jwt-of-'):] return None
def urlopen(self, req, timeout=None): url = urllib.parse.urlparse(req.full_url) who = self._who(req) if url.path.startswith('/storage/v1/object/libraries/'): self.seen.append(('storage', who)) path = url.path[len('/storage/v1/object/libraries/'):] if who != 'service' or path != self.libraries[0]['storage_path']: raise urllib.error.HTTPError(req.full_url, 404, 'not found', {}, None) return _Resp(self.csv) table = url.path.rsplit('/', 1)[-1] q = urllib.parse.parse_qs(url.query) self.seen.append((table, who)) want_id = (q.get('id') or [''])[0].replace('eq.', '') want_user = (q.get('user_id') or [''])[0].replace('eq.', '') rows = getattr(self, table, None) if rows is None: return _Resp('[]') out = [] for r in rows: if r['id'] != want_id or (want_user and r['user_id'] != want_user): continue if who == 'service': out.append(r) elif who == r['user_id']: # *_select_own out.append(r) elif table == 'plasmids' and who in self.project['members'] \ and r['user_id'] == self.project['user_id'] \ and r['id'] in self.project['plasmid_ids']: # plasmids_select_shared out.append(r) # libraries: no shared policy. Nothing else is visible. return _Resp(json.dumps(out[:1]))
@pytest.fixturedef db(monkeypatch): fake = FakeSupabase() monkeypatch.setattr(A, 'SUPABASE_URL', 'https://db.test') monkeypatch.setattr(A, 'SUPABASE_SERVICE_KEY', SERVICE) monkeypatch.setattr(A, 'SUPABASE_ANON_KEY', ANON) monkeypatch.setattr(urllib.request, 'urlopen', fake.urlopen) return fake
def _as(monkeypatch, uid): who = SimpleNamespace(anonymous=False, user_id=uid, token=_jwt(uid)) monkeypatch.setattr(A, 'get_auth', lambda: who) monkeypatch.setattr(server._auth, 'get_auth', lambda: who) return who
def _authorizing_rpc(kind, owner, artifact, calls): """0068's `artifact` action, saying yes β and naming the owner.""" def rpc(auth_module, auth, action, project_id=None, payload=None): calls.append((action, project_id, dict(payload or {}), auth.token)) return {'owner_id': owner, 'artifact_id': artifact, 'kind': kind} return rpc
# ββ the report βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def test_the_collaborator_opens_the_library_the_membership_check_authorized(db, monkeypatch): _as(monkeypatch, RECIPIENT) calls = [] monkeypatch.setattr(ws, 'rpc', _authorizing_rpc('library', OWNER, LIB, calls)) client = server.create_app().test_client()
# The id the owner's session holds is the minted 32-hex spelling. r = client.get('/api/library/' + LIB32 + '?project=' + PROJECT)
assert r.status_code == 200, r.get_json() body = r.get_json() assert body['ok'] and body['shared'] is True and body['reopened'] is True assert body['library_id'] == LIB assert [v['Mutations'] for v in body['variants']] == ['A12G', 'L40V'] # Authorized with the CALLER's JWT, before and after the fetch. assert [c[0] for c in calls] == ['artifact', 'artifact'] assert all(c[3] == _jwt(RECIPIENT) for c in calls) # Nothing private crossed. assert 'storage_path' not in r.get_data(as_text=True) assert OWNER not in r.get_data(as_text=True)
def test_the_collaborators_own_lookup_still_goes_as_the_collaborator(db, monkeypatch): """The route tries the caller's own row first. That read must stay under RLS as the caller β it is what lets a guessed id return nothing.""" _as(monkeypatch, RECIPIENT) monkeypatch.setattr(ws, 'rpc', _authorizing_rpc('library', OWNER, LIB, [])) server.create_app().test_client().get('/api/library/' + LIB + '?project=' + PROJECT) lib_reads = [w for t, w in db.seen if t == 'libraries'] assert lib_reads == [RECIPIENT, 'service'], db.seen
def test_a_refusal_still_reads_as_not_found_and_never_loads(db, monkeypatch): _as(monkeypatch, RECIPIENT)
def refuse(*a, **k): raise ws.WorkspaceError('Result unavailable.', 403) monkeypatch.setattr(ws, 'rpc', refuse) r = server.create_app().test_client().get('/api/library/' + LIB + '?project=' + PROJECT) assert r.status_code == 404 # The only libraries read was the caller's own, as the caller. assert [w for t, w in db.seen if t == 'libraries'] == [RECIPIENT]
def test_without_a_project_there_is_no_membership_read_at_all(db, monkeypatch): _as(monkeypatch, RECIPIENT) monkeypatch.setattr(ws, 'rpc', lambda *a, **k: pytest.fail('no project, no RPC')) r = server.create_app().test_client().get('/api/library/' + LIB) assert r.status_code == 404 assert 'service' not in [w for t, w in db.seen if t == 'libraries']
def test_the_owner_still_reads_their_own_library_as_themselves(db, monkeypatch): """The RLS backstop is intact everywhere else.""" _as(monkeypatch, OWNER) monkeypatch.setattr(ws, 'rpc', lambda *a, **k: pytest.fail('the owner never needs the RPC')) monkeypatch.setattr(A, 'attach_library_async', lambda *a, **k: None) r = server.create_app().test_client().get('/api/library/' + LIB32 + '?project=' + PROJECT) assert r.status_code == 200 assert [w for t, w in db.seen if t == 'libraries'] == [OWNER]
# ββ the same hole, for the other kind it hid βββββββββββββββββββββββββββββ
def test_an_editors_contributed_plasmid_opens_for_another_member(db, monkeypatch): """plasmids_select_shared admits only rows the project OWNER authored, and the RPC names the AUTHOR. So an editor's contribution was authorized and then hidden from everybody else β the same bug, on a table that did have a shared policy.""" who = _as(monkeypatch, RECIPIENT) monkeypatch.setattr(ws, 'rpc', _authorizing_rpc('plasmid', EDITOR, PLASMID, [])) kind, shaped = ws.shared_artifact(A, who, PROJECT, {'kind': 'plasmid', 'artifact_id': PLASMID}) assert kind == 'plasmid' and shaped['id'] == PLASMID and shaped['name'] == 'pMSTN-opt' assert 'meta' not in shaped and 'user_id' not in shaped
# ββ the scope of the exception βββββββββββββββββββββββββββββββββββββββββββ
def test_the_exception_ends_with_the_loader(db, monkeypatch): who = _as(monkeypatch, RECIPIENT) monkeypatch.setattr(ws, 'rpc', _authorizing_rpc('library', OWNER, LIB, [])) ws.shared_artifact(A, who, PROJECT, {'kind': 'library', 'artifact_id': LIB}) assert A._READING_FOR_A_MEMBER.get() is None assert A._user_pgrst_headers()['Authorization'] == 'Bearer ' + _jwt(RECIPIENT)
def test_the_exception_ends_even_when_the_loader_raises(db, monkeypatch): who = _as(monkeypatch, RECIPIENT) monkeypatch.setattr(ws, 'rpc', _authorizing_rpc('library', OWNER, LIB, []))
def boom(owner, lid): assert A._user_pgrst_headers()['Authorization'] == 'Bearer ' + SERVICE raise RuntimeError('storage fell over') monkeypatch.setattr(A, 'load_library', boom) with pytest.raises(RuntimeError): ws.shared_artifact(A, who, PROJECT, {'kind': 'library', 'artifact_id': LIB}) assert A._READING_FOR_A_MEMBER.get() is None assert A._user_pgrst_headers()['Authorization'] == 'Bearer ' + _jwt(RECIPIENT)
def test_the_loader_runs_with_exactly_the_owner_and_id_the_rpc_named(db, monkeypatch): """Never the client's: the client asked for LIB32 and a different owner would be meaningless to it anyway.""" who = _as(monkeypatch, RECIPIENT) monkeypatch.setattr(ws, 'rpc', _authorizing_rpc('library', OWNER, LIB, [])) got = [] monkeypatch.setattr(A, 'load_library', lambda owner, lid: got.append((owner, lid)) or { 'library_id': lid, 'variants': []}) ws.shared_artifact(A, who, PROJECT, {'kind': 'library', 'artifact_id': LIB32}) assert got == [(OWNER, LIB)]
def test_a_membership_revoked_during_the_fetch_still_receives_nothing(db, monkeypatch): who = _as(monkeypatch, RECIPIENT) n = {'calls': 0}
def rpc(auth_module, auth, action, project_id=None, payload=None): n['calls'] += 1 if n['calls'] > 1: raise ws.WorkspaceError('Project or invitation unavailable.', 403) return {'owner_id': OWNER, 'artifact_id': LIB, 'kind': 'library'} monkeypatch.setattr(ws, 'rpc', rpc) with pytest.raises(ws.WorkspaceError): ws.shared_artifact(A, who, PROJECT, {'kind': 'library', 'artifact_id': LIB}) assert n['calls'] == 2
def test_the_override_refuses_to_start_without_an_owner(): with pytest.raises(ValueError): with A.reading_for_a_member(''): pass assert A._READING_FOR_A_MEMBER.get() is Nonedee/auth.py+63-1
dee/core/project_workspaces.py+8-1
tests/test_a_shared_library_opens_for_the_collaborator.pyAdded+291