122 lines
6.3 KiB
Python
122 lines
6.3 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
|
|
|
|
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()
|
|
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:
|
|
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()
|
|
# Reuse the existing getter WITHOUT running its schema constructor.
|
|
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:
|
|
value=credentials.get(s.environment,s.feishu_app_id,row['principal_id'])
|
|
if not value or value.access_expires_at<=time.time()+10:continue
|
|
with client.stream('GET','/open-apis/authen/v1/user_info',
|
|
headers={'Authorization':'Bearer '+value.access_token})as response:
|
|
if response.status_code!=200: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
|
|
tenant=info.get('tenant_key')
|
|
if not isinstance(tenant,str)or not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',tenant):continue
|
|
return {'status':'verified','tenant_key':tenant,'app_id':s.feishu_app_id,'environment':s.environment}
|
|
except Exception:continue
|
|
raise ValueError()
|
|
finally:db.close()
|
|
|
|
try:print(json.dumps(discover()))
|
|
except Exception:print(json.dumps({'status':'tenant_discovery_unavailable'}))
|
|
"""
|
|
|
|
|
|
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()
|
|
value=json.loads(result.stdout)
|
|
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',required=True)
|
|
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():
|
|
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)
|
|
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
|