#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Encryption at rest: operator surface (P3A) (#7501)
ConnorYoh76047297f9eb
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/controller/StorageEncryptionAdminController.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/controller/StorageEncryptionAdminController.javaindex d0845678ef..1712de53fe 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/controller/StorageEncryptionAdminController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/controller/StorageEncryptionAdminController.java@@ -95,22 +95,32 @@ public class StorageEncryptionAdminController {.toList();String fingerprint = null;Integer masterKeyVersion = null;+ String masterKeySource = null;if (encryptionState.isMaterialised()) {try {FileEncryptionKeyService keyService = encryptionState.keyService();fingerprint = keyService.masterKey().fingerprint();masterKeyVersion = keyService.masterKey().currentVersion();+ masterKeySource = keyService.masterKey().source().wireName();} catch (StorageEncryptionException ignored) {// Materialisation failed; status still reports counts and key rows.}}+ // Counted in the database so the total stays right if `keys` is ever paged.+ long pendingRotationRows =+ masterKeyVersion == null+ ? 0+ : keyRepository.countByMasterKeyVersionLessThan(masterKeyVersion);return new StorageEncryptionStatusResponse(encryptionState.isWriteEnabled(),encryptionState.isMaterialised(),fingerprint,masterKeyVersion,+ masterKeySource,+ applicationProperties.getStorage().getProvider(),storedFileRepository.countByEncryptionKeyIdIsNotNull(),storedFileRepository.countByEncryptionKeyIdIsNull(),+ pendingRotationRows,keys);}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/crypto/FileEncryptionMasterKey.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/crypto/FileEncryptionMasterKey.javaindex 5b78b00135..0b90bb770e 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/crypto/FileEncryptionMasterKey.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/crypto/FileEncryptionMasterKey.java@@ -49,6 +49,24 @@ public class FileEncryptionMasterKey {private final SecretKey key;private final SecretKey previousKey;private final int currentVersion;+ private final Source source;++ /** Where the master key came from, so the UI can warn about an unbacked-up generated key. */+ public enum Source {+ CONFIG("config"),+ ENVIRONMENT("environment"),+ GENERATED("generated");++ private final String wireName;++ Source(String wireName) {+ this.wireName = wireName;+ }++ public String wireName() {+ return wireName;+ }+ }public FileEncryptionMasterKey(String configuredKey, boolean clusterEnabled) {this(configuredKey, null, CURRENT_VERSION, clusterEnabled);@@ -66,7 +84,9 @@ public class FileEncryptionMasterKey {String previousKeyBase64,int currentVersion,boolean clusterEnabled) {- this.key = resolveKey(configuredKey, clusterEnabled);+ Resolved resolved = resolveKey(configuredKey, clusterEnabled);+ this.key = resolved.key();+ this.source = resolved.source();this.previousKey =previousKeyBase64 == null || previousKeyBase64.isBlank()? null@@ -90,19 +110,27 @@ public class FileEncryptionMasterKey {return currentVersion;}+ public Source source() {+ return source;+ }+public boolean hasPreviousKey() {return previousKey != null;}- private static SecretKey resolveKey(String configuredKey, boolean clusterEnabled) {+ private record Resolved(SecretKey key, Source source) {}++ private static Resolved resolveKey(String configuredKey, boolean clusterEnabled) {String configured = configuredKey;String source = "stirling.security.fileEncryptionKey";+ Source provenance = Source.CONFIG;if (configured == null || configured.isBlank()) {configured = System.getenv("STIRLING_FILE_ENCRYPTION_KEY");source = "STIRLING_FILE_ENCRYPTION_KEY";+ provenance = Source.ENVIRONMENT;}if (configured != null && !configured.isBlank()) {- return decodeKey(configured, source);+ return new Resolved(decodeKey(configured, source), provenance);}if (clusterEnabled) {throw new IllegalStateException(@@ -111,7 +139,7 @@ public class FileEncryptionMasterKey {+ " stirling.security.fileEncryptionKey) to the same value on every"+ " node.");}- return loadOrCreateKeyFile();+ return new Resolved(loadOrCreateKeyFile(), Source.GENERATED);}/**diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/model/api/StorageEncryptionStatusResponse.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/model/api/StorageEncryptionStatusResponse.javaindex 0699a1aecd..f6832329c1 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/model/api/StorageEncryptionStatusResponse.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/model/api/StorageEncryptionStatusResponse.java@@ -13,8 +13,14 @@ public record StorageEncryptionStatusResponse(boolean active,String masterKeyFingerprint,Integer masterKeyVersion,+ /** Where the master key came from: config, environment or generated. */+ String masterKeySource,+ /** Backend serving stored blobs: local, database or s3. */+ String provider,long encryptedFiles,long plaintextFiles,+ /** Key rows still wrapped by an older master key, counted in the database. */+ long pendingRotationRows,List<KeyInfo> keys) {public record KeyInfo(diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/storage/crypto/FileEncryptionMasterKeySourceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/storage/crypto/FileEncryptionMasterKeySourceTest.javanew file mode 100644index 0000000000..99039531d2--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/storage/crypto/FileEncryptionMasterKeySourceTest.java@@ -0,0 +1,30 @@+package stirling.software.proprietary.storage.crypto;++import static org.assertj.core.api.Assertions.assertThat;++import java.util.Base64;++import org.junit.jupiter.api.Test;++/**+ * Provenance drives the "this key was generated for you" warning, which is the only prompt an+ * operator gets to back up a key they never chose.+ */+class FileEncryptionMasterKeySourceTest {++ private static final String MASTER = Base64.getEncoder().encodeToString(new byte[32]);++ @Test+ void configuredKeyReportsConfig() {+ FileEncryptionMasterKey key = new FileEncryptionMasterKey(MASTER, false);++ assertThat(key.source()).isEqualTo(FileEncryptionMasterKey.Source.CONFIG);+ assertThat(key.source().wireName()).isEqualTo("config");+ }++ @Test+ void wireNamesMatchTheValuesTheUiSwitchesOn() {+ assertThat(FileEncryptionMasterKey.Source.ENVIRONMENT.wireName()).isEqualTo("environment");+ assertThat(FileEncryptionMasterKey.Source.GENERATED.wireName()).isEqualTo("generated");+ }+}diff --git a/devGuide/STORAGE_ENCRYPTION_AT_REST.md b/devGuide/STORAGE_ENCRYPTION_AT_REST.mdindex 6ec8d047aa..638e05ed8d 100644--- a/devGuide/STORAGE_ENCRYPTION_AT_REST.md+++ b/devGuide/STORAGE_ENCRYPTION_AT_REST.md@@ -74,6 +74,29 @@ Disabling only stops encrypting *new* writes. Existing encrypted files stay readkey material is present — the decrypt path is always active and is never licence-gated, so a lapsedlicence cannot lock you out of your own data.+## Backing up the master key++Every scope key in `file_encryption_keys` is wrapped by the master key, so the master key is the+single thing standing between a backup and unreadable files. Losing it makes every encrypted stored+file unrecoverable — there is no recovery path, by design.++Back it up when you enable encryption, not later:++- **Key set in config or environment.** Store the base64 value in whatever holds your other+ secrets. The value in `stirling.security.fileEncryptionKey` or `STIRLING_FILE_ENCRYPTION_KEY`+ *is* the backup.+- **Auto-generated key.** The server wrote `configs/file-encryption.key` on first use and logged a+ warning. Copy that file somewhere durable and off the machine. Nothing else in the install holds+ a copy. `/status` reports `masterKeySource: "generated"` for this case, and the admin UI shows a+ warning until the key is configured explicitly.++To check a backup matches the running system, compare its fingerprint against the one in the+startup log or in `/status` — see [Status and backup verification](#status-and-backup-verification).+The fingerprint is a SHA-256 prefix, so it can be compared safely without exposing key material.++Restoring is just putting the key back: set it in config or the environment, or restore the file to+`configs/file-encryption.key`, and start the server. No re-encryption is involved.+## Encrypting files that already existEnabling the flag does not touch the existing plaintext backlog. To convert it:@@ -163,9 +186,14 @@ Two semantics worth knowing when reading the trail:curl http://localhost:8080/api/v1/admin/storage-encryption/status```-Reports whether writes are encrypted, the master-key fingerprint, encrypted vs plaintext file-counts, and every key row with its status history. All endpoints under-`/api/v1/admin/storage-encryption` require an admin account.+Reports whether writes are encrypted, the master-key fingerprint, where the key came from+(`masterKeySource`: `config`, `environment` or `generated`), the storage backend, encrypted vs+plaintext file counts, the number of key rows still on an older master key, and every key row with+its status history. All endpoints under `/api/v1/admin/storage-encryption` require an admin+account.++The same information is on the Storage tab under Infrastructure in the admin UI, which is the+surface most operators should use.## What this protects againstdiff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex fa42c83b22..628e92d38c 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -8344,6 +8344,172 @@ subtitleCreated = "Copy this secret now — it won't be shown again."title = "Create API key"titleCreated = "Key created"+[portal.infrastructure.encryption]+heading = "Encryption at rest"+hintLabel = "More about this section"+subheading = "Stored files are encrypted before they reach disk, the database or object storage."+unknown = "Unknown"++[portal.infrastructure.encryption.auditNotice]+description = "Encryption is active on this licence, but encrypt, decrypt, revocation and export events are not written to the audit trail. Encryption itself is unaffected."+title = "Audit events need an Enterprise licence"++[portal.infrastructure.encryption.coverage]+decryptOnlyNote = "New uploads are stored as plaintext. Files encrypted earlier are still readable."+encrypted = "Encrypted files"+heading = "Coverage"+percentEncrypted = "{{percent}}% encrypted"+plaintext = "Plaintext files"+progressLabel = "{{percent}}% of stored files encrypted"+subheading = "Covers files in My Files and signing workflows. Files a pipeline reads in place, including network sources, are not stored here and are not encrypted."++[portal.infrastructure.encryption.error]+action = "That key change could not be applied. Please try again."+keyMissing = "That key no longer exists. Refresh to see the current list."+migrationStart = "The migration could not be started. Please try again."+rotate = "The re-wrap could not be completed. Please try again."++[portal.infrastructure.encryption.generatedKey]+backupGuide = "How to back it up"+description = "No encryption key was configured, so one was created on this server. Back it up now: if it is lost, encrypted files cannot be recovered."+title = "This key was generated for you"++[portal.infrastructure.encryption.keys]+changedAt = "Changed {{when}}"+changedBy = "By {{actor}}"+changedByAt = "By {{actor}} on {{when}}"+heading = "Scope keys"+keyVersion = "Version {{version}}"+neverChanged = "Never changed"+restore = "Restore access"+retiredNote = "A retired key still decrypts the files stored under it, but a newer key wraps new uploads."+revoke = "Revoke"+subheading = "One key per scope. Revoking a key blocks reads of everything stored under it."++[portal.infrastructure.encryption.keys.columns]+actions = "Actions"+lastChange = "Last change"+scope = "Scope"+status = "Status"++[portal.infrastructure.encryption.keys.empty]+description = "A key is created the first time someone uploads a file, not at startup."+title = "No keys yet"++[portal.infrastructure.encryption.masterKey]+backend = "Storage backend"+compareNote = "Compare this against the fingerprint in your key backup and in the startup log."+copied = "Copied"+copy = "Copy"+copyFailed = "This browser would not allow copying. The fingerprint is selected, so copy it manually."+fingerprint = "Fingerprint"+fingerprintHelp = "What is this fingerprint for?"+heading = "Master key"+notMaterialised = "The key machinery has not started on this node yet."+s3StreamingNote = "While anything is encrypted, object-store downloads are streamed through this server rather than redirected, so they use its bandwidth."+subheading = "Wraps every scope key. Never shown or accepted over the API."+version = "Version"++[portal.infrastructure.encryption.migration]+backlog_one = "{{formatted}} file is stored as plaintext and can be encrypted now."+backlog_other = "{{formatted}} files are stored as plaintext and can be encrypted now."+encrypted = "Encrypted"+failedCount = "Failed"+heading = "Encrypt existing files"+hint = "Encrypts the plaintext backlog left from before encryption was switched on. Progress is held in memory, so a backend restart resets it to not started. Running again skips files that are already encrypted."+noBacklog = "Every stored file is already encrypted."+progressLabel = "{{processed}} of {{total}} files encrypted"+requiresEncryptionOn = "Switch encryption on before running this: the backlog is encrypted using the same write path as new uploads."+runAgain = "Run again"+skipped = "Skipped"+skippedHelp = "What does skipped mean?"+skippedNote = "Skipped files were replaced by a user while the run was in progress, so their copy was left alone."+start = "Start"+startedAt = "Started {{when}}"++[portal.infrastructure.encryption.migration.confirm]+cancel = "Cancel"+confirm = "Start encrypting"+noCancel = "There is no stop control. Once started, the run continues until it finishes or encryption is switched off."+rewrites_one = "Rewrites {{formatted}} stored file, replacing the plaintext copy with an encrypted one."+rewrites_other = "Rewrites {{formatted}} stored files, replacing the plaintext copies with encrypted ones."+throttled = "The job is throttled and safe to re-run. Files already encrypted are skipped."+title = "Encrypt the existing backlog?"++[portal.infrastructure.encryption.migration.failed]+description = "Encryption was switched off while the migration was running, so the remaining files were left untouched. Switch it back on and run again."+title = "The run stopped early"++[portal.infrastructure.encryption.migration.state]+COMPLETED = "Completed"+FAILED = "Failed"+IDLE = "Not started"+RUNNING = "Running"++[portal.infrastructure.encryption.revoke]+cancel = "Cancel"+clusterDelay = "On a cluster, other nodes apply this within 60 seconds."+confirm = "Revoke access"+readsFail = "Files already stored under this key stop opening, for everyone."+reversible = "This is reversible. No key material is deleted."+title = "Revoke access to this key?"+uploadsContinue = "New uploads keep working. They get a fresh key, so they stay readable."++[portal.infrastructure.encryption.rotation]+currentVersion = "Current version"+heading = "Master key rotation"+hint = "Re-wraps scope keys under a new master key; file contents are never rewritten. The new key is set in configuration and applied on restart, so this button only performs the re-wrap."+pendingRows = "Rows on an older version"+rewrap = "Re-wrap keys"+rewrapped_one = "{{count}} key row re-wrapped."+rewrapped_other = "{{count}} key rows re-wrapped."+runbook = "Rotation runbook"++[portal.infrastructure.encryption.rotation.confirm]+cancel = "Cancel"+confirm = "Re-wrap keys"+noFiles = "File contents are not touched. Only the key table is rewritten."+rerunnable = "Safe to run again if it does not finish."+rewraps_one = "Re-wraps {{count}} key row under the current master key."+rewraps_other = "Re-wraps {{count}} key rows under the current master key."+title = "Re-wrap the key table?"++[portal.infrastructure.encryption.rotation.pending]+description = "Do not remove the previous key from configuration yet. Files under those keys would stop opening."+title_one = "{{count}} key row is still on the previous master key"+title_other = "{{count}} key rows are still on the previous master key"++[portal.infrastructure.encryption.scope]+global = "All users"+source = "Source {{id}}"+team = "Team {{id}}"++[portal.infrastructure.encryption.status]+ACTIVE = "Active"+DISABLED = "Revoked"+RETIRED = "Retired"++[portal.infrastructure.encryption.unavailable.forbidden]+description = "Your account does not have permission to view encryption settings."+title = "Not available for your account"++[portal.infrastructure.encryption.unavailable.registry-unavailable]+description = "The encryption key registry could not be read. Check the database connection and the application logs."+title = "Key registry unavailable"++[portal.infrastructure.encryption.unavailable.storage-disabled]+description = "File storage is switched off on this server, so there is nothing to encrypt."+title = "Storage is disabled"++[portal.infrastructure.encryption.unavailable.unknown]+description = "Encryption status could not be loaded. Please try again."+title = "Status unavailable"++[portal.infrastructure.encryption.writeState]+decryptOnly = "Decrypt only"+encrypting = "Encrypting new uploads"+off = "Off"+[portal.infrastructure.keyLabel]active = "Active"revoked = "Revoked"diff --git a/frontend/editor/src/core/i18n/translationAudit.ts b/frontend/editor/src/core/i18n/translationAudit.tsindex e7ac246d2f..5d7ffd7a38 100644--- a/frontend/editor/src/core/i18n/translationAudit.ts+++ b/frontend/editor/src/core/i18n/translationAudit.ts@@ -112,6 +112,11 @@ export const I18N_PROJECTS: TranslationProject[] = [// A failure's disabled reason arrives from the server as a key and is rendered with// t(thatKey), so nothing in source names it, but the copy still has to exist./^portal\.failures\.disabled\./,+ // Encryption panel copy keyed by backend enum values: key status, write+ // state, migration state, and the reason a status read was refused. Each+ // is t(`...${value}`) where the value comes from the API response.+ /^portal\.infrastructure\.encryption\.(status|writeState|unavailable)\./,+ /^portal\.infrastructure\.encryption\.migration\.state\./,],minUsedKeys: 100,minLocaleKeys: 100,diff --git a/frontend/editor/src/core/ui/Tooltip.css b/frontend/editor/src/core/ui/Tooltip.cssnew file mode 100644index 0000000000..a4bc6d8dd4--- /dev/null+++ b/frontend/editor/src/core/ui/Tooltip.css@@ -0,0 +1,38 @@+.sui-tip {+ position: relative;+ display: inline-flex;+ align-items: center;+}++/* Matches the editor tooltip (components/shared/tooltip/Tooltip.module.css):+ same surface, radius, type scale and soft two-layer shadow, so the product+ has one tooltip look rather than two. Fixed and portalled to the body,+ because a tooltip in the flow is clipped by the first ancestor that hides+ its overflow. */+.sui-tip__bubble {+ position: fixed;+ z-index: 1300;+ width: max-content;+ max-width: min(22rem, calc(100vw - 2rem));+ padding: 0.625rem 0.75rem;+ border: 0.0625rem solid var(--c-border);+ border-radius: 0.75rem;+ background-color: var(--c-surface-raised);+ box-shadow:+ 0 0.625rem 0.9375rem -0.1875rem rgba(0, 0, 0, 0.1),+ 0 0.25rem 0.375rem -0.125rem rgba(0, 0, 0, 0.05);+ color: var(--c-text);+ font-family: var(--font-sans);+ font-size: 0.875rem;+ font-weight: 400;+ line-height: 1.5;+ text-align: left;+ white-space: normal;+ pointer-events: none;+ /* The trigger often sits inside styled text (an uppercased stat label, a+ heading). The bubble is portalled out, but reset anyway so it always reads+ as prose regardless of where it is mounted. */+ text-transform: none;+ letter-spacing: normal;+ font-style: normal;+}diff --git a/frontend/editor/src/core/ui/Tooltip.stories.tsx b/frontend/editor/src/core/ui/Tooltip.stories.tsxnew file mode 100644index 0000000000..c14f9f0c83--- /dev/null+++ b/frontend/editor/src/core/ui/Tooltip.stories.tsx@@ -0,0 +1,72 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { expect, userEvent, within } from "storybook/test";+import { ActionIcon } from "@app/ui/ActionIcon";+import { Button } from "@app/ui/Button";+import { Tooltip } from "@app/ui/Tooltip";++const meta: Meta<typeof Tooltip> = {+ title: "Primitives/Tooltip",+ component: Tooltip,+ parameters: { layout: "centered" },+ argTypes: {+ placement: {+ control: "inline-radio",+ options: ["top", "bottom", "left", "right"],+ },+ },+};+export default meta;+type Story = StoryObj<typeof Tooltip>;++export const Default: Story = {+ args: {+ content: "Skipped files were replaced while the run was in progress.",+ children: <Button variant="secondary">Hover me</Button>,+ },+};++/** The common shape: an icon that exists only to carry the explanation. */+export const OnAnIconTrigger: Story = {+ args: {+ content: "Counts every file the run left alone.",+ children: <ActionIcon variant="quiet" aria-label="What is this?" />,+ },+};++export const Placements: Story = {+ render: () => (+ <div style={{ display: "flex", gap: 48, padding: 48 }}>+ {(["top", "bottom", "left", "right"] as const).map((placement) => (+ <Tooltip key={placement} placement={placement} content={placement}>+ <Button variant="secondary">{placement}</Button>+ </Tooltip>+ ))}+ </div>+ ),+};++/** Keyboard reach: focusing the trigger opens it, and Escape closes it. */+export const OpensOnFocus: Story = {+ args: {+ content: "Reachable without a mouse.",+ children: <Button variant="secondary">Focus me</Button>,+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const trigger = canvas.getByRole("button", { name: /focus me/i });+ await userEvent.tab();+ await expect(trigger).toHaveFocus();+ // Portalled to the body, so it is not inside the canvas element. That is the+ // point: in the flow it was clipped by the first ancestor hiding overflow.+ const tip = await within(document.body).findByRole("tooltip");+ await expect(tip.parentElement).toBe(document.body);+ await expect(trigger).toHaveAttribute("aria-describedby", tip.id);++ // Placed inside the viewport rather than hanging off an edge.+ const box = tip.getBoundingClientRect();+ await expect(box.left).toBeGreaterThanOrEqual(0);+ await expect(box.top).toBeGreaterThanOrEqual(0);+ await expect(box.right).toBeLessThanOrEqual(window.innerWidth);+ await expect(box.bottom).toBeLessThanOrEqual(window.innerHeight);+ },+};diff --git a/frontend/editor/src/core/ui/Tooltip.tsx b/frontend/editor/src/core/ui/Tooltip.tsxnew file mode 100644index 0000000000..fc53e5290b--- /dev/null+++ b/frontend/editor/src/core/ui/Tooltip.tsx@@ -0,0 +1,156 @@+import {+ cloneElement,+ useCallback,+ useEffect,+ useId,+ useLayoutEffect,+ useRef,+ useState,+ type ReactElement,+ type ReactNode,+} from "react";+import { createPortal } from "react-dom";+import "@app/ui/Tooltip.css";++export type TooltipPlacement = "top" | "bottom" | "left" | "right";++/** Breathing room kept between the bubble and both the trigger and the viewport. */+const GAP = 8;++export interface TooltipProps {+ /** Explanatory text. Keep it to a sentence or two. */+ content: ReactNode;+ placement?: TooltipPlacement;+ /**+ * The trigger. Must be focusable (a Button or ActionIcon), otherwise the+ * tooltip is unreachable by keyboard and by touch.+ */+ children: ReactElement;+ className?: string;+}++/**+ * Hover, focus and tap tooltip with no context dependencies, so it works in the+ * editor, the portal and the processor alike. The richer editor tooltip+ * (`@app/components/shared/Tooltip`) needs the sidebar, preferences and+ * app-config providers, which the portal does not mount; this matches its look.+ *+ * The bubble is portalled to the body and positioned fixed, because a tooltip+ * rendered inside the flow is clipped by the first ancestor that hides its+ * overflow — a card, a table, a scroll container.+ */+export function Tooltip({+ content,+ placement = "top",+ children,+ className,+}: TooltipProps) {+ const [open, setOpen] = useState(false);+ const [pos, setPos] = useState<{ top: number; left: number } | null>(null);+ const id = useId();+ const anchorRef = useRef<HTMLSpanElement | null>(null);+ const bubbleRef = useRef<HTMLDivElement | null>(null);++ const place = useCallback(() => {+ const anchor = anchorRef.current?.getBoundingClientRect();+ const bubble = bubbleRef.current?.getBoundingClientRect();+ if (!anchor || !bubble) return;++ let top: number;+ let left: number;+ switch (placement) {+ case "bottom":+ top = anchor.bottom + GAP;+ left = anchor.left + anchor.width / 2 - bubble.width / 2;+ break;+ case "left":+ top = anchor.top + anchor.height / 2 - bubble.height / 2;+ left = anchor.left - bubble.width - GAP;+ break;+ case "right":+ top = anchor.top + anchor.height / 2 - bubble.height / 2;+ left = anchor.right + GAP;+ break;+ default:+ top = anchor.top - bubble.height - GAP;+ left = anchor.left + anchor.width / 2 - bubble.width / 2;+ }++ // Flip rather than hang off the top or bottom edge.+ if (top < GAP && placement === "top") top = anchor.bottom + GAP;+ if (+ top + bubble.height > window.innerHeight - GAP &&+ placement === "bottom"+ )+ top = anchor.top - bubble.height - GAP;++ const maxLeft = window.innerWidth - bubble.width - GAP;+ setPos({+ top: Math.max(+ GAP,+ Math.min(top, window.innerHeight - bubble.height - GAP),+ ),+ left: Math.max(GAP, Math.min(left, Math.max(GAP, maxLeft))),+ });+ }, [placement]);++ // Measured before paint, so the bubble never shows at its unplaced position.+ useLayoutEffect(() => {+ if (!open) {+ setPos(null);+ return;+ }+ place();+ }, [open, place, content]);++ useEffect(() => {+ if (!open) return;+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") setOpen(false);+ };+ const reflow = () => place();+ document.addEventListener("keydown", onKeyDown);+ window.addEventListener("resize", reflow);+ // Capture phase: the trigger may sit inside a scrolling container.+ window.addEventListener("scroll", reflow, true);+ return () => {+ document.removeEventListener("keydown", onKeyDown);+ window.removeEventListener("resize", reflow);+ window.removeEventListener("scroll", reflow, true);+ };+ }, [open, place]);++ return (+ // React's onFocus/onBlur bubble, so the trigger's focus opens the bubble.+ <span+ ref={anchorRef}+ className={["sui-tip", className ?? ""].filter(Boolean).join(" ")}+ onMouseEnter={() => setOpen(true)}+ onMouseLeave={() => setOpen(false)}+ onFocus={() => setOpen(true)}+ onBlur={() => setOpen(false)}+ >+ {cloneElement(children as ReactElement<{ "aria-describedby"?: string }>, {+ "aria-describedby": open ? id : undefined,+ })}+ {open+ ? createPortal(+ <div+ ref={bubbleRef}+ role="tooltip"+ id={id}+ className="sui-tip__bubble"+ style={{+ top: pos?.top ?? 0,+ left: pos?.left ?? 0,+ visibility: pos ? "visible" : "hidden",+ }}+ >+ {content}+ </div>,+ document.body,+ )+ : null}+ </span>+ );+}diff --git a/frontend/editor/src/core/ui/index.ts b/frontend/editor/src/core/ui/index.tsindex 386cc00f31..1fa5f997b0 100644--- a/frontend/editor/src/core/ui/index.ts+++ b/frontend/editor/src/core/ui/index.ts@@ -33,6 +33,7 @@ export * from "@app/ui/StatTile";// Feedbackexport * from "@app/ui/Spinner";+export * from "@app/ui/Tooltip";export * from "@app/ui/Skeleton";export * from "@app/ui/Avatar";export * from "@app/ui/Chip";diff --git a/frontend/editor/src/portal/api/storageEncryption.ts b/frontend/editor/src/portal/api/storageEncryption.tsnew file mode 100644index 0000000000..151032a703--- /dev/null+++ b/frontend/editor/src/portal/api/storageEncryption.ts@@ -0,0 +1,163 @@+import { apiClient, HttpError } from "@portal/api/http";++/**+ * Admin API for storage encryption at rest. Mirrors the Spring surface added in+ * PR #7173 (`/api/v1/admin/storage-encryption`), which is admin-only and never+ * accepts or returns key material.+ */++const BASE = "/api/v1/admin/storage-encryption";++/**+ * Runbook sections the panel links to. These point at the devGuide until the+ * encryption-at-rest pages are published on docs.stirlingpdf.com.+ */+const RUNBOOK =+ "https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/STORAGE_ENCRYPTION_AT_REST.md";+const section = (anchor: string) => `${RUNBOOK}#${anchor}`;+export const RUNBOOK_BACKUP = section("backing-up-the-master-key");+export const RUNBOOK_ROTATION = section("rotating-the-master-key");++export type EncryptionKeyStatus = "ACTIVE" | "RETIRED" | "DISABLED";++export type EncryptionScopeType = "GLOBAL" | "TEAM" | "SOURCE";++/** Where the master key came from. Absent on backends that predate the field. */+export type MasterKeySource = "config" | "environment" | "generated";++export interface EncryptionKeyInfo {+ keyId: string;+ scopeType: EncryptionScopeType;+ scopeId: number;+ keyVersion: number;+ masterKeyVersion: number;+ status: EncryptionKeyStatus;+ createdAt: string;+ statusChangedAt: string | null;+ statusChangedBy: string | null;+}++export interface StorageEncryptionStatus {+ /** New uploads are encrypted. False with `active` true means decrypt-only. */+ writeEnabled: boolean;+ /** Key machinery is materialised, so encrypted content can be read. */+ active: boolean;+ /** SHA-256 prefix of the master key, for comparing against a backup. */+ masterKeyFingerprint: string | null;+ masterKeyVersion: number | null;+ /** Null until the key machinery has materialised on this node. */+ masterKeySource: MasterKeySource | null;+ /** Backend serving stored blobs: local, database or s3. */+ provider: string | null;+ encryptedFiles: number;+ plaintextFiles: number;+ /** Counted server-side, so it stays right when the key list is paged. */+ pendingRotationRows: number;+ keys: EncryptionKeyInfo[];+}++export type MigrationState = "IDLE" | "RUNNING" | "COMPLETED" | "FAILED";++export interface MigrationStatus {+ state: MigrationState;+ total: number | null;+ processed: number | null;+ skipped: number | null;+ failed: number | null;+ startedAt: string | null;+ finishedAt: string | null;+}++export interface RotationResult {+ rewrapped: number;+ masterKeyVersion: number;+}++/**+ * Why the panel cannot show a status. The backend distinguishes these+ * deliberately: storage off is a configuration statement, an unreadable+ * registry is an operational fault, and they need different copy.+ */+export type EncryptionUnavailableReason =+ | "storage-disabled"+ | "registry-unavailable"+ | "forbidden"+ | "unknown";++export function unavailableReason(error: unknown): EncryptionUnavailableReason {+ if (!(error instanceof HttpError)) return "unknown";+ // 403 covers both a disabled store and a caller without the admin role, and the+ // only signal is the detail prose. Match on the two words rather than the exact+ // sentence, and fall back to a reason whose copy asserts no cause: guessing+ // "your account lacks permission" at a config problem sends the operator to the+ // wrong place entirely.+ if (error.status === 403) {+ const detail = JSON.stringify(error.body ?? "").toLowerCase();+ return detail.includes("storage") && detail.includes("disabled")+ ? "storage-disabled"+ : "forbidden";+ }+ if (error.status === 503) return "registry-unavailable";+ return "unknown";+}++/** True when the backend rejected the action because of current state, not a fault. */+export function isConflict(error: unknown): boolean {+ return error instanceof HttpError && error.status === 409;+}++/** The key row is gone, so retrying the same call cannot succeed. */+export function isMissing(error: unknown): boolean {+ return error instanceof HttpError && error.status === 404;+}++export async function fetchEncryptionStatus(): Promise<StorageEncryptionStatus> {+ return apiClient.local.json<StorageEncryptionStatus>(`${BASE}/status`);+}++export async function disableEncryptionKey(+ keyId: string,+): Promise<EncryptionKeyInfo> {+ return apiClient.local.json<EncryptionKeyInfo>(+ `${BASE}/keys/${encodeURIComponent(keyId)}/disable`,+ { method: "POST" },+ );+}++/**+ * Reverses a revocation. Resolves to ACTIVE when the scope has no other active+ * key and RETIRED when it does, so callers must read the returned status rather+ * than assuming ACTIVE.+ */+export async function enableEncryptionKey(+ keyId: string,+): Promise<EncryptionKeyInfo> {+ return apiClient.local.json<EncryptionKeyInfo>(+ `${BASE}/keys/${encodeURIComponent(keyId)}/enable`,+ { method: "POST" },+ );+}++export async function startEncryptionMigration(): Promise<MigrationStatus> {+ return apiClient.local.json<MigrationStatus>(`${BASE}/migrate`, {+ method: "POST",+ });+}++export async function fetchMigrationStatus(): Promise<MigrationStatus> {+ return apiClient.local.json<MigrationStatus>(`${BASE}/migrate/status`);+}++export async function rotateMasterKey(): Promise<RotationResult> {+ return apiClient.local.json<RotationResult>(`${BASE}/master/rotate`, {+ method: "POST",+ });+}++/** Key rows still wrapped by an older master key version. */+export function pendingRotationCount(status: StorageEncryptionStatus): number {+ // Server-side count, not a filter over `keys`: that list is a page, and under-+ // reporting 0 pending rows is the signal an operator uses to decide the outgoing+ // master key is safe to delete.+ return status.pendingRotationRows;+}diff --git a/frontend/editor/src/portal/components/InfoHint.css b/frontend/editor/src/portal/components/InfoHint.cssnew file mode 100644index 0000000000..6aa3ba2f94--- /dev/null+++ b/frontend/editor/src/portal/components/InfoHint.css@@ -0,0 +1,21 @@+/* ActionIcon is sized to match a control's height, which is far taller than the+ label or heading this sits beside — enough to push a stat's value off the row+ its siblings sit on. Shrink it to the text it annotates. */+.portal-hint .mantine-ActionIcon-root {+ /* ActionIcon sets --ai-size inline to beat Mantine, so a custom property here+ loses. Set the box directly instead, and clear the mins it ships with. */+ width: 1.1rem;+ height: 1.1rem;+ min-width: 0;+ min-height: 0;+ color: var(--c-text-subtle);+}++.portal-hint .mantine-ActionIcon-root:hover {+ color: var(--c-text);+}++/* Keep the trigger on the text baseline rather than the line box's centre. */+.portal-hint {+ vertical-align: middle;+}diff --git a/frontend/editor/src/portal/components/InfoHint.tsx b/frontend/editor/src/portal/components/InfoHint.tsxnew file mode 100644index 0000000000..544f828432--- /dev/null+++ b/frontend/editor/src/portal/components/InfoHint.tsx@@ -0,0 +1,29 @@+import { ActionIcon, Tooltip, type TooltipPlacement } from "@app/ui";+import LocalIcon from "@app/components/shared/LocalIcon";+import "@portal/components/InfoHint.css";++export interface InfoHintProps {+ /** The explanation. Shown on hover, keyboard focus and tap. */+ content: string;+ /** Accessible name for the trigger, e.g. "What does skipped mean?". */+ label: string;+ placement?: TooltipPlacement;+}++/**+ * The small circled "i" that carries a line of explanation next to a heading or+ * a label, so the copy is there when someone wants it and out of the way when+ * they do not.+ *+ * Sized to the text rather than to a control, because the usual home for one of+ * these is inside a label whose line box it must not inflate.+ */+export function InfoHint({ content, label, placement = "top" }: InfoHintProps) {+ return (+ <Tooltip content={content} placement={placement} className="portal-hint">+ <ActionIcon variant="quiet" size="sm" aria-label={label}>+ <LocalIcon icon="info-rounded" width="0.9rem" />+ </ActionIcon>+ </Tooltip>+ );+}diff --git a/frontend/editor/src/portal/components/infrastructure/EncryptionKeyTable.tsx b/frontend/editor/src/portal/components/infrastructure/EncryptionKeyTable.tsxnew file mode 100644index 0000000000..79d4136769--- /dev/null+++ b/frontend/editor/src/portal/components/infrastructure/EncryptionKeyTable.tsx@@ -0,0 +1,211 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import {+ Banner,+ Button,+ Card,+ column,+ DataTable,+ EmptyState,+ Modal,+ type DataTableColumn,+ type StatusTone,+} from "@app/ui";+import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";+import type {+ EncryptionKeyInfo,+ EncryptionKeyStatus,+} from "@portal/api/storageEncryption";++const STATUS_TONE: Record<EncryptionKeyStatus, StatusTone> = {+ ACTIVE: "success",+ RETIRED: "neutral",+ DISABLED: "danger",+};++export interface EncryptionKeyTableProps {+ /** Why the last revoke or restore failed. Shown here, beside the rows it concerns. */+ actionError?: string | null;+ keys: EncryptionKeyInfo[];+ /** Shows the cross-node propagation delay in the revoke dialog. */+ clusterEnabled?: boolean;+ /** Key id currently being changed, so its row can show pending state. */+ busyKeyId?: string | null;+ onRevoke: (key: EncryptionKeyInfo) => void;+ onRestore: (key: EncryptionKeyInfo) => void;+}++/**+ * One row per scope key, with the kill switch. Revoking opens a confirmation+ * that spells out the consequences: the surprising ones (the scope keeps+ * uploading, and a cluster takes a minute to converge) are the reason the+ * dialog exists at all.+ */+export function EncryptionKeyTable({+ actionError = null,+ keys,+ clusterEnabled = false,+ busyKeyId = null,+ onRevoke,+ onRestore,+}: EncryptionKeyTableProps) {+ const { t } = useTranslation();+ const [pendingRevoke, setPendingRevoke] = useState<EncryptionKeyInfo | null>(+ null,+ );++ const scopeLabel = (key: EncryptionKeyInfo): string => {+ if (key.scopeType === "GLOBAL")+ return t("portal.infrastructure.encryption.scope.global");+ if (key.scopeType === "SOURCE")+ return t("portal.infrastructure.encryption.scope.source", {+ id: key.scopeId,+ });+ return t("portal.infrastructure.encryption.scope.team", {+ id: key.scopeId,+ });+ };++ const lastChange = (key: EncryptionKeyInfo): string => {+ const when = key.statusChangedAt+ ? new Date(key.statusChangedAt).toLocaleString()+ : null;+ if (key.statusChangedBy && when)+ return t("portal.infrastructure.encryption.keys.changedByAt", {+ actor: key.statusChangedBy,+ when,+ });+ if (key.statusChangedBy)+ return t("portal.infrastructure.encryption.keys.changedBy", {+ actor: key.statusChangedBy,+ });+ if (when)+ return t("portal.infrastructure.encryption.keys.changedAt", { when });+ return t("portal.infrastructure.encryption.keys.neverChanged");+ };++ const columns: DataTableColumn<EncryptionKeyInfo>[] = [+ column.entity({+ key: "scope",+ header: t("portal.infrastructure.encryption.keys.columns.scope"),+ sortable: true,+ primary: (row) => scopeLabel(row),+ note: (row) =>+ t("portal.infrastructure.encryption.keys.keyVersion", {+ version: row.keyVersion,+ }),+ }),+ column.badge({+ key: "status",+ header: t("portal.infrastructure.encryption.keys.columns.status"),+ sortable: true,+ get: (row) => ({+ tone: STATUS_TONE[row.status],+ label: t(`portal.infrastructure.encryption.status.${row.status}`),+ }),+ }),+ column.muted({+ key: "lastChange",+ header: t("portal.infrastructure.encryption.keys.columns.lastChange"),+ get: (row) => lastChange(row),+ }),+ column.actions({+ key: "actions",+ header: t("portal.infrastructure.encryption.keys.columns.actions"),+ get: (row) => [+ row.status === "DISABLED"+ ? {+ label: t("portal.infrastructure.encryption.keys.restore"),+ disabled: busyKeyId === row.keyId,+ onClick: () => onRestore(row),+ }+ : {+ label: t("portal.infrastructure.encryption.keys.revoke"),+ tone: "danger",+ disabled: busyKeyId === row.keyId,+ onClick: () => setPendingRevoke(row),+ },+ ],+ }),+ ];++ return (+ <section>+ <Card padding="loose">+ <SectionHeader+ title={t("portal.infrastructure.encryption.keys.heading")}+ hint={t("portal.infrastructure.encryption.keys.subheading")}+ hintLabel={t("portal.infrastructure.encryption.hintLabel")}+ />+ {actionError ? (+ <Banner tone="warning" description={actionError} />+ ) : null}++ {/* Column headers over an empty body are chrome around nothing. */}+ {keys.length === 0 ? (+ <EmptyState+ size="compact"+ title={t("portal.infrastructure.encryption.keys.empty.title")}+ description={t(+ "portal.infrastructure.encryption.keys.empty.description",+ )}+ />+ ) : (+ <>+ <DataTable+ columns={columns}+ rows={keys}+ rowKey={(row) => row.keyId}+ />+ {keys.some((key) => key.status === "RETIRED") ? (+ <p className="portal-enc__note">+ {t("portal.infrastructure.encryption.keys.retiredNote")}+ </p>+ ) : null}+ </>+ )}++ <Modal+ open={pendingRevoke !== null}+ onClose={() => setPendingRevoke(null)}+ width="md"+ title={t("portal.infrastructure.encryption.revoke.title")}+ subtitle={pendingRevoke ? scopeLabel(pendingRevoke) : undefined}+ footer={+ <>+ <Button+ variant="secondary"+ onClick={() => setPendingRevoke(null)}+ >+ {t("portal.infrastructure.encryption.revoke.cancel")}+ </Button>+ <Button+ variant="primary"+ accent="danger"+ onClick={() => {+ if (pendingRevoke) onRevoke(pendingRevoke);+ setPendingRevoke(null);+ }}+ >+ {t("portal.infrastructure.encryption.revoke.confirm")}+ </Button>+ </>+ }+ >+ <ul className="portal-enc__consequences">+ <li>{t("portal.infrastructure.encryption.revoke.readsFail")}</li>+ <li>+ {t("portal.infrastructure.encryption.revoke.uploadsContinue")}+ </li>+ <li>{t("portal.infrastructure.encryption.revoke.reversible")}</li>+ {clusterEnabled ? (+ <li>+ {t("portal.infrastructure.encryption.revoke.clusterDelay")}+ </li>+ ) : null}+ </ul>+ </Modal>+ </Card>+ </section>+ );+}diff --git a/frontend/editor/src/portal/components/infrastructure/EncryptionMigrationCard.tsx b/frontend/editor/src/portal/components/infrastructure/EncryptionMigrationCard.tsxnew file mode 100644index 0000000000..25e3902a5d--- /dev/null+++ b/frontend/editor/src/portal/components/infrastructure/EncryptionMigrationCard.tsx@@ -0,0 +1,231 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import {+ Banner,+ Button,+ Card,+ ProgressBar,+ StatTile,+ Modal,+ StatusBadge,+} from "@app/ui";+import { InfoHint } from "@portal/components/InfoHint";+import type { StatusTone } from "@app/ui";+import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";+import type {+ MigrationState,+ MigrationStatus,+} from "@portal/api/storageEncryption";++const STATE_TONE: Record<MigrationState, StatusTone> = {+ IDLE: "neutral",+ RUNNING: "info",+ COMPLETED: "success",+ FAILED: "danger",+};++export interface EncryptionMigrationCardProps {+ /** Null before the first status read. */+ status: MigrationStatus | null;+ plaintextFiles: number;+ /** Encryption must be writing before a run can start. */+ writeEnabled: boolean;+ starting?: boolean;+ /** Set when the last start attempt was rejected (409) or failed. */+ actionError?: string | null;+ onStart: () => void;+}++/**+ * The encrypt-existing job. FAILED is a first-class state rather than a stalled+ * spinner, because the run now ends FAILED when the write flag is turned off+ * mid-run, and the operator needs to be told why nothing else was processed.+ */+export function EncryptionMigrationCard({+ status,+ plaintextFiles,+ writeEnabled,+ starting = false,+ actionError = null,+ onStart,+}: EncryptionMigrationCardProps) {+ const { t } = useTranslation();+ const state: MigrationState = status?.state ?? "IDLE";+ const total = status?.total ?? 0;+ const processed = status?.processed ?? 0;+ const skipped = status?.skipped ?? 0;+ const failed = status?.failed ?? 0;+ const fraction = total > 0 ? Math.min(processed / total, 1) : 0;+ const canStart = writeEnabled && plaintextFiles > 0 && state !== "RUNNING";+ const [confirming, setConfirming] = useState(false);++ return (+ <section>+ <Card padding="loose">+ <div className="portal-enc__head">+ <SectionHeader+ title={t("portal.infrastructure.encryption.migration.heading")}+ hint={t("portal.infrastructure.encryption.migration.hint")}+ hintLabel={t("portal.infrastructure.encryption.hintLabel")}+ />+ <StatusBadge tone={STATE_TONE[state]} size="sm">+ {t(`portal.infrastructure.encryption.migration.state.${state}`)}+ </StatusBadge>+ </div>+ {status?.startedAt ? (+ <p className="portal-enc__note">+ {t("portal.infrastructure.encryption.migration.startedAt", {+ when: new Date(status.startedAt).toLocaleString(),+ })}+ </p>+ ) : null}++ {state === "FAILED" ? (+ <Banner+ tone="danger"+ title={t("portal.infrastructure.encryption.migration.failed.title")}+ description={t(+ "portal.infrastructure.encryption.migration.failed.description",+ )}+ />+ ) : null}++ {actionError ? (+ <Banner tone="warning" description={actionError} />+ ) : null}++ {state === "RUNNING" || state === "COMPLETED" || state === "FAILED" ? (+ <>+ <ProgressBar+ value={fraction}+ height={10}+ // A stopped run should not read as healthy progress.+ color={+ state === "FAILED"+ ? "var(--c-text-subtle)"+ : state === "COMPLETED"+ ? "var(--color-green)"+ : undefined+ }+ label={t(+ "portal.infrastructure.encryption.migration.progressLabel",+ { processed, total },+ )}+ />+ <div className="portal-enc__migration-stats">+ <StatTile+ label={t(+ "portal.infrastructure.encryption.migration.encrypted",+ )}+ value={processed.toLocaleString()}+ />+ <StatTile+ label={+ <>+ {t("portal.infrastructure.encryption.migration.skipped")}+ <InfoHint+ content={t(+ "portal.infrastructure.encryption.migration.skippedNote",+ )}+ label={t(+ "portal.infrastructure.encryption.migration.skippedHelp",+ )}+ />+ </>+ }+ value={skipped.toLocaleString()}+ />+ <StatTile+ label={t(+ "portal.infrastructure.encryption.migration.failedCount",+ )}+ value={failed.toLocaleString()}+ tone={failed > 0 ? "danger" : "default"}+ />+ </div>+ </>+ ) : (+ <p className="portal-enc__note">+ {plaintextFiles > 0+ ? t("portal.infrastructure.encryption.migration.backlog", {+ count: plaintextFiles,+ // count drives plural selection; formatted is what is rendered,+ // so large backlogs read as 1,840 rather than 1840.+ formatted: plaintextFiles.toLocaleString(),+ })+ : t("portal.infrastructure.encryption.migration.noBacklog")}+ </p>+ )}++ {/* Start is disabled without the write flag; say why rather than leaving a+ dead button next to a backlog the copy says can be encrypted. */}+ {!writeEnabled && plaintextFiles > 0 ? (+ <p className="portal-enc__note">+ {t(+ "portal.infrastructure.encryption.migration.requiresEncryptionOn",+ )}+ </p>+ ) : null}++ <div className="portal-enc__actions">+ <Button+ variant="primary"+ size="sm"+ disabled={!canStart || starting}+ onClick={() => setConfirming(true)}+ >+ {state === "FAILED" || state === "COMPLETED"+ ? t("portal.infrastructure.encryption.migration.runAgain")+ : t("portal.infrastructure.encryption.migration.start")}+ </Button>+ </div>++ <Modal+ open={confirming}+ onClose={() => setConfirming(false)}+ width="md"+ title={t("portal.infrastructure.encryption.migration.confirm.title")}+ footer={+ <>+ <Button variant="secondary" onClick={() => setConfirming(false)}>+ {t("portal.infrastructure.encryption.migration.confirm.cancel")}+ </Button>+ <Button+ variant="primary"+ onClick={() => {+ setConfirming(false);+ onStart();+ }}+ >+ {t(+ "portal.infrastructure.encryption.migration.confirm.confirm",+ )}+ </Button>+ </>+ }+ >+ <ul className="portal-enc__consequences">+ <li>+ {t(+ "portal.infrastructure.encryption.migration.confirm.rewrites",+ {+ count: plaintextFiles,+ formatted: plaintextFiles.toLocaleString(),+ },+ )}+ </li>+ {/* The reason this dialog exists: there is no stop control. */}+ <li>+ {t("portal.infrastructure.encryption.migration.confirm.noCancel")}+ </li>+ <li>+ {t(+ "portal.infrastructure.encryption.migration.confirm.throttled",+ )}+ </li>+ </ul>+ </Modal>+ </Card>+ </section>+ );+}diff --git a/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.css b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.cssnew file mode 100644index 0000000000..292575f2f7--- /dev/null+++ b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.css@@ -0,0 +1,177 @@+/*+ * Encryption-at-rest panel. Own `portal-enc__` namespace rather than extending+ * `portal-infra__`, so this section can move out of the Storage tab later+ * without dragging shared selectors with it.+ */++.portal-enc__stack {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++/* Own copies of the three text treatments this panel needs. Borrowing the+ portal-infra__ equivalents coupled the panel to a file that is being trimmed+ as Infrastructure tabs come and go; one of them has already gone. */+.portal-enc__cell-strong {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--c-text);+}++.portal-enc__mono {+ font-family: var(--font-mono);+ font-size: 0.75rem;+ color: var(--c-text-muted);+}++.portal-enc__muted {+ font-size: 0.75rem;+ color: var(--c-text-subtle);+}++.portal-enc__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+ flex-wrap: wrap;+}++.portal-enc__coverage {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1.5rem;+ flex-wrap: wrap;+ margin-bottom: 0.75rem;+}++.portal-enc__coverage-tiles {+ display: flex;+ align-items: baseline;+ gap: 2rem;+}++.portal-enc__coverage-bar {+ margin-top: 0.5rem;+}++/* Master key + rotation sit side by side, stacking on narrow viewports.+ Stretch keeps the pair the same height instead of leaving the shorter card+ floating against a taller neighbour. */+.portal-enc__split {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 1rem;+ align-items: stretch;+}++.portal-enc__split > * {+ height: 100%;+}++@media (max-width: 60rem) {+ .portal-enc__split {+ grid-template-columns: 1fr;+ }+}++.portal-enc__kv {+ display: flex;+ flex-direction: column;+ gap: 0.6rem;+}++.portal-enc__kv-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+}++.portal-enc__kv-label {+ font-size: 0.75rem;+ color: var(--c-text-subtle);+}++/* Label, value and copy sit together: across a wide card, a space-between row+ separates the fingerprint from the word "Fingerprint" by half a screen. */+.portal-enc__fingerprint {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ flex-wrap: wrap;+}++/* Banners inside a card need breathing room from whatever follows them. */+.portal-enc__stack .sui-banner,+.portal-enc__split .sui-banner {+ margin: 0.75rem 0 0;+}++/* ...but a banner that is itself a row of the stack is spaced by the stack's+ gap. Leaving the margin on stacks the two, so consecutive banners sat 1.75rem+ apart while every other row sat at 1rem. */+.portal-enc__stack > .sui-banner {+ margin: 0;+}++.portal-enc__fingerprint code {+ font-family: var(--font-mono);+ font-size: 0.8125rem;+ color: var(--c-text);+ letter-spacing: 0.02em;+}++.portal-enc__scope {+ display: flex;+ flex-direction: column;+ gap: 0.1rem;+}++.portal-enc__actions {+ display: flex;+ justify-content: flex-end;+ gap: 0.4rem;+}++.portal-enc__note {+ font-size: 0.75rem;+ color: var(--c-text-subtle);+ margin: 0.5rem 0 0;+}++/* Revoke dialog: the consequences list is the point of the dialog, so it gets+ more room than a typical confirm body. */+.portal-enc__consequences {+ margin: 0.25rem 0 0;+ padding-left: 1.1rem;+ display: flex;+ flex-direction: column;+ gap: 0.4rem;+ font-size: 0.8125rem;+ color: var(--c-text-muted);+}++.portal-enc__consequences strong {+ color: var(--c-text);+ font-weight: 600;+}++.portal-enc__migration-stats {+ display: flex;+ align-items: start;+ gap: 1.5rem;+ flex-wrap: wrap;+ margin-top: 0.75rem;+}++/* One label carries a hint icon and the others do not. A fixed height rather+ than a minimum, so the icon cannot push its value off the row. */+.portal-enc__migration-stats .sui-stat__label {+ display: flex;+ align-items: center;+ gap: 0.25rem;+ height: 1.25rem;+}diff --git a/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.stories.tsx b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.stories.tsxnew file mode 100644index 0000000000..752e06dacb--- /dev/null+++ b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.stories.tsx@@ -0,0 +1,429 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse } from "msw";+import { expect, userEvent, within } from "storybook/test";+import { EncryptionPanel } from "@portal/components/infrastructure/EncryptionPanel";+import type {+ EncryptionKeyInfo,+ MigrationStatus,+ StorageEncryptionStatus,+} from "@portal/api/storageEncryption";+// SectionHeader's styles live in Infrastructure.css, and the real view loads it,+// so the stories load it too or they render larger than the app does.+import "@portal/views/Infrastructure.css";++const BASE = "/api/v1/admin/storage-encryption";++const key = (+ over: Partial<EncryptionKeyInfo> & { keyId: string },+): EncryptionKeyInfo => ({+ scopeType: "TEAM",+ scopeId: 1,+ keyVersion: 1,+ masterKeyVersion: 2,+ status: "ACTIVE",+ createdAt: "2026-06-02T09:14:00",+ statusChangedAt: null,+ statusChangedBy: null,+ ...over,+});++const ACTIVE_STATUS: StorageEncryptionStatus = {+ writeEnabled: true,+ active: true,+ masterKeyFingerprint: "9f2c41a7be03d5e8",+ masterKeyVersion: 2,+ masterKeySource: "config",+ provider: "local",+ encryptedFiles: 4128,+ plaintextFiles: 0,+ pendingRotationRows: 0,+ keys: [+ key({ keyId: "1f0b6a11-0000-4000-8000-000000000001", scopeId: 1 }),+ key({ keyId: "1f0b6a11-0000-4000-8000-000000000002", scopeId: 4 }),+ key({+ keyId: "1f0b6a11-0000-4000-8000-000000000003",+ scopeType: "GLOBAL",+ scopeId: 0,+ }),+ ],+};++const IDLE_MIGRATION: MigrationStatus = {+ state: "IDLE",+ total: null,+ processed: null,+ skipped: null,+ failed: null,+ startedAt: null,+ finishedAt: null,+};++/** Handlers for a healthy, fully encrypted install. */+const handlers = (+ status: StorageEncryptionStatus,+ migration: MigrationStatus = IDLE_MIGRATION,+) => [+ http.get(`${BASE}/status`, () => HttpResponse.json(status)),+ http.get(`${BASE}/migrate/status`, () => HttpResponse.json(migration)),+ http.post(`${BASE}/keys/:keyId/disable`, ({ params }) =>+ HttpResponse.json(key({ keyId: String(params.keyId), status: "DISABLED" })),+ ),+ http.post(`${BASE}/keys/:keyId/enable`, ({ params }) =>+ HttpResponse.json(key({ keyId: String(params.keyId), status: "RETIRED" })),+ ),+];++const meta: Meta<typeof EncryptionPanel> = {+ title: "Portal/Infrastructure/EncryptionPanel",+ component: EncryptionPanel,+ parameters: {+ layout: "padded",+ msw: { handlers: handlers(ACTIVE_STATUS) },+ },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "72rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof EncryptionPanel>;++/** 01. Feature has never been switched on: nothing encrypted, no keys. */+export const EncryptionOff: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: handlers({+ writeEnabled: false,+ active: false,+ masterKeyFingerprint: null,+ masterKeyVersion: null,+ masterKeySource: null,+ provider: "local",+ encryptedFiles: 0,+ plaintextFiles: 1840,+ pendingRotationRows: 0,+ keys: [],+ }),+ },+ },+};++/** 02. The healthy state: encrypting, fully covered, keys listed. */+export const Active: Story = {+ globals: { tier: "enterprise" },+};++/** 03. Non-Enterprise licence: encryption runs, audit does not. */+export const ProLicenceAuditNotice: Story = {+ globals: { tier: "enterprise" },+ args: { auditAvailable: false },+};++/** 04. The revoke dialog, which is where the surprising behaviour is explained. */+export const RevokeConfirmation: Story = {+ globals: { tier: "enterprise" },+ args: { clusterEnabled: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const buttons = await canvas.findAllByRole("button", { name: /revoke/i });+ await userEvent.click(buttons[0]);+ // Presence, not visibility: the a11y scan harness does not compute layout,+ // so toBeVisible() fails there on an element the browser renders fine.+ await expect(+ await within(document.body).findByText(/stop opening/i),+ ).toBeInTheDocument();+ },+};++/** 05. A revoked key, showing who did it. */+export const KeyRevoked: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: handlers({+ ...ACTIVE_STATUS,+ keys: [+ key({+ keyId: "1f0b6a11-0000-4000-8000-000000000001",+ scopeId: 1,+ status: "DISABLED",+ statusChangedAt: "2026-08-11T14:02:00",+ statusChangedBy: "[email protected]",+ }),+ key({ keyId: "1f0b6a11-0000-4000-8000-000000000002", scopeId: 4 }),+ ],+ }),+ },+ },+};++/**+ * 06. Restored while the scope had minted a replacement, so the key comes back+ * RETIRED rather than ACTIVE. The case a reviewer is most likely to assume+ * works the other way.+ */+export const KeyRestoredAsRetired: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: handlers({+ ...ACTIVE_STATUS,+ keys: [+ key({+ keyId: "1f0b6a11-0000-4000-8000-000000000001",+ scopeId: 1,+ keyVersion: 1,+ status: "RETIRED",+ statusChangedAt: "2026-08-11T14:09:00",+ statusChangedBy: "[email protected]",+ }),+ key({+ keyId: "1f0b6a11-0000-4000-8000-000000000009",+ scopeId: 1,+ keyVersion: 2,+ status: "ACTIVE",+ }),+ ],+ }),+ },+ },+};++/**+ * The migration confirmation. This one exists because the run cannot be+ * stopped: there is no cancel endpoint, so the dialog is the last exit.+ */+export const MigrationConfirmation: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: handlers({+ ...ACTIVE_STATUS,+ encryptedFiles: 2288,+ plaintextFiles: 1840,+ }),+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(+ await canvas.findByRole("button", { name: /^start$/i }),+ );+ await expect(+ await within(document.body).findByText(/no stop control/i),+ ).toBeInTheDocument();+ },+};++/** The re-wrap confirmation, over a table with rows still on the old key. */+export const RotationConfirmation: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: handlers({+ ...ACTIVE_STATUS,+ masterKeyVersion: 3,+ pendingRotationRows: 2,+ }),+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(+ await canvas.findByRole("button", { name: /re-wrap keys/i }),+ );+ await expect(+ await within(document.body).findByText(/File contents are not touched/i),+ ).toBeInTheDocument();+ },+};++/** 07. Migration in flight over a real backlog. */+export const MigrationRunning: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: handlers(+ { ...ACTIVE_STATUS, encryptedFiles: 3120, plaintextFiles: 1008 },+ {+ state: "RUNNING",+ total: 4128,+ processed: 3120,+ skipped: 4,+ failed: 0,+ startedAt: "2026-08-11T13:40:00Z",+ finishedAt: null,+ },+ ),+ },+ },+};++/** 08. The run stopped because encryption was switched off mid-flight. */+export const MigrationFailed: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: handlers(+ { ...ACTIVE_STATUS, encryptedFiles: 812, plaintextFiles: 3316 },+ {+ state: "FAILED",+ total: 4128,+ processed: 812,+ skipped: 2,+ failed: 0,+ startedAt: "2026-08-11T13:40:00Z",+ finishedAt: "2026-08-11T13:44:00Z",+ },+ ),+ },+ },+};++/**+ * A revoke that fails. Asserts the message lands inside the key card rather+ * than merely existing somewhere on the panel, which is the part that makes+ * this a regression test rather than a smoke test.+ */+export const KeyActionFailed: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ // First match wins in MSW, so the failing handler has to precede the+ // healthy set rather than follow it.+ handlers: [+ http.post(`${BASE}/keys/:keyId/disable`, () =>+ HttpResponse.json({ detail: "boom" }, { status: 500 }),+ ),+ ...handlers(ACTIVE_STATUS),+ ],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const rowButtons = await canvas.findAllByRole("button", {+ name: /^revoke$/i,+ });+ await userEvent.click(rowButtons[0]);+ await userEvent.click(+ await within(document.body).findByRole("button", {+ name: /revoke access/i,+ }),+ );++ const message = await canvas.findByText(/could not be applied/i);+ const keysCard = canvas.getByText(/scope keys/i).closest(".sui-card");+ await expect(keysCard).not.toBeNull();+ await expect(keysCard?.contains(message)).toBe(true);+ },+};++/**+ * Decrypt-only on S3. The backend suppresses presigned URLs once any key row+ * exists, not only while writes are encrypted, so the bandwidth note belongs+ * in this state too.+ */+export const DecryptOnlyOnS3: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: handlers({+ ...ACTIVE_STATUS,+ writeEnabled: false,+ active: true,+ provider: "s3",+ encryptedFiles: 4128,+ plaintextFiles: 12,+ }),+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ await canvas.findByText(/streamed through this server/i),+ ).toBeInTheDocument();+ },+};++/** 09. Mid-rotation: rows still on the old key, so the old key must be kept. */+export const RotationPending: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: handlers({+ ...ACTIVE_STATUS,+ masterKeyVersion: 3,+ pendingRotationRows: 2,+ keys: [+ key({+ keyId: "1f0b6a11-0000-4000-8000-000000000001",+ scopeId: 1,+ masterKeyVersion: 2,+ }),+ key({+ keyId: "1f0b6a11-0000-4000-8000-000000000002",+ scopeId: 4,+ masterKeyVersion: 2,+ }),+ key({+ keyId: "1f0b6a11-0000-4000-8000-000000000003",+ scopeType: "GLOBAL",+ scopeId: 0,+ masterKeyVersion: 3,+ }),+ ],+ }),+ },+ },+};++/** 11. Storage switched off: the API refuses before touching the database. */+export const StorageDisabled: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: [+ http.get(`${BASE}/status`, () =>+ HttpResponse.json({ detail: "Storage is disabled" }, { status: 403 }),+ ),+ http.get(`${BASE}/migrate/status`, () =>+ HttpResponse.json(IDLE_MIGRATION),+ ),+ ],+ },+ },+};++/** The key registry could not be read at all. */+export const RegistryUnavailable: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: [+ http.get(`${BASE}/status`, () =>+ HttpResponse.json(+ { detail: "The storage encryption key registry could not be read" },+ { status: 503 },+ ),+ ),+ http.get(`${BASE}/migrate/status`, () =>+ HttpResponse.json(IDLE_MIGRATION),+ ),+ ],+ },+ },+};++/** The master key was auto-generated, so it may never have been backed up. */+export const GeneratedMasterKey: Story = {+ globals: { tier: "enterprise" },+ parameters: {+ msw: {+ handlers: handlers({ ...ACTIVE_STATUS, masterKeySource: "generated" }),+ },+ },+};diff --git a/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.tsx b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.tsxnew file mode 100644index 0000000000..b0a33d1ab3--- /dev/null+++ b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.tsx@@ -0,0 +1,496 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ Banner,+ Button,+ Card,+ EmptyState,+ ProgressBar,+ Skeleton,+ StatTile,+ StatusBadge,+} from "@app/ui";+import { errorMessage } from "@portal/api/http";+import {+ disableEncryptionKey,+ enableEncryptionKey,+ fetchEncryptionStatus,+ fetchMigrationStatus,+ isConflict,+ isMissing,+ pendingRotationCount,+ rotateMasterKey,+ RUNBOOK_BACKUP,+ startEncryptionMigration,+ unavailableReason,+ type EncryptionKeyInfo,+ type MigrationStatus,+ type StorageEncryptionStatus,+} from "@portal/api/storageEncryption";+import { InfoHint } from "@portal/components/InfoHint";+import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";+import { EncryptionKeyTable } from "@portal/components/infrastructure/EncryptionKeyTable";+import { EncryptionMigrationCard } from "@portal/components/infrastructure/EncryptionMigrationCard";+import { EncryptionRotationCard } from "@portal/components/infrastructure/EncryptionRotationCard";+import "@portal/components/infrastructure/EncryptionPanel.css";++/** How often to re-read migration progress while a run is going. */+const MIGRATION_POLL_MS = 2000;++export interface EncryptionPanelProps {+ /** Shows the cross-node propagation note when revoking. */+ clusterEnabled?: boolean;+ /**+ * Whether the licence records audit events (Enterprise). Supplied by the view+ * from the backend's `runningEE` flag rather than read here, because the+ * portal tier is derived from the SaaS account link and never reports+ * Enterprise on a self-hosted install.+ */+ auditAvailable?: boolean;+}++/**+ * Encryption at rest, as an operator sees it: whether it is on, whether the key+ * backup matches, which scopes have keys, and the two long-running actions+ * (encrypt the backlog, re-wrap after a master-key change).+ *+ * Audit events need an Enterprise licence even though encryption itself is Pro,+ * so a Pro operator is told explicitly rather than assuming a trail exists.+ */+export function EncryptionPanel({+ clusterEnabled = false,+ auditAvailable = true,+}: EncryptionPanelProps) {+ const { t } = useTranslation();++ const [status, setStatus] = useState<StorageEncryptionStatus | null>(null);+ const [loadError, setLoadError] = useState<unknown>(null);+ const [loading, setLoading] = useState(true);+ const [migration, setMigration] = useState<MigrationStatus | null>(null);+ const [busyKeyId, setBusyKeyId] = useState<string | null>(null);+ const [starting, setStarting] = useState(false);+ const [rotating, setRotating] = useState(false);+ const [lastRewrapped, setLastRewrapped] = useState<number | null>(null);+ // One per action area: a single shared string renders wherever it is passed,+ // so a failed revoke surfaced under "Encrypt existing files".+ const [keyActionError, setKeyActionError] = useState<string | null>(null);+ const [rotateError, setRotateError] = useState<string | null>(null);+ const [migrationError, setMigrationError] = useState<string | null>(null);+ const [copyError, setCopyError] = useState<string | null>(null);+ const [copied, setCopied] = useState(false);+ const mounted = useRef(true);+ const fingerprintRef = useRef<HTMLElement | null>(null);++ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);++ const load = useCallback(async () => {+ try {+ const [next, run] = await Promise.all([+ fetchEncryptionStatus(),+ fetchMigrationStatus().catch(() => null),+ ]);+ if (!mounted.current) return;+ setStatus(next);+ setMigration(run);+ setLoadError(null);+ } catch (error) {+ if (!mounted.current) return;+ setLoadError(error);+ } finally {+ if (mounted.current) setLoading(false);+ }+ }, []);++ useEffect(() => {+ void load();+ }, [load]);++ // Progress lives in the backend's memory, so poll only while a run is active.+ useEffect(() => {+ if (migration?.state !== "RUNNING") return;+ const timer = window.setInterval(() => {+ void fetchMigrationStatus()+ .then((next) => {+ if (!mounted.current) return;+ setMigration(next);+ // The run has just changed the encrypted/plaintext split, so re-read+ // status: without this the coverage card keeps its pre-run counts.+ if (next.state !== "RUNNING") void load();+ })+ .catch(() => {+ /* transient: the next tick retries */+ });+ }, MIGRATION_POLL_MS);+ return () => window.clearInterval(timer);+ }, [migration?.state, load]);++ const runKeyAction = async (+ key: EncryptionKeyInfo,+ action: (keyId: string) => Promise<EncryptionKeyInfo>,+ ) => {+ setBusyKeyId(key.keyId);+ setKeyActionError(null);+ try {+ await action(key.keyId);+ await load();+ } catch (error) {+ setKeyActionError(+ isConflict(error)+ ? errorMessage(error)+ : isMissing(error)+ ? t("portal.infrastructure.encryption.error.keyMissing")+ : t("portal.infrastructure.encryption.error.action"),+ );+ await load();+ } finally {+ if (mounted.current) setBusyKeyId(null);+ }+ };++ const onStartMigration = async () => {+ setStarting(true);+ setMigrationError(null);+ try {+ setMigration(await startEncryptionMigration());+ } catch (error) {+ setMigrationError(+ isConflict(error)+ ? errorMessage(error)+ : t("portal.infrastructure.encryption.error.migrationStart"),+ );+ } finally {+ if (mounted.current) setStarting(false);+ }+ };++ /**+ * navigator.clipboard is absent on plain-http origins, which is how plenty of+ * self-hosted installs are reached. Fall back to selecting the fingerprint so+ * the operator can copy it manually, and always confirm which happened.+ */+ const copyFingerprint = async (fingerprint: string | null) => {+ if (!fingerprint) return;+ try {+ await navigator.clipboard.writeText(fingerprint);+ setCopied(true);+ setCopyError(null);+ } catch {+ const node = fingerprintRef.current;+ if (node) {+ const range = document.createRange();+ range.selectNodeContents(node);+ const selection = window.getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);+ }+ setCopied(false);+ setCopyError(t("portal.infrastructure.encryption.masterKey.copyFailed"));+ }+ };++ const onRotate = async () => {+ setRotating(true);+ setRotateError(null);+ try {+ const result = await rotateMasterKey();+ setLastRewrapped(result.rewrapped);+ await load();+ } catch (error) {+ setRotateError(+ isConflict(error)+ ? errorMessage(error)+ : t("portal.infrastructure.encryption.error.rotate"),+ );+ // A rotation can fail partway, so the pending count on screen is stale.+ await load();+ } finally {+ if (mounted.current) setRotating(false);+ }+ };++ if (loading) {+ return (+ <div className="portal-enc__stack" aria-hidden>+ <Skeleton height="7rem" />+ <Skeleton height="11rem" />+ </div>+ );+ }++ if (loadError || !status) {+ const reason = unavailableReason(loadError);+ // Keep the section heading: without it this is an unexplained message+ // floating in the middle of the Storage tab.+ return (+ <section className="portal-enc__stack">+ <SectionHeader+ title={t("portal.infrastructure.encryption.heading")}+ hint={t("portal.infrastructure.encryption.subheading")}+ hintLabel={t("portal.infrastructure.encryption.hintLabel")}+ />+ <Card padding="loose">+ <EmptyState+ size="compact"+ title={t(+ `portal.infrastructure.encryption.unavailable.${reason}.title`,+ )}+ description={t(+ `portal.infrastructure.encryption.unavailable.${reason}.description`,+ )}+ />+ </Card>+ </section>+ );+ }++ const totalFiles = status.encryptedFiles + status.plaintextFiles;+ const coverage = totalFiles > 0 ? status.encryptedFiles / totalFiles : 0;+ const coveragePercent = Math.round(coverage * 100);+ // Keyed off the count, not the fraction: rounding makes 4,127/4,128 display as+ // 100%, and a green badge over an amber bar is worse than either alone.+ const fullyCovered = status.plaintextFiles === 0 && totalFiles > 0;+ // Nothing encrypted, no keys, machinery never started: the key, rotation and+ // revocation cards describe machinery that does not exist yet, so showing+ // them is five cards of noise. Coverage and the backlog are the whole story.+ const neverUsed =+ !status.writeEnabled && !status.active && status.keys.length === 0;+ const writeStateTone = status.writeEnabled+ ? "success"+ : status.active+ ? "warning"+ : "neutral";+ const writeStateKey = status.writeEnabled+ ? "encrypting"+ : status.active+ ? "decryptOnly"+ : "off";++ return (+ <div className="portal-enc__stack">+ {/* Sectioning elements, not divs: SectionHeader renders a <header>, which+ becomes a banner landmark unless it is scoped by a section. */}+ <section className="portal-enc__head">+ <SectionHeader+ title={t("portal.infrastructure.encryption.heading")}+ hint={t("portal.infrastructure.encryption.subheading")}+ hintLabel={t("portal.infrastructure.encryption.hintLabel")}+ />+ <StatusBadge tone={writeStateTone} size="sm">+ {t(`portal.infrastructure.encryption.writeState.${writeStateKey}`)}+ </StatusBadge>+ </section>++ {!auditAvailable ? (+ <Banner+ tone="info"+ title={t("portal.infrastructure.encryption.auditNotice.title")}+ description={t(+ "portal.infrastructure.encryption.auditNotice.description",+ )}+ />+ ) : null}++ {status.masterKeySource === "generated" ? (+ <Banner+ tone="warning"+ title={t("portal.infrastructure.encryption.generatedKey.title")}+ description={t(+ "portal.infrastructure.encryption.generatedKey.description",+ )}+ action={+ <Button+ variant="secondary"+ size="sm"+ as="a"+ href={RUNBOOK_BACKUP}+ target="_blank"+ rel="noopener noreferrer"+ >+ {t("portal.infrastructure.encryption.generatedKey.backupGuide")}+ </Button>+ }+ />+ ) : null}++ <section>+ <Card padding="loose">+ <SectionHeader+ title={t("portal.infrastructure.encryption.coverage.heading")}+ hint={t("portal.infrastructure.encryption.coverage.subheading")}+ hintLabel={t("portal.infrastructure.encryption.hintLabel")}+ />+ <div className="portal-enc__coverage">+ <div className="portal-enc__coverage-tiles">+ <StatTile+ label={t("portal.infrastructure.encryption.coverage.encrypted")}+ value={status.encryptedFiles.toLocaleString()}+ />+ <StatTile+ label={t("portal.infrastructure.encryption.coverage.plaintext")}+ value={status.plaintextFiles.toLocaleString()}+ tone={status.plaintextFiles > 0 ? "warning" : "default"}+ />+ </div>+ {totalFiles > 0 ? (+ <StatusBadge+ tone={fullyCovered ? "success" : "warning"}+ size="sm"+ >+ {t(+ "portal.infrastructure.encryption.coverage.percentEncrypted",+ { percent: coveragePercent },+ )}+ </StatusBadge>+ ) : null}+ </div>+ <div className="portal-enc__coverage-bar">+ <ProgressBar+ value={coverage}+ height={10}+ color={fullyCovered ? "var(--color-green)" : undefined}+ label={t(+ "portal.infrastructure.encryption.coverage.progressLabel",+ { percent: coveragePercent },+ )}+ />+ </div>+ {!status.writeEnabled && status.active ? (+ <p className="portal-enc__note">+ {t("portal.infrastructure.encryption.coverage.decryptOnlyNote")}+ </p>+ ) : null}+ </Card>+ </section>++ {neverUsed ? null : (+ <>+ <section className="portal-enc__split">+ <Card padding="loose">+ <SectionHeader+ title={t("portal.infrastructure.encryption.masterKey.heading")}+ hint={t(+ "portal.infrastructure.encryption.masterKey.subheading",+ )}+ hintLabel={t("portal.infrastructure.encryption.hintLabel")}+ />+ {status.masterKeyFingerprint ? (+ <>+ <div className="portal-enc__kv">+ <div className="portal-enc__fingerprint">+ <span className="portal-enc__kv-label">+ {t(+ "portal.infrastructure.encryption.masterKey.fingerprint",+ )}+ </span>+ <code ref={fingerprintRef}>+ {status.masterKeyFingerprint}+ </code>+ <InfoHint+ content={t(+ "portal.infrastructure.encryption.masterKey.compareNote",+ )}+ label={t(+ "portal.infrastructure.encryption.masterKey.fingerprintHelp",+ )}+ />+ <Button+ variant="quiet"+ size="sm"+ onClick={() =>+ void copyFingerprint(status.masterKeyFingerprint)+ }+ >+ {copied+ ? t(+ "portal.infrastructure.encryption.masterKey.copied",+ )+ : t(+ "portal.infrastructure.encryption.masterKey.copy",+ )}+ </Button>+ </div>+ <div className="portal-enc__kv-row">+ <span className="portal-enc__kv-label">+ {t(+ "portal.infrastructure.encryption.masterKey.version",+ )}+ </span>+ <span className="portal-enc__cell-strong">+ {status.masterKeyVersion}+ </span>+ </div>+ {status.provider ? (+ <div className="portal-enc__kv-row">+ <span className="portal-enc__kv-label">+ {t(+ "portal.infrastructure.encryption.masterKey.backend",+ )}+ </span>+ <span className="portal-enc__cell-strong">+ {status.provider}+ </span>+ </div>+ ) : null}+ </div>+ {/* Presigned URLs are suppressed once anything is encrypted, so+ object-store downloads start streaming through the app. */}+ {status.provider === "s3" &&+ (status.writeEnabled ||+ status.active ||+ status.keys.length > 0) ? (+ <p className="portal-enc__note">+ {t(+ "portal.infrastructure.encryption.masterKey.s3StreamingNote",+ )}+ </p>+ ) : null}+ {copyError ? (+ <Banner tone="warning" description={copyError} />+ ) : null}+ </>+ ) : (+ <p className="portal-enc__note">+ {t(+ "portal.infrastructure.encryption.masterKey.notMaterialised",+ )}+ </p>+ )}+ </Card>++ <EncryptionRotationCard+ actionError={rotateError}+ masterKeyVersion={status.masterKeyVersion}+ pendingRows={pendingRotationCount(status)}+ rotating={rotating}+ lastRewrapped={lastRewrapped}+ onRotate={() => void onRotate()}+ />+ </section>++ <EncryptionKeyTable+ actionError={keyActionError}+ keys={status.keys}+ clusterEnabled={clusterEnabled}+ busyKeyId={busyKeyId}+ onRevoke={(key) => void runKeyAction(key, disableEncryptionKey)}+ onRestore={(key) => void runKeyAction(key, enableEncryptionKey)}+ />+ </>+ )}++ <EncryptionMigrationCard+ status={migration}+ plaintextFiles={status.plaintextFiles}+ writeEnabled={status.writeEnabled}+ starting={starting}+ actionError={migrationError}+ onStart={() => void onStartMigration()}+ />+ </div>+ );+}diff --git a/frontend/editor/src/portal/components/infrastructure/EncryptionRotationCard.tsx b/frontend/editor/src/portal/components/infrastructure/EncryptionRotationCard.tsxnew file mode 100644index 0000000000..705019f433--- /dev/null+++ b/frontend/editor/src/portal/components/infrastructure/EncryptionRotationCard.tsx@@ -0,0 +1,154 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Banner, Button, Card, Modal } from "@app/ui";+import { RUNBOOK_ROTATION } from "@portal/api/storageEncryption";+import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";++export interface EncryptionRotationCardProps {+ masterKeyVersion: number | null;+ /** Key rows still wrapped by an older master-key version. */+ pendingRows: number;+ rotating?: boolean;+ /** Rows re-wrapped by the last run, for confirmation after the action. */+ lastRewrapped?: number | null;+ actionError?: string | null;+ onRotate: () => void;+}++/**+ * Rotation is a re-wrap of the key table, never a file rewrite, and key material+ * never crosses HTTP. The warning while rows are pending is the load-bearing+ * part: removing the outgoing key at that point would seal those files.+ */+export function EncryptionRotationCard({+ masterKeyVersion,+ pendingRows,+ rotating = false,+ lastRewrapped = null,+ actionError = null,+ onRotate,+}: EncryptionRotationCardProps) {+ const { t } = useTranslation();+ const [confirming, setConfirming] = useState(false);++ return (+ <section>+ <Card padding="loose">+ <SectionHeader+ title={t("portal.infrastructure.encryption.rotation.heading")}+ hint={t("portal.infrastructure.encryption.rotation.hint")}+ hintLabel={t("portal.infrastructure.encryption.hintLabel")}+ />++ <div className="portal-enc__kv">+ <div className="portal-enc__kv-row">+ <span className="portal-enc__kv-label">+ {t("portal.infrastructure.encryption.rotation.currentVersion")}+ </span>+ <span className="portal-enc__cell-strong">+ {masterKeyVersion ??+ t("portal.infrastructure.encryption.unknown")}+ </span>+ </div>+ <div className="portal-enc__kv-row">+ <span className="portal-enc__kv-label">+ {t("portal.infrastructure.encryption.rotation.pendingRows")}+ </span>+ <span className="portal-enc__cell-strong">{pendingRows}</span>+ </div>+ </div>++ {pendingRows > 0 ? (+ <Banner+ tone="warning"+ title={t(+ "portal.infrastructure.encryption.rotation.pending.title",+ {+ count: pendingRows,+ },+ )}+ description={t(+ "portal.infrastructure.encryption.rotation.pending.description",+ )}+ />+ ) : null}++ {lastRewrapped !== null ? (+ <Banner+ tone="success"+ description={t(+ "portal.infrastructure.encryption.rotation.rewrapped",+ {+ count: lastRewrapped,+ },+ )}+ />+ ) : null}++ {actionError ? (+ <Banner tone="warning" description={actionError} />+ ) : null}++ <div className="portal-enc__actions">+ <Button+ variant="secondary"+ size="sm"+ disabled={pendingRows === 0 || rotating}+ onClick={() => setConfirming(true)}+ >+ {t("portal.infrastructure.encryption.rotation.rewrap")}+ </Button>+ <Button+ variant="tertiary"+ size="sm"+ as="a"+ href={RUNBOOK_ROTATION}+ target="_blank"+ rel="noopener noreferrer"+ >+ {t("portal.infrastructure.encryption.rotation.runbook")}+ </Button>+ </div>++ <Modal+ open={confirming}+ onClose={() => setConfirming(false)}+ width="md"+ title={t("portal.infrastructure.encryption.rotation.confirm.title")}+ footer={+ <>+ <Button variant="secondary" onClick={() => setConfirming(false)}>+ {t("portal.infrastructure.encryption.rotation.confirm.cancel")}+ </Button>+ <Button+ variant="primary"+ onClick={() => {+ setConfirming(false);+ onRotate();+ }}+ >+ {t("portal.infrastructure.encryption.rotation.confirm.confirm")}+ </Button>+ </>+ }+ >+ <ul className="portal-enc__consequences">+ <li>+ {t("portal.infrastructure.encryption.rotation.confirm.rewraps", {+ count: pendingRows,+ })}+ </li>+ <li>+ {t("portal.infrastructure.encryption.rotation.confirm.noFiles")}+ </li>+ <li>+ {t(+ "portal.infrastructure.encryption.rotation.confirm.rerunnable",+ )}+ </li>+ </ul>+ </Modal>+ </Card>+ </section>+ );+}diff --git a/frontend/editor/src/portal/components/infrastructure/SectionHeader.tsx b/frontend/editor/src/portal/components/infrastructure/SectionHeader.tsxindex fa2ba6d0b5..aec96a5d87 100644--- a/frontend/editor/src/portal/components/infrastructure/SectionHeader.tsx+++ b/frontend/editor/src/portal/components/infrastructure/SectionHeader.tsx@@ -1,9 +1,29 @@-/** Title + sub-line heading shared by every Infrastructure section. */-export function SectionHeader({ title, sub }: { title: string; sub: string }) {+import { InfoHint } from "@portal/components/InfoHint";++export interface SectionHeaderProps {+ title: string;+ /** Sub-line under the title. Prefer `hint` for anything explanatory. */+ sub?: string;+ /** Explanation, carried by an info icon beside the title instead of a sub-line. */+ hint?: string;+ /** Accessible name for the hint trigger. Required whenever `hint` is set. */+ hintLabel?: string;+}++/** Title + explanation heading shared by every Infrastructure section. */+export function SectionHeader({+ title,+ sub,+ hint,+ hintLabel,+}: SectionHeaderProps) {return (<header className="portal-infra__section-head">- <h2 className="portal-infra__section-title">{title}</h2>- <p className="portal-infra__section-sub">{sub}</p>+ <div className="portal-infra__section-title-row">+ <h2 className="portal-infra__section-title">{title}</h2>+ {hint ? <InfoHint content={hint} label={hintLabel ?? title} /> : null}+ </div>+ {sub ? <p className="portal-infra__section-sub">{sub}</p> : null}</header>);}diff --git a/frontend/editor/src/portal/views/Infrastructure.css b/frontend/editor/src/portal/views/Infrastructure.cssindex 962be38b04..d20b2f99b3 100644--- a/frontend/editor/src/portal/views/Infrastructure.css+++ b/frontend/editor/src/portal/views/Infrastructure.css@@ -58,6 +58,12 @@margin-bottom: 0.625rem;}+.portal-infra__section-title-row {+ display: flex;+ align-items: center;+ gap: 0.375rem;+}+.portal-infra__section-title {margin: 0;font-size: 0.9375rem;diff --git a/frontend/editor/src/portal/views/Infrastructure.test.tsx b/frontend/editor/src/portal/views/Infrastructure.test.tsxindex afd23e0ff1..e1473f7186 100644--- a/frontend/editor/src/portal/views/Infrastructure.test.tsx+++ b/frontend/editor/src/portal/views/Infrastructure.test.tsx@@ -25,6 +25,9 @@ vi.mock("@portal/components/infrastructure/ApiKeysTab", () => ({vi.mock("@portal/components/infrastructure/AuditTab", () => ({AuditTab: () => <div data-testid="audit-tab" />,}));+vi.mock("@portal/components/infrastructure/EncryptionPanel", () => ({+ EncryptionPanel: () => <div data-testid="storage-tab" />,+}));import { Infrastructure } from "@portal/views/Infrastructure";@@ -69,8 +72,9 @@ describe("Infrastructure view", () => {it("renders the backend-less tabs as inert: disabled, aria-disabled, never active", () => {renderView();+ // Storage is no longer in this list: it reads a real backend now.const byLabel = new Map(tabButtons().map((b) => [b.textContent, b]));- for (const key of ["deployments", "security", "models", "storage"]) {+ for (const key of ["deployments", "security", "models"]) {const btn = byLabel.get(`${T}.${key}`) as HTMLButtonElement;expect(btn).toBeDisabled();expect(btn).toHaveAttribute("aria-disabled", "true");@@ -96,12 +100,26 @@ describe("Infrastructure view", () => {});it("ignores a deep link to a disabled tab and stays on the default", () => {- renderView("/infrastructure?tab=storage");+ renderView("/infrastructure?tab=models");expect(screen.getByTestId("api-keys-tab")).toBeInTheDocument();expect(screen.queryByTestId("audit-tab")).not.toBeInTheDocument();});+ it("switches to the storage tab when clicked", () => {+ renderView();++ fireEvent.click(screen.getByRole("button", { name: `${T}.storage` }));+ expect(screen.getByTestId("storage-tab")).toBeInTheDocument();+ expect(screen.queryByTestId("api-keys-tab")).not.toBeInTheDocument();+ });++ it("honours ?tab=storage deep links", () => {+ renderView("/infrastructure?tab=storage");++ expect(screen.getByTestId("storage-tab")).toBeInTheDocument();+ });+it("disables the audit tab (inert, never opens) for non-enterprise users", () => {enterprise.enabled = false;renderView();diff --git a/frontend/editor/src/portal/views/Infrastructure.tsx b/frontend/editor/src/portal/views/Infrastructure.tsxindex fa1ff272b9..18a34d7efb 100644--- a/frontend/editor/src/portal/views/Infrastructure.tsx+++ b/frontend/editor/src/portal/views/Infrastructure.tsx@@ -6,12 +6,13 @@ import { useView } from "@portal/contexts/ViewContext";import { useEnterpriseEnabled } from "@portal/hooks/useEnterpriseEnabled";import { ApiKeysTab } from "@portal/components/infrastructure/ApiKeysTab";import { AuditTab } from "@portal/components/infrastructure/AuditTab";+import { EncryptionPanel } from "@portal/components/infrastructure/EncryptionPanel";import "@portal/views/Infrastructure.css";-type InfraTab = "api-keys" | "audit";+type InfraTab = "api-keys" | "audit" | "storage";/** Shown but inert: no backend behind these screens yet. */-type DisabledInfraTab = "deployments" | "security" | "models" | "storage";+type DisabledInfraTab = "deployments" | "security" | "models";export function Infrastructure() {const { t } = useTranslation();@@ -19,10 +20,14 @@ export function Infrastructure() {const { setActiveView } = useView();const [searchParams, setSearchParams] = useSearchParams();// Audit is Enterprise-only; disabled (greyed, inert) on non-enterprise instances.- const auditEnabled = useEnterpriseEnabled().enabled;+ const enterprise = useEnterpriseEnabled();+ const auditEnabled = enterprise.enabled;const canOpenTab = useCallback(- (key: string) => key === "api-keys" || (key === "audit" && auditEnabled),+ (key: string) =>+ key === "api-keys" ||+ key === "storage" ||+ (key === "audit" && auditEnabled),[auditEnabled],);@@ -61,11 +66,9 @@ export function Infrastructure() {label: t("portal.infrastructure.tabs.models"),disabled: true,},- {- key: "storage",- label: t("portal.infrastructure.tabs.storage"),- disabled: true,- },+ // Enabled again: unlike the mock-backed tabs removed in #7497, this one+ // reads the real /api/v1/admin/storage-encryption surface.+ { key: "storage", label: t("portal.infrastructure.tabs.storage") },];return (@@ -97,6 +100,14 @@ export function Infrastructure() {<div className="portal-infra__panel">{tab === "api-keys" && <ApiKeysTab />}{tab === "audit" && <AuditTab />}+ {tab === "storage" && (+ // Treat "still resolving" as available: flashing "your licence records+ // no audit trail" at an Enterprise operator is worse than the notice+ // arriving a beat late.+ <EncryptionPanel+ auditAvailable={enterprise.loading || enterprise.enabled}+ />+ )}</div></div>);