fix(deploy): report safe tenant discovery stages without changing services
This commit is contained in:
@@ -19,6 +19,9 @@ from relay.config import Settings
|
||||
from relay.credential_store import CredentialStore,CredentialKeyring
|
||||
from relay.store import Postgres
|
||||
|
||||
diag={'stage':'settings','matched_bindings':0,'expired_access':0,'credential_errors':0,
|
||||
'user_mismatch':0,'missing_tenant':0,'platform_rejected':0,'network_errors':0}
|
||||
|
||||
def discover():
|
||||
s=Settings(role='connector')
|
||||
target=urlsplit(s.feishu_api_base)
|
||||
@@ -27,6 +30,7 @@ def discover():
|
||||
raise ValueError()
|
||||
target.port
|
||||
if s.credential_mode!='broker' or not s.credential_keyring_file:raise ValueError()
|
||||
diag['stage']='database_connect'
|
||||
if s.database_url:
|
||||
db=Postgres(s.database_url)
|
||||
db.execute('SET default_transaction_read_only TO on')
|
||||
@@ -35,48 +39,96 @@ def discover():
|
||||
db=sqlite3.connect((s.data_dir/'metadata.sqlite').resolve().as_uri()+'?mode=ro',uri=True,timeout=2)
|
||||
db.row_factory=sqlite3.Row
|
||||
try:
|
||||
diag['stage']='credentials_query'
|
||||
rows=db.execute('''SELECT c.principal_id FROM work_credentials_v2 c
|
||||
JOIN devices d ON d.owner=c.principal_id
|
||||
WHERE c.environment=? AND c.app_id=? AND d.revoked=0
|
||||
ORDER BY c.updated_at DESC LIMIT 3''',(s.environment,s.feishu_app_id)).fetchall()
|
||||
diag['matched_bindings']=len(rows)
|
||||
# Reuse the existing getter WITHOUT running its schema constructor.
|
||||
diag['stage']='keyring'
|
||||
credentials=CredentialStore.__new__(CredentialStore)
|
||||
credentials.db=db;credentials.keyring=CredentialKeyring.from_file(s.credential_keyring_file)
|
||||
with httpx.Client(base_url=s.feishu_api_base.rstrip('/'),trust_env=False,
|
||||
follow_redirects=False,timeout=httpx.Timeout(3,connect=2))as client:
|
||||
for row in rows:
|
||||
try:
|
||||
diag['stage']='credential_read'
|
||||
value=credentials.get(s.environment,s.feishu_app_id,row['principal_id'])
|
||||
if not value or value.access_expires_at<=time.time()+10:continue
|
||||
if not value or value.access_expires_at<=time.time()+10:
|
||||
diag['expired_access']+=1
|
||||
continue
|
||||
diag['stage']='user_info'
|
||||
with client.stream('GET','/open-apis/authen/v1/user_info',
|
||||
headers={'Authorization':'Bearer '+value.access_token})as response:
|
||||
if response.status_code!=200:continue
|
||||
diag['http_status']=response.status_code
|
||||
if response.status_code!=200:
|
||||
diag['platform_rejected']+=1
|
||||
continue
|
||||
body=bytearray()
|
||||
for chunk in response.iter_bytes():
|
||||
body.extend(chunk)
|
||||
if len(body)>65536:raise ValueError()
|
||||
data=json.loads(body)
|
||||
info=data.get('data',{})
|
||||
if data.get('code')!=0 or not isinstance(info,dict):continue
|
||||
if info.get('open_id')!=row['principal_id']:continue
|
||||
if type(data.get('code'))is int:diag['platform_code']=data['code']
|
||||
if data.get('code')!=0 or not isinstance(info,dict):
|
||||
diag['platform_rejected']+=1
|
||||
continue
|
||||
if info.get('open_id')!=row['principal_id']:
|
||||
diag['user_mismatch']+=1
|
||||
continue
|
||||
tenant=info.get('tenant_key')
|
||||
if not isinstance(tenant,str)or not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',tenant):continue
|
||||
if not isinstance(tenant,str)or not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',tenant):
|
||||
diag['missing_tenant']+=1
|
||||
continue
|
||||
return {'status':'verified','tenant_key':tenant,'app_id':s.feishu_app_id,'environment':s.environment}
|
||||
except Exception:continue
|
||||
except httpx.HTTPError as error:
|
||||
diag['network_errors']+=1
|
||||
diag['error_class']=type(error).__name__
|
||||
continue
|
||||
except Exception as error:
|
||||
diag['credential_errors']+=1
|
||||
diag['error_class']=type(error).__name__
|
||||
continue
|
||||
raise ValueError()
|
||||
finally:db.close()
|
||||
|
||||
try:print(json.dumps(discover()))
|
||||
except Exception:print(json.dumps({'status':'tenant_discovery_unavailable'}))
|
||||
except Exception as error:
|
||||
if not any(diag.get(k)for k in ('expired_access','credential_errors','user_mismatch','missing_tenant','platform_rejected','network_errors')):
|
||||
diag['error_class']=type(error).__name__
|
||||
print(json.dumps({'status':'tenant_discovery_unavailable','diagnostic':diag}))
|
||||
"""
|
||||
|
||||
|
||||
def safe_diagnostic(value):
|
||||
if not isinstance(value,dict):return {}
|
||||
result={}
|
||||
if value.get('stage')in {'settings','database_connect','credentials_query','keyring','credential_read','user_info'}:
|
||||
result['stage']=value['stage']
|
||||
if value.get('error_class')in {'ValidationError','OperationalError','ProgrammingError','UndefinedTable',
|
||||
'UndefinedColumn','CredentialError','PermissionError','FileNotFoundError','ReadOnlySqlTransaction',
|
||||
'ConnectError','ConnectTimeout','ReadTimeout','SSLError','ValueError','TypeError'}:
|
||||
result['error_class']=value['error_class']
|
||||
for key in ('matched_bindings','expired_access','credential_errors','user_mismatch','missing_tenant',
|
||||
'platform_rejected','network_errors','http_status','platform_code'):
|
||||
number=value.get(key)
|
||||
if type(number)is int and 0<=number<=2147483647:result[key]=number
|
||||
return result
|
||||
|
||||
|
||||
def discover_tenant(container,env):
|
||||
result=subprocess.run(['docker','exec','-i',container,'python','-'],input=DISCOVERY_CODE,
|
||||
stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True,timeout=25)
|
||||
try:
|
||||
if result.returncode or len(result.stdout)>4096:raise ValueError()
|
||||
if result.returncode or len(result.stdout)>4096:
|
||||
print('TENANT_DIAGNOSTIC '+json.dumps({'stage':'container_execution','exit_code':result.returncode}))
|
||||
raise ValueError()
|
||||
value=json.loads(result.stdout)
|
||||
if isinstance(value,dict)and value.get('status')=='tenant_discovery_unavailable':
|
||||
print('TENANT_DIAGNOSTIC '+json.dumps(safe_diagnostic(value.get('diagnostic'))))
|
||||
raise ValueError()
|
||||
if (set(value)!={'status','tenant_key','app_id','environment'}or value['status']!='verified'
|
||||
or value['app_id']!=env.get('HN_FEISHU_APP_ID')
|
||||
or value['environment']!=env.get('HN_ENVIRONMENT','production')
|
||||
@@ -90,10 +142,11 @@ def discover_tenant(container,env):
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--output',required=True)
|
||||
parser.add_argument('--output')
|
||||
parser.add_argument('--diagnose',action='store_true',help='Read-only discovery check; no output file or token prompt.')
|
||||
parser.add_argument('--container',default='hainuo-relay-connector-1')
|
||||
args=parser.parse_args();path=Path(args.output)
|
||||
if not path.is_absolute()or path.exists()or path.is_symlink():
|
||||
args=parser.parse_args();path=Path(args.output)if args.output else None
|
||||
if not args.diagnose and(path is None or not path.is_absolute()or path.exists()or path.is_symlink()):
|
||||
raise ValueError('output must be a new absolute file')
|
||||
# Keep existing fields in process; never print docker Env or token values.
|
||||
result=subprocess.run(['docker','inspect',args.container,'--format','{{json .Config.Env}}'],
|
||||
@@ -101,6 +154,10 @@ def main():
|
||||
if result.returncode:raise ValueError('cannot inspect current connector')
|
||||
env=dict(item.split('=',1)for item in json.loads(result.stdout)if '='in item)
|
||||
tenant=discover_tenant(args.container,env)
|
||||
if args.diagnose:
|
||||
print('TENANT_DIAGNOSTIC '+json.dumps({'status':'verified',
|
||||
'verification_token_configured':bool(env.get('HN_FEISHU_VERIFICATION_TOKEN'))}))
|
||||
return
|
||||
configured=env.get('HN_FEISHU_TENANT_KEY')
|
||||
if configured and configured!=tenant:
|
||||
raise ValueError('configured tenant does not match verified platform identity')
|
||||
|
||||
Reference in New Issue
Block a user