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.
This commit is contained in:
Zakk committed 2026-09-29 07:53:04 +10:00
1 parent 0cf09d0582
commit aec2ebae90
15 files changed
+115 -13

No files matched your search

+6 -4
View File
@@ -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');
+29
View File
@@ -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$/);
});
+9 -1
View File
@@ -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();
});
+2
View File
@@ -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;
+1
View File
@@ -116,6 +116,7 @@ export function Connections(props: PageProps) {
{vm.ruleAction.canShow && <Button onPress={() => vm.showRule()}>{t('conn.showRule')}</Button>}
{vm.ruleAction.canEdit && <Button onPress={() => vm.showRule(true)}>{t('conn.editRule')}</Button>}
{vm.canViewFlow && <Button onPress={vm.showFlow}>{t('conn.viewFlow')}</Button>}
{vm.canTrace && <Button onPress={vm.traceConnection}>{t('conn.trace')}</Button>}
{cur.source && <Button onPress={vm.onlyClient}>{t('conn.onlyThisClient')}</Button>}
</div>
{vm.canClose && cur.closable && (
@@ -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);
},
+4
View File
@@ -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'));
});
+13 -1
View File
@@ -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<Connection['observed_by'], Key> = {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)
+1 -1
View File
@@ -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: <RuleList {...props} />,
dns: <DnsRules {...props} />,
+13 -5
View File
@@ -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<TraceResolve, Key> = {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<typeof useTraceForm>, go: PageProps['go']) {
+11 -1
View File
@@ -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();
});
+19
View File
@@ -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<TraceLink>) => 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'});
+1
View File
@@ -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",
+1
View File
@@ -393,6 +393,7 @@
"conn.stateHelp.routing": "正在匹配路由规则。",
"conn.tab.list": "连接",
"conn.tab.traffic": "流量",
"conn.trace": "追踪此连接",
"conn.truncated": "连接列表已截断,仅显示部分记录。",
"conn.ungrouped": "不分组",
"conn.viewFlow": "查看流程",
+1
View File
@@ -393,6 +393,7 @@
"conn.stateHelp.routing": "正在比對路由規則。",
"conn.tab.list": "連線",
"conn.tab.traffic": "流量",
"conn.trace": "追蹤此連線",
"conn.truncated": "連線清單已截斷,僅顯示部分記錄。",
"conn.ungrouped": "不分組",
"conn.viewFlow": "查看流程",