File size: 22,908 Bytes
01864c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
"""HTTP regression tests with synthetic identity/storage/ML dependencies."""
import hashlib, hmac, json, sys, types, unittest, uuid
from unittest.mock import patch, Mock, MagicMock
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
# Import the real HTTP app without downloading/loading ML models.
# Keep lightweight HTTP stubs local to app import; other suites need the real engine.
_stub_names = ('src.transcription.engine', 'src.output.formatter')
_previous_modules = {name: sys.modules.get(name) for name in _stub_names}
try:
    for name, attr in [('src.transcription.engine','TranscriptionEngine'),('src.output.formatter','OutputFormatter')]:
     module=types.ModuleType(name);setattr(module,attr,Mock());module.NATIVE_MODELS={'yo':'ncair-yoruba','ig':'ncair-igbo','ha':'ncair-hausa'};module.native_asr_enabled=lambda:True;sys.modules[name]=module
    import app as api
finally:
    for name, previous in _previous_modules.items():
        if previous is None:
            sys.modules.pop(name, None)
        else:
            sys.modules[name] = previous
from fastapi.testclient import TestClient
from starlette.requests import Request

class SecurityTests(unittest.TestCase):
 def setUp(self):
  self.client=TestClient(api.app,raise_server_exceptions=False)
  self.jobs={};self.calls=[]
  def database(method,path,payload=None,params=None):
   self.calls.append((method,path,payload,params))
   if path.endswith('/complete_minutes'):return {'state':'settled'}
   if path.endswith('/transcription_jobs'):
    jid=(params or {}).get('job_id','eq.').removeprefix('eq.')
    if method=='GET':return [self.jobs[jid]] if jid in self.jobs else []
    if method=='PATCH':self.jobs[jid].update(payload);return [self.jobs[jid]]
   return []
  self.patches=[patch.object(api,'_verified_uid',lambda r:r.headers.get('authorization','').removeprefix('Bearer ') or None),
   patch.object(api,'_billing_profile',return_value={'credits':100,'plan':'free'}),
   patch.object(api,'_supabase_request',side_effect=database),
   patch.object(api,'_SUPABASE_URL','https://example.invalid'),patch.object(api,'_SUPABASE_KEY','synthetic'),
   patch.object(api,'_purge_old_jobs'),patch.object(api,'_paused',return_value=None),
   patch.object(api,'engine',types.SimpleNamespace(registry=types.SimpleNamespace(list_available_models=lambda:{'tiny':{}}))),
   patch.object(api,'_default_model_key',return_value='tiny'),patch.object(api,'_probe_duration_sec',return_value=60),
   patch.object(api,'_executor'),patch.object(api,'_reserve_work',return_value={'reserved':1}),patch.object(api,'_finish_work',return_value={'state':'settled'}),
   patch.object(api,'_WORK_SLOTS',Mock(acquire=Mock(return_value=True)))]
  for p in self.patches:p.start()
 def tearDown(self):
  for p in reversed(self.patches):p.stop()
 def headers(self,uid='owner'):return {'Authorization':'Bearer '+uid}
 def job(self,status='done'):
  jid=str(uuid.uuid4());self.jobs[jid]={'firebase_uid':'owner','status':status,'result':{'text':'private synthetic'},'progress':{'current':1,'total':2}};return jid
 def test_companion_requires_identity_before_reading_upload(self):
  response=self.client.post('/companion/transcribe',json={'id':str(uuid.uuid4())})
  self.assertEqual(response.status_code,401)
 def test_companion_retry_returns_existing_job_without_upload_or_charge(self):
  with patch('src.companion.load_upload',return_value={'job_id':'existing-job'}) as load, patch('src.companion.assemble_upload') as assemble:
   response=self.client.post('/companion/transcribe',json={'id':str(uuid.uuid4())},headers=self.headers())
  self.assertEqual(response.status_code,202)
  self.assertEqual(response.json()['job_id'],'existing-job')
  self.assertEqual(load.call_args.args[0],'owner')
  assemble.assert_not_called();api._reserve_work.assert_not_called();api._executor.submit.assert_not_called()
 def test_companion_database_duplicate_does_not_run_another_worker(self):
  with patch.object(api,'_reserve_work',return_value={'duplicate':True,'job_id':'original'}):
   response=self.client.post('/transcribe',files={'file':('test.wav',b'audio')},headers=self.headers())
  self.assertEqual(response.status_code,202)
  self.assertEqual(response.json()['job_id'],'original')
  api._executor.submit.assert_not_called();api._WORK_SLOTS.release.assert_called_once()
 def test_repetition_cleanup_does_not_log_transcript_content(self):
  private='Synthetic confidential meeting phrase'
  with patch.object(api,'_is_repetition_loop',return_value=True), self.assertLogs(api.logger,level='INFO') as captured:
   self.assertEqual(api._drop_repetition_segments([{'text':private}]),[])
  self.assertNotIn(private,' '.join(captured.output))
 def test_account_deletion_requires_identity(self):
  with patch.object(api._requests,'post') as send:
   response=self.client.post('/account/delete')
  self.assertEqual(response.status_code,401);send.assert_not_called()
 def test_account_deletion_preserves_pending_and_forwards_identity(self):
  for status,payload in [(200,{'deleted':True}),(202,{'requested':True,'pending':True})]:
   with patch.object(api._requests,'post',return_value=Mock(status_code=status,json=lambda:payload)) as send:
    response=self.client.post('/account/delete',headers=self.headers(),json={'firebase_uid':'someone-else'})
   self.assertEqual(response.status_code,status);self.assertEqual(response.json(),payload)
   self.assertEqual(send.call_args.kwargs['headers']['x-firebase-token'],'owner')
   self.assertEqual(send.call_args.kwargs['json'],{'confirm':'DELETE'})
 def test_account_deletion_preserves_reauthentication_and_ownership_errors(self):
  for status in [401,409]:
   with patch.object(api._requests,'post',return_value=Mock(status_code=status,json=lambda:{'error':'Action required'})):
    response=self.client.post('/account/delete',headers=self.headers())
   self.assertEqual(response.status_code,status);self.assertEqual(response.json()['detail'],'Action required')
 def test_account_deletion_transport_failure_is_retryable(self):
  with patch.object(api._requests,'post',side_effect=RuntimeError('offline')):
   response=self.client.post('/account/delete',headers=self.headers())
  self.assertEqual(response.status_code,503)
 def test_translation_invalid_input_does_not_reserve(self):
  r=self.client.post('/translate',headers=self.headers(),json={'target_language':'auto','segments':[{'text':'hello'}]})
  self.assertEqual(r.status_code,400);api._reserve_work.assert_not_called()
 def test_translation_cache_owner_bound_and_free(self):
  api._reserve_work.return_value={'cached':{'target_language':'es','texts':['hola']}}
  with patch('src.translation.translate_texts') as generate:
   r=self.client.post('/translate',headers=self.headers(),json={'target_language':'es','segments':[{'text':'hello'}],'firebase_uid':'other'})
  self.assertEqual(r.status_code,200,r.text);self.assertEqual(r.json()['credits_charged'],0)
  self.assertEqual(api._reserve_work.call_args.args[0],'owner');generate.assert_not_called();api._finish_work.assert_not_called()
 def test_translation_success_charges_five_and_failure_refunds(self):
  api._reserve_work.return_value={'reserved':5}
  with patch.dict(api.os.environ,{'ANTHROPIC_API_KEY':'synthetic'}), patch.object(api,'_anthropic_available',True), patch.object(api,'_anthropic',MagicMock(),create=True), patch('src.translation.translate_texts',return_value=['سلام']):
   r=self.client.post('/translate',headers=self.headers(),json={'target_language':'fa','segments':[{'text':'hello'}]})
  self.assertEqual(r.status_code,200,r.text);self.assertEqual(r.json()['credits_charged'],5)
  self.assertEqual(api._reserve_work.call_args.args[2],5)
  self.assertTrue(any(c[1].endswith('/complete_minutes') for c in self.calls))
  with patch.dict(api.os.environ,{'ANTHROPIC_API_KEY':''}):
   r=self.client.post('/translate',headers=self.headers(),json={'target_language':'fa','segments':[{'text':'hello'}]})
  self.assertEqual(r.status_code,503);api._finish_work.assert_called_once()
  self.assertFalse(api._finish_work.call_args.args[1])
 def test_anonymous_compute_rejected_before_body(self):
  for url in ['/transcribe','/minutes','/minutes/docx','/translate']:
   self.assertEqual(self.client.post(url,content=b'not-even-json').status_code,401)
  api._executor.submit.assert_not_called()
 def test_cross_user_cannot_read_or_cancel(self):
  jid=self.job()
  for path in ['result','status','progress']:
   self.assertEqual(self.client.get(f'/{path}/{jid}').status_code,401)
   self.assertEqual(self.client.get(f'/{path}/{jid}',headers=self.headers('other')).status_code,404)
  self.assertEqual(self.client.post(f'/cancel/{jid}',headers=self.headers('other')).status_code,404)
 def test_result_read_is_repeatable(self):
  jid=self.job()
  for _ in range(2):self.assertEqual(self.client.get('/result/'+jid,headers=self.headers()).json(),{'text':'private synthetic'})
  self.assertFalse(any(c[0]=='DELETE' for c in self.calls))
 def test_owner_cancel_only(self):
  jid=self.job('processing');r=self.client.post('/cancel/'+jid,headers=self.headers())
  self.assertEqual(r.status_code,200);self.assertEqual(self.jobs[jid]['status'],'cancelled')
 def test_identity_and_job_id_are_server_owned(self):
  for _ in range(2):
   r=self.client.post('/transcribe',headers=self.headers(),files={'file':('test.wav',b'fake')},data={'job_id':'attacker-selected','firebase_uid':'victim'})
   self.assertEqual(r.status_code,202,r.text);self.assertNotEqual(r.json()['job_id'],'attacker-selected')
  calls=api._reserve_work.call_args_list
  self.assertEqual(calls[0].args[0],'owner');self.assertNotEqual(calls[0].args[1],calls[1].args[1])
 def test_billing_outage_fails_closed(self):
  with patch.object(api,'_billing_profile',side_effect=api.HTTPException(503,'Billing unavailable')):
   self.assertEqual(self.client.post('/transcribe',headers=self.headers()).status_code,503)
  api._executor.submit.assert_not_called()
 def test_storage_outage_reservation_no_queue(self):
  api._reserve_work.side_effect=api.HTTPException(503,'unavailable')
  r=self.client.post('/transcribe',headers=self.headers(),files={'file':('test.wav',b'fake')})
  self.assertEqual(r.status_code,503);api._executor.submit.assert_not_called();api._WORK_SLOTS.release.assert_called_once()
 def test_queue_failure_refunds(self):
  api._executor.submit.side_effect=RuntimeError('queue offline')
  # Job exists in real SQL; patch status update for this synthetic queue failure.
  with patch.object(api,'_upsert_job'):
   r=self.client.post('/transcribe',headers=self.headers(),files={'file':('test.wav',b'fake')})
  self.assertEqual(r.status_code,503);self.assertFalse(api._finish_work.call_args.args[1]);api._WORK_SLOTS.release.assert_called_once()
 def test_audio_limits(self):
  for seconds,expected in [(None,400),(float('nan'),400),(7201,413)]:
   api._probe_duration_sec.return_value=seconds
   self.assertEqual(self.client.post('/transcribe',headers=self.headers(),files={'file':('test.wav',b'fake')}).status_code,expected)
  api._executor.submit.assert_not_called()
 def test_body_limit_before_parse(self):
  r=self.client.post('/minutes',headers={**self.headers(),'Content-Length':str(2*1024*1024)},content=b'{}')
  self.assertEqual(r.status_code,413)
 def test_suspended_account(self):
  api._billing_profile.return_value={'disabled_at':'2026-10-10'}
  self.assertEqual(self.client.get('/result/'+str(uuid.uuid4()),headers=self.headers()).status_code,403)
 def test_support_role_denied_before_session_lookup(self):
  from google.oauth2 import id_token
  api._supabase_request.side_effect=lambda *a,**k:[{'role':'support_admin','active':True}]
  with patch.object(id_token,'verify_firebase_token',return_value={'email':'support@example.invalid'}):
   r=self.client.post('/credits/admin-grant',headers=self.headers(),json={'firebase_uid':'owner','amount':10})
  self.assertEqual(r.status_code,403)
 def test_minutes_invalid_input_does_not_reserve(self):
  self.assertEqual(self.client.post('/minutes',headers=self.headers(),json={'segments':[{'text':42}]}).status_code,400)
  api._reserve_work.assert_not_called()
 def test_minutes_success_settles_and_failure_refunds(self):
  with patch.object(api,'_generate_minutes_with_claude',return_value={'summary':'synthetic'}):
   r=self.client.post('/minutes',headers=self.headers(),json={'segments':[{'text':'hello'}]})
  self.assertEqual(r.status_code,200);self.assertTrue(any(c[1].endswith('/complete_minutes') for c in self.calls))
  with patch.object(api,'_generate_minutes_with_claude',side_effect=RuntimeError('synthetic failure')):
   r=self.client.post('/minutes',headers=self.headers(),json={'segments':[{'text':'hello'}]})
  self.assertEqual(r.status_code,500);self.assertFalse(api._finish_work.call_args.args[1])
 def test_minutes_cached_output_never_regenerates_or_charges(self):
  api._reserve_work.return_value={'cached':{'summary':'cached synthetic'}}
  with patch.object(api,'_generate_minutes_with_claude') as generate:
   r=self.client.post('/minutes',headers=self.headers(),json={'segments':[{'text':'hello'}]})
  self.assertEqual(r.json(),{'summary':'cached synthetic'});generate.assert_not_called();api._finish_work.assert_not_called()
 def test_sandbox_and_unbound_apple_receipts_rejected(self):
  from src.apple_iap import account_token
  tx={'bundleId':api.APPLE_BUNDLE_ID,'productId':api.APPLE_PRODUCT_PREFIX+'starter','transactionId':'synthetic','type':'Consumable','environment':'Sandbox','appAccountToken':account_token('owner')}
  with patch('src.apple_iap.verify_jws',return_value=tx):
   r=self.client.post('/credits/apple',headers=self.headers(),json={'signed_transaction':'synthetic'})
   self.assertEqual(r.status_code,403)
   tx['environment']='Production';tx.pop('appAccountToken')
   self.assertEqual(self.client.post('/credits/apple',headers=self.headers(),json={'signed_transaction':'synthetic'}).status_code,403)
 def test_google_play_purchase_checks(self):
  from src.apple_iap import account_token
  pid=api.APPLE_PRODUCT_PREFIX+'starter'
  good={'purchaseState':0,'consumptionState':0,'orderId':'GPA.synthetic','obfuscatedExternalAccountId':account_token('owner'),'regionCode':'NG'}
  post=lambda body=None:self.client.post('/credits/google',headers=self.headers(),json=body or {'product_id':pid,'purchase_token':'synthetic'})
  with patch('src.google_play.get_purchase',return_value=dict(good,purchaseType=0)),patch('src.google_play.consume',return_value=True) as consume:
   self.assertEqual(post().status_code,403)  # test purchase on a normal account
  with patch('src.google_play.get_purchase',return_value=dict(good,obfuscatedExternalAccountId=account_token('someone-else'))):
   self.assertEqual(post().status_code,403)  # bought on another account
  with patch('src.google_play.get_purchase',return_value=dict(good,purchaseState=2)):
   self.assertEqual(post().status_code,409)  # payment still pending
  self.assertEqual(post({'product_id':'com.other.app.coins','purchase_token':'x'}).status_code,400)
  with patch('src.google_play.get_purchase',return_value=good),patch('src.google_play.consume',return_value=True) as consume,\
       patch.object(api,'_apply_credits',return_value=200) as credit:
   r=post()
   self.assertEqual(r.status_code,200);self.assertEqual(r.json()['credits_added'],100)
   credit.assert_called_once();self.assertEqual(credit.call_args.args[3],'google:GPA.synthetic');consume.assert_called_once()
 def test_google_play_refunds_reverse_credits_once(self):
  def database(method,path,payload=None,params=None):
   return [{'firebase_uid':'owner','delta':100}] if (params or {}).get('reference')=='eq.google:GPA.refunded' else []
  with patch('src.google_play.configured',return_value=True),\
       patch('src.google_play.voided_purchases',return_value=[{'orderId':'GPA.refunded'},{'orderId':'GPA.unknown'}]),\
       patch.object(api,'_supabase_request',side_effect=database),patch.object(api,'_apply_credits',return_value=0) as credit:
   self.assertEqual(api._google_voided_sync(),1)
  credit.assert_called_once_with('owner',-100,'refund','google-refund:GPA.refunded','Google Play refund: order GPA.refunded reversed')
 def test_webhook_signature_and_order_binding(self):
  with patch.dict(api.os.environ,{'PAYSTACK_SECRET_KEY':'synthetic-secret'}):
   self.assertEqual(self.client.post('/paystack/webhook',json={}).status_code,403)
   body=json.dumps({'event':'charge.success','data':{'reference':'synthetic-order','domain':'live','status':'success','amount':150000,'currency':'NGN','customer':{'email':'owner@example.invalid'},'metadata':{'firebase_uid':'victim','credits':999999}}}).encode()
   sig=hmac.new(b'synthetic-secret',body,hashlib.sha512).hexdigest()
   api._supabase_request.side_effect=lambda *a,**k:{'balance':100}
   r=self.client.post('/paystack/webhook',content=body,headers={'x-paystack-signature':sig})
   self.assertEqual(r.status_code,200)
   self.assertNotIn('firebase_uid',api._supabase_request.call_args.args[2])
   self.assertEqual(api._supabase_request.call_args.args[1],'/rest/v1/rpc/fulfill_payment_order')

class PaymentReliabilityTests(unittest.TestCase):
 def setUp(self):
  self.client=TestClient(api.app,raise_server_exceptions=False)
  self.secret=patch.dict(api.os.environ,{'PAYSTACK_SECRET_KEY':'synthetic-secret'});self.secret.start()
  self.auth=patch.object(api,'_require_uid',return_value='owner');self.auth.start()
  self.data={'reference':'order-1','domain':'live','status':'success','amount':150000,'currency':'NGN','customer':{'email':'buyer@example.invalid'}}
 def tearDown(self):
  self.auth.stop();self.secret.stop()
 def webhook(self,data=None):
  body=json.dumps({'event':'charge.success','data':self.data if data is None else data}).encode()
  return self.client.post('/paystack/webhook',content=body,headers={'x-paystack-signature':hmac.new(b'synthetic-secret',body,hashlib.sha512).hexdigest()})
 def test_failed_grants_are_not_acknowledged(self):
  for result in [None,{}, {'error':'unknown_order'}, {'error':'order_mismatch'}, {'balance':None}]:
   with patch.object(api,'_supabase_request',return_value=result):self.assertEqual(self.webhook().status_code,503)
 def test_duplicate_is_successful_and_malformed_charge_rejected(self):
  with patch.object(api,'_supabase_request',return_value={'already_credited':True}) as db:
   self.assertEqual(self.webhook().status_code,200)
   self.assertEqual(self.webhook({'domain':'live','status':'success','amount':True}).status_code,400)
   self.assertEqual(db.call_count,1)
 def test_verification_checks_order_ownership_before_provider(self):
  with patch.object(api,'_supabase_request',return_value=[]) as db,patch('src.payments.verified_charge') as verify:
   r=self.client.post('/paystack/verify',json={'reference':'order-1'})
   self.assertEqual(r.status_code,404);verify.assert_not_called()
   self.assertEqual(db.call_args.args[3]['firebase_uid'],'eq.owner')
 def test_verification_recovers_successful_charge(self):
  order={'reference':'order-1','credits':100,'fulfilled_at':None}
  with patch.object(api,'_supabase_request',side_effect=[[order],{'balance':130}]) as db,patch('src.payments.verified_charge',return_value=self.data):
   r=self.client.post('/paystack/verify',json={'reference':'order-1'})
   self.assertEqual(r.status_code,200,r.text);self.assertTrue(r.json()['credited'])
   self.assertEqual(db.call_args.args[1],'/rest/v1/rpc/fulfill_payment_order')
 def test_pending_and_test_money_never_credit(self):
  for change in [{'status':'pending'},{'domain':'test'}]:
   with patch.object(api,'_supabase_request',return_value=[{'credits':100,'fulfilled_at':None}]) as db,patch('src.payments.verified_charge',return_value={**self.data,**change}):
    r=self.client.post('/paystack/verify',json={'reference':'order-1'})
    self.assertFalse(r.json()['credited']);self.assertEqual(db.call_count,1)
 def test_already_fulfilled_does_not_require_paystack(self):
  with patch.object(api,'_supabase_request',return_value=[{'credits':100,'fulfilled_at':'today'}]),patch('src.payments.verified_charge') as verify:
   r=self.client.post('/paystack/verify',json={'reference':'order-1'})
   self.assertTrue(r.json()['credited']);verify.assert_not_called()

if __name__=='__main__':unittest.main()


class DiacriticsGuardTests(unittest.TestCase):
    def test_only_tone_marks_may_change(self):
        self.assertTrue(api._is_same_text_with_marks("Bawo ni, se daadaa ni?", "Báwo ni, ṣé dáadáa ni?"))
        self.assertFalse(api._is_same_text_with_marks(
            "Ne i Shin", "I cannot add proper tone marks to this text because it does not appear to contain recognizable Yoruba words."))
        self.assertFalse(api._is_same_text_with_marks("Mo fe lo raja", "I want to go shopping"))


class AdminCreditTests(unittest.TestCase):
    def setUp(self):
        self.client = TestClient(api.app, raise_server_exceptions=False)
        self.patches = [patch.object(api, '_require_staff', return_value='staff@example.invalid'),
                        patch.object(api, '_SUPABASE_URL', 'https://example.invalid'),
                        patch.object(api, '_SUPABASE_KEY', 'synthetic')]
        for p in self.patches: p.start()

    def tearDown(self):
        for p in reversed(self.patches): p.stop()

    def post(self):
        return self.client.post('/credits/admin-grant', json={'firebase_uid': 'user-1', 'amount': 100, 'note': 'test'})

    def test_grant_returns_new_balance(self):
        with patch.object(api._requests, 'post', return_value=Mock(status_code=200, text='{"balance": 130}', json=lambda: {'balance': 130})):
            r = self.post()
        self.assertEqual(r.status_code, 200); self.assertEqual(r.json(), {'balance': 130})

    def test_refusal_says_why(self):
        body = {'code': 'P0001', 'message': 'profile_not_found'}
        with patch.object(api._requests, 'post', return_value=Mock(status_code=400, text='x', json=lambda: body)):
            r = self.post()
        self.assertEqual(r.status_code, 409)
        self.assertIn('no NarratifAI profile', r.json()['detail'])


class NotifyTests(unittest.TestCase):
    def test_notification_saved_for_users_not_the_notetaker(self):
        with patch.object(api, '_supabase_request') as db:
            api._notify('user-1', 'transcript_ready', 'Transcript ready', 'Board meeting has been transcribed.', {'route': '/history'})
            api._notify(api.NOTETAKER_UID, 'transcript_ready', 'x', 'y', {})
            api._notify('', 'transcript_ready', 'x', 'y', {})
        self.assertEqual(db.call_count, 1)
        self.assertEqual(db.call_args.args[1], '/rest/v1/notifications')
        self.assertEqual(db.call_args.kwargs['payload']['firebase_uid'], 'user-1')

    def test_a_failing_notification_never_breaks_the_job(self):
        with patch.object(api, '_supabase_request', side_effect=RuntimeError('db down')):
            api._notify('user-1', 'transcript_failed', 'x', 'y', {})   # no exception