fix(deploy): discover approval tenant from verified existing authorization

This commit is contained in:
ex_tianzy
2026-11-17 11:51:17 +08:00
parent c80c6a0d27
commit 3132c07256
3 changed files with 164 additions and 6 deletions
+4 -2
View File
@@ -7,7 +7,7 @@
## 执行前必须具备
1. 应用事件与回调中支持并配置长连接接收card.action.trigger。复用当前唯一longconn,不能新开第二个连接。
2. 本应用租户tenant_key和Verification Token。不是App ID、user token、App Secret或Encrypt Key。脚本优先在当前connector环境中本地复用字段,缺项才在ECS交互输入,token不回显;不要贴回私有配置。
2. Verification Token从当前connector本地配置复用,确实缺失才在ECS私密输入。tenant_key不再要求用户填写:脚本在现有connector中以只读数据库连接读取当前应用/环境、未撤销绑定的有效授权,调用既有user_info接口并核对open_id,再提取tenant_key。不会刷新/修改授权、不新增scope、不读取业务正文;令牌不离开容器。没有可核实的有效授权时停止并提示检查Work授权,不允许猜填。
3. 当前客户端具备broker v2协议。本轮先升级ECS,手机审批实际请求需要后续客户端开启remote_approvals;该客户端开关仍默认关闭,服务端升级不等于真人审批已可用。
## 准备与切换
@@ -64,4 +64,6 @@ sudo python3 deployable/scripts/broker_deploy.py state \
## 保密与边界
身份JSON、plan.json、compose.broker.json含私有信息,只保存在ECS受限目录,勿发聊天或提交Git。缺少tenant_key或Verification Token时只需本人在平台本地核对,不需要把账号密码交给助手。真实PostgreSQL/SDK回调/手机UI尚待本次环境验收,不能凭本地测试数宣称上线。
身份JSON、plan.json、compose.broker.json含私有信息,只保存在ECS受限目录,勿发聊天或提交Git。tenant_key由脚本自动核实;Verification Token确实缺失时才由本人在平台本地核对,不需要把账号密码交给助手。真实PostgreSQL/SDK回调/手机UI尚待本次环境验收,不能凭本地测试数宣称上线。
2026-11-17现场修正:c80c6a0的旧准备脚本曾要求用户输入tenant_key,用户未知该运维字段而中止,未生成候选/切换服务。修复后移除tenant输入;12项自动发现测试通过,覆盖只读加密SQL、有效授权用户匹配、过期/403/重定向/缺字段拒绝、应用/环境匹配,以及不输出身份正文或令牌。私有化user_info文档已确认tenant_key字段:[获取用户信息](https://open.w.cnooc.com.cn/document/uAjLw4CM/ukTMukTMukTM/reference/authen-v1/user_info/get)。测试不代表现场已成功取得tenant_key。
+86 -4
View File
@@ -9,6 +9,85 @@ 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)
@@ -21,7 +100,10 @@ def main():
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=env.get('HN_FEISHU_TENANT_KEY')or input('请输入本测试应用所属租户 tenant_key(不是 App ID):').strip()
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)):
@@ -30,10 +112,10 @@ def main():
with os.fdopen(fd,'w',encoding='utf-8')as stream:
json.dump({'tenant_key':tenant,'verification_token':token},stream)
stream.write('\n')
print('Callback identity prepared privately; no services changed. Token must match the platform application.')
print('Tenant verified automatically from existing authorization; callback identity prepared privately. No services changed.')
if __name__=='__main__':
try:main()
except (ValueError,OSError,EOFError,KeyboardInterrupt):
raise SystemExit('STOP: callback identity preparation incomplete; values withheld')from None
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
@@ -0,0 +1,74 @@
"""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'}
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