From aec2ebae90b42fcf080b177545e82bf0391f7a8d Mon Sep 17 00:00:00 2001 From: Zakk Date: Tue, 29 Sep 2026 06:39:19 +1000 Subject: [PATCH] feat(rules): prefill the trace from a link and trace a connection The trace tab reads its target, port, network and source IP from the address, so a link fills the form in; the person still runs it. The connection detail opens it for the shown connection. --- e2e/connection-rule.spec.ts | 10 ++++--- e2e/trace-links.spec.ts | 29 +++++++++++++++++++ src/api/selectors.test.ts | 10 ++++++- src/api/selectors.ts | 2 ++ src/features/connections/Connections.tsx | 1 + .../connections/useConnectionsPage.ts | 4 +++ src/features/connections/view.test.ts | 4 +++ src/features/connections/view.ts | 14 ++++++++- src/features/rules/Rules.tsx | 2 +- src/features/rules/useRoutingTrace.ts | 18 ++++++++---- src/features/shared/link.test.ts | 12 +++++++- src/features/shared/link.ts | 19 ++++++++++++ src/i18n/locales/en.json | 1 + src/i18n/locales/zh-CN.json | 1 + src/i18n/locales/zh-TW.json | 1 + 15 files changed, 115 insertions(+), 13 deletions(-) create mode 100644 e2e/trace-links.spec.ts diff --git a/e2e/connection-rule.spec.ts b/e2e/connection-rule.spec.ts index ef2517e0..27d6f873 100644 --- a/e2e/connection-rule.spec.ts +++ b/e2e/connection-rule.spec.ts @@ -112,12 +112,14 @@ for (const width of [360, 768, 1440]) const close = detail(page).getByRole('button', {name: 'Close connection', exact: true}); await expect(close).toBeVisible(); const boxes = await detail(page) - .getByRole('button', {name: /^(Add rule|Show matched rule|Edit matched rule's outbound settings|View flow|Only this device|Close connection)$/}) + .getByRole('button', { + name: /^(Add rule|Show matched rule|Edit matched rule's outbound settings|View flow|Trace this connection|Only this device|Close connection)$/ + }) .evaluateAll(buttons => buttons.map(button => button.getBoundingClientRect().toJSON() as DOMRect)); - expect(boxes).toHaveLength(6); + expect(boxes).toHaveLength(7); // One button style: a quiet button beside a filled one reads as a misaligned label. const fills = await detail(page) - .getByRole('button', {name: /^(Add rule|Show matched rule|Edit matched rule's outbound settings|View flow|Only this device)$/}) + .getByRole('button', {name: /^(Add rule|Show matched rule|Edit matched rule's outbound settings|View flow|Trace this connection|Only this device)$/}) .evaluateAll(buttons => buttons.map(button => getComputedStyle(button).backgroundColor)); expect(new Set(fills).size).toBe(1); expect(new Set(boxes.map(box => box.height)).size).toBe(1); @@ -132,7 +134,7 @@ for (const width of [360, 768, 1440]) for (const gap of [...gaps, ...leading]) expect(Math.abs(gap - gaps[0])).toBeLessThanOrEqual(1); expect(lines.every(line => Math.abs(line[0].left - boxes[0].left) <= 1)).toBe(true); // The destructive action ends the group on a line of its own. - expect(lines.at(-1)).toEqual([boxes[5]]); + expect(lines.at(-1)).toEqual([boxes[6]]); }); const top = (page: import('@playwright/test').Page) => page.locator('.rp-top'); diff --git a/e2e/trace-links.spec.ts b/e2e/trace-links.spec.ts new file mode 100644 index 00000000..4cacd243 --- /dev/null +++ b/e2e/trace-links.spec.ts @@ -0,0 +1,29 @@ +import {detail, expect, test} from './fixtures'; + +test.use({viewport: {width: 1440, height: 900}}); + +test('a trace link fills in the form without running it', async ({page}) => { + let traced = false; + page.on('request', request => { + if (request.url().includes('/routing/trace')) traced = true; + }); + await page.goto('/#/rules?tab=trace&domain=example.com&dst_port=443&src_ip=10.0.0.2'); + await expect(page.getByLabel('Domain', {exact: true})).toHaveValue('example.com'); + await expect(page.getByLabel('Destination port', {exact: true})).toHaveValue('443'); + // The source sits under the advanced fields, which open to show it. + await expect(page.getByLabel('Source IP', {exact: true})).toHaveValue('10.0.0.2'); + await expect(page.getByRole('button', {name: 'Run trace', exact: true})).toBeEnabled(); + expect(traced).toBe(false); +}); + +test('a connection opens the trace of its target and source', async ({page}) => { + await page.goto('/#/connections?tab=list&id=1'); + await detail(page).getByRole('button', {name: 'Trace this connection', exact: true}).click(); + await expect(page).toHaveURL(/#\/rules\?tab=trace&network=tcp&domain=api\.telegram\.org&dst_ip=149\.154\.167\.220&dst_port=443&src_ip=10\.0\.0\.12$/); + await expect(page.getByLabel('Domain', {exact: true})).toHaveValue('api.telegram.org'); + await expect(page.getByLabel('Destination IP', {exact: true})).toHaveValue('149.154.167.220'); + await expect(page.getByLabel('Source IP', {exact: true})).toHaveValue('10.0.0.12'); + // The link pushed history: Back returns to the connection. + await page.goBack(); + await expect(page).toHaveURL(/#\/connections\?tab=list&id=1$/); +}); diff --git a/src/api/selectors.test.ts b/src/api/selectors.test.ts index a45b03b8..2f61b3c3 100644 --- a/src/api/selectors.test.ts +++ b/src/api/selectors.test.ts @@ -1,6 +1,6 @@ import {expect, it} from 'vitest'; import type {ApiEvent, GroupSummary} from './model'; -import {eventSummary, memoryTone, nodeOwner, resolveSelectedLeaf, routineGap, shortId} from './selectors'; +import {addressPort, eventSummary, memoryTone, nodeOwner, resolveSelectedLeaf, routineGap, shortId} from './selectors'; import {formatNumber, LOCALE, readLang, translate} from '../i18n'; import {createMockApi} from './mock'; @@ -82,3 +82,11 @@ it('files a node under its provider, or under the built-in or unattributed owner it('tones memory use by its share of the limit', () => { expect([0, 75, 75.5, 90, 90.5].map(memoryTone)).toEqual(['ok', 'ok', 'warn', 'warn', 'err']); }); + +it('reads the port of an address, including a bracketed IPv6 one', () => { + expect(addressPort('149.154.167.220:443')).toBe('443'); + expect(addressPort('[2001:db8::1]:8443')).toBe('8443'); + expect(addressPort('2001:db8::1')).toBeUndefined(); + expect(addressPort('10.0.0.2')).toBeUndefined(); + expect(addressPort(undefined)).toBeUndefined(); +}); diff --git a/src/api/selectors.ts b/src/api/selectors.ts index a7bb1e95..0db44f01 100644 --- a/src/api/selectors.ts +++ b/src/api/selectors.ts @@ -94,6 +94,8 @@ export function sourceIp(src: string | undefined): string | undefined { if (!src) return undefined; return ipLiteral(src.startsWith('[') ? src.slice(1, src.indexOf(']')) : src.split(':').length === 2 ? src.split(':')[0] : src); } +// The port of an `ip:port` or `[ipv6]:port` address; a bare address has none. +export const addressPort = (address: string | undefined) => address?.match(/^(?:\[[^\]]+\]|[^:]+):(\d+)$/)?.[1]; export function outboundLabel(name: string | null, label: LabelFn): string { return name === 'direct' ? label('ui.direct') : name === 'block' ? label('ui.block') : name === null || name === 'unknown' ? label('ui.unknown') : name; diff --git a/src/features/connections/Connections.tsx b/src/features/connections/Connections.tsx index f0f0f37a..b33430ff 100644 --- a/src/features/connections/Connections.tsx +++ b/src/features/connections/Connections.tsx @@ -116,6 +116,7 @@ export function Connections(props: PageProps) { {vm.ruleAction.canShow && } {vm.ruleAction.canEdit && } {vm.canViewFlow && } + {vm.canTrace && } {cur.source && } {vm.canClose && cur.closable && ( diff --git a/src/features/connections/useConnectionsPage.ts b/src/features/connections/useConnectionsPage.ts index 84468d2a..da4b4888 100644 --- a/src/features/connections/useConnectionsPage.ts +++ b/src/features/connections/useConnectionsPage.ts @@ -254,6 +254,10 @@ export function useConnectionsPage({go, query}: PageProps) { showRule: (edit = false) => { if (cur?.rule_id) go('rules', within('', {tab: 'list', rule: cur.rule_id, edit: edit ? cur.rule_id : null})); }, + canTrace: offered(capabilities.data?.resources, 'routing_trace', {whileLoading: false}) && !!model.detail?.traceQuery, + traceConnection: () => { + if (model.detail?.traceQuery) go('rules', model.detail.traceQuery); + }, showFlow: () => { if (model.detail && canViewFlow) go('flows', model.detail.flowQuery); }, diff --git a/src/features/connections/view.test.ts b/src/features/connections/view.test.ts index 63c76461..11b176d4 100644 --- a/src/features/connections/view.test.ts +++ b/src/features/connections/view.test.ts @@ -263,6 +263,10 @@ it('prepares fallback flow links and exports only visible raw counters', () => { const row = {...connections.tcp[0], network: 'tcp', id: 'a/b', flow_id: null, download_bytes: '9007199254740993'}; const model = connectionsView([row], {...connections, visibility: 'partial'}, undefined, 'all', 'all', 'en-US', t); expect(connectionDetail(row, 'en-US', t, new Map(), false)?.flowQuery).toBe('tab=records&connection_id=a%2Fb'); + expect( + connectionDetail({...row, domain: 'example.com', dst: '[2001:db8::1]:443', src: '10.0.0.2:5353', network: 'udp'}, 'en-US', t, new Map(), false)?.traceQuery + ).toBe('tab=trace&network=udp&domain=example.com&dst_ip=2001%3Adb8%3A%3A1&dst_port=443&src_ip=10.0.0.2'); + expect(connectionDetail({...row, domain: null, dst: undefined}, 'en-US', t, new Map(), false)?.traceQuery).toBeNull(); expect(connectionsExport([row], new Map())).toContain('9007199254740993'); expect(model.visibility).toBe(t('conn.visibilityPartial')); }); diff --git a/src/features/connections/view.ts b/src/features/connections/view.ts index 39fe167e..774150bc 100644 --- a/src/features/connections/view.ts +++ b/src/features/connections/view.ts @@ -12,6 +12,7 @@ import { nodeLabel, outboundLabel, sourceIp, + addressPort, type MessageRef, type OutboundNames } from '../../api/selectors'; @@ -22,7 +23,7 @@ import type {Key} from '../../i18n'; import type {SortDescriptor} from 'react-aria-components'; import type {Help} from '../../ui/ui'; import {csvLine} from '../../ui/ui'; -import {ruleHref} from '../shared/link'; +import {ruleHref, traceQuery} from '../shared/link'; import {within} from '../../shell/route'; const observers: Record = {userspace: 'conn.observed.userspace', ebpf: 'conn.observed.ebpf', mixed: 'conn.observed.mixed'}; // Where the chain came from: captured when the connection was routed, rebuilt from retained records, or not known. @@ -346,6 +347,17 @@ export function connectionDetail( ([key, value]) => [t(key), typeof value === 'string' ? value : t(value.key, value.params)] as [string, string] ), flowQuery: within('', {tab: 'records', ...(current.flow_id ? {id: current.flow_id} : {connection_id: current.id})}), + // The trace of this connection's target, from its source; null when it has neither a domain nor an address. + traceQuery: + current.domain || sourceIp(current.dst) + ? traceQuery({ + network: current.network === 'udp' ? 'udp' : 'tcp', + domain: current.domain ?? '', + dst_ip: sourceIp(current.dst), + dst_port: addressPort(current.dst), + src_ip: sourceIp(current.src) + }) + : null, source: current.src ? (sourceIp(current.src) ?? current.src) : null, closable: current.state === 'active' || current.state === 'dialing' || current.state === 'routing', stateHelp: connectionStateHelp(current.state, t) diff --git a/src/features/rules/Rules.tsx b/src/features/rules/Rules.tsx index 39970235..6ed1ebb5 100644 --- a/src/features/rules/Rules.tsx +++ b/src/features/rules/Rules.tsx @@ -28,7 +28,7 @@ import type {EvaluationView} from './view'; export function Rules(props: PageProps) { const t = useT(); const view = useRulesPage(props); - const traceForm = useTraceForm(); + const traceForm = useTraceForm(props.query); const content = { list: , dns: , diff --git a/src/features/rules/useRoutingTrace.ts b/src/features/rules/useRoutingTrace.ts index c1c77043..2bc7c101 100644 --- a/src/features/rules/useRoutingTrace.ts +++ b/src/features/rules/useRoutingTrace.ts @@ -10,13 +10,14 @@ import {queryTypes, useGroups, useNodeProbe, useNodes, useRules} from '../../sto import {ipLiteral, resolveSelectedLeaf} from '../../api/selectors'; import {isPort} from '../../dae/setup'; import {useLang, useT} from '../../i18n'; -import {toast, toastFailure} from '../../ui/ui'; +import {toast, toastFailure, useLinked} from '../../ui/ui'; import {dnsView, evaluationView, queryView, traceReason, traceSeed, traceStatusView} from './view'; import {probeToast} from '../shared/probe'; import {errorText} from '../../api/error'; import {offered} from '../../api/capabilities'; import type {PageProps} from '../../shell/routes'; import {useQuickRule} from '../shared/useQuickRule'; +import {parseTraceLink} from '../shared/link'; type TraceProblem = {field: 'domain' | 'dst_ip' | 'dst_port' | 'src_ip' | 'src_port'; key: Key}; export type TraceResolve = 'none' | 'live' | 'query'; const resolveLabels: Record = {none: 'rule.resolveNone', live: 'rule.resolveLive', query: 'rule.resolveQuery'}; @@ -31,10 +32,17 @@ const blankForm = { // Null until the backend says what it offers: live when it can resolve, else none. resolve: null as TraceResolve | null }; -// Held by the rules page rather than the trace tab, so what was typed survives a tab switch. -export function useTraceForm() { - const [form, setForm] = useState(blankForm); - const [advanced, setAdvanced] = useState(false); +// Held by the rules page rather than the trace tab, so what was typed survives a tab switch. A link that names a +// target fills the form in, opening the advanced fields when it names the source; it does not run the trace. +export function useTraceForm(query: string) { + const linked = useMemo(() => parseTraceLink(query), [query]); + const [form, setForm] = useState(() => (linked ? {...blankForm, ...linked} : blankForm)); + const [advanced, setAdvanced] = useState(!!linked?.src_ip); + useLinked(linked && JSON.stringify(linked), () => { + if (!linked) return; + setForm({...blankForm, ...linked}); + setAdvanced(!!linked.src_ip); + }); return {form, setForm, advanced, setAdvanced}; } export function useRoutingTrace({form, setForm, advanced, setAdvanced}: ReturnType, go: PageProps['go']) { diff --git a/src/features/shared/link.test.ts b/src/features/shared/link.test.ts index 22cd2cee..5bd32bdb 100644 --- a/src/features/shared/link.test.ts +++ b/src/features/shared/link.test.ts @@ -1,6 +1,6 @@ import {expect, it} from 'vitest'; import type {ConfigSource} from '../../api/model'; -import {groupQuery, nodeHref, parseRuleSeed, ruleSeedHref, sectionSourceHref} from './link'; +import {groupQuery, nodeHref, parseRuleSeed, parseTraceLink, ruleSeedHref, sectionSourceHref, traceQuery} from './link'; it('round trips IPv6 and reserved URL characters without reinterpreting the condition kind', () => { for (const seed of [ @@ -60,3 +60,13 @@ it('focuses a group by its backend id, and opens the page unfocused before the l expect(groupQuery(groups, 'new')).toBe(''); expect(groupQuery(undefined, 'proxy')).toBe(''); }); + +it('carries a trace target and source through the address and back', () => { + const link = {network: 'udp', domain: 'example.com', dst_ip: '2001:db8::1', dst_port: '443', src_ip: '10.0.0.2'} as const; + expect(parseTraceLink(traceQuery(link))).toEqual(link); + // Empty values stay out of the address; a missing network is TCP. + expect(traceQuery({dst_ip: '1.1.1.1', domain: '', dst_port: '53'})).toBe('tab=trace&dst_ip=1.1.1.1&dst_port=53'); + expect(parseTraceLink('tab=trace&dst_ip=1.1.1.1')).toEqual({network: 'tcp', domain: '', dst_ip: '1.1.1.1', dst_port: '', src_ip: ''}); + expect(parseTraceLink('tab=trace&src_ip=10.0.0.2')).toBeNull(); + expect(parseTraceLink('tab=trace')).toBeNull(); +}); diff --git a/src/features/shared/link.ts b/src/features/shared/link.ts index fcd3eff8..a44c59fd 100644 --- a/src/features/shared/link.ts +++ b/src/features/shared/link.ts @@ -19,6 +19,25 @@ export function groupQuery(groups: ReadonlyArray<{id: string; name: string}> | u return id ? within('', {group: id}) : ''; } +// The routing trace with its form filled in from a link: the target, and the source when the link knows it. The person +// runs the trace. +export type TraceLink = {network: 'tcp' | 'udp'; domain: string; dst_ip: string; dst_port: string; src_ip: string}; +const traceKeys = ['network', 'domain', 'dst_ip', 'dst_port', 'src_ip'] as const; +export const traceQuery = (link: Partial) => within('', {tab: 'trace', ...Object.fromEntries(traceKeys.map(key => [key, link[key] || null]))}); +// Null when the link names no target, so a plain visit to the tab keeps what was typed. +export function parseTraceLink(query: string): TraceLink | null { + const params = new URLSearchParams(query); + const value = (key: (typeof traceKeys)[number]) => params.get(key) ?? ''; + if (!value('domain') && !value('dst_ip')) return null; + return { + network: value('network') === 'udp' ? 'udp' : 'tcp', + domain: value('domain'), + dst_ip: value('dst_ip'), + dst_port: value('dst_port'), + src_ip: value('src_ip') + }; +} + // The Settings card holding what the backend records and keeps: log level, flow and DNS recording, retention. export const recordingSettingsHref = href('settings', {card: 'runtime'}); diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 805bc610..5d8b79c7 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -471,6 +471,7 @@ "conn.stateHelp.routing": "Matching the routing rules.", "conn.tab.list": "Connections", "conn.tab.traffic": "Traffic", + "conn.trace": "Trace this connection", "conn.truncated": "The connection list is truncated; only some records are shown.", "conn.ungrouped": "None", "conn.viewFlow": "View flow", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index e0857b5d..a1826618 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -393,6 +393,7 @@ "conn.stateHelp.routing": "正在匹配路由规则。", "conn.tab.list": "连接", "conn.tab.traffic": "流量", + "conn.trace": "追踪此连接", "conn.truncated": "连接列表已截断,仅显示部分记录。", "conn.ungrouped": "不分组", "conn.viewFlow": "查看流程", diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json index f57f2005..a0dae6c2 100644 --- a/src/i18n/locales/zh-TW.json +++ b/src/i18n/locales/zh-TW.json @@ -393,6 +393,7 @@ "conn.stateHelp.routing": "正在比對路由規則。", "conn.tab.list": "連線", "conn.tab.traffic": "流量", + "conn.trace": "追蹤此連線", "conn.truncated": "連線清單已截斷,僅顯示部分記錄。", "conn.ungrouped": "不分組", "conn.viewFlow": "查看流程",