Validation and apply errors
Source files: 58 · checked against Etemenanki 46c12e4 · katana v6.1.0 · shinku-quic v0.1.0
Etemenanki/supervisor/src/build/validate.rsEtemenanki/supervisor/src/build/apply.rsEtemenanki/supervisor/src/build/mod.rsEtemenanki/supervisor/src/lib.rsEtemenanki/supervisor/src/build/users.rsEtemenanki/supervisor/src/build/inbound.rsEtemenanki/supervisor/src/build/outbound.rsEtemenanki/supervisor/src/entity/id.rsEtemenanki/supervisor/src/entity/user.rsEtemenanki/supervisor/src/supervisor.rsEtemenanki/supervisor/src/topology/spec_plan/plan.rsEtemenanki/supervisor/src/topology/spec_plan/inbound.rsEtemenanki/supervisor/src/topology/spec_plan/transport.rsEtemenanki/supervisor/src/topology/inbound/mod.rsEtemenanki/supervisor/src/topology/balancer.rsEtemenanki/supervisor/src/topology/plane.rsEtemenanki/supervisor/src/system/listener.rsEtemenanki/protocols/src/hysteria/server/masquerade.rsEtemenanki/protocols/src/hysteria/auth.rsEtemenanki/protocols/src/hysteria/obfs.rsEtemenanki/protocols/src/hysteria/config.rsEtemenanki/protocols/src/tun/device.rsEtemenanki/protocols/src/transports/ws/endpoint.rsEtemenanki/protocols/src/ss_2022/users.rsEtemenanki/protocols/src/ss_2022/crypto.rsEtemenanki/protocols/src/anytls/padding.rsEtemenanki/protocols/src/sss/transform/stream.rsEtemenanki/protocols/src/helpers/address_family.rsEtemenanki/app/src/instance.rsEtemenanki/app/src/lower.rsEtemenanki/app/src/main.rsEtemenanki/app/src/api.rsEtemenanki/ffi/src/error.rsEtemenanki/webclient/src/lib.rsEtemenanki/webclient/src/router.rsEtemenanki/supervisor/tests/unit/validate.rsEtemenanki/supervisor/tests/unit/plan.rsEtemenanki/supervisor/tests/hot_swap.rsEtemenanki/supervisor/tests/sss.rsEtemenanki/protocols/tests/unit/hysteria/server/masquerade.rsEtemenanki/protocols/tests/unit/ss_2022/users.rsEtemenanki/app/tests/unit/lower.rsEtemenanki/app/tests/unit/subscribe.rskatana/src/main.rskatana/src/runtime.rskatana/src/manager/node.rskatana/src/lower/inbound.rskatana/src/lower/mod.rskatana/src/api/mod.rskatana/src/api/helium.rskatana/src/api/hysteria.rskatana/src/api/newv2board.rskatana/tests/unit/lower/outbound.rskatana/tests/unit/lower/spec.rskatana/tests/unit/lower/inbound.rskatana/tests/unit/api/helium.rskatana/tests/unit/runtime.rsshinku-quic/shinku-quic/src/hop.rs
A Spec<U> is typed, but types cannot say which fields go together, which tags exist or which values are in range. Those rules live in one function, supervisor/src/build/validate.rs → validate, and every path that runs a spec goes through it before anything is built. A spec that breaks a rule is refused whole with an ApplyError, and what was running keeps running. This page lists every rule in the order validate checks it, with the variant and the exact text it produces, then covers the other ApplyError variants, the dry run check(), and how each front end reports the errors.
It is for contributors who add a field to a spec type, change a rule, or write a front end that lowers its own format into a spec. The spec types themselves are on The spec: desired state. What happens after validation (the plan, prepare and commit) is on Planning and applying a change.
Responsibilities
Section titled “Responsibilities”build/validate.rs owns every rule about what a spec means. Its module comment states the split: a front end owns only syntax, which is parsing its own format and reading files, so a rule is never checked on one side only. The module is pure: no sockets, no files, no clock. Validation never parses PEM either; certificate bytes are opaque to it, and the unit tests pass b"cert" as a certificate.
validate checks:
- that tags are non-empty and unique within their kind, and that no balancer shares a tag with an outbound;
- that every tag a balancer, a route rule, the route default or an inbound names exists;
- that every balancer member can be probed over TCP;
- each outbound’s fields against each other (TLS and REALITY settings against the shape, REALITY only under VLESS, Vision only over REALITY, AnyTLS over TLS with a password, key lengths, sss limits, WireGuard address families, Hysteria 2 port hopping and QUIC settings);
- that no two binds are the same or share a socket path, that each protocol sits on its kind of bind, that a Unix socket is bound only on Unix, that only a TCP bind reads a PROXY protocol header, that only a WebSocket transport on a TCP bind reads a real-IP header, under a header name and from at least one trusted proxy, and that a handoff socket stands only beside a stream protocol’s TCP bind, on Unix, at an absolute path a Unix socket can be bound at, with permission bits alone for its mode;
- each inbound’s fields against each other (the transport rules every protocol with a transport meets, REALITY settings, Vision, open mode, SOCKS UDP over a transport, AnyTLS’s shape and padding scheme, sss limits, Hysteria 2 settings, TUN MTU and platform);
- the users each inbound would admit (
validate_admission).
It does not:
- read certificates, keys, CA bundles or geodata. The builders in prepare parse and load those (
compile_routesreads geodata), and a failure isApplyError::Build. - bind anything. A port in use fails as
ApplyError::Bind. - decide defaults or fill gaps. An outbound’s WebSocket host, gRPC authority and TLS name are the front end’s to fill; a gap that reaches the supervisor is refused rather than guessed at (see
an_outbound_needs_a_ws_host_and_a_grpc_authority). - collect errors. It returns the first broken rule, so one refusal reports one problem.
Inbounds and outbounds share one StreamShape (supervisor/src/topology/spec_plan/transport.rs) and the TLS pairing helper tls_mismatch, so the TLS rule is written once for both sides. The WebSocket host and gRPC authority rules apply to outbounds only.
Where validation runs
Section titled “Where validation runs”| Caller | What runs | When |
|---|---|---|
topology/spec_plan/plan.rs → plan |
validate(desired), as its first statement |
Every Supervisor::apply, apply_with, update, update_with, SupervisorBuilder::start and check, through Actor::stage on the blocking pool |
supervisor.rs → stage_user_edit |
validate_admission for each inbound admitting the edited set |
Supervisor::set_users, upsert_user and remove_user, staged on the blocking pool by Actor::edit_users |
supervisor.rs → Actor::prepare |
probe_target |
Building a balancer, to find each member’s probe destination |
Because plan validates before it computes a single step, and Actor::stage runs stage_users only on a plan that succeeded, no code path reaches the builders with an unvalidated spec. The builders rely on it: build/mod.rs says every builder takes a validated spec, and Actor::prepare has expect("validated: members are outbounds") and expect("validated: members are probeable") where it builds a balancer.
Key types
Section titled “Key types”The two entry points
Section titled “The two entry points”/// Check every semantic rule of `spec`.pub fn validate<U: UserId>(spec: &Spec<U>) -> Result<(), ApplyError>;
/// Check the users `inbound` would admit from `set`: no credential with two/// owners, and every credential usable by the inbound's protocol.pub fn validate_admission<U: UserId>( inbound: &InboundSpec, set: &UserSet<U>,) -> Result<(), ApplyError>;
/// Where a TCP health probe reaches `outbound`, if anywhere.pub(crate) fn probe_target(outbound: &OutboundSpec) -> Option<&Destination>;Both public functions are reachable as etemenanki_supervisor::build::validate::validate and …::validate_admission, so a front end can run them without a supervisor. Of the modules under build/, only apply and validate are pub; dns, inbound, outbound, route and users are pub(crate). The private helpers are:
| Helper | Returns | Does |
|---|---|---|
unique_tags(kind, tags) |
Result<HashSet<&CompactString>, ApplyError> |
Refuses an empty tag, then a repeated one, in iteration order; returns the set for the reference checks |
validate_outbound(outbound) |
Result<(), ApplyError> |
The per-outbound rules |
outbound_transport(transport) |
Result<(), CompactString> |
REALITY pairing and the client’s server name; otherwise TLS pairing, then the WebSocket host and gRPC authority |
reality_settings(transport) |
Result<(), CompactString> |
An inbound transport’s REALITY pairing and its RealityServerSpec rules |
client_version_value(v) |
u32 |
A three-byte client version as the one number REALITY compares |
inbound_transport(inbound, t) |
Result<(), CompactString> |
The rules an inbound’s transport meets whichever protocol it carries |
sss_limits(max_datagram, flush_delay) |
Result<(), CompactString> |
The limits both sss ends share, and the flush delay each sets |
needs_users(inbound) |
Result<(), ApplyError> |
A protocol with no open mode needs a user set |
tls_mismatch(shape) |
CompactString |
The text for a TLS pairing error, which depends on which side is missing |
obfs(obfs) |
Result<(), CompactString> |
The Salamander key length, shared by inbound and outbound |
hy2_quic(quic) |
Result<(), CompactString> |
Upstream’s limits on a Hysteria 2 quic block, shared by inbound and outbound |
port_hopping(hop) |
Result<(), CompactString> |
A Hysteria 2 outbound’s hop ports and shortest interval |
validate_inbound(inbound) |
Result<(), ApplyError> |
The per-inbound rules |
real_ip_header(inbound, real_ip) |
Result<(), CompactString> |
The rules for an inbound’s RealIpSpec |
handoff_socket(inbound, handoff) |
Result<(), CompactString> |
The rules for an inbound’s HandoffSpec |
invalid_inbound(inbound, reason) |
ApplyError |
ApplyError::Invalid naming Resource::Inbound(tag) |
Inside validate, the sets that unique_tags returns do the reference checks. A balancer’s members are looked up in by_tag, a HashMap<&CompactString, &OutboundSpec> over the outbounds, and each route target goes through the closure routable, which is true for a tag in the outbound set or the balancer set. validate_admission keeps the identities it has seen in seen, a HashMap<Vec<u8>, &U> from identity to the user who presented it first.
Constants
Section titled “Constants”| Constant | Type | Value | Rule |
|---|---|---|---|
MIN_TUN_MTU |
u16 |
1280 |
The smallest MTU the userspace stack serves |
HY2_UDP_IDLE |
RangeInclusive<u64> |
2..=600 (seconds, inclusive) |
A Hysteria 2 UDP association’s idle timeout. The comment gives the reason: below it a busy association is swept between packets, above it a dead one holds its socket for ten minutes |
MIN_SALAMANDER_PSK |
usize |
4 |
The shortest Salamander key, on either side. protocols/src/hysteria/obfs.rs → MIN_PSK_LEN is also 4, and Salamander::new refuses the same keys with ProtocolError::Malformed("hysteria2 obfs psk is too short") |
HY2_IDLE_TIMEOUT |
RangeInclusive<u64> |
4..=120 (seconds) |
Upstream’s range for a Hysteria 2 max_idle_timeout |
HY2_KEEP_ALIVE |
RangeInclusive<u64> |
2..=60 (seconds) |
Upstream’s range for a Hysteria 2 keep_alive_period |
QUIC_VARINT_MAX |
u64 |
(1 << 62) - 1 |
The largest number QUIC can carry, and so the largest receive window |
MAX_SOCKET_PATH |
usize |
107 |
The longest path a Unix socket can be bound at: sun_path holds 108 bytes, its terminating NUL included |
Rules also read these values from etemenanki-protocols:
| Value | Source | Used for |
|---|---|---|
STATUS_AUTH_OK = 233 |
protocols/src/hysteria/auth.rs |
The one status a masquerade may not use |
QuicOptions::MIN_RECEIVE_WINDOW = 16_384 |
protocols/src/hysteria/config.rs |
The smallest QUIC receive window upstream accepts |
HopInterval::MIN_CONFIGURED = 5 s |
shinku-quic/src/hop.rs, re-exported as etemenanki_protocols::hysteria::config::HopInterval |
The shortest hop interval upstream’s configuration accepts. shinku-quic does not enforce it, so validation does |
Method::key_len() = 16 for 2022-blake3-aes-128-gcm, 32 for 2022-blake3-aes-256-gcm and 2022-blake3-chacha20-poly1305 |
protocols/src/ss_2022/crypto.rs |
Shadowsocks 2022 key sizes |
WsRoute::real_ip_header(name) |
protocols/src/transports/ws/endpoint.rs |
Whether a real-IP header name is a valid HTTP header name: validation builds WsRoute::new("/").real_ip_header(&header) and refuses on its error, which is the same call build_transport makes |
normalise_psk(method, psk) |
protocols/src/ss_2022/users.rs |
A user PSK: accepted at the method’s length, folded to it when longer (the first key_len bytes of its SHA-256, ss_2022/crypto.rs → fold_key), refused when shorter with ErrorKind::InvalidInput and shadowsocks-2022: PSK too short (<len> < <n>) |
PaddingScheme::from_lines(lines) |
protocols/src/anytls/padding.rs |
An AnyTLS inbound’s padding scheme: the lines joined with \n must parse, within MAX_SCHEME_LEN (2,048 bytes); the SchemeError text is the reason |
MAX_FLUSH_DELAY = 10 ms |
protocols/src/sss/transform/stream.rs |
The longest sss flush delay t_c |
The spec carries Shadowsocks 2022 keys as decoded bytes. Front ends decode the base64 text of a key with ss_2022/users.rs → decode_psk, which fails with ErrorKind::InvalidInput and decode PSK: <e>; that is a lowering error, never an ApplyError.
ApplyError
Section titled “ApplyError”/// Why a spec was not applied.////// A spec that fails validation is refused as a whole, and what was running/// keeps running.#[derive(Debug, thiserror::Error)]pub enum ApplyError { /// Two resources of one kind share a tag, or a balancer's tag is also an /// outbound's. #[error("duplicate {kind} tag {tag}")] DuplicateTag { kind: ResourceKind, tag: CompactString }, /// `from` names a tag nothing of that kind carries: a rule or a balancer /// naming a missing outbound, or an inbound naming a missing user set. #[error("{from} references unknown {kind} {tag}")] UnknownReference { from: Resource, kind: ResourceKind, tag: CompactString }, /// A balancer with nothing to choose from. #[error("balancer {balancer} has no members")] EmptyBalancer { balancer: CompactString }, /// A balancer member no TCP health probe can reach, so its health, which /// is all a balancer selects on, could never be known. #[error("balancer {balancer}: outbound {member} has no upstream a TCP health probe can reach")] UnprobeableMember { balancer: CompactString, member: CompactString }, /// A spec that breaks one of its documented invariants, such as TLS /// material missing under a shape that layers TLS, or a Trojan inbound /// without a user set. #[error("{resource}: {reason}")] Invalid { resource: Resource, reason: CompactString }, /// A resource's spec was valid, but constructing it failed: a /// certificate that does not parse, geo data that cannot be read. #[error("building {resource} failed: {source}")] Build { resource: Resource, #[source] source: io::Error }, /// An inbound's listener could not be bound. #[error("inbound {inbound}: binding {bind} failed: {source}")] Bind { inbound: CompactString, bind: BindSpec, #[source] source: io::Error }, /// The spec needs a change that ends live connections, and the apply /// did not allow one. #[error("inbound {inbound}: {reason}; this ends its live connections and needs allow_disruptive")] Disruptive { inbound: CompactString, reason: CompactString }, /// The supervisor has shut down. #[error("the supervisor has shut down")] Stopped,}The enum doc states the contract: a spec that fails validation is refused as a whole, and what was running keeps running. lib.rs re-exports the module at the crate root (pub use build::apply;), so etemenanki_supervisor::apply::ApplyError and etemenanki_supervisor::apply::ApplyReport are a second path to the same types; etemenanki-app imports them from build::apply.
| Variant | Stage | Produced by |
|---|---|---|
DuplicateTag |
validate | unique_tags, and the balancer and outbound collision check |
UnknownReference |
validate | A balancer member, a route rule or the route default, or an inbound’s user set naming a tag that does not exist |
EmptyBalancer |
validate | A balancer with no members |
UnprobeableMember |
validate | A balancer member for which probe_target returns None |
Invalid |
validate, user edits | Every other rule of validate and validate_admission; also stage_user_edit for an unknown set |
Build |
staging and prepare, reported by prepare | A builder or a listener preparation step that failed. Validation passed |
Bind |
prepare | system/listener.rs → bind for a new listener |
Disruptive |
after staging, before prepare | A plan with a Step::Disrupt and ApplyOptions::allow_disruptive unset |
Stopped |
any | The actor is gone, or there is no running spec to edit |
Build and Bind carry the io::Error both in their text and as source(). ApplyError does not implement Clone.
How resources print
Section titled “How resources print”Every text above builds on two Display implementations in supervisor/src/entity/id.rs:
| Value | Prints |
|---|---|
ResourceKind::Inbound / Outbound / Balancer / UserSet |
inbound / outbound / balancer / user set |
Resource::Inbound(tag) |
inbound <tag> |
Resource::Outbound(OutboundId) |
outbound <tag>@v<version> |
Resource::Balancer(tag) |
balancer <tag> |
Resource::UserSet(tag) |
user set <tag> |
Resource::Route |
route |
Resource::Dns |
dns |
A bind prints through topology/inbound/mod.rs → impl Display for BindSpec:
BindSpec |
Prints |
|---|---|
Tcp { host, port } |
<host>:<port> |
Udp { host, port } |
udp <host>:<port> |
Unix(path) |
unix:<path> |
Handoff(spec) |
handoff:<path> |
Tun(TunSource::Create(spec)) |
tun <name>, or tun auto when name is None |
Tun(TunSource::Fd(device)), Unix only |
tun fd <n> |
ApplyReport
Section titled “ApplyReport”A successful apply returns what it did to each resource. The type sits beside ApplyError in build/apply.rs:
#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct ApplyReport { /// Kept as they were: their spec did not change. pub reused: Vec<Resource>, /// Constructed from their spec: new, or changed, in which case an /// outbound is a new version of its tag. pub built: Vec<Resource>, /// Inbounds that kept their listener and now serve new connections with /// a new handler. pub swapped: Vec<CompactString>, /// Outbound versions taken out of service. Their live flows are handled /// by the drain policy. pub drained: Vec<OutboundId>, /// Inbounds with a listener closed and bound again elsewhere, because /// their BindSpec or their handoff socket changed. A handoff socket /// added is not one. pub rebound: Vec<CompactString>, /// Inbounds whose runtime was stopped and started again on the handle it /// kept, ending its live connections: the disruptive changes an apply /// was allowed to make. pub restarted: Vec<CompactString>, /// Inbounds taken out of the spec: their listeners closed, and their /// sessions with them. pub removed: Vec<CompactString>,}Every resource of the desired spec appears in reused or built; the other five lists say what that meant for what was already running. It has no Display. Planning and applying a change says how each list is filled. etemenanki-app prints it with app/src/instance.rs → summary: each non-empty list as <label> [<item>, …], joined by ; , in the order built, swapped, drained, rebound, restarted, removed, reused, or nothing to run when all are empty. Items print with the Display forms above, and drained outbounds as <tag>@v<version>.
/// Validate `spec` and build everything it describes — outbounds, routes/// with their geo data, handlers with their certificates, user tables —/// without binding a listener or starting anything. It refuses what a start/// would, short of a port or device that cannot be bound.pub async fn check<U: UserId>(spec: &Spec<U>) -> Result<(), ApplyError>;It is re-exported at the crate root as etemenanki_supervisor::check. See The dry run.
Data flow
Section titled “Data flow”Where each variant can come from during one apply:
flowchart LR FE["Supervisor::apply"] -->|"Command::Apply"| PLAN["stage: plan, validate first"] FE -->|"actor gone"| ST["Stopped"] PLAN -->|"a rule is broken"| VE["DuplicateTag, UnknownReference, EmptyBalancer, UnprobeableMember, Invalid"] PLAN --> USERS["stage: users, handlers, tables"] USERS --> DIS["plan.disruptions()"] DIS -->|"allow_disruptive unset"| DE["Disruptive"] DIS --> PREP["prepare, bind = true"] PREP -->|"construction fails, staged or now"| BE["Build"] PREP -->|"a listener cannot bind"| BI["Bind"] PREP --> COM["commit: cannot fail"]
Actor::stage runs on the blocking pool: first plan, which validates before anything else, then stage_users, which admits the users and builds each built inbound’s handler and each changed user table, before the disruption gate. A staged handler or table that failed to build is not reported there: prepare reports it as Build, in inbound order, after DNS, outbounds, balancers and the route.
The order inside validate. Each box stops at its first broken rule:
flowchart TB T1["user set tags"] --> T2["outbound tags"] T2 --> T3["balancer tags"] T3 --> T4["balancer tag equal to an outbound tag"] T4 --> T5["inbound tags"] T5 --> O["validate_outbound, each outbound in order"] O --> B["each balancer: members exist and are probeable"] B --> R["route rules in order, then the default"] R --> I1["next inbound: binds unique, user set exists"] I1 --> I2["validate_inbound"] I2 --> I3["validate_admission, when it names a set"] I3 -->|"more inbounds"| I1
The inbound checks run per inbound, so inbound 2’s admission is checked before inbound 3’s bind.
The rules, in check order
Section titled “The rules, in check order”The texts below were captured from the pinned etemenanki-app with --test, where the app could produce them, and read from the code otherwise. A placeholder in angle brackets stands for a value. The unit tests in supervisor/tests/unit/validate.rs match on the variant and the resource, never on the text.
1. Tags
Section titled “1. Tags”unique_tags runs once per kind, in the order user sets, outbounds, balancers, inbounds, with the balancer and outbound collision check between balancers and inbounds. For each tag it checks emptiness first, then repetition.
| Rule | Variant | Text | Test |
|---|---|---|---|
| A user set tag is not empty | Invalid on the user set |
an empty-tag reason | no_tag_may_be_empty |
| User set tags are unique | DuplicateTag { kind: UserSet } |
duplicate user set tag <tag> |
tags_are_unique_within_each_kind |
| An outbound tag is not empty | Invalid on the outbound |
an empty-tag reason | no_tag_may_be_empty |
| Outbound tags are unique | DuplicateTag { kind: Outbound } |
duplicate outbound tag <tag> |
tags_are_unique_within_each_kind |
| A balancer tag is not empty | Invalid on the balancer |
an empty-tag reason | none |
| Balancer tags are unique | DuplicateTag { kind: Balancer } |
duplicate balancer tag <tag> |
tags_are_unique_within_each_kind |
| No balancer shares a tag with an outbound | DuplicateTag { kind: Balancer } |
duplicate balancer tag <tag> |
a_balancer_may_not_share_an_outbounds_tag |
| An inbound tag is not empty | Invalid on the inbound |
an empty-tag reason | no_tag_may_be_empty |
| Inbound tags are unique | DuplicateTag { kind: Inbound } |
duplicate inbound tag <tag> |
tags_are_unique_within_each_kind |
Why the rules are what they are:
- Outbound and balancer tags share one namespace. A route names either kind by tag, so one tag on both would be ambiguous. Inbound tags and user set tags live apart:
an_inbound_may_share_an_outbounds_tagaccepts an inbound taggeddirectbeside an outbound taggeddirect. - The empty tag is reserved. The supervisor makes two targets of its own and tags both with the empty string: the blackhole of
topology/plane.rs→Plane::empty, the plane an actor holds before its first apply publishes one, and the DNS service reached as an outbound (supervisor.rs→internal_id). Because no spec tag is empty, neither names one of the spec’s outbounds. - Checks run in kind order, not file order. etemenanki-app lowers the users listed inside an inbound to a user set tagged with the inbound’s own tag. Two Trojan inbounds both tagged
tare therefore refused asduplicate user set tag t, notduplicate inbound tag t. The text was captured from the app.
2. Outbounds
Section titled “2. Outbounds”validate_outbound runs for each outbound in spec order. Every error it returns is ApplyError::Invalid naming the outbound (Resource::Outbound).
For the proxy protocols that dial over a transport (SOCKS, HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, sss and AnyTLS), outbound_transport checks the upstream’s OutboundTransportSpec first. A REALITY transport is checked on its own, and the TLS, WebSocket and gRPC rules apply to every other shape:
| Rule | Text | Test |
|---|---|---|
The shape is Reality, so REALITY settings are present |
outbound <tag>@v0: a reality transport carries no reality settings |
a_reality_outbound_validates_and_its_field_must_match |
REALITY settings are present, so the shape is Reality |
outbound <tag>@v0: the transport carries reality settings but its shape is not reality |
same |
| A REALITY transport carries no TLS settings | outbound <tag>@v0: a reality transport carries no tls settings |
none |
The REALITY server name is not empty and holds no * |
outbound <tag>@v0: invalid reality server name "<name>", the name printed with {:?} |
none |
| The shape layers TLS, so TLS settings are present | outbound <tag>@v0: the transport layers tls but carries no tls settings |
an_outbound_carries_tls_settings_exactly_when_its_shape_layers_tls |
| TLS settings are present, so the shape layers TLS | outbound <tag>@v0: the transport carries tls settings but does not layer tls |
same |
A WebSocket shape has a host |
outbound <tag>@v0: ws transport needs a host |
an_outbound_needs_a_ws_host_and_a_grpc_authority |
A gRPC shape has an authority |
outbound <tag>@v0: grpc transport needs an authority |
same |
StreamShape::uses_tls decides the pairing: Tcp and Reality never layer this project’s TLS, Tls always does, and Ws and Grpc do when their tls flag is set.
Two rules then tie the transport to the protocol, the same two the inbound side holds:
| Rule | Text | Test |
|---|---|---|
A Reality shape only under VLESS |
outbound <tag>@v0: reality is for vless only |
a_reality_outbound_is_vless_only |
A VLESS outbound with VlessFlow::Vision only over a Reality shape |
outbound <tag>@v0: vless vision (xtls-rprx-vision) rides only over reality |
none |
The first keeps a mistyped security = "reality" under another protocol from validating and building a REALITY dial as that protocol. The second holds because Vision frames the body and splices the raw socket, which only the REALITY record layer supports.
Then the protocol’s own rules:
| Protocol | Rule | Text | Test |
|---|---|---|---|
| Shadowsocks 2022 | psk and every entry of identity_psks are exactly method.key_len() bytes |
outbound <tag>@v0: shadowsocks-2022 keys must be <n> bytes for this method |
shadowsocks_2022_client_keys_are_sized_to_their_method |
| sss | max_datagram is at least 1 |
outbound <tag>@v0: sss udp_max_datagram must be at least 1 |
none for the outbound |
| sss | flush_delay is at most 10 ms |
outbound <tag>@v0: sss flush_delay must be at most 10ms |
none for the outbound |
| AnyTLS | The upstream’s shape is Tls |
outbound <tag>@v0: anytls runs over tls only; its shape must be tls |
an_anytls_outbound_needs_tls_and_a_password |
| AnyTLS | password is not empty |
outbound <tag>@v0: anytls password must not be empty |
same |
| Hysteria 2 | password is not empty |
outbound <tag>@v0: hysteria2 password must not be empty |
a_hysteria2_client_needs_a_password_and_a_stream |
| Hysteria 2 | max_concurrent_streams is at least 1 |
outbound <tag>@v0: max_concurrent_streams must be at least 1 |
same |
| Hysteria 2 | a Salamander key is at least 4 bytes | outbound <tag>@v0: salamander obfs key must be at least 4 bytes |
a_salamander_key_is_at_least_4_bytes_on_either_side |
| Hysteria 2 | with hop, at least one port |
outbound <tag>@v0: port hopping needs at least one port |
hysteria2_port_hopping_needs_ports_and_a_sane_interval |
| Hysteria 2 | with hop, no port 0 |
outbound <tag>@v0: port 0 cannot be hopped to |
same |
| Hysteria 2 | with hop, the interval’s minimum (interval.min()) is at least HopInterval::MIN_CONFIGURED |
outbound <tag>@v0: the hop interval must be at least 5 seconds |
same |
| Hysteria 2 | quic.stream_receive_window is 16,384 to 2^62 − 1 |
outbound <tag>@v0: stream_receive_window must be at least 16384 bytes |
hysteria2_quic_settings_stay_within_upstreams_limits |
| Hysteria 2 | quic.conn_receive_window is 16,384 to 2^62 − 1 |
outbound <tag>@v0: conn_receive_window must be at least 16384 bytes |
same |
| Hysteria 2 | quic.max_idle_timeout is 4 to 120 whole seconds |
outbound <tag>@v0: max_idle_timeout must be a whole number of seconds between 4 and 120 |
same |
| Hysteria 2 | quic.keep_alive_period, when set, is 2 to 60 whole seconds |
outbound <tag>@v0: keep_alive_period must be a whole number of seconds between 2 and 60 |
same |
| Hysteria 2 | quic.max_incoming_streams is not Some(0) |
outbound <tag>@v0: max_incoming_streams must be at least 1 |
same |
| WireGuard | address_family = Ipv4Only needs an IPv4 address among addresses |
outbound <tag>@v0: wireguard address_family ipv4_only needs an IPv4 address |
a_wireguard_address_family_needs_an_address_of_that_family |
| WireGuard | address_family = Ipv6Only needs an IPv6 address |
outbound <tag>@v0: wireguard address_family ipv6_only needs an IPv6 address |
same |
The family name in the WireGuard text comes from AddressFamilyStrategy::as_str. Auto, PreferIpv4 and PreferIpv6 need no particular address. Freedom and blackhole outbounds have no rules here.
The Hysteria 2 rules run in the order of the table: the obfuscation key, then port_hopping when hop is set, then hy2_quic. hy2_quic checks the stream window, the connection window, the idle timeout, the keep-alive and the incoming streams, in that order, and is shared with the inbound. A window above 2^62 − 1 is refused with the same at least text. “Whole” means no fraction of a second (subsec_nanos() == 0), so a 30.5 s idle timeout is refused. The hop interval rule reads the interval’s shortest draw, so a random interval from 4 to 30 s is refused.
Captured from the app:
configuration invalid: outbound wg@v0: wireguard address_family ipv6_only needs an IPv6 addressconfiguration invalid: outbound hy2-out@v0: hysteria2 password must not be emptyconfiguration invalid: outbound hy2-out@v0: max_concurrent_streams must be at least 1configuration invalid: outbound hy2-out@v0: salamander obfs key must be at least 4 bytesconfiguration invalid: outbound t-out@v0: reality is for vless onlyconfiguration invalid: outbound v-out@v0: vless vision (xtls-rprx-vision) rides only over realityconfiguration invalid: outbound v-out@v0: invalid reality server name "*.example.com"configuration invalid: outbound any-out@v0: anytls runs over tls only; its shape must be tlsconfiguration invalid: outbound any-out@v0: anytls password must not be emptyconfiguration invalid: outbound x-out@v0: sss flush_delay must be at most 10ms3. Balancers
Section titled “3. Balancers”For each balancer in spec order:
| Rule | Variant | Text | Test |
|---|---|---|---|
| It has at least one member | EmptyBalancer |
balancer <b> has no members |
a_balancer_needs_a_member |
| Each member, in order, is an outbound tag | UnknownReference { from: Balancer(b), kind: Outbound } |
balancer <b> references unknown outbound <m> |
a_balancer_member_must_be_a_known_outbound |
| Each member can be probed over TCP | UnprobeableMember |
balancer <b>: outbound <m> has no upstream a TCP health probe can reach |
a_balancer_member_needs_an_upstream_a_tcp_probe_can_reach |
Members are looked up among outbounds only, so a balancer naming another balancer fails the second rule: balancer outer references unknown outbound inner (a_balancer_member_may_not_be_another_balancer). Balancers are members of nothing.
probe_target decides the third rule. Health is all a balancer selects on, and a TCP connect is how it learns health, so a member without a TCP upstream would be marked down forever:
| Outbound protocol | probe_target |
|---|---|
| SOCKS, HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, sss | Some(&upstream.server) |
| AnyTLS | Some(&anytls.upstream.server) |
| Freedom, blackhole | None: no upstream |
| Hysteria 2, WireGuard | None: the upstream listens on UDP |
Actor::prepare calls probe_target again for each member and hands the destination to Member::new. Balancer::new still refuses an empty member list with a balancer needs at least one outbound (as a Build error), but validation refuses that spec first.
4. The route
Section titled “4. The route”Each rule’s outbound, in rule order, and then route.default must name an outbound or a balancer:
| Rule | Variant | Text | Test |
|---|---|---|---|
| A rule names a known outbound or balancer | UnknownReference { from: Route, kind: Outbound } |
route references unknown outbound <tag> |
a_route_rule_must_name_a_known_outbound_or_balancer |
| The default names a known outbound or balancer | same | same | the_route_default_must_name_a_known_outbound_or_balancer |
The text says outbound even when a balancer was meant; the kind is fixed because both share one namespace. a_route_may_name_a_balancer accepts a default that names a balancer. Whether geosite and geoip codes exist is not validation’s to say: geodata is read by build/route.rs → compile_routes, so a missing or unreadable file, or a missing code, is a Build error on route.
5. Inbounds
Section titled “5. Inbounds”For each inbound in spec order, four steps:
-
The binds are unique. Each bind
InboundSpec::binds()yields, the inbound’s own and then its handoff socket’s, is compared with every bind collected before it (aVec<BindSpec>filled as the loop goes). An equal value, or a bind at the same socket path as one before it (BindSpec::socket_path, the path of aUnixorHandoffbind) however else the two differ, fails asInvalid { resource: Inbound(<the later inbound>) }with<bind> is bound by another inbound, naming the later bind. Captured:inbound b: 127.0.0.1:1080 is bound by another inbound. TCP and UDP binds are different kinds, so a Hysteria 2 inbound may use a SOCKS inbound’s port number (the_same_port_over_udp_is_another_bind). Tests:two_inbounds_may_not_share_a_bind, andtwo_binds_may_not_share_a_socket_path, where a handoff socket at another’s path with mode0o666instead of0o660, and a Unix listener at a handoff socket’s path, are both refused.“Equal” is
BindSpec’sPartialEq:BindSpecEqual when Tcp { host, port },Udp { host, port }Same kind, the same hoststring compared as text, and the same portUnix(path)The PathBufs are equal, which compares components: a doubled/and an inner.collapse,..does notHandoff(spec)The paths compare as for Unix, andmodeandgidare equal too. Two handoff sockets at one path collide in any case, throughsocket_pathTun(TunSource::Create(spec))The DeviceSpecs are equal field by fieldTun(TunSource::Fd(device))topology/inbound/mod.rs→impl PartialEq for SuppliedTun: the same descriptor number and the same MTU -
The user set exists. When
usersisSome(tag)and no user set carries that tag:UnknownReference { from: Inbound(tag), kind: UserSet }, printedinbound <tag> references unknown user set <set>. Test:an_inbound_must_name_a_known_user_set. -
validate_inbound, below. -
validate_admissionagainst the named set, when there is one. See Admission.
validate_inbound
Section titled “validate_inbound”Every error is Invalid { resource: Inbound(tag) }, printed inbound <tag>: <reason>.
The pairing comes first. Each protocol is served on one kind of bind:
| Protocol | Bind it needs |
|---|---|
| SOCKS, HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, AnyTLS, sss | BindSpec::Tcp or BindSpec::Unix |
| Hysteria 2 | BindSpec::Udp |
| TUN | BindSpec::Tun |
Any other combination fails with the protocol cannot be served on <bind>, for example inbound in: the protocol cannot be served on udp 127.0.0.1:2000. No protocol pairs with a Handoff bind: as an inbound’s own bind it fails here, the protocol cannot be served on handoff:<path> (a_handoff_bind_is_no_inbounds_own). Test: each_protocol_is_served_only_on_its_kind_of_bind.
Two bind rules follow the pairing:
| Rule | Reason text | Test |
|---|---|---|
| A Unix bind is served only on Unix. The check is compiled only off Unix | unix sockets are not served on <os>, with std::env::consts::OS, for example unix sockets are not served on windows |
none |
proxy_protocol is set only on a Tcp bind |
only a tcp listener reads a PROXY protocol header |
none |
When handoff is set, handoff_socket checks it next. A handoff socket stands beside a TCP listener, whose transport and protocol serve what it is handed, at a path a Unix socket can be bound at, with nothing but permission bits for its mode. Its rules, in order:
| Rule | Reason text | Test |
|---|---|---|
The platform is Unix. The check is compiled everywhere (cfg!(not(unix))) |
handoff sockets are not served on <os>, with std::env::consts::OS |
none |
The inbound’s own bind is Tcp. The protocol was already paired with its bind, so a TCP bind is a stream protocol’s |
only a stream inbound on a tcp listener takes a handoff socket |
a_handoff_socket_stands_beside_a_stream_inbounds_tcp_listener (SOCKS on a Unix bind, Hysteria 2 and TUN refused; SOCKS on TCP accepted) |
path is absolute and names a file (Path::file_name is Some) |
the handoff socket <path> must be an absolute path to a file, for example the handoff socket run/test/1080.sock must be an absolute path to a file |
a_handoff_socket_is_an_absolute_path_a_unix_socket_can_take (a relative path, / and the empty path refused) |
path is at most MAX_SOCKET_PATH (107) bytes |
the handoff socket <path> is longer than 107 bytes |
same (107 bytes accepted, 108 refused) |
mode has no bit outside 0o777 |
the handoff socket's mode <octal> holds more than permission bits, for example the handoff socket's mode 4660 holds more than permission bits |
a_handoff_sockets_mode_is_permission_bits_alone (0o4660 refused) |
The path is printed with Path::display and the mode in octal without a prefix. A gid has no rule: whether the process may give the file that group is found only when the socket is bound (see Bind).
When real_ip is set, real_ip_header checks it next. A real-IP header is read off WebSocket upgrades on a TCP listener, and counts only from a trusted proxy, so a setting that could never count is reported as a mistake rather than kept. Its three rules, in order:
| Rule | Reason text | Test |
|---|---|---|
The protocol has a transport (InboundProtocolSpec::transport()), its shape is StreamShape::Ws, and the bind is Tcp |
only a websocket transport on a tcp listener reads a real-ip header |
a_real_ip_header_needs_a_websocket_a_trusted_proxy_and_a_name (plain TCP and gRPC refused, WebSocket accepted); shadowsocks_and_socks_over_websocket_read_a_real_ip_header (accepted on Shadowsocks and SOCKS) |
trusted holds at least one network |
a real-ip header needs at least one trusted proxy |
same |
header is a valid HTTP header name |
the real-ip header "<header>" is not a header name, with the name printed with {:?}, for example the real-ip header "X Real IP" is not a header name |
same |
For every protocol that carries an InboundTransportSpec, the ones InboundProtocolSpec::transport() names (SOCKS, HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, AnyTLS and sss), inbound_transport runs next, once, in this order. A protocol added later meets the same rules without calling them (every_protocol_meets_the_same_transport_rules):
| Rule | Reason text | Test |
|---|---|---|
On a Unix bind, the shape is StreamShape::Tcp |
a unix socket carries no transport; its shape must be plain tcp |
a_unix_listener_carries_only_the_plain_tcp_shape |
| The shape layers TLS, so TLS material is present | the transport layers tls but carries no tls settings |
an_inbound_carries_tls_material_exactly_when_its_shape_layers_tls |
| TLS material is present, so the shape layers TLS | the transport carries tls settings but does not layer tls |
same |
The shape is Reality, so REALITY settings are present |
a reality transport carries no reality settings |
reality_field_must_match_its_shape |
REALITY settings are present, so the shape is Reality |
the transport carries reality settings but its shape is not reality |
same |
| At least one server name | reality needs at least one server name |
reality_settings_fail_closed |
No server name empty or holding * |
invalid reality server name "<name>", the name printed with {:?} |
same |
| At least one shortId | reality needs at least one shortId |
same |
dest has a non-zero port |
reality dest needs a non-zero port |
same |
A domain dest has a non-empty host |
reality dest needs a host |
same |
With both bounds set, min_client_version is not above max_client_version, each compared as one number (client_version_value) |
reality min_client_version is above max_client_version |
same |
A Reality shape only under VLESS |
reality is for vless only |
reality_is_vless_only, which tries every other protocol, AnyTLS included |
A VLESS inbound with VlessFlow::Vision only over a Reality shape |
vless vision (xtls-rprx-vision) rides only over reality |
none |
A Reality shape layers none of this project’s TLS, so the TLS pairing refuses TLS material beside it before the REALITY rules run. An inbound’s WebSocket host and gRPC authority may be None: a server has nothing to borrow them from and needs neither (an_inbound_needs_no_ws_host_or_grpc_authority).
Then the protocol’s own rules:
| Protocol | Rule | Reason text | Test |
|---|---|---|---|
| SOCKS | With udp on, the shape is plain StreamShape::Tcp: the relay’s datagrams go to a UDP socket beside the listener, in the clear |
socks serves udp associate over plain tcp only; turn udp off to wrap it in a transport |
socks_relays_udp_over_plain_tcp_only |
| SOCKS | On a Unix bind with udp on, udp_bind is set |
socks over a unix socket has no local IP for UDP associate; set udp_bind or turn udp off |
socks_over_a_unix_socket_needs_a_udp_bind_to_serve_udp |
| Trojan, VLESS, VMess | users is Some (needs_users) |
the protocol has no open mode and needs a user set |
trojan_vless_and_vmess_need_a_user_set |
| AnyTLS | The shape is StreamShape::Tls |
anytls runs over tls only; its shape must be tls |
anytls_needs_tls_a_user_set_and_a_scheme_that_parses |
| AnyTLS | users is Some |
the protocol has no open mode and needs a user set |
same |
| AnyTLS | A padding_scheme parses with PaddingScheme::from_lines, within 2,048 bytes once joined |
the SchemeError text, for example padding scheme line 2: an item is neither c nor min-max with 1 <= min <= max <= 1048576 |
same |
| sss | users is Some (needs_users) |
the protocol has no open mode and needs a user set |
validation_refuses_bad_limits in supervisor/tests/sss.rs |
| sss | max_datagram is at least 1 |
sss udp_max_datagram must be at least 1 |
same |
| sss | flush_delay is at most 10 ms |
sss flush_delay must be at most 10ms |
same |
| sss | header_timeout is above zero |
sss header_timeout must be above zero |
same |
| Shadowsocks 2022 | The server psk is exactly method.key_len() bytes |
the shadowsocks-2022 key must be <n> bytes for this method |
a_shadowsocks_2022_server_key_is_sized_to_its_method |
| Hysteria 2 | Not both shared_password and users |
a shared password and a user set cannot both be set; a credential would have two answers |
hysteria2_takes_a_shared_password_or_a_user_set_but_not_both |
| Hysteria 2 | One of them is set | hysteria2 needs a shared password or a user set |
same |
| Hysteria 2 | A shared password is not empty | the shared password must not be empty |
a_hysteria2_shared_password_may_not_be_empty |
| Hysteria 2 | udp_idle_timeout, when set, is 2 to 600 whole seconds |
udp_idle_timeout must be between 2 and 600 seconds |
a_hysteria2_udp_idle_timeout_is_between_2_and_600_seconds |
| Hysteria 2 | max_connections and max_circuits are at least 1 |
max_connections and max_circuits must be at least 1 |
hysteria2_serves_at_least_one_connection_and_one_circuit |
| Hysteria 2 | A Salamander key is at least 4 bytes | salamander obfs key must be at least 4 bytes |
a_salamander_key_is_at_least_4_bytes_on_either_side |
| Hysteria 2 | The quic block passes hy2_quic |
the texts of Outbounds, without the outbound prefix |
hysteria2_quic_settings_stay_within_upstreams_limits |
| Hysteria 2 | A masquerade builds with Masquerade::new |
the constructor’s error text | a_masquerade_may_not_answer_with_the_success_status |
| TUN | The device MTU (TunSource::mtu) is at least 1280 |
tun mtu must be at least 1280 |
a_tun_device_mtu_is_at_least_1280 |
| TUN | A TunSource::Create device passes check_platform |
the platform check’s error text | none |
Details that decide edge cases:
-
The idle timeout is compared as whole seconds (
Duration::as_secs).Nonemeans UDP relay is off and needs no bound;a_hysteria2_udp_idle_timeout_is_between_2_and_600_secondsaccepts 2 and 600, refuses 1 and 601, and acceptsNone. -
Shared password or user set. Were both set, a credential could have two answers.
Hysteria2InboundSpec::user_authis ignored when a shared password is set. -
SOCKS over a transport. A wrapped SOCKS inbound serves
CONNECTalone. Under TLS the relay’s datagrams would name every target the TLS hides, and behind a WebSocket or gRPC front the client reaches the front, not the relay. etemenanki-app leavesudpat its default when it reads a SOCKS inbound’s[inbound.stream], so a wrapped SOCKS inbound must setudp = false. -
AnyTLS on a Unix socket. The Unix rule wants plain TCP and AnyTLS wants TLS, so an AnyTLS inbound on a Unix bind is always refused: by the Unix rule when its shape is
Tls, and by AnyTLS’s own rule when it isTcp. -
Masquerade.
protocols/src/hysteria/server/masquerade.rs→Masquerade::newrefuses two things, and validation wraps its text as the reason. Answering an unauthenticated request with the success status would tell a prober that it had authenticated, so233is refused.http::StatusCode::from_u16accepts 100 to 999, and anything outside that is refused:inbound hy2: hysteria2: 233 is the authentication success status and cannot be used for the masqueradeinbound hy2: hysteria2: 1000 is not an HTTP status codehy2_handlerinbuild/inbound.rscallsMasquerade::newagain when it builds the handler; validation has already refused a bad one. WhenmasqueradeisNone, the handler usesMasquerade::default(): status 404, body404 page not found\n, content typetext/plain; charset=utf-8, the answer of an unconfigured Go server. -
TUN platform check.
protocols/src/tun/device.rs→check_platformrefuses two things. On every platform but Linux, macOS and Windows, a device spec withroutes, withErrorKind::Unsupported:inbound <tag>: tun routes are installed only on Linux, macOS and Windows; add them with the OS route tool. On macOS, anamethat is notutunfollowed by digits, withErrorKind::InvalidInput:inbound <tag>: tun name "<name>": macOS names a tun device utun<N>, or leave it unset. On Linux and Windows it accepts every spec. The desktoptun::open(compiled on every target but Android and iOS) calls the same function, so--testand a real start agree. On Android and iOS,tun::openrefuses every device withUnsupportedandtun devices are created by the system VPN API here; adopt its descriptor; that happens at bind time, so it is aBinderror thatcheckcannot see. On Windows, a Wintun adapter that cannot be created is aBinderror too:creating a Wintun adapter (needs wintun.dll beside the executable, and an elevated process): <e>. A supplied device (TunSource::Fd, Unix only) skips the platform check: its platform set it up. Its MTU is still checked. -
Shadowsocks 2022 server key. The server
pskmust be exactly the method’s length; the spec type says it is “decoded and sized tomethod”, so sizing is the front end’s job. etemenanki-app sizes the server key and every client key itself withnormalise_pskwhile lowering, so neitherthe shadowsocks-2022 key must be <n> bytes for this methodnorshadowsocks-2022 keys must be <n> bytes for this methodcomes from the app (see etemenanki-app). User keys are more lenient (see below).
Captured from the app, one inbound at a time:
configuration invalid: inbound s: socks serves udp associate over plain tcp only; turn udp off to wrap it in a transportconfiguration invalid: inbound t: reality is for vless onlyconfiguration invalid: inbound v: vless vision (xtls-rprx-vision) rides only over realityconfiguration invalid: inbound v: invalid reality server name "*.example.com"configuration invalid: inbound any: anytls runs over tls only; its shape must be tlsconfiguration invalid: inbound any: padding scheme line 2: an item is neither c nor min-max with 1 <= min <= max <= 1048576configuration invalid: inbound x: sss udp_max_datagram must be at least 1configuration invalid: inbound x: sss flush_delay must be at most 10msconfiguration invalid: inbound x: sss header_timeout must be above zeroAdmission
Section titled “Admission”validate_admission checks the users an inbound would admit from its set. validate calls it for each inbound that names a set, and stage_user_edit calls it for each inbound admitting a set being edited, so a user edit is held to the same rules as a full apply.
An inbound admits users by exactly one credential kind, build/users.rs → credential_kind:
| Inbound protocol | Credential kind |
|---|---|
| SOCKS, HTTP | Account |
| Hysteria 2 | Account with Hysteria2UserAuth::Account, Password with Hysteria2UserAuth::Password |
| Trojan, AnyTLS, Shadowsocks | Password |
| VLESS, VMess, sss | Uuid |
| Shadowsocks 2022 | Ss2022Psk |
| TUN | none: admission returns Ok(()) at once |
A user without that credential is skipped, here and when the inbound is built. For every other user, in key order (the set is a BTreeMap keyed by the front end’s UserId), the function derives an identity (the first table below), inserts it into seen, and runs four checks in the order of the second table, stopping at the first failure:
| Credential | Identity compared |
|---|---|
Uuid |
The 16 bytes of the UUID |
Password |
The password’s UTF-8 bytes |
Ss2022Psk |
The decoded PSK bytes as given, before normalising |
Account |
The username’s bytes, ASCII-lowercased on a Hysteria 2 inbound. The account’s password is not part of it |
| Check | Reason text | Test |
|---|---|---|
| No two users present the same identity | users <a> and <b> present the same username for accounts, users <a> and <b> present the same credential otherwise |
two_users_may_not_present_the_same_credential, hysteria2_usernames_collide_case_insensitively |
| Shadowsocks 2022: the user PSK normalises to the method | user <name>: shadowsocks-2022: PSK too short (<len> < <n>) |
a_shadowsocks_2022_user_key_must_normalise_to_the_method |
Hysteria 2 account: a name without :, and a non-empty name and password |
user <name>: a hysteria2 account needs a name without ':' and a password |
a_hysteria2_username_may_not_hold_a_colon |
| Hysteria 2 by password: the password is not empty | user <name>: a hysteria2 password must not be empty |
a_hysteria2_password_may_not_be_empty |
Each is Invalid { resource: Inbound(tag) }, printed inbound <tag>: <reason>. Why:
- One credential, one owner. If two users presented the same credential, whichever the table matched would decide who the traffic is attributed to.
<a>is the user seen first in key order and<b>the second. - Only the admitting kind counts. Two users who share a password are no conflict on a SOCKS inbound, which admits by account (
a_shared_credential_of_another_kind_is_no_conflict). - Hysteria 2 folds case. Hysteria 2 compares usernames case-insensitively on the wire (
Authenticator::user_passlowercases withto_ascii_lowercasetoo), soAliceandaliceare one username there and only there. On a SOCKS inbound the same two names are distinct. - The Hysteria 2 wire form is
user:pass. A name holding a colon could never be presented, and an empty part is no credential. SOCKS carries the name in its own field and accepts a colon (a_hysteria2_username_may_not_hold_a_colonchecks a SOCKS inbound). - A longer Shadowsocks 2022 user key is folded, not refused:
normalise_psktakes the firstkey_lenbytes of its SHA-256. Each inbound admitting the user normalises the key to its own method’s length, which is why the check lives in admission and not on the user.
Admission texts name the user rather than the credential, and key errors print lengths only. A user is named by UserId::name(), a supervisor/src/entity/user.rs → UserName (Email or Username), whose Display is the bare string:
| Front end | UserId |
name() |
|---|---|---|
| etemenanki-app | app/src/lower.rs → UserKey, which is UserName itself |
The user’s email. A SOCKS or HTTP account, and a Hysteria 2 user without an email, is named by the username it authenticates as, so for those users the text shows that username |
| katana | src/lower/mod.rs → Uid(i64), the panel user id |
UserName::Username of the id in decimal |
Captured from the app:
configuration invalid: inbound t: users a@example.com and b@example.com present the same credentialconfiguration invalid: inbound ss: users alice and bob present the same credentialconfiguration invalid: inbound ss: user alice: shadowsocks-2022: PSK too short (15 < 16)configuration invalid: inbound hy2: users Alice and alice present the same usernameconfiguration invalid: inbound hy2: user a:b: a hysteria2 account needs a name without ':' and a passwordconfiguration invalid: inbound hy2: user a: a hysteria2 account needs a name without ':' and a passwordThe last line is a user with an empty password.
Errors after validation
Section titled “Errors after validation”Disruptive
Section titled “Disruptive”Actor::apply checks the plan right after staging returns and before it prepares anything:
let (spec, plan, users) = self.stage(spec).await?;if !options.allow_disruptive && let Some((inbound, reason)) = plan.disruptions().next(){ let refused = ApplyError::Disruptive { inbound: inbound.clone(), reason: reason.clone() }; drop_off_runtime((spec, users)); return Err(refused);}Only the first disruption in step order is reported. Plan::disruptions() yields the Step::Disrupt steps in the order of the plan, and plan collects them in a list of handler swaps that it appends after Step::PublishPlane, one inbound at a time in spec order. The reported disruption is therefore the first disruptive inbound in spec order. The text is inbound <tag>: <reason>; this ends its live connections and needs allow_disruptive, for example inbound hy2-in: the hysteria2 obfuscation changed; connected clients cannot follow the new key; this ends its live connections and needs allow_disruptive. Which changes are disruptive, and every reason text, are on Planning and applying a change. A refused disruptive spec binds nothing, but staging has already built its handlers and user tables; they are dropped with the spec on the blocking pool (drop_off_runtime). Test: a_hysteria2_obfuscation_change_needs_allow_disruptive in supervisor/tests/hot_swap.rs.
The spec was valid, but constructing one of its resources failed. Actor::prepare wraps each failure with the resource it was building. An inbound’s handler or user table is built earlier, in staging (stage_users, or stage_user_edit for a user edit), and prepare reports its error in inbound order, after DNS, outbounds, balancers and the route:
| Resource in the text | Built by | Typical cause |
|---|---|---|
dns |
build/dns.rs → build_dns |
A resolver that does not build, or an unreadable system hosts file for a split spec with use_hosts |
outbound <tag>@v<n> |
build/outbound.rs → build_outbound |
A CA bundle that does not parse |
balancer <tag> |
Balancer::new |
An empty member list, which validation refuses first |
route |
build/route.rs → compile_routes |
Geodata missing, unreadable or without a referenced code |
inbound <tag> |
In staging: build_handler, user_table, UserTarget::prepare (which builds a VMess set with UserTable::prepare_for). In prepare: prepare_swap, Pending::pair |
A certificate or key that does not parse; a QUIC endpoint that cannot open on its socket; a TUN device that cannot be prepared |
Captured from the app:
configuration invalid: building inbound v failed: no certificate in PEM bundleconfiguration invalid: building inbound hy2 failed: hysteria2: the certificate file contains no certificatesconfiguration invalid: building outbound t-out@v1 failed: no certificate in CA PEM bundleconfiguration invalid: building route failed: a geosite matcher is used but no geosite file is configuredconfiguration invalid: building inbound ss failed: shadowsocks-2022: multi-user requires an aes-gcm methodSome builders repeat a rule validation already enforces, as a backstop. Each fails as Build if it is ever reached:
| Backstop | Text | Repeats |
|---|---|---|
build/inbound.rs → hy2_handler |
Masquerade::new’s text |
The masquerade rule |
build/inbound.rs → user_table |
inbound <tag>: user <label>: <e> around normalise_psk’s error |
The Shadowsocks 2022 user key rule |
build/inbound.rs → mismatch |
inbound <tag>: protocol and bind do not match |
The protocol and bind pairing: a TUN protocol whose bind is not a device, or a stream protocol whose user table came out as a Hysteria 2 table, a prepared VMess set or none |
build/inbound.rs → build_transport |
missing tls; missing reality settings; not a header name: "<name>" from WsRoute::real_ip_header |
The inbound TLS and REALITY pairings; the real-IP header name rule |
build/inbound.rs → padding |
the SchemeError text, as InvalidInput |
The AnyTLS padding scheme rule |
build/outbound.rs → transport_connector |
missing tls, missing ws host, missing grpc authority, missing reality |
The outbound TLS and REALITY pairings and the WebSocket and gRPC rules |
system/listener.rs → check_obfs |
malformed: hysteria2 obfs psk is too short, from Salamander::new, as InvalidInput |
The Salamander key length |
system/listener.rs → mismatch |
the handler is not of the kind its listener serves |
A handler or user table of another kind than its listener, in Pending::pair, prepare_swap and UserTarget::prepare |
topology/balancer.rs → Balancer::new |
a balancer needs at least one outbound |
The empty balancer rule |
check_obfs runs in prepare (in Pending::pair and prepare_swap) so that switching a live listener to a new key cannot fail at commit.
Validator::from_config has one more backstop, which does not fail: when two admitted users’ keys are equal once normalised, it keeps the first, skips the second and logs shadowsocks-2022: users "<a>" and "<b>" share a key; only "<a>" is matched at WARN. The protocols test users_sharing_a_psk_resolve_to_the_first pins it.
system/listener.rs → bind failed for a new listener: a TCP, UDP, Unix or handoff bind, a Unix or handoff socket path that holds something other than a socket, a Unix or handoff bind that finds no free staging name (no free name to stage <path> under), a handoff socket’s directory that cannot be created or given its mode or group, a handoff socket that cannot be given its mode or group, creating a TUN device (tun::open), adopting a supplied one (tun::adopt, Unix only), or taking a second handle on the device (try_clone). On Windows, a Wintun adapter that cannot be created fails with creating a Wintun adapter (needs wintun.dll beside the executable, and an elevated process): <e>. Off Unix, a Unix bind or a handoff socket fails with ErrorKind::Unsupported and unix socket <path>: not served on this platform, a backstop that validation’s unix sockets are not served on <os> or handoff sockets are not served on <os> reaches first. The text is inbound <tag>: binding <bind> failed: <io error>. Only listener::bind produces Bind. What Pending::pair does with a bound socket (open the Hysteria 2 QUIC endpoint, prepare a TUN device) fails as Build.
A Unix or handoff socket is bound under a staging name beside its path and moved over the path when its listener starts, at commit. At the path, bind looks at what is there first (symlink_metadata):
| At the path | bind |
|---|---|
| Nothing | Binds |
| A stale socket file | Binds; the file is replaced at commit |
| A file that is not a socket | Refuses with ErrorKind::AlreadyExists and <path> exists and is not a socket, for example inbound socks: binding unix:/run/etemenanki/socks.sock failed: /run/etemenanki/socks.sock exists and is not a socket |
bind logs at INFO when it takes a TUN device: inbound <tag> owns tun device <name> for a created one, inbound <tag> serves a supplied tun device for an adopted one. Those lines come from prepare, so they appear even for an apply that is refused afterwards. inbound <tag> listening on <bind> is logged only when commit starts the listener.
Stopped
Section titled “Stopped”Every Supervisor method that changes or reads what the actor owns (apply, apply_with, update, update_with, set_users, upsert_user, remove_user, close, sessions, shutdown) goes through ask, which sends a Command on the actor’s channel (capacity 16) and awaits a oneshot reply. Either step failing becomes Stopped: the actor has shut down, or it dropped the reply. Command::Update (through Actor::edited) and stage_user_edit also return Stopped when there is no running spec to edit. close and sessions turn Stopped into 0 and an empty list, and shutdown ignores it. http_ping looks its outbound up through ask too (Command::Target), and a failure there is the delay test’s own PingError::Stopped (the supervisor has stopped), not an ApplyError.
The user path
Section titled “The user path”set_users, upsert_user and remove_user do not run validate: they change one user set and nothing else. Actor::edit_users stages the edit on the blocking pool with stage_user_edit, which fails with:
| Case | Error | Text |
|---|---|---|
| No running spec | Stopped |
the supervisor has shut down |
| No set carries the tag | Invalid { resource: UserSet(tag) } |
user set <tag>: no such user set |
| An inbound admitting the set refuses a user | Invalid { resource: Inbound(tag) } |
the admission texts |
A user table does not build (user_table) or does not fit its listener (UserTarget::prepare) |
Build { resource: Inbound(tag) } |
building inbound <tag> failed: <io error> |
remove_user for a user who is not in the set returns Ok(false) and checks nothing. Every table is prepared before any is stored, so a refused edit stores none. Users, principals and sessions covers the rest of that path.
The dry run: check
Section titled “The dry run: check”check runs the first half of an apply on a throwaway actor:
pub async fn check<U: UserId>(spec: &Spec<U>) -> Result<(), ApplyError> { let mut actor = Actor::new(SocketOptions::default()); let (spec, plan, users) = actor.stage(spec.clone()).await?; let checked = actor.prepare(&plan, &spec, users, false).await.map(drop); drop_off_runtime(spec); checked}Actor::new builds the actor’s state (root token, TaskTracker, Sessions, Tracker, sampler) and spawns nothing. Its running state is RunningState::empty(), so the plan builds every resource and reuses none, and it has no Disrupt step. check clones the spec, because staging moves it to the blocking pool. Actor::stage plans it and stages its users there, the same staging an apply runs; prepare then runs with bind = false. Whatever was built is dropped when check returns, and the spec is dropped on the blocking pool.
What check covers:
| Step | Done | Can fail with |
|---|---|---|
validate, in staging |
Every rule on this page | The validation variants |
admit for each inbound, in staging |
Admissions and user keys | none |
build_handler for each inbound, in staging |
Server TLS configs from the PEM bytes, the Hysteria 2 QUIC server config and masquerade, user tables (including Validator::from_config) |
Build on inbound <tag>, reported by prepare after the rows below |
build_dns |
The resolvers; for a split spec with use_hosts, reads the system hosts file |
Build on dns |
build_outbound for each outbound |
Transport connectors, TLS client configs and CA bundles, protocol keys | Build on outbound <tag>@v<n> |
Balancer::new for each balancer |
Members with their probe destinations; no probe task is started | Build on balancer <tag> |
compile_routes |
The route table, and the geodata sets the rules reference, read from their files | Build on route |
What check cannot see:
| Not done | Where it happens on a start | Fails with |
|---|---|---|
| Binding TCP, UDP, Unix and handoff listeners, including the check that a socket path holds no other file, and creating a handoff socket’s directory and giving it and the socket their mode and group | listener::bind |
Bind |
Creating a TUN device and installing its routes (tun::open, including the Wintun adapter on Windows), or adopting a supplied descriptor (tun::adopt) |
listener::bind |
Bind |
Opening the Hysteria 2 endpoint on its socket (Hy2Inbound::open), checking its obfuscation key (check_obfs), preparing a TUN device (TunInbound::prepare) |
Pending::pair |
Build |
| A disruption against a running supervisor | Actor::apply |
Disruptive |
| Anything on the network: resolving upstreams, reaching them, probing balancer members | after commit | not an ApplyError |
So check and a start agree on every semantic rule and on every constructor except the bind-time ones. A spec that passes check can still be refused by a running supervisor as Disruptive, because check plans from nothing. The app demonstrates the bind gap: a SOCKS inbound whose listen names an existing regular file passes --test with Configuration OK., and a start refuses it as Bind.
check runs on the caller’s task, except for staging and the final drop, which run on the blocking pool (system/blocking.rs → off_runtime, drop_off_runtime). It takes no SupervisorBuilder settings: its actor uses SocketOptions::default(). The socket policy has no effect there, because check dials nothing.
Callers:
| Caller | Function | What it checks |
|---|---|---|
etemenanki-app --test |
app/src/instance.rs → check → check_bytes |
The config file and the subscribe file it names, merged and lowered, and the [api] options (crate::api::options), then etemenanki_supervisor::check on the spec. A bad [api] therefore fails --test as LoadError::Config |
| etemenanki-app REST API | app/src/api.rs → ConfigFile::set_route → check_bytes |
The edited config, before it is written |
| katana | src/runtime.rs → check_node → lower::test_spec |
The node’s real_ip_header and real_ip_from, its handoff keys and its [node.hysteria] congestion, the process-wide outbounds and DNS and the node’s own route table (without audit rules), plus the locally configured inbound of a node whose node_type is Hysteria 2 |
| Tests | app/tests/unit/subscribe.rs → every_lowered_node_builds_and_the_dns_setup_with_it; katana tests/unit/lower/outbound.rs → wireguard_ipv4_only_builds_with_ipv4_address, wireguard_ipv6_only_requires_ipv6_address |
A lowered subscribe example; katana’s WireGuard lowering |
In katana, build_node (used at startup and for the nodes a reload adds), test_config (--test) and apply_reload call check_node, each after building the node’s panel client. For a node whose node_type is Hysteria 2, test_spec lowers the inbound from [node.hysteria] (src/api/hysteria.rs → local, with a port of 0 replaced by 1) and admits one placeholder user (uid 0, email placeholder). For every other node, a helium node included (it names no node_type, because its panel describes the protocol), the inbound and its users come from the panel and are not part of the check. Before either, test_spec lowers [node.controller]’s real_ip_header and real_ip_from (src/lower/inbound.rs → real_ip) for every node type: those keys are local, so a mistake in them is refused at --test, start and reload, before any panel names a WebSocket node (the_node_check_refuses_a_half_real_ip_setting in tests/unit/lower/spec.rs). It also judges [node.hysteria] congestion (inbound::congestion) on every node, so --test reports unknown hysteria congestion "vegas" (expected "cubic", "bbr" or "reno") on a helium node too, before its panel describes a Hysteria 2 node (a_helium_nodes_check_judges_its_congestion_control).
How front ends report the errors
Section titled “How front ends report the errors”The supervisor returns an ApplyError and logs nothing about a refusal. Its only log line about an apply is the DEBUG line applied: <n> built, <n> reused, <n> swapped, <n> drained at the end of a commit (supervisor.rs → Actor::commit). Each front end adds its own context.
etemenanki-app
Section titled “etemenanki-app”app/src/instance.rs → LoadError joins the two sources of failure, both #[error(transparent)], so the text is the inner error’s:
pub enum LoadError { /// The files could not be read, or what they say could not be lowered. Config(#[from] io::Error), /// The supervisor refused the spec. Apply(#[from] ApplyError),}The app’s lowering (app/src/lower.rs → lower) refuses syntax and file problems itself (LoadError::Config) and leaves the rules on this page to the supervisor, with two exceptions:
- Shadowsocks 2022 server and client keys. The spec wants them sized to the method, so the lowering sizes them with
normalise_psk: it folds a longer key and refuses a short one, asinbound <tag>: shadowsocks-2022: PSK too short (<len> < <n>)oroutbound <tag>: shadowsocks-2022: PSK too short (<len> < <n>). A user’s key is decoded but not sized, because its size depends on the inbound admitting it, so the supervisor’s admission check sizes it. - User names. A user set is a map, so a second entry under a taken name would replace the first. The lowering refuses a user without the name its protocol keys it by (
inbound <tag>: users[<i>] has no email; a user of this inbound is named by its email, or… has no userfor an account) and two entries under one name (inbound <tag>: users[<i>] and users[<j>] are both named "<name>";accounts[…]for SOCKS and HTTP). Two names presenting one credential are left to admission.
app/tests/unit/lower.rs → semantic_problems_are_left_to_the_supervisor lowers a config that breaks many of this page’s rules (a duplicate inbound tag, a TUN MTU of 1000, a Hysteria 2 inbound with both a password and users, a 1-second UDP idle timeout and zero circuits, a shared Trojan password, a WireGuard family without a matching address, a Hysteria 2 client with zero streams, a balancer and a rule naming a missing outbound), and asserts that lowering accepts it and carries those values into the spec. syntax_errors_are_refused pins what the app refuses on its own. The lowering itself is on etemenanki-app: from TOML to a spec.
Captured from the app, the lowering’s own refusals print without the supervisor’s wording:
configuration invalid: inbound ss: shadowsocks-2022: PSK too short (16 < 32)configuration invalid: outbound ss-out: shadowsocks-2022: PSK too short (15 < 16)configuration invalid: inbound t: users[0] and users[1] are both named "alice@example.com"configuration invalid: inbound t: users[1] has no email; a user of this inbound is named by its emailThe app’s tracing_subscriber::fmt subscriber writes to stdout, ERROR lines included. The --test and start lines are logged by target etemenanki_app (app/src/main.rs); config loaded, config reloaded and the reload errors by target etemenanki_app::instance.
| Where | Output |
|---|---|
--test, accepted |
Configuration OK. on stdout, exit status 0 |
--test, refused |
configuration invalid: <e> at ERROR, exit status 1 |
| Start, refused | failed to start: <e> at ERROR, exit status 1 |
| Start, API cannot start | failed to start: API on <listen>: <e> at ERROR, exit status 1 |
| Start, applied | config loaded: <summary> at INFO |
| Reload, applied | config reloaded: <summary> at INFO |
| Reload, files unreadable | reload: cannot read <path>: <e> at ERROR |
Reload, refused as Disruptive |
reload refused, keeping the running config: inbound <tag>: <reason>, which would end its live connections; restart to apply it at ERROR |
| Reload, any other refusal | reload: <e>; keeping the running config at ERROR |
The app starts with SupervisorBuilder::start (Instance::start → Core::start with Supervisor::builder()) and reloads with Supervisor::apply, both with the default ApplyOptions. It refuses a reload that changes a TUN inbound (its device or its settings) or a Hysteria 2 listener’s obfuscation, and a restart applies it. <summary> is the summary format described under ApplyReport. The reload path is on etemenanki-app: running, reloading and shutting down.
For the REST API, impl From<LoadError> for ControlError sorts failures by fault. Bind and Stopped become ControlError::Failed (HTTP 500): not the config’s fault. Every other ApplyError becomes ControlError::Invalid (HTTP 422). An io::Error from lowering is Invalid when its kind is InvalidData or InvalidInput, and Failed otherwise. The other two variants do not come from a load: UnknownGroup (HTTP 404, no route group named "<group>") and Stale (HTTP 409, the config file has changed since it was read; its ETag is now <etag>). webclient/src/router.rs maps each variant to its status. ConfigFile::set_route refuses as Stale in two places: before the edit, when If-Match names another ETag, and after check_bytes, when the file on disk no longer holds the bytes it read. It re-reads the file at that point because the check builds everything a start would and takes a while, and a hand edit saved meanwhile must not be overwritten.
The FFI
Section titled “The FFI”FfiError is declared #[uniffi(flat_error)]. ffi/src/error.rs → impl From<LoadError> for FfiError first picks out the client’s own refusal of a server inbound, FfiError::ServerInbound, printed inbound "<tag>" serves <protocol>, a server protocol; only a tun inbound and local socks or http inbounds run in a client. Everything else goes through ControlError:
ControlError |
FfiError |
|---|---|
Invalid |
Config { message } |
Stale |
Config, with the Stale text as its message |
UnknownGroup |
UnknownGroup { group } |
Failed |
Io { message } |
Config and Io print the message alone, so a mobile app sees the ApplyError text unchanged. Because ApplyError::Stopped becomes ControlError::Failed, it reaches the app as FfiError::Io with the text the supervisor has shut down, not as FfiError::Stopped (Mobile library (etemenanki-ffi)).
katana
Section titled “katana”--test(src/runtime.rs→test_config) first refuses a config without nodes (config defines no [[node]] entries), runswarn_shared_wireguard(aWARNwhen several nodes route to one WireGuard outbound), then builds each node’s panel client and runscheck_node, prefixing any error with the node id. It printsConfiguration OKon stdout, orconfiguration error: <e>on stderr with exit status 1. Captured:configuration error: node 1: outbound wg-egress@v0: wireguard address_family ipv6_only needs an IPv6 address.- A config file reload (
apply_reload) runscheck_nodefor each new or changed node, and for every node when[[outbound]]or[dns]changed, before it touches any running one. A refusal logsreload: node <node>: <e>; keeping current configatERROR, where<node>is<panel_type>@<host>#<node_id>, followed by/<node_type>when one is set. See Process runtime and reload. - A node applies its spec with
Supervisor::apply_withandApplyOptions { allow_disruptive: true }(src/manager/node.rs→reconcile), so katana never receivesDisruptive, and a changed Hysteria 2 obfuscation is applied rather than refused. See Node manager. - katana reads a Hysteria 2 node’s
[node.hysteria]insrc/api/hysteria.rs(localfor a node the block describes alone,uniproxyfor a UniProxy node it completes) and keeps two checks of its own there that the supervisor also makes: the Salamander key length (obfs_password must be at least 4 bytes for salamander) and the 2 to 600 second UDP idle timeout (upstream’s range). The same file refuses settings the supervisor has no rule for:udp_idle_timeout is set but udp is not enabled,obfs_password is set but obfs is not; did you mean obfs = "salamander"?andunknown obfs "<x>" (expected "salamander"). It then holds the node to helium-node-api’s rules (validate), which a helium panel’s node config meets as it is read. The lowering of the inbound (src/lower/inbound.rs→lower_hysteria) checks the masquerade throughMasquerade::new(its comment: the supervisor refuses the same responses, and katana judges them too “so the refusal reads as it always has”), and refusesunknown hysteria credential kind "<x>" (expected "uuid" or "user_pass")andunknown hysteria congestion "<x>" (expected "cubic", "bbr" or "reno"). These texts carry noinboundprefix, for exampleconfiguration error: node 1: udp_idle_timeout must be between 2 and 600 secondsandconfiguration error: node 1: obfs_password must be at least 4 bytes for salamander. The supervisor’s rules still apply behind them. Lowering inbounds and outbounds covers that file. PanelClient::new(src/api/mod.rs) builds the client a node’spanel_typenames:NewV2boardorV2board, orHelium, in any case. It refusesSSpanel, in any case, by name, withpanel_type "SSpanel" is not supported: katana serves the NewV2board and Helium panelsquoting the value as the file spells it, and any other value withunknown panel_type "<value>", the value lower-cased.--testprints, for example,configuration error: node 1: panel_type "SSpanel" is not supported: katana serves the NewV2board and Helium panels. At startup a node it refuses is logged and not run; a reload that names one is refused as a whole.- A helium node’s panel client (
src/api/helium.rs→Client::new,refuse_local_protocol) refuses a local key that would say what the panel describes:[node.api] node_typeandenable_vless, and every[node.hysteria]key butcongestion. It names the first one set, in that order, for exampleconfiguration error: node 1: [node.api] node_type is set, but a helium node's protocol is described by the panel; remove it (of [node.hysteria], only congestion is this host's to choose).build_node,test_configandapply_reloadeach build the client before they callcheck_node, so a start,--testand a reload all refuse it, and a reload that hits it is refused as a whole. A newV2board client refusesnode_type = "sss"the same way, withnewV2board: no UniProxy panel describes an sss node; sss is Helium's own protocol, served with panel_type = "Helium". See Panel clients. - katana’s real-IP lowering (
src/lower/inbound.rs→real_ip) takesreal_ip_headerandreal_ip_fromtogether or not at all, and refuses what the supervisor would refuse later or could never see:real_ip_from is set without real_ip_header,real_ip_header needs real_ip_from: the proxies trusted to set it,real_ip_header "<h>" is not a header name, andreal_ip_from "<net>": <cidr error>for a network that does not parse. Its comment gives the reason: refusing a half or a typo keeps a node from quietly taking no header, or from trusting an address no one meant. These texts carry noinboundprefix either, for exampleconfiguration error: node 1: real_ip_header needs real_ip_from: the proxies trusted to set it. The loweredRealIpSpecreaches the inbound only on a node whose transport is WebSocket, so the supervisor’s own rules never see it elsewhere. - katana’s handoff lowering (
src/lower/inbound.rs→handoff) readshandoff_dirandhandoff_group, and refuses what would leave a socket the relay cannot reach:handoff_group is set without handoff_dir,handoff_dir "<dir>" must be an absolute path,handoff_dir "<dir>" is too long: with "<name>" in it, a socket's path would pass the 107 bytes a Unix socket's path may have, where<name>is the node’s longest socket name, its name at port 65535 (65535.sockon every address,<listen_ip>-65535.sockon one),handoff_group "<name>": reading /etc/group: <error>andhandoff_group "<name>" is not a group in /etc/group.test_specruns it for every node type, Hysteria 2 included, so--test, a start and a reload refuse a bad key before any panel names a port, for exampleconfiguration error: node 1: handoff_group is set without handoff_dir. The socket path it lowers is then held to the supervisor’s rules too, and the directory’s creation, mode and group are checked only when the socket is bound. - katana’s user lowering (
src/lower/mod.rs→lower_users) skips, with aWARN, a user whose credential cannot be lowered (skipping user <uid>: <why>), a uid listed twice (skipping user <uid>: listed twice), and a user whose credential an earlier user already presented (skipping user <uid>: shares its credential with user <first>). The first user keeps the credential, so two panel users who share one do not reachvalidate_admission. The reasons name the user and never the credential. See Lowering a node into a spec.
Invariants
Section titled “Invariants”| Invariant | Why | Pinned by |
|---|---|---|
| Every apply, update, start and check validates before it plans a step | plan calls validate first, and every path calls plan |
supervisor/tests/unit/plan.rs → an_invalid_spec_is_refused_without_a_plan |
| A refused spec changes nothing that runs | Validation and Disruptive refuse before prepare; staging and prepare have no visible effect, and what they built is dropped |
supervisor/tests/hot_swap.rs → a_refused_spec_changes_nothing: an unknown route target, and a spec that also swaps the user set and the route default but cannot bind a port, both leave the epoch, the users and the listeners as they were |
| Validation touches no file, socket or clock | Pure functions over the spec | The unit tests build every spec in memory with arbitrary TLS bytes |
| Each rule is tested alone | Each test breaks one rule in an otherwise valid spec and, where the rule has an edge, checks the edge that is still accepted | supervisor/tests/unit/validate.rs (module comment) |
| The builders can assume validity | The expect calls in Actor::prepare rely on validation |
the tag and balancer tests |
| Outbound and balancer tags share one namespace; inbound and user set tags do not | A route names outbounds and balancers alike | a_balancer_may_not_share_an_outbounds_tag, an_inbound_may_share_an_outbounds_tag |
| No spec tag is empty | The empty tag names the supervisor’s own targets | no_tag_may_be_empty |
| A user edit meets the same admission rules as an apply | stage_user_edit calls validate_admission |
no dedicated test |
| Admission texts name the user, not the credential | Users are named by UserId::name(); key errors print lengths only. A name may be an account’s username (etemenanki-app) |
no dedicated test |
check and a start agree on semantics and construction |
The same stage and prepare, differing only in bind |
no dedicated test |
Failure paths and cancellation
Section titled “Failure paths and cancellation”- One error per refusal.
validatereturns at the first broken rule, andprepareat the first failed step. A spec with several problems needs as many attempts to find them. - What a refusal releases. Everything staging and
preparebuilt lives in local values, the staged users and thePreparedstruct. On an error they are dropped; the spec, and on aDisruptiverefusal the staged users with it, are dropped on the blocking pool (drop_off_runtime). Listeners bound earlier in the same prepare close again (a_refused_spec_changes_nothingbinds a spare port first and checks that it is free afterwards), and a Unix or handoff socket file created by such a bind, still under its staging name, is removed by itsSocketFileguard. Nothing at the socket’s path was touched, so a running listener’s socket file stays where it is. User keys are handed out on a staged copy ofUserKeys, kept only if the apply commits. - Dropping an apply future.
askfirst sends the command, then awaits the reply. A caller that drops the future while the send is still waiting for channel capacity sends nothing. Once the command is in the channel, the actor runs the apply to the end and commits it if it succeeds; the reply is then sent to nobody and ignored (let _ = reply.send(...)). checkis an ordinary future on the caller’s task, apart from its staging and its final drop, which it hands to the blocking pool. Dropping it drops everything prepare built. A blocking-pool task cannot be cancelled, so staging that is already running when the future is dropped runs to its end, and what it built is dropped with its result.- The first spec.
SupervisorBuilder::startapplies the first spec before it spawns the sampler, the guard’s sweep, the usage sink or the actor task. A refused first spec starts nothing and returns theApplyError. Before it applies anything,startasserts that the sample interval is not zero; a zero interval panics withthe sample interval must not be zeroinstead of returning anApplyError. - Logs from a refused apply. The supervisor logs no refusal, but prepare’s own
INFOlines stay in the log: a TUN device created or adopted while preparing an apply that is refused afterwards has already loggedinbound <tag> owns tun device <name>orinbound <tag> serves a supplied tun device.
Limits
Section titled “Limits”| Limit | Value | Where |
|---|---|---|
| Errors reported per refusal | 1 | validate, prepare |
| TUN MTU | at least 1280 (MIN_TUN_MTU) |
validate_inbound |
| Hysteria 2 UDP idle timeout | 2 to 600 whole seconds, inclusive (HY2_UDP_IDLE), when set |
validate_inbound |
Hysteria 2 max_connections, max_circuits |
at least 1 | validate_inbound |
Hysteria 2 client max_concurrent_streams |
at least 1 | validate_outbound |
| Salamander key | at least 4 bytes (MIN_SALAMANDER_PSK) |
obfs |
| Masquerade status | 100 to 999, except 233 | Masquerade::new |
| Hysteria 2 QUIC receive windows | 16,384 (QuicOptions::MIN_RECEIVE_WINDOW) to 2^62 − 1 (QUIC_VARINT_MAX) bytes, on both sides |
hy2_quic |
Hysteria 2 max_idle_timeout |
4 to 120 whole seconds (HY2_IDLE_TIMEOUT), on both sides |
hy2_quic |
Hysteria 2 keep_alive_period |
2 to 60 whole seconds (HY2_KEEP_ALIVE), when set, on both sides |
hy2_quic |
Hysteria 2 max_incoming_streams |
at least 1, when set | hy2_quic |
| Hysteria 2 hop ports | at least one, none of them 0 | port_hopping |
| Hysteria 2 hop interval | shortest draw at least 5 s (HopInterval::MIN_CONFIGURED) |
port_hopping |
| Shadowsocks 2022 server key and client keys | exactly 16 bytes (2022-blake3-aes-128-gcm) or 32 bytes (2022-blake3-aes-256-gcm, 2022-blake3-chacha20-poly1305) |
validate_inbound, validate_outbound |
| Shadowsocks 2022 user key | at least the method’s length; longer keys are folded | validate_admission |
| Shadowsocks 2022 inbound admitting users | 2022-blake3-aes-128-gcm or 2022-blake3-aes-256-gcm only |
Validator::from_config, at build time |
| AnyTLS padding scheme | at most 2,048 bytes once joined (MAX_SCHEME_LEN) |
PaddingScheme::from_lines, from validate_inbound |
sss max_datagram |
at least 1 | sss_limits, both sides |
sss flush_delay |
at most 10 ms (MAX_FLUSH_DELAY) |
sss_limits, both sides |
sss header_timeout |
above zero | validate_inbound |
| REALITY server names and shortIds | at least one each; no empty name, no * |
reality_settings; one server name, outbound_transport |
| Supervisor command channel | 16 queued commands | SupervisorBuilder::start |
supervisor/tests/unit/validate.rs is compiled into the crate (#[path] from build/validate.rs), so cargo test -p etemenanki-supervisor --lib runs it. It builds a valid base spec (one SOCKS inbound on 127.0.0.1:1080, one freedom outbound direct, the system resolver) and breaks one rule at a time.
| Test | Pins |
|---|---|
the_base_spec_is_valid |
The base spec passes |
tags_are_unique_within_each_kind |
DuplicateTag for inbounds, outbounds, balancers and user sets |
a_balancer_may_not_share_an_outbounds_tag |
The shared namespace |
an_inbound_may_share_an_outbounds_tag |
Other kinds live apart |
no_tag_may_be_empty |
Invalid on the inbound, the outbound and the user set |
a_route_rule_must_name_a_known_outbound_or_balancer |
UnknownReference from Route |
the_route_default_must_name_a_known_outbound_or_balancer |
The same for the default |
a_route_may_name_a_balancer |
A balancer is routable |
a_balancer_member_must_be_a_known_outbound |
UnknownReference from the balancer |
a_balancer_member_may_not_be_another_balancer |
Members are outbounds only |
an_inbound_must_name_a_known_user_set |
UnknownReference from the inbound, kind UserSet |
a_balancer_needs_a_member |
EmptyBalancer |
a_balancer_member_needs_an_upstream_a_tcp_probe_can_reach |
UnprobeableMember for freedom, blackhole, Hysteria 2 and WireGuard |
two_inbounds_may_not_share_a_bind |
The later inbound is invalid |
the_same_port_over_udp_is_another_bind |
TCP and UDP binds differ |
each_protocol_is_served_only_on_its_kind_of_bind |
Six refused pairings, three accepted |
an_inbound_carries_tls_material_exactly_when_its_shape_layers_tls |
Eight shape and material combinations |
an_inbound_needs_no_ws_host_or_grpc_authority |
Inbound gaps are accepted |
an_outbound_carries_tls_settings_exactly_when_its_shape_layers_tls |
Six combinations |
an_outbound_needs_a_ws_host_and_a_grpc_authority |
Outbound gaps are refused |
a_unix_listener_carries_only_the_plain_tcp_shape |
TLS and WebSocket shapes refused on a Unix bind |
every_protocol_meets_the_same_transport_rules |
SOCKS, HTTP, Trojan, VLESS, VMess, Shadowsocks and Shadowsocks 2022 over the same six transports, on TCP and Unix binds: gRPC with TLS and WebSocket without accepted, mismatched TLS refused, and on a Unix bind only plain TCP |
shadowsocks_runs_over_a_transport |
Shadowsocks of either kind over TLS, WebSocket and gRPC, with and without TLS, in its shared mode |
socks_relays_udp_over_plain_tcp_only |
SOCKS with udp refused over TLS, WebSocket and gRPC, accepted without it, and accepted over plain TCP with it |
shadowsocks_and_socks_over_websocket_read_a_real_ip_header |
A real-IP header accepted on Shadowsocks and SOCKS over WebSocket |
anytls_needs_tls_a_user_set_and_a_scheme_that_parses |
AnyTLS over TLS with and without a scheme accepted; no user set, the plain TCP, WebSocket and gRPC shapes, an empty scheme, stop=x, a scheme with no stop, a \r, a reversed range and one over 2 KiB refused; a Unix bind refused |
an_anytls_outbound_needs_tls_and_a_password |
An AnyTLS client over plain TCP, WebSocket or gRPC refused, an empty password refused, and the Tls shape without TLS settings refused |
a_vless_reality_inbound_validates, reality_settings_fail_closed |
A VLESS inbound over REALITY accepted; no server name, a wildcard name, no shortId, port 0, an empty host and reversed client versions refused |
reality_field_must_match_its_shape, reality_is_vless_only |
The REALITY shape without settings and settings beside a TCP shape refused; every other protocol, AnyTLS included, refused over REALITY |
a_reality_outbound_validates_and_its_field_must_match, a_reality_outbound_is_vless_only |
A VLESS client over REALITY accepted, the field against its shape refused both ways; a Trojan client over REALITY refused |
a_handoff_socket_stands_beside_a_stream_inbounds_tcp_listener |
A handoff socket beside SOCKS on TCP accepted; beside SOCKS on a Unix bind, Hysteria 2 and TUN refused |
a_handoff_bind_is_no_inbounds_own |
A Handoff bind as an inbound’s own bind refused |
a_handoff_socket_is_an_absolute_path_a_unix_socket_can_take |
A relative path, / and the empty path refused; 107 bytes accepted, 108 refused |
a_handoff_sockets_mode_is_permission_bits_alone |
Mode 0o4660 refused |
two_binds_may_not_share_a_socket_path |
A second inbound’s handoff socket at the first’s path with another mode, and a Unix listener at a handoff socket’s path, refused |
a_real_ip_header_needs_a_websocket_a_trusted_proxy_and_a_name |
X-Real-IP trusting 127.0.0.1/32 and ::1/128 on WebSocket accepted; plain TCP, gRPC, no trusted network and the name X Real IP refused |
trojan_vless_and_vmess_need_a_user_set |
No open mode; naming a set satisfies the rule |
hysteria2_takes_a_shared_password_or_a_user_set_but_not_both |
Both and neither refused |
a_hysteria2_shared_password_may_not_be_empty |
Empty shared password |
a_hysteria2_udp_idle_timeout_is_between_2_and_600_seconds |
1 and 601 refused, 2, 600 and None accepted |
hysteria2_serves_at_least_one_connection_and_one_circuit |
Zero refused, one accepted |
a_salamander_key_is_at_least_4_bytes_on_either_side |
3 bytes refused, 4 accepted, inbound and outbound |
hysteria2_quic_settings_stay_within_upstreams_limits |
On both sides, a 16,383-byte stream window, a zero connection window, a 3 s or 30.5 s idle timeout, a 61 s keep-alive and zero incoming streams refused; on an outbound, 16,384 bytes, 120 s and 2 s accepted |
hysteria2_port_hopping_needs_ports_and_a_sane_interval |
No ports, port 0 and a 4 s shortest interval refused; three ports at a fixed 5 s and one port at 10 to 60 s accepted |
a_masquerade_may_not_answer_with_the_success_status |
233 refused, 404 accepted |
a_tun_device_mtu_is_at_least_1280 |
1279 refused, 1280 accepted |
socks_over_a_unix_socket_needs_a_udp_bind_to_serve_udp |
The Unix and UDP rule and its three accepted edges |
a_shadowsocks_2022_server_key_is_sized_to_its_method |
One byte short or long refused |
a_wireguard_address_family_needs_an_address_of_that_family |
Five address and family combinations |
a_hysteria2_client_needs_a_password_and_a_stream |
Empty password, zero streams |
shadowsocks_2022_client_keys_are_sized_to_their_method |
Both the user key and an identity key |
two_users_may_not_present_the_same_credential |
A shared Trojan password |
a_shared_credential_of_another_kind_is_no_conflict |
Only the admitting kind counts |
hysteria2_usernames_collide_case_insensitively |
Alice and alice on Hysteria 2 only |
a_hysteria2_username_may_not_hold_a_colon |
Hysteria 2 only |
a_hysteria2_password_may_not_be_empty |
By-password admission; a UUID-shaped password is accepted |
a_shadowsocks_2022_user_key_must_normalise_to_the_method |
A short key refused, a longer one folded and accepted |
Other tests that pin this page:
| File | Test | Pins |
|---|---|---|
supervisor/tests/unit/plan.rs |
an_invalid_spec_is_refused_without_a_plan |
plan refuses before planning |
supervisor/tests/hot_swap.rs |
a_refused_spec_changes_nothing |
UnknownReference and Bind refusals leave everything running as it was. The unbindable spec also replaces the user set (alice with bob) and routes to block; afterwards alice still connects and is routed direct, bob is refused, the epoch is unchanged, and a spare port bound earlier in the same prepare is free again |
supervisor/tests/hot_swap.rs |
a_hysteria2_obfuscation_change_needs_allow_disruptive |
Disruptive for an obfuscation change |
protocols/tests/unit/hysteria/server/masquerade.rs |
the_authentication_success_status_is_refused, a_value_that_is_not_a_status_code_is_refused |
The two masquerade refusals; 0, 99, 1000 and 65535 refused, 599 accepted |
protocols/tests/unit/ss_2022/users.rs |
users_sharing_a_psk_resolve_to_the_first |
The Validator::from_config backstop keeps the first of two users with one key |
app/tests/unit/lower.rs |
semantic_problems_are_left_to_the_supervisor, syntax_errors_are_refused |
The split between the app and the supervisor |
app/tests/unit/subscribe.rs |
every_lowered_node_builds_and_the_dns_setup_with_it |
A lowered subscribe example passes check |
supervisor/tests/sss.rs |
validation_refuses_bad_limits |
An sss inbound with max_datagram 0, a zero header_timeout, an 11 ms flush_delay, no user set, or a REALITY shape refused; one with chains accepted |
katana tests/unit/lower/spec.rs |
the_new_node_kinds_pass_the_supervisors_validation |
katana’s VLESS over REALITY with Vision, AnyTLS, SOCKS and HTTP over TLS, Shadowsocks and sss over WebSocket and TLS, and a Hysteria 2 node as helium describes it lower to specs validate accepts |
katana tests/unit/lower/outbound.rs |
wireguard_ipv4_only_builds_with_ipv4_address, wireguard_ipv6_only_requires_ipv6_address |
katana’s WireGuard lowering against check |
katana tests/unit/lower/spec.rs |
the_node_check_refuses_a_half_real_ip_setting |
test_spec refuses real_ip_header without real_ip_from, and accepts the two together |
katana tests/unit/lower/spec.rs |
the_node_check_refuses_a_handoff_setting_the_relay_could_not_use |
test_spec refuses a relative handoff_dir and handoff_group alone, and accepts the two together |
katana tests/unit/lower/spec.rs |
a_helium_nodes_check_judges_its_congestion_control |
A helium node’s test_spec holds no inbound, accepts congestion = "bbr" and refuses "vegas" |
katana tests/unit/api/helium.rs |
local_keys_the_panel_describes_are_refused |
Each of the twelve keys refused by name on a helium node, through PanelClient::new too; congestion accepted |
katana tests/unit/runtime.rs |
an_sspanel_node_is_refused_at_test_and_at_start, a_reload_to_sspanel_changes_nothing |
panel_type = "SSpanel" refused by name at --test and at start, where the node is not run; a reload that moves a running node to it is refused whole, and the node runs on |
katana tests/unit/lower/inbound.rs |
a_handoff_setting_the_relay_could_not_use_is_refused |
The five refusals by their text, all InvalidInput, a 97-byte directory among them; a 96-byte directory accepted for a node on every address, and refused for one on 2001:db8::1, with 2001:db8::1-65535.sock in the error |
Rules with no dedicated test: an empty balancer tag, an empty Hysteria 2 account name or password (only the colon is tested), VLESS Vision off REALITY on either side, TLS settings beside a REALITY outbound transport, a REALITY client’s server name, the sss limits on an outbound, the TUN platform check, a Unix bind or a handoff socket off Unix, proxy_protocol on a bind other than TCP, the user path’s no such user set, and a user edit refused by admission (the admission tests call validate and validate_admission directly, and the only set_users call in the suites succeeds). No supervisor test matches an error’s text; only the protocols crate’s masquerade test and katana’s WireGuard test match a fragment of one. Rewording a rule therefore passes the suites; update this page and Error messages with it. How to run the suites is on Testing.