From b2bfd66b6b4e1c740e5a05af4aa5b6b867fe6806 Mon Sep 17 00:00:00 2001 From: Anilkumar Reddy Date: Sat, 14 Nov 2026 21:24:05 -0600 Subject: [PATCH 1/3] feat: align deployment notifications and job summaries --- CONTRIBUTING.md | 6 + README.md | 10 +- RELEASING.md | 11 + docs/consistent-reporting.md | 138 ++++++++++ scripts/contracts.mjs | 15 +- src/action.ts | 136 ++++++---- src/notification.ts | 11 +- src/reporting.ts | 120 +++++++++ src/result.ts | 4 +- src/security.ts | 3 + tests/action-core.ts | 26 ++ tests/action.test.ts | 24 +- tests/reporting-bundle.test.ts | 138 ++++++++++ tests/reporting.test.ts | 449 +++++++++++++++++++++++++++++++++ tests/shared-packages.test.ts | 11 +- 15 files changed, 1024 insertions(+), 78 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 7bb44cf..b39e6ad 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 and pnpm 12.6.0 (`corepack enable`). Install with `pnpm install --frozen-lockfile`. The package is private and must not be published to npm. Run `pnpm format`, `pnpm lint`, `pnpm typecheck`, `pnpm contracts:check`, `pnpm test`, `pnpm test:coverage`, `pnpm audit`, `pnpm bundle`, `pnpm bundle:check`, `pnpm scan:public`, and `pnpm quality`. Coverage gates require 95% statements, branches, lines, and functions. Commit reproducible dist and its license inventory. diff --git a/README.md b/README.md index 3871adf..af1a766 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,13 @@ # CommerceKit CCv2 Deploy +> **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. + **UNRELEASED. No v1 tag exists.** Deploy existing SAP Commerce Cloud builds using Cloud Portal technical-user OAuth and provider-neutral NotificationEvent v1 outputs. Build creation is not a public feature. ## Authentication @@ -138,7 +146,7 @@ Safe reads and token requests retry selected transient errors at most three atte ## Result and events -`result-json` is a compact allowlisted schemaVersion 1 object containing operation, outcome, known deployment/build/environment identifiers, modes, last vendor status/percentage, poll count, duration, actionRequired, decision, newDeploymentCode, timedOut, cancellation requested/rollback flags, trafficSplit updated flag, and safe error code/message. Unknown optional fields are omitted. Each JSON output is bounded to 16 KiB. No raw responses, stage/history data, reasons, credentials, or traffic entities are output. +`result-json` is a compact allowlisted schemaVersion 1 object containing operation, outcome, known deployment/build/environment identifiers, modes, last vendor status/percentage, poll count, duration, actionRequired, decision, newDeploymentCode, timedOut, cancellation requested/rollback flags, trafficSplit updated flag, and safe error code/message. Unknown optional fields are omitted. The reporting candidate bounds structured JSON outputs to 64 KiB, aligned with the shared parser and cleanup; the unchanged published-baseline bundle uses 16 KiB. No raw responses, stage/history data, reasons, credentials, or traffic entities are output. DEPLOYED → success; FAIL → failure; UNDEPLOYED → cancelled; manual/canary handoff → action-required; timeout, auth/API/client errors or undocumented status → internal-error. Handoffs emit `ccv2.deployment.action-required`; all other final events emit `ccv2.deployment.completed`. Events validate offline through the pinned [shared notification contract](contracts/README.md). Only approved GitHub context variables are read. Links include a validated workflow URL; no Cloud Portal URL is guessed. diff --git a/RELEASING.md b/RELEASING.md index 303ed20..7b9e3d3 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,5 +1,16 @@ # Release policy — UNRELEASED +## 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. + NO RELEASE UNTIL BUILD, DEPLOY AND NOTIFY ARE SANDBOX-VERIFIED TOGETHER. No tags, moving v1, GitHub Release, npm publishing, or Marketplace publication until all gates pass: diff --git a/docs/consistent-reporting.md b/docs/consistent-reporting.md new file mode 100644 index 0000000..b736157 --- /dev/null +++ b/docs/consistent-reporting.md @@ -0,0 +1,138 @@ +# Consistent Action reporting candidate + +## Scope and package gate + +Inspected current main `bb6d1d6a2ac43a5b6e5b6831c78c5cf28bdb95ca`. 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 **21 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. + +Deploy includes all operation, deployment/build/environment, database/strategy, +green-decision, rollback, waiting and polling settings. The three free-form or +structured inputs `decision-reason`, `cancel-reason` and `traffic-split-json` +show presence only; raw request/reason bodies are never copied to outputs, +notifications or summaries. This also applies before validation completes. +Manual/canary handoff keeps the existing `action-required` event/status and +uses the shared warning style with a safe instruction to review the deployment. +Cancellation/traffic-update outcomes appear as named result rows. + +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. All 21 invalid deployment settings +can expand under JSON Unicode escaping even when each projected value is bounded +to 256 characters. A worst-case malformed-Unicode test verifies a valid event over +16 KiB remains present, schema-valid and below 64 KiB with all input names. +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: 279 tests; 98.60% statements, 96.48% branches, 98.48% functions, 99.49% lines | +| Input definition parity with `action.yml` | Covered by candidate tests: 21 names, confidentiality/presence policy | +| Shared-schema input context and summary/status tests | PASS: 310 tests/12 files; 99.12% statements, 97.48% branches, 98.57% functions, 99.76% lines | +| Actual standalone bundle status/input/masking/summary matrix | PASS: 6 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: `98074f2e9ef8f821d1789a604fe0ba385fc9dbf8d2145cf5f5bfc4910115f8b4`. + +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 fd92b9d..0df4a62 100644 --- a/scripts/contracts.mjs +++ b/scripts/contracts.mjs @@ -8,12 +8,23 @@ import { } from "@commercekit-tools/notification-contract"; const require = createRequire(import.meta.url); const manifest = 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(manifest.private, true); + assert.match( + manifest.dependencies["@commercekit-tools/notification-contract"], + /^file:.+\.tgz$/u, + ); +} for (const name of [ "@commercekit-tools/notification-contract", "@commercekit-tools/ccv2-client", ]) { - assert.equal(manifest.dependencies[name], "0.0.3"); - assert.equal(require(`${name}/package.json`).version, "0.0.3"); + const candidate = + name === "@commercekit-tools/notification-contract" && candidateVersion; + if (!candidate) assert.equal(manifest.dependencies[name], "0.0.3"); + assert.equal(require(`${name}/package.json`).version, candidate || "0.0.3"); } assert.equal(schema.properties.schemaVersion.const, 1); for (const file of [ diff --git a/src/action.ts b/src/action.ts index 6703d9d..0b23664 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 { DeployClient } from "./client.js"; import { DeploymentApi, decisionPoint } 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,14 +26,19 @@ 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 api: DeploymentApi | 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; result.operation = input.operation; result.subscriptionCode = input.subscriptionCode; for (const key of [ @@ -216,30 +227,42 @@ export async function run( result.pollCount = api?.pollCount ?? 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 operation = result.operation; result = JSON.parse( JSON.stringify(result, (_key, value: unknown) => typeof value === "string" ? safe.text(value) : value, ), ) as Result; + result.outcome = outcome; + result.operation = operation; try { - await emit(core, result, safe, env); + Object.assign(result, inputContext(captured, validated, safe)); } catch { - result = { - ...initialResult(), - durationMs: result.durationMs, - operation: result.operation, - 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.", + ); } + if (result.outcome === "action-required") + result.issues = [ + { + code: "deployment-action-required", + message: + "The deployment requires a further manual or canary decision. Review its current state before continuing.", + }, + ]; + const outputFailure = await emit(core, result, safe, env); + if (!["success", "action-required"].includes(result.outcome)) + core.setFailed(result.error?.message ?? "CCv2 deployment did not succeed."); + else if (outputFailure) + core.setFailed("Action result outputs could not be written."); + else + core.info( + result.actionRequired + ? "Deployment requires a further decision." + : "Deployment completed successfully.", + ); return result; } async function emit( @@ -248,11 +271,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({ operation: result.operation, "deployment-code": result.deploymentCode ?? "", @@ -268,33 +305,34 @@ async function emit( "duration-ms": String(result.durationMs), "result-json": json, "notification-event": eventJson, - })) - core.setOutput(name, value); - const rows = Object.entries(result).filter( - ([key, v]) => typeof v !== "object" && key !== "schemaVersion", - ); - if (result.error) rows.push(["Error", result.error.message]); - try { - core.summary.addRaw( - "

CCv2 Deploy

" + - 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 (!["success", "action-required"].includes(result.outcome)) - core.setFailed(result.error?.message ?? "CCv2 deployment did not succeed."); - else - core.info( - result.actionRequired - ? "Deployment requires a further decision." - : "Deployment completed successfully.", - ); + return outputFailure; } diff --git a/src/notification.ts b/src/notification.ts index 078baa7..8551616 100644 --- a/src/notification.ts +++ b/src/notification.ts @@ -23,7 +23,16 @@ export function context(env: NodeJS.ProcessEnv, safe: Sanitizer) { return ctx; } export function event(result: Result, env: NodeJS.ProcessEnv, safe: Sanitizer) { - const data: DeploymentEventData = {}; + const data: DeploymentEventData = { + ...(result.inputs + ? { + inputs: result.inputs, + inputsValidated: result.inputsValidated ?? false, + inputsTruncated: result.inputsTruncated ?? false, + } + : {}), + ...(result.issues ? { issues: result.issues } : {}), + }; for (const key of [ "subscriptionCode", "deploymentCode", diff --git a/src/reporting.ts b/src/reporting.ts new file mode 100644 index 0000000..8db23d6 --- /dev/null +++ b/src/reporting.ts @@ -0,0 +1,120 @@ +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: "operation" }, + { name: "token-endpoint", confidential: true }, + { name: "client-id", confidential: true }, + { name: "client-secret", confidential: true }, + { name: "resource", confidential: true }, + { name: "subscription-code" }, + { name: "deployment-code" }, + { name: "build-code" }, + { name: "environment-code" }, + { name: "database-update-mode" }, + { name: "strategy" }, + { name: "validate-deployment-modes" }, + { name: "green-decision" }, + { name: "decision-reason", display: "presence" }, + { name: "traffic-split-json", display: "presence" }, + { name: "rollback-database" }, + { name: "cancel-reason", display: "presence" }, + { name: "wait-for-completion" }, + { 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: { + operation: input.operation, + "subscription-code": input.subscriptionCode, + "deployment-code": input.deploymentCode ?? "", + "build-code": input.buildCode ?? "", + "environment-code": input.environmentCode ?? "", + "database-update-mode": input.databaseUpdateMode ?? "", + strategy: input.strategy ?? "", + "validate-deployment-modes": String(input.validateDeploymentModes), + "green-decision": input.greenDecision, + "decision-reason": input.decisionReason ?? "", + "traffic-split-json": input.trafficSplit ? "provided" : "", + "rollback-database": String(input.rollbackDatabase), + "cancel-reason": input.cancelReason ?? "", + "wait-for-completion": raw["wait-for-completion"] || "true", + "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 = [ + ["Operation", result.operation], + ["Deployment status", result.deploymentStatus], + ["Subscription", result.subscriptionCode], + ["Deployment code", result.deploymentCode], + ["Original deployment code", result.originalDeploymentCode], + ["Build code", result.buildCode], + ["Environment", result.environmentCode], + ["Database update", result.databaseUpdateMode], + ["Strategy", result.strategy], + ["Decision", result.decision], + ["Progress (%)", result.percentage], + ["Poll count", result.pollCount], + ["Duration (ms)", result.durationMs], + ["Action required", result.actionRequired], + ["Timed out", result.timedOut], + ["Cancellation requested", result.cancellation?.requested], + ["Rollback database", result.cancellation?.rollbackDatabase], + ["Traffic split updated", result.trafficSplit?.updated], + ] as const; + return renderActionSummary({ + title: "CCv2 Deploy", + 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 317bdf2..a8c4cb4 100644 --- a/src/result.ts +++ b/src/result.ts @@ -1,9 +1,10 @@ import type { DeploymentEvent, SafeNotificationError, + NotificationInputContext, } from "@commercekit-tools/notification-contract"; import type { Operation, Decision } from "./inputs.js"; -export interface Result { +export interface Result extends Partial { schemaVersion: 1; operation: Operation; outcome: Exclude; @@ -24,6 +25,7 @@ export interface Result { timedOut: boolean; cancellation?: { requested: boolean; rollbackDatabase: boolean }; trafficSplit?: { updated: boolean }; + issues?: SafeNotificationError[]; error?: Required; } export const initialResult = (): Result => ({ diff --git a/src/security.ts b/src/security.ts index eff8054..e3126f7 100644 --- a/src/security.ts +++ b/src/security.ts @@ -14,6 +14,9 @@ export class Sanitizer { this.mask(value); this.secrets.add(value); } + knownSecrets(): readonly string[] { + return [...this.secrets]; + } text(value: string, max = 1000): string { // Keep Deploy's plain-text/URL/JWT disclosure policy atop shared redaction. const text = redactJwtLikeTokens( diff --git a/tests/action-core.ts b/tests/action-core.ts new file mode 100644 index 0000000..8117097 --- /dev/null +++ b/tests/action-core.ts @@ -0,0 +1,26 @@ +import { vi } from "vitest"; +import type { Core } from "../src/action.js"; +import { raw } from "./fixtures.js"; +import { validateNotificationEvent } from "@commercekit-tools/notification-contract"; +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) => { + if (k === "notification-event" && v) + validateNotificationEvent(JSON.parse(v)); + 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 c95a66b..b3c11f9 100644 --- a/tests/action.test.ts +++ b/tests/action.test.ts @@ -2,33 +2,13 @@ import { validateNotificationEvent } from "@commercekit-tools/notification-contr const validateEvent = (value: unknown) => Boolean(validateNotificationEvent(value)); import { it, expect, vi } 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 { 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) => { - if (k === "notification-event") validateNotificationEvent(JSON.parse(v)); - 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 id = "synthetic-deploy"; const detail = { code: id, diff --git a/tests/reporting-bundle.test.ts b/tests/reporting-bundle.test.ts new file mode 100644 index 0000000..b5cdf6d --- /dev/null +++ b/tests/reporting-bundle.test.ts @@ -0,0 +1,138 @@ +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 = [ + ["DEPLOYED", "success", 0, "✅"], + ["FAIL", "failure", 1, "❌"], + ["UNDEPLOYED", "cancelled", 1, "⏹️"], + ["FUTURE", "internal-error", 1, "❌"], + ["handoff", "action-required", 0, "⚠️"], + ["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 deployment %s writes consistent masked event, outputs and job summary", + (status, expected, exit, icon) => { + const dir = mkdtempSync(join(tmpdir(), "ccv2-deploy-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});if(url.endsWith('/progress'))return Response.json({deploymentStatus:${JSON.stringify(status === "handoff" ? "DEPLOYING" : status)},percentage:90});if(url.endsWith('/decisions'))return Response.json({deploymentDecisions:[]});return Response.json({code:'synthetic.1',status:'DEPLOYING',strategy:${JSON.stringify(status === "handoff" ? "GREEN" : "ROLLING_UPDATE")},isCanaryAvailable:${status === "handoff"},canaryStatus:'STARTED',expireAtTimestamp:'2099-01-01T00:00:00Z'});};`, + ); + 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_BUILD-CODE": status === "invalid" ? "" : "synthetic-build", + "INPUT_ENVIRONMENT-CODE": "synthetic-env", + "INPUT_DATABASE-UPDATE-MODE": "NONE", + INPUT_STRATEGY: status === "handoff" ? "GREEN" : "ROLLING_UPDATE", + "INPUT_VALIDATE-DEPLOYMENT-MODES": "false", + "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.deployment.completed" && + event.eventType !== "ccv2.deployment.action-required" + ) + throw Error("Expected deployment 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 Deploy`); + 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..acad548 --- /dev/null +++ b/tests/reporting.test.ts @@ -0,0 +1,449 @@ +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 authentication = [ + "token-endpoint", + "client-id", + "client-secret", + "resource", +]; +const terminal = (status = "DEPLOYED") => [ + token, + { code: "synthetic.1" }, + { code: "synthetic.1" }, + { deploymentStatus: status }, + { code: "synthetic.1" }, +]; +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.deployment.completed" && + value.eventType !== "ccv2.deployment.action-required" + ) + throw Error("Expected deploy event."); + return value; +} +function rendered(c: ReturnType) { + return vi + .mocked(c.core.summary.addRaw) + .mock.calls.map(([text]) => text) + .join(""); +} + +describe("consistent deployment reporting", () => { + it("covers all declared Action inputs with confidential and presence-only policy", () => { + 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(21); + expect( + reporting.inputDefinitions + .filter((input) => input.confidential) + .map((input) => input.name), + ).toEqual(authentication); + expect( + reporting.inputDefinitions + .filter((input) => input.display === "presence") + .map((input) => input.name), + ).toEqual(["decision-reason", "traffic-split-json", "cancel-reason"]); + }); + it("reports normalized defaults, all fields and redaction markers through the shared schema", () => { + const { context, safe } = settings(); + expect(context.inputsValidated).toBe(true); + expect(context.inputsTruncated).toBe(false); + expect(context.inputs).toMatchObject({ + operation: "deploy", + "poll-interval-seconds": "60", + "timeout-minutes": "240", + "green-decision": "MANUAL", + "validate-deployment-modes": "true", + "rollback-database": "false", + "wait-for-completion": "true", + }); + 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(21); + const value = notification.event( + { ...initialResult(), outcome: "success", ...context }, + workflow, + safe, + ); + expect(parse(JSON.stringify(value)).data).toMatchObject(context); + }); + it.each(["deploy", "resume", "decide", "cancel"])( + "projects safe effective settings for %s", + (operation) => { + const values = { + ...raw, + operation, + "poll-interval-seconds": "20", + "timeout-minutes": "8", + ...(operation === "deploy" + ? {} + : { + "deployment-code": "synthetic-existing", + "build-code": "", + "environment-code": "", + "database-update-mode": "", + strategy: "", + }), + ...(operation === "decide" + ? { + "green-decision": "ACCEPT", + "decision-reason": "SYNTHETIC_PRIVATE_REASON", + } + : {}), + ...(operation === "cancel" + ? { "cancel-reason": "SYNTHETIC_PRIVATE_CANCEL" } + : {}), + }; + const { context } = settings(values); + expect(context.inputs).toMatchObject({ + operation, + "poll-interval-seconds": "20", + "timeout-minutes": "8", + }); + expect(JSON.stringify(context)).not.toContain("SYNTHETIC_PRIVATE_REASON"); + expect(JSON.stringify(context)).not.toContain("SYNTHETIC_PRIVATE_CANCEL"); + }, + ); + it("never reflects invalid structured input or free-text reason bodies", () => { + const values = { + ...raw, + "traffic-split-json": '{"password":"SYNTHETIC_PRIVATE_JSON"}', + "decision-reason": "SYNTHETIC_PRIVATE_REASON", + "cancel-reason": "SYNTHETIC_PRIVATE_CANCEL", + "api-base-url": + "https://username:password@example.invalid/private?token=private", + "environment-code": "x".repeat(1000), + }; + const { context } = settings(values, false); + expect(context.inputsValidated).toBe(false); + expect(context.inputsTruncated).toBe(true); + expect(context.inputs["environment-code"]!.length).toBeLessThanOrEqual(256); + for (const name of [ + "traffic-split-json", + "decision-reason", + "cancel-reason", + ]) + expect(context.inputs[name]).toBeTruthy(); + for (const marker of [ + "SYNTHETIC_PRIVATE_JSON", + "SYNTHETIC_PRIVATE_REASON", + "SYNTHETIC_PRIVATE_CANCEL", + "username", + "password", + "token=private", + ]) + expect(JSON.stringify(context)).not.toContain(marker); + }); + it("omits validated traffic request bodies even for safe canary configuration", () => { + const { context } = settings({ + ...raw, + strategy: "GREEN", + "green-decision": "PREPARE_CANARY", + "traffic-split-json": + '{"services":[{"code":"synthetic-private-service","percentage":20}]}', + }); + expect(context.inputsValidated).toBe(true); + expect(context.inputs["traffic-split-json"]).toBeTruthy(); + expect(JSON.stringify(context)).not.toContain("synthetic-private-service"); + }); + it.each([ + ["DEPLOYED", "success", "✅"], + ["FAIL", "failure", "❌"], + ["UNDEPLOYED", "cancelled", "⏹️"], + ["FUTURE", "internal-error", "❌"], + ])( + "uses shared status styling and complete input/result tables for %s", + async (status, outcome, icon) => { + const c = fakeCore({ "validate-deployment-modes": "false" }); + const result = await run(c.core, harness(terminal(status)).rt, workflow); + const value = parse(c.outputs["notification-event"]!); + expect(result.outcome).toBe(outcome); + expect(value.status).toBe(outcome); + expect(value.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 Deploy", + "Result", + "Inputs", + "Operation", + "Deployment status", + "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); + expect(c.core.summary.write).toHaveBeenCalledOnce(); + if (result.error) + expect(html).toContain(result.error.code.replaceAll("_", "\\_")); + }, + ); + it("renders manual/canary handoff as warning while preserving action-required semantics", async () => { + const c = fakeCore({ + "validate-deployment-modes": "false", + strategy: "GREEN", + }); + const detail = { + code: "synthetic.1", + status: "DEPLOYING", + strategy: "GREEN", + isCanaryAvailable: true, + canaryStatus: "STARTED", + expireAtTimestamp: "2099-01-01T00:00:00Z", + }; + const result = await run( + c.core, + harness([ + token, + { code: "synthetic.1" }, + detail, + { deploymentStatus: "DEPLOYING", percentage: 90 }, + detail, + { deploymentDecisions: [] }, + ]).rt, + workflow, + ); + const value = parse(c.outputs["notification-event"]!); + expect(result.outcome).toBe("action-required"); + expect(value.status).toBe("action-required"); + expect(value.data.issues?.[0]?.code).toBe("deployment-action-required"); + expect(rendered(c)).toContain("⚠️"); + expect(rendered(c)).toContain("deployment-action-required"); + expect(c.core.setFailed).not.toHaveBeenCalled(); + }); + it("captures/masks credentials first, reads once and reports invalid input before any API call", async () => { + const c = fakeCore({ "build-code": "" }); + const order: string[] = []; + vi.mocked(c.core.getInput).mockImplementation((name) => { + order.push(`read:${name}`); + return name === "build-code" ? "" : (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:operation"), + ); + expect( + vi.mocked(c.core.getInput).mock.calls.map(([name]) => name), + ).toHaveLength(21); + }); + it("escapes malicious text and masks secrets in every output/summary", async () => { + const c = fakeCore({ + "subscription-code": `&${raw["client-secret"]}`, + }); + await run(c.core, harness([]).rt); + expect(rendered(c)).not.toContain("