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
10 changes: 9 additions & 1 deletion .github/workflows/binding-publish-all.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ on:
description: 'Maven: publish without pressing Publish in the Portal, and wait for each package before its dependents'
type: boolean
default: false
setup_done:
description: 'I did the steps in the Publishing setup card. A real run stops on that card until this is ticked'
type: boolean
default: false

permissions:
contents: read
Expand All @@ -47,7 +51,7 @@ concurrency:

jobs:
preflight:
# Lists every selected package with its registry status, and stops a real run that npm cannot accept.
# Lists every selected package with its registry status, and stops a real run that needs registry setup first.
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-24.04
timeout-minutes: 10
Expand All @@ -60,6 +64,7 @@ jobs:
PYTHON: ${{ inputs.python }}
TYPESCRIPT: ${{ inputs.typescript }}
JAVA: ${{ inputs.java }}
SETUP_DONE: ${{ inputs.setup_done }}

steps:
- name: Check out repository
Expand Down Expand Up @@ -96,6 +101,9 @@ jobs:
if [[ "$EXECUTE" == true ]]; then
args+=(--execute)
fi
if [[ "$SETUP_DONE" == true ]]; then
args+=(--setup-done)
fi
python tooling/extension-bindings/ci/publish_all.py preflight "${args[@]}"

publish:
Expand Down
6 changes: 6 additions & 0 deletions tooling/extension-bindings/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,12 @@ It takes package keys (or `all`), a checkbox per language, `dry_run`, and
stops in preflight, before publishing anything, when an npm package would
need its first release.
- **Maven Central and Go** need no setup for a new package.
When an npm or PyPI package needs setup first, the summary starts with the
same publishing setup card that pull requests get, with the values and
commands to use, and a real run stops there before publishing anything. Do
the steps, then run it again with `setup_done` ticked. The registries do not
show a pending PyPI publisher, or an npm trusted publisher that is still
Pending validation, so the workflow cannot see that the steps are done.
2. One job per language with something new starts that registry's own workflow
(`binding-promote.yml`, `binding-publish-pypi.yml`, `binding-publish-npm.yml`,
`binding-publish-maven.yml`) and waits for it. Because each registry is still
Expand Down
44 changes: 43 additions & 1 deletion tooling/extension-bindings/ci/publish-npm.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import yaml

from generation import Target, of_language, select_targets, summarize
from publish_setup import NPM_NO_TRUST, fetch, npm_state, trust_command
from publish_setup import Package as SetupPackage

LANGUAGE = "typescript"
TOOLING = Path("tooling/extension-bindings")
Expand Down Expand Up @@ -117,6 +119,30 @@ def already_published(name: str, version: str) -> bool:
return result.returncode == 0 and result.stdout.strip() == version


def has_trusted_publisher(name: str, version: str) -> bool:
"""Whether the latest version on npm came through trusted publishing.

npm does not show trusted publisher settings publicly, so one added in the
last two days, still Pending validation, looks the same as none.
"""
return npm_state(SetupPackage(f"{name}:typescript", "typescript", name, version), fetch) != NPM_NO_TRUST


def untrusted_warning(names: list[str]) -> str:
return "\n".join(
[
f"⚠️ {', '.join(names)}: the latest version on npm was not published through trusted publishing, "
"so npm refuses this workflow with a 404 unless a trusted publisher was added since. If you added "
"it in the last 2 days and npmjs.com shows Pending validation, this run validates it. Otherwise "
"add it (asks for 2FA) and run again:",
"",
"```sh",
trust_command(names),
"```",
]
)


def npm_status(name: str) -> str:
"""Whether a package is on npm: "published", "missing", or "staged" when only
the placeholder of a staged first release exists, waiting for approval."""
Expand Down Expand Up @@ -153,6 +179,7 @@ def publish(root: Path, targets: list[Target], execute: bool) -> None:
directories[package["name"]] = root / target[1]
build_only = add_unselected_dependencies(root, catalog, packages, directories)
statuses: dict[str, str] = {}
untrusted: list[str] = []
if execute:
# Decide every package before publishing any, so a missing token stops
# the run before it has published only some of them.
Expand All @@ -167,6 +194,13 @@ def publish(root: Path, targets: list[Target], execute: bool) -> None:
f"{', '.join(first_releases)} not on npm yet. A first release is staged with the "
f"stage-only token in the {STAGE_TOKEN} secret, which is not set."
)
untrusted = sorted(
name
for name, status in statuses.items()
if status == "published" and not has_trusted_publisher(name, packages[name]["version"])
)
if untrusted:
summarize(untrusted_warning(untrusted))
published = []
staged = []
with tempfile.TemporaryDirectory(prefix="npm-bindings-") as name:
Expand Down Expand Up @@ -207,7 +241,15 @@ def publish(root: Path, targets: list[Target], execute: bool) -> None:
staged.append(f"{package_name}@{version}")
summarize(f"Staged {package_name}@{version} as its first release.")
else:
run(["npm", "publish", "--access", "public", "--ignore-scripts"], destination)
try:
run(["npm", "publish", "--access", "public", "--ignore-scripts"], destination)
except subprocess.CalledProcessError as error:
if package_name in untrusted:
raise ValueError(
f"npm refused {package_name}: it has no trusted publisher for this workflow. "
"The run summary has the npm trust command."
) from error
raise
published.append(f"{package_name}@{version}")
summarize(f"Published {package_name}@{version}.")
if execute:
Expand Down
45 changes: 44 additions & 1 deletion tooling/extension-bindings/ci/publish_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@
publisher be added to a package that already exists, and PyPI needs a
pending trusted publisher for a project that does not exist yet. A
real run stops before publishing anything when npm would need a first
release, and warns about a PyPI first release.
release, and warns about a PyPI first release. When an npm or PyPI
package needs setup first, such as an npm trust command, the
publishing setup card from publish_setup.py goes above the plan, and
a real run stops there until it is run again with --setup-done.
Registries do not show a pending PyPI publisher or an npm trusted
publisher that is still Pending validation, so only the maintainer
can say the steps are done.

dispatch Starts one of the per-registry publish workflows (binding-promote.yml,
binding-publish-pypi.yml, binding-publish-npm.yml or
Expand Down Expand Up @@ -37,6 +43,7 @@
import yaml

from generation import LANGUAGES, summarize, write_outputs
import publish_setup

TOOLING = Path("tooling/extension-bindings")
WORKFLOWS = {
Expand Down Expand Up @@ -188,6 +195,30 @@ def preflight(
return findings, pending, any(item.blocking for item in findings)


def setup_card(findings: list[Finding], get: publish_setup.Fetch = publish_setup.fetch) -> str | None:
"""The publishing setup card for the npm and PyPI versions this run would publish, when any need setup."""
chosen = [
publish_setup.Package(f"{item.package.key}:{item.package.language}", item.package.language,
item.package.coordinate, item.package.version)
for item in findings
if item.package.language in ("python", "typescript") and item.status != PUBLISHED
]
setup = publish_setup.inspect(chosen, get)
if not any(item.state in publish_setup.ACTION for item in setup):
return None
return publish_setup.card(setup).removeprefix(publish_setup.MARKER + "\n")


def setup_stop(card: str | None, execute: bool, setup_done: bool) -> str | None:
"""Why a real run stops on the setup card, or None when it goes on."""
if card is None or not execute or setup_done:
return None
return (
"⛔ This run stopped before publishing anything, because the packages above need registry setup first. "
"Do the steps in the card, then run this workflow again with the same packages and **setup_done** ticked."
)


def report(findings: list[Finding], execute: bool) -> str:
lines = [
f"## Binding publication plan ({'real run' if execute else 'dry run'})",
Expand Down Expand Up @@ -264,6 +295,7 @@ def main() -> None:
check.add_argument("--packages", default="all", help="comma-separated package keys, or all")
check.add_argument("--languages", default="all", help="comma-separated go, python, typescript, java, or all")
check.add_argument("--execute", action="store_true", help="a real run, which stops on blocking findings")
check.add_argument("--setup-done", action="store_true", help="the steps in the publishing setup card are done")
start = commands.add_parser("dispatch", help="run one language's publish workflow and wait for it")
start.add_argument("--root", type=Path, default=Path.cwd())
start.add_argument("--language", required=True, choices=list(WORKFLOWS))
Expand All @@ -277,6 +309,17 @@ def main() -> None:
try:
if args.command == "preflight":
findings, pending, blocked = preflight(root, args.packages, args.languages, args.execute)
# Setup a maintainer must do first goes above the plan, where it is seen.
card = setup_card(findings)
if card:
summarize(card)
if stop := setup_stop(card, args.execute, args.setup_done):
summarize(stop)
summarize(report(findings, args.execute))
write_outputs(languages="[]", blocked="true")
sys.exit(1)
if card and args.execute:
summarize("setup_done is ticked, so the run goes on with the steps above taken as done.")
summarize(report(findings, args.execute))
if blocked:
summarize("⛔ A real run cannot publish these first releases. Nothing was published.")
Expand Down
6 changes: 3 additions & 3 deletions tooling/extension-bindings/ci/publish_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,11 @@ def card(findings: list[Finding]) -> str:
bold = lambda names: ", ".join(f"**{name}**" for name in names) # noqa: E731
lines = [MARKER, "### Publishing setup", ""]
if not any(state in ACTION for state in by_state):
lines += ["Nothing to set up on npm or PyPI before this pull request is published."]
lines += ["Nothing to set up on npm or PyPI before these packages are published."]
else:
lines += [
"For maintainers. Do these steps before you run the publish workflows for this pull request, "
"or that run fails for the packages below. They need an account with write access to the package.",
"For maintainers. Do these steps before these packages are published, or the publish run fails "
"for them. They need an account with write access to the package.",
]
if names := by_state.get(PYPI_NEW):
lines += [
Expand Down
32 changes: 32 additions & 0 deletions tooling/extension-bindings/ci/test_publish_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import json
import unittest
from datetime import datetime, timedelta, timezone
from pathlib import Path
Expand Down Expand Up @@ -147,5 +148,36 @@ def test_a_run_that_never_starts_times_out(self) -> None:
now=lambda: next(clock), sleep=lambda _: None)


class SetupCardTests(unittest.TestCase):
def finding(self, key: str, language: str, coordinate: str, status: str) -> script.Finding:
return script.Finding(script.Package(key, language, coordinate, "0.2.0"), status)

def test_the_card_lists_setup_for_versions_this_run_publishes(self) -> None:
npm = json.dumps({"versions": {"0.1.0": {"_npmUser": {"name": "someone"}}}, "dist-tags": {"latest": "0.1.0"}})
bodies = {"https://registry.npmjs.org/@example%2Fenv": npm.encode()}
findings = [
self.finding("env", "typescript", "@example/env", script.NEW_VERSION),
self.finding("env", "python", "example-env", script.FIRST_RELEASE),
self.finding("env", "go", "example.com/x/env", script.NEW_VERSION),
self.finding("common", "typescript", "@example/common", script.PUBLISHED),
]
card = script.setup_card(findings, lambda url: bodies.get(url))
assert card is not None
self.assertTrue(card.startswith("### Publishing setup"))
self.assertIn("npm trust github @example/env", card)
self.assertIn("| PyPI Project Name | example-env (one publisher each) |", card)
self.assertNotIn("@example/common", card)

def test_a_real_run_stops_on_the_card_until_setup_is_done(self) -> None:
self.assertIn("setup_done", script.setup_stop("card", execute=True, setup_done=False))
self.assertIsNone(script.setup_stop("card", execute=True, setup_done=True))
self.assertIsNone(script.setup_stop("card", execute=False, setup_done=False))
self.assertIsNone(script.setup_stop(None, execute=True, setup_done=False))

def test_no_card_when_nothing_needs_setup(self) -> None:
findings = [self.finding("env", "typescript", "@example/env", script.FIRST_RELEASE)]
self.assertIsNone(script.setup_card(findings, lambda url: None))


if __name__ == "__main__":
unittest.main()
28 changes: 28 additions & 0 deletions tooling/extension-bindings/ci/test_publish_npm.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ def setUp(self) -> None:
self.package("owner", "@example/owner", {"@example/addon": "^0.1.0"})
self.write("tooling/extension-bindings/emitters/typescript/node_modules/typescript/bin/tsc", "")
self.targets = select_targets(self.catalog, "owner:typescript,addon:typescript")
# Every published package has a trusted publisher unless a test says otherwise.
trusted = patch.object(script, "has_trusted_publisher", return_value=True)
self.trusted = trusted.start()
self.addCleanup(trusted.stop)

def package(self, key: str, name: str, dependencies: dict | None = None, version: str = "0.1.0") -> None:
self.write(
Expand Down Expand Up @@ -191,6 +195,30 @@ def test_a_staged_first_release_waits_for_approval(self) -> None:
self.assertFalse(any(command[:3] == ["npm", "stage", "publish"] for command in commands))
self.assertEqual(sum(command[:2] == ["npm", "publish"] for command in commands), 1)

def test_a_package_without_trusted_publishing_gets_the_trust_command(self) -> None:
self.trusted.return_value = False
summaries = []
with patch.object(script, "summarize", side_effect=summaries.append):
self.run_publication({"@example/addon": "published", "@example/owner": "published"}, None)
warning = next(text for text in summaries if text.startswith("⚠️"))
self.assertIn("for p in @example/addon @example/owner; do", warning)
self.assertIn("Pending validation", warning)

def test_npm_refusing_an_untrusted_package_says_why(self) -> None:
self.trusted.side_effect = lambda name, version: name != "@example/addon"

def run(command, cwd, **options):
if command[:2] == ["npm", "publish"] and str(cwd).endswith("@example/addon"):
raise script.subprocess.CalledProcessError(1, command)
return SimpleNamespace(stdout="11.15.0\n")

with patch.object(script, "run", side_effect=run), patch.object(
script, "already_published", return_value=False
), patch.object(script, "npm_status", return_value="published"), self.assertRaisesRegex(
ValueError, "npm refused @example/addon: it has no trusted publisher"
):
script.publish(self.root, self.targets, True)

def test_npm_status_reads_the_registry(self) -> None:
def view(stdout="", stderr="", code=0):
return SimpleNamespace(returncode=code, stdout=stdout, stderr=stderr)
Expand Down
Loading