diff --git a/.env.example b/.env.example index 25c0889..58e4eb2 100644 --- a/.env.example +++ b/.env.example @@ -17,7 +17,6 @@ VITE_HTTPS_CERT_FILE= # required when VITE_ENABLE_HTTPS=true VITE_HTTPS_KEY_FILE= # required when VITE_ENABLE_HTTPS=true VITE_VERIFY_SSL=false # set true to verify the backend TLS certificate VITE_USE_POLLING=false # set true when the filesystem does not emit file events reliably -VITE_MOCK_STORE_API=false # set true to serve mock secret, variable and mapping routes until SOARCA has them ########## Docker Compose (dev) ########## # Values used by `docker-compose.dev.yml`. Compose will substitute ${VAR} from the diff --git a/README.md b/README.md index 6828e2f..513f99d 100644 --- a/README.md +++ b/README.md @@ -25,8 +25,10 @@ Firefox 119+, Safari 17.4+). API queries refetch stale data when the window regains focus or the connection returns. Scrollable pages, panels, modals and code blocks share the same thin scrollbars. -Side-panel tabs stay above the scrolling content. Native editors and text areas -keep their own scrollbars, with matching theme colors. +Side-panel tabs stay above the scrolling content. JSON editors also use the shared +Radix scroll area while retaining textarea editing and vertical resizing. +On narrow windows, the playbook workspace scrolls horizontally rather than +clipping its side panels. Each panel keeps its own vertical scrolling. ## Running the Project @@ -121,7 +123,6 @@ flowchart TB - `VITE_HTTPS_CERT_FILE` - Path to the TLS certificate used by Vite - `VITE_HTTPS_KEY_FILE` - Path to the TLS certificate key used by Vite - `VITE_VERIFY_SSL` - Set to `true` to verify the backend certificate when Vite proxies API requests -- `VITE_MOCK_STORE_API` - Set to `true` for the temporary resource and mapping endpoints (see [Mock store API](#mock-store-api)) - `DOCKER_HOST_PORT` - The port of the host machine that is mapped to the `VITE_SERVER_PORT` of the Vite dev server running in the container. This is only relevant when running the Development Container. - `HOST_PORT` - is the same of the `VITE_SERVER_PORT` if run locally or `DOCKER_HOST_PORT` if running the Development Container. @@ -173,45 +174,24 @@ flowchart TB ``` The app will be available at `http://localhost:HOST_PORT` with hot-reload enabled. -#### Mock store API - -The Resources page has tabs for stored variables, read-only secrets, -authentication and targets. The current SOARCA backend does not yet serve -these APIs. Set `VITE_MOCK_STORE_API=true` to let the development server answer -these routes with in-memory seed data: - -- `/api/secret/...`: read-only metadata and version history. Secret values are never returned. -- `/api/variable/...`: create, edit, delete and restore global variable versions. -- `/api/cacao/authentication-info/...` and `/api/cacao/target/...`: manage versioned CACAO objects and their field mappings. -- `/api/playbook/{id}/mapping` and `/api/playbook/{id}/resolve`: map external playbook variables to stored secrets and variables, and check whether a run can resolve them. The mock reads the playbook from SOARCA to know its external variables. - -All other `/api` requests still go to SOARCA. The flag also grants the -`secret:read`, `variable:read`, `variable:write`, `mapping:read`, -`mapping:write`, `authentication-info:read`, `authentication-info:write`, -`authentication-info:use`, `target:read`, `target:write` and `target:use` -permissions to signed-in users because SOARCA does not issue them yet. The -flag defaults to off, and the mock is not served by preview or production -builds. Data resets on server restart. - -Deleting a variable, target or authentication that is still in use shows -instructions to remove its mappings or references first. For these deletion -conflicts (HTTP 409), the dialog also shows the API's explanation, including -blocking references when provided. Other API errors keep their generic messages. - -In the visual editor's Variables tab, the database-plus button adds an external -variable backed by a stored variable or secret. The plus button adds an -external declaration without a stored source. A row's database-plus button -changes its source. Mappings follow the latest resource version unless a -version is pinned. The playbook is saved first; if saving its mapping fails, -the editor keeps the draft for a retry. - -The playbook Resources tab can add stored authentication and -targets, or create playbook-only objects. Adding a stored target also adds its -stored authentication when needed. The GUI copies the CACAO objects into the -playbook, but not their mappings or secret values. -Failed stored-resource checks show an error and a retry action. Adding a target -uses an existing playbook authentication copy only when the store returns 404, -not when access is denied or the request fails. +#### Resources preview + +Resources shows read-only sample variables, secret metadata, authentication and +targets in both development and production builds. A notice identifies the data +as examples, not records from SOARCA. Search, filters, version history and detail +views work without resource API requests. The samples contain no real secrets. +All Resources sample data lives in +`src/pages/main-page/store-pages/sampleResources.ts`. + +The page is available when sign-in is disabled, or to signed-in users with +`playbook:read`. This does not grant any resource API permissions. + +Stored-resource selection and mappings in playbooks are disabled until SOARCA +supports their APIs. Disabled stored-resource buttons explain this limitation. +Manual external variables and playbook-local authentication +and targets continue to work. Sample data cannot be attached to a playbook or +sent to an execution. The former development mock API and its environment flag +have been removed. ### Enable sign-in diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index e2b4574..a581701 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -20,7 +20,6 @@ services: - VITE_HTTPS_CERT_FILE=${VITE_HTTPS_CERT_FILE:-/app/certs/server.crt} - VITE_HTTPS_KEY_FILE=${VITE_HTTPS_KEY_FILE:-/app/certs/server.key} - VITE_VERIFY_SSL=${VITE_VERIFY_SSL:-false} - - VITE_MOCK_STORE_API=${VITE_MOCK_STORE_API:-false} - VITE_IS_DOCKER=true volumes: - .:/app diff --git a/src/App.tsx b/src/App.tsx index b12ccc7..869650e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -82,7 +82,7 @@ function App() { } > } /> ( } + element={ + + } > } /> diff --git a/src/auth/AuthGate.tsx b/src/auth/AuthGate.tsx index 7400d47..9e23ad9 100644 --- a/src/auth/AuthGate.tsx +++ b/src/auth/AuthGate.tsx @@ -87,9 +87,15 @@ export function AuthGate() { return ; } -export function PermissionGate({ permission }: { permission: Permission }) { - const { can } = useAuth(); - if (can(permission)) return ; +export function PermissionGate({ + permission, + allowAnonymous = false, +}: { + permission: Permission; + allowAnonymous?: boolean; +}) { + const { can, user } = useAuth(); + if (can(permission) || (allowAnonymous && user?.anonymous)) return ; return ( diff --git a/src/auth/AuthProvider.tsx b/src/auth/AuthProvider.tsx index 0af9f57..6b44afa 100644 --- a/src/auth/AuthProvider.tsx +++ b/src/auth/AuthProvider.tsx @@ -4,7 +4,6 @@ import toast from "react-hot-toast"; import { redirectToLogin } from "@/api/utils"; import { AuthContext } from "@/auth/AuthContext"; import { beginSignOut, isSigningOut, resetSigningOut } from "@/auth/oidc"; -import { MOCKED_PERMISSIONS } from "@/auth/permissions"; import { loadSession } from "@/auth/session"; export function AuthProvider({ children }: PropsWithChildren) { @@ -56,10 +55,7 @@ export function AuthProvider({ children }: PropsWithChildren) { isLoggingOut, // Only the initial check blocks; a failed background refetch keeps the cached user. isError: session.isLoadingError, - can: (permission) => - !!user && - (user.permissions.includes(permission) || - MOCKED_PERMISSIONS.includes(permission)), + can: (permission) => !!user && user.permissions.includes(permission), logout: () => { if (isSigningOut()) return; setIsLoggingOut(true); diff --git a/src/auth/permissions.ts b/src/auth/permissions.ts index 2cc3f1a..e8725f2 100644 --- a/src/auth/permissions.ts +++ b/src/auth/permissions.ts @@ -19,23 +19,7 @@ export const Permissions = { export type Permission = (typeof Permissions)[keyof typeof Permissions]; -// SOARCA does not issue the store permissions yet. While the mock store API -// answers those routes, the GUI grants them to every signed-in user. -export const MOCKED_PERMISSIONS: readonly Permission[] = - import.meta.env.DEV && - import.meta.env.MODE !== "test" && - import.meta.env.VITE_MOCK_STORE_API === "true" - ? [ - Permissions.SecretRead, - Permissions.VariableRead, - Permissions.VariableWrite, - Permissions.AuthenticationInfoRead, - Permissions.AuthenticationInfoWrite, - Permissions.AuthenticationInfoUse, - Permissions.TargetRead, - Permissions.TargetWrite, - Permissions.TargetUse, - Permissions.MappingRead, - Permissions.MappingWrite, - ] - : []; +// Resources are sample-only until SOARCA supports their APIs. +export const STORED_RESOURCES_AVAILABLE = false; +export const STORED_RESOURCES_UNAVAILABLE_MESSAGE = + "Stored resources are preview-only and cannot be used in playbooks until SOARCA supports them."; diff --git a/src/components/CodeEditor.tsx b/src/components/CodeEditor.tsx index 85f6a30..c9b8e6a 100644 --- a/src/components/CodeEditor.tsx +++ b/src/components/CodeEditor.tsx @@ -1,20 +1,28 @@ -import React from "react"; +import React, { useLayoutEffect, useRef } from "react"; import styled from "styled-components"; +import { ScrollArea } from "./ScrollArea"; + const EditorContainer = styled.div` width: 100%; margin-bottom: ${({ theme }) => theme.spacing.lg}; `; -const EditorTextarea = styled.textarea<{ +const EditorFrame = styled.div<{ $hasError?: boolean; $minHeight?: string; + $readOnly?: boolean; + $disabled?: boolean; }>` resize: vertical; + overflow: hidden; + display: flex; + flex-direction: column; + width: 100%; + height: ${({ $minHeight = "400px" }) => $minHeight}; min-height: ${({ $minHeight = "400px" }) => $minHeight}; - padding: ${({ theme }) => theme.spacing.md}; border: 2px solid ${({ theme, $hasError }) => $hasError ? theme.colors.error.border : theme.colors.border.medium}; @@ -25,23 +33,56 @@ const EditorTextarea = styled.textarea<{ background-color: ${({ theme }) => theme.colors.background.secondary}; - &:focus { + &:focus-within { border-color: ${({ theme, $hasError }) => $hasError ? theme.colors.error.border : theme.colors.info.border}; - background-color: ${({ theme }) => theme.colors.background.primary}; - outline: none; + background-color: ${({ theme, $readOnly }) => + $readOnly + ? theme.colors.background.secondary + : theme.colors.background.primary}; } - &:read-only:focus { - background-color: ${({ theme }) => theme.colors.background.secondary}; - } + ${({ theme, $disabled }) => + $disabled && + ` + cursor: not-allowed; + opacity: ${theme.interactions.disabledOpacity}; + `} +`; + +const EditorScrollArea = styled(ScrollArea)` + flex: 1; +`; + +const EditorTextarea = styled.textarea` + resize: none; + + overflow: hidden; + flex: 1 0 auto; + + width: 100%; + min-height: 0; + padding: ${({ theme }) => theme.spacing.md}; + border: none; + + font: inherit; + + background: transparent; + outline: none; &:disabled { cursor: not-allowed; - opacity: ${({ theme }) => theme.interactions.disabledOpacity}; } `; +const fitText = (textarea: HTMLTextAreaElement) => { + // Measure the text without the flex fill, so shortening it removes overflow. + textarea.style.flex = "none"; + textarea.style.height = "0px"; + textarea.style.height = `${textarea.scrollHeight}px`; + textarea.style.removeProperty("flex"); +}; + export interface CodeEditorProps extends React.HTMLAttributes { $value: string; $onChange?: (value: string) => void; @@ -85,19 +126,42 @@ export const CodeEditor: React.FC = ({ $inputId, ...rest }) => { + const ref = useRef(null); + useLayoutEffect(() => { + const textarea = ref.current; + if (!textarea) return; + fitText(textarea); + let width = textarea.clientWidth; + const observer = new ResizeObserver(() => { + if (textarea.clientWidth === width) return; + width = textarea.clientWidth; + fitText(textarea); + }); + observer.observe(textarea); + return () => observer.disconnect(); + }, [$value, placeholder]); + return ( - $onChange?.(e.target.value)} - placeholder={placeholder} - disabled={disabled} - readOnly={readOnly} - aria-required={$required || undefined} + + $readOnly={readOnly} + $disabled={disabled} + > + + $onChange?.(e.target.value)} + placeholder={placeholder} + disabled={disabled} + readOnly={readOnly} + aria-required={$required || undefined} + /> + + ); }; diff --git a/src/mock/storeApi.test.ts b/src/mock/storeApi.test.ts deleted file mode 100644 index dffbbd4..0000000 --- a/src/mock/storeApi.test.ts +++ /dev/null @@ -1,450 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import type { PlaybookResolve, StoredVariable, Variables } from "@/types"; - -import { - createStoreApi, - isStoreRoute, - MAX_VERSIONS, - validateVariableValue, - type MockPlaybook, -} from "./storeApi"; - -const PLAYBOOK = "playbook--1"; -const playbookVariables: Variables = { - __token__: { type: "string", external: true }, - __user__: { type: "string", external: true }, - __retries__: { type: "integer", external: true }, - __webhook__: { type: "string", external: true }, - __old_password__: { type: "string", external: true }, - __legacy__: { type: "string", external: true }, - __unmapped__: { type: "string", external: true }, - __internal__: { type: "string" }, -}; - -const setup = (extra: Partial = {}) => { - const playbook = { - id: PLAYBOOK, - playbook_variables: playbookVariables, - ...extra, - }; - const { handle, forgetPlaybook } = createStoreApi({ - loadPlaybook: async (id) => (id === PLAYBOOK ? playbook : null), - loadPlaybooks: async () => [playbook], - now: () => "2026-08-01T00:00:00Z", - }); - const call = async (method: string, path: string, body?: unknown) => { - const res = await handle({ - method, - path, - query: new URLSearchParams(), - body, - }); - if (!res) throw new Error(`No route for ${method} ${path}`); - return res; - }; - return Object.assign(call, { forgetPlaybook }); -}; - -describe("isStoreRoute", () => { - it("claims only the store routes", () => { - expect(isStoreRoute("/secret/")).toBe(true); - expect(isStoreRoute("/variable/fw-api-user/versions")).toBe(true); - expect(isStoreRoute("/playbook/abc/mapping")).toBe(true); - expect(isStoreRoute("/playbook/abc/resolve")).toBe(true); - expect(isStoreRoute("/cacao/authentication-info/")).toBe(true); - expect(isStoreRoute("/cacao/target/id/mapping")).toBe(true); - expect(isStoreRoute("/cacao/agent/")).toBe(false); - expect(isStoreRoute("/playbook/")).toBe(false); - expect(isStoreRoute("/playbook/abc")).toBe(false); - expect(isStoreRoute("/trigger/playbook/abc")).toBe(false); - expect(isStoreRoute("/secrets")).toBe(false); - }); - - describe("stored CACAO objects", () => { - const auth = "http-basic--test"; - const target = "http-api--test"; - - it("accepts only empty credentials and mappings valid for the authentication type", async () => { - const call = setup(); - expect( - ( - await call("POST", "/cacao/authentication-info/", { - object: { id: auth, type: "http-basic", password: "plaintext" }, - }) - ).status, - ).toBe(422); - const created = await call("POST", "/cacao/authentication-info/", { - object: { id: auth, type: "http-basic", user_id: "", password: "" }, - }); - expect(created.status).toBe(201); - expect(created.headers?.Location).toContain(auth); - expect( - ( - await call("PUT", `/cacao/authentication-info/${auth}/mapping`, { - version: 0, - fields: { token: { secret: "jira-token" } }, - }) - ).status, - ).toBe(422); - const saved = await call( - "PUT", - `/cacao/authentication-info/${auth}/mapping`, - { - version: 0, - fields: { - user_id: { variable: "fw-api-user", version: 1 }, - password: { secret: "fw-api-password", version: 1 }, - }, - }, - ); - expect(saved.status).toBe(200); - expect(saved.body).toMatchObject({ - version: 1, - fields: { - user_id: { variable: "fw-api-user", version: 1, status: "ok" }, - password: { - secret: "fw-api-password", - version: 1, - status: "destroyed", - }, - }, - }); - expect( - ( - await call("PUT", `/cacao/authentication-info/${auth}/mapping`, { - version: 0, - fields: {}, - }) - ).status, - ).toBe(409); - }); - - it("rejects a target field that is both literal and mapped and checks versions", async () => { - const call = setup(); - const object = { - id: target, - type: "http-api", - name: "Firewall", - address: { url: ["https://example.org"] }, - }; - expect((await call("POST", "/cacao/target/", { object })).status).toBe( - 201, - ); - expect( - ( - await call("PUT", `/cacao/target/${target}/mapping`, { - version: 0, - fields: { "address.url": { secret: "jira-base-url" } }, - }) - ).status, - ).toBe(422); - expect( - ( - await call("PUT", `/cacao/target/${target}`, { - version: 1, - object: { ...object, address: { url: [""] } }, - }) - ).status, - ).toBe(200); - expect( - ( - await call("PUT", `/cacao/target/${target}/mapping`, { - version: 0, - fields: { "address.url": { secret: "jira-base-url" } }, - }) - ).status, - ).toBe(200); - expect( - (await call("PUT", `/cacao/target/${target}`, { version: 2, object })) - .status, - ).toBe(422); - expect( - (await call("PUT", `/cacao/target/${target}`, { version: 1, object })) - .status, - ).toBe(409); - }); - - it("protects authentication referenced by targets and objects referenced by playbooks", async () => { - const call = setup({ - target_definitions: { - [target]: { type: "http-api", name: "Firewall" }, - }, - }); - await call("POST", "/cacao/authentication-info/", { - object: { id: auth, type: "http-basic" }, - }); - await call("POST", "/cacao/target/", { - object: { - id: target, - type: "http-api", - name: "Firewall", - authentication_info: auth, - }, - }); - expect( - (await call("DELETE", `/cacao/authentication-info/${auth}`)).status, - ).toBe(409); - expect((await call("DELETE", `/cacao/target/${target}`)).status).toBe( - 409, - ); - }); - - it("protects and retains variable versions pinned by object mappings", async () => { - const call = setup(); - await call("POST", "/cacao/target/", { - object: { id: target, type: "http-api", name: "Firewall", port: "" }, - }); - await call("PUT", `/cacao/target/${target}/mapping`, { - version: 0, - fields: { port: { variable: "soc-mail-domain", version: 1 } }, - }); - expect((await call("DELETE", "/variable/soc-mail-domain")).status).toBe( - 409, - ); - for (let version = 1; version <= MAX_VERSIONS + 2; version++) - await call("PUT", "/variable/soc-mail-domain", { - version, - value: `v${version + 1}`, - }); - const versions = (await call("GET", "/variable/soc-mail-domain/versions")) - .body as { version: number }[]; - expect(versions.map((entry) => entry.version)).toContain(1); - expect(versions).toHaveLength(MAX_VERSIONS + 1); - }); - - it("resolves stored copies, their mappings and drift without returning secret values", async () => { - const sampleAuth = "http-basic--5d2e9a71-2e78-4e16-9e00-a29b8ae01300"; - const sampleTarget = "http-api--9c41e0b2-6af2-4403-8c11-bff974f62948"; - const call = setup({ - playbook_variables: {}, - authentication_info_definitions: { - [sampleAuth]: { - type: "http-basic", - name: "firewall-api", - user_id: "", - password: "", - }, - }, - target_definitions: { - [sampleTarget]: { - type: "http-api", - name: "perimeter-firewall", - address: { url: ["https://old.example.org"] }, - port: "443", - authentication_info: sampleAuth, - }, - }, - }); - const result = (await call("GET", `/playbook/${PLAYBOOK}/resolve`)) - .body as PlaybookResolve; - expect(result.ready).toBe(true); - expect(result.authentication_info?.[0].fields).toEqual([ - { - field: "user_id", - source: { variable: "fw-api-user" }, - version: 2, - status: "ok", - }, - { - field: "password", - source: { secret: "fw-api-password" }, - version: 3, - status: "ok", - }, - ]); - expect(result.targets?.[0].warnings).toContainEqual({ - code: "drift", - field: "address.url", - }); - expect(JSON.stringify(result)).not.toContain("soarca-svc"); - }); - }); -}); - -describe("secrets", () => { - it("are read-only", async () => { - const call = setup(); - const res = await call("POST", "/secret/", { name: "x" }); - expect(res.status).toBe(405); - }); -}); - -describe("variables", () => { - it("rejects a write based on a stale version", async () => { - const call = setup(); - const res = await call("PUT", "/variable/fw-api-user", { - version: 1, - value: "someone", - }); - expect(res.status).toBe(409); - }); - - it("keeps only the last versions", async () => { - const call = setup(); - for (let version = 1; version <= MAX_VERSIONS + 2; version++) - await call("PUT", "/variable/soc-mail-domain", { - version, - value: `v${version + 1}.example.org`, - }); - const meta = (await call("GET", "/variable/soc-mail-domain")) - .body as StoredVariable; - const versions = (await call("GET", "/variable/soc-mail-domain/versions")) - .body as unknown[]; - expect(meta.version).toBe(MAX_VERSIONS + 3); - expect(versions).toHaveLength(MAX_VERSIONS); - expect(meta.oldest_version).toBe(4); - }); - - it("keeps versions that a mapping pins", async () => { - const call = setup(); - await call("PUT", `/playbook/${PLAYBOOK}/mapping`, { - version: 0, - variables: { __user__: { variable: "soc-mail-domain", version: 1 } }, - }); - for (let version = 1; version <= MAX_VERSIONS + 2; version++) - await call("PUT", "/variable/soc-mail-domain", { - version, - value: `v${version + 1}.example.org`, - }); - const versions = (await call("GET", "/variable/soc-mail-domain/versions")) - .body as { version: number }[]; - expect(versions.map((v) => v.version)).toEqual([ - 1, - ...Array.from({ length: MAX_VERSIONS }, (_, i) => i + 4), - ]); - }); - - it("rejects values that do not match the type", () => { - expect(validateVariableValue("ipv4-addr", "10.0.0.1/24")).toBeNull(); - expect(validateVariableValue("ipv4-addr", "999.1.1.1")).not.toBeNull(); - expect(validateVariableValue("uuid", "not-a-uuid")).not.toBeNull(); - expect(validateVariableValue("md5-hash", "abc")).not.toBeNull(); - expect(validateVariableValue("dictionary", "[]")).not.toBeNull(); - expect(validateVariableValue("dictionary", '{"a":"b"}')).toBeNull(); - }); - - it("does not create a version when only the description changes", async () => { - const call = setup(); - const res = await call("PATCH", "/variable/fw-api-user", { - description: "New text", - }); - expect((res.body as StoredVariable).version).toBe(2); - }); - - it("refuses to delete a variable that a mapping uses", async () => { - const call = setup(); - await call("PUT", `/playbook/${PLAYBOOK}/mapping`, { - version: 0, - variables: { __user__: { variable: "fw-api-user" } }, - }); - const res = await call("DELETE", "/variable/fw-api-user"); - expect(res.status).toBe(409); - expect((res.body as { message: string }).message).toContain(PLAYBOOK); - }); -}); - -describe("playbook mapping", () => { - it("only maps external variables, from a named source", async () => { - const call = setup(); - const internal = await call("PUT", `/playbook/${PLAYBOOK}/mapping`, { - version: 0, - variables: { __internal__: { secret: "jira-token" } }, - }); - const literal = await call("PUT", `/playbook/${PLAYBOOK}/mapping`, { - version: 0, - variables: { __token__: { value: "abc" } }, - }); - expect(internal.status).toBe(422); - expect(literal.status).toBe(422); - }); - - it("rejects a save based on a stale mapping version", async () => { - const call = setup(); - const mapping = { __token__: { secret: "jira-token" } }; - await call("PUT", `/playbook/${PLAYBOOK}/mapping`, { - version: 0, - variables: mapping, - }); - const res = await call("PUT", `/playbook/${PLAYBOOK}/mapping`, { - version: 0, - variables: mapping, - }); - expect(res.status).toBe(409); - }); - - it("rejects the second of two saves sent at the same time", async () => { - const call = setup(); - const save = () => - call("PUT", `/playbook/${PLAYBOOK}/mapping`, { - version: 0, - variables: { __token__: { secret: "jira-token" } }, - }); - const statuses = (await Promise.all([save(), save()])).map((r) => r.status); - expect(statuses.sort()).toEqual([200, 409]); - }); - - it("forgets the mapping of a deleted playbook", async () => { - const call = setup(); - await call("PUT", `/playbook/${PLAYBOOK}/mapping`, { - version: 0, - variables: { __user__: { variable: "soc-mail-domain" } }, - }); - call.forgetPlaybook(PLAYBOOK); - expect((await call("GET", `/playbook/${PLAYBOOK}/mapping`)).status).toBe( - 404, - ); - expect((await call("DELETE", "/variable/soc-mail-domain")).status).toBe( - 204, - ); - }); - - it("is not ready while an external variable is unmapped", async () => { - const call = setup(); - const resolve = (await call("GET", `/playbook/${PLAYBOOK}/resolve`)) - .body as PlaybookResolve; - expect(resolve.variables).toEqual([]); - expect(resolve.ready).toBe(false); - }); - - it("does not invent a secret type mismatch absent from the draft API", async () => { - const call = setup(); - await call("PUT", `/playbook/${PLAYBOOK}/mapping`, { - version: 0, - variables: { __retries__: { secret: "jira-token" } }, - }); - const resolve = (await call("GET", `/playbook/${PLAYBOOK}/resolve`)) - .body as PlaybookResolve; - expect(resolve.variables[0].status).toBe("ok"); - }); - - it("reports the status of every mapped source", async () => { - const call = setup(); - await call("PUT", `/playbook/${PLAYBOOK}/mapping`, { - version: 0, - variables: { - __token__: { secret: "jira-token" }, - __user__: { variable: "fw-api-user", version: 1 }, - __retries__: { variable: "soc-mail-domain" }, - __webhook__: { secret: "teams-webhook" }, - __old_password__: { secret: "fw-api-password", version: 1 }, - __legacy__: { secret: "legacy-kms-key" }, - }, - }); - const resolve = (await call("GET", `/playbook/${PLAYBOOK}/resolve`)) - .body as PlaybookResolve; - const status = Object.fromEntries( - resolve.variables.map((v) => [v.ref, [v.status, v.version]]), - ); - expect(status).toEqual({ - __token__: ["ok", 2], - __user__: ["ok", 1], - __retries__: ["type_mismatch", 1], - __webhook__: ["deleted", 1], - __old_password__: ["destroyed", 1], - __legacy__: ["invalid", undefined], - }); - expect(resolve.unmapped).toEqual(["__unmapped__"]); - expect(resolve.ready).toBe(false); - }); -}); diff --git a/src/mock/storeApi.ts b/src/mock/storeApi.ts deleted file mode 100644 index 8087778..0000000 --- a/src/mock/storeApi.ts +++ /dev/null @@ -1,1199 +0,0 @@ -import { - authenticationFields, - CREDENTIAL_FIELDS, - sameJson, - targetFieldHasLiteral, - targetNeedsAddress, -} from "../cacaoResources"; - -import type { - AgentTarget, - AgentTargets, - AuthenticationInformation, - AuthenticationInformations, - CacaoFieldMapping, - CacaoResourceKind, - MappingSource, - PlaybookMapping, - PlaybookMappingVersion, - PlaybookResolve, - ReferenceStatus, - ResolvedObject, - SecretBackend, - SecretMetadata, - SecretVersion, - StoredVariable, - StoredVariableVersion, - Variables, -} from "@/types"; - -// In-memory stand-in for the secret, variable, CACAO and mapping routes from the -// SOARCA design doc. The Vite dev server runs it (see vite.config.ts), so it -// uses only plain JavaScript and can be tested without a server. - -export const NAME_PATTERN = /^[a-z0-9][a-z0-9_.-]{0,127}$/; -export const MAX_VERSIONS = 10; - -export interface MockRequest { - method: string; - /** Path without the `/api` prefix, for example `/variable/fw-api-user`. */ - path: string; - query: URLSearchParams; - body?: unknown; - /** Passed to the playbook loader so it can ask SOARCA as the same user. */ - authorization?: string; -} - -export interface MockResponse { - status: number; - body?: unknown; - headers?: Record; -} - -export type MockPlaybook = { - id: string; - playbook_variables?: Variables; - authentication_info_definitions?: AuthenticationInformations; - target_definitions?: AgentTargets; -}; - -/** Returns the playbook, or null when it does not exist. */ -export type PlaybookLoader = ( - id: string, - authorization?: string, -) => Promise; - -interface StoreOptions { - loadPlaybook: PlaybookLoader; - loadPlaybooks: (authorization?: string) => Promise; - identity?: string; - now?: () => string; -} - -interface SecretEntry { - meta: SecretMetadata; - versions: SecretVersion[]; -} - -interface VariableEntry { - meta: StoredVariable; - versions: StoredVariableVersion[]; -} - -interface MappingEntry { - current: PlaybookMapping; - history: PlaybookMapping[]; -} - -type MockCacaoObject = Record & { - id: string; - type: string; - name?: string; -}; - -type MockCacaoResource = { - version: number; - modified: string; - modified_by: string; - object: MockCacaoObject; -}; - -interface CacaoEntry { - current: MockCacaoResource; - history: MockCacaoResource[]; - mapping?: { - current: CacaoFieldMapping; - history: CacaoFieldMapping[]; - }; -} - -const BACKEND: SecretBackend = { - type: "openbao", - production: false, - versioning: true, - max_versions: MAX_VERSIONS, - // Secrets are managed outside SOARCA, so the mock only reads them. - operations: ["list", "get"], - kinds: ["password", "token", "url", "ssh-private-key", "generic"], -}; - -const ADMIN = "identity--8a3e0f52-1b7c-4d29-9e61-0c5d2f7a4b10"; - -const json = (status: number, body?: unknown): MockResponse => ({ - status, - body, -}); - -const error = (status: number, path: string, message: string) => - json(status, { status, "original-call": `/api${path}`, message }); - -const isRecord = (value: unknown): value is Record => - typeof value === "object" && value !== null && !Array.isArray(value); - -/** True for the paths this mock owns. Everything else belongs to SOARCA. */ -export const isStoreRoute = (path: string) => - /^\/(secret|variable)(\/|$)/.test(path) || - /^\/cacao\/(authentication-info|target)(\/|$)/.test(path) || - /^\/playbook\/[^/]+\/(mapping|resolve)(\/|$)/.test(path); - -export function validateVariableValue( - type: string, - value: string, -): string | null { - switch (type) { - case "integer": - case "long": - return /^-?\d+$/.test(value) ? null : "Value must be a whole number."; - case "bool": - return value === "true" || value === "false" - ? null - : "Value must be true or false."; - case "float": - return value.trim() !== "" && Number.isFinite(Number(value)) - ? null - : "Value must be a number."; - case "ipv4-addr": { - const [ip, prefix, ...extra] = value.split("/"); - const octets = ip.split("."); - return extra.length === 0 && - octets.length === 4 && - octets.every((o) => /^\d{1,3}$/.test(o) && Number(o) <= 255) && - (prefix === undefined || (/^\d{1,2}$/.test(prefix) && +prefix <= 32)) - ? null - : "Value must be an IPv4 address."; - } - case "ipv6-addr": - return value.includes(":") && /^[0-9a-fA-F:.]+(\/\d{1,3})?$/.test(value) - ? null - : "Value must be an IPv6 address."; - case "mac-addr": - return /^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}$/.test(value) - ? null - : "Value must be a MAC address."; - case "uuid": - return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( - value, - ) - ? null - : "Value must be a UUID."; - case "hexstring": - case "hash": - return /^[0-9a-fA-F]+$/.test(value) - ? null - : "Value must contain only hexadecimal digits."; - case "md5-hash": - return /^[0-9a-fA-F]{32}$/.test(value) - ? null - : "Value must be 32 hexadecimal digits."; - case "sha256-hash": - return /^[0-9a-fA-F]{64}$/.test(value) - ? null - : "Value must be 64 hexadecimal digits."; - case "dictionary": - try { - const parsed: unknown = JSON.parse(value); - return isRecord(parsed) ? null : "Value must be a JSON object."; - } catch { - return "Value must be a JSON object."; - } - case "uri": - try { - new URL(value); - return null; - } catch { - return "Value must be an absolute URI."; - } - default: - return null; - } -} - -function seedSecrets(): SecretEntry[] { - const secret = ( - name: string, - kind: SecretMetadata["kind"], - description: string, - versions: SecretVersion[], - ): SecretEntry => { - const current = versions.find((v) => v.current) ?? versions.at(-1)!; - return { - meta: { - name, - kind, - description, - version: current.version, - oldest_version: versions[0].version, - created: versions[0].created, - modified: current.created, - }, - versions, - }; - }; - return [ - secret("fw-api-password", "password", "Perimeter firewall API user", [ - { version: 1, created: "2026-01-12T09:00:00Z", destroyed: true }, - { - version: 2, - created: "2026-03-02T14:20:00Z", - deleted: "2026-05-10T08:00:00Z", - }, - { version: 3, created: "2026-05-10T08:00:00Z", current: true }, - ]), - secret("jira-token", "token", "Jira API token for the SOC project", [ - { version: 1, created: "2026-02-01T10:00:00Z" }, - { version: 2, created: "2026-06-01T10:00:00Z", current: true }, - ]), - secret("jira-base-url", "url", "Jira instance base URL", [ - { version: 1, created: "2026-02-01T10:05:00Z", current: true }, - ]), - secret("soc-ssh-key", "ssh-private-key", "Jump host key for responders", [ - { version: 1, created: "2026-04-18T16:45:00Z", current: true }, - ]), - secret("teams-webhook", "generic", "", [ - { - version: 1, - created: "2026-04-20T12:00:00Z", - current: true, - deleted: "2026-07-01T09:30:00Z", - }, - ]), - secret("legacy-kms-key", "invalid", "Written outside SOARCA", [ - { version: 1, created: "2025-11-03T07:00:00Z", current: true }, - ]), - ]; -} - -function seedVariables(): VariableEntry[] { - const variable = ( - name: string, - type: string, - values: string[], - description: string, - created: string, - ): VariableEntry => { - const versions = values.map((value, i) => ({ - version: i + 1, - value, - created, - created_by: ADMIN, - current: i === values.length - 1 || undefined, - })); - return { - meta: { - name, - type, - value: values.at(-1)!, - description, - version: values.length, - oldest_version: 1, - created, - created_by: ADMIN, - modified: created, - modified_by: ADMIN, - }, - versions, - }; - }; - return [ - variable( - "fw-api-user", - "string", - ["soarca", "soarca-svc"], - "Firewall API service account", - "2026-01-12T09:00:00Z", - ), - variable( - "firewall-mgmt-ip", - "ipv4-addr", - ["10.20.0.1"], - "Management address of the perimeter firewall", - "2026-01-12T09:05:00Z", - ), - variable( - "soc-mail-domain", - "string", - ["soc.example.org"], - "Domain used for SOC notifications", - "2026-02-14T11:00:00Z", - ), - variable( - "block-max-retries", - "integer", - ["5", "3"], - "How often a block action is retried", - "2026-02-14T11:10:00Z", - ), - variable( - "auto-block-enabled", - "bool", - ["false"], - "Allow playbooks to block without manual approval", - "2026-05-22T15:30:00Z", - ), - variable( - "case-management-endpoint", - "string", - [ - "https://cases.example.org/api/v1/incidents/security-operations", - "https://cases.example.org/api/v2/incidents/security-operations", - "https://cases.example.org/api/v3/incidents/security-operations", - "https://cases.example.org/api/v4/incidents/security-operations", - "https://cases.example.org/api/v5/incidents/security-operations", - "https://cases.example.org/api/v6/incidents/security-operations", - "https://cases.example.org/api/v7/incidents/security-operations", - "https://cases.example.org/api/v6/incidents/security-operations", - ], - "Case management service endpoint", - "2026-05-22T15:45:00Z", - ), - variable( - "notification-template", - "string", - [ - "A security incident requires investigation by the operations team. Review the associated case for details.", - ], - "Default incident notification", - "2026-05-22T15:50:00Z", - ), - ]; -} - -export function createStoreApi({ - loadPlaybook, - loadPlaybooks, - identity = ADMIN, - now = () => new Date().toISOString(), -}: StoreOptions) { - const secrets = new Map(seedSecrets().map((s) => [s.meta.name, s])); - const variables = new Map(seedVariables().map((v) => [v.meta.name, v])); - const mappings = new Map(); - const resources: Record> = { - "authentication-info": new Map(), - target: new Map(), - }; - - const sampleAuth = "http-basic--5d2e9a71-2e78-4e16-9e00-a29b8ae01300"; - const sampleTarget = "http-api--9c41e0b2-6af2-4403-8c11-bff974f62948"; - const modified = "2026-05-10T08:00:00Z"; - resources["authentication-info"].set(sampleAuth, { - current: { - version: 1, - modified, - modified_by: identity, - object: { - id: sampleAuth, - type: "http-basic", - name: "firewall-api", - description: "Firewall API account", - user_id: "", - password: "", - }, - }, - history: [], - mapping: { - current: { - version: 1, - modified, - modified_by: identity, - fields: { - user_id: { variable: "fw-api-user" }, - password: { secret: "fw-api-password" }, - }, - }, - history: [], - }, - }); - resources.target.set(sampleTarget, { - current: { - version: 1, - modified, - modified_by: identity, - object: { - id: sampleTarget, - type: "http-api", - name: "perimeter-firewall", - description: "Firewall management API", - address: { url: ["https://firewall.example.org/api"] }, - port: "443", - authentication_info: sampleAuth, - }, - }, - history: [], - }); - - const secretStatus = (source: { - secret: string; - version?: number; - }): { status: ReferenceStatus; version?: number } => { - const entry = secrets.get(source.secret); - if (!entry) return { status: "missing" }; - if (entry.meta.kind === "invalid") return { status: "invalid" }; - const wanted = source.version ?? entry.meta.version; - const version = entry.versions.find((v) => v.version === wanted); - if (!version) return { status: "missing" }; - if (version.destroyed) return { status: "destroyed", version: wanted }; - if (version.deleted) return { status: "deleted", version: wanted }; - return { status: "ok", version: wanted }; - }; - - const variableStatus = ( - source: { variable: string; version?: number }, - type?: string, - ): { status: ReferenceStatus; version?: number } => { - const entry = variables.get(source.variable); - if (!entry) return { status: "missing" }; - const wanted = source.version ?? entry.meta.version; - if (!entry.versions.some((v) => v.version === wanted)) - return { status: "missing" }; - if (type !== undefined && entry.meta.type !== type) - return { status: "type_mismatch", version: wanted }; - return { status: "ok", version: wanted }; - }; - - const resolveSource = (source: MappingSource, type?: string) => - "secret" in source ? secretStatus(source) : variableStatus(source, type); - - const mappingsUsing = (variableName: string) => [ - ...[...mappings.entries()] - .filter(([, m]) => - Object.values(m.current.variables).some( - (s) => "variable" in s && s.variable === variableName, - ), - ) - .map(([playbookId]) => playbookId), - ...Object.values(resources).flatMap((store) => - [...store.entries()] - .filter(([, entry]) => - Object.values(entry.mapping?.current.fields ?? {}).some( - (s) => "variable" in s && s.variable === variableName, - ), - ) - .map(([id]) => id), - ), - ]; - - const parseSource = (value: unknown): MappingSource | string => { - if (!isRecord(value)) return "must be an object"; - const keys = Object.keys(value).filter((k) => k !== "version"); - if (keys.length !== 1 || !["secret", "variable"].includes(keys[0])) - return "needs exactly one of secret or variable"; - const name = value[keys[0]]; - if (typeof name !== "string" || !name) return "needs a name"; - const version = value.version; - if ( - version !== undefined && - (!Number.isInteger(version) || (version as number) < 1) - ) - return "has a version that is not a positive whole number"; - const pinned = version === undefined ? {} : { version: version as number }; - return keys[0] === "secret" - ? { secret: name, ...pinned } - : { variable: name, ...pinned }; - }; - - const validCacaoObject = ( - req: MockRequest, - kind: CacaoResourceKind, - id?: string, - existing?: CacaoEntry, - ): { value: MockCacaoObject } | { failure: MockResponse } => { - const body = isRecord(req.body) ? req.body : {}; - if (!isRecord(body.object)) - return { - failure: error(422, req.path, "object must be a CACAO object."), - }; - const object = body.object; - if (typeof object.type !== "string" || !object.type) - return { failure: error(422, req.path, "Type is required.") }; - if (existing && object.type !== existing.current.object.type) - return { - failure: error( - 422, - req.path, - "The type of a stored object cannot change.", - ), - }; - if (kind === "target" && (typeof object.name !== "string" || !object.name)) - return { failure: error(422, req.path, "Target name is required.") }; - if (object.id !== undefined && typeof object.id !== "string") - return { - failure: error(422, req.path, "The object ID must be a string."), - }; - if (id && object.id !== undefined && object.id !== id) - return { failure: error(422, req.path, "The object ID cannot change.") }; - const objectId = - id ?? object.id ?? `${object.type}--${crypto.randomUUID()}`; - if (!objectId.startsWith(`${object.type}--`)) - return { - failure: error(422, req.path, "The object ID must match its type."), - }; - if (kind === "authentication-info") { - for (const key of CREDENTIAL_FIELDS) { - if (object[key] !== undefined && object[key] !== "") - return { - failure: error( - 422, - req.path, - `Credential field ${key} must be empty.`, - ), - }; - } - } - const result = { ...object, id: objectId, type: object.type }; - if ( - kind === "target" && - Object.keys(existing?.mapping?.current.fields ?? {}).some((field) => - targetFieldHasLiteral(result, field), - ) - ) - return { - failure: error( - 422, - req.path, - "A field cannot have a value and a mapping.", - ), - }; - return { value: result }; - }; - - const mappingWithStatus = ( - mapping: CacaoFieldMapping, - ): CacaoFieldMapping => ({ - ...mapping, - fields: Object.fromEntries( - Object.entries(mapping.fields).map(([field, source]) => [ - field, - { ...source, status: resolveSource(source).status }, - ]), - ), - }); - - const putCacaoMapping = ( - req: MockRequest, - kind: CacaoResourceKind, - entry: CacaoEntry, - ) => { - const body = isRecord(req.body) ? req.body : {}; - if (!isRecord(body.fields)) - return error(422, req.path, "fields must be an object."); - const expected = entry.mapping?.current.version ?? 0; - if ((body.version ?? 0) !== expected) - return error( - 409, - req.path, - `Someone else changed this mapping. The current version is ${expected}.`, - ); - const fields: Record = {}; - for (const [field, raw] of Object.entries(body.fields)) { - const allowed = - kind === "authentication-info" - ? authenticationFields(entry.current.object.type).some( - ({ key }) => key === field, - ) - : field === "port" || /^address\.[^.]+$/.test(field); - if (!allowed) - return error( - 422, - req.path, - `Field ${field} is not valid for this type.`, - ); - if ( - kind === "target" && - targetFieldHasLiteral(entry.current.object, field) - ) - return error(422, req.path, `Field ${field} already has a value.`); - const source = parseSource(raw); - if (typeof source === "string") - return error(422, req.path, `The source for ${field} ${source}.`); - fields[field] = source; - } - const next: CacaoFieldMapping = { - version: expected + 1, - modified: now(), - modified_by: identity, - fields, - }; - entry.mapping = { - current: next, - history: entry.mapping - ? [...entry.mapping.history, entry.mapping.current].slice( - -(MAX_VERSIONS - 1), - ) - : [], - }; - return json(200, mappingWithStatus(next)); - }; - - const handleCacao = async ( - req: MockRequest, - kind: CacaoResourceKind, - parts: string[], - ): Promise => { - const store = resources[kind]; - if (parts.length === 0) { - if (req.method === "GET") { - const type = req.query.get("type"); - return json( - 200, - [...store.values()] - .map((entry) => entry.current) - .filter((entry) => !type || entry.object.type === type), - ); - } - if (req.method !== "POST") return undefined; - const validated = validCacaoObject(req, kind); - if ("failure" in validated) return validated.failure; - const object = validated.value; - if (store.has(object.id)) - return error(409, req.path, `Object '${object.id}' already exists.`); - const current: MockCacaoResource = { - version: 1, - modified: now(), - modified_by: identity, - object, - }; - store.set(object.id, { current, history: [] }); - return { - ...json(201, current), - headers: { - Location: `/cacao/${kind}/${encodeURIComponent(object.id)}`, - }, - }; - } - - const [id, route, ...tail] = parts; - const entry = store.get(id); - if (!entry) return error(404, req.path, `Object '${id}' not found.`); - if (route === "versions" && tail.length === 0 && req.method === "GET") - return json(200, [...entry.history, entry.current]); - if (route === "mapping") { - if (tail.length === 1 && tail[0] === "versions" && req.method === "GET") - return json( - 200, - entry.mapping - ? [ - ...entry.mapping.history.map(mappingWithStatus), - { ...mappingWithStatus(entry.mapping.current), current: true }, - ] - : [], - ); - if (tail.length !== 0) return undefined; - if (req.method === "GET") - return entry.mapping - ? json(200, mappingWithStatus(entry.mapping.current)) - : error(404, req.path, "This object has no mapping yet."); - if (req.method === "PUT") return putCacaoMapping(req, kind, entry); - return undefined; - } - if (route !== undefined) return undefined; - if (req.method === "GET") { - const wanted = req.query.get("version"); - const version = wanted - ? [...entry.history, entry.current].find( - (item) => item.version === Number(wanted), - ) - : entry.current; - return version - ? json(200, version) - : error(404, req.path, `Version ${wanted} is not retained.`); - } - if (req.method === "PUT") { - const body = isRecord(req.body) ? req.body : {}; - if (body.version !== entry.current.version) - return error( - 409, - req.path, - `Someone else changed this object. The current version is ${entry.current.version}.`, - ); - const validated = validCacaoObject(req, kind, id, entry); - if ("failure" in validated) return validated.failure; - const object = validated.value; - entry.history = [...entry.history, entry.current].slice( - -(MAX_VERSIONS - 1), - ); - entry.current = { - version: entry.current.version + 1, - modified: now(), - modified_by: identity, - object, - }; - return json(200, entry.current); - } - if (req.method === "DELETE") { - if (req.query.get("force") !== "true") { - const playbooks = await loadPlaybooks(req.authorization); - const references = playbooks - .filter((playbook) => - Object.hasOwn( - kind === "target" - ? (playbook.target_definitions ?? {}) - : (playbook.authentication_info_definitions ?? {}), - id, - ), - ) - .map((playbook) => playbook.id); - if (kind === "authentication-info") - references.push( - ...[...resources.target.values()] - .filter( - (target) => target.current.object.authentication_info === id, - ) - .map((target) => target.current.object.id), - ); - if (references.length) - return error( - 409, - req.path, - `This object is still referenced by: ${references.join(", ")}.`, - ); - } - store.delete(id); - return json(204); - } - return undefined; - }; - - const handleSecrets = (req: MockRequest, parts: string[]) => { - if (req.method !== "GET") - return error( - 405, - req.path, - "This secret backend is read-only. Manage secrets in OpenBao.", - ); - if (parts.length === 0) { - const kind = req.query.get("kind"); - const list = [...secrets.values()] - .map((s) => s.meta) - .filter((m) => !kind || m.kind === kind); - return json(200, list); - } - if (parts[0] === "backend" && parts.length === 1) return json(200, BACKEND); - const entry = secrets.get(parts[0]); - if (!entry) return error(404, req.path, `Secret '${parts[0]}' not found.`); - if (parts.length === 1) return json(200, entry.meta); - if (parts[1] === "versions" && parts.length === 2) - return json(200, entry.versions); - return undefined; - }; - - // Mappings that pin a version keep it, beyond the newest MAX_VERSIONS. - const pinnedVersions = (variableName: string) => - new Set( - [ - ...[...mappings.values()].flatMap((m) => - Object.values(m.current.variables), - ), - ...Object.values(resources).flatMap((store) => - [...store.values()].flatMap((entry) => - Object.values(entry.mapping?.current.fields ?? {}), - ), - ), - ].flatMap((s) => - "variable" in s && s.variable === variableName && s.version - ? [s.version] - : [], - ), - ); - - const writeVariableVersion = (entry: VariableEntry, value: string) => { - const version = entry.meta.version + 1; - const created = now(); - const all = [ - ...entry.versions.map((v) => ({ ...v, current: undefined })), - { version, value, created, created_by: identity, current: true }, - ]; - const pinned = pinnedVersions(entry.meta.name); - const newest = new Set(all.slice(-MAX_VERSIONS).map((v) => v.version)); - entry.versions = all.filter( - (v) => newest.has(v.version) || pinned.has(v.version), - ); - entry.meta = { - ...entry.meta, - value, - version, - oldest_version: entry.versions[0].version, - modified: created, - modified_by: identity, - }; - }; - - const createVariable = (req: MockRequest, body: Record) => { - const { name, type, value, description = "" } = body; - if (typeof name !== "string" || !NAME_PATTERN.test(name)) - return error( - 422, - req.path, - "Name must start with a lowercase letter or digit and use only a-z, 0-9, '_', '.' or '-' (at most 128 characters).", - ); - if (variables.has(name)) - return error(409, req.path, `Variable '${name}' already exists.`); - if (typeof type !== "string" || !type) - return error(422, req.path, "Type is required."); - if (typeof value !== "string") - return error(422, req.path, "Value must be a string."); - const invalid = validateVariableValue(type, value); - if (invalid) return error(422, req.path, invalid); - const created = now(); - const entry: VariableEntry = { - meta: { - name, - type, - value, - description: String(description), - version: 1, - oldest_version: 1, - created, - created_by: identity, - modified: created, - modified_by: identity, - }, - versions: [ - { version: 1, value, created, created_by: identity, current: true }, - ], - }; - variables.set(name, entry); - return json(201, entry.meta); - }; - - const handleVariables = (req: MockRequest, parts: string[]) => { - const body = isRecord(req.body) ? req.body : {}; - if (parts.length === 0) { - if (req.method === "GET") - return json( - 200, - [...variables.values()].map((v) => v.meta), - ); - if (req.method === "POST") return createVariable(req, body); - return undefined; - } - - const entry = variables.get(parts[0]); - if (!entry) - return error(404, req.path, `Variable '${parts[0]}' not found.`); - - if (parts.length === 2 && parts[1] === "versions" && req.method === "GET") - return json(200, entry.versions); - if (parts.length !== 1) return undefined; - - switch (req.method) { - case "GET": { - const asked = req.query.get("version"); - if (!asked) return json(200, entry.meta); - const old = entry.versions.find((v) => v.version === Number(asked)); - if (!old) - return error(404, req.path, `Version ${asked} is not retained.`); - return json(200, { - ...entry.meta, - value: old.value, - version: old.version, - }); - } - case "PUT": { - if ("type" in body && body.type !== entry.meta.type) - return error(422, req.path, "The type of a variable cannot change."); - if (body.version !== entry.meta.version) - return error( - 409, - req.path, - `Someone else changed '${entry.meta.name}'. The current version is ${entry.meta.version}.`, - ); - if (typeof body.value !== "string") - return error(422, req.path, "Value must be a string."); - const invalid = validateVariableValue(entry.meta.type, body.value); - if (invalid) return error(422, req.path, invalid); - writeVariableVersion(entry, body.value); - return json(200, entry.meta); - } - case "PATCH": { - if (typeof body.description !== "string") - return error(422, req.path, "Description must be a string."); - // Editing the description does not create a version. - entry.meta = { - ...entry.meta, - description: body.description, - modified: now(), - modified_by: identity, - }; - return json(200, entry.meta); - } - case "DELETE": { - const users = mappingsUsing(entry.meta.name); - if (users.length) - return error( - 409, - req.path, - `'${entry.meta.name}' is still mapped in: ${users.join(", ")}. Remove those mappings first.`, - ); - variables.delete(entry.meta.name); - return json(204); - } - } - return undefined; - }; - - const putMapping = async (req: MockRequest, playbookId: string) => { - const body = isRecord(req.body) ? req.body : {}; - if (!isRecord(body.variables)) - return error(422, req.path, "variables must be an object."); - const playbook = await loadPlaybook(playbookId, req.authorization); - if (!playbook) - return error(404, req.path, `Playbook '${playbookId}' not found.`); - const playbookVariables = playbook.playbook_variables ?? {}; - // Checked after the playbook loads, so a write made meanwhile is not lost. - const entry = mappings.get(playbookId); - const expected = entry?.current.version ?? 0; - if ((body.version ?? 0) !== expected) - return error( - 409, - req.path, - `Someone else changed this mapping. The current version is ${expected}.`, - ); - - const parsed: Record = {}; - for (const [ref, raw] of Object.entries(body.variables)) { - if (playbookVariables[ref]?.external !== true) - return error( - 422, - req.path, - `${ref} is not an external variable of this playbook.`, - ); - const source = parseSource(raw); - if (typeof source === "string") - return error(422, req.path, `The source for ${ref} ${source}.`); - parsed[ref] = source; - } - - const next: PlaybookMapping = { - variables: parsed, - version: expected + 1, - modified: now(), - modified_by: identity, - }; - mappings.set(playbookId, { - current: next, - history: entry - ? [...entry.history, entry.current].slice(-(MAX_VERSIONS - 1)) - : [], - }); - return json(200, next); - }; - - const handleMapping = async ( - req: MockRequest, - playbookId: string, - rest: string[], - ): Promise => { - const entry = mappings.get(playbookId); - if (rest.length === 1 && rest[0] === "versions" && req.method === "GET") { - if (!entry) return json(200, []); - const history: PlaybookMappingVersion[] = [ - ...entry.history, - { ...entry.current, current: true }, - ]; - return json(200, history); - } - if (rest.length !== 0) return undefined; - - switch (req.method) { - case "GET": - return entry - ? json(200, entry.current) - : error(404, req.path, "This playbook has no mapping yet."); - case "DELETE": - if (!entry) - return error(404, req.path, "This playbook has no mapping yet."); - mappings.delete(playbookId); - return json(204); - case "PUT": - return putMapping(req, playbookId); - } - return undefined; - }; - - const handleResolve = async ( - req: MockRequest, - playbookId: string, - ): Promise => { - const playbook = await loadPlaybook(playbookId, req.authorization); - if (!playbook) - return error(404, req.path, `Playbook '${playbookId}' not found.`); - const playbookVariables = playbook.playbook_variables ?? {}; - const mapped = mappings.get(playbookId)?.current.variables ?? {}; - const resolved = Object.entries(mapped).map(([ref, source]) => { - const variable = playbookVariables[ref]; - const result = - variable?.external === true - ? resolveSource(source, variable.type) - : { status: "missing" as const }; - return { ref, source, ...result }; - }); - const unmapped = Object.entries(playbookVariables) - .filter(([ref, v]) => v.external === true && !(ref in mapped)) - .map(([ref]) => ref); - const resolveObject = ( - kind: CacaoResourceKind, - ref: string, - copy: AuthenticationInformation | AgentTarget, - ): ResolvedObject | undefined => { - const entry = resources[kind].get(ref); - if (!entry) return undefined; - const object = entry.current.object; - const fieldMappings = entry.mapping?.current.fields ?? {}; - const fields = Object.entries(fieldMappings).map(([field, source]) => ({ - field, - source, - ...resolveSource(source), - })); - const missing: string[] = []; - if (kind === "authentication-info") { - for (const { key } of authenticationFields(object.type)) - if (!fieldMappings[key]) missing.push(`${ref}.${key}`); - } else { - const address = isRecord(object.address) ? object.address : {}; - for (const key of Object.keys(address)) { - const field = `address.${key}`; - if (!targetFieldHasLiteral(object, field) && !fieldMappings[field]) - missing.push(`${ref}.${field}`); - } - if ( - targetNeedsAddress(object.type) && - !Object.keys(address).some( - (key) => - targetFieldHasLiteral(object, `address.${key}`) || - !!fieldMappings[`address.${key}`], - ) && - !missing.some((field) => field.startsWith(`${ref}.address.`)) - ) - missing.push(`${ref}.address`); - if (object.port === "" && !fieldMappings.port) - missing.push(`${ref}.port`); - if ( - typeof object.authentication_info === "string" && - resources["authentication-info"].has(object.authentication_info) && - !playbook.authentication_info_definitions?.[ - object.authentication_info - ] - ) - missing.push(`${ref}.authentication_info`); - } - unmapped.push(...missing); - const warnings: NonNullable = - cacaoDriftFields(kind, copy, object, fieldMappings).map((field) => ({ - code: "drift", - field, - })); - return { - ref, - name: typeof object.name === "string" ? object.name : ref, - version: entry.current.version, - status: - copy.type !== object.type - ? "type_mismatch" - : missing.length - ? "incomplete" - : "ok", - ...(warnings.length ? { warnings } : {}), - fields, - }; - }; - const authenticationInfo = Object.entries( - playbook.authentication_info_definitions ?? {}, - ).flatMap(([ref, copy]) => { - const result = resolveObject("authentication-info", ref, copy); - return result ? [result] : []; - }); - const targets = Object.entries(playbook.target_definitions ?? {}).flatMap( - ([ref, copy]) => { - const result = resolveObject("target", ref, copy); - return result ? [result] : []; - }, - ); - const result: PlaybookResolve = { - playbook_id: playbookId, - ready: - resolved.every((v) => v.status === "ok") && - [...authenticationInfo, ...targets].every( - (object) => - object.status === "ok" && - object.fields.every((field) => field.status === "ok"), - ) && - unmapped.length === 0, - variables: resolved, - authentication_info: authenticationInfo, - targets, - unmapped, - }; - return json(200, result); - }; - - /** Answers a store route, or returns undefined so the request goes on to SOARCA. */ - async function handle(req: MockRequest): Promise { - if (!isStoreRoute(req.path)) return undefined; - const parts = req.path.split("/").filter(Boolean).map(decodeURIComponent); - const [group, ...rest] = parts; - if (group === "secret") return handleSecrets(req, rest); - if (group === "variable") return handleVariables(req, rest); - if ( - group === "cacao" && - (rest[0] === "authentication-info" || rest[0] === "target") - ) - return handleCacao(req, rest[0], rest.slice(1)); - if (group === "playbook" && rest.length >= 2) { - const [playbookId, route, ...tail] = rest; - if (route === "mapping") return handleMapping(req, playbookId, tail); - if (route === "resolve" && tail.length === 0 && req.method === "GET") - return handleResolve(req, playbookId); - } - return undefined; - } - - /** Deleting a playbook deletes its mapping. */ - const forgetPlaybook = (playbookId: string) => mappings.delete(playbookId); - - return { handle, forgetPlaybook }; -} - -/** Fields where a playbook's copy differs from the stored object, ignoring mapped fields. */ -const cacaoDriftFields = ( - kind: "authentication-info" | "target", - copy: unknown, - stored: unknown, - mappings: Record, -) => { - if (!isRecord(copy) || !isRecord(stored)) return []; - const drift = ["name", "description"].filter( - (field) => (copy[field] ?? "") !== (stored[field] ?? ""), - ); - if (kind !== "target") return drift; - const oldAddress = isRecord(copy.address) ? copy.address : {}; - const newAddress = isRecord(stored.address) ? stored.address : {}; - for (const type of new Set([ - ...Object.keys(oldAddress), - ...Object.keys(newAddress), - ])) { - const field = `address.${type}`; - if ( - !Object.hasOwn(mappings, field) && - !sameJson(oldAddress[type] ?? [], newAddress[type] ?? []) - ) - drift.push(field); - } - if ( - !Object.hasOwn(mappings, "port") && - (copy.port ?? "") !== (stored.port ?? "") - ) - drift.push("port"); - const compared = new Set([ - "id", - "type", - "name", - "description", - "address", - "port", - ]); - for (const field of new Set([...Object.keys(copy), ...Object.keys(stored)])) { - if (!compared.has(field) && !sameJson(copy[field], stored[field])) - drift.push(field); - } - return drift; -}; diff --git a/src/pages/main-page/MainPage.test.tsx b/src/pages/main-page/MainPage.test.tsx index 324969d..f769cfc 100644 --- a/src/pages/main-page/MainPage.test.tsx +++ b/src/pages/main-page/MainPage.test.tsx @@ -11,6 +11,7 @@ import { MemoryRouter, Route, Routes } from "react-router"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { AuthContext } from "@/auth/AuthContext"; +import { Permissions } from "@/auth/permissions"; import { ThemeModeProvider } from "@/theme"; import { ThemedApp } from "@/theme/ThemedApp"; import { MainPage } from "./MainPage"; @@ -53,6 +54,7 @@ it("keeps the account menu and settings theme controls in sync", () => { const client = new QueryClient({ defaultOptions: { queries: { retry: false } }, }); + render( @@ -122,3 +124,42 @@ it("keeps the account menu and settings theme controls in sync", () => { fireEvent.click(logoutButton); expect(logout).toHaveBeenCalledOnce(); }); + +it.each([ + { anonymous: true, playbookReader: false, visible: true }, + { anonymous: false, playbookReader: true, visible: true }, + { anonymous: false, playbookReader: false, visible: false }, +])( + "shows the sample Resources navigation for $anonymous anonymous / $playbookReader playbook reader", + ({ anonymous, playbookReader, visible }) => { + render( + + + + playbookReader && permission === Permissions.PlaybookRead, + logout: vi.fn(), + retry: vi.fn(), + }} + > + + + + + + , + ); + expect(screen.queryByText("Resources") !== null).toBe(visible); + }, +); diff --git a/src/pages/main-page/MainPage.tsx b/src/pages/main-page/MainPage.tsx index f7377c8..01d12cf 100644 --- a/src/pages/main-page/MainPage.tsx +++ b/src/pages/main-page/MainPage.tsx @@ -62,6 +62,7 @@ import { ThemeModeControl } from "./ThemeModeControl"; interface NavRoute { label: string; icon: TablerIcon; + allowAnonymous?: boolean; /** The item opens the first permitted page and is active on any of them. */ pages: readonly { path: string; permission?: Permission }[]; } @@ -82,7 +83,12 @@ const NAV_ROUTES: NavRoute[] = [ { path: PATHS.MONITORING.BASE, permission: Permissions.PlaybookRead }, ], }, - { label: "Resources", icon: IconStack2, pages: RESOURCE_TABS }, + { + label: "Resources", + icon: IconStack2, + pages: RESOURCE_TABS, + allowAnonymous: true, + }, { label: "Settings", icon: IconSettings, pages: [{ path: PATHS.SETTINGS }] }, ]; @@ -141,7 +147,10 @@ export const MainPage: React.FC = () => { {!auth.isLoading && NAV_ROUTES.map((route) => { const target = route.pages.find( - (page) => !page.permission || auth.can(page.permission), + (page) => + (route.allowAnonymous && auth.user?.anonymous) || + !page.permission || + auth.can(page.permission), ); if (!target) return null; return ( diff --git a/src/pages/main-page/playbooks-page/PlaybookCreatePage.tsx b/src/pages/main-page/playbooks-page/PlaybookCreatePage.tsx index 5031361..56642fb 100644 --- a/src/pages/main-page/playbooks-page/PlaybookCreatePage.tsx +++ b/src/pages/main-page/playbooks-page/PlaybookCreatePage.tsx @@ -86,7 +86,7 @@ export const PlaybookCreatePage: React.FC = () => { - 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/PlaybookVisualCreatePage.test.tsx b/src/pages/main-page/playbooks-page/PlaybookVisualCreatePage.test.tsx index 1890ed7..c55cc8e 100644 --- a/src/pages/main-page/playbooks-page/PlaybookVisualCreatePage.test.tsx +++ b/src/pages/main-page/playbooks-page/PlaybookVisualCreatePage.test.tsx @@ -17,6 +17,13 @@ import { PlaybookVisualCreatePage } from "./PlaybookVisualCreatePage"; const navigate = vi.fn(); const saveFailed = vi.fn(); +const features = vi.hoisted(() => ({ storedResources: true })); +vi.mock("@/auth/permissions", async (importOriginal) => ({ + ...(await importOriginal()), + get STORED_RESOURCES_AVAILABLE() { + return features.storedResources; + }, +})); vi.mock("react-router", () => ({ useNavigate: () => navigate })); vi.mock("react-hot-toast", () => ({ default: { success: vi.fn(), error: vi.fn() }, @@ -58,9 +65,26 @@ vi.mock("./workspace/PlaybookWorkspace", () => ({ afterEach(() => { cleanup(); vi.resetAllMocks(); + features.storedResources = true; }); describe("PlaybookVisualCreatePage", () => { + it("rejects mapping changes before saving a playbook while resource integration is disabled", async () => { + features.storedResources = false; + render( + + + , + ); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(saveFailed).toHaveBeenCalled()); + expect((saveFailed.mock.calls[0][0] as Error).message).toBe( + "Stored resource mappings are not available yet.", + ); + expect(createPlaybook).not.toHaveBeenCalled(); + expect(savePlaybookMapping).not.toHaveBeenCalled(); + }); + it("retries a failed mapping without creating a second playbook", async () => { vi.mocked(createPlaybook).mockResolvedValue({ id: "playbook--saved", 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/theme/GlobalStyles.ts b/src/theme/GlobalStyles.ts index 80856f2..e5ee7c0 100644 --- a/src/theme/GlobalStyles.ts +++ b/src/theme/GlobalStyles.ts @@ -57,12 +57,6 @@ export const GlobalStyles = createGlobalStyle` transition: background-color 0.2s ease, color 0.2s ease; } - /* Native scrollbars that remain, e.g. in text areas and the code editor. */ - * { - scrollbar-color: ${({ theme }) => theme.colors.primary.main} transparent; - scrollbar-width: thin; - } - @media (prefers-reduced-motion: reduce) { *, *::before, 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/utils.ts b/src/utils.ts index f2bf53e..03f7f22 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -16,7 +16,7 @@ export const PATHS = { DETAIL: "/playbooks/:playbookId", EDIT_JSON: "/playbooks/:playbookId/edit-json", NEW: "/playbooks/new", - UPLOAD: "/playbooks/upload", + IMPORT: "/playbooks/import", }, MONITORING: { BASE: "/monitoring", 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()), },