diff --git a/.azure-pipelines/npm-publish.yml b/.azure-pipelines/npm-publish.yml index 7e2d2db43c5..46234059bde 100644 --- a/.azure-pipelines/npm-publish.yml +++ b/.azure-pipelines/npm-publish.yml @@ -10,9 +10,10 @@ # # This pipeline warns about absent literal CSS export files; all other archive checks still fail closed. # Released manifests and tarballs are not patched. -# Existing 1ES source analysis stays configured; scan coverage of the detached tree must be verified in ADO. +# Component Governance scans the agent build directory, including the retained release worktree. +# Actual detection of the tagged dependency inputs must be verified in ADO. # -# Production publishing is not activated: no feed credential, service connection or writer runs here. +# Publish follows successful Release validation automatically, subject to the WIF service connection checks. trigger: none pr: none schedules: [] @@ -26,6 +27,7 @@ parameters: variables: ArtifactName: logicappsux-npm-release-cohort PackageOutput: '$(Build.ArtifactStagingDirectory)/logicappsux-npm-release-cohort' + NpmRegistry: 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/' resources: repositories: @@ -42,6 +44,8 @@ extends: image: ubuntu-latest os: linux sdl: + componentgovernance: + useAgentBuildDirectory: true sourceAnalysisPool: name: Azure-Pipelines-1ESPT-ExDShared image: windows-latest @@ -81,6 +85,7 @@ extends: RECIPE_SHA: '$(Build.SourceVersion)' SOURCE_REPOSITORY: '$(Build.Repository.Name)' AGENT_TMP: '$(Agent.TempDirectory)' + RELEASE_SCAN_ROOT: '$(Agent.BuildDirectory)' ARTIFACT_ROOT: '$(PackageOutput)' # Publish the manifest digest as a job output so the verifier pins the exact uploaded manifest. - bash: | @@ -115,101 +120,293 @@ extends: variables: ExpectedManifestSha256: $[ dependencies.BuildRelease.outputs['manifest.ManifestSha256'] ] ExpectedSourceSha: $[ dependencies.BuildRelease.outputs['manifest.SourceSha'] ] + ArtifactDir: '$(Pipeline.Workspace)/release-artifact' templateContext: inputs: - input: pipelineArtifact buildType: current artifactName: '$(ArtifactName)' - targetPath: '$(Pipeline.Workspace)/release-artifact' + targetPath: '$(ArtifactDir)' + steps: + - checkout: none + - template: /.azure-pipelines/npm-verify-release.steps.yml@self + parameters: + releaseVersion: ${{ parameters.releaseVersion }} + + # Release never writes to the feed; Publish requires the protected service connection. + - job: ProductionPublishNotActivated + displayName: Release stage remains validation-only + dependsOn: VerifyRelease steps: - checkout: none - bash: | set -euo pipefail - python3 -I - <<'PY' - import base64, hashlib, json, os, re, stat - version = os.environ['RELEASE_VERSION'] - if len(version) > 40 or not re.fullmatch(r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)', version): - raise SystemExit('Invalid releaseVersion. Enter a stable version such as 5.1024.0 (without the v prefix).') - hex40 = re.compile(r'[0-9a-f]{40}') - build_id, recipe_sha, source_sha = os.environ['BUILD_ID'], os.environ['RECIPE_SHA'].lower(), os.environ['SOURCE_SHA'] - manifest_sha256 = os.environ['EXPECTED_MANIFEST_SHA256'] - if not re.fullmatch(r'[1-9]\d{0,14}', build_id) or not hex40.fullmatch(recipe_sha) or not hex40.fullmatch(source_sha): - raise SystemExit('Run identity is invalid.') - if not re.fullmatch(r'[0-9a-f]{64}', manifest_sha256): - raise SystemExit('Expected manifest digest is missing.') - packages = ['logic-apps-shared', 'designer-ui', 'designer-ui-v2', 'logic-apps-chatbot', 'logic-apps-designer', - 'logic-apps-designer-v2', 'logic-apps-data-mapper', 'logic-apps-data-mapper-v2', 'vscode-extension-logic-apps'] - files = ['microsoft-%s-%s.tgz' % (name, version) for name in packages] - root = os.environ['ARTIFACT_DIR'] - if not stat.S_ISDIR(os.lstat(root).st_mode) or os.path.realpath(root) != os.path.abspath(root): - raise SystemExit('Artifact directory is not confined.') - # 1ES adds a reserved _manifest/ SBOM directory to pipeline artifacts; it is never read here. - entries = os.listdir(root) - if '_manifest' in entries: - if not stat.S_ISDIR(os.lstat(os.path.join(root, '_manifest')).st_mode): - raise SystemExit('Reserved _manifest entry is not a directory.') - entries.remove('_manifest') - if sorted(entries) != sorted(files + ['publisher-artifact.json']): - raise SystemExit('Artifact must contain exactly the nine tarballs and the manifest.') - def read_regular(name, limit): - try: - fd = os.open(os.path.join(root, name), os.O_RDONLY | os.O_NOFOLLOW) - except OSError: - raise SystemExit('Artifact entry is not a regular file: ' + name) - with os.fdopen(fd, 'rb') as handle: - if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode): - raise SystemExit('Artifact entry is not a regular file: ' + name) - data = handle.read(limit + 1) - if len(data) > limit: - raise SystemExit('Artifact entry is too large: ' + name) - return data - manifest = read_regular('publisher-artifact.json', 128 * 1024) - if hashlib.sha256(manifest).hexdigest() != manifest_sha256: - raise SystemExit('Manifest digest does not match the producing job.') - record = json.loads(manifest) - if not isinstance(record, dict) or sorted(record) != ['destination', 'packages', 'source']: - raise SystemExit('Manifest shape is invalid.') - source = record['source'] - if not isinstance(source, dict): - raise SystemExit('Manifest shape is invalid.') - expected_source = {'repository': 'Azure/LogicAppsUX', 'releaseRef': 'refs/tags/v' + version, - 'verifiedSha': source_sha, 'version': version, 'buildId': build_id, 'recipeSha': recipe_sha} - if source != expected_source: - raise SystemExit('Manifest provenance does not match this run, release tag, source SHA or recipe commit.') - expected_destination = {'registry': 'https://msazure.pkgs.visualstudio.com/One/_packaging/microsoft-logic-apps/npm/registry/', - 'feedId': '44fc6edc-394a-403a-86cd-700a15978af1', 'distTag': 'latest'} - if record['destination'] != expected_destination: - raise SystemExit('Manifest destination is invalid.') - expected_packages = [] - for name, file in zip(packages, files): - data = read_regular(file, 64 * 1024 * 1024) - expected_packages.append({'name': '@microsoft/' + name, 'version': version, 'file': file, - 'integrity': 'sha512-' + base64.b64encode(hashlib.sha512(data).digest()).decode(), - 'sha256': hashlib.sha256(data).hexdigest(), 'bytes': len(data)}) - if record['packages'] != expected_packages: - raise SystemExit('Package identity or integrity mismatch.') - print('Verified nine packages for v%s at %s from build %s.' % (version, source_sha, build_id)) - PY - displayName: Verify manifest digest, provenance and nine tarballs + echo '##vso[task.logissue type=warning]Release stage validated artifacts only. Feed writes require the protected Publish stage.' + displayName: Report that Release stage did not write to npm env: BASH_ENV: /dev/null - ARTIFACT_DIR: '$(Pipeline.Workspace)/release-artifact' - RELEASE_VERSION: ${{ parameters.releaseVersion }} - BUILD_ID: '$(Build.BuildId)' - RECIPE_SHA: '$(Build.SourceVersion)' - SOURCE_SHA: '$(ExpectedSourceSha)' - EXPECTED_MANIFEST_SHA256: '$(ExpectedManifestSha256)' - # Intentionally credential-free. A feed writer is not wired until the hosted gates (writer - # boundary, least-privilege identity, protected recipe ref, single writer) are verified. - - job: ProductionPublishNotActivated - displayName: Production publish not activated - dependsOn: VerifyRelease + - stage: Publish + displayName: Publish verified npm release cohort + dependsOn: Release + # Serialize this pipeline's Publish stages, not writers outside this pipeline. + lockBehavior: sequential + # Stage conditions use dependencies; job variables below use stageDependencies. + condition: and( + not(canceled()), + eq(dependencies.Release.result, 'Succeeded'), + eq(dependencies.Release.outputs['VerifyRelease.verification.ArtifactVerified'], 'true'), + eq(variables['Build.Reason'], 'Manual'), + eq(variables['Build.SourceBranch'], 'refs/heads/hotfix/v1.23123') + ) + jobs: + - job: PublishRelease + displayName: Publish release cohort with reconciled readback + workspace: + clean: all + variables: + ArtifactDir: '$(Pipeline.Workspace)/release-artifact' + NpmWriter: '$(Agent.TempDirectory)/npm-writer-private' + ExpectedManifestSha256: $[ stageDependencies.Release.BuildRelease.outputs['manifest.ManifestSha256'] ] + ExpectedSourceSha: $[ stageDependencies.Release.BuildRelease.outputs['manifest.SourceSha'] ] + templateContext: + inputs: + - input: pipelineArtifact + buildType: current + artifactName: '$(ArtifactName)' + targetPath: '$(ArtifactDir)' steps: - checkout: none + - template: /.azure-pipelines/npm-verify-release.steps.yml@self + parameters: + releaseVersion: ${{ parameters.releaseVersion }} + prepareWriter: true + - task: UseNode@1 + displayName: Use Node 24 + inputs: + version: '24.x' + - task: npmAuthenticate@0 + displayName: Authenticate npm writer via protected WIF + inputs: + workingFile: '$(NpmWriter)/.npmrc' + workloadIdentityServiceConnection: 21d5a1d8-11d3-425c-8d3a-e7f088725481 + feedUrl: 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/' - bash: | set -euo pipefail - echo '##vso[task.logissue type=warning]Verified artifact only. Production npm publishing is not activated in this pipeline.' - displayName: Report that no feed write was attempted + python3 -I - <<'PY' + import hashlib + import json + import os + import re + import subprocess + import tempfile + from pathlib import Path + + os.umask(0o077) + root = Path(os.environ['DIR']).resolve() + registry = os.environ['REGISTRY'] + version = os.environ['RELEASE_VERSION'] + auth_line = re.compile(r'//pkgs\.dev\.azure\.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/:_authToken=\S+') + if registry != 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/': + raise SystemExit('Publish registry endpoint is not approved.') + npmrc = root / '.npmrc' + if not npmrc.is_file(): + raise SystemExit('Writer .npmrc is missing.') + if not any(auth_line.fullmatch(line.strip()) for line in npmrc.read_text(encoding='utf-8').splitlines()): + raise SystemExit('Scoped npm _authToken line is missing after npmAuthenticate.') + cohort = json.loads((root / 'cohort.json').read_text(encoding='utf-8')) + rows = cohort.get('packages') + if not isinstance(rows, list) or len(rows) != 9: + raise SystemExit('cohort.json must contain exactly nine validated package rows.') + + numeric_semver = r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)' + inventory_version = re.compile(numeric_semver + r'(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?') + + def parse_numeric_semver(value): + if not re.fullmatch(numeric_semver, value): + raise SystemExit('Encountered non-numeric semver; failing closed.') + parts = value.split('.') + return int(parts[0]), int(parts[1]), int(parts[2]) + + target_key = parse_numeric_semver(version) + base_env = {'PATH': os.environ['PATH'], 'HOME': str(root)} + write_root = root / 'write-cache' + write_root.mkdir(exist_ok=True) + + def run_npm(args, cache_dir, timeout_seconds): + command = [ + 'npm', + *args, + '--registry', + registry, + '--userconfig', + str(npmrc), + '--globalconfig', + '/dev/null', + '--strict-ssl', + 'true', + '--ignore-scripts', + '--fetch-retries', + '0', + '--fetch-timeout', + '60000', + '--logs-max', + '0', + '--cache', + str(cache_dir), + ] + return subprocess.run( + command, + cwd=root, + env=base_env, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + timeout=timeout_seconds, + check=False, + ) + + def read_npm(args, timeout_seconds): + # A fresh cache prevents a retry or readback from proving state using local bytes. + with tempfile.TemporaryDirectory(dir=root, prefix='read-cache-') as cache: + return run_npm([*args, '--prefer-online'], cache, timeout_seconds) + + def read_json(args, spec): + try: + result = read_npm([*args, '--json'], 90) + if result.returncode == 0: + return json.loads(result.stdout) + except (subprocess.TimeoutExpired, ValueError): + pass + raise SystemExit(f'Registry metadata is inconclusive for {spec}.') + + def inventory(name): + payload = read_json(['view', name, 'name', 'version', 'versions', 'dist-tags'], name) + if not isinstance(payload, dict) or sorted(payload.keys()) != ['dist-tags', 'name', 'version', 'versions']: + raise SystemExit(f'Inventory shape is invalid for {name}.') + if payload['name'] != name: + raise SystemExit(f'Inventory package identity mismatch for {name}.') + versions = payload['versions'] + if not isinstance(versions, list) or not all(isinstance(v, str) and inventory_version.fullmatch(v) for v in versions): + raise SystemExit(f'Inventory versions list is invalid for {name}.') + if any(v.startswith(version + '+') for v in versions): + raise SystemExit(f'An existing version has the same SemVer precedence as {name}@{version}.') + tags = payload['dist-tags'] + if not isinstance(tags, dict) or 'latest' not in tags or not isinstance(tags['latest'], str): + raise SystemExit(f'Inventory dist-tags are invalid for {name}.') + if payload['version'] != tags['latest']: + raise SystemExit(f'Inventory latest tag is unstable for {name}.') + if any(tagged not in versions for tagged in tags.values()): + raise SystemExit(f'Inventory contains an unlisted tagged version for {name}.') + latest_key = parse_numeric_semver(tags['latest']) + if latest_key > target_key: + raise SystemExit(f'Latest published version for {name} is newer than target {version}.') + return payload + + def verify_exact_present(row): + name, file_name = row['name'], row['file'] + spec = f'{name}@{version}' + payload = read_json(['view', spec, 'name', 'version', 'dist.integrity', 'dist.tarball'], spec) + if not isinstance(payload, dict) or sorted(payload.keys()) != ['dist.integrity', 'dist.tarball', 'name', 'version']: + raise SystemExit(f'Exact version payload shape is invalid for {spec}.') + if payload['name'] != name or payload['version'] != version or payload['dist.integrity'] != row['integrity']: + raise SystemExit(f'Exact version metadata mismatch for {spec}.') + package = name.split('/', 1)[1] + attachment = f'{package}/-/{package}-{version}.tgz' + legacy_registry = 'https://msazure.pkgs.visualstudio.com/One/_packaging/microsoft-logic-apps/npm/registry/' + allowed_roots = f'(?:{re.escape(registry)}|{re.escape(legacy_registry)})' + # Accept only the exact attachment route, optionally with the npm scope/slash escaped. + route = allowed_roots + r'(?:@|%40)microsoft(?:/|%2[fF])' + re.escape(attachment) + tarball = payload['dist.tarball'] + if not isinstance(tarball, str) or not re.fullmatch(route, tarball): + raise SystemExit(f'Unapproved registry attachment for {spec}.') + # Fetch that attachment directly using the authenticated alias. npm handles service redirects. + with tempfile.TemporaryDirectory(dir=root, prefix='readback-') as readback: + try: + pack = read_npm(['pack', f'{registry}@microsoft/{attachment}', '--pack-destination', readback], 120) + except subprocess.TimeoutExpired: + raise SystemExit(f'Exact readback timed out for {spec}.') + packed_path = Path(readback) / file_name + if pack.returncode != 0 or not packed_path.is_file(): + raise SystemExit(f'Exact readback failed for {spec}.') + if packed_path.stat().st_size != row['bytes'] or hashlib.sha256(packed_path.read_bytes()).hexdigest() != row['sha256']: + raise SystemExit(f'Exact readback bytes mismatch for {spec}.') + + states = [] + for row in rows: + name = row['name'] + file_name = row['file'] + if not isinstance(name, str) or not re.fullmatch(r'@microsoft/[a-z0-9-]+', name): + raise SystemExit('cohort.json contains invalid package name.') + if row.get('version') != version: + raise SystemExit(f'cohort.json version mismatch for {name}.') + if not isinstance(file_name, str) or '/' in file_name: + raise SystemExit(f'cohort.json file is invalid for {name}.') + local_file = root / file_name + if (not local_file.is_file() or local_file.stat().st_size != row['bytes'] + or hashlib.sha256(local_file.read_bytes()).hexdigest() != row['sha256']): + raise SystemExit(f'Private writer tarball does not match the verified artifact for {name}.') + inv = inventory(name) + latest = inv['dist-tags']['latest'] + target_present = version in inv['versions'] + if target_present: + if latest != version: + raise SystemExit(f'Target version already exists but latest is {latest} for {name}.') + verify_exact_present(row) + states.append({'row': row, 'present': True}) + else: + states.append({'row': row, 'present': False}) + + for state in states: + row = state['row'] + name = row['name'] + file_name = row['file'] + spec = f'{name}@{version}' + if state['present']: + print(f'Exact latest version already present for {spec}; no publish needed.') + continue + + inv = inventory(name) + latest = inv['dist-tags']['latest'] + if version in inv['versions']: + if latest != version: + raise SystemExit(f'Recheck found existing {spec} but latest is {latest}; refusing write.') + verify_exact_present(row) + print(f'Recheck found exact latest version already present for {spec}; no publish needed.') + continue + + publish_result = None + publish_timeout = False + try: + publish_result = run_npm(['publish', f'./{file_name}', '--tag', 'latest'], write_root, 180) + except subprocess.TimeoutExpired: + publish_timeout = True + + post_inv = inventory(name) + if version not in post_inv['versions'] or post_inv['dist-tags']['latest'] != version: + state_desc = 'timeout' if publish_timeout else f'exit {publish_result.returncode}' + raise SystemExit(f'Publish lacked exact evidence for {spec} after {state_desc}.') + verify_exact_present(row) + if publish_timeout: + print(f'Publish timed out but exact latest evidence is confirmed for {spec}.') + elif publish_result.returncode == 0: + print(f'Published and verified exact latest {spec}.') + else: + print(f'Publish returned nonzero but exact latest evidence is confirmed for {spec}.') + + # Check the whole cohort's latest tags after writing. Exact versions are immutable, + # and the bytes were freshly read from this same feed above. + for row in rows: + name = row['name'] + if inventory(name)['dist-tags']['latest'] != version: + raise SystemExit(f'Final registry latest is not {version} for {name}.') + print(f'Azure Artifacts npm base feed confirmed all nine exact versions, artifact digests, and latest={version}.') + PY + displayName: Preflight, publish, and reconcile npm release cohort + workingDirectory: '$(NpmWriter)' env: - BASH_ENV: /dev/null \ No newline at end of file + BASH_ENV: /dev/null + DIR: '$(NpmWriter)' + REGISTRY: '$(NpmRegistry)' + RELEASE_VERSION: ${{ parameters.releaseVersion }} \ No newline at end of file diff --git a/.azure-pipelines/npm-verify-release.steps.yml b/.azure-pipelines/npm-verify-release.steps.yml new file mode 100644 index 00000000000..2817b45b2b5 --- /dev/null +++ b/.azure-pipelines/npm-verify-release.steps.yml @@ -0,0 +1,169 @@ +parameters: + - name: releaseVersion + type: string + default: '' + - name: prepareWriter + type: boolean + default: false + +steps: + - bash: | + set -euo pipefail + python3 -I - <<'PY' + import base64 + import hashlib + import json + import os + import re + import stat + from pathlib import Path + + version = os.environ['RELEASE_VERSION'] + if len(version) > 40 or not re.fullmatch(r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)', version): + raise SystemExit('Invalid releaseVersion. Enter a stable version such as 5.1024.0 (without the v prefix).') + + hex40 = re.compile(r'[0-9a-f]{40}') + build_id = os.environ['BUILD_ID'] + recipe_sha = os.environ['RECIPE_SHA'].lower() + source_sha = os.environ['SOURCE_SHA'] + manifest_sha256 = os.environ['EXPECTED_MANIFEST_SHA256'] + if not re.fullmatch(r'[1-9]\d{0,14}', build_id) or not hex40.fullmatch(recipe_sha) or not hex40.fullmatch(source_sha): + raise SystemExit('Run identity is invalid.') + if not re.fullmatch(r'[0-9a-f]{64}', manifest_sha256): + raise SystemExit('Expected manifest digest is missing.') + + packages = [ + 'logic-apps-shared', + 'designer-ui', + 'designer-ui-v2', + 'logic-apps-chatbot', + 'logic-apps-designer', + 'logic-apps-designer-v2', + 'logic-apps-data-mapper', + 'logic-apps-data-mapper-v2', + 'vscode-extension-logic-apps', + ] + files = ['microsoft-%s-%s.tgz' % (name, version) for name in packages] + root = os.environ['ARTIFACT_DIR'] + if not stat.S_ISDIR(os.lstat(root).st_mode) or os.path.realpath(root) != os.path.abspath(root): + raise SystemExit('Artifact directory is not confined.') + + entries = os.listdir(root) + if '_manifest' in entries: + if not stat.S_ISDIR(os.lstat(os.path.join(root, '_manifest')).st_mode): + raise SystemExit('Reserved _manifest entry is not a directory.') + entries.remove('_manifest') + if sorted(entries) != sorted(files + ['publisher-artifact.json']): + raise SystemExit('Artifact must contain exactly the nine tarballs and the manifest.') + + nofollow = getattr(os, 'O_NOFOLLOW', 0) + nonblock = getattr(os, 'O_NONBLOCK', 0) + + def read_regular(name, limit): + path = os.path.join(root, name) + try: + fd = os.open(path, os.O_RDONLY | nofollow | nonblock) + except OSError: + raise SystemExit('Artifact entry is not a regular file: ' + name) + with os.fdopen(fd, 'rb') as handle: + if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode): + raise SystemExit('Artifact entry is not a regular file: ' + name) + data = handle.read(limit + 1) + if len(data) > limit: + raise SystemExit('Artifact entry is too large: ' + name) + return data + + manifest = read_regular('publisher-artifact.json', 128 * 1024) + if hashlib.sha256(manifest).hexdigest() != manifest_sha256: + raise SystemExit('Manifest digest does not match the producing job.') + + record = json.loads(manifest) + if not isinstance(record, dict) or sorted(record) != ['destination', 'packages', 'source']: + raise SystemExit('Manifest shape is invalid.') + + source = record['source'] + if not isinstance(source, dict): + raise SystemExit('Manifest shape is invalid.') + + expected_source = { + 'repository': 'Azure/LogicAppsUX', + 'releaseRef': 'refs/tags/v' + version, + 'verifiedSha': source_sha, + 'version': version, + 'buildId': build_id, + 'recipeSha': recipe_sha, + } + if source != expected_source: + raise SystemExit('Manifest provenance does not match this run, release tag, source SHA or recipe commit.') + + expected_destination = { + 'registry': 'https://msazure.pkgs.visualstudio.com/One/_packaging/microsoft-logic-apps/npm/registry/', + 'feedId': '44fc6edc-394a-403a-86cd-700a15978af1', + 'distTag': 'latest', + } + if record['destination'] != expected_destination: + raise SystemExit('Manifest destination is invalid.') + + writer_path = None + if os.environ['PREPARE_WRITER'] == 'true': + writer_dir = os.environ['WRITER_DIR'] + registry = os.environ['REGISTRY'] + if registry != 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/': + raise SystemExit('Writer registry must use the approved modern endpoint.') + if not os.path.isabs(writer_dir) or os.path.realpath(writer_dir) != os.path.abspath(writer_dir): + raise SystemExit('Writer directory is not confined.') + writer_path = Path(writer_dir) + writer_path.mkdir(mode=0o700, exist_ok=False) + + expected_packages = [] + for name, file in zip(packages, files): + data = read_regular(file, 64 * 1024 * 1024) + expected_packages.append( + { + 'name': '@microsoft/' + name, + 'version': version, + 'file': file, + 'integrity': 'sha512-' + base64.b64encode(hashlib.sha512(data).digest()).decode(), + 'sha256': hashlib.sha256(data).hexdigest(), + 'bytes': len(data), + } + ) + # Copy the same bytes just hashed; never reopen the downloaded file for publishing. + if writer_path is not None: + fd = os.open(writer_path / file, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o400) + with os.fdopen(fd, 'wb') as handle: + handle.write(data) + + if record['packages'] != expected_packages: + raise SystemExit('Package identity or integrity mismatch.') + + if writer_path is not None: + cohort_path = writer_path / 'cohort.json' + fd = os.open(str(cohort_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600) + with os.fdopen(fd, 'w', encoding='utf-8') as handle: + json.dump({'packages': expected_packages}, handle, separators=(',', ':')) + + npmrc_path = writer_path / '.npmrc' + fd = os.open(str(npmrc_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600) + with os.fdopen(fd, 'w', encoding='utf-8') as handle: + handle.write('registry=' + registry + '\n') + + print('Verified nine packages for v%s at %s from build %s.' % (version, source_sha, build_id)) + print('##vso[task.setvariable variable=ArtifactVerified;isOutput=true]true') + PY + name: verification + displayName: Verify manifest digest, provenance and nine tarballs + env: + BASH_ENV: /dev/null + ARTIFACT_DIR: '$(ArtifactDir)' + RELEASE_VERSION: ${{ parameters.releaseVersion }} + BUILD_ID: '$(Build.BuildId)' + RECIPE_SHA: '$(Build.SourceVersion)' + SOURCE_SHA: '$(ExpectedSourceSha)' + EXPECTED_MANIFEST_SHA256: '$(ExpectedManifestSha256)' + ${{ if eq(parameters.prepareWriter, true) }}: + PREPARE_WRITER: 'true' + WRITER_DIR: '$(NpmWriter)' + REGISTRY: '$(NpmRegistry)' + ${{ if ne(parameters.prepareWriter, true) }}: + PREPARE_WRITER: 'false' diff --git a/scripts/ado-npm-publisher-lib.cjs b/scripts/ado-npm-publisher-lib.cjs index 5e7658020b2..832347c61df 100644 --- a/scripts/ado-npm-publisher-lib.cjs +++ b/scripts/ado-npm-publisher-lib.cjs @@ -252,6 +252,12 @@ function materializeDetachedSourceWorktree(recipeRoot, sourceRoot, commitSha) { return () => runGit(['worktree', 'remove', '--force', sourceRoot], recipeRoot); } +function restoreTrackedReleaseSource(sourceRoot, commitSha) { + // Restore the committed scanner inputs without removing dependencies and other untracked build outputs. + runGit(['restore', '--source', normalizeSha(commitSha), '--staged', '--worktree', '--no-recurse-submodules', '--', '.'], sourceRoot); + runGit(['diff', '--quiet', 'HEAD', '--', '.'], sourceRoot); +} + function verifyCheckoutHead(sourceRoot, expectedSha) { const head = runGit(['rev-parse', 'HEAD'], sourceRoot).trim().toLowerCase(); if (head !== normalizeSha(expectedSha)) { @@ -387,6 +393,7 @@ module.exports = { releaseRunSource, resolveLocalReleaseTag, resolveReleaseMetadata, + restoreTrackedReleaseSource, snapshotCheckout, verifyBuildPrerequisites, verifyCheckoutHead, diff --git a/scripts/ado-npm-publisher.cjs b/scripts/ado-npm-publisher.cjs index d493e019d4f..6c31611d31a 100644 --- a/scripts/ado-npm-publisher.cjs +++ b/scripts/ado-npm-publisher.cjs @@ -12,6 +12,7 @@ const { readVerifiedContracts, releaseRunSource, resolveLocalReleaseTag, + restoreTrackedReleaseSource, snapshotCheckout, verifyCheckoutHead, verifyCleanCheckout, @@ -137,8 +138,11 @@ async function buildReleaseArtifact(env, log, { run = spawnSync, sandbox = withS const commitSha = resolveLocalReleaseTag(root, source.releaseRef); const verified = { ...source, kind: 'release-tag', commitSha }; log(`Resolved ${source.releaseRef} to ${commitSha}; packing has not started.`); - const sourceRoot = path.join(env.AGENT_TMP, 'release-source'); + const scanRoot = env.RELEASE_SCAN_ROOT; + assert(scanRoot === undefined || path.isAbsolute(scanRoot), 'Expected an absolute release scan root.'); + const sourceRoot = path.join(scanRoot === undefined ? env.AGENT_TMP : fs.realpathSync(scanRoot), 'release-source'); const removeSource = materializeDetachedSourceWorktree(root, sourceRoot, verified.commitSha); + let retainForScan = false; try { const contracts = snapshotCheckout(sourceRoot, verified); const buildEnv = { ...env, SOURCE_ROOT: sourceRoot }; @@ -149,9 +153,16 @@ async function buildReleaseArtifact(env, log, { run = spawnSync, sandbox = withS warnMissingCss: warning => log(`Warning: ${sanitizeAgentOutput(warning)}`), }); log(`Packed and validated ${artifact.packages.length} release tarballs for ${verified.releaseTag} at ${verified.commitSha} (run ${verified.buildId}, recipe ${verified.recipeSha}); publication was not attempted.`); + if (scanRoot !== undefined) { + restoreTrackedReleaseSource(sourceRoot, verified.commitSha); + log(`Retaining tagged source ${verified.commitSha} for Component Governance at ${sanitizeAgentOutput(sourceRoot)}.`); + retainForScan = true; // The injected task runs after this step; workspace cleanup owns the tree. + } return artifact; } finally { - removeSource(); + if (!retainForScan) { + removeSource(); + } } } diff --git a/scripts/ado-npm-publisher.test.cjs b/scripts/ado-npm-publisher.test.cjs index 953a3d66407..432874e9dbc 100644 --- a/scripts/ado-npm-publisher.test.cjs +++ b/scripts/ado-npm-publisher.test.cjs @@ -288,15 +288,18 @@ function releaseRepoFixture({ tagType = 'annotated' } = {}) { return { repo, sha }; } -// Extracts an inline python verifier from the pipeline YAML so the tests run the exact hosted code. +// Run the exact inline pipeline code without loading any hosted services. const pipelineFile = path.join(__dirname, '..', '.azure-pipelines', 'npm-publish.yml'); -function pipelinePython(index) { - const yaml = fs.readFileSync(pipelineFile, 'utf8'); +const verifierFile = path.join(path.dirname(pipelineFile), 'npm-verify-release.steps.yml'); +function pipelinePython(file, index = 0) { + const yaml = fs.readFileSync(file, 'utf8'); const block = [...yaml.matchAll(/python3 -I - <<'PY'\n([\s\S]*?)\n *PY\n/g)][index][1].split('\n'); const indent = Math.min(...block.filter(line => line.trim()).map(line => /^ */.exec(line)[0].length)); return block.map(line => line.slice(indent)).join('\n'); } -const runPython = (index, env) => spawnSync('python3', ['-I', '-'], { input: pipelinePython(index), encoding: 'utf8', env: { PATH: process.env.PATH, ...env } }); +const runPython = (file, env, options = {}) => spawnSync(options.executable ?? 'python3', ['-I', '-'], { + input: pipelinePython(file, options.index), encoding: 'utf8', env: { PATH: process.env.PATH, ...env }, cwd: options.cwd, timeout: 30_000, +}); test('rejects whitespace, non-stable refs and queue macro text before any request', async () => { assert.deepEqual(parseReleaseRef(releaseRef), { version, tag: 'v5.1022.0' }); @@ -1080,27 +1083,45 @@ test('branch fixture rejects a reserved test version already in upstream invento }); -test('release pipeline takes only the releaseVersion and keeps every job credential-free', () => { +test('only the separate protected Publish stage can authenticate after verifying the current run', () => { const yaml = fs.readFileSync(pipelineFile, 'utf8'); + const [release, publish] = yaml.split(/(?= {6}- stage: Publish\n)/); + const verifier = fs.readFileSync(verifierFile, 'utf8'); assert.match(yaml, /^trigger: none\npr: none\nschedules: \[\]$/m); assert.deepEqual([...yaml.matchAll(/^ {2}- name: (\w+)/gm)].map(match => match[1]), ['releaseVersion']); - assert.doesNotMatch(yaml, /npmAuthenticate|System\.AccessToken|serviceConnection|workloadIdentity|type: boolean/i); + assert.doesNotMatch(release, /npmAuthenticate|System\.AccessToken|serviceConnection|workloadIdentity|type: boolean/i); assert.match(yaml, /name: Azure-Pipelines-1ESPT-ExDShared\s+image: ubuntu-latest\s+os: linux/); assert.match(yaml, /fetchTags: true/); assert.match(yaml, /fetchDepth: 0/); - const verify = yaml.slice(yaml.indexOf('- job: VerifyRelease'), yaml.indexOf('- job: ProductionPublishNotActivated')); + assert.match(yaml, /persistCredentials: false/); + assert.match(release, /componentgovernance:\s+useAgentBuildDirectory: true/); + assert.match(release, /RELEASE_SCAN_ROOT: '\$\(Agent\.BuildDirectory\)'/); + const verify = release.slice(release.indexOf('- job: VerifyRelease'), release.indexOf('- job: ProductionPublishNotActivated')); assert.match(verify, /buildType: current/); assert.match(verify, /steps:\s+- checkout: none/); assert.equal((yaml.match(/- checkout: self/g) ?? []).length, 1); - assert.match(yaml.slice(yaml.indexOf('- job: ProductionPublishNotActivated')), /checkout: none/); + assert.match(release.slice(release.indexOf('- job: ProductionPublishNotActivated')), /checkout: none/); + assert.doesNotMatch(publish, /trigger: manual/); + assert.match(publish, /dependsOn: Release/); + assert.match(publish, /^ {8}lockBehavior: sequential$/m); + assert.match(publish, /eq\(dependencies\.Release\.result, 'Succeeded'\)/); + assert.match(publish, /eq\(dependencies\.Release\.outputs\['VerifyRelease\.verification\.ArtifactVerified'\], 'true'\)/); + assert.match(publish, /eq\(variables\['Build\.Reason'\], 'Manual'\)/); + assert.match(publish, /eq\(variables\['Build\.SourceBranch'\], 'refs\/heads\/hotfix\/v1\.23123'\)/); + assert.match(publish, /stageDependencies\.Release\.BuildRelease\.outputs\['manifest\.ManifestSha256'\]/); + assert.match(publish, /stageDependencies\.Release\.BuildRelease\.outputs\['manifest\.SourceSha'\]/); + assert.match(publish, /buildType: current/); + assert.match(publish, /steps:\s+- checkout: none\s+- template: .*npm-verify-release\.steps\.yml[\s\S]+npmAuthenticate@0/); + assert.match(publish, /workloadIdentityServiceConnection: 21d5a1d8-11d3-425c-8d3a-e7f088725481/); + assert.doesNotMatch(publish, /build-release-artifact|npm (?:install|ci)|System\.AccessToken/); // The verifier restates the cohort independently of the producer; it must still name the same nine packages in order. - const listed = /packages = \[([^\]]+)\]/.exec(verify)[1].match(/'[^']+'/g).map(name => `@microsoft/${name.slice(1, -1)}`); + const listed = /packages = \[([^\]]+)\]/.exec(verifier)[1].match(/'[^']+'/g).map(name => `@microsoft/${name.slice(1, -1)}`); assert.deepEqual(listed, COHORT.map(item => item.name)); }); test('inline verifiers accept the same-run artifact and reject changed bytes, wrong runs and unexpected entries', () => { const { dir } = artifactFixture(releaseProvenance); - const recorded = runPython(0, { PACKAGE_OUTPUT: dir }); + const recorded = runPython(pipelineFile, { PACKAGE_OUTPUT: dir }); assert.equal(recorded.status, 0, recorded.stderr); const outputs = Object.fromEntries([...recorded.stdout.matchAll(/variable=(\w+);isOutput=true\](\S+)/g)].map(match => match.slice(1))); const manifestBytes = fs.readFileSync(path.join(dir, 'publisher-artifact.json')); @@ -1108,7 +1129,7 @@ test('inline verifiers accept the same-run artifact and reject changed bytes, wr const env = { ARTIFACT_DIR: dir, RELEASE_VERSION: releaseVersion, BUILD_ID: releaseEnv.BUILD_ID, RECIPE_SHA: recipeSha, SOURCE_SHA: outputs.SourceSha, EXPECTED_MANIFEST_SHA256: outputs.ManifestSha256 }; - const verify = (overrides = {}) => runPython(1, { ...env, ...overrides }); + const verify = (overrides = {}) => runPython(verifierFile, { ...env, PREPARE_WRITER: 'false', ...overrides }); const good = verify(); assert.equal(good.status, 0, good.stderr); assert.match(good.stdout, /Verified nine packages for v5\.1022\.0/); @@ -1165,6 +1186,247 @@ test('inline verifiers accept the same-run artifact and reject changed bytes, wr rejects({}, /not a regular file/); }); +const writerRegistry = 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/'; +const legacyWriterRegistry = 'https://msazure.pkgs.visualstudio.com/One/_packaging/microsoft-logic-apps/npm/registry/'; +const testTokenLine = `//${new URL(writerRegistry).host}${new URL(writerRegistry).pathname}:_authToken=fixture-only`; + +function writerAttachment(name, registry = writerRegistry) { + return `${registry}${name}/-/${name.split('/')[1]}-${version}.tgz`; +} + +function writerFixture() { + const { dir, record } = artifactFixture(releaseProvenance); + const scratch = workspace(); + const cwd = path.join(scratch, 'writer'); + const manifest = fs.readFileSync(path.join(dir, 'publisher-artifact.json')); + const prepare = (writerDir = cwd) => runPython(verifierFile, { + ARTIFACT_DIR: dir, RELEASE_VERSION: releaseVersion, BUILD_ID: releaseEnv.BUILD_ID, RECIPE_SHA: recipeSha, + SOURCE_SHA: commitSha, EXPECTED_MANIFEST_SHA256: crypto.createHash('sha256').update(manifest).digest('hex'), + PREPARE_WRITER: 'true', WRITER_DIR: writerDir, REGISTRY: writerRegistry, + }); + const interpreter = spawnSync('python3', ['-I', '-c', 'import sys; print(sys.executable)'], { encoding: 'utf8' }); + assert.equal(interpreter.status, 0, interpreter.stderr); + const executable = interpreter.stdout.trim(); + const statePath = path.join(scratch, 'registry.json'); + const callsPath = path.join(scratch, 'calls.jsonl'); + const state = Object.fromEntries(record.packages.map(entry => [entry.name, { + ...entry, latest: previousVersion, previousVersion, tarball: writerAttachment(entry.name), + }])); + // No real npm on PATH, even if the writer asks for an unexpected command. + fs.writeFileSync(path.join(scratch, 'npm'), `#!${executable} +import json, os, pathlib, shutil, sys +root = pathlib.Path(__file__).resolve().parent +args = sys.argv[1:] +command, target = args[:2] +def flag(name): + return args[args.index(name) + 1] +assert flag('--registry') == ${JSON.stringify(writerRegistry)} +assert '--ignore-scripts' in args and flag('--globalconfig') == '/dev/null' +assert command == 'publish' or '--prefer-online' in args +assert pathlib.Path(flag('--userconfig')).resolve() == pathlib.Path.cwd() / '.npmrc' +assert 'SYSTEM_ACCESSTOKEN' not in os.environ and 'NPM_CONFIG_REGISTRY' not in os.environ +state_path = root / 'registry.json' +state = json.loads(state_path.read_text()) +if command == 'publish': + name = next(n for n, e in state.items() if e['file'] == pathlib.Path(target).name) +elif command == 'pack': + name = next(n for n, e in state.items() + if target == flag('--registry') + n + '/-/' + n.split('/')[1] + '-' + e['version'] + '.tgz') +else: + name = '@' + target[1:].partition('@')[0] +entry = state[name] +version = entry['version'] +with (root / 'calls.jsonl').open('a') as log: + log.write(json.dumps([command, name, flag('--cache')]) + '\\n') +if command == 'view' and target == name: + if entry.get('metadata') == 'unavailable': + print('untrusted npm output fixture-only', file=sys.stderr) + sys.exit(1) + if entry.get('metadata') == 'malformed': + print('{"dist-tags":') + sys.exit(0) + latest = entry['latest'] + versions = sorted({entry['previousVersion'], latest} | ({version} if entry.get('present') else set()) | set(entry.get('extraVersions', []))) + print(json.dumps({'name': name, 'version': latest, 'versions': versions, 'dist-tags': {'latest': latest}})) +elif command == 'view' and target == name + '@' + version: + assert args[2:6] == ['name', 'version', 'dist.integrity', 'dist.tarball'] + print(json.dumps({'name': name, 'version': version, 'dist.integrity': entry.get('registryIntegrity', entry['integrity']), + 'dist.tarball': entry['tarball']})) +elif command == 'publish': + assert flag('--tag') == 'latest' and target.startswith('./') + assert not entry.get('present') + if not entry.get('dropWrite'): + entry.update({'present': True, 'latest': version}) + if entry.get('moveLatestFor'): + other = state[entry['moveLatestFor']] + other['latest'] = other['previousVersion'] + state_path.write_text(json.dumps(state)) + sys.exit(1 if entry.get('nonzeroWrite') else 0) +elif command == 'pack': + dest = pathlib.Path(flag('--pack-destination')) / entry['file'] + if entry.get('wrongBytes'): + dest.write_bytes(b'not the published attachment') + else: + shutil.copyfile(entry['file'], dest) +else: + sys.exit(13) +`, { mode: 0o700 }); + return { + dir, cwd, prepare, state, record, + run() { + fs.writeFileSync(statePath, JSON.stringify(state)); + fs.writeFileSync(callsPath, ''); + const result = runPython(pipelineFile, { PATH: scratch, DIR: cwd, REGISTRY: writerRegistry, RELEASE_VERSION: releaseVersion, + SYSTEM_ACCESSTOKEN: 'not-for-npm', NPM_CONFIG_REGISTRY: 'https://not-the-feed.invalid/' }, + { executable, cwd, index: 1 }); + const calls = fs.readFileSync(callsPath, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line)); + const persisted = JSON.parse(fs.readFileSync(statePath, 'utf8')); + Object.assign(state, persisted); + return { ...result, calls, writes: calls.filter(([command]) => command === 'publish').map(([, name]) => name) }; + }, + }; +} + +function prepareWriter(fixture, authenticate = true) { + const prepared = fixture.prepare(); + assert.equal(prepared.status, 0, prepared.stderr); + if (authenticate) fs.appendFileSync(path.join(fixture.cwd, '.npmrc'), `${testTokenLine}\n`); +} + +test('writer copies only verified bytes to private scratch and will not use a missing WIF token', () => { + const fixture = writerFixture(); + prepareWriter(fixture, false); + assert.equal(fs.statSync(fixture.cwd).mode & 0o777, 0o700); + const { file } = fixture.record.packages[0]; + const original = fs.readFileSync(path.join(fixture.dir, file)); + fs.writeFileSync(path.join(fixture.dir, file), 'tampered'); + assert.deepEqual(fs.readFileSync(path.join(fixture.cwd, file)), original); + const tampered = fixture.prepare(path.join(workspace(), 'writer')); + assert.notEqual(tampered.status, 0); + assert.match(tampered.stderr, /identity or integrity mismatch/); + const result = fixture.run(); + assert.notEqual(result.status, 0); + assert.deepEqual(result.calls, []); +}); + +test('writer preflights the full cohort, reads back every publication and makes an exact retry a no-op', () => { + const fixture = writerFixture(); + prepareWriter(fixture); + const names = fixture.record.packages.map(item => item.name); + fixture.state[names[0]].tarball = writerAttachment(names[0], legacyWriterRegistry); + fixture.state[names[1]].tarball = writerAttachment(names[1]).replace('@microsoft/', '%40microsoft%2f'); + const result = fixture.run(); + assert.equal(result.status, 0, result.stderr); + const firstWrite = result.calls.findIndex(([command]) => command === 'publish'); + assert.deepEqual([...new Set(result.calls.slice(0, firstWrite).map(([, name]) => name))], names); + assert.deepEqual(result.writes, names); + const packs = result.calls.filter(([command]) => command === 'pack'); + assert.deepEqual(packs.map(([, name]) => name), names); + assert.equal(new Set(packs.map(([, , cache]) => cache)).size, 9); + assert.ok(packs.every(([, , cache]) => !result.calls.some(([command, , writeCache]) => command === 'publish' && cache === writeCache))); + const retry = fixture.run(); + assert.equal(retry.status, 0, retry.stderr); + assert.deepEqual(retry.writes, []); + assert.deepEqual(retry.calls.filter(([command]) => command === 'pack').map(([, name]) => name), names); +}); + +test('a changed private tarball blocks publishing the entire cohort', () => { + const fixture = writerFixture(); + prepareWriter(fixture); + const privateTarball = path.join(fixture.cwd, fixture.record.packages.at(-1).file); + fs.chmodSync(privateTarball, 0o600); + fs.appendFileSync(privateTarball, 'changed'); + const result = fixture.run(); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /does not match the verified artifact/); + assert.deepEqual(result.writes, []); +}); + +test('the last package blocks all writes if latest is newer, bytes conflict, or registry reads are inconclusive', () => { + const fixture = writerFixture(); + prepareWriter(fixture); + const name = fixture.record.packages.at(-1).name; + const defaults = fixture.state[name]; + for (const change of [ + { latest: '5.1023.0' }, + { extraVersions: [`${version}+ambiguous`] }, + { present: true, latest: version, registryIntegrity: 'sha512-conflicting' }, + { present: true, latest: version, wrongBytes: true }, + { present: true }, + { metadata: 'unavailable' }, + { metadata: 'malformed' }, + ]) { + fixture.state[name] = { ...defaults, ...change }; + const result = fixture.run(); + assert.notEqual(result.status, 0, JSON.stringify(change)); + assert.deepEqual(result.writes, []); + assert.doesNotMatch(result.stderr + result.stdout, /fixture-only/); + } +}); + +test('writer rejects attachments outside the exact feed, package and version before packing or writing', () => { + const fixture = writerFixture(); + prepareWriter(fixture); + const { name } = fixture.record.packages.at(-1); + const approved = writerAttachment(name); + const otherName = fixture.record.packages[0].name; + Object.assign(fixture.state[name], { present: true, latest: version }); + for (const tarball of [ + null, + approved.replace('https:', 'http:'), + approved.replace('pkgs.dev.azure.com', 'other.invalid'), + approved.replace('/One/_packaging/', '/other/_packaging/'), + approved.replace('/microsoft-logic-apps/', '/other-feed/'), + writerAttachment(otherName), + approved.replace(`-${version}.tgz`, `-${previousVersion}.tgz`), + `${approved}?unexpected=1`, + ]) { + fixture.state[name].tarball = tarball; + const result = fixture.run(); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /Unapproved registry attachment/); + assert.ok(result.calls.every(([command]) => command === 'view')); + } +}); + +test('writer reconciles a nonzero response with exact bytes, stops on an unproved result and resumes safely', () => { + const fixture = writerFixture(); + prepareWriter(fixture); + const [first, second, ...rest] = fixture.record.packages.map(item => item.name); + fixture.state[first].nonzeroWrite = true; + fixture.state[second].dropWrite = true; + const result = fixture.run(); + assert.notEqual(result.status, 0); + assert.deepEqual(result.writes, [first, second]); + assert.ok(result.calls.some(([command, name]) => command === 'pack' && name === first)); + fixture.state[second].dropWrite = false; + const retry = fixture.run(); + assert.equal(retry.status, 0, retry.stderr); + assert.deepEqual(retry.writes, [second, ...rest]); +}); + +test('writer stops after the first publish when registry readback differs despite matching metadata', () => { + const fixture = writerFixture(); + prepareWriter(fixture); + const [first] = fixture.record.packages; + fixture.state[first.name].wrongBytes = true; + const result = fixture.run(); + assert.notEqual(result.status, 0); + assert.deepEqual(result.writes, [first.name]); + assert.ok(result.calls.some(([command, name]) => command === 'pack' && name === first.name)); +}); + +test('writer fails if an earlier package is no longer latest at the end of publication', () => { + const fixture = writerFixture(); + prepareWriter(fixture); + const names = fixture.record.packages.map(item => item.name); + fixture.state[names.at(-1)].moveLatestFor = names[0]; + const result = fixture.run(); + assert.notEqual(result.status, 0); + assert.deepEqual(result.writes, names); + assert.match(result.stderr, /Final registry latest is not/); +}); + test('accepts only canonical ASCII stable releaseVersion', () => { assert.equal(parseReleaseVersion(releaseVersion), releaseVersion); for (const value of ['v5.1022.0', '5.01022.0', '5.1022.00', '5.1022.0', '5.1022.0\n', '5.1022.0 ', '5.1022', '', undefined]) { @@ -1241,19 +1503,24 @@ test('release reads close each connection, refuse redirects and sanitize failure }); // Builds from a local repository checkout: no network source fetch is available to this path. -function releaseBuild({ repo, env: overrides = {} }) { +function releaseBuild({ repo, env: overrides = {}, failBuild = false }) { const tmp = workspace(); const env = { ...releaseEnv, RECIPE_SHA: gitFixture(repo, 'rev-parse', 'HEAD'), ...overrides, AGENT_TMP: tmp, ARTIFACT_ROOT: path.join(tmp, 'out'), PATH: process.env.PATH }; - const sourceRoot = path.join(tmp, 'release-source'); + const sourceRoot = path.join(overrides.RELEASE_SCAN_ROOT ?? tmp, 'release-source'); const calls = []; const run = (command, args, { cwd }) => { assert.equal(cwd, sourceRoot); if (calls.length === 0) { assert.equal(fs.readFileSync(path.join(cwd, 'release-source.txt'), 'utf8'), 'tagged bytes\n'); assert.equal(gitFixture(cwd, 'rev-parse', 'HEAD'), gitFixture(repo, 'rev-parse', `${releaseRef}^{commit}`)); + fs.mkdirSync(path.join(cwd, 'node_modules')); + fs.writeFileSync(path.join(cwd, 'node_modules', '.modules.yaml'), 'fixture dependency metadata\n'); } calls.push(args); + if (failBuild && args.includes('build:lib')) { + return { status: 1, stdout: '', stderr: '' }; + } if (command === process.execPath) { for (const item of COHORT) { const file = path.join(sourceRoot, item.directory, 'package.json'); @@ -1293,11 +1560,32 @@ test('release build uses the annotated tag bytes rather than the recipe and veri assert.equal(fs.readFileSync(marker, 'utf8'), 'updated recipe bytes\n'); // The manifest goes through the inline verifier exactly as the hosted consumer job would see it. const manifestPath = path.join(env.ARTIFACT_ROOT, 'publisher-artifact.json'); - const verify = runPython(1, { ARTIFACT_DIR: env.ARTIFACT_ROOT, RELEASE_VERSION: releaseVersion, BUILD_ID: env.BUILD_ID, RECIPE_SHA: recipeHead, SOURCE_SHA: sha, + const verify = runPython(verifierFile, { ARTIFACT_DIR: env.ARTIFACT_ROOT, RELEASE_VERSION: releaseVersion, BUILD_ID: env.BUILD_ID, + RECIPE_SHA: recipeHead, SOURCE_SHA: sha, PREPARE_WRITER: 'false', EXPECTED_MANIFEST_SHA256: crypto.createHash('sha256').update(fs.readFileSync(manifestPath)).digest('hex') }); assert.equal(verify.status, 0, verify.stderr); }); +test('hosted release keeps the exact tagged worktree and restores tracked manifests for Component Governance', async () => { + const { repo, sha } = releaseRepoFixture(); + const scanRoot = workspace(); + const { result, logs } = releaseBuild({ repo, env: { RELEASE_SCAN_ROOT: scanRoot } }); + assert.equal((await result).source.verifiedSha, sha); + const sourceRoot = path.join(scanRoot, 'release-source'); + assert.equal(gitFixture(sourceRoot, 'rev-parse', 'HEAD'), sha); + assert.equal(gitFixture(sourceRoot, 'status', '--porcelain', '--untracked-files=no'), ''); + assert.equal(fs.readFileSync(path.join(sourceRoot, 'node_modules', '.modules.yaml'), 'utf8'), 'fixture dependency metadata\n'); + assert.match(logs.at(-1), /Retaining tagged source .* for Component Governance/); +}); + +test('failed hosted release cleans the scan worktree', async () => { + const { repo } = releaseRepoFixture(); + const scanRoot = workspace(); + const { result } = releaseBuild({ repo, env: { RELEASE_SCAN_ROOT: scanRoot }, failBuild: true }); + await assert.rejects(result, /corepack failed: exit 1/); + assert.equal(fs.existsSync(path.join(scanRoot, 'release-source')), false); +}); + test('release build accepts a lightweight local tag without GitHub API access', async (t) => { const { repo, sha } = releaseRepoFixture({ tagType: 'lightweight' }); const fetchCall = t.mock.method(globalThis, 'fetch', () => { throw new Error('unexpected network'); });