From 22076dfef1b5477680c2708e553113b74d5fd546 Mon Sep 17 00:00:00 2001 From: Anilkumar Reddy Date: Sat, 14 Nov 2026 21:24:04 -0600 Subject: [PATCH 1/3] feat: align build notifications and job summaries --- CONTRIBUTING.md | 6 + README.md | 10 +- RELEASING.md | 11 + docs/consistent-reporting.md | 137 ++++++++++++ scripts/contracts.mjs | 18 +- src/action.ts | 129 +++++++----- src/notification.ts | 19 +- src/reporting.ts | 93 +++++++++ src/result.ts | 4 +- src/security.ts | 3 + tests/action-core.ts | 23 +++ tests/action.test.ts | 33 +-- tests/compatibility.test.ts | 36 +++- tests/reporting-bundle.test.ts | 132 ++++++++++++ tests/reporting.test.ts | 368 +++++++++++++++++++++++++++++++++ 15 files changed, 931 insertions(+), 91 deletions(-) create mode 100644 docs/consistent-reporting.md create mode 100644 src/reporting.ts create mode 100644 tests/action-core.ts create mode 100644 tests/reporting-bundle.test.ts create mode 100644 tests/reporting.test.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eb1afde..eb6ace2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,11 @@ # Contributing +The current reporting feature is an unpublished 0.0.6 contract candidate. +Read [the candidate validation gate](docs/consistent-reporting.md) before running +normal validation: source requires new public helpers while normal dependency +files and dist deliberately remain on published 0.0.3. Do not disguise a source +package as a registry version or commit a machine-local dependency. + Use Node **24.21.0**, pnpm **12.6.0**, and Corepack: ```sh diff --git a/README.md b/README.md index b10dda1..61df009 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,13 @@ # CommerceKit CCv2 Build +> **Unpublished reporting candidate.** The consistent input/notification/job-summary +> changes require notification-contract 0.0.6, which is not published. Normal +> registry manifests, lockfile and committed bundle remain on the published +> 0.0.3 baseline. Registry build/merge readiness is BLOCKED until separately +> authorized publication, exact repinning and normal bundle regeneration. +> See [reporting validation](docs/consistent-reporting.md). Inputs, remote-operation +> policies and failure semantics remain unchanged. + **Status: Initial implementation under development.** No Action release or Marketplace listing is available yet. Both this Action and CommerceKit Notifications remain unreleased. The examples below describe future usage after coordinated release approval. @@ -82,7 +90,7 @@ All seven outputs are strings and are written before handled failure is reported | `result-json` | Always on handled completion | Sanitized schemaVersion 1 result | | `notification-event` | Always on handled completion | Valid NotificationEvent v1 `ccv2.build.completed` | -`result-json` contains `schemaVersion`, `outcome`, `pollCount`, `retryCount`, `durationMs`, and `timedOut`. Known optional fields are `subscriptionCode`, `applicationCode`, `buildCode`, `buildName`, `branch`, `buildStatus`, `percentage`, `numberOfTasks`, `startedTaskCount`, and `error` (`code`, `message`, optional `httpStatus`). Each JSON output is capped at 16 KiB. There are no raw task payloads, headers, logs, or raw API responses. +`result-json` contains `schemaVersion`, `outcome`, `pollCount`, `retryCount`, `durationMs`, and `timedOut`. Known optional fields are `subscriptionCode`, `applicationCode`, `buildCode`, `buildName`, `branch`, `buildStatus`, `percentage`, `numberOfTasks`, `startedTaskCount`, and `error` (`code`, `message`, optional `httpStatus`). The reporting candidate bounds each structured JSON output to 64 KiB, aligned with the shared parser and cleanup; the unchanged published-baseline bundle uses 16 KiB. There are no raw task payloads, headers, logs, or raw API responses. The notification carries only supported build fields, safe error information, and approved GitHub context. `retryCount` counts actual extra HTTP attempts, including an authorization refresh replay; it is not the poll count. The workflow run link is included when safely constructible. No Cloud Portal UI link is guessed. The [shared contract](contracts/README.md) is validated at runtime and in tests. diff --git a/RELEASING.md b/RELEASING.md index 8920ba5..6f0171d 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,5 +1,16 @@ # Releasing +## Consistent reporting gate + +**BLOCKED:** this source candidate requires unpublished notification-contract +0.0.6. Source-tarball integration tests do not establish registry readiness. +Publication needs separate owner authorization; then verify the exact public +package, pin a supported exact registry version, regenerate the normal lockfile +and standalone bundle, and rerun all normal quality/CI/CodeQL checks. Coordinated +Notify rendering must support the new input context. Existing live validation, +release and deployment gates remain in force. No Git tag, publication, deployment, +provider send or real SAP operation is authorized by this reporting change. + **UNRELEASED — NO RELEASE UNTIL THE COMPLETE ACTION SUITE IS SANDBOX-VERIFIED.** Implementation may merge after review. Do not create `v1.0.0`, create or move `v1`, publish a GitHub Release or Marketplace listing, or publish an npm package while these gates remain open. diff --git a/docs/consistent-reporting.md b/docs/consistent-reporting.md new file mode 100644 index 0000000..36bb49d --- /dev/null +++ b/docs/consistent-reporting.md @@ -0,0 +1,137 @@ +# Consistent Action reporting candidate + +## Scope and package gate + +Inspected current main `923535d589bd8cebece4f3cbf479608f9535c4c3`. This change keeps every +existing input, endpoint, remote mutation, polling/deadline, retry/refresh policy +and domain outcome in place. It consumes the existing notification-contract +package for input capture/projection, schema/factories, redaction, status style +and Markdown summary rendering. No auth, HTTP or provider-delivery subsystem +was added. + +**BLOCKED — normal registry build/merge readiness:** the new public APIs and +Build/Deploy optional context fields require unpublished notification-contract +**0.0.6**. Normal `package.json`, `pnpm-lock.yaml` and `dist` deliberately remain +on published notification-contract **0.0.3** and ccv2-client **0.0.3**. These are +baseline artifacts, not a claim that the richer source is bundled/released. +A source-tarball candidate is tested only in a private isolated consumer; no +permanent `file:` dependency, source alias or fake registry version is committed. +After separately authorized publication, verify exact registry provenance, +repin/rebuild normally and run all required checks before merge or adoption. + +## Notification and summary behavior + +Every handled outcome reports all **11 input names**. Valid configuration +uses effective normalized defaults; invalid configuration shows safely captured +settings with `inputsValidated=false`. Capture reads each input once and masks +the four authentication values before any public field is read. Token endpoint, +client ID, client secret and resource are always literal `[REDACTED]` in public +context. Received tokens continue to use the existing Action masker. + +Shared known-secret/JWT redaction precedes the 256-character per-value bound; +truncation is explicit. API URLs use only a validated safe HTTPS origin. Arbitrary +credential-bearing URLs are not reflected. Missing optional values are visible +as not set. Markdown/HTML control syntax is escaped by the shared renderer. + +Build includes subscription/application, branch/name, API origin and polling/ +timeout settings. Its existing success/failure/cancelled/internal-error event +semantics remain unchanged. No artificial warning replaces a build error. +The immutable 16-case pre-extraction fixture is retained byte-for-byte; only +additive input context and the intentionally replaced summary presentation are +separated from the legacy comparison and independently asserted. + +Each execution attempts a GitHub job summary after outputs, including handled +input/API/authentication/timeout failures. The shared layout is an icon/status +heading followed by Result and Inputs tables, safe Issues when present, and a +validated workflow link when available. Human labels replace internal property +names. Icons/labels reuse the shared status mapping: + +| Outcome | Style | Operation behavior | +| ----------------------------- | -------------------- | ------------------------------------------------- | +| success | ✅ Succeeded | Existing success behavior | +| failure | ❌ Failed | Existing failure behavior | +| internal-error | ❌ CommerceKit error | Existing validation/API/deadline failure behavior | +| cancelled | ⏹️ Cancelled | Existing Action exit policy is retained | +| action-required (Deploy only) | ⚠️ Action required | Existing non-failing manual/canary handoff | + +Trusted local outcome/operation enums (and allowlisted Build statuses) retain +their actual semantics when a credential coincidentally equals an enum word. +Public copies of supplied input values remain redacted. Arbitrary API strings +are never restored after sanitization. This prevents masking from manufacturing +an invalid event or a different domain outcome. + +Structured result/event JSON is bounded to **64 KiB**, deliberately raised from +16 KiB for the unreleased reporting candidate. Invalid input settings +can expand under JSON Unicode escaping even when each projected value is bounded +to 256 characters. A malformed-Unicode test verifies the event remains present, schema-valid and +below 64 KiB with all input names; the coordinated Deploy test also covers events +above the former 16 KiB bound. +Scalar outputs retain their existing bound and endpoint field validation. + +Reporting cannot overwrite the operation result. Event creation failure emits +an empty notification output, a safe warning and an issue in the available +summary; consumers must skip notification delivery when the event is empty. +Each output is attempted independently, and the summary is still attempted if +an output write fails. An output contract failure can fail the Action separately +while keeping the original domain result/event status. An existing operation +error remains the primary Action failure. Summary errors warn without erasing +outputs or changing the operation outcome. + +## Validation evidence + +Status vocabulary: PASS, FAIL, BLOCKED, NOT RUN. + +| Check | Result | +| -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| Published 0.0.3 baseline frozen installation and full `pnpm quality` | PASS: 182 tests; 99.58% statements, 98.33% branches, 100% functions, 99.56% lines | +| Input definition parity with `action.yml` | Covered by candidate tests: 11 names, confidentiality/presence policy | +| Shared-schema input context and summary/status tests | PASS: 207 tests/10 files; 100% statements, 98.60% branches, 100% functions, 100% lines | +| Actual standalone bundle status/input/masking/summary matrix | PASS: 5 new status/input/summary cases plus the existing standalone bundle test, mocked fetch only | +| Normal new-source registry CI/bundle consistency | BLOCKED by unpublished 0.0.6; baseline normal files remain unchanged | +| Real SAP, hosted Sandbox dispatch, live Slack/Teams delivery | NOT RUN | + +The candidate procedure copies the reviewed source into a separate private +workspace, verifies and installs an exact source-packed 0.0.6 tarball, builds its +own bundle, and runs `COMMERCEKIT_CANDIDATE_CONTRACT_VERSION=0.0.6 pnpm quality`. +`scripts/contracts.mjs` permits that explicit candidate mode only with a private +manifest, an installed exact 0.0.6 package and a `file:*.tgz` dependency in that +temporary workspace. The client remains exact registry 0.0.3. Normal mode still +requires exact published 0.0.3; candidate mode never turns normal CI green. + +All existing 95% statement/branch/function/line thresholds and production source +inclusion remain unchanged. Original fixtures and remote-operation tests remain. +Synthetic bundle tests run without runtime package installation or registry +credentials and check zero mock requests for invalid configuration. They do not +call SAP, create a hosted Sandbox run, or deliver a provider webhook. + +## Reviewed candidate package and final commands + +Final tested contract source: +`b88ed58976af9aee532488d82ea09340b35a4d8c` in existing action-kit. +It is an **unpublished source candidate**, not a registry dependency. + +- Tarball: `commercekit-tools-notification-contract-0.0.6.tgz`, 18852 bytes. +- SHA256: `645b38e7456e63b96e7630da7d63c1f6ccbf27854b5b7001ff77db435afa2393`. +- Integrity: `sha512-eqV2tVnjmuYtG5ExjqScPCGxxR8MW8QlbeuXMA/YjzKzujgSMf9oMQpvQDqmysGhHLN8918XtNh9gbO7UQH4Ug==`. +- Candidate Action bundle SHA256: `d013e6db0897c6be5248d46203f8b509417097f18924c99aa396dd90af657dbf`. + +The final commands actually executed in a fresh private isolated consumer were: + +```sh +pnpm install --no-frozen-lockfile +pnpm install --frozen-lockfile +pnpm bundle +COMMERCEKIT_CANDIDATE_CONTRACT_VERSION=0.0.6 pnpm quality +``` + +The first command resolves only the temporary source-tarball dependency; the next +verifies that exact temporary lockfile. All quality steps passed: formatting, +lint, strict types, schema/compatibility checks, coverage, bundle consistency, +public scan and production dependency audit (no known vulnerabilities). Source +`pnpm format:check`, public scan and `git diff --check` also passed. Normal source +manifests/locks/dist and endpoint/input validation modules have no changes. + +No source was copied from the shared package. No normal install uses the +candidate tarball. No publication, Git tag, deployment, provider send or real +SAP request occurred. Registry readiness stays BLOCKED until separately +approved publication and normal consumer regeneration/validation. diff --git a/scripts/contracts.mjs b/scripts/contracts.mjs index efcbe5e..d60e0c1 100644 --- a/scripts/contracts.mjs +++ b/scripts/contracts.mjs @@ -3,13 +3,27 @@ import assert from "node:assert/strict"; import schema from "@commercekit-tools/notification-contract/schema" with { type: "json" }; import { validateNotificationEvent } from "@commercekit-tools/notification-contract"; const root = JSON.parse(readFileSync("package.json", "utf8")); +const candidateVersion = process.env.COMMERCEKIT_CANDIDATE_CONTRACT_VERSION; +if (candidateVersion !== undefined) { + assert.equal(candidateVersion, "0.0.6"); + assert.equal(root.private, true); + assert.match( + root.dependencies["@commercekit-tools/notification-contract"], + /^file:.+\.tgz$/u, + ); +} for (const name of ["notification-contract", "ccv2-client"]) { const id = "@commercekit-tools/" + name; const { default: pkg } = await import(id + "/package.json", { with: { type: "json" }, }); - assert.equal(pkg.version, "0.0.3"); - assert.equal(root.dependencies[id], "0.0.3"); + const expected = + name === "notification-contract" && candidateVersion + ? candidateVersion + : "0.0.3"; + assert.equal(pkg.version, expected); + if (name !== "notification-contract" || !candidateVersion) + assert.equal(root.dependencies[id], "0.0.3"); } assert.equal(schema.properties.schemaVersion.const, 1); assert(!existsSync("contracts/notification-event-v1.schema.json")); diff --git a/src/action.ts b/src/action.ts index 30907f2..29b95c3 100644 --- a/src/action.ts +++ b/src/action.ts @@ -1,12 +1,18 @@ import type * as core from "@actions/core"; -import { readInputs } from "./inputs.js"; -import { Sanitizer, escapeHtml } from "./security.js"; +import { + captureActionInputs, + type SafeNotificationError, +} from "@commercekit-tools/notification-contract"; +import { readInputs, type Inputs } from "./inputs.js"; +import { Sanitizer } from "./security.js"; import { ActionError, waitTimeout } from "./errors.js"; import { runtime, type Runtime } from "./runtime.js"; import { BuildTransport } from "./transport.js"; -import { BuildApi } from "./api.js"; +import { BuildApi, statuses } from "./api.js"; import { initialResult, type Result } from "./result.js"; import { event } from "./notification.js"; +import { inputContext, inputDefinitions, summary } from "./reporting.js"; +const maxStructuredOutputBytes = 65536; export type Core = Pick< typeof core, "getInput" | "setSecret" | "setOutput" | "setFailed" | "info" | "warning" @@ -20,15 +26,20 @@ export async function run( const started = rt.now(); const safe = new Sanitizer((v) => core.setSecret(v)); let result = initialResult(); + let captured: Record = {}; + let validated: Inputs | undefined; let timer: ReturnType | undefined; let transport: BuildTransport | undefined; let api: BuildApi | undefined; let activeSignal: AbortSignal | undefined; try { - const input = readInputs( - (n) => core.getInput(n, { trimWhitespace: false }), - safe, + captured = captureActionInputs( + inputDefinitions, + (name) => core.getInput(name, { trimWhitespace: false }), + (value) => safe.add(value), ); + const input = readInputs((name) => captured[name] ?? "", safe); + validated = input; Object.assign(result, { subscriptionCode: input.subscriptionCode, buildName: input.buildName, @@ -121,29 +132,32 @@ export async function run( result.pollCount = api?.pollCount ?? 0; result.retryCount = transport?.retryCount ?? 0; result.durationMs = Math.max(0, Math.floor(rt.now() - started)); - // Explicit allowlisted model; sanitize every string before any output or summary. + // Sanitize untrusted data without changing locally selected semantic enums. + const outcome = result.outcome; + const buildStatus = + result.buildStatus && statuses.includes(result.buildStatus) + ? result.buildStatus + : undefined; result = JSON.parse( JSON.stringify(result, (_key, value: unknown) => typeof value === "string" ? safe.text(value) : value, ), ) as Result; + result.outcome = outcome; + if (buildStatus) result.buildStatus = buildStatus; try { - await emit(core, result, safe, env); + Object.assign(result, inputContext(captured, validated, safe)); } catch { - result = { - ...initialResult(), - durationMs: result.durationMs, - error: { - code: "INTERNAL_ERROR", - message: "The Action could not publish its result.", - }, - }; - try { - await emit(core, result, safe, {}); - } catch { - core.setFailed("The Action could not publish its result."); - } + core.warning( + "The input summary could not be prepared; the Action result is preserved.", + ); } + const outputFailure = await emit(core, result, safe, env); + if (result.outcome !== "success") + core.setFailed(result.error?.message ?? "CCv2 build did not succeed."); + else if (outputFailure) + core.setFailed("Action result outputs could not be written."); + else core.info("Build completed successfully."); return result; } async function emit( @@ -152,11 +166,25 @@ async function emit( safe: Sanitizer, env: NodeJS.ProcessEnv, ) { - const notification = event(result, env, safe); + const reportingIssues: SafeNotificationError[] = []; + let eventJson: string; + try { + eventJson = JSON.stringify(event(result, env, safe)); + if (Buffer.byteLength(eventJson) > maxStructuredOutputBytes) + throw Error("Output exceeds limit."); + } catch { + eventJson = ""; + reportingIssues.push({ + code: "notification-unavailable", + message: + "The notification event could not be prepared; the Action result is preserved.", + }); + core.warning( + "The notification event could not be prepared; the Action result is preserved.", + ); + } const json = JSON.stringify(result); - const eventJson = JSON.stringify(notification); - if (Buffer.byteLength(json) > 16384 || Buffer.byteLength(eventJson) > 16384) - throw Error("Output exceeds limit."); + let outputFailure = false; for (const [name, value] of Object.entries({ "build-code": result.buildCode ?? "", "build-status": result.buildStatus ?? "", @@ -166,35 +194,34 @@ async function emit( "duration-ms": String(result.durationMs), "result-json": json, "notification-event": eventJson, - })) - core.setOutput(name, value); - const rows = [ - ["Status", result.buildStatus ?? result.outcome], - ["Build code", result.buildCode], - ["Build name", result.buildName], - ["Branch", result.branch], - ["Application", result.applicationCode], - ["Percentage", result.percentage], - ["Poll count", result.pollCount], - ["Duration (ms)", result.durationMs], - ["Error", result.error?.message], - ].filter(([, v]) => v !== undefined); - try { - core.summary.addRaw( - "

CCv2 Build

" + - rows - .map( - ([k, v]) => - ``, - ) - .join("") + - "
${k}${escapeHtml(String(v))}
", + })) { + try { + const limit = + name === "result-json" || name === "notification-event" + ? maxStructuredOutputBytes + : 16384; + if (Buffer.byteLength(value) > limit) + throw Error("Output exceeds limit."); + core.setOutput(name, value); + } catch { + outputFailure = true; + } + } + if (outputFailure) { + core.warning( + "Action result outputs could not be written; the original result is preserved.", ); + reportingIssues.push({ + code: "outputs-unavailable", + message: + "Some Action outputs could not be written. Review the available result and run summary.", + }); + } + try { + core.summary.addRaw(summary(result, safe, env, reportingIssues)); await core.summary.write(); } catch { core.warning("The step summary could not be written."); } - if (result.outcome !== "success") - core.setFailed(result.error?.message ?? "CCv2 build did not succeed."); - else core.info("Build completed successfully."); + return outputFailure; } diff --git a/src/notification.ts b/src/notification.ts index e59b4f5..8cf8eb0 100644 --- a/src/notification.ts +++ b/src/notification.ts @@ -7,14 +7,19 @@ import { controls } from "./inputs.js"; import type { Sanitizer } from "./security.js"; export function context(env: NodeJS.ProcessEnv, safe: Sanitizer) { - // Keep Build's exact-secret/control-character exclusion before shared allowlisted extraction. - const filtered = Object.fromEntries( - Object.entries(env).filter( - ([, value]) => - value !== undefined && !controls.test(value) && !safe.contains(value), - ), + // Read only the package's allowlisted environment values, with Build's stricter policy. + const ctx = extractSafeGitHubContext( + new Proxy(env, { + get(target, key: string) { + const value = target[key]; + return value !== undefined && + !controls.test(value) && + !safe.contains(value) + ? value + : undefined; + }, + }), ); - const ctx = extractSafeGitHubContext(filtered); if (ctx.runUrl && safe.contains(ctx.runUrl)) delete ctx.runUrl; return ctx; } diff --git a/src/reporting.ts b/src/reporting.ts new file mode 100644 index 0000000..a651efe --- /dev/null +++ b/src/reporting.ts @@ -0,0 +1,93 @@ +import { + createActionInputContext, + renderActionSummary, + type ActionInputDefinition, + type NotificationInputContext, + type SafeNotificationError, +} from "@commercekit-tools/notification-contract"; +import type { Inputs } from "./inputs.js"; +import type { Result } from "./result.js"; +import type { Sanitizer } from "./security.js"; +import { context } from "./notification.js"; + +export const inputDefinitions: readonly ActionInputDefinition[] = [ + { name: "token-endpoint", confidential: true }, + { name: "client-id", confidential: true }, + { name: "client-secret", confidential: true }, + { name: "resource", confidential: true }, + { name: "subscription-code" }, + { name: "branch" }, + { name: "build-name" }, + { name: "application-code" }, + { name: "api-base-url", display: "url-origin" }, + { name: "poll-interval-seconds" }, + { name: "timeout-minutes" }, +]; + +export function inputContext( + raw: Readonly>, + input: Inputs | undefined, + safe: Sanitizer, +): NotificationInputContext { + return createActionInputContext(inputDefinitions, raw, { + validated: input !== undefined, + secrets: safe.knownSecrets(), + ...(input + ? { + effective: { + "subscription-code": input.subscriptionCode, + branch: input.branch, + "build-name": input.buildName, + "application-code": input.applicationCode ?? "", + "api-base-url": input.apiBaseUrl, + "poll-interval-seconds": String(input.pollIntervalMs / 1000), + "timeout-minutes": String(input.timeoutMs / 60000), + }, + } + : {}), + }); +} + +export function summary( + result: Result, + safe: Sanitizer, + env: NodeJS.ProcessEnv, + reportingIssues: readonly SafeNotificationError[] = [], +): string { + const ctx = context(env, safe); + const facts = [ + ["Build status", result.buildStatus], + ["Subscription", result.subscriptionCode], + ["Application", result.applicationCode], + ["Build code", result.buildCode], + ["Build name", result.buildName], + ["Branch", result.branch], + ["Progress (%)", result.percentage], + ["Poll count", result.pollCount], + ["Retry count", result.retryCount], + ["Duration (ms)", result.durationMs], + ["Timed out", result.timedOut], + ] as const; + return renderActionSummary({ + title: "CCv2 Build", + status: result.outcome, + facts: facts.flatMap(([label, value]) => + value === undefined ? [] : [{ label, value }], + ), + ...(result.inputs + ? { + inputContext: { + inputs: result.inputs, + inputsValidated: result.inputsValidated ?? false, + inputsTruncated: result.inputsTruncated ?? false, + }, + } + : {}), + ...(result.error ? { error: result.error } : {}), + issues: [...(result.issues ?? []), ...reportingIssues].slice(0, 3), + ...(ctx.runUrl + ? { links: [{ label: "View workflow", url: ctx.runUrl }] } + : {}), + secrets: safe.knownSecrets(), + }); +} diff --git a/src/result.ts b/src/result.ts index d367a23..52e39e9 100644 --- a/src/result.ts +++ b/src/result.ts @@ -1,9 +1,10 @@ import type { CompletedStatus, SafeNotificationError, + NotificationInputContext, } from "@commercekit-tools/notification-contract"; import type { BuildStatus } from "./api.js"; -export interface Result { +export interface Result extends Partial { schemaVersion: 1; outcome: CompletedStatus; subscriptionCode?: string; @@ -19,6 +20,7 @@ export interface Result { durationMs: number; timedOut: boolean; retryCount: number; + issues?: SafeNotificationError[]; error?: Required & { httpStatus?: number }; } export const initialResult = (): Result => ({ diff --git a/src/security.ts b/src/security.ts index 133e979..45f815b 100644 --- a/src/security.ts +++ b/src/security.ts @@ -16,6 +16,9 @@ export class Sanitizer { this.mask(value); this.secrets.add(value); } + knownSecrets(): readonly string[] { + return [...this.secrets]; + } text(value: string, max = 1000): string { const secrets = [...this.secrets]; const text = redactJwtLikeTokens( diff --git a/tests/action-core.ts b/tests/action-core.ts new file mode 100644 index 0000000..68fe44a --- /dev/null +++ b/tests/action-core.ts @@ -0,0 +1,23 @@ +import { vi } from "vitest"; +import type { Core } from "../src/action.js"; +import { raw } from "./fixtures.js"; +export function fakeCore(overrides: Record = {}) { + const outputs: Record = {}; + const calls: string[] = []; + const summary = { addRaw: vi.fn(), write: vi.fn(async () => {}) }; + const core = { + getInput: vi.fn((n: string) => overrides[n] ?? raw[n] ?? ""), + setSecret: vi.fn(), + setOutput: vi.fn((k: string, v: string) => { + calls.push(k); + outputs[k] = v; + }), + setFailed: vi.fn(() => { + calls.push("failed"); + }), + info: vi.fn(), + warning: vi.fn(), + summary, + } as unknown as Core; + return { core, outputs, calls }; +} diff --git a/tests/action.test.ts b/tests/action.test.ts index 8d3f7d7..4ed3393 100644 --- a/tests/action.test.ts +++ b/tests/action.test.ts @@ -1,31 +1,12 @@ import { it, expect, vi, describe } from "vitest"; -import { run, type Core } from "../src/action.js"; +import { run } from "../src/action.js"; import { raw } from "./fixtures.js"; import { harness, token } from "./harness.js"; import { context, event } from "../src/notification.js"; import { validateNotificationEvent as validateEvent } from "@commercekit-tools/notification-contract"; import { Sanitizer } from "../src/security.js"; import { initialResult } from "../src/result.js"; -export function fakeCore(overrides: Record = {}) { - const outputs: Record = {}; - const calls: string[] = []; - const summary = { addRaw: vi.fn(), write: vi.fn(async () => {}) }; - const core = { - getInput: vi.fn((n: string) => overrides[n] ?? raw[n] ?? ""), - setSecret: vi.fn(), - setOutput: vi.fn((k: string, v: string) => { - calls.push(k); - outputs[k] = v; - }), - setFailed: vi.fn(() => { - calls.push("failed"); - }), - info: vi.fn(), - warning: vi.fn(), - summary, - } as unknown as Core; - return { core, outputs, calls }; -} +import { fakeCore } from "./action-core.js"; const create = { code: "synthetic.1" }; const env = { GITHUB_REPOSITORY: "synthetic/example", @@ -188,13 +169,17 @@ describe("orchestration, polling, outputs and notification events", () => { ); expect(c.calls.at(-1)).toBe("failed"); }); - it("attempts minimal fallback if output publishing throws", async () => { + it("preserves a successful build result when an output write fails", async () => { const c = fakeCore(); vi.mocked(c.core.setOutput).mockImplementationOnce(() => { throw Error(); }); await run(c.core, harness([token, create, { buildStatus: "SUCCESS" }]).rt); - expect(c.outputs["notification-event"]).toContain("internal-error"); + expect(c.outputs["notification-event"]).toContain('"status":"success"'); + expect(c.outputs["result-json"]).toContain('"outcome":"success"'); + expect(c.core.setFailed).toHaveBeenCalledWith( + "Action result outputs could not be written.", + ); expect(c.calls.at(-1)).toBe("failed"); }); it("fails safely if even fallback output cannot be written", async () => { @@ -204,7 +189,7 @@ describe("orchestration, polling, outputs and notification events", () => { }); await run(c.core, harness([token, create, { buildStatus: "SUCCESS" }]).rt); expect(c.core.setFailed).toHaveBeenCalledWith( - "The Action could not publish its result.", + "Action result outputs could not be written.", ); }); it("handles runner cancellation without deleting build", async () => { diff --git a/tests/compatibility.test.ts b/tests/compatibility.test.ts index fa869ee..f18a315 100644 --- a/tests/compatibility.test.ts +++ b/tests/compatibility.test.ts @@ -5,8 +5,9 @@ import { harness, token } from "./harness.js"; import { raw } from "./fixtures.js"; import { validateNotificationEvent } from "@commercekit-tools/notification-contract"; -// Captured on the pre-migration implementation at ebdc830. Only generated identity/time is normalized. -it("preserves complete public outputs and validates every completion path", async () => { +// Preserve immutable pre-migration operation/output semantics. New additive input +// context and the deliberately replaced summary UI are tested in reporting.test.ts. +it("preserves legacy domain outputs and failure ordering across every completion path", async () => { const create = { code: "synthetic.1" }; const cases: [string, object[], Record?][] = [ ...["SUCCESS", "FAIL", "DELETED", "UNKNOWN"].map( @@ -70,7 +71,12 @@ it("preserves complete public outputs and validates every completion path", asyn ["unexpected", []], ["cancelled", []], ]; - const fixtures = []; + const fixtures: { + name: string; + outputs: unknown; + calls: string[]; + summaries: string[]; + }[] = []; for (const [name, replies, overrides = {}] of cases) { const outputs: Record = {}; const calls: string[] = []; @@ -129,7 +135,27 @@ it("preserves complete public outputs and validates every completion path", asyn summaries, }); } - expect(JSON.parse(JSON.stringify(fixtures))).toEqual( - JSON.parse(readFileSync("tests/fixtures/build-compatibility.json", "utf8")), + function legacyProjection(value: typeof fixtures) { + return value.map(({ summaries, ...fixture }) => { + void summaries; + const copy = JSON.parse(JSON.stringify(fixture)); + for (const key of [ + "inputs", + "inputsValidated", + "inputsTruncated", + "issues", + ]) { + delete copy.outputs["result-json"][key]; + delete copy.outputs["notification-event"].data[key]; + } + return copy; + }); + } + expect(legacyProjection(fixtures)).toEqual( + legacyProjection( + JSON.parse( + readFileSync("tests/fixtures/build-compatibility.json", "utf8"), + ), + ), ); }); diff --git a/tests/reporting-bundle.test.ts b/tests/reporting-bundle.test.ts new file mode 100644 index 0000000..238921d --- /dev/null +++ b/tests/reporting-bundle.test.ts @@ -0,0 +1,132 @@ +import { + copyFileSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { spawnSync } from "node:child_process"; +import { expect, it } from "vitest"; +import { parseNotificationEventJson } from "@commercekit-tools/notification-contract"; +import { inputDefinitions } from "../src/reporting.js"; + +const scenarios = [ + ["SUCCESS", "success", 0, "✅"], + ["FAIL", "failure", 1, "❌"], + ["DELETED", "cancelled", 1, "⏹️"], + ["UNKNOWN", "internal-error", 1, "❌"], + ["invalid", "internal-error", 1, "❌"], +] as const; +function parseOutputs(text: string): Record { + const lines = text.split("\n"); + const values: Record = {}; + for (let index = 0; index < lines.length; index++) { + const [name, delimiter] = lines[index]!.split("<<"); + if (!delimiter) continue; + const body = []; + while (++index < lines.length && lines[index] !== delimiter) + body.push(lines[index]); + values[name!] = body.join("\n"); + } + return values; +} +it.each(scenarios)( + "bundled build %s writes consistent masked event, outputs and job summary", + (status, expected, exit, icon) => { + const dir = mkdtempSync(join(tmpdir(), "ccv2-build-report-")); + try { + const outputPath = join(dir, "output"); + const summaryPath = join(dir, "summary"); + const requestsPath = join(dir, "requests"); + const preload = join(dir, "fetch.cjs"); + writeFileSync(outputPath, ""); + writeFileSync(summaryPath, ""); + writeFileSync( + preload, + `const fs=require('node:fs');let requests=0;process.once('exit',()=>fs.writeFileSync(${JSON.stringify(requestsPath)},String(requests)));global.fetch=async(url,init)=>{requests++;url=String(url);if(!['https://auth.example.invalid','https://portalapi.commerce.ondemand.com'].includes(new URL(url).origin))throw Error('Unexpected network destination');if(init.redirect!=='error')throw Error('Unsafe redirects');if(url.includes('oauth2'))return Response.json({access_token:'SYNTHETIC_BUNDLE_TOKEN',token_type:'Bearer'});if(init.method==='POST')return Response.json({code:'synthetic.1'},{status:201});return Response.json({buildStatus:${JSON.stringify(status)},percentage:100});};`, + ); + copyFileSync("dist/index.js", join(dir, "index.js")); + copyFileSync("dist/package.json", join(dir, "package.json")); + const child = spawnSync( + process.execPath, + ["--require", preload, join(dir, "index.js")], + { + cwd: dir, + encoding: "utf8", + timeout: 10000, + env: { + ...process.env, + NODE_AUTH_TOKEN: "", + GITHUB_TOKEN: "", + GH_TOKEN: "", + NODE_PATH: "", + "INPUT_TOKEN-ENDPOINT": "https://auth.example.invalid/oauth2/token", + "INPUT_CLIENT-ID": "SYNTHETIC_BUNDLE_CLIENT", + "INPUT_CLIENT-SECRET": "SYNTHETIC_BUNDLE_SECRET", + INPUT_RESOURCE: "SYNTHETIC_BUNDLE_RESOURCE", + "INPUT_SUBSCRIPTION-CODE": "synthetic-subscription", + INPUT_BRANCH: status === "invalid" ? "" : "main", + "INPUT_BUILD-NAME": "synthetic-build", + "INPUT_APPLICATION-CODE": "synthetic-app", + "INPUT_POLL-INTERVAL-SECONDS": "10", + "INPUT_TIMEOUT-MINUTES": "1", + GITHUB_OUTPUT: outputPath, + GITHUB_STEP_SUMMARY: summaryPath, + GITHUB_REPOSITORY: "synthetic/example", + GITHUB_RUN_ID: "123", + }, + }, + ); + expect(child.status, child.stderr).toBe(exit); + const outputs = parseOutputs(readFileSync(outputPath, "utf8")); + const event = parseNotificationEventJson(outputs["notification-event"]!); + if (event.eventType !== "ccv2.build.completed") + throw Error("Expected build event."); + expect(event.status).toBe(expected); + expect(event.data.inputsValidated).toBe(status !== "invalid"); + expect(Object.keys(event.data.inputs!).sort()).toEqual( + inputDefinitions.map((input) => input.name).sort(), + ); + expect(JSON.parse(outputs["result-json"]!).inputs).toEqual( + event.data.inputs, + ); + const summary = readFileSync(summaryPath, "utf8"); + expect(summary).toContain(`## ${icon} CCv2 Build`); + for (const value of [ + "### Result", + "### Inputs", + "| Input | Value |", + "View workflow", + ]) + expect(summary).toContain(value); + for (const { name } of inputDefinitions) expect(summary).toContain(name); + if (expected !== "success") + expect(summary).toContain("| Code | Detail |"); + const sinks = + outputs["notification-event"]! + + outputs["result-json"]! + + summary + + child.stdout + + child.stderr; + for (const value of [ + "SYNTHETIC_BUNDLE_CLIENT", + "SYNTHETIC_BUNDLE_SECRET", + "SYNTHETIC_BUNDLE_RESOURCE", + "SYNTHETIC_BUNDLE_TOKEN", + "https://auth.example.invalid/oauth2/token", + ]) { + // GitHub's add-mask command intentionally contains the secret for runner masking. + expect( + outputs["notification-event"]! + outputs["result-json"]! + summary, + ).not.toContain(value); + } + expect(sinks).not.toContain("Unexpected network destination"); + if (status === "invalid") + expect(readFileSync(requestsPath, "utf8")).toBe("0"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, +); diff --git a/tests/reporting.test.ts b/tests/reporting.test.ts new file mode 100644 index 0000000..23ff2c6 --- /dev/null +++ b/tests/reporting.test.ts @@ -0,0 +1,368 @@ +import { readFileSync } from "node:fs"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { parseNotificationEventJson } from "@commercekit-tools/notification-contract"; +import { run } from "../src/action.js"; +import { readInputs } from "../src/inputs.js"; +import * as notification from "../src/notification.js"; +import * as reporting from "../src/reporting.js"; +import { initialResult } from "../src/result.js"; +import { Sanitizer } from "../src/security.js"; +import { raw } from "./fixtures.js"; +import { harness, token } from "./harness.js"; +import { fakeCore } from "./action-core.js"; + +afterEach(() => vi.restoreAllMocks()); +const workflow = { + GITHUB_REPOSITORY: "synthetic/example", + GITHUB_RUN_ID: "123", +}; +const replies = (status = "SUCCESS") => [ + token, + { code: "synthetic.1" }, + { buildStatus: status }, +]; +const authentication = [ + "token-endpoint", + "client-id", + "client-secret", + "resource", +]; +function settings(values: Record = raw, validated = true) { + const safe = new Sanitizer(() => {}); + authentication.forEach((name) => safe.add(values[name] ?? "")); + return { + safe, + context: reporting.inputContext( + values, + validated ? readInputs((name) => values[name] ?? "", safe) : undefined, + safe, + ), + }; +} +function parse(text: string) { + const value = parseNotificationEventJson(text); + if (value.eventType !== "ccv2.build.completed") + throw Error("Expected build event."); + return value; +} +function rendered(c: ReturnType) { + return vi + .mocked(c.core.summary.addRaw) + .mock.calls.map(([text]) => text) + .join(""); +} + +describe("consistent build reporting", () => { + it("covers every declared Action input with explicit authentication confidentiality", () => { + const inputYaml = readFileSync("action.yml", "utf8") + .split("\ninputs:\n")[1]! + .split("\noutputs:\n")[0]!; + const names = [...inputYaml.matchAll(/^ {2}([a-z-]+):$/gm)].map( + (match) => match[1], + ); + expect(reporting.inputDefinitions.map((input) => input.name)).toEqual( + names, + ); + expect(names).toHaveLength(11); + expect( + reporting.inputDefinitions + .filter((input) => input.confidential) + .map((input) => input.name), + ).toEqual(authentication); + }); + it("reports defaults, all fields and four redaction markers in the shared schema", () => { + const { context, safe } = settings(); + expect(context.inputsValidated).toBe(true); + expect(context.inputsTruncated).toBe(false); + expect(context.inputs).toMatchObject({ + "poll-interval-seconds": "60", + "timeout-minutes": "120", + branch: "feature/test", + }); + expect(context.inputs["api-base-url"]).toMatch( + /^https:\/\/portalapi\.commerce\.ondemand\.com\/?$/, + ); + for (const name of authentication) + expect(context.inputs[name]).toBe("[REDACTED]"); + expect(Object.keys(context.inputs)).toHaveLength(11); + const event = notification.event( + { ...initialResult(), outcome: "success", ...context }, + workflow, + safe, + ); + expect(parse(JSON.stringify(event)).data).toMatchObject(context); + }); + it("projects exact application and overridden validated policy values", () => { + const { context } = settings({ + ...raw, + "application-code": "synthetic-app", + "poll-interval-seconds": "20", + "timeout-minutes": "8", + }); + expect(context.inputs).toMatchObject({ + "application-code": "synthetic-app", + "poll-interval-seconds": "20", + "timeout-minutes": "8", + }); + }); + it("sanitizes rejected settings, known secrets, JWTs and long values before reporting", () => { + const secret = "SYNTHETIC_INPUT_SECRET_123"; + const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzeW50aGV0aWMifQ.c2lnbmF0dXJl"; + const { context } = settings( + { + ...raw, + "client-secret": secret, + branch: `${secret} ${jwt}`, + "build-name": "x".repeat(1000), + "api-base-url": + "https://username:password@example.invalid/private?token=private", + }, + false, + ); + expect(context.inputsValidated).toBe(false); + expect(context.inputsTruncated).toBe(true); + expect(context.inputs["build-name"]!.length).toBeLessThanOrEqual(256); + const serialized = JSON.stringify(context); + for (const marker of [secret, jwt, "username", "password", "token=private"]) + expect(serialized).not.toContain(marker); + }); + it.each([ + ["SUCCESS", "success", "✅"], + ["FAIL", "failure", "❌"], + ["DELETED", "cancelled", "⏹️"], + ["FUTURE", "internal-error", "❌"], + ])( + "uses the shared status style and input/result tables for %s", + async (status, outcome, icon) => { + const c = fakeCore(); + const result = await run(c.core, harness(replies(status)).rt, workflow); + const event = parse(c.outputs["notification-event"]!); + expect(result.outcome).toBe(outcome); + expect(event.status).toBe(outcome); + expect(event.data.inputs).toEqual(result.inputs); + const html = rendered(c); + for (const name of reporting.inputDefinitions.map((item) => item.name)) + expect(html).toContain(name); + for (const expected of [ + icon, + "CCv2 Build", + "Result", + "Inputs", + "Poll count", + "Duration \\(ms\\)", + "View workflow", + "| Input | Value |", + ]) + expect(html).toContain(expected); + for (const secret of [ + ...authentication.map((name) => raw[name]!), + token.access_token, + ]) + expect(html).not.toContain(secret); + if (result.buildStatus) expect(html).toContain("Build status"); + expect(c.core.summary.write).toHaveBeenCalledOnce(); + if (result.error) + expect(html).toContain(result.error.code.replaceAll("_", "\\_")); + }, + ); + it("captures authentication before any public input, reads once, and reports invalid input without API calls", async () => { + const c = fakeCore({ branch: "" }); + const order: string[] = []; + vi.mocked(c.core.getInput).mockImplementation((name) => { + order.push(`read:${name}`); + return name === "branch" ? "" : (raw[name] ?? ""); + }); + vi.mocked(c.core.setSecret).mockImplementation((value) => { + order.push(`mask:${value}`); + }); + const h = harness([]); + const result = await run(c.core, h.rt); + expect(result.inputsValidated).toBe(false); + expect(parse(c.outputs["notification-event"]!).data.inputs).toEqual( + result.inputs, + ); + expect(rendered(c)).toContain("INVALID\\_INPUT"); + expect(h.fetcher).not.toHaveBeenCalled(); + for (const name of authentication) + expect(order.indexOf(`mask:${raw[name]}`)).toBeLessThan( + order.indexOf("read:subscription-code"), + ); + expect( + vi.mocked(c.core.getInput).mock.calls.map(([name]) => name), + ).toHaveLength(11); + }); + it("escapes malicious text and preserves secret masking in every output and summary", async () => { + const c = fakeCore({ + "build-name": ` & ${raw["client-secret"]}`, + }); + await run(c.core, harness(replies()).rt); + const html = rendered(c); + expect(html).not.toContain("