From 46e0015ad813004b450610af45ece0a6bfb4e90d Mon Sep 17 00:00:00 2001 From: Paul2803k Date: Mon, 30 Nov 2026 23:33:13 +0100 Subject: [PATCH 1/3] Centralize reduced-motion and base CSS resets in GlobalStyles --- src/components/CodeBlock.tsx | 1 - src/components/Link.tsx | 1 - src/components/Sidebar.tsx | 1 - src/pages/LoginPage.tsx | 7 ------- .../PlaybookDetailPage.styles.tsx | 10 ---------- .../visual-editor/pages/VisualEditor.styles.tsx | 10 ---------- .../visual-editor/panels/Panel.styles.tsx | 5 ----- src/theme/GlobalStyles.ts | 15 +++++++++++++++ 8 files changed, 15 insertions(+), 35 deletions(-) diff --git a/src/components/CodeBlock.tsx b/src/components/CodeBlock.tsx index c1dd3855..d1eafcc6 100644 --- a/src/components/CodeBlock.tsx +++ b/src/components/CodeBlock.tsx @@ -22,7 +22,6 @@ const Frame = styled(ScrollArea)<{ $maxHeight?: string }>` const Pre = styled.pre<{ $copyable?: boolean }>` counter-reset: line; - margin: 0; padding: ${({ theme }) => theme.spacing.sm} 0; padding-right: ${({ $copyable }) => ($copyable ? "2.5rem" : 0)}; diff --git a/src/components/Link.tsx b/src/components/Link.tsx index c3f792ec..572125b7 100644 --- a/src/components/Link.tsx +++ b/src/components/Link.tsx @@ -8,7 +8,6 @@ const StyledLink = styled.a<{ $subtle?: boolean }>` align-items: center; font: ${({ theme }) => theme.typography.body.font}; - text-decoration: none; ${({ $subtle, theme }) => $subtle ? ` diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx index 18be1cca..9d04eeb2 100644 --- a/src/components/Sidebar.tsx +++ b/src/components/Sidebar.tsx @@ -143,7 +143,6 @@ export const NavItem = styled.a<{ $isActive?: boolean }>` font: ${({ theme }) => theme.typography.bodyMedium.font}; color: ${({ theme }) => theme.colors.text.secondary}; - text-decoration: none; transition: color ${({ theme }) => theme.transitions.base}, diff --git a/src/pages/LoginPage.tsx b/src/pages/LoginPage.tsx index bf29d333..2a4b381a 100644 --- a/src/pages/LoginPage.tsx +++ b/src/pages/LoginPage.tsx @@ -267,13 +267,6 @@ const ProviderButton = styled(Button)` pointer-events: none; opacity: ${({ theme }) => theme.interactions.disabledOpacity}; } - - @media (prefers-reduced-motion: reduce) { - .provider-arrow { - transform: none; - transition: none; - } - } `; const ProviderIdentity = styled.span` diff --git a/src/pages/main-page/playbooks-page/playbook-detail-page/PlaybookDetailPage.styles.tsx b/src/pages/main-page/playbooks-page/playbook-detail-page/PlaybookDetailPage.styles.tsx index 48c47a63..5d67d2c2 100644 --- a/src/pages/main-page/playbooks-page/playbook-detail-page/PlaybookDetailPage.styles.tsx +++ b/src/pages/main-page/playbooks-page/playbook-detail-page/PlaybookDetailPage.styles.tsx @@ -36,8 +36,6 @@ export const TitleRow = styled.div` export const PageTitle = styled.h2` overflow: hidden; - margin: 0; - font: ${({ theme }) => theme.typography.h2.font}; color: ${({ theme }) => theme.colors.text.primary}; text-overflow: ellipsis; @@ -64,10 +62,6 @@ export const DetailBody = styled.div<{ min-height: 0; transition: grid-template-columns ${({ theme }) => theme.transitions.base}; - - @media (prefers-reduced-motion: reduce) { - transition: none; - } `; export const DiagramFrame = styled.div` @@ -92,7 +86,6 @@ export const FieldGrid = styled.dl` display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: ${({ theme }) => theme.spacing.lg}; - margin: 0; `; export const Field = styled.div<{ $wide?: boolean }>` @@ -110,7 +103,6 @@ export const FieldLabel = styled.dt` `; export const FieldValue = styled.dd` - margin: 0; font: ${({ theme }) => theme.typography.body.font}; color: ${({ theme }) => theme.colors.text.primary}; `; @@ -149,14 +141,12 @@ export const ReferenceItem = styled.div` `; export const Description = styled.p` - margin: 0; font: ${({ theme }) => theme.typography.body.font}; color: ${({ theme }) => theme.colors.text.primary}; white-space: pre-line; `; export const EmptyText = styled.p` - margin: 0; font: ${({ theme }) => theme.typography.caption.font}; color: ${({ theme }) => theme.colors.text.secondary}; `; diff --git a/src/pages/main-page/playbooks-page/visual-editor/pages/VisualEditor.styles.tsx b/src/pages/main-page/playbooks-page/visual-editor/pages/VisualEditor.styles.tsx index d84f6fa3..c9fba4c3 100644 --- a/src/pages/main-page/playbooks-page/visual-editor/pages/VisualEditor.styles.tsx +++ b/src/pages/main-page/playbooks-page/visual-editor/pages/VisualEditor.styles.tsx @@ -9,10 +9,6 @@ const PANEL_BORDERS_WIDTH = "2px"; const fadeWhenCollapsed = css<{ $collapsed: boolean }>` opacity: ${({ $collapsed }) => ($collapsed ? 0 : 1)}; transition: opacity ${({ theme }) => theme.transitions.base}; - - @media (prefers-reduced-motion: reduce) { - transition: none; - } `; export const EditorScroll = styled(ScrollArea)` @@ -37,10 +33,6 @@ export const EditorLayout = styled.div<{ padding: ${({ theme }) => theme.spacing.lg}; transition: grid-template-columns ${({ theme }) => theme.transitions.base}; - - @media (prefers-reduced-motion: reduce) { - transition: none; - } `; export const EditorFallback = styled.div` @@ -56,7 +48,6 @@ export const Toolbar = styled.div` export const ToolbarTitle = styled.h2` flex: 1; - margin: 0; font: ${({ theme }) => theme.typography.h2.font}; color: ${({ theme }) => theme.colors.text.primary}; `; @@ -115,7 +106,6 @@ export const SidePanelTitle = styled.h3` align-items: center; min-width: 0; - margin: 0; font: ${({ theme }) => theme.typography.h3.font}; color: ${({ theme }) => theme.colors.text.primary}; diff --git a/src/pages/main-page/playbooks-page/visual-editor/panels/Panel.styles.tsx b/src/pages/main-page/playbooks-page/visual-editor/panels/Panel.styles.tsx index 53198212..8e59b23b 100644 --- a/src/pages/main-page/playbooks-page/visual-editor/panels/Panel.styles.tsx +++ b/src/pages/main-page/playbooks-page/visual-editor/panels/Panel.styles.tsx @@ -28,13 +28,11 @@ export const SectionTitle = styled.div` `; export const Hint = styled.p` - margin: 0; font: ${({ theme }) => theme.typography.caption.font}; color: ${({ theme }) => theme.colors.text.tertiary}; `; export const IssueList = styled.ul` - margin: 0; padding-left: ${({ theme }) => theme.spacing.lg}; font: ${({ theme }) => theme.typography.caption.font}; `; @@ -152,11 +150,8 @@ export const IssueCount = styled.span<{ $blocking: boolean }>` `; export const EntryList = styled.ul` - margin: 0; - padding: 0; border: 1px solid ${({ theme }) => theme.colors.border.light}; border-radius: ${({ theme }) => theme.radius.md}; - list-style: none; `; diff --git a/src/theme/GlobalStyles.ts b/src/theme/GlobalStyles.ts index d0ae3327..cc0f9c81 100644 --- a/src/theme/GlobalStyles.ts +++ b/src/theme/GlobalStyles.ts @@ -18,6 +18,10 @@ export const GlobalStyles = createGlobalStyle` background: none; } + a { + text-decoration: none; + } + /* Headings are chosen for document structure; their look comes from theme.typography. */ h1, h2, h3, h4, h5, h6 { font-size: inherit; @@ -54,4 +58,15 @@ export const GlobalStyles = createGlobalStyle` scrollbar-color: ${({ theme }) => theme.colors.primary.main} transparent; scrollbar-width: thin; } + + @media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + scroll-behavior: auto !important; + transition-duration: 0.01ms !important; + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + } + } `; From d95e21e34a1e46670d48eea306269c4daef21789 Mon Sep 17 00:00:00 2001 From: Paul2803k Date: Tue, 1 Dec 2026 00:09:35 +0100 Subject: [PATCH 2/3] Replace native Select with SearchSelect, add DataTable and store API client --- .env.example | 1 + README.md | 19 + docker-compose.dev.yml | 1 + package-lock.json | 34 ++ package.json | 1 + src/api/store.ts | 64 +++ src/api/storeQueries.ts | 28 ++ src/auth/AuthProvider.tsx | 6 +- src/auth/permissions.ts | 16 + src/cacaoResources.ts | 18 + src/components/Containers.tsx | 4 - src/components/CopyButton.tsx | 6 +- src/components/DataTable.tsx | 354 ++++++++++++++ src/components/Form.tsx | 136 +----- src/components/SearchSelect.tsx | 4 + src/components/VariableInput.test.ts | 73 +++ src/components/VariableInput.tsx | 134 +++-- src/components/index.ts | 1 + src/mock/storeApi.test.ts | 117 +++++ src/mock/storeApi.ts | 458 ++++++++++++++++++ .../visual-editor/model/specs/cacao-2.0.ts | 21 +- .../visual-editor/panels/PlaybookPanel.tsx | 16 +- src/theme/theme.ts | 20 + src/types/index.ts | 1 + src/types/store.d.ts | 81 ++++ src/vite-env.d.ts | 5 + vite.config.ts | 90 +++- 27 files changed, 1503 insertions(+), 206 deletions(-) create mode 100644 src/api/store.ts create mode 100644 src/api/storeQueries.ts create mode 100644 src/cacaoResources.ts create mode 100644 src/components/DataTable.tsx create mode 100644 src/components/VariableInput.test.ts create mode 100644 src/mock/storeApi.test.ts create mode 100644 src/mock/storeApi.ts create mode 100644 src/types/store.d.ts diff --git a/.env.example b/.env.example index 58e4eb26..6628138d 100644 --- a/.env.example +++ b/.env.example @@ -17,6 +17,7 @@ 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 and variable 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 2c7433a5..0cf68a18 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,7 @@ 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 Resources page's temporary secret and variable 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. @@ -172,6 +173,24 @@ flowchart TB ``` The app will be available at `http://localhost:HOST_PORT` with hot-reload enabled. +#### Mock store API + +The Resources page groups global variables and read-only secrets into two tabs. +SOARCA does not serve this API yet. 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. + +All other `/api` requests still go to SOARCA. The flag also grants +`secret:read`, `variable:read` and `variable:write` to signed-in users because +SOARCA does not issue those permissions yet. The flag defaults to off, and the +mock is not served by preview or production builds. Data resets on server restart. + +Playbook mappings, resolution and changes to execution inputs are not included +yet. How global, external and step variables work together still needs planning. +Existing playbook inputs keep their behavior. + ### Enable sign-in The GUI reads its login providers from `/auth-config.json`, a file you deploy diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index a5817011..e2b4574c 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -20,6 +20,7 @@ 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/package-lock.json b/package-lock.json index af7fe23d..6c332f2e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "@radix-ui/react-scroll-area": "^1.4.0", "@tabler/icons-react": "^3.49.0", "@tanstack/react-query": "^5.108.4", + "@tanstack/react-table": "^8.21.3", "@xyflow/react": "^12.12.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", @@ -3178,6 +3179,39 @@ } } }, + "node_modules/@tanstack/react-table": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/@tanstack/react-table/-/react-table-8.21.3.tgz", + "integrity": "sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww==", + "license": "MIT", + "dependencies": { + "@tanstack/table-core": "8.21.3" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": ">=16.8", + "react-dom": ">=16.8" + } + }, + "node_modules/@tanstack/table-core": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/@tanstack/table-core/-/table-core-8.21.3.tgz", + "integrity": "sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, "node_modules/@testing-library/dom": { "version": "10.4.2", "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", diff --git a/package.json b/package.json index a4662da7..01624d1b 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "@radix-ui/react-scroll-area": "^1.4.0", "@tabler/icons-react": "^3.49.0", "@tanstack/react-query": "^5.108.4", + "@tanstack/react-table": "^8.21.3", "@xyflow/react": "^12.12.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", diff --git a/src/api/store.ts b/src/api/store.ts new file mode 100644 index 00000000..3fe0291b --- /dev/null +++ b/src/api/store.ts @@ -0,0 +1,64 @@ +import type { + NewStoredVariable, + SecretBackend, + SecretMetadata, + SecretVersion, + StoredVariable, + StoredVariableVersion, +} from "@/types"; +import { + deleteToApi, + fetchFromApi, + HttpMutationMethod, + mutationToApi, +} from "./utils"; + +const segment = (value: string) => encodeURIComponent(value); + +export const getSecretBackend = () => + fetchFromApi(`/api/secret/backend`); + +export const getSecrets = () => fetchFromApi(`/api/secret/`); + +export const getSecretVersions = (secret: string) => + fetchFromApi(`/api/secret/${segment(secret)}/versions`); + +export const getVariables = () => + fetchFromApi(`/api/variable/`); + +export const getVariableVersions = (variable: string) => + fetchFromApi( + `/api/variable/${segment(variable)}/versions`, + ); + +export const createVariable = (variable: NewStoredVariable) => + mutationToApi( + HttpMutationMethod.POST, + `/api/variable/`, + variable, + ); + +/** Writes a new version. `version` is the one the user saw; a stale one gives 409. */ +export const updateVariableValue = ( + variable: string, + version: number, + value: string, +) => + mutationToApi( + HttpMutationMethod.PUT, + `/api/variable/${segment(variable)}`, + { version, value }, + ); + +export const updateVariableDescription = ( + variable: string, + description: string, +) => + mutationToApi( + HttpMutationMethod.PATCH, + `/api/variable/${segment(variable)}`, + { description }, + ); + +export const deleteVariable = (variable: string) => + deleteToApi(`/api/variable/${segment(variable)}`); diff --git a/src/api/storeQueries.ts b/src/api/storeQueries.ts new file mode 100644 index 00000000..25505506 --- /dev/null +++ b/src/api/storeQueries.ts @@ -0,0 +1,28 @@ +import { queryOptions } from "@tanstack/react-query"; + +import { + getSecretBackend, + getSecrets, + getSecretVersions, + getVariables, + getVariableVersions, +} from "./store"; + +/** Every component that reads the store uses these, so keys and caching match. */ +export const storeQueries = { + secretBackend: () => + queryOptions({ queryKey: ["secret-backend"], queryFn: getSecretBackend }), + secrets: () => queryOptions({ queryKey: ["secrets"], queryFn: getSecrets }), + secretVersions: (secret: string) => + queryOptions({ + queryKey: ["secret", secret, "versions"], + queryFn: () => getSecretVersions(secret), + }), + variables: () => + queryOptions({ queryKey: ["variables"], queryFn: getVariables }), + variableVersions: (variable: string) => + queryOptions({ + queryKey: ["variable", variable, "versions"], + queryFn: () => getVariableVersions(variable), + }), +}; diff --git a/src/auth/AuthProvider.tsx b/src/auth/AuthProvider.tsx index ff611a5b..5097c2a4 100644 --- a/src/auth/AuthProvider.tsx +++ b/src/auth/AuthProvider.tsx @@ -4,6 +4,7 @@ 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) { @@ -50,7 +51,10 @@ export function AuthProvider({ children }: PropsWithChildren) { isLoading: session.isLoading, // Only the initial check blocks; a failed background refetch keeps the cached user. isError: session.isLoadingError, - can: (permission) => user?.permissions.includes(permission) ?? false, + can: (permission) => + !!user && + (user.permissions.includes(permission) || + MOCKED_PERMISSIONS.includes(permission)), logout: () => { if (isSigningOut()) return; void beginSignOut().then( diff --git a/src/auth/permissions.ts b/src/auth/permissions.ts index 248d99ad..28695ff6 100644 --- a/src/auth/permissions.ts +++ b/src/auth/permissions.ts @@ -3,6 +3,22 @@ export const Permissions = { PlaybookRead: "playbook:read", PlaybookWrite: "playbook:write", PlaybookExecute: "playbook:execute", + SecretRead: "secret:read", + VariableRead: "variable:read", + VariableWrite: "variable:write", } as const; 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, + ] + : []; diff --git a/src/cacaoResources.ts b/src/cacaoResources.ts new file mode 100644 index 00000000..648ae176 --- /dev/null +++ b/src/cacaoResources.ts @@ -0,0 +1,18 @@ +/** CACAO 2.0 variable-type-ov values. */ +export const VARIABLE_TYPES = [ + "bool", + "dictionary", + "float", + "hexstring", + "integer", + "ipv4-addr", + "ipv6-addr", + "long", + "mac-addr", + "hash", + "md5-hash", + "sha256-hash", + "string", + "uri", + "uuid", +] as const; diff --git a/src/components/Containers.tsx b/src/components/Containers.tsx index 871b857c..96b9a8e5 100644 --- a/src/components/Containers.tsx +++ b/src/components/Containers.tsx @@ -57,8 +57,4 @@ export const HeaderActions = styled.div` width: 15rem; max-width: 100%; } - - > select { - width: 9rem; - } `; diff --git a/src/components/CopyButton.tsx b/src/components/CopyButton.tsx index f2c534f2..4c4a006e 100644 --- a/src/components/CopyButton.tsx +++ b/src/components/CopyButton.tsx @@ -3,10 +3,10 @@ import React from "react"; import toast from "react-hot-toast"; import { formatErrorForToast } from "@/api/utils"; -import { Button } from "./Button"; +import { Button, type ButtonProps } from "./Button"; import Icon from "./Icon"; -export interface CopyButtonProps extends React.ButtonHTMLAttributes { +export interface CopyButtonProps extends ButtonProps { $value: string; } @@ -25,7 +25,7 @@ export const CopyButton: React.FC = ({ }) => { const handleClick = async (e: React.MouseEvent) => { e.stopPropagation(); - if (disabled || !$value) return; + if (disabled) return; try { await navigator.clipboard.writeText($value); diff --git a/src/components/DataTable.tsx b/src/components/DataTable.tsx new file mode 100644 index 00000000..62d3b72a --- /dev/null +++ b/src/components/DataTable.tsx @@ -0,0 +1,354 @@ +import { + IconArrowsSort, + IconSortAscending, + IconSortDescending, +} from "@tabler/icons-react"; +import { + flexRender, + getCoreRowModel, + getSortedRowModel, + useReactTable, + type ColumnDef, + type SortingState, +} from "@tanstack/react-table"; +import { Fragment, useState, type ReactNode } from "react"; +import styled from "styled-components"; + +import { ScrollArea } from "./ScrollArea"; + +export const TablePage = styled.section` + display: flex; + flex: 1; + flex-direction: column; + + min-width: 0; + min-height: 0; + + background-color: ${({ theme }) => theme.colors.background.primary}; +`; + +export const TableToolbar = styled.div` + display: flex; + flex-shrink: 0; + flex-wrap: wrap; + gap: ${({ theme }) => theme.spacing.md}; + align-items: center; + justify-content: space-between; + + padding: ${({ theme }) => theme.spacing.lg}; +`; + +export const TableInset = styled.div` + display: flex; + flex: 1; + flex-direction: column; + + min-width: 0; + min-height: 0; + padding: 0 ${({ theme }) => theme.spacing.lg} + ${({ theme }) => theme.spacing.lg}; +`; + +const TableScrollArea = styled(ScrollArea)` + --scroll-area-radius: calc(${({ theme }) => theme.radius.md} - 1px) + calc(${({ theme }) => theme.radius.md} - 1px) 0 0; + + flex: 1 1 auto; + + width: 100%; + min-height: 0; + border: 1px solid ${({ theme }) => theme.colors.dataTable.border}; + border-bottom: 0; + border-radius: ${({ theme }) => theme.radius.md} + ${({ theme }) => theme.radius.md} 0 0; + + background: ${({ theme }) => theme.colors.dataTable.bodyBg}; + + /* A size container, so the detail rows can use cqi units for the visible width. */ + > [data-radix-scroll-area-viewport] { + container-type: inline-size; + } +`; + +const Grid = styled.table<{ $minWidth: number }>` + table-layout: fixed; + border-collapse: collapse; + + width: 100%; + min-width: ${({ $minWidth }) => $minWidth}px; + + font: ${({ theme }) => theme.typography.caption.font}; + text-align: left; + + th, + td { + padding: ${({ theme }) => theme.spacing.sm}; + border-bottom: 1px solid ${({ theme }) => theme.colors.dataTable.border}; + white-space: nowrap; + } + + th:first-child, + td:first-child { + padding-left: ${({ theme }) => theme.spacing.lg}; + } + + th:last-child, + td:last-child { + padding-right: ${({ theme }) => theme.spacing.lg}; + } + + th { + position: sticky; + z-index: 2; + top: 0; + + border-bottom: 0; + + font: ${({ theme }) => theme.typography.caption.font}; + font-weight: ${({ theme }) => theme.fonts.weight.medium}; + color: ${({ theme }) => theme.colors.dataTable.headerText}; + + background: ${({ theme }) => theme.colors.dataTable.headerBg}; + box-shadow: inset 0 -1px ${({ theme }) => theme.colors.dataTable.border}; + } + + td { + overflow: hidden; + color: ${({ theme }) => theme.colors.text.primary}; + text-overflow: ellipsis; + } + + td > span { + max-width: 100%; + } + + tbody tr:not([data-detail]) { + background: ${({ theme }) => theme.colors.background.primary}; + } + + tbody tr:not([data-detail]):hover { + background: ${({ theme }) => theme.colors.dataTable.rowHoverBg}; + } + + tbody tr:not([data-detail]):hover td:first-child { + box-shadow: inset 3px 0 ${({ theme }) => theme.colors.primary.main}; + } + + tr[data-clickable="true"] { + cursor: pointer; + } + + tr[data-clickable="true"]:focus-visible { + outline: 2px solid ${({ theme }) => theme.colors.primary.main}; + outline-offset: -2px; + } + + [data-actions="true"] { + position: sticky; + z-index: 1; + right: 0; + + text-align: right; + + background: ${({ theme }) => theme.colors.background.primary}; + } + + th[data-actions="true"] { + z-index: 3; + background: ${({ theme }) => theme.colors.dataTable.headerBg}; + } + + tbody tr:hover [data-actions="true"] { + background: ${({ theme }) => theme.colors.dataTable.rowHoverBg}; + } + + td[data-detail-cell] { + overflow: visible; + padding: 0; + white-space: normal; + background: ${({ theme }) => theme.colors.dataTable.detailBg}; + } +`; + +const DetailBox = styled.div` + position: sticky; + left: 0; + width: min(100%, 100cqi); + padding: ${({ theme }) => `${theme.spacing.sm} ${theme.spacing.lg}`}; +`; + +const SortButton = styled.button` + display: inline-flex; + gap: ${({ theme }) => theme.spacing.xs}; + align-items: center; + + &:hover { + color: ${({ theme }) => theme.colors.dataTable.headerHoverText}; + } + + &:focus-visible { + outline: 2px solid ${({ theme }) => theme.colors.dataTable.headerHoverText}; + outline-offset: 3px; + } +`; + +const Footer = styled.div` + flex-shrink: 0; + + padding: ${({ theme }) => `${theme.spacing.sm} ${theme.spacing.lg}`}; + border: 1px solid ${({ theme }) => theme.colors.dataTable.border}; + + font: ${({ theme }) => theme.typography.caption.font}; + color: ${({ theme }) => theme.colors.text.secondary}; + + background: ${({ theme }) => theme.colors.dataTable.footerBg}; +`; + +export interface DataTableProps { + data: T[]; + columns: ColumnDef[]; + label: string; + emptyMessage: string; + initialSorting?: SortingState; + renderDetail?: (row: T) => ReactNode; + /** Makes rows clickable, with Enter on a focused row doing the same. */ + onRowClick?: (row: T) => void; + getRowId?: (row: T) => string; + /** Below this width in pixels the table scrolls horizontally. */ + minWidth?: number; +} + +export function DataTable({ + data, + columns, + label, + emptyMessage, + initialSorting = [], + renderDetail, + onRowClick, + getRowId, + minWidth = 850, +}: DataTableProps) { + const [sorting, setSorting] = useState(initialSorting); + // TanStack Table v8 returns mutable callbacks that React Compiler cannot memoize. + // oxlint-disable-next-line react/incompatible-library + const table = useReactTable({ + data, + columns, + state: { sorting }, + onSortingChange: setSorting, + getCoreRowModel: getCoreRowModel(), + getSortedRowModel: getSortedRowModel(), + getRowId, + getRowCanExpand: () => !!renderDetail, + autoResetExpanded: false, + }); + const rows = table.getRowModel().rows; + const visibleColumns = table.getVisibleLeafColumns(); + const totalSize = visibleColumns.reduce( + (sum, column) => sum + column.getSize(), + 0, + ); + + return ( + <> + + + + {visibleColumns.map((column) => ( + 0 + ? { width: `${(column.getSize() / totalSize) * 100}%` } + : undefined + } + /> + ))} + + + {table.getHeaderGroups().map((group) => ( + + {group.headers.map((header) => { + const sorted = header.column.getIsSorted(); + const SortIcon = + sorted === "asc" + ? IconSortAscending + : sorted === "desc" + ? IconSortDescending + : IconArrowsSort; + return ( + + {header.isPlaceholder ? null : header.column.getCanSort() ? ( + + {flexRender( + header.column.columnDef.header, + header.getContext(), + )} + + + ) : ( + flexRender( + header.column.columnDef.header, + header.getContext(), + ) + )} + + ); + })} + + ))} + + + {rows.map((row) => ( + + onRowClick(row.original))} + onKeyDown={ + onRowClick && + ((e) => { + if (e.key === "Enter" && e.target === e.currentTarget) + onRowClick(row.original); + }) + } + > + {row.getVisibleCells().map((cell) => ( + + {flexRender( + cell.column.columnDef.cell, + cell.getContext(), + )} + + ))} + + {renderDetail && row.getIsExpanded() && ( + + + {renderDetail(row.original)} + + + )} + + ))} + + + +
+ {rows.length === 0 + ? emptyMessage + : `${rows.length} ${rows.length === 1 ? "result" : "results"}`} +
+ + ); +} diff --git a/src/components/Form.tsx b/src/components/Form.tsx index eeb8b7af..0e732b5c 100644 --- a/src/components/Form.tsx +++ b/src/components/Form.tsx @@ -15,9 +15,11 @@ interface ControlSizeProps { * @example * */ -export const Input = styled.input` +export const Input = styled.input` width: 100%; - border: 1px solid ${({ theme }) => theme.colors.border.medium}; + border: 1px solid + ${({ theme, $hasError }) => + $hasError ? theme.colors.error.border : theme.colors.border.medium}; border-radius: ${({ theme }) => theme.radius.md}; ${({ $size = ThemeSize.Medium, theme }) => { @@ -59,136 +61,6 @@ export const Input = styled.input` } `; -/** - * Styled select element keeping the same visuals as the `Input` component. - * Option elements are styled where supported by the browser. - */ -const StyledSelect = styled.select` - width: 100%; - border: 1px solid ${({ theme }) => theme.colors.border.medium}; - border-radius: ${({ theme }) => theme.radius.md}; - - ${({ $size = ThemeSize.Medium, theme }) => { - const { height, paddingX } = getControlSize(theme, $size); - return ` - height: ${height}; - padding: 0 ${theme.spacing["2xl"]} 0 ${paddingX}; - `; - }}; - - font: ${({ theme }) => theme.typography.body.font}; - font-size: ${({ $size = ThemeSize.Medium, theme }) => - getControlSize(theme, $size).fontSize}; - color: ${({ theme }) => theme.colors.text.primary}; - - -webkit-appearance: none; - appearance: none; - background-color: ${({ theme }) => theme.colors.background.primary}; - background-image: ${({ theme }) => { - const color = theme.colors.text.tertiary.replace("#", "%23"); - return `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='${color}' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C%2Fsvg%3E")`; - }}; - background-repeat: no-repeat; - background-position: right ${({ theme }) => theme.spacing.md} center; - - transition: border-color ${({ theme }) => theme.transitions.base}; - - &:hover { - border-color: ${({ theme }) => theme.colors.primary.hover}; - } - &:focus { - border-color: ${({ theme }) => theme.colors.primary.main}; - outline: none; - box-shadow: - 0 0 8px 0px ${({ theme }) => theme.colors.primary.main}20, - 0 0 12px 0px ${({ theme }) => theme.colors.primary.main}10; - } - - &:disabled { - cursor: not-allowed; - opacity: 0.5; - background-color: ${({ theme }) => theme.colors.background.secondary}; - } - - & > option { - padding: ${({ theme }) => `${theme.spacing.md}`}; - border-radius: ${({ theme }) => theme.radius.md}; - - font: ${({ theme }) => theme.typography.body.font}; - line-height: 1.75; - color: ${({ theme }) => theme.colors.text.primary}; - - background: ${({ theme }) => theme.colors.background.primary}; - } - - & > option:hover { - background: ${({ theme }) => theme.colors.background.secondary}; - } -`; - -const StyledOption = styled.option` - padding: ${({ theme }) => `${theme.spacing.md}`}; - border-radius: ${({ theme }) => theme.radius.md}; - - font: ${({ theme }) => theme.typography.body.font}; - line-height: 1.75; - color: ${({ theme }) => theme.colors.text.primary}; - - background: ${({ theme }) => theme.colors.background.primary}; -`; - -export interface SelectProps - extends - Omit, "value">, - ControlSizeProps { - $value?: string | number; - $onChange?: (value: string) => void; - $options: Array<{ - value: string; - label: React.ReactNode; - disabled?: boolean; - }>; - $placeholder?: string; -} - -/** - * Controlled Select component that accepts `$value`, `$onChange` and `$options`. - * Renders styled options and falls back to children if provided. - * @param $value - Controlled value of the select (string|number). - * @param $onChange - Handler invoked with the selected value. - * @param $options - Array of options to render: { value, label, disabled? }. - * @param $placeholder - Optional placeholder entry rendered with empty value. - * @param $size - Same sizes as Button. Defaults to Medium. - */ -export const Select: React.FC = ({ - $value, - $onChange, - $options, - $placeholder, - children, - ...rest -}) => { - const handleChange: React.ChangeEventHandler = (e) => { - if ($onChange) $onChange(e.target.value); - if (rest.onChange) - (rest.onChange as React.ChangeEventHandler)(e); - }; - - return ( - - {typeof $placeholder === "string" && ( - {$placeholder} - )} - {($options || []).map((opt) => ( - - {opt.label} - - ))} - {children} - - ); -}; - /** * Form group container for label + input pairs with consistent spacing. * Stacks label and input vertically with a small gap and adds bottom margin between groups. diff --git a/src/components/SearchSelect.tsx b/src/components/SearchSelect.tsx index 45bbcb14..2cd4aaf9 100644 --- a/src/components/SearchSelect.tsx +++ b/src/components/SearchSelect.tsx @@ -31,6 +31,8 @@ type CommonProps = { $disabled?: boolean; $loading?: boolean; $ariaLabel?: string; + title?: string; + $searchable?: boolean; $clearable?: boolean; $required?: boolean; }; @@ -175,6 +177,7 @@ export const SearchSelect: React.FC = (props) => { "aria-label": props.$ariaLabel, required: props.$required, isMulti: !!props.$multi, + isSearchable: props.$searchable ?? true, isClearable: props.$clearable ?? true, placeholder: $placeholder ?? "Select…", value: props.$multi @@ -205,6 +208,7 @@ export const SearchSelect: React.FC = (props) => { return ( { if (event.key === "Escape") { escapeClosedMenu.current = menuOpen.current; diff --git a/src/components/VariableInput.test.ts b/src/components/VariableInput.test.ts new file mode 100644 index 00000000..2fef9738 --- /dev/null +++ b/src/components/VariableInput.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from "vitest"; + +import { validateVariableValue } from "./VariableInput"; + +describe("validateVariableValue", () => { + it("treats empty values as valid unless required", () => { + expect(validateVariableValue("string", "")).toBeUndefined(); + expect(validateVariableValue("integer", "")).toBeUndefined(); + expect(validateVariableValue("bool", "", false)).toBeUndefined(); + expect(validateVariableValue("bool", "", true)).toBe("Value is required."); + }); + + it("requires dictionaries to be JSON objects rather than arrays or primitives", () => { + expect(validateVariableValue("dictionary", '{"a": 1}')).toBeUndefined(); + expect(validateVariableValue("dictionary", "{}")).toBeUndefined(); + expect(validateVariableValue("dictionary", "[1, 2]")).toBeTruthy(); + expect(validateVariableValue("dictionary", "null")).toBeTruthy(); + expect(validateVariableValue("dictionary", '"hello"')).toBeTruthy(); + expect(validateVariableValue("dictionary", "{bad json")).toBeTruthy(); + }); + + it("validates numeric, boolean, and URI values", () => { + expect(validateVariableValue("integer", "-42")).toBeUndefined(); + expect(validateVariableValue("integer", "3.14")).toBeTruthy(); + expect(validateVariableValue("long", "9001")).toBeUndefined(); + expect(validateVariableValue("float", "-3.14")).toBeUndefined(); + expect(validateVariableValue("float", "1e5")).toBeUndefined(); + expect(validateVariableValue("float", " ")).toBeTruthy(); + expect(validateVariableValue("bool", "true")).toBeUndefined(); + expect(validateVariableValue("bool", "false")).toBeUndefined(); + expect(validateVariableValue("bool", "maybe")).toBeTruthy(); + expect( + validateVariableValue("uri", "https://example.com/a"), + ).toBeUndefined(); + expect(validateVariableValue("uri", "not a uri")).toBeTruthy(); + }); + + it("validates simple regex formats", () => { + expect(validateVariableValue("hexstring", "4a6f686e")).toBeUndefined(); + expect(validateVariableValue("hexstring", "0x4a6f")).toBeTruthy(); + expect( + validateVariableValue("mac-addr", "00:1A:2B:3C:4D:5E"), + ).toBeUndefined(); + expect(validateVariableValue("mac-addr", "invalid")).toBeTruthy(); + expect( + validateVariableValue("uuid", "550e8400-e29b-41d4-a716-446655440000"), + ).toBeUndefined(); + expect(validateVariableValue("uuid", "not-a-uuid")).toBeTruthy(); + expect(validateVariableValue("hash", "deadbeef")).toBeUndefined(); + expect(validateVariableValue("hash", "xyz")).toBeTruthy(); + expect(validateVariableValue("md5-hash", "a".repeat(32))).toBeUndefined(); + expect(validateVariableValue("md5-hash", "a".repeat(31))).toBeTruthy(); + expect( + validateVariableValue("sha256-hash", "f".repeat(64)), + ).toBeUndefined(); + expect(validateVariableValue("sha256-hash", "f".repeat(63))).toBeTruthy(); + }); + + it("validates IPv4 and IPv6 addresses with optional CIDR prefixes", () => { + expect(validateVariableValue("ipv4-addr", "192.168.1.1")).toBeUndefined(); + expect(validateVariableValue("ipv4-addr", "10.0.0.0/24")).toBeUndefined(); + expect(validateVariableValue("ipv4-addr", "999.168.1.1")).toBeTruthy(); + expect(validateVariableValue("ipv4-addr", "192.168.1.1/33")).toBeTruthy(); + expect( + validateVariableValue("ipv6-addr", "2001:0db8:85a3::8a2e:0370:7334"), + ).toBeUndefined(); + expect(validateVariableValue("ipv6-addr", "::1")).toBeUndefined(); + expect(validateVariableValue("ipv6-addr", "fe80::1/64")).toBeUndefined(); + expect(validateVariableValue("ipv6-addr", "not-an-ip")).toBeTruthy(); + expect(validateVariableValue("ipv6-addr", "192.168.1.1")).toBeTruthy(); + expect(validateVariableValue("ipv6-addr", "fe80::1/129")).toBeTruthy(); + }); +}); diff --git a/src/components/VariableInput.tsx b/src/components/VariableInput.tsx index 16bfcd3a..7f58ecfa 100644 --- a/src/components/VariableInput.tsx +++ b/src/components/VariableInput.tsx @@ -1,5 +1,6 @@ import { CodeEditor } from "./CodeEditor"; -import { Input, Select } from "./Form"; +import { Input } from "./Form"; +import { SearchSelect } from "./SearchSelect"; import { ThemeSize } from "./utils"; interface VariableInputProps { @@ -15,17 +16,15 @@ interface VariableInputProps { } type TextFormat = { - inputType?: "number" | "url"; + inputType?: "number"; step?: string; placeholder: string; - pattern?: string; }; const INTEGER_FORMAT: TextFormat = { inputType: "number", step: "1", placeholder: "Enter integer value", - pattern: "^-?\\d+$", }; const TEXT_FORMATS: Record = { @@ -35,47 +34,108 @@ const TEXT_FORMATS: Record = { inputType: "number", step: "any", placeholder: "Enter float value", - pattern: "^-?\\d+(\\.\\d+)?$", + }, + hexstring: { + placeholder: "4a6f686e", }, "ipv4-addr": { placeholder: "192.168.1.1", - pattern: "^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$", }, "ipv6-addr": { placeholder: "2001:0db8:85a3::8a2e:0370:7334", - pattern: "^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$", }, "mac-addr": { placeholder: "00:1A:2B:3C:4D:5E", - pattern: "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$", }, - uri: { inputType: "url", placeholder: "https://example.com" }, + uri: { placeholder: "https://example.com" }, uuid: { placeholder: "550e8400-e29b-41d4-a716-446655440000", - pattern: - "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", }, - hash: { placeholder: "Hash value (hex string)", pattern: "^[a-fA-F0-9]+$" }, + hash: { placeholder: "Hash value (hex string)" }, "md5-hash": { placeholder: "MD5 hash (32 characters)", - pattern: "^[a-fA-F0-9]{32}$", }, "sha256-hash": { placeholder: "SHA-256 hash (64 characters)", - pattern: "^[a-fA-F0-9]{64}$", }, }; -const isInvalidJson = (text: string) => { - if (text.trim() === "") return false; +const isValidDictionary = (text: string): boolean => { try { - JSON.parse(text); - return false; + const parsed: unknown = JSON.parse(text); + return ( + typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) + ); } catch { - return true; + return false; } }; +const FORMAT_CHECKS: Record = { + integer: { pattern: /^-?\d+$/, message: "Enter a whole number." }, + long: { pattern: /^-?\d+$/, message: "Enter a whole number." }, + hexstring: { + pattern: /^[0-9a-fA-F]+$/, + message: "Use hexadecimal digits only (0-9, a-f).", + }, + "ipv4-addr": { + pattern: + /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\/(?:3[0-2]|[12]?\d))?$/, + message: "Enter a valid IPv4 address (e.g. 192.168.1.1).", + }, + "ipv6-addr": { + pattern: /^[0-9a-fA-F]*:[0-9a-fA-F:.]*(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?$/, + message: "Enter a valid IPv6 address (e.g. 2001:db8::1).", + }, + "mac-addr": { + pattern: /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/, + message: "Enter a valid MAC address (e.g. 00:1A:2B:3C:4D:5E).", + }, + uuid: { + pattern: + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + message: "Enter a valid UUID.", + }, + hash: { pattern: /^[a-fA-F0-9]+$/, message: "Enter a hexadecimal hash." }, + "md5-hash": { + pattern: /^[a-fA-F0-9]{32}$/, + message: "Enter a 32-character hexadecimal MD5 hash.", + }, + "sha256-hash": { + pattern: /^[a-fA-F0-9]{64}$/, + message: "Enter a 64-character hexadecimal SHA-256 hash.", + }, +}; + +/** Validates a CACAO variable value for the given type. Returns an error message or undefined. */ +export function validateVariableValue( + type: string, + value: string, + required = false, +): string | undefined { + if (value === "") return required ? "Value is required." : undefined; + if (type === "bool") + return value === "true" || value === "false" + ? undefined + : "Select True or False."; + if (type === "float") + return value.trim() !== "" && Number.isFinite(Number(value)) + ? undefined + : "Enter a valid number."; + if (type === "dictionary") + return isValidDictionary(value) ? undefined : "Enter a valid JSON object."; + if (type === "uri") { + try { + new URL(value); + return undefined; + } catch { + return "Enter a valid URI (e.g. https://example.com)."; + } + } + const check = FORMAT_CHECKS[type]; + return check && !check.pattern.test(value) ? check.message : undefined; +} + /** Input for a CACAO variable value. The control and its checks depend on the variable type. */ export const VariableInput: React.FC = ({ id, @@ -88,17 +148,20 @@ export const VariableInput: React.FC = ({ onChange, }) => { const change = (next: string) => onChange(variableKey, next); + const invalid = value !== "" && !!validateVariableValue(type, value); switch (type) { case "bool": return ( - { - const val = e.target.value; - if (val === "" || /^0x[0-9a-fA-F]*$/.test(val)) change(val); - }} - disabled={disabled} - aria-required={$required || undefined} - placeholder="0x..." - pattern="^0x[0-9a-fA-F]*$" - /> - ); case "dictionary": return ( = ({ disabled={disabled} $required={$required} placeholder='{"key": "value"}' - $hasError={isInvalidJson(value)} + $hasError={invalid} $minHeight="100px" /> ); @@ -144,6 +190,7 @@ export const VariableInput: React.FC = ({ = ({ disabled={disabled} aria-required={$required || undefined} placeholder={format.placeholder} - pattern={format.pattern} /> ); } diff --git a/src/components/index.ts b/src/components/index.ts index 4395f147..c9ede3b8 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -6,6 +6,7 @@ export * from "./CodeEditor"; export * from "./ConfirmDialog"; export * from "./Containers"; export * from "./CopyButton"; +export * from "./DataTable"; export * from "./Details"; export * from "./ExportButton"; export * from "./export"; diff --git a/src/mock/storeApi.test.ts b/src/mock/storeApi.test.ts new file mode 100644 index 00000000..ad81c8a2 --- /dev/null +++ b/src/mock/storeApi.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from "vitest"; + +import type { SecretMetadata, StoredVariable } from "@/types"; + +import { + createStoreApi, + isStoreRoute, + MAX_VERSIONS, + validateVariableValue, +} from "./storeApi"; + +const setup = () => { + const { handle } = createStoreApi({ + now: () => "2026-08-01T00:00:00Z", + }); + return async (method: string, path: string, body?: unknown) => { + const response = await handle({ + method, + path, + query: new URLSearchParams(), + body, + }); + if (!response) throw new Error(`No route for ${method} ${path}`); + return response; + }; +}; + +describe("isStoreRoute", () => { + it("only claims secret and variable routes", () => { + expect(isStoreRoute("/secret/")).toBe(true); + expect(isStoreRoute("/variable/fw-api-user/versions")).toBe(true); + expect(isStoreRoute("/playbook/abc/mapping")).toBe(false); + expect(isStoreRoute("/playbook/abc/resolve")).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("secrets", () => { + it("are read-only", async () => { + const response = await setup()("POST", "/secret/", { name: "x" }); + expect(response.status).toBe(405); + }); + + it("returns metadata without secret values", async () => { + const response = await setup()("GET", "/secret/"); + expect(response.status).toBe(200); + const secrets = response.body as SecretMetadata[]; + expect(secrets.length).toBeGreaterThan(0); + for (const secret of secrets) { + expect(secret).toHaveProperty("name"); + expect(secret).not.toHaveProperty("value"); + } + }); +}); + +describe("variables", () => { + it("creates and deletes a variable", async () => { + const call = setup(); + const created = await call("POST", "/variable/", { + name: "test-endpoint", + type: "string", + value: "https://example.org", + description: "Test endpoint", + }); + expect(created.status).toBe(201); + expect(created.body).toMatchObject({ + name: "test-endpoint", + value: "https://example.org", + version: 1, + }); + expect((await call("DELETE", "/variable/test-endpoint")).status).toBe(204); + expect((await call("GET", "/variable/test-endpoint")).status).toBe(404); + }); + + it("rejects a write based on a stale version", async () => { + const response = await setup()("PUT", "/variable/fw-api-user", { + version: 1, + value: "someone", + }); + expect(response.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("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 response = await setup()("PATCH", "/variable/fw-api-user", { + description: "New text", + }); + expect((response.body as StoredVariable).version).toBe(2); + }); +}); diff --git a/src/mock/storeApi.ts b/src/mock/storeApi.ts new file mode 100644 index 00000000..0ce956a7 --- /dev/null +++ b/src/mock/storeApi.ts @@ -0,0 +1,458 @@ +import type { + SecretBackend, + SecretMetadata, + SecretVersion, + StoredVariable, + StoredVariableVersion, +} from "@/types"; + +// In-memory stand-in for the secret and variable 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; +} + +export interface MockResponse { + status: number; + body?: unknown; +} + +interface StoreOptions { + identity?: string; + now?: () => string; +} + +interface SecretEntry { + meta: SecretMetadata; + versions: SecretVersion[]; +} + +interface VariableEntry { + meta: StoredVariable; + versions: StoredVariableVersion[]; +} + +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); + +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({ + 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 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; + }; + + 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 }, + ]; + entry.versions = all.slice(-MAX_VERSIONS); + 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": { + variables.delete(entry.meta.name); + return json(204); + } + } + return undefined; + }; + + /** 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); + return undefined; + } + + return { handle }; +} diff --git a/src/pages/main-page/playbooks-page/visual-editor/model/specs/cacao-2.0.ts b/src/pages/main-page/playbooks-page/visual-editor/model/specs/cacao-2.0.ts index 37a8cf4a..5653dc41 100644 --- a/src/pages/main-page/playbooks-page/visual-editor/model/specs/cacao-2.0.ts +++ b/src/pages/main-page/playbooks-page/visual-editor/model/specs/cacao-2.0.ts @@ -9,10 +9,13 @@ import { IconRepeat, } from "@tabler/icons-react"; +import { VARIABLE_TYPES } from "@/cacaoResources"; import { ThemeVariant } from "@/components/utils"; import type { CacaoSpec, Field, StepField } from "./types"; +export { VARIABLE_TYPES }; + // Open vocabulary from the spec. These are suggestions: other values are allowed. const AGENT_TARGET_TYPES = [ "group", @@ -33,23 +36,7 @@ const variableEntry: Field[] = [ label: "Type", kind: "text", required: true, - vocabulary: [ - "bool", - "dictionary", - "float", - "hexstring", - "integer", - "ipv4-addr", - "ipv6-addr", - "long", - "mac-addr", - "hash", - "md5-hash", - "sha256-hash", - "string", - "uri", - "uuid", - ], + vocabulary: [...VARIABLE_TYPES], }, { key: "value", label: "Value", kind: "variable-value" }, { key: "description", label: "Description", kind: "text" }, diff --git a/src/pages/main-page/playbooks-page/visual-editor/panels/PlaybookPanel.tsx b/src/pages/main-page/playbooks-page/visual-editor/panels/PlaybookPanel.tsx index 3e519ff9..0f509ea4 100644 --- a/src/pages/main-page/playbooks-page/visual-editor/panels/PlaybookPanel.tsx +++ b/src/pages/main-page/playbooks-page/visual-editor/panels/PlaybookPanel.tsx @@ -1,6 +1,12 @@ import { useId } from "react"; -import { Badge, FormGroup, FormLabel, Select, ThemeSize } from "@/components"; +import { + Badge, + FormGroup, + FormLabel, + SearchSelect, + ThemeSize, +} from "@/components"; import type { Playbook } from "@/types"; import type { EditPlaybook } from "../model/editor"; @@ -50,11 +56,13 @@ const SpecVersionField: React.FC<{ return ( CACAO version - onSearchChange(e.target.value)} + /> + + {children} + + ); +} + +/** The expanded history of a row, with its loading, error and empty states. */ +export function ResourceHistory({ + query, + empty, + note, + children, +}: PropsWithChildren<{ + query: QueryLike; + empty: boolean; + /** Shown above the versions once they are loaded. */ + note?: ReactNode; +}>) { + if (query.isLoading) + return ( + + + + ); + + if (query.isLoadingError) + return ; + + if (empty) return No versions available.; + + return ( +
+ {note} + {children} +
+ ); +} + +/** Toggles the history row. Hidden when only one version is kept unless `alwaysShow` is set. */ +export function HistoryButton({ + row, + alwaysShow = false, +}: { + row: Row; + alwaysShow?: boolean; +}) { + const { name, version, oldest_version } = row.original; + if (!alwaysShow && version <= oldest_version) return null; + return ( + + ); +} + +const asResource = (row: T) => row as ResourceSummary; + +export function nameColumn( + size: number, + getResource: (row: T) => ResourceSummary = asResource, +): ColumnDef { + return { + id: "name", + accessorFn: (r) => getResource(r).name, + size, + header: "Name", + cell: ({ row }) => { + const { name } = getResource(row.original); + return {name}; + }, + }; +} + +export function descriptionColumn( + size: number, + getResource: (row: T) => ResourceSummary = asResource, +): ColumnDef { + return { + id: "description", + accessorFn: (r) => getResource(r).description, + size, + header: "Description", + cell: ({ row }) => { + const { description } = getResource(row.original); + return description ? ( + {description} + ) : ( + No description + ); + }, + }; +} + +export function versionColumn( + size: number, + getResource: (row: T) => ResourceSummary = asResource, +): ColumnDef { + return { + id: "version", + accessorFn: (r) => getResource(r).version, + size, + header: "Version", + cell: ({ row }) => `v${getResource(row.original).version}`, + }; +} + +export function modifiedColumn( + size: number, + getResource: (row: T) => ResourceSummary = asResource, +): ColumnDef { + return { + id: "modified", + accessorFn: (r) => getResource(r).modified, + size, + header: "Modified", + cell: ({ row }) => formatStoreDate(getResource(row.original).modified), + }; +} diff --git a/src/pages/main-page/store-pages/SecretsPage.tsx b/src/pages/main-page/store-pages/SecretsPage.tsx new file mode 100644 index 00000000..f2d6e606 --- /dev/null +++ b/src/pages/main-page/store-pages/SecretsPage.tsx @@ -0,0 +1,175 @@ +import { useQuery } from "@tanstack/react-query"; +import type { ColumnDef } from "@tanstack/react-table"; +import React, { 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 { formatDateTime } from "@/utils"; + +import { + descriptionColumn, + HistoryButton, + modifiedColumn, + nameColumn, + ResourceHistory, + ResourceToolbar, + versionColumn, +} from "./ResourceTable"; +import { Muted, 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 = () => { + 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 columns = useMemo[]>( + () => [ + nameColumn(160), + { + accessorKey: "kind", + size: 120, + header: "Type", + cell: ({ row }) => , + }, + descriptionColumn(180), + versionColumn(90), + modifiedColumn(120), + { + id: "actions", + size: 130, + header: "Actions", + enableSorting: false, + cell: ({ row }) => ( + + + + ), + }, + ], + [], + ); + + if (secrets.isLoading) + return ( + + + + ); + + if (secrets.isLoadingError) + return ( + + + + ); + + return ( + <> + + + + + secret.name} + renderDetail={(secret) => } + initialSorting={[{ id: "name", desc: false }]} + emptyMessage={ + kind + ? "No secrets match the filters" + : search.trim() + ? `No secrets match "${search.trim()}"` + : "No secrets stored" + } + /> + + + ); +}; diff --git a/src/pages/main-page/store-pages/StorePage.test.tsx b/src/pages/main-page/store-pages/StorePage.test.tsx new file mode 100644 index 00000000..b3aa3b7b --- /dev/null +++ b/src/pages/main-page/store-pages/StorePage.test.tsx @@ -0,0 +1,607 @@ +// @vitest-environment jsdom +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + cleanup, + fireEvent, + render, + screen, + waitFor, + within, +} from "@testing-library/react"; +import toast from "react-hot-toast"; +import { MemoryRouter } from "react-router"; +import { ThemeProvider } from "styled-components"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; + +import { + createVariable, + deleteVariable, + getSecretBackend, + getSecrets, + getSecretVersions, + getVariableVersions, + getVariables, + updateVariableDescription, + updateVariableValue, +} from "@/api/store"; +import { AuthContext } from "@/auth/AuthContext"; +import { Permissions, type Permission } from "@/auth/permissions"; +import { theme } from "@/theme"; +import type { SecretMetadata, StoredVariable } from "@/types"; + +import { StorePage } from "./StorePage"; + +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(), +})); + +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", +}; + +function renderStore(path: string, permissions: Permission[]) { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + return render( + + + permissions.includes(permission), + logout: vi.fn(), + retry: vi.fn(), + }} + > + + + + + + , + ); +} + +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; + +beforeAll(() => { + globalThis.ResizeObserver ??= class { + observe() {} + unobserve() {} + disconnect() {} + }; + HTMLDialogElement.prototype.showModal = function () { + this.setAttribute("open", ""); + }; + HTMLDialogElement.prototype.close = function () { + this.removeAttribute("open"); + }; +}); + +afterAll(() => { + HTMLDialogElement.prototype.showModal = originalShowModal; + HTMLDialogElement.prototype.close = originalClose; +}); + +beforeEach(() => { + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + unobserve() {} + disconnect() {} + }, + ); +}); + +afterEach(() => { + cleanup(); + vi.resetAllMocks(); + vi.unstubAllGlobals(); +}); + +describe("Secrets and variables page", () => { + 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("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: "" }, + ]); + 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, ""); + }); + }); + + 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]); + + 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" }), + ); + 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" }), + ); + 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" } }, + ); + 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", + }), + ); + 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", + }); + fireEvent.click(within(table).getByRole("button", { name: "Name" })); + expect( + timeline.closest("tr")?.previousElementSibling?.textContent, + ).toContain("test-secret"); + expect(getSecretVersions).toHaveBeenCalledWith("test-secret"); + }); + + 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]); + fireEvent.click( + await screen.findByRole("button", { name: "View history of alpha" }), + ); + expect( + await screen.findByRole("list", { name: "Versions of alpha" }), + ).toBeTruthy(); + expect( + screen.queryByRole("button", { name: "Restore version 1 of alpha" }), + ).toBeNull(); + }); + + 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 toastError = vi.spyOn(toast, "error"); + 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" })); + + await waitFor(() => + expect(toastError).toHaveBeenCalledWith( + expect.stringMatching( + /^The description was saved, but the value was not\. /, + ), + ), + ); + 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, + ]); + + fireEvent.click( + await screen.findByRole("button", { name: "Delete alpha" }), + ); + const confirm = screen.getByRole("dialog"); + fireEvent.click(within(confirm).getByRole("button", { name: "Delete" })); + + await waitFor(() => expect(deleteVariable).toHaveBeenCalledWith("alpha")); + }); + + 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(); + }); +}); diff --git a/src/pages/main-page/store-pages/StorePage.tsx b/src/pages/main-page/store-pages/StorePage.tsx new file mode 100644 index 00000000..a7d85333 --- /dev/null +++ b/src/pages/main-page/store-pages/StorePage.tsx @@ -0,0 +1,32 @@ +import { NavLink, useLocation } from "react-router"; + +import { useAuth } from "@/auth/AuthContext"; +import { TablePage } from "@/components"; +import { PATHS } from "@/utils"; + +import { TableTabs } from "./StorePages.styles"; +import { SecretsPage } from "./SecretsPage"; +import { RESOURCE_TABS, resourceTabAt } from "./utils"; +import { VariablesPage } from "./VariablesPage"; + +export function StorePage() { + const { can } = useAuth(); + const { pathname } = useLocation(); + + return ( + + + {RESOURCE_TABS.filter((tab) => can(tab.permission)).map((tab) => ( + + {tab.label} + + ))} + + {resourceTabAt(pathname)?.path === PATHS.SECRETS ? ( + + ) : ( + + )} + + ); +} diff --git a/src/pages/main-page/store-pages/StorePages.styles.tsx b/src/pages/main-page/store-pages/StorePages.styles.tsx new file mode 100644 index 00000000..0b38d098 --- /dev/null +++ b/src/pages/main-page/store-pages/StorePages.styles.tsx @@ -0,0 +1,84 @@ +import styled from "styled-components"; + +export const TableTabs = styled.nav` + display: flex; + flex-shrink: 0; + gap: ${({ theme }) => theme.spacing.lg}; + + margin: 0 ${({ theme }) => theme.spacing.lg}; + padding-top: ${({ theme }) => theme.spacing.sm}; + border-bottom: 1px solid ${({ theme }) => theme.colors.dataTable.border}; + + a { + display: block; + + padding: ${({ theme }) => `${theme.spacing.sm} ${theme.spacing.md}`}; + border-bottom: 2px solid transparent; + + font: ${({ theme }) => theme.typography.body.font}; + color: ${({ theme }) => theme.colors.text.secondary}; + } + + a[aria-current="page"] { + border-bottom-color: ${({ theme }) => theme.colors.primary.main}; + color: ${({ theme }) => theme.colors.primary.main}; + } + + a:focus-visible { + outline: 2px solid ${({ theme }) => theme.colors.primary.main}; + outline-offset: -2px; + } +`; + +export const HistoryLoading = styled.div` + display: flex; + align-items: center; + justify-content: center; + min-height: 3rem; +`; + +export const TableText = styled.span` + overflow: hidden; + display: inline-block; + + max-width: 100%; + + text-overflow: ellipsis; + white-space: nowrap; + vertical-align: middle; +`; + +export const Mono = styled.span` + overflow: hidden; + display: inline-block; + + max-width: 100%; + + font: ${({ theme }) => theme.typography.code.font}; + color: ${({ theme }) => theme.colors.text.primary}; + text-overflow: ellipsis; + white-space: nowrap; + vertical-align: middle; + + [data-current] & { + color: ${({ theme }) => theme.colors.success.text}; + } +`; + +export const Muted = styled.span` + font: ${({ theme }) => theme.typography.caption.font}; + color: ${({ theme }) => theme.colors.text.secondary}; +`; + +export const RowActions = styled.div` + display: flex; + gap: ${({ theme }) => theme.spacing.xs}; + justify-content: flex-end; + min-height: ${({ theme }) => theme.control_height.sm}; + + button { + width: ${({ theme }) => theme.control_height.sm}; + padding: 0; + border-color: transparent; + } +`; diff --git a/src/pages/main-page/store-pages/VariableFormModal.tsx b/src/pages/main-page/store-pages/VariableFormModal.tsx new file mode 100644 index 00000000..e1543bd8 --- /dev/null +++ b/src/pages/main-page/store-pages/VariableFormModal.tsx @@ -0,0 +1,224 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import React, { useRef, useState } from "react"; +import toast from "react-hot-toast"; +import styled from "styled-components"; + +import { + createVariable, + updateVariableDescription, + updateVariableValue, +} from "@/api/store"; +import { storeQueries } from "@/api/storeQueries"; +import { formatErrorForToast } from "@/api/utils"; +import { VARIABLE_TYPES } from "@/cacaoResources"; +import { + Button, + FormGroup, + FormLabel, + Input, + Modal, + RequiredMark, + SearchSelect, + ThemeVariant, + validateVariableValue, + VariableInput, +} from "@/components"; +import type { StoredVariable } from "@/types"; + +import { NAME_PATTERN } from "./utils"; + +const ModalForm = styled.form` + overflow: hidden; + display: flex; + flex: 1; + flex-direction: column; + + min-height: 0; +`; + +const FieldError = styled.span` + font: ${({ theme }) => theme.typography.small.font}; + color: ${({ theme }) => theme.colors.error.text}; +`; + +interface VariableFormModalProps { + /** The variable to edit. Leave out to create one. */ + variable?: StoredVariable; + onClose: () => void; +} + +export const VariableFormModal: React.FC = ({ + variable, + onClose, +}) => { + const queryClient = useQueryClient(); + const [name, setName] = useState(variable?.name ?? ""); + const [type, setType] = useState(variable?.type ?? "string"); + const [value, setValue] = useState(variable?.value ?? ""); + const [description, setDescription] = useState(variable?.description ?? ""); + + const nameError = + !variable && name && !NAME_PATTERN.test(name) + ? "Use lowercase letters, digits, '_', '.' or '-', starting with a letter or digit." + : undefined; + const valueRequired = type === "bool"; + const valueError = validateVariableValue(type, value, valueRequired); + + const descriptionSaved = useRef(false); + const mutation = useMutation({ + mutationFn: async () => { + if (!variable) { + return createVariable({ name, type, value, description }); + } + descriptionSaved.current = false; + // A new description keeps the version, so it is saved first. If updating the + // value then fails, updating the cached description ensures a retry skips it. + if (description !== variable.description) { + const updated = await updateVariableDescription( + variable.name, + description, + ); + descriptionSaved.current = true; + queryClient.setQueryData( + storeQueries.variables().queryKey, + (list) => list?.map((v) => (v.name === updated.name ? updated : v)), + ); + } + if (value !== variable.value) { + await updateVariableValue(variable.name, variable.version, value); + } + }, + onSuccess: () => { + toast.success(variable ? "Variable saved" : "Variable created"); + onClose(); + }, + onError: (err: Error) => { + const message = formatErrorForToast(err, "Could not save the variable"); + toast.error( + descriptionSaved.current + ? `The description was saved, but the value was not. ${message}` + : message, + ); + }, + onSettled: () => + Promise.all([ + queryClient.invalidateQueries({ + queryKey: storeQueries.variables().queryKey, + }), + variable && + queryClient.invalidateQueries({ + queryKey: storeQueries.variableVersions(variable.name).queryKey, + }), + ]), + }); + + const unchanged = + !!variable && + value === variable.value && + description === variable.description; + const canSubmit = + !mutation.isPending && !unchanged && !!name && !nameError && !valueError; + const close = () => !mutation.isPending && onClose(); + + return ( + + + + {variable ? `Edit ${variable.name}` : "New variable"} + + + + { + e.preventDefault(); + if (canSubmit) mutation.mutate(); + }} + > + + + + Name + {!variable && } + + setName(e.target.value)} + /> + {nameError && {nameError}} + + + Type + { + if (next) { + setType(next); + setValue(""); + } + }} + $disabled={!!variable || mutation.isPending} + title={variable ? "The type cannot change" : undefined} + $options={VARIABLE_TYPES.map((t) => ({ value: t, label: t }))} + /> + + + + Value + {valueRequired && } + + setValue(next)} + /> + {value !== "" && valueError && ( + {valueError} + )} + + + Description + setDescription(e.target.value)} + /> + + + + + + + + + ); +}; diff --git a/src/pages/main-page/store-pages/VariablesPage.tsx b/src/pages/main-page/store-pages/VariablesPage.tsx new file mode 100644 index 00000000..bf2277dc --- /dev/null +++ b/src/pages/main-page/store-pages/VariablesPage.tsx @@ -0,0 +1,412 @@ +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 { deleteVariable, updateVariableValue } from "@/api/store"; +import { storeQueries } from "@/api/storeQueries"; +import { formatErrorForToast } from "@/api/utils"; +import { useAuth } from "@/auth/AuthContext"; +import { RequirePermission } from "@/auth/AuthGate"; +import { Permissions } from "@/auth/permissions"; +import { + Badge, + Button, + CenteredCardContent, + ConfirmDialog, + CopyButton, + DataTable, + HeaderActions, + Icon, + QueryError, + Spinner, + TableInset, + ThemeSize, + ThemeVariant, +} from "@/components"; +import type { StoredVariable } from "@/types"; +import { formatDateTime } from "@/utils"; + +import { + descriptionColumn, + HistoryButton, + modifiedColumn, + nameColumn, + ResourceHistory, + ResourceToolbar, + versionColumn, +} from "./ResourceTable"; +import { Mono, Muted, RowActions } from "./StorePages.styles"; +import { VariableFormModal } from "./VariableFormModal"; +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}`); + }, + onError: (err: Error) => { + toast.error(formatErrorForToast(err, "Could not restore the version")); + }, + onSettled: async () => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: storeQueries.variables().queryKey, + }), + queryClient.invalidateQueries({ + queryKey: storeQueries.variableVersions(variable.name).queryKey, + }), + ]); + }, + }); + + return ( + 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(); + const [search, setSearch] = useState(""); + const [type, setType] = useState(""); + const [dialog, setDialog] = useState(); + const [revealed, setRevealed] = useState>(() => new Set()); + const close = () => setDialog(undefined); + 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"); + }, + onError: (err: Error) => + toast.error(formatErrorForToast(err, "Could not delete the variable"), { + duration: 8000, + }), + onSettled: () => + void queryClient.invalidateQueries({ + queryKey: storeQueries.variables().queryKey, + }), + }); + + 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 columns = useMemo[]>( + () => [ + nameColumn(150), + { + accessorKey: "type", + size: 90, + header: "Type", + cell: ({ row }) => ( + {row.original.type} + ), + }, + { + accessorKey: "value", + size: 120, + header: "Value", + enableSorting: false, + cell: ({ row }) => ( + + ), + }, + descriptionColumn(150), + versionColumn(80), + modifiedColumn(110), + { + accessorKey: "modified_by", + size: 115, + header: "Modified by", + cell: ({ row }) => ( + + {shortIdentity(row.original.modified_by)} + + ), + }, + { + id: "actions", + size: 180, + header: "Actions", + enableSorting: false, + cell: ({ row }) => { + const v = row.original; + return ( + + + + + + + + + + ); + }, + }, + ], + [revealed, toggleReveal], + ); + + if (variables.isLoading) + return ( + + + + ); + + if (variables.isLoadingError) + return ( + + + + ); + + return ( + <> + + + + + + + + + + variable.name} + renderDetail={(variable) => ( + + )} + initialSorting={[{ id: "name", desc: false }]} + emptyMessage={ + type + ? "No variables match the filters" + : search.trim() + ? `No variables match "${search.trim()}"` + : "No variables stored" + } + /> + + {dialog?.kind === "create" && } + {dialog?.kind === "edit" && activeVariable && ( + + )} + activeVariable && remove.mutate(activeVariable.name)} + /> + + ); +}; diff --git a/src/pages/main-page/store-pages/VersionTimeline.tsx b/src/pages/main-page/store-pages/VersionTimeline.tsx new file mode 100644 index 00000000..b653dfa8 --- /dev/null +++ b/src/pages/main-page/store-pages/VersionTimeline.tsx @@ -0,0 +1,240 @@ +import { useLayoutEffect, useRef, type ReactNode } from "react"; +import styled from "styled-components"; + +import { ScrollArea } from "@/components"; + +type VersionState = "current" | "previous" | "deleted" | "destroyed"; + +type VersionTimelineItem = { + version: number; + current?: boolean; + state?: Exclude; + modifiedTitle: string; + details?: ReactNode; + action?: ReactNode; +}; + +const DOT_SIZE = "0.7rem"; + +const stateLabels: Record = { + current: { label: "Current", title: "The version in use" }, + previous: { label: "Previous", title: "An older version, not in use" }, + deleted: { + label: "Deleted", + title: "Hidden from use. An operator can still restore it.", + }, + destroyed: { + label: "Destroyed", + title: "Data removed for good. It cannot be restored.", + }, +}; + +const Timeline = styled.ol` + display: flex; + width: max-content; + margin-inline: auto; + list-style: none; +`; + +const Entry = styled.li` + display: flex; + flex: 1 0 14rem; + flex-direction: column; + gap: ${({ theme }) => theme.spacing.sm}; + align-items: center; + + min-width: 0; + padding-bottom: ${({ theme }) => theme.spacing.xs}; +`; + +const Node = styled.div` + position: relative; + + display: flex; + align-items: center; + justify-content: center; + + width: 100%; + + &::before, + &::after { + content: ""; + + position: absolute; + top: 50%; + + width: 50%; + height: 1px; + + background: ${({ theme }) => theme.colors.border.medium}; + } + + &::before { + left: 0; + } + + &::after { + right: 0; + } + + li:first-child &::before, + li:last-child &::after { + display: none; + } +`; + +const Dot = styled.span` + position: relative; + z-index: 1; + + display: block; + + width: ${DOT_SIZE}; + height: ${DOT_SIZE}; + border: 2px solid ${({ theme }) => theme.colors.border.dark}; + border-radius: 50%; + + background: ${({ theme }) => theme.colors.dataTable.detailBg}; + + [data-current] & { + border-color: ${({ theme }) => theme.colors.success.text}; + } + + [data-state="deleted"] & { + border-color: ${({ theme }) => theme.colors.warning.text}; + } + + [data-state="destroyed"] & { + border-color: ${({ theme }) => theme.colors.error.text}; + } +`; + +const Version = styled.strong` + [data-current] & { + color: ${({ theme }) => theme.colors.success.text}; + } + + [data-state="deleted"] & { + color: ${({ theme }) => theme.colors.warning.text}; + } + + [data-state="destroyed"] & { + color: ${({ theme }) => theme.colors.error.text}; + } +`; + +const Legend = styled.ul` + display: flex; + gap: ${({ theme }) => theme.spacing.md}; + align-items: center; + + font: ${({ theme }) => theme.typography.caption.font}; + color: ${({ theme }) => theme.colors.text.secondary}; + list-style: none; + + li { + display: flex; + gap: ${({ theme }) => theme.spacing.xs}; + align-items: center; + } + + ${Dot} { + background: transparent; + } +`; + +const Content = styled.div` + display: flex; + flex-direction: column; + gap: ${({ theme }) => theme.spacing.xs}; + align-items: center; + + max-width: 100%; + padding-inline: ${({ theme }) => theme.spacing.sm}; + + font: ${({ theme }) => theme.typography.caption.font}; + text-align: center; +`; + +const Heading = styled.div` + display: flex; + gap: ${({ theme }) => theme.spacing.sm}; + align-items: center; + + min-height: ${({ theme }) => theme.control_height.sm}; + + font: ${({ theme }) => theme.typography.caption.font}; +`; + +const versionTooltip = (item: VersionTimelineItem) => { + const parts: string[] = []; + if (item.current) parts.push("Current version"); + if (item.state) { + const { label, title } = stateLabels[item.state]; + parts.push(`${label}. ${title}`); + } + return parts.length > 0 + ? `${parts.join(" · ")}\n${item.modifiedTitle}` + : item.modifiedTitle; +}; + +/** Explains the colors that `VersionTimeline` uses for the given states. */ +export function VersionLegend({ states }: { states: VersionState[] }) { + return ( + + {states.map((state) => ( +
  • + + {stateLabels[state].label} +
  • + ))} +
    + ); +} + +export function VersionTimeline({ + items, + label, +}: { + items: VersionTimelineItem[]; + label: string; +}) { + const currentRef = useRef(null); + const currentVersion = items.find((item) => item.current)?.version; + + useLayoutEffect(() => { + currentRef.current?.scrollIntoView?.({ + inline: "nearest", + block: "nearest", + }); + }, [currentVersion]); + + return ( + + + {items.map((item) => ( + + + v{item.version} + {item.action} + + + + + {item.details} + + ))} + + + ); +} diff --git a/src/pages/main-page/store-pages/utils.ts b/src/pages/main-page/store-pages/utils.ts new file mode 100644 index 00000000..f8de1165 --- /dev/null +++ b/src/pages/main-page/store-pages/utils.ts @@ -0,0 +1,32 @@ +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. */ +export const RESOURCE_TABS = [ + { + path: PATHS.VARIABLES, + label: "Variables", + permission: Permissions.VariableRead, + }, + { path: PATHS.SECRETS, label: "Secrets", permission: Permissions.SecretRead }, +] as const; + +export const resourceTabAt = (pathname: string) => + RESOURCE_TABS.find((tab) => matchPath(tab.path, pathname)); + +/** Allowed secret and variable names, from the SOARCA API design. */ +export const NAME_PATTERN = /^[a-z0-9][a-z0-9_.-]{0,127}$/; + +/** `identity--8a3e0f52-...` becomes `8a3e0f52`, enough to tell users apart. */ +export const shortIdentity = (identity: string) => + identity.replace(/^identity--/, "").slice(0, 8); + +export const formatStoreDate = (value: string) => + parseDate(value)?.toLocaleDateString("en-GB") || value || "—"; + +export const matchesSearch = (search: string, ...fields: string[]) => { + const needle = search.trim().toLowerCase(); + return !needle || fields.some((f) => f.toLowerCase().includes(needle)); +}; diff --git a/src/utils.ts b/src/utils.ts index b22b3925..5a6e2ee5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -24,6 +24,8 @@ export const PATHS = { DETAIL: "/monitoring/:executionId", }, SETTINGS: "/settings", + SECRETS: "/secrets", + VARIABLES: "/variables", LOGIN: "/login", LOGIN_CALLBACK: "/login/callback", NOT_FOUND: "/are-you-lost",