diff --git a/scripts/release/workflow.py b/scripts/release/workflow.py index 2ef4ced3..1111cbdf 100644 --- a/scripts/release/workflow.py +++ b/scripts/release/workflow.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +import base64 import hashlib import json import os @@ -13,6 +14,7 @@ import sys import tempfile from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, cast +import urllib.request sys.dont_write_bytecode = True @@ -50,6 +52,19 @@ def version_text(version: Tuple[int, int, int]) -> str: return '.'.join(str(part) for part in version) +def jwt_claims(token: str) -> Dict[str, Any]: + """Decode an OIDC token's claims without verifying the signature.""" + parts = token.split('.') + if len(parts) < 2: + return {} + segment = parts[1] + '=' * (-len(parts[1]) % 4) + try: + claims: object = json.loads(base64.urlsafe_b64decode(segment.encode('ascii')).decode('utf-8')) + except (ValueError, UnicodeDecodeError): + return {} + return cast(Dict[str, Any], claims) if isinstance(claims, dict) else {} + + def named_values(output: str, keys: Sequence[str]) -> Dict[str, str]: fields = dict(line.split(': ', 1) for line in output.splitlines() if ': ' in line) if any(not fields.get(key) for key in keys): @@ -317,7 +332,7 @@ def publish_npm(self) -> None: '--loglevel=http'], capture=True, check=False) if published.returncode: detail = (published.stderr or published.stdout or '').strip() - raise ValueError(f'npm publish of {identity} failed ({published.returncode}): {detail}{self.registry_hint(detail)}{self.npm_debug_report()}') + raise ValueError(f'npm publish of {identity} failed ({published.returncode}): {detail}{self.registry_hint(detail)}{self.oidc_identity()}{self.npm_debug_report()}') emit(f"::notice::Published {identity} to dist-tag '{self.value('NPM_TAG')}'.") def registry_hint(self, detail: str) -> str: @@ -328,6 +343,24 @@ def registry_hint(self, detail: str) -> str: return ('\nThe registry answered 404, which npm also uses when the package Trusted Publisher does not name this repository and workflow. ' f'Confirm the npm Trusted Publisher for this package lists {repository} and .github/workflows/release.yml.') + def oidc_identity(self) -> str: + """Report the claims npm presents to the registry's token exchange.""" + request_url = self.value('ACTIONS_ID_TOKEN_REQUEST_URL') + request_token = self.value('ACTIONS_ID_TOKEN_REQUEST_TOKEN') + if not request_url or not request_token: + return '' + request = urllib.request.Request(f'{request_url}&audience=npm%3Aregistry.npmjs.org', headers={'Authorization': f'bearer {request_token}'}) + try: + with urllib.request.urlopen(request, timeout=30) as response: + payload = cast(Dict[str, Any], json.loads(response.read().decode('utf-8'))) + except (OSError, ValueError) as error: + return f'\nThe runner refused an npm OIDC token: {error}' + claims = jwt_claims(str(payload.get('value', ''))) + if not claims: + return '' + shown = ', '.join(f'{key}={claims.get(key, "")!r}' for key in ('repository', 'repository_owner', 'workflow', 'environment')) + return f'\nThe workflow presented this identity to npm: {shown}' + def npm_debug_report(self, directory: Optional[Path] = None) -> str: """Quote npm's own debug log, which carries the registry's reason.""" log_directory = directory if directory is not None else Path.home() / '.npm' / '_logs' diff --git a/scripts/tests/test_release_workflow_driver.py b/scripts/tests/test_release_workflow_driver.py index 4764b3c3..bc9eb1f3 100644 --- a/scripts/tests/test_release_workflow_driver.py +++ b/scripts/tests/test_release_workflow_driver.py @@ -2,6 +2,7 @@ """Exercise release orchestration without any real remote writes or publication.""" from __future__ import annotations +import base64 import hashlib import json import os @@ -231,6 +232,31 @@ def test_publication_reruns_skip_npm_and_update_github(self) -> None: self.assertIn(str(Path('dist') / 'fixture.unitypackage.sha256'), commands[-1]) self.assertIn('--clobber' if exists else '--verify-tag', commands[-1]) + def test_registry_identity_reports_the_claims_npm_presents(self) -> None: + claims = {'repository': 'owner/repository', 'repository_owner': 'owner', 'workflow': 'Release', 'environment': ''} + payload = base64.urlsafe_b64encode(json.dumps(claims).encode('utf-8')).decode('ascii').rstrip('=') + token = f'header.{payload}.signature' + self.assertEqual(workflow.jwt_claims(token), claims) + self.assertEqual(workflow.jwt_claims('opaque'), {}) + self.assertEqual(self.driver.oidc_identity(), '') + + class Response: + def read(self) -> bytes: + return json.dumps({'value': token}).encode('utf-8') + + def __enter__(self) -> 'Response': + return self + + def __exit__(self, *arguments: object) -> bool: + return False + + self.driver.environment.update(ACTIONS_ID_TOKEN_REQUEST_URL='https://oidc.invalid/request', ACTIONS_ID_TOKEN_REQUEST_TOKEN='token') + with patch.object(workflow.urllib.request, 'urlopen', return_value=Response()): + report = self.driver.oidc_identity() + self.assertIn("repository='owner/repository'", report) + self.assertIn("workflow='Release'", report) + self.assertNotIn('signature', report) + def test_npm_debug_log_supplies_the_registry_reason(self) -> None: logs = self.root / 'npm-logs' logs.mkdir()