Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .github/workflows/node-simple-pnpm.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,18 @@ on:
type: string
required: true

npm-own-registry-scopes:
description: |
Space-separated npm scopes this repository installs from and
publishes to npm.platforma.bio instead of npmjs, e.g.
'@platforma-open'. Empty (default): unchanged. Publishing there needs
the repository's `npm-publish` environment (main only); which
repository may publish which package is decided by the registry
(first publish, npm provenance, admin pins).
type: string
required: false
default: ''

#
# Distribution control
#
Expand Down Expand Up @@ -631,6 +643,7 @@ jobs:
pnpm-version: ${{ env.PNPM_VERSION || inputs.pnpm-version }}
cache-hashfiles-search-path: ${{ inputs.cache-hashfiles-search-path }}
npmrc-config: ${{ inputs.npmrc-config }}
own-registry-scopes: ${{ inputs.npm-own-registry-scopes }}
cache-s3-access-key: ${{ env.HZ_CI_CACHE_S3_ACCESS_KEY }}
cache-s3-secret-key: ${{ env.HZ_CI_CACHE_S3_SECRET_KEY }}

Expand Down Expand Up @@ -794,6 +807,7 @@ jobs:
pnpm-version: ${{ env.PNPM_VERSION || inputs.pnpm-version }}
cache-hashfiles-search-path: ${{ inputs.cache-hashfiles-search-path }}
npmrc-config: ${{ inputs.npmrc-config }}
own-registry-scopes: ${{ inputs.npm-own-registry-scopes }}
cache-s3-access-key: ${{ env.HZ_CI_CACHE_S3_ACCESS_KEY }}
cache-s3-secret-key: ${{ env.HZ_CI_CACHE_S3_SECRET_KEY }}

Expand Down Expand Up @@ -934,6 +948,7 @@ jobs:
pnpm-version: ${{ env.PNPM_VERSION || inputs.pnpm-version }}
cache-hashfiles-search-path: ${{ inputs.cache-hashfiles-search-path }}
npmrc-config: ${{ inputs.npmrc-config }}
own-registry-scopes: ${{ inputs.npm-own-registry-scopes }}
cache-s3-access-key: ${{ env.HZ_CI_CACHE_S3_ACCESS_KEY }}
cache-s3-secret-key: ${{ env.HZ_CI_CACHE_S3_SECRET_KEY }}

Expand Down Expand Up @@ -1143,6 +1158,24 @@ jobs:
NPMJS_TOKEN: ${{ env.NPMJS_TOKEN }}
PL_DOCKER_REGISTRY_PUSH_TO: ${{ inputs.pl-docker-registry-push-to }}

# Does anything packed go to our own registry? Then the upload job runs
# in the protected `npm-publish` environment, which that registry's OIDC
# allow entry requires. Repos that publish only to npmjs are unaffected.
# Gated on the opt-in input: a repository that does not set
# npm-own-registry-scopes never gets the environment, whatever its
# .npmrc maps.
- name: Any package for npm.platforma.bio?
id: npm-own-registry
if: inputs.npm-own-registry-scopes != ''
&& steps.npm-pack.outputs.count != '' && steps.npm-pack.outputs.count != '0'
shell: bash
env:
MANIFEST: ${{ steps.npm-pack.outputs.dir }}/manifest.jsonl
run: |
if grep -q '"registry":"https://npm.platforma.bio/' "${MANIFEST}"; then
echo "own=true" >> "${GITHUB_OUTPUT}"
fi

- name: Upload npm tarballs
if: steps.npm-pack.outputs.count != '' && steps.npm-pack.outputs.count != '0'
uses: actions/upload-artifact@v4
Expand All @@ -1159,6 +1192,8 @@ jobs:
started: 'true'
# Set only when the pack step ran: '' means no release.
npm-pack-count: ${{ steps.npm-pack.outputs.count }}
# 'true' when at least one package goes to npm.platforma.bio.
npm-own-registry: ${{ steps.npm-own-registry.outputs.own }}

# npm upload with trusted publishing. Fixed GitHub-hosted runner, not
# gha-runner-label: npm rejects OIDC tokens from self-hosted runners. Runs
Expand All @@ -1174,6 +1209,10 @@ jobs:
!cancelled() &&
needs.build-test-publish.result == 'success' &&
needs.build-test-publish.outputs.npm-pack-count != ''
# npm.platforma.bio accepts the OIDC token only from this environment
# (main-only branch rule, no reviewer: docs/npm-registry.md in
# milaboratory/infrastructure). Empty = no environment, as before.
environment: ${{ needs.build-test-publish.outputs.npm-own-registry == 'true' && 'npm-publish' || '' }}
permissions:
id-token: write
contents: write
Expand Down
6 changes: 3 additions & 3 deletions actions/node/npm-split-publish/lib/publish/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion actions/node/npm-split-publish/lib/publish/index.js.map

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions actions/node/npm-split-publish/src/bin/publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
//
// Env: TARBALL_DIR (required), ACCESS_PUBLIC ('true'), NPM_AUTH_TOKEN,
// NPMJS_FALLBACK_TOKEN, NPM_PUBLISH_USERCONFIG (default
// $RUNNER_TEMP/publish.npmrc).
// $RUNNER_TEMP/publish.npmrc). Uploads to npm.platforma.bio use a GitHub OIDC
// token (core.getIDToken; the job needs `id-token: write`).

import * as core from '@actions/core';
import * as path from 'path';
Expand All @@ -22,7 +23,7 @@ async function main(): Promise<void> {
npmjsFallbackToken: process.env.NPMJS_FALLBACK_TOKEN,
userconfig,
},
{ run: spawnRunner, log: core.info, group: core.group },
{ run: spawnRunner, log: core.info, group: core.group, oidcToken: (audience) => core.getIDToken(audience) },
);
core.info(`Published ${published.length} package(s).`);
}
Expand Down
45 changes: 42 additions & 3 deletions actions/node/npm-split-publish/src/publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ import { readPackedManifest } from './tarball';

export const NPMJS_HOST = 'registry.npmjs.org';
export const GITHUB_PACKAGES_HOST = 'npm.pkg.github.com';
/**
* Our registry (Verdaccio + OIDC). It accepts a GitHub Actions OIDC token with
* this audience as the npm token: no stored secret. The publishing job must
* run in the protected `npm-publish` environment, which the registry's allow
* entry requires.
*/
export const OWN_REGISTRY_HOST = 'npm.platforma.bio';
export const OWN_REGISTRY_AUDIENCE = 'https://npm.platforma.bio';

export interface Credentials {
/** Token for npm.pkg.github.com (the job's GITHUB_TOKEN). Sent nowhere else. */
Expand All @@ -37,12 +45,18 @@ export interface PublishDeps {
run: Runner;
log: (message: string) => void;
group: <T>(title: string, fn: () => Promise<T>) => Promise<T>;
/**
* A GitHub Actions OIDC token for `audience`. Called before every upload to
* the own registry: the tokens live minutes, a publish run can take longer.
*/
oidcToken?: (audience: string) => Promise<string>;
}

// Env var names the generated npm config refers to; npm expands them when it
// reads the file, so the file itself holds no secret.
const NPM_AUTH_TOKEN_VAR = 'NPM_AUTH_TOKEN';
const NPMJS_FALLBACK_TOKEN_VAR = 'NPMJS_FALLBACK_TOKEN';
const OWN_REGISTRY_TOKEN_VAR = 'NPM_PLATFORMA_OIDC_TOKEN';

/**
* npm config (userconfig) for uploading `entries`. Every registry must be
Expand Down Expand Up @@ -77,8 +91,14 @@ export function npmrcFor(entries: ManifestEntry[], credentials: Credentials): st
}
lines.add(`//${GITHUB_PACKAGES_HOST}/:_authToken=\${${NPM_AUTH_TOKEN_VAR}}`);
break;
case OWN_REGISTRY_HOST:
// Filled per upload with a fresh OIDC token (publishTarballs).
lines.add(`//${OWN_REGISTRY_HOST}/:_authToken=\${${OWN_REGISTRY_TOKEN_VAR}}`);
break;
default:
throw new Error(`${registry}: no credentials for this registry (supported: ${NPMJS_HOST}, ${GITHUB_PACKAGES_HOST})`);
throw new Error(
`${registry}: no credentials for this registry (supported: ${NPMJS_HOST}, ${GITHUB_PACKAGES_HOST}, ${OWN_REGISTRY_HOST})`,
);
}
}
return [...lines].map((l) => l + '\n').join('');
Expand Down Expand Up @@ -166,6 +186,7 @@ export async function publishTarballs(options: PublishOptions, deps: PublishDeps
NPM_CONFIG_USERCONFIG: userconfig,
[NPM_AUTH_TOKEN_VAR]: options.npmAuthToken ?? '',
[NPMJS_FALLBACK_TOKEN_VAR]: options.npmjsFallbackToken ?? '',
[OWN_REGISTRY_TOKEN_VAR]: '',
};
const envRun: Runner = (command, args, runOptions) => run(command, args, { ...runOptions, env });

Expand All @@ -176,13 +197,31 @@ export async function publishTarballs(options: PublishOptions, deps: PublishDeps
log(`${label}: already in ${entry.registry}, skipping`);
continue;
}
// Each upload gets its own env: a fresh OIDC token for the own registry
// (tokens live minutes), nothing extra for the others.
let uploadEnv = env;
if (new URL(entry.registry).hostname === OWN_REGISTRY_HOST) {
if (!deps.oidcToken) throw new Error(`${label}: no OIDC token source for ${OWN_REGISTRY_HOST}`);
uploadEnv = { ...env, [OWN_REGISTRY_TOKEN_VAR]: await deps.oidcToken(OWN_REGISTRY_AUDIENCE) };
// npm 11 sees GitHub's OIDC variables and first tries its own
// trusted-publishing exchange against this registry (a token with an
// audience the registry refuses: a 401 in its log on every upload).
// The token above is all it needs.
delete uploadEnv.ACTIONS_ID_TOKEN_REQUEST_URL;
delete uploadEnv.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
}
const result = await group(`${label} -> ${entry.registry}`, () =>
envRun('npm', publishArgs(entry, dir, accessPublic), { cwd, echo: true }),
run('npm', publishArgs(entry, dir, accessPublic), { cwd, echo: true, env: uploadEnv }),
);
if (result.code !== 0) {
// A version the lookup could not see, e.g. a restricted package queried
// without a token on a re-run: the registry refuses it as a duplicate.
if (/You cannot publish over the previously published versions/.test(result.stderr + result.stdout)) {
// npmjs: "You cannot publish over ..."; our registry (Verdaccio): E409
// "this package is already present". E409 counts only for our registry:
// on npmjs a 409 can be a transient conflict, not a duplicate.
const output = result.stderr + result.stdout;
const own = new URL(entry.registry).hostname === OWN_REGISTRY_HOST;
if (/You cannot publish over the previously published versions/.test(output) || (own && /E409|this package is already present/.test(output))) {
log(`${label}: already in ${entry.registry} (refused as a duplicate), skipping`);
continue;
}
Expand Down
77 changes: 77 additions & 0 deletions actions/node/npm-split-publish/test/publish.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,80 @@ describe.skipIf(npmMajor < 11)('publishArgs with real npm 11', () => {
expect(result.status).toBe(0);
});
});

describe('own registry (npm.platforma.bio)', () => {
const OWN = 'https://npm.platforma.bio/';
const BLOCK = entry('@platforma-open/milaboratories.some-block', { registry: OWN });
const BLOCK2 = entry('@platforma-open/milaboratories.some-block.model', { registry: OWN });

it('npmrcFor refers to the OIDC token only through an env var', () => {
expect(npmrcFor([BLOCK], {})).toBe('//npm.platforma.bio/:_authToken=${NPM_PLATFORMA_OIDC_TOKEN}\n');
});

it('mints a fresh token with the registry audience before every upload there, and none for npmjs', async () => {
const audiences: string[] = [];
let n = 0;
const oidcToken = async (audience: string) => { audiences.push(audience); return `jwt-${++n}`; };
const npm = fakeNpm();
const dir = tarballDir([LIB, BLOCK, BLOCK2]);
await publishTarballs({ dir, userconfig: `${dir}.npmrc`, accessPublic: false }, { ...quiet, run: npm.run, oidcToken });
expect(audiences).toEqual(['https://npm.platforma.bio', 'https://npm.platforma.bio']);
const tokens = npm.publishes().map((c) => c.options.env!.NPM_PLATFORMA_OIDC_TOKEN);
expect(tokens).toEqual(['', 'jwt-1', 'jwt-2']);
expect(npm.configs.every((c) => !c.includes('jwt-'))).toBe(true);
});

it("hides GitHub's OIDC variables from npm on uploads to the own registry only", async () => {
const saved = { url: process.env.ACTIONS_ID_TOKEN_REQUEST_URL, token: process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN };
process.env.ACTIONS_ID_TOKEN_REQUEST_URL = 'https://oidc.example';
process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN = 'req-token';
try {
const npm = fakeNpm();
const dir = tarballDir([LIB, BLOCK]);
await publishTarballs(
{ dir, userconfig: `${dir}.npmrc`, accessPublic: false },
{ ...quiet, run: npm.run, oidcToken: async () => 'jwt' },
);
const [toNpmjs, toOwn] = npm.publishes().map((c) => c.options.env!);
expect(toNpmjs.ACTIONS_ID_TOKEN_REQUEST_URL).toBe('https://oidc.example');
expect(toOwn.ACTIONS_ID_TOKEN_REQUEST_URL).toBeUndefined();
expect(toOwn.ACTIONS_ID_TOKEN_REQUEST_TOKEN).toBeUndefined();
} finally {
if (saved.url === undefined) delete process.env.ACTIONS_ID_TOKEN_REQUEST_URL; else process.env.ACTIONS_ID_TOKEN_REQUEST_URL = saved.url;
if (saved.token === undefined) delete process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN; else process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN = saved.token;
}
});

it('fails without an OIDC token source', async () => {
const npm = fakeNpm();
await expect(publish([BLOCK], npm)).rejects.toThrow('no OIDC token source for npm.platforma.bio');
expect(npm.publishes()).toEqual([]);
});

it("treats Verdaccio's E409 duplicate as already published", async () => {
const npm = fakeNpm();
const run = fakeRunner((call: Call) =>
call.args[0] === 'publish'
? { code: 1, stdout: '', stderr: 'npm error code E409\nnpm error 409 Conflict - PUT https://npm.platforma.bio/x - this package is already present' }
: undefined,
npm.run,
);
const dir = tarballDir([BLOCK]);
const published = await publishTarballs({ dir, userconfig: `${dir}.npmrc`, accessPublic: false }, { ...quiet, run, oidcToken: async () => 'jwt' });
expect(published).toEqual([]);
});

it('does NOT treat a 409 from npmjs as already published (fails the release instead)', async () => {
const npm = fakeNpm();
const run = fakeRunner((call: Call) =>
call.args[0] === 'publish'
? { code: 1, stdout: '', stderr: 'npm error code E409\nnpm error 409 Conflict - PUT https://registry.npmjs.org/x - Conflict' }
: undefined,
npm.run,
);
const dir = tarballDir([LIB]);
await expect(
publishTarballs({ dir, userconfig: `${dir}.npmrc`, accessPublic: false }, { ...quiet, run, oidcToken: async () => 'jwt' }),
).rejects.toThrow();
});
});
42 changes: 42 additions & 0 deletions actions/node/own-registry-scopes/action.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: Map our scopes to npm.platforma.bio
author: 'MiLaboratories'
description: |
Adds `@<scope>:registry=https://npm.platforma.bio/` to the workspace .npmrc
for every scope served by our own registry, after create-npmrc wrote it.
One central place, so no repository has to list the registry in its own
npmrc-config. Reads need no token (our scopes are public); uploads go
through publish-tarballs, which authenticates with GitHub OIDC.

Opt-in per repository while repositories move to npm.platforma.bio:
`npm-own-registry-scopes: '@platforma-open'` in the caller's
node-simple-pnpm inputs. Idempotent: an existing line for the same scope is
replaced.

inputs:
scopes:
description: Space-separated scope names, with or without `@`, e.g. '@platforma-open'.
required: true
registry:
description: Registry URL for those scopes.
required: false
default: 'https://npm.platforma.bio/'

runs:
using: composite
steps:
- name: Map scopes to our registry
shell: bash
env:
SCOPES: ${{ inputs.scopes }}
REGISTRY: ${{ inputs.registry }}
run: |
npmrc="${GITHUB_WORKSPACE}/.npmrc"
touch "${npmrc}"
for scope in ${SCOPES}; do
scope="${scope#@}"
case "${scope}" in *[!a-z0-9._-]*|'') echo "::error::bad scope name '${scope}'"; exit 1;; esac
grep -v -F "@${scope}:registry=" "${npmrc}" > "${npmrc}.tmp" || true
mv "${npmrc}.tmp" "${npmrc}"
echo "@${scope}:registry=${REGISTRY}" >> "${npmrc}"
echo "@${scope} -> ${REGISTRY}"
done
14 changes: 14 additions & 0 deletions actions/node/prepare-pnpm/action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ inputs:
required: false
default: ''

own-registry-scopes:
description: |
Space-separated npm scopes to install from and publish to
npm.platforma.bio, e.g. '@platforma-open'. Empty (default): unchanged.
Opt-in while repositories move; see actions/node/own-registry-scopes.
required: false
default: ''

npmrc-config:
description: |
Generates a .npmrc file based on provided configuration.
Expand Down Expand Up @@ -81,6 +89,12 @@ runs:
echo "$line" >> "$npmrc"
fi

- name: Map own-registry scopes to npm.platforma.bio
if: inputs.own-registry-scopes != ''
uses: milaboratory/github-ci/actions/node/own-registry-scopes@v4-beta
with:
scopes: ${{ inputs.own-registry-scopes }}

- name: Install pnpm - ${{ inputs.pnpm-version }}
if: inputs.pnpm-version != ''
uses: pnpm/action-setup@v4
Expand Down
14 changes: 14 additions & 0 deletions actions/node/prepare/action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ inputs:
required: false
default: 'false'

own-registry-scopes:
description: |
Space-separated npm scopes to install from and publish to
npm.platforma.bio, e.g. '@platforma-open'. Empty (default): unchanged.
Opt-in while repositories move; see actions/node/own-registry-scopes.
required: false
default: ''

npmrc-config:
description: |
Generates a .npmrc file based on provided configuration.
Expand All @@ -95,6 +103,12 @@ runs:
with:
npmrcConfig: ${{ inputs.npmrc-config }}

- name: Map own-registry scopes to npm.platforma.bio
if: inputs.own-registry-scopes != ''
uses: milaboratory/github-ci/actions/node/own-registry-scopes@v4-beta
with:
scopes: ${{ inputs.own-registry-scopes }}

- name: Set up cache for a NodeJS/Electron application
uses: milaboratory/github-ci/actions/node/cache@v4-beta
with:
Expand Down
Loading