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 = () => {