From 2bf3e402f99f2e83cec1a131deea0283e0e3276e Mon Sep 17 00:00:00 2001 From: Tigran Babloyan Date: Wed, 11 Nov 2026 11:18:18 +0400 Subject: [PATCH 1/2] feat(AF-1027): verification settings, timeline stage and samples UI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Environment modal gains a post-deployment verification section (HTTP and PromQL checks, client rules mirroring #1023/#1024). The deployment detail page shows a verification row, card with the config snapshot and samples, a timeline stage after the outcome, and a did-not-roll-back callout on a breach; the list tags the verification status. The request response now carries verification_snapshot (window, interval, threshold, check count — no check targets). New e2e spec drives a breach against WireMock. --- .../deploygov/api/DeploymentRequestView.java | 32 +- .../DeploymentVerificationSnapshotView.java | 18 + .../DefaultDeploymentRequestService.java | 17 +- .../web/DeploymentRequestResponse.java | 26 +- .../DefaultDeploymentRequestServiceTest.java | 43 +- .../internal/web/DeploygovWebModelsTest.java | 23 ++ docs/04-api-spec.md | 6 +- docs/06-frontend.md | 10 +- docs/18-deployment-governance.md | 13 +- e2e/docker-compose.e2e.yml | 3 + e2e/helpers/deployments.ts | 3 + e2e/tests/deployment-verification.spec.ts | 145 +++++++ frontend/src/api/deploymentRequests.test.ts | 16 + frontend/src/api/deploymentRequests.ts | 12 + .../PipelineEnvironmentsTab.test.tsx | 251 ++++++++++++ .../deployments/PipelineEnvironmentsTab.tsx | 381 +++++++++++++++++- .../deployments/verificationForm.test.ts | 175 ++++++++ .../deployments/verificationForm.ts | 191 +++++++++ frontend/src/locales/de.json | 72 +++- frontend/src/locales/en.json | 72 +++- frontend/src/locales/es.json | 72 +++- frontend/src/locales/fr.json | 72 +++- frontend/src/locales/hy.json | 72 +++- frontend/src/locales/ru.json | 72 +++- frontend/src/locales/zh-CN.json | 72 +++- .../deployments/DeploymentDetailPage.test.tsx | 117 ++++++ .../deployments/DeploymentDetailPage.tsx | 173 +++++++- .../deployments/DeploymentListPage.test.tsx | 34 ++ .../pages/deployments/DeploymentListPage.tsx | 41 +- .../buildDeploymentTimelineStages.test.ts | 73 ++++ .../buildDeploymentTimelineStages.ts | 23 +- frontend/src/types/api.ts | 96 +++++ .../src/utils/__tests__/enumLabels.test.ts | 22 + .../src/utils/__tests__/statusColors.test.ts | 15 +- frontend/src/utils/enumLabels.ts | 32 ++ frontend/src/utils/statusColors.ts | 16 + frontend/vite.config.ts | 1 + help-corpus/manifest.json | 6 +- 38 files changed, 2467 insertions(+), 51 deletions(-) create mode 100644 backend/src/main/java/com/bablsoft/accessflow/deploygov/api/DeploymentVerificationSnapshotView.java create mode 100644 e2e/tests/deployment-verification.spec.ts create mode 100644 frontend/src/components/deployments/verificationForm.test.ts create mode 100644 frontend/src/components/deployments/verificationForm.ts diff --git a/backend/src/main/java/com/bablsoft/accessflow/deploygov/api/DeploymentRequestView.java b/backend/src/main/java/com/bablsoft/accessflow/deploygov/api/DeploymentRequestView.java index cfe5e1bc4..de9eadc24 100644 --- a/backend/src/main/java/com/bablsoft/accessflow/deploygov/api/DeploymentRequestView.java +++ b/backend/src/main/java/com/bablsoft/accessflow/deploygov/api/DeploymentRequestView.java @@ -56,7 +56,35 @@ public record DeploymentRequestView( VerificationStatus verificationStatus, Instant verificationStartedAt, Instant verificationFinishedAt, - String verificationDetail) { + String verificationDetail, + /** The config snapshot the window was opened with (#1027); null when never verified. */ + DeploymentVerificationSnapshotView verificationSnapshot) { + + /** Backward-compatible constructor without the #1027 verification snapshot. */ + public DeploymentRequestView(UUID id, UUID pipelineId, String pipelineName, PipelineProvider provider, + UUID environmentId, String environmentName, UUID submittedBy, + String submittedByEmail, String version, String commitSha, + String artifactRef, String runUrl, String externalRunId, + Map metadata, QueryStatus status, + SubmissionReason submissionReason, String justification, + UUID aiAnalysisId, RiskLevel aiRiskLevel, Integer aiRiskScore, + String aiSummary, int requiredApprovals, Instant scheduledFor, + DeploymentOutcome outcome, Instant outcomeReportedAt, + String outcomeDetail, Instant createdAt, + List decisions, UUID onBehalfOfUserId, + String onBehalfOfEmail, boolean changeTicketRequired, + DeploymentTicketView changeTicket, + VerificationStatus verificationStatus, + Instant verificationStartedAt, Instant verificationFinishedAt, + String verificationDetail) { + this(id, pipelineId, pipelineName, provider, environmentId, environmentName, submittedBy, + submittedByEmail, version, commitSha, artifactRef, runUrl, externalRunId, metadata, + status, submissionReason, justification, aiAnalysisId, aiRiskLevel, aiRiskScore, + aiSummary, requiredApprovals, scheduledFor, outcome, outcomeReportedAt, outcomeDetail, + createdAt, decisions, onBehalfOfUserId, onBehalfOfEmail, changeTicketRequired, + changeTicket, verificationStatus, verificationStartedAt, verificationFinishedAt, + verificationDetail, null); + } /** Backward-compatible constructor without the #874 on-behalf-of principal. */ public DeploymentRequestView(UUID id, UUID pipelineId, String pipelineName, PipelineProvider provider, @@ -75,7 +103,7 @@ public DeploymentRequestView(UUID id, UUID pipelineId, String pipelineName, Pipe status, submissionReason, justification, aiAnalysisId, aiRiskLevel, aiRiskScore, aiSummary, requiredApprovals, scheduledFor, outcome, outcomeReportedAt, outcomeDetail, createdAt, decisions, null, null, false, null, VerificationStatus.PENDING, null, null, - null); + null, null); } public DeploymentRequestView { diff --git a/backend/src/main/java/com/bablsoft/accessflow/deploygov/api/DeploymentVerificationSnapshotView.java b/backend/src/main/java/com/bablsoft/accessflow/deploygov/api/DeploymentVerificationSnapshotView.java new file mode 100644 index 000000000..44bba73e8 --- /dev/null +++ b/backend/src/main/java/com/bablsoft/accessflow/deploygov/api/DeploymentVerificationSnapshotView.java @@ -0,0 +1,18 @@ +package com.bablsoft.accessflow.deploygov.api; + +import java.time.Duration; + +/** + * The verification config a request was verified against (#1027), as snapshotted when its window + * opened. Deliberately carries no check URLs or queries: the request detail is readable by its + * submitter and reviewers, while an environment's config is admin-only. + */ +public record DeploymentVerificationSnapshotView(Duration window, Duration sampleInterval, + int failureThreshold, int checkCount) { + + public static DeploymentVerificationSnapshotView of(DeploymentVerificationConfig config) { + return config == null ? null + : new DeploymentVerificationSnapshotView(config.window(), config.sampleInterval(), + config.failureThreshold(), config.checks().size()); + } +} diff --git a/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestService.java b/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestService.java index bd1483720..da584e2aa 100644 --- a/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestService.java +++ b/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestService.java @@ -19,6 +19,7 @@ import com.bablsoft.accessflow.deploygov.api.DeploymentRequestSubmissionResult; import com.bablsoft.accessflow.deploygov.api.DeploymentRequestView; import com.bablsoft.accessflow.deploygov.api.DeploymentVerificationSampleView; +import com.bablsoft.accessflow.deploygov.api.DeploymentVerificationSnapshotView; import com.bablsoft.accessflow.deploygov.api.DeploymentReviewDecisionView; import com.bablsoft.accessflow.deploygov.api.DeploymentTicketView; import com.bablsoft.accessflow.deploygov.api.FreezeBehavior; @@ -37,6 +38,7 @@ import com.bablsoft.accessflow.deploygov.internal.persistence.repo.DeploymentReviewDecisionRepository; import com.bablsoft.accessflow.deploygov.internal.persistence.repo.DeploymentTicketRepository; import com.bablsoft.accessflow.deploygov.internal.persistence.repo.DeploymentVerificationRepository; +import com.bablsoft.accessflow.deploygov.internal.verification.DeploymentVerificationConfigCodec; import lombok.RequiredArgsConstructor; import org.springframework.context.ApplicationEventPublisher; import org.springframework.dao.DataIntegrityViolationException; @@ -88,6 +90,7 @@ public class DefaultDeploymentRequestService implements DeploymentRequestService private final ObjectMapper objectMapper; private final Clock clock; private final DeploymentVerificationRepository verificationRepository; + private final DeploymentVerificationConfigCodec verificationConfigCodec; @Override @Transactional @@ -435,7 +438,19 @@ private DeploymentRequestView toView(DeploymentRequestEntity entity, entity.getVerificationStatus(), entity.getVerificationStartedAt(), entity.getVerificationFinishedAt(), - entity.getVerificationDetail()); + entity.getVerificationDetail(), + readVerificationSnapshot(entity)); + } + + /** Fail-soft on read: an unreadable snapshot hides the card; the job already failed it closed. */ + private DeploymentVerificationSnapshotView readVerificationSnapshot( + DeploymentRequestEntity entity) { + try { + return DeploymentVerificationSnapshotView.of( + verificationConfigCodec.fromJson(entity.getVerificationConfig())); + } catch (DeploymentVerificationConfigCodec.VerificationConfigParseException ex) { + return null; + } } private Map readMetadata(String json) { diff --git a/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/web/DeploymentRequestResponse.java b/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/web/DeploymentRequestResponse.java index 74c48689f..7bf50eeee 100644 --- a/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/web/DeploymentRequestResponse.java +++ b/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/web/DeploymentRequestResponse.java @@ -5,9 +5,11 @@ import com.bablsoft.accessflow.core.api.SubmissionReason; import com.bablsoft.accessflow.deploygov.api.DeploymentOutcome; import com.bablsoft.accessflow.deploygov.api.DeploymentRequestView; +import com.bablsoft.accessflow.deploygov.api.DeploymentVerificationSnapshotView; import com.bablsoft.accessflow.deploygov.api.PipelineProvider; import com.bablsoft.accessflow.deploygov.api.VerificationStatus; +import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; @@ -54,7 +56,26 @@ public record DeploymentRequestResponse( VerificationStatus verificationStatus, Instant verificationStartedAt, Instant verificationFinishedAt, - String verificationDetail) { + String verificationDetail, + /** The config the window was opened with (#1027); null (omitted) when never verified. */ + VerificationSnapshot verificationSnapshot) { + + /** Window and interval as ISO-8601 strings; no check URLs or queries. */ + public record VerificationSnapshot(String window, String sampleInterval, int failureThreshold, + int checkCount) { + + static VerificationSnapshot from(DeploymentVerificationSnapshotView view) { + if (view == null) { + return null; + } + return new VerificationSnapshot(iso(view.window()), iso(view.sampleInterval()), + view.failureThreshold(), view.checkCount()); + } + + private static String iso(Duration duration) { + return duration == null ? null : duration.toString(); + } + } /** Every path but the detail read: reviewer eligibility is a detail-read concern, never computed here. */ static DeploymentRequestResponse from(DeploymentRequestView view) { @@ -75,6 +96,7 @@ static DeploymentRequestResponse from(DeploymentRequestView view, boolean canRev view.changeTicketRequired(), DeploymentChangeTicketResponse.from(view.changeTicket()), view.verificationStatus(), view.verificationStartedAt(), - view.verificationFinishedAt(), view.verificationDetail()); + view.verificationFinishedAt(), view.verificationDetail(), + VerificationSnapshot.from(view.verificationSnapshot())); } } diff --git a/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestServiceTest.java b/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestServiceTest.java index b6e86d842..579956379 100644 --- a/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestServiceTest.java +++ b/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestServiceTest.java @@ -13,6 +13,10 @@ import com.bablsoft.accessflow.core.api.UserQueryService; import com.bablsoft.accessflow.core.api.UserRoleType; import com.bablsoft.accessflow.core.api.UserView; +import com.bablsoft.accessflow.deploygov.api.DeploymentVerificationConfig; +import com.bablsoft.accessflow.deploygov.api.DeploymentVerificationSnapshotView; +import com.bablsoft.accessflow.deploygov.api.HttpHealthCheck; +import com.bablsoft.accessflow.deploygov.internal.verification.DeploymentVerificationConfigCodec; import com.bablsoft.accessflow.deploygov.api.DeploymentBreakGlassNotAllowedException; import com.bablsoft.accessflow.deploygov.api.DeploymentEnvironmentNotFoundException; import com.bablsoft.accessflow.deploygov.api.DeploymentPipelineNotFoundException; @@ -49,6 +53,7 @@ import tools.jackson.databind.json.JsonMapper; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.util.List; @@ -116,7 +121,8 @@ void setUp() { permissionResolver, freezeWindowEvaluator, stateService, auditWriter, aiAnalysisLookupService, userQueryService, eventPublisher, JsonMapper.builder().build(), CLOCK, - verificationRepository); + verificationRepository, + new DeploymentVerificationConfigCodec(JsonMapper.builder().build())); pipeline = pipeline(); environment = environment(); @@ -631,6 +637,41 @@ void getCarriesTheVerificationState() { assertThat(view.verificationStartedAt()).isEqualTo(started); assertThat(view.verificationFinishedAt()).isEqualTo(started.plusSeconds(60)); assertThat(view.verificationDetail()).isEqualTo("health: 1/1 failed samples"); + assertThat(view.verificationSnapshot()).isNull(); + } + + @Test + void getCarriesTheVerificationSnapshotWithoutCheckTargets() { + var entity = existing(QueryStatus.EXECUTED); + entity.setVerificationStatus(VerificationStatus.RUNNING); + entity.setVerificationConfig(new DeploymentVerificationConfigCodec(JsonMapper.builder().build()) + .toJson(new DeploymentVerificationConfig(Duration.ofMinutes(15), + Duration.ofSeconds(30), 3, List.of( + new HttpHealthCheck("health", "https://svc.example.com/healthz", 200, + null), + new HttpHealthCheck("ready", "https://svc.example.com/ready", 204, + "ok"))))); + when(requestRepository.findByIdAndOrganizationId(entity.getId(), ORG)) + .thenReturn(Optional.of(entity)); + + var snapshot = service.get(entity.getId(), ORG, SUBMITTER, Set.of()).verificationSnapshot(); + + assertThat(snapshot).isEqualTo(new DeploymentVerificationSnapshotView( + Duration.ofMinutes(15), Duration.ofSeconds(30), 3, 2)); + } + + @Test + void getHidesAnUnreadableVerificationSnapshot() { + var entity = existing(QueryStatus.FAILED); + entity.setVerificationStatus(VerificationStatus.FAILED); + entity.setVerificationConfig("{\"window\":\"PT1M\"}"); + when(requestRepository.findByIdAndOrganizationId(entity.getId(), ORG)) + .thenReturn(Optional.of(entity)); + + var view = service.get(entity.getId(), ORG, SUBMITTER, Set.of()); + + assertThat(view.verificationSnapshot()).isNull(); + assertThat(view.verificationStatus()).isEqualTo(VerificationStatus.FAILED); } @Test diff --git a/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/web/DeploygovWebModelsTest.java b/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/web/DeploygovWebModelsTest.java index e62955390..078d7a47a 100644 --- a/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/web/DeploygovWebModelsTest.java +++ b/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/web/DeploygovWebModelsTest.java @@ -5,6 +5,7 @@ import com.bablsoft.accessflow.core.api.QueryStatus; import com.bablsoft.accessflow.core.api.RiskLevel; import com.bablsoft.accessflow.core.api.SubmissionReason; +import com.bablsoft.accessflow.deploygov.api.DeploymentVerificationSnapshotView; import com.bablsoft.accessflow.deploygov.api.DeploymentEnvironmentView; import com.bablsoft.accessflow.deploygov.api.DeploymentFreezeWindowView; import com.bablsoft.accessflow.deploygov.api.DeploymentGateView; @@ -26,6 +27,7 @@ import tools.jackson.databind.json.JsonMapper; import tools.jackson.databind.PropertyNamingStrategies; +import java.time.Duration; import java.time.Instant; import java.time.LocalTime; import java.util.Map; @@ -538,6 +540,27 @@ void deploymentRequestViewDefaultsVerificationStatusAndResponseMapsIt() { SubmissionReason.USER_SUBMITTED, null, null, null, null, null, 1, null, null, null, null, Instant.now(), null, null, null, false, null, null, null, null, null); assertThat(defaulted.verificationStatus()).isEqualTo(VerificationStatus.PENDING); + assertThat(response.verificationSnapshot()).isNull(); + } + + @Test + void deploymentRequestResponseMapsTheVerificationSnapshotAsIsoDurations() { + var view = new DeploymentRequestView(UUID.randomUUID(), UUID.randomUUID(), "p", + PipelineProvider.GENERIC, UUID.randomUUID(), "prod", UUID.randomUUID(), null, + "1.0.0", null, null, null, null, null, QueryStatus.EXECUTED, + SubmissionReason.USER_SUBMITTED, null, null, null, null, null, 1, null, null, null, + null, Instant.now(), null, null, null, false, null, VerificationStatus.RUNNING, + null, null, null, new DeploymentVerificationSnapshotView(Duration.ofMinutes(15), + Duration.ofSeconds(30), 3, 2)); + + var snapshot = DeploymentRequestResponse.from(view).verificationSnapshot(); + + assertThat(snapshot).isEqualTo( + new DeploymentRequestResponse.VerificationSnapshot("PT15M", "PT30S", 3, 2)); + assertThat(DeploymentRequestResponse.VerificationSnapshot.from( + new DeploymentVerificationSnapshotView(null, null, 1, 1))) + .isEqualTo(new DeploymentRequestResponse.VerificationSnapshot(null, null, 1, 1)); + assertThat(DeploymentVerificationSnapshotView.of(null)).isNull(); } @Test diff --git a/docs/04-api-spec.md b/docs/04-api-spec.md index 3046979b6..563272fe5 100644 --- a/docs/04-api-spec.md +++ b/docs/04-api-spec.md @@ -9516,7 +9516,11 @@ back. Break-glass deployments are verified like any other. Request detail and list bodies carry `verification_status`, `verification_started_at`, `verification_finished_at` and `verification_detail` (breach detail reads `": / failed samples"`); the gate carries `verification_status` and -`verification_detail`. A breach reaches the submitter's browser through the existing +`verification_detail`. Since #1027 they also carry `verification_snapshot` — the config the +window was opened with, omitted until a window opens (and when the stored snapshot cannot be +read): `{ "window": "PT15M", "sample_interval": "PT30S", "failure_threshold": 3, +"check_count": 2 }`. It deliberately carries **no** check names, URLs or queries: the request is +readable by its submitter and reviewers, while an environment's config is admin-only. A breach reaches the submitter's browser through the existing `deployment.status_changed` WebSocket event. **Sample entry** (`GET /deployment-requests/{id}/verification-samples`): diff --git a/docs/06-frontend.md b/docs/06-frontend.md index 776e14c29..ad1cee8d7 100644 --- a/docs/06-frontend.md +++ b/docs/06-frontend.md @@ -926,22 +926,22 @@ id; `deploymentMetricKeys` follows the same rule for the metrics reads). Types i `DeploymentFreezeWindow`, `DeploymentRoutingPolicy`, `DeploymentEnvironmentVersion`, `DeploymentVersionHistoryEntry`, `DeploymentMetrics`, `DeploymentEnvironmentMetrics`, …; request status reuses `QueryStatus`, risk reuses `RiskLevel`, so `StatusPill`/`RiskPill` are reused unchanged). Enum labels `pipelineProviderLabel` / -`freezeBehaviorLabel` / `deploymentOutcomeLabel` / `leadTimeSourceLabel` / `deploymentRollbackReviewStatusLabel` / -`isoWeekdayLabel` in `src/utils/enumLabels.ts`; outcome/rollback colors and `driftColor` in +`freezeBehaviorLabel` / `deploymentOutcomeLabel` / `verificationStatusLabel` / `verificationCheckKindLabel` / `verificationComparatorLabel` / `leadTimeSourceLabel` / `deploymentRollbackReviewStatusLabel` / +`isoWeekdayLabel` in `src/utils/enumLabels.ts`; outcome/rollback/verification colors and `driftColor` in `src/utils/statusColors.ts`. All visible strings are `t()`-keyed under `deploygov.*` in every registered locale. | Route | Page | Notes | |-------|------|-------| -| `/deployments` | `DeploymentListPage` | Deployment requests (non-reviewers are server-scoped to their own submissions). Filter bar: status, pipeline, environment name, exact version; server pagination, forced `created_at DESC` (no sortable columns). The pipeline filter is built from the loaded rows unless the caller holds `DEPLOYMENT_PIPELINE_MANAGE` — a `DEPLOYMENT_REVIEW`-only user cannot call `GET /deployment-pipelines`. Row click → detail. A **Drift** column (#743) reads the per-pipeline matrix through one `useQueries` fan-out over the distinct `pipeline_id`s on the page (keys shared with the detail page, so revisits are cache hits; a 404 leaves those rows unbadged) and badges **only** the request that is currently live on its environment (`current_request_id === row.id`) — drift describes the environment now, so badging a superseded historical request would mislead. A **Ticket** column (#994) shows the linked change ticket through `ChangeTicketLink` (its key, linked to the ticket URL in a new tab when one is stored, plain text otherwise) with an approved / rejected decision tag, and `—` when the row has none. | -| `/deployments/:id` | `DeploymentDetailPage` | Metadata `Descriptions` (version, commit, artifact, CI-run link, external run id, submitter, reason, schedule), AI risk card (`RiskPill` + summary), approvals progress + decisions table, request `metadata` JSON block, and an `ApprovalTimeline` fed by the pure `buildDeploymentTimelineStages.ts` (submitted → AI → review → scheduled → release → outcome, incl. the `EXECUTED → FAILED` outcome flip). While `APPROVED`, the page calls `GET /deployment-gate?request_id=` for the **releasability banner** (releasable / held-by-freeze with reason / scheduled); a gate 404 hides the banner silently. The submitter can cancel via `Popconfirm` while cancellable. **Approve / Reject (#770)** sit in the same action row, driven solely by the response's `can_review` flag — the server's answer to the decision guard, because the review plan's approver rules are not in this payload and a `DEPLOYMENT_REVIEW`-only gate would offer a button the backend then refuses. They carry their own copy of the queue's comment modal (≤2000 chars — a third inline copy alongside `DeploymentReviewTabs`' two, matching how `ApiRequestDetailPage` duplicates its own queue's; there is no shared component) and invalidate the detail, list and review-queue keys on success. Where `can_review` is false no **decision** control renders at all — not a disabled one, unlike the queue — and the submitter of a `PENDING_REVIEW` request gets `deploygov.reviews.selfSubmissionHint` beside their Cancel button. A **Drift** row (#743) joins the pipeline matrix by environment: the drift chip when this request is the environment's live deploy, otherwise a muted "Superseded — {environment} now runs {version}"; a matrix 404 hides the row entirely, same treatment as the gate. A **Change ticket** card (#994) renders when the request's environment has `change_ticket_required` or a ticket is already linked: the `ChangeTicketLink`, the ticketing system label, and the ticket's status with its resolution when present — or "No change ticket linked yet". The releasability banner gains two states from the gate response: *waiting for the change ticket* (info) while no linked ticket is approved, and *the change ticket was rejected* (warning). | +| `/deployments` | `DeploymentListPage` | Deployment requests (non-reviewers are server-scoped to their own submissions). Filter bar: status, pipeline, environment name, exact version; server pagination, forced `created_at DESC` (no sortable columns). The pipeline filter is built from the loaded rows unless the caller holds `DEPLOYMENT_PIPELINE_MANAGE` — a `DEPLOYMENT_REVIEW`-only user cannot call `GET /deployment-pipelines`. Row click → detail. A **Drift** column (#743) reads the per-pipeline matrix through one `useQueries` fan-out over the distinct `pipeline_id`s on the page (keys shared with the detail page, so revisits are cache hits; a 404 leaves those rows unbadged) and badges **only** the request that is currently live on its environment (`current_request_id === row.id`) — drift describes the environment now, so badging a superseded historical request would mislead. A **Ticket** column (#994) shows the linked change ticket through `ChangeTicketLink` (its key, linked to the ticket URL in a new tab when one is stored, plain text otherwise) with an approved / rejected decision tag, and `—` when the row has none. The **Outcome** cell (#1027) adds a `verification ` tag once `verification_status` leaves `PENDING`, because a breach leaves `outcome = SUCCEEDED`. | +| `/deployments/:id` | `DeploymentDetailPage` | Metadata `Descriptions` (version, commit, artifact, CI-run link, external run id, submitter, reason, schedule), AI risk card (`RiskPill` + summary), approvals progress + decisions table, request `metadata` JSON block, and an `ApprovalTimeline` fed by the pure `buildDeploymentTimelineStages.ts` (submitted → AI → review → scheduled → release → outcome, incl. the `EXECUTED → FAILED` outcome flip). While `APPROVED`, the page calls `GET /deployment-gate?request_id=` for the **releasability banner** (releasable / held-by-freeze with reason / scheduled); a gate 404 hides the banner silently. The submitter can cancel via `Popconfirm` while cancellable. **Approve / Reject (#770)** sit in the same action row, driven solely by the response's `can_review` flag — the server's answer to the decision guard, because the review plan's approver rules are not in this payload and a `DEPLOYMENT_REVIEW`-only gate would offer a button the backend then refuses. They carry their own copy of the queue's comment modal (≤2000 chars — a third inline copy alongside `DeploymentReviewTabs`' two, matching how `ApiRequestDetailPage` duplicates its own queue's; there is no shared component) and invalidate the detail, list and review-queue keys on success. Where `can_review` is false no **decision** control renders at all — not a disabled one, unlike the queue — and the submitter of a `PENDING_REVIEW` request gets `deploygov.reviews.selfSubmissionHint` beside their Cancel button. A **Drift** row (#743) joins the pipeline matrix by environment: the drift chip when this request is the environment's live deploy, otherwise a muted "Superseded — {environment} now runs {version}"; a matrix 404 hides the row entirely, same treatment as the gate. A **Change ticket** card (#994) renders when the request's environment has `change_ticket_required` or a ticket is already linked: the `ChangeTicketLink`, the ticketing system label, and the ticket's status with its resolution when present — or "No change ticket linked yet". The releasability banner gains two states from the gate response: *waiting for the change ticket* (info) while no linked ticket is approved, and *the change ticket was rejected* (warning). **Post-deployment verification (#1027):** once `verification_status` leaves `PENDING`, a *Verification* row (status tag, beside drift — the matrix's unchanged "current" says nothing about health), a *Verification* card (the request's `verification_snapshot` window / interval / threshold, started / finished, detail, and the samples table from `GET /deployment-requests/{id}/verification-samples` under `deploymentKeys.verification(id)`, a child of the detail key) and a timeline stage after the outcome stage. The detail query and the samples query both refetch every 10 s only while `RUNNING`, because a breach pushes no WebSocket event to non-submitters. `FAILED` adds an error callout — "verification failed — the release is still running … AccessFlow did not roll back" — and the release stage keeps reading as released (`executionFailed` is `FAILED` with no outcome only). | | `/deployment-reviews` | *redirect* → `/reviews?tab=deployments` (or `?tab=rollbacks`) | Since #772 the two `DEPLOYMENT_REVIEW`-gated queues are tabs of the unified review hub (`pages/deployments/DeploymentReviewTabs.tsx`). **Deployments** (`PendingDeploymentsTab`): queue rows (pipeline/environment/version/risk/approvals/schedule) with approve/reject via a shared comment modal (≤2000 chars); own submissions render disabled buttons with a tooltip (self-approval is also blocked server-side with 409). **Rollbacks** (`RollbackReviewsTab`, `?tab=rollbacks`): the mandatory post-rollback acknowledgements — status filter, outcome detail, acknowledge with optional comment (idempotent; self-ack 409), link to the deployment. The legacy URL (with or without `?tab=rollbacks`) redirects into the matching tab. | | `/deployment-versions` | `DeploymentVersionsPage` | Org-wide version matrix (#743) — one row per environment deployed at least once: pipeline (linking to the per-pipeline matrix), environment + tag chips, current/previous version, deployed-at, last outcome + rollback badge, drift badge. Filters: pipeline, tag, environment name, and a drift tri-state (`Any` / `Behind latest only` / `Up to date only` → `drifted` `undefined`/`true`/`false` — the "up to date" case is why the api module guards on `typeof … === 'boolean'` rather than truthiness). Guarded any-of `DEPLOYMENT_PIPELINE_MANAGE` / `DEPLOYMENT_REVIEW` / `QUERY_ADMIN`, mirroring the controller's `hasAnyAuthority`. Tag options come from the loaded rows, so the list collapses to the selected tag until cleared (the selection is pinned so it cannot vanish from its own `Select`). Empty with no filters ⇒ `EmptyState`; empty with filters ⇒ the table's `emptyFiltered` text. | | `/deployment-versions/:pipelineId` | `PipelineVersionsPage` | The per-pipeline matrix as a standalone route (#743), **deliberately unguarded** — the server answers 404-never-403, which is what gives a `can_trigger`-only user (who cannot reach the admin settings page, and cannot call `GET /deployment-pipelines` to pick from) a reachable surface. Entry points: the pipeline column on `/deployment-versions`, and a "Version matrix" button beside the pipeline filter on `/deployments`. Wraps the same `PipelineVersionsTab`; a rejected matrix read renders the not-found `EmptyState`. | | `/deployment-metrics` | `DeploymentMetricsPage` | DORA + approval-SLA metrics (#987) over the #984 read API — the page never derives a metric, it only formats (`deploymentMetricsFilters.ts`: presets → `[from, to)` UTC-day windows via `trendsFiltersForRange`, a custom `RangePicker` capped at 366 days like the backend, seconds → `formatDurationCompact`, rates → `Intl` percent, missing values → `—`). Body is the shared `components/deployments/DeploymentMetricsPanel`: `MetricTile` row (frequency, lead time p50/p95 with the `lead_time.source` caption, change failure rate with the `unreported` caveat, time to restore + open incidents, approval latency, timeout rate, break-glass count), a Bklit `AreaChart` of `daily` (deployments / failed / rolled back), a `RingChart` of failed + rolled back over executed with the rate in `RingCenter`, and the per-environment breakdown table from `GET /deployment-metrics/environments` (pipeline links to `/deployment-versions/:pipelineId`). Filters are `Select`s, never `Segmented`: period, environment (options from the breakdown, read without the environment filter so they do not collapse; the table rows are narrowed in memory), and a pipeline picker only for `DEPLOYMENT_PIPELINE_MANAGE` (`GET /deployment-pipelines` is admin-only). Empty when `deployment_frequency.total === 0`. Guarded any-of `DEPLOYMENT_PIPELINE_MANAGE` / `DEPLOYMENT_REVIEW` / `QUERY_ADMIN`. | | `/deployment-metrics/:pipelineId` | `PipelineMetricsPage` | The same panel fixed to one pipeline (#987), **deliberately unguarded** like `PipelineVersionsPage` — the per-pipeline endpoint is 404-never-403 and open to `can_trigger`. Reached from the "Metrics" button beside "Version matrix" on `/deployments`; environment options come from the pipeline's version matrix, and there is no breakdown table (that endpoint needs a functional permission). The pipeline settings page carries the same panel as its *Metrics* tab (`?tab=metrics`). | | `/admin/deployment-pipelines` | `DeploymentPipelinesPage` | `DEPLOYMENT_PIPELINE_MANAGE`-gated CRUD list (name, copyable id, provider label, repository, AI toggle, active tag) + create modal (name 3–255, provider, repository URL ≤2048, project ref ≤512, review plan, AI toggle + AI config — validation parity with `CreateDeploymentPipelineRequest`). Create navigates straight into settings. | -| `/admin/deployment-pipelines/:id` | `DeploymentPipelineSettingsPage` | The header subtitle carries the provider label plus the pipeline's full id as a `PipelineIdCopy` (#771) — the UUID every CI integration is configured with, previously readable only out of the address bar or the CI snippet. Tabs: **General** (edit form, `clear_review_plan`/`clear_ai_config` on unset, active switch); **Environments** (`PipelineEnvironmentsTab` — ordered list, per-env `tags` (a `Select mode="tags"` with parity validation against `@Size(max=10)` / element `@Size(max=32)`; both mutations always send an array, never null, because the server reads null as "leave unchanged"), `require_review`/`required_approvals`/review-plan overrides/`allow_break_glass`, and a **Requires change ticket** switch with a matching table column for `change_ticket_required` (#994); since #877 the existing **Order** field gains a `{ type: 'number', min: 0 }` rule (parity with `@Min(0)`), is `required` in edit mode (the update path reads null as "leave unchanged", so a cleared value must not silently keep the old position) and takes its create prefill from the pure `environmentLadder.ts` (`max + 1`, `0` when empty — never the row count, which the unique `(pipeline, sort_order)` constraint would refuse), and a new **Database** `Select` over `listDatasources` is sent as `datasource_id` + `clear_datasource` (the `clear_review_plan` shape) and rendered as a table column that falls back to the raw id for a datasource deleted since binding); **Versions** (`PipelineVersionsTab` — the unpaginated per-pipeline matrix in server order, including never-deployed environments as `—` + a "Never deployed" chip, with a per-environment `EnvironmentHistoryDrawer`); **Metrics** (`DeploymentMetricsPanel` fixed to this pipeline, #987 — tiles and charts, no breakdown table); **Permissions** (`PipelinePermissionsTab` — user + group grant tables mirroring the connector-permission UI, capabilities `can_trigger`/`can_break_glass`/`expires_at`); **Freeze windows** (`PipelineFreezeWindowsTab` — the global list client-filtered to this pipeline + org-global rows ("Global" badge); one-off vs weekly-recurring editor with ISO-weekday multi-select, `HH:mm` time pickers, an IANA timezone select from `Intl.supportedValuesOf('timeZone')`, and a CSS-grid week-strip visualisation from the pure `freezeWindowCalendar.ts`); **Routing policies** (`PipelineRoutingPoliciesTab` — flat typed conditions (environments/providers/min-risk/version globs/day+time window), `required_approvals` required for `REQUIRE_APPROVALS`/`ESCALATE` and hidden for `AUTO_*`, priority conflicts surfaced from the 409); **Simulate** (`PipelineSimulateTab`, #1066 — the deployment decision trace at an optional hypothetical instant `at`, with the gate's `releasable` verdict in a banner above the shared `DecisionTraceView`); **CI setup** (`CiSnippetPanel` — copyable GitHub Actions / GitLab CI / Azure Pipelines / curl snippets from `ci-templates/`, pipeline id and origin pre-filled). The nine-tab strip is synced to `?tab=` (unknown values fall back to `general`), which makes a tab linkable and the e2e deterministic on an overflowed strip. Pure form logic lives in `freezeWindowForm.ts` / `deploymentRoutingPolicyForm.ts` / `versionMatrix.ts` / `environmentLadder.ts` (coverage-listed). | +| `/admin/deployment-pipelines/:id` | `DeploymentPipelineSettingsPage` | The header subtitle carries the provider label plus the pipeline's full id as a `PipelineIdCopy` (#771) — the UUID every CI integration is configured with, previously readable only out of the address bar or the CI snippet. Tabs: **General** (edit form, `clear_review_plan`/`clear_ai_config` on unset, active switch); **Environments** (`PipelineEnvironmentsTab` — ordered list, per-env `tags` (a `Select mode="tags"` with parity validation against `@Size(max=10)` / element `@Size(max=32)`; both mutations always send an array, never null, because the server reads null as "leave unchanged"), `require_review`/`required_approvals`/review-plan overrides/`allow_break_glass`, and a **Requires change ticket** switch with a matching table column for `change_ticket_required` (#994); a **Post-deployment verification** section (#1027) — a switch revealing window / interval / threshold `InputNumber`s and a `Form.List` of up to ten checks whose type `Select` swaps HTTP fields (URL, expected status, body contains) for PromQL ones (Prometheus URL, query, comparator, threshold, no-data switch); form values ⇄ wire (minutes ⇄ ISO-8601, the other kind's fields dropped) and the client rules live in the pure `verificationForm.ts`; off ⇒ `verification: null` on create and `clear_verification: true` on update; a *Verification* column shows the check count; since #877 the existing **Order** field gains a `{ type: 'number', min: 0 }` rule (parity with `@Min(0)`), is `required` in edit mode (the update path reads null as "leave unchanged", so a cleared value must not silently keep the old position) and takes its create prefill from the pure `environmentLadder.ts` (`max + 1`, `0` when empty — never the row count, which the unique `(pipeline, sort_order)` constraint would refuse), and a new **Database** `Select` over `listDatasources` is sent as `datasource_id` + `clear_datasource` (the `clear_review_plan` shape) and rendered as a table column that falls back to the raw id for a datasource deleted since binding); **Versions** (`PipelineVersionsTab` — the unpaginated per-pipeline matrix in server order, including never-deployed environments as `—` + a "Never deployed" chip, with a per-environment `EnvironmentHistoryDrawer`); **Metrics** (`DeploymentMetricsPanel` fixed to this pipeline, #987 — tiles and charts, no breakdown table); **Permissions** (`PipelinePermissionsTab` — user + group grant tables mirroring the connector-permission UI, capabilities `can_trigger`/`can_break_glass`/`expires_at`); **Freeze windows** (`PipelineFreezeWindowsTab` — the global list client-filtered to this pipeline + org-global rows ("Global" badge); one-off vs weekly-recurring editor with ISO-weekday multi-select, `HH:mm` time pickers, an IANA timezone select from `Intl.supportedValuesOf('timeZone')`, and a CSS-grid week-strip visualisation from the pure `freezeWindowCalendar.ts`); **Routing policies** (`PipelineRoutingPoliciesTab` — flat typed conditions (environments/providers/min-risk/version globs/day+time window), `required_approvals` required for `REQUIRE_APPROVALS`/`ESCALATE` and hidden for `AUTO_*`, priority conflicts surfaced from the 409); **Simulate** (`PipelineSimulateTab`, #1066 — the deployment decision trace at an optional hypothetical instant `at`, with the gate's `releasable` verdict in a banner above the shared `DecisionTraceView`); **CI setup** (`CiSnippetPanel` — copyable GitHub Actions / GitLab CI / Azure Pipelines / curl snippets from `ci-templates/`, pipeline id and origin pre-filled). The nine-tab strip is synced to `?tab=` (unknown values fall back to `general`), which makes a tab linkable and the e2e deterministic on an overflowed strip. Pure form logic lives in `freezeWindowForm.ts` / `deploymentRoutingPolicyForm.ts` / `versionMatrix.ts` / `environmentLadder.ts` / `verificationForm.ts` (coverage-listed). | Live refresh: the backend pushes `deployment.status_changed` to the **submitter** on every transition; `websocketManager.invokeDefault` invalidates the deployment detail (incl. its gate diff --git a/docs/18-deployment-governance.md b/docs/18-deployment-governance.md index 584434c84..8a61b2524 100644 --- a/docs/18-deployment-governance.md +++ b/docs/18-deployment-governance.md @@ -183,7 +183,18 @@ hold a snapshot of the config and the verdict, and the `deployment_verifications - **Save-time rules.** A config is rejected with `422 DEPLOYMENT_VERIFICATION_INVALID` when its window is outside 1 minute–24 hours, its interval outside 30 seconds–window, its failure threshold one the window cannot reach, two checks share a name, or a URL is refused or does not - resolve. Column detail is in + resolve. +- **In the web UI (#1027).** The environment modal on the pipeline settings page has a + *Post-deployment verification* section: a switch that reveals the window, interval and failure + threshold and a list of checks, each with a type `Select` that swaps between the HTTP and the + PromQL fields. The form mirrors every rule above that needs no network; host policy is only + known server-side and comes back as the 422's `detail`. Turning the switch off sends + `clear_verification: true`. The deployment detail page adds a *Verification* stage to the + timeline after the outcome stage (hidden while `PENDING`), a *Verification* row beside drift, and + a card with the request's `verification_snapshot`, its timestamps and the samples table — polled + every 10 seconds while `RUNNING`. A breach renders as "verification failed — the release is still + running" and says AccessFlow did not roll back; the release stage keeps reading as released. + The deployments list shows the verification status as a second tag in the outcome cell. Column detail is in [03-data-model.md](03-data-model.md#deployment_environments) (`deployment_environments`, `deployment_requests`, `deployment_verifications`). diff --git a/e2e/docker-compose.e2e.yml b/e2e/docker-compose.e2e.yml index 3a524eb31..2f777e3cc 100644 --- a/e2e/docker-compose.e2e.yml +++ b/e2e/docker-compose.e2e.yml @@ -113,6 +113,9 @@ services: # Keep the release update check (#836) off in CI: no egress to accessflow.io, and a # deterministic `status: UNKNOWN` for update-status.spec.ts. ACCESSFLOW_UPDATES_ENABLED: "false" + # Sample running post-deployment verifications every 5 s instead of 30 s (#1027), so + # deployment-verification.spec.ts sees its breach well inside the spec budget. + ACCESSFLOW_DEPLOYGOV_VERIFICATION_CHECK: PT5S # Parallel Playwright workers + the pg_sleep statement-timeout specs exhaust Hikari's default # 10-connection app pool, cascading into login 500s and hook timeouts. Postgres allows 100. SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE: "25" diff --git a/e2e/helpers/deployments.ts b/e2e/helpers/deployments.ts index 99b48208d..c3a0bbe11 100644 --- a/e2e/helpers/deployments.ts +++ b/e2e/helpers/deployments.ts @@ -59,6 +59,8 @@ export async function createDeploymentEnvironmentViaApi( datasourceId?: string; /** Releases wait for an approved ServiceNow / Jira change ticket (#990). */ changeTicketRequired?: boolean; + /** Post-deployment verification config (#1023), snake_case wire shape. */ + verification?: Record; }, ): Promise { const res = await request.post( @@ -76,6 +78,7 @@ export async function createDeploymentEnvironmentViaApi( ...(options.changeTicketRequired === undefined ? {} : { change_ticket_required: options.changeTicketRequired }), + ...(options.verification === undefined ? {} : { verification: options.verification }), }, }, ); diff --git a/e2e/tests/deployment-verification.spec.ts b/e2e/tests/deployment-verification.spec.ts new file mode 100644 index 000000000..ad2cfdb20 --- /dev/null +++ b/e2e/tests/deployment-verification.spec.ts @@ -0,0 +1,145 @@ +import { expect, test } from '@playwright/test'; +import { loginViaApi } from '../helpers/datasources'; +import { + confirmDeploymentExecutionViaApi, + createDeploymentEnvironmentViaApi, + createDeploymentPipelineViaApi, + deleteDeploymentPipelineViaApi, + reportDeploymentOutcomeViaApi, + triggerDeploymentViaApi, + waitForDeploymentStatus, + type CreatedDeploymentPipeline, +} from '../helpers/deployments'; +import { login } from '../helpers/login'; +import { activeTabPanel, clickTab, findRowAcrossPages } from '../helpers/ui'; + +const ADMIN_EMAIL = 'e2e@accessflow.test'; +const ADMIN_PASSWORD = 'E2ePassword!123'; + +// WireMock (the mock-ai service) resolves from the backend container to a private address — +// allowed by the outbound policy — and answers an unmapped path with 404, so every sample of this +// check fails against `expected_status: 200`. An unresolvable host would be refused at save time. +const FAILING_HEALTH_URL = 'http://mock-ai:8080/verification-health'; + +// The backend samples every 5 s in the e2e stack (ACCESSFLOW_DEPLOYGOV_VERIFICATION_CHECK). +test.describe.configure({ timeout: 120_000 }); + +test.describe.serial('post-deployment verification (#1027)', () => { + const stamp = Date.now(); + let adminToken = ''; + let pipeline: CreatedDeploymentPipeline | null = null; + + test.beforeAll(async ({ request }) => { + adminToken = await loginViaApi(request, ADMIN_EMAIL, ADMIN_PASSWORD); + // AI and review off: every trigger lands straight in APPROVED, so no second user is needed. + pipeline = await createDeploymentPipelineViaApi(request, adminToken, { + name: `e2e-verification-1027-${stamp}`, + provider: 'GENERIC', + aiAnalysisEnabled: false, + }); + }); + + test.afterAll(async ({ request }) => { + if (pipeline) await deleteDeploymentPipelineViaApi(request, adminToken, pipeline.id); + }); + + test('an admin adds an HTTP check to an environment and it round-trips', async ({ page }) => { + await login(page, ADMIN_EMAIL, ADMIN_PASSWORD); + await page.goto(`/admin/deployment-pipelines/${pipeline!.id}`); + await expect(page.getByRole('heading', { name: pipeline!.name })).toBeVisible({ + timeout: 15_000, + }); + + await clickTab(page, 'Environments'); + const envPanel = activeTabPanel(page); + await envPanel.getByRole('button', { name: 'Add environment' }).click(); + const dialog = page.getByRole('dialog').filter({ hasText: 'Add environment' }); + await expect(dialog).toBeVisible(); + const nameInput = dialog.getByLabel('Name', { exact: true }); + await nameInput.fill('canary'); + await expect(nameInput).toHaveValue('canary'); + + await dialog.getByRole('switch', { name: 'Verify after release' }).click(); + await dialog.getByLabel('Check name').fill('health'); + await dialog.getByLabel('Health URL').fill(FAILING_HEALTH_URL); + await dialog.getByLabel('Body contains (optional)').fill('ok'); + + const saved = page.waitForResponse( + (r) => + r.request().method() === 'POST' && + new URL(r.url()).pathname.endsWith(`/deployment-pipelines/${pipeline!.id}/environments`), + { timeout: 15_000 }, + ); + await dialog.getByRole('button', { name: 'Save' }).click(); + const response = await saved; + expect(response.status(), await response.text()).toBe(201); + const body = (await response.json()) as { + verification?: { window: string; checks: { name: string; url?: string }[] }; + }; + expect(body.verification?.window).toBe('PT15M'); + expect(body.verification?.checks[0]).toMatchObject({ name: 'health', url: FAILING_HEALTH_URL }); + + const row = envPanel.locator('.ant-table-row', { hasText: 'canary' }); + await expect(row).toContainText('Checks: 1'); + + await row.getByRole('button', { name: 'Edit' }).click(); + const editDialog = page.getByRole('dialog').filter({ hasText: 'Edit environment' }); + await expect(editDialog.getByLabel('Name', { exact: true })).toHaveValue('canary'); + await expect(editDialog.getByRole('switch', { name: 'Verify after release' })).toBeChecked(); + await expect(editDialog.getByLabel('Check name')).toHaveValue('health'); + await expect(editDialog.getByLabel('Health URL')).toHaveValue(FAILING_HEALTH_URL); + await expect(editDialog.getByLabel('Body contains (optional)')).toHaveValue('ok'); + await editDialog.getByRole('button', { name: 'Cancel' }).click(); + }); + + test('a breached verification shows as failed, never as a rollback', async ({ + page, + request, + }) => { + const environment = `verify-${stamp}`; + await createDeploymentEnvironmentViaApi(request, adminToken, pipeline!.id, { + name: environment, + requireReview: false, + verification: { + window: 'PT1M', + sample_interval: 'PT30S', + failure_threshold: 1, + checks: [{ kind: 'HTTP_HEALTH', name: 'health', url: FAILING_HEALTH_URL }], + }, + }); + const triggered = await triggerDeploymentViaApi(request, adminToken, { + pipelineId: pipeline!.id, + environment, + version: `9.9.${stamp % 1000}`, + }); + await waitForDeploymentStatus(request, adminToken, triggered.id, 'APPROVED'); + await confirmDeploymentExecutionViaApi(request, adminToken, triggered.id); + const reported = await reportDeploymentOutcomeViaApi( + request, + adminToken, + triggered.id, + 'SUCCEEDED', + ); + expect(reported.ok, `outcome rejected: ${reported.error}`).toBe(true); + + await login(page, ADMIN_EMAIL, ADMIN_PASSWORD); + await page.goto(`/deployments/${triggered.id}`); + + // The page polls while RUNNING; the first failed sample breaches a threshold of 1. + await expect( + page.getByText('Verification failed — the release is still running'), + ).toBeVisible({ timeout: 60_000 }); + await expect(page.getByText(/AccessFlow did not roll back/)).toBeVisible(); + const samples = page.getByRole('row').filter({ hasText: 'health' }).filter({ hasText: '404' }); + await expect(samples.first()).toBeVisible({ timeout: 15_000 }); + await expect(page.getByText('health: 1/1 failed samples').first()).toBeVisible(); + + await page.goto('/deployments'); + const listRow = page.getByRole('row').filter({ hasText: pipeline!.name }).filter({ + hasText: environment, + }); + await findRowAcrossPages(page, listRow); + await expect(listRow).toContainText('succeeded'); + await expect(listRow).toContainText('verification failed'); + }); +}); diff --git a/frontend/src/api/deploymentRequests.test.ts b/frontend/src/api/deploymentRequests.test.ts index 3a573dfd7..6e506dcdf 100644 --- a/frontend/src/api/deploymentRequests.test.ts +++ b/frontend/src/api/deploymentRequests.test.ts @@ -36,6 +36,12 @@ describe('api/deploymentRequests', () => { ]); expect(deploymentKeys.detail('d-1')).toEqual(['deployments', 'detail', 'd-1']); expect(deploymentKeys.gate('d-1')).toEqual(['deployments', 'detail', 'd-1', 'gate']); + expect(deploymentKeys.verification('d-1')).toEqual([ + 'deployments', + 'detail', + 'd-1', + 'verification', + ]); }); it('lists deployment requests with every filter', async () => { @@ -96,4 +102,14 @@ describe('api/deploymentRequests', () => { }); expect(gate.releasable).toBe(true); }); + + it('fetches the verification samples of a request', async () => { + get.mockResolvedValue({ + data: [{ id: 's-1', check_name: 'health', passed: false, sampled_at: '2026-11-11T10:00:00Z' }], + }); + const samples = await api.getDeploymentVerificationSamples('d-1'); + expect(get).toHaveBeenCalledWith('/api/v1/deployment-requests/d-1/verification-samples'); + expect(samples).toHaveLength(1); + expect(samples[0]?.check_name).toBe('health'); + }); }); diff --git a/frontend/src/api/deploymentRequests.ts b/frontend/src/api/deploymentRequests.ts index 212e25c37..2125d2d80 100644 --- a/frontend/src/api/deploymentRequests.ts +++ b/frontend/src/api/deploymentRequests.ts @@ -4,6 +4,7 @@ import type { DeploymentRequest, DeploymentRequestListFilters, DeploymentRequestPage, + DeploymentVerificationSample, } from '@/types/api'; const BASE = '/api/v1/deployment-requests'; @@ -15,6 +16,7 @@ export const deploymentKeys = { details: () => ['deployments', 'detail'] as const, detail: (id: string) => ['deployments', 'detail', id] as const, gate: (id: string) => ['deployments', 'detail', id, 'gate'] as const, + verification: (id: string) => ['deployments', 'detail', id, 'verification'] as const, }; export async function listDeploymentRequests( @@ -49,3 +51,13 @@ export async function getDeploymentGate(requestId: string): Promise { + const { data } = await apiClient.get( + `${BASE}/${id}/verification-samples`, + ); + return data; +} diff --git a/frontend/src/components/deployments/PipelineEnvironmentsTab.test.tsx b/frontend/src/components/deployments/PipelineEnvironmentsTab.test.tsx index 99a3cc139..99cfb65fb 100644 --- a/frontend/src/components/deployments/PipelineEnvironmentsTab.test.tsx +++ b/frontend/src/components/deployments/PipelineEnvironmentsTab.test.tsx @@ -2,6 +2,7 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'; import { render, screen, waitFor, fireEvent } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { App as AntdApp } from 'antd'; +import { AxiosError, type AxiosResponse } from 'axios'; import type { ReactNode } from 'react'; import '@/i18n'; import type { Datasource, DeploymentEnvironment, ReviewPlan } from '@/types/api'; @@ -77,6 +78,40 @@ const production: DeploymentEnvironment = { created_at: '2026-08-01T10:00:00Z', }; +const verified: DeploymentEnvironment = { + ...staging, + id: 'env-3', + name: 'canary', + sort_order: 20, + verification: { + window: 'PT15M', + sample_interval: 'PT30S', + failure_threshold: 3, + checks: [ + { + kind: 'HTTP_HEALTH', + name: 'health', + url: 'https://svc.example.com/healthz', + expected_status: 200, + }, + { + kind: 'PROMQL_THRESHOLD', + name: 'errors', + prometheus_url: 'https://prom.example.com', + query: 'sum(rate(errors[5m]))', + comparator: 'LT', + threshold: 0.05, + no_data_is_failure: true, + }, + ], + }, +}; + +function problem(status: number, data: Record): AxiosError { + const response = { data, status, statusText: '', headers: {}, config: {} as never } as AxiosResponse; + return new AxiosError('failed', undefined, undefined, undefined, response); +} + const warehouse = { id: 'ds-1', organization_id: 'org-1', @@ -166,6 +201,7 @@ describe('PipelineEnvironmentsTab', () => { allow_break_glass: false, change_ticket_required: false, datasource_id: null, + verification: null, }); }); @@ -449,4 +485,219 @@ describe('PipelineEnvironmentsTab', () => { ).toBeInTheDocument(); expect(updateDeploymentEnvironment).not.toHaveBeenCalled(); }); + + describe('post-deployment verification (#1027)', () => { + async function openCreate() { + render(wrap()); + await screen.findByText('staging'); + fireEvent.click(screen.getByRole('button', { name: /add environment/i })); + await screen.findByRole('dialog'); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'canary' } }); + } + + function enable() { + fireEvent.click(screen.getByRole('switch', { name: 'Verify after release' })); + } + + it('summarises the check count in the table and an em dash when off', async () => { + listDeploymentEnvironments.mockResolvedValue([staging, verified]); + render(wrap()); + await screen.findByText('canary'); + expect(screen.getByText('Checks: 2')).toBeInTheDocument(); + expect(screen.getByText('Verification').closest('th')).not.toBeNull(); + }); + + it('hides the fields until the switch is on', async () => { + await openCreate(); + expect(screen.queryByLabelText('Health URL')).toBeNull(); + enable(); + expect(await screen.findByLabelText('Health URL')).toBeInTheDocument(); + }); + + it('creates an environment with an HTTP check', async () => { + await openCreate(); + enable(); + fireEvent.change(await screen.findByLabelText('Check name'), { target: { value: 'health' } }); + fireEvent.change(screen.getByLabelText('Health URL'), { + target: { value: 'https://svc.example.com/healthz' }, + }); + fireEvent.change(screen.getByLabelText('Body contains (optional)'), { + target: { value: 'ok' }, + }); + + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(createDeploymentEnvironment).toHaveBeenCalledTimes(1)); + expect(createDeploymentEnvironment.mock.calls[0]![1].verification).toEqual({ + window: 'PT15M', + sample_interval: 'PT1M', + failure_threshold: 3, + checks: [ + { + kind: 'HTTP_HEALTH', + name: 'health', + url: 'https://svc.example.com/healthz', + expected_status: 200, + body_contains: 'ok', + }, + ], + }); + }); + + it('swaps to the PromQL fields when the kind changes', async () => { + await openCreate(); + enable(); + fireEvent.mouseDown(await screen.findByLabelText('Check type')); + fireEvent.click(await screen.findByText('PromQL threshold')); + expect(await screen.findByLabelText('Prometheus URL')).toBeInTheDocument(); + expect(screen.queryByLabelText('Health URL')).toBeNull(); + fireEvent.change(screen.getByLabelText('Check name'), { target: { value: 'errors' } }); + fireEvent.change(screen.getByLabelText('Prometheus URL'), { + target: { value: 'https://prom.example.com' }, + }); + fireEvent.change(screen.getByLabelText('PromQL query'), { + target: { value: 'sum(rate(errors[5m]))' }, + }); + fireEvent.change(screen.getByLabelText('Threshold'), { target: { value: '0.05' } }); + + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(createDeploymentEnvironment).toHaveBeenCalledTimes(1)); + expect(createDeploymentEnvironment.mock.calls[0]![1].verification.checks).toEqual([ + { + kind: 'PROMQL_THRESHOLD', + name: 'errors', + prometheus_url: 'https://prom.example.com', + query: 'sum(rate(errors[5m]))', + comparator: 'LT', + threshold: 0.05, + no_data_is_failure: true, + }, + ]); + }); + + it('refuses a non-http URL and a missing check name', async () => { + await openCreate(); + enable(); + fireEvent.change(await screen.findByLabelText('Health URL'), { + target: { value: 'ftp://svc.example.com' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect(await screen.findByText('Use an http:// or https:// URL.')).toBeInTheDocument(); + expect(createDeploymentEnvironment).not.toHaveBeenCalled(); + }); + + it('refuses a threshold the window cannot reach and an interval longer than the window', async () => { + await openCreate(); + enable(); + fireEvent.change(await screen.findByLabelText('Window'), { target: { value: '2' } }); + fireEvent.change(screen.getByLabelText('Sample every'), { target: { value: '1' } }); + fireEvent.change(screen.getByLabelText('Failures to breach'), { target: { value: '3' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect(await screen.findByText(/collects at most 2 samples/)).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText('Sample every'), { target: { value: '5' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect( + await screen.findByText(/no longer than the window/), + ).toBeInTheDocument(); + expect(createDeploymentEnvironment).not.toHaveBeenCalled(); + }); + + it('refuses duplicate check names and an empty check list', async () => { + await openCreate(); + enable(); + await screen.findByLabelText('Check name'); + // Window bounds are clamped by the InputNumber's own min / max, so no out-of-range value + // reaches the Form rule. + fireEvent.click(screen.getByRole('button', { name: /add check/i })); + const names = await screen.findAllByLabelText('Check name'); + fireEvent.change(names[0]!, { target: { value: 'health' } }); + fireEvent.change(names[1]!, { target: { value: 'health' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect( + (await screen.findAllByText('Another check already uses this name.')).length, + ).toBeGreaterThan(0); + + for (const remove of screen.getAllByRole('button', { name: /remove check/i })) { + fireEvent.click(remove); + } + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect(await screen.findByText('Add between 1 and 10 checks.')).toBeInTheDocument(); + expect(createDeploymentEnvironment).not.toHaveBeenCalled(); + }); + + it('prefills a stored config on edit and round-trips it unchanged', async () => { + listDeploymentEnvironments.mockResolvedValue([verified]); + render(wrap()); + await screen.findByText('canary'); + fireEvent.click(screen.getByRole('button', { name: 'Edit' })); + await screen.findByRole('dialog'); + expect(await screen.findByLabelText('Health URL')).toHaveValue( + 'https://svc.example.com/healthz', + ); + expect(screen.getByLabelText('Prometheus URL')).toHaveValue('https://prom.example.com'); + + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(updateDeploymentEnvironment).toHaveBeenCalledTimes(1)); + const input = updateDeploymentEnvironment.mock.calls[0]![2]; + expect(input.clear_verification).toBe(false); + expect(input.verification).toEqual({ + window: 'PT15M', + sample_interval: 'PT30S', + failure_threshold: 3, + checks: [ + { + kind: 'HTTP_HEALTH', + name: 'health', + url: 'https://svc.example.com/healthz', + expected_status: 200, + body_contains: null, + }, + { + kind: 'PROMQL_THRESHOLD', + name: 'errors', + prometheus_url: 'https://prom.example.com', + query: 'sum(rate(errors[5m]))', + comparator: 'LT', + threshold: 0.05, + no_data_is_failure: true, + }, + ], + }); + }); + + it('sends clear_verification when the switch is turned off on edit', async () => { + listDeploymentEnvironments.mockResolvedValue([verified]); + render(wrap()); + await screen.findByText('canary'); + fireEvent.click(screen.getByRole('button', { name: 'Edit' })); + await screen.findByLabelText('Health URL'); + fireEvent.click(screen.getByRole('switch', { name: 'Verify after release' })); + + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(updateDeploymentEnvironment).toHaveBeenCalledTimes(1)); + expect(updateDeploymentEnvironment.mock.calls[0]![2]).toEqual( + expect.objectContaining({ verification: null, clear_verification: true }), + ); + }); + + it('surfaces the server detail of a 422 DEPLOYMENT_VERIFICATION_INVALID', async () => { + createDeploymentEnvironment.mockRejectedValue( + problem(422, { + error: 'DEPLOYMENT_VERIFICATION_INVALID', + reason: 'host_unresolvable', + detail: 'The host of check health does not resolve', + }), + ); + await openCreate(); + enable(); + fireEvent.change(await screen.findByLabelText('Check name'), { target: { value: 'health' } }); + fireEvent.change(screen.getByLabelText('Health URL'), { + target: { value: 'https://nope.example.com' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect( + await screen.findByText('The host of check health does not resolve'), + ).toBeInTheDocument(); + }); + }); }); diff --git a/frontend/src/components/deployments/PipelineEnvironmentsTab.tsx b/frontend/src/components/deployments/PipelineEnvironmentsTab.tsx index 214867dd2..0fa95c652 100644 --- a/frontend/src/components/deployments/PipelineEnvironmentsTab.tsx +++ b/frontend/src/components/deployments/PipelineEnvironmentsTab.tsx @@ -12,8 +12,8 @@ import { Table, Tag, } from 'antd'; -import type { TableColumnsType } from 'antd'; -import { PlusOutlined } from '@ant-design/icons'; +import type { FormInstance, TableColumnsType } from 'antd'; +import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useTranslation } from 'react-i18next'; import { @@ -29,7 +29,25 @@ import { nextSortOrder } from './environmentLadder'; import { listReviewPlans, reviewPlanKeys } from '@/api/reviewPlans'; import { apiErrorMessage } from '@/utils/apiErrors'; import { showApiError } from '@/utils/showApiError'; +import { + VERIFICATION_CHECK_KINDS, + VERIFICATION_COMPARATORS, + verificationCheckKindLabel, + verificationComparatorLabel, +} from '@/utils/enumLabels'; import type { DeploymentEnvironment } from '@/types/api'; +import { + VERIFICATION_LIMITS as LIMITS, + defaultCheckValues, + defaultVerificationValues, + isDuplicateCheckName, + isHttpUrl, + maxSamplesInWindow, + toVerificationFormValues, + toVerificationWire, + verificationCheckCount, + type VerificationFormValues, +} from './verificationForm'; interface EnvironmentFormValues { name: string; @@ -42,6 +60,7 @@ interface EnvironmentFormValues { allow_break_glass: boolean; change_ticket_required: boolean; datasource_id?: string | null; + verification: VerificationFormValues; } const DATASOURCE_PAGE = { page: 0, size: 200 }; @@ -81,6 +100,7 @@ export function PipelineEnvironmentsTab({ pipelineId }: { pipelineId: string }) allow_break_glass: false, change_ticket_required: false, datasource_id: null, + verification: defaultVerificationValues(), }); } else { form.setFieldsValue({ @@ -93,6 +113,7 @@ export function PipelineEnvironmentsTab({ pipelineId }: { pipelineId: string }) allow_break_glass: modalFor.allow_break_glass, change_ticket_required: modalFor.change_ticket_required, datasource_id: modalFor.datasource_id, + verification: toVerificationFormValues(modalFor.verification), }); } }, [modalFor, form, envsQuery.data]); @@ -109,6 +130,10 @@ export function PipelineEnvironmentsTab({ pipelineId }: { pipelineId: string }) const saveMutation = useMutation({ mutationFn: (values: EnvironmentFormValues) => { + // Read from the store, not `values`: fields under a switched-off section are unmounted. + const verification = toVerificationWire( + form.getFieldValue('verification') as VerificationFormValues | undefined, + ); if (modalFor === 'create') { return createDeploymentEnvironment(pipelineId, { name: values.name, @@ -120,6 +145,7 @@ export function PipelineEnvironmentsTab({ pipelineId }: { pipelineId: string }) allow_break_glass: values.allow_break_glass, change_ticket_required: values.change_ticket_required, datasource_id: values.datasource_id ?? null, + verification, }); } return updateDeploymentEnvironment(pipelineId, (modalFor as DeploymentEnvironment).id, { @@ -137,6 +163,9 @@ export function PipelineEnvironmentsTab({ pipelineId }: { pipelineId: string }) change_ticket_required: values.change_ticket_required, datasource_id: values.datasource_id ?? null, clear_datasource: values.datasource_id == null, + // Off ⇒ remove: the server reads a null config as "leave unchanged". + verification, + clear_verification: verification == null, }); }, onSuccess: () => { @@ -228,6 +257,20 @@ export function PipelineEnvironmentsTab({ pipelineId }: { pipelineId: string }) align: 'center' as const, render: (v: boolean) => (v ? '✓' : '—'), }, + { + title: t('deploygov.settings.verificationColumn'), + key: 'verification', + width: 120, + align: 'center' as const, + render: (_v, row) => { + const count = verificationCheckCount(row.verification); + return count == null ? ( + — + ) : ( + t('deploygov.settings.verificationChecksCount', { n: count }) + ); + }, + }, { title: '', key: 'actions', @@ -392,8 +435,342 @@ export function PipelineEnvironmentsTab({ pipelineId }: { pipelineId: string }) > + ); } + +const VERIFICATION = 'verification'; +const CHECKS = [VERIFICATION, 'checks'] as const; + +/** + * Parity with DeploymentVerificationConfigRequest / DeploymentVerificationCheckRequest (#1023) + * and the network-free #1024 rules — see verificationForm.ts. Window 1..1440 min, interval + * 0.5 min..window, threshold 1..20 and ≤ samples in the window, 1..10 checks, name required ≤ 64 + * and unique, URL required ≤ 2048 http(s), expected status 100..599, body ≤ 1024, query ≤ 4096, + * comparator + threshold required on PromQL checks. + */ +function VerificationSection({ form }: { form: FormInstance }) { + const { t } = useTranslation(); + return ( + <> +
+ {t('deploygov.settings.verificationSection')} +
+ + + + + prev.verification?.enabled !== cur.verification?.enabled + } + > + {({ getFieldValue }) => + getFieldValue([VERIFICATION, 'enabled']) ? : null + } + + + ); +} + +function VerificationFields({ form }: { form: FormInstance }) { + const { t } = useTranslation(); + const numberValue = (field: 'window_minutes' | 'interval_minutes') => + form.getFieldValue([VERIFICATION, field]) as number | null | undefined; + const kindOptions = VERIFICATION_CHECK_KINDS.map((k) => ({ + value: k, + label: verificationCheckKindLabel(t, k), + })); + const comparatorOptions = VERIFICATION_COMPARATORS.map((c) => ({ + value: c, + label: verificationComparatorLabel(t, c), + })); + const httpUrlRule = { + validator: async (_: unknown, value: string | null | undefined) => { + if (value && value.trim() !== '' && !isHttpUrl(value)) { + throw new Error(t('deploygov.settings.verificationUrlScheme')); + } + }, + }; + + return ( + <> +
+ + + + { + if (value == null) return; + const windowMinutes = numberValue('window_minutes'); + if ( + value < LIMITS.intervalMinMinutes || + (windowMinutes != null && value > windowMinutes) + ) { + throw new Error(t('deploygov.settings.verificationIntervalRange')); + } + }, + }, + ]} + > + + + { + const samples = maxSamplesInWindow( + numberValue('window_minutes'), + numberValue('interval_minutes'), + ); + if (value != null && samples != null && value > samples) { + throw new Error( + t('deploygov.settings.verificationThresholdExceedsSamples', { samples }), + ); + } + }, + }, + ]} + > + + +
+ { + const count = checks?.length ?? 0; + if (count < 1 || count > LIMITS.maxChecks) { + throw new Error(t('deploygov.settings.verificationChecksRange')); + } + }, + }, + ]} + > + {(fields, { add, remove }, { errors }) => ( +
+ {fields.map((field, index) => ( +
+
+ + + +
+ + prev.verification?.checks?.[index]?.kind !== + cur.verification?.checks?.[index]?.kind + } + > + {({ getFieldValue }) => + getFieldValue([...CHECKS, field.name, 'kind']) === 'PROMQL_THRESHOLD' ? ( + <> + + + + + + +
+ + + +
+ + + + + + +
+ + ) + } + +
+ ))} + +
+ +
+
+ )} + + + ); +} diff --git a/frontend/src/components/deployments/verificationForm.test.ts b/frontend/src/components/deployments/verificationForm.test.ts new file mode 100644 index 000000000..332e5efd0 --- /dev/null +++ b/frontend/src/components/deployments/verificationForm.test.ts @@ -0,0 +1,175 @@ +import { describe, expect, it } from 'vitest'; +import { + defaultCheckValues, + defaultVerificationValues, + isDuplicateCheckName, + isHttpUrl, + isoDurationSeconds, + maxSamplesInWindow, + minutesToIso, + toVerificationFormValues, + toVerificationWire, + verificationCheckCount, +} from './verificationForm'; +import type { DeploymentVerificationConfig } from '@/types/api'; + +const config: DeploymentVerificationConfig = { + window: 'PT15M', + sample_interval: 'PT30S', + failure_threshold: 3, + checks: [ + { kind: 'HTTP_HEALTH', name: 'health', url: 'https://svc.example.com/healthz', expected_status: 204 }, + { + kind: 'PROMQL_THRESHOLD', + name: 'error-rate', + prometheus_url: 'https://prom.example.com', + query: 'sum(rate(errors[5m]))', + comparator: 'GTE', + threshold: 0.05, + no_data_is_failure: false, + }, + ], +}; + +describe('verificationForm', () => { + it('parses ISO-8601 time durations to seconds', () => { + expect(isoDurationSeconds('PT15M')).toBe(900); + expect(isoDurationSeconds('PT30S')).toBe(30); + expect(isoDurationSeconds('PT1H30M')).toBe(5400); + expect(isoDurationSeconds('PT1.5S')).toBe(1.5); + expect(isoDurationSeconds('P1D')).toBeNull(); + expect(isoDurationSeconds('PT')).toBeNull(); + expect(isoDurationSeconds(null)).toBeNull(); + expect(isoDurationSeconds('')).toBeNull(); + }); + + it('formats minutes as whole minutes or seconds', () => { + expect(minutesToIso(15)).toBe('PT15M'); + expect(minutesToIso(0.5)).toBe('PT30S'); + expect(minutesToIso(1.25)).toBe('PT75S'); + }); + + it('defaults to off with one HTTP check', () => { + const values = defaultVerificationValues(); + expect(values.enabled).toBe(false); + expect(values.checks).toEqual([defaultCheckValues()]); + expect(defaultCheckValues('PROMQL_THRESHOLD').kind).toBe('PROMQL_THRESHOLD'); + }); + + it('maps a stored config into form values', () => { + const values = toVerificationFormValues(config); + expect(values.enabled).toBe(true); + expect(values.window_minutes).toBe(15); + expect(values.interval_minutes).toBe(0.5); + expect(values.failure_threshold).toBe(3); + expect(values.checks[0]).toMatchObject({ kind: 'HTTP_HEALTH', url: 'https://svc.example.com/healthz', expected_status: 204 }); + expect(values.checks[1]).toMatchObject({ + kind: 'PROMQL_THRESHOLD', + comparator: 'GTE', + threshold: 0.05, + no_data_is_failure: false, + }); + }); + + it('falls back to defaults for absent config and omitted check fields', () => { + expect(toVerificationFormValues(null).enabled).toBe(false); + expect(toVerificationFormValues(undefined).enabled).toBe(false); + const values = toVerificationFormValues({ + window: 'bogus', + sample_interval: 'PT1M', + failure_threshold: 1, + checks: [{ kind: 'PROMQL_THRESHOLD', name: 'p' }], + }); + expect(values.window_minutes).toBeNull(); + expect(values.checks[0]).toMatchObject({ comparator: 'LT', no_data_is_failure: true, expected_status: 200 }); + }); + + it('round-trips form values back to the wire, dropping the other kind’s fields', () => { + const wire = toVerificationWire(toVerificationFormValues(config)); + expect(wire).toEqual({ + window: 'PT15M', + sample_interval: 'PT30S', + failure_threshold: 3, + checks: [ + { + kind: 'HTTP_HEALTH', + name: 'health', + url: 'https://svc.example.com/healthz', + expected_status: 204, + body_contains: null, + }, + { + kind: 'PROMQL_THRESHOLD', + name: 'error-rate', + prometheus_url: 'https://prom.example.com', + query: 'sum(rate(errors[5m]))', + comparator: 'GTE', + threshold: 0.05, + no_data_is_failure: false, + }, + ], + }); + }); + + it('returns null when verification is off', () => { + expect(toVerificationWire(defaultVerificationValues())).toBeNull(); + expect(toVerificationWire(undefined)).toBeNull(); + }); + + it('trims text and fills defaults for unset fields', () => { + const wire = toVerificationWire({ + enabled: true, + window_minutes: null, + interval_minutes: null, + failure_threshold: null, + checks: [ + { ...defaultCheckValues(), name: ' h ', url: ' https://x.example ', body_contains: ' ', expected_status: null }, + { ...defaultCheckValues('PROMQL_THRESHOLD'), name: 'p', comparator: null, threshold: null, no_data_is_failure: undefined }, + ], + }); + expect(wire?.window).toBe('PT0M'); + expect(wire?.failure_threshold).toBe(0); + expect(wire?.checks[0]).toEqual({ + kind: 'HTTP_HEALTH', + name: 'h', + url: 'https://x.example', + expected_status: null, + body_contains: null, + }); + expect(wire?.checks[1]).toMatchObject({ comparator: 'LT', threshold: 0, no_data_is_failure: true, prometheus_url: '', query: '' }); + }); + + it('accepts only http(s) URLs', () => { + expect(isHttpUrl('https://svc.example.com/h')).toBe(true); + expect(isHttpUrl('HTTP://svc')).toBe(true); + expect(isHttpUrl('ftp://svc')).toBe(false); + expect(isHttpUrl('svc.example.com')).toBe(false); + expect(isHttpUrl(null)).toBe(false); + }); + + it('computes how many samples fit in the window', () => { + expect(maxSamplesInWindow(15, 1)).toBe(15); + expect(maxSamplesInWindow(1, 0.5)).toBe(2); + expect(maxSamplesInWindow(5, 2)).toBe(2); + expect(maxSamplesInWindow(null, 1)).toBeNull(); + expect(maxSamplesInWindow(5, 0)).toBeNull(); + }); + + it('detects duplicate check names, ignoring blanks and the row itself', () => { + const checks = [ + { ...defaultCheckValues(), name: 'health' }, + { ...defaultCheckValues(), name: ' health ' }, + { ...defaultCheckValues(), name: '' }, + ]; + expect(isDuplicateCheckName(checks, 0, 'health')).toBe(true); + expect(isDuplicateCheckName(checks, 0, 'other')).toBe(false); + expect(isDuplicateCheckName(checks, 2, '')).toBe(false); + expect(isDuplicateCheckName(undefined, 0, 'x')).toBe(false); + expect(isDuplicateCheckName([undefined], 1, 'x')).toBe(false); + }); + + it('counts checks for the table summary', () => { + expect(verificationCheckCount(config)).toBe(2); + expect(verificationCheckCount(null)).toBeNull(); + }); +}); diff --git a/frontend/src/components/deployments/verificationForm.ts b/frontend/src/components/deployments/verificationForm.ts new file mode 100644 index 000000000..3d756cecd --- /dev/null +++ b/frontend/src/components/deployments/verificationForm.ts @@ -0,0 +1,191 @@ +import type { + DeploymentVerificationConfig, + DeploymentVerificationConfigInput, + VerificationCheckInput, + VerificationCheckKind, + VerificationComparator, +} from '@/types/api'; + +/** + * Client-side mirror of the backend's verification rules: Bean Validation on + * DeploymentVerificationConfigRequest / DeploymentVerificationCheckRequest (#1023) plus the + * semantic checks of #1024 that need no network (window / interval ranges, threshold reachable in + * the window, unique names, http(s) URLs). Host policy (resolvability, restricted addresses, the + * allow-list) is only decidable server-side and surfaces as 422 DEPLOYMENT_VERIFICATION_INVALID. + */ +export const VERIFICATION_LIMITS = { + maxChecks: 10, + nameMax: 64, + urlMax: 2048, + bodyContainsMax: 1024, + queryMax: 4096, + thresholdMin: 1, + thresholdMax: 20, + windowMinMinutes: 1, + windowMaxMinutes: 1440, + intervalMinMinutes: 0.5, + expectedStatusMin: 100, + expectedStatusMax: 599, +} as const; + +export interface VerificationCheckFormValues { + kind: VerificationCheckKind; + name: string; + url?: string | null; + expected_status?: number | null; + body_contains?: string | null; + prometheus_url?: string | null; + query?: string | null; + comparator?: VerificationComparator | null; + threshold?: number | null; + no_data_is_failure?: boolean; +} + +export interface VerificationFormValues { + enabled: boolean; + window_minutes: number | null; + interval_minutes: number | null; + failure_threshold: number | null; + checks: VerificationCheckFormValues[]; +} + +export function defaultCheckValues( + kind: VerificationCheckKind = 'HTTP_HEALTH', +): VerificationCheckFormValues { + return { + kind, + name: '', + url: null, + expected_status: 200, + body_contains: null, + prometheus_url: null, + query: null, + comparator: 'LT', + threshold: null, + no_data_is_failure: true, + }; +} + +export function defaultVerificationValues(): VerificationFormValues { + return { + enabled: false, + window_minutes: 15, + interval_minutes: 1, + failure_threshold: 3, + checks: [defaultCheckValues()], + }; +} + +const ISO_DURATION = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/; + +/** Seconds in an ISO-8601 time-only duration (`PT1H30M`, `PT30S`); null when unparseable. */ +export function isoDurationSeconds(value: string | null | undefined): number | null { + if (!value) return null; + const match = ISO_DURATION.exec(value); + if (!match || value === 'PT') return null; + const [, h, m, s] = match; + return Number(h ?? 0) * 3600 + Number(m ?? 0) * 60 + Number(s ?? 0); +} + +/** Minutes ⇄ ISO-8601: whole minutes stay `PTnM`, anything finer goes out in seconds. */ +export function minutesToIso(minutes: number): string { + const seconds = Math.round(minutes * 60); + return seconds % 60 === 0 ? `PT${seconds / 60}M` : `PT${seconds}S`; +} + +function isoToMinutes(value: string | null | undefined): number | null { + const seconds = isoDurationSeconds(value); + return seconds == null ? null : seconds / 60; +} + +export function toVerificationFormValues( + config: DeploymentVerificationConfig | null | undefined, +): VerificationFormValues { + if (!config) return defaultVerificationValues(); + return { + enabled: true, + window_minutes: isoToMinutes(config.window), + interval_minutes: isoToMinutes(config.sample_interval), + failure_threshold: config.failure_threshold, + checks: config.checks.map((check) => ({ + ...defaultCheckValues(check.kind), + name: check.name, + url: check.url ?? null, + expected_status: check.expected_status ?? 200, + body_contains: check.body_contains ?? null, + prometheus_url: check.prometheus_url ?? null, + query: check.query ?? null, + comparator: check.comparator ?? 'LT', + threshold: check.threshold ?? null, + no_data_is_failure: check.no_data_is_failure ?? true, + })), + }; +} + +function blankToNull(value: string | null | undefined): string | null { + return value == null || value.trim() === '' ? null : value.trim(); +} + +function toWireCheck(check: VerificationCheckFormValues): VerificationCheckInput { + if (check.kind === 'HTTP_HEALTH') { + return { + kind: 'HTTP_HEALTH', + name: check.name.trim(), + url: (check.url ?? '').trim(), + expected_status: check.expected_status ?? null, + body_contains: blankToNull(check.body_contains), + }; + } + return { + kind: 'PROMQL_THRESHOLD', + name: check.name.trim(), + prometheus_url: (check.prometheus_url ?? '').trim(), + query: (check.query ?? '').trim(), + comparator: check.comparator ?? 'LT', + threshold: check.threshold ?? 0, + no_data_is_failure: check.no_data_is_failure ?? true, + }; +} + +/** Null when the switch is off — the caller sends `null` / `clear_verification: true`. */ +export function toVerificationWire( + values: VerificationFormValues | undefined, +): DeploymentVerificationConfigInput | null { + if (!values?.enabled) return null; + return { + window: minutesToIso(values.window_minutes ?? 0), + sample_interval: minutesToIso(values.interval_minutes ?? 0), + failure_threshold: values.failure_threshold ?? 0, + checks: (values.checks ?? []).map(toWireCheck), + }; +} + +export function isHttpUrl(value: string | null | undefined): boolean { + return /^https?:\/\/\S+$/i.test((value ?? '').trim()); +} + +/** How many samples the window can collect — the ceiling on `failure_threshold` (#1024). */ +export function maxSamplesInWindow( + windowMinutes: number | null | undefined, + intervalMinutes: number | null | undefined, +): number | null { + if (windowMinutes == null || intervalMinutes == null || intervalMinutes <= 0) return null; + return Math.floor(Math.round(windowMinutes * 60) / Math.round(intervalMinutes * 60)); +} + +export function isDuplicateCheckName( + checks: readonly (VerificationCheckFormValues | undefined)[] | undefined, + index: number, + name: string | null | undefined, +): boolean { + const normalized = (name ?? '').trim(); + if (normalized === '') return false; + return (checks ?? []).some( + (check, i) => i !== index && (check?.name ?? '').trim() === normalized, + ); +} + +/** "Verification: n checks" in the environments table; null when off. */ +export function verificationCheckCount(config: DeploymentVerificationConfig | null | undefined) { + return config ? config.checks.length : null; +} diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json index 9fe6f90f0..898af0b78 100644 --- a/frontend/src/locales/de.json +++ b/frontend/src/locales/de.json @@ -4038,6 +4038,23 @@ "DAY": "Aufrufe pro Tag", "USER_MINUTE": "Aufrufe pro Benutzer und Minute", "USER_DAY": "Aufrufe pro Benutzer und Tag" + }, + "verification_status": { + "PENDING": "ausstehend", + "RUNNING": "läuft", + "PASSED": "bestanden", + "FAILED": "fehlgeschlagen", + "SKIPPED": "übersprungen" + }, + "verification_check_kind": { + "HTTP_HEALTH": "HTTP-Health", + "PROMQL_THRESHOLD": "PromQL-Schwellenwert" + }, + "verification_comparator": { + "LT": "<", + "LTE": "≤", + "GT": ">", + "GTE": "≥" } }, "access": { @@ -5755,7 +5772,8 @@ "versionFilterPlaceholder": "Exakte Version", "countLabel": "{{total}} Deployments", "empty": "Noch keine Deployment-Anfragen", - "notFound": "Deployment-Anfrage nicht gefunden" + "notFound": "Deployment-Anfrage nicht gefunden", + "verificationTag": "Verifizierung {{status}}" }, "detail": { "title": "Deployment", @@ -5816,7 +5834,25 @@ "timeline_released": "Freigabe", "timeline_execution_failed": "Ausführung fehlgeschlagen", "timeline_cancelled": "Abgebrochen", - "timeline_outcome": "Ergebnis" + "timeline_outcome": "Ergebnis", + "verification": "Verifizierung", + "verificationFailedTitle": "Verifizierung fehlgeschlagen — das Release läuft weiter", + "verificationFailedBody": "AccessFlow hat nichts zurückgerollt. Entscheiden Sie, ob zurückgerollt werden soll, und melden Sie dann ROLLED_BACK aus der Pipeline.", + "verificationWindow": "Zeitfenster", + "verificationInterval": "Prüfintervall", + "verificationThreshold": "Fehlerschwellenwert", + "verificationStarted": "Gestartet", + "verificationFinished": "Beendet", + "verificationDetail": "Details", + "verificationSampledAt": "Geprüft am", + "verificationCheck": "Check", + "verificationResult": "Ergebnis", + "verificationObserved": "Beobachtet", + "verificationSampleDetail": "Details", + "verificationNoSamples": "Noch keine Stichproben", + "verificationMinutesValue": "{{n}} Min.", + "verificationSecondsValue": "{{n}} s", + "timeline_verification": "Verifizierung" }, "reviews": { "approve": "Genehmigen", @@ -6059,7 +6095,37 @@ "editUserPermission": "Berechtigung bearbeiten — {{user}}", "editGroupPermission": "Berechtigung bearbeiten — {{group}}", "revoke": "Widerrufen", - "tabSimulate": "Simulieren" + "tabSimulate": "Simulieren", + "verificationSection": "Verifizierung nach dem Deployment", + "verificationEnabled": "Nach dem Release verifizieren", + "verificationEnabledHelp": "Sobald die Pipeline SUCCEEDED meldet, prüft AccessFlow diese Checks während des Zeitfensters. Ein Verstoß markiert das Deployment als fehlgeschlagen — AccessFlow rollt nie etwas zurück.", + "verificationWindow": "Zeitfenster", + "verificationInterval": "Prüfen alle", + "verificationThreshold": "Fehler bis zum Verstoß", + "verificationMinutes": "Min.", + "verificationWindowRange": "Das Zeitfenster muss zwischen 1 und 1440 Minuten liegen.", + "verificationIntervalRange": "Das Prüfintervall muss mindestens 0,5 Minuten betragen und darf das Zeitfenster nicht überschreiten.", + "verificationThresholdRange": "Der Fehlerschwellenwert muss zwischen 1 und 20 liegen.", + "verificationThresholdExceedsSamples": "Das Zeitfenster erfasst höchstens {{samples}} Stichproben — senken Sie den Schwellenwert oder vergrößern Sie das Zeitfenster.", + "verificationChecksRange": "Fügen Sie zwischen 1 und 10 Checks hinzu.", + "verificationCheckKind": "Check-Typ", + "verificationCheckName": "Check-Name", + "verificationCheckNameDuplicate": "Ein anderer Check verwendet diesen Namen bereits.", + "verificationRemoveCheck": "Check entfernen", + "verificationAddCheck": "Check hinzufügen", + "verificationUrl": "Health-URL", + "verificationUrlScheme": "Verwenden Sie eine http://- oder https://-URL.", + "verificationExpectedStatus": "Erwarteter Status", + "verificationExpectedStatusRange": "Der erwartete Status muss zwischen 100 und 599 liegen.", + "verificationBodyContains": "Body enthält (optional)", + "verificationPrometheusUrl": "Prometheus-URL", + "verificationPrometheusUrlHelp": "Nur die Basis-URL — /api/v1/query wird angehängt.", + "verificationQuery": "PromQL-Abfrage", + "verificationComparator": "Bestanden, wenn der Wert", + "verificationValueThreshold": "Schwellenwert", + "verificationNoDataIsFailure": "Keine Daten gelten als Fehler", + "verificationColumn": "Verifizierung", + "verificationChecksCount": "Checks: {{n}}" }, "freezeWindows": { "title": "Freeze-Fenster", diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json index 89c19e783..045288f61 100644 --- a/frontend/src/locales/en.json +++ b/frontend/src/locales/en.json @@ -4076,6 +4076,23 @@ "DAY": "Calls per day", "USER_MINUTE": "Per-user calls per minute", "USER_DAY": "Per-user calls per day" + }, + "verification_status": { + "PENDING": "pending", + "RUNNING": "running", + "PASSED": "passed", + "FAILED": "failed", + "SKIPPED": "skipped" + }, + "verification_check_kind": { + "HTTP_HEALTH": "HTTP health", + "PROMQL_THRESHOLD": "PromQL threshold" + }, + "verification_comparator": { + "LT": "<", + "LTE": "≤", + "GT": ">", + "GTE": "≥" } }, "access": { @@ -5755,7 +5772,8 @@ "versionFilterPlaceholder": "Exact version", "countLabel": "{{total}} deployments", "empty": "No deployment requests yet", - "notFound": "Deployment request not found" + "notFound": "Deployment request not found", + "verificationTag": "verification {{status}}" }, "detail": { "title": "Deployment", @@ -5816,7 +5834,25 @@ "timeline_released": "Release", "timeline_execution_failed": "Execution failed", "timeline_cancelled": "Cancelled", - "timeline_outcome": "Outcome" + "timeline_outcome": "Outcome", + "verification": "Verification", + "verificationFailedTitle": "Verification failed — the release is still running", + "verificationFailedBody": "AccessFlow did not roll back. Decide whether to roll back, then report ROLLED_BACK from the pipeline.", + "verificationWindow": "Window", + "verificationInterval": "Sample interval", + "verificationThreshold": "Failure threshold", + "verificationStarted": "Started", + "verificationFinished": "Finished", + "verificationDetail": "Detail", + "verificationSampledAt": "Sampled at", + "verificationCheck": "Check", + "verificationResult": "Result", + "verificationObserved": "Observed", + "verificationSampleDetail": "Detail", + "verificationNoSamples": "No samples yet", + "verificationMinutesValue": "{{n}} min", + "verificationSecondsValue": "{{n}} s", + "timeline_verification": "Verification" }, "reviews": { "approve": "Approve", @@ -6059,7 +6095,37 @@ "editUserPermission": "Edit permission — {{user}}", "editGroupPermission": "Edit permission — {{group}}", "revoke": "Revoke", - "tabSimulate": "Simulate" + "tabSimulate": "Simulate", + "verificationSection": "Post-deployment verification", + "verificationEnabled": "Verify after release", + "verificationEnabledHelp": "After the pipeline reports SUCCEEDED, AccessFlow samples these checks for the window. A breach marks the deployment failed — AccessFlow never rolls anything back.", + "verificationWindow": "Window", + "verificationInterval": "Sample every", + "verificationThreshold": "Failures to breach", + "verificationMinutes": "min", + "verificationWindowRange": "Window must be between 1 and 1440 minutes.", + "verificationIntervalRange": "Sample interval must be at least 0.5 minutes and no longer than the window.", + "verificationThresholdRange": "Failure threshold must be between 1 and 20.", + "verificationThresholdExceedsSamples": "The window collects at most {{samples}} samples — lower the threshold or widen the window.", + "verificationChecksRange": "Add between 1 and 10 checks.", + "verificationCheckKind": "Check type", + "verificationCheckName": "Check name", + "verificationCheckNameDuplicate": "Another check already uses this name.", + "verificationRemoveCheck": "Remove check", + "verificationAddCheck": "Add check", + "verificationUrl": "Health URL", + "verificationUrlScheme": "Use an http:// or https:// URL.", + "verificationExpectedStatus": "Expected status", + "verificationExpectedStatusRange": "Expected status must be between 100 and 599.", + "verificationBodyContains": "Body contains (optional)", + "verificationPrometheusUrl": "Prometheus URL", + "verificationPrometheusUrlHelp": "Base URL only — /api/v1/query is appended.", + "verificationQuery": "PromQL query", + "verificationComparator": "Passes when value is", + "verificationValueThreshold": "Threshold", + "verificationNoDataIsFailure": "No data counts as failure", + "verificationColumn": "Verification", + "verificationChecksCount": "Checks: {{n}}" }, "freezeWindows": { "title": "Freeze windows", diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json index 574db694f..70113ab35 100644 --- a/frontend/src/locales/es.json +++ b/frontend/src/locales/es.json @@ -4038,6 +4038,23 @@ "DAY": "Llamadas por día", "USER_MINUTE": "Llamadas por usuario y minuto", "USER_DAY": "Llamadas por usuario y día" + }, + "verification_status": { + "PENDING": "pendiente", + "RUNNING": "en curso", + "PASSED": "superada", + "FAILED": "fallida", + "SKIPPED": "omitida" + }, + "verification_check_kind": { + "HTTP_HEALTH": "Salud HTTP", + "PROMQL_THRESHOLD": "Umbral PromQL" + }, + "verification_comparator": { + "LT": "<", + "LTE": "≤", + "GT": ">", + "GTE": "≥" } }, "access": { @@ -5755,7 +5772,8 @@ "versionFilterPlaceholder": "Versión exacta", "countLabel": "{{total}} despliegues", "empty": "Aún no hay solicitudes de despliegue", - "notFound": "Solicitud de despliegue no encontrada" + "notFound": "Solicitud de despliegue no encontrada", + "verificationTag": "verificación {{status}}" }, "detail": { "title": "Despliegue", @@ -5816,7 +5834,25 @@ "timeline_released": "Liberación", "timeline_execution_failed": "Ejecución fallida", "timeline_cancelled": "Cancelado", - "timeline_outcome": "Resultado" + "timeline_outcome": "Resultado", + "verification": "Verificación", + "verificationFailedTitle": "La verificación falló — la versión sigue en ejecución", + "verificationFailedBody": "AccessFlow no revirtió nada. Decide si revertir y luego informa ROLLED_BACK desde el pipeline.", + "verificationWindow": "Ventana", + "verificationInterval": "Intervalo de muestreo", + "verificationThreshold": "Umbral de fallos", + "verificationStarted": "Iniciada", + "verificationFinished": "Finalizada", + "verificationDetail": "Detalle", + "verificationSampledAt": "Muestreado", + "verificationCheck": "Comprobación", + "verificationResult": "Resultado", + "verificationObserved": "Observado", + "verificationSampleDetail": "Detalle", + "verificationNoSamples": "Aún no hay muestras", + "verificationMinutesValue": "{{n}} min", + "verificationSecondsValue": "{{n}} s", + "timeline_verification": "Verificación" }, "reviews": { "approve": "Aprobar", @@ -6059,7 +6095,37 @@ "editUserPermission": "Editar permiso — {{user}}", "editGroupPermission": "Editar permiso — {{group}}", "revoke": "Revocar", - "tabSimulate": "Simular" + "tabSimulate": "Simular", + "verificationSection": "Verificación posterior al despliegue", + "verificationEnabled": "Verificar tras la publicación", + "verificationEnabledHelp": "Cuando el pipeline informa SUCCEEDED, AccessFlow muestrea estas comprobaciones durante la ventana. Una infracción marca el despliegue como fallido — AccessFlow nunca revierte nada.", + "verificationWindow": "Ventana", + "verificationInterval": "Muestrear cada", + "verificationThreshold": "Fallos hasta infracción", + "verificationMinutes": "min", + "verificationWindowRange": "La ventana debe estar entre 1 y 1440 minutos.", + "verificationIntervalRange": "El intervalo de muestreo debe ser de al menos 0,5 minutos y no superar la ventana.", + "verificationThresholdRange": "El umbral de fallos debe estar entre 1 y 20.", + "verificationThresholdExceedsSamples": "La ventana recoge como máximo {{samples}} muestras — baja el umbral o amplía la ventana.", + "verificationChecksRange": "Añade entre 1 y 10 comprobaciones.", + "verificationCheckKind": "Tipo de comprobación", + "verificationCheckName": "Nombre de la comprobación", + "verificationCheckNameDuplicate": "Otra comprobación ya usa este nombre.", + "verificationRemoveCheck": "Quitar comprobación", + "verificationAddCheck": "Añadir comprobación", + "verificationUrl": "URL de salud", + "verificationUrlScheme": "Usa una URL http:// o https://.", + "verificationExpectedStatus": "Estado esperado", + "verificationExpectedStatusRange": "El estado esperado debe estar entre 100 y 599.", + "verificationBodyContains": "El cuerpo contiene (opcional)", + "verificationPrometheusUrl": "URL de Prometheus", + "verificationPrometheusUrlHelp": "Solo la URL base — se añade /api/v1/query.", + "verificationQuery": "Consulta PromQL", + "verificationComparator": "Pasa cuando el valor es", + "verificationValueThreshold": "Umbral", + "verificationNoDataIsFailure": "Sin datos cuenta como fallo", + "verificationColumn": "Verificación", + "verificationChecksCount": "Comprobaciones: {{n}}" }, "freezeWindows": { "title": "Ventanas de congelación", diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json index dbfdedf08..16a5d11bd 100644 --- a/frontend/src/locales/fr.json +++ b/frontend/src/locales/fr.json @@ -4038,6 +4038,23 @@ "DAY": "Appels par jour", "USER_MINUTE": "Appels par utilisateur et par minute", "USER_DAY": "Appels par utilisateur et par jour" + }, + "verification_status": { + "PENDING": "en attente", + "RUNNING": "en cours", + "PASSED": "réussie", + "FAILED": "échouée", + "SKIPPED": "ignorée" + }, + "verification_check_kind": { + "HTTP_HEALTH": "Santé HTTP", + "PROMQL_THRESHOLD": "Seuil PromQL" + }, + "verification_comparator": { + "LT": "<", + "LTE": "≤", + "GT": ">", + "GTE": "≥" } }, "access": { @@ -5755,7 +5772,8 @@ "versionFilterPlaceholder": "Version exacte", "countLabel": "{{total}} déploiements", "empty": "Aucune demande de déploiement pour le moment", - "notFound": "Demande de déploiement introuvable" + "notFound": "Demande de déploiement introuvable", + "verificationTag": "vérification {{status}}" }, "detail": { "title": "Déploiement", @@ -5816,7 +5834,25 @@ "timeline_released": "Libération", "timeline_execution_failed": "Échec de l'exécution", "timeline_cancelled": "Annulé", - "timeline_outcome": "Résultat" + "timeline_outcome": "Résultat", + "verification": "Vérification", + "verificationFailedTitle": "Vérification échouée — la version est toujours en service", + "verificationFailedBody": "AccessFlow n’a effectué aucun retour arrière. Décidez s’il faut revenir en arrière, puis signalez ROLLED_BACK depuis le pipeline.", + "verificationWindow": "Fenêtre", + "verificationInterval": "Intervalle d’échantillonnage", + "verificationThreshold": "Seuil d’échec", + "verificationStarted": "Démarrée", + "verificationFinished": "Terminée", + "verificationDetail": "Détail", + "verificationSampledAt": "Échantillonné le", + "verificationCheck": "Contrôle", + "verificationResult": "Résultat", + "verificationObserved": "Observé", + "verificationSampleDetail": "Détail", + "verificationNoSamples": "Aucun échantillon pour l’instant", + "verificationMinutesValue": "{{n}} min", + "verificationSecondsValue": "{{n}} s", + "timeline_verification": "Vérification" }, "reviews": { "approve": "Approuver", @@ -6059,7 +6095,37 @@ "editUserPermission": "Modifier l'autorisation — {{user}}", "editGroupPermission": "Modifier l'autorisation — {{group}}", "revoke": "Révoquer", - "tabSimulate": "Simuler" + "tabSimulate": "Simuler", + "verificationSection": "Vérification post-déploiement", + "verificationEnabled": "Vérifier après la mise en production", + "verificationEnabledHelp": "Dès que le pipeline signale SUCCEEDED, AccessFlow échantillonne ces contrôles pendant la fenêtre. Un dépassement marque le déploiement en échec — AccessFlow ne fait jamais de retour arrière.", + "verificationWindow": "Fenêtre", + "verificationInterval": "Échantillonner toutes les", + "verificationThreshold": "Échecs avant dépassement", + "verificationMinutes": "min", + "verificationWindowRange": "La fenêtre doit être comprise entre 1 et 1440 minutes.", + "verificationIntervalRange": "L’intervalle d’échantillonnage doit être d’au moins 0,5 minute et ne pas dépasser la fenêtre.", + "verificationThresholdRange": "Le seuil d’échec doit être compris entre 1 et 20.", + "verificationThresholdExceedsSamples": "La fenêtre collecte au plus {{samples}} échantillons — baissez le seuil ou élargissez la fenêtre.", + "verificationChecksRange": "Ajoutez entre 1 et 10 contrôles.", + "verificationCheckKind": "Type de contrôle", + "verificationCheckName": "Nom du contrôle", + "verificationCheckNameDuplicate": "Un autre contrôle utilise déjà ce nom.", + "verificationRemoveCheck": "Supprimer le contrôle", + "verificationAddCheck": "Ajouter un contrôle", + "verificationUrl": "URL de santé", + "verificationUrlScheme": "Utilisez une URL http:// ou https://.", + "verificationExpectedStatus": "Statut attendu", + "verificationExpectedStatusRange": "Le statut attendu doit être compris entre 100 et 599.", + "verificationBodyContains": "Le corps contient (facultatif)", + "verificationPrometheusUrl": "URL Prometheus", + "verificationPrometheusUrlHelp": "URL de base uniquement — /api/v1/query est ajouté.", + "verificationQuery": "Requête PromQL", + "verificationComparator": "Réussit quand la valeur est", + "verificationValueThreshold": "Seuil", + "verificationNoDataIsFailure": "Absence de données = échec", + "verificationColumn": "Vérification", + "verificationChecksCount": "Contrôles : {{n}}" }, "freezeWindows": { "title": "Fenêtres de gel", diff --git a/frontend/src/locales/hy.json b/frontend/src/locales/hy.json index 9234ca6d3..ac3b2629b 100644 --- a/frontend/src/locales/hy.json +++ b/frontend/src/locales/hy.json @@ -4038,6 +4038,23 @@ "DAY": "Կանչեր օրում", "USER_MINUTE": "Մեկ օգտատիրոջ կանչեր րոպեում", "USER_DAY": "Մեկ օգտատիրոջ կանչեր օրում" + }, + "verification_status": { + "PENDING": "սպասվում է", + "RUNNING": "ընթացքում է", + "PASSED": "անցել է", + "FAILED": "ձախողվել է", + "SKIPPED": "բաց է թողնվել" + }, + "verification_check_kind": { + "HTTP_HEALTH": "HTTP առողջություն", + "PROMQL_THRESHOLD": "PromQL շեմ" + }, + "verification_comparator": { + "LT": "<", + "LTE": "≤", + "GT": ">", + "GTE": "≥" } }, "access": { @@ -5755,7 +5772,8 @@ "versionFilterPlaceholder": "Ճշգրիտ տարբերակ", "countLabel": "{{total}} տեղակայում", "empty": "Դեռ տեղակայման հայտեր չկան", - "notFound": "Տեղակայման հայտը չի գտնվել" + "notFound": "Տեղակայման հայտը չի գտնվել", + "verificationTag": "ստուգում՝ {{status}}" }, "detail": { "title": "Տեղակայում", @@ -5816,7 +5834,25 @@ "timeline_released": "Թողարկում", "timeline_execution_failed": "Կատարումը ձախողվեց", "timeline_cancelled": "Չեղարկված", - "timeline_outcome": "Արդյունք" + "timeline_outcome": "Արդյունք", + "verification": "Ստուգում", + "verificationFailedTitle": "Ստուգումը ձախողվեց — թողարկումը դեռ աշխատում է", + "verificationFailedBody": "AccessFlow-ը ոչինչ հետ չի գլորել։ Որոշեք՝ արդյոք հետ գլորել, ապա pipeline-ից հաղորդեք ROLLED_BACK։", + "verificationWindow": "Պատուհան", + "verificationInterval": "Նմուշառման միջակայք", + "verificationThreshold": "Ձախողման շեմ", + "verificationStarted": "Սկսվել է", + "verificationFinished": "Ավարտվել է", + "verificationDetail": "Մանրամասն", + "verificationSampledAt": "Նմուշառվել է", + "verificationCheck": "Ստուգում", + "verificationResult": "Արդյունք", + "verificationObserved": "Դիտարկված", + "verificationSampleDetail": "Մանրամասն", + "verificationNoSamples": "Նմուշներ դեռ չկան", + "verificationMinutesValue": "{{n}} րոպե", + "verificationSecondsValue": "{{n}} վ", + "timeline_verification": "Ստուգում" }, "reviews": { "approve": "Հաստատել", @@ -6059,7 +6095,37 @@ "editUserPermission": "Խմբագրել թույլտվությունը — {{user}}", "editGroupPermission": "Խմբագրել թույլտվությունը — {{group}}", "revoke": "Հետ կանչել", - "tabSimulate": "Սիմուլյացիա" + "tabSimulate": "Սիմուլյացիա", + "verificationSection": "Տեղակայումից հետո ստուգում", + "verificationEnabled": "Ստուգել թողարկումից հետո", + "verificationEnabledHelp": "Երբ pipeline-ը հաղորդում է SUCCEEDED, AccessFlow-ը պատուհանի ընթացքում նմուշառում է այս ստուգումները։ Խախտումը տեղակայումը նշում է որպես ձախողված — AccessFlow-ը երբեք ոչինչ հետ չի գլորում։", + "verificationWindow": "Պատուհան", + "verificationInterval": "Նմուշառել ամեն", + "verificationThreshold": "Ձախողումներ մինչև խախտում", + "verificationMinutes": "րոպե", + "verificationWindowRange": "Պատուհանը պետք է լինի 1-ից 1440 րոպե։", + "verificationIntervalRange": "Նմուշառման միջակայքը պետք է լինի առնվազն 0,5 րոպե և չգերազանցի պատուհանը։", + "verificationThresholdRange": "Ձախողման շեմը պետք է լինի 1-ից 20։", + "verificationThresholdExceedsSamples": "Պատուհանը հավաքում է առավելագույնը {{samples}} նմուշ — իջեցրեք շեմը կամ մեծացրեք պատուհանը։", + "verificationChecksRange": "Ավելացրեք 1-ից 10 ստուգում։", + "verificationCheckKind": "Ստուգման տեսակ", + "verificationCheckName": "Ստուգման անվանում", + "verificationCheckNameDuplicate": "Այս անվանումն արդեն օգտագործվում է մեկ այլ ստուգման կողմից։", + "verificationRemoveCheck": "Հեռացնել ստուգումը", + "verificationAddCheck": "Ավելացնել ստուգում", + "verificationUrl": "Առողջության URL", + "verificationUrlScheme": "Օգտագործեք http:// կամ https:// URL։", + "verificationExpectedStatus": "Սպասվող կարգավիճակ", + "verificationExpectedStatusRange": "Սպասվող կարգավիճակը պետք է լինի 100-ից 599։", + "verificationBodyContains": "Մարմինը պարունակում է (ըստ ցանկության)", + "verificationPrometheusUrl": "Prometheus URL", + "verificationPrometheusUrlHelp": "Միայն բազային URL — /api/v1/query-ն ավելացվում է։", + "verificationQuery": "PromQL հարցում", + "verificationComparator": "Անցնում է, երբ արժեքը", + "verificationValueThreshold": "Շեմ", + "verificationNoDataIsFailure": "Տվյալների բացակայությունը ձախողում է", + "verificationColumn": "Ստուգում", + "verificationChecksCount": "Ստուգումներ՝ {{n}}" }, "freezeWindows": { "title": "Սառեցման պատուհաններ", diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json index 90d376c7f..abebbbb61 100644 --- a/frontend/src/locales/ru.json +++ b/frontend/src/locales/ru.json @@ -4038,6 +4038,23 @@ "DAY": "Вызовов в день", "USER_MINUTE": "Вызовов пользователя в минуту", "USER_DAY": "Вызовов пользователя в день" + }, + "verification_status": { + "PENDING": "ожидает", + "RUNNING": "выполняется", + "PASSED": "пройдена", + "FAILED": "не пройдена", + "SKIPPED": "пропущена" + }, + "verification_check_kind": { + "HTTP_HEALTH": "HTTP-проверка", + "PROMQL_THRESHOLD": "Порог PromQL" + }, + "verification_comparator": { + "LT": "<", + "LTE": "≤", + "GT": ">", + "GTE": "≥" } }, "access": { @@ -5755,7 +5772,8 @@ "versionFilterPlaceholder": "Точная версия", "countLabel": "{{total}} развертываний", "empty": "Запросов на развертывание пока нет", - "notFound": "Запрос на развертывание не найден" + "notFound": "Запрос на развертывание не найден", + "verificationTag": "проверка: {{status}}" }, "detail": { "title": "Развертывание", @@ -5816,7 +5834,25 @@ "timeline_released": "Выпуск", "timeline_execution_failed": "Ошибка выполнения", "timeline_cancelled": "Отменено", - "timeline_outcome": "Результат" + "timeline_outcome": "Результат", + "verification": "Проверка", + "verificationFailedTitle": "Проверка не пройдена — релиз продолжает работать", + "verificationFailedBody": "AccessFlow ничего не откатывал. Решите, нужен ли откат, затем сообщите ROLLED_BACK из pipeline.", + "verificationWindow": "Окно", + "verificationInterval": "Интервал опроса", + "verificationThreshold": "Порог сбоев", + "verificationStarted": "Начата", + "verificationFinished": "Завершена", + "verificationDetail": "Подробности", + "verificationSampledAt": "Время замера", + "verificationCheck": "Проверка", + "verificationResult": "Результат", + "verificationObserved": "Наблюдаемое", + "verificationSampleDetail": "Подробности", + "verificationNoSamples": "Замеров пока нет", + "verificationMinutesValue": "{{n}} мин", + "verificationSecondsValue": "{{n}} с", + "timeline_verification": "Проверка" }, "reviews": { "approve": "Одобрить", @@ -6059,7 +6095,37 @@ "editUserPermission": "Редактировать доступ — {{user}}", "editGroupPermission": "Редактировать доступ — {{group}}", "revoke": "Отозвать", - "tabSimulate": "Симуляция" + "tabSimulate": "Симуляция", + "verificationSection": "Проверка после развёртывания", + "verificationEnabled": "Проверять после релиза", + "verificationEnabledHelp": "Когда pipeline сообщает SUCCEEDED, AccessFlow опрашивает эти проверки в течение окна. Нарушение помечает развёртывание как неудачное — AccessFlow никогда ничего не откатывает.", + "verificationWindow": "Окно", + "verificationInterval": "Опрашивать каждые", + "verificationThreshold": "Сбоев до нарушения", + "verificationMinutes": "мин", + "verificationWindowRange": "Окно должно быть от 1 до 1440 минут.", + "verificationIntervalRange": "Интервал опроса должен быть не меньше 0,5 минуты и не больше окна.", + "verificationThresholdRange": "Порог сбоев должен быть от 1 до 20.", + "verificationThresholdExceedsSamples": "За окно собирается не более {{samples}} замеров — уменьшите порог или увеличьте окно.", + "verificationChecksRange": "Добавьте от 1 до 10 проверок.", + "verificationCheckKind": "Тип проверки", + "verificationCheckName": "Название проверки", + "verificationCheckNameDuplicate": "Это название уже используется другой проверкой.", + "verificationRemoveCheck": "Удалить проверку", + "verificationAddCheck": "Добавить проверку", + "verificationUrl": "URL проверки работоспособности", + "verificationUrlScheme": "Используйте URL http:// или https://.", + "verificationExpectedStatus": "Ожидаемый статус", + "verificationExpectedStatusRange": "Ожидаемый статус должен быть от 100 до 599.", + "verificationBodyContains": "Тело содержит (необязательно)", + "verificationPrometheusUrl": "URL Prometheus", + "verificationPrometheusUrlHelp": "Только базовый URL — /api/v1/query добавляется автоматически.", + "verificationQuery": "Запрос PromQL", + "verificationComparator": "Успешно, если значение", + "verificationValueThreshold": "Порог", + "verificationNoDataIsFailure": "Отсутствие данных — сбой", + "verificationColumn": "Проверка", + "verificationChecksCount": "Проверок: {{n}}" }, "freezeWindows": { "title": "Окна заморозки", diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json index b827ae7a5..b8f8d53d0 100644 --- a/frontend/src/locales/zh-CN.json +++ b/frontend/src/locales/zh-CN.json @@ -4038,6 +4038,23 @@ "DAY": "每日调用数", "USER_MINUTE": "单用户每分钟调用数", "USER_DAY": "单用户每日调用数" + }, + "verification_status": { + "PENDING": "待处理", + "RUNNING": "进行中", + "PASSED": "已通过", + "FAILED": "失败", + "SKIPPED": "已跳过" + }, + "verification_check_kind": { + "HTTP_HEALTH": "HTTP 健康检查", + "PROMQL_THRESHOLD": "PromQL 阈值" + }, + "verification_comparator": { + "LT": "<", + "LTE": "≤", + "GT": ">", + "GTE": "≥" } }, "access": { @@ -5755,7 +5772,8 @@ "versionFilterPlaceholder": "精确版本", "countLabel": "{{total}} 个部署", "empty": "暂无部署请求", - "notFound": "未找到部署请求" + "notFound": "未找到部署请求", + "verificationTag": "验证{{status}}" }, "detail": { "title": "部署", @@ -5816,7 +5834,25 @@ "timeline_released": "发布", "timeline_execution_failed": "执行失败", "timeline_cancelled": "已取消", - "timeline_outcome": "结果" + "timeline_outcome": "结果", + "verification": "验证", + "verificationFailedTitle": "验证失败——该版本仍在运行", + "verificationFailedBody": "AccessFlow 未执行回滚。请决定是否回滚,然后从流水线报告 ROLLED_BACK。", + "verificationWindow": "时间窗口", + "verificationInterval": "采样间隔", + "verificationThreshold": "失败阈值", + "verificationStarted": "开始时间", + "verificationFinished": "结束时间", + "verificationDetail": "详情", + "verificationSampledAt": "采样时间", + "verificationCheck": "检查", + "verificationResult": "结果", + "verificationObserved": "观测值", + "verificationSampleDetail": "详情", + "verificationNoSamples": "暂无样本", + "verificationMinutesValue": "{{n}} 分钟", + "verificationSecondsValue": "{{n}} 秒", + "timeline_verification": "验证" }, "reviews": { "approve": "批准", @@ -6059,7 +6095,37 @@ "editUserPermission": "编辑权限——{{user}}", "editGroupPermission": "编辑权限——{{group}}", "revoke": "撤销", - "tabSimulate": "模拟" + "tabSimulate": "模拟", + "verificationSection": "部署后验证", + "verificationEnabled": "发布后验证", + "verificationEnabledHelp": "流水线报告 SUCCEEDED 后,AccessFlow 会在时间窗口内对这些检查进行采样。一旦违规,部署会被标记为失败——AccessFlow 绝不会自动回滚。", + "verificationWindow": "时间窗口", + "verificationInterval": "采样间隔", + "verificationThreshold": "触发违规的失败次数", + "verificationMinutes": "分钟", + "verificationWindowRange": "时间窗口必须在 1 到 1440 分钟之间。", + "verificationIntervalRange": "采样间隔至少为 0.5 分钟,且不能超过时间窗口。", + "verificationThresholdRange": "失败阈值必须在 1 到 20 之间。", + "verificationThresholdExceedsSamples": "该时间窗口最多采集 {{samples}} 个样本——请降低阈值或扩大时间窗口。", + "verificationChecksRange": "请添加 1 到 10 个检查。", + "verificationCheckKind": "检查类型", + "verificationCheckName": "检查名称", + "verificationCheckNameDuplicate": "已有其他检查使用此名称。", + "verificationRemoveCheck": "移除检查", + "verificationAddCheck": "添加检查", + "verificationUrl": "健康检查 URL", + "verificationUrlScheme": "请使用 http:// 或 https:// URL。", + "verificationExpectedStatus": "期望状态码", + "verificationExpectedStatusRange": "期望状态码必须在 100 到 599 之间。", + "verificationBodyContains": "响应体包含(可选)", + "verificationPrometheusUrl": "Prometheus URL", + "verificationPrometheusUrlHelp": "仅填写基础 URL——会自动追加 /api/v1/query。", + "verificationQuery": "PromQL 查询", + "verificationComparator": "通过条件:值", + "verificationValueThreshold": "阈值", + "verificationNoDataIsFailure": "无数据视为失败", + "verificationColumn": "验证", + "verificationChecksCount": "检查:{{n}}" }, "freezeWindows": { "title": "冻结窗口", diff --git a/frontend/src/pages/deployments/DeploymentDetailPage.test.tsx b/frontend/src/pages/deployments/DeploymentDetailPage.test.tsx index 16e122d3a..9f748a73d 100644 --- a/frontend/src/pages/deployments/DeploymentDetailPage.test.tsx +++ b/frontend/src/pages/deployments/DeploymentDetailPage.test.tsx @@ -19,7 +19,9 @@ const { listPipelineEnvironmentVersionsMock, approveDeploymentMock, rejectDeploymentMock, + getDeploymentVerificationSamplesMock, } = vi.hoisted(() => ({ + getDeploymentVerificationSamplesMock: vi.fn(), getDeploymentRequestMock: vi.fn(), getDeploymentGateMock: vi.fn(), cancelDeploymentRequestMock: vi.fn(), @@ -48,6 +50,7 @@ vi.mock('@/api/deploymentRequests', () => ({ getDeploymentRequest: getDeploymentRequestMock, getDeploymentGate: getDeploymentGateMock, cancelDeploymentRequest: cancelDeploymentRequestMock, + getDeploymentVerificationSamples: getDeploymentVerificationSamplesMock, deploymentKeys: { all: ['deployments'] as const, lists: () => ['deployments', 'list'] as const, @@ -55,6 +58,7 @@ vi.mock('@/api/deploymentRequests', () => ({ details: () => ['deployments', 'detail'] as const, detail: (id: string) => ['deployments', 'detail', id] as const, gate: (id: string) => ['deployments', 'detail', id, 'gate'] as const, + verification: (id: string) => ['deployments', 'detail', id, 'verification'] as const, }, })); @@ -87,6 +91,7 @@ const baseRequest: DeploymentRequest = { outcome: null, outcome_reported_at: null, outcome_detail: null, + verification_status: 'PENDING', created_at: '2026-05-01T10:00:00Z', can_review: false, decisions: [ @@ -173,6 +178,8 @@ describe('DeploymentDetailPage', () => { listPipelineEnvironmentVersionsMock.mockResolvedValue([]); approveDeploymentMock.mockReset(); rejectDeploymentMock.mockReset(); + getDeploymentVerificationSamplesMock.mockReset(); + getDeploymentVerificationSamplesMock.mockResolvedValue([]); seedUser('u-me'); }); @@ -596,4 +603,114 @@ describe('DeploymentDetailPage', () => { expect(screen.queryByText(/^Superseded/)).not.toBeInTheDocument(); expect(screen.queryByText('Drift')).not.toBeInTheDocument(); }); + + describe('post-deployment verification (#1027)', () => { + const breached: DeploymentRequest = { + ...baseRequest, + status: 'FAILED', + outcome: 'SUCCEEDED', + outcome_reported_at: '2026-05-01T12:00:00Z', + verification_status: 'FAILED', + verification_started_at: '2026-05-01T12:00:00Z', + verification_finished_at: '2026-05-01T12:01:00Z', + verification_detail: 'health: 1/1 failed samples', + verification_snapshot: { + window: 'PT15M', + sample_interval: 'PT30S', + failure_threshold: 1, + check_count: 1, + }, + }; + const sample = { + id: 's-1', + deployment_request_id: 'req-1', + check_name: 'health', + check_kind: 'HTTP_HEALTH' as const, + sampled_at: '2026-05-01T12:00:30Z', + passed: false, + observed_value: '503', + detail: 'expected status 200, got 503', + }; + + it('shows the samples, the snapshot and the did-not-roll-back callout on a breach', async () => { + getDeploymentRequestMock.mockResolvedValue(breached); + getDeploymentVerificationSamplesMock.mockResolvedValue([sample]); + + render(wrap()); + + expect( + await screen.findByText('Verification failed — the release is still running'), + ).toBeInTheDocument(); + expect(screen.getByText(/AccessFlow did not roll back/)).toBeInTheDocument(); + expect(await screen.findByText('expected status 200, got 503')).toBeInTheDocument(); + expect(screen.getByText('503')).toBeInTheDocument(); + expect(screen.getByText('15 min')).toBeInTheDocument(); + expect(screen.getByText('30 s')).toBeInTheDocument(); + expect(screen.getAllByText('health: 1/1 failed samples').length).toBeGreaterThan(0); + expect(getDeploymentVerificationSamplesMock).toHaveBeenCalledWith('req-1'); + // Never a rollback: the release stage stays "released", not an execution failure. + expect(screen.queryByText(/rolled back/i)).toBeNull(); + }); + + it('fetches no samples and shows no card while verification is PENDING', async () => { + getDeploymentRequestMock.mockResolvedValue(baseRequest); + getDeploymentGateMock.mockResolvedValue(releasableGate); + + render(wrap()); + + await screen.findByText('Ship the checkout fix'); + expect(getDeploymentVerificationSamplesMock).not.toHaveBeenCalled(); + expect(screen.queryByText('No samples yet')).toBeNull(); + expect(screen.queryByText(/Verification failed/)).toBeNull(); + }); + + it('polls the request and the samples only while RUNNING', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + getDeploymentRequestMock.mockResolvedValue({ + ...breached, + status: 'EXECUTED', + verification_status: 'RUNNING', + verification_finished_at: null, + verification_detail: null, + verification_snapshot: null, + }); + + render(wrap()); + + expect(await screen.findByText('No samples yet')).toBeInTheDocument(); + expect(screen.queryByText(/Verification failed/)).toBeNull(); + const requestCalls = getDeploymentRequestMock.mock.calls.length; + const sampleCalls = getDeploymentVerificationSamplesMock.mock.calls.length; + await act(async () => { + await vi.advanceTimersByTimeAsync(10_500); + }); + await waitFor(() => + expect(getDeploymentVerificationSamplesMock.mock.calls.length).toBeGreaterThan(sampleCalls), + ); + expect(getDeploymentRequestMock.mock.calls.length).toBeGreaterThan(requestCalls); + } finally { + vi.useRealTimers(); + } + }); + + it('does not poll once the verification has finished', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + getDeploymentRequestMock.mockResolvedValue({ ...breached, verification_status: 'PASSED' }); + + render(wrap()); + + await screen.findByText('No samples yet'); + const sampleCalls = getDeploymentVerificationSamplesMock.mock.calls.length; + await act(async () => { + await vi.advanceTimersByTimeAsync(10_500); + }); + expect(getDeploymentVerificationSamplesMock.mock.calls.length).toBe(sampleCalls); + expect(screen.queryByText(/Verification failed/)).toBeNull(); + } finally { + vi.useRealTimers(); + } + }); + }); }); diff --git a/frontend/src/pages/deployments/DeploymentDetailPage.tsx b/frontend/src/pages/deployments/DeploymentDetailPage.tsx index fc8beaa08..094ded6e4 100644 --- a/frontend/src/pages/deployments/DeploymentDetailPage.tsx +++ b/frontend/src/pages/deployments/DeploymentDetailPage.tsx @@ -29,6 +29,7 @@ import { deploymentKeys, getDeploymentGate, getDeploymentRequest, + getDeploymentVerificationSamples, } from '@/api/deploymentRequests'; import { deploymentVersionKeys, @@ -47,12 +48,20 @@ import { pipelineProviderLabel, reviewDecisionTypeLabel, submissionReasonLabel, + verificationStatusLabel, } from '@/utils/enumLabels'; +import { verificationStatusColor } from '@/utils/statusColors'; +import { isoDurationSeconds } from '@/components/deployments/verificationForm'; import { fmtDate } from '@/utils/dateFormat'; import { apiErrorMessage } from '@/utils/apiErrors'; import { showApiError } from '@/utils/showApiError'; import { buildDeploymentTimelineStages } from './buildDeploymentTimelineStages'; -import type { DeploymentDecision, DeploymentRequest } from '@/types/api'; +import type { + DeploymentDecision, + DeploymentRequest, + DeploymentVerificationSample, + VerificationStatus, +} from '@/types/api'; import { OnBehalfOfTag } from '@/components/common/OnBehalfOfTag'; /** @@ -65,6 +74,27 @@ function isCancellable(request: DeploymentRequest): boolean { return new Date(request.scheduled_for).getTime() > Date.now(); } +/** How often a running verification window is re-read; the job samples every 30 s by default. */ +const VERIFICATION_POLL_MS = 10_000; + +function VerificationTag({ status }: { status: VerificationStatus }) { + const { t } = useTranslation(); + const color = verificationStatusColor(status); + return ( + + {verificationStatusLabel(t, status)} + + ); +} + +function durationText(t: ReturnType['t'], iso: string | null | undefined) { + const seconds = isoDurationSeconds(iso); + if (seconds == null) return iso ?? '—'; + return seconds % 60 === 0 + ? t('deploygov.detail.verificationMinutesValue', { n: seconds / 60 }) + : t('deploygov.detail.verificationSecondsValue', { n: seconds }); +} + export default function DeploymentDetailPage() { const { t } = useTranslation(); const { id = '' } = useParams(); @@ -79,8 +109,21 @@ export default function DeploymentDetailPage() { queryKey: deploymentKeys.detail(id), queryFn: () => getDeploymentRequest(id), enabled: !!id, + // A breach flips the request to FAILED; only the submitter gets a WebSocket push, so poll + // while the window is open. + refetchInterval: (query) => + query.state.data?.verification_status === 'RUNNING' ? VERIFICATION_POLL_MS : false, }); const request = requestQuery.data; + const verificationStatus = request?.verification_status ?? 'PENDING'; + const verificationRunning = verificationStatus === 'RUNNING'; + + const samplesQuery = useQuery({ + queryKey: deploymentKeys.verification(id), + queryFn: () => getDeploymentVerificationSamples(id), + enabled: !!id && verificationStatus !== 'PENDING', + refetchInterval: verificationRunning ? VERIFICATION_POLL_MS : false, + }); // Freeze state lives only on the gate; ask it just while the request is APPROVED. // A 404 (visibility) simply hides the banner — retry would never succeed. @@ -213,6 +256,36 @@ export default function DeploymentDetailPage() { }, ]; + const sampleColumns: TableColumnsType = [ + { + title: t('deploygov.detail.verificationSampledAt'), + dataIndex: 'sampled_at', + render: (v: string) => fmtDate(v), + }, + { title: t('deploygov.detail.verificationCheck'), dataIndex: 'check_name' }, + { + title: t('deploygov.detail.verificationResult'), + dataIndex: 'passed', + render: (passed: boolean) => ( + + ), + }, + { + title: t('deploygov.detail.verificationObserved'), + dataIndex: 'observed_value', + render: (v: string | null | undefined) => ( + + {v ?? '—'} + + ), + }, + { + title: t('deploygov.detail.verificationSampleDetail'), + dataIndex: 'detail', + render: (v: string | null | undefined) => v ?? '—', + }, + ]; + const metadataEntries = Object.keys(request?.metadata ?? {}); return ( @@ -260,6 +333,26 @@ export default function DeploymentDetailPage() { /> )} + {/* FAILED + SUCCEEDED: the deploy ran and is still live. Never phrase this as a + rollback — AccessFlow does not roll anything back. */} + {verificationStatus === 'FAILED' && ( + + {request.verification_detail && ( +
+ {request.verification_detail} +
+ )} + {t('deploygov.detail.verificationFailedBody')} + + } + /> + )} + {request.version}, }, ...(driftRow ? [driftRow] : []), + // Beside drift on purpose: the matrix's unchanged "current" says nothing about + // whether that version is healthy. + ...(verificationStatus !== 'PENDING' + ? [ + { + key: 'verification', + label: t('deploygov.detail.verification'), + children: , + }, + ] + : []), { key: 'commit', label: t('deploygov.detail.commit'), @@ -459,6 +563,73 @@ export default function DeploymentDetailPage() {
+ {verificationStatus !== 'PENDING' && ( + } + > +
+ + + rowKey="id" + size="small" + pagination={false} + loading={samplesQuery.isLoading} + dataSource={samplesQuery.data ?? []} + columns={sampleColumns} + locale={{ emptyText: t('deploygov.detail.verificationNoSamples') }} + scroll={{ x: true }} + /> +
+
+ )} + {(request.change_ticket_required || request.change_ticket) && (
diff --git a/frontend/src/pages/deployments/DeploymentListPage.test.tsx b/frontend/src/pages/deployments/DeploymentListPage.test.tsx index 05b6f4507..06b9f7b55 100644 --- a/frontend/src/pages/deployments/DeploymentListPage.test.tsx +++ b/frontend/src/pages/deployments/DeploymentListPage.test.tsx @@ -88,6 +88,7 @@ const baseRequest: DeploymentRequest = { outcome: null, outcome_reported_at: null, outcome_detail: null, + verification_status: 'PENDING', created_at: '2026-05-01T10:00:00Z', decisions: [], can_review: false, @@ -171,6 +172,39 @@ describe('DeploymentListPage', () => { expect(screen.getByText('1 deployments')).toBeInTheDocument(); }); + it('tags a breached verification beside the SUCCEEDED outcome, and nothing while PENDING', async () => { + listDeploymentRequestsMock.mockResolvedValue( + pageOf([ + { + ...baseRequest, + id: 'req-breach', + version: '3.0.0', + status: 'FAILED', + outcome: 'SUCCEEDED', + outcome_reported_at: '2026-05-01T12:00:00Z', + verification_status: 'FAILED', + }, + { ...baseRequest, id: 'req-pending', version: '3.0.1' }, + ]), + ); + + render(wrap()); + + expect(await screen.findByText('verification failed')).toBeInTheDocument(); + expect(screen.getByText('succeeded')).toBeInTheDocument(); + expect(screen.getAllByText(/^verification /)).toHaveLength(1); + }); + + it('shows a skipped verification for a request without an outcome tag', async () => { + listDeploymentRequestsMock.mockResolvedValue( + pageOf([{ ...baseRequest, verification_status: 'SKIPPED' }]), + ); + + render(wrap()); + + expect(await screen.findByText('verification skipped')).toBeInTheDocument(); + }); + it('shows the linked change ticket with its decision in the ticket column', async () => { listDeploymentRequestsMock.mockResolvedValue( pageOf([ diff --git a/frontend/src/pages/deployments/DeploymentListPage.tsx b/frontend/src/pages/deployments/DeploymentListPage.tsx index 5510bcdbd..c09f243ed 100644 --- a/frontend/src/pages/deployments/DeploymentListPage.tsx +++ b/frontend/src/pages/deployments/DeploymentListPage.tsx @@ -16,8 +16,13 @@ import { } from '@/api/deploymentVersions'; import { DriftChip } from '@/components/deployments/versionMatrixCells'; import { ChangeTicketLink } from '@/components/deployments/ChangeTicketLink'; -import { deploymentOutcomeLabel, enumOptions, queryStatusLabel } from '@/utils/enumLabels'; -import { deploymentOutcomeColor } from '@/utils/statusColors'; +import { + deploymentOutcomeLabel, + enumOptions, + queryStatusLabel, + verificationStatusLabel, +} from '@/utils/enumLabels'; +import { deploymentOutcomeColor, verificationStatusColor } from '@/utils/statusColors'; import { timeAgo } from '@/utils/dateFormat'; import { usePermission } from '@/utils/permissions'; import type { DeploymentEnvironmentVersion, DeploymentRequest, QueryStatus } from '@/types/api'; @@ -145,13 +150,33 @@ export default function DeploymentListPage() { title: t('deploygov.deployments.outcome'), dataIndex: 'outcome', width: 130, - render: (outcome: DeploymentRequest['outcome']) => { - if (outcome == null) return —; - const color = deploymentOutcomeColor(outcome); + render: (outcome: DeploymentRequest['outcome'], row) => { + const verification = row.verification_status ?? 'PENDING'; + if (outcome == null && verification === 'PENDING') return —; + const color = outcome == null ? null : deploymentOutcomeColor(outcome); + const verificationColor = verificationStatusColor(verification); return ( - - {deploymentOutcomeLabel(t, outcome)} - + + {outcome != null && color && ( + + {deploymentOutcomeLabel(t, outcome)} + + )} + {/* A breach leaves outcome SUCCEEDED, so the verification tag says it failed. */} + {verification !== 'PENDING' && ( + + {t('deploygov.deployments.verificationTag', { + status: verificationStatusLabel(t, verification), + })} + + )} + ); }, }, diff --git a/frontend/src/pages/deployments/buildDeploymentTimelineStages.test.ts b/frontend/src/pages/deployments/buildDeploymentTimelineStages.test.ts index 1ca331b35..b201be32f 100644 --- a/frontend/src/pages/deployments/buildDeploymentTimelineStages.test.ts +++ b/frontend/src/pages/deployments/buildDeploymentTimelineStages.test.ts @@ -50,6 +50,7 @@ function makeRequest(overrides: Partial): DeploymentRequest { outcome: null, outcome_reported_at: null, outcome_detail: null, + verification_status: 'PENDING', created_at: '2026-08-20T10:00:00Z', decisions: [], can_review: false, @@ -194,4 +195,76 @@ describe('buildDeploymentTimelineStages', () => { expect(release?.label).toBe('deploygov.detail.timeline_cancelled'); expect(release?.cancelled).toBe(true); }); + + describe('post-deployment verification stage (#1027)', () => { + const released = { + status: 'EXECUTED' as QueryStatus, + outcome: 'SUCCEEDED' as const, + outcome_reported_at: '2026-08-20T12:00:00Z', + }; + + it('adds no stage while verification is PENDING', () => { + const stages = buildDeploymentTimelineStages(makeRequest(released), t); + expect(stages.map((s) => s.label)).not.toContain('deploygov.detail.timeline_verification'); + }); + + it.each([ + ['RUNNING', { active: true }], + ['PASSED', { done: true }], + ['FAILED', { failed: true }], + ['SKIPPED', { skipped: true }], + ] as const)('renders %s after the outcome stage', (status, flags) => { + const stages = buildDeploymentTimelineStages( + makeRequest({ + ...released, + ...(status === 'FAILED' ? { status: 'FAILED' as QueryStatus } : {}), + verification_status: status, + verification_finished_at: status === 'RUNNING' ? null : '2026-08-20T12:15:00Z', + verification_detail: 'health: 1/1 failed samples', + }), + t, + ); + const last = stages[stages.length - 1]; + expect(stages[stages.length - 2]?.label).toBe('deploygov.detail.timeline_outcome'); + expect(last?.label).toBe('deploygov.detail.timeline_verification'); + expect(last?.who).toBe(`enums.verification_status.${status}`); + expect(last?.detail).toBe('health: 1/1 failed samples'); + expect(last?.time).toBe(status === 'RUNNING' ? null : '2026-08-20T12:15:00Z'); + expect(last).toMatchObject(flags); + }); + + it('keeps the release stage released when verification failed a SUCCEEDED deploy', () => { + const stages = buildDeploymentTimelineStages( + makeRequest({ + ...released, + status: 'FAILED', + verification_status: 'FAILED', + }), + t, + ); + const release = stages.find((s) => s.label === 'deploygov.detail.timeline_released'); + expect(release).toMatchObject({ done: true, failed: false }); + expect(stages.map((s) => s.label)).not.toContain('deploygov.detail.timeline_execution_failed'); + const outcome = stages.find((s) => s.label === 'deploygov.detail.timeline_outcome'); + expect(outcome).toMatchObject({ done: true, failed: false }); + expect(stages[stages.length - 1]).toMatchObject({ failed: true }); + }); + + it('shows a SKIPPED stage for a request whose first outcome failed', () => { + const stages = buildDeploymentTimelineStages( + makeRequest({ + status: 'FAILED', + outcome: 'FAILED', + outcome_reported_at: '2026-08-20T12:00:00Z', + verification_status: 'SKIPPED', + verification_detail: 'outcome:FAILED', + }), + t, + ); + expect(stages[stages.length - 1]).toMatchObject({ + label: 'deploygov.detail.timeline_verification', + skipped: true, + }); + }); + }); }); diff --git a/frontend/src/pages/deployments/buildDeploymentTimelineStages.ts b/frontend/src/pages/deployments/buildDeploymentTimelineStages.ts index 972d9950a..9c455424d 100644 --- a/frontend/src/pages/deployments/buildDeploymentTimelineStages.ts +++ b/frontend/src/pages/deployments/buildDeploymentTimelineStages.ts @@ -2,7 +2,11 @@ import type { TFunction } from 'i18next'; import type { TimelineStage } from '@/components/review/ApprovalTimeline'; import type { DeploymentRequest } from '@/types/api'; import { fmtDate } from '@/utils/dateFormat'; -import { deploymentOutcomeLabel, riskLevelLabel } from '@/utils/enumLabels'; +import { + deploymentOutcomeLabel, + riskLevelLabel, + verificationStatusLabel, +} from '@/utils/enumLabels'; const REVIEW_DONE_STATUSES = ['APPROVED', 'EXECUTED', 'FAILED', 'CANCELLED'] as const; @@ -98,6 +102,8 @@ export function buildDeploymentTimelineStages( } const executed = request.status === 'EXECUTED' || request.outcome_reported_at != null; + // A verification breach (#1025) is FAILED with a SUCCEEDED outcome: the release did run, so + // only a FAILED request with no outcome at all reads as an execution failure here. const executionFailed = request.status === 'FAILED' && request.outcome == null; out.push({ label: @@ -124,5 +130,20 @@ export function buildDeploymentTimelineStages( detail: request.outcome_detail, }); } + + // Starts on the outcome report, so it sits after the outcome stage; nothing to show before. + const verification = request.verification_status; + if (verification != null && verification !== 'PENDING') { + out.push({ + label: t('deploygov.detail.timeline_verification'), + who: verificationStatusLabel(t, verification), + time: request.verification_finished_at ?? null, + done: verification === 'PASSED', + active: verification === 'RUNNING', + failed: verification === 'FAILED', + skipped: verification === 'SKIPPED', + detail: request.verification_detail ?? null, + }); + } return out; } diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts index f933413de..4db2c9e56 100644 --- a/frontend/src/types/api.ts +++ b/frontend/src/types/api.ts @@ -5213,6 +5213,86 @@ export type FreezeBehavior = 'HOLD' | 'REJECT'; export type DeploymentOutcome = 'SUCCEEDED' | 'FAILED' | 'ROLLED_BACK'; +// ─── Post-deployment verification (#1023–#1027) ─── + +/** `PENDING` until the first outcome report; `FAILED` flips the request to `FAILED` (#1025). */ +export type VerificationStatus = 'PENDING' | 'RUNNING' | 'PASSED' | 'FAILED' | 'SKIPPED'; + +export type VerificationCheckKind = 'HTTP_HEALTH' | 'PROMQL_THRESHOLD'; + +export type VerificationComparator = 'LT' | 'LTE' | 'GT' | 'GTE'; + +/** Request shape of an HTTP health check — `expected_status` defaults to 200 server-side. */ +export interface HttpHealthCheckInput { + kind: 'HTTP_HEALTH'; + name: string; + url: string; + expected_status?: number | null; + body_contains?: string | null; +} + +/** Request shape of a PromQL threshold check — `no_data_is_failure` defaults to true. */ +export interface PromqlThresholdCheckInput { + kind: 'PROMQL_THRESHOLD'; + name: string; + prometheus_url: string; + query: string; + comparator: VerificationComparator; + threshold: number; + no_data_is_failure?: boolean | null; +} + +export type VerificationCheckInput = HttpHealthCheckInput | PromqlThresholdCheckInput; + +export interface DeploymentVerificationConfigInput { + /** ISO-8601 duration, PT1M..PT24H. */ + window: string; + /** ISO-8601 duration, PT30S..window. */ + sample_interval: string; + failure_threshold: number; + checks: VerificationCheckInput[]; +} + +/** Response check — flat like the server record; the other kind's fields are omitted. */ +export interface VerificationCheck { + kind: VerificationCheckKind; + name: string; + url?: string | null; + expected_status?: number | null; + body_contains?: string | null; + prometheus_url?: string | null; + query?: string | null; + comparator?: VerificationComparator | null; + threshold?: number | null; + no_data_is_failure?: boolean | null; +} + +export interface DeploymentVerificationConfig { + window: string; + sample_interval: string; + failure_threshold: number; + checks: VerificationCheck[]; +} + +/** The config a request was verified against (#1027) — no check targets, by design. */ +export interface DeploymentVerificationSnapshot { + window?: string | null; + sample_interval?: string | null; + failure_threshold: number; + check_count: number; +} + +export interface DeploymentVerificationSample { + id: string; + deployment_request_id: string; + check_name: string; + check_kind: VerificationCheckKind; + sampled_at: string; + passed: boolean; + observed_value?: string | null; + detail?: string | null; +} + /** Same literals as RoutingAction; a distinct alias keeps the deploygov surface self-describing. */ export type DeploymentRoutingAction = RoutingAction; @@ -5273,6 +5353,8 @@ export interface DeploymentEnvironment { change_ticket_required: boolean; /** The datasource this environment's schema changes land on; null = deploy-only (#877). */ datasource_id: string | null; + /** Omitted when verification is off (#1023). */ + verification?: DeploymentVerificationConfig | null; created_at: string; } @@ -5287,6 +5369,7 @@ export interface CreateDeploymentEnvironmentInput { allow_break_glass?: boolean; change_ticket_required?: boolean; datasource_id?: string | null; + verification?: DeploymentVerificationConfigInput | null; } export interface UpdateDeploymentEnvironmentInput { @@ -5307,6 +5390,9 @@ export interface UpdateDeploymentEnvironmentInput { /** Null leaves the binding unchanged; `clear_datasource: true` unbinds and wins (#877). */ datasource_id?: string | null; clear_datasource?: boolean; + /** Null leaves the config unchanged; `clear_verification: true` removes it and wins (#1023). */ + verification?: DeploymentVerificationConfigInput | null; + clear_verification?: boolean; } export interface DeploymentPipelinePermission { @@ -5587,6 +5673,13 @@ export interface DeploymentRequest { change_ticket_required?: boolean; /** Absent when no ticket is linked (#994). */ change_ticket?: DeploymentTicketRef | null; + /** Never null on the wire (#1025). */ + verification_status: VerificationStatus; + verification_started_at?: string | null; + verification_finished_at?: string | null; + verification_detail?: string | null; + /** The config the window was opened with (#1027); absent when never verified. */ + verification_snapshot?: DeploymentVerificationSnapshot | null; } export type DeploymentRequestPage = PageEnvelope; @@ -5682,6 +5775,9 @@ export interface DeploymentGateStatus { change_ticket_required?: boolean; /** The ticket the gate judged by; absent when none is linked (#993). */ change_ticket?: DeploymentTicketRef | null; + /** Post-deployment verification state (#1025); never feeds `releasable`. */ + verification_status?: VerificationStatus; + verification_detail?: string | null; } // ─── Deployment version inventory & drift (#742 API, #743 UI) ─── diff --git a/frontend/src/utils/__tests__/enumLabels.test.ts b/frontend/src/utils/__tests__/enumLabels.test.ts index 4d0fa3c46..89aff2aa8 100644 --- a/frontend/src/utils/__tests__/enumLabels.test.ts +++ b/frontend/src/utils/__tests__/enumLabels.test.ts @@ -3,6 +3,12 @@ import type { TFunction } from 'i18next'; import i18n from '@/i18n'; import { accessGrantStatusLabel, + VERIFICATION_CHECK_KINDS, + VERIFICATION_COMPARATORS, + VERIFICATION_STATUSES, + verificationCheckKindLabel, + verificationComparatorLabel, + verificationStatusLabel, aiProviderLabel, authProviderLabel, channelTypeLabel, @@ -304,3 +310,19 @@ describe('API governance enum labels (AF-500)', () => { } }); }); + +describe('post-deployment verification enum labels (#1027)', () => { + it('translates every verification status, check kind and comparator', () => { + for (const v of VERIFICATION_STATUSES) { + expect(verificationStatusLabel(t, v)).not.toBe(`enums.verification_status.${v}`); + } + for (const v of VERIFICATION_CHECK_KINDS) { + expect(verificationCheckKindLabel(t, v)).not.toBe(`enums.verification_check_kind.${v}`); + } + for (const v of VERIFICATION_COMPARATORS) { + expect(verificationComparatorLabel(t, v)).not.toBe(`enums.verification_comparator.${v}`); + } + expect(verificationStatusLabel(t, 'FAILED')).toBe('failed'); + expect(verificationComparatorLabel(t, 'LT')).toBe('<'); + }); +}); diff --git a/frontend/src/utils/__tests__/statusColors.test.ts b/frontend/src/utils/__tests__/statusColors.test.ts index e21a302ba..26554c154 100644 --- a/frontend/src/utils/__tests__/statusColors.test.ts +++ b/frontend/src/utils/__tests__/statusColors.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { accessGrantStatusColor, statusColor } from '../statusColors'; -import type { AccessGrantStatus, QueryStatus } from '@/types/api'; +import { accessGrantStatusColor, statusColor, verificationStatusColor } from '../statusColors'; +import type { AccessGrantStatus, QueryStatus, VerificationStatus } from '@/types/api'; describe('statusColor', () => { it.each<[QueryStatus, string]>([ @@ -59,3 +59,14 @@ describe('accessGrantStatusColor', () => { }); }); +describe('verificationStatusColor', () => { + it.each<[VerificationStatus, string]>([ + ['PENDING', 'var(--fg-muted)'], + ['RUNNING', 'var(--status-info)'], + ['PASSED', 'var(--risk-low)'], + ['FAILED', 'var(--risk-crit)'], + ['SKIPPED', 'var(--fg-muted)'], + ])('maps %s to the expected fg token', (status, fg) => { + expect(verificationStatusColor(status).fg).toBe(fg); + }); +}); diff --git a/frontend/src/utils/enumLabels.ts b/frontend/src/utils/enumLabels.ts index edea54104..2512d746a 100644 --- a/frontend/src/utils/enumLabels.ts +++ b/frontend/src/utils/enumLabels.ts @@ -82,6 +82,9 @@ import type { RowSecurityValueType, DiscoveryDetector, DeploymentOutcome, + VerificationCheckKind, + VerificationComparator, + VerificationStatus, LeadTimeSource, DeploymentTicketDecision, DeploymentRollbackReviewStatus, @@ -1001,6 +1004,35 @@ export const DEPLOYMENT_OUTCOMES: readonly DeploymentOutcome[] = [ export const deploymentOutcomeLabel = (t: TFunction, v: DeploymentOutcome): string => t(`enums.deployment_outcome.${v}` as const); +export const VERIFICATION_STATUSES: readonly VerificationStatus[] = [ + 'PENDING', + 'RUNNING', + 'PASSED', + 'FAILED', + 'SKIPPED', +] as const; + +export const verificationStatusLabel = (t: TFunction, v: VerificationStatus): string => + t(`enums.verification_status.${v}` as const); + +export const VERIFICATION_CHECK_KINDS: readonly VerificationCheckKind[] = [ + 'HTTP_HEALTH', + 'PROMQL_THRESHOLD', +] as const; + +export const verificationCheckKindLabel = (t: TFunction, v: VerificationCheckKind): string => + t(`enums.verification_check_kind.${v}` as const); + +export const VERIFICATION_COMPARATORS: readonly VerificationComparator[] = [ + 'LT', + 'LTE', + 'GT', + 'GTE', +] as const; + +export const verificationComparatorLabel = (t: TFunction, v: VerificationComparator): string => + t(`enums.verification_comparator.${v}` as const); + export const leadTimeSourceLabel = (t: TFunction, v: LeadTimeSource): string => t(`enums.lead_time_source.${v}` as const); diff --git a/frontend/src/utils/statusColors.ts b/frontend/src/utils/statusColors.ts index 4f2c65008..e18aee304 100644 --- a/frontend/src/utils/statusColors.ts +++ b/frontend/src/utils/statusColors.ts @@ -9,6 +9,7 @@ import type { BreakGlassEventStatus, DecisionStepOutcome, DeploymentOutcome, + VerificationStatus, DeploymentRollbackReviewStatus, DeploymentTicketDecision, GrantUsageRecommendation, @@ -387,3 +388,18 @@ export const apiDriftFindingKindColor = (kind: ApiDriftFindingKind): ColorTriple return WARN; } }; + +/** A FAILED verification is the release's health, not a rollback — crit, never the warn tone. */ +export const verificationStatusColor = (status: VerificationStatus): ColorTriple => { + switch (status) { + case 'PASSED': + return { fg: 'var(--risk-low)', bg: 'var(--risk-low-bg)', border: 'var(--risk-low-border)' }; + case 'FAILED': + return { fg: 'var(--risk-crit)', bg: 'var(--risk-crit-bg)', border: 'var(--risk-crit-border)' }; + case 'RUNNING': + return { fg: 'var(--status-info)', bg: 'var(--status-info-bg)', border: 'var(--status-info-border)' }; + case 'PENDING': + case 'SKIPPED': + return { fg: 'var(--fg-muted)', bg: 'var(--status-neutral-bg)', border: 'var(--status-neutral-border)' }; + } +}; diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 3a1658551..4d3832a23 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -187,6 +187,7 @@ export default defineConfig({ 'src/components/deployments/deploymentRoutingPolicyForm.ts', 'src/components/deployments/versionMatrix.ts', 'src/components/deployments/environmentLadder.ts', + 'src/components/deployments/verificationForm.ts', 'src/pages/requestGroups/groupBuilder.ts', 'src/pages/lifecycle/erasureConfigForm.ts', 'src/realtime/collabProvider.ts', diff --git a/help-corpus/manifest.json b/help-corpus/manifest.json index 8eca2ac6f..3fc6e8aac 100644 --- a/help-corpus/manifest.json +++ b/help-corpus/manifest.json @@ -1,8 +1,8 @@ { "schemaVersion": 1, "corpusVersion": "debe778a1394", - "generatedAt": "2026-11-10T15:03:00.861Z", - "sourceCommit": "9a82bd18a235668d39ebecd1627ac4ae4b088727", + "generatedAt": "2026-11-11T07:13:06.668Z", + "sourceCommit": "d3bacb04fddb57c0401ca5960a70434162ea0aa4", "chunkCount": 615, "sha256": "debe778a139480445a9c4945403fec4d253471c837b75d6236b7484cddc70d4d", "quickReferenceSha256": "24edf02e4c124fee2ce843e9333a470905f9a55868ddc3cdef869315ca473072", @@ -429,7 +429,7 @@ "url": "https://accessflow.io/docs/", "section": "Navigation", "chunks": 9, - "sha256": "198c5a970d39cd6fee394942c8870147e1e3f405892d7ca377b3a1fb77c77177" + "sha256": "cb28ca6bd022a4eff61ced2c688c6b80351465cdf632a0ba3bed26c71b64905e" } ] } From fdbe7c54b0e05a6caa584c9a1f32cfd2e6d6632d Mon Sep 17 00:00:00 2001 From: Tigran Babloyan Date: Wed, 11 Nov 2026 11:34:42 +0400 Subject: [PATCH 2/2] =?UTF-8?q?fix(AF-1027):=20address=20review=20?= =?UTF-8?q?=E2=80=94=20422=20reasons,=20URL=20rules,=20stale=20samples?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Name the failed rule of a 422 DEPLOYMENT_VERIFICATION_INVALID from its reason/checkName (its detail is generic); mirror the userinfo and Prometheus query/fragment rules client-side; refetch samples when the window closes; outcome-aware breach callout after ROLLED_BACK; translate SKIPPED tokens and hide the empty card; hide SKIPPED in the list; pin the snapshot wire shape; doc wording fixes. --- .../DefaultDeploymentRequestService.java | 4 ++ .../internal/web/DeploygovWebModelsTest.java | 33 +++++++++ docs/04-api-spec.md | 12 ++-- docs/06-frontend.md | 6 +- docs/18-deployment-governance.md | 29 +++++--- e2e/tests/deployment-verification.spec.ts | 4 +- .../PipelineEnvironmentsTab.test.tsx | 43 ++++++++++-- .../deployments/PipelineEnvironmentsTab.tsx | 34 +++++++--- .../deployments/verificationForm.test.ts | 60 +++++++++++++++-- .../deployments/verificationForm.ts | 67 ++++++++++++++++++- frontend/src/locales/de.json | 27 +++++++- frontend/src/locales/en.json | 27 +++++++- frontend/src/locales/es.json | 27 +++++++- frontend/src/locales/fr.json | 27 +++++++- frontend/src/locales/hy.json | 27 +++++++- frontend/src/locales/ru.json | 27 +++++++- frontend/src/locales/zh-CN.json | 27 +++++++- .../deployments/DeploymentDetailPage.test.tsx | 57 ++++++++++++++++ .../deployments/DeploymentDetailPage.tsx | 58 +++++++++++++--- .../deployments/DeploymentListPage.test.tsx | 17 ++++- .../pages/deployments/DeploymentListPage.tsx | 6 +- .../buildDeploymentTimelineStages.test.ts | 26 ++++++- .../buildDeploymentTimelineStages.ts | 32 ++++++++- help-corpus/manifest.json | 6 +- 24 files changed, 604 insertions(+), 79 deletions(-) diff --git a/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestService.java b/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestService.java index da584e2aa..efe609d50 100644 --- a/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestService.java +++ b/backend/src/main/java/com/bablsoft/accessflow/deploygov/internal/DefaultDeploymentRequestService.java @@ -40,6 +40,7 @@ import com.bablsoft.accessflow.deploygov.internal.persistence.repo.DeploymentVerificationRepository; import com.bablsoft.accessflow.deploygov.internal.verification.DeploymentVerificationConfigCodec; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationEventPublisher; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.domain.Page; @@ -63,6 +64,7 @@ * trigger is idempotent on the CI run identity, and an active {@code REJECT} freeze window * auto-rejects at submission. */ +@Slf4j @Service @RequiredArgsConstructor public class DefaultDeploymentRequestService implements DeploymentRequestService { @@ -449,6 +451,8 @@ private DeploymentVerificationSnapshotView readVerificationSnapshot( return DeploymentVerificationSnapshotView.of( verificationConfigCodec.fromJson(entity.getVerificationConfig())); } catch (DeploymentVerificationConfigCodec.VerificationConfigParseException ex) { + log.debug("Unreadable verification snapshot on deployment request {}: {}", + entity.getId(), ex.getMessage()); return null; } } diff --git a/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/web/DeploygovWebModelsTest.java b/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/web/DeploygovWebModelsTest.java index 078d7a47a..1c570bab7 100644 --- a/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/web/DeploygovWebModelsTest.java +++ b/backend/src/test/java/com/bablsoft/accessflow/deploygov/internal/web/DeploygovWebModelsTest.java @@ -563,6 +563,39 @@ null, null, null, new DeploymentVerificationSnapshotView(Duration.ofMinutes(15), assertThat(DeploymentVerificationSnapshotView.of(null)).isNull(); } + @Test + void deploymentRequestWireShapeCarriesTheVerificationSnapshotInSnakeCase() { + var mapper = JsonMapper.builder() + .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) + .changeDefaultPropertyInclusion(incl -> incl.withValueInclusion( + JsonInclude.Include.NON_NULL)) + .build(); + var verified = new DeploymentRequestView(UUID.randomUUID(), UUID.randomUUID(), "p", + PipelineProvider.GENERIC, UUID.randomUUID(), "prod", UUID.randomUUID(), null, + "1.0.0", null, null, null, null, null, QueryStatus.EXECUTED, + SubmissionReason.USER_SUBMITTED, null, null, null, null, null, 1, null, null, null, + null, Instant.now(), null, null, null, false, null, VerificationStatus.RUNNING, + null, null, null, new DeploymentVerificationSnapshotView(Duration.ofMinutes(15), + Duration.ofSeconds(30), 3, 2)); + + var json = mapper.readTree(mapper.writeValueAsString(DeploymentRequestResponse.from(verified))); + + var snapshot = json.get("verification_snapshot"); + assertThat(snapshot.get("window").asString()).isEqualTo("PT15M"); + assertThat(snapshot.get("sample_interval").asString()).isEqualTo("PT30S"); + assertThat(snapshot.get("failure_threshold").asInt()).isEqualTo(3); + assertThat(snapshot.get("check_count").asInt()).isEqualTo(2); + + var unverified = new DeploymentRequestView(UUID.randomUUID(), UUID.randomUUID(), "p", + PipelineProvider.GENERIC, UUID.randomUUID(), "prod", UUID.randomUUID(), null, + "1.0.0", null, null, null, null, null, QueryStatus.APPROVED, + SubmissionReason.USER_SUBMITTED, null, null, null, null, null, 1, null, null, null, + null, Instant.now(), null); + var plain = mapper.readTree( + mapper.writeValueAsString(DeploymentRequestResponse.from(unverified))); + assertThat(plain.has("verification_snapshot")).isFalse(); + } + @Test void verificationSampleResponseMapsAllFields() { var view = new DeploymentVerificationSampleView(UUID.randomUUID(), UUID.randomUUID(), diff --git a/docs/04-api-spec.md b/docs/04-api-spec.md index 563272fe5..b4738f8b5 100644 --- a/docs/04-api-spec.md +++ b/docs/04-api-spec.md @@ -9516,11 +9516,13 @@ back. Break-glass deployments are verified like any other. Request detail and list bodies carry `verification_status`, `verification_started_at`, `verification_finished_at` and `verification_detail` (breach detail reads `": / failed samples"`); the gate carries `verification_status` and -`verification_detail`. Since #1027 they also carry `verification_snapshot` — the config the -window was opened with, omitted until a window opens (and when the stored snapshot cannot be -read): `{ "window": "PT15M", "sample_interval": "PT30S", "failure_threshold": 3, -"check_count": 2 }`. It deliberately carries **no** check names, URLs or queries: the request is -readable by its submitter and reviewers, while an environment's config is admin-only. A breach reaches the submitter's browser through the existing +`verification_detail`. Since #1027 the request detail and list bodies — not the gate — also +carry `verification_snapshot`: the config the window was opened with, omitted until a window +opens (and when the stored snapshot cannot be read), e.g. `{ "window": "PT15M", +"sample_interval": "PT30S", "failure_threshold": 3, "check_count": 2 }`. It deliberately carries +**no** check names, URLs or queries: the request is readable by its submitter and reviewers, +while an environment's config is admin-only. A breach reaches the submitter's browser through +the existing `deployment.status_changed` WebSocket event. **Sample entry** (`GET /deployment-requests/{id}/verification-samples`): diff --git a/docs/06-frontend.md b/docs/06-frontend.md index ad1cee8d7..901348585 100644 --- a/docs/06-frontend.md +++ b/docs/06-frontend.md @@ -933,15 +933,15 @@ registered locale. | Route | Page | Notes | |-------|------|-------| -| `/deployments` | `DeploymentListPage` | Deployment requests (non-reviewers are server-scoped to their own submissions). Filter bar: status, pipeline, environment name, exact version; server pagination, forced `created_at DESC` (no sortable columns). The pipeline filter is built from the loaded rows unless the caller holds `DEPLOYMENT_PIPELINE_MANAGE` — a `DEPLOYMENT_REVIEW`-only user cannot call `GET /deployment-pipelines`. Row click → detail. A **Drift** column (#743) reads the per-pipeline matrix through one `useQueries` fan-out over the distinct `pipeline_id`s on the page (keys shared with the detail page, so revisits are cache hits; a 404 leaves those rows unbadged) and badges **only** the request that is currently live on its environment (`current_request_id === row.id`) — drift describes the environment now, so badging a superseded historical request would mislead. A **Ticket** column (#994) shows the linked change ticket through `ChangeTicketLink` (its key, linked to the ticket URL in a new tab when one is stored, plain text otherwise) with an approved / rejected decision tag, and `—` when the row has none. The **Outcome** cell (#1027) adds a `verification ` tag once `verification_status` leaves `PENDING`, because a breach leaves `outcome = SUCCEEDED`. | -| `/deployments/:id` | `DeploymentDetailPage` | Metadata `Descriptions` (version, commit, artifact, CI-run link, external run id, submitter, reason, schedule), AI risk card (`RiskPill` + summary), approvals progress + decisions table, request `metadata` JSON block, and an `ApprovalTimeline` fed by the pure `buildDeploymentTimelineStages.ts` (submitted → AI → review → scheduled → release → outcome, incl. the `EXECUTED → FAILED` outcome flip). While `APPROVED`, the page calls `GET /deployment-gate?request_id=` for the **releasability banner** (releasable / held-by-freeze with reason / scheduled); a gate 404 hides the banner silently. The submitter can cancel via `Popconfirm` while cancellable. **Approve / Reject (#770)** sit in the same action row, driven solely by the response's `can_review` flag — the server's answer to the decision guard, because the review plan's approver rules are not in this payload and a `DEPLOYMENT_REVIEW`-only gate would offer a button the backend then refuses. They carry their own copy of the queue's comment modal (≤2000 chars — a third inline copy alongside `DeploymentReviewTabs`' two, matching how `ApiRequestDetailPage` duplicates its own queue's; there is no shared component) and invalidate the detail, list and review-queue keys on success. Where `can_review` is false no **decision** control renders at all — not a disabled one, unlike the queue — and the submitter of a `PENDING_REVIEW` request gets `deploygov.reviews.selfSubmissionHint` beside their Cancel button. A **Drift** row (#743) joins the pipeline matrix by environment: the drift chip when this request is the environment's live deploy, otherwise a muted "Superseded — {environment} now runs {version}"; a matrix 404 hides the row entirely, same treatment as the gate. A **Change ticket** card (#994) renders when the request's environment has `change_ticket_required` or a ticket is already linked: the `ChangeTicketLink`, the ticketing system label, and the ticket's status with its resolution when present — or "No change ticket linked yet". The releasability banner gains two states from the gate response: *waiting for the change ticket* (info) while no linked ticket is approved, and *the change ticket was rejected* (warning). **Post-deployment verification (#1027):** once `verification_status` leaves `PENDING`, a *Verification* row (status tag, beside drift — the matrix's unchanged "current" says nothing about health), a *Verification* card (the request's `verification_snapshot` window / interval / threshold, started / finished, detail, and the samples table from `GET /deployment-requests/{id}/verification-samples` under `deploymentKeys.verification(id)`, a child of the detail key) and a timeline stage after the outcome stage. The detail query and the samples query both refetch every 10 s only while `RUNNING`, because a breach pushes no WebSocket event to non-submitters. `FAILED` adds an error callout — "verification failed — the release is still running … AccessFlow did not roll back" — and the release stage keeps reading as released (`executionFailed` is `FAILED` with no outcome only). | +| `/deployments` | `DeploymentListPage` | Deployment requests (non-reviewers are server-scoped to their own submissions). Filter bar: status, pipeline, environment name, exact version; server pagination, forced `created_at DESC` (no sortable columns). The pipeline filter is built from the loaded rows unless the caller holds `DEPLOYMENT_PIPELINE_MANAGE` — a `DEPLOYMENT_REVIEW`-only user cannot call `GET /deployment-pipelines`. Row click → detail. A **Drift** column (#743) reads the per-pipeline matrix through one `useQueries` fan-out over the distinct `pipeline_id`s on the page (keys shared with the detail page, so revisits are cache hits; a 404 leaves those rows unbadged) and badges **only** the request that is currently live on its environment (`current_request_id === row.id`) — drift describes the environment now, so badging a superseded historical request would mislead. A **Ticket** column (#994) shows the linked change ticket through `ChangeTicketLink` (its key, linked to the ticket URL in a new tab when one is stored, plain text otherwise) with an approved / rejected decision tag, and `—` when the row has none. The **Outcome** cell (#1027) adds a `verification ` tag once `verification_status` leaves `PENDING`, because a breach leaves `outcome = SUCCEEDED` — except `SKIPPED`, which would tag every deploy to an environment without checks. | +| `/deployments/:id` | `DeploymentDetailPage` | Metadata `Descriptions` (version, commit, artifact, CI-run link, external run id, submitter, reason, schedule), AI risk card (`RiskPill` + summary), approvals progress + decisions table, request `metadata` JSON block, and an `ApprovalTimeline` fed by the pure `buildDeploymentTimelineStages.ts` (submitted → AI → review → scheduled → release → outcome, incl. the `EXECUTED → FAILED` outcome flip). While `APPROVED`, the page calls `GET /deployment-gate?request_id=` for the **releasability banner** (releasable / held-by-freeze with reason / scheduled); a gate 404 hides the banner silently. The submitter can cancel via `Popconfirm` while cancellable. **Approve / Reject (#770)** sit in the same action row, driven solely by the response's `can_review` flag — the server's answer to the decision guard, because the review plan's approver rules are not in this payload and a `DEPLOYMENT_REVIEW`-only gate would offer a button the backend then refuses. They carry their own copy of the queue's comment modal (≤2000 chars — a third inline copy alongside `DeploymentReviewTabs`' two, matching how `ApiRequestDetailPage` duplicates its own queue's; there is no shared component) and invalidate the detail, list and review-queue keys on success. Where `can_review` is false no **decision** control renders at all — not a disabled one, unlike the queue — and the submitter of a `PENDING_REVIEW` request gets `deploygov.reviews.selfSubmissionHint` beside their Cancel button. A **Drift** row (#743) joins the pipeline matrix by environment: the drift chip when this request is the environment's live deploy, otherwise a muted "Superseded — {environment} now runs {version}"; a matrix 404 hides the row entirely, same treatment as the gate. A **Change ticket** card (#994) renders when the request's environment has `change_ticket_required` or a ticket is already linked: the `ChangeTicketLink`, the ticketing system label, and the ticket's status with its resolution when present — or "No change ticket linked yet". The releasability banner gains two states from the gate response: *waiting for the change ticket* (info) while no linked ticket is approved, and *the change ticket was rejected* (warning). **Post-deployment verification (#1027):** once `verification_status` leaves `PENDING`, a *Verification* row (status tag, beside drift — the matrix's unchanged "current" says nothing about health), a *Verification* card (the request's `verification_snapshot` window / interval / threshold, started / finished, detail, and the samples table from `GET /deployment-requests/{id}/verification-samples` under `deploymentKeys.verification(id)`, a child of the detail key) and a timeline stage after the outcome stage. The detail query and the samples query both refetch every 10 s only while `RUNNING`, because a breach pushes no WebSocket event to non-submitters, and the samples are invalidated once more when the status leaves `RUNNING` (the two polls tick independently). A `SKIPPED` request with no `verification_snapshot` was never sampled: no card, no samples request, and the row carries the reason, which `verificationDetailText` translates from the backend's machine tokens (`no verification configured`, `outcome:`). `FAILED` adds an error callout — "verification failed — the release is still running … AccessFlow did not roll back" — which becomes a warning saying the pipeline reported a rollback once `outcome` is `ROLLED_BACK` (the #1025 carve-out), and the release stage keeps reading as released (`executionFailed` is `FAILED` with no outcome only). | | `/deployment-reviews` | *redirect* → `/reviews?tab=deployments` (or `?tab=rollbacks`) | Since #772 the two `DEPLOYMENT_REVIEW`-gated queues are tabs of the unified review hub (`pages/deployments/DeploymentReviewTabs.tsx`). **Deployments** (`PendingDeploymentsTab`): queue rows (pipeline/environment/version/risk/approvals/schedule) with approve/reject via a shared comment modal (≤2000 chars); own submissions render disabled buttons with a tooltip (self-approval is also blocked server-side with 409). **Rollbacks** (`RollbackReviewsTab`, `?tab=rollbacks`): the mandatory post-rollback acknowledgements — status filter, outcome detail, acknowledge with optional comment (idempotent; self-ack 409), link to the deployment. The legacy URL (with or without `?tab=rollbacks`) redirects into the matching tab. | | `/deployment-versions` | `DeploymentVersionsPage` | Org-wide version matrix (#743) — one row per environment deployed at least once: pipeline (linking to the per-pipeline matrix), environment + tag chips, current/previous version, deployed-at, last outcome + rollback badge, drift badge. Filters: pipeline, tag, environment name, and a drift tri-state (`Any` / `Behind latest only` / `Up to date only` → `drifted` `undefined`/`true`/`false` — the "up to date" case is why the api module guards on `typeof … === 'boolean'` rather than truthiness). Guarded any-of `DEPLOYMENT_PIPELINE_MANAGE` / `DEPLOYMENT_REVIEW` / `QUERY_ADMIN`, mirroring the controller's `hasAnyAuthority`. Tag options come from the loaded rows, so the list collapses to the selected tag until cleared (the selection is pinned so it cannot vanish from its own `Select`). Empty with no filters ⇒ `EmptyState`; empty with filters ⇒ the table's `emptyFiltered` text. | | `/deployment-versions/:pipelineId` | `PipelineVersionsPage` | The per-pipeline matrix as a standalone route (#743), **deliberately unguarded** — the server answers 404-never-403, which is what gives a `can_trigger`-only user (who cannot reach the admin settings page, and cannot call `GET /deployment-pipelines` to pick from) a reachable surface. Entry points: the pipeline column on `/deployment-versions`, and a "Version matrix" button beside the pipeline filter on `/deployments`. Wraps the same `PipelineVersionsTab`; a rejected matrix read renders the not-found `EmptyState`. | | `/deployment-metrics` | `DeploymentMetricsPage` | DORA + approval-SLA metrics (#987) over the #984 read API — the page never derives a metric, it only formats (`deploymentMetricsFilters.ts`: presets → `[from, to)` UTC-day windows via `trendsFiltersForRange`, a custom `RangePicker` capped at 366 days like the backend, seconds → `formatDurationCompact`, rates → `Intl` percent, missing values → `—`). Body is the shared `components/deployments/DeploymentMetricsPanel`: `MetricTile` row (frequency, lead time p50/p95 with the `lead_time.source` caption, change failure rate with the `unreported` caveat, time to restore + open incidents, approval latency, timeout rate, break-glass count), a Bklit `AreaChart` of `daily` (deployments / failed / rolled back), a `RingChart` of failed + rolled back over executed with the rate in `RingCenter`, and the per-environment breakdown table from `GET /deployment-metrics/environments` (pipeline links to `/deployment-versions/:pipelineId`). Filters are `Select`s, never `Segmented`: period, environment (options from the breakdown, read without the environment filter so they do not collapse; the table rows are narrowed in memory), and a pipeline picker only for `DEPLOYMENT_PIPELINE_MANAGE` (`GET /deployment-pipelines` is admin-only). Empty when `deployment_frequency.total === 0`. Guarded any-of `DEPLOYMENT_PIPELINE_MANAGE` / `DEPLOYMENT_REVIEW` / `QUERY_ADMIN`. | | `/deployment-metrics/:pipelineId` | `PipelineMetricsPage` | The same panel fixed to one pipeline (#987), **deliberately unguarded** like `PipelineVersionsPage` — the per-pipeline endpoint is 404-never-403 and open to `can_trigger`. Reached from the "Metrics" button beside "Version matrix" on `/deployments`; environment options come from the pipeline's version matrix, and there is no breakdown table (that endpoint needs a functional permission). The pipeline settings page carries the same panel as its *Metrics* tab (`?tab=metrics`). | | `/admin/deployment-pipelines` | `DeploymentPipelinesPage` | `DEPLOYMENT_PIPELINE_MANAGE`-gated CRUD list (name, copyable id, provider label, repository, AI toggle, active tag) + create modal (name 3–255, provider, repository URL ≤2048, project ref ≤512, review plan, AI toggle + AI config — validation parity with `CreateDeploymentPipelineRequest`). Create navigates straight into settings. | -| `/admin/deployment-pipelines/:id` | `DeploymentPipelineSettingsPage` | The header subtitle carries the provider label plus the pipeline's full id as a `PipelineIdCopy` (#771) — the UUID every CI integration is configured with, previously readable only out of the address bar or the CI snippet. Tabs: **General** (edit form, `clear_review_plan`/`clear_ai_config` on unset, active switch); **Environments** (`PipelineEnvironmentsTab` — ordered list, per-env `tags` (a `Select mode="tags"` with parity validation against `@Size(max=10)` / element `@Size(max=32)`; both mutations always send an array, never null, because the server reads null as "leave unchanged"), `require_review`/`required_approvals`/review-plan overrides/`allow_break_glass`, and a **Requires change ticket** switch with a matching table column for `change_ticket_required` (#994); a **Post-deployment verification** section (#1027) — a switch revealing window / interval / threshold `InputNumber`s and a `Form.List` of up to ten checks whose type `Select` swaps HTTP fields (URL, expected status, body contains) for PromQL ones (Prometheus URL, query, comparator, threshold, no-data switch); form values ⇄ wire (minutes ⇄ ISO-8601, the other kind's fields dropped) and the client rules live in the pure `verificationForm.ts`; off ⇒ `verification: null` on create and `clear_verification: true` on update; a *Verification* column shows the check count; since #877 the existing **Order** field gains a `{ type: 'number', min: 0 }` rule (parity with `@Min(0)`), is `required` in edit mode (the update path reads null as "leave unchanged", so a cleared value must not silently keep the old position) and takes its create prefill from the pure `environmentLadder.ts` (`max + 1`, `0` when empty — never the row count, which the unique `(pipeline, sort_order)` constraint would refuse), and a new **Database** `Select` over `listDatasources` is sent as `datasource_id` + `clear_datasource` (the `clear_review_plan` shape) and rendered as a table column that falls back to the raw id for a datasource deleted since binding); **Versions** (`PipelineVersionsTab` — the unpaginated per-pipeline matrix in server order, including never-deployed environments as `—` + a "Never deployed" chip, with a per-environment `EnvironmentHistoryDrawer`); **Metrics** (`DeploymentMetricsPanel` fixed to this pipeline, #987 — tiles and charts, no breakdown table); **Permissions** (`PipelinePermissionsTab` — user + group grant tables mirroring the connector-permission UI, capabilities `can_trigger`/`can_break_glass`/`expires_at`); **Freeze windows** (`PipelineFreezeWindowsTab` — the global list client-filtered to this pipeline + org-global rows ("Global" badge); one-off vs weekly-recurring editor with ISO-weekday multi-select, `HH:mm` time pickers, an IANA timezone select from `Intl.supportedValuesOf('timeZone')`, and a CSS-grid week-strip visualisation from the pure `freezeWindowCalendar.ts`); **Routing policies** (`PipelineRoutingPoliciesTab` — flat typed conditions (environments/providers/min-risk/version globs/day+time window), `required_approvals` required for `REQUIRE_APPROVALS`/`ESCALATE` and hidden for `AUTO_*`, priority conflicts surfaced from the 409); **Simulate** (`PipelineSimulateTab`, #1066 — the deployment decision trace at an optional hypothetical instant `at`, with the gate's `releasable` verdict in a banner above the shared `DecisionTraceView`); **CI setup** (`CiSnippetPanel` — copyable GitHub Actions / GitLab CI / Azure Pipelines / curl snippets from `ci-templates/`, pipeline id and origin pre-filled). The nine-tab strip is synced to `?tab=` (unknown values fall back to `general`), which makes a tab linkable and the e2e deterministic on an overflowed strip. Pure form logic lives in `freezeWindowForm.ts` / `deploymentRoutingPolicyForm.ts` / `versionMatrix.ts` / `environmentLadder.ts` / `verificationForm.ts` (coverage-listed). | +| `/admin/deployment-pipelines/:id` | `DeploymentPipelineSettingsPage` | The header subtitle carries the provider label plus the pipeline's full id as a `PipelineIdCopy` (#771) — the UUID every CI integration is configured with, previously readable only out of the address bar or the CI snippet. Tabs: **General** (edit form, `clear_review_plan`/`clear_ai_config` on unset, active switch); **Environments** (`PipelineEnvironmentsTab` — ordered list, per-env `tags` (a `Select mode="tags"` with parity validation against `@Size(max=10)` / element `@Size(max=32)`; both mutations always send an array, never null, because the server reads null as "leave unchanged"), `require_review`/`required_approvals`/review-plan overrides/`allow_break_glass`, and a **Requires change ticket** switch with a matching table column for `change_ticket_required` (#994); a **Post-deployment verification** section (#1027) — a switch revealing window / interval / threshold `InputNumber`s and a `Form.List` of up to ten checks whose type `Select` swaps HTTP fields (URL, expected status, body contains) for PromQL ones (Prometheus URL, query, comparator, threshold, no-data switch); form values ⇄ wire (minutes ⇄ ISO-8601, the other kind's fields dropped), the client rules (incl. `verificationUrlProblem`: http(s), a host, no userinfo, no query/fragment on a Prometheus URL) and `verificationInvalidMessage` — which turns the 422's `reason` / `checkName` into a translated sentence, since its `detail` is generic — live in the pure `verificationForm.ts`; off ⇒ `verification: null` on create and `clear_verification: true` on update; a *Verification* column shows the check count; since #877 the existing **Order** field gains a `{ type: 'number', min: 0 }` rule (parity with `@Min(0)`), is `required` in edit mode (the update path reads null as "leave unchanged", so a cleared value must not silently keep the old position) and takes its create prefill from the pure `environmentLadder.ts` (`max + 1`, `0` when empty — never the row count, which the unique `(pipeline, sort_order)` constraint would refuse), and a new **Database** `Select` over `listDatasources` is sent as `datasource_id` + `clear_datasource` (the `clear_review_plan` shape) and rendered as a table column that falls back to the raw id for a datasource deleted since binding); **Versions** (`PipelineVersionsTab` — the unpaginated per-pipeline matrix in server order, including never-deployed environments as `—` + a "Never deployed" chip, with a per-environment `EnvironmentHistoryDrawer`); **Metrics** (`DeploymentMetricsPanel` fixed to this pipeline, #987 — tiles and charts, no breakdown table); **Permissions** (`PipelinePermissionsTab` — user + group grant tables mirroring the connector-permission UI, capabilities `can_trigger`/`can_break_glass`/`expires_at`); **Freeze windows** (`PipelineFreezeWindowsTab` — the global list client-filtered to this pipeline + org-global rows ("Global" badge); one-off vs weekly-recurring editor with ISO-weekday multi-select, `HH:mm` time pickers, an IANA timezone select from `Intl.supportedValuesOf('timeZone')`, and a CSS-grid week-strip visualisation from the pure `freezeWindowCalendar.ts`); **Routing policies** (`PipelineRoutingPoliciesTab` — flat typed conditions (environments/providers/min-risk/version globs/day+time window), `required_approvals` required for `REQUIRE_APPROVALS`/`ESCALATE` and hidden for `AUTO_*`, priority conflicts surfaced from the 409); **Simulate** (`PipelineSimulateTab`, #1066 — the deployment decision trace at an optional hypothetical instant `at`, with the gate's `releasable` verdict in a banner above the shared `DecisionTraceView`); **CI setup** (`CiSnippetPanel` — copyable GitHub Actions / GitLab CI / Azure Pipelines / curl snippets from `ci-templates/`, pipeline id and origin pre-filled). The nine-tab strip is synced to `?tab=` (unknown values fall back to `general`), which makes a tab linkable and the e2e deterministic on an overflowed strip. Pure form logic lives in `freezeWindowForm.ts` / `deploymentRoutingPolicyForm.ts` / `versionMatrix.ts` / `environmentLadder.ts` / `verificationForm.ts` (coverage-listed). | Live refresh: the backend pushes `deployment.status_changed` to the **submitter** on every transition; `websocketManager.invokeDefault` invalidates the deployment detail (incl. its gate diff --git a/docs/18-deployment-governance.md b/docs/18-deployment-governance.md index 8a61b2524..00b6515ae 100644 --- a/docs/18-deployment-governance.md +++ b/docs/18-deployment-governance.md @@ -183,20 +183,27 @@ hold a snapshot of the config and the verdict, and the `deployment_verifications - **Save-time rules.** A config is rejected with `422 DEPLOYMENT_VERIFICATION_INVALID` when its window is outside 1 minute–24 hours, its interval outside 30 seconds–window, its failure threshold one the window cannot reach, two checks share a name, or a URL is refused or does not - resolve. + resolve. Column detail is in +[03-data-model.md](03-data-model.md#deployment_environments) (`deployment_environments`, +`deployment_requests`, `deployment_verifications`). - **In the web UI (#1027).** The environment modal on the pipeline settings page has a *Post-deployment verification* section: a switch that reveals the window, interval and failure threshold and a list of checks, each with a type `Select` that swaps between the HTTP and the - PromQL fields. The form mirrors every rule above that needs no network; host policy is only - known server-side and comes back as the 422's `detail`. Turning the switch off sends - `clear_verification: true`. The deployment detail page adds a *Verification* stage to the - timeline after the outcome stage (hidden while `PENDING`), a *Verification* row beside drift, and - a card with the request's `verification_snapshot`, its timestamps and the samples table — polled - every 10 seconds while `RUNNING`. A breach renders as "verification failed — the release is still - running" and says AccessFlow did not roll back; the release stage keeps reading as released. - The deployments list shows the verification status as a second tag in the outcome cell. Column detail is in -[03-data-model.md](03-data-model.md#deployment_environments) (`deployment_environments`, -`deployment_requests`, `deployment_verifications`). + PromQL fields. The form mirrors every rule above that needs no network, including no + `user:password@` in a URL and no query string or fragment on a Prometheus URL; the host policy + is only known server-side, so the form names the failed rule from the 422's `reason` and + `checkName` (its `detail` is one generic sentence). Turning the switch off sends + `verification: null` on create and `clear_verification: true` on an edit. The deployment detail + page adds a *Verification* stage to the timeline after the outcome stage (hidden while + `PENDING`), a *Verification* row beside drift, and a card with the request's + `verification_snapshot`, its timestamps and the samples table — polled every 10 seconds while + `RUNNING` and fetched once more when the window closes. A request that was never sampled + (`SKIPPED` with no snapshot) gets no card; its row shows the translated reason. A breach with + the outcome still `SUCCEEDED` renders as "verification failed — the + release is still running" and says AccessFlow did not roll back; once the pipeline reports + `ROLLED_BACK` the callout says the rollback was reported instead. The release stage keeps + reading as released. The deployments list adds the verification status as a second tag in the + outcome cell, except `SKIPPED`, which would otherwise tag every unverified deploy. --- diff --git a/e2e/tests/deployment-verification.spec.ts b/e2e/tests/deployment-verification.spec.ts index ad2cfdb20..3bd577532 100644 --- a/e2e/tests/deployment-verification.spec.ts +++ b/e2e/tests/deployment-verification.spec.ts @@ -125,7 +125,9 @@ test.describe.serial('post-deployment verification (#1027)', () => { await login(page, ADMIN_EMAIL, ADMIN_PASSWORD); await page.goto(`/deployments/${triggered.id}`); - // The page polls while RUNNING; the first failed sample breaches a threshold of 1. + // The page polls while RUNNING; the first failed sample breaches a threshold of 1. RUNNING + // itself is not asserted (issue #1027 step 10b asks for it): with a 5 s job tick it usually + // ends before the page loads, so an assertion on it would flake. The unit tests cover it. await expect( page.getByText('Verification failed — the release is still running'), ).toBeVisible({ timeout: 60_000 }); diff --git a/frontend/src/components/deployments/PipelineEnvironmentsTab.test.tsx b/frontend/src/components/deployments/PipelineEnvironmentsTab.test.tsx index 99cfb65fb..2ab5ad3bb 100644 --- a/frontend/src/components/deployments/PipelineEnvironmentsTab.test.tsx +++ b/frontend/src/components/deployments/PipelineEnvironmentsTab.test.tsx @@ -574,7 +574,7 @@ describe('PipelineEnvironmentsTab', () => { ]); }); - it('refuses a non-http URL and a missing check name', async () => { + it('refuses a non-http URL', async () => { await openCreate(); enable(); fireEvent.change(await screen.findByLabelText('Health URL'), { @@ -680,12 +680,35 @@ describe('PipelineEnvironmentsTab', () => { ); }); - it('surfaces the server detail of a 422 DEPLOYMENT_VERIFICATION_INVALID', async () => { + it('refuses credentials in a URL and a query string on a Prometheus URL', async () => { + await openCreate(); + enable(); + fireEvent.change(await screen.findByLabelText('Health URL'), { + target: { value: 'https://user:secret@svc.example.com/healthz' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect(await screen.findByText(/Remove the user:password@ part/)).toBeInTheDocument(); + + fireEvent.mouseDown(screen.getByLabelText('Check type')); + fireEvent.click(await screen.findByText('PromQL threshold')); + fireEvent.change(await screen.findByLabelText('Prometheus URL'), { + target: { value: 'https://prom.example.com/?tenant=a' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect( + await screen.findByText('Use the base URL only — no query string or fragment.'), + ).toBeInTheDocument(); + expect(createDeploymentEnvironment).not.toHaveBeenCalled(); + }); + + it('names the rule a 422 DEPLOYMENT_VERIFICATION_INVALID reports, not its generic detail', async () => { + // The server's real shape: one generic `detail`, the rule in `reason` / `checkName`. createDeploymentEnvironment.mockRejectedValue( problem(422, { error: 'DEPLOYMENT_VERIFICATION_INVALID', reason: 'host_unresolvable', - detail: 'The host of check health does not resolve', + checkName: 'health', + detail: 'The verification config is invalid', }), ); await openCreate(); @@ -696,8 +719,20 @@ describe('PipelineEnvironmentsTab', () => { }); fireEvent.click(screen.getByRole('button', { name: 'Save' })); expect( - await screen.findByText('The host of check health does not resolve'), + await screen.findByText( + 'Check "health": the host does not resolve from the AccessFlow server.', + ), ).toBeInTheDocument(); + expect(screen.queryByText('The verification config is invalid')).toBeNull(); + }); + + it('falls back to the server detail for any other error', async () => { + createDeploymentEnvironment.mockRejectedValue( + problem(409, { error: 'DEPLOYMENT_ENVIRONMENT_DUPLICATE_NAME', detail: 'Name taken' }), + ); + await openCreate(); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect(await screen.findByText('Name taken')).toBeInTheDocument(); }); }); }); diff --git a/frontend/src/components/deployments/PipelineEnvironmentsTab.tsx b/frontend/src/components/deployments/PipelineEnvironmentsTab.tsx index 0fa95c652..e0f656a04 100644 --- a/frontend/src/components/deployments/PipelineEnvironmentsTab.tsx +++ b/frontend/src/components/deployments/PipelineEnvironmentsTab.tsx @@ -15,6 +15,7 @@ import { import type { FormInstance, TableColumnsType } from 'antd'; import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import axios from 'axios'; import { useTranslation } from 'react-i18next'; import { createDeploymentEnvironment, @@ -41,7 +42,8 @@ import { defaultCheckValues, defaultVerificationValues, isDuplicateCheckName, - isHttpUrl, + verificationInvalidMessage, + verificationUrlProblem, maxSamplesInWindow, toVerificationFormValues, toVerificationWire, @@ -177,7 +179,15 @@ export function PipelineEnvironmentsTab({ pipelineId }: { pipelineId: string }) setModalFor(null); void invalidate(); }, - onError: (err) => showApiError(message, err, (e) => apiErrorMessage(e, () => t('deploygov.error'))), + // The 422's `detail` is one generic sentence; name the actual rule from `reason` (#1024). + onError: (err) => + showApiError( + message, + err, + (e) => + (axios.isAxiosError(e) ? verificationInvalidMessage(t, e.response?.data) : null) ?? + apiErrorMessage(e, () => t('deploygov.error')), + ), }); const deleteMutation = useMutation({ @@ -493,13 +503,15 @@ function VerificationFields({ form }: { form: FormInstance ({ validator: async (_: unknown, value: string | null | undefined) => { - if (value && value.trim() !== '' && !isHttpUrl(value)) { - throw new Error(t('deploygov.settings.verificationUrlScheme')); - } + const problem = verificationUrlProblem(value, { prometheus }); + if (problem === 'scheme') throw new Error(t('deploygov.settings.verificationUrlScheme')); + if (problem === 'invalid') throw new Error(t('deploygov.settings.verificationUrlInvalid')); + if (problem === 'userinfo') throw new Error(t('deploygov.settings.verificationUrlUserinfo')); + if (problem === 'query') throw new Error(t('deploygov.settings.verificationUrlQuery')); }, - }; + }); return ( <> @@ -671,10 +683,10 @@ function VerificationFields({ form }: { form: FormInstance - + - +
{ expect(wire?.checks[1]).toMatchObject({ comparator: 'LT', threshold: 0, no_data_is_failure: true, prometheus_url: '', query: '' }); }); - it('accepts only http(s) URLs', () => { - expect(isHttpUrl('https://svc.example.com/h')).toBe(true); - expect(isHttpUrl('HTTP://svc')).toBe(true); - expect(isHttpUrl('ftp://svc')).toBe(false); - expect(isHttpUrl('svc.example.com')).toBe(false); - expect(isHttpUrl(null)).toBe(false); + it('mirrors the network-free URL rules', () => { + const http = { prometheus: false }; + const prom = { prometheus: true }; + expect(verificationUrlProblem('https://svc.example.com/h?probe=1', http)).toBeNull(); + expect(verificationUrlProblem('HTTP://svc', http)).toBeNull(); + expect(verificationUrlProblem('', http)).toBeNull(); + expect(verificationUrlProblem(null, http)).toBeNull(); + expect(verificationUrlProblem('ftp://svc', http)).toBe('scheme'); + expect(verificationUrlProblem('svc.example.com', http)).toBe('scheme'); + expect(verificationUrlProblem('https://', http)).toBe('invalid'); + expect(verificationUrlProblem('https://exa mple.com', http)).toBe('invalid'); + expect(verificationUrlProblem('https://u:p@svc.example.com', http)).toBe('userinfo'); + expect(verificationUrlProblem('https://u@svc.example.com', prom)).toBe('userinfo'); + expect(verificationUrlProblem('https://prom:9090/?x=1', prom)).toBe('query'); + expect(verificationUrlProblem('https://prom:9090/#a', prom)).toBe('query'); + expect(verificationUrlProblem('https://prom:9090/prefix', prom)).toBeNull(); + }); + + it('names the rule a 422 DEPLOYMENT_VERIFICATION_INVALID reports', () => { + const t = ((key: string, opts?: Record) => + opts ? `${key}|${String(opts.check)}` : key) as unknown as TFunction; + for (const reason of VERIFICATION_INVALID_REASONS) { + expect( + verificationInvalidMessage(t, { + error: 'DEPLOYMENT_VERIFICATION_INVALID', + reason, + checkName: 'health', + }), + ).toBe(`deploygov.settings.verificationInvalid.${reason}|health`); + } + expect( + verificationInvalidMessage(t, { + error: 'DEPLOYMENT_VERIFICATION_INVALID', + reason: 'window_out_of_range', + }), + ).toBe('deploygov.settings.verificationInvalid.window_out_of_range|—'); + expect( + verificationInvalidMessage(t, { + error: 'DEPLOYMENT_VERIFICATION_INVALID', + reason: 'duplicate_check_name', + check_name: 'h', + }), + ).toBe('deploygov.settings.verificationInvalid.duplicate_check_name|h'); + expect( + verificationInvalidMessage(t, { error: 'DEPLOYMENT_VERIFICATION_INVALID', reason: 'new' }), + ).toBeNull(); + expect(verificationInvalidMessage(t, { error: 'OTHER', reason: 'host_missing' })).toBeNull(); + expect(verificationInvalidMessage(t, null)).toBeNull(); + expect(verificationInvalidMessage(t, 'text')).toBeNull(); }); it('computes how many samples fit in the window', () => { diff --git a/frontend/src/components/deployments/verificationForm.ts b/frontend/src/components/deployments/verificationForm.ts index 3d756cecd..fe43193c3 100644 --- a/frontend/src/components/deployments/verificationForm.ts +++ b/frontend/src/components/deployments/verificationForm.ts @@ -1,3 +1,4 @@ +import type { TFunction } from 'i18next'; import type { DeploymentVerificationConfig, DeploymentVerificationConfigInput, @@ -160,8 +161,70 @@ export function toVerificationWire( }; } -export function isHttpUrl(value: string | null | undefined): boolean { - return /^https?:\/\/\S+$/i.test((value ?? '').trim()); +export type VerificationUrlProblem = 'scheme' | 'invalid' | 'userinfo' | 'query'; + +/** + * The network-free half of the server's URL rules (#1024): http(s) only, an absolute URL with a + * host, no `user:password@`, and — for a Prometheus base URL, which gets `/api/v1/query` + * appended — no query string or fragment. Resolution and the address policy stay server-side. + */ +export function verificationUrlProblem( + value: string | null | undefined, + options: { prometheus: boolean }, +): VerificationUrlProblem | null { + const trimmed = (value ?? '').trim(); + if (trimmed === '') return null; + if (!/^https?:\/\//i.test(trimmed)) return 'scheme'; + let url: URL; + try { + url = new URL(trimmed); + } catch { + return 'invalid'; + } + if (url.hostname === '') return 'invalid'; + if (url.username !== '' || url.password !== '') return 'userinfo'; + if (options.prometheus && (trimmed.includes('?') || trimmed.includes('#'))) return 'query'; + return null; +} + +/** The `reason` codes of 422 DEPLOYMENT_VERIFICATION_INVALID (docs/04-api-spec.md, #1024). */ +export const VERIFICATION_INVALID_REASONS = [ + 'window_out_of_range', + 'sample_interval_out_of_range', + 'failure_threshold_exceeds_samples', + 'duplicate_check_name', + 'invalid_url', + 'scheme_not_allowed', + 'userinfo_present', + 'host_missing', + 'host_unresolvable', + 'restricted_address', + 'metadata_endpoint', + 'host_not_allowed', +] as const; + +export type VerificationInvalidReason = (typeof VERIFICATION_INVALID_REASONS)[number]; + +interface VerificationInvalidBody { + error?: string; + reason?: string; + checkName?: string; + check_name?: string; +} + +/** + * The server's `detail` for this 422 is one generic sentence; the actual rule is in `reason` + * (and `checkName` for a per-check rule). Null when the body is not this error or the reason is + * unknown, so the caller falls back to the generic path. + */ +export function verificationInvalidMessage(t: TFunction, body: unknown): string | null { + if (body == null || typeof body !== 'object') return null; + const problem = body as VerificationInvalidBody; + if (problem.error !== 'DEPLOYMENT_VERIFICATION_INVALID') return null; + const reason = VERIFICATION_INVALID_REASONS.find((r) => r === problem.reason); + if (!reason) return null; + const check = problem.checkName ?? problem.check_name ?? '—'; + return t(`deploygov.settings.verificationInvalid.${reason}`, { check }); } /** How many samples the window can collect — the ceiling on `failure_threshold` (#1024). */ diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json index 898af0b78..be760cbbe 100644 --- a/frontend/src/locales/de.json +++ b/frontend/src/locales/de.json @@ -5852,7 +5852,11 @@ "verificationNoSamples": "Noch keine Stichproben", "verificationMinutesValue": "{{n}} Min.", "verificationSecondsValue": "{{n}} s", - "timeline_verification": "Verifizierung" + "timeline_verification": "Verifizierung", + "verificationFailedRolledBackTitle": "Verifizierung fehlgeschlagen — die Pipeline hat ein Rollback gemeldet", + "verificationFailedRolledBackBody": "Die Pipeline hat nach dem Verstoß ROLLED_BACK gemeldet. AccessFlow selbst hat nichts zurückgerollt; die Stichproben unten sind der Nachweis.", + "verificationSkippedNoConfig": "Für diese Umgebung ist keine Verifizierung konfiguriert", + "verificationSkippedOutcome": "Nicht verifiziert — die Pipeline hat {{outcome}} gemeldet" }, "reviews": { "approve": "Genehmigen", @@ -6125,7 +6129,26 @@ "verificationValueThreshold": "Schwellenwert", "verificationNoDataIsFailure": "Keine Daten gelten als Fehler", "verificationColumn": "Verifizierung", - "verificationChecksCount": "Checks: {{n}}" + "verificationChecksCount": "Checks: {{n}}", + "verificationUrlInvalid": "Geben Sie eine gültige absolute URL mit Host ein.", + "verificationUrlUserinfo": "Entfernen Sie den Teil user:password@ — Zugangsdaten sind in der URL nicht erlaubt.", + "verificationUrlQuery": "Nur die Basis-URL — ohne Query-String oder Fragment.", + "verificationUrlPlaceholder": "https://service.example.com/healthz", + "verificationPrometheusUrlPlaceholder": "https://prometheus.example.com", + "verificationInvalid": { + "window_out_of_range": "Das Zeitfenster muss zwischen 1 Minute und 24 Stunden liegen.", + "sample_interval_out_of_range": "Das Prüfintervall muss mindestens 30 Sekunden betragen und darf das Zeitfenster nicht überschreiten.", + "failure_threshold_exceeds_samples": "Der Fehlerschwellenwert ist höher als die Zahl der Stichproben, die das Zeitfenster erfassen kann.", + "duplicate_check_name": "Zwei Checks heißen „{{check}}“.", + "invalid_url": "Check „{{check}}“: Die URL ist ungültig. Eine Prometheus-URL darf keinen Query-String und kein Fragment enthalten.", + "scheme_not_allowed": "Check „{{check}}“: Nur http://- und https://-URLs sind erlaubt.", + "userinfo_present": "Check „{{check}}“: Entfernen Sie den Teil user:password@ aus der URL.", + "host_missing": "Check „{{check}}“: Die URL hat keinen Host.", + "host_unresolvable": "Check „{{check}}“: Der Host lässt sich vom AccessFlow-Server aus nicht auflösen.", + "restricted_address": "Check „{{check}}“: localhost-, Loopback- und Link-Local-Adressen sind nicht erlaubt.", + "metadata_endpoint": "Check „{{check}}“: Cloud-Metadaten-Endpunkte sind nicht erlaubt.", + "host_not_allowed": "Check „{{check}}“: Der Host steht nicht auf der Verifizierungs-Allow-List dieses Servers." + } }, "freezeWindows": { "title": "Freeze-Fenster", diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json index 045288f61..0eb05b3c7 100644 --- a/frontend/src/locales/en.json +++ b/frontend/src/locales/en.json @@ -5852,7 +5852,11 @@ "verificationNoSamples": "No samples yet", "verificationMinutesValue": "{{n}} min", "verificationSecondsValue": "{{n}} s", - "timeline_verification": "Verification" + "timeline_verification": "Verification", + "verificationFailedRolledBackTitle": "Verification failed — the pipeline reported a rollback", + "verificationFailedRolledBackBody": "The pipeline reported ROLLED_BACK after the breach. AccessFlow itself rolled nothing back; the samples below are the evidence.", + "verificationSkippedNoConfig": "No verification configured on this environment", + "verificationSkippedOutcome": "Not verified — the pipeline reported {{outcome}}" }, "reviews": { "approve": "Approve", @@ -6125,7 +6129,26 @@ "verificationValueThreshold": "Threshold", "verificationNoDataIsFailure": "No data counts as failure", "verificationColumn": "Verification", - "verificationChecksCount": "Checks: {{n}}" + "verificationChecksCount": "Checks: {{n}}", + "verificationUrlInvalid": "Enter a valid absolute URL with a host.", + "verificationUrlUserinfo": "Remove the user:password@ part — credentials are not allowed in the URL.", + "verificationUrlQuery": "Use the base URL only — no query string or fragment.", + "verificationUrlPlaceholder": "https://service.example.com/healthz", + "verificationPrometheusUrlPlaceholder": "https://prometheus.example.com", + "verificationInvalid": { + "window_out_of_range": "The window must be between 1 minute and 24 hours.", + "sample_interval_out_of_range": "The sample interval must be at least 30 seconds and no longer than the window.", + "failure_threshold_exceeds_samples": "The failure threshold is higher than the number of samples the window can collect.", + "duplicate_check_name": "Two checks share the name \"{{check}}\".", + "invalid_url": "Check \"{{check}}\": the URL is not valid. A Prometheus URL must not carry a query string or fragment.", + "scheme_not_allowed": "Check \"{{check}}\": only http:// and https:// URLs are allowed.", + "userinfo_present": "Check \"{{check}}\": remove the user:password@ part from the URL.", + "host_missing": "Check \"{{check}}\": the URL has no host.", + "host_unresolvable": "Check \"{{check}}\": the host does not resolve from the AccessFlow server.", + "restricted_address": "Check \"{{check}}\": localhost, loopback and link-local addresses are not allowed.", + "metadata_endpoint": "Check \"{{check}}\": cloud metadata endpoints are not allowed.", + "host_not_allowed": "Check \"{{check}}\": the host is not on this server's verification allow-list." + } }, "freezeWindows": { "title": "Freeze windows", diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json index 70113ab35..3a20da235 100644 --- a/frontend/src/locales/es.json +++ b/frontend/src/locales/es.json @@ -5852,7 +5852,11 @@ "verificationNoSamples": "Aún no hay muestras", "verificationMinutesValue": "{{n}} min", "verificationSecondsValue": "{{n}} s", - "timeline_verification": "Verificación" + "timeline_verification": "Verificación", + "verificationFailedRolledBackTitle": "La verificación falló — el pipeline informó una reversión", + "verificationFailedRolledBackBody": "El pipeline informó ROLLED_BACK tras la infracción. AccessFlow no revirtió nada por sí mismo; las muestras de abajo son la evidencia.", + "verificationSkippedNoConfig": "Este entorno no tiene verificación configurada", + "verificationSkippedOutcome": "Sin verificar — el pipeline informó {{outcome}}" }, "reviews": { "approve": "Aprobar", @@ -6125,7 +6129,26 @@ "verificationValueThreshold": "Umbral", "verificationNoDataIsFailure": "Sin datos cuenta como fallo", "verificationColumn": "Verificación", - "verificationChecksCount": "Comprobaciones: {{n}}" + "verificationChecksCount": "Comprobaciones: {{n}}", + "verificationUrlInvalid": "Introduce una URL absoluta válida con host.", + "verificationUrlUserinfo": "Quita la parte user:password@ — no se permiten credenciales en la URL.", + "verificationUrlQuery": "Solo la URL base — sin cadena de consulta ni fragmento.", + "verificationUrlPlaceholder": "https://service.example.com/healthz", + "verificationPrometheusUrlPlaceholder": "https://prometheus.example.com", + "verificationInvalid": { + "window_out_of_range": "La ventana debe estar entre 1 minuto y 24 horas.", + "sample_interval_out_of_range": "El intervalo de muestreo debe ser de al menos 30 segundos y no superar la ventana.", + "failure_threshold_exceeds_samples": "El umbral de fallos supera el número de muestras que la ventana puede recoger.", + "duplicate_check_name": "Dos comprobaciones se llaman «{{check}}».", + "invalid_url": "Comprobación «{{check}}»: la URL no es válida. Una URL de Prometheus no puede llevar cadena de consulta ni fragmento.", + "scheme_not_allowed": "Comprobación «{{check}}»: solo se permiten URL http:// y https://.", + "userinfo_present": "Comprobación «{{check}}»: quita la parte user:password@ de la URL.", + "host_missing": "Comprobación «{{check}}»: la URL no tiene host.", + "host_unresolvable": "Comprobación «{{check}}»: el host no se resuelve desde el servidor de AccessFlow.", + "restricted_address": "Comprobación «{{check}}»: no se permiten direcciones localhost, loopback ni link-local.", + "metadata_endpoint": "Comprobación «{{check}}»: no se permiten endpoints de metadatos de la nube.", + "host_not_allowed": "Comprobación «{{check}}»: el host no está en la lista de permitidos de verificación de este servidor." + } }, "freezeWindows": { "title": "Ventanas de congelación", diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json index 16a5d11bd..7110534e7 100644 --- a/frontend/src/locales/fr.json +++ b/frontend/src/locales/fr.json @@ -5852,7 +5852,11 @@ "verificationNoSamples": "Aucun échantillon pour l’instant", "verificationMinutesValue": "{{n}} min", "verificationSecondsValue": "{{n}} s", - "timeline_verification": "Vérification" + "timeline_verification": "Vérification", + "verificationFailedRolledBackTitle": "Vérification échouée — le pipeline a signalé un retour arrière", + "verificationFailedRolledBackBody": "Le pipeline a signalé ROLLED_BACK après le dépassement. AccessFlow n’a lui-même rien annulé ; les échantillons ci-dessous en sont la preuve.", + "verificationSkippedNoConfig": "Aucune vérification configurée sur cet environnement", + "verificationSkippedOutcome": "Non vérifié — le pipeline a signalé {{outcome}}" }, "reviews": { "approve": "Approuver", @@ -6125,7 +6129,26 @@ "verificationValueThreshold": "Seuil", "verificationNoDataIsFailure": "Absence de données = échec", "verificationColumn": "Vérification", - "verificationChecksCount": "Contrôles : {{n}}" + "verificationChecksCount": "Contrôles : {{n}}", + "verificationUrlInvalid": "Saisissez une URL absolue valide avec un hôte.", + "verificationUrlUserinfo": "Retirez la partie user:password@ — les identifiants ne sont pas autorisés dans l’URL.", + "verificationUrlQuery": "URL de base uniquement — sans chaîne de requête ni fragment.", + "verificationUrlPlaceholder": "https://service.example.com/healthz", + "verificationPrometheusUrlPlaceholder": "https://prometheus.example.com", + "verificationInvalid": { + "window_out_of_range": "La fenêtre doit être comprise entre 1 minute et 24 heures.", + "sample_interval_out_of_range": "L’intervalle d’échantillonnage doit être d’au moins 30 secondes et ne pas dépasser la fenêtre.", + "failure_threshold_exceeds_samples": "Le seuil d’échec dépasse le nombre d’échantillons que la fenêtre peut collecter.", + "duplicate_check_name": "Deux contrôles portent le nom « {{check}} ».", + "invalid_url": "Contrôle « {{check}} » : l’URL n’est pas valide. Une URL Prometheus ne doit pas contenir de chaîne de requête ni de fragment.", + "scheme_not_allowed": "Contrôle « {{check}} » : seules les URL http:// et https:// sont autorisées.", + "userinfo_present": "Contrôle « {{check}} » : retirez la partie user:password@ de l’URL.", + "host_missing": "Contrôle « {{check}} » : l’URL n’a pas d’hôte.", + "host_unresolvable": "Contrôle « {{check}} » : l’hôte ne se résout pas depuis le serveur AccessFlow.", + "restricted_address": "Contrôle « {{check}} » : les adresses localhost, loopback et link-local ne sont pas autorisées.", + "metadata_endpoint": "Contrôle « {{check}} » : les points de terminaison de métadonnées cloud ne sont pas autorisés.", + "host_not_allowed": "Contrôle « {{check}} » : l’hôte ne figure pas dans la liste d’autorisation de vérification de ce serveur." + } }, "freezeWindows": { "title": "Fenêtres de gel", diff --git a/frontend/src/locales/hy.json b/frontend/src/locales/hy.json index ac3b2629b..0b9fb0807 100644 --- a/frontend/src/locales/hy.json +++ b/frontend/src/locales/hy.json @@ -5852,7 +5852,11 @@ "verificationNoSamples": "Նմուշներ դեռ չկան", "verificationMinutesValue": "{{n}} րոպե", "verificationSecondsValue": "{{n}} վ", - "timeline_verification": "Ստուգում" + "timeline_verification": "Ստուգում", + "verificationFailedRolledBackTitle": "Ստուգումը ձախողվեց — pipeline-ը հաղորդել է հետ գլորման մասին", + "verificationFailedRolledBackBody": "Խախտումից հետո pipeline-ը հաղորդել է ROLLED_BACK։ AccessFlow-ը ինքը ոչինչ հետ չի գլորել․ ստորև նմուշներն ապացույցն են։", + "verificationSkippedNoConfig": "Այս միջավայրում ստուգում կազմաձևված չէ", + "verificationSkippedOutcome": "Չի ստուգվել — pipeline-ը հաղորդել է {{outcome}}" }, "reviews": { "approve": "Հաստատել", @@ -6125,7 +6129,26 @@ "verificationValueThreshold": "Շեմ", "verificationNoDataIsFailure": "Տվյալների բացակայությունը ձախողում է", "verificationColumn": "Ստուգում", - "verificationChecksCount": "Ստուգումներ՝ {{n}}" + "verificationChecksCount": "Ստուգումներ՝ {{n}}", + "verificationUrlInvalid": "Մուտքագրեք վավեր բացարձակ URL՝ հոստով։", + "verificationUrlUserinfo": "Հեռացրեք user:password@ մասը — URL-ում մուտքի տվյալներ չեն թույլատրվում։", + "verificationUrlQuery": "Միայն բազային URL — առանց հարցման տողի կամ ֆրագմենտի։", + "verificationUrlPlaceholder": "https://service.example.com/healthz", + "verificationPrometheusUrlPlaceholder": "https://prometheus.example.com", + "verificationInvalid": { + "window_out_of_range": "Պատուհանը պետք է լինի 1 րոպեից 24 ժամ։", + "sample_interval_out_of_range": "Նմուշառման միջակայքը պետք է լինի առնվազն 30 վայրկյան և չգերազանցի պատուհանը։", + "failure_threshold_exceeds_samples": "Ձախողման շեմը գերազանցում է պատուհանի հավաքելիք նմուշների քանակը։", + "duplicate_check_name": "Երկու ստուգում ունեն «{{check}}» անվանումը։", + "invalid_url": "«{{check}}» ստուգում․ URL-ը վավեր չէ։ Prometheus URL-ը չպետք է պարունակի հարցման տող կամ ֆրագմենտ։", + "scheme_not_allowed": "«{{check}}» ստուգում․ թույլատրվում են միայն http:// և https:// URL-ներ։", + "userinfo_present": "«{{check}}» ստուգում․ հեռացրեք user:password@ մասը URL-ից։", + "host_missing": "«{{check}}» ստուգում․ URL-ը հոստ չունի։", + "host_unresolvable": "«{{check}}» ստուգում․ հոստը չի լուծվում AccessFlow սերվերից։", + "restricted_address": "«{{check}}» ստուգում․ localhost, loopback և link-local հասցեները թույլատրված չեն։", + "metadata_endpoint": "«{{check}}» ստուգում․ ամպային մետատվյալների վերջնակետերը թույլատրված չեն։", + "host_not_allowed": "«{{check}}» ստուգում․ հոստը այս սերվերի ստուգման թույլատրված ցուցակում չէ։" + } }, "freezeWindows": { "title": "Սառեցման պատուհաններ", diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json index abebbbb61..641e20e3a 100644 --- a/frontend/src/locales/ru.json +++ b/frontend/src/locales/ru.json @@ -5852,7 +5852,11 @@ "verificationNoSamples": "Замеров пока нет", "verificationMinutesValue": "{{n}} мин", "verificationSecondsValue": "{{n}} с", - "timeline_verification": "Проверка" + "timeline_verification": "Проверка", + "verificationFailedRolledBackTitle": "Проверка не пройдена — pipeline сообщил об откате", + "verificationFailedRolledBackBody": "После нарушения pipeline сообщил ROLLED_BACK. Сам AccessFlow ничего не откатывал; замеры ниже — доказательство.", + "verificationSkippedNoConfig": "Для этого окружения проверка не настроена", + "verificationSkippedOutcome": "Не проверялось — pipeline сообщил {{outcome}}" }, "reviews": { "approve": "Одобрить", @@ -6125,7 +6129,26 @@ "verificationValueThreshold": "Порог", "verificationNoDataIsFailure": "Отсутствие данных — сбой", "verificationColumn": "Проверка", - "verificationChecksCount": "Проверок: {{n}}" + "verificationChecksCount": "Проверок: {{n}}", + "verificationUrlInvalid": "Введите корректный абсолютный URL с хостом.", + "verificationUrlUserinfo": "Удалите часть user:password@ — учётные данные в URL не допускаются.", + "verificationUrlQuery": "Только базовый URL — без строки запроса и фрагмента.", + "verificationUrlPlaceholder": "https://service.example.com/healthz", + "verificationPrometheusUrlPlaceholder": "https://prometheus.example.com", + "verificationInvalid": { + "window_out_of_range": "Окно должно быть от 1 минуты до 24 часов.", + "sample_interval_out_of_range": "Интервал опроса должен быть не меньше 30 секунд и не больше окна.", + "failure_threshold_exceeds_samples": "Порог сбоев больше, чем число замеров, которые может собрать окно.", + "duplicate_check_name": "Две проверки называются «{{check}}».", + "invalid_url": "Проверка «{{check}}»: URL некорректен. URL Prometheus не должен содержать строку запроса или фрагмент.", + "scheme_not_allowed": "Проверка «{{check}}»: допускаются только URL http:// и https://.", + "userinfo_present": "Проверка «{{check}}»: удалите часть user:password@ из URL.", + "host_missing": "Проверка «{{check}}»: в URL нет хоста.", + "host_unresolvable": "Проверка «{{check}}»: хост не разрешается с сервера AccessFlow.", + "restricted_address": "Проверка «{{check}}»: адреса localhost, loopback и link-local не допускаются.", + "metadata_endpoint": "Проверка «{{check}}»: эндпоинты облачных метаданных не допускаются.", + "host_not_allowed": "Проверка «{{check}}»: хоста нет в списке разрешённых для проверки на этом сервере." + } }, "freezeWindows": { "title": "Окна заморозки", diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json index b8f8d53d0..3a3f700ce 100644 --- a/frontend/src/locales/zh-CN.json +++ b/frontend/src/locales/zh-CN.json @@ -5852,7 +5852,11 @@ "verificationNoSamples": "暂无样本", "verificationMinutesValue": "{{n}} 分钟", "verificationSecondsValue": "{{n}} 秒", - "timeline_verification": "验证" + "timeline_verification": "验证", + "verificationFailedRolledBackTitle": "验证失败——流水线已报告回滚", + "verificationFailedRolledBackBody": "违规后流水线报告了 ROLLED_BACK。AccessFlow 本身未执行任何回滚;下方样本即为依据。", + "verificationSkippedNoConfig": "此环境未配置验证", + "verificationSkippedOutcome": "未验证——流水线报告了 {{outcome}}" }, "reviews": { "approve": "批准", @@ -6125,7 +6129,26 @@ "verificationValueThreshold": "阈值", "verificationNoDataIsFailure": "无数据视为失败", "verificationColumn": "验证", - "verificationChecksCount": "检查:{{n}}" + "verificationChecksCount": "检查:{{n}}", + "verificationUrlInvalid": "请输入包含主机的有效绝对 URL。", + "verificationUrlUserinfo": "请移除 user:password@ 部分——URL 中不允许包含凭据。", + "verificationUrlQuery": "仅填写基础 URL——不能包含查询字符串或片段。", + "verificationUrlPlaceholder": "https://service.example.com/healthz", + "verificationPrometheusUrlPlaceholder": "https://prometheus.example.com", + "verificationInvalid": { + "window_out_of_range": "时间窗口必须在 1 分钟到 24 小时之间。", + "sample_interval_out_of_range": "采样间隔至少为 30 秒,且不能超过时间窗口。", + "failure_threshold_exceeds_samples": "失败阈值高于该时间窗口可采集的样本数。", + "duplicate_check_name": "有两个检查同名“{{check}}”。", + "invalid_url": "检查“{{check}}”:URL 无效。Prometheus URL 不能包含查询字符串或片段。", + "scheme_not_allowed": "检查“{{check}}”:仅允许 http:// 和 https:// URL。", + "userinfo_present": "检查“{{check}}”:请从 URL 中移除 user:password@ 部分。", + "host_missing": "检查“{{check}}”:URL 缺少主机。", + "host_unresolvable": "检查“{{check}}”:无法从 AccessFlow 服务器解析该主机。", + "restricted_address": "检查“{{check}}”:不允许 localhost、回环和链路本地地址。", + "metadata_endpoint": "检查“{{check}}”:不允许云元数据端点。", + "host_not_allowed": "检查“{{check}}”:该主机不在本服务器的验证允许列表中。" + } }, "freezeWindows": { "title": "冻结窗口", diff --git a/frontend/src/pages/deployments/DeploymentDetailPage.test.tsx b/frontend/src/pages/deployments/DeploymentDetailPage.test.tsx index 9f748a73d..9f7ccaf94 100644 --- a/frontend/src/pages/deployments/DeploymentDetailPage.test.tsx +++ b/frontend/src/pages/deployments/DeploymentDetailPage.test.tsx @@ -652,6 +652,63 @@ describe('DeploymentDetailPage', () => { expect(screen.queryByText(/rolled back/i)).toBeNull(); }); + it('stops advising a rollback once the pipeline has reported ROLLED_BACK', async () => { + getDeploymentRequestMock.mockResolvedValue({ ...breached, outcome: 'ROLLED_BACK' }); + + render(wrap()); + + expect( + await screen.findByText('Verification failed — the pipeline reported a rollback'), + ).toBeInTheDocument(); + expect(screen.queryByText('Verification failed — the release is still running')).toBeNull(); + expect(screen.queryByText(/Decide whether to roll back/)).toBeNull(); + }); + + it('shows a translated reason and no samples card for an unverified environment', async () => { + getDeploymentRequestMock.mockResolvedValue({ + ...baseRequest, + status: 'EXECUTED', + outcome: 'SUCCEEDED', + outcome_reported_at: '2026-05-01T12:00:00Z', + verification_status: 'SKIPPED', + verification_detail: 'no verification configured', + }); + + render(wrap()); + + expect( + (await screen.findAllByText('No verification configured on this environment')).length, + ).toBeGreaterThan(0); + expect(screen.queryByText('no verification configured')).toBeNull(); + expect(screen.queryByText('No samples yet')).toBeNull(); + expect(getDeploymentVerificationSamplesMock).not.toHaveBeenCalled(); + }); + + it('fetches the samples once more when the window closes', async () => { + getDeploymentRequestMock.mockResolvedValueOnce({ + ...breached, + status: 'EXECUTED', + verification_status: 'RUNNING', + verification_finished_at: null, + }); + getDeploymentRequestMock.mockResolvedValue(breached); + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + render(wrap()); + await screen.findByText('No samples yet'); + getDeploymentVerificationSamplesMock.mockResolvedValue([sample]); + await act(async () => { + await vi.advanceTimersByTimeAsync(10_500); + }); + expect( + await screen.findByText('Verification failed — the release is still running'), + ).toBeInTheDocument(); + expect(await screen.findByText('expected status 200, got 503')).toBeInTheDocument(); + } finally { + vi.useRealTimers(); + } + }); + it('fetches no samples and shows no card while verification is PENDING', async () => { getDeploymentRequestMock.mockResolvedValue(baseRequest); getDeploymentGateMock.mockResolvedValue(releasableGate); diff --git a/frontend/src/pages/deployments/DeploymentDetailPage.tsx b/frontend/src/pages/deployments/DeploymentDetailPage.tsx index 094ded6e4..523876aae 100644 --- a/frontend/src/pages/deployments/DeploymentDetailPage.tsx +++ b/frontend/src/pages/deployments/DeploymentDetailPage.tsx @@ -14,7 +14,7 @@ import { Tag, } from 'antd'; import type { TableColumnsType } from 'antd'; -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { ThunderboltOutlined } from '@ant-design/icons'; import { useNavigate, useParams } from 'react-router-dom'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; @@ -55,7 +55,10 @@ import { isoDurationSeconds } from '@/components/deployments/verificationForm'; import { fmtDate } from '@/utils/dateFormat'; import { apiErrorMessage } from '@/utils/apiErrors'; import { showApiError } from '@/utils/showApiError'; -import { buildDeploymentTimelineStages } from './buildDeploymentTimelineStages'; +import { + buildDeploymentTimelineStages, + verificationDetailText, +} from './buildDeploymentTimelineStages'; import type { DeploymentDecision, DeploymentRequest, @@ -118,13 +121,31 @@ export default function DeploymentDetailPage() { const verificationStatus = request?.verification_status ?? 'PENDING'; const verificationRunning = verificationStatus === 'RUNNING'; + // A SKIPPED request with no snapshot never opened a window: nothing was ever sampled. + const verificationSampled = + verificationStatus !== 'PENDING' && + !(verificationStatus === 'SKIPPED' && request?.verification_snapshot == null); + const samplesQuery = useQuery({ queryKey: deploymentKeys.verification(id), queryFn: () => getDeploymentVerificationSamples(id), - enabled: !!id && verificationStatus !== 'PENDING', + enabled: !!id && verificationSampled, refetchInterval: verificationRunning ? VERIFICATION_POLL_MS : false, }); + // The two polls tick independently, so the render that sees the window close also stops the + // samples poll — usually before it fetched the breaching sample. Fetch once more on the way out. + const previousVerificationStatus = useRef(verificationStatus); + useEffect(() => { + if (previousVerificationStatus.current === 'RUNNING' && verificationStatus !== 'RUNNING') { + void queryClient.invalidateQueries({ queryKey: deploymentKeys.verification(id) }); + } + previousVerificationStatus.current = verificationStatus; + }, [verificationStatus, queryClient, id]); + const verificationDetail = request + ? verificationDetailText(t, verificationStatus, request.verification_detail) + : null; + // Freeze state lives only on the gate; ask it just while the request is APPROVED. // A 404 (visibility) simply hides the banner — retry would never succeed. const gateQuery = useQuery({ @@ -334,12 +355,17 @@ export default function DeploymentDetailPage() { )} {/* FAILED + SUCCEEDED: the deploy ran and is still live. Never phrase this as a - rollback — AccessFlow does not roll anything back. */} + rollback — AccessFlow does not roll anything back. Once the pipeline reports + ROLLED_BACK (accepted after a breach, #1025) the "still running" advice is stale. */} {verificationStatus === 'FAILED' && ( {request.verification_detail && ( @@ -347,7 +373,9 @@ export default function DeploymentDetailPage() { {request.verification_detail}
)} - {t('deploygov.detail.verificationFailedBody')} + {request.outcome === 'ROLLED_BACK' + ? t('deploygov.detail.verificationFailedRolledBackBody') + : t('deploygov.detail.verificationFailedBody')} } /> @@ -391,7 +419,17 @@ export default function DeploymentDetailPage() { { key: 'verification', label: t('deploygov.detail.verification'), - children: , + // With no card to carry it, an unsampled request's reason sits here. + children: ( + + + {!verificationSampled && verificationDetail && ( + + {verificationDetail} + + )} + + ), }, ] : []), @@ -563,7 +601,7 @@ export default function DeploymentDetailPage() {
- {verificationStatus !== 'PENDING' && ( + {verificationSampled && ( } @@ -612,7 +650,7 @@ export default function DeploymentDetailPage() { { key: 'detail', label: t('deploygov.detail.verificationDetail'), - children: request.verification_detail ?? '—', + children: verificationDetail ?? '—', }, ]} /> diff --git a/frontend/src/pages/deployments/DeploymentListPage.test.tsx b/frontend/src/pages/deployments/DeploymentListPage.test.tsx index 06b9f7b55..b7ff9093d 100644 --- a/frontend/src/pages/deployments/DeploymentListPage.test.tsx +++ b/frontend/src/pages/deployments/DeploymentListPage.test.tsx @@ -195,14 +195,25 @@ describe('DeploymentListPage', () => { expect(screen.getAllByText(/^verification /)).toHaveLength(1); }); - it('shows a skipped verification for a request without an outcome tag', async () => { + it('leaves a skipped verification untagged — it would tag every unverified deploy', async () => { listDeploymentRequestsMock.mockResolvedValue( - pageOf([{ ...baseRequest, verification_status: 'SKIPPED' }]), + pageOf([ + { + ...baseRequest, + status: 'EXECUTED', + outcome: 'SUCCEEDED', + outcome_reported_at: '2026-05-01T12:00:00Z', + verification_status: 'SKIPPED', + }, + { ...baseRequest, id: 'req-2', version: '3.0.2', verification_status: 'RUNNING' }, + ]), ); render(wrap()); - expect(await screen.findByText('verification skipped')).toBeInTheDocument(); + expect(await screen.findByText('verification running')).toBeInTheDocument(); + expect(screen.getByText('succeeded')).toBeInTheDocument(); + expect(screen.queryByText('verification skipped')).toBeNull(); }); it('shows the linked change ticket with its decision in the ticket column', async () => { diff --git a/frontend/src/pages/deployments/DeploymentListPage.tsx b/frontend/src/pages/deployments/DeploymentListPage.tsx index c09f243ed..c3ec53eea 100644 --- a/frontend/src/pages/deployments/DeploymentListPage.tsx +++ b/frontend/src/pages/deployments/DeploymentListPage.tsx @@ -151,8 +151,10 @@ export default function DeploymentListPage() { dataIndex: 'outcome', width: 130, render: (outcome: DeploymentRequest['outcome'], row) => { + // SKIPPED is left out: it would tag every deploy to an environment with no checks. const verification = row.verification_status ?? 'PENDING'; - if (outcome == null && verification === 'PENDING') return —; + const showVerification = verification !== 'PENDING' && verification !== 'SKIPPED'; + if (outcome == null && !showVerification) return —; const color = outcome == null ? null : deploymentOutcomeColor(outcome); const verificationColor = verificationStatusColor(verification); return ( @@ -163,7 +165,7 @@ export default function DeploymentListPage() { )} {/* A breach leaves outcome SUCCEEDED, so the verification tag says it failed. */} - {verification !== 'PENDING' && ( + {showVerification && ( { expect(stages[stages.length - 1]).toMatchObject({ label: 'deploygov.detail.timeline_verification', skipped: true, + detail: 'deploygov.detail.verificationSkippedOutcome:outcome=enums.deployment_outcome.FAILED', }); }); + + it('translates the SKIPPED machine tokens and passes a breach detail through', () => { + expect(verificationDetailText(t, 'SKIPPED', 'no verification configured')).toBe( + 'deploygov.detail.verificationSkippedNoConfig', + ); + expect(verificationDetailText(t, 'SKIPPED', 'outcome:ROLLED_BACK')).toBe( + 'deploygov.detail.verificationSkippedOutcome:outcome=enums.deployment_outcome.ROLLED_BACK', + ); + expect(verificationDetailText(t, 'SKIPPED', 'outcome:SUCCEEDED')).toBe( + 'deploygov.detail.verificationSkippedOutcome:outcome=enums.deployment_outcome.SUCCEEDED', + ); + expect(verificationDetailText(t, 'SKIPPED', 'outcome:WHATEVER')).toBe('outcome:WHATEVER'); + expect(verificationDetailText(t, 'SKIPPED', 'something new')).toBe('something new'); + expect(verificationDetailText(t, 'FAILED', 'outcome:FAILED')).toBe('outcome:FAILED'); + expect(verificationDetailText(t, 'FAILED', 'health: 1/1 failed samples')).toBe( + 'health: 1/1 failed samples', + ); + expect(verificationDetailText(t, 'SKIPPED', null)).toBeNull(); + expect(verificationDetailText(t, 'SKIPPED', '')).toBeNull(); + }); }); }); diff --git a/frontend/src/pages/deployments/buildDeploymentTimelineStages.ts b/frontend/src/pages/deployments/buildDeploymentTimelineStages.ts index 9c455424d..8afe4944a 100644 --- a/frontend/src/pages/deployments/buildDeploymentTimelineStages.ts +++ b/frontend/src/pages/deployments/buildDeploymentTimelineStages.ts @@ -1,6 +1,6 @@ import type { TFunction } from 'i18next'; import type { TimelineStage } from '@/components/review/ApprovalTimeline'; -import type { DeploymentRequest } from '@/types/api'; +import type { DeploymentRequest, VerificationStatus } from '@/types/api'; import { fmtDate } from '@/utils/dateFormat'; import { deploymentOutcomeLabel, @@ -8,6 +8,34 @@ import { verificationStatusLabel, } from '@/utils/enumLabels'; +const SKIPPED_OUTCOME_PREFIX = 'outcome:'; + +/** + * The backend's `verification_detail` for a SKIPPED request is a machine token + * (`no verification configured`, `outcome:FAILED`, `outcome:ROLLED_BACK` — #1025), so it is + * translated here; a breach detail (`: n/threshold failed samples`) is shown as sent. + */ +export function verificationDetailText( + t: TFunction, + status: VerificationStatus, + detail: string | null | undefined, +): string | null { + if (detail == null || detail === '') return null; + if (status !== 'SKIPPED') return detail; + if (detail === 'no verification configured') { + return t('deploygov.detail.verificationSkippedNoConfig'); + } + if (detail.startsWith(SKIPPED_OUTCOME_PREFIX)) { + const outcome = detail.slice(SKIPPED_OUTCOME_PREFIX.length); + if (outcome === 'FAILED' || outcome === 'ROLLED_BACK' || outcome === 'SUCCEEDED') { + return t('deploygov.detail.verificationSkippedOutcome', { + outcome: deploymentOutcomeLabel(t, outcome), + }); + } + } + return detail; +} + const REVIEW_DONE_STATUSES = ['APPROVED', 'EXECUTED', 'FAILED', 'CANCELLED'] as const; export function buildDeploymentTimelineStages( @@ -142,7 +170,7 @@ export function buildDeploymentTimelineStages( active: verification === 'RUNNING', failed: verification === 'FAILED', skipped: verification === 'SKIPPED', - detail: request.verification_detail ?? null, + detail: verificationDetailText(t, verification, request.verification_detail), }); } return out; diff --git a/help-corpus/manifest.json b/help-corpus/manifest.json index 3fc6e8aac..31ccce5bd 100644 --- a/help-corpus/manifest.json +++ b/help-corpus/manifest.json @@ -1,8 +1,8 @@ { "schemaVersion": 1, "corpusVersion": "debe778a1394", - "generatedAt": "2026-11-11T07:13:06.668Z", - "sourceCommit": "d3bacb04fddb57c0401ca5960a70434162ea0aa4", + "generatedAt": "2026-11-11T07:26:16.507Z", + "sourceCommit": "2bf3e402f99f2e83cec1a131deea0283e0e3276e", "chunkCount": 615, "sha256": "debe778a139480445a9c4945403fec4d253471c837b75d6236b7484cddc70d4d", "quickReferenceSha256": "24edf02e4c124fee2ce843e9333a470905f9a55868ddc3cdef869315ca473072", @@ -429,7 +429,7 @@ "url": "https://accessflow.io/docs/", "section": "Navigation", "chunks": 9, - "sha256": "cb28ca6bd022a4eff61ced2c688c6b80351465cdf632a0ba3bed26c71b64905e" + "sha256": "9929f8b21083b52ff7d7ca8ace6df3b0602ab9056d081d83f3430e1ab7a8c7dc" } ] }