Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

11.7 KB
Raw Blame
import type { Meta, StoryObj } from "@storybook/react-vite";
import { http, HttpResponse } from "msw";
import { expect, userEvent, within } from "storybook/test";
import { EncryptionPanel } from "@processor/components/infrastructure/EncryptionPanel";
import type {
  EncryptionKeyInfo,
  MigrationStatus,
  StorageEncryptionStatus,
} from "@processor/api/storageEncryption";
// SectionHeader's styles live in infrastructure.css, which the panel loads too;
// without it the stories render larger than the app does.
import "@processor/components/infrastructure/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" }),
    },
  },
};