From 51ba90517c370ca05262ea7666b1aac9fed3b482 Mon Sep 17 00:00:00 2001 From: Derek Date: Mon, 16 Nov 2026 16:08:00 +1100 Subject: [PATCH 01/10] fix(hunts): show and set a hunt's enabled state The Hunts console had no way to see or change whether the runner fires a hunt. - The list row and detail header show Disabled or Auto-disabled. The tooltip shows the stop time and ClickHouse reason. - The detail action menu has Disable, Enable and Re-enable. Each sends a PUT with enabled. - The hunt form has an Enabled switch. Edits send enabled only when the switch changes. Any PUT with enabled true clears a runner stop. - The update request type makes enabled optional. The generated type needs enabled for its default. - Regenerated engine types match the spec and have the engine's other changes. --- .../CloneHuntModal/CloneHuntModal.test.tsx | 1 + .../Hunts/components/CloneHuntModal/index.tsx | 1 + .../components/CreateHuntDrawer/index.tsx | 1 + .../CreateUpdateHuntForm.test.tsx | 45 ++ .../huntTargetTable.test.tsx | 70 ++ .../components/CreateUpdateHuntForm/index.tsx | 12 +- .../HuntStateTag/HuntStateTag.stories.tsx | 33 + .../HuntStateTag/HuntStateTag.test.tsx | 62 ++ .../Hunts/components/HuntStateTag/index.tsx | 41 + .../components/ListHuntsTree/HuntList.tsx | 9 +- .../HuntDetailActionMenu.test.tsx | 125 +++ .../HuntDetailActionMenu/index.tsx | 100 ++- .../Hunts/components/ViewHuntDetail/index.tsx | 9 + .../ConfigurationDetailsTabContent.test.tsx | 1 + .../useCreateHunt/useCreateHunt.test.tsx | 4 + .../useFetchHuntDetail.test.tsx | 1 + .../src/Hunts/hooks/useHuntRunState/index.ts | 16 + .../src/Hunts/hooks/useUpdateHunt/index.tsx | 8 +- .../src/Hunts/hooks/useUpdateHunt/types.ts | 6 +- .../useUpdateHunt/useUpdateHunt.test.tsx | 1 + .../transformHuntDetailToFormData.test.ts | 59 ++ .../transformHuntDetailToFormData.ts | 12 + .../CreateUpdateOrganisationForm.test.tsx | 3 + .../api/endpoints/generator/mocks/hunts.ts | 6 + .../useFetchInfiniteFilteredHunts.mocks.ts | 3 + .../useFetchInfiniteFilteredHunts.test.tsx | 3 + packages/dfe-engine-types/specs/openapi.json | 722 ++++++++++++++---- packages/dfe-engine-types/types/index.d.ts | 506 +++++++++--- 28 files changed, 1597 insertions(+), 263 deletions(-) create mode 100644 apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.stories.tsx create mode 100644 apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx create mode 100644 apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx create mode 100644 apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx create mode 100644 apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/index.ts diff --git a/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/CloneHuntModal.test.tsx b/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/CloneHuntModal.test.tsx index 9eae9b477..caedd09ad 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/CloneHuntModal.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/CloneHuntModal.test.tsx @@ -28,6 +28,7 @@ const hunt: THuntDetailResponse = { global_source_table_name: 'windows_audit', customers: ['acme'], rules: [{ rule_name: 'brute_force' }], + enabled: true, }; const openClone = async (source: THuntDetailResponse) => { diff --git a/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/index.tsx b/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/index.tsx index 23c3232b4..1f6d304cc 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/index.tsx @@ -62,6 +62,7 @@ export const CloneHuntModal = ({ global_source_table_name: hunt.global_source_table_name, customers: hunt.customers ?? [], rules: hunt.rules.map((rule) => rule.rule_name), + enabled: hunt.enabled, ...values, }); }; diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateHuntDrawer/index.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateHuntDrawer/index.tsx index 57f656aea..5aa6140d3 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateHuntDrawer/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateHuntDrawer/index.tsx @@ -99,6 +99,7 @@ export const CreateHuntDrawer = ({ display_name: '', global_target_table_name: '', global_source_table_name: '', + enabled: true, }} /> diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx index 63d4c6168..deb692f26 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx @@ -64,6 +64,7 @@ describe('CreateUpdateHuntForm name', () => { cron: ['*/15 * * * *'], log_buffer: 60, global_source_table_name: 'windows_audit', + enabled: true, }} />, { wrapper }, @@ -86,6 +87,7 @@ describe('CreateUpdateHuntForm cron expressions', () => { cron: ['0 * * * *', '0 0 * * *'], log_buffer: 60, global_source_table_name: 'windows_audit', + enabled: true, }; const renderForm = (onFinish = vi.fn()) => render( @@ -144,6 +146,49 @@ describe('CreateUpdateHuntForm cron expressions', () => { }); }); +describe('CreateUpdateHuntForm enabled', () => { + const stored = { + name: 'windows_audit', + customers: ['acme'], + rules: ['brute_force'], + cron: ['*/15 * * * *'], + log_buffer: 60, + global_source_table_name: 'windows_audit', + enabled: true, + }; + + test.each([ + { case: 'left on', clicks: 0, saved: true }, + { case: 'turned off', clicks: 1, saved: false }, + { case: 'turned off then on', clicks: 2, saved: true }, + ])( + 'saves enabled as the switch holds it, $case', + async ({ clicks, saved }) => { + const onFinish = vi.fn(); + render( + , + { wrapper }, + ); + const toggle = screen.getByRole('switch', { name: 'Enabled' }); + expect(toggle).toBeChecked(); + + for (let i = 0; i < clicks; i++) { + await userEvent.click(toggle); + } + await userEvent.click(screen.getByRole('button', { name: 'Save Hunt' })); + + await waitFor(() => expect(onFinish).toHaveBeenCalledTimes(1)); + expect(onFinish.mock.calls[0]?.[0].enabled).toBe(saved); + }, + ); +}); + describe('CreateUpdateHuntForm refusals', () => { const organisationsField = () => { const item = screen diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx index 2953f85af..9824f71f9 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx @@ -98,6 +98,7 @@ const hunt: THuntDetailResponse = { global_source_table_name: 'windows_audit', customers: ['acme'], rules: [{ rule_name: 'brute_force' }], + enabled: true, }; /** Records the body of the one write the form sends, and answers it. */ @@ -240,3 +241,72 @@ describe('Edit Hunt target and source table', () => { }, ); }); + +describe('Add Hunt enabled', () => { + test.each([ + { case: 'left on', clicks: 0, sent: true }, + { case: 'turned off', clicks: 1, sent: false }, + ])( + 'opens with the switch on and sends enabled: $sent when $case', + { timeout: TEST_TIMEOUT_MS }, + async ({ clicks, sent: expected }) => { + const sent = captureWrite('post', '/api/v1/hunts'); + render(, { wrapper }); + const drawer = await openDrawer('Add Hunt'); + const toggle = drawer.getByRole('switch', { name: 'Enabled' }); + + expect(toggle).toBeChecked(); + await fillNewHunt(drawer, { source: 'windows_audit', target: '' }); + for (let i = 0; i < clicks; i++) { + await userEvent.click(toggle); + } + await userEvent.click(drawer.getByRole('button', { name: 'Add Hunt' })); + + await waitFor(() => expect(sent.body).toBeDefined()); + expect(sent.body).toMatchObject({ enabled: expected }); + }, + ); +}); + +describe('Edit Hunt enabled', () => { + test.each([ + { case: 'an enabled hunt left alone', stored: true, clicks: 0 }, + { case: 'a disabled hunt left alone', stored: false, clicks: 0 }, + { + case: 'an enabled hunt switched off', + stored: true, + clicks: 1, + sent: false, + }, + { + case: 'a disabled hunt switched on', + stored: false, + clicks: 1, + sent: true, + }, + ])( + 'names enabled only when it changed: $case', + { timeout: TEST_TIMEOUT_MS }, + async ({ stored, clicks, sent: expected }) => { + const sent = captureWrite('put', '/api/v1/hunts/windows_audit'); + render(, { + wrapper, + }); + const drawer = await openDrawer('Edit Hunt'); + const toggle = drawer.getByRole('switch', { name: 'Enabled' }); + + expect(toggle.getAttribute('aria-checked')).toBe(String(stored)); + for (let i = 0; i < clicks; i++) { + await userEvent.click(toggle); + } + await userEvent.click(drawer.getByRole('button', { name: 'Edit Hunt' })); + + await waitFor(() => expect(sent.body).toBeDefined()); + if (expected === undefined) { + expect(sent.body).not.toHaveProperty('enabled'); + } else { + expect(sent.body).toMatchObject({ enabled: expected }); + } + }, + ); +}); diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx index bc349b1ab..dfbffa3fc 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx @@ -7,7 +7,7 @@ import { useAntdZodResolver } from '@/core/utils/zod/useAntdZodResolver'; import { RULE_HUNT_NAME_VALIDATOR } from '@/core/validationSchemas/utils'; import { CRONBuilderDrawer } from '@/Hunts/components/CRONBuilderDrawer'; import { IconDeviceFloppy, IconPlus, IconTrash } from '@repo/dfe-icons'; -import { Button, FormProps, Input } from 'antd'; +import { Button, FormProps, Input, Switch } from 'antd'; import { useEffect, useMemo } from 'react'; import z from 'zod'; import { RuleSelect } from './RuleSelectCreate'; @@ -53,6 +53,7 @@ const buildFormSchema = (nameIsNew: boolean) => log_buffer: z .number({ message: 'Log buffer is required' }) .min(1, { message: 'Log buffer is required' }), + enabled: z.boolean(), }); export type CreateUpdateHuntFormData = z.infer< ReturnType @@ -196,6 +197,15 @@ export const CreateUpdateHuntForm = ({ )} + + + + {error && !unknownOrg && }
diff --git a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.stories.tsx b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.stories.tsx new file mode 100644 index 000000000..31ebd25c1 --- /dev/null +++ b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.stories.tsx @@ -0,0 +1,33 @@ +import type { Meta, StoryObj } from '@storybook/nextjs-vite'; +import { HuntStateTag } from './index'; + +const meta: Meta = { + title: 'Hunts/HuntStateTag', + component: HuntStateTag, + tags: ['autodocs'], + argTypes: { + enabled: { control: 'boolean' }, + autoDisabledAt: { control: 'number' }, + autoDisabledReason: { control: 'text' }, + }, +}; + +export default meta; + +type Story = StoryObj; + +export const Running: Story = { + args: { enabled: true }, +}; + +export const Disabled: Story = { + args: { enabled: false }, +}; + +export const AutoDisabled: Story = { + args: { + enabled: false, + autoDisabledAt: 1_763_300_000, + autoDisabledReason: 'resource_limit:241', + }, +}; diff --git a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx new file mode 100644 index 000000000..858f0f4af --- /dev/null +++ b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx @@ -0,0 +1,62 @@ +import { buildTestWrapper } from '@/core/utils/test-utils/buildTestWrapper'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it } from 'vitest'; +import { HuntStateTag } from '.'; + +const { wrapper } = buildTestWrapper().withTheme(); + +describe('HuntStateTag', () => { + it.each([ + { + case: 'an enabled hunt renders nothing', + props: { enabled: true, autoDisabledAt: null }, + tag: null, + tooltip: null, + }, + { + case: 'a hunt with no state renders nothing', + props: {}, + tag: null, + tooltip: null, + }, + { + case: 'a disabled hunt reads Disabled', + props: { enabled: false }, + tag: 'Disabled', + tooltip: + /^This hunt fires nothing\. Its configuration, state and watermark are kept\.$/, + }, + { + case: 'an auto-disabled hunt reads Auto-disabled and names the reason', + props: { + enabled: false, + autoDisabledAt: 1_763_300_000, + autoDisabledReason: 'resource_limit:241', + }, + tag: 'Auto-disabled', + tooltip: + /after repeated ClickHouse resource-limit failures \(resource_limit:241\)\. Re-enable the hunt to clear it\./, + }, + { + case: 'the auto-disable wins over a plain disable', + props: { enabled: false, autoDisabledAt: 1_763_300_000 }, + tag: 'Auto-disabled', + tooltip: + /^Stopped .* after repeated ClickHouse resource-limit failures\./, + }, + ])('$case', async ({ props, tag, tooltip }) => { + render(, { wrapper }); + + if (tag === null) { + expect(screen.queryByText(/disabled/i)).not.toBeInTheDocument(); + return; + } + const shown = screen.getByText(tag); + expect(shown).toBeInTheDocument(); + if (tooltip !== null) { + await userEvent.hover(shown); + expect(await screen.findByText(tooltip)).toBeInTheDocument(); + } + }); +}); diff --git a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx new file mode 100644 index 000000000..afbd297cc --- /dev/null +++ b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx @@ -0,0 +1,41 @@ +import { Tooltip } from '@/core/components/Tooltip'; +import { formatEpochSecondsLocal } from '@/core/helpers/date.helpers'; +import { Tag } from 'antd'; + +interface HuntStateTagProps { + enabled?: boolean | null; + autoDisabledAt?: number | null; + autoDisabledReason?: string | null; + className?: string; +} + +/** A tag for a hunt the runner is not firing, and nothing for one it is. */ +export const HuntStateTag = ({ + enabled, + autoDisabledAt, + autoDisabledReason, + className, +}: HuntStateTagProps) => { + if (autoDisabledAt != null) { + const reason = autoDisabledReason ? ` (${autoDisabledReason})` : ''; + return ( + + + Auto-disabled + + + ); + } + + if (enabled === false) { + return ( + + Disabled + + ); + } + + return null; +}; diff --git a/apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.tsx b/apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.tsx index 44b9ba9aa..1a0e95b61 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.tsx @@ -3,6 +3,7 @@ import { CustomScrollbar } from '@/core/components/CustomScrollbar'; import { THuntListItem } from '@/core/hooks/useFetchInfiniteFilteredHunts/types'; import { useSetComponentHeight } from '@/core/hooks/useSetComponentHeight'; import { cn } from '@/core/utils/style'; +import { HuntStateTag } from '@/Hunts/components/HuntStateTag'; import { Spin } from 'antd'; import { EmptyList } from './EmptyList'; import { ErrorList } from './ErrorList'; @@ -75,7 +76,13 @@ export const HuntList = ({ )} onClick={() => setSelectedHuntName(hunt.name)} > - {hunt.display_name} + {hunt.display_name} + ); diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx new file mode 100644 index 000000000..feff04454 --- /dev/null +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx @@ -0,0 +1,125 @@ +import { server } from '@/core/components/RbacProtected/hooks/hooks.mocks'; +import { buildTestWrapper } from '@/core/utils/test-utils/buildTestWrapper'; +import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { App } from 'antd'; +import { http, HttpResponse } from 'msw'; +import type { ReactElement, ReactNode } from 'react'; +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from 'vitest'; +import { HuntDetailActionMenu } from '.'; + +// Edit, Clone and Delete reach their own APIs. What is under test is the enable action. +vi.mock('@/Hunts/components/UpdateHuntDrawer', () => ({ + UpdateHuntDrawer: ({ trigger }: { trigger: ReactElement }) => trigger, +})); +vi.mock('@/Hunts/components/CloneHuntModal', () => ({ + CloneHuntModal: ({ trigger }: { trigger: ReactElement }) => trigger, +})); +vi.mock('@/Hunts/components/DeleteHuntModal', () => ({ + DeleteHuntModal: ({ trigger }: { trigger: ReactElement }) => trigger, +})); + +const listed = vi.hoisted(() => ({ + autoDisabledAt: null as number | null, +})); +vi.mock('@/Hunts/contexts/ListHuntsContext', () => ({ + useListHuntsContext: () => ({ + setSelectedHuntName: vi.fn(), + data: { + items: [ + { + name: 'windows_audit', + auto_disabled_at: listed.autoDisabledAt, + auto_disabled_reason: 'resource_limit:241', + }, + ], + }, + }), +})); + +beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); +afterEach(() => { + server.resetHandlers(); + listed.autoDisabledAt = null; +}); +afterAll(() => server.close()); + +const { wrapper: Providers } = buildTestWrapper().withTheme().withReactQuery(); +const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + +); + +const hunt: THuntDetailResponse = { + name: 'windows_audit', + display_name: 'Windows audit', + cron: '*/5 * * * *', + log_buffer: 60, + global_target_table_name: 'alerts', + global_source_table_name: 'windows_audit', + customers: ['acme'], + rules: [{ rule_name: 'brute_force' }], + enabled: true, +}; + +describe('HuntDetailActionMenu enable action', () => { + it.each([ + { + case: 'an enabled hunt', + enabled: true, + autoDisabledAt: null, + label: 'Disable Hunt', + sent: false, + notice: 'Hunt Windows audit disabled', + }, + { + case: 'a disabled hunt', + enabled: false, + autoDisabledAt: null, + label: 'Enable Hunt', + sent: true, + notice: 'Hunt Windows audit enabled', + }, + { + case: 'a hunt the runner stopped', + enabled: false, + autoDisabledAt: 1_763_300_000, + label: 'Re-enable Hunt', + sent: true, + notice: 'Hunt Windows audit enabled', + }, + ])( + 'offers $label for $case and sends enabled: $sent', + async ({ enabled, autoDisabledAt, label, sent: expected, notice }) => { + listed.autoDisabledAt = autoDisabledAt; + let body: Record | undefined; + server.use( + http.put('/api/v1/hunts/windows_audit', async ({ request }) => { + body = (await request.json()) as Record; + return HttpResponse.json(hunt); + }), + ); + render(, { wrapper }); + + await userEvent.click(await screen.findByRole('button', { name: label })); + + await waitFor(() => expect(body).toBeDefined()); + expect(body).toMatchObject({ + enabled: expected, + cron: '*/5 * * * *', + global_source_table_name: 'windows_audit', + }); + expect(await screen.findByText(notice)).toBeInTheDocument(); + }, + ); +}); diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx index fcaa943c9..a7f2c18de 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx @@ -1,4 +1,6 @@ import { ActionsMenu } from '@/core/components/ActionsMenu'; +import { ApiErrorNotification } from '@/core/components/ApiErrorNotification'; +import { RbacProtected } from '@/core/components/RbacProtected'; import { QUERY_KEYS } from '@/core/config/api/endpoints/queryKeys'; import { CloneHuntModal } from '@/Hunts/components/CloneHuntModal'; import { DeleteHuntModal } from '@/Hunts/components/DeleteHuntModal'; @@ -6,8 +8,20 @@ import { UpdateHuntDrawer } from '@/Hunts/components/UpdateHuntDrawer'; import { useListHuntsContext } from '@/Hunts/contexts/ListHuntsContext'; import { THuntCreateResponse } from '@/Hunts/hooks/useCreateHunt/types'; import { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; +import { useHuntRunState } from '@/Hunts/hooks/useHuntRunState'; +import { useUpdateHunt } from '@/Hunts/hooks/useUpdateHunt'; import { THuntUpdateResponse } from '@/Hunts/hooks/useUpdateHunt/types'; -import { IconCopy, IconEdit, IconTrash } from '@repo/dfe-icons'; +import { + transformHuntDetailToFormData, + transformHuntFormDataToUpdateRequest, +} from '@/Hunts/utils/transformHuntData/transformHuntDetailToFormData'; +import { + IconCopy, + IconEdit, + IconPlayerPause, + IconPlayerPlay, + IconTrash, +} from '@repo/dfe-icons'; import { useQueryClient } from '@tanstack/react-query'; import { App, Button } from 'antd'; @@ -16,6 +30,85 @@ interface HuntDetailActionMenuProps { hunt: THuntDetailResponse; } +/** Disable, Enable, or Re-enable, which also clears a stop the runner made. */ +const ToggleHuntEnabled = ({ + hunt, + onSuccess, +}: { + hunt: THuntDetailResponse; + onSuccess: (hunt: THuntUpdateResponse) => void; +}) => { + const { notification } = App.useApp(); + const { enabled, autoDisabledAt } = useHuntRunState(hunt); + const autoDisabled = autoDisabledAt != null; + const turnOn = autoDisabled || enabled === false; + const label = autoDisabled + ? 'Re-enable Hunt' + : turnOn + ? 'Enable Hunt' + : 'Disable Hunt'; + const Icon = turnOn ? IconPlayerPlay : IconPlayerPause; + const huntLabel = hunt.display_name || hunt.name; + + const { mutate, isPending } = useUpdateHunt({ + name: hunt.name, + onSuccess: (response) => { + onSuccess(response); + notification.success({ + title: `Hunt ${huntLabel} ${turnOn ? 'enabled' : 'disabled'}`, + placement: 'bottomLeft', + }); + }, + onError: (error) => { + notification.error({ + title: `Hunt ${huntLabel} was not ${turnOn ? 'enabled' : 'disabled'}`, + description: , + placement: 'bottomLeft', + }); + }, + }); + + const toggle = () => + mutate({ + ...transformHuntFormDataToUpdateRequest( + transformHuntDetailToFormData(hunt), + hunt, + ), + enabled: turnOn, + }); + + return ( + + + + + + + + + ); +}; + export const HuntDetailActionMenu = ({ hunt, onEditSuccess: onEditSuccessProp, @@ -75,6 +168,11 @@ export const HuntDetailActionMenu = ({ } onSuccess={onEditSuccess} /> + { + const state = useHuntRunState(hunt); + return ; +}; + export const ViewHuntDetail = () => { const { selectedHuntName } = useListHuntsContext(); const { @@ -57,6 +65,7 @@ export const ViewHuntDetail = () => { Hunt Configuration: {huntDetail.display_name ?? huntDetail.name} +
diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntTabs/ConfigurationDetailsTabContent/ConfigurationDetailsTabContent.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntTabs/ConfigurationDetailsTabContent/ConfigurationDetailsTabContent.test.tsx index 52dac7708..3c43a6cc4 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntTabs/ConfigurationDetailsTabContent/ConfigurationDetailsTabContent.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntTabs/ConfigurationDetailsTabContent/ConfigurationDetailsTabContent.test.tsx @@ -17,6 +17,7 @@ const hunt = (cron: THuntDetailResponse['cron']): THuntDetailResponse => ({ scheduling_mode: null, min_interval_seconds: null, explain_queries: null, + enabled: true, }); describe('ConfigurationDetailsTabContent cron', () => { diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useCreateHunt/useCreateHunt.test.tsx b/apps/dfe-core-ui/src/Hunts/hooks/useCreateHunt/useCreateHunt.test.tsx index 195eee6ba..62e487ced 100644 --- a/apps/dfe-core-ui/src/Hunts/hooks/useCreateHunt/useCreateHunt.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/hooks/useCreateHunt/useCreateHunt.test.tsx @@ -35,6 +35,7 @@ describe('.useCreateHunt', () => { global_source_table_name: 'string', customers: ['string'], rules: ['string'], + enabled: true, }; describe('onSuccess', () => { test('should call onSuccess', async () => { @@ -55,6 +56,7 @@ describe('.useCreateHunt', () => { customers: requestBody.customers, rules: requestBody.rules, display_name: requestBody.display_name, + enabled: requestBody.enabled, }); const expectedResponse: THuntCreateResponse = { @@ -79,6 +81,7 @@ describe('.useCreateHunt', () => { checkpoint_timestamp_field: 'string', scheduling_mode: 'string', min_interval_seconds: 0, + enabled: true, explain_queries: false, }; @@ -123,6 +126,7 @@ describe('.useCreateHunt', () => { customers: requestBody.customers, rules: requestBody.rules, display_name: requestBody.display_name, + enabled: requestBody.enabled, }); await waitFor(() => { diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useFetchHuntDetail/useFetchHuntDetail.test.tsx b/apps/dfe-core-ui/src/Hunts/hooks/useFetchHuntDetail/useFetchHuntDetail.test.tsx index fea5fb4dc..9462fa6c6 100644 --- a/apps/dfe-core-ui/src/Hunts/hooks/useFetchHuntDetail/useFetchHuntDetail.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/hooks/useFetchHuntDetail/useFetchHuntDetail.test.tsx @@ -48,6 +48,7 @@ describe('.useFetchHuntDetail', () => { checkpoint_timestamp_field: 'string', scheduling_mode: 'string', min_interval_seconds: 0, + enabled: true, }; await waitFor(() => { diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/index.ts b/apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/index.ts new file mode 100644 index 000000000..aa0a3e390 --- /dev/null +++ b/apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/index.ts @@ -0,0 +1,16 @@ +import { useListHuntsContext } from '@/Hunts/contexts/ListHuntsContext'; +import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; + +/** The detail carries `enabled` only, so the runner's stop comes from the list row. */ +export const useHuntRunState = (hunt: THuntDetailResponse) => { + const { + data: { items }, + } = useListHuntsContext(); + const listed = items.find((item) => item.name === hunt.name); + + return { + enabled: hunt.enabled, + autoDisabledAt: listed?.auto_disabled_at, + autoDisabledReason: listed?.auto_disabled_reason, + }; +}; diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/index.tsx b/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/index.tsx index ca5cbca5a..d3762c68e 100644 --- a/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/index.tsx @@ -1,7 +1,11 @@ import { QUERY_KEYS } from '@/core/config/api/endpoints/queryKeys'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { updateHunt } from './api'; -import { THuntUpdateRequest, THuntUpdateResponse } from './types'; +import { + THuntUpdateBody, + THuntUpdateRequest, + THuntUpdateResponse, +} from './types'; export const useUpdateHunt = ({ name, @@ -16,7 +20,7 @@ export const useUpdateHunt = ({ const { data, mutate, isPending, error } = useMutation({ mutationFn: (hunt: THuntUpdateRequest) => updateHunt({ - body: hunt, + body: hunt as THuntUpdateBody, pathParams: { name }, }), onSuccess: (data) => { diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/types.ts b/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/types.ts index 48a4e8366..ccf1799a3 100644 --- a/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/types.ts +++ b/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/types.ts @@ -5,9 +5,13 @@ import { } from '@/core/config/api/client.types'; import { updateHuntPath } from './api'; -export type THuntUpdateRequest = DfeClientRequestBody< +export type THuntUpdateBody = DfeClientRequestBody< DfeClientOperationFor >; +/** The spec requires `enabled` for its default, yet a PUT that omits it leaves the hunt as it is. */ +export type THuntUpdateRequest = Omit & { + enabled?: THuntUpdateBody['enabled']; +}; export type THuntUpdateResponse = DfeClientSuccessResponseBody< DfeClientOperationFor >; diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/useUpdateHunt.test.tsx b/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/useUpdateHunt.test.tsx index 885e9bacf..927354d6d 100644 --- a/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/useUpdateHunt.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/useUpdateHunt.test.tsx @@ -85,6 +85,7 @@ describe('.useUpdateHunt', () => { checkpoint_timestamp_field: 'string', scheduling_mode: 'string', min_interval_seconds: 0, + enabled: true, }; await waitFor(() => { diff --git a/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts b/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts index e164544f6..aad009d0c 100644 --- a/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts +++ b/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts @@ -29,6 +29,7 @@ const huntDetail: THuntDetailResponse = { scheduling_mode: null, min_interval_seconds: null, explain_queries: null, + enabled: true, }; describe('transformHuntDetailToFormData', () => { @@ -42,10 +43,21 @@ describe('transformHuntDetailToFormData', () => { rules: ['rule_one'], global_target_table_name: 'target', global_source_table_name: '', + enabled: true, }; expect(transformHuntDetailToFormData(huntDetail)).toEqual(expectedFormData); }); + it.each([ + { case: 'enabled', stored: true, shown: true }, + { case: 'disabled', stored: false, shown: false }, + { case: 'storing no state, as enabled', stored: undefined, shown: true }, + ])('opens a hunt $case with the switch $shown', ({ stored, shown }) => { + const hunt = { ...huntDetail, enabled: stored } as THuntDetailResponse; + + expect(transformHuntDetailToFormData(hunt).enabled).toBe(shown); + }); + it('opens a stored hunt naming no organisation with none selected', () => { const { customers: _customers, ...namingNone } = huntDetail; @@ -136,6 +148,42 @@ describe('transformHuntFormDataToUpdateRequest', () => { expect(transformHuntDetailToFormData(hunt).cron).toEqual(expected); }); + it.each([ + { case: 'leaves an enabled hunt alone', stored: true, form: true }, + { case: 'leaves a disabled hunt alone', stored: false, form: false }, + { + case: 'leaves a hunt storing no state alone', + stored: undefined, + form: true, + }, + { + case: 'names false when an enabled hunt is switched off', + stored: true, + form: false, + sent: false, + }, + { + case: 'names true when a disabled hunt is switched on', + stored: false, + form: true, + sent: true, + }, + ])('enabled: $case', ({ stored, form, sent }) => { + const hunt = { ...huntDetail, enabled: stored } as THuntDetailResponse; + const formValues = { + ...transformHuntDetailToFormData(hunt), + enabled: form, + }; + + const request = transformHuntFormDataToUpdateRequest(formValues, hunt); + + if (sent === undefined) { + expect(request).not.toHaveProperty('enabled'); + } else { + expect(request.enabled).toBe(sent); + } + }); + it.each(['', ' ', null, undefined])( 'sends no target table key when the form value is %j', (blank) => { @@ -162,6 +210,7 @@ describe('transformHuntFormDataToCreateRequest', () => { rules: ['rule_one'], global_source_table_name: 'windows_audit', global_target_table_name: 'alerts', + enabled: true, }; it('sends the form as it is when both tables are filled', () => { @@ -171,6 +220,16 @@ describe('transformHuntFormDataToCreateRequest', () => { }); }); + it.each([true, false])( + 'sends enabled: %j as the form holds it', + (enabled) => { + expect( + transformHuntFormDataToCreateRequest({ ...formValues, enabled }) + .enabled, + ).toBe(enabled); + }, + ); + it('sends every expression when the form holds several', () => { const cron = ['*/15 * * * *', '0 0 * * *']; diff --git a/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.ts b/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.ts index 09c9de5a5..af215b8ce 100644 --- a/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.ts +++ b/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.ts @@ -25,6 +25,7 @@ export const transformHuntDetailToFormData = ( rules: hunt.rules.map((rule) => rule.rule_name), global_target_table_name: hunt.global_target_table_name ?? '', global_source_table_name: hunt.global_source_table_name ?? '', + enabled: hunt.enabled ?? true, }); /** @@ -43,6 +44,16 @@ export const transformHuntFormDataToCreateRequest = ( return { ...rest, cron: cronForRequest(cron), ...targetTableField(values) }; }; +/** + * An edit that leaves the switch alone must not name `enabled`, because the + * engine clears a runner stop on any PUT that names it true. + */ +const enabledField = ( + values: CreateUpdateHuntFormData, + hunt: THuntDetailResponse, +) => + values.enabled !== (hunt.enabled ?? true) ? { enabled: values.enabled } : {}; + export const transformHuntFormDataToUpdateRequest = ( values: CreateUpdateHuntFormData, hunt: THuntDetailResponse, @@ -58,4 +69,5 @@ export const transformHuntFormDataToUpdateRequest = ( scheduling_mode: hunt.scheduling_mode ?? null, min_interval_seconds: hunt.min_interval_seconds ?? null, explain_queries: hunt.explain_queries ?? null, + ...enabledField(values, hunt), }); diff --git a/apps/dfe-core-ui/src/core/components/CreateUpdateOrganisationForm/CreateUpdateOrganisationForm.test.tsx b/apps/dfe-core-ui/src/core/components/CreateUpdateOrganisationForm/CreateUpdateOrganisationForm.test.tsx index 3c0ce2c46..847bab72a 100644 --- a/apps/dfe-core-ui/src/core/components/CreateUpdateOrganisationForm/CreateUpdateOrganisationForm.test.tsx +++ b/apps/dfe-core-ui/src/core/components/CreateUpdateOrganisationForm/CreateUpdateOrganisationForm.test.tsx @@ -197,6 +197,9 @@ describe('CreateUpdateOrganisationForm refusals', () => { running: false, too_aggressive: false, run_requested: false, + enabled: true, + auto_disabled_at: null, + auto_disabled_reason: '', }; const oldOrg = { name: 'oldco', diff --git a/apps/dfe-core-ui/src/core/config/api/endpoints/generator/mocks/hunts.ts b/apps/dfe-core-ui/src/core/config/api/endpoints/generator/mocks/hunts.ts index 7c07dca83..72944ef0f 100644 --- a/apps/dfe-core-ui/src/core/config/api/endpoints/generator/mocks/hunts.ts +++ b/apps/dfe-core-ui/src/core/config/api/endpoints/generator/mocks/hunts.ts @@ -27,6 +27,9 @@ export const hunts = { running: false, too_aggressive: false, run_requested: false, + enabled: true, + auto_disabled_at: null, + auto_disabled_reason: '', }, ], total_size: 0, @@ -76,6 +79,7 @@ export const hunts = { scheduling_mode: 'string', min_interval_seconds: 0, explain_queries: false, + enabled: true, }, }: { mockedResponse?: THuntCreateResponse; @@ -142,6 +146,7 @@ export const hunts = { checkpoint_timestamp_field: 'string', scheduling_mode: 'string', min_interval_seconds: 0, + enabled: true, }, name = 'name', }: { @@ -177,6 +182,7 @@ export const hunts = { checkpoint_timestamp_field: 'string', scheduling_mode: 'string', min_interval_seconds: 0, + enabled: true, }, name = 'name', }: { diff --git a/apps/dfe-core-ui/src/core/hooks/useFetchInfiniteFilteredHunts/useFetchInfiniteFilteredHunts.mocks.ts b/apps/dfe-core-ui/src/core/hooks/useFetchInfiniteFilteredHunts/useFetchInfiniteFilteredHunts.mocks.ts index b80ea9cca..0bcbf7c2b 100644 --- a/apps/dfe-core-ui/src/core/hooks/useFetchInfiniteFilteredHunts/useFetchInfiniteFilteredHunts.mocks.ts +++ b/apps/dfe-core-ui/src/core/hooks/useFetchInfiniteFilteredHunts/useFetchInfiniteFilteredHunts.mocks.ts @@ -15,6 +15,9 @@ const HUNT_ITEM: THuntListItem = { running: false, too_aggressive: false, run_requested: false, + enabled: true, + auto_disabled_at: null, + auto_disabled_reason: '', } as const; const TOTAL_ITEMS = 25; diff --git a/apps/dfe-core-ui/src/core/hooks/useFetchInfiniteFilteredHunts/useFetchInfiniteFilteredHunts.test.tsx b/apps/dfe-core-ui/src/core/hooks/useFetchInfiniteFilteredHunts/useFetchInfiniteFilteredHunts.test.tsx index d615a7349..357c80a85 100644 --- a/apps/dfe-core-ui/src/core/hooks/useFetchInfiniteFilteredHunts/useFetchInfiniteFilteredHunts.test.tsx +++ b/apps/dfe-core-ui/src/core/hooks/useFetchInfiniteFilteredHunts/useFetchInfiniteFilteredHunts.test.tsx @@ -73,6 +73,9 @@ describe('useFetchInfiniteFilteredHunts', () => { running: false, too_aggressive: false, run_requested: false, + enabled: true, + auto_disabled_at: null, + auto_disabled_reason: '', }; expect(result.current.data).toBeDefined(); diff --git a/packages/dfe-engine-types/specs/openapi.json b/packages/dfe-engine-types/specs/openapi.json index 67d31ebd4..3ecb41947 100644 --- a/packages/dfe-engine-types/specs/openapi.json +++ b/packages/dfe-engine-types/specs/openapi.json @@ -2,8 +2,8 @@ "openapi": "3.1.0", "info": { "title": "DFE Engine API", - "description": "Data Fusion Engine -- configuration, scheduling, and query API", - "version": "1.22.80" + "description": "Configuration, scheduling and query API for the Data Fusion Engine.\n\nEvery route sits under `/api/v1` on the engine URL your deployment publishes. Get a token with `POST /api/v1/auth/login` (JSON body `username` and `password`, the console's accounts work here), then send it as `Authorization: Bearer ` on every other call.", + "version": "1.22.91" }, "paths": { "/api/v1/auth/login": { @@ -12,7 +12,7 @@ "Auth" ], "summary": "Login", - "description": "Authenticate with local credentials and receive a JWT token.\n\nThe password check runs off the event loop. Failed attempts back off per\nusername and per client address (``auth.login_throttle``); a waiting attempt is\nrefused with 429 before the password is checked.", + "description": "Authenticate with local credentials and receive a JWT token.\n\nThe password check runs off the event loop. Failed attempts back off per\nusername and per client address (``auth.login_throttle``). A waiting attempt is\nrefused with 429 before the password is checked.", "operationId": "auth.login", "requestBody": { "content": { @@ -46,7 +46,7 @@ } }, "403": { - "description": "The break-glass account is disabled in governance settings", + "description": "The break-glass password is right, but the account is disabled in governance settings", "content": { "application/problem+json": { "schema": { @@ -243,7 +243,7 @@ "Auth" ], "summary": "Get Me", - "description": "Get the current authenticated user's info.\n\nA session on an issued password reports the flag and no roles, permissions,\ngroups or orgs, because its token carries none until the change.\n\n``hyperdx_role`` and ``hyperdx_identity`` are what dfe-hyperdx takes a\nsession's dashboard role and team from; it caches this answer for 30 seconds,\nso a group change reaches HyperDX in that window rather than at token expiry.", + "description": "Get the current authenticated user's info.\n\nA session on an issued password reports the flag and no roles, permissions,\ngroups or orgs, because its token carries none until the change.\n\n``hyperdx_role`` and ``hyperdx_identity`` are what dfe-hyperdx takes a\nsession's dashboard role and team from. It caches this answer for 30 seconds,\nso a group change reaches dfe-hyperdx in that window rather than at token expiry.", "operationId": "auth.me.list", "responses": { "200": { @@ -387,7 +387,7 @@ "Auth" ], "summary": "Get Setup Status", - "description": "Report first-run setup state and what is configured (no auth -- pre-login UI).\n\nDriven by the setup state machine (``state_machines/setup.py``). The\nregistries the wizard renders -- OIDC providers and organisations -- are\nreturned while setup is outstanding and dropped once it completes, so a\nconfigured deployment does not serve its inventory to anonymous callers.\nThe exception is the name and display name of each enabled OIDC provider,\nwhich stay (no configuration) because the login screen needs to know which\nIdPs to offer and what to call them. Accounts are never returned; the\n``first_user`` step reports whether a real (non break-glass) user exists.", + "description": "Report first-run setup state and what is configured (no auth -- pre-login UI).\n\nDriven by the setup state machine (``state_machines/setup.py``). The\nregistries the wizard renders -- OIDC providers and organisations -- are\nreturned while setup is outstanding and dropped once it completes, so a\nconfigured deployment does not serve its inventory to anonymous callers.\nThe exception is the name and display name of each enabled OIDC provider,\nwhich stay (no configuration) because the login screen needs to know which\nIdPs to offer and what to call them. Accounts are never returned. The\n``first_user`` step reports whether a real (non break-glass) user exists.", "operationId": "auth.setup-status.list", "responses": { "200": { @@ -1757,7 +1757,7 @@ "Accounts" ], "summary": "Account Git Status", - "description": "Poll whether an account's password has merged to the deploy repo's main.\n\nStep 2 of the review-PR path for the local admin and ``breakglass``: the UI\npolls this after the operator merges the PR; it fetches remote main and flips\n``merged`` true. Durable immediately in the auto-merge and file-share modes. A\nregular user is never git-persisted, so it reports not-git-backed (durable in\nits own store).", + "description": "Poll whether an account's password has merged to the deploy repo's main.\n\nStep 2 of the review-PR path for the local admin and ``breakglass``: the UI\npolls this after the operator merges the PR. It fetches remote main and flips\n``merged`` true. Durable immediately in the auto-merge and file-share modes. A\nregular user is never git-persisted, so it reports not-git-backed (durable in\nits own store).", "operationId": "auth.accounts.git-status", "parameters": [ { @@ -2771,7 +2771,7 @@ "Groups" ], "summary": "Add Member", - "description": "Add a member to a group (idempotent; checked at the group's scope).", + "description": "Add a member to a group (idempotent, checked at the group's scope).", "operationId": "auth.groups.members.create", "parameters": [ { @@ -4763,7 +4763,7 @@ "OIDC Providers" ], "summary": "Update Provider", - "description": "Update an OIDC provider configuration (admin only).\n\nA secret the body omits, value and env var name alike, keeps what the provider already holds, so an update that only flips ``enabled`` does not strand a stored credential; an empty env var name clears the name and keeps the stored copy. A secret the body names an env var for and sends no value for moves onto that env var and its stored copy is deleted once the update is saved, unless the name is the one already held with nothing stored. A move onto an env var the engine does not set is refused (``env_var_not_set``). Any update that touches more than ``enabled`` or ``display_name`` must leave the provider passing the field rules. Both are checked before a secret is written or deleted.", + "description": "Update an OIDC provider configuration (admin only).\n\nA secret the body omits, value and env var name alike, keeps what the provider already holds, so an update that only flips ``enabled`` does not strand a stored credential. An empty env var name clears the name and keeps the stored copy. A secret the body names an env var for and sends no value for moves onto that env var and its stored copy is deleted once the update is saved, unless the name is the one already held with nothing stored. A move onto an env var the engine does not set is refused (``env_var_not_set``). Any update that touches more than ``enabled`` or ``display_name`` must leave the provider passing the field rules. Both are checked before a secret is written or deleted.", "operationId": "auth.oidc-providers.apply", "parameters": [ { @@ -5241,7 +5241,7 @@ "Organisations" ], "summary": "Create Org", - "description": "Create a new customer organisation (admin only).\n\nIf HyperDX integration is enabled, the lifecycle manager handles\nteam creation as part of org provisioning. Failure is non-fatal.\n\nA hunt already naming the org, such as one whose org was deleted, has the new\norg's tenant ids stored first. A production+team posture routes that hunt\nchange to review, and the ``X-DFE-Review-Required`` header says so.", + "description": "Create a new customer organisation (admin only).\n\nIf the Search integration is enabled, the lifecycle manager handles\nteam creation as part of org provisioning. Failure is non-fatal.\n\nA hunt already naming the org, such as one whose org was deleted, has the new\norg's tenant ids stored first. A production+team posture routes that hunt\nchange to review, and the ``X-DFE-Review-Required`` header says so.", "operationId": "orgs.create", "requestBody": { "required": true, @@ -5331,7 +5331,7 @@ "Organisations" ], "summary": "List Orgs", - "description": "List organisations visible to the caller, paginated.\n\nSystem-scope org:read holders see every org; org-scope holders see\nonly the orgs their grants cover.", + "description": "List organisations visible to the caller, paginated.\n\nSystem-scope org:read holders see every org. Org-scope holders see\nonly the orgs their grants cover.", "operationId": "orgs.list", "parameters": [ { @@ -5502,14 +5502,20 @@ "in": "query", "required": false, "schema": { - "type": "integer", - "maximum": 1000, - "minimum": 1, - "description": "Most tenant ids to return -- a suggestion list, not an export", - "default": 200, + "anyOf": [ + { + "type": "integer", + "maximum": 1000, + "minimum": 1 + }, + { + "type": "null" + } + ], + "description": "Most tenant ids to return -- a suggestion list, not an export. Unset takes orgs.available_ids_limit (200 by default)", "title": "Limit" }, - "description": "Most tenant ids to return -- a suggestion list, not an export" + "description": "Most tenant ids to return -- a suggestion list, not an export. Unset takes orgs.available_ids_limit (200 by default)" } ], "responses": { @@ -6570,7 +6576,7 @@ "Sources" ], "summary": "List Sources", - "description": "List sources with pagination, search, filtering, and a full object tree.\n\nThe landing source (``main``) is always the first item when it is in the\nresult set; remaining sources keep the requested sort. A caller held to its\norgs does not see a fetcher source bound to another org.", + "description": "List sources with pagination, search, filtering, and a full object tree.\n\nThe landing source (``main``) is always the first item when it is in the\nresult set. Remaining sources keep the requested sort. A caller held to its\norgs does not see a fetcher source bound to another org.", "operationId": "sources.list", "parameters": [ { @@ -8400,7 +8406,7 @@ "Sources" ], "summary": "Delete Source", - "description": "Delete a source by name. Its fetcher instance, receiver rule and topics go with it.\n\nAn engine-owned source -- the landing table's own -- is refused with 409\n``conflict``, the same answer PUT and PATCH give.\n\nThe answer reports the reconcile as a create or an update does: on a\ndeployment that renders the app config itself, ``restart_required`` names the\ncommand that takes away the containers the source's instances ran in.\n\nA delete production+team sends to review answers ``review_required`` and\ntouches nothing else: main still carries the source, so its topics, records and\nHyperDX source stay until the branch is merged.", + "description": "Delete a source by name. Its fetcher instance, receiver rule and topics go with it.\n\nAn engine-owned source -- the landing table's own -- is refused with 409\n``conflict``, the same answer PUT and PATCH give.\n\nThe answer reports the reconcile as a create or an update does: on a\ndeployment that renders the app config itself, ``restart_required`` names the\ncommand that takes away the containers the source's instances ran in.\n\nA delete production+team sends to review answers ``review_required`` and\ntouches nothing else: main still carries the source, so its topics, records and\nSearch source stay until the branch is merged.", "operationId": "sources.delete", "parameters": [ { @@ -8689,7 +8695,7 @@ "Sources" ], "summary": "Get Source Signals", - "description": "Whether this source's records are arriving, and how fast.\n\nReads the loader's per-table counter out of the otel tables over a bounded\nfive-minute window, so the console can put a number beside a source without\nthe operator opening HyperDX. It answers 200 with nulls where the series is\nabsent: a source that was only just defined has nothing to report, and that\nis not an error.", + "description": "Whether this source's records are arriving, and how fast.\n\nReads the loader's per-table counter out of the otel tables over a bounded\nfive-minute window, so the console can put a number beside a source without\nthe operator opening Search. It answers 200 with nulls where the series is\nabsent: a source that was only just defined has nothing to report, and that\nis not an error.", "operationId": "sources.signals", "parameters": [ { @@ -8893,7 +8899,7 @@ "Sources" ], "summary": "Bulk Action", - "description": "Perform a bulk action on multiple sources.\n\n``enable`` / ``disable`` / ``dormant`` / ``delete`` apply immediately.\n``deploy`` submits one ``source:deploy`` background task per accepted source\n(poll ``GET /operations/{operation}``); refused names land in ``failed``.\n\nAn action that applies immediately reports the one reconcile it ends with, as\na single-source write does.", + "description": "Perform a bulk action on multiple sources.\n\n``enable`` / ``disable`` / ``dormant`` / ``delete`` apply immediately.\n``deploy`` submits one ``source:deploy`` background task per accepted source\n(poll ``GET /operations/{operation}``). Refused names land in ``failed``.\n\nAn action that applies immediately reports the one reconcile it ends with, as\na single-source write does.", "operationId": "sources.bulk", "requestBody": { "content": { @@ -8985,7 +8991,7 @@ "Sources" ], "summary": "Reconcile Apps", - "description": "Bring the deploy repo's derived app state into step with the sources.\n\nRecompiles every stack-scoped routing block (receiver, loader, archiver) and\ndeploys, syncs or removes the instances of every instance-scoped app (a fetcher\nper active fetcher-based source). Every source write does this on its own; this\nroute is the retry when one reported ``apps_sync_error``, and the pass that\ndeletes a stranded ``_load`` topic a deploy reported in ``topics_pending_removal``.", + "description": "Bring the deploy repo's derived app state into step with the sources.\n\nRecompiles every stack-scoped routing block (receiver, loader, archiver) and\ndeploys, syncs or removes the instances of every instance-scoped app (a fetcher\nper active fetcher-based source). Every source write does this on its own. This\nroute is the retry when one reported ``apps_sync_error``, and the pass that\ndeletes a stranded ``_load`` topic a deploy reported in ``topics_pending_removal``.", "operationId": "sources.reconcile-apps", "responses": { "200": { @@ -10622,7 +10628,7 @@ "Services" ], "summary": "Get Service Config", - "description": "Get a full service config by service + instance, every credential masked.", + "description": "A service config as its instance runs it, every credential masked.\n\nThe stored keys over the app's own defaults, read from its mounted contract.\nWith no contract mounted only the stored keys are shown.", "operationId": "services.get", "parameters": [ { @@ -10722,7 +10728,7 @@ "Services" ], "summary": "Save Service Config", - "description": "Create or update a service config.\n\nEach top-level section in the body replaces the stored one, and a section the\nbody leaves out is kept as stored, so a form that sends some sections cannot\ndrop the rest and the secrets in them. A section written as ``null`` is removed.\n\nA read shows every set secret masked, so a masked value written back keeps the\nsecret stored there, matched as the app surface matches one. A mask with nothing\nstored behind it, or in a list entry that cannot be told apart, is a 400\n``masked_value`` and nothing is saved. A changed field beside a masked secret,\nin the same mapping or with the secret one mapping down, is a 400\n``credential_reentry_required``: the secret is typed again.", + "description": "Create or update a service config.\n\nEach top-level section in the body replaces the stored one, and a section the\nbody leaves out is kept as stored, so a form that sends some sections cannot\ndrop the rest and the secrets in them. A section written as ``null`` is removed.\n\nA read shows every set secret masked, so a masked value written back keeps the\nsecret stored there, matched as the app surface matches one. A mask with nothing\nstored behind it, or in a list entry that cannot be told apart, is a 400\n``masked_value`` and nothing is saved. A changed field beside a masked secret,\nin the same mapping or with the secret one mapping down, is a 400\n``credential_reentry_required``: the secret is typed again. A value the app's\ncontract refuses is a 422 ``invalid_config``.", "operationId": "services.apply", "parameters": [ { @@ -11113,7 +11119,7 @@ "Deployment" ], "summary": "List Admin Links", - "description": "Each admin UI this deployment runs, in the order its deployer listed them.\n\nThe deployer supplies the list, so an empty one means it listed none. Gated to\nthe admin-class roles, which hold ``deployment:*`` or ``*``: the list maps the\ndeployment's consoles. Links only; nothing here carries a credential.", + "description": "Each admin UI this deployment runs, in the order its deployer listed them.\n\nThe deployer supplies the list, so an empty one means it listed none. Gated to\nthe admin-class roles, which hold ``deployment:*`` or ``*``: the list maps the\ndeployment's consoles. Links only. Nothing here carries a credential.", "operationId": "deployment.admin-links.list", "parameters": [ { @@ -12072,7 +12078,7 @@ "Rules" ], "summary": "Create Rule", - "description": "Create a new hunt rule via RuleCreationService.\n\nThe service sanitizes the SQL, applies CEL->SQL transpilation,\nvalidates column references, and optionally estimates query cost. A rule\nwhose SQL the hunt runner could not compile is refused with 422. The cost\npreview counts only the orgs the hunts running the rule read, cut to the orgs\nits author may read.\n\nA production+team write is routed to a review branch instead of the branch the\nrunner git-syncs, and the ``X-DFE-Review-Required`` header says so.", + "description": "Create a new hunt rule via RuleCreationService.\n\nThe rule is written as SQL or as a structured ``condition``, which the engine\ncompiles to the SQL and stores with it. The service sanitizes the SQL,\napplies CEL->SQL transpilation, validates column references, and optionally\nestimates query cost. A rule whose SQL the hunt runner could not compile is\nrefused with 422. The cost preview counts only the orgs the hunts running the\nrule read, cut to the orgs its author may read.\n\nA production+team write is routed to a review branch instead of the branch the\nrunner git-syncs, and the ``X-DFE-Review-Required`` header says so.", "operationId": "rules.create", "requestBody": { "required": true, @@ -12163,8 +12169,8 @@ "tags": [ "Rules" ], - "summary": "Create Rule From Hyperdx", - "description": "Create a hunt rule from the SQL a HyperDX view renders to.\n\nWraps the create pipeline with ``source_type='hyperdx'`` and auto-derives a\nunique rule id from the saved-search name, so the caller need not supply one.\nA view whose SQL the hunt runner could not compile, or that matches every\nevent, is refused with 422. RBAC: ``rule:write`` (data_analyst) --\n``org_viewer`` has neither this grant nor the UI button.", + "summary": "Create Rule From Search", + "description": "Create a hunt rule from the SQL a Search view renders to.\n\nWraps the create pipeline with ``source_type='hyperdx'`` and auto-derives a\nunique rule id from the saved-search name, so the caller need not supply one.\nA view whose SQL the hunt runner could not compile, or that matches every\nevent, is refused with 422. RBAC: ``rule:write`` (data_analyst) --\n``org_viewer`` has neither this grant nor the UI button.", "operationId": "rules.from-hyperdx", "requestBody": { "content": { @@ -12342,6 +12348,98 @@ } } }, + "/api/v1/rules/preview": { + "post": { + "tags": [ + "Rules" + ], + "summary": "Preview Rule", + "description": "Compile a condition and check it exactly as a save would, writing nothing.\n\nRuns the creation pipeline of ``POST /rules`` (compile, parse, the forbidden-keyword\nand column checks, the matches-everything check and the alert-volume preview) under the\nsame org fence, and stops before the save. A condition the save would refuse comes back\nwith 200 and its reasons in ``sql_errors`` or ``matches_everything``, so a builder can\nshow them as the author edits. A body that is not a condition at all is 422.", + "operationId": "rules.preview", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RulePreviewRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RulePreviewResponse" + } + } + } + }, + "401": { + "description": "No valid session: the credentials are missing, invalid or expired, or the account behind them is disabled or blocked", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "403": { + "description": "Refused: the session lacks the action this route checks, or its account must replace an issued password first. A SCIM route answers a refused action in the RFC 7644 error envelope", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "default": { + "description": "Problem details (RFC 9457)", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + } + }, + "security": [ + { + "BearerAuth": [] + } + ], + "x-scalo": { + "group": "rules", + "resource": "rules", + "hierarchy": [ + "rules" + ], + "verb": "preview", + "read_only": false, + "cli": { + "hidden": false, + "aliases": [], + "positional": [] + }, + "action": "rule:validate" + } + } + }, "/api/v1/rules/{name}": { "get": { "tags": [ @@ -12439,7 +12537,7 @@ "Rules" ], "summary": "Update Rule", - "description": "Replace a detection rule (re-runs creation pipeline, preserves created_at).\n\nA replacement the hunt runner could not compile is refused with 422 and the\nstored rule is left as it was. A production+team write is routed to a review\nbranch instead of the branch the runner git-syncs, and the\n``X-DFE-Review-Required`` header says so.", + "description": "Replace a detection rule (re-runs creation pipeline, preserves created_at).\n\nThe replacement is written as SQL or as a ``condition``, as on create, and a\nrule replaced with SQL no longer carries a condition.\n\nA replacement the hunt runner could not compile is refused with 422 and the\nstored rule is left as it was. A production+team write is routed to a review\nbranch instead of the branch the runner git-syncs, and the\n``X-DFE-Review-Required`` header says so.", "operationId": "rules.apply", "parameters": [ { @@ -13393,7 +13491,7 @@ "System" ], "summary": "Get System Status", - "description": "Conditions that leave the engine degraded while it keeps serving.\n\nA refused YAML write keeps the old file or the old deploy-repo content, so reads\nstay correct and readiness is not failed; this is where the refusal shows.", + "description": "Conditions that leave the engine degraded while it keeps serving.\n\nA refused YAML write keeps the old file or the old deploy-repo content, so reads\nstay correct and readiness is not failed. This is where the refusal shows.", "operationId": "system.status", "responses": { "200": { @@ -13608,7 +13706,7 @@ "System" ], "summary": "Put Retention", - "description": "Store the override in the deploy repo, then apply it to every table that follows it.\n\nThe engine's own tables and every deployed source's table are brought to the new\neffective default in this request, with ``ALTER TABLE ... MODIFY TTL`` (or\n``REMOVE TTL`` for 0). A table that declares its own TTL is left alone. A\nClickHouse failure answers 502 with the override ALREADY committed; sending the\nsame value again applies it.", + "description": "Store the override in the deploy repo, then apply it to every table that follows it.\n\nThe engine's own tables and every deployed source's table are brought to the new\neffective default in this request, with ``ALTER TABLE ... MODIFY TTL`` (or\n``REMOVE TTL`` for 0). A table that declares its own TTL is left alone. A\nClickHouse failure answers 502 with the override ALREADY committed. Sending the\nsame value again applies it.", "operationId": "system.retention.apply", "requestBody": { "content": { @@ -13792,7 +13890,7 @@ "System" ], "summary": "Patch Defaults", - "description": "Store the named defaults. Only ttl_days is applied to live tables.\n\nOmitted fields are left alone. null clears that override. Common-header type,\nversion and engine are what a source inherits the next time it is deployed;\nthis request does not rewrite them onto live tables. A patch that names\nttl_days stores it and then runs the same reconcile as PUT /retention.", + "description": "Store the named defaults. Only ttl_days is applied to live tables.\n\nOmitted fields are left alone. null clears that override. Common-header type,\nversion and engine are what a source inherits the next time it is deployed.\nThis request does not rewrite them onto live tables. A patch that names\nttl_days stores it and then runs the same reconcile as PUT /retention.", "operationId": "system.defaults.update", "requestBody": { "content": { @@ -14578,7 +14676,7 @@ "hunts" ], "summary": "Get Engine Status", - "description": "Report hunt scheduling status.\n\nHunts execute in the separate dfe-hunt-runner service (pull-based, coordinated\nvia ClickHouse), not in this API process, so ``runners`` counts the runners that\nbeat within their last two polls and ``running`` is whether any did. For \"is this\nhunt running\", read the per-hunt ``running`` on the hunts list; ``hunt_count`` is\nthe configured-hunt count.", + "description": "Report hunt scheduling status.\n\nHunts execute in the separate dfe-hunt-runner service (pull-based, coordinated\nvia ClickHouse), not in this API process, so ``runners`` counts the runners that\nbeat within their last two polls and ``running`` is whether any did. For \"is this\nhunt running\", read the per-hunt ``running`` on the hunts list. ``hunt_count`` is\nthe configured-hunt count.", "operationId": "hunts.status", "responses": { "200": { @@ -14671,6 +14769,24 @@ }, "description": "Case-insensitive search in name, display_name, customers, rules, source_table, target_table" }, + { + "name": "rule", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only the hunts whose rules include this rule, by its exact name", + "title": "Rule" + }, + "description": "Only the hunts whose rules include this rule, by its exact name" + }, { "name": "page_size", "in": "query", @@ -15096,7 +15212,7 @@ "hunts" ], "summary": "Delete Hunt", - "description": "Delete a hunt configuration.\n\nA production+team delete is routed to a review branch, so the runner keeps\nexecuting the hunt until that branch is merged; ``X-DFE-Review-Required`` says so.", + "description": "Delete a hunt configuration.\n\nA production+team delete is routed to a review branch, so the runner keeps\nexecuting the hunt until that branch is merged. ``X-DFE-Review-Required`` says so.", "operationId": "hunts.delete", "parameters": [ { @@ -15182,7 +15298,7 @@ "hunts" ], "summary": "Trigger Hunt", - "description": "Queue an ad-hoc run: mark the hunt due now for the runner to claim.\n\nThe pull model is kept. Nothing is pushed at the runner and no listener is added\n-- the fire is written into the coordination state, and the runner that is\nalready running picks it up on its next poll, through the same claim that stops\na hunt double-running. 202 says it is queued, not that it has run; the response\ncarries the poll interval so the caller knows the longest wait before it starts.\n\nA hunt with no rate schedule is not something the runner ticks, so a queued run\nfor one sits unclaimed. That is the schedule's shape, not a failure here.\n\n503 is reserved for ClickHouse actually being unreachable; any other failure to\nwrite the request is a 500, so a bug here never reads as an outage.", + "description": "Queue an ad-hoc run: mark the hunt due now for the runner to claim.\n\nThe pull model is kept. Nothing is pushed at the runner and no listener is added\n-- the fire is written into the coordination state, and the runner that is\nalready running picks it up on its next poll, through the same claim that stops\na hunt double-running. 202 says it is queued, not that it has run. The response\ncarries the poll interval so the caller knows the longest wait before it starts.\n\nA hunt with no rate schedule is not something the runner ticks, so a queued run\nfor one sits unclaimed. That is the schedule's shape, not a failure here.\n\n503 is reserved for ClickHouse actually being unreachable. Any other failure to\nwrite the request is a 500, so a bug here never reads as an outage.", "operationId": "hunts.run", "parameters": [ { @@ -16296,7 +16412,7 @@ "sampler" ], "summary": "List Samples", - "description": "List recent sample tasks (most recent first); a caller held to its orgs sees only theirs.", + "description": "List recent sample tasks (most recent first). A caller held to its orgs sees only theirs.", "operationId": "samples.list", "parameters": [ { @@ -20180,7 +20296,7 @@ "schemas" ], "summary": "Discover Json Paths", - "description": "Discover JSON paths inside a source's ``_json`` column.\n\nResolves the requested ``version`` (or the source's current version). If that\nversion defines a ``meta_schema`` it uses ``db.`` only after deploy;\nuntil then discovery runs on ``db.`` filtered by the version's\nmatch rule. Versions without ``meta_schema`` always use the landing table.\n\nReturns one record per path with observed types, a suggested column name,\nand whether the path is already promoted. ``?samples=N`` adds random\ndistinct example values; ``?stats=true`` adds coverage + distinct counts.\n\nA caller without a platform grant holding ``schema:read`` reads only its own\norgs' rows, as the sampler holds it, and a table it cannot be held on is 403.", + "description": "Discover JSON paths inside a source's ``_json`` column.\n\nResolves the requested ``version`` (or the source's current version). If that\nversion defines a ``meta_schema`` it uses ``db.`` only after deploy;\nuntil then discovery runs on ``db.`` filtered by the version's\nmatch rule. Versions without ``meta_schema`` always use the landing table.\n\nReturns one record per path with observed types, a suggested column name,\nand whether the path is already promoted. ``?samples=N`` adds random\ndistinct example values. ``?stats=true`` adds coverage + distinct counts.\n\nA caller without a platform grant holding ``schema:read`` reads only its own\norgs' rows, as the sampler holds it, and a table it cannot be held on is 403.", "operationId": "schemas.json-paths", "parameters": [ { @@ -20341,7 +20457,7 @@ "schemas" ], "summary": "Sample Source Rows", - "description": "Return random sample rows for a source, scoped to its match rule.\n\nResolves the requested ``version`` (or the source's current version). A\nversion with a ``meta_schema`` uses ``db.`` only after that version\nis deployed and the table exists; otherwise rows are read from\n``db.`` filtered by the version's match rule.\n\nIntended for inspecting real data while authoring a match condition or CEL\nbefore promoting any JSON path -- a row-level companion to the per-path\n``?samples=N`` on ``/json-paths``.\n\nA caller without a platform grant holding ``schema:read`` reads only its own\norgs' rows, as the sampler holds it, and a table it cannot be held on is 403.", + "description": "Return random sample rows for a source, scoped to its match rule.\n\nResolves the requested ``version`` (or the source's current version). A\nversion with a ``meta_schema`` uses ``db.`` only after that version\nis deployed and the table exists. Otherwise rows are read from\n``db.`` filtered by the version's match rule.\n\nIntended for inspecting real data while authoring a match condition or CEL\nbefore promoting any JSON path -- a row-level companion to the per-path\n``?samples=N`` on ``/json-paths``.\n\nA caller without a platform grant holding ``schema:read`` reads only its own\norgs' rows, as the sampler holds it, and a table it cannot be held on is 403.", "operationId": "schemas.sample-rows", "parameters": [ { @@ -20466,7 +20582,7 @@ "schemas" ], "summary": "Promote Field", - "description": "Promote JSON path(s) into dedicated typed columns.\n\nCreates a new schema version on the source's meta-schema (or on ``schema_path``\nwhen the source has none), adding one column per path with an ``@source`` directive\nnaming the bare record path, which is what dfe-loader reads to fill the column on\nthe next ingest. Existing rows are not backfilled. Core meta-schemas are forked to\n``{source_name}_{schema_stem}`` under the same parent path before promoting.\n``?dry_run=true`` returns the proposed diff and DDL without forking core schemas,\nadding meta-schema versions, or updating the source. A core source, such as the\nlanding source ``main``, is refused with 409 before any schema is resolved or\nwritten, dry run included; its ``json-paths`` and ``sample-rows`` reads stay open.", + "description": "Promote JSON path(s) into dedicated typed columns.\n\nCreates a new schema version on the source's meta-schema (or on ``schema_path``\nwhen the source has none), adding one column per path with an ``@source`` directive\nnaming the bare record path, which is what dfe-loader reads to fill the column on\nthe next ingest. Existing rows are not backfilled. Core meta-schemas are forked to\n``{source_name}_{schema_stem}`` under the same parent path before promoting.\n``?dry_run=true`` returns the proposed diff and DDL without forking core schemas,\nadding meta-schema versions, or updating the source. A core source, such as the\nlanding source ``main``, is refused with 409 before any schema is resolved or\nwritten, dry run included. Its ``json-paths`` and ``sample-rows`` reads stay open.", "operationId": "schemas.promote-field", "parameters": [ { @@ -20661,7 +20777,7 @@ "SCIM" ], "summary": "Create User", - "description": "Provision a user. IdP-owned; local password is randomised when omitted.\n\nA password the IdP does send is held to the same length floor as every other\npassword the API sets, and one under it is refused rather than replaced.", + "description": "Provision a user. IdP-owned. Local password is randomised when omitted.\n\nA password the IdP does send is held to the same length floor as every other\npassword the API sets, and one under it is refused rather than replaced.", "operationId": "scim.v2.users.create", "responses": { "200": { @@ -21966,7 +22082,7 @@ "sigma" ], "summary": "Generate All Sigma Views", - "description": "Generate Sigma view DDL for all sources (stored definitions win over field maps).\n\nDefaults to the data database, since that is where a propagated hunt reads\nthe view from (``{source}_sigma``); an explicit ``database`` still overrides it.", + "description": "Generate Sigma view DDL for all sources (stored definitions win over field maps).\n\nDefaults to the data database, since that is where a propagated hunt reads\nthe view from (``{source}_sigma``). An explicit ``database`` still overrides it.", "operationId": "sigma.views.create", "parameters": [ { @@ -22364,7 +22480,7 @@ "sigma" ], "summary": "Generate Sigma View", - "description": "Generate (preview) Sigma view DDL for a source.\n\nA stored view definition drives generation - including its JSON-derived\ncolumns - when one exists; otherwise falls back to the static field maps via\nthe source mapper, keeping only the mappings whose column the source's table\ncarries. Returns the DDL string; does NOT execute it against ClickHouse.\n\nDefaults to the data database, since that is where a propagated hunt reads\nthe view from (``{source}_sigma``); an explicit ``database`` still overrides it.", + "description": "Generate (preview) Sigma view DDL for a source.\n\nA stored view definition drives generation - including its JSON-derived\ncolumns - when one exists. Otherwise falls back to the static field maps via\nthe source mapper, keeping only the mappings whose column the source's table\ncarries. Returns the DDL string. Does NOT execute it against ClickHouse.\n\nDefaults to the data database, since that is where a propagated hunt reads\nthe view from (``{source}_sigma``). An explicit ``database`` still overrides it.", "operationId": "sigma.views.post", "parameters": [ { @@ -23254,7 +23370,7 @@ "sigma" ], "summary": "Disable Provider", - "description": "Disable a provider (blocks scheduled polling; a manual sync is refused).", + "description": "Disable a provider (blocks scheduled polling, a manual sync is refused).", "operationId": "sigma.providers.disable", "parameters": [ { @@ -23348,7 +23464,7 @@ "sigma" ], "summary": "Sync Provider Endpoint", - "description": "Trigger a provider sync into the catalogue.\n\nSubmitted to the task manager (a git-repo clone is long-running); blocks up to\n``wait`` seconds for inline completion, else returns ``pending`` - poll via\nGET /sigma/syncs/{task_id}.", + "description": "Trigger a provider sync into the catalogue.\n\nSubmitted to the task manager (a git-repo clone is long-running). Blocks up to\n``wait`` seconds for inline completion, else returns ``pending`` - poll via\nGET /sigma/syncs/{task_id}.", "operationId": "sigma.providers.sync", "parameters": [ { @@ -24014,7 +24130,7 @@ "sigma" ], "summary": "Adopt Catalogue Rule", - "description": "Detach a rule from upstream (pin its content; a re-import records drift only).", + "description": "Detach a rule from upstream (pin its content, a re-import records drift only).", "operationId": "sigma.catalogue.adopt", "parameters": [ { @@ -24369,7 +24485,7 @@ "sigma" ], "summary": "Propagate", - "description": "Generate sigma-bound DFE rules + hunts from the current selection.\n\nFor each SELECTED sigma rule, converts its detection to a ClickHouse WHERE over\nthe matching source's ``{source}_sigma`` view and stores a DFE rule (with a\n``sigma_rule_id`` back-reference), then binds it into a per-source hunt. Drifted\nor hand-edited bindings are reported ``skipped_drifted`` unless ``force``.\nSubmitted to the task manager; blocks up to ``wait`` seconds for inline\ncompletion, else returns ``pending`` - poll via GET /sigma/propagations/{id}.\n\nA production+team run commits each generated rule and hunt to its own review\nbranch rather than the branch the hunt runner syncs; the report carries every\nbranch and PR, and ``X-DFE-Review-Required`` says so on a run that completed\ninline. 422 ``unknown_org`` when ``hunt_customers`` names no registered org.", + "description": "Generate sigma-bound DFE rules + hunts from the current selection.\n\nFor each SELECTED sigma rule, converts its detection to a ClickHouse WHERE over\nthe matching source's ``{source}_sigma`` view and stores a DFE rule (with a\n``sigma_rule_id`` back-reference), then binds it into a per-source hunt. Drifted\nor hand-edited bindings are reported ``skipped_drifted`` unless ``force``.\nSubmitted to the task manager. Blocks up to ``wait`` seconds for inline\ncompletion, else returns ``pending`` - poll via GET /sigma/propagations/{id}.\n\nA production+team run commits each generated rule and hunt to its own review\nbranch rather than the branch the hunt runner syncs. The report carries every\nbranch and PR, and ``X-DFE-Review-Required`` says so on a run that completed\ninline. 422 ``unknown_org`` when ``hunt_customers`` names no registered org.", "operationId": "sigma.propagate", "parameters": [ { @@ -25733,7 +25849,7 @@ "Governed Ops: Backing Services" ], "summary": "List Overlays", - "description": "List substrate/platform overlay resources in the deploy repo's infra/ dir.", + "description": "List infra overlay resources in the deploy repo's infra/ dir.", "operationId": "backing-services.overlays", "parameters": [ { @@ -26093,7 +26209,7 @@ "Governed Ops: Backing Services" ], "summary": "Set Overlay Var", - "description": "Set a substrate/platform value.\n\n409 managed_by_provider, before any other check, when DFE does not run the\nservice and the value is one of its read_only paths; helmvars:override does not\nlift it. 403 with the policy that blocked it when the var is protected - the\nstorage model, the data-layer modes and the disk size are decided at deploy, and\nmoving one on a live deployment is a data migration. 400 when the value would\nlower a declared node or broker count, or leave it undeclared (a parent map that\nomits it), which loses data rather than capacity; helmvars:override does not lift it.", + "description": "Set an infra overlay value.\n\n409 managed_by_provider, before any other check, when DFE does not run the\nservice and the value is one of its read_only paths. helmvars:override does not\nlift it. 403 with the policy that blocked it when the var is protected - the\nstorage model, the data-layer modes and the disk size are decided at deploy, and\nmoving one on a live deployment is a data migration. 400 when the value would\nlower a declared node or broker count, or leave it undeclared (a parent map that\nomits it), which loses data rather than capacity. helmvars:override does not lift it.", "operationId": "backing-services.overlays.vars.apply", "parameters": [ { @@ -26231,7 +26347,7 @@ "Governed Ops: Backing Services" ], "summary": "Delete Overlay Var", - "description": "Revert a substrate/platform value to its chart default. Protected vars refuse.\n\n409 managed_by_provider, before any other check and whatever the caller holds,\nwhen DFE does not run the service and the value is one of its read_only paths.\n400 when the revert would lower a declared node or broker count, or leave it\nundeclared, unless the caller holds helmvars:override. An undeclared count falls\nto the chart or profile default, which the engine cannot read, so a revert that\nleaves one undeclared is refused whatever that default is.", + "description": "Revert an infra overlay value to its chart default. Protected vars refuse.\n\n409 managed_by_provider, before any other check and whatever the caller holds,\nwhen DFE does not run the service and the value is one of its read_only paths.\n400 when the revert would lower a declared node or broker count, or leave it\nundeclared, unless the caller holds helmvars:override. An undeclared count falls\nto the chart or profile default, which the engine cannot read, so a revert that\nleaves one undeclared is refused whatever that default is.", "operationId": "backing-services.overlays.vars.delete", "parameters": [ { @@ -27206,7 +27322,7 @@ "App Management" ], "summary": "Set App Config", - "description": "Write options the app declares, and environment keys it does not.\n\nJudged against the app's own contract before anything is committed, so a value\nthe app would refuse at startup leaves the deploy repo where it was rather than\nlanding a commit an operator then has to revert.\n\nA secret is written like any other option: it goes into the overlay as the rest\nof this surface writes one, and neither this response nor a read route on this\nsurface says what it is. A masked value written back as it was read keeps the\nstored credential; the mask where nothing is stored is a 400 ``masked_value``.\nA changed field beside a stored credential, in the same mapping or with the\ncredential one mapping down (``brokers`` beside ``sasl.password``), is a 400\n``credential_reentry_required`` until that mapping is written whole with its\ncredentials typed again. A setting inside another mapping beside it, such as\n``producer.retries``, is not. ``config`` and ``extraEnv`` are roots, so a\nsetting directly under either never needs one.\n\n409 where the deployment already decides the value: a config path the chart\nderives, or an `extraEnv` name the chart sets for this app.", + "description": "Write options the app declares, and environment keys it does not.\n\nJudged against the app's own contract before anything is committed, so a value\nthe app would refuse at startup leaves the deploy repo where it was rather than\nlanding a commit an operator then has to revert.\n\nA secret is written like any other option: it goes into the overlay as the rest\nof this surface writes one, and neither this response nor a read route on this\nsurface says what it is. A masked value written back as it was read keeps the\nstored credential. The mask where nothing is stored is a 400 ``masked_value``.\nA changed field beside a stored credential, in the same mapping or with the\ncredential one mapping down (``brokers`` beside ``sasl.password``), is a 400\n``credential_reentry_required`` until that mapping is written whole with its\ncredentials typed again. A setting inside another mapping beside it, such as\n``producer.retries``, is not. ``config`` and ``extraEnv`` are roots, so a\nsetting directly under either never needs one.\n\n409 where the deployment already decides the value: a config path the chart\nderives, or an `extraEnv` name the chart sets for this app.", "operationId": "apps.config.put", "parameters": [ { @@ -28155,7 +28271,7 @@ "App Management" ], "summary": "Relink App Files", - "description": "Re-resolve every link in the set to what its target now names.\n\nA tag link follows its tag; a version-pinned link advances to the artefact's\ncurrent version. This is the fix-once-roll-everywhere half of the library.", + "description": "Re-resolve every link in the set to what its target now names.\n\nA tag link follows its tag. A version-pinned link advances to the artefact's\ncurrent version. This is the fix-once-roll-everywhere half of the library.", "operationId": "apps.files.relink", "parameters": [ { @@ -28283,7 +28399,7 @@ "App Management" ], "summary": "Copy App Files", - "description": "Copy this instance's authored files onto another instance of the same app.\n\nA transform is written against one source; reusing it on another should not mean\nretyping it. Only the files move - the target keeps its own source binding,\nscaling and identity.", + "description": "Copy this instance's authored files onto another instance of the same app.\n\nA transform is written against one source. Reusing it on another should not mean\nretyping it. Only the files move - the target keeps its own source binding,\nscaling and identity.", "operationId": "apps.files.copy", "parameters": [ { @@ -29073,7 +29189,7 @@ "App Management" ], "summary": "Dry Run App File", - "description": "Run an authored file over real events from the source, and report each one.\n\nNothing is written: no topic, no table, no commit. ``content`` runs unsaved\ncontent, which is what makes this useful in an editor; omitted, the file\nalready in the overlay runs instead.", + "description": "Run an authored file over real events from the source, and report each one.\n\nNothing is written: no topic, no table, no commit. ``content`` runs unsaved\ncontent, which is what makes this useful in an editor. Omitted, the file\nalready in the overlay runs instead.", "operationId": "apps.files.dry-run", "parameters": [ { @@ -30740,7 +30856,7 @@ "Artefact Library" ], "summary": "Publish Version", - "description": "Publish content as a version.\n\nRe-sending identical content is a no-op naming the version that already holds\nit; sending different content at an existing version number is refused.", + "description": "Publish content as a version.\n\nRe-sending identical content is a no-op naming the version that already holds\nit. Sending different content at an existing version number is refused.", "operationId": "library.versions.create", "parameters": [ { @@ -31547,7 +31663,7 @@ "Governed Ops: Actions" ], "summary": "Get Action", - "description": "One defined action; a credential a legacy definition still carries comes back masked.", + "description": "One defined action. A credential a legacy definition still carries comes back masked.", "operationId": "governance.actions.get", "parameters": [ { @@ -31864,7 +31980,7 @@ "Governed Ops: Actions" ], "summary": "Invoke Action", - "description": "Invoke a defined action - gated on the action's OWN required_action.\n\n``body.params`` supplies values for the action's declared params (422 on a\nconstraint violation; omitted params take their defaults). A hunt or rule\ndocument the action would leave invalid is 422 ``invalid_document``, with the\nhunts API's own message. A change to the infra overlay meets the backing-services\nguards on what the action leaves, dry run included, whatever the caller holds:\n409 ``managed_by_provider`` for a read-only value of a service DFE does not run,\nthen 400 ``scale_down_refused`` where it lowers or un-declares a node or broker\ncount.\nDirect commit in dev/solo; a production+team invoke is routed to a review PR (or\n409 ``review_required`` when no forge is configured).", + "description": "Invoke a defined action - gated on the action's OWN required_action.\n\n``body.params`` supplies values for the action's declared params (422 on a\nconstraint violation. Omitted params take their defaults). A hunt or rule\ndocument the action would leave invalid is 422 ``invalid_document``, with the\nhunts API's own message. A change to the infra overlay meets the backing-services\nguards on what the action leaves, dry run included, whatever the caller holds:\n409 ``managed_by_provider`` for a read-only value of a service DFE does not run,\nthen 400 ``scale_down_refused`` where it lowers or un-declares a node or broker\ncount.\nDirect commit in dev/solo. A production+team invoke is routed to a review PR (or\n409 ``review_required`` when no forge is configured).", "operationId": "governance.actions.invoke", "parameters": [ { @@ -32586,7 +32702,7 @@ "Governed Ops: Gitops" ], "summary": "Put Auto Merge", - "description": "Toggle auto-merge. Enabling requires the deployment gate; disabling always works.", + "description": "Toggle auto-merge. Enabling requires the deployment gate. Disabling always works.", "operationId": "gitops.auto-merge.put", "requestBody": { "content": { @@ -32679,7 +32795,7 @@ "Governed Ops: Gitops" ], "summary": "List Classes", - "description": "The resource-class registry - what VarChange.cls may legally name.\n\nRegistry metadata only (no resource content), so any authenticated caller\nmay read it; the per-class listings below are gated by each class's grant.", + "description": "The resource-class registry - what VarChange.cls may legally name.\n\nRegistry metadata only (no resource content), so any authenticated caller\nmay read it. The per-class listings below are gated by each class's grant.", "operationId": "gitops.classes.list", "parameters": [ { @@ -33093,7 +33209,7 @@ "Governed Ops: Gitops" ], "summary": "Get Log", - "description": "Gitcrud audit log: every governed-ops git change, newest-first.\n\nFlat + cursor-paginated by default; ?group_by= buckets the page for\nsummaries. applied_revision (the Argo-synced SHA) turns state into\napplied/pending; without it every entry is 'committed'.", + "description": "Gitcrud audit log: every governed-ops git change, newest-first.\n\nFlat + cursor-paginated by default; ?group_by= buckets the page for\nsummaries. applied_revision (the Argo-synced SHA) turns state into\napplied/pending. Without it every entry is 'committed'.", "operationId": "gitops.log.list", "parameters": [ { @@ -33375,7 +33491,7 @@ "Governed Ops: Lifecycle" ], "summary": "Set Lifecycle", - "description": "Set a service's lifecycle state - per-service RBAC; pinned services are 404.", + "description": "Set a service's lifecycle state - per-service RBAC. Pinned services are 404.", "operationId": "lifecycle.post", "parameters": [ { @@ -33476,8 +33592,8 @@ "tags": [ "Rules: Authoring" ], - "summary": "From Hyperdx", - "description": "Strip a HyperDX query's time bounds -> {window}, ready to save as a rule.", + "summary": "Strip Search Query Time Bounds", + "description": "Strip a Search query's time bounds -> {window}, ready to save as a rule.", "operationId": "authoring.from-hyperdx", "requestBody": { "content": { @@ -34039,7 +34155,7 @@ "Client Config" ], "summary": "Client Config", - "description": "Runtime config for the web UI.\n\nAuthenticated but ungated: every console pane may read it, and the HyperDX URL\nit returns is internal to the deployment.", + "description": "Runtime config for the web UI.\n\nAuthenticated but ungated: every console pane may read it, and the Search URL\nit returns is internal to the deployment.", "operationId": "config.client", "responses": { "200": { @@ -34107,9 +34223,9 @@ "/api/v1/hyperdx/connection": { "get": { "tags": [ - "HyperDX" + "Search" ], - "summary": "Hyperdx Connection", + "summary": "Get Search Connection", "description": "Return the caller's OWN org connection - never another org's.\n\nA caller granted ``query:execute`` at system scope by a declared, unscoped role\nother than ``org_viewer`` gets the platform reader. Any other caller gets its org's pinned\n``dfe_org_`` user, whatever roles it holds at that org's scope. A caller\nthat resolves to zero or several separate orgs is refused (403) so isolation\nfails closed rather than guessing.", "operationId": "hyperdx.connection", "responses": { @@ -34178,10 +34294,10 @@ "/api/v1/hyperdx/sources": { "get": { "tags": [ - "HyperDX" + "Search" ], - "summary": "Hyperdx Sources", - "description": "List every HyperDX team and the DFE sources on it.\n\nA deploy writes its source to every team, so this is the read that says where\nit landed. 503 when HyperDX is not deployed or not answering -- an empty list\nwould read as \"the source is missing\", which is a different fault.", + "summary": "List Search Sources", + "description": "List every Search team and the DFE sources on it.\n\nA deploy writes its source to every team, so this is the read that says where\nit landed. 503 when Search is not deployed or not answering -- an empty list\nwould read as \"the source is missing\", which is a different fault.", "operationId": "hyperdx.sources", "responses": { "200": { @@ -39156,7 +39272,7 @@ }, "type": "object", "title": "DeclaredValue", - "description": "One value as the deploy repo declares it.\n\n``source`` names the overlay file it came from; a null source means the\ndeployment declared nothing and the chart or profile default applies. Those\ndefaults live in dfe-infra, which the engine does not read, so the API says\n\"not declared\" rather than guessing a number." + "description": "One value as the deploy repo declares it.\n\n``source`` names the overlay file it came from. A null source means the\ndeployment declared nothing and the chart or profile default applies. Those\ndefaults live in dfe-infra, which the engine does not read, so the API says\n\"not declared\" rather than guessing a number." }, "DefaultComparison": { "properties": { @@ -39315,11 +39431,12 @@ "type": "string", "enum": [ "deploy-repo", + "registry", "deployment", "engine" ], "title": "Source", - "description": "deploy-repo when the stack version came from pins.yaml, deployment when it came from what deployed this pod, else engine." + "description": "deploy-repo when the stack version came from pins.yaml, registry when the published stack manifests matched the images this deployment runs, deployment when it came from what deployed this pod, else engine." }, "backing": { "additionalProperties": { @@ -39712,7 +39829,7 @@ "_field_type" ], "title": "DraftColumn", - "description": "A ready-to-send meta-schema column derived from a discovered JSON path.\n\nShaped to drop straight into ``MetaSchemaAddVersionRequest.columns`` (the\ncreate-version endpoint) or a new meta-schema's version -- the UI sends these\nverbatim, no field mapping. ``type`` is derived from the first observed\nClickHouse type; for a multi-type path (``is_consistent=false``) confirm it\nbefore saving." + "description": "A ready-to-send meta-schema column derived from a discovered JSON path.\n\nShaped to drop straight into ``MetaSchemaAddVersionRequest.columns`` (the\ncreate-version endpoint) or a new meta-schema's version -- the UI sends these\nverbatim, no field mapping. ``type`` is derived from the first observed\nClickHouse type. For a multi-type path (``is_consistent=false``) confirm it\nbefore saving." }, "DryRunEventModel": { "properties": { @@ -39780,10 +39897,9 @@ }, "limit": { "type": "integer", - "maximum": 100.0, "minimum": 1.0, "title": "Limit", - "description": "Events to sample and run over", + "description": "Events to sample and run over, at most transform_validation.dry_run_max_events (100 by default), which a larger value is refused against", "default": 10 } }, @@ -40589,7 +40705,7 @@ "query" ], "title": "FromHyperdxRequest", - "description": "Body for turning a HyperDX query into rule SQL." + "description": "Body for turning a Search query into rule SQL." }, "GenerateRequest": { "properties": { @@ -41253,6 +41369,12 @@ ], "title": "Explain Queries" }, + "enabled": { + "type": "boolean", + "title": "Enabled", + "description": "Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing.", + "default": true + }, "rules": { "items": { "type": "string" @@ -41383,6 +41505,12 @@ ], "title": "Explain Queries" }, + "enabled": { + "type": "boolean", + "title": "Enabled", + "description": "Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing.", + "default": true + }, "name": { "type": "string", "title": "Name", @@ -41642,6 +41770,30 @@ ], "title": "Next Due", "description": "Epoch seconds of the next scheduled fire; null = no rate schedule" + }, + "enabled": { + "type": "boolean", + "title": "Enabled", + "description": "Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing.", + "default": true + }, + "auto_disabled_at": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Auto Disabled At", + "description": "When the runner stopped the hunt after repeated resource-limit failures, epoch seconds" + }, + "auto_disabled_reason": { + "type": "string", + "title": "Auto Disabled Reason", + "description": "The ClickHouse error category and code that tripped the auto-disable", + "default": "" } }, "type": "object", @@ -41763,6 +41915,12 @@ ], "title": "Explain Queries" }, + "enabled": { + "type": "boolean", + "title": "Enabled", + "description": "Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing.", + "default": true + }, "rules": { "items": { "type": "string" @@ -41797,7 +41955,7 @@ }, "type": "object", "title": "HyperDXConfig", - "description": "Whether the UI links to HyperDX, and where." + "description": "Whether the UI links to Search, and where." }, "HyperDXConnection": { "properties": { @@ -41816,6 +41974,24 @@ "password": { "type": "string", "title": "Password" + }, + "platform": { + "type": "boolean", + "title": "Platform", + "description": "True for the platform reader, which reads every org" + }, + "database": { + "type": "string", + "title": "Database", + "description": "The DFE data database every seeded table lives in" + }, + "tables": { + "additionalProperties": { + "type": "string" + }, + "type": "object", + "title": "Tables", + "description": "Seeded table name by dfe-schemas manifest id" } }, "type": "object", @@ -41823,10 +41999,13 @@ "name", "host", "username", - "password" + "password", + "platform", + "database", + "tables" ], "title": "HyperDXConnection", - "description": "Connection material in the fork's shape (name, host URL, username, password)." + "description": "Connection material in the fork's shape, plus where its seed sources live." }, "HyperDXSourcesResponse": { "properties": { @@ -41840,19 +42019,19 @@ }, "type": "object", "title": "HyperDXSourcesResponse", - "description": "Where every deployed DFE source actually landed in HyperDX." + "description": "Where every deployed DFE source actually landed in Search." }, "HyperDXTeamSource": { "properties": { "id": { "type": "string", "title": "Id", - "description": "HyperDX source id on that team" + "description": "Search source id on that team" }, "name": { "type": "string", "title": "Name", - "description": "DFE source name; the HyperDX source carries the same one" + "description": "DFE source name; the Search source carries the same one" }, "table": { "additionalProperties": { @@ -41869,19 +42048,19 @@ "name" ], "title": "HyperDXTeamSource", - "description": "One HyperDX source on one team, as the fork holds it." + "description": "One Search source on one team, as dfe-hyperdx holds it." }, "HyperDXTeamSources": { "properties": { "team": { "type": "string", "title": "Team", - "description": "HyperDX team id" + "description": "Search team id" }, "team_name": { "type": "string", "title": "Team Name", - "description": "HyperDX team name: the ClickHouse user its members read as" + "description": "Search team name: the ClickHouse user its members read as" }, "sources": { "items": { @@ -41897,7 +42076,7 @@ "team_name" ], "title": "HyperDXTeamSources", - "description": "One HyperDX team and the DFE sources it holds." + "description": "One Search team and the DFE sources it holds." }, "IngestCredentialResponse": { "properties": { @@ -43123,7 +43302,7 @@ "versions" ], "title": "MetaSchema", - "description": "A schema for a ClickHouse table.\n\nAttributes:\n current: Current version of the schema.\n versions: Dictionary of versions and their metadata.\n path: Registry path key (e.g. ``aws/cloudtrail``); omitted from YAML on disk." + "description": "A schema for a ClickHouse table.\n\nAttributes:\n current: Current version of the schema.\n versions: Dictionary of versions and their metadata.\n path: Registry path key (e.g. ``aws/cloudtrail``). Omitted from YAML on disk." }, "MetaSchemaAddVersionRequest": { "properties": { @@ -44088,7 +44267,7 @@ "name" ], "title": "Org", - "description": "A customer organisation.\n\nAttributes:\n name: Primary identifier (filename stem).\n display_name: Human-readable label for UI display.\n org_ids: Tenant IDs used for ClickHouse row-level security filters.\n enabled: Whether this org is active.\n hyperdx_team_id: HyperDX team ID for this org's connection sync.\n hyperdx_team_api_key_env: Environment variable name holding the org's HyperDX team API key.\n ch_password_env: Environment variable name holding the ClickHouse password.\n created_at: ISO 8601 timestamp of creation.\n updated_at: ISO 8601 timestamp of last update." + "description": "A customer organisation.\n\nAttributes:\n name: Primary identifier (filename stem).\n display_name: Human-readable label for UI display.\n org_ids: Tenant IDs used for ClickHouse row-level security filters.\n enabled: Whether this org is active.\n hyperdx_team_id: dfe-hyperdx team ID for this org's connection sync.\n hyperdx_team_api_key_env: Environment variable name holding the org's dfe-hyperdx team API key.\n ch_password_env: Environment variable name holding the ClickHouse password.\n created_at: ISO 8601 timestamp of creation.\n updated_at: ISO 8601 timestamp of last update." }, "OrgResponse": { "properties": { @@ -47136,18 +47315,6 @@ "title": "Cache", "description": "Allow cached results", "default": true - }, - "store": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "title": "Store", - "description": "Target store (database/schema/topic) - only if query allows" } }, "type": "object", @@ -48117,6 +48284,105 @@ "title": "RuleBlockResponse", "description": "One block of the receiver's rule set: a source's rows, a profile's, or the default." }, + "RuleCondition": { + "properties": { + "field": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Field", + "description": "Field a test reads: a column of the source table, or a dotted path inside the record as it arrived (e.g. 'tags.collector.type', or '_json.tags.collector.type'). Each part is letters, digits, '_' and '-', starting with a letter or '_'. Absent on a group" + }, + "operator": { + "anyOf": [ + { + "type": "string", + "enum": [ + "equals", + "not_equals", + "exists", + "includes", + "starts_with", + "ends_with", + "lt", + "lte", + "gt", + "gte", + "in" + ] + }, + { + "type": "null" + } + ], + "title": "Operator", + "description": "How a test compares ``field`` to ``value``: equals (the default for a test), not_equals, exists, includes, starts_with, ends_with, lt, lte, gt, gte, in. Absent on a group", + "x-dfe-operand-kinds": { + "ends_with": "text", + "equals": "text_or_number", + "exists": "none", + "gt": "number_or_date", + "gte": "number_or_date", + "in": "list", + "includes": "text", + "lt": "number_or_date", + "lte": "number_or_date", + "not_equals": "text_or_number", + "starts_with": "text" + } + }, + "value": { + "anyOf": [ + { + "$ref": "#/components/schemas/Scalar" + }, + { + "items": { + "$ref": "#/components/schemas/Scalar" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Value", + "description": "Operand for the operator, by its kind: none for exists, text for includes, starts_with and ends_with, text or a number for equals and not_equals, a number or an ISO 8601 date or date-time for lt, lte, gt and gte, a list of texts or of numbers for in" + }, + "negate": { + "type": "boolean", + "title": "Negate", + "description": "Invert this test or group", + "default": false + }, + "all": { + "items": { + "$ref": "#/components/schemas/RuleCondition" + }, + "type": "array", + "title": "All", + "description": "A group that holds when every part holds" + }, + "any": { + "items": { + "$ref": "#/components/schemas/RuleCondition" + }, + "type": "array", + "title": "Any", + "description": "A group that holds when at least one part holds" + } + }, + "additionalProperties": false, + "type": "object", + "title": "RuleCondition", + "description": "One test on a field, or ``all`` or ``any`` of several, as the rule builder writes it.\n\nA test compares one ``field`` with an ``operator``. ``all`` holds when every\npart does and ``any`` when at least one does. Each part is a condition of its\nown, so groups nest, and ``negate`` inverts the test or group it sits on.", + "x-dfe-max-nesting": 4 + }, "RuleCreateRequest": { "properties": { "display_name": { @@ -48138,10 +48404,28 @@ "default": "medium" }, "user_sql": { - "type": "string", - "minLength": 1, + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "null" + } + ], "title": "User Sql", - "description": "Full detection query: SELECT ... FROM . WHERE ... (the FROM names the source table)" + "description": "Full detection query: SELECT ... FROM .
WHERE ... (the FROM names the source table). Give this or ``condition``, not both. A rule saved this way has no ``condition``" + }, + "condition": { + "anyOf": [ + { + "$ref": "#/components/schemas/RuleCondition" + }, + { + "type": "null" + } + ], + "description": "The rule's structured condition, which the engine compiles to its SQL and stores with it, so the builder reopens on it. Reads the table of ``source``. Give this or ``user_sql``, not both" }, "cel_filter": { "anyOf": [ @@ -48211,13 +48495,12 @@ "hyperdx" ], "title": "Source Type", - "description": "'raw' (plain SQL) or 'hyperdx' (HyperDX saved search format)", + "description": "'raw' (plain SQL) or 'hyperdx' (Search saved search format)", "default": "raw" } }, "type": "object", "required": [ - "user_sql", "name" ], "title": "RuleCreateRequest", @@ -48290,7 +48573,7 @@ "type": "string", "minLength": 1, "title": "Raw Sql", - "description": "The ClickHouse SELECT the HyperDX view renders to" + "description": "The ClickHouse SELECT the Search view renders to" }, "saved_search_name": { "anyOf": [ @@ -48302,7 +48585,7 @@ } ], "title": "Saved Search Name", - "description": "HyperDX saved-search name; seeds the rule id and label" + "description": "Search saved-search name; seeds the rule id and label" }, "severity": { "type": "string", @@ -48341,7 +48624,7 @@ "raw_sql" ], "title": "RuleFromHyperdxRequest", - "description": "Create a hunt rule from the SQL a HyperDX view runs.\n\nHyperDX renders the view to ``raw_sql`` and sends it here. The create\npipeline strips the UI meta (time bounds, LIMIT, ``__hdx_time_bucket``,\nSETTINGS) via the HyperDX sanitizer, and the engine derives a unique rule id\nfrom the saved-search name. The caller gets that id back and opens\n``/rules/{id}`` -- no id to invent, no IndexedDB round-trip." + "description": "Create a hunt rule from the SQL a Search view runs.\n\nSearch renders the view to ``raw_sql`` and sends it here. The create\npipeline strips the UI meta (time bounds, LIMIT, ``__hdx_time_bucket``,\nSETTINGS) via the dfe-hyperdx sanitizer, and the engine derives a unique rule id\nfrom the saved-search name. The caller gets that id back and opens\n``/rules/{id}`` -- no id to invent, no IndexedDB round-trip." }, "RuleFromHyperdxResponse": { "properties": { @@ -48380,7 +48663,7 @@ "display_name" ], "title": "RuleFromHyperdxResponse", - "description": "The rule created from a HyperDX query." + "description": "The rule created from a Search query." }, "RuleOrderRequest": { "properties": { @@ -48511,6 +48794,146 @@ "title": "RuleOrderResponse", "description": "The field's blocks as the reorder leaves them." }, + "RulePreviewRequest": { + "properties": { + "source": { + "type": "string", + "title": "Source", + "description": "Source label whose table the condition reads" + }, + "condition": { + "$ref": "#/components/schemas/RuleCondition" + }, + "cel_filter": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Cel Filter", + "description": "CEL expression ANDed in, as on save" + }, + "cost_window_minutes": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Cost Window Minutes", + "description": "Lookback window in minutes the volume preview counts over. Absent or 0 uses the deployment's preview window." + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Name", + "description": "The rule being edited. The volume preview then counts the orgs of the hunts that run it and of the hunt it names, as its save would" + }, + "hunt_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Hunt Name", + "description": "The hunt the rule names as its own, which the count follows. Defaults to the stored rule's" + } + }, + "type": "object", + "required": [ + "source", + "condition" + ], + "title": "RulePreviewRequest", + "description": "A condition to compile and check as a save would, without saving it." + }, + "RulePreviewResponse": { + "properties": { + "user_sql": { + "type": "string", + "title": "User Sql", + "description": "The rule SQL the condition compiles to, empty when it does not" + }, + "source_db": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Source Db" + }, + "source_table": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Source Table" + }, + "where_clause": { + "type": "string", + "title": "Where Clause", + "description": "The detection WHERE the rule would store" + }, + "sql_errors": { + "items": { + "$ref": "#/components/schemas/SqlValidationError" + }, + "type": "array", + "title": "Sql Errors", + "description": "Why a save would be refused as invalid" + }, + "matches_everything": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Matches Everything", + "description": "Why a save would be refused for matching every event, when it would" + }, + "cost_estimate": { + "anyOf": [ + { + "$ref": "#/components/schemas/CostEstimate" + }, + { + "type": "null" + } + ] + } + }, + "type": "object", + "required": [ + "user_sql", + "where_clause" + ], + "title": "RulePreviewResponse", + "description": "What a save of the condition would compile to and find, and nothing written." + }, "RuleResponse": { "properties": { "name": { @@ -48564,6 +48987,17 @@ ], "title": "Cel Filter" }, + "condition": { + "anyOf": [ + { + "$ref": "#/components/schemas/RuleCondition" + }, + { + "type": "null" + } + ], + "description": "The structured condition the SQL was compiled from, absent for a rule written as SQL" + }, "original_sql": { "type": "string", "title": "Original Sql" @@ -48716,10 +49150,28 @@ "default": "medium" }, "user_sql": { - "type": "string", - "minLength": 1, + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "null" + } + ], "title": "User Sql", - "description": "Full detection query: SELECT ... FROM .
WHERE ... (the FROM names the source table)" + "description": "Full detection query: SELECT ... FROM .
WHERE ... (the FROM names the source table). Give this or ``condition``, not both. A rule saved this way has no ``condition``" + }, + "condition": { + "anyOf": [ + { + "$ref": "#/components/schemas/RuleCondition" + }, + { + "type": "null" + } + ], + "description": "The rule's structured condition, which the engine compiles to its SQL and stores with it, so the builder reopens on it. Reads the table of ``source``. Give this or ``user_sql``, not both" }, "cel_filter": { "anyOf": [ @@ -48777,9 +49229,6 @@ } }, "type": "object", - "required": [ - "user_sql" - ], "title": "RuleUpdateRequest", "description": "Update an existing hunt rule (re-runs creation pipeline, and ``source_type`` is not accepted)." }, @@ -48801,7 +49250,7 @@ "anomaly" ], "title": "SampleMode", - "description": "How to pick the sample.\n\n- ``recent`` - newest rows first (fast tail; ClickHouse ORDER BY ts DESC,\n Kafka reads from the partition high-watermark backwards).\n- ``random`` - uniform-ish random rows (fair distribution, no recency bias).\n- ``smart`` - logreducer representative/diverse sample (default). Gated.\n- ``anomaly`` - logreducer isolation-forest outliers (the weird events). Gated." + "description": "How to pick the sample.\n\n- ``recent`` - newest rows first (fast tail, ClickHouse ORDER BY ts DESC,\n Kafka reads from the partition high-watermark backwards).\n- ``random`` - uniform-ish random rows (fair distribution, no recency bias).\n- ``smart`` - logreducer representative/diverse sample (default). Gated.\n- ``anomaly`` - logreducer isolation-forest outliers (the weird events). Gated." }, "SampleRecord": { "properties": { @@ -48969,7 +49418,7 @@ }, "type": "object", "title": "SampleRequest", - "description": "A request to sample a source.\n\nProvide EITHER a registered ``source`` (its CH table / land topic are\nresolved for you) OR an explicit ``table``/``topic`` (ad-hoc - for a source\nthat is not registered yet, e.g. AI onboarding). ``filter`` (ClickHouse\nbackend only) must be one condition over the sampled table's columns; it is\nreplaced by the condition rendered from its parse tree, and anything else is\nrefused when the request is built." + "description": "A request to sample a source.\n\nProvide EITHER a registered ``source`` (its CH table / land topic are\nresolved for you) OR an explicit ``table``/``topic`` (ad-hoc - for a source\nthat is not registered yet, e.g. AI onboarding). ``filter`` (ClickHouse\nbackend only) must be one condition over the sampled table's columns. It is\nreplaced by the condition rendered from its parse tree, and anything else is\nrefused when the request is built." }, "SampleResult": { "properties": { @@ -49229,6 +49678,19 @@ "title": "ScaffoldRequest", "description": "Body for a starter SELECT over a table's columns." }, + "Scalar": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + }, + { + "type": "number" + } + ] + }, "ScalingRequest": { "properties": { "replica_count": { @@ -49894,7 +50356,7 @@ } ], "title": "Hyperdx Source Teams", - "description": "How many HyperDX teams now carry a source over this source's table" + "description": "How many Search teams now carry a source over this source's table" }, "hyperdx_source_error": { "anyOf": [ @@ -49906,7 +50368,7 @@ } ], "title": "Hyperdx Source Error", - "description": "Why HyperDX was not pointed at the table. Never fails the deploy - the schema is live and HyperDX may be down or not deployed at all." + "description": "Why Search was not pointed at the table. Never fails the deploy - the schema is live and Search may be down or not deployed at all." }, "restart_required": { "items": { @@ -50512,7 +50974,7 @@ "config" ], "title": "ServiceConfigDetail", - "description": "Full service config. Inner config is dynamic (schema-less mode)." + "description": "One service config as its instance runs it: the stored keys over the app's defaults." }, "ServiceConfigSummary": { "properties": { @@ -50775,7 +51237,7 @@ "default_ttl_days" ], "title": "SetupStatus", - "description": "Pre-login setup snapshot: the wizard state plus what is configured.\n\nAccounts are deliberately absent. Whether a real user exists is reported\nthrough the ``first_user`` step; the account list itself is never served\nto an unauthenticated caller." + "description": "Pre-login setup snapshot: the wizard state plus what is configured.\n\nAccounts are deliberately absent. Whether a real user exists is reported\nthrough the ``first_user`` step. The account list itself is never served\nto an unauthenticated caller." }, "SetupStep": { "properties": { @@ -50857,7 +51319,7 @@ } ], "title": "Type", - "description": "Optional ClickHouse type to CAST the value to (e.g. 'String', 'UInt32')" + "description": "Optional ClickHouse type for the value (e.g. 'String', 'UInt32')" } }, "type": "object", @@ -50865,7 +51327,7 @@ "sigma_field" ], "title": "SigmaViewColumn", - "description": "One column exposed by a Sigma source-view.\n\nA column maps a standard ``sigma_field`` (the alias the view exposes) to EITHER\na real table column (``source_column``) OR a dotted path inside the source's\n``_json`` column (``json_path``) - exactly one of the two. ``type`` is an\noptional ClickHouse type the extracted value is CAST to (mainly for a\nJSON-derived column, whose subcolumn is otherwise a ``Dynamic``). This is the\nSigma-named shape of :class:`~dfe_engine.fieldmap.remap_view.RemapColumn`." + "description": "One column exposed by a Sigma source-view.\n\nA column maps a standard ``sigma_field`` (the alias the view exposes) to EITHER\na real table column (``source_column``) OR a dotted path inside the source's\n``_json`` column (``json_path``) - exactly one of the two. ``type`` is an\noptional ClickHouse type for the value, read as RemapColumn reads it. This is the\nSigma-named shape of :class:`~dfe_engine.fieldmap.remap_view.RemapColumn`." }, "SigmaViewDefinition": { "properties": { @@ -50900,7 +51362,7 @@ "source_name" ], "title": "SigmaViewDefinition", - "description": "A CRUD-managed Sigma view definition for one source.\n\nKeyed (in the store) by ``source_name``; the generated view targets table\n``source_name`` and is named ``{source_name}_sigma``. ``include_source_columns``\nappends ``SELECT *`` so the base table columns remain visible alongside the\nSigma-aligned aliases (the legacy view's behaviour)." + "description": "A CRUD-managed Sigma view definition for one source.\n\nKeyed (in the store) by ``source_name``. The generated view targets table\n``source_name`` and is named ``{source_name}_sigma``. ``include_source_columns``\nappends ``SELECT *`` so the base table columns remain visible alongside the\nSigma-aligned aliases (the legacy view's behaviour)." }, "SigmaViewResult": { "properties": { @@ -50983,7 +51445,7 @@ }, "type": "object", "title": "SigmaViewWriteRequest", - "description": "Create/replace body for a source's Sigma view definition (source_name is the path).\n\nEach column maps a Sigma field to a real source column OR a path inside the\nsource's ``_json`` payload (a JSON-derived column); the ``SigmaViewColumn``\nvalidator enforces exactly one per column." + "description": "Create/replace body for a source's Sigma view definition (source_name is the path).\n\nEach column maps a Sigma field to a real source column OR a path inside the\nsource's ``_json`` payload (a JSON-derived column). The ``SigmaViewColumn``\nvalidator enforces exactly one per column." }, "SourceBundle-Input": { "properties": { @@ -51980,8 +52442,7 @@ "version": { "type": "string", "title": "Version", - "description": "Common header version (semver)", - "default": "1.0.3" + "description": "Common header version (semver); the profile's current version when omitted" } }, "type": "object", @@ -54080,7 +54541,7 @@ }, "type": "object", "title": "SystemDefaultsPatch", - "description": "A partial change. Omitted fields stay as they are; null clears that override." + "description": "A partial change. Omitted fields stay as they are. Null clears that override." }, "SystemDefaultsUpdate": { "properties": { @@ -54431,7 +54892,7 @@ "error" ], "title": "TopicFailure", - "description": "One topic the broker would not do the thing to; the broker's own text is in the log." + "description": "One topic the broker would not do the thing to. The broker's own text is in the log." }, "TopicRemoveResponse": { "properties": { @@ -54622,7 +55083,7 @@ }, "type": "object", "title": "TopicUpdateResponse", - "description": "Outcome of a converge pass.\n\n``refused`` is what DFE declined to do (a partition decrease, a replication\nfactor change); ``failed`` is what the broker rejected. They are different\nproblems with different fixes, so they are different lists." + "description": "Outcome of a converge pass.\n\n``refused`` is what DFE declined to do (a partition decrease, a replication\nfactor change). ``failed`` is what the broker rejected. They are different\nproblems with different fixes, so they are different lists." }, "TotalsResponse": { "properties": { @@ -55489,7 +55950,7 @@ }, "type": "array", "title": "Org Ids", - "description": "Orgs this user can browse in the data plane (HyperDX). Empty means no org-scoped data access." + "description": "Orgs this user can browse in the data plane (Search). Empty means no org-scoped data access." }, "external": { "type": "boolean", @@ -55829,11 +56290,12 @@ "type": "string", "enum": [ "deploy-repo", + "registry", "deployment", "engine" ], "title": "Source", - "description": "deploy-repo when the stack version came from pins.yaml, deployment when it came from what deployed this pod, else engine." + "description": "deploy-repo when the stack version came from pins.yaml, registry when the published stack manifests matched the images this deployment runs, deployment when it came from what deployed this pod, else engine." }, "python_version": { "type": "string", diff --git a/packages/dfe-engine-types/types/index.d.ts b/packages/dfe-engine-types/types/index.d.ts index 4740eb80f..a08fbdf8e 100644 --- a/packages/dfe-engine-types/types/index.d.ts +++ b/packages/dfe-engine-types/types/index.d.ts @@ -18,7 +18,7 @@ export interface paths { * @description Authenticate with local credentials and receive a JWT token. * * The password check runs off the event loop. Failed attempts back off per - * username and per client address (``auth.login_throttle``); a waiting attempt is + * username and per client address (``auth.login_throttle``). A waiting attempt is * refused with 429 before the password is checked. */ post: operations["auth.login"]; @@ -90,8 +90,8 @@ export interface paths { * groups or orgs, because its token carries none until the change. * * ``hyperdx_role`` and ``hyperdx_identity`` are what dfe-hyperdx takes a - * session's dashboard role and team from; it caches this answer for 30 seconds, - * so a group change reaches HyperDX in that window rather than at token expiry. + * session's dashboard role and team from. It caches this answer for 30 seconds, + * so a group change reaches dfe-hyperdx in that window rather than at token expiry. */ get: operations["auth.me.list"]; put?: never; @@ -139,7 +139,7 @@ export interface paths { * configured deployment does not serve its inventory to anonymous callers. * The exception is the name and display name of each enabled OIDC provider, * which stay (no configuration) because the login screen needs to know which - * IdPs to offer and what to call them. Accounts are never returned; the + * IdPs to offer and what to call them. Accounts are never returned. The * ``first_user`` step reports whether a real (non break-glass) user exists. */ get: operations["auth.setup-status.list"]; @@ -421,7 +421,7 @@ export interface paths { * @description Poll whether an account's password has merged to the deploy repo's main. * * Step 2 of the review-PR path for the local admin and ``breakglass``: the UI - * polls this after the operator merges the PR; it fetches remote main and flips + * polls this after the operator merges the PR. It fetches remote main and flips * ``merged`` true. Durable immediately in the auto-merge and file-share modes. A * regular user is never git-persisted, so it reports not-git-backed (durable in * its own store). @@ -550,7 +550,7 @@ export interface paths { put?: never; /** * Add Member - * @description Add a member to a group (idempotent; checked at the group's scope). + * @description Add a member to a group (idempotent, checked at the group's scope). */ post: operations["auth.groups.members.create"]; delete?: never; @@ -790,7 +790,7 @@ export interface paths { * Update Provider * @description Update an OIDC provider configuration (admin only). * - * A secret the body omits, value and env var name alike, keeps what the provider already holds, so an update that only flips ``enabled`` does not strand a stored credential; an empty env var name clears the name and keeps the stored copy. A secret the body names an env var for and sends no value for moves onto that env var and its stored copy is deleted once the update is saved, unless the name is the one already held with nothing stored. A move onto an env var the engine does not set is refused (``env_var_not_set``). Any update that touches more than ``enabled`` or ``display_name`` must leave the provider passing the field rules. Both are checked before a secret is written or deleted. + * A secret the body omits, value and env var name alike, keeps what the provider already holds, so an update that only flips ``enabled`` does not strand a stored credential. An empty env var name clears the name and keeps the stored copy. A secret the body names an env var for and sends no value for moves onto that env var and its stored copy is deleted once the update is saved, unless the name is the one already held with nothing stored. A move onto an env var the engine does not set is refused (``env_var_not_set``). Any update that touches more than ``enabled`` or ``display_name`` must leave the provider passing the field rules. Both are checked before a secret is written or deleted. */ put: operations["auth.oidc-providers.apply"]; post?: never; @@ -887,7 +887,7 @@ export interface paths { * List Orgs * @description List organisations visible to the caller, paginated. * - * System-scope org:read holders see every org; org-scope holders see + * System-scope org:read holders see every org. Org-scope holders see * only the orgs their grants cover. */ get: operations["orgs.list"]; @@ -896,7 +896,7 @@ export interface paths { * Create Org * @description Create a new customer organisation (admin only). * - * If HyperDX integration is enabled, the lifecycle manager handles + * If the Search integration is enabled, the lifecycle manager handles * team creation as part of org provisioning. Failure is non-fatal. * * A hunt already naming the org, such as one whose org was deleted, has the new @@ -1071,7 +1071,7 @@ export interface paths { * @description List sources with pagination, search, filtering, and a full object tree. * * The landing source (``main``) is always the first item when it is in the - * result set; remaining sources keep the requested sort. A caller held to its + * result set. Remaining sources keep the requested sort. A caller held to its * orgs does not see a fetcher source bound to another org. */ get: operations["sources.list"]; @@ -1373,7 +1373,7 @@ export interface paths { * * A delete production+team sends to review answers ``review_required`` and * touches nothing else: main still carries the source, so its topics, records and - * HyperDX source stay until the branch is merged. + * Search source stay until the branch is merged. */ delete: operations["sources.delete"]; options?: never; @@ -1452,7 +1452,7 @@ export interface paths { * * Reads the loader's per-table counter out of the otel tables over a bounded * five-minute window, so the console can put a number beside a source without - * the operator opening HyperDX. It answers 200 with nulls where the series is + * the operator opening Search. It answers 200 with nulls where the series is * absent: a source that was only just defined has nothing to report, and that * is not an error. */ @@ -1506,7 +1506,7 @@ export interface paths { * * ``enable`` / ``disable`` / ``dormant`` / ``delete`` apply immediately. * ``deploy`` submits one ``source:deploy`` background task per accepted source - * (poll ``GET /operations/{operation}``); refused names land in ``failed``. + * (poll ``GET /operations/{operation}``). Refused names land in ``failed``. * * An action that applies immediately reports the one reconcile it ends with, as * a single-source write does. @@ -1533,7 +1533,7 @@ export interface paths { * * Recompiles every stack-scoped routing block (receiver, loader, archiver) and * deploys, syncs or removes the instances of every instance-scoped app (a fetcher - * per active fetcher-based source). Every source write does this on its own; this + * per active fetcher-based source). Every source write does this on its own. This * route is the retry when one reported ``apps_sync_error``, and the pass that * deletes a stranded ``_load`` topic a deploy reported in ``topics_pending_removal``. */ @@ -1833,7 +1833,10 @@ export interface paths { }; /** * Get Service Config - * @description Get a full service config by service + instance, every credential masked. + * @description A service config as its instance runs it, every credential masked. + * + * The stored keys over the app's own defaults, read from its mounted contract. + * With no contract mounted only the stored keys are shown. */ get: operations["services.get"]; /** @@ -1849,7 +1852,8 @@ export interface paths { * stored behind it, or in a list entry that cannot be told apart, is a 400 * ``masked_value`` and nothing is saved. A changed field beside a masked secret, * in the same mapping or with the secret one mapping down, is a 400 - * ``credential_reentry_required``: the secret is typed again. + * ``credential_reentry_required``: the secret is typed again. A value the app's + * contract refuses is a 422 ``invalid_config``. */ put: operations["services.apply"]; post?: never; @@ -1916,7 +1920,7 @@ export interface paths { * * The deployer supplies the list, so an empty one means it listed none. Gated to * the admin-class roles, which hold ``deployment:*`` or ``*``: the list maps the - * deployment's consoles. Links only; nothing here carries a credential. + * deployment's consoles. Links only. Nothing here carries a credential. */ get: operations["deployment.admin-links.list"]; put?: never; @@ -2032,11 +2036,12 @@ export interface paths { * Create Rule * @description Create a new hunt rule via RuleCreationService. * - * The service sanitizes the SQL, applies CEL->SQL transpilation, - * validates column references, and optionally estimates query cost. A rule - * whose SQL the hunt runner could not compile is refused with 422. The cost - * preview counts only the orgs the hunts running the rule read, cut to the orgs - * its author may read. + * The rule is written as SQL or as a structured ``condition``, which the engine + * compiles to the SQL and stores with it. The service sanitizes the SQL, + * applies CEL->SQL transpilation, validates column references, and optionally + * estimates query cost. A rule whose SQL the hunt runner could not compile is + * refused with 422. The cost preview counts only the orgs the hunts running the + * rule read, cut to the orgs its author may read. * * A production+team write is routed to a review branch instead of the branch the * runner git-syncs, and the ``X-DFE-Review-Required`` header says so. @@ -2058,8 +2063,8 @@ export interface paths { get?: never; put?: never; /** - * Create Rule From Hyperdx - * @description Create a hunt rule from the SQL a HyperDX view renders to. + * Create Rule From Search + * @description Create a hunt rule from the SQL a Search view renders to. * * Wraps the create pipeline with ``source_type='hyperdx'`` and auto-derives a * unique rule id from the saved-search name, so the caller need not supply one. @@ -2096,6 +2101,32 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/rules/preview": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Preview Rule + * @description Compile a condition and check it exactly as a save would, writing nothing. + * + * Runs the creation pipeline of ``POST /rules`` (compile, parse, the forbidden-keyword + * and column checks, the matches-everything check and the alert-volume preview) under the + * same org fence, and stops before the save. A condition the save would refuse comes back + * with 200 and its reasons in ``sql_errors`` or ``matches_everything``, so a builder can + * show them as the author edits. A body that is not a condition at all is 422. + */ + post: operations["rules.preview"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/rules/{name}": { parameters: { query?: never; @@ -2112,6 +2143,9 @@ export interface paths { * Update Rule * @description Replace a detection rule (re-runs creation pipeline, preserves created_at). * + * The replacement is written as SQL or as a ``condition``, as on create, and a + * rule replaced with SQL no longer carries a condition. + * * A replacement the hunt runner could not compile is refused with 422 and the * stored rule is left as it was. A production+team write is routed to a review * branch instead of the branch the runner git-syncs, and the @@ -2276,7 +2310,7 @@ export interface paths { * @description Conditions that leave the engine degraded while it keeps serving. * * A refused YAML write keeps the old file or the old deploy-repo content, so reads - * stay correct and readiness is not failed; this is where the refusal shows. + * stay correct and readiness is not failed. This is where the refusal shows. */ get: operations["system.status"]; put?: never; @@ -2326,7 +2360,7 @@ export interface paths { * The engine's own tables and every deployed source's table are brought to the new * effective default in this request, with ``ALTER TABLE ... MODIFY TTL`` (or * ``REMOVE TTL`` for 0). A table that declares its own TTL is left alone. A - * ClickHouse failure answers 502 with the override ALREADY committed; sending the + * ClickHouse failure answers 502 with the override ALREADY committed. Sending the * same value again applies it. */ put: operations["system.retention.apply"]; @@ -2359,8 +2393,8 @@ export interface paths { * @description Store the named defaults. Only ttl_days is applied to live tables. * * Omitted fields are left alone. null clears that override. Common-header type, - * version and engine are what a source inherits the next time it is deployed; - * this request does not rewrite them onto live tables. A patch that names + * version and engine are what a source inherits the next time it is deployed. + * This request does not rewrite them onto live tables. A patch that names * ttl_days stores it and then runs the same reconcile as PUT /retention. */ patch: operations["system.defaults.update"]; @@ -2557,7 +2591,7 @@ export interface paths { * Hunts execute in the separate dfe-hunt-runner service (pull-based, coordinated * via ClickHouse), not in this API process, so ``runners`` counts the runners that * beat within their last two polls and ``running`` is whether any did. For "is this - * hunt running", read the per-hunt ``running`` on the hunts list; ``hunt_count`` is + * hunt running", read the per-hunt ``running`` on the hunts list. ``hunt_count`` is * the configured-hunt count. */ get: operations["hunts.status"]; @@ -2628,7 +2662,7 @@ export interface paths { * @description Delete a hunt configuration. * * A production+team delete is routed to a review branch, so the runner keeps - * executing the hunt until that branch is merged; ``X-DFE-Review-Required`` says so. + * executing the hunt until that branch is merged. ``X-DFE-Review-Required`` says so. */ delete: operations["hunts.delete"]; options?: never; @@ -2652,13 +2686,13 @@ export interface paths { * The pull model is kept. Nothing is pushed at the runner and no listener is added * -- the fire is written into the coordination state, and the runner that is * already running picks it up on its next poll, through the same claim that stops - * a hunt double-running. 202 says it is queued, not that it has run; the response + * a hunt double-running. 202 says it is queued, not that it has run. The response * carries the poll interval so the caller knows the longest wait before it starts. * * A hunt with no rate schedule is not something the runner ticks, so a queued run * for one sits unclaimed. That is the schedule's shape, not a failure here. * - * 503 is reserved for ClickHouse actually being unreachable; any other failure to + * 503 is reserved for ClickHouse actually being unreachable. Any other failure to * write the request is a 500, so a bug here never reads as an outage. */ post: operations["hunts.run"]; @@ -2878,7 +2912,7 @@ export interface paths { }; /** * List Samples - * @description List recent sample tasks (most recent first); a caller held to its orgs sees only theirs. + * @description List recent sample tasks (most recent first). A caller held to its orgs sees only theirs. */ get: operations["samples.list"]; put?: never; @@ -3503,7 +3537,7 @@ export interface paths { * * Returns one record per path with observed types, a suggested column name, * and whether the path is already promoted. ``?samples=N`` adds random - * distinct example values; ``?stats=true`` adds coverage + distinct counts. + * distinct example values. ``?stats=true`` adds coverage + distinct counts. * * A caller without a platform grant holding ``schema:read`` reads only its own * orgs' rows, as the sampler holds it, and a table it cannot be held on is 403. @@ -3530,7 +3564,7 @@ export interface paths { * * Resolves the requested ``version`` (or the source's current version). A * version with a ``meta_schema`` uses ``db.`` only after that version - * is deployed and the table exists; otherwise rows are read from + * is deployed and the table exists. Otherwise rows are read from * ``db.`` filtered by the version's match rule. * * Intended for inspecting real data while authoring a match condition or CEL @@ -3570,7 +3604,7 @@ export interface paths { * ``?dry_run=true`` returns the proposed diff and DDL without forking core schemas, * adding meta-schema versions, or updating the source. A core source, such as the * landing source ``main``, is refused with 409 before any schema is resolved or - * written, dry run included; its ``json-paths`` and ``sample-rows`` reads stay open. + * written, dry run included. Its ``json-paths`` and ``sample-rows`` reads stay open. */ post: operations["schemas.promote-field"]; delete?: never; @@ -3594,7 +3628,7 @@ export interface paths { put?: never; /** * Create User - * @description Provision a user. IdP-owned; local password is randomised when omitted. + * @description Provision a user. IdP-owned. Local password is randomised when omitted. * * A password the IdP does send is held to the same length floor as every other * password the API sets, and one under it is refused rather than replaced. @@ -3794,7 +3828,7 @@ export interface paths { * @description Generate Sigma view DDL for all sources (stored definitions win over field maps). * * Defaults to the data database, since that is where a propagated hunt reads - * the view from (``{source}_sigma``); an explicit ``database`` still overrides it. + * the view from (``{source}_sigma``). An explicit ``database`` still overrides it. */ post: operations["sigma.views.create"]; delete?: never; @@ -3825,12 +3859,12 @@ export interface paths { * @description Generate (preview) Sigma view DDL for a source. * * A stored view definition drives generation - including its JSON-derived - * columns - when one exists; otherwise falls back to the static field maps via + * columns - when one exists. Otherwise falls back to the static field maps via * the source mapper, keeping only the mappings whose column the source's table - * carries. Returns the DDL string; does NOT execute it against ClickHouse. + * carries. Returns the DDL string. Does NOT execute it against ClickHouse. * * Defaults to the data database, since that is where a propagated hunt reads - * the view from (``{source}_sigma``); an explicit ``database`` still overrides it. + * the view from (``{source}_sigma``). An explicit ``database`` still overrides it. */ post: operations["sigma.views.post"]; /** @@ -3946,7 +3980,7 @@ export interface paths { put?: never; /** * Disable Provider - * @description Disable a provider (blocks scheduled polling; a manual sync is refused). + * @description Disable a provider (blocks scheduled polling, a manual sync is refused). */ post: operations["sigma.providers.disable"]; delete?: never; @@ -3968,7 +4002,7 @@ export interface paths { * Sync Provider Endpoint * @description Trigger a provider sync into the catalogue. * - * Submitted to the task manager (a git-repo clone is long-running); blocks up to + * Submitted to the task manager (a git-repo clone is long-running). Blocks up to * ``wait`` seconds for inline completion, else returns ``pending`` - poll via * GET /sigma/syncs/{task_id}. */ @@ -4058,7 +4092,7 @@ export interface paths { put?: never; /** * Adopt Catalogue Rule - * @description Detach a rule from upstream (pin its content; a re-import records drift only). + * @description Detach a rule from upstream (pin its content, a re-import records drift only). */ post: operations["sigma.catalogue.adopt"]; delete?: never; @@ -4144,11 +4178,11 @@ export interface paths { * the matching source's ``{source}_sigma`` view and stores a DFE rule (with a * ``sigma_rule_id`` back-reference), then binds it into a per-source hunt. Drifted * or hand-edited bindings are reported ``skipped_drifted`` unless ``force``. - * Submitted to the task manager; blocks up to ``wait`` seconds for inline + * Submitted to the task manager. Blocks up to ``wait`` seconds for inline * completion, else returns ``pending`` - poll via GET /sigma/propagations/{id}. * * A production+team run commits each generated rule and hunt to its own review - * branch rather than the branch the hunt runner syncs; the report carries every + * branch rather than the branch the hunt runner syncs. The report carries every * branch and PR, and ``X-DFE-Review-Required`` says so on a run that completed * inline. 422 ``unknown_org`` when ``hunt_customers`` names no registered org. */ @@ -4375,7 +4409,7 @@ export interface paths { }; /** * List Overlays - * @description List substrate/platform overlay resources in the deploy repo's infra/ dir. + * @description List infra overlay resources in the deploy repo's infra/ dir. */ get: operations["backing-services.overlays"]; put?: never; @@ -4438,21 +4472,21 @@ export interface paths { get?: never; /** * Set Overlay Var - * @description Set a substrate/platform value. + * @description Set an infra overlay value. * * 409 managed_by_provider, before any other check, when DFE does not run the - * service and the value is one of its read_only paths; helmvars:override does not + * service and the value is one of its read_only paths. helmvars:override does not * lift it. 403 with the policy that blocked it when the var is protected - the * storage model, the data-layer modes and the disk size are decided at deploy, and * moving one on a live deployment is a data migration. 400 when the value would * lower a declared node or broker count, or leave it undeclared (a parent map that - * omits it), which loses data rather than capacity; helmvars:override does not lift it. + * omits it), which loses data rather than capacity. helmvars:override does not lift it. */ put: operations["backing-services.overlays.vars.apply"]; post?: never; /** * Delete Overlay Var - * @description Revert a substrate/platform value to its chart default. Protected vars refuse. + * @description Revert an infra overlay value to its chart default. Protected vars refuse. * * 409 managed_by_provider, before any other check and whatever the caller holds, * when DFE does not run the service and the value is one of its read_only paths. @@ -4609,7 +4643,7 @@ export interface paths { * A secret is written like any other option: it goes into the overlay as the rest * of this surface writes one, and neither this response nor a read route on this * surface says what it is. A masked value written back as it was read keeps the - * stored credential; the mask where nothing is stored is a 400 ``masked_value``. + * stored credential. The mask where nothing is stored is a 400 ``masked_value``. * A changed field beside a stored credential, in the same mapping or with the * credential one mapping down (``brokers`` beside ``sasl.password``), is a 400 * ``credential_reentry_required`` until that mapping is written whole with its @@ -4747,7 +4781,7 @@ export interface paths { * Relink App Files * @description Re-resolve every link in the set to what its target now names. * - * A tag link follows its tag; a version-pinned link advances to the artefact's + * A tag link follows its tag. A version-pinned link advances to the artefact's * current version. This is the fix-once-roll-everywhere half of the library. */ post: operations["apps.files.relink"]; @@ -4770,7 +4804,7 @@ export interface paths { * Copy App Files * @description Copy this instance's authored files onto another instance of the same app. * - * A transform is written against one source; reusing it on another should not mean + * A transform is written against one source. Reusing it on another should not mean * retyping it. Only the files move - the target keeps its own source binding, * scaling and identity. */ @@ -4870,7 +4904,7 @@ export interface paths { * @description Run an authored file over real events from the source, and report each one. * * Nothing is written: no topic, no table, no commit. ``content`` runs unsaved - * content, which is what makes this useful in an editor; omitted, the file + * content, which is what makes this useful in an editor. Omitted, the file * already in the overlay runs instead. */ post: operations["apps.files.dry-run"]; @@ -5104,7 +5138,7 @@ export interface paths { * @description Publish content as a version. * * Re-sending identical content is a no-op naming the version that already holds - * it; sending different content at an existing version number is refused. + * it. Sending different content at an existing version number is refused. */ post: operations["library.versions.create"]; delete?: never; @@ -5226,7 +5260,7 @@ export interface paths { }; /** * Get Action - * @description One defined action; a credential a legacy definition still carries comes back masked. + * @description One defined action. A credential a legacy definition still carries comes back masked. */ get: operations["governance.actions.get"]; put?: never; @@ -5291,14 +5325,14 @@ export interface paths { * @description Invoke a defined action - gated on the action's OWN required_action. * * ``body.params`` supplies values for the action's declared params (422 on a - * constraint violation; omitted params take their defaults). A hunt or rule + * constraint violation. Omitted params take their defaults). A hunt or rule * document the action would leave invalid is 422 ``invalid_document``, with the * hunts API's own message. A change to the infra overlay meets the backing-services * guards on what the action leaves, dry run included, whatever the caller holds: * 409 ``managed_by_provider`` for a read-only value of a service DFE does not run, * then 400 ``scale_down_refused`` where it lowers or un-declares a node or broker * count. - * Direct commit in dev/solo; a production+team invoke is routed to a review PR (or + * Direct commit in dev/solo. A production+team invoke is routed to a review PR (or * 409 ``review_required`` when no forge is configured). */ post: operations["governance.actions.invoke"]; @@ -5454,7 +5488,7 @@ export interface paths { get: operations["gitops.auto-merge.list"]; /** * Put Auto Merge - * @description Toggle auto-merge. Enabling requires the deployment gate; disabling always works. + * @description Toggle auto-merge. Enabling requires the deployment gate. Disabling always works. */ put: operations["gitops.auto-merge.put"]; post?: never; @@ -5476,7 +5510,7 @@ export interface paths { * @description The resource-class registry - what VarChange.cls may legally name. * * Registry metadata only (no resource content), so any authenticated caller - * may read it; the per-class listings below are gated by each class's grant. + * may read it. The per-class listings below are gated by each class's grant. */ get: operations["gitops.classes.list"]; put?: never; @@ -5543,7 +5577,7 @@ export interface paths { * * Flat + cursor-paginated by default; ?group_by= buckets the page for * summaries. applied_revision (the Argo-synced SHA) turns state into - * applied/pending; without it every entry is 'committed'. + * applied/pending. Without it every entry is 'committed'. */ get: operations["gitops.log.list"]; put?: never; @@ -5585,7 +5619,7 @@ export interface paths { put?: never; /** * Set Lifecycle - * @description Set a service's lifecycle state - per-service RBAC; pinned services are 404. + * @description Set a service's lifecycle state - per-service RBAC. Pinned services are 404. */ post: operations["lifecycle.post"]; delete?: never; @@ -5604,8 +5638,8 @@ export interface paths { get?: never; put?: never; /** - * From Hyperdx - * @description Strip a HyperDX query's time bounds -> {window}, ready to save as a rule. + * Strip Search Query Time Bounds + * @description Strip a Search query's time bounds -> {window}, ready to save as a rule. */ post: operations["authoring.from-hyperdx"]; delete?: never; @@ -5725,7 +5759,7 @@ export interface paths { * Client Config * @description Runtime config for the web UI. * - * Authenticated but ungated: every console pane may read it, and the HyperDX URL + * Authenticated but ungated: every console pane may read it, and the Search URL * it returns is internal to the deployment. */ get: operations["config.client"]; @@ -5745,7 +5779,7 @@ export interface paths { cookie?: never; }; /** - * Hyperdx Connection + * Get Search Connection * @description Return the caller's OWN org connection - never another org's. * * A caller granted ``query:execute`` at system scope by a declared, unscoped role @@ -5771,11 +5805,11 @@ export interface paths { cookie?: never; }; /** - * Hyperdx Sources - * @description List every HyperDX team and the DFE sources on it. + * List Search Sources + * @description List every Search team and the DFE sources on it. * * A deploy writes its source to every team, so this is the read that says where - * it landed. 503 when HyperDX is not deployed or not answering -- an empty list + * it landed. 503 when Search is not deployed or not answering -- an empty list * would read as "the source is missing", which is a different fault. */ get: operations["hyperdx.sources"]; @@ -8362,7 +8396,7 @@ export interface components { * DeclaredValue * @description One value as the deploy repo declares it. * - * ``source`` names the overlay file it came from; a null source means the + * ``source`` names the overlay file it came from. A null source means the * deployment declared nothing and the chart or profile default applies. Those * defaults live in dfe-infra, which the engine does not read, so the API says * "not declared" rather than guessing a number. @@ -8467,10 +8501,10 @@ export interface components { }; /** * Source - * @description deploy-repo when the stack version came from pins.yaml, deployment when it came from what deployed this pod, else engine. + * @description deploy-repo when the stack version came from pins.yaml, registry when the published stack manifests matched the images this deployment runs, deployment when it came from what deployed this pod, else engine. * @enum {string} */ - source: "deploy-repo" | "deployment" | "engine"; + source: "deploy-repo" | "registry" | "deployment" | "engine"; /** * Backing * @description Who runs each backing service, keyed as GET /backing-services names it. managed_by is dfe wherever the deployer states no provider. @@ -8699,7 +8733,7 @@ export interface components { * Shaped to drop straight into ``MetaSchemaAddVersionRequest.columns`` (the * create-version endpoint) or a new meta-schema's version -- the UI sends these * verbatim, no field mapping. ``type`` is derived from the first observed - * ClickHouse type; for a multi-type path (``is_consistent=false``) confirm it + * ClickHouse type. For a multi-type path (``is_consistent=false``) confirm it * before saving. */ DraftColumn: { @@ -8792,7 +8826,7 @@ export interface components { source: string; /** * Limit - * @description Events to sample and run over + * @description Events to sample and run over, at most transform_validation.dry_run_max_events (100 by default), which a larger value is refused against * @default 10 */ limit: number; @@ -9225,7 +9259,7 @@ export interface components { }; /** * FromHyperdxRequest - * @description Body for turning a HyperDX query into rule SQL. + * @description Body for turning a Search query into rule SQL. */ FromHyperdxRequest: { /** Query */ @@ -9623,6 +9657,12 @@ export interface components { min_interval_seconds?: number | null; /** Explain Queries */ explain_queries?: boolean | null; + /** + * Enabled + * @description Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing. + * @default true + */ + enabled: boolean; /** * Rules * @description Rule names, each the ``{name}.yaml`` rule file the hunt runner reads @@ -9674,6 +9714,12 @@ export interface components { min_interval_seconds?: number | null; /** Explain Queries */ explain_queries?: boolean | null; + /** + * Enabled + * @description Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing. + * @default true + */ + enabled: boolean; /** * Name * @description Hunt file name (YAML stem) @@ -9833,6 +9879,23 @@ export interface components { * @description Epoch seconds of the next scheduled fire; null = no rate schedule */ next_due?: number | null; + /** + * Enabled + * @description Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing. + * @default true + */ + enabled: boolean; + /** + * Auto Disabled At + * @description When the runner stopped the hunt after repeated resource-limit failures, epoch seconds + */ + auto_disabled_at?: number | null; + /** + * Auto Disabled Reason + * @description The ClickHouse error category and code that tripped the auto-disable + * @default + */ + auto_disabled_reason: string; }; /** * HuntWriteRequest @@ -9874,6 +9937,12 @@ export interface components { min_interval_seconds?: number | null; /** Explain Queries */ explain_queries?: boolean | null; + /** + * Enabled + * @description Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing. + * @default true + */ + enabled: boolean; /** * Rules * @description Rule names, each the ``{name}.yaml`` rule file the hunt runner reads @@ -9882,7 +9951,7 @@ export interface components { }; /** * HyperDXConfig - * @description Whether the UI links to HyperDX, and where. + * @description Whether the UI links to Search, and where. */ HyperDXConfig: { /** @@ -9898,7 +9967,7 @@ export interface components { }; /** * HyperDXConnection - * @description Connection material in the fork's shape (name, host URL, username, password). + * @description Connection material in the fork's shape, plus where its seed sources live. */ HyperDXConnection: { /** Name */ @@ -9909,10 +9978,27 @@ export interface components { username: string; /** Password */ password: string; + /** + * Platform + * @description True for the platform reader, which reads every org + */ + platform: boolean; + /** + * Database + * @description The DFE data database every seeded table lives in + */ + database: string; + /** + * Tables + * @description Seeded table name by dfe-schemas manifest id + */ + tables: { + [key: string]: string; + }; }; /** * HyperDXSourcesResponse - * @description Where every deployed DFE source actually landed in HyperDX. + * @description Where every deployed DFE source actually landed in Search. */ HyperDXSourcesResponse: { /** Teams */ @@ -9920,17 +10006,17 @@ export interface components { }; /** * HyperDXTeamSource - * @description One HyperDX source on one team, as the fork holds it. + * @description One Search source on one team, as dfe-hyperdx holds it. */ HyperDXTeamSource: { /** * Id - * @description HyperDX source id on that team + * @description Search source id on that team */ id: string; /** * Name - * @description DFE source name; the HyperDX source carries the same one + * @description DFE source name; the Search source carries the same one */ name: string; /** @@ -9943,17 +10029,17 @@ export interface components { }; /** * HyperDXTeamSources - * @description One HyperDX team and the DFE sources it holds. + * @description One Search team and the DFE sources it holds. */ HyperDXTeamSources: { /** * Team - * @description HyperDX team id + * @description Search team id */ team: string; /** * Team Name - * @description HyperDX team name: the ClickHouse user its members read as + * @description Search team name: the ClickHouse user its members read as */ team_name: string; /** Sources */ @@ -10615,7 +10701,7 @@ export interface components { * Attributes: * current: Current version of the schema. * versions: Dictionary of versions and their metadata. - * path: Registry path key (e.g. ``aws/cloudtrail``); omitted from YAML on disk. + * path: Registry path key (e.g. ``aws/cloudtrail``). Omitted from YAML on disk. */ MetaSchema: { /** @@ -11174,8 +11260,8 @@ export interface components { * display_name: Human-readable label for UI display. * org_ids: Tenant IDs used for ClickHouse row-level security filters. * enabled: Whether this org is active. - * hyperdx_team_id: HyperDX team ID for this org's connection sync. - * hyperdx_team_api_key_env: Environment variable name holding the org's HyperDX team API key. + * hyperdx_team_id: dfe-hyperdx team ID for this org's connection sync. + * hyperdx_team_api_key_env: Environment variable name holding the org's dfe-hyperdx team API key. * ch_password_env: Environment variable name holding the ClickHouse password. * created_at: ISO 8601 timestamp of creation. * updated_at: ISO 8601 timestamp of last update. @@ -12339,11 +12425,6 @@ export interface components { * @default true */ cache: boolean; - /** - * Store - * @description Target store (database/schema/topic) - only if query allows - */ - store?: string | null; }; /** * QueryResponse @@ -12817,6 +12898,47 @@ export interface components { */ warnings?: string[]; }; + /** + * RuleCondition + * @description One test on a field, or ``all`` or ``any`` of several, as the rule builder writes it. + * + * A test compares one ``field`` with an ``operator``. ``all`` holds when every + * part does and ``any`` when at least one does. Each part is a condition of its + * own, so groups nest, and ``negate`` inverts the test or group it sits on. + */ + RuleCondition: { + /** + * Field + * @description Field a test reads: a column of the source table, or a dotted path inside the record as it arrived (e.g. 'tags.collector.type', or '_json.tags.collector.type'). Each part is letters, digits, '_' and '-', starting with a letter or '_'. Absent on a group + */ + field?: string | null; + /** + * Operator + * @description How a test compares ``field`` to ``value``: equals (the default for a test), not_equals, exists, includes, starts_with, ends_with, lt, lte, gt, gte, in. Absent on a group + */ + operator?: ("equals" | "not_equals" | "exists" | "includes" | "starts_with" | "ends_with" | "lt" | "lte" | "gt" | "gte" | "in") | null; + /** + * Value + * @description Operand for the operator, by its kind: none for exists, text for includes, starts_with and ends_with, text or a number for equals and not_equals, a number or an ISO 8601 date or date-time for lt, lte, gt and gte, a list of texts or of numbers for in + */ + value?: components["schemas"]["Scalar"] | components["schemas"]["Scalar"][] | null; + /** + * Negate + * @description Invert this test or group + * @default false + */ + negate: boolean; + /** + * All + * @description A group that holds when every part holds + */ + all?: components["schemas"]["RuleCondition"][]; + /** + * Any + * @description A group that holds when at least one part holds + */ + any?: components["schemas"]["RuleCondition"][]; + }; /** * RuleCreateRequest * @description Create a hunt rule via RuleCreationService. @@ -12835,9 +12957,11 @@ export interface components { severity: string; /** * User Sql - * @description Full detection query: SELECT ... FROM .
WHERE ... (the FROM names the source table) + * @description Full detection query: SELECT ... FROM .
WHERE ... (the FROM names the source table). Give this or ``condition``, not both. A rule saved this way has no ``condition`` */ - user_sql: string; + user_sql?: string | null; + /** @description The rule's structured condition, which the engine compiles to its SQL and stores with it, so the builder reopens on it. Reads the table of ``source``. Give this or ``user_sql``, not both */ + condition?: components["schemas"]["RuleCondition"] | null; /** * Cel Filter * @description CEL expression filter @@ -12871,7 +12995,7 @@ export interface components { name: string; /** * Source Type - * @description 'raw' (plain SQL) or 'hyperdx' (HyperDX saved search format) + * @description 'raw' (plain SQL) or 'hyperdx' (Search saved search format) * @default raw * @enum {string} */ @@ -12905,23 +13029,23 @@ export interface components { }; /** * RuleFromHyperdxRequest - * @description Create a hunt rule from the SQL a HyperDX view runs. + * @description Create a hunt rule from the SQL a Search view runs. * - * HyperDX renders the view to ``raw_sql`` and sends it here. The create + * Search renders the view to ``raw_sql`` and sends it here. The create * pipeline strips the UI meta (time bounds, LIMIT, ``__hdx_time_bucket``, - * SETTINGS) via the HyperDX sanitizer, and the engine derives a unique rule id + * SETTINGS) via the dfe-hyperdx sanitizer, and the engine derives a unique rule id * from the saved-search name. The caller gets that id back and opens * ``/rules/{id}`` -- no id to invent, no IndexedDB round-trip. */ RuleFromHyperdxRequest: { /** * Raw Sql - * @description The ClickHouse SELECT the HyperDX view renders to + * @description The ClickHouse SELECT the Search view renders to */ raw_sql: string; /** * Saved Search Name - * @description HyperDX saved-search name; seeds the rule id and label + * @description Search saved-search name; seeds the rule id and label */ saved_search_name?: string | null; /** @@ -12943,7 +13067,7 @@ export interface components { }; /** * RuleFromHyperdxResponse - * @description The rule created from a HyperDX query. + * @description The rule created from a Search query. */ RuleFromHyperdxResponse: { /** @@ -13034,6 +13158,69 @@ export interface components { /** Blocks */ blocks: components["schemas"]["RuleBlockResponse"][]; }; + /** + * RulePreviewRequest + * @description A condition to compile and check as a save would, without saving it. + */ + RulePreviewRequest: { + /** + * Source + * @description Source label whose table the condition reads + */ + source: string; + condition: components["schemas"]["RuleCondition"]; + /** + * Cel Filter + * @description CEL expression ANDed in, as on save + */ + cel_filter?: string | null; + /** + * Cost Window Minutes + * @description Lookback window in minutes the volume preview counts over. Absent or 0 uses the deployment's preview window. + */ + cost_window_minutes?: number | null; + /** + * Name + * @description The rule being edited. The volume preview then counts the orgs of the hunts that run it and of the hunt it names, as its save would + */ + name?: string | null; + /** + * Hunt Name + * @description The hunt the rule names as its own, which the count follows. Defaults to the stored rule's + */ + hunt_name?: string | null; + }; + /** + * RulePreviewResponse + * @description What a save of the condition would compile to and find, and nothing written. + */ + RulePreviewResponse: { + /** + * User Sql + * @description The rule SQL the condition compiles to, empty when it does not + */ + user_sql: string; + /** Source Db */ + source_db?: string | null; + /** Source Table */ + source_table?: string | null; + /** + * Where Clause + * @description The detection WHERE the rule would store + */ + where_clause: string; + /** + * Sql Errors + * @description Why a save would be refused as invalid + */ + sql_errors?: components["schemas"]["SqlValidationError"][]; + /** + * Matches Everything + * @description Why a save would be refused for matching every event, when it would + */ + matches_everything?: string | null; + cost_estimate?: components["schemas"]["CostEstimate"] | null; + }; /** * RuleResponse * @description A detection rule as the API returns it. @@ -13059,6 +13246,8 @@ export interface components { where_clause: string; /** Cel Filter */ cel_filter?: string | null; + /** @description The structured condition the SQL was compiled from, absent for a rule written as SQL */ + condition?: components["schemas"]["RuleCondition"] | null; /** Original Sql */ original_sql: string; /** Hunt Name */ @@ -13115,9 +13304,11 @@ export interface components { severity: string; /** * User Sql - * @description Full detection query: SELECT ... FROM .
WHERE ... (the FROM names the source table) + * @description Full detection query: SELECT ... FROM .
WHERE ... (the FROM names the source table). Give this or ``condition``, not both. A rule saved this way has no ``condition`` */ - user_sql: string; + user_sql?: string | null; + /** @description The rule's structured condition, which the engine compiles to its SQL and stores with it, so the builder reopens on it. Reads the table of ``source``. Give this or ``user_sql``, not both */ + condition?: components["schemas"]["RuleCondition"] | null; /** * Cel Filter * @description CEL expression filter @@ -13155,7 +13346,7 @@ export interface components { * SampleMode * @description How to pick the sample. * - * - ``recent`` - newest rows first (fast tail; ClickHouse ORDER BY ts DESC, + * - ``recent`` - newest rows first (fast tail, ClickHouse ORDER BY ts DESC, * Kafka reads from the partition high-watermark backwards). * - ``random`` - uniform-ish random rows (fair distribution, no recency bias). * - ``smart`` - logreducer representative/diverse sample (default). Gated. @@ -13192,7 +13383,7 @@ export interface components { * Provide EITHER a registered ``source`` (its CH table / land topic are * resolved for you) OR an explicit ``table``/``topic`` (ad-hoc - for a source * that is not registered yet, e.g. AI onboarding). ``filter`` (ClickHouse - * backend only) must be one condition over the sampled table's columns; it is + * backend only) must be one condition over the sampled table's columns. It is * replaced by the condition rendered from its parse tree, and anything else is * refused when the request is built. */ @@ -13399,6 +13590,7 @@ export interface components { */ limit: number; }; + Scalar: string | number; /** * ScalingRequest * @description Body for setting an instance's scaling dials. @@ -13691,12 +13883,12 @@ export interface components { apps_sync_error?: string | null; /** * Hyperdx Source Teams - * @description How many HyperDX teams now carry a source over this source's table + * @description How many Search teams now carry a source over this source's table */ hyperdx_source_teams?: number | null; /** * Hyperdx Source Error - * @description Why HyperDX was not pointed at the table. Never fails the deploy - the schema is live and HyperDX may be down or not deployed at all. + * @description Why Search was not pointed at the table. Never fails the deploy - the schema is live and Search may be down or not deployed at all. */ hyperdx_source_error?: string | null; /** @@ -14047,7 +14239,7 @@ export interface components { }; /** * ServiceConfigDetail - * @description Full service config. Inner config is dynamic (schema-less mode). + * @description One service config as its instance runs it: the stored keys over the app's defaults. */ ServiceConfigDetail: { /** @@ -14154,7 +14346,7 @@ export interface components { * @description Pre-login setup snapshot: the wizard state plus what is configured. * * Accounts are deliberately absent. Whether a real user exists is reported - * through the ``first_user`` step; the account list itself is never served + * through the ``first_user`` step. The account list itself is never served * to an unauthenticated caller. */ SetupStatus: { @@ -14258,8 +14450,7 @@ export interface components { * A column maps a standard ``sigma_field`` (the alias the view exposes) to EITHER * a real table column (``source_column``) OR a dotted path inside the source's * ``_json`` column (``json_path``) - exactly one of the two. ``type`` is an - * optional ClickHouse type the extracted value is CAST to (mainly for a - * JSON-derived column, whose subcolumn is otherwise a ``Dynamic``). This is the + * optional ClickHouse type for the value, read as RemapColumn reads it. This is the * Sigma-named shape of :class:`~dfe_engine.fieldmap.remap_view.RemapColumn`. */ SigmaViewColumn: { @@ -14280,7 +14471,7 @@ export interface components { json_path?: string | null; /** * Type - * @description Optional ClickHouse type to CAST the value to (e.g. 'String', 'UInt32') + * @description Optional ClickHouse type for the value (e.g. 'String', 'UInt32') */ type?: string | null; }; @@ -14288,7 +14479,7 @@ export interface components { * SigmaViewDefinition * @description A CRUD-managed Sigma view definition for one source. * - * Keyed (in the store) by ``source_name``; the generated view targets table + * Keyed (in the store) by ``source_name``. The generated view targets table * ``source_name`` and is named ``{source_name}_sigma``. ``include_source_columns`` * appends ``SELECT *`` so the base table columns remain visible alongside the * Sigma-aligned aliases (the legacy view's behaviour). @@ -14358,7 +14549,7 @@ export interface components { * @description Create/replace body for a source's Sigma view definition (source_name is the path). * * Each column maps a Sigma field to a real source column OR a path inside the - * source's ``_json`` payload (a JSON-derived column); the ``SigmaViewColumn`` + * source's ``_json`` payload (a JSON-derived column). The ``SigmaViewColumn`` * validator enforces exactly one per column. */ SigmaViewWriteRequest: { @@ -14888,10 +15079,9 @@ export interface components { type: string; /** * Version - * @description Common header version (semver) - * @default 1.0.3 + * @description Common header version (semver); the profile's current version when omitted */ - version: string; + version?: string; }; /** * SourceImportResponse @@ -15883,7 +16073,7 @@ export interface components { }; /** * SystemDefaultsPatch - * @description A partial change. Omitted fields stay as they are; null clears that override. + * @description A partial change. Omitted fields stay as they are. Null clears that override. */ SystemDefaultsPatch: { /** @@ -16108,7 +16298,7 @@ export interface components { }; /** * TopicFailure - * @description One topic the broker would not do the thing to; the broker's own text is in the log. + * @description One topic the broker would not do the thing to. The broker's own text is in the log. */ TopicFailure: { /** Name */ @@ -16182,7 +16372,7 @@ export interface components { * @description Outcome of a converge pass. * * ``refused`` is what DFE declined to do (a partition decrease, a replication - * factor change); ``failed`` is what the broker rejected. They are different + * factor change). ``failed`` is what the broker rejected. They are different * problems with different fixes, so they are different lists. */ TopicUpdateResponse: { @@ -16644,7 +16834,7 @@ export interface components { groups?: string[]; /** * Org Ids - * @description Orgs this user can browse in the data plane (HyperDX). Empty means no org-scoped data access. + * @description Orgs this user can browse in the data plane (Search). Empty means no org-scoped data access. */ org_ids?: string[]; /** @@ -16855,10 +17045,10 @@ export interface components { }; /** * Source - * @description deploy-repo when the stack version came from pins.yaml, deployment when it came from what deployed this pod, else engine. + * @description deploy-repo when the stack version came from pins.yaml, registry when the published stack manifests matched the images this deployment runs, deployment when it came from what deployed this pod, else engine. * @enum {string} */ - source: "deploy-repo" | "deployment" | "engine"; + source: "deploy-repo" | "registry" | "deployment" | "engine"; /** * Python Version * @description Python interpreter version @@ -17592,7 +17782,7 @@ export interface operations { "application/problem+json": components["schemas"]["Problem"]; }; }; - /** @description The break-glass account is disabled in governance settings */ + /** @description The break-glass password is right, but the account is disabled in governance settings */ 403: { headers: { [name: string]: unknown; @@ -20742,8 +20932,8 @@ export interface operations { "orgs.available-ids": { parameters: { query?: { - /** @description Most tenant ids to return -- a suggestion list, not an export */ - limit?: number; + /** @description Most tenant ids to return -- a suggestion list, not an export. Unset takes orgs.available_ids_limit (200 by default) */ + limit?: number | null; }; header?: never; path?: never; @@ -24458,6 +24648,66 @@ export interface operations { }; }; }; + "rules.preview": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["RulePreviewRequest"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["RulePreviewResponse"]; + }; + }; + /** @description No valid session: the credentials are missing, invalid or expired, or the account behind them is disabled or blocked */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Refused: the session lacks the action this route checks, or its account must replace an issued password first. A SCIM route answers a refused action in the RFC 7644 error envelope */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Problem details (RFC 9457) */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + }; + }; "rules.get": { parameters: { query?: never; @@ -25889,6 +26139,8 @@ export interface operations { query?: { /** @description Case-insensitive search in name, display_name, customers, rules, source_table, target_table */ search?: string | null; + /** @description Only the hunts whose rules include this rule, by its exact name */ + rule?: string | null; /** @description Items per page: 0 means 50, above 1000 is cut to it */ page_size?: number; /** @description The next_page_token of the previous page */ From 21187acaba23687cb058115c6fcf1ae09794cc9c Mon Sep 17 00:00:00 2001 From: Derek Date: Mon, 16 Nov 2026 17:35:55 +1100 Subject: [PATCH 02/10] fix(hunts): read the runner's stop from the hunt detail The engine returns auto_disabled_at and auto_disabled_reason on GET /hunts/{name}. The console read the stop from the loaded list page. A direct link to a hunt outside that page showed no Auto-disabled tag and offered Disable instead of Re-enable. - useHuntRunState takes the stop from the detail and falls back to the list row only for an engine that leaves the field out. - Enable, Disable and Re-enable fetch the hunt before the PUT. The engine has no per-field write, so a toggle sends the whole config. Without the read, it could undo an edit made since the page loaded. - Above the Enabled switch, the edit drawer warns when the runner stopped the hunt. It says a save leaves the hunt stopped. - Engine types regenerated from the engine's spec. A Playwright spec covers the toggle and the edit rule against the live stack. --- .../dfe-core-ui/e2e/specs/huntEnabled.spec.ts | 205 ++++++++++++++++++ .../CloneHuntModal/CloneHuntModal.test.tsx | 1 + .../CreateUpdateHuntForm.test.tsx | 72 ++++++ .../huntTargetTable.test.tsx | 32 +++ .../components/CreateUpdateHuntForm/index.tsx | 15 +- .../HuntStateTag/HuntStateTag.stories.tsx | 3 +- .../components/UpdateHuntDrawer/index.tsx | 6 + .../HuntDetailActionMenu.test.tsx | 52 +++++ .../HuntDetailActionMenu/index.tsx | 49 +++-- .../ConfigurationDetailsTabContent.test.tsx | 1 + .../useCreateHunt/useCreateHunt.test.tsx | 1 + .../useFetchHuntDetail.test.tsx | 1 + .../src/Hunts/hooks/useHuntRunState/index.ts | 18 +- .../useHuntRunState/useHuntRunState.test.tsx | 98 +++++++++ .../useUpdateHunt/useUpdateHunt.test.tsx | 1 + .../transformHuntDetailToFormData.test.ts | 1 + .../api/endpoints/generator/mocks/hunts.ts | 3 + packages/dfe-engine-types/specs/openapi.json | 54 ++++- packages/dfe-engine-types/types/index.d.ts | 33 ++- 19 files changed, 599 insertions(+), 47 deletions(-) create mode 100644 apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts create mode 100644 apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/useHuntRunState.test.tsx diff --git a/apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts b/apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts new file mode 100644 index 000000000..9dee35b40 --- /dev/null +++ b/apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts @@ -0,0 +1,205 @@ +import { expect, Page, test } from '@playwright/test'; + +import { BASE_URL, e2eClient } from '@e2e/config/e2e.client'; +import { engine, forgetEngineToken } from '@e2e/config/engineApi.helpers'; +import { loginAs } from '@e2e/config/login.helpers'; + +/** + * A hunt's enabled state in the console: the actions menu turns it off and on, + * an edit that leaves the switch alone keeps a disabled hunt disabled, and a + * hunt the runner stopped shows why until Re-enable brings it back. + * + * The last case needs a hunt runner ticking against this engine with a hunt + * whose SQL trips a ClickHouse limit. E2E_STOPPED_HUNT names that hunt, and the + * case is skipped without it. It runs with no reset, because reset_all deletes + * every hunt, that one included. + */ + +const ORG = 'stopco'; +const HUNT = 'stop_hunt'; +const HUNT_LABEL = 'Stop Hunt'; +const RULE = 'stop_rule'; +const STOPPED = process.env.E2E_STOPPED_HUNT; +const SHOTS = 'test-results/hunt-enabled'; + +type HuntRow = { + name: string; + display_name: string | null; + enabled: boolean; + auto_disabled_at: number | null; + auto_disabled_reason: string; +}; + +const deleteIfPresent = async (path: string) => { + try { + await engine('DELETE', path); + } catch (error) { + if (!String(error).includes('-> 404')) throw error; + } +}; + +const huntRow = async (name: string): Promise => { + const page = await engine<{ items: HuntRow[] }>( + 'GET', + `/api/v1/hunts?per_page=100&search=${name}`, + ); + const row = page.items.find((item) => item.name === name); + if (!row) throw new Error(`hunt ${name} is not in the list`); + return row; +}; + +const openHunt = async (page: Page, name: string, label: string) => { + await page.goto(`${BASE_URL}/hunts?name=${name}`); + await expect( + page.getByRole('heading', { name: new RegExp(label) }), + ).toBeVisible(); +}; + +const listRow = (page: Page, label: string) => + page.getByRole('listitem').filter({ hasText: label }); + +// The menu stays open after a toggle, with its button renamed Close actions. +const openMenu = async (page: Page) => { + const open = page.getByRole('button', { name: 'Close actions', exact: true }); + if ((await open.count()) === 0) { + await page.getByRole('button', { name: 'Actions', exact: true }).click(); + } +}; + +const menuAction = async (page: Page, action: string) => { + await openMenu(page); + await page.getByRole('button', { name: action, exact: true }).click(); +}; + +test.describe('A hunt made through the API', () => { + test.beforeEach(async ({ playwright, page }) => { + await e2eClient({ playwright, seedScript: 'reset_all' }); + await e2eClient({ playwright, seedScript: 'seed_setup_complete' }); + await e2eClient({ playwright, seedScript: 'seed_dfe_admin_user' }); + forgetEngineToken(); + + await deleteIfPresent(`/api/v1/hunts/${HUNT}`); + await deleteIfPresent(`/api/v1/rules/${RULE}`); + await engine('POST', '/api/v1/orgs', { + name: ORG, + display_name: 'Stop Co', + org_ids: [`${ORG}-1`], + }); + await engine('POST', '/api/v1/rules', { + name: RULE, + severity: 'medium', + user_sql: "SELECT * FROM dfe.main WHERE _source = 'stop'", + estimate_cost: false, + }); + await engine('POST', '/api/v1/hunts', { + name: HUNT, + display_name: HUNT_LABEL, + cron: '*/5 * * * *', + log_buffer: 60, + customers: [ORG], + rules: [RULE], + global_source_table_name: 'main', + }); + + await loginAs(page, 'dfe_admin'); + }); + + test('Disable and enable from the actions menu', async ({ page }) => { + await openHunt(page, HUNT, HUNT_LABEL); + await expect(listRow(page, HUNT_LABEL).getByText('Disabled')).toHaveCount( + 0, + ); + + await menuAction(page, 'Disable Hunt'); + await expect(page.getByText(`Hunt ${HUNT_LABEL} disabled`)).toBeVisible(); + await expect(listRow(page, HUNT_LABEL).getByText('Disabled')).toBeVisible(); + await expect( + page + .getByRole('heading', { name: new RegExp(HUNT_LABEL) }) + .getByText('Disabled'), + ).toBeVisible(); + await page.screenshot({ path: `${SHOTS}/disabled.png` }); + expect((await huntRow(HUNT)).enabled).toBe(false); + + await menuAction(page, 'Enable Hunt'); + await expect(page.getByText(`Hunt ${HUNT_LABEL} enabled`)).toBeVisible(); + await expect(listRow(page, HUNT_LABEL).getByText('Disabled')).toHaveCount( + 0, + ); + expect((await huntRow(HUNT)).enabled).toBe(true); + }); + + test('An edit that leaves the switch alone keeps a disabled hunt disabled', async ({ + page, + }) => { + await engine('PUT', `/api/v1/hunts/${HUNT}`, { + display_name: HUNT_LABEL, + cron: '*/5 * * * *', + log_buffer: 60, + customers: [ORG], + rules: [RULE], + global_source_table_name: 'main', + enabled: false, + }); + await openHunt(page, HUNT, HUNT_LABEL); + await expect(listRow(page, HUNT_LABEL).getByText('Disabled')).toBeVisible(); + + await menuAction(page, 'Edit Hunt'); + const drawer = page.getByRole('dialog'); + const enabled = drawer.getByRole('switch', { name: 'Enabled' }); + await expect(enabled).not.toBeChecked(); + await page.screenshot({ path: `${SHOTS}/edit-switch-off.png` }); + // The drawer's submit carries the drawer's own title. + await drawer + .getByRole('button', { name: 'Edit Hunt', exact: true }) + .click(); + await expect(drawer).toBeHidden(); + + await expect(listRow(page, HUNT_LABEL).getByText('Disabled')).toBeVisible(); + expect((await huntRow(HUNT)).enabled).toBe(false); + }); +}); + +test.describe('A hunt the runner stopped', () => { + test.beforeEach(async ({ page }) => { + test.skip(!STOPPED, 'E2E_STOPPED_HUNT names no hunt a runner is stopping'); + forgetEngineToken(); + await loginAs(page, 'dfe_admin'); + }); + + test('shows why until Re-enable', async ({ page }) => { + const name = STOPPED as string; + await expect + .poll(async () => (await huntRow(name)).auto_disabled_at, { + timeout: 180_000, + message: `the runner has not stopped ${name}`, + }) + .not.toBeNull(); + const stopped = await huntRow(name); + expect(stopped.auto_disabled_reason).toMatch(/^resource_limit:/); + const label = stopped.display_name || name; + + await openHunt(page, name, label); + const tag = listRow(page, label).getByText('Auto-disabled'); + await expect(tag).toBeVisible(); + await tag.hover(); + await expect(page.getByRole('tooltip')).toContainText( + stopped.auto_disabled_reason, + ); + await page.screenshot({ path: `${SHOTS}/auto-disabled.png` }); + + await openMenu(page); + await expect( + page.getByRole('button', { name: 'Re-enable Hunt', exact: true }), + ).toBeVisible(); + await page.screenshot({ path: `${SHOTS}/auto-disabled-menu.png` }); + await page + .getByRole('button', { name: 'Re-enable Hunt', exact: true }) + .click(); + await expect(page.getByText(`Hunt ${label} enabled`)).toBeVisible(); + await expect(listRow(page, label).getByText('Auto-disabled')).toHaveCount( + 0, + ); + expect((await huntRow(name)).auto_disabled_at).toBeNull(); + }); +}); diff --git a/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/CloneHuntModal.test.tsx b/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/CloneHuntModal.test.tsx index caedd09ad..01de553c3 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/CloneHuntModal.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CloneHuntModal/CloneHuntModal.test.tsx @@ -29,6 +29,7 @@ const hunt: THuntDetailResponse = { customers: ['acme'], rules: [{ rule_name: 'brute_force' }], enabled: true, + auto_disabled_reason: '', }; const openClone = async (source: THuntDetailResponse) => { diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx index deb692f26..1426a2a72 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx @@ -245,3 +245,75 @@ describe('CreateUpdateHuntForm refusals', () => { ).not.toBeInTheDocument(); }); }); + +describe('CreateUpdateHuntForm runner stop', () => { + const stored = { + name: 'stopped', + customers: ['acme'], + rules: ['brute_force'], + cron: ['0 * * * *'], + log_buffer: 60, + global_source_table_name: 'windows_audit', + enabled: true, + }; + const renderForm = ({ + autoDisabled, + onFinish = vi.fn(), + }: { + autoDisabled?: { at: number; reason: string } | null; + onFinish?: () => void; + }) => + render( + , + { wrapper }, + ); + + test('says when and why the runner stopped the hunt', () => { + renderForm({ + autoDisabled: { at: 1_763_300_000, reason: 'resource_limit:241' }, + }); + + expect( + screen.getByText( + /The runner stopped this hunt on .+ \(resource_limit:241\)\./, + ), + ).toBeInTheDocument(); + expect( + screen.getByText( + 'Saving leaves it stopped. Use Re-enable Hunt in the actions menu to start it again.', + ), + ).toBeInTheDocument(); + }); + + test.each([ + { case: 'is not passed', autoDisabled: undefined }, + { case: 'is null', autoDisabled: null }, + ])('shows no stop notice when autoDisabled $case', ({ autoDisabled }) => { + renderForm({ autoDisabled }); + + expect(screen.queryByText(/The runner stopped this hunt/)).toBeNull(); + }); + + test('leaves the Enabled switch as the stored value and still toggles it', async () => { + const onFinish = vi.fn(); + renderForm({ + autoDisabled: { at: 1_763_300_000, reason: 'resource_limit:241' }, + onFinish, + }); + const toggle = screen.getByRole('switch', { name: 'Enabled' }); + + expect(toggle).toBeChecked(); + await userEvent.click(toggle); + await userEvent.click(screen.getByRole('button', { name: 'Save Hunt' })); + + await waitFor(() => expect(onFinish).toHaveBeenCalledTimes(1)); + expect(onFinish.mock.calls[0]?.[0].enabled).toBe(false); + }); +}); diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx index 9824f71f9..01dca1c0b 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx @@ -99,6 +99,7 @@ const hunt: THuntDetailResponse = { customers: ['acme'], rules: [{ rule_name: 'brute_force' }], enabled: true, + auto_disabled_reason: '', }; /** Records the body of the one write the form sends, and answers it. */ @@ -310,3 +311,34 @@ describe('Edit Hunt enabled', () => { }, ); }); + +describe('Edit Hunt runner stop', () => { + test( + 'shows the stop from the detail and saves without naming enabled', + { timeout: TEST_TIMEOUT_MS }, + async () => { + const sent = captureWrite('put', '/api/v1/hunts/windows_audit'); + render( + , + { wrapper }, + ); + const drawer = await openDrawer('Edit Hunt'); + + expect( + drawer.getByText( + /The runner stopped this hunt on .+ \(resource_limit:241\)\./, + ), + ).toBeInTheDocument(); + await userEvent.click(drawer.getByRole('button', { name: 'Edit Hunt' })); + + await waitFor(() => expect(sent.body).toBeDefined()); + expect(sent.body).not.toHaveProperty('enabled'); + }, + ); +}); diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx index dfbffa3fc..a64261151 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx @@ -3,11 +3,12 @@ import { Form } from '@/core/components/Form'; import { OrganisationSelect } from '@/core/components/OrganisationSelect'; import { SourceSelect } from '@/core/components/SourceSelect'; import { getApiErrorResponseBody } from '@/core/config/api/client'; +import { formatEpochSecondsLocal } from '@/core/helpers/date.helpers'; import { useAntdZodResolver } from '@/core/utils/zod/useAntdZodResolver'; import { RULE_HUNT_NAME_VALIDATOR } from '@/core/validationSchemas/utils'; import { CRONBuilderDrawer } from '@/Hunts/components/CRONBuilderDrawer'; import { IconDeviceFloppy, IconPlus, IconTrash } from '@repo/dfe-icons'; -import { Button, FormProps, Input, Switch } from 'antd'; +import { Alert, Button, FormProps, Input, Switch } from 'antd'; import { useEffect, useMemo } from 'react'; import z from 'zod'; import { RuleSelect } from './RuleSelectCreate'; @@ -70,6 +71,8 @@ type CreateUpdateHuntFormProps = FormProps & { error: Error | null; buttonLabel?: string; disabledFields?: DisabledFields; + /** Set when the runner stopped the hunt. A save leaves that stop in place. */ + autoDisabled?: { at: number; reason: string } | null; }; export const CreateUpdateHuntForm = ({ @@ -79,6 +82,7 @@ export const CreateUpdateHuntForm = ({ error, buttonLabel = 'Save Hunt', disabledFields, + autoDisabled, ...props }: CreateUpdateHuntFormProps) => { const [form] = Form.useForm(); @@ -197,6 +201,15 @@ export const CreateUpdateHuntForm = ({ )} + {autoDisabled && ( + + )} { setIsDrawerVisible(false); onClose?.(); @@ -119,6 +124,7 @@ export const UpdateHuntDrawer = ({ error={error} buttonLabel={title} initialValues={initialValues} + autoDisabled={autoDisabled} disabledFields={{ name: true, }} diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx index feff04454..a1dba7bdd 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx @@ -70,6 +70,7 @@ const hunt: THuntDetailResponse = { customers: ['acme'], rules: [{ rule_name: 'brute_force' }], enabled: true, + auto_disabled_reason: '', }; describe('HuntDetailActionMenu enable action', () => { @@ -104,6 +105,9 @@ describe('HuntDetailActionMenu enable action', () => { listed.autoDisabledAt = autoDisabledAt; let body: Record | undefined; server.use( + http.get('/api/v1/hunts/windows_audit', () => + HttpResponse.json({ ...hunt, enabled }), + ), http.put('/api/v1/hunts/windows_audit', async ({ request }) => { body = (await request.json()) as Record; return HttpResponse.json(hunt); @@ -122,4 +126,52 @@ describe('HuntDetailActionMenu enable action', () => { expect(await screen.findByText(notice)).toBeInTheDocument(); }, ); + + it('writes the config the server holds now, not the one the page loaded', async () => { + let body: Record | undefined; + server.use( + http.get('/api/v1/hunts/windows_audit', () => + HttpResponse.json({ ...hunt, cron: '0 3 * * *', log_buffer: 15 }), + ), + http.put('/api/v1/hunts/windows_audit', async ({ request }) => { + body = (await request.json()) as Record; + return HttpResponse.json(hunt); + }), + ); + render(, { wrapper }); + + await userEvent.click( + await screen.findByRole('button', { name: 'Disable Hunt' }), + ); + + await waitFor(() => expect(body).toBeDefined()); + expect(body).toMatchObject({ + enabled: false, + cron: '0 3 * * *', + log_buffer: 15, + }); + }); + + it('reports a failed fresh read and sends no update', async () => { + let putSent = false; + server.use( + http.get('/api/v1/hunts/windows_audit', () => + HttpResponse.json({ detail: 'gone' }, { status: 500 }), + ), + http.put('/api/v1/hunts/windows_audit', () => { + putSent = true; + return HttpResponse.json(hunt); + }), + ); + render(, { wrapper }); + + await userEvent.click( + await screen.findByRole('button', { name: 'Disable Hunt' }), + ); + + expect( + await screen.findByText('Hunt Windows audit was not disabled'), + ).toBeInTheDocument(); + expect(putSent).toBe(false); + }); }); diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx index a7f2c18de..45cf1bc40 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx @@ -7,6 +7,7 @@ import { DeleteHuntModal } from '@/Hunts/components/DeleteHuntModal'; import { UpdateHuntDrawer } from '@/Hunts/components/UpdateHuntDrawer'; import { useListHuntsContext } from '@/Hunts/contexts/ListHuntsContext'; import { THuntCreateResponse } from '@/Hunts/hooks/useCreateHunt/types'; +import { fetchHuntDetail } from '@/Hunts/hooks/useFetchHuntDetail/api'; import { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; import { useHuntRunState } from '@/Hunts/hooks/useHuntRunState'; import { useUpdateHunt } from '@/Hunts/hooks/useUpdateHunt'; @@ -24,6 +25,7 @@ import { } from '@repo/dfe-icons'; import { useQueryClient } from '@tanstack/react-query'; import { App, Button } from 'antd'; +import { useState } from 'react'; interface HuntDetailActionMenuProps { onEditSuccess?: (hunt: THuntUpdateResponse) => void; @@ -50,6 +52,15 @@ const ToggleHuntEnabled = ({ const Icon = turnOn ? IconPlayerPlay : IconPlayerPause; const huntLabel = hunt.display_name || hunt.name; + const [isReading, setIsReading] = useState(false); + + const onError = (error: Error) => + notification.error({ + title: `Hunt ${huntLabel} was not ${turnOn ? 'enabled' : 'disabled'}`, + description: , + placement: 'bottomLeft', + }); + const { mutate, isPending } = useUpdateHunt({ name: hunt.name, onSuccess: (response) => { @@ -59,23 +70,27 @@ const ToggleHuntEnabled = ({ placement: 'bottomLeft', }); }, - onError: (error) => { - notification.error({ - title: `Hunt ${huntLabel} was not ${turnOn ? 'enabled' : 'disabled'}`, - description: , - placement: 'bottomLeft', - }); - }, + onError, }); - const toggle = () => - mutate({ - ...transformHuntFormDataToUpdateRequest( - transformHuntDetailToFormData(hunt), - hunt, - ), - enabled: turnOn, - }); + // The engine has no per-field write, so a toggle sends the whole config, and a fresh read keeps it from undoing an edit landed since the page loaded. + const toggle = async () => { + setIsReading(true); + try { + const fresh = await fetchHuntDetail({ pathParams: { name: hunt.name } }); + mutate({ + ...transformHuntFormDataToUpdateRequest( + transformHuntDetailToFormData(fresh), + fresh, + ), + enabled: turnOn, + }); + } catch (error) { + onError(error instanceof Error ? error : new Error(String(error))); + } finally { + setIsReading(false); + } + }; return ( @@ -85,8 +100,8 @@ const ToggleHuntEnabled = ({ type="text" icon={} aria-label={label} - loading={isPending} - onClick={toggle} + loading={isReading || isPending} + onClick={() => void toggle()} > {label} diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntTabs/ConfigurationDetailsTabContent/ConfigurationDetailsTabContent.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntTabs/ConfigurationDetailsTabContent/ConfigurationDetailsTabContent.test.tsx index 3c43a6cc4..ea94c3024 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntTabs/ConfigurationDetailsTabContent/ConfigurationDetailsTabContent.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntTabs/ConfigurationDetailsTabContent/ConfigurationDetailsTabContent.test.tsx @@ -18,6 +18,7 @@ const hunt = (cron: THuntDetailResponse['cron']): THuntDetailResponse => ({ min_interval_seconds: null, explain_queries: null, enabled: true, + auto_disabled_reason: '', }); describe('ConfigurationDetailsTabContent cron', () => { diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useCreateHunt/useCreateHunt.test.tsx b/apps/dfe-core-ui/src/Hunts/hooks/useCreateHunt/useCreateHunt.test.tsx index 62e487ced..a0ed30c8b 100644 --- a/apps/dfe-core-ui/src/Hunts/hooks/useCreateHunt/useCreateHunt.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/hooks/useCreateHunt/useCreateHunt.test.tsx @@ -82,6 +82,7 @@ describe('.useCreateHunt', () => { scheduling_mode: 'string', min_interval_seconds: 0, enabled: true, + auto_disabled_reason: '', explain_queries: false, }; diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useFetchHuntDetail/useFetchHuntDetail.test.tsx b/apps/dfe-core-ui/src/Hunts/hooks/useFetchHuntDetail/useFetchHuntDetail.test.tsx index 9462fa6c6..aa6c59a9d 100644 --- a/apps/dfe-core-ui/src/Hunts/hooks/useFetchHuntDetail/useFetchHuntDetail.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/hooks/useFetchHuntDetail/useFetchHuntDetail.test.tsx @@ -49,6 +49,7 @@ describe('.useFetchHuntDetail', () => { scheduling_mode: 'string', min_interval_seconds: 0, enabled: true, + auto_disabled_reason: '', }; await waitFor(() => { diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/index.ts b/apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/index.ts index aa0a3e390..ba5ca36f1 100644 --- a/apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/index.ts +++ b/apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/index.ts @@ -1,16 +1,26 @@ import { useListHuntsContext } from '@/Hunts/contexts/ListHuntsContext'; import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; -/** The detail carries `enabled` only, so the runner's stop comes from the list row. */ +/** + * The runner's stop comes from the detail, and from the list row only for an + * engine whose detail omits it, so a hunt outside the loaded page still shows it. + */ export const useHuntRunState = (hunt: THuntDetailResponse) => { const { data: { items }, } = useListHuntsContext(); - const listed = items.find((item) => item.name === hunt.name); + const detailHasStop = hunt.auto_disabled_at !== undefined; + const listed = detailHasStop + ? undefined + : items.find((item) => item.name === hunt.name); return { enabled: hunt.enabled, - autoDisabledAt: listed?.auto_disabled_at, - autoDisabledReason: listed?.auto_disabled_reason, + autoDisabledAt: detailHasStop + ? hunt.auto_disabled_at + : listed?.auto_disabled_at, + autoDisabledReason: detailHasStop + ? hunt.auto_disabled_reason + : listed?.auto_disabled_reason, }; }; diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/useHuntRunState.test.tsx b/apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/useHuntRunState.test.tsx new file mode 100644 index 000000000..3991a6d87 --- /dev/null +++ b/apps/dfe-core-ui/src/Hunts/hooks/useHuntRunState/useHuntRunState.test.tsx @@ -0,0 +1,98 @@ +import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; +import { renderHook } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { useHuntRunState } from '.'; + +const list = vi.hoisted(() => ({ + items: [] as Array<{ + name: string; + auto_disabled_at?: number | null; + auto_disabled_reason?: string | null; + }>, +})); +vi.mock('@/Hunts/contexts/ListHuntsContext', () => ({ + useListHuntsContext: () => ({ data: { items: list.items } }), +})); + +afterEach(() => { + list.items = []; +}); + +const hunt: THuntDetailResponse = { + name: 'windows_audit', + display_name: 'Windows audit', + auto_disabled_reason: '', + cron: '*/5 * * * *', + log_buffer: 60, + global_source_table_name: 'windows_audit', + customers: ['acme'], + rules: [{ rule_name: 'brute_force' }], + enabled: true, +}; + +// An engine that predates the stop on the detail leaves the field out. +const olderEngine = { auto_disabled_at: undefined }; + +describe('useHuntRunState', () => { + it.each([ + { + case: 'the detail carries the stop and the list holds no matching item', + detail: { auto_disabled_at: 1_763_300_000, auto_disabled_reason: 'r:1' }, + items: [], + expected: { autoDisabledAt: 1_763_300_000, autoDisabledReason: 'r:1' }, + }, + { + case: 'the detail carries the stop and the list row disagrees', + detail: { auto_disabled_at: 1_763_300_000, auto_disabled_reason: 'r:1' }, + items: [ + { + name: 'windows_audit', + auto_disabled_at: 1_700_000_000, + auto_disabled_reason: 'old', + }, + ], + expected: { autoDisabledAt: 1_763_300_000, autoDisabledReason: 'r:1' }, + }, + { + case: 'the detail says no stop and the list row is stale', + detail: { auto_disabled_at: null, auto_disabled_reason: '' }, + items: [ + { + name: 'windows_audit', + auto_disabled_at: 1_700_000_000, + auto_disabled_reason: 'old', + }, + ], + expected: { autoDisabledAt: null, autoDisabledReason: '' }, + }, + { + case: 'the detail omits the fields and the list row has the stop', + detail: olderEngine, + items: [ + { + name: 'windows_audit', + auto_disabled_at: 1_763_300_000, + auto_disabled_reason: 'r:1', + }, + ], + expected: { autoDisabledAt: 1_763_300_000, autoDisabledReason: 'r:1' }, + }, + { + case: 'the detail omits the fields and only another hunt is listed', + detail: olderEngine, + items: [{ name: 'other', auto_disabled_at: 1_763_300_000 }], + expected: { + autoDisabledAt: undefined, + autoDisabledReason: undefined, + }, + }, + ])('with $case', ({ detail, items, expected }) => { + list.items = items; + + const { result } = renderHook(() => + useHuntRunState({ ...hunt, ...detail }), + ); + + expect(result.current).toEqual({ enabled: true, ...expected }); + }); +}); diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/useUpdateHunt.test.tsx b/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/useUpdateHunt.test.tsx index 927354d6d..43c63a13c 100644 --- a/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/useUpdateHunt.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/hooks/useUpdateHunt/useUpdateHunt.test.tsx @@ -86,6 +86,7 @@ describe('.useUpdateHunt', () => { scheduling_mode: 'string', min_interval_seconds: 0, enabled: true, + auto_disabled_reason: '', }; await waitFor(() => { diff --git a/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts b/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts index aad009d0c..655c36784 100644 --- a/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts +++ b/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts @@ -30,6 +30,7 @@ const huntDetail: THuntDetailResponse = { min_interval_seconds: null, explain_queries: null, enabled: true, + auto_disabled_reason: '', }; describe('transformHuntDetailToFormData', () => { diff --git a/apps/dfe-core-ui/src/core/config/api/endpoints/generator/mocks/hunts.ts b/apps/dfe-core-ui/src/core/config/api/endpoints/generator/mocks/hunts.ts index 72944ef0f..bb55d2df2 100644 --- a/apps/dfe-core-ui/src/core/config/api/endpoints/generator/mocks/hunts.ts +++ b/apps/dfe-core-ui/src/core/config/api/endpoints/generator/mocks/hunts.ts @@ -80,6 +80,7 @@ export const hunts = { min_interval_seconds: 0, explain_queries: false, enabled: true, + auto_disabled_reason: '', }, }: { mockedResponse?: THuntCreateResponse; @@ -147,6 +148,7 @@ export const hunts = { scheduling_mode: 'string', min_interval_seconds: 0, enabled: true, + auto_disabled_reason: '', }, name = 'name', }: { @@ -183,6 +185,7 @@ export const hunts = { scheduling_mode: 'string', min_interval_seconds: 0, enabled: true, + auto_disabled_reason: '', }, name = 'name', }: { diff --git a/packages/dfe-engine-types/specs/openapi.json b/packages/dfe-engine-types/specs/openapi.json index 3ecb41947..eb5f93bd3 100644 --- a/packages/dfe-engine-types/specs/openapi.json +++ b/packages/dfe-engine-types/specs/openapi.json @@ -15020,7 +15020,7 @@ "hunts" ], "summary": "Get Hunt", - "description": "Get full hunt configuration by file name.", + "description": "Get full hunt configuration by file name, with the runner's stop on it if any.", "operationId": "hunts.get", "parameters": [ { @@ -41370,10 +41370,16 @@ "title": "Explain Queries" }, "enabled": { - "type": "boolean", + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], "title": "Enabled", - "description": "Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing.", - "default": true + "description": "Whether the runner fires this hunt. Omitted on an update keeps the stored value. True also clears a stop the runner put on the hunt." }, "rules": { "items": { @@ -41505,17 +41511,17 @@ ], "title": "Explain Queries" }, + "name": { + "type": "string", + "title": "Name", + "description": "Hunt file name (YAML stem)" + }, "enabled": { "type": "boolean", "title": "Enabled", "description": "Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing.", "default": true }, - "name": { - "type": "string", - "title": "Name", - "description": "Hunt file name (YAML stem)" - }, "rules": { "items": { "$ref": "#/components/schemas/HuntRuleEntry" @@ -41534,6 +41540,24 @@ "type": "object", "title": "Customer Tenant Ids", "description": "Each customer's tenant ids, resolved when the hunt was saved: the _org_id values the runner reads. A customer missing here stops every run." + }, + "auto_disabled_at": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Auto Disabled At", + "description": "When the runner stopped the hunt after repeated resource-limit failures, epoch seconds" + }, + "auto_disabled_reason": { + "type": "string", + "title": "Auto Disabled Reason", + "description": "The ClickHouse error category and code that tripped the stop", + "default": "" } }, "type": "object", @@ -41916,10 +41940,16 @@ "title": "Explain Queries" }, "enabled": { - "type": "boolean", + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], "title": "Enabled", - "description": "Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing.", - "default": true + "description": "Whether the runner fires this hunt. Omitted on an update keeps the stored value. True also clears a stop the runner put on the hunt." }, "rules": { "items": { diff --git a/packages/dfe-engine-types/types/index.d.ts b/packages/dfe-engine-types/types/index.d.ts index a08fbdf8e..b94203f49 100644 --- a/packages/dfe-engine-types/types/index.d.ts +++ b/packages/dfe-engine-types/types/index.d.ts @@ -2644,7 +2644,7 @@ export interface paths { }; /** * Get Hunt - * @description Get full hunt configuration by file name. + * @description Get full hunt configuration by file name, with the runner's stop on it if any. */ get: operations["hunts.get"]; /** @@ -9659,10 +9659,9 @@ export interface components { explain_queries?: boolean | null; /** * Enabled - * @description Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing. - * @default true + * @description Whether the runner fires this hunt. Omitted on an update keeps the stored value. True also clears a stop the runner put on the hunt. */ - enabled: boolean; + enabled?: boolean | null; /** * Rules * @description Rule names, each the ``{name}.yaml`` rule file the hunt runner reads @@ -9714,17 +9713,17 @@ export interface components { min_interval_seconds?: number | null; /** Explain Queries */ explain_queries?: boolean | null; + /** + * Name + * @description Hunt file name (YAML stem) + */ + name: string; /** * Enabled * @description Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing. * @default true */ enabled: boolean; - /** - * Name - * @description Hunt file name (YAML stem) - */ - name: string; /** Rules */ rules: components["schemas"]["HuntRuleEntry"][]; /** @@ -9734,6 +9733,17 @@ export interface components { customer_tenant_ids?: { [key: string]: string[]; }; + /** + * Auto Disabled At + * @description When the runner stopped the hunt after repeated resource-limit failures, epoch seconds + */ + auto_disabled_at?: number | null; + /** + * Auto Disabled Reason + * @description The ClickHouse error category and code that tripped the stop + * @default + */ + auto_disabled_reason: string; }; /** * HuntEngineStatus @@ -9939,10 +9949,9 @@ export interface components { explain_queries?: boolean | null; /** * Enabled - * @description Whether the runner fires this hunt. False keeps its YAML, state and watermark and fires nothing. - * @default true + * @description Whether the runner fires this hunt. Omitted on an update keeps the stored value. True also clears a stop the runner put on the hunt. */ - enabled: boolean; + enabled?: boolean | null; /** * Rules * @description Rule names, each the ``{name}.yaml`` rule file the hunt runner reads From e97c76c97fd5e665a5805b371e346b5b2d86b86b Mon Sep 17 00:00:00 2001 From: Derek Date: Mon, 16 Nov 2026 17:41:17 +1100 Subject: [PATCH 03/10] fix(hunts): decide the toggle's direction from the fresh read The actions menu fetched the hunt afresh for the PUT body but took the toggle direction from page state. If another session changed enabled after page load, the button wrote the opposite enabled value. - After the read, a hunt with auto_disabled_at set gets enabled true, and any other hunt gets the opposite of its enabled value. - The success and failure notices name the direction that was sent. - The menu label still comes from the page state, because it only guides the click. --- .../HuntDetailActionMenu.test.tsx | 24 +++++++++++++++++++ .../HuntDetailActionMenu/index.tsx | 12 ++++++---- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx index a1dba7bdd..f6b4dba14 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx @@ -152,6 +152,30 @@ describe('HuntDetailActionMenu enable action', () => { }); }); + it('sends the direction the server state calls for, not the one on the page', async () => { + let body: Record | undefined; + server.use( + http.get('/api/v1/hunts/windows_audit', () => + HttpResponse.json({ ...hunt, enabled: false }), + ), + http.put('/api/v1/hunts/windows_audit', async ({ request }) => { + body = (await request.json()) as Record; + return HttpResponse.json(hunt); + }), + ); + render(, { wrapper }); + + await userEvent.click( + await screen.findByRole('button', { name: 'Disable Hunt' }), + ); + + await waitFor(() => expect(body).toBeDefined()); + expect(body).toMatchObject({ enabled: true }); + expect( + await screen.findByText('Hunt Windows audit enabled'), + ).toBeInTheDocument(); + }); + it('reports a failed fresh read and sends no update', async () => { let putSent = false; server.use( diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx index 45cf1bc40..db7585453 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx @@ -25,7 +25,7 @@ import { } from '@repo/dfe-icons'; import { useQueryClient } from '@tanstack/react-query'; import { App, Button } from 'antd'; -import { useState } from 'react'; +import { useRef, useState } from 'react'; interface HuntDetailActionMenuProps { onEditSuccess?: (hunt: THuntUpdateResponse) => void; @@ -53,10 +53,12 @@ const ToggleHuntEnabled = ({ const huntLabel = hunt.display_name || hunt.name; const [isReading, setIsReading] = useState(false); + // The direction the PUT carries, which the fresh read can change from the label's. + const sent = useRef(turnOn); const onError = (error: Error) => notification.error({ - title: `Hunt ${huntLabel} was not ${turnOn ? 'enabled' : 'disabled'}`, + title: `Hunt ${huntLabel} was not ${sent.current ? 'enabled' : 'disabled'}`, description: , placement: 'bottomLeft', }); @@ -66,7 +68,7 @@ const ToggleHuntEnabled = ({ onSuccess: (response) => { onSuccess(response); notification.success({ - title: `Hunt ${huntLabel} ${turnOn ? 'enabled' : 'disabled'}`, + title: `Hunt ${huntLabel} ${sent.current ? 'enabled' : 'disabled'}`, placement: 'bottomLeft', }); }, @@ -75,15 +77,17 @@ const ToggleHuntEnabled = ({ // The engine has no per-field write, so a toggle sends the whole config, and a fresh read keeps it from undoing an edit landed since the page loaded. const toggle = async () => { + sent.current = turnOn; setIsReading(true); try { const fresh = await fetchHuntDetail({ pathParams: { name: hunt.name } }); + sent.current = fresh.auto_disabled_at != null || fresh.enabled === false; mutate({ ...transformHuntFormDataToUpdateRequest( transformHuntDetailToFormData(fresh), fresh, ), - enabled: turnOn, + enabled: sent.current, }); } catch (error) { onError(error instanceof Error ? error : new Error(String(error))); From 8c8f4752d7b3cc413751ef65061eb63fb5cfddb3 Mon Sep 17 00:00:00 2001 From: Derek Date: Mon, 16 Nov 2026 18:28:40 +1100 Subject: [PATCH 04/10] fix(hunts): announce the runner's stop in the hunt detail The stop reason and Re-enable Hunt route were available only in the header tag's hover tooltip and the edit form. A screen-reader user on the detail view never heard them. - ViewHuntDetail renders a warning Alert under the header row and above the tabs when the run state has a stop. It gives the stop time, the reason and the Re-enable Hunt route. - The header tag and its tooltip stay as they were. --- .../ViewHuntDetail/ViewHuntDetail.test.tsx | 98 +++++++++++++++++++ .../Hunts/components/ViewHuntDetail/index.tsx | 22 ++++- 2 files changed, 119 insertions(+), 1 deletion(-) create mode 100644 apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx new file mode 100644 index 000000000..6663acba5 --- /dev/null +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx @@ -0,0 +1,98 @@ +import { buildTestWrapper } from '@/core/utils/test-utils/buildTestWrapper'; +import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; +import { render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { ViewHuntDetail } from '.'; + +// The tabs, the action menu and the trigger reach their own APIs. What is under test is the stop notice. +vi.mock('@/Hunts/components/ViewHuntTabs', () => ({ + ViewHuntDetailTabs: () => null, +})); +vi.mock('./HuntDetailActionMenu', () => ({ HuntDetailActionMenu: () => null })); +vi.mock('./TriggerHunt', () => ({ TriggerHunt: () => null })); +vi.mock('@/core/hooks/useSetComponentHeight', () => ({ + useSetComponentHeight: () => ({ componentHeight: 600 }), +})); + +const state = vi.hoisted(() => ({ + detail: undefined as unknown, + listed: [] as Array<{ name: string; auto_disabled_at?: number | null }>, +})); +vi.mock('@/Hunts/contexts/ListHuntsContext', () => ({ + useListHuntsContext: () => ({ + selectedHuntName: 'windows_audit', + data: { items: state.listed }, + }), +})); +vi.mock('@/Hunts/hooks/useFetchHuntDetail', () => ({ + useFetchHuntDetail: () => ({ + data: state.detail, + isLoading: false, + error: null, + }), +})); + +afterEach(() => { + state.listed = []; +}); + +const { wrapper } = buildTestWrapper().withTheme(); + +const hunt: THuntDetailResponse = { + name: 'windows_audit', + display_name: 'Windows audit', + cron: '*/5 * * * *', + log_buffer: 60, + global_source_table_name: 'windows_audit', + customers: ['acme'], + rules: [{ rule_name: 'brute_force' }], + enabled: true, + auto_disabled_reason: '', +}; + +const NOTICE = /^The runner stopped this hunt on /; +const WAY_BACK = + 'It fires nothing until you choose Re-enable Hunt from the actions menu.'; + +describe('ViewHuntDetail runner stop', () => { + it.each([ + { + case: 'the detail carries the stop', + detail: { + ...hunt, + auto_disabled_at: 1_763_300_000, + auto_disabled_reason: 'resource_limit:241', + }, + shown: /\(resource_limit:241\)\.$/, + }, + { + case: 'the detail carries the stop with no reason', + detail: { ...hunt, auto_disabled_at: 1_763_300_000 }, + shown: /\d\.$/, + }, + ])('announces the stop when $case', ({ detail, shown }) => { + state.detail = detail; + + render(, { wrapper }); + + expect(screen.getByRole('alert')).toBeInTheDocument(); + expect(screen.getByText(NOTICE)).toHaveTextContent(shown); + expect(screen.getByText(WAY_BACK)).toBeInTheDocument(); + expect(screen.getByText('Auto-disabled')).toBeInTheDocument(); + }); + + it.each([ + { case: 'an enabled hunt', detail: hunt }, + { + case: 'a hunt switched off by config', + detail: { ...hunt, enabled: false }, + }, + ])('shows no stop notice for $case', ({ detail }) => { + state.detail = { ...detail, auto_disabled_at: null }; + + render(, { wrapper }); + + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + expect(screen.queryByText(NOTICE)).not.toBeInTheDocument(); + }); +}); diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx index c87812b09..4a24080ee 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx @@ -1,6 +1,7 @@ import { CustomScrollbar } from '@/core/components/CustomScrollbar'; import { EmptyDetail } from '@/core/components/EmptyDetail'; import { GenericErrorCard } from '@/core/components/GenericError'; +import { formatEpochSecondsLocal } from '@/core/helpers/date.helpers'; import { useSetComponentHeight } from '@/core/hooks/useSetComponentHeight'; import { HuntStateTag } from '@/Hunts/components/HuntStateTag'; import { ViewHuntDetailTabs } from '@/Hunts/components/ViewHuntTabs'; @@ -8,7 +9,7 @@ import { useListHuntsContext } from '@/Hunts/contexts/ListHuntsContext'; import { useFetchHuntDetail } from '@/Hunts/hooks/useFetchHuntDetail'; import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; import { useHuntRunState } from '@/Hunts/hooks/useHuntRunState'; -import { Spin } from 'antd'; +import { Alert, Spin } from 'antd'; import { HuntDetailActionMenu } from './HuntDetailActionMenu'; import { TriggerHunt } from './TriggerHunt'; @@ -17,6 +18,23 @@ const HuntDetailStateTag = ({ hunt }: { hunt: THuntDetailResponse }) => { return ; }; +/** The stop and the way back as text, because the tag's tooltip is hover only. */ +const HuntStopAlert = ({ hunt }: { hunt: THuntDetailResponse }) => { + const { autoDisabledAt, autoDisabledReason } = useHuntRunState(hunt); + if (autoDisabledAt == null) { + return null; + } + const reason = autoDisabledReason ? ` (${autoDisabledReason})` : ''; + return ( + + ); +}; + export const ViewHuntDetail = () => { const { selectedHuntName } = useListHuntsContext(); const { @@ -73,6 +91,8 @@ export const ViewHuntDetail = () => { + + ); From 00d337353462deff533a6493b4289815200965ea Mon Sep 17 00:00:00 2001 From: Derek Date: Mon, 16 Nov 2026 18:58:14 +1100 Subject: [PATCH 05/10] fix(hunts): clarify stop alerts and block triggers when stopped - Both stop alerts say the hunt stopped after repeated ClickHouse resource-limit failures, with the reason code in brackets when there is one. - The edit form's Enabled switch distinguishes saved configuration (on) from runner status (stopped) for screen readers. - The toggle waits for the query refetch before showing its success notice, so it never appears beside a stale Auto-disabled tag. - Trigger On-Demand is disabled with a tooltip when the hunt is stopped. Its modal cannot send a run when stopped. --- .../CreateUpdateHuntForm.test.tsx | 61 +++++++++--- .../components/CreateUpdateHuntForm/index.tsx | 8 +- .../HuntDetailActionMenu.test.tsx | 52 +++++++++- .../HuntDetailActionMenu/index.tsx | 7 +- .../TriggerHunt/TriggerHunt.test.tsx | 99 +++++++++++++++++++ .../ViewHuntDetail/TriggerHunt/index.tsx | 26 +++-- .../ViewHuntDetail/ViewHuntDetail.test.tsx | 7 +- .../Hunts/components/ViewHuntDetail/index.tsx | 4 +- 8 files changed, 234 insertions(+), 30 deletions(-) create mode 100644 apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/TriggerHunt.test.tsx diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx index 1426a2a72..93a52df19 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx @@ -275,22 +275,55 @@ describe('CreateUpdateHuntForm runner stop', () => { { wrapper }, ); - test('says when and why the runner stopped the hunt', () => { - renderForm({ + test.each([ + { + case: 'with a reason', + reason: 'resource_limit:241', + copy: /^The runner stopped this hunt on .+ after repeated ClickHouse resource-limit failures \(resource_limit:241\)\.$/, + }, + { + case: 'without a reason', + reason: '', + copy: /^The runner stopped this hunt on .+ after repeated ClickHouse resource-limit failures\.$/, + }, + ])( + 'says when and why the runner stopped the hunt $case', + ({ reason, copy }) => { + renderForm({ autoDisabled: { at: 1_763_300_000, reason } }); + + expect(screen.getByText(copy)).toBeInTheDocument(); + expect( + screen.getByText( + 'Saving leaves it stopped. Use Re-enable Hunt in the actions menu to start it again.', + ), + ).toBeInTheDocument(); + }, + ); + + test.each([ + { + case: 'stopped by the runner', autoDisabled: { at: 1_763_300_000, reason: 'resource_limit:241' }, - }); + shown: + 'On in the saved configuration, but the runner has stopped it. Re-enable Hunt in the actions menu starts it again.', + hidden: 'A disabled hunt keeps its configuration and fires nothing.', + }, + { + case: 'not stopped', + autoDisabled: null, + shown: 'A disabled hunt keeps its configuration and fires nothing.', + hidden: + 'On in the saved configuration, but the runner has stopped it. Re-enable Hunt in the actions menu starts it again.', + }, + ])( + 'describes the Enabled switch for a hunt $case', + ({ autoDisabled, shown, hidden }) => { + renderForm({ autoDisabled }); - expect( - screen.getByText( - /The runner stopped this hunt on .+ \(resource_limit:241\)\./, - ), - ).toBeInTheDocument(); - expect( - screen.getByText( - 'Saving leaves it stopped. Use Re-enable Hunt in the actions menu to start it again.', - ), - ).toBeInTheDocument(); - }); + expect(screen.getByText(shown)).toBeInTheDocument(); + expect(screen.queryByText(hidden)).toBeNull(); + }, + ); test.each([ { case: 'is not passed', autoDisabled: undefined }, diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx index a64261151..38e3a9dde 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx @@ -206,7 +206,7 @@ export const CreateUpdateHuntForm = ({ type="warning" showIcon className="mb-4" - title={`The runner stopped this hunt on ${formatEpochSecondsLocal(autoDisabled.at)}${autoDisabled.reason ? ` (${autoDisabled.reason})` : ''}.`} + title={`The runner stopped this hunt on ${formatEpochSecondsLocal(autoDisabled.at)} after repeated ClickHouse resource-limit failures${autoDisabled.reason ? ` (${autoDisabled.reason})` : ''}.`} description="Saving leaves it stopped. Use Re-enable Hunt in the actions menu to start it again." /> )} @@ -214,7 +214,11 @@ export const CreateUpdateHuntForm = ({ name="enabled" label="Enabled" valuePropName="checked" - extra="A disabled hunt keeps its configuration and fires nothing." + extra={ + autoDisabled + ? 'On in the saved configuration, but the runner has stopped it. Re-enable Hunt in the actions menu starts it again.' + : 'A disabled hunt keeps its configuration and fires nothing.' + } > diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx index f6b4dba14..d17a307bc 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/HuntDetailActionMenu.test.tsx @@ -1,10 +1,13 @@ import { server } from '@/core/components/RbacProtected/hooks/hooks.mocks'; import { buildTestWrapper } from '@/core/utils/test-utils/buildTestWrapper'; +import { HuntStateTag } from '@/Hunts/components/HuntStateTag'; +import { useFetchHuntDetail } from '@/Hunts/hooks/useFetchHuntDetail'; import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; +import { useHuntRunState } from '@/Hunts/hooks/useHuntRunState'; import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { App } from 'antd'; -import { http, HttpResponse } from 'msw'; +import { delay, http, HttpResponse } from 'msw'; import type { ReactElement, ReactNode } from 'react'; import { afterAll, @@ -73,6 +76,10 @@ const hunt: THuntDetailResponse = { auto_disabled_reason: '', }; +const RunStateTag = ({ hunt: detail }: { hunt: THuntDetailResponse }) => ( + +); + describe('HuntDetailActionMenu enable action', () => { it.each([ { @@ -176,6 +183,49 @@ describe('HuntDetailActionMenu enable action', () => { ).toBeInTheDocument(); }); + it('raises the notice only after the refetch has cleared the stop', async () => { + let stopped = true; + server.use( + http.get('/api/v1/hunts/windows_audit', async () => { + if (!stopped) { + await delay(150); + } + return HttpResponse.json({ + ...hunt, + auto_disabled_at: stopped ? 1_763_300_000 : null, + auto_disabled_reason: stopped ? 'resource_limit:241' : '', + }); + }), + http.put('/api/v1/hunts/windows_audit', () => { + stopped = false; + return HttpResponse.json(hunt); + }), + ); + const StoppedHunt = () => { + const { data } = useFetchHuntDetail({ name: 'windows_audit' }); + if (!data) { + return null; + } + return ( + <> + + + + ); + }; + render(, { wrapper }); + expect(await screen.findByText('Auto-disabled')).toBeInTheDocument(); + + await userEvent.click( + await screen.findByRole('button', { name: 'Re-enable Hunt' }), + ); + + expect( + await screen.findByText('Hunt Windows audit enabled'), + ).toBeInTheDocument(); + expect(screen.queryByText('Auto-disabled')).toBeNull(); + }); + it('reports a failed fresh read and sends no update', async () => { let putSent = false; server.use( diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx index db7585453..b003afd54 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx @@ -41,6 +41,7 @@ const ToggleHuntEnabled = ({ onSuccess: (hunt: THuntUpdateResponse) => void; }) => { const { notification } = App.useApp(); + const queryClient = useQueryClient(); const { enabled, autoDisabledAt } = useHuntRunState(hunt); const autoDisabled = autoDisabledAt != null; const turnOn = autoDisabled || enabled === false; @@ -65,8 +66,12 @@ const ToggleHuntEnabled = ({ const { mutate, isPending } = useUpdateHunt({ name: hunt.name, - onSuccess: (response) => { + onSuccess: async (response) => { onSuccess(response); + // The notice waits for the refetch, so the row, header and menu no longer say Auto-disabled when it shows. + await queryClient.invalidateQueries({ + queryKey: QUERY_KEYS.hunts.default(), + }); notification.success({ title: `Hunt ${huntLabel} ${sent.current ? 'enabled' : 'disabled'}`, placement: 'bottomLeft', diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/TriggerHunt.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/TriggerHunt.test.tsx new file mode 100644 index 000000000..993bede0c --- /dev/null +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/TriggerHunt.test.tsx @@ -0,0 +1,99 @@ +import { server } from '@/core/components/RbacProtected/hooks/hooks.mocks'; +import { buildTestWrapper } from '@/core/utils/test-utils/buildTestWrapper'; +import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { App } from 'antd'; +import { http, HttpResponse } from 'msw'; +import type { ReactNode } from 'react'; +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from 'vitest'; +import { TriggerHunt } from '.'; + +vi.mock('@/Hunts/contexts/ListHuntsContext', () => ({ + useListHuntsContext: () => ({ data: { items: [] } }), +})); + +beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +const { wrapper: Providers } = buildTestWrapper().withTheme().withReactQuery(); +const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + +); + +const hunt: THuntDetailResponse = { + name: 'windows_audit', + display_name: 'Windows audit', + cron: '*/5 * * * *', + log_buffer: 60, + global_source_table_name: 'windows_audit', + customers: ['acme'], + rules: [{ rule_name: 'brute_force' }], + enabled: true, + auto_disabled_reason: '', +}; + +const captureRuns = () => { + const runs: string[] = []; + server.use( + http.post('/api/v1/hunts/windows_audit/run', () => { + runs.push('run'); + return HttpResponse.json({ poll_seconds: 30 }); + }), + ); + return runs; +}; + +describe('TriggerHunt', () => { + it('is disabled with the reason for a hunt the runner stopped, and sends nothing', async () => { + const runs = captureRuns(); + render( + , + { wrapper }, + ); + const button = await screen.findByRole('button', { + name: /Trigger On-Demand/, + }); + + expect(button).toBeDisabled(); + await userEvent.click(button); + await userEvent.hover(button.parentElement ?? button); + + expect( + await screen.findByText( + 'The runner stopped this hunt. Re-enable it first.', + ), + ).toBeInTheDocument(); + expect(screen.queryByText('Trigger On-Demand Hunt')).toBeNull(); + expect(runs).toEqual([]); + }); + + it('queues a run for a hunt the runner is firing', async () => { + const runs = captureRuns(); + render(, { + wrapper, + }); + const button = await screen.findByRole('button', { + name: /Trigger On-Demand/, + }); + + expect(button).toBeEnabled(); + await userEvent.click(button); + await userEvent.click( + await screen.findByRole('button', { name: 'Trigger Hunt' }), + ); + + await waitFor(() => expect(runs).toEqual(['run'])); + }); +}); diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/index.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/index.tsx index 56b60a23c..bce08be18 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/index.tsx @@ -1,17 +1,18 @@ import { FormNotification } from '@/core/components/FormNotification'; import { Modal } from '@/core/components/Modal'; import { RbacProtected } from '@/core/components/RbacProtected'; +import { Tooltip } from '@/core/components/Tooltip'; +import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; +import { useHuntRunState } from '@/Hunts/hooks/useHuntRunState'; import { useTriggerHunt } from '@/Hunts/hooks/useTriggerHunt'; import { IconPlayerPlay } from '@repo/dfe-icons'; import { App, Button } from 'antd'; import { useState } from 'react'; -export const TriggerHunt = ({ - selectedHuntName, -}: { - selectedHuntName: string; -}) => { +export const TriggerHunt = ({ hunt }: { hunt: THuntDetailResponse }) => { + const selectedHuntName = hunt.name; const [isOpen, setIsOpen] = useState(false); + const stopped = useHuntRunState(hunt).autoDisabledAt != null; const { notification } = App.useApp(); @@ -41,9 +42,17 @@ export const TriggerHunt = ({ <> - + + + diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx index 6663acba5..62a3e4d37 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx @@ -63,12 +63,12 @@ describe('ViewHuntDetail runner stop', () => { auto_disabled_at: 1_763_300_000, auto_disabled_reason: 'resource_limit:241', }, - shown: /\(resource_limit:241\)\.$/, + shown: /failures \(resource_limit:241\)\.$/, }, { case: 'the detail carries the stop with no reason', detail: { ...hunt, auto_disabled_at: 1_763_300_000 }, - shown: /\d\.$/, + shown: /failures\.$/, }, ])('announces the stop when $case', ({ detail, shown }) => { state.detail = detail; @@ -76,6 +76,9 @@ describe('ViewHuntDetail runner stop', () => { render(, { wrapper }); expect(screen.getByRole('alert')).toBeInTheDocument(); + expect(screen.getByText(NOTICE)).toHaveTextContent( + /after repeated ClickHouse resource-limit failures/, + ); expect(screen.getByText(NOTICE)).toHaveTextContent(shown); expect(screen.getByText(WAY_BACK)).toBeInTheDocument(); expect(screen.getByText('Auto-disabled')).toBeInTheDocument(); diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx index 4a24080ee..286644ee5 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx @@ -29,7 +29,7 @@ const HuntStopAlert = ({ hunt }: { hunt: THuntDetailResponse }) => { ); @@ -86,7 +86,7 @@ export const ViewHuntDetail = () => {
- +
From be1155ed6b01808d7da4e3eae494f7168c0ebea1 Mon Sep 17 00:00:00 2001 From: Derek Date: Mon, 16 Nov 2026 19:21:00 +1100 Subject: [PATCH 06/10] fix(hunts): test the enabled state in the console Two Playwright specs against a running engine. huntEnabled.spec.ts tests Disable and Enable from the actions menu. It tests an edit that leaves the switch alone. With E2E_STOPPED_HUNT set, it tests a runner-stopped hunt until Re-enable. huntEnabledShots.spec.ts captures every state in light and dark at 1920 and 1280. Its whole-page aria snapshots are evidence for a usability review. --- .../e2e/specs/huntEnabledShots.spec.ts | 185 ++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 apps/dfe-core-ui/e2e/specs/huntEnabledShots.spec.ts diff --git a/apps/dfe-core-ui/e2e/specs/huntEnabledShots.spec.ts b/apps/dfe-core-ui/e2e/specs/huntEnabledShots.spec.ts new file mode 100644 index 000000000..57a78de2b --- /dev/null +++ b/apps/dfe-core-ui/e2e/specs/huntEnabledShots.spec.ts @@ -0,0 +1,185 @@ +import { mkdirSync, writeFileSync } from 'node:fs'; + +import { expect, Page, test } from '@playwright/test'; + +import { BASE_URL, e2eClient } from '@e2e/config/e2e.client'; +import { engine, forgetEngineToken } from '@e2e/config/engineApi.helpers'; +import { loginAs } from '@e2e/config/login.helpers'; + +/** + * Usability evidence for the hunt enabled state: screenshots and aria + * snapshots of the list row tag, the header, the Enabled switch, the stop alert + * and the Re-enable flow, in light and dark at 1920 and 1280. + * + * E2E_STOPPED_HUNT names a hunt the runner (or its coordinator) stopped before + * the run. Without it the stop states are skipped. The last pass re-enables it. + */ + +const ORG = 'shotco'; +const DISABLED = 'shot_disabled'; +const DISABLED_LABEL = 'Shot Disabled'; +const RULE = 'shot_rule'; +const STOPPED = process.env.E2E_STOPPED_HUNT; +const OUT = 'test-results/hunt-shots'; + +const THEMES = ['light', 'dark'] as const; +const WIDTHS = [1920, 1280] as const; + +const deleteIfPresent = async (path: string) => { + try { + await engine('DELETE', path); + } catch (error) { + if (!String(error).includes('-> 404')) throw error; + } +}; + +const huntBody = (label: string) => ({ + display_name: label, + cron: '*/5 * * * *', + log_buffer: 60, + customers: [ORG], + rules: [RULE], + global_source_table_name: 'main', +}); + +// The whole body, so a drawer or a tooltip rendered in a portal is in the tree. +const capture = async (page: Page, name: string) => { + await page.screenshot({ path: `${OUT}/${name}.png` }); + const aria = await page.locator('body').ariaSnapshot(); + writeFileSync(`${OUT}/${name}.aria.yaml`, aria); +}; + +const openHunt = async (page: Page, name: string, label: string) => { + await page.goto(`${BASE_URL}/hunts?name=${name}`); + await expect( + page.getByRole('heading', { name: new RegExp(label) }), + ).toBeVisible(); +}; + +const openMenu = async (page: Page) => { + const open = page.getByRole('button', { name: 'Close actions', exact: true }); + if ((await open.count()) === 0) { + await page.getByRole('button', { name: 'Actions', exact: true }).click(); + } +}; + +// The toggle adds or removes the `dark` class on the root once it has taken. +const setTheme = async (page: Page, theme: (typeof THEMES)[number]) => { + const toggle = page.getByRole('button', { name: `Switch to ${theme} mode` }); + if ((await toggle.count()) > 0) { + await toggle.click(); + } + const root = page.locator('html'); + if (theme === 'dark') { + await expect(root).toHaveClass(/dark/); + } else { + await expect(root).not.toHaveClass(/dark/); + } +}; + +test.beforeEach(async ({ playwright, page }) => { + mkdirSync(OUT, { recursive: true }); + await e2eClient({ playwright, seedScript: 'reset_all' }); + await e2eClient({ playwright, seedScript: 'seed_setup_complete' }); + await e2eClient({ playwright, seedScript: 'seed_dfe_admin_user' }); + forgetEngineToken(); + await deleteIfPresent(`/api/v1/hunts/${DISABLED}`); + await deleteIfPresent(`/api/v1/rules/${RULE}`); + await engine('POST', '/api/v1/orgs', { + name: ORG, + display_name: 'Shot Co', + org_ids: [`${ORG}-1`], + }); + await engine('POST', '/api/v1/rules', { + name: RULE, + severity: 'medium', + user_sql: "SELECT * FROM dfe.main WHERE _source = 'shot'", + estimate_cost: false, + }); + await engine('POST', '/api/v1/hunts', { + name: DISABLED, + ...huntBody(DISABLED_LABEL), + }); + await engine('PUT', `/api/v1/hunts/${DISABLED}`, { + ...huntBody(DISABLED_LABEL), + enabled: false, + }); + if (STOPPED) { + await deleteIfPresent(`/api/v1/hunts/${STOPPED}`); + await engine('POST', '/api/v1/hunts', { + name: STOPPED, + ...huntBody('Shot Stopped'), + }); + } + await loginAs(page, 'dfe_admin'); +}); + +test('the enabled state in every theme and width', async ({ page }) => { + test.setTimeout(600_000); + for (const theme of THEMES) { + for (const width of WIDTHS) { + await page.setViewportSize({ + width, + height: width === 1920 ? 1080 : 800, + }); + const tag = `${theme}-${width}`; + + await openHunt(page, DISABLED, DISABLED_LABEL); + await setTheme(page, theme); + await capture(page, `${tag}-disabled`); + await openMenu(page); + await capture(page, `${tag}-disabled-menu`); + await page + .getByRole('button', { name: 'Edit Hunt', exact: true }) + .click(); + const drawer = page.getByRole('dialog'); + await expect( + drawer.getByRole('switch', { name: 'Enabled' }), + ).not.toBeChecked(); + await capture(page, `${tag}-disabled-edit`); + await page + .getByRole('dialog') + .getByRole('button', { name: 'Close' }) + .click(); + await expect(drawer).toBeHidden(); + + if (!STOPPED) continue; + await openHunt(page, STOPPED, 'Shot Stopped'); + const stopTag = page + .getByRole('listitem') + .filter({ hasText: 'Shot Stopped' }) + .getByText('Auto-disabled'); + await expect(stopTag).toBeVisible(); + await stopTag.hover(); + await expect(page.getByRole('tooltip')).toBeVisible(); + await capture(page, `${tag}-stopped-tooltip`); + await openMenu(page); + await expect( + page.getByRole('button', { name: 'Re-enable Hunt', exact: true }), + ).toBeVisible(); + await capture(page, `${tag}-stopped-menu`); + await page + .getByRole('button', { name: 'Edit Hunt', exact: true }) + .click(); + const stopDrawer = page.getByRole('dialog'); + await expect(stopDrawer.getByRole('alert')).toBeVisible(); + await capture(page, `${tag}-stopped-edit`); + await page + .getByRole('dialog') + .getByRole('button', { name: 'Close' }) + .click(); + await expect(stopDrawer).toBeHidden(); + } + } + if (STOPPED) { + await openHunt(page, STOPPED, 'Shot Stopped'); + await openMenu(page); + await page + .getByRole('button', { name: 'Re-enable Hunt', exact: true }) + .click(); + await expect(page.getByText('Hunt Shot Stopped enabled')).toBeVisible(); + // The settled state: the tag has gone from the row and the header. + await expect(page.getByText('Auto-disabled')).toHaveCount(0); + await capture(page, 'dark-1280-reenabled'); + } +}); From 7dfd2f1e7729c19291bbfab41438830847a2a99a Mon Sep 17 00:00:00 2001 From: Derek Date: Mon, 16 Nov 2026 19:32:32 +1100 Subject: [PATCH 07/10] fix(hunts): show the full hunt name on hover in the list The row cuts off long display names. There was no way to see the full text. The name uses the repo's Tooltip component, like the source list's origin label. --- .../ListHuntsTree/HuntList.test.tsx | 61 +++++++++++++++++++ .../components/ListHuntsTree/HuntList.tsx | 5 +- 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.test.tsx diff --git a/apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.test.tsx new file mode 100644 index 000000000..94f966163 --- /dev/null +++ b/apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.test.tsx @@ -0,0 +1,61 @@ +import { buildTestWrapper } from '@/core/utils/test-utils/buildTestWrapper'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; +import { HuntList } from './HuntList'; + +const LONG_NAME = + 'Windows security audit failures across every domain controller in the estate'; + +// The empty and error states are not under test, and EmptyList pulls in the code editor. +vi.mock('./EmptyList', () => ({ EmptyList: () => null })); +vi.mock('./ErrorList', () => ({ ErrorList: () => null })); +vi.mock('@/core/hooks/useSetComponentHeight', () => ({ + useSetComponentHeight: () => ({ componentHeight: 600 }), +})); +vi.mock('@/Hunts/contexts/ListHuntsContext', () => ({ + useListHuntsContext: () => ({ + data: { + items: [ + { + name: 'windows_audit', + display_name: LONG_NAME, + enabled: true, + }, + { name: 'dns_audit', display_name: 'DNS audit', enabled: true }, + ], + }, + error: null, + isLoading: false, + loadMoreRef: { current: null }, + isFetchingNextPage: false, + selectedHuntName: null, + setSelectedHuntName: vi.fn(), + filters: {}, + hasFilters: false, + setFilters: vi.fn(), + }), +})); + +const { wrapper } = buildTestWrapper().withTheme(); + +describe('HuntList', () => { + it('shows the full display name in a tooltip on the truncated name', async () => { + render(, { wrapper }); + + await userEvent.hover(screen.getByText(LONG_NAME)); + + expect(await screen.findByRole('tooltip')).toHaveTextContent(LONG_NAME); + }); + + it('gives each row its own name in the tooltip', async () => { + render(, { wrapper }); + + await userEvent.hover(screen.getByText('DNS audit')); + + expect(await screen.findByRole('tooltip')).toHaveTextContent('DNS audit'); + expect( + screen.queryByText(LONG_NAME, { selector: '[role=tooltip] *' }), + ).toBeNull(); + }); +}); diff --git a/apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.tsx b/apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.tsx index 1a0e95b61..68d04f165 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ListHuntsTree/HuntList.tsx @@ -1,5 +1,6 @@ import { useListHuntsContext } from '@/Hunts/contexts/ListHuntsContext'; import { CustomScrollbar } from '@/core/components/CustomScrollbar'; +import { Tooltip } from '@/core/components/Tooltip'; import { THuntListItem } from '@/core/hooks/useFetchInfiniteFilteredHunts/types'; import { useSetComponentHeight } from '@/core/hooks/useSetComponentHeight'; import { cn } from '@/core/utils/style'; @@ -76,7 +77,9 @@ export const HuntList = ({ )} onClick={() => setSelectedHuntName(hunt.name)} > - {hunt.display_name} + + {hunt.display_name} + Date: Mon, 16 Nov 2026 20:24:12 +1100 Subject: [PATCH 08/10] fix(e2e): recreate the stopped hunt after the reset The first describe's reset_all wipes every hunt definition. Running the whole file left the stopped case's list without E2E_STOPPED_HUNT. The case recreates the definition before checking the list. The stop marker survives the reset as coordinator state. The recreated hunt shows Auto-disabled again. --- apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts b/apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts index 9dee35b40..e8396063c 100644 --- a/apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts +++ b/apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts @@ -161,9 +161,21 @@ test.describe('A hunt made through the API', () => { }); test.describe('A hunt the runner stopped', () => { + // The reset above wiped the hunt's definition. Its stop marker is coordinator + // state and survives, so the definition is put back and the marker shows again. test.beforeEach(async ({ page }) => { test.skip(!STOPPED, 'E2E_STOPPED_HUNT names no hunt a runner is stopping'); forgetEngineToken(); + await deleteIfPresent(`/api/v1/hunts/${STOPPED}`); + await engine('POST', '/api/v1/hunts', { + name: STOPPED, + display_name: 'Stopped Hunt', + cron: '*/5 * * * *', + log_buffer: 60, + customers: [ORG], + rules: [RULE], + global_source_table_name: 'main', + }); await loginAs(page, 'dfe_admin'); }); From 525aafea5ea305c34eb3b2cdea2218417dbe5c86 Mon Sep 17 00:00:00 2001 From: Derek Date: Mon, 16 Nov 2026 21:18:38 +1100 Subject: [PATCH 09/10] fix(hunts): explain auto-disable reasons and add re-enable button The auto-disable reason explains repeated hits on ClickHouse's memory limit, rows-to-read limit or quota. The reason code stays in the API. All UI text says Auto-disabled and names the hunt runner. The light tag text has a contrast ratio of 6.9:1. The detail alert has a Re-enable Hunt button beside the actions menu entry. Both use one shared hook. The edit drawer's Enabled switch shows the effective state. The switch starts off for an auto-disabled hunt. Turning it on clears the stop. Both states use one helper line. Disabled hunts show Trigger On-Demand as off with its reason. The shots spec finishes animations before each capture. It scrolls the drawer to its submit button. --- .../dfe-core-ui/e2e/specs/huntEnabled.spec.ts | 27 +++++- .../e2e/specs/huntEnabledShots.spec.ts | 64 ++++++++----- .../CreateUpdateHuntForm.test.tsx | 59 ++++++------ .../huntTargetTable.test.tsx | 4 +- .../components/CreateUpdateHuntForm/index.tsx | 14 +-- .../HuntStateTag/HuntStateTag.stories.tsx | 2 +- .../HuntStateTag/HuntStateTag.test.tsx | 31 +++++- .../Hunts/components/HuntStateTag/index.tsx | 21 +++- .../HuntDetailActionMenu/index.tsx | 78 ++------------- .../TriggerHunt/TriggerHunt.test.tsx | 47 +++++---- .../ViewHuntDetail/TriggerHunt/index.tsx | 20 ++-- .../ViewHuntDetail/ViewHuntDetail.test.tsx | 48 +++++++--- .../Hunts/components/ViewHuntDetail/index.tsx | 33 +++++-- .../hooks/useToggleHuntEnabled/index.tsx | 96 +++++++++++++++++++ .../src/Hunts/utils/autoDisable.ts | 27 ++++++ .../transformHuntDetailToFormData.test.ts | 54 +++++++++-- .../transformHuntDetailToFormData.ts | 8 +- .../src/core/utils/theme/tokens/colors.ts | 2 + 18 files changed, 432 insertions(+), 203 deletions(-) create mode 100644 apps/dfe-core-ui/src/Hunts/hooks/useToggleHuntEnabled/index.tsx create mode 100644 apps/dfe-core-ui/src/Hunts/utils/autoDisable.ts diff --git a/apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts b/apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts index e8396063c..698459c96 100644 --- a/apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts +++ b/apps/dfe-core-ui/e2e/specs/huntEnabled.spec.ts @@ -66,9 +66,14 @@ const openMenu = async (page: Page) => { } }; +// The menu's own entry: the alert on an auto-disabled hunt has a button of the same name. const menuAction = async (page: Page, action: string) => { await openMenu(page); - await page.getByRole('button', { name: action, exact: true }).click(); + await page + .getByRole('button', { name: 'Close actions', exact: true }) + .locator('..') + .getByRole('button', { name: action, exact: true }) + .click(); }; test.describe('A hunt made through the API', () => { @@ -195,19 +200,35 @@ test.describe('A hunt the runner stopped', () => { const tag = listRow(page, label).getByText('Auto-disabled'); await expect(tag).toBeVisible(); await tag.hover(); + // The reason reaches the user as words, never as the API's code. await expect(page.getByRole('tooltip')).toContainText( + /Auto-disabled by the hunt runner on .+ after hitting .+ repeatedly\./, + ); + await expect(page.getByRole('tooltip')).not.toContainText( stopped.auto_disabled_reason, ); + await expect( + page.getByRole('button', { name: /Trigger On-Demand/ }), + ).toBeDisabled(); await page.screenshot({ path: `${SHOTS}/auto-disabled.png` }); + const alertButton = page + .getByRole('alert') + .getByRole('button', { name: 'Re-enable Hunt', exact: true }); + await expect(alertButton).toBeVisible(); await openMenu(page); await expect( - page.getByRole('button', { name: 'Re-enable Hunt', exact: true }), + page + .getByRole('button', { name: 'Close actions', exact: true }) + .locator('..') + .getByRole('button', { name: 'Re-enable Hunt', exact: true }), ).toBeVisible(); await page.screenshot({ path: `${SHOTS}/auto-disabled-menu.png` }); + // The open menu sits over the alert, so it is closed before the alert's button is used. await page - .getByRole('button', { name: 'Re-enable Hunt', exact: true }) + .getByRole('button', { name: 'Close actions', exact: true }) .click(); + await alertButton.click(); await expect(page.getByText(`Hunt ${label} enabled`)).toBeVisible(); await expect(listRow(page, label).getByText('Auto-disabled')).toHaveCount( 0, diff --git a/apps/dfe-core-ui/e2e/specs/huntEnabledShots.spec.ts b/apps/dfe-core-ui/e2e/specs/huntEnabledShots.spec.ts index 57a78de2b..981ad643b 100644 --- a/apps/dfe-core-ui/e2e/specs/huntEnabledShots.spec.ts +++ b/apps/dfe-core-ui/e2e/specs/huntEnabledShots.spec.ts @@ -43,12 +43,32 @@ const huntBody = (label: string) => ({ }); // The whole body, so a drawer or a tooltip rendered in a portal is in the tree. +// Animations are run to their end first, so a drawer or tooltip is never caught mid-slide. const capture = async (page: Page, name: string) => { - await page.screenshot({ path: `${OUT}/${name}.png` }); + await page.screenshot({ path: `${OUT}/${name}.png`, animations: 'disabled' }); const aria = await page.locator('body').ariaSnapshot(); writeFileSync(`${OUT}/${name}.aria.yaml`, aria); }; +// The actions menu's own entry, as the alert carries a button of the same name. +const menuButton = (page: Page, name: string) => + page + .getByRole('button', { name: 'Close actions', exact: true }) + .locator('..') + .getByRole('button', { name, exact: true }); + +// The drawer has finished opening once its last control, the submit button, is +// on screen. The form is scrolled to it, so the alert, the switch and the +// button are in the shot at the smaller height too. +const settledDrawer = async (page: Page) => { + const drawer = page.getByRole('dialog'); + const submit = drawer.getByRole('button', { name: 'Edit Hunt', exact: true }); + await expect(drawer.getByRole('switch', { name: 'Enabled' })).toBeVisible(); + await expect(submit).toBeVisible(); + await submit.scrollIntoViewIfNeeded(); + return drawer; +}; + const openHunt = async (page: Page, name: string, label: string) => { await page.goto(`${BASE_URL}/hunts?name=${name}`); await expect( @@ -126,21 +146,22 @@ test('the enabled state in every theme and width', async ({ page }) => { await openHunt(page, DISABLED, DISABLED_LABEL); await setTheme(page, theme); + // A disabled hunt fires nothing, so the on-demand trigger is off with its reason. + const trigger = page.getByRole('button', { name: /Trigger On-Demand/ }); + await expect(trigger).toBeDisabled(); + await trigger.hover({ force: true }); + await expect(page.getByRole('tooltip')).toBeVisible(); await capture(page, `${tag}-disabled`); await openMenu(page); + await expect(menuButton(page, 'Enable Hunt')).toBeVisible(); await capture(page, `${tag}-disabled-menu`); - await page - .getByRole('button', { name: 'Edit Hunt', exact: true }) - .click(); - const drawer = page.getByRole('dialog'); + await menuButton(page, 'Edit Hunt').click(); + const drawer = await settledDrawer(page); await expect( drawer.getByRole('switch', { name: 'Enabled' }), ).not.toBeChecked(); await capture(page, `${tag}-disabled-edit`); - await page - .getByRole('dialog') - .getByRole('button', { name: 'Close' }) - .click(); + await drawer.getByRole('button', { name: 'Close' }).click(); await expect(drawer).toBeHidden(); if (!STOPPED) continue; @@ -150,32 +171,31 @@ test('the enabled state in every theme and width', async ({ page }) => { .filter({ hasText: 'Shot Stopped' }) .getByText('Auto-disabled'); await expect(stopTag).toBeVisible(); + await expect( + page.getByRole('alert').getByRole('button', { name: 'Re-enable Hunt' }), + ).toBeVisible(); await stopTag.hover(); await expect(page.getByRole('tooltip')).toBeVisible(); await capture(page, `${tag}-stopped-tooltip`); await openMenu(page); - await expect( - page.getByRole('button', { name: 'Re-enable Hunt', exact: true }), - ).toBeVisible(); + await expect(menuButton(page, 'Re-enable Hunt')).toBeVisible(); await capture(page, `${tag}-stopped-menu`); - await page - .getByRole('button', { name: 'Edit Hunt', exact: true }) - .click(); - const stopDrawer = page.getByRole('dialog'); + await menuButton(page, 'Edit Hunt').click(); + const stopDrawer = await settledDrawer(page); await expect(stopDrawer.getByRole('alert')).toBeVisible(); + await expect( + stopDrawer.getByRole('switch', { name: 'Enabled' }), + ).not.toBeChecked(); await capture(page, `${tag}-stopped-edit`); - await page - .getByRole('dialog') - .getByRole('button', { name: 'Close' }) - .click(); + await stopDrawer.getByRole('button', { name: 'Close' }).click(); await expect(stopDrawer).toBeHidden(); } } if (STOPPED) { await openHunt(page, STOPPED, 'Shot Stopped'); - await openMenu(page); await page - .getByRole('button', { name: 'Re-enable Hunt', exact: true }) + .getByRole('alert') + .getByRole('button', { name: 'Re-enable Hunt' }) .click(); await expect(page.getByText('Hunt Shot Stopped enabled')).toBeVisible(); // The settled state: the tag has gone from the row and the header. diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx index 93a52df19..6ea655eb9 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/CreateUpdateHuntForm.test.tsx @@ -279,49 +279,43 @@ describe('CreateUpdateHuntForm runner stop', () => { { case: 'with a reason', reason: 'resource_limit:241', - copy: /^The runner stopped this hunt on .+ after repeated ClickHouse resource-limit failures \(resource_limit:241\)\.$/, + copy: /^Auto-disabled by the hunt runner on .+ after hitting ClickHouse's memory limit repeatedly\.$/, }, { case: 'without a reason', reason: '', - copy: /^The runner stopped this hunt on .+ after repeated ClickHouse resource-limit failures\.$/, + copy: /^Auto-disabled by the hunt runner on .+ after hitting a ClickHouse resource limit repeatedly\.$/, }, ])( - 'says when and why the runner stopped the hunt $case', + 'says when and why the hunt runner auto-disabled the hunt $case', ({ reason, copy }) => { renderForm({ autoDisabled: { at: 1_763_300_000, reason } }); expect(screen.getByText(copy)).toBeInTheDocument(); + expect(screen.queryByText(/resource_limit/)).toBeNull(); expect( - screen.getByText( - 'Saving leaves it stopped. Use Re-enable Hunt in the actions menu to start it again.', - ), + screen.getByText('Turn Enabled on and save to start it again.'), ).toBeInTheDocument(); }, ); + // The alert says it all, so the switch keeps its one line in both states. test.each([ { - case: 'stopped by the runner', + case: 'auto-disabled by the hunt runner', autoDisabled: { at: 1_763_300_000, reason: 'resource_limit:241' }, - shown: - 'On in the saved configuration, but the runner has stopped it. Re-enable Hunt in the actions menu starts it again.', - hidden: 'A disabled hunt keeps its configuration and fires nothing.', - }, - { - case: 'not stopped', - autoDisabled: null, - shown: 'A disabled hunt keeps its configuration and fires nothing.', - hidden: - 'On in the saved configuration, but the runner has stopped it. Re-enable Hunt in the actions menu starts it again.', }, + { case: 'not auto-disabled', autoDisabled: null }, ])( - 'describes the Enabled switch for a hunt $case', - ({ autoDisabled, shown, hidden }) => { + 'describes the Enabled switch once for a hunt $case', + ({ autoDisabled }) => { renderForm({ autoDisabled }); - expect(screen.getByText(shown)).toBeInTheDocument(); - expect(screen.queryByText(hidden)).toBeNull(); + expect( + screen.getAllByText( + 'A disabled hunt keeps its configuration and fires nothing.', + ), + ).toHaveLength(1); }, ); @@ -331,22 +325,29 @@ describe('CreateUpdateHuntForm runner stop', () => { ])('shows no stop notice when autoDisabled $case', ({ autoDisabled }) => { renderForm({ autoDisabled }); - expect(screen.queryByText(/The runner stopped this hunt/)).toBeNull(); + expect(screen.queryByText(/Auto-disabled by the hunt runner/)).toBeNull(); }); - test('leaves the Enabled switch as the stored value and still toggles it', async () => { + test('turning the Enabled switch on submits enabled: true', async () => { const onFinish = vi.fn(); - renderForm({ - autoDisabled: { at: 1_763_300_000, reason: 'resource_limit:241' }, - onFinish, - }); + render( + , + { wrapper }, + ); const toggle = screen.getByRole('switch', { name: 'Enabled' }); - expect(toggle).toBeChecked(); + expect(toggle).not.toBeChecked(); await userEvent.click(toggle); await userEvent.click(screen.getByRole('button', { name: 'Save Hunt' })); await waitFor(() => expect(onFinish).toHaveBeenCalledTimes(1)); - expect(onFinish.mock.calls[0]?.[0].enabled).toBe(false); + expect(onFinish.mock.calls[0]?.[0].enabled).toBe(true); }); }); diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx index 01dca1c0b..177ae115e 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/huntTargetTable.test.tsx @@ -332,9 +332,11 @@ describe('Edit Hunt runner stop', () => { expect( drawer.getByText( - /The runner stopped this hunt on .+ \(resource_limit:241\)\./, + /Auto-disabled by the hunt runner on .+ after hitting ClickHouse's memory limit repeatedly\./, ), ).toBeInTheDocument(); + // The switch shows the effective state, off, and an untouched switch names nothing. + expect(drawer.getByRole('switch', { name: 'Enabled' })).not.toBeChecked(); await userEvent.click(drawer.getByRole('button', { name: 'Edit Hunt' })); await waitFor(() => expect(sent.body).toBeDefined()); diff --git a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx index 38e3a9dde..3fe04f4c1 100644 --- a/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/CreateUpdateHuntForm/index.tsx @@ -3,10 +3,10 @@ import { Form } from '@/core/components/Form'; import { OrganisationSelect } from '@/core/components/OrganisationSelect'; import { SourceSelect } from '@/core/components/SourceSelect'; import { getApiErrorResponseBody } from '@/core/config/api/client'; -import { formatEpochSecondsLocal } from '@/core/helpers/date.helpers'; import { useAntdZodResolver } from '@/core/utils/zod/useAntdZodResolver'; import { RULE_HUNT_NAME_VALIDATOR } from '@/core/validationSchemas/utils'; import { CRONBuilderDrawer } from '@/Hunts/components/CRONBuilderDrawer'; +import { autoDisableNotice } from '@/Hunts/utils/autoDisable'; import { IconDeviceFloppy, IconPlus, IconTrash } from '@repo/dfe-icons'; import { Alert, Button, FormProps, Input, Switch } from 'antd'; import { useEffect, useMemo } from 'react'; @@ -71,7 +71,7 @@ type CreateUpdateHuntFormProps = FormProps & { error: Error | null; buttonLabel?: string; disabledFields?: DisabledFields; - /** Set when the runner stopped the hunt. A save leaves that stop in place. */ + /** Set when the hunt runner auto-disabled the hunt. Saving with Enabled on clears it. */ autoDisabled?: { at: number; reason: string } | null; }; @@ -206,19 +206,15 @@ export const CreateUpdateHuntForm = ({ type="warning" showIcon className="mb-4" - title={`The runner stopped this hunt on ${formatEpochSecondsLocal(autoDisabled.at)} after repeated ClickHouse resource-limit failures${autoDisabled.reason ? ` (${autoDisabled.reason})` : ''}.`} - description="Saving leaves it stopped. Use Re-enable Hunt in the actions menu to start it again." + title={autoDisableNotice(autoDisabled.at, autoDisabled.reason)} + description="Turn Enabled on and save to start it again." /> )} diff --git a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.stories.tsx b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.stories.tsx index 30675c978..08922659f 100644 --- a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.stories.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.stories.tsx @@ -24,7 +24,7 @@ export const Disabled: Story = { args: { enabled: false }, }; -// A runner stop leaves the YAML's enabled flag on: the stop is state, not config. +// An auto-disable leaves the YAML's enabled flag on: it is state, not config. export const AutoDisabled: Story = { args: { enabled: true, diff --git a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx index 858f0f4af..66c6b3200 100644 --- a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx @@ -36,14 +36,14 @@ describe('HuntStateTag', () => { }, tag: 'Auto-disabled', tooltip: - /after repeated ClickHouse resource-limit failures \(resource_limit:241\)\. Re-enable the hunt to clear it\./, + /^Auto-disabled by the hunt runner on .+ after hitting ClickHouse's memory limit repeatedly\. Turn Enabled on to start it again\.$/, }, { case: 'the auto-disable wins over a plain disable', props: { enabled: false, autoDisabledAt: 1_763_300_000 }, tag: 'Auto-disabled', tooltip: - /^Stopped .* after repeated ClickHouse resource-limit failures\./, + /^Auto-disabled by the hunt runner on .+ after hitting a ClickHouse resource limit repeatedly\./, }, ])('$case', async ({ props, tag, tooltip }) => { render(, { wrapper }); @@ -59,4 +59,31 @@ describe('HuntStateTag', () => { expect(await screen.findByText(tooltip)).toBeInTheDocument(); } }); + + // The raw code never reaches the user: the API's reason becomes words. + it.each([ + { reason: 'resource_limit:241', words: "ClickHouse's memory limit" }, + { reason: 'resource_limit:158', words: "ClickHouse's rows-to-read limit" }, + { reason: 'resource_limit:201', words: "ClickHouse's quota" }, + { + reason: 'resource_limit:999', + words: 'a ClickHouse resource limit (error 999)', + }, + { reason: '', words: 'a ClickHouse resource limit' }, + { reason: 'something_else', words: 'a ClickHouse resource limit' }, + ])('names $reason as $words', async ({ reason, words }) => { + render( + , + { wrapper }, + ); + + await userEvent.hover(screen.getByText('Auto-disabled')); + + const tooltip = await screen.findByRole('tooltip'); + expect(tooltip).toHaveTextContent(words); + expect(tooltip).not.toHaveTextContent(/resource_limit/); + }); }); diff --git a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx index afbd297cc..80a37f4cf 100644 --- a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx @@ -1,5 +1,7 @@ import { Tooltip } from '@/core/components/Tooltip'; -import { formatEpochSecondsLocal } from '@/core/helpers/date.helpers'; +import { useTheme } from '@/core/contexts/ClientContext/ThemeContext'; +import { colors } from '@/core/utils/theme'; +import { autoDisableNotice } from '@/Hunts/utils/autoDisable'; import { Tag } from 'antd'; interface HuntStateTagProps { @@ -9,20 +11,29 @@ interface HuntStateTagProps { className?: string; } -/** A tag for a hunt the runner is not firing, and nothing for one it is. */ +/** A tag for a hunt the hunt runner is not firing, and nothing for one it is. */ export const HuntStateTag = ({ enabled, autoDisabledAt, autoDisabledReason, className, }: HuntStateTagProps) => { + const { colorMode } = useTheme(); if (autoDisabledAt != null) { - const reason = autoDisabledReason ? ` (${autoDisabledReason})` : ''; return ( - + Auto-disabled diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx index b003afd54..30b3b9b60 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/HuntDetailActionMenu/index.tsx @@ -1,5 +1,4 @@ import { ActionsMenu } from '@/core/components/ActionsMenu'; -import { ApiErrorNotification } from '@/core/components/ApiErrorNotification'; import { RbacProtected } from '@/core/components/RbacProtected'; import { QUERY_KEYS } from '@/core/config/api/endpoints/queryKeys'; import { CloneHuntModal } from '@/Hunts/components/CloneHuntModal'; @@ -7,15 +6,9 @@ import { DeleteHuntModal } from '@/Hunts/components/DeleteHuntModal'; import { UpdateHuntDrawer } from '@/Hunts/components/UpdateHuntDrawer'; import { useListHuntsContext } from '@/Hunts/contexts/ListHuntsContext'; import { THuntCreateResponse } from '@/Hunts/hooks/useCreateHunt/types'; -import { fetchHuntDetail } from '@/Hunts/hooks/useFetchHuntDetail/api'; import { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; -import { useHuntRunState } from '@/Hunts/hooks/useHuntRunState'; -import { useUpdateHunt } from '@/Hunts/hooks/useUpdateHunt'; +import { useToggleHuntEnabled } from '@/Hunts/hooks/useToggleHuntEnabled'; import { THuntUpdateResponse } from '@/Hunts/hooks/useUpdateHunt/types'; -import { - transformHuntDetailToFormData, - transformHuntFormDataToUpdateRequest, -} from '@/Hunts/utils/transformHuntData/transformHuntDetailToFormData'; import { IconCopy, IconEdit, @@ -25,14 +18,12 @@ import { } from '@repo/dfe-icons'; import { useQueryClient } from '@tanstack/react-query'; import { App, Button } from 'antd'; -import { useRef, useState } from 'react'; interface HuntDetailActionMenuProps { onEditSuccess?: (hunt: THuntUpdateResponse) => void; hunt: THuntDetailResponse; } -/** Disable, Enable, or Re-enable, which also clears a stop the runner made. */ const ToggleHuntEnabled = ({ hunt, onSuccess, @@ -40,66 +31,11 @@ const ToggleHuntEnabled = ({ hunt: THuntDetailResponse; onSuccess: (hunt: THuntUpdateResponse) => void; }) => { - const { notification } = App.useApp(); - const queryClient = useQueryClient(); - const { enabled, autoDisabledAt } = useHuntRunState(hunt); - const autoDisabled = autoDisabledAt != null; - const turnOn = autoDisabled || enabled === false; - const label = autoDisabled - ? 'Re-enable Hunt' - : turnOn - ? 'Enable Hunt' - : 'Disable Hunt'; - const Icon = turnOn ? IconPlayerPlay : IconPlayerPause; - const huntLabel = hunt.display_name || hunt.name; - - const [isReading, setIsReading] = useState(false); - // The direction the PUT carries, which the fresh read can change from the label's. - const sent = useRef(turnOn); - - const onError = (error: Error) => - notification.error({ - title: `Hunt ${huntLabel} was not ${sent.current ? 'enabled' : 'disabled'}`, - description: , - placement: 'bottomLeft', - }); - - const { mutate, isPending } = useUpdateHunt({ - name: hunt.name, - onSuccess: async (response) => { - onSuccess(response); - // The notice waits for the refetch, so the row, header and menu no longer say Auto-disabled when it shows. - await queryClient.invalidateQueries({ - queryKey: QUERY_KEYS.hunts.default(), - }); - notification.success({ - title: `Hunt ${huntLabel} ${sent.current ? 'enabled' : 'disabled'}`, - placement: 'bottomLeft', - }); - }, - onError, + const { label, turnOn, loading, toggle } = useToggleHuntEnabled({ + hunt, + onSuccess, }); - - // The engine has no per-field write, so a toggle sends the whole config, and a fresh read keeps it from undoing an edit landed since the page loaded. - const toggle = async () => { - sent.current = turnOn; - setIsReading(true); - try { - const fresh = await fetchHuntDetail({ pathParams: { name: hunt.name } }); - sent.current = fresh.auto_disabled_at != null || fresh.enabled === false; - mutate({ - ...transformHuntFormDataToUpdateRequest( - transformHuntDetailToFormData(fresh), - fresh, - ), - enabled: sent.current, - }); - } catch (error) { - onError(error instanceof Error ? error : new Error(String(error))); - } finally { - setIsReading(false); - } - }; + const Icon = turnOn ? IconPlayerPlay : IconPlayerPause; return ( @@ -109,8 +45,8 @@ const ToggleHuntEnabled = ({ type="text" icon={} aria-label={label} - loading={isReading || isPending} - onClick={() => void toggle()} + loading={loading} + onClick={toggle} > {label} diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/TriggerHunt.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/TriggerHunt.test.tsx index 993bede0c..ce6f694a5 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/TriggerHunt.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/TriggerHunt.test.tsx @@ -56,28 +56,35 @@ const captureRuns = () => { }; describe('TriggerHunt', () => { - it('is disabled with the reason for a hunt the runner stopped, and sends nothing', async () => { - const runs = captureRuns(); - render( - , - { wrapper }, - ); - const button = await screen.findByRole('button', { - name: /Trigger On-Demand/, - }); + it.each([ + { + case: 'the hunt runner auto-disabled', + detail: { ...hunt, auto_disabled_at: 1_763_300_000 }, + reason: 'The hunt runner auto-disabled this hunt. Re-enable it first.', + }, + { + case: 'its configuration disabled', + detail: { ...hunt, enabled: false, auto_disabled_at: null }, + reason: 'This hunt is disabled and fires nothing. Enable it first.', + }, + ])( + 'is disabled with the reason for a hunt $case, and sends nothing', + async ({ detail, reason }) => { + const runs = captureRuns(); + render(, { wrapper }); + const button = await screen.findByRole('button', { + name: /Trigger On-Demand/, + }); - expect(button).toBeDisabled(); - await userEvent.click(button); - await userEvent.hover(button.parentElement ?? button); + expect(button).toBeDisabled(); + await userEvent.click(button); + await userEvent.hover(button.parentElement ?? button); - expect( - await screen.findByText( - 'The runner stopped this hunt. Re-enable it first.', - ), - ).toBeInTheDocument(); - expect(screen.queryByText('Trigger On-Demand Hunt')).toBeNull(); - expect(runs).toEqual([]); - }); + expect(await screen.findByText(reason)).toBeInTheDocument(); + expect(screen.queryByText('Trigger On-Demand Hunt')).toBeNull(); + expect(runs).toEqual([]); + }, + ); it('queues a run for a hunt the runner is firing', async () => { const runs = captureRuns(); diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/index.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/index.tsx index bce08be18..41c6cd399 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/TriggerHunt/index.tsx @@ -12,7 +12,15 @@ import { useState } from 'react'; export const TriggerHunt = ({ hunt }: { hunt: THuntDetailResponse }) => { const selectedHuntName = hunt.name; const [isOpen, setIsOpen] = useState(false); - const stopped = useHuntRunState(hunt).autoDisabledAt != null; + const { enabled, autoDisabledAt } = useHuntRunState(hunt); + // A disabled hunt fires nothing, however it came to be disabled. + const reason = + autoDisabledAt != null + ? 'The hunt runner auto-disabled this hunt. Re-enable it first.' + : enabled === false + ? 'This hunt is disabled and fires nothing. Enable it first.' + : undefined; + const stopped = reason !== undefined; const { notification } = App.useApp(); @@ -27,7 +35,7 @@ export const TriggerHunt = ({ hunt }: { hunt: THuntDetailResponse }) => { setIsOpen(false); notification.success({ title: 'On-demand run queued', - description: `The runner picks it up within ${data.poll_seconds} seconds.`, + description: `The hunt runner picks it up within ${data.poll_seconds} seconds.`, placement: 'bottomLeft', }); }, @@ -42,13 +50,7 @@ export const TriggerHunt = ({ hunt }: { hunt: THuntDetailResponse }) => { <> - + diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx index 62a3e4d37..5d95716e7 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/ViewHuntDetail.test.tsx @@ -1,7 +1,18 @@ +import { server } from '@/core/components/RbacProtected/hooks/hooks.mocks'; import { buildTestWrapper } from '@/core/utils/test-utils/buildTestWrapper'; import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; -import { render, screen } from '@testing-library/react'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { render, screen, within } from '@testing-library/react'; +import { App } from 'antd'; +import type { ReactNode } from 'react'; +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from 'vitest'; import { ViewHuntDetail } from '.'; // The tabs, the action menu and the trigger reach their own APIs. What is under test is the stop notice. @@ -32,11 +43,20 @@ vi.mock('@/Hunts/hooks/useFetchHuntDetail', () => ({ }), })); +// The alert's Re-enable button reads the permissions the RBAC mocks serve. +beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); afterEach(() => { + server.resetHandlers(); state.listed = []; }); +afterAll(() => server.close()); -const { wrapper } = buildTestWrapper().withTheme(); +const { wrapper: Providers } = buildTestWrapper().withTheme().withReactQuery(); +const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + +); const hunt: THuntDetailResponse = { name: 'windows_audit', @@ -50,9 +70,8 @@ const hunt: THuntDetailResponse = { auto_disabled_reason: '', }; -const NOTICE = /^The runner stopped this hunt on /; -const WAY_BACK = - 'It fires nothing until you choose Re-enable Hunt from the actions menu.'; +const NOTICE = /^Auto-disabled by the hunt runner on /; +const WAY_BACK = 'It fires nothing until it is re-enabled.'; describe('ViewHuntDetail runner stop', () => { it.each([ @@ -63,24 +82,27 @@ describe('ViewHuntDetail runner stop', () => { auto_disabled_at: 1_763_300_000, auto_disabled_reason: 'resource_limit:241', }, - shown: /failures \(resource_limit:241\)\.$/, + shown: /after hitting ClickHouse's memory limit repeatedly\.$/, }, { case: 'the detail carries the stop with no reason', detail: { ...hunt, auto_disabled_at: 1_763_300_000 }, - shown: /failures\.$/, + shown: /after hitting a ClickHouse resource limit repeatedly\.$/, }, - ])('announces the stop when $case', ({ detail, shown }) => { + ])('announces the stop when $case', async ({ detail, shown }) => { state.detail = detail; render(, { wrapper }); - expect(screen.getByRole('alert')).toBeInTheDocument(); - expect(screen.getByText(NOTICE)).toHaveTextContent( - /after repeated ClickHouse resource-limit failures/, - ); + const alert = screen.getByRole('alert'); + expect(alert).toBeInTheDocument(); expect(screen.getByText(NOTICE)).toHaveTextContent(shown); + expect(alert).not.toHaveTextContent(/resource_limit/); expect(screen.getByText(WAY_BACK)).toBeInTheDocument(); + // The button shows once the RBAC read has answered. + expect( + await within(alert).findByRole('button', { name: 'Re-enable Hunt' }), + ).toBeInTheDocument(); expect(screen.getByText('Auto-disabled')).toBeInTheDocument(); }); diff --git a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx index 286644ee5..fd967c7ae 100644 --- a/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/ViewHuntDetail/index.tsx @@ -1,7 +1,7 @@ import { CustomScrollbar } from '@/core/components/CustomScrollbar'; import { EmptyDetail } from '@/core/components/EmptyDetail'; import { GenericErrorCard } from '@/core/components/GenericError'; -import { formatEpochSecondsLocal } from '@/core/helpers/date.helpers'; +import { RbacProtected } from '@/core/components/RbacProtected'; import { useSetComponentHeight } from '@/core/hooks/useSetComponentHeight'; import { HuntStateTag } from '@/Hunts/components/HuntStateTag'; import { ViewHuntDetailTabs } from '@/Hunts/components/ViewHuntTabs'; @@ -9,7 +9,9 @@ import { useListHuntsContext } from '@/Hunts/contexts/ListHuntsContext'; import { useFetchHuntDetail } from '@/Hunts/hooks/useFetchHuntDetail'; import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; import { useHuntRunState } from '@/Hunts/hooks/useHuntRunState'; -import { Alert, Spin } from 'antd'; +import { useToggleHuntEnabled } from '@/Hunts/hooks/useToggleHuntEnabled'; +import { autoDisableNotice } from '@/Hunts/utils/autoDisable'; +import { Alert, Button, Spin } from 'antd'; import { HuntDetailActionMenu } from './HuntDetailActionMenu'; import { TriggerHunt } from './TriggerHunt'; @@ -18,19 +20,38 @@ const HuntDetailStateTag = ({ hunt }: { hunt: THuntDetailResponse }) => { return ; }; -/** The stop and the way back as text, because the tag's tooltip is hover only. */ +/** The way back, in the alert itself rather than only behind the actions menu. */ +const ReenableHuntButton = ({ hunt }: { hunt: THuntDetailResponse }) => { + const { label, loading, toggle } = useToggleHuntEnabled({ hunt }); + return ( + + + + + + + + + ); +}; + +/** The auto-disable and the way back as text, because the tag's tooltip is hover only. */ const HuntStopAlert = ({ hunt }: { hunt: THuntDetailResponse }) => { const { autoDisabledAt, autoDisabledReason } = useHuntRunState(hunt); if (autoDisabledAt == null) { return null; } - const reason = autoDisabledReason ? ` (${autoDisabledReason})` : ''; return ( } /> ); }; diff --git a/apps/dfe-core-ui/src/Hunts/hooks/useToggleHuntEnabled/index.tsx b/apps/dfe-core-ui/src/Hunts/hooks/useToggleHuntEnabled/index.tsx new file mode 100644 index 000000000..8b026be9a --- /dev/null +++ b/apps/dfe-core-ui/src/Hunts/hooks/useToggleHuntEnabled/index.tsx @@ -0,0 +1,96 @@ +import { ApiErrorNotification } from '@/core/components/ApiErrorNotification'; +import { QUERY_KEYS } from '@/core/config/api/endpoints/queryKeys'; +import { fetchHuntDetail } from '@/Hunts/hooks/useFetchHuntDetail/api'; +import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; +import { useHuntRunState } from '@/Hunts/hooks/useHuntRunState'; +import { useUpdateHunt } from '@/Hunts/hooks/useUpdateHunt'; +import type { THuntUpdateResponse } from '@/Hunts/hooks/useUpdateHunt/types'; +import { + transformHuntDetailToFormData, + transformHuntFormDataToUpdateRequest, +} from '@/Hunts/utils/transformHuntData/transformHuntDetailToFormData'; +import { useQueryClient } from '@tanstack/react-query'; +import { App } from 'antd'; +import { useRef, useState } from 'react'; + +interface UseToggleHuntEnabledOptions { + hunt: THuntDetailResponse; + onSuccess?: (hunt: THuntUpdateResponse) => void; +} + +/** + * Disable, Enable, or Re-enable, which also clears an auto-disable. The one + * write behind the actions menu entry and the alert's button. + */ +export const useToggleHuntEnabled = ({ + hunt, + onSuccess, +}: UseToggleHuntEnabledOptions) => { + const { notification } = App.useApp(); + const queryClient = useQueryClient(); + const { enabled, autoDisabledAt } = useHuntRunState(hunt); + const autoDisabled = autoDisabledAt != null; + const turnOn = autoDisabled || enabled === false; + const label = autoDisabled + ? 'Re-enable Hunt' + : turnOn + ? 'Enable Hunt' + : 'Disable Hunt'; + const huntLabel = hunt.display_name || hunt.name; + + const [isReading, setIsReading] = useState(false); + // The direction the PUT carries, which the fresh read can change from the label's. + const sent = useRef(turnOn); + + const onError = (error: Error) => + notification.error({ + title: `Hunt ${huntLabel} was not ${sent.current ? 'enabled' : 'disabled'}`, + description: , + placement: 'bottomLeft', + }); + + const { mutate, isPending } = useUpdateHunt({ + name: hunt.name, + onSuccess: async (response) => { + onSuccess?.(response); + // The notice waits for the refetch, so the row, header and menu no longer say Auto-disabled when it shows. + await queryClient.invalidateQueries({ + queryKey: QUERY_KEYS.hunts.default(), + }); + notification.success({ + title: `Hunt ${huntLabel} ${sent.current ? 'enabled' : 'disabled'}`, + placement: 'bottomLeft', + }); + }, + onError, + }); + + // The engine has no per-field write, so a toggle sends the whole config, and a fresh read keeps it from undoing an edit landed since the page loaded. + const toggle = async () => { + sent.current = turnOn; + setIsReading(true); + try { + const fresh = await fetchHuntDetail({ pathParams: { name: hunt.name } }); + sent.current = fresh.auto_disabled_at != null || fresh.enabled === false; + mutate({ + ...transformHuntFormDataToUpdateRequest( + transformHuntDetailToFormData(fresh), + fresh, + ), + enabled: sent.current, + }); + } catch (error) { + onError(error instanceof Error ? error : new Error(String(error))); + } finally { + setIsReading(false); + } + }; + + return { + label, + turnOn, + autoDisabled, + loading: isReading || isPending, + toggle: () => void toggle(), + }; +}; diff --git a/apps/dfe-core-ui/src/Hunts/utils/autoDisable.ts b/apps/dfe-core-ui/src/Hunts/utils/autoDisable.ts new file mode 100644 index 000000000..bee3ec6ff --- /dev/null +++ b/apps/dfe-core-ui/src/Hunts/utils/autoDisable.ts @@ -0,0 +1,27 @@ +import { formatEpochSecondsLocal } from '@/core/helpers/date.helpers'; +import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; + +// The ClickHouse error codes the hunt runner counts as a resource limit. +const LIMITS: Record = { + '241': "ClickHouse's memory limit", + '158': "ClickHouse's rows-to-read limit", + '201': "ClickHouse's quota", +}; + +/** The API's reason code as words. The code itself stays in the API. */ +export const describeAutoDisableLimit = (reason?: string | null): string => { + const code = reason?.match(/^resource_limit:(\d+)$/)?.[1]; + if (!code) { + return 'a ClickHouse resource limit'; + } + return LIMITS[code] ?? `a ClickHouse resource limit (error ${code})`; +}; + +/** One sentence for the tag's tooltip, the detail's alert and the edit form's alert. */ +export const autoDisableNotice = (at: number, reason?: string | null) => + `Auto-disabled by the hunt runner on ${formatEpochSecondsLocal(at)} after hitting ${describeAutoDisableLimit(reason)} repeatedly.`; + +/** What the hunt does: on in its configuration and not auto-disabled. */ +export const effectiveEnabled = ( + hunt: Pick, +): boolean => (hunt.enabled ?? true) && hunt.auto_disabled_at == null; diff --git a/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts b/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts index 655c36784..c56861cc9 100644 --- a/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts +++ b/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.test.ts @@ -49,15 +49,34 @@ describe('transformHuntDetailToFormData', () => { expect(transformHuntDetailToFormData(huntDetail)).toEqual(expectedFormData); }); + // The switch shows what the hunt does: on in its configuration and not auto-disabled. it.each([ - { case: 'enabled', stored: true, shown: true }, - { case: 'disabled', stored: false, shown: false }, - { case: 'storing no state, as enabled', stored: undefined, shown: true }, - ])('opens a hunt $case with the switch $shown', ({ stored, shown }) => { - const hunt = { ...huntDetail, enabled: stored } as THuntDetailResponse; + { case: 'enabled', stored: true, stoppedAt: null, shown: true }, + { case: 'disabled', stored: false, stoppedAt: null, shown: false }, + { + case: 'storing no state, as enabled', + stored: undefined, + stoppedAt: null, + shown: true, + }, + { + case: 'enabled but auto-disabled, as off', + stored: true, + stoppedAt: 1_763_300_000, + shown: false, + }, + ])( + 'opens a hunt $case with the switch $shown', + ({ stored, stoppedAt, shown }) => { + const hunt = { + ...huntDetail, + enabled: stored, + auto_disabled_at: stoppedAt, + } as THuntDetailResponse; - expect(transformHuntDetailToFormData(hunt).enabled).toBe(shown); - }); + expect(transformHuntDetailToFormData(hunt).enabled).toBe(shown); + }, + ); it('opens a stored hunt naming no organisation with none selected', () => { const { customers: _customers, ...namingNone } = huntDetail; @@ -169,8 +188,25 @@ describe('transformHuntFormDataToUpdateRequest', () => { form: true, sent: true, }, - ])('enabled: $case', ({ stored, form, sent }) => { - const hunt = { ...huntDetail, enabled: stored } as THuntDetailResponse; + { + case: 'leaves an auto-disabled hunt alone with the switch off', + stored: true, + stoppedAt: 1_763_300_000, + form: false, + }, + { + case: 'names true when an auto-disabled hunt is switched on', + stored: true, + stoppedAt: 1_763_300_000, + form: true, + sent: true, + }, + ])('enabled: $case', ({ stored, stoppedAt, form, sent }) => { + const hunt = { + ...huntDetail, + enabled: stored, + auto_disabled_at: stoppedAt ?? null, + } as THuntDetailResponse; const formValues = { ...transformHuntDetailToFormData(hunt), enabled: form, diff --git a/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.ts b/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.ts index af215b8ce..7238cd431 100644 --- a/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.ts +++ b/apps/dfe-core-ui/src/Hunts/utils/transformHuntData/transformHuntDetailToFormData.ts @@ -2,6 +2,7 @@ import type { CreateUpdateHuntFormData } from '@/Hunts/components/CreateUpdateHu import type { THuntCreateRequest } from '@/Hunts/hooks/useCreateHunt/types'; import type { THuntDetailResponse } from '@/Hunts/hooks/useFetchHuntDetail/types'; import type { THuntUpdateRequest } from '@/Hunts/hooks/useUpdateHunt/types'; +import { effectiveEnabled } from '@/Hunts/utils/autoDisable'; const cronList = (cron: THuntDetailResponse['cron']): string[] => { if (Array.isArray(cron)) { @@ -25,7 +26,7 @@ export const transformHuntDetailToFormData = ( rules: hunt.rules.map((rule) => rule.rule_name), global_target_table_name: hunt.global_target_table_name ?? '', global_source_table_name: hunt.global_source_table_name ?? '', - enabled: hunt.enabled ?? true, + enabled: effectiveEnabled(hunt), }); /** @@ -46,13 +47,14 @@ export const transformHuntFormDataToCreateRequest = ( /** * An edit that leaves the switch alone must not name `enabled`, because the - * engine clears a runner stop on any PUT that names it true. + * engine clears an auto-disable on any PUT that names it true. The switch + * opens showing the effective state, so turning it on is what clears it. */ const enabledField = ( values: CreateUpdateHuntFormData, hunt: THuntDetailResponse, ) => - values.enabled !== (hunt.enabled ?? true) ? { enabled: values.enabled } : {}; + values.enabled !== effectiveEnabled(hunt) ? { enabled: values.enabled } : {}; export const transformHuntFormDataToUpdateRequest = ( values: CreateUpdateHuntFormData, diff --git a/apps/dfe-core-ui/src/core/utils/theme/tokens/colors.ts b/apps/dfe-core-ui/src/core/utils/theme/tokens/colors.ts index 82d87c798..1a25f4afc 100644 --- a/apps/dfe-core-ui/src/core/utils/theme/tokens/colors.ts +++ b/apps/dfe-core-ui/src/core/utils/theme/tokens/colors.ts @@ -21,6 +21,8 @@ const semantic = { error: '#ff4d4f', // 5.57:1 on white: error text on a light surface meets WCAG AA (4.5:1). errorOnLight: '#cf1322', + // 6.9:1 on the warning tag's cream: warning text on a light surface meets WCAG AA (4.5:1). + warningOnLight: '#9a3412', info: brand.tertiary, } as const; From 4d41fc4fa0603f6236d230a5a7c9b1fcd015dcf7 Mon Sep 17 00:00:00 2001 From: Derek Date: Mon, 16 Nov 2026 21:24:44 +1100 Subject: [PATCH 10/10] fix(hunts): the list tooltip names Re-enable Hunt The list row has no Enabled switch, so its tag's tooltip points at the action the detail offers instead. --- .../src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx | 2 +- apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx index 66c6b3200..0204a3015 100644 --- a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/HuntStateTag.test.tsx @@ -36,7 +36,7 @@ describe('HuntStateTag', () => { }, tag: 'Auto-disabled', tooltip: - /^Auto-disabled by the hunt runner on .+ after hitting ClickHouse's memory limit repeatedly\. Turn Enabled on to start it again\.$/, + /^Auto-disabled by the hunt runner on .+ after hitting ClickHouse's memory limit repeatedly\. Use Re-enable Hunt to start it again\.$/, }, { case: 'the auto-disable wins over a plain disable', diff --git a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx index 80a37f4cf..b895c4db7 100644 --- a/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx +++ b/apps/dfe-core-ui/src/Hunts/components/HuntStateTag/index.tsx @@ -22,7 +22,7 @@ export const HuntStateTag = ({ if (autoDisabledAt != null) { return (