feat: prefill isolated issue-only reporter for clients without Git

This commit is contained in:
阿白叔 committed 2026-10-30 14:05:16 +08:00
1 parent 6c708224d2
commit e9b77186dc
15 files changed
+435 -20

No files matched your search

+15 -3
View File
@@ -22,6 +22,7 @@ def main():
parser.add_argument('--live-model', action='store_true')
parser.add_argument('--incident', action='store_true', help='Inject a read-only controlled failure and verify automatic diagnosis and Git escalation')
parser.add_argument('--outbox-only', action='store_true', help='Verify failed publication stays in local outbox without creating another real issue')
parser.add_argument('--without-git', action='store_true', help='Simulate a client with no Git credentials or executable')
args = parser.parse_args()
output = args.output.resolve()
output.mkdir(parents=True, exist_ok=True)
@@ -32,8 +33,14 @@ def main():
shutil.copy2(args.provider_config / name, data / 'dsh' / name)
if args.incident:
(data / 'dsh').mkdir(parents=True, exist_ok=True)
(data / 'dsh/issue-config.json').write_text(json.dumps({'enabled': not args.outbox_only, 'acceptance': True,
'server': 'https://git.simgreek.com', 'repository': 'Skyworth_Digital_Hardware/dxdesigner-part-replacement'}), encoding='utf8')
(data / 'dsh/issue-config.json').write_text(json.dumps({'enabled': not args.outbox_only, 'acceptance': True}), encoding='utf8')
if args.without_git:
original_run = subprocess.run
def no_git_run(command, *positional, **keywords):
if isinstance(command, (list, tuple)) and Path(str(command[0])).stem.casefold() == 'git':
raise FileNotFoundError('Git is not installed in this acceptance client')
return original_run(command, *positional, **keywords)
subprocess.run = no_git_run
os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = f'127.0.0.1:{args.port}'
os.environ.pop('QT_QPA_PLATFORM', None)
from PySide6.QtCore import QTimer, Qt
@@ -122,9 +129,13 @@ def main():
report['checks'].append('native composer draft survived direct navigation')
if args.incident:
row = window._dsh_automation.latest
assert row['issue_code'] == 'dsh_acceptance_failure', 'Unexpected UI error replaced controlled incident'
assert row['status'] == ('pending_issue' if args.outbox_only else 'escalated') and row['attempts'] == 0
if not args.outbox_only:
assert row['ticket']['attachment_status'] == 'uploaded'
if args.without_git:
assert row['ticket']['credential_source'] == 'prefilled_issue_token'
report['checks'].append('client without Git used only the prefilled issue reporter token')
report['incident'] = row
report['checks'].append('real native automatic diagnosis and reflection, evidence and ' +
('retryable local issue outbox' if args.outbox_only else 'Git issue attachment') + ' completed without CAD mutations')
@@ -151,6 +162,7 @@ def main():
log = (data / 'logs/application.log').read_text(encoding='utf8')
report['cleanShutdown'] = 'application_clean_shutdown exit_code=0' in log
report['uncaughtErrors'] = 'uncaught_main_thread' in log
report['unexpectedUiErrors'] = 'operation=ui message=' in log
if args.live_model or args.incident:
audit_file = data / 'dsh/harness-home/task-tool-audit.jsonl'
audit = [json.loads(line) for line in audit_file.read_text(encoding='utf8').splitlines()] if audit_file.is_file() else []
@@ -158,7 +170,7 @@ def main():
report['modelToolSucceeded'] = any(row['name'] == 'dx_task_snapshot' and row['is_error'] is False for row in audit)
(output / 'desktop-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
print(json.dumps(report, ensure_ascii=True))
return 0 if report['cleanShutdown'] and not report['uncaughtErrors'] and (not (args.live_model or args.incident) or report['modelToolSucceeded']) else 1
return 0 if report['cleanShutdown'] and not report['uncaughtErrors'] and not report['unexpectedUiErrors'] and (not (args.live_model or args.incident) or report['modelToolSucceeded']) else 1
if __name__ == '__main__':
+9 -3
View File
@@ -2,9 +2,15 @@
import {writeFile} from 'node:fs/promises';
export async function connect(port=9226) {
const targets=await fetch(`http://127.0.0.1:${port}/json`).then(r=>r.json());
const target=targets.find(x=>x.type==='page');
if(!target) throw Error('The embedded DSH page has not opened');
let target;
const deadline=Date.now()+45000;
while(Date.now()<deadline){
const targets=await fetch(`http://127.0.0.1:${port}/json`,{signal:AbortSignal.timeout(3000)}).then(r=>r.json());
target=targets.find(x=>x.type==='page'&&x.url?.startsWith('http://127.0.0.1:'));
if(target)break;
await new Promise(resolve=>setTimeout(resolve,100));
}
if(!target) throw Error('The embedded DSH page did not navigate to the owned local runtime');
const socket=new WebSocket(target.webSocketDebuggerUrl);
await new Promise((resolve,reject)=>{socket.onopen=resolve;socket.onerror=reject;});
let sequence=0;
+131
View File
@@ -0,0 +1,131 @@
"""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)
+58
View File
@@ -0,0 +1,58 @@
"""Verify actual issue-only token boundaries without printing the token."""
from __future__ import annotations
import json
import os
from pathlib import Path
import sys
import urllib.error
import urllib.request
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'src'))
def main():
from dx_productivity.dsh.git_issues import GitIssuePublisher
from dx_productivity.dsh.issue_credentials import load_bootstrap
bootstrap = load_bootstrap()
assert bootstrap and bootstrap['scopes'] == ['write:issue']
# Empty PATH ensures no Git executable or Git credential helper can be used.
os.environ['PATH'] = ''
config, headers, source = GitIssuePublisher(REPO / 'build/absent-user-issue-config.json').connection()
assert source == 'prefilled_issue_token'
base = config['server'].rstrip('/') + '/api/v1'
target = '/repos/' + config['repository']
def status(route, method='GET', body=None):
request = urllib.request.Request(base + route, method=method, data=body,
headers=headers | {'Content-Type': 'application/json'})
try:
with urllib.request.urlopen(request, timeout=20) as response:
return response.status
except urllib.error.HTTPError as error:
return error.code
positive = {name: status(route) for name, route in {
'list_issues': target + '/issues?limit=1', 'issue_comments': target + '/issues/4/comments',
'issue_attachments': target + '/issues/4/assets'}.items()}
assert all(value == 200 for value in positive.values()), positive
negative = {
'read_repository_contents': status(target + '/contents'),
'read_releases': status(target + '/releases'),
'read_admin_users': status('/admin/users'),
'read_organization_teams': status('/orgs/' + config['repository'].split('/')[0] + '/teams'),
# Empty payloads cannot create a repository/release/file even if a
# permission regression admits the route. Require an explicit denial.
'create_repository': status('/user/repos', 'POST', b'{}'),
'create_release': status(target + '/releases', 'POST', b'{}'),
'write_code': status(target + '/contents/__dsh_scope_probe__', 'POST', b'{}'),
}
assert all(value in {401, 403, 404} for value in negative.values()), negative
report = {'status': 'passed', 'username': bootstrap['username'], 'token_id': bootstrap.get('token_id'),
'scopes': bootstrap['scopes'], 'credential_source': source, 'git_executable_available': False,
'no_local_user_configuration': True, 'allowed': positive, 'denied': negative}
(REPO / 'build/dsh-issue-reporter-permissions.json').write_text(json.dumps(report, indent=2), encoding='utf8')
print(json.dumps(report))
if __name__ == '__main__':
main()