Compare commits

...
4 Commits
Author SHA1 Message Date
james.maes 5196609974 Merge pull request #16 from QRun-IO/develop
release: publish npm Trusted Publishing support in orb 0.6.7
2026-09-29 14:18:44 -05:00
james.maes 988401023a Merge pull request #15 from QRun-IO/feature/GH-912-npm-trusted-publishing
fix(ci): support CircleCI npm Trusted Publishing
2026-09-29 14:17:01 -05:00
james.maes e23bd4588d test(ci): preserve stdin for npm subprocesses (#912) 2026-09-29 14:14:32 -05:00
james.maes 51e9bba5b0 fix(ci): support tokenless npm publishing (#912)
Refs QRun-IO/qqq#912. Use CircleCI OIDC with isolated npm configuration and retain legacy authentication by default.
2026-09-29 14:09:04 -05:00
6 changed files with 206 additions and 7 deletions

No files matched your search

+4 -1
View File
@@ -26,12 +26,15 @@ jobs:
# You may want to add additional validation steps to ensure the commands are working as expected.
command-test:
docker:
- image: cimg/base:current
- image: cimg/node:24.21
steps:
- checkout
- run:
name: Verify Maven settings stay out of build logs
command: bash tests/test_maven_settings_output.sh
- run:
name: Verify npm publisher authentication and dist-tags
command: python3 tests/test_node_npm_publish.py
# Run your orb's commands to validate them.
- qqq-orb/install_asciidoctor
+14
View File
@@ -60,6 +60,20 @@ workflows:
| `static_analysis` | Run SpotBugs and PMD static analysis |
| `security_scan` | Run Gitleaks, Semgrep, OWASP Dependency Check, and CycloneDX SBOM |
### npm Trusted Publishing
For npm Trusted Publishing, set `npm_trusted_publishing: true` and use a supported
executor such as `node_version: "24.21"` on `node_publish`. Configure the package's
[npm Trusted Publisher](https://docs.npmjs.com/trusted-publishers/) for the exact
CircleCI organization, project, pipeline definition and VCS origin, and allow
direct `npm publish`. The job requires Node >=22.14.0 and npm >=11.5.1, obtains an
OIDC identity at publish time, and does not run `npm whoami` or need `NPM_TOKEN`.
Existing token authentication remains the default. Trusted mode requires no
project `.npmrc` or npm credential/config-path environment settings; it ignores user/global
npm config and clears conventional token variables to prevent token fallback.
CircleCI does not currently provide npm provenance attestations. A successful
real publication, not a dry run, verifies the trust relationship.
### Branch Types
| Branch | Version Format |
+14 -3
View File
@@ -3,10 +3,21 @@ description: >
- Sets up NPM authentication
- Publishes the package to NPM
parameters:
trusted_publishing:
type: boolean
default: false
description: "Authenticate npm publish using the CircleCI job's OIDC identity."
steps:
- run:
name: "Setup NPM authentication"
command: <<include(scripts/node_npm_auth.sh)>>
- unless:
condition: << parameters.trusted_publishing >>
steps:
- run:
name: "Setup NPM authentication"
command: <<include(scripts/node_npm_auth.sh)>>
- run:
name: "Publish to NPM"
environment:
QQQ_NPM_TRUSTED_PUBLISHING: << parameters.trusted_publishing >>
command: <<include(scripts/node_npm_publish.sh)>>
+6 -1
View File
@@ -16,6 +16,10 @@ parameters:
type: string
default: "snapshot"
description: "Branch type: snapshot, release_candidate, release, or hotfix"
npm_trusted_publishing:
type: boolean
default: false
description: "Use CircleCI OIDC instead of NPM_TOKEN (Node >=22.14, npm >=11.5.1)."
steps:
- git_full_checkout
@@ -26,7 +30,8 @@ steps:
- attach_workspace:
at: .
- node_build_package
- node_publish
- node_publish:
trusted_publishing: << parameters.npm_trusted_publishing >>
# GitHub releases only for final releases and hotfixes (not RCs)
# RCs just publish artifacts - GitHub release happens when merged to main
+40 -2
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
############################################################################
## node_npm_publish.sh
@@ -16,7 +16,45 @@
## Usage: Called by CircleCI orb command node_publish
############################################################################
set -e
set +x
set -euo pipefail
if [[ "${QQQ_NPM_TRUSTED_PUBLISHING:-false}" == "true" ]]; then
NPM_CLI_VERSION=$(npm --version)
node - "$NPM_CLI_VERSION" <<'NODE'
const atLeast = (actual, minimum) => {
const parts = actual.split('.').map(Number);
return minimum.every((part, index) => parts[index] === part)
|| minimum.some((part, index) => parts[index] > part
&& minimum.slice(0, index).every((value, previous) => parts[previous] === value));
};
if (!atLeast(process.versions.node, [22, 14, 0]) || !atLeast(process.argv[2], [11, 5, 1])) {
console.error('Trusted publishing requires Node >=22.14.0 and npm >=11.5.1.');
process.exit(1);
}
if (Object.keys(process.env).some(name => /^npm_config_.*(auth|password|username|userconfig|globalconfig)/i.test(name))) {
console.error('Remove npm credential/config-path environment settings before using trusted publishing.');
process.exit(1);
}
NODE
# Do not inherit a project/user token or write the short-lived identity to disk.
if [[ -f .npmrc ]]; then
echo "Trusted publishing requires a publish directory without .npmrc." >&2
exit 1
fi
unset NPM_TOKEN NODE_AUTH_TOKEN NPM_AUTH_TOKEN
PUBLISH_CONFIG_DIR=$(mktemp -d)
trap 'rm -rf "$PUBLISH_CONFIG_DIR"' EXIT
export NPM_CONFIG_USERCONFIG="$PUBLISH_CONFIG_DIR/user.npmrc"
export NPM_CONFIG_GLOBALCONFIG="$PUBLISH_CONFIG_DIR/global.npmrc"
NPM_ID_TOKEN=$(circleci run oidc get --claims '{"aud":"npm:registry.npmjs.org"}')
if [[ -z "$NPM_ID_TOKEN" ]]; then
echo "CircleCI did not provide an npm OIDC token." >&2
exit 1
fi
export NPM_ID_TOKEN
fi
# Extract version from package.json
VERSION=$(grep '"version"' package.json | sed 's/.*"version": "//;s/".*//')
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""Exercise publisher boundaries without network access or real credentials."""
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / 'src/scripts/node_npm_publish.sh'
NODE = shutil.which('node')
NPM = shutil.which('npm')
class PublishTests(unittest.TestCase):
def run_publish(self, version='1.0.0-RC.1', trusted=True, project_config=False, **overrides):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
bin_dir = root / 'bin'
bin_dir.mkdir()
(root / 'package.json').write_text(json.dumps({'version': version}) + '\n')
if project_config:
(root / '.npmrc').write_text('//registry.npmjs.org/:_authToken=synthetic-old-token\n')
scripts = {
'npm': '''#!/usr/bin/env python3
import json, os, pathlib, subprocess, sys
if sys.argv[1:] == ['--version']:
print(os.environ.get('TEST_NPM_VERSION', '11.19.0'))
else:
assert sys.argv[1] == 'publish', 'Unexpected npm command'
if os.environ['QQQ_NPM_TRUSTED_PUBLISHING'] == 'true':
assert os.environ.get('NPM_ID_TOKEN') == 'synthetic-oidc-token'
assert all(not os.environ.get(name) for name in ['NPM_TOKEN', 'NODE_AUTH_TOKEN', 'NPM_AUTH_TOKEN'])
assert os.environ['NPM_CONFIG_USERCONFIG'] != os.environ['NPM_CONFIG_GLOBALCONFIG']
assert not pathlib.Path(os.environ['NPM_CONFIG_USERCONFIG']).exists()
assert not pathlib.Path(os.environ['NPM_CONFIG_GLOBALCONFIG']).exists()
registry = subprocess.check_output([os.environ['TEST_REAL_NPM'], 'config', 'get', 'registry'], text=True)
assert registry.strip() == 'https://registry.npmjs.org/'
pathlib.Path('published.json').write_text(json.dumps(sys.argv[1:]))
sys.exit(int(os.environ.get('TEST_PUBLISH_STATUS', '0')))
''',
'circleci': '''#!/usr/bin/env python3
import os, pathlib, sys
assert sys.argv[1:] == ['run', 'oidc', 'get', '--claims', '{"aud":"npm:registry.npmjs.org"}']
pathlib.Path('oidc-called').touch()
print(os.environ.get('TEST_OIDC_VALUE', 'synthetic-oidc-token'))
sys.exit(int(os.environ.get('TEST_OIDC_STATUS', '0')))
''',
'node': '''#!/usr/bin/env python3
import os, subprocess, sys
if sys.argv[1] != '-':
os.execv(os.environ['TEST_REAL_NODE'], [os.environ['TEST_REAL_NODE'], *sys.argv[1:]])
source = sys.stdin.read()
if 'TEST_NODE_VERSION' in os.environ:
source = source.replace('process.versions.node', repr(os.environ['TEST_NODE_VERSION']))
sys.exit(subprocess.run([os.environ['TEST_REAL_NODE'], *sys.argv[1:]], input=source, text=True).returncode)
'''
}
for name, contents in scripts.items():
executable = bin_dir / name
executable.write_text(contents)
executable.chmod(0o755)
env = dict(os.environ, PATH=str(bin_dir) + os.pathsep + os.environ['PATH'],
QQQ_NPM_TRUSTED_PUBLISHING=str(trusted).lower(), TEST_REAL_NODE=NODE, TEST_REAL_NPM=NPM,
NPM_TOKEN='synthetic-old-token', NODE_AUTH_TOKEN='synthetic-old-token',
NPM_AUTH_TOKEN='synthetic-old-token', **overrides)
result = subprocess.run(['bash', '-x', str(SCRIPT)], cwd=root, env=env,
text=True, capture_output=True)
self.assertNotIn('synthetic-oidc-token', result.stdout + result.stderr)
self.assertNotIn('synthetic-old-token', result.stdout + result.stderr)
published = root / 'published.json'
return result, json.loads(published.read_text()) if published.exists() else None, (root / 'oidc-called').exists()
def test_tags_and_legacy_authentication(self):
for trusted in [True, False]:
for version, tag in [('1.0.0-RC.1', 'rc'), ('1.0.0-SNAPSHOT', 'snapshot'),
('1.0.0-alpha.1', 'next'), ('1.0.0-beta.1', 'next'), ('1.0.0', 'latest')]:
with self.subTest(trusted=trusted, version=version):
result, args, oidc = self.run_publish(version, trusted)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(args, ['publish', '--access', 'public', '--tag', tag])
self.assertEqual(oidc, trusted)
def test_oidc_failure_or_empty_token_stops_publication(self):
for overrides in [{'TEST_OIDC_STATUS': '7'}, {'TEST_OIDC_VALUE': ''}]:
with self.subTest(overrides=overrides):
result, args, oidc = self.run_publish(**overrides)
self.assertNotEqual(result.returncode, 0)
self.assertIsNone(args)
self.assertTrue(oidc)
def test_unsupported_toolchains_stop_before_requesting_identity(self):
for overrides in [{'TEST_NPM_VERSION': '11.5.0'}, {'TEST_NPM_VERSION': '10.9.0'},
{'TEST_NODE_VERSION': '22.13.1'}, {'TEST_NODE_VERSION': '20.20.0'}]:
with self.subTest(overrides=overrides):
result, args, oidc = self.run_publish(**overrides)
self.assertNotEqual(result.returncode, 0)
self.assertIsNone(args)
self.assertFalse(oidc)
def test_minimum_toolchain_is_supported(self):
result, args, oidc = self.run_publish(TEST_NPM_VERSION='11.5.1', TEST_NODE_VERSION='22.14.0')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIsNotNone(args)
self.assertTrue(oidc)
def test_project_or_environment_credentials_are_rejected(self):
for overrides in [{'project_config': True}, {'NPM_CONFIG__AUTH': 'synthetic-old-token'},
{'npm_config_userconfig': '/synthetic/legacy.npmrc'},
{'npm_config_USERCONFIG': '/synthetic/legacy.npmrc'},
{'Npm_Config_Globalconfig': '/synthetic/legacy.npmrc'}]:
with self.subTest(overrides=overrides):
result, args, oidc = self.run_publish(**overrides)
self.assertNotEqual(result.returncode, 0)
self.assertIsNone(args)
self.assertFalse(oidc)
def test_publish_failure_is_not_reported_as_success(self):
result, args, oidc = self.run_publish(TEST_PUBLISH_STATUS='9')
self.assertEqual(result.returncode, 9)
self.assertIsNotNone(args)
self.assertTrue(oidc)
self.assertNotIn('Successfully published', result.stdout)
if __name__ == '__main__':
unittest.main()