Compare commits
4 Commits
ac4fd967aa
...
487cb171f2
| Author | SHA1 | Date | |
|---|---|---|---|
| 487cb171f2 | |||
| 7789353690 | |||
| ccfcbc82c5 | |||
| 7626c9cb60 |
@@ -8,49 +8,56 @@ Reference: `Docs/Refactoring.md` for full analysis of each issue.
|
||||
|
||||
## Open Issues
|
||||
|
||||
1. Ban history durability and fail2ban DB size management
|
||||
- status: completed
|
||||
- description: BanGUI currently reads fail2ban history directly, but fail2ban's `dbpurgeage` may erase old history and can cause DB growth issues with long retention. Implement a BanGUI-native persistent archive and keep fail2ban DB short-lived.
|
||||
- acceptance criteria:
|
||||
- BanGUI can configure and fetch fail2ban `dbpurgeage` and `dbfile` from server API.
|
||||
- Introduce periodic sync job that reads new fail2ban ban/unban events and writes them to BanGUI app DB.
|
||||
- Use dedupe logic to avoid duplicate entries (unique constraint by `ip,jail,action,timestamp`).
|
||||
- Add persistence policy settings (default 365 days) in UI and server config.
|
||||
- Add backfill workflow on startup for last 7 days if archive empty.
|
||||
- Existing history API endpoints must support both a `source` filter (`fail2ban`, `archive`) and time range.
|
||||
- implementation notes:
|
||||
- Add repository methods `archive_ban_event`, `get_archived_history(...)`, `purge_archived_history(age_seconds)`.
|
||||
- Add periodic task in `backend/app/tasks/history_sync.py` triggered by scheduler.
|
||||
- Extend `Backend/app/routers/history.py` to include endpoint `/api/history/archive`.
|
||||
|
||||
2. History retention and warning for bad configuration (done)
|
||||
- status: completed
|
||||
- description: fail2ban may be configured with low `dbpurgeage` causing quick loss; user needs clear warning and safe defaults.
|
||||
- acceptance criteria:
|
||||
- On server settings load, if `dbpurgeage` < 86400, expose warning state in API.
|
||||
- UI displays warning banner: "Current fail2ban purge age is under 24h; detailed history may be lost.".
|
||||
- Allow user to increase `dbpurgeage` through server settings panel; sync to fail2ban using `set dbpurgeage`.
|
||||
- Add tests for server service response and UI warning logic.
|
||||
|
||||
3. History access from existing BanGUI features
|
||||
- status: completed
|
||||
- description: Doors for dashboard and map data should use archived history to avoid data gaps.
|
||||
- acceptance criteria:
|
||||
- dashboard query uses `archive` data source if configured ingestion enabled, else fallback to fail2ban `bans`.
|
||||
- world map grouping includes archived data and can aggregate `count` with timeframe filters.
|
||||
- API and UI unit tests verify data source fallback.
|
||||
|
||||
4. Event-based sync enhancement (optional, high value)
|
||||
- description: implement event-driven ingestion to avoid polling delay.
|
||||
- acceptance criteria:
|
||||
- Add fail2ban hook or systemd journal watcher to capture ban/unban events in real time.
|
||||
- Recorded events store to BanGUI archive in transaction-safe manner.
|
||||
- Add validation for event integrity and order.
|
||||
|
||||
---
|
||||
### History page filters and behavior (frontend)
|
||||
|
||||
1. [x] Time range filter currently not working
|
||||
- Scope: frontend `history` page state/logic (likely in `frontend/src` route or component for history table)
|
||||
- Expected behavior: selecting start/end timestamps (or presets) should filter history rows by event timestamp in the backend query or local data, then rerender filtered results immediately.
|
||||
- Investigation:
|
||||
- check component(s) handling time range input, change handlers, and query construction.
|
||||
- confirm backend API supports `startTime`/`endTime` parameters for history endpoint (`/api/history` or similar).
|
||||
- confirm values are passed as ISO strings/epoch and matched in backend.
|
||||
- Fix should include:
|
||||
- wiring the time range inputs to the filtering state.
|
||||
- constructing API query with time range params.
|
||||
- verifying with unit/integration tests plus manual through UI.
|
||||
|
||||
2. [x] Global filter (All | Blocklist | Selfblock) not working
|
||||
- Scope: frontend `history` page filter chips or select control.
|
||||
- Expected behavior: choosing `All`, `Blocklist`, `Selfblock` should apply corresponding filter in same history query (no results for unmatched types).
|
||||
- Tasks:
|
||||
- locate filter control component and event handlers.
|
||||
- validate value mapping semantics (`all`=>no filter, `blocklist`=>source=blocklist, `selfblock`=>source=selfblock or equivalent).
|
||||
- ensure filter value is merged with time range + jail/ip filters in API call.
|
||||
- add tests for each filter option to confirm behavior.
|
||||
|
||||
3. [x] Jail and IP address filters UX alignment with time range
|
||||
- Scope: frontend `history` page layout/CSS component; likely `HistoryFilters` container.
|
||||
- Expected behavior:
|
||||
- Jail filter and IP address filter should be same look (input/select style and spacing) as time range widget.
|
||||
- Place Jail/IP filters next to time range controls in same row.
|
||||
- Should be responsive and consistent.
|
||||
- Tasks:
|
||||
- modify the `history` filter container markup so time range, jail, ip filter are co-located.
|
||||
- apply matching CSS classes/styles to Jail/IP as existing time range control.
|
||||
- verify cross-browser/responsive display with storybook/test if exists.
|
||||
|
||||
4. [x] Remove “Apply” and “Clear” buttons; auto-apply on field change
|
||||
- Scope: frontend `history` filter form behavior.
|
||||
- Expected behavior:
|
||||
- Any filter field change (time range, type, jail, IP) triggers immediate query update (debounced 150-300 ms if needed).
|
||||
- Remove explicit “Apply” and “Clear” buttons from UI.
|
||||
- Clear can be replaced by resetting fields automatically or via a small “reset” icon if needed.
|
||||
- Implementation steps:
|
||||
- remove button UI elements and event bindings from history page component.
|
||||
- make each filter input onChange call the shared `applyFilters` logic with current state.
|
||||
- add debounce to avoid 100% rapid API churn.
|
||||
- for clear semantics, ensure default/empty state on filter input binds to default query (All).
|
||||
- add tests to verify no apply/clear buttons present and updates via input change.
|
||||
|
||||
### Acceptance criteria
|
||||
- On `history` page, time range selection + filter chips + jail/ip are functional and produce filtered results.
|
||||
- Time range, jail/IP inputs are styled consistently and in same filter row.
|
||||
- No apply/clear buttons are visible and filter updates occur on value change (with optional debounce).
|
||||
- Relevant tests added/updated in frontend test suite.
|
||||
|
||||
|
||||
@@ -210,7 +210,7 @@ Use Fluent UI React components as the building blocks. The following mapping sho
|
||||
|
||||
| Element | Fluent component | Notes |
|
||||
|---|---|---|
|
||||
| Data tables | `DetailsList` | All ban tables, jail overviews, history tables. Enable column sorting, selection, and shimmer loading. |
|
||||
| Data tables | `DetailsList` | All ban tables, jail overviews, history tables. Enable column sorting, selection, and shimmer loading. Use clear pagination controls (page number + prev/next) and a page-size selector (25/50/100) for large result sets. |
|
||||
| Stat cards | `DocumentCard` or custom `Stack` card | Dashboard status bar — server status, total bans, active jails. Use `Depth 4`. |
|
||||
| Status indicators | `Badge` / `Icon` + colour | Server online/offline, jail running/stopped/idle. |
|
||||
| Country labels | Monospaced text + flag emoji or icon | Geo data next to IP addresses. |
|
||||
|
||||
@@ -150,16 +150,18 @@ function GeoLayer({
|
||||
}
|
||||
|
||||
return (
|
||||
<g
|
||||
key={geo.rsmKey}
|
||||
style={{ cursor: cc ? "pointer" : "default" }}
|
||||
<g key={geo.rsmKey} style={{ cursor: cc ? "pointer" : "default" }}>
|
||||
<Geography
|
||||
geography={geo}
|
||||
role={cc ? "button" : undefined}
|
||||
tabIndex={cc ? 0 : undefined}
|
||||
aria-label={cc
|
||||
? `${cc}: ${String(count)} ban${count !== 1 ? "s" : ""}${
|
||||
isSelected ? " (selected)" : ""
|
||||
}`
|
||||
: undefined}
|
||||
aria-label={
|
||||
cc
|
||||
? `${cc}: ${String(count)} ban${count !== 1 ? "s" : ""}${
|
||||
isSelected ? " (selected)" : ""
|
||||
}`
|
||||
: undefined
|
||||
}
|
||||
aria-pressed={isSelected || undefined}
|
||||
onClick={(): void => {
|
||||
if (cc) handleClick(cc);
|
||||
@@ -194,46 +196,43 @@ function GeoLayer({
|
||||
onMouseLeave={(): void => {
|
||||
setTooltip(null);
|
||||
}}
|
||||
>
|
||||
<Geography
|
||||
geography={geo}
|
||||
style={{
|
||||
default: {
|
||||
fill: isSelected ? tokens.colorBrandBackground : fillColor,
|
||||
stroke: tokens.colorNeutralStroke2,
|
||||
strokeWidth: 0.75,
|
||||
outline: "none",
|
||||
},
|
||||
hover: {
|
||||
fill: isSelected
|
||||
? tokens.colorBrandBackgroundHover
|
||||
: cc && count > 0
|
||||
? tokens.colorNeutralBackground3
|
||||
: fillColor,
|
||||
stroke: tokens.colorNeutralStroke1,
|
||||
strokeWidth: 1,
|
||||
outline: "none",
|
||||
},
|
||||
pressed: {
|
||||
fill: cc ? tokens.colorBrandBackgroundPressed : fillColor,
|
||||
stroke: tokens.colorBrandStroke1,
|
||||
strokeWidth: 1,
|
||||
outline: "none",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
{count > 0 && cx !== undefined && cy !== undefined && isFinite(cx) && isFinite(cy) && (
|
||||
<text
|
||||
x={cx}
|
||||
y={cy}
|
||||
textAnchor="middle"
|
||||
dominantBaseline="central"
|
||||
className={styles.countLabel}
|
||||
>
|
||||
{count}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
style={{
|
||||
default: {
|
||||
fill: isSelected ? tokens.colorBrandBackground : fillColor,
|
||||
stroke: tokens.colorNeutralStroke2,
|
||||
strokeWidth: 0.75,
|
||||
outline: "none",
|
||||
},
|
||||
hover: {
|
||||
fill: isSelected
|
||||
? tokens.colorBrandBackgroundHover
|
||||
: cc && count > 0
|
||||
? tokens.colorNeutralBackground3
|
||||
: fillColor,
|
||||
stroke: tokens.colorNeutralStroke1,
|
||||
strokeWidth: 1,
|
||||
outline: "none",
|
||||
},
|
||||
pressed: {
|
||||
fill: cc ? tokens.colorBrandBackgroundPressed : fillColor,
|
||||
stroke: tokens.colorBrandStroke1,
|
||||
strokeWidth: 1,
|
||||
outline: "none",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
{count > 0 && cx !== undefined && cy !== undefined && isFinite(cx) && isFinite(cy) && (
|
||||
<text
|
||||
x={cx}
|
||||
y={cy}
|
||||
textAnchor="middle"
|
||||
dominantBaseline="central"
|
||||
className={styles.countLabel}
|
||||
>
|
||||
{count}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
},
|
||||
)}
|
||||
|
||||
@@ -12,7 +12,7 @@ import { FluentProvider, webLightTheme } from "@fluentui/react-components";
|
||||
vi.mock("react-simple-maps", () => ({
|
||||
ComposableMap: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
ZoomableGroup: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
Geography: ({ children }: { children?: React.ReactNode }) => <g>{children}</g>,
|
||||
Geography: ({ children, ...props }: { children?: React.ReactNode } & Record<string, unknown>) => <g {...props}>{children}</g>,
|
||||
useGeographies: () => ({
|
||||
geographies: [{ rsmKey: "geo-1", id: 840 }],
|
||||
path: { centroid: () => [10, 10] },
|
||||
@@ -37,7 +37,10 @@ describe("WorldMap", () => {
|
||||
// Tooltip should not be present initially
|
||||
expect(screen.queryByRole("tooltip")).toBeNull();
|
||||
|
||||
const countryButton = screen.getByRole("button", { name: /US: 42 bans/i });
|
||||
// Country map area is exposed as an accessible button with an accurate label
|
||||
const countryButton = screen.getByRole("button", { name: "US: 42 bans" });
|
||||
expect(countryButton).toBeInTheDocument();
|
||||
|
||||
fireEvent.mouseEnter(countryButton, { clientX: 10, clientY: 10 });
|
||||
|
||||
const tooltip = screen.getByRole("tooltip");
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* Rows with repeatedly-banned IPs are highlighted in amber.
|
||||
*/
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
@@ -136,6 +136,24 @@ const useStyles = makeStyles({
|
||||
},
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Utilities
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function areHistoryQueriesEqual(
|
||||
a: HistoryQuery,
|
||||
b: HistoryQuery,
|
||||
): boolean {
|
||||
return (
|
||||
a.range === b.range &&
|
||||
a.origin === b.origin &&
|
||||
a.jail === b.jail &&
|
||||
a.ip === b.ip &&
|
||||
a.page === b.page &&
|
||||
a.page_size === b.page_size
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Column definitions for the main history table
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -372,6 +390,7 @@ function IpDetailView({ ip, onBack }: IpDetailViewProps): React.JSX.Element {
|
||||
|
||||
export function HistoryPage(): React.JSX.Element {
|
||||
const styles = useStyles();
|
||||
const cardStyles = useCardStyles();
|
||||
|
||||
// Filter state
|
||||
const [range, setRange] = useState<TimeRange>("24h");
|
||||
@@ -388,15 +407,23 @@ export function HistoryPage(): React.JSX.Element {
|
||||
const { items, total, page, loading, error, setPage, refresh } =
|
||||
useHistory(appliedQuery);
|
||||
|
||||
const applyFilters = useCallback((): void => {
|
||||
setAppliedQuery({
|
||||
range: range,
|
||||
useEffect((): void => {
|
||||
const nextQuery: HistoryQuery = {
|
||||
range,
|
||||
origin: originFilter !== "all" ? originFilter : undefined,
|
||||
jail: jailFilter.trim() || undefined,
|
||||
ip: ipFilter.trim() || undefined,
|
||||
page: 1,
|
||||
page_size: PAGE_SIZE,
|
||||
});
|
||||
}, [range, originFilter, jailFilter, ipFilter]);
|
||||
};
|
||||
|
||||
if (areHistoryQueriesEqual(nextQuery, appliedQuery)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setPage(1);
|
||||
setAppliedQuery(nextQuery);
|
||||
}, [range, originFilter, jailFilter, ipFilter, setPage, appliedQuery]);
|
||||
|
||||
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
|
||||
@@ -458,7 +485,7 @@ export function HistoryPage(): React.JSX.Element {
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className={styles.filterLabel}>
|
||||
<div className={`${styles.filterLabel} ${cardStyles.card}`}>
|
||||
<Text size={200}>Jail</Text>
|
||||
<Input
|
||||
placeholder="e.g. sshd"
|
||||
@@ -470,7 +497,7 @@ export function HistoryPage(): React.JSX.Element {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.filterLabel}>
|
||||
<div className={`${styles.filterLabel} ${cardStyles.card}`}>
|
||||
<Text size={200}>IP Address</Text>
|
||||
<Input
|
||||
placeholder="e.g. 192.168"
|
||||
@@ -479,29 +506,9 @@ export function HistoryPage(): React.JSX.Element {
|
||||
setIpFilter(data.value);
|
||||
}}
|
||||
size="small"
|
||||
onKeyDown={(e): void => {
|
||||
if (e.key === "Enter") applyFilters();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button appearance="primary" size="small" onClick={applyFilters}>
|
||||
Apply
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
appearance="subtle"
|
||||
size="small"
|
||||
onClick={(): void => {
|
||||
setRange("24h");
|
||||
setOriginFilter("all");
|
||||
setJailFilter("");
|
||||
setIpFilter("");
|
||||
setAppliedQuery({ page_size: PAGE_SIZE });
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* ---------------------------------------------------------------- */}
|
||||
|
||||
@@ -25,7 +25,12 @@ import {
|
||||
makeStyles,
|
||||
tokens,
|
||||
} from "@fluentui/react-components";
|
||||
import { ArrowCounterclockwiseRegular, DismissRegular } from "@fluentui/react-icons";
|
||||
import {
|
||||
ArrowCounterclockwiseRegular,
|
||||
ChevronLeftRegular,
|
||||
ChevronRightRegular,
|
||||
DismissRegular,
|
||||
} from "@fluentui/react-icons";
|
||||
import { DashboardFilterBar } from "../components/DashboardFilterBar";
|
||||
import { WorldMap } from "../components/WorldMap";
|
||||
import { useMapData } from "../hooks/useMapData";
|
||||
@@ -68,6 +73,15 @@ const useStyles = makeStyles({
|
||||
borderRadius: tokens.borderRadiusMedium,
|
||||
backgroundColor: tokens.colorNeutralBackground2,
|
||||
},
|
||||
pagination: {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: tokens.spacingHorizontalS,
|
||||
padding: `${tokens.spacingVerticalS} ${tokens.spacingHorizontalM}`,
|
||||
borderTop: `1px solid ${tokens.colorNeutralStroke2}`,
|
||||
backgroundColor: tokens.colorNeutralBackground2,
|
||||
},
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -79,6 +93,10 @@ export function MapPage(): React.JSX.Element {
|
||||
const [range, setRange] = useState<TimeRange>("24h");
|
||||
const [originFilter, setOriginFilter] = useState<BanOriginFilter>("all");
|
||||
const [selectedCountry, setSelectedCountry] = useState<string | null>(null);
|
||||
const [page, setPage] = useState<number>(1);
|
||||
const [pageSize, setPageSize] = useState<number>(100);
|
||||
|
||||
const PAGE_SIZE_OPTIONS = [25, 50, 100] as const;
|
||||
|
||||
const { countries, countryNames, bans, total, loading, error, refresh } =
|
||||
useMapData(range, originFilter);
|
||||
@@ -99,6 +117,10 @@ export function MapPage(): React.JSX.Element {
|
||||
}
|
||||
}, [mapThresholdError]);
|
||||
|
||||
useEffect(() => {
|
||||
setPage(1);
|
||||
}, [range, originFilter, selectedCountry, bans, pageSize]);
|
||||
|
||||
/** Bans visible in the companion table (filtered by selected country). */
|
||||
const visibleBans = useMemo(() => {
|
||||
if (!selectedCountry) return bans;
|
||||
@@ -109,6 +131,15 @@ export function MapPage(): React.JSX.Element {
|
||||
? (countryNames[selectedCountry] ?? selectedCountry)
|
||||
: null;
|
||||
|
||||
const totalPages = Math.max(1, Math.ceil(visibleBans.length / pageSize));
|
||||
const hasPrev = page > 1;
|
||||
const hasNext = page < totalPages;
|
||||
|
||||
const pageBans = useMemo(() => {
|
||||
const start = (page - 1) * pageSize;
|
||||
return visibleBans.slice(start, start + pageSize);
|
||||
}, [visibleBans, page, pageSize]);
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
{/* ---------------------------------------------------------------- */}
|
||||
@@ -235,7 +266,7 @@ export function MapPage(): React.JSX.Element {
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
visibleBans.map((ban) => (
|
||||
pageBans.map((ban) => (
|
||||
<TableRow key={`${ban.ip}-${ban.banned_at}`}>
|
||||
<TableCell>
|
||||
<TableCellLayout>{ban.ip}</TableCellLayout>
|
||||
@@ -282,6 +313,53 @@ export function MapPage(): React.JSX.Element {
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div className={styles.pagination}>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: tokens.spacingHorizontalS }}>
|
||||
<Text size={200} style={{ color: tokens.colorNeutralForeground3 }}>
|
||||
Showing {pageBans.length} of {visibleBans.length} filtered ban{visibleBans.length !== 1 ? "s" : ""}
|
||||
{" · "}Page {page} of {totalPages}
|
||||
</Text>
|
||||
|
||||
<div style={{ display: "flex", alignItems: "center", gap: tokens.spacingHorizontalS }}>
|
||||
<Text size={200} style={{ color: tokens.colorNeutralForeground3 }}>
|
||||
Page size
|
||||
</Text>
|
||||
<select
|
||||
aria-label="Page size"
|
||||
value={pageSize}
|
||||
onChange={(event): void => {
|
||||
setPageSize(Number(event.target.value));
|
||||
}}
|
||||
>
|
||||
{PAGE_SIZE_OPTIONS.map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: tokens.spacingHorizontalXS }}>
|
||||
<Button
|
||||
icon={<ChevronLeftRegular />}
|
||||
appearance="subtle"
|
||||
disabled={!hasPrev}
|
||||
onClick={(): void => {
|
||||
setPage(page - 1);
|
||||
}}
|
||||
aria-label="Previous page"
|
||||
/>
|
||||
<Button
|
||||
icon={<ChevronRightRegular />}
|
||||
appearance="subtle"
|
||||
disabled={!hasNext}
|
||||
onClick={(): void => {
|
||||
setPage(page + 1);
|
||||
}}
|
||||
aria-label="Next page"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
|
||||
import { HistoryPage } from "../HistoryPage";
|
||||
|
||||
let lastQuery: Record<string, unknown> | null = null;
|
||||
const mockUseHistory = vi.fn((query: Record<string, unknown>) => {
|
||||
console.log("mockUseHistory called", query);
|
||||
lastQuery = query;
|
||||
return {
|
||||
items: [],
|
||||
@@ -18,16 +18,16 @@ const mockUseHistory = vi.fn((query: Record<string, unknown>) => {
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../hooks/useHistory", () => ({
|
||||
vi.mock("../../hooks/useHistory", () => ({
|
||||
useHistory: (query: Record<string, unknown>) => mockUseHistory(query),
|
||||
useIpHistory: () => ({ detail: null, loading: false, error: null, refresh: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("../components/WorldMap", () => ({
|
||||
vi.mock("../../components/WorldMap", () => ({
|
||||
WorldMap: () => <div data-testid="world-map" />,
|
||||
}));
|
||||
|
||||
vi.mock("../api/config", () => ({
|
||||
vi.mock("../../api/config", () => ({
|
||||
fetchMapColorThresholds: async () => ({
|
||||
threshold_low: 10,
|
||||
threshold_medium: 50,
|
||||
@@ -35,8 +35,10 @@ vi.mock("../api/config", () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
import { HistoryPage } from "../HistoryPage";
|
||||
|
||||
describe("HistoryPage", () => {
|
||||
it("renders DashboardFilterBar and applies origin+range filters", async () => {
|
||||
it("auto-applies filters on change and hides apply/clear actions", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
@@ -45,14 +47,30 @@ describe("HistoryPage", () => {
|
||||
</FluentProvider>,
|
||||
);
|
||||
|
||||
// Initial load should include the default query.
|
||||
expect(lastQuery).toEqual({ page_size: 50 });
|
||||
// Initial load should include the auto-applied default query.
|
||||
await waitFor(() => {
|
||||
expect(lastQuery).toEqual({
|
||||
range: "24h",
|
||||
origin: undefined,
|
||||
jail: undefined,
|
||||
ip: undefined,
|
||||
page: 1,
|
||||
page_size: 50,
|
||||
});
|
||||
});
|
||||
|
||||
// Change the time-range and origin filter, then apply.
|
||||
expect(screen.queryByRole("button", { name: /apply/i })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: /clear/i })).toBeNull();
|
||||
|
||||
// Time-range and origin updates should be applied automatically.
|
||||
await user.click(screen.getByRole("button", { name: /Last 7 days/i }));
|
||||
await user.click(screen.getByRole("button", { name: /Blocklist/i }));
|
||||
await user.click(screen.getByRole("button", { name: /Apply/i }));
|
||||
await waitFor(() => {
|
||||
expect(lastQuery).toMatchObject({ range: "7d" });
|
||||
});
|
||||
|
||||
expect(lastQuery).toMatchObject({ range: "7d", origin: "blocklist" });
|
||||
await user.click(screen.getByRole("button", { name: /Blocklist/i }));
|
||||
await waitFor(() => {
|
||||
expect(lastQuery).toMatchObject({ origin: "blocklist" });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,42 +2,43 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
|
||||
import { getLastArgs, setMapData } from "../../hooks/useMapData";
|
||||
import { MapPage } from "../MapPage";
|
||||
|
||||
const mockFetchMapColorThresholds = vi.fn(async () => ({
|
||||
threshold_low: 10,
|
||||
threshold_medium: 50,
|
||||
threshold_high: 100,
|
||||
}));
|
||||
|
||||
let lastArgs: { range: string; origin: string } = { range: "", origin: "" };
|
||||
const mockUseMapData = vi.fn((range: string, origin: string) => {
|
||||
lastArgs = { range, origin };
|
||||
return {
|
||||
vi.mock("../../hooks/useMapData", () => {
|
||||
let lastArgs: { range: string; origin: string } = { range: "", origin: "" };
|
||||
let dataState = {
|
||||
countries: {},
|
||||
countryNames: {},
|
||||
bans: [],
|
||||
total: 0,
|
||||
loading: false,
|
||||
error: null,
|
||||
refresh: vi.fn(),
|
||||
refresh: () => {},
|
||||
};
|
||||
|
||||
return {
|
||||
useMapData: (range: string, origin: string) => {
|
||||
lastArgs = { range, origin };
|
||||
return { ...dataState };
|
||||
},
|
||||
setMapData: (newState: Partial<typeof dataState>) => {
|
||||
dataState = { ...dataState, ...newState };
|
||||
},
|
||||
getLastArgs: () => lastArgs,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../hooks/useMapData", () => ({
|
||||
useMapData: (range: string, origin: string) => mockUseMapData(range, origin),
|
||||
vi.mock("../../api/config", () => ({
|
||||
fetchMapColorThresholds: vi.fn(async () => ({
|
||||
threshold_low: 10,
|
||||
threshold_medium: 50,
|
||||
threshold_high: 100,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../api/config", async () => ({
|
||||
fetchMapColorThresholds: mockFetchMapColorThresholds,
|
||||
}));
|
||||
|
||||
const mockWorldMap = vi.fn((_props: unknown) => <div data-testid="world-map" />);
|
||||
vi.mock("../components/WorldMap", () => ({
|
||||
WorldMap: (props: unknown) => {
|
||||
mockWorldMap(props);
|
||||
return <div data-testid="world-map" />;
|
||||
},
|
||||
vi.mock("../../components/WorldMap", () => ({
|
||||
WorldMap: () => <div data-testid="world-map" />,
|
||||
}));
|
||||
|
||||
describe("MapPage", () => {
|
||||
@@ -51,17 +52,63 @@ describe("MapPage", () => {
|
||||
);
|
||||
|
||||
// Initial load should call useMapData with default filters.
|
||||
expect(lastArgs).toEqual({ range: "24h", origin: "all" });
|
||||
|
||||
// Map should receive country names from the hook so tooltips can show human-readable labels.
|
||||
expect(mockWorldMap).toHaveBeenCalled();
|
||||
const firstCallArgs = mockWorldMap.mock.calls[0]?.[0];
|
||||
expect(firstCallArgs).toMatchObject({ countryNames: {} });
|
||||
expect(getLastArgs()).toEqual({ range: "24h", origin: "all" });
|
||||
|
||||
await user.click(screen.getByRole("button", { name: /Last 7 days/i }));
|
||||
expect(lastArgs.range).toBe("7d");
|
||||
expect(getLastArgs().range).toBe("7d");
|
||||
|
||||
await user.click(screen.getByRole("button", { name: /Blocklist/i }));
|
||||
expect(lastArgs.origin).toBe("blocklist");
|
||||
expect(getLastArgs().origin).toBe("blocklist");
|
||||
});
|
||||
|
||||
it("supports pagination with 100 items per page and reset on filter changes", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const bans = Array.from({ length: 120 }, (_, index) => ({
|
||||
ip: `192.0.2.${index}`,
|
||||
jail: "ssh",
|
||||
banned_at: new Date(Date.now() - index * 1000).toISOString(),
|
||||
service: null,
|
||||
country_code: "US",
|
||||
country_name: "United States",
|
||||
asn: null,
|
||||
org: null,
|
||||
ban_count: 1,
|
||||
origin: "selfblock",
|
||||
}));
|
||||
|
||||
setMapData({
|
||||
countries: { US: 120 },
|
||||
countryNames: { US: "United States" },
|
||||
bans,
|
||||
total: 120,
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
render(
|
||||
<FluentProvider theme={webLightTheme}>
|
||||
<MapPage />
|
||||
</FluentProvider>,
|
||||
);
|
||||
|
||||
expect(await screen.findByText(/Page 1 of 2/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Showing 100 of 120 filtered bans/i)).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole("button", { name: /Next page/i }));
|
||||
expect(await screen.findByText(/Page 2 of 2/i)).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole("button", { name: /Previous page/i }));
|
||||
expect(await screen.findByText(/Page 1 of 2/i)).toBeInTheDocument();
|
||||
|
||||
// Page size selector should adjust pagination
|
||||
await user.selectOptions(screen.getByRole("combobox", { name: /Page size/i }), "25");
|
||||
expect(await screen.findByText(/Page 1 of 5/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Showing 25 of 120 filtered bans/i)).toBeInTheDocument();
|
||||
|
||||
// Changing filter keeps page reset to 1
|
||||
await user.click(screen.getByRole("button", { name: /Blocklist/i }));
|
||||
expect(getLastArgs().origin).toBe("blocklist");
|
||||
expect(await screen.findByText(/Page 1 of 5/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user