Files
dxdesigner-part-replacement/tools/provision_dsh_issue_reporter.py
T

132 lines
7.0 KiB
Python

"""Provision the issue-only reporter. Never print or commit its credentials."""
from __future__ import annotations
import base64
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import secrets
import subprocess
import sys
import urllib.error
import urllib.request
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'src'))
SERVER = 'https://git.simgreek.com'
ORG = 'Skyworth_Digital_Hardware'
PROJECT = 'dxdesigner-part-replacement'
BOT = 'dsh-issue-reporter'
TEAM = 'dsh-issue-reporters'
def main():
import win32crypt
from dx_productivity.trial_task_center.application import resolve_data_root
root = resolve_data_root(None) / 'dsh'
root.mkdir(parents=True, exist_ok=True)
state_path = root / 'issue-reporter-issuer.dpapi'
if state_path.is_file():
_, plain = win32crypt.CryptUnprotectData(state_path.read_bytes(), None, None, None, 0)
state = json.loads(plain)
else:
state = {'username': BOT, 'password': secrets.token_urlsafe(48)}
def save_state():
blob = win32crypt.CryptProtectData(json.dumps(state).encode(), 'DSH issue reporter issuer', None, None, None, 0)
temporary = state_path.with_suffix('.tmp')
temporary.write_bytes(blob)
os.replace(temporary, state_path)
# Save issuer recovery before any remote creation; never overwrite another user's account.
new_state = not state_path.is_file()
r = subprocess.run(['git', 'credential', 'fill'], input='protocol=https\nhost=git.simgreek.com\n\n',
text=True, capture_output=True, timeout=20, env=os.environ | {'GIT_TERMINAL_PROMPT': '0', 'GCM_INTERACTIVE': 'never'},
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
credential = dict(line.split('=', 1) for line in r.stdout.splitlines() if '=' in line)
assert r.returncode == 0 and credential.get('password'), 'Administrator credential unavailable'
admin_auth = 'Basic ' + base64.b64encode((credential.get('username', '') + ':' + credential['password']).encode()).decode()
def api(route, method='GET', data=None, auth=admin_auth):
request = urllib.request.Request(SERVER + '/api/v1' + route,
data=None if data is None else json.dumps(data).encode(), method=method,
headers={'Authorization': auth, 'Content-Type': 'application/json'})
try:
with urllib.request.urlopen(request, timeout=25) as response:
value = response.read()
return json.loads(value) if value else None
except urllib.error.HTTPError as error:
try:
message = json.loads(error.read()).get('message', '')
except (ValueError, AttributeError):
message = ''
for secret in (state.get('password'), state.get('token'), credential.get('password')):
if secret:
message = message.replace(secret, '<REDACTED>')
error.dsh_detail = {'route': route, 'method': method, 'message': message[:350]}
raise
assert api('/user')['is_admin'], 'Site administrator required for isolated reporter account'
exists = False
try:
api('/users/' + BOT); exists = True
except urllib.error.HTTPError as error:
if error.code != 404:
raise
if new_state and exists:
raise RuntimeError('Reporter username exists without local issuer state; refusing to change that account')
save_state()
if not exists:
api('/admin/users', 'POST', {'username': BOT, 'email': BOT + '@users.noreply.git.simgreek.com',
'full_name': 'DSH 工单上报', 'password': state['password'], 'must_change_password': False,
'restricted': True, 'visibility': 'private', 'send_notify': False})
api('/admin/users/' + BOT, 'PATCH', {'login_name': BOT, 'restricted': True, 'admin': False,
'allow_create_organization': False, 'allow_git_hook': False, 'allow_import_local': False,
'max_repo_creation': 0, 'visibility': 'private'})
teams = api('/orgs/' + ORG + '/teams')
team = next((row for row in teams if row['name'] == TEAM), None)
units = {'repo.issues': 'write', **{name: 'none' for name in
['repo.code', 'repo.pulls', 'repo.releases', 'repo.wiki', 'repo.ext_wiki', 'repo.ext_issues',
'repo.projects', 'repo.packages', 'repo.actions']}}
options = {'name': TEAM, 'description': 'DSH reporter: only this project issues, comments and attachments',
'permission': 'write', 'units_map': units, 'includes_all_repositories': False,
'can_create_org_repo': False, 'visibility': 'private'}
if team is None:
team = api('/orgs/' + ORG + '/teams', 'POST', options)
else:
# Refuse to modify a non-dedicated team or broaden an existing membership.
members = api(f"/teams/{team['id']}/members")
assert all(row['login'] == BOT for row in members), 'Reporter team has other members'
team = api(f"/teams/{team['id']}", 'PATCH', options)
repos = api(f"/teams/{team['id']}/repos")
assert all(row['full_name'] == ORG + '/' + PROJECT for row in repos), 'Reporter team includes other projects'
api(f"/teams/{team['id']}/repos/{ORG}/{PROJECT}", 'PUT')
api(f"/teams/{team['id']}/members/{BOT}", 'PUT')
state['team_id'] = team['id']
save_state()
bot_auth = 'Basic ' + base64.b64encode((BOT + ':' + state['password']).encode()).decode()
if not state.get('token'):
token = api('/users/' + BOT + '/tokens', 'POST',
{'name': 'dsh-tool-issue-only-' + datetime.now(timezone.utc).strftime('%Y%m%d'), 'scopes': ['write:issue']}, bot_auth)
assert token['scopes'] == ['write:issue'], 'Unexpected token permissions'
state.update(token=token['sha1'], token_id=token['id'], scopes=token['scopes'])
save_state()
team = api(f"/teams/{team['id']}")
assert team['units_map'].get('repo.issues') == 'write'
assert all(level == 'none' for unit, level in team['units_map'].items() if unit != 'repo.issues')
bootstrap = {'server': SERVER, 'repository': ORG + '/' + PROJECT, 'username': BOT,
'token': state['token'], 'token_id': state['token_id'], 'scopes': ['write:issue']}
output = REPO / 'integration/dsh/issue-bootstrap.json'
output.write_text(json.dumps(bootstrap, indent=2), encoding='utf8')
report = {'status': 'provisioned', 'username': BOT, 'team_id': team['id'], 'token_id': state['token_id'],
'scopes': ['write:issue'], 'repository': bootstrap['repository'], 'units_map': team['units_map'],
'restricted_account': True, 'prefilled_bootstrap': True, 'issuer_only_local_dpapi': True}
(REPO / 'build/dsh-issue-reporter-provisioning.json').write_text(json.dumps(report, indent=2), encoding='utf8')
print(json.dumps(report))
if __name__ == '__main__':
try:
main()
except Exception as error:
print(json.dumps({'status': 'failed', 'error': type(error).__name__, 'http_status': getattr(error, 'code', None),
'detail': getattr(error, 'dsh_detail', {})}))
raise SystemExit(1)