"""Automatic tenant lookup: real encrypted temp SQL, synthetic user-info API.""" import importlib.util import json import sys from pathlib import Path from types import SimpleNamespace import httpx import pytest from test_credential_api import env,authorize spec=importlib.util.spec_from_file_location('approval_identity_test',Path(__file__).resolve().parents[1]/'scripts/approval_identity.py') identity=importlib.util.module_from_spec(spec);spec.loader.exec_module(identity) @pytest.mark.parametrize('failure',[None,'wrong_user','expired','permission','missing_tenant','redirect']) async def test_in_container_lookup_is_readonly_and_never_refreshes(env,monkeypatch,capsys,failure): await authorize(env) from relay import config monkeypatch.setattr(config,'Settings',lambda **kw:env['settings']) credentials=env['api'].broker.store if failure=='expired': old=credentials.get('test','cli_test','ou_a') credentials.save('test','cli_test','ou_a',expected_version=old.version, access_token='fake-expired-access',refresh_token='fake-refresh-private', access_expires_at=1,refresh_expires_at=9999999999,scopes=['read']) before='\n'.join(env['store'].db.iterdump());calls=[] def platform(request): calls.append(request) assert request.method=='GET'and request.url.path=='/open-apis/authen/v1/user_info' assert request.url.host=='work.example.test' if failure=='permission':return httpx.Response(403,json={'code':99991679}) if failure=='redirect':return httpx.Response(302,headers={'Location':'https://unapproved.example.test'}) data={'open_id':'ou_other'if failure=='wrong_user'else'ou_a', 'tenant_key':'tenant_verified','name':'synthetic-private-user','email':'synthetic-private@example.test'} if failure=='missing_tenant':data.pop('tenant_key') return httpx.Response(200,json={'code':0,'data':data}) original=httpx.Client monkeypatch.setattr(httpx,'Client',lambda **kwargs:original(**kwargs,transport=httpx.MockTransport(platform))) exec(identity.DISCOVERY_CODE,{}) output=capsys.readouterr().out;result=json.loads(output) if failure is None: assert result=={'status':'verified','tenant_key':'tenant_verified','app_id':'cli_test','environment':'test'} else: assert result['status']=='tenant_discovery_unavailable' diagnostic=result['diagnostic'] if failure=='expired':assert diagnostic['expired_access']==1 elif failure=='wrong_user':assert diagnostic['user_mismatch']==1 elif failure=='missing_tenant':assert diagnostic['missing_tenant']==1 else:assert diagnostic['platform_rejected']==1 assert len(calls)==(0 if failure=='expired'else 1) assert '\n'.join(env['store'].db.iterdump())==before assert env['platform'].refreshes==0 assert all(secret not in output for secret in ('fake-access','fake-refresh','synthetic-private','email')) @pytest.mark.parametrize('mutate',[{'app_id':'different'},{'environment':'production'}, {'tenant_key':'invalid tenant'},{'status':'unavailable'},{'extra':'forbidden'}]) def test_lookup_rejects_mismatched_container_metadata(monkeypatch,mutate): body={'status':'verified','tenant_key':'tenant_verified','app_id':'cli_test','environment':'test',**mutate} calls=[] def run(args,**kwargs):calls.append((args,kwargs));return SimpleNamespace(returncode=0,stdout=json.dumps(body)) monkeypatch.setattr(identity.subprocess,'run',run) with pytest.raises(ValueError):identity.discover_tenant('synthetic-connector',{'HN_FEISHU_APP_ID':'cli_test','HN_ENVIRONMENT':'test'}) assert calls[0][0]==['docker','exec','-i','synthetic-connector','python','-'] def test_prepare_never_asks_user_for_tenant_or_prints_verification_token(tmp_path,monkeypatch,capsys): output=tmp_path/'callback.json' env=['HN_FEISHU_APP_ID=cli_test','HN_ENVIRONMENT=test','HN_FEISHU_VERIFICATION_TOKEN=synthetic-private-verify'] monkeypatch.setattr(sys,'argv', ['approval_identity.py','--output',str(output)]) monkeypatch.setattr(identity.subprocess,'run',lambda *a,**kw:SimpleNamespace(returncode=0,stdout=json.dumps(env))) monkeypatch.setattr(identity,'discover_tenant',lambda *a:'tenant_verified') def forbidden(*a):raise AssertionError('No interactive identity fields should be requested') monkeypatch.setattr('builtins.input',forbidden) monkeypatch.setattr(identity.getpass,'getpass',forbidden) identity.main() assert json.loads(output.read_text())=={'tenant_key':'tenant_verified','verification_token':'synthetic-private-verify'} assert 'synthetic-private-verify'not in capsys.readouterr().out def test_diagnostic_whitelist_drops_secrets_and_untrusted_strings(): assert identity.safe_diagnostic({'stage':'user_info','http_status':403,'platform_code':99991679, 'email':'private@example.test','access_token':'private-secret','error_class':'private-secret', 'matched_bindings':True,'expired_access':-1})=={'stage':'user_info','http_status':403,'platform_code':99991679} def test_diagnose_does_not_prompt_or_write(tmp_path,monkeypatch,capsys): monkeypatch.setattr(sys,'argv',['approval_identity.py','--diagnose']) monkeypatch.setattr(identity.subprocess,'run',lambda *a,**kw:SimpleNamespace(returncode=0,stdout='[]')) monkeypatch.setattr(identity,'discover_tenant',lambda *a:'tenant_verified') def forbidden(*a):raise AssertionError('Diagnostic must not prompt') monkeypatch.setattr(identity.getpass,'getpass',forbidden) identity.main() assert '"status": "verified"'in capsys.readouterr().out assert not list(tmp_path.iterdir()) def test_failed_discovery_reports_only_safe_stage_counts(monkeypatch,capsys): body={'status':'tenant_discovery_unavailable','diagnostic':{'stage':'user_info', 'expired_access':2,'network_errors':0,'access_token':'do-not-print','name':'do-not-print'}} monkeypatch.setattr(identity.subprocess,'run',lambda *a,**kw:SimpleNamespace(returncode=0,stdout=json.dumps(body))) with pytest.raises(ValueError):identity.discover_tenant('connector',{}) output=capsys.readouterr().out assert '"expired_access": 2'in output and 'do-not-print'not in output