From e72e191796bbaaf7edfa330ed5584b38220bbd94 Mon Sep 17 00:00:00 2001 From: Paolo Scattolin Date: Fri, 4 Dec 2026 12:01:35 +0100 Subject: [PATCH 1/3] Rename playbook upload to import --- src/App.tsx | 2 +- src/pages/main-page/playbooks-page/PlaybookCreatePage.tsx | 4 ++-- src/pages/main-page/playbooks-page/PlaybooksPage.tsx | 4 ++-- src/utils.ts | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index b12ccc7..9e19f7b 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -82,7 +82,7 @@ function App() { } > } /> { - Upload playbook + Import playbook @@ -181,7 +181,7 @@ export const PlaybookCreatePage: React.FC = () => { onClick={handleSubmit} disabled={!canSubmit} > - Upload + Import diff --git a/src/pages/main-page/playbooks-page/PlaybooksPage.tsx b/src/pages/main-page/playbooks-page/PlaybooksPage.tsx index d6166f6..08bee8e 100644 --- a/src/pages/main-page/playbooks-page/PlaybooksPage.tsx +++ b/src/pages/main-page/playbooks-page/PlaybooksPage.tsx @@ -207,10 +207,10 @@ export const PlaybooksPage: React.FC = () => { - {canEdit && ( - - )} - {canWrite && ( - - )} - - ); - }, + cell: ({ row }) => ( + + + + ), }, ], - [canEdit, canWrite], + [], ); - if (query.isLoading) return ; - - if (query.isLoadingError) - return ( - - - - ); - return ( <> resource.object.type)), + ].sort()} onTypeChange={setType} search={search} onSearchChange={setSearch} - > - - {canWrite && ( - - )} - - + /> resource.object.id} initialSorting={[{ id: "name", desc: false }]} - emptyMessage={ - type - ? `No ${noun} match the filters` - : search.trim() - ? `No ${noun} match "${search.trim()}"` - : `No ${noun} stored` - } + emptyMessage={`No ${noun} match the filters`} /> - {(dialog?.kind === "create" || - ((dialog?.kind === "edit" || dialog?.kind === "view") && - activeResource)) && ( - setSelectedId(undefined)} /> )} - - activeResource && remove.mutate(activeResource.object.id) - } - /> ); }; diff --git a/src/pages/main-page/store-pages/SecretsPage.tsx b/src/pages/main-page/store-pages/SecretsPage.tsx index 26e402e..0794547 100644 --- a/src/pages/main-page/store-pages/SecretsPage.tsx +++ b/src/pages/main-page/store-pages/SecretsPage.tsx @@ -1,19 +1,7 @@ -import { useQuery } from "@tanstack/react-query"; import type { ColumnDef } from "@tanstack/react-table"; -import React, { useMemo, useState } from "react"; +import { useMemo, useState } from "react"; -import { storeQueries } from "@/api/storeQueries"; -import { - Badge, - CenteredCardContent, - DataTable, - QueryError, - Spinner, - TableInset, - ThemeSize, - ThemeVariant, -} from "@/components"; -import type { SecretMetadata } from "@/types"; +import { Badge, DataTable, TableInset, ThemeVariant } from "@/components"; import { formatDateTime } from "@/utils"; import { @@ -21,98 +9,52 @@ import { HistoryButton, modifiedColumn, nameColumn, - ResourceHistory, ResourceToolbar, versionColumn, } from "./ResourceTable"; -import { Muted, RowActions } from "./StorePages.styles"; +import { sampleSecrets, type SampleSecret } from "./sampleResources"; +import { RowActions } from "./StorePages.styles"; import { matchesSearch } from "./utils"; import { VersionLegend, VersionTimeline } from "./VersionTimeline"; -const KindBadge = ({ kind }: { kind: SecretMetadata["kind"] }) => - kind === "invalid" ? ( - - invalid - - ) : ( - {kind} - ); - -const SecretVersions = ({ secret }: { secret: SecretMetadata }) => { - const query = useQuery(storeQueries.secretVersions(secret.name)); - const versions = (query.data ?? []).toSorted((a, b) => a.version - b.version); - return ( - 1 && ( - - Versions before v{secret.oldest_version} are no longer kept. - - ) - } - > - ({ - version: v.version, - current: v.current, - state: v.destroyed - ? "destroyed" - : v.deleted - ? "deleted" - : v.current - ? undefined - : "previous", - modifiedTitle: v.deleted - ? `Created at ${formatDateTime(v.created)}\nDeleted at ${formatDateTime(v.deleted)}` - : `Created at ${formatDateTime(v.created)}`, - }))} - /> - - ); -}; - -export const SecretsPage: React.FC = () => { +export const SecretsPage = () => { const [search, setSearch] = useState(""); const [kind, setKind] = useState(""); - - const backend = useQuery(storeQueries.secretBackend()); - const secrets = useQuery(storeQueries.secrets()); - - const kinds = [ - ...new Set([ - ...(backend.data?.kinds ?? []), - ...(secrets.data ?? []).map((s) => s.kind), - ...(kind ? [kind] : []), - ]), - ]; - - const rows = (secrets.data ?? []).filter( - (s) => - (!kind || s.kind === kind) && - matchesSearch(search, s.name, s.description), + const rows = sampleSecrets.filter( + (secret) => + (!kind || secret.kind === kind) && + matchesSearch(search, secret.name, secret.description), ); - - const columns = useMemo[]>( + const columns = useMemo[]>( () => [ nameColumn(160), { accessorKey: "kind", size: 120, header: "Type", - cell: ({ row }) => , + cell: ({ row }) => ( + + {row.original.kind} + + ), }, descriptionColumn(180), versionColumn(90), modifiedColumn(120), { id: "actions", - size: 130, + size: 90, header: "Actions", enableSorting: false, cell: ({ row }) => ( @@ -125,26 +67,12 @@ export const SecretsPage: React.FC = () => { [], ); - if (secrets.isLoading) - return ( - - - - ); - - if (secrets.isLoadingError) - return ( - - - - ); - return ( <> secret.kind))]} onTypeChange={setKind} search={search} onSearchChange={setSearch} @@ -159,15 +87,27 @@ export const SecretsPage: React.FC = () => { columns={columns} label="Secrets" getRowId={(secret) => secret.name} - renderDetail={(secret) => } + renderDetail={(secret) => ( + ({ + version: version.version, + current: version.current, + state: version.destroyed + ? "destroyed" + : version.deleted + ? "deleted" + : version.current + ? undefined + : "previous", + modifiedTitle: version.deleted + ? `Created at ${formatDateTime(version.created)}\nDeleted at ${formatDateTime(version.deleted)}` + : `Created at ${formatDateTime(version.created)}`, + }))} + /> + )} initialSorting={[{ id: "name", desc: false }]} - emptyMessage={ - kind - ? "No secrets match the filters" - : search.trim() - ? `No secrets match "${search.trim()}"` - : "No secrets stored" - } + emptyMessage="No secrets match the filters" /> diff --git a/src/pages/main-page/store-pages/StorePage.test.tsx b/src/pages/main-page/store-pages/StorePage.test.tsx index 40138c4..48a7b50 100644 --- a/src/pages/main-page/store-pages/StorePage.test.tsx +++ b/src/pages/main-page/store-pages/StorePage.test.tsx @@ -5,87 +5,55 @@ import { fireEvent, render, screen, - waitFor, within, } from "@testing-library/react"; -import { MemoryRouter } from "react-router"; +import { MemoryRouter, Outlet } from "react-router"; import { ThemeProvider } from "styled-components"; import { afterAll, afterEach, beforeAll, + beforeEach, describe, expect, it, vi, } from "vitest"; -import { - createVariable, - deleteVariable, - getSecretBackend, - getCacaoResources, - getCacaoFieldMapping, - getSecrets, - getSecretVersions, - getVariableVersions, - getVariables, - updateVariableDescription, - updateVariableValue, -} from "@/api/store"; +import App from "@/App"; import { AuthContext } from "@/auth/AuthContext"; import { Permissions, type Permission } from "@/auth/permissions"; import { theme } from "@/theme"; -import type { CacaoResource, SecretMetadata, StoredVariable } from "@/types"; -import { StorePage } from "./StorePage"; +import { RESOURCE_TABS } from "./utils"; -vi.mock("@/api/store", () => ({ - getVariables: vi.fn(), - getSecrets: vi.fn(), - getSecretBackend: vi.fn(), - getSecretVersions: vi.fn(), - getVariableVersions: vi.fn(), - createVariable: vi.fn(), - updateVariableValue: vi.fn(), - updateVariableDescription: vi.fn(), - deleteVariable: vi.fn(), - getCacaoResources: vi.fn(), - getCacaoFieldMapping: vi.fn(), +vi.mock("@/pages/main-page/MainPage", () => ({ + MainPage: () => , + ScrollPage: () => , })); -const variable = (name: string, version: number): StoredVariable => ({ - name, - version, - type: "string", - value: name, - description: "", - oldest_version: 1, - created: "2026-01-01T00:00:00Z", - modified: "2026-01-01T00:00:00Z", - created_by: "identity--1", - modified_by: "identity--1", -}); -const secret: SecretMetadata = { - name: "test-secret", - kind: "token", - description: "", - version: 2, - oldest_version: 1, - created: "2026-01-01T00:00:00Z", - modified: "2026-01-01T00:00:00Z", -}; +const fetch = vi.fn(); -function renderStore(path: string, permissions: Permission[]) { - const client = new QueryClient({ - defaultOptions: { queries: { retry: false } }, - }); +function renderStore( + path: string, + permissions: Permission[] = [Permissions.PlaybookRead], + anonymous = false, +) { return render( - + - + @@ -104,11 +72,6 @@ function renderStore(path: string, permissions: Permission[]) { ); } -const chooseOption = (combobox: HTMLElement, optionName: string) => { - fireEvent.keyDown(combobox, { key: "ArrowDown" }); - fireEvent.click(screen.getByRole("option", { name: optionName })); -}; - const originalShowModal = HTMLDialogElement.prototype.showModal; const originalClose = HTMLDialogElement.prototype.close; @@ -131,510 +94,143 @@ afterAll(() => { HTMLDialogElement.prototype.close = originalClose; }); +beforeEach(() => vi.stubGlobal("fetch", fetch)); afterEach(() => { cleanup(); vi.resetAllMocks(); + vi.unstubAllGlobals(); }); -describe("Secrets and variables page", () => { +describe("read-only sample Resources", () => { it.each([ - { - path: "/targets", - type: "http-api", - label: "target", - permission: Permissions.TargetRead, - write: Permissions.TargetWrite, - }, - { - path: "/authentication-info", - type: "http-basic", - label: "authentication", - permission: Permissions.AuthenticationInfoRead, - write: Permissions.AuthenticationInfoWrite, - }, + ["/variables", "Variables"], + ["/secrets", "Secrets"], + ["/authentication-info", "Authentication"], + ["/targets", "Targets"], ])( - "opens a read-only $label even when editing is permitted", - async ({ path, type, label, permission, write }) => { - const resource: CacaoResource = { - version: 2, - modified: "2026-01-01", - modified_by: "identity--1", - object: { id: `${type}--1`, type, name: "Example resource" }, - }; - vi.mocked(getCacaoResources).mockResolvedValue([resource]); - vi.mocked(getCacaoFieldMapping).mockResolvedValue(null); - renderStore(path, [permission, write, Permissions.MappingWrite]); - fireEvent.click( - await screen.findByRole("button", { name: "Show Example resource" }), + "shows %s to playbook readers without resource permissions or API requests", + (path, table) => { + renderStore(path); + expect(screen.getByRole("table", { name: table })).toBeTruthy(); + expect(screen.getAllByRole("link")).toHaveLength(4); + expect(screen.getByRole("alert").textContent).toContain( + "read-only sample resources", + ); + expect(screen.getByRole("alert").textContent).toContain( + "cannot be used in playbooks", ); - const dialog = await screen.findByRole("dialog", { - name: `View ${label}`, - }); - expect(await within(dialog).findByText("Example resource")).toBeTruthy(); - expect(within(dialog).queryByRole("button", { name: "Save" })).toBeNull(); - expect(within(dialog).queryByRole("textbox")).toBeNull(); - fireEvent.click(within(dialog).getByRole("button", { name: "Close" })); expect( - screen.getByRole("button", { name: "Edit Example resource" }), + screen + .getByRole("alert") + .compareDocumentPosition(screen.getByRole("navigation")) & + Node.DOCUMENT_POSITION_FOLLOWING, ).toBeTruthy(); - expect(screen.getByText("v2")).toBeTruthy(); - expect( - screen.queryByRole("button", { name: /View history of/ }), - ).toBeNull(); + expect(fetch).not.toHaveBeenCalled(); }, ); - it("sorts and searches variables, then switches to secret versions", async () => { - vi.mocked(getVariables).mockResolvedValue([ - variable("zebra", 2), - variable("alpha", 1), - ]); - vi.mocked(getSecrets).mockResolvedValue([secret]); - vi.mocked(getSecretBackend).mockResolvedValue({ - type: "OpenBao", - production: false, - versioning: true, - max_versions: 10, - operations: ["list", "get"], - kinds: ["token"], - }); - vi.mocked(getSecretVersions).mockResolvedValue([ - { version: 2, created: secret.created, current: true }, - { version: 1, created: secret.created, destroyed: true }, - ]); - renderStore("/variables", [ - Permissions.VariableRead, - Permissions.VariableWrite, - Permissions.SecretRead, - ]); - - const table = await screen.findByRole("table", { name: "Variables" }); - expect(within(table).getAllByRole("row")[1].textContent).toContain("alpha"); - fireEvent.click(within(table).getByRole("button", { name: "Name" })); - expect(within(table).getAllByRole("row")[1].textContent).toContain("zebra"); - fireEvent.change( - screen.getByRole("searchbox", { name: "Search variables" }), - { target: { value: "alpha" } }, - ); - expect(within(table).queryByText("zebra")).toBeNull(); - expect(screen.getByText("1 result")).toBeTruthy(); - - fireEvent.click(screen.getByRole("link", { name: "Secrets" })); - const secretsTable = await screen.findByRole("table", { name: "Secrets" }); - fireEvent.change( - screen.getByRole("combobox", { name: "Filter secrets by type" }), - { target: { value: "token" } }, - ); - expect(within(secretsTable).getByText("test-secret")).toBeTruthy(); - expect(getSecretVersions).not.toHaveBeenCalled(); - const history = screen.getByRole("button", { - name: "View history of test-secret", - }); - fireEvent.click(history); - const versionList = await screen.findByRole("list", { - name: "Versions of test-secret", - }); - expect( - within(versionList) - .getAllByRole("listitem") - .map((item) => item.textContent?.match(/v\d+/)?.[0]), - ).toEqual(["v1", "v2"]); - fireEvent.click(history); - expect( - screen.queryByRole("list", { name: "Versions of test-secret" }), - ).toBeNull(); - }); - - it("only shows permitted tabs and write actions", async () => { - vi.mocked(getVariables).mockResolvedValue([variable("alpha", 2)]); - renderStore("/variables", [Permissions.VariableRead]); - expect( - await screen.findByRole("table", { name: "Variables" }), - ).toBeTruthy(); - expect(screen.queryByRole("link", { name: "Secrets" })).toBeNull(); - expect(screen.queryByRole("button", { name: "New" })).toBeNull(); - expect(screen.queryByRole("button", { name: "Edit alpha" })).toBeNull(); - expect( - screen.getByRole("button", { name: "View history of alpha" }), - ).toBeTruthy(); - }); + it.each(RESOURCE_TABS)( + "allows anonymous mode to open $label without resource permissions", + ({ path, label }) => { + renderStore(path, [], true); + expect(screen.getByRole("table", { name: label })).toBeTruthy(); + expect(fetch).not.toHaveBeenCalled(); + }, + ); - it("copies the complete variable value, including an empty value", async () => { - const writeText = vi.fn().mockResolvedValue(undefined); - vi.stubGlobal("navigator", { - ...navigator, - clipboard: { writeText }, - }); - vi.mocked(getVariables).mockResolvedValue([ - { ...variable("long", 1), value: "https://example.org/a/long/value" }, - { ...variable("empty", 1), value: "" }, - ]); + it("denies signed-in users who cannot read playbooks", () => { renderStore("/variables", [Permissions.VariableRead]); - - fireEvent.click( - await screen.findByRole("button", { name: "Copy value of long" }), - ); - fireEvent.click( - screen.getByRole("button", { name: "Copy value of empty" }), - ); - await waitFor(() => { - expect(writeText).toHaveBeenNthCalledWith( - 1, - "https://example.org/a/long/value", - ); - expect(writeText).toHaveBeenNthCalledWith(2, ""); - }); + expect(screen.getByText("Access denied")).toBeTruthy(); + expect(screen.queryByRole("table")).toBeNull(); + expect(fetch).not.toHaveBeenCalled(); }); - it("reveals and hides a variable and its history together", async () => { - const current = { ...variable("alpha", 2), value: "current-value" }; - vi.mocked(getVariables).mockResolvedValue([ - current, - { ...variable("beta", 1), value: "other-value" }, - ]); - vi.mocked(getVariableVersions).mockResolvedValue([ - { - version: 1, - value: "previous-value", - created: current.created, - created_by: current.created_by, - }, - { - version: 2, - value: current.value, - created: current.created, - created_by: current.created_by, - current: true, - }, - ]); - renderStore("/variables", [Permissions.VariableRead]); + it.each(RESOURCE_TABS)( + "never exposes write actions on $label even with all backend permissions", + ({ path }) => { + renderStore(path, Object.values(Permissions)); + expect( + screen.queryByRole("button", { name: /^(New|Edit|Delete|Restore)/ }), + ).toBeNull(); + expect(fetch).not.toHaveBeenCalled(); + }, + ); - const table = await screen.findByRole("table", { name: "Variables" }); - expect(table.textContent).not.toContain("current-value"); - fireEvent.click( - screen.getByRole("button", { name: "View history of alpha" }), + it("keeps variable search, sorting, reveal and read-only history usable", () => { + renderStore("/variables"); + const table = screen.getByRole("table", { name: "Variables" }); + expect(within(table).getAllByRole("row")[1].textContent).toContain( + "api-timeout", ); - const history = await screen.findByRole("list", { - name: "Versions of alpha", - }); - expect(history.textContent).not.toContain("previous-value"); - expect(history.textContent).not.toContain("current-value"); - fireEvent.click( - screen.getByRole("button", { - name: "Reveal values of alpha", - }), - ); - expect(within(history).getByText("previous-value")).toBeTruthy(); - expect(within(history).getByText("current-value")).toBeTruthy(); - expect(within(table).getAllByText("current-value")).toHaveLength(2); - expect(table.textContent).not.toContain("other-value"); - fireEvent.click( - screen.getByRole("button", { name: "Hide values of alpha" }), + fireEvent.click(within(table).getByRole("button", { name: "Name" })); + expect(within(table).getAllByRole("row")[1].textContent).toContain( + "web-proxy-url", ); - expect(history.textContent).not.toContain("previous-value"); - expect(table.textContent).not.toContain("current-value"); - }); - - it("filters variables by type together with search and can clear the filter", async () => { - vi.mocked(getVariables).mockResolvedValue([ - variable("alpha", 1), - { ...variable("beta", 1), type: "integer", value: "2" }, - { ...variable("gamma", 1), type: "integer", value: "3" }, - ]); - renderStore("/variables", [Permissions.VariableRead]); - const table = await screen.findByRole("table", { name: "Variables" }); - const filter = screen.getByRole("combobox", { - name: "Filter variables by type", - }); - chooseOption(filter, "integer"); - expect(within(table).queryByText("alpha")).toBeNull(); - expect(within(table).getByText("beta")).toBeTruthy(); - expect(screen.getByText("2 results")).toBeTruthy(); - fireEvent.change( screen.getByRole("searchbox", { name: "Search variables" }), - { target: { value: "alpha" } }, + { target: { value: "fw-api-user" } }, ); - expect(screen.getByText("No variables match the filters")).toBeTruthy(); - fireEvent.keyDown(filter, { key: "Backspace" }); - expect(within(table).getAllByRole("row")[1].textContent).toContain("alpha"); expect(screen.getByText("1 result")).toBeTruthy(); - }); - - it("shows only the secrets tab for users without variable access and supports filtering invalid secrets", async () => { - vi.mocked(getSecrets).mockResolvedValue([ - secret, - { ...secret, name: "broken-secret", kind: "invalid" }, - ]); - vi.mocked(getSecretBackend).mockResolvedValue({ - type: "OpenBao", - production: false, - versioning: true, - max_versions: 10, - operations: ["list", "get"], - kinds: ["token"], - }); - renderStore("/secrets", [Permissions.SecretRead]); - const table = await screen.findByRole("table", { name: "Secrets" }); - expect(screen.queryByRole("link", { name: "Variables" })).toBeNull(); - expect(getVariables).not.toHaveBeenCalled(); - - const filter = screen.getByRole("combobox", { - name: "Filter secrets by type", - }); - chooseOption(filter, "invalid"); - expect(within(table).getByText("broken-secret")).toBeTruthy(); - expect(within(table).queryByText("test-secret")).toBeNull(); - }); - - it("shows a retryable error instead of an empty table", async () => { - vi.mocked(getVariables).mockRejectedValue(new Error("offline")); - renderStore("/variables", [Permissions.VariableRead]); - expect(await screen.findByText(/Could not load variables/)).toBeTruthy(); - expect(screen.getByRole("button", { name: "Try again" })).toBeTruthy(); - expect(screen.queryByText("No variables stored")).toBeNull(); - }); - - it("keeps the expanded secret with its row when sorting and reports failed history requests", async () => { - vi.mocked(getSecrets).mockResolvedValue([ - secret, - { ...secret, name: "another" }, - ]); - vi.mocked(getSecretBackend).mockResolvedValue({ - type: "OpenBao", - production: false, - versioning: true, - max_versions: 10, - operations: ["list", "get"], - kinds: ["token"], - }); - vi.mocked(getSecretVersions) - .mockRejectedValueOnce(new Error("offline")) - .mockResolvedValueOnce([ - { version: 1, created: secret.created, destroyed: true }, - ]); - renderStore("/secrets", [Permissions.SecretRead]); - const table = await screen.findByRole("table", { name: "Secrets" }); fireEvent.click( - within(table).getByRole("button", { - name: "View history of test-secret", - }), + screen.getByRole("button", { name: "Reveal values of fw-api-user" }), ); - expect(await screen.findByText(/Could not load the versions/)).toBeTruthy(); - fireEvent.click(screen.getByRole("button", { name: "Try again" })); - const timeline = await screen.findByRole("list", { - name: "Versions of test-secret", + expect(screen.getByText("soarca-demo")).toBeTruthy(); + fireEvent.click( + screen.getByRole("button", { name: "View history of fw-api-user" }), + ); + const history = screen.getByRole("list", { + name: "Versions of fw-api-user", }); - fireEvent.click(within(table).getByRole("button", { name: "Name" })); + expect(within(history).getByText("soarca")).toBeTruthy(); expect( - timeline.closest("tr")?.previousElementSibling?.textContent, - ).toContain("test-secret"); - expect(getSecretVersions).toHaveBeenCalledWith("test-secret"); + within(history).queryByRole("button", { name: /Restore/ }), + ).toBeNull(); + expect(fetch).not.toHaveBeenCalled(); }); - it("restores a variable version from the history and hides restore without permission", async () => { - const current = variable("alpha", 2); - const versions = [ - { - version: 1, - value: "old", - created: current.created, - created_by: "identity--1", - }, - { - version: 2, - value: current.value, - created: current.created, - created_by: "identity--1", - current: true, - }, - ]; - vi.mocked(getVariables).mockResolvedValue([current]); - vi.mocked(getVariableVersions).mockResolvedValue(versions); - vi.mocked(updateVariableValue).mockResolvedValue({ - ...current, - version: 3, - value: "old", - }); - const page = renderStore("/variables", [ - Permissions.VariableRead, - Permissions.VariableWrite, - ]); - fireEvent.click( - await screen.findByRole("button", { name: "View history of alpha" }), - ); - const restore = await screen.findByRole("button", { - name: "Restore version 1 of alpha", - }); - fireEvent.click(restore); - await waitFor(() => - expect(updateVariableValue).toHaveBeenCalledWith("alpha", 2, "old"), - ); - page.unmount(); - renderStore("/variables", [Permissions.VariableRead]); + it("shows secret history without exposing secret values or contacting a backend", () => { + renderStore("/secrets"); fireEvent.click( - await screen.findByRole("button", { name: "View history of alpha" }), + screen.getByRole("button", { name: "View history of fw-api-password" }), ); expect( - await screen.findByRole("list", { name: "Versions of alpha" }), + screen.getByRole("list", { name: "Versions of fw-api-password" }), ).toBeTruthy(); expect( - screen.queryByRole("button", { name: "Restore version 1 of alpha" }), + screen.queryByRole("button", { name: /Reveal|Copy value/ }), ).toBeNull(); + expect(fetch).not.toHaveBeenCalled(); }); - it("creates a variable and validates name and typed values", async () => { - vi.mocked(getVariables).mockResolvedValue([]); - vi.mocked(createVariable).mockResolvedValue({ - ...variable("fw-token", 1), - type: "dictionary", - value: '{"key": "val"}', - }); - renderStore("/variables", [ - Permissions.VariableRead, - Permissions.VariableWrite, - ]); - - fireEvent.click(await screen.findByRole("button", { name: "New" })); - const dialog = screen.getByRole("dialog", { name: "New variable" }); - const createBtn = within(dialog).getByRole("button", { name: "Create" }); - expect(createBtn.hasAttribute("disabled")).toBe(true); - - fireEvent.change(within(dialog).getByLabelText(/^Name/), { - target: { value: "Bad Name!" }, - }); - expect( - within(dialog).getByText(/Use lowercase letters, digits/), - ).toBeTruthy(); - expect(createBtn.hasAttribute("disabled")).toBe(true); - - fireEvent.change(within(dialog).getByLabelText(/^Name/), { - target: { value: "fw-token" }, - }); - chooseOption(within(dialog).getByLabelText("Type"), "bool"); - // Boolean values must be explicitly chosen before creating. - expect(createBtn.hasAttribute("disabled")).toBe(true); - - chooseOption(within(dialog).getByLabelText("Type"), "dictionary"); - fireEvent.change(within(dialog).getByLabelText(/^Value/), { - target: { value: "[1, 2]" }, - }); - expect(within(dialog).getByText(/valid JSON object/)).toBeTruthy(); - expect(createBtn.hasAttribute("disabled")).toBe(true); - - fireEvent.change(within(dialog).getByLabelText(/^Value/), { - target: { value: '{"key": "val"}' }, - }); - expect(createBtn.hasAttribute("disabled")).toBe(false); - fireEvent.submit(createBtn.closest("form")!); - - await waitFor(() => - expect(createVariable).toHaveBeenCalledWith({ - name: "fw-token", - type: "dictionary", - value: '{"key": "val"}', - description: "", - }), - ); - }); - - it("saves the description, reports a partial save, and retries only the value", async () => { - const initial = variable("alpha", 2); - const afterDesc = { ...initial, description: "new", version: 3 }; - vi.mocked(getVariables) - .mockResolvedValueOnce([initial]) - .mockResolvedValueOnce([afterDesc]); - vi.mocked(updateVariableDescription).mockResolvedValue(afterDesc); - vi.mocked(updateVariableValue) - .mockRejectedValueOnce(new Error("Conflict")) - .mockResolvedValueOnce({ ...afterDesc, version: 4, value: "beta" }); - - renderStore("/variables", [ - Permissions.VariableRead, - Permissions.VariableWrite, - ]); - - fireEvent.click(await screen.findByRole("button", { name: "Edit alpha" })); - fireEvent.change(screen.getByLabelText("Value"), { - target: { value: "beta" }, - }); - fireEvent.change(screen.getByLabelText("Description"), { - target: { value: "new" }, - }); - fireEvent.click(screen.getByRole("button", { name: "Save" })); - - expect((await screen.findByRole("alert")).textContent).toMatch( - /^The description was saved, but the value was not\. Conflict/, - ); - expect(updateVariableDescription).toHaveBeenCalledTimes(1); - expect(updateVariableValue).toHaveBeenCalledWith("alpha", 2, "beta"); - - const dialog = screen.getByRole("dialog", { name: "Edit variable" }); - await waitFor(() => - expect( - within(dialog) - .getByRole("button", { name: "Save" }) - .hasAttribute("disabled"), - ).toBe(false), - ); - fireEvent.click(within(dialog).getByRole("button", { name: "Save" })); - - await waitFor(() => - expect(updateVariableValue).toHaveBeenCalledWith("alpha", 3, "beta"), - ); - expect(updateVariableDescription).toHaveBeenCalledTimes(1); - }); - - it("deletes a variable after confirmation", async () => { - vi.mocked(getVariables).mockResolvedValue([variable("alpha", 1)]); - vi.mocked(deleteVariable).mockResolvedValue(undefined); - renderStore("/variables", [ - Permissions.VariableRead, - Permissions.VariableWrite, - ]); - + it("shows a target's sample authentication name without resource permissions or requests", () => { + renderStore("/targets"); fireEvent.click( - await screen.findByRole("button", { name: "Delete alpha" }), + screen.getByRole("button", { name: "Show perimeter-firewall" }), ); - const confirm = screen.getByRole("dialog"); - fireEvent.click(within(confirm).getByRole("button", { name: "Delete" })); - - await waitFor(() => expect(deleteVariable).toHaveBeenCalledWith("alpha")); + const dialog = screen.getByRole("dialog", { name: "View target" }); + expect(within(dialog).getByText("firewall-api")).toBeTruthy(); + expect(fetch).not.toHaveBeenCalled(); }); - it("hides variable history when only one version is retained, but keeps single-version secrets expandable", async () => { - vi.mocked(getVariables).mockResolvedValue([ - variable("first", 1), - { ...variable("pruned", 4), oldest_version: 4 }, - { ...variable("multiple", 5), oldest_version: 4 }, - ]); - vi.mocked(getSecrets).mockResolvedValue([ - { ...secret, name: "first", version: 1 }, - { ...secret, name: "pruned", version: 4, oldest_version: 4 }, - ]); - renderStore("/variables", [ - Permissions.VariableRead, - Permissions.SecretRead, - ]); - await screen.findByRole("table", { name: "Variables" }); - expect( - screen.queryByRole("button", { name: "View history of first" }), - ).toBeNull(); - expect( - screen.queryByRole("button", { name: "View history of pruned" }), - ).toBeNull(); - expect( - screen.getByRole("button", { name: "View history of multiple" }), - ).toBeTruthy(); - - cleanup(); - renderStore("/secrets", [Permissions.VariableRead, Permissions.SecretRead]); - await screen.findByRole("table", { name: "Secrets" }); - expect( - screen.getByRole("button", { name: "View history of first" }), - ).toBeTruthy(); - expect( - screen.getByRole("button", { name: "View history of pruned" }), - ).toBeTruthy(); - }); + it.each([ + ["/targets", "perimeter-firewall", "View target"], + ["/authentication-info", "firewall-api", "View authentication"], + ])( + "opens sample details on %s without loading mappings or allowing edits", + (path, name, title) => { + renderStore(path, Object.values(Permissions)); + fireEvent.click(screen.getByRole("button", { name: `Show ${name}` })); + const dialog = screen.getByRole("dialog", { name: title }); + expect(within(dialog).getByText(name)).toBeTruthy(); + if (path === "/targets") + expect(within(dialog).getByText("firewall-api")).toBeTruthy(); + expect(within(dialog).queryByRole("textbox")).toBeNull(); + expect( + within(dialog).queryByRole("button", { name: /Save|Create/ }), + ).toBeNull(); + fireEvent.click(within(dialog).getByRole("button", { name: "Close" })); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(fetch).not.toHaveBeenCalled(); + }, + ); }); diff --git a/src/pages/main-page/store-pages/StorePage.tsx b/src/pages/main-page/store-pages/StorePage.tsx index e21b746..5114f5e 100644 --- a/src/pages/main-page/store-pages/StorePage.tsx +++ b/src/pages/main-page/store-pages/StorePage.tsx @@ -1,24 +1,25 @@ import { NavLink, useLocation } from "react-router"; -import { useAuth } from "@/auth/AuthContext"; -import { TablePage } from "@/components"; +import { Notice, TablePage } from "@/components"; import { PATHS } from "@/utils"; -import { TableTabs } from "./StorePages.styles"; +import { ResourceNotice, TableTabs } from "./StorePages.styles"; import { CacaoResourcesPage } from "./CacaoResourcesPage"; import { SecretsPage } from "./SecretsPage"; import { RESOURCE_TABS, resourceTabAt } from "./utils"; import { VariablesPage } from "./VariablesPage"; export function StorePage() { - const { can } = useAuth(); const { pathname } = useLocation(); const active = resourceTabAt(pathname)?.path; return ( + + + - {RESOURCE_TABS.filter((tab) => can(tab.permission)).map((tab) => ( + {RESOURCE_TABS.map((tab) => ( {tab.label} diff --git a/src/pages/main-page/store-pages/StorePages.styles.tsx b/src/pages/main-page/store-pages/StorePages.styles.tsx index 6ae4edf..fc1748c 100644 --- a/src/pages/main-page/store-pages/StorePages.styles.tsx +++ b/src/pages/main-page/store-pages/StorePages.styles.tsx @@ -1,5 +1,9 @@ import styled from "styled-components"; +export const ResourceNotice = styled.div` + margin: ${({ theme }) => `${theme.spacing.md} ${theme.spacing.lg} 0`}; +`; + export const TableTabs = styled.nav` display: flex; flex-shrink: 0; diff --git a/src/pages/main-page/store-pages/VariablesPage.tsx b/src/pages/main-page/store-pages/VariablesPage.tsx index afff37c..1091369 100644 --- a/src/pages/main-page/store-pages/VariablesPage.tsx +++ b/src/pages/main-page/store-pages/VariablesPage.tsx @@ -1,39 +1,17 @@ -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import type { ColumnDef } from "@tanstack/react-table"; -import { - IconEye, - IconEyeOff, - IconPencil, - IconPlus, - IconRestore, - IconTrash, -} from "@tabler/icons-react"; -import React, { useCallback, useMemo, useState } from "react"; -import toast from "react-hot-toast"; -import styled from "styled-components"; +import { IconEye, IconEyeOff } from "@tabler/icons-react"; +import { useMemo, useState } from "react"; -import { deleteVariable, updateVariableValue } from "@/api/store"; -import { storeQueries } from "@/api/storeQueries"; -import { useAuth } from "@/auth/AuthContext"; -import { RequirePermission } from "@/auth/AuthGate"; -import { Permissions } from "@/auth/permissions"; import { Badge, Button, - CenteredCardContent, - ConfirmDialog, CopyButton, DataTable, - HeaderActions, Icon, - Notice, - QueryError, - Spinner, TableInset, ThemeSize, ThemeVariant, } from "@/components"; -import type { StoredVariable } from "@/types"; import { formatDateTime } from "@/utils"; import { @@ -41,224 +19,24 @@ import { HistoryButton, modifiedColumn, nameColumn, - ResourceHistory, ResourceToolbar, versionColumn, } from "./ResourceTable"; -import { Mono, Muted, RowActions } from "./StorePages.styles"; -import { VariableFormModal } from "./VariableFormModal"; +import { sampleVariables, type SampleVariable } from "./sampleResources"; +import { Mono, RowActions } from "./StorePages.styles"; import { matchesSearch, shortIdentity } from "./utils"; import { VersionLegend, VersionTimeline } from "./VersionTimeline"; -const RevealButton = ({ - name, - visible, - onToggle, -}: { - name: string; - visible: boolean; - onToggle: (name: string) => void; -}) => ( - -); - -const VariableValue = ({ - value, - visible, - modified, -}: { - value: string; - visible: boolean; - modified?: string; -}) => ( - - {visible ? value : "********"} - -); - -const RestoreActions = styled(RowActions)` - button:disabled { - border-color: transparent; - } -`; - -const VariableHistory = ({ - variable, - visible, -}: { - variable: StoredVariable; - visible: boolean; -}) => { - const { can } = useAuth(); - const queryClient = useQueryClient(); - const query = useQuery(storeQueries.variableVersions(variable.name)); - const versions = (query.data ?? []).toSorted((a, b) => a.version - b.version); - // Restoring writes the old value as a new version, so history stays intact. - const restore = useMutation({ - mutationFn: (value: string) => - updateVariableValue(variable.name, variable.version, value), - onSuccess: (saved) => { - toast.success(`Restored as v${saved.version}`); - }, - - onSettled: async () => { - await Promise.all([ - queryClient.invalidateQueries({ - queryKey: storeQueries.variables().queryKey, - }), - queryClient.invalidateQueries({ - queryKey: storeQueries.resolveAll(), - }), - queryClient.invalidateQueries({ - queryKey: storeQueries.variableVersions(variable.name).queryKey, - }), - ]); - }, - }); - - return ( - - {restore.error && ( - - )} - {variable.oldest_version > 1 && ( - - Versions before v{variable.oldest_version} are no longer kept. - - )} - - } - > - { - const modified = `Modified by ${v.created_by} at ${formatDateTime(v.created)}`; - const blocked = - v.value === variable.value - ? "Already the current value" - : restore.isPending - ? "Restore in progress" - : undefined; - return { - version: v.version, - current: v.current, - state: v.current ? undefined : "previous", - modifiedTitle: modified, - details: ( - - ), - action: - !v.current && can(Permissions.VariableWrite) ? ( - - - - ) : undefined, - }; - })} - /> - - ); -}; - -type Dialog = { kind: "create" } | { kind: "edit" | "delete"; name: string }; - -export const VariablesPage: React.FC = () => { - const queryClient = useQueryClient(); +export const VariablesPage = () => { const [search, setSearch] = useState(""); const [type, setType] = useState(""); - const [dialog, setDialog] = useState(); const [revealed, setRevealed] = useState>(() => new Set()); - const close = () => { - setDialog(undefined); - remove.reset(); - }; - const toggleReveal = useCallback((name: string) => { - setRevealed((previous) => { - const next = new Set(previous); - if (next.has(name)) next.delete(name); - else next.add(name); - return next; - }); - }, []); - - const variables = useQuery(storeQueries.variables()); - const activeVariable = - dialog && dialog.kind !== "create" - ? variables.data?.find((v) => v.name === dialog.name) - : undefined; - - const remove = useMutation({ - mutationFn: (name: string) => deleteVariable(name), - onSuccess: (_, name) => { - close(); - setRevealed((previous) => { - const next = new Set(previous); - next.delete(name); - return next; - }); - queryClient.removeQueries({ - queryKey: storeQueries.variableVersions(name).queryKey, - exact: true, - }); - toast.success("Variable deleted"); - }, - - onSettled: () => - Promise.all([ - queryClient.invalidateQueries({ - queryKey: storeQueries.variables().queryKey, - }), - queryClient.invalidateQueries({ - queryKey: storeQueries.resolveAll(), - }), - ]), - }); - - const types = [ - ...new Set([ - ...(variables.data ?? []).map((v) => v.type), - ...(type ? [type] : []), - ]), - ].sort(); - const rows = (variables.data ?? []).filter( - (v) => - (!type || v.type === type) && - matchesSearch(search, v.name, v.description, v.type), + const rows = sampleVariables.filter( + (variable) => + (!type || variable.type === type) && + matchesSearch(search, variable.name, variable.description, variable.type), ); - - const columns = useMemo[]>( + const columns = useMemo[]>( () => [ nameColumn(150), { @@ -275,10 +53,9 @@ export const VariablesPage: React.FC = () => { header: "Value", enableSorting: false, cell: ({ row }) => ( - + + {revealed.has(row.original.name) ? row.original.value : "********"} + ), }, descriptionColumn(150), @@ -296,91 +73,59 @@ export const VariablesPage: React.FC = () => { }, { id: "actions", - size: 180, + size: 115, header: "Actions", enableSorting: false, cell: ({ row }) => { - const v = row.original; + const variable = row.original; + const visible = revealed.has(variable.name); return ( - + - - - - ); }, }, ], - [revealed, toggleReveal], + [revealed], ); - if (variables.isLoading) - return ( - - - - ); - - if (variables.isLoadingError) - return ( - - - - ); - return ( <> variable.type)), + ].sort()} onTypeChange={setType} search={search} onSearchChange={setSearch} > - - - - - - + { label="Variables" getRowId={(variable) => variable.name} renderDetail={(variable) => ( - ({ + version: version.version, + current: version.current, + state: version.current ? undefined : "previous", + modifiedTitle: `Modified by ${version.created_by} at ${formatDateTime(version.created)}`, + details: ( + + {revealed.has(variable.name) ? version.value : "********"} + + ), + }))} /> )} initialSorting={[{ id: "name", desc: false }]} - emptyMessage={ - type - ? "No variables match the filters" - : search.trim() - ? `No variables match "${search.trim()}"` - : "No variables stored" - } + emptyMessage="No variables match the filters" /> - {dialog?.kind === "create" && } - {dialog?.kind === "edit" && activeVariable && ( - - )} - activeVariable && remove.mutate(activeVariable.name)} - /> ); }; diff --git a/src/pages/main-page/store-pages/sampleResources.ts b/src/pages/main-page/store-pages/sampleResources.ts new file mode 100644 index 0000000..4a328ca --- /dev/null +++ b/src/pages/main-page/store-pages/sampleResources.ts @@ -0,0 +1,319 @@ +import type { + CacaoFieldMapping, + CacaoResource, + CacaoResourceKind, + SecretMetadata, + SecretVersion, + StoredVariable, + StoredVariableVersion, +} from "@/types"; + +const created = "2026-01-12T09:00:00Z"; +const modified = "2026-05-10T08:00:00Z"; +const identity = "identity--demo"; + +export type SampleVariable = StoredVariable & { + versions: StoredVariableVersion[]; +}; + +const variable = ( + name: string, + type: string, + values: [string, ...string[]], + description: string, +): SampleVariable => ({ + name, + type, + value: values[values.length - 1], + description, + version: values.length, + oldest_version: 1, + created, + modified, + created_by: identity, + modified_by: identity, + versions: values.map((value, index) => ({ + version: index + 1, + value, + created: index === values.length - 1 ? modified : created, + created_by: identity, + current: index === values.length - 1, + })), +}); + +export const sampleVariables: SampleVariable[] = [ + variable( + "fw-api-user", + "string", + ["soarca", "soarca-demo"], + "Example firewall service account", + ), + variable( + "firewall-mgmt-ip", + "ipv4-addr", + ["192.0.2.10"], + "Example firewall management address", + ), + variable( + "soc-mail-domain", + "string", + ["soc.example.org"], + "Example notification domain", + ), + variable("block-max-retries", "integer", ["5", "3"], "Example retry limit"), + variable("auto-block-enabled", "bool", ["false"], "Example approval setting"), + variable( + "soc-ssh-user", + "string", + ["responder"], + "Example responder account", + ), + variable( + "web-proxy-url", + "uri", + ["https://proxy.example.org:8443"], + "Example outbound proxy", + ), + variable( + "api-timeout", + "integer", + ["30", "60"], + "Example request timeout in seconds", + ), +]; + +export type SampleSecret = SecretMetadata & { versions: SecretVersion[] }; + +const secret = ( + name: string, + kind: SecretMetadata["kind"], + description: string, + versions: [SecretVersion, ...SecretVersion[]], +): SampleSecret => ({ + name, + kind, + description, + version: versions[versions.length - 1].version, + oldest_version: versions[0].version, + created: versions[0].created, + modified: versions[versions.length - 1].created, + versions, +}); + +export const sampleSecrets: SampleSecret[] = [ + secret( + "fw-api-password", + "password", + "Example firewall credential metadata", + [ + { version: 1, created, destroyed: true }, + { version: 2, created, deleted: modified }, + { version: 3, created: modified, current: true }, + ], + ), + secret("jira-token", "token", "Example incident service token metadata", [ + { version: 1, created }, + { version: 2, created: modified, current: true }, + ]), + secret("jira-base-url", "url", "Example service URL metadata", [ + { version: 1, created, current: true }, + ]), + secret("soc-ssh-key", "ssh-private-key", "Example responder key metadata", [ + { version: 1, created, current: true }, + ]), + secret("teams-webhook", "generic", "Example deleted secret metadata", [ + { version: 1, created, current: true, deleted: modified }, + ]), + secret("legacy-kms-key", "invalid", "Example unreadable secret metadata", [ + { version: 1, created, current: true }, + ]), + secret( + "response-api-token", + "token", + "Example response platform token metadata", + [{ version: 1, created, current: true }], + ), + secret("proxy-password", "password", "Example proxy credential metadata", [ + { version: 1, created }, + { version: 2, created: modified, current: true }, + ]), +]; + +const authenticationId = "http-basic--5d2e9a71-2e78-4e16-9e00-a29b8ae01300"; +const responseAuthenticationId = "oauth2--7aa210c4-5c30-4819-8619-79f420d27016"; +const sshAuthenticationId = "private-key--a04a71f5-c681-4dfb-b4f2-f428bf1763c3"; +const proxyAuthenticationId = "user-auth--cd8f7c96-8b64-4938-83b9-7abf56a5b421"; +const targetId = "http-api--9c41e0b2-6af2-4403-8c11-bff974f62948"; + +export const sampleCacaoResources: { + [K in CacaoResourceKind]: CacaoResource[]; +} = { + "authentication-info": [ + { + version: 1, + modified, + modified_by: identity, + object: { + id: authenticationId, + type: "http-basic", + name: "firewall-api", + description: "Example firewall authentication", + }, + }, + { + version: 1, + modified, + modified_by: identity, + object: { + id: responseAuthenticationId, + type: "oauth2", + name: "response-platform-api", + description: "Example response platform token authentication", + }, + }, + { + version: 2, + modified, + modified_by: identity, + object: { + id: sshAuthenticationId, + type: "private-key", + name: "responder-ssh", + description: "Example responder SSH authentication", + }, + }, + { + version: 1, + modified, + modified_by: identity, + object: { + id: proxyAuthenticationId, + type: "user-auth", + name: "outbound-proxy", + description: "Example proxy account authentication", + }, + }, + ], + target: [ + { + version: 2, + modified, + modified_by: identity, + object: { + id: targetId, + type: "http-api", + name: "perimeter-firewall", + description: "Example firewall management API", + address: { url: ["https://firewall.example.org/api"] }, + port: "443", + authentication_info: authenticationId, + }, + }, + { + version: 1, + modified, + modified_by: identity, + object: { + id: "http-api--1dd05dc8-a0fb-4b79-a50e-053ae868dbec", + type: "http-api", + name: "response-platform", + description: "Example incident response API", + address: { url: ["https://response.example.org/api"] }, + port: "443", + authentication_info: responseAuthenticationId, + }, + }, + { + version: 3, + modified, + modified_by: identity, + object: { + id: "ssh--06950cf9-c484-4bb3-9bc5-863eddb48bdf", + type: "ssh", + name: "soc-jump-host", + description: "Example responder jump host", + address: { ipv4: ["192.0.2.25"], dname: ["jump.soc.example.org"] }, + port: "22", + authentication_info: sshAuthenticationId, + }, + }, + { + version: 1, + modified, + modified_by: identity, + object: { + id: "linux--4f44f277-b43d-4c64-b6ad-609520834ba6", + type: "linux", + name: "forensics-workstation", + description: "Example Linux investigation workstation", + address: { ipv4: ["198.51.100.40"], ipv6: ["2001:db8::40"] }, + authentication_info: sshAuthenticationId, + }, + }, + { + version: 1, + modified, + modified_by: identity, + object: { + id: "net-address--589c544f-78dc-44ca-9889-38fdf64c0a99", + type: "net-address", + name: "internal-dns", + description: "Example network service", + address: { ipv4: ["203.0.113.53"], dname: ["dns.example.org"] }, + port: "53", + }, + }, + { + version: 2, + modified, + modified_by: identity, + object: { + id: "http-api--364d7a29-77b5-48a5-b687-86dbd6632c92", + type: "http-api", + name: "outbound-web-proxy", + description: "Example outbound proxy management API", + address: { url: ["https://proxy.example.org/api"] }, + port: "8443", + authentication_info: proxyAuthenticationId, + }, + }, + ], +}; + +export const sampleFieldMappings: Record = { + [authenticationId]: { + version: 1, + modified, + modified_by: identity, + fields: { + user_id: { variable: "fw-api-user", status: "ok" }, + password: { secret: "fw-api-password", status: "ok" }, + }, + }, + [responseAuthenticationId]: { + version: 1, + modified, + modified_by: identity, + fields: { + token: { secret: "response-api-token", status: "ok" }, + }, + }, + [sshAuthenticationId]: { + version: 2, + modified, + modified_by: identity, + fields: { + username: { variable: "soc-ssh-user", status: "ok" }, + private_key: { secret: "soc-ssh-key", status: "ok" }, + }, + }, + [proxyAuthenticationId]: { + version: 1, + modified, + modified_by: identity, + fields: { + username: { variable: "fw-api-user", status: "ok" }, + password: { secret: "proxy-password", status: "ok" }, + }, + }, +}; diff --git a/src/pages/main-page/store-pages/utils.ts b/src/pages/main-page/store-pages/utils.ts index 5644d42..9165e8b 100644 --- a/src/pages/main-page/store-pages/utils.ts +++ b/src/pages/main-page/store-pages/utils.ts @@ -3,20 +3,28 @@ import { matchPath } from "react-router"; import { Permissions } from "@/auth/permissions"; import { parseDate, PATHS } from "@/utils"; -/** The tabs of the Resources page. Each has its own URL and permission. */ +/** Read-only sample tabs share the playbook reader audience. */ export const RESOURCE_TABS = [ { path: PATHS.VARIABLES, label: "Variables", - permission: Permissions.VariableRead, + permission: Permissions.PlaybookRead, + }, + { + path: PATHS.SECRETS, + label: "Secrets", + permission: Permissions.PlaybookRead, }, - { path: PATHS.SECRETS, label: "Secrets", permission: Permissions.SecretRead }, { path: PATHS.AUTHENTICATION_INFO, label: "Authentication", - permission: Permissions.AuthenticationInfoRead, + permission: Permissions.PlaybookRead, + }, + { + path: PATHS.TARGETS, + label: "Targets", + permission: Permissions.PlaybookRead, }, - { path: PATHS.TARGETS, label: "Targets", permission: Permissions.TargetRead }, ] as const; export const resourceTabAt = (pathname: string) => diff --git a/src/types/store.d.ts b/src/types/store.d.ts index c9fa283..9ec64e5 100644 --- a/src/types/store.d.ts +++ b/src/types/store.d.ts @@ -1,5 +1,4 @@ -// Secret, variable and mapping API. SOARCA does not serve these yet; in -// development the Vite mock in src/mock answers them (VITE_MOCK_STORE_API=true). +// Planned secret, variable and mapping API. Resources currently shows static samples. import type { AgentTarget, AuthenticationInformation } from "./cacao"; import type { ISODateString } from "./common"; diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index 1abd5b9..dbb4c62 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -1,8 +1,3 @@ /// declare const __APP_VERSION__: string; - -interface ImportMetaEnv { - /** "true" makes the dev server answer the secret, variable and mapping routes with mock data. */ - readonly VITE_MOCK_STORE_API?: string; -} diff --git a/vite.config.ts b/vite.config.ts index d576f7e..728a99b 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,17 +1,12 @@ import react from "@vitejs/plugin-react-swc"; import { execSync } from "child_process"; import fs from "node:fs"; -import http from "node:http"; -import https from "node:https"; import type { ServerOptions as HttpsServerOptions } from "node:https"; import path from "node:path"; import sbom from "rollup-plugin-sbom"; import { defineConfig, loadEnv, type Connect, type Plugin } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; -import { createStoreApi, isStoreRoute } from "./src/mock/storeApi"; -import type { Playbook } from "./src/types"; - // Serves config/auth-config.json at runtime, like nginx does in production, // so provider changes need no rebuild. const authConfig = (): Plugin => { @@ -34,141 +29,6 @@ const authConfig = (): Plugin => { }; }; -/** - * Answers the secret, variable, CACAO and mapping routes that SOARCA does not have - * yet (VITE_MOCK_STORE_API=true). Other /api requests still go to SOARCA. - */ -const mockStoreApi = (backendUrl: string, verifySsl: boolean): Plugin => { - const loadBackend = (route: string, authorization?: string) => - new Promise((resolve, reject) => { - const url = new URL(route, `${backendUrl.replace(/\/$/, "")}/`); - const request = (url.protocol === "https:" ? https : http).get( - url, - { - headers: authorization ? { Authorization: authorization } : {}, - rejectUnauthorized: verifySsl, - }, - (res) => { - let data = ""; - res.on("data", (chunk) => (data += chunk)); - res.on("end", () => { - if (res.statusCode === 404) return resolve(null); - if (res.statusCode !== 200) - return reject( - new Error(`Could not load playbooks: HTTP ${res.statusCode}.`), - ); - try { - resolve(JSON.parse(data) as unknown); - } catch { - reject(new Error("SOARCA returned invalid playbook JSON.")); - } - }); - }, - ); - request.on("error", reject); - }); - - const loadPlaybook = async (id: string, authorization?: string) => { - const result = await loadBackend( - `playbook/${encodeURIComponent(id)}`, - authorization, - ); - if (result === null) return null; - if (typeof result !== "object" || !("id" in result)) - throw new Error("SOARCA returned an invalid playbook."); - return result as Playbook; - }; - const loadPlaybooks = async (authorization?: string) => { - const result = await loadBackend("playbook/", authorization); - if (!Array.isArray(result)) - throw new Error("SOARCA returned an invalid playbook list."); - return result as Playbook[]; - }; - - const store = createStoreApi({ loadPlaybook, loadPlaybooks }); - - const readBody = (req: Connect.IncomingMessage) => - new Promise((resolve, reject) => { - let data = ""; - req.on("data", (chunk) => (data += chunk)); - req.on("error", reject); - req.on("end", () => { - try { - resolve(data ? JSON.parse(data) : undefined); - } catch (err) { - reject(err); - } - }); - }); - - const serve: Connect.NextHandleFunction = (req, res, next) => { - const url = new URL(req.url ?? "/", "http://localhost"); - if (!url.pathname.startsWith("/api/")) return next(); - const path = url.pathname.slice("/api".length); - const method = req.method ?? "GET"; - const deleted = method === "DELETE" && /^\/playbook\/([^/]+)$/.exec(path); - if (deleted) - res.on("finish", () => { - if (res.statusCode < 300) - store.forgetPlaybook(decodeURIComponent(deleted[1])); - }); - if (!isStoreRoute(path)) return next(); - const body = ["POST", "PUT", "PATCH"].includes(method) - ? readBody(req) - : Promise.resolve(undefined); - void body - .then((parsed) => - store.handle({ - method, - path, - query: url.searchParams, - body: parsed, - authorization: req.headers.authorization, - }), - ) - .then(async (answer) => { - const reply = answer ?? { - status: 404, - body: { - status: 404, - "original-call": url.pathname, - message: "Not found.", - }, - }; - // A short delay makes loading states visible, as with a real backend. - await new Promise((r) => setTimeout(r, 250)); - res.statusCode = reply.status; - for (const [name, value] of Object.entries(reply.headers ?? {})) - res.setHeader(name, value); - if (reply.body === undefined) return res.end(); - res.setHeader("Content-Type", "application/json"); - res.end(JSON.stringify(reply.body)); - }) - .catch((err: unknown) => { - console.error("Mock store API failed", err); - if (res.headersSent) return res.end(); - const status = err instanceof SyntaxError ? 400 : 500; - res.statusCode = status; - res.setHeader("Content-Type", "application/json"); - res.end( - JSON.stringify({ - status, - "original-call": url.pathname, - message: - status === 400 - ? "The request body must be valid JSON." - : "The mock store API failed.", - }), - ); - }); - }; - - return { - name: "soarca-mock-store-api", - configureServer: (server) => void server.middlewares.use(serve), - }; -}; - /** * Resolve the app version. */ @@ -222,17 +82,7 @@ export default defineConfig(({ mode }) => { ); return { - plugins: [ - react(), - tsconfigPaths(), - sbom(), - authConfig(), - env.VITE_MOCK_STORE_API === "true" && - mockStoreApi( - env.VITE_BACKEND_URL || "http://localhost:8080", - env.VITE_VERIFY_SSL === "true", - ), - ], + plugins: [react(), tsconfigPaths(), sbom(), authConfig()], define: { __APP_VERSION__: JSON.stringify(getAppVersion()), },