Skip to content

Destination audit

Source files: 36 · checked against Etemenanki 46c12e4 · katana v6.1.0
  • Etemenanki/environment/src/routing.rs
  • Etemenanki/environment/tests/unit/routing.rs
  • Etemenanki/supervisor/src/supervisor.rs
  • Etemenanki/supervisor/src/track/mod.rs
  • Etemenanki/supervisor/src/connector.rs
  • Etemenanki/supervisor/src/topology/router.rs
  • Etemenanki/supervisor/src/topology/plane.rs
  • Etemenanki/supervisor/src/topology/flow.rs
  • Etemenanki/supervisor/src/topology/outbound/mod.rs
  • Etemenanki/supervisor/src/topology/outbound/proxy.rs
  • Etemenanki/supervisor/src/topology/outbound/udp_fanout.rs
  • Etemenanki/supervisor/src/topology/spec_plan/dns.rs
  • Etemenanki/supervisor/src/build/apply.rs
  • Etemenanki/supervisor/src/policy.rs
  • Etemenanki/supervisor/tests/tracking.rs
  • Etemenanki/protocols/src/flow.rs
  • Etemenanki/protocols/src/sniff/mod.rs
  • Etemenanki/app/tests/integration/e2e_udp_route.rs
  • katana/src/rule.rs
  • katana/src/api/mod.rs
  • katana/src/api/newv2board.rs
  • katana/src/api/helium.rs
  • katana/src/lower/mod.rs
  • katana/src/lower/inbound.rs
  • katana/src/lower/outbound.rs
  • katana/src/lower/route.rs
  • katana/src/manager/node.rs
  • katana/src/config.rs
  • katana/src/runtime.rs
  • katana/tests/unit/rule.rs
  • katana/tests/unit/lower/spec.rs
  • katana/tests/unit/runtime.rs
  • katana/tests/unit/api/newv2board.rs
  • katana/tests/unit/api/helium.rs
  • katana/tests/integration/sniff.rs
  • katana/tests/support/mod.rs

Destination audit lets a panel, or a local file, forbid destinations by regular expression. Since katana 4 the audit is part of routing. src/rule.rs turns each rule id into a blackhole outbound tagged audit#<id> and a route toward it, and the lowering puts those routes at the head of the node’s route table. The supervisor (the kernel’s run-time manager) matches them like any other route. katana records no hit and reports none: katana 6 removed the hit ledger and the illegal-access report along with SSPanel, the only panel that took one (see Upgrading to katana 6).

This page is for contributors who change src/rule.rs, the way the panel clients build their rule lists, or the audit parts of src/manager/node.rs. It covers where rules come from, how they are lowered, what they match, what a match does to the flow, and what happens when the rules change. The lowering of the rest of a node is on Lowering a node, and the operator’s view is on the destination audit guide.

Piece File → symbol Job
Rule sources src/api/newv2board.rs → detect_rules (for the newV2board client’s node_rule), src/api/helium.rs → Client::node_rule, src/api/mod.rs → read_local_rules Build the node’s ordered list of DetectRules: the local file first, then the newV2board node config’s block routes (helium sends none)
Refresh src/manager/node.rs → NodeManager::refresh_rules Ask the panel client for the list at bootstrap and in every poll, unless disable_get_rule is set
Rule store src/rule.rs → RuleManager Hold the list in force; replace it only when ids or pattern text changed
Lowering src/rule.rs → audit_routes, called by src/lower/mod.rs → shared_spec One blackhole OutboundSpec and one RouteRuleSpec per rule id, spliced in front of [node.route]
Tag reservation src/rule.rs → AUDIT_TAG_PREFIX, checked by src/lower/outbound.rs → lower_outbounds Refuse an [[outbound]] whose tag starts with audit#
Matching and blocking Etemenanki: supervisor/src/topology/router.rs, environment/src/routing.rs, supervisor/src/topology/outbound/ Done by the supervisor’s route table and its Blackhole outbound; katana adds no check of its own

katana does not:

  • test any destination itself. The route table decides;
  • record, count or log a match. Nothing in katana reads the flows an audit route catches, and no log line names the user or the rule;
  • report matches to any panel. Neither newV2board nor helium takes such a report.

The 3.x pipeline checked each flow in katana’s own connector. That code is gone, and each part of it now lives in other code:

katana 3.0.1 katana 4 and later
RuleManager::detect, called through Dispatcher::forbidden in src/connector.rs A RouteMatch::DomainRegex route per rule id, built by src/rule.rs → audit_routes and matched by the supervisor’s route table (Routing plane)
dest_string in katana’s connector supervisor/src/topology/router.rs → route_target passes the requested and the sniffed name, and environment/src/routing.rs → Domains::of lower-cases them
refused() in katana’s connector The supervisor’s Blackhole outbound, supervisor/src/topology/outbound/ (Outbounds)
The hit recorded inside detect, on the connecting task No hit is recorded. katana 4 and 5 read hits back from FlowEvent::Opened for SSPanel’s illegal-access report; katana 6 removed both
One RuleManager per NodeManager, its rules and hits held in maps keyed by the node tag One RuleManager per NodeManager, holding one list with no tag key
Rules refreshed after the reconcile of a poll Rules refreshed before the reconcile, so a changed list is lowered in the same poll

What these moves change for matching and blocking is listed under Changes from 3.x.

src/rule.rs
pub const AUDIT_TAG_PREFIX: &str = "audit#";
pub fn audit_tag(id: i64) -> CompactString;
pub fn audit_routes(rules: &[DetectRule]) -> (Vec<OutboundSpec>, Vec<RouteRuleSpec>);
#[derive(Default)]
pub struct RuleManager {
rules: Mutex<Arc<[DetectRule]>>,
}
impl RuleManager {
pub fn new() -> Self;
pub fn update(&self, rules: Vec<DetectRule>) -> bool;
pub fn rules(&self) -> Arc<[DetectRule]>;
}
Item Behaviour
AUDIT_TAG_PREFIX "audit#". Every audit outbound’s tag starts with it, and no [[outbound]] may.
audit_tag(id) format_compact!("{AUDIT_TAG_PREFIX}{id}"), so rule 7 is audit#7 and a local rule is audit#-1.
audit_routes(rules) One blackhole outbound and one route per distinct rule id, in the order the ids first appear. See Lowering rules into routes.
RuleManager::update(rules) Compares the new list with the one in force, element by element and in order, on id and on the pattern’s source text (Regex::as_str), because regex::Regex has no Eq. Returns false and keeps the old Arc when they are the same; otherwise stores the new list and returns true.
RuleManager::rules() A clone of the Arc<[DetectRule]> in force. The lowering reads the rules through it.

The mutex is a parking_lot::Mutex, held only for one clone or comparison, never across an .await. Only the node’s own task touches it: the poll and config-edit paths replace and read rules. RuleManager derives Default, and new() returns the default: no rules.

src/api/mod.rs
#[derive(Debug, Clone)]
pub struct DetectRule {
pub id: i64,
pub pattern: Regex,
}
#[derive(Debug, Clone)]
pub struct RouteRule {
pub match_: Vec<String>,
pub action: String,
}
pub fn read_local_rules(path: &str) -> Vec<DetectRule>;
impl PanelClient {
pub async fn node_rule(&self) -> Result<Option<Vec<DetectRule>>>;
pub fn inherit_routes(&self, old: &PanelClient);
}
  • DetectRule.pattern is a regex::Regex compiled with default flags: case-sensitive and unanchored. The panel clients compile it to reject a bad pattern early. The route table does not use this Regex: audit_routes builds each rule id’s DomainRegexSet from the patterns’ source text (as_str()).
  • RouteRule is one entry of a newV2board node config’s routes array, cached by the client for node_rule.
  • PanelClient dispatches each call to the newV2board or helium client. inherit_routes does something only when the new and the old client are both newV2board clients.
src/manager/node.rs
pub struct NodeManager {
// ...
rules: RuleManager,
supervisor: OnceLock<Supervisor<Uid>>,
// ...
}
impl NodeManager {
async fn refresh_rules(&self);
}

Each node owns one RuleManager, so two nodes never share rules, even when they read the same rule file. The rest of NodeManager is on Node manager.

flowchart LR
  panel["newV2board block routes"]
  file["rule_list_path"]
  client["PanelClient::node_rule"]
  store["RuleManager rules"]
  lower["audit_routes in node_spec"]
  sup["supervisor apply, new plane"]
  flow["flow routed to audit#id"]
  hole["Blackhole outbound"]
  panel --> client
  file --> client
  client -->|"refresh_rules, update"| store
  store -->|"rules()"| lower
  lower -->|"Spec"| sup
  sup --> flow
  flow --> hole

One blocked flow, from the client’s request to its end:

sequenceDiagram
  participant C as client
  participant I as inbound core
  participant AC as AppConnector
  participant B as audit#7 blackhole
  C->>I: request for ads.example.com
  I->>AC: connect(flow)
  AC->>AC: plane.route matches the audit#7 route
  AC->>B: connect_stream
  B-->>AC: Blackhole stream, tracked as a flow
  AC-->>I: Blackhole stream
  I-->>C: accepted, then end of stream

NodeManager::refresh_rules asks the current panel client for the list and hands a full answer to RuleManager::update:

node_rule returns refresh_rules does
Ok(Some(rules)) self.rules.update(rules)
Ok(None) nothing: the list in force stays
Err(e) logs node <id>: node_rule: <error> at WARN; the list in force stays

It runs in two places, and only when [node.controller].disable_get_rule is false (the default):

  1. Bootstrap. Each try_bootstrap attempt starts with self.api().forget_etags(), so the node config, and with it a newV2board node’s routes, is read in full. It refreshes after it has read the node and its users and before it lowers the first spec, so that spec is lowered with the list this refresh stored. refresh_rules cannot fail the bootstrap: an error would only be logged, and the node would start with whatever list it holds.
  2. Every poll. poll_cycle refreshes after node_info and user_list and before reconcile, as its comment says, “so a changed rule set is lowered this cycle”. The poll timer and the cycle are described on Node manager.

With disable_get_rule = true, katana does not call node_rule, so neither the node config’s routes nor the local file are read into rules. The checks that --test, start-up and a reload run on a node’s config never refresh either: they check lower::test_spec, which lowers the node with no audit rules (see Checks without rules).

Neither panel client makes a request for its rules: at katana 6 node_rule never fails and never answers “not modified”. Both build the list the same way: read_local_rules(&self.rule_list_path) first, then the panel’s rules appended. Local rules therefore always come first. The helium client has no panel rules to append, so its list is the local one alone. katana 6 removed SSPanel, whose detect_rules endpoint was the one rule request a panel client made.

UniProxy has no rule endpoint. The newV2board client derives its rules from the node config it already fetches, through parse_node_config and detect_rules, both private to src/api/newv2board.rs:

  1. Every time node_info parses a config answer (GET /api/v1/server/UniProxy/config), it replaces its cached routes: Mutex<Vec<RouteRule>> with the answer’s routes array (each entry’s match list and action). A 304 leaves the cache as it is.
  2. node_rule makes no request. detect_rules reads the local file, then walks the cached routes with their index i, and for every route whose action is exactly "block" compiles r.match_.join("|") into one regex with id i as i64.
  3. It always returns Ok(Some(rules)): it never fails and never answers “not modified”.
Part of a UniProxy node config
"routes": [
{ "id": 3, "match": ["^ads\\.", "^promo\\."], "action": "block" },
{ "id": 4, "match": ["example.org"], "action": "dns", "action_value": "198.51.100.53" }
]

This gives rule 0 with the pattern ^ads\.|^promo\.. The id is the route’s position in the array, from 0, not the panel’s id field; routes with other actions keep their positions, so ids can have gaps. The id matters only for grouping and for the audit outbound’s tag. A route whose joined regex does not compile is skipped whole, with WARN invalid block rule ["<entry>", ...]: <error>, which prints the route’s whole match list.

Two consequences of deriving rules from the node config:

  • A rebuilt client keeps the routes. A config edit that leaves the node the same node but changes its panel_type spelling, any [node.api] field, enable_mtls or [node.hysteria] gives it a new panel client (NodeManager::apply_static). Before the swap, PanelClient::inherit_routes copies the old client’s cached routes into the new one, so, as the comment on it says, “a client rebuilt for a config edit then keeps enforcing them even if the panel is unreachable when it takes over”.
  • Under newV2board, a locally described Hysteria 2 node has only local rules. When node_type is Hysteria 2 and [node.hysteria].port is set, NodeManager::node_info builds the node from the config and never asks the panel, so the route cache stays empty. A helium node is never described locally: its client refuses [node.hysteria].port.

Helium’s node API v2 has no rule endpoint either, and its node config carries no routes. helium::Client::node_rule makes no request and returns Ok(Some(read_local_rules(&self.rule_list_path))), so a helium node’s audit rules are its rule_list_path alone, every one with id -1. Like the newV2board client’s, it never fails and never answers “not modified”. The helium client caches no routes, so inherit_routes has nothing to carry over between two helium clients.

read_local_rules(path) in src/api/mod.rs:

  • returns an empty list when path is empty (the default of [node.api].rule_list_path);
  • reads the whole file with std::fs::read_to_string. When that fails, it logs WARN cannot read rule_list_path <path>: <error> and returns an empty list; the panel’s rules still load;
  • trims each line and skips it when it is empty or starts with #. There are no inline comments;
  • compiles every other line with Regex::new as DetectRule { id: -1, pattern }, or skips it with WARN invalid local rule "<line>": <error>.

A relative path is opened relative to katana’s working directory.

The two skip warnings (invalid local rule, invalid block rule) format the line, the pattern or the match list with {:?}. The text is therefore quoted and its backslashes are doubled: the pattern ^ads\. logs as "^ads\\.", and a match list as ["^ads\\.", "^promo\\."]. The <error> part is the regex crate’s Display, which for a syntax error runs over several lines: the pattern, a caret under the fault, and the reason.

Source Rule id One rule per Pattern
Local file -1 non-comment line the trimmed line
newV2board routes with action = "block" position in routes, from 0 route match entries joined with |

helium adds no row: its node config carries no routes, so a helium node has the local file’s rules alone.

lower::node_spec receives the rules as its audit argument (NodeManager::lower_off_runtime passes the list self.rules.rules() returns) and hands them to shared_spec, which builds everything in a node’s spec except its inbound and users:

src/lower/mod.rs
fn shared_spec(cfg: &NodeConfig, globals: &Globals, audit: &[DetectRule]) -> io::Result<Spec<Uid>> {
let (audit_outbounds, audit_rules) = rule::audit_routes(audit);
let mut outbounds = outbound::lower_outbounds(globals)?;
outbounds.extend(audit_outbounds);
let dns = outbound::lower_dns(&globals.dns)?;
let mut route = route::lower_route(&cfg.route)?;
route.rules.splice(0..0, audit_rules);
// ... Spec { outbounds, route, dns, .. }
}
  1. Group by id. Walk the rules in order. A rule whose id has not been seen starts a group (id, vec![pattern]); a rule whose id has been seen appends its pattern’s source text to that group. Groups keep the order in which their ids first appeared, and patterns keep list order within a group.

  2. Compile each group with etemenanki_environment::routing::parse_domain_regexes(&patterns), which builds one RouteMatch::DomainRegex(DomainRegexSet). A DomainRegexSet compiles the patterns into as few regex::RegexSets as the engine’s compiled-size limit allows, splitting the list in halves on CompiledTooBig, and compares equal to another set when their pattern texts are equal (Routing).

  3. Skip a group that does not compile. When parse_domain_regexes returns an error, audit_routes logs WARN audit rule <id> skipped: <error> and leaves out both the outbound and the route of that id, so no route ever names a missing outbound. The error names the first pattern at fault (invalid domain regex "<pattern>": <error>), or the whole set (domain regex set of <n> patterns: <error>). Every pattern has already compiled once in the panel client, so this is a safety net.

  4. Emit for each remaining group, in order:

    src/rule.rs
    OutboundSpec {
    tag: audit_tag(id),
    protocol: OutboundProtocolSpec::Blackhole,
    drain: None,
    }
    RouteRuleSpec {
    matchers: vec![matcher],
    outbound: audit_tag(id),
    }

drain: None leaves the outbound under the spec’s drain policy. katana’s spec takes its drain policy from Policies::default() (policies in src/lower/mod.rs sets only ip_ban and carrier_max_failures), and that DrainPolicy is Keep (“leave them on the old version until they end on their own”), so a removed audit outbound’s live flows run until they end.

Spec part Order
outbounds direct, block, freedom, blackhole, then each [[outbound]] in file order, then one audit#<id> blackhole per rule id
route.rules one audit#<id> rule per rule id, then the [[node.route.rule]] entries from lower_route
route.default [node.route].default, or "direct"

For example, a newV2board node with the local rules ^tracker\. and ^metrics\., whose node config’s routes are a block route matching ^ads\. and ^promo\., a dns route and a block route matching tracker, lowers to:

Route index Matcher Outbound
0 DomainRegex(["^tracker\\.", "^metrics\\."]) audit#-1
1 DomainRegex(["^ads\\.|^promo\\."]) audit#0
2 DomainRegex(["tracker"]) audit#2
3 and later the [[node.route.rule]] entries as written

The two local rules share id -1, so they share one group, one matcher and one outbound. The newV2board client has already joined each route’s match list into one pattern.

audit_routes gives every rule id a blackhole outbound of its own, tagged with the id, so the outbound a caught flow is opened on names the rule that caught it (FlowEntry::outbound in the supervisor’s tracker). katana itself no longer reads that tag. Each outbound is also a destination of its own to the UDP fan-out: FanOutLink keeps one sub-link per outbound version it sends to, keyed by OutboundId (supervisor/src/topology/outbound/udp_fanout.rs), so each rule a UDP association matches opens its own sub-link.

lower_outbounds refuses an [[outbound]] whose tag starts with audit#, with the same error as a repeated or built-in tag. The check is a case-sensitive starts_with. The pinned binary prints:

configuration error: node 1: duplicate/reserved outbound tag audit#1

Without the check, an [[outbound]] named audit#1 would collide with the audit outbound of rule 1.

lower::test_spec, which --test, start-up (build_node) and the reload check (check_node in src/runtime.rs) all lower, passes no audit rules: shared_spec(cfg, globals, &[]), or, for a node whose node_type is Hysteria 2 (never a helium node, which sets no node_type), node_spec of the node api::hysteria::local builds from [node.hysteria], with one placeholder user and &[] for the rules. So:

  • --test does not open rule_list_path and does not ask the panel. A missing file or a bad regex prints no error; it shows up as WARN lines once the node runs.

  • A [[node.route.rule]] cannot send traffic to an audit outbound. The check’s spec has no audit# outbounds, and the supervisor refuses the route:

    configuration error: node 1: route references unknown outbound audit#7

An audit route is an ordinary route, so it matches the way every route does. The details are on Routing plane and Routing; what matters for the audit is below.

route_target (supervisor/src/topology/router.rs) turns a flow into a RouteTarget. For domain matchers only two fields count: the flow’s requested destination and its sniffed name. RouteTable::pick folds both once per routed flow (Domains::of in environment/src/routing.rs):

Name Taken from Folded
Requested flow.destination.remote when it is Remote::Domain; nothing for an IP to_ascii_lowercase
Sniffed flow.sniffed, the TLS SNI or HTTP Host a protocol core recovered from the first payload bytes to_ascii_lowercase

RouteMatch::DomainRegex(set) matches when set matches either name. From that:

  • Domain names only. An IP address is never tested. A flow addressed by IP matches only through its sniffed name. The comment at the top of src/rule.rs states the design: “Rules match domain names only — the one requested, or the one sniffed — lower-cased.”
  • Sniffing is limited. Sniffing runs only for a flow addressed by IP (protocols/src/sniff/mod.rs → worth_sniffing), only when [node.controller].disable_sniffing is false (the default), and only on the first payload bytes it can read before its budget or timeout (Sniffing). A payload that names no plausible domain leaves the flow without one.
  • UDP packets carry no sniffed name. FanOutLink routes each packet as flow.toward(to), and Flow::toward sets sniffed: None (protocols/src/flow.rs). A UDP packet matches only when the client addressed it by name.
  • Patterns see lower case. The name is folded but the pattern is not: a pattern is compiled as written, so a letter in upper case never matches unless the pattern turns on (?i).
  • Search, not whole-name match. RegexSet::is_match finds a match anywhere in the name, so tracker matches mytracker.example.net. ^ and $ anchor to the whole name.
  • The port is not part of it. A rule cannot select a port.

The route table returns the first rule with a matching matcher, and the audit rules come first. So:

  • A name that [node.route] would send to direct, or to a proxy outbound, is still blocked when an audit rule matches it.
  • A name that [node.route] would send to block goes to the audit outbound instead, because the audit route is picked first. Both are blackholes, so the client sees the same thing.
  • A name that several rule ids match goes to the first of them only. Local rules come first, so a name that a local rule and a newV2board block route both match goes to audit#-1.

Every flow the supervisor’s connector opens goes through the route table, whichever inbound decoded it: a TCP request, each mux sub-flow, each Hysteria 2 stream, and each packet of a UDP association. Before it routes anything, AppConnector::connect (supervisor/src/connector.rs) runs session.admit(&flow.user.user_data) on the connection’s session, when it has one; a flow refused there is never routed.

DNS queries are no exception. Plane::route (supervisor/src/topology/plane.rs) sends a port-53 flow to the supervisor’s DNS service only when the plane has a DNS target, which only DnsSpec::Split creates. katana’s [dns] lowers to DnsSpec::Single, which leaves applications’ DNS “routed like any other flow”, so port-53 flows pass through the route table like any other. An audit rule sees only such a flow’s own destination name, never the name a query asks for: a query addressed to a resolver’s IP has no requested name, a UDP packet has no sniffed name, and no matcher reads the question inside the query.

The flow is routed to audit#<id>, a Blackhole outbound (supervisor/src/topology/outbound/mod.rs). No outbound kind exists to refuse a routed flow; a route drops one with a Blackhole outbound, the same kind as the built-in block.

Flow What the supervisor opens What the flow sees
TCP connect_stream resolves at once to OutboundStream::Blackhole, which the connector wraps as a tracked flow The dial succeeds. Every read returns end of stream at once; every write is accepted whole and discarded; flush and shutdown succeed.
UDP packet FanOutLink opens a sub-link on audit#<id>: connect_datagram resolves at once to a BlackholeLink Every packet sent to it is reported as sent and discarded; it never delivers a packet. The association keeps running for its other destinations.

For a TCP flow the client’s request is accepted, then the protocol core relays the outbound’s end of stream, and the client reads end of stream without any byte from the destination. In katana 3.x the dial failed instead, and the protocol core received it as a failed connect.

A blackholed flow is tracked like any other. The connector wraps a TCP flow as Metered<OutboundStream>, and FanOutLink wraps each UDP sub-link as a MeteredDatagram, so the bytes the client writes into the blackhole count as the flow’s up, and FlowHandle::add_up charges them to the user’s pacer, which enforces the speed limit (Tracking).

A UDP association that sends several packets matching one rule id reuses that id’s sub-link while it stays open, so it normally produces one flow. FanOutLink keeps at most MAX_SUBS = 64 sub-links and drops the one least recently sent to when it opens another; a later packet routed to audit#<id> then opens a new sub-link, which is a new flow. one_association_routes_each_peer_separately in app/tests/integration/e2e_udp_route.rs pins, through etemenanki-app, that a packet routed to a blackhole is not relayed and that the association keeps serving its other peers.

A changed rule list reaches the running node through the normal reconcile, in the same poll that fetched it:

  1. refresh_rules stores the new list with RuleManager::update.
  2. reconcile lowers the node again. The new spec differs from the applied one only in its audit outbounds and routes. Rule changes are not among the causes of drop_all (a pending local rebuild, or a change to the node’s disruptive part, disruptive_part, which holds no rules), so when nothing else changed the node applies the spec with apply_with and closes nothing afterwards.
  3. The supervisor plans the difference (Reconcile). An added id is a new blackhole outbound; a removed id’s outbound is drained under DrainPolicy::Keep; an id whose patterns changed keeps its outbound, since the OutboundSpec is the same, and only its route changes. The new route table is published as a new plane. apply_with answers with an ApplyReport that lists an unchanged audit outbound under reused, a new one under built and a removed one under drained; katana does not read the report.
  4. The plane is read-copy-update: each new flow, mux sub-flow and UDP packet is routed on the plane current at the time, and a flow already open keeps the target it was opened on (Routing plane).

So a new rule blocks new flows once the poll that fetched it has applied it, and connections already open are not closed, whether a rule now matches them or not. A rule that is removed stops matching new flows; flows already on its blackhole run until they end. The node’s module comment sums it up: “an audit change republishes routes without closing anything”.

A config edit to rule_list_path changes a field the panel client keeps ([node.api]), so it builds a new client and runs one poll cycle at once, without dropping connections. rule_list_path is not part of a node’s identity for any panel type, so the edit reconfigures the running node rather than replacing it. That poll’s refresh_rules builds the list with the file at the new path.

Invariant Enforced by Pinned by
Audit routes come before every [[node.route.rule]] route.rules.splice(0..0, audit_rules) in shared_spec audit_rules_route_first_to_one_blackhole_per_rule_id (tests/unit/lower/spec.rs)
One blackhole outbound and one route per rule id, in order of first appearance; the patterns of one id share one DomainRegex matcher Grouping in audit_routes the same test pins one route per id (ids 7, 9, 7 give routes to audit#7, audit#9, then block), a single DomainRegex matcher on the first route, and Blackhole for both audit outbounds; it does not check which patterns the matcher holds
An [[outbound]] cannot take an audit# tag starts_with(AUDIT_TAG_PREFIX) in lower_outbounds an_audit_tag_is_reserved
No route names an audit outbound that is missing audit_routes skips the outbound and the route of an id together; test_spec has no audit outbounds, so [node.route] cannot name one none
An identical list does not replace the one in force Element-wise id and as_str() comparison in update update_skips_identical_ruleset (tests/unit/rule.rs)
Equal rule lists lower to equal specs DomainRegexSet equality on pattern text domain_regex_equality_is_by_pattern (environment/tests/unit/routing.rs)
A rule’s patterns match as one matcher, and an invalid pattern is refused by name parse_domain_regexes domain_regex_matches_any_of_its_patterns, invalid_domain_regex_is_rejected
A rule’s patterns still build when they are too large for one RegexSet Halving on CompiledTooBig regexes_too_big_for_one_set_still_build
Names are folded before domain matchers see them Domains::of domain_matching_is_case_insensitive (checked for suffix, keyword and full matchers)
A sniffed name lets domain rules match a flow addressed by IP with_sniffed_domain in route_target a_sniffed_domain_makes_an_ip_target_match_domain_rules; end to end with a domain_suffix route, a_sniffed_host_reaches_a_domain_rule and disable_sniffing_stops_the_domain_rule_matching (tests/integration/sniff.rs)
Each UDP sub-link is a flow of its own, filed under the outbound it is open on FanOutLink a_udp_association_counts_each_sub_link_and_charges_its_session (supervisor/tests/tracking.rs)
A domain matcher never matches an IP destination without a sniffed name Domains::of has no requested name for an IP domain_matchers_never_match_ip_dests (environment/tests/unit/routing.rs, for suffix, keyword and full matchers)
A rule change blocks new flows to the names it matches without dropping live connections or respawning the node Reconcile without drop_all; plane publish a_client_edit_takes_effect_without_dropping_connections (tests/unit/runtime.rs)
A rebuilt newV2board client keeps the block routes until it reads the config itself inherit_routes a_rebuilt_client_keeps_the_routes_it_has_not_read (tests/unit/api/newv2board.rs)
Situation What happens Log
rule_list_path cannot be read The list is built without local rules WARN katana::api: cannot read rule_list_path <path>: <error>
A local line does not compile That line is skipped WARN katana::api: invalid local rule "<line>": <error>
A newV2board block route’s joined regex does not compile That route is skipped WARN katana::api::newv2board: invalid block rule ["<entry>", ...]: <error>
A rule id’s patterns do not compile as a set That id’s outbound and route are left out WARN katana::rule: audit rule <id> skipped: <error>
An [[outbound]] tag starts with audit# [[outbound]] is shared by every node, so no node builds: --test fails on the first node, start-up starts none of them, and a reload is refused configuration error: node 1: duplicate/reserved outbound tag audit#1 under --test; ERROR node <id>: <error> at start-up; ERROR reload: node <panel>@<host>#<id>[/<type>]: <error>; keeping current config on a reload
A [[node.route.rule]] names an audit# tag Refused by the supervisor’s check configuration error: node 1: route references unknown outbound audit#7 under --test

The skip warnings quote their pattern with {:?} (Log texts of skipped rules).

Cancellation. The audit has no task of its own. Its rules are refreshed and lowered on the node’s task, inside the bootstrap attempt or the poll cycle, so they stop with the node, and the supervisor matches them in its route table. Nothing in the audit holds a lock across an .await.

What Value Where
AUDIT_TAG_PREFIX "audit#" src/rule.rs
Outbounds and routes added per node one of each per distinct rule id that compiles audit_routes
Local rule id -1 read_local_rules
newV2board rule id the route’s index in routes, from 0 newv2board::detect_rules
Rule refresh interval the poll period: update_periodic seconds, default 60, at least 1 src/config.rs, NodeManager::poll_period
UDP sub-links per association MAX_SUBS = 64; the least recently sent to is dropped first supervisor/src/topology/outbound/udp_fanout.rs
RegexSet size split in halves until each part fits the regex crate’s default compiled-size limit RegexSets::compile in environment/src/routing.rs

The route-based audit changes what an operator sees in five ways. Each follows from the mechanism above:

katana 3.0.1 katana 4 and later
What a rule is tested against The requested host as sent: a domain name, case as sent, or an IP literal The requested name and the sniffed name, lower-cased; never an IP
A flow addressed by IP with a TLS SNI or HTTP Host Not matched by its name Matched by its sniffed name (TCP, with sniffing on)
A flow [node.route] sends to block Refused without testing the audit rules Blackholed by the audit route
The flow Failed to open (PermissionDenied, refused), which the protocol core received as a failed connect Opened on a blackhole: the request is accepted, then reads end of stream
A UDP packet that matches Dropped, the packet tested against the rules on each send Swallowed by the rule’s BlackholeLink sub-link, normally one flow per association and rule id

What stayed the same: local rules first and id -1, the newV2board rule source, and no connection dropped when the rules change. katana 4 and 5 also kept one entry per (uid, rule_id) per report and sent the entries to SSPanel alone; katana 6 removed that ledger, the report and the SSPanel rule source along with SSPanel.

katana:

File Test What it pins
tests/unit/rule.rs update_skips_identical_ruleset update returns true for a new list, false for the same ids and pattern text, true for a changed pattern
tests/unit/lower/spec.rs audit_rules_route_first_to_one_blackhole_per_rule_id Rules 7: ^ads\., 9: tracker, 7: ^promo\. and a [node.route] rule to block lower to routes toward audit#7, audit#9, block; the first matcher is a DomainRegex; both audit outbounds are Blackhole
tests/unit/lower/spec.rs an_audit_tag_is_reserved An [[outbound]] tagged audit#1 fails the lowering with an error containing reserved
tests/unit/runtime.rs a_client_edit_takes_effect_without_dropping_connections A newV2board node gets a rule_list_path edit to a file holding ^localhost$. The node is reconfigured, not respawned (its update channel is the same); new flows to localhost fail within 10 s; a connection opened before the edit, to the echo’s address, keeps relaying.
tests/unit/runtime.rs a_newv2board_node_is_also_the_type_it_asks_for A rule_list_path edit leaves a newV2board node’s identity unchanged
tests/unit/api/newv2board.rs a_rebuilt_client_keeps_the_routes_it_has_not_read A client that inherits a block route for blocked\.example returns one rule that matches blocked.example
tests/unit/api/newv2board.rs a_config_body_parses_with_its_routes Of a block route and a dns route, detect_rules returns one rule, id 0, matching x.b.com
tests/unit/api/helium.rs the_audit_rules_are_the_local_list A helium client’s node_rule returns the rule file’s one pattern, id -1, matching blocked.example; with no rule_list_path it returns an empty list
tests/integration/sniff.rs a_sniffed_host_reaches_a_domain_rule, disable_sniffing_stops_the_domain_rule_matching Through a real Xray client, an HTTP request to an IP whose Host is sniffed.example reaches a domain_suffix route with sniffing on, and falls to the default block with disable_sniffing = true. They skip themselves when the Xray-core source or go is missing.

Etemenanki:

File Test What it pins
environment/tests/unit/routing.rs domain_regex_matches_any_of_its_patterns One DomainRegex of two patterns matches a name either pattern matches
environment/tests/unit/routing.rs invalid_domain_regex_is_rejected A set with one bad pattern fails, and the error names it
environment/tests/unit/routing.rs domain_regex_equality_is_by_pattern Two sets are equal when their patterns are
environment/tests/unit/routing.rs regexes_too_big_for_one_set_still_build A list too large for one set splits and still matches every pattern
environment/tests/unit/routing.rs domain_matching_is_case_insensitive, a_sniffed_domain_makes_an_ip_target_match_domain_rules Name folding and sniffed names, for the other domain matchers
environment/tests/unit/routing.rs domain_matchers_never_match_ip_dests Suffix, keyword and full domain matchers never match an IP destination without a sniffed name
supervisor/tests/tracking.rs a_udp_association_counts_each_sub_link_and_charges_its_session A SOCKS association that sends to two targets routed to two outbounds has two flows, one per sub-link, each filed under its outbound and the rule that routed it
app/tests/integration/e2e_udp_route.rs one_association_routes_each_peer_separately A packet routed to a blackhole is not relayed, and the association keeps serving its other peers

Nothing tests an audit rule matched through a sniffed name, an audit rule matched by a UDP packet, a pattern with upper-case letters against a folded name, or the skip of an id whose set does not compile. Add a test when you touch those paths; the harnesses are described on Testing.