feat(deploy): add guarded active broker permission profile updates
This commit is contained in:
@@ -612,6 +612,79 @@ def activate(root,plan,ready):
|
||||
print("ACTIVATED: connector/router only. Verify real OAuth, v2 client, unbind and task routing.")
|
||||
|
||||
|
||||
def container_permission_profiles(container):
|
||||
values=run(['docker','inspect',container['id'],'--format','{{json .Config.Env}}'],True)
|
||||
env=dict(value.split('=',1) for value in values if '=' in value)
|
||||
try:
|
||||
value=json.loads(env['HN_CREDENTIAL_PERMISSION_PROFILES'])
|
||||
if not isinstance(value,dict):raise ValueError()
|
||||
return value
|
||||
except (KeyError,ValueError,TypeError):
|
||||
raise DeployError('cannot verify active connector product scopes') from None
|
||||
|
||||
|
||||
def update_permissions(root,plan,profiles_path,apply=False):
|
||||
"""Change approved scopes on the active broker, without changing images/keys."""
|
||||
profiles=profiles_from(Path(profiles_path))
|
||||
check(root,plan,baseline=False)
|
||||
built=json.loads((root/'candidate.json').read_text(encoding='utf-8'))
|
||||
current=service(plan['project'],'connector')
|
||||
if current['image']!=built['image'] or current.get('state',{}).get('health')!='healthy':
|
||||
raise DeployError('permission update requires the active healthy candidate connector')
|
||||
overlay_path=root/'compose.broker.json'
|
||||
overlay=json.loads(overlay_path.read_text(encoding='utf-8'))
|
||||
old=json.loads(overlay['services']['connector']['environment']['HN_CREDENTIAL_PERMISSION_PROFILES'])
|
||||
if container_permission_profiles(current)!=old:
|
||||
raise DeployError('active connector scopes differ from selected plan; no changes made')
|
||||
if set(old)!=set(profiles) or any(not set(scopes)<=set(profiles[name]) for name,scopes in old.items()):
|
||||
raise DeployError('permission update is additive only; preserve all existing profiles and scopes')
|
||||
additions={name:sorted(set(scopes)-set(old[name])) for name,scopes in profiles.items()}
|
||||
print('Product scope additions: '+json.dumps(additions,sort_keys=True))
|
||||
if not any(additions.values()):
|
||||
print('PERMISSIONS UNCHANGED: no files or containers changed')
|
||||
return
|
||||
if not apply:
|
||||
print('PERMISSIONS REVIEW: no files or containers changed; use --apply after platform approval/publication')
|
||||
return
|
||||
backup=root/('permission-backup-'+secrets.token_hex(8))
|
||||
backup.mkdir(mode=0o700)
|
||||
for name in ('compose.broker.json','plan.json'):
|
||||
shutil.copyfile(str(root/name),str(backup/name));os.chmod(str(backup/name),0o600)
|
||||
next_overlay=json.loads(json.dumps(overlay))
|
||||
next_overlay['services']['connector']['environment']['HN_CREDENTIAL_PERMISSION_PROFILES']=json.dumps(profiles,separators=(',',':'))
|
||||
next_plan=json.loads(json.dumps(plan))
|
||||
touched=False
|
||||
try:
|
||||
replace_json(overlay_path,next_overlay);touched=True
|
||||
next_plan['prepared_hashes']['compose.broker.json']=digest(overlay_path)
|
||||
replace_json(root/'plan.json',next_plan)
|
||||
check(root,next_plan,baseline=False)
|
||||
# Validate what Compose will actually pass, with secrets kept in-process.
|
||||
resolved=run(compose(next_plan,overlay_path)+['config','--format','json'],True)
|
||||
value=resolved['services']['connector']['environment'].get('HN_CREDENTIAL_PERMISSION_PROFILES','')
|
||||
if json.loads(value)!=profiles:raise DeployError('resolved product scopes do not match approved input')
|
||||
print('PERMISSIONS APPLY: recreate connector only; same image, credentials and storage',flush=True)
|
||||
command=compose(next_plan,overlay_path)+['up','-d','--no-deps','--no-build','--pull','never',
|
||||
'--wait','--wait-timeout','180','connector']
|
||||
run(command)
|
||||
after=service(plan['project'],'connector')
|
||||
if after['image']!=current['image'] or after.get('state',{}).get('health')!='healthy':
|
||||
raise DeployError('connector did not retain its reviewed healthy image')
|
||||
if container_permission_profiles(after)!=profiles:
|
||||
raise DeployError('running connector did not load the approved product scopes')
|
||||
except Exception:
|
||||
if touched:
|
||||
for name in ('compose.broker.json','plan.json'):
|
||||
replace_json(root/name,json.loads((backup/name).read_text(encoding='utf-8')))
|
||||
try:
|
||||
run(compose(plan,overlay_path)+['up','-d','--no-deps','--no-build','--pull','never',
|
||||
'--wait','--wait-timeout','180','connector'])
|
||||
except Exception:
|
||||
raise DeployError('permission update failed; files restored but connector rollback unconfirmed; run state') from None
|
||||
raise DeployError('permission update failed; original configuration restored; no credential keys changed') from None
|
||||
print('PERMISSIONS UPDATED: connector only; backup='+str(backup)+'; obtain a NEW authorization transaction next')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
sub = parser.add_subparsers(dest="action",required=True)
|
||||
@@ -628,6 +701,10 @@ def main():
|
||||
update.add_argument("--plan",required=True)
|
||||
update.add_argument("--source-root",default=str(Path(__file__).resolve().parents[1]))
|
||||
update.add_argument("--output",required=True)
|
||||
permissions=sub.add_parser('update-permissions')
|
||||
permissions.add_argument('--plan',required=True)
|
||||
permissions.add_argument('--profiles',required=True)
|
||||
permissions.add_argument('--apply',action='store_true')
|
||||
for name in ("repair-router","state","diagnose","check","build","activate","rollback"):
|
||||
cmd = sub.add_parser(name)
|
||||
cmd.add_argument("--plan",required=True)
|
||||
@@ -648,7 +725,9 @@ def main():
|
||||
return
|
||||
root = Path(args.plan).resolve()
|
||||
plan = load_plan(root)
|
||||
if args.action == "repair-router":
|
||||
if args.action == 'update-permissions':
|
||||
update_permissions(root,plan,args.profiles,args.apply)
|
||||
elif args.action == "repair-router":
|
||||
repair_router(root,plan)
|
||||
elif args.action == "state":
|
||||
deployment_state(root,plan)
|
||||
|
||||
Reference in New Issue
Block a user