"""Use the existing Supabase schema through each staff user's JWT and RLS.""" import json import logging from pathlib import Path import re import threading import time from urllib.parse import quote import httpx log=logging.getLogger('defectrag.cloud') _staff_cache={} _cache_lock=threading.Lock() def read_public_config(path): text=Path(path).read_text(encoding='utf8') output={} for source,key in (('supabaseUrl','url'),('supabasePublishableKey','key')): match=re.search(r'''["']?'''+source+r'''["']?\s*:\s*["']([^"']*)''',text) output[key]=match.group(1) if match else '' if not output['url'].startswith('https://') or not output['key'].startswith('sb_publishable_'): raise ValueError('Supabase public settings are not configured') return output class StaffRepository: table='shared_inspections' bucket='team-inspections' notes_table='staff_notes' storage_type='supabase' workspace='team' workspace_stats_enabled=False def __init__(self,config,token,artifacts): self.config,self.token,self.artifacts=config,token,Path(artifacts) self.headers={'apikey':config['key'],'Authorization':'Bearer '+token} if config.get('auth_workflow_enabled'): # Supabase verifies the JWT. No decoded/browser AAL or role is trusted. # Deliberately fresh for each protected operation: revocation must # not reuse the legacy 45-second membership cache before GPU work. posture=self.request('POST','/rest/v1/rpc/defectrag_auth_status',json={}) if (not isinstance(posture,dict) or posture.get('approved') is not True or posture.get('revoked') is not False or posture.get('authorized') is not True or type(posture.get('mfa_required')) is not bool or (posture['mfa_required'] and posture.get('aal2') is not True) or posture.get('role') not in ('staff','developer') or not posture.get('user_id')): raise ValueError('Approved staff and required authenticator verification are needed. Open Staff workspace.') self.user={'id':posture['user_id']} self.staff={'user_id':posture['user_id'],'role':posture['role'],'display_name':posture.get('display_name') or 'Staff member'} return # Do not trust decoded JWT claims. Supabase validates the token, and the # staff allowlist is read through its existing authenticated policies. with _cache_lock: cached=_staff_cache.get(token) if cached and cached[0]>time.time(): self.user,self.staff=cached[1:] else: self.user=self.request('GET','/auth/v1/user') rows=self.request('GET','/rest/v1/staff_members',params={'user_id':'eq.'+self.user['id'],'select':'user_id,display_name,role','limit':'1'}) if not rows: raise ValueError('Your account is not on the staff allowlist') self.staff=rows[0] with _cache_lock: if len(_staff_cache)>=256: _staff_cache.clear() _staff_cache[token]=(time.time()+45,self.user,self.staff) def request(self,method,path,**kwargs): ignore_conflict=kwargs.pop('ignore_conflict',False) headers={**self.headers,**kwargs.pop('headers',{})} try: with httpx.Client(timeout=30,trust_env=False) as client: response=client.request(method,self.config['url']+path,headers=headers,**kwargs) except httpx.HTTPError: raise RuntimeError('Cloud request did not complete. Retry the same submission to verify whether it was saved.') from None if not response.is_success: try: detail=response.json() code=detail.get('code',detail.get('error','unknown')) except (ValueError,AttributeError): code='unexpected_response' if ignore_conflict and response.status_code in (400,409) and code in ('23505','Duplicate','ResourceAlreadyExists','KeyAlreadyExists'): return None if response.status_code in (401,403): raise ValueError('Staff session expired or access denied. Sign in again.') if code in ('PGRST202','PGRST205'): raise ValueError('Required Supabase function/table is unavailable. Apply the reviewed additive migration.') raise RuntimeError(f'Supabase request failed ({response.status_code}, {code}); no durable success was reported.') return response.json() if response.content else None def decorate(self,row): if not row: return None record=dict(row['payload']) record['storage']=self.storage_type record['workspace']=self.workspace record['owner_id']=row['owner_id'] for kind in ('image','heatmap'): if self.config.get('auth_workflow_enabled'): # SessionRepository replaces these with scoped artifact URLs; # the backend fetches private bytes under the current user JWT. record[kind+'_url']=f"/api/inspections/{record['id']}/{kind}" continue result=self.request('POST','/storage/v1/object/sign/'+self.bucket+'/'+quote(row[kind+'_path'],safe='/'),json={'expiresIn':600}) signed=result.get('signedURL',result.get('signedUrl')) record[kind+'_url']=signed if signed.startswith('https://') else self.config['url']+'/storage/v1'+signed return record def private_artifact(self,identifier,kind): if kind not in ('image','heatmap'):raise ValueError('Invalid private artifact') row=self.raw(identifier) if row is None:raise ValueError('Private inspection is unavailable') try: with httpx.Client(timeout=25,trust_env=False) as client: with client.stream('GET',self.config['url']+'/storage/v1/object/authenticated/'+self.bucket+'/'+quote(row[kind+'_path'],safe='/'),headers=self.headers) as response: if not response.is_success:raise ValueError('Private artifact access denied') content=bytearray() for chunk in response.iter_bytes(chunk_size=65536): if len(content)+len(chunk)>10*1024*1024:raise ValueError('Private artifact exceeds the size limit') content.extend(chunk) if not content:raise ValueError('Private artifact is empty') return bytes(content) except httpx.HTTPError: raise RuntimeError('Private artifact could not be loaded. Retry later.') from None def raw(self,identifier,archived=False): rows=self.request('GET','/rest/v1/'+self.table,params={'id':'eq.'+identifier,'select':'*','limit':'1', 'archived_at':'not.is.null' if archived else 'is.null'}) return rows[0] if rows else None def save(self,record): paths={} for kind,suffix in (('image',''),('heatmap','_heatmap')): source=self.artifacts/f"{record['id']}{suffix}.jpg" destination=f"{self.user['id']}/{record['id']}/{kind}.jpg" self.request('POST','/storage/v1/object/team-inspections/'+destination, content=source.read_bytes(),headers={'Content-Type':'image/jpeg','x-upsert':'false'}) paths[kind+'_path']=destination payload={key:value for key,value in record.items() if not key.endswith('_url')} row={'id':record['id'],'owner_id':self.user['id'],'created_at':record['created_at'], 'payload':payload,'conversation':[],**paths} self.request('POST','/rest/v1/shared_inspections',json=row,headers={'Prefer':'return=minimal'}) return self.decorate(row) def get(self,identifier): return self.decorate(self.raw(identifier)) def raw_list(self,category='',verdict='',batch='',limit=100,offset=0,archived=False): params={'select':'id,owner_id,created_at,payload,image_path,heatmap_path,archived_at','archived_at':'not.is.null' if archived else 'is.null', 'order':'created_at.desc','limit':str(limit),'offset':str(offset)} for key,value in (('category',category),('verdict',verdict),('batch',batch)): if value: params['payload->>'+key]='eq.'+value return self.request('GET','/rest/v1/'+self.table,params=params) def list(self,category='',verdict='',batch='',limit=100,offset=0,archived=False): # Lists need no images until a record is opened. Avoid two storage API # calls per row for large history pages. rows=[] while len(rows)