Files

179 lines
9.4 KiB
Python

#!/usr/bin/env python3
"""Prepare a private callback identity file without printing the token."""
import argparse
import getpass
import json
import os
from pathlib import Path
import re
import subprocess
# Runs inside the EXISTING connector, not a new SDK/consumer container. All
# stored credentials stay there. SQL is read-only; never refresh or authorize.
DISCOVERY_CODE = r"""
import json,re,sqlite3,time
from urllib.parse import urlsplit
import httpx
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)
if (target.scheme!='https' or not target.hostname or target.username or target.password
or target.path not in ('','/') or target.query or target.fragment):
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')
db.execute("SET statement_timeout TO '2000ms'")
else:
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:
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:
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 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):
diag['missing_tenant']+=1
continue
return {'status':'verified','tenant_key':tenant,'app_id':s.feishu_app_id,'environment':s.environment}
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 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:
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')
or not isinstance(value['tenant_key'],str)
or not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',value['tenant_key'])):
raise ValueError()
return value['tenant_key']
except (ValueError,TypeError,KeyError):
raise ValueError('tenant discovery unavailable; preserve current services and check Work authorization')from None
def main():
parser=argparse.ArgumentParser()
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 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}}'],
stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
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')
token=env.get('HN_FEISHU_VERIFICATION_TOKEN')or getpass.getpass('请输入应用“事件与回调”中的 Verification Token(输入不显示):')
if (not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',tenant)or not 8<=len(token)<=512
or any(ord(c)<33 or ord(c)>126 for c in token)):
raise ValueError('invalid callback identity; no values displayed')
fd=os.open(str(path),os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
with os.fdopen(fd,'w',encoding='utf-8')as stream:
json.dump({'tenant_key':tenant,'verification_token':token},stream)
stream.write('\n')
print('Tenant verified automatically from existing authorization; callback identity prepared privately. No services changed.')
if __name__=='__main__':
try:main()
except (ValueError,OSError,EOFError,KeyboardInterrupt,subprocess.TimeoutExpired):
raise SystemExit('STOP: callback identity not verified; current services preserved. Check Work authorization or platform connectivity; do not guess tenant_key.')from None