Compare commits

...
Author SHA1 Message Date
james.maesandCodex fa6267406f fix: regenerate packed profiles with Linux zlib
Co-Authored-By: Codex <noreply@openai.com>
2026-10-21 08:58:29 -05:00
james.maesandCodex 5518ab27a3 fix: preserve legacy qbit hotfix publication policies
Co-Authored-By: Codex <noreply@openai.com>
2026-10-21 08:58:28 -05:00
james.maesandCodex cc30f599e6 fix(ci): provide a stable verification gate across branches (#59)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 03:12:12 -05:00
james.maesandCodex 05a2a5217a fix: audit rc worker pins independently of native workers (#58)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 02:23:51 -05:00
james.maesandCodex 7d73ac90b6 fix: distinguish missing RC refs from GitHub error bodies (#57)
* fix: distinguish missing rc refs from github error bodies

Co-Authored-By: Codex <noreply@openai.com>

* fix: reject empty ref responses across jq versions

Co-Authored-By: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-10-21 02:15:32 -05:00
19 changed files with 2160 additions and 43 deletions

No files matched your search

+2
View File
@@ -49,6 +49,7 @@ jobs:
python3 tests/test_cli_ci_contract.py
python3 tests/test_maven_ci_contract.py
python3 tests/test_standardize_qbit.py
python3 tests/test_qbit_hotfix_profile.py
python3 tests/test_rollout_version.py
python3 tests/test_validate_standard.py
python3 tests/test_voyage_profile.py
@@ -62,6 +63,7 @@ jobs:
python3 tests/test_rc_finalize_sweep.py
python3 tests/test_rc_guard.py
python3 -m unittest discover -s tests -p test_rc_timeout_recovery.py
python3 -m unittest discover -s tests -p test_rc_ref_lookup.py
python3 -m unittest discover -s tests -p test_generate_rc_workflow.py
python3 -m unittest discover -s tests -p test_audit_estate.py
python3 tests/test_all_profiles.py
+23 -7
View File
@@ -135,7 +135,7 @@ jobs:
echo "merge_sha=$merge_sha"
echo "merged_at=$merged_at"
} >> "$GITHUB_OUTPUT"
echo "Pushed $branch; CircleCI publish_release_candidate cuts the RC." >> "$GITHUB_STEP_SUMMARY"
echo "Pushed $branch; the CircleCI publisher cuts the RC." >> "$GITHUB_STEP_SUMMARY"
echo "Release line: $branch. Waiting without a runner for qbit-rc-published." >> "$GITHUB_STEP_SUMMARY"
- name: Persist trusted release intent
if: steps.merge.outputs.merge_sha != ''
@@ -174,6 +174,22 @@ jobs:
fi
workdir=$(mktemp -d)
trap 'rm -rf "$workdir"' EXIT
# BEGIN RC REF LOOKUP
read_ref() {
local body sha
if body=$(gh api "repos/$REPO/git/ref/$1" 2>"$workdir/ref-error"); then
sha=$(jq -er '.object.sha' <<< "$body") || return 1
[[ "$sha" =~ ^[0-9a-f]{40}$ ]] || return 1
printf '%s\n' "$sha"
elif jq -se 'length == 1 and .[0].status == "404"' >/dev/null 2>&1 <<< "$body"; then
# gh prints HTTP error JSON on stdout even when --jq was requested.
return 0
else
cat "$workdir/ref-error" >&2
return 1
fi
}
# END RC REF LOOKUP
# The evaluator is inline so a pinned reusable workflow cannot fetch mutable code.
cat > "$workdir/rc_guard.py" <<'PY'
# BEGIN RC GUARD
@@ -187,7 +203,7 @@ jobs:
raise ReleaseFailure("Status response does not identify the exact release merge")
# Circle's workflow Check Run is stable even when job statuses receive -1/-2 suffixes.
publishers = [x for x in status.get("check_runs", [])
if x.get("name") == "publish_release_candidate" and x.get("app", {}).get("id") == 18001]
if x.get("name") in ("publish_release_candidate", "verify") and x.get("app", {}).get("id") == 18001]
if not publishers:
return ""
publisher = max(publishers, key=lambda x: x["id"])
@@ -249,10 +265,10 @@ jobs:
job.get('branch'), str(job.get('build_num'))) != (repo, merge, branch, build):
raise ReleaseFailure('Timeout job does not identify the exact cut')
workflow = job.get('workflows', {})
if workflow.get('workflow_name') != 'publish_release_candidate' or workflow.get('job_name') != 'qqq-orb/mvn_publish':
if workflow.get('workflow_name') not in ('publish_release_candidate', 'verify') or workflow.get('job_name') != 'qqq-orb/mvn_publish':
raise ReleaseFailure('Unexpected Circle publication workflow/job')
if (publisher.get('head_sha') != merge or publisher.get('app', {}).get('id') != 18001
or publisher.get('name') != 'publish_release_candidate'
or publisher.get('name') != workflow.get('workflow_name')
or publisher.get('status') != 'completed' or publisher.get('conclusion') != 'failure'):
raise ReleaseFailure('Recovery requires the failed exact Circle publisher')
from urllib.parse import urlsplit
@@ -319,7 +335,7 @@ jobs:
directory = pathlib.Path(directory)
status = json.loads((directory / 'status.json').read_text())
intent = json.loads((directory / 'intent.json').read_text())
publishers = [p for p in status['check_runs'] if p.get('name') == 'publish_release_candidate' and p.get('app', {}).get('id') == 18001]
publishers = [p for p in status['check_runs'] if p.get('name') in ('publish_release_candidate', 'verify') and p.get('app', {}).get('id') == 18001]
if status.get('sha') != merge or not publishers:
raise ReleaseFailure('Exact publisher evidence missing')
class NoRedirect(urllib.request.HTTPRedirectHandler):
@@ -442,7 +458,7 @@ jobs:
PY
MERGED_AT=$(jq -er .merged_at "$workdir/intent.json")
lock=automation/qbit-rc-pending
current_lock=$(gh api "repos/$REPO/git/ref/heads/$lock" -q .object.sha 2>/dev/null || true)
current_lock=$(read_ref "heads/$lock")
# A duplicate after completed finalization is safe only after tag/source checks below.
[[ -z "$current_lock" || "$current_lock" == "$MERGE_SHA" ]] || { echo "::error::Different release owns pending lock"; exit 1; }
gh api "repos/$REPO/commits/$MERGE_SHA/check-runs?filter=latest&per_page=100" \
@@ -520,7 +536,7 @@ jobs:
python3 "$workdir/rc_guard.py" central "$version" "$artifact" "$workdir/central.pom" "$last_modified" "$MERGED_AT"
# 3. Signed annotated tag on the exact bump; duplicate runs must not accept a different tag.
existing=$(gh api "repos/$REPO/git/ref/tags/v$version" --jq '.object.sha' 2>/dev/null || true)
existing=$(read_ref "tags/v$version")
target=""; release_exists=false
if [[ -n "$existing" ]]; then
target=$(gh api "repos/$REPO/git/tags/$existing" --jq '.object.sha')
+1
View File
@@ -58,6 +58,7 @@ test-pipelines: pack
bash tests/test_cli_ci_behavior.sh
python3 tests/test_cli_ci_contract.py
python3 tests/test_standardize_qbit.py
python3 tests/test_qbit_hotfix_profile.py
python3 tests/test_rollout_version.py
python3 tests/test_validate_standard.py
python3 tests/test_voyage_profile.py
+18 -6
View File
@@ -61,11 +61,23 @@ parser is pinned to PyYAML 6.0.3 and uses its safe loader.
| Event | Workflow | Job contract |
| --- | --- | --- |
| develop | publish_snapshot | existing mvn_publish, snapshot |
| release/* | publish_release_candidate | existing mvn_publish, release_candidate |
| vX.Y.Z tag resolving to the checkout | publish_release | existing mvn_publish, release |
| main, feature/*, hotfix/*, other/unknown branch | test_only | existing mvn_test_only |
| Disabled publication or unrecognized/unproven tag | test_only | full verification, no publication |
| develop | verify | existing mvn_publish, snapshot |
| release/* | verify | existing mvn_publish, release_candidate |
| vX.Y.Z tag resolving to the checkout | verify | existing mvn_publish, release |
| main, feature/*, hotfix/*, other/unknown branch | verify | existing mvn_test_only |
| Disabled publication or unrecognized/unproven tag | verify | full verification, no publication |
Generated `qbit`, `core`, `frontend-core`, and `frontend-material` pipelines use
the stable workflow name `verify`. All selected jobs, dependencies and filters
remain intact; this adds no executor or duplicate build. Other profiles retain
their existing workflow names and native checks.
When upgrading from legacy workflow names, upgrade the immutable RC worker pin
alongside the orb so finalization recognizes both names. Confirm the CircleCI
app's successful `verify` check on the exact migration commit before replacing
legacy required contexts. Require `setup` and `verify` on managed branches,
preserving other required checks and controls. Human approval is not required;
automated checks authorize the migration.
The pipeline SHA must match the checkout when Circle supplies it. A tagged release
must resolve to that checkout; missing local tags are fetched individually. A main
@@ -182,7 +194,7 @@ manifest validation already ran in setup. It adds no new security scanner and
makes no security-scanning claim. Keep docs-only disabled if those paths are build
inputs or packaged application content.
The light route keeps workflow `test_only` and names its job
The light route keeps workflow `verify` and names its job
`qqq-orb/mvn_test_only`. Verify actual CircleCI/GitHub status contexts on the canary
before changing any protection rule; workflow/job identity alone is not proof of
the hosted context name. Current protections must not be removed speculatively.
+13 -1
View File
@@ -8,11 +8,16 @@ recognized contracts:
|---|---|---|
| `release_on_main` | boolean, default false | Main pushes select the existing release job when release publishing is enabled. |
| `release_tag_policy` | `stable`, `v-prefix`, `none` | Stable `v1.2.3`, the existing broad `/v.*/` contract, or no tags. |
| `test_branch_policy` | `all`, `non-release`, `non-release-no-integration`, `feature`, `non-release-no-main` | Selects one of the five audited test branch exclusions. |
| `test_branch_policy` | `all`, `non-release`, `non-release-no-integration`, `feature`, `non-release-no-main`, `non-release-no-hotfix`, `non-release-no-main-hotfix`, `feature-no-hotfix` | Selects an audited test branch exclusion. |
| `publish.hotfix` | boolean, default false | Runs the existing Maven hotfix publisher for nonempty `hotfix/*` branch events only when explicitly enabled. |
`feature` preserves the original exclusion of develop, main, release branches,
and integration-prefixed branches; it is not a new feature-prefix-only rule.
All policies continue to exclude the RC coordination lock branch.
The three hotfix exclusions preserve the corresponding legacy policies while
the single shared publisher handles hotfix events. Existing manifests do not
enable hotfix publication implicitly; migration enables it only when the source
configuration contains the recognized hotfix publisher and branch filter.
No consumer-supplied regex, command, job, or arbitrary branch-publication rule
is accepted.
@@ -39,3 +44,10 @@ Focused tests cover the immutable inventory, unknown-filter rejection, canonical
caller agreement, main opt-in, broad/stable tag selection, HEAD provenance,
publication opt-out and test exclusions. The packed generator suite also exercises
main, broad RC-shaped tags, and excluded integration branches.
Fifteen additional main-branch fixtures exercise 195 branch/tag cases,
checking both test and publication selection. Source and packed generator tests
also verify hotfix opt-in, its boolean validation, and unchanged main behavior.
CMS's original YAML is retained with its immutable source SHA: its unquoted
stable-tag regex is invalid YAML. The fixture repairs only that quoting. Both
audited spellings of the stable regex map to the same ASCII-digit tag policy;
arbitrary regexes remain rejected.
+12 -1
View File
@@ -26,7 +26,8 @@ https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-t
- Finalization retrieves the unique unexpired intent artifact and verifies its
originating successful `release-rc.yml` run, repository, trigger and attempt.
Callback fields must match that immutable intent.
- The exact merge SHA must have a successful `publish_release_candidate` Check Run
- The exact merge SHA must have a successful `verify` (or legacy
`publish_release_candidate`) Check Run
from CircleCI app ID `18001`; unrelated job statuses cannot authorize release.
Terminal publisher failure stops finalization immediately. Pending/absent publication cannot authorize a tag.
The RC bump must have exactly that one parent and the release branch must still
@@ -107,3 +108,13 @@ is gone, the completed release needs no recovery dispatch. Ordinary callbacks an
scheduled reconciliation retain the requirement for a successful Circle publisher.
Central status API: https://central.sonatype.org/publish/publish-portal-api/
### Auditing independent worker revisions
The estate audit accepts `rc_worker_sha` in a profile or repository policy. For
example, set `profiles.qbit.rc_worker_sha` to the approved immutable RC worker
commit and keep `--worker-sha` at the approved revision for unchanged native
workers. The audit still compares every caller to its exact canonical template
and rejects mutable or mismatched pins. This avoids a fleet-wide native caller
update when only RC release behavior changes. Required-check policy is separate;
omitting it continues to report enforcement as unknown.
+19 -4
View File
@@ -110,6 +110,8 @@ def load_manifest(path, setup_version):
publish_keys = ("release",)
if profile in ("qbit", "core"):
publish_keys += ("asciidoc",)
if profile == "qbit":
publish_keys += ("hotfix",)
if profile not in ("qbit", "cli", "all", "app-starter", "voyage", "frontend-next"):
publish_keys += ("feature", "hotfix")
publishing = mapping(data.get("publish", {}), publish_keys, "publish")
@@ -126,7 +128,8 @@ def load_manifest(path, setup_version):
if tag_policy not in ("stable", "v-prefix", "none"):
raise ManifestError("Unsupported QBit release tag policy")
test_policy = data.get("test_branch_policy", "all")
if test_policy not in ("all", "non-release", "non-release-no-integration", "feature", "non-release-no-main"):
if test_policy not in ("all", "non-release", "non-release-no-integration", "feature", "non-release-no-main",
"non-release-no-hotfix", "non-release-no-main-hotfix", "feature-no-hotfix"):
raise ManifestError("Unsupported QBit test branch policy")
return {"profile": profile, "orb_version": version, "default_branch": default_branch,
"java_version": java, "node_version": node, "browsers": boolean(data, "browsers", True),
@@ -136,7 +139,8 @@ def load_manifest(path, setup_version):
"release_tag_policy": tag_policy, "test_branch_policy": test_policy,
"docs_only": boolean(data, "docs_only", False),
"publish_context": publish_context,
"publish": {key: boolean(publishing, key, key != "asciidoc" and profile not in ("cli", "all"))
"publish": {key: boolean(publishing, key, key != "asciidoc" and profile not in ("cli", "all")
and not (profile == "qbit" and key == "hotfix"))
for key in publish_keys}}
@@ -173,7 +177,7 @@ def proven_docs_only(config, branch, tag):
def event_kind(branch, tag, release_on_main=False, release_tag_policy="stable"):
if tag:
if release_tag_policy == "none" or not re.fullmatch(r"v.*" if release_tag_policy == "v-prefix" else r"v\d+\.\d+\.\d+", tag):
if release_tag_policy == "none" or not re.fullmatch(r"v.*" if release_tag_policy == "v-prefix" else r"v\d+\.\d+\.\d+", tag, flags=re.ASCII):
return "test"
tagged = git("rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}")
if not tagged and git("fetch", "--no-tags", "origin", f"refs/tags/{tag}:refs/tags/{tag}") is not None:
@@ -191,6 +195,8 @@ def event_kind(branch, tag, release_on_main=False, release_tag_policy="stable"):
def qbit_template(config, branch, tag):
"""Profile-owned template; add future profiles as reviewed renderers, not raw YAML."""
kind = event_kind(branch, tag, config.get("release_on_main", False), config.get("release_tag_policy", "stable"))
if not tag and re.fullmatch(r"hotfix/.+", branch) and config["publish"].get("hotfix", False):
kind = "hotfix"
if kind != "test" and not config["publish"][kind]:
kind = "test"
workflow = "test_only" if kind == "test" else "publish_" + kind
@@ -201,7 +207,10 @@ def qbit_template(config, branch, tag):
ignores = {"all": None, "non-release": "/(develop|release/.*)/",
"non-release-no-integration": "/(develop|release/.*|integration.*)/",
"feature": "/(develop|main|release/.*|integration.*)/",
"non-release-no-main": "/(develop|main|release/.*)/"}
"non-release-no-main": "/(develop|main|release/.*)/",
"non-release-no-hotfix": "/(develop|release/.*|hotfix/.*)/",
"non-release-no-main-hotfix": "/(develop|main|release/.*|hotfix/.*)/",
"feature-no-hotfix": "/(develop|main|release/.*|hotfix/.*|integration.*)/"}
ignored = ignores[config.get("test_branch_policy", "all")]
if ignored:
filters["branches"]["ignore"] = ["automation/qbit-rc-pending", ignored]
@@ -441,6 +450,12 @@ def main():
if expected and (not re.fullmatch(r"[0-9a-fA-F]{40}", expected) or git("rev-parse", "HEAD") != (expected + "\n").encode()):
raise ManifestError("Checkout does not match the pipeline commit")
output = PROFILE_TEMPLATES[config["profile"]](config, os.environ.get("CIRCLE_BRANCH", ""), os.environ.get("CIRCLE_TAG", ""))
if config["profile"] in ("qbit", "core", "frontend-core", "frontend-material"):
# One whole-workflow check follows the same commit from feature to release.
# Keep every selected job, dependency and filter; add no runner or duplicate build.
if len(output["workflows"]) != 1:
raise ManifestError("Stable verification requires exactly one selected workflow")
output["workflows"] = {"verify": next(iter(output["workflows"].values()))}
parameters = continuation_parameters(config["profile"])
if config["profile"] == "core":
output["parameters"] = copy.deepcopy(CORE_TEMPLATE["parameters"])
+19 -4
View File
@@ -110,6 +110,8 @@ def load_manifest(path, setup_version):
publish_keys = ("release",)
if profile in ("qbit", "core"):
publish_keys += ("asciidoc",)
if profile == "qbit":
publish_keys += ("hotfix",)
if profile not in ("qbit", "cli", "all", "app-starter", "voyage", "frontend-next"):
publish_keys += ("feature", "hotfix")
publishing = mapping(data.get("publish", {}), publish_keys, "publish")
@@ -126,7 +128,8 @@ def load_manifest(path, setup_version):
if tag_policy not in ("stable", "v-prefix", "none"):
raise ManifestError("Unsupported QBit release tag policy")
test_policy = data.get("test_branch_policy", "all")
if test_policy not in ("all", "non-release", "non-release-no-integration", "feature", "non-release-no-main"):
if test_policy not in ("all", "non-release", "non-release-no-integration", "feature", "non-release-no-main",
"non-release-no-hotfix", "non-release-no-main-hotfix", "feature-no-hotfix"):
raise ManifestError("Unsupported QBit test branch policy")
return {"profile": profile, "orb_version": version, "default_branch": default_branch,
"java_version": java, "node_version": node, "browsers": boolean(data, "browsers", True),
@@ -136,7 +139,8 @@ def load_manifest(path, setup_version):
"release_tag_policy": tag_policy, "test_branch_policy": test_policy,
"docs_only": boolean(data, "docs_only", False),
"publish_context": publish_context,
"publish": {key: boolean(publishing, key, key != "asciidoc" and profile not in ("cli", "all"))
"publish": {key: boolean(publishing, key, key != "asciidoc" and profile not in ("cli", "all")
and not (profile == "qbit" and key == "hotfix"))
for key in publish_keys}}
@@ -173,7 +177,7 @@ def proven_docs_only(config, branch, tag):
def event_kind(branch, tag, release_on_main=False, release_tag_policy="stable"):
if tag:
if release_tag_policy == "none" or not re.fullmatch(r"v.*" if release_tag_policy == "v-prefix" else r"v\d+\.\d+\.\d+", tag):
if release_tag_policy == "none" or not re.fullmatch(r"v.*" if release_tag_policy == "v-prefix" else r"v\d+\.\d+\.\d+", tag, flags=re.ASCII):
return "test"
tagged = git("rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}")
if not tagged and git("fetch", "--no-tags", "origin", f"refs/tags/{tag}:refs/tags/{tag}") is not None:
@@ -191,6 +195,8 @@ def event_kind(branch, tag, release_on_main=False, release_tag_policy="stable"):
def qbit_template(config, branch, tag):
"""Profile-owned template; add future profiles as reviewed renderers, not raw YAML."""
kind = event_kind(branch, tag, config.get("release_on_main", False), config.get("release_tag_policy", "stable"))
if not tag and re.fullmatch(r"hotfix/.+", branch) and config["publish"].get("hotfix", False):
kind = "hotfix"
if kind != "test" and not config["publish"][kind]:
kind = "test"
workflow = "test_only" if kind == "test" else "publish_" + kind
@@ -201,7 +207,10 @@ def qbit_template(config, branch, tag):
ignores = {"all": None, "non-release": "/(develop|release/.*)/",
"non-release-no-integration": "/(develop|release/.*|integration.*)/",
"feature": "/(develop|main|release/.*|integration.*)/",
"non-release-no-main": "/(develop|main|release/.*)/"}
"non-release-no-main": "/(develop|main|release/.*)/",
"non-release-no-hotfix": "/(develop|release/.*|hotfix/.*)/",
"non-release-no-main-hotfix": "/(develop|main|release/.*|hotfix/.*)/",
"feature-no-hotfix": "/(develop|main|release/.*|hotfix/.*|integration.*)/"}
ignored = ignores[config.get("test_branch_policy", "all")]
if ignored:
filters["branches"]["ignore"] = ["automation/qbit-rc-pending", ignored]
@@ -441,6 +450,12 @@ def main():
if expected and (not re.fullmatch(r"[0-9a-fA-F]{40}", expected) or git("rev-parse", "HEAD") != (expected + "\n").encode()):
raise ManifestError("Checkout does not match the pipeline commit")
output = PROFILE_TEMPLATES[config["profile"]](config, os.environ.get("CIRCLE_BRANCH", ""), os.environ.get("CIRCLE_TAG", ""))
if config["profile"] in ("qbit", "core", "frontend-core", "frontend-material"):
# One whole-workflow check follows the same commit from feature to release.
# Keep every selected job, dependency and filter; add no runner or duplicate build.
if len(output["workflows"]) != 1:
raise ManifestError("Stable verification requires exactly one selected workflow")
output["workflows"] = {"verify": next(iter(output["workflows"].values()))}
parameters = continuation_parameters(config["profile"])
if config["profile"] == "core":
output["parameters"] = copy.deepcopy(CORE_TEMPLATE["parameters"])
+1 -1
View File
@@ -116,7 +116,7 @@ def reconcile(api, repo):
validate_run(run, intent, repo, merge, run_id)
checks = api.request(prefix + 'commits/' + merge + '/check-runs?filter=latest&per_page=100')
publishers = [c for c in checks.get('check_runs', [])
if c.get('name') == 'publish_release_candidate' and c.get('app', {}).get('id') == 18001]
if c.get('name') in ('publish_release_candidate', 'verify') and c.get('app', {}).get('id') == 18001]
if not publishers:
return 'publisher-running'
publisher = max(publishers, key=lambda c: c['id'])
File diff suppressed because it is too large. Load diff
+19
View File
@@ -74,6 +74,25 @@ class AuditTests(unittest.TestCase):
report = audit.audit(entry, Snapshot({'.qqq-ci.yml': audit.generator.yaml.safe_dump(manifest)}), VERSION, SHA, POLICY)
self.assertIn('missing_rc_bridge', [f['code'] for f in report['findings']])
def test_rc_pin_policy_does_not_force_unchanged_auxiliary_worker_updates(self):
entry = dict(ENTRY, name='qbit-authentik', nameWithOwner='QRun-IO/qbit-authentik')
rc_sha = 'b' * 40
definition = audit.auxiliary.BRIDGES['qbit-schema-drift']
manifest = {'profile': 'qbit', 'orb_version': VERSION, 'default_branch': 'develop', 'release_completion': True}
files = {audit.rc_worker.CALLER_PATH: audit.rc_worker.generate(rc_sha),
definition['path']: audit.generator.yaml.safe_dump(audit.auxiliary.canonical('qbit-schema-drift', SHA), sort_keys=False),
'.qqq-ci.yml': audit.generator.yaml.safe_dump(manifest),
'.circleci/config.yml': audit.generator.yaml.safe_dump(audit.standard.canonical_caller('qbit', VERSION))}
policy = dict(POLICY, rc_worker_sha=rc_sha)
self.assertEqual('pass', audit.audit(entry, Snapshot(files), VERSION, SHA, policy)['status'])
for pin in (SHA, 'main', ''):
with self.subTest(pin=pin):
report = audit.audit(entry, Snapshot(files), VERSION, SHA, dict(POLICY, rc_worker_sha=pin))
self.assertTrue(report['findings'])
files[definition['path']] = files[definition['path']].replace(SHA, rc_sha)
report = audit.audit(entry, Snapshot(files), VERSION, SHA, policy)
self.assertIn('native_maintenance_bridge_drift', [f['code'] for f in report['findings']])
def test_qbit_rc_bridge_missing_drift_pin_and_duplicate(self):
entry = dict(ENTRY, name='qbit-test', nameWithOwner='QRun-IO/qbit-test')
path = audit.rc_worker.CALLER_PATH
+36 -13
View File
@@ -192,10 +192,12 @@ class PipelineTests(unittest.TestCase):
return result
def assert_full(self, result, workflow="test_only"):
self.assertEqual(list(result["workflows"]), [workflow])
self.assertEqual(list(result["workflows"]), ["verify"])
self.assertNotIn("docs_only", result.get("jobs", {}))
job, options = next(iter(result["workflows"][workflow]["jobs"][0].items()))
job, options = next(iter(result["workflows"]["verify"]["jobs"][0].items()))
self.assertEqual(job, "qqq-orb/mvn_test_only" if workflow == "test_only" else "qqq-orb/mvn_publish")
if workflow != "test_only":
self.assertEqual(options["branch_type"], workflow.removeprefix("publish_"))
self.assertEqual(options["context"], ["qqq-maven-registry-credentials"])
self.assertFalse(options["compile_before_verify"])
return options
@@ -225,6 +227,24 @@ class PipelineTests(unittest.TestCase):
self.write_manifest(publish={"asciidoc": True})
self.assertTrue(self.assert_full(self.render(CIRCLE_BRANCH="develop"), "publish_snapshot")["publish_asciidoc"])
def test_qbit_hotfix_is_opt_in_in_source_and_packed_generator(self):
for packed in ([False, True] if PACKED else [False]):
self.write_manifest()
self.assert_full(self.render(packed=packed, CIRCLE_BRANCH="hotfix/1.2.3"))
self.write_manifest(publish={"hotfix": True})
options = self.assert_full(self.render(packed=packed, CIRCLE_BRANCH="hotfix/1.2.3"), "publish_hotfix")
self.assertNotIn("notify_rc_published", options)
self.assert_full(self.render(packed=packed, CIRCLE_BRANCH="main"))
self.assert_full(self.render(packed=packed, CIRCLE_BRANCH="hotfix/"))
self.write_manifest(publish={"hotfix": "true"})
self.render(packed=packed, CIRCLE_BRANCH="hotfix/1.2.3", ok=False)
def test_stable_tags_require_ascii_digits_in_source_and_packed_generator(self):
tag = "v\u0661.\u0662.\u0663"
self.git("tag", tag)
for packed in ([False, True] if PACKED else [False]):
self.assert_full(self.render(packed=packed, CIRCLE_TAG=tag))
def test_qbit_rc_completion_is_explicit_and_rc_only(self):
options = self.assert_full(self.render(CIRCLE_BRANCH="release/1"), "publish_release_candidate")
self.assertFalse(options["notify_rc_published"])
@@ -298,8 +318,8 @@ class PipelineTests(unittest.TestCase):
self.change_docs()
for packed in ([False, True] if PACKED else [False]):
result = self.render(packed=packed)
self.assertEqual(list(result["workflows"]), ["test_only"])
options = result["workflows"]["test_only"]["jobs"][0]["docs_only"]
self.assertEqual(list(result["workflows"]), ["verify"])
options = result["workflows"]["verify"]["jobs"][0]["docs_only"]
self.assertEqual(options["name"], "qqq-orb/mvn_test_only")
self.assertIn("git diff --check", result["jobs"]["docs_only"]["steps"][1]["run"]["command"])
(self.repo / "App.java").write_text("changed\n", encoding="utf-8")
@@ -360,8 +380,8 @@ class PipelineTests(unittest.TestCase):
for branch, tag, workflow in events:
with self.subTest(workflow=workflow):
result = self.render(CIRCLE_BRANCH=branch, CIRCLE_TAG=tag)
self.assertEqual(list(result["workflows"]), [workflow])
actual = result["workflows"][workflow]["jobs"]
self.assertEqual(list(result["workflows"]), ["verify"])
actual = result["workflows"]["verify"]["jobs"]
expected = baseline["workflows"][workflow]["jobs"]
self.assertEqual(len(actual), len(expected))
for before, after in zip(expected, actual):
@@ -422,8 +442,8 @@ class PipelineTests(unittest.TestCase):
with self.subTest(branch=branch, enabled=enabled):
result = self.render(CIRCLE_BRANCH=branch, QQQ_CI_RUN_PLAYWRIGHT=str(enabled).lower())
workflow = base + ("_with_playwright" if enabled else "")
self.assertEqual(list(result["workflows"]), [workflow])
jobs = result["workflows"][workflow]["jobs"]
self.assertEqual(list(result["workflows"]), ["verify"])
jobs = result["workflows"]["verify"]["jobs"]
self.assertEqual(len(jobs), 2 if enabled else 1)
maven = [j for j in jobs if next(iter(j)).startswith("qqq-orb/mvn_frontend_")]
self.assertEqual(len(maven), 1)
@@ -454,8 +474,10 @@ class PipelineTests(unittest.TestCase):
("hotfix/fix", "", "publish_hotfix_release"), ("", "publish-fixture", "publish_feature"),
("", "v1.0.0", "publish_release")]:
result = self.render(CIRCLE_BRANCH=branch, CIRCLE_TAG=tag)
self.assertEqual(list(result["workflows"]), [workflow])
options = next(iter(result["workflows"][workflow]["jobs"][0].values()))
self.assertEqual(list(result["workflows"]), ["verify"])
options = next(iter(result["workflows"]["verify"]["jobs"][0].values()))
expected_kind = {"publish_hotfix_release": "hotfix"}.get(workflow, workflow.removeprefix("publish_"))
self.assertEqual(options["branch_type"], expected_kind)
if profile == "frontend-core":
self.assertTrue(options["npm_trusted_publishing"])
self.assertEqual(options["node_version"], "24.21")
@@ -463,9 +485,9 @@ class PipelineTests(unittest.TestCase):
else:
self.assertEqual(options["context"], ["qqq-maven-registry-credentials"])
main = self.render(CIRCLE_BRANCH="main")
self.assertEqual(list(main["workflows"]), ["publish_release" if profile == "frontend-core" else "test_only"])
self.assertEqual(list(main["workflows"]), ["verify"])
rc_tag = self.render(CIRCLE_BRANCH="", CIRCLE_TAG="v1.0.0-RC.1")
self.assertEqual(list(rc_tag["workflows"]), ["publish_release" if profile == "frontend-core" else "test_only"])
self.assertEqual(list(rc_tag["workflows"]), ["verify"])
def test_profile_specific_options_rejected(self):
for profile, options in [("qbit", {"node_version": "22"}), ("frontend-core", {"browsers": False}),
@@ -532,7 +554,8 @@ class PipelineTests(unittest.TestCase):
{"CIRCLE_BRANCH": "integration-example"}):
result = self.render(**environment)
if environment.get("CIRCLE_BRANCH") != "integration-example":
self.assertIn("publish_release", result["workflows"])
self.assertEqual(list(result["workflows"]), ["verify"])
self.assertEqual(result["workflows"]["verify"]["jobs"][0]["qqq-orb/mvn_publish"]["branch_type"], "release")
if PACKED:
self.assertEqual(result, self.render(packed=True, **environment))
+73
View File
@@ -0,0 +1,73 @@
"""Preserve the audited main-branch hotfix contracts in the shared profile."""
import importlib.util
import json
from pathlib import Path
import re
import unittest
from unittest import mock
import yaml
ROOT = Path(__file__).resolve().parents[1]
def load(name, path):
spec = importlib.util.spec_from_file_location(name, ROOT / path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
migration = load('migration', 'tools/standardize_qbit.py')
pipeline = load('pipeline', 'src/scripts/generate_pipeline.py')
def selects(filters, branch, tag):
selector = filters.get('tags' if tag else 'branches', {})
if tag and not selector:
return False
def matches(patterns):
patterns = patterns if isinstance(patterns, list) else [patterns]
return any(re.fullmatch(p[1:-1], tag or branch, flags=re.ASCII) is not None if p.startswith('/') and p.endswith('/') else p == (tag or branch) for p in patterns)
return ('only' not in selector or matches(selector['only'])) and ('ignore' not in selector or not matches(selector['ignore']))
class HotfixMigrationTests(unittest.TestCase):
def test_audited_main_job_selection_is_preserved(self):
fixtures = json.loads((ROOT/'tests/fixtures/qbit-main-hotfix-policies.json').read_text())
for fixture in fixtures:
manifest = migration.infer_manifest(fixture['config'], '0.7.13', 'develop')
with mock.patch.object(Path, 'read_text', return_value=yaml.safe_dump(manifest)):
config = pipeline.load_manifest('unused', '0.7.13')
cases = [(branch, '') for branch in ('main','develop','feature/a','release/1','hotfix/1.2.3','integration-test','staging')]
cases += [('', tag) for tag in ('v1.2.3','v1.2.3-RC.1','vanything','publish1','invalid','v\u0661.\u0662.\u0663')]
for branch, tag in cases:
with self.subTest(repository=fixture['repository'], branch=branch, tag=tag):
expected = sorted((job, options.get('branch_type')) for workflow in fixture['config']['workflows'].values() for entry in workflow['jobs'] for job, options in entry.items() if selects(options.get('filters', {}), branch, tag))
with mock.patch.object(pipeline, 'git', return_value=b'verified-head\n'):
generated = pipeline.qbit_template(config, branch, tag)
actual = sorted((job, options.get('branch_type')) for workflow in generated['workflows'].values() for entry in workflow['jobs'] for job, options in entry.items() if selects(options.get('filters', {}), branch, tag))
# The canonical setup's tag filter prevents non-release tag runs.
caller = migration.canonical_caller('0.7.13', manifest['release_tag_policy'])
setup = caller['workflows']['setup']['jobs'][0]['qqq-orb/generate_pipeline']
if not selects(setup['filters'], branch, tag): actual = []
self.assertEqual(actual, expected)
def test_cms_repair_only_quotes_the_existing_tag_pattern(self):
fixtures = json.loads((ROOT/'tests/fixtures/qbit-main-hotfix-policies.json').read_text())
fixture = next(row for row in fixtures if row['repository'] == 'QRun-IO/qbit-cms')
with self.assertRaises(yaml.YAMLError):
yaml.safe_load(fixture['original_yaml'])
repaired = fixture['original_yaml'].replace(r'only: [/^v[0-9]+\.[0-9]+\.[0-9]+$/]',
r"only: ['/^v[0-9]+\.[0-9]+\.[0-9]+$/']")
self.assertEqual(yaml.safe_load(repaired), fixture['config'])
def test_stable_tag_selection_uses_ascii_digits(self):
with mock.patch.object(pipeline, 'git', return_value=b'verified-head\n'):
self.assertEqual(pipeline.event_kind('', 'v\u0661.\u0662.\u0663'), 'test')
self.assertEqual(pipeline.event_kind('', 'v1.2.3'), 'release')
def test_existing_manifest_does_not_enable_hotfix_publication(self):
raw = 'profile: qbit\norb_version: 0.7.13\ndefault_branch: develop\n'
with mock.patch.object(Path, 'read_text', return_value=raw):
config = pipeline.load_manifest('unused','0.7.13')
self.assertFalse(config['publish'].get('hotfix', False))
result = pipeline.qbit_template(config, 'hotfix/1.2.3', '')
self.assertIn('qqq-orb/mvn_test_only', result['workflows']['test_only']['jobs'][0])
if __name__ == '__main__': unittest.main()
+11
View File
@@ -58,6 +58,17 @@ class FixtureAPI:
class SweepTests(unittest.TestCase):
def test_stable_gate_and_mixed_name_latest_failure(self):
api = FixtureAPI()
api.status['check_runs'][0]['name'] = 'verify'
self.assertEqual('dispatched', sweep.reconcile(api, REPO))
api.sent.clear()
api.status['check_runs'].append(dict(api.status['check_runs'][0],
id=10, name='publish_release_candidate', conclusion='failure'))
with self.assertRaises(sweep.InvalidIntent):
sweep.reconcile(api, REPO)
self.assertEqual([], api.sent)
def test_idle_never_dispatches_or_reads_artifacts(self):
api = FixtureAPI(); api.lock = None
self.assertEqual('idle', sweep.reconcile(api, REPO))
+11
View File
@@ -23,6 +23,17 @@ def bump(parent=SHA, version='1.2.3-RC.4'):
class ReleaseGuardTests(unittest.TestCase):
def test_stable_workflow_preserves_exact_source_and_latest_attempt_checks(self):
result = status()
result['check_runs'][0]['name'] = 'verify'
self.assertEqual('1.2.3-RC.4', evaluate(SHA, result, bump()))
result['check_runs'].append(dict(result['check_runs'][0], id=10, conclusion='failure'))
with self.assertRaisesRegex(Failure, 'CircleCI failed'):
evaluate(SHA, result, bump())
result['check_runs'] = [dict(result['check_runs'][0], head_sha=OTHER)]
with self.assertRaises(Failure):
evaluate(SHA, result, bump())
def test_success_exact_built_source(self):
self.assertEqual('1.2.3-RC.4', evaluate(SHA, status(), bump()))
+44
View File
@@ -0,0 +1,44 @@
"""Exercise actual shell handling of gh error JSON, including the observed 404."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import textwrap
import unittest
SOURCE = Path(__file__).parents[1].joinpath('.github/workflows/qbit-release-rc.yml').read_text()
FUNCTION = textwrap.dedent(SOURCE.split(' # BEGIN RC REF LOOKUP\n')[1].split(' # END RC REF LOOKUP')[0])
@unittest.skipUnless(shutil.which('bash') and shutil.which('jq'), 'Bash and jq required')
class RefLookupTests(unittest.TestCase):
def lookup(self, body, code):
with tempfile.TemporaryDirectory() as directory:
env = dict(os.environ, BODY=body, CODE=str(code), REPO='QRun-IO/qbit-alerts', workdir=directory)
script = 'set -euo pipefail\ngh() { printf "%s" "$BODY"; return "$CODE"; }\n' + FUNCTION + '\nresult=$(read_ref tags/v0.1.0-RC.17)\nprintf "%s" "$result"\n'
return subprocess.run(['bash', '-c', script], env=env, text=True, capture_output=True)
def test_absent_tag_returns_empty_not_error_json(self):
result = self.lookup('{"message":"Not Found","documentation_url":"https://docs.github.com/rest/git/refs#get-a-reference","status":"404"}', 1)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stdout)
def test_existing_tag_returns_only_valid_object_sha(self):
result = self.lookup('{"object":{"sha":"' + 'a' * 40 + '"}}', 0)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('a' * 40, result.stdout)
def test_permission_network_and_server_errors_are_not_missing_refs(self):
for body in ('{"status":"403"}', '{"status":"500"}', '', ' ', '\n', 'not json'):
with self.subTest(body=body):
self.assertNotEqual(0, self.lookup(body, 1).returncode)
def test_malformed_success_response_is_rejected(self):
for body in ('{}', '{"object":{"sha":null}}', '{"object":{"sha":"not-a-sha"}}'):
with self.subTest(body=body):
self.assertNotEqual(0, self.lookup(body, 0).returncode)
if __name__ == '__main__':
unittest.main()
+9
View File
@@ -30,6 +30,15 @@ def validate(job, publisher):
class TimeoutRecoveryTests(unittest.TestCase):
def test_stable_gate_must_match_the_actual_publishing_workflow(self):
job, publisher = evidence()
job['workflows']['workflow_name'] = 'verify'
publisher['name'] = 'verify'
validate(job, publisher)
publisher['name'] = 'publish_release_candidate'
with self.assertRaises(Failure):
validate(job, publisher)
def test_exact_upload_timeout_after_successful_verify(self):
self.assertEqual((124, 0), validate(*evidence()))
+5 -2
View File
@@ -6,6 +6,8 @@ Example: python tools/audit_estate.py --inventory inventory.json --orb-version 0
Policy: {"profiles":{"qbit":{"required_checks":{"main":["observed context"],
"develop":["observed context"]}}},"repositories":{"QRun-IO/example":{...}}}.
Only use contexts verified on hosted canaries. Absent policy is unknown, not pass.
A profile/repository policy may set rc_worker_sha independently of --worker-sha
so an RC-only worker change does not require updating unchanged native workers.
"""
import argparse
import base64
@@ -209,11 +211,12 @@ def audit(entry, snapshot, version, worker_sha, policy):
if profile == 'qbit' and (rc_enabled or existing_rc):
path = rc_worker.CALLER_PATH
raw = rc_source
rc_sha = policy.get("rc_worker_sha", worker_sha)
if raw is None:
finding('missing_rc_bridge', path)
elif not re.fullmatch(r'[0-9a-f]{40}', worker_sha or ''):
elif not re.fullmatch(r'[0-9a-f]{40}', rc_sha or ''):
finding('native_pin_policy_missing', path)
elif raw != rc_worker.generate(worker_sha):
elif raw != rc_worker.generate(rc_sha):
finding('rc_bridge_drift', path)
else:
native_paths.add(path)
+9 -4
View File
@@ -43,8 +43,8 @@ def publication_filters(kind, filters):
raise ValueError("Unknown publication filters")
branches = filters.get("branches")
tags = filters.get("tags")
if kind in ("snapshot", "release_candidate"):
expected = "develop" if kind == "snapshot" else r"/release\/.*/"
if kind in ("snapshot", "release_candidate", "hotfix"):
expected = {"snapshot": "develop", "release_candidate": r"/release\/.*/", "hotfix": r"/hotfix\/.*/"}[kind]
if not isinstance(branches, dict) or set(branches) != {"only"} or single_filter(branches["only"]) != expected or tags not in (None, {"only": []}):
raise ValueError("Unknown snapshot/RC filters")
return False, "none"
@@ -58,7 +58,8 @@ def publication_filters(kind, filters):
tag_filter = single_filter(tags["only"])
if not isinstance(tag_filter, str):
raise ValueError("Unknown release tag filter")
policy = {r"/^v\d+\.\d+\.\d+$/": "stable", "/v.*/": "v-prefix"}.get(tag_filter)
policy = {r"/^v\d+\.\d+\.\d+$/": "stable", r"/^v[0-9]+\.[0-9]+\.[0-9]+$/": "stable",
"/v.*/": "v-prefix"}.get(tag_filter)
if policy is None:
raise ValueError("Unknown release tag filter")
return main, policy
@@ -80,6 +81,9 @@ def test_filters(filters):
"/(develop|release/.*|integration.*)/": "non-release-no-integration",
"/(develop|main|release/.*|integration.*)/": "feature",
"/(develop|main|release/.*)/": "non-release-no-main",
"/(develop|release/.*|hotfix/.*)/": "non-release-no-hotfix",
"/(develop|main|release/.*|hotfix/.*)/": "non-release-no-main-hotfix",
"/(develop|main|release/.*|hotfix/.*|integration.*)/": "feature-no-hotfix",
}.get(pattern.replace(r"\/", "/"))
if policy is None:
raise ValueError("Unknown test branch filters")
@@ -119,7 +123,7 @@ def infer_manifest(config, version, default_branch):
raise ValueError("Custom pre-steps require review")
if job.endswith("/mvn_publish"):
kind = options.get("branch_type")
if kind not in ("snapshot", "release_candidate", "release"):
if kind not in ("snapshot", "release_candidate", "release", "hotfix"):
raise ValueError("Custom publication contract requires review")
if kind in publications:
raise ValueError("Duplicate publication jobs require review")
@@ -143,6 +147,7 @@ def infer_manifest(config, version, default_branch):
"test_branch_policy": test_policy or "all",
"publish": {**{kind: kind in publications
for kind in ("snapshot", "release_candidate", "release")},
**({"hotfix": True} if "hotfix" in publications else {}),
"asciidoc": False},
}