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

+25 -11
View File
@@ -12,6 +12,7 @@ import urllib.request
from uuid import uuid4
from .evidence import scrub
from .issue_credentials import issue_target, load_bootstrap
class NoRedirect(urllib.request.HTTPRedirectHandler):
@@ -23,30 +24,43 @@ class GitIssuePublisher:
def __init__(self, config_path: Path):
self.config_path = Path(config_path)
def __call__(self, record, archive: Path):
if not self.config_path.is_file():
return {'status': 'unavailable', 'reason': 'issue_target_not_configured'}
config = json.loads(self.config_path.read_text(encoding='utf8'))
def connection(self):
config = issue_target(self.config_path)
if not config.get('enabled'):
return {'status': 'unavailable', 'reason': 'issue_submission_disabled'}
return config, {}, 'issue_submission_disabled'
parsed = urllib.parse.urlsplit(config['server'])
if parsed.scheme != 'https' or not parsed.hostname or parsed.username or parsed.password or parsed.path not in {'', '/'}:
raise ValueError('invalid_issue_server')
owner, repo = config['repository'].split('/')
if not all(value and all(c.isalnum() or c in '-_.' for c in value) and value not in {'.', '..'} for value in (owner, repo)):
raise ValueError('invalid_issue_repository')
bootstrap = load_bootstrap()
if (bootstrap and bootstrap['server'].rstrip('/') == config['server'].rstrip('/')
and bootstrap['repository'] == config['repository']):
return config, {'Authorization': 'token ' + bootstrap['token']}, 'prefilled_issue_token'
env = os.environ | {'GIT_TERMINAL_PROMPT': '0', 'GCM_INTERACTIVE': 'never'}
credential = subprocess.run(['git', 'credential', 'fill'], input=f'protocol=https\nhost={parsed.netloc}\n\n',
text=True, capture_output=True, env=env, timeout=20, check=False,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
try:
credential = subprocess.run(['git', 'credential', 'fill'], input=f'protocol=https\nhost={parsed.netloc}\n\n',
text=True, capture_output=True, env=env, timeout=20, check=False,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
except (FileNotFoundError, subprocess.TimeoutExpired):
return config, {}, 'git_not_installed'
fields = dict(line.split('=', 1) for line in credential.stdout.splitlines() if '=' in line)
if credential.returncode or not fields.get('password'):
return {'status': 'unavailable', 'reason': 'git_credential_unavailable'}
return config, {}, 'git_credential_unavailable'
authorization = 'Basic ' + base64.b64encode((fields.get('username', '') + ':' + fields['password']).encode()).decode()
return config, {'Authorization': authorization}, 'machine_git_credential'
def __call__(self, record, archive: Path):
config, authentication, source = self.connection()
if not authentication:
return {'status': 'unavailable', 'reason': source}
parsed = urllib.parse.urlsplit(config['server'])
owner, repo = config['repository'].split('/')
opener = urllib.request.build_opener(NoRedirect())
api = f'{parsed.scheme}://{parsed.netloc}/api/v1/repos/{owner}/{repo}'
def request(path, payload=None, content_type='application/json'):
headers = {'Authorization': authorization, 'Accept': 'application/json'}
headers = authentication | {'Accept': 'application/json'}
if payload is not None:
headers['Content-Type'] = content_type
call = urllib.request.Request(api + path, data=payload, headers=headers)
@@ -60,7 +74,7 @@ class GitIssuePublisher:
body = (Path(record['evidence_dir']) / 'issue.md').read_text(encoding='utf8')
issue = request('/issues', json.dumps({'title': scrub(title), 'body': scrub(body)}, ensure_ascii=False).encode())
result = {'status': 'submitted', 'url': issue['html_url'], 'number': issue['number'],
'attachment_status': 'pending'}
'attachment_status': 'pending', 'credential_source': source}
# Existing issue and attachment are reused when an interrupted upload is retried.
try:
attachments = request(f"/issues/{issue['number']}/assets")
@@ -0,0 +1,37 @@
"""Portable issue-only reporter credential, bound to its exact issue target."""
from __future__ import annotations
import json
from pathlib import Path
import sys
DEFAULT_TARGET = {'enabled': True, 'server': 'https://git.simgreek.com',
'repository': 'Skyworth_Digital_Hardware/dxdesigner-part-replacement'}
def bootstrap_path() -> Path:
if getattr(sys, 'frozen', False):
return Path(sys._MEIPASS) / 'dsh-runtime' / 'issue-bootstrap.json'
return Path(__file__).resolve().parents[3] / 'integration' / 'dsh' / 'issue-bootstrap.json'
def load_bootstrap() -> dict:
try:
row = json.loads(bootstrap_path().read_text(encoding='utf8'))
if not isinstance(row, dict):
return {}
if row.get('scopes') != ['write:issue'] or not row.get('token') or not row.get('username'):
return {}
if not row.get('server', '').startswith('https://') or len(row.get('repository', '').split('/')) != 2:
return {}
return row
except (OSError, ValueError, TypeError):
return {}
def issue_target(config_path: Path) -> dict:
bootstrap = load_bootstrap()
target = DEFAULT_TARGET | {key: bootstrap[key] for key in ('server', 'repository') if key in bootstrap}
if config_path.is_file():
target.update(json.loads(config_path.read_text(encoding='utf8')))
return target
+6 -1
View File
@@ -9,6 +9,7 @@ import sys
from uuid import uuid4
from .snapshot import TaskSnapshot
from ..trial_task_center.path_access import retry_sharing_violation
HARNESS_VERSION = '0.2.1-rc.5'
@@ -48,5 +49,9 @@ def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_
'task_name': str(task_name)[:128], 'automation': automation or {}}
temporary = data_root / ('context-' + uuid4().hex + '.tmp')
temporary.write_text(json.dumps(value, ensure_ascii=False), encoding='utf8')
os.replace(temporary, data_root / 'task-context.json')
destination = data_root / 'task-context.json'
try:
retry_sharing_violation(lambda: os.replace(temporary, destination), target=destination)
finally:
temporary.unlink(missing_ok=True)
return value