Skip to content

VMess: keys and authentication

Source files: 33 · checked against Etemenanki 46c12e4 · katana v6.1.0
  • Etemenanki/protocols/src/vmess/aead.rs
  • Etemenanki/protocols/src/vmess/keys.rs
  • Etemenanki/protocols/src/vmess/accounts.rs
  • Etemenanki/protocols/src/macros.rs
  • Etemenanki/protocols/src/vmess/protocol.rs
  • Etemenanki/protocols/src/vmess/session.rs
  • Etemenanki/protocols/src/vmess/framing.rs
  • Etemenanki/protocols/src/vmess/core.rs
  • Etemenanki/protocols/src/error.rs
  • Etemenanki/protocols/benches/vmess_users.rs
  • Etemenanki/supervisor/src/build/inbound.rs
  • Etemenanki/supervisor/src/build/validate.rs
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/supervisor.rs
  • Etemenanki/supervisor/src/system/listener.rs
  • Etemenanki/supervisor/src/system/blocking.rs
  • Etemenanki/supervisor/src/topology/flow.rs
  • Etemenanki/supervisor/src/topology/inbound/mod.rs
  • Etemenanki/supervisor/src/topology/spec_plan/inbound.rs
  • Etemenanki/app/src/config.rs
  • Etemenanki/app/src/lower.rs
  • Etemenanki/protocols/tests/unit/vmess/aead.rs
  • Etemenanki/protocols/tests/unit/vmess/accounts.rs
  • Etemenanki/protocols/tests/unit/vmess/protocol.rs
  • Etemenanki/protocols/tests/unit/vmess/core.rs
  • Etemenanki/protocols/tests/unit/vmess/codec.rs
  • Etemenanki/protocols/tests/pipeline/vmess.rs
  • Etemenanki/app/tests/integration/e2e_xray_vmess.rs
  • Etemenanki/supervisor/tests/unit/plan.rs
  • Etemenanki/supervisor/tests/unit/serve.rs
  • Etemenanki/app/tests/unit/lower.rs
  • katana/src/lower/inbound.rs
  • katana/src/config.rs

VMess in Etemenanki is the AEAD-only variant: every connection starts with a 16-byte authentication id, followed by a request header sealed with AES-128-GCM. This page covers the cryptographic half of that protocol: how each key is derived from the user’s UUID, how the authentication id is built and checked, the clock check and the switch that relaxes it, how the header envelope is sealed and opened, the in-crate SHAKE128, the typed key wrappers, and AccountValidator, which finds the configured user an incoming id belongs to, trying the likely users before all the others, and rejects replays.

The byte layout of the inner request header, the chunk framing of the body and the server state machine are on VMess: wire format and core. Read this page before you change a key derivation, a salt, the time window or the replay set. The derivations and salts must stay byte-compatible with Xray. Every unit test seals and opens with this crate’s own code, so only the Xray interoperability tests notice a wrong salt or KDF step, and those tests are skipped when go is not installed.

File Symbol(s) Responsibility
protocols/src/vmess/aead.rs kdf, kdf16, cmd_key The recursive HMAC-SHA256 KDF and the account’s cmd key.
protocols/src/vmess/aead.rs GcmKey, GcmNonce, ConnNonce Role-named constructors for every header key and nonce.
protocols/src/vmess/aead.rs create_auth_id, auth_id_decipher, decode_auth_id_dec Sealing and opening the 16-byte authentication id.
protocols/src/vmess/aead.rs seal_vmess_aead_header, open_vmess_aead_header_slice The sealed request-header envelope.
protocols/src/vmess/aead.rs Shake128 A self-contained SHAKE128 XOF for chunk-length masking and padding.
protocols/src/vmess/keys.rs CmdKey, BodyKey, BodyIv, AuthId, AuthIdPlain Typed 16-byte key material, so the compiler rejects swapped keys.
protocols/src/vmess/accounts.rs AccountValidator, Account, MatchedAccount, UserHint, AuthFailure, PreparedUsers, PreparedHotTier User matching and its search order (a caller’s user hint, the address hints, the hot tier, then every user), the clock check and its switch, replay protection, and user sets and hot tiers built ahead of the swap that installs them.

The module does not parse the inner header, frame the body or drive the connection. protocols/src/vmess/protocol.rs and protocols/src/vmess/framing.rs call into it for that, and protocols/src/vmess/core.rs → VMessCore calls AccountValidator::verify_from and open_vmess_aead_header_slice from its handshake states.

Every per-user secret starts from the account’s cmd key, the MD5 of the 16 raw UUID bytes followed by a fixed magic string:

const CMD_KEY_MAGIC: &[u8] = b"c48619fe-8f02-49e0-b9e9-edf763e17e21";
pub fn cmd_key(uuid: &uuid::Uuid) -> CmdKey

CmdKey = MD5(uuid.as_bytes() || CMD_KEY_MAGIC). No other derivation reads the UUID; the validator keeps it only to report which account matched.

kdf is VMess’s recursively nested HMAC. The salt SALT_VMESS_AEAD_KDF ("VMess AEAD KDF") keys the innermost HMAC-SHA256, and each element of path adds one more HMAC level whose hash function is the level below it:

pub fn kdf(key: &[u8], path: &[&[u8]]) -> [u8; 32]
pub fn kdf16(key: &[u8], path: &[&[u8]]) -> [u8; 16]
fn hmac_chain(keys: &[&[u8]], level: usize, msg: &[u8]) -> [u8; 32]

For a path p1 … pn:

Level Keyed with Hash function inside the HMAC
H0 "VMess AEAD KDF" SHA-256
H1 p1 H0
Hi pi H(i-1)
Hn pn H(n-1)

kdf(key, path) returns Hn(key), the full 32 bytes. kdf16 truncates it to the first 16. hmac_chain treats every level as a hash with a 64-byte block and a 32-byte output: a key longer than 64 bytes is first hashed with the level below (SHA-256 at level 0). None of the salts, auth ids or nonces fed to it exceed 64 bytes, so that branch exists for correctness only.

flowchart LR
  K["input key (cmd key or body key/IV)"] --> Hn
  subgraph chain["kdf(key, p1..pn)"]
    Hn["Hn: HMAC keyed pn"] -->|"inner and outer hash"| H1["H1: HMAC keyed p1"]
    H1 -->|"inner and outer hash"| H0["H0: HMAC-SHA256 keyed 'VMess AEAD KDF'"]
  end
  Hn --> Out["32-byte digest"]
  Out --> K16["kdf16: first 16 bytes (keys)"]
  Out --> N12["first 12 bytes (GCM nonces)"]

Each level calls the level below twice (inner and outer hash), so a path of length n costs 2^(n+1) SHA-256 invocations. The auth-id key (n = 1) costs 4. Each request-header key or nonce (n = 3) costs 16, so opening one header derives four values for 64 SHA-256 calls. This is why AccountValidator derives a user’s auth-id decryption key once, when the user joins the validator, and keeps it across user-set changes, rather than deriving it per connection.

All salts are private &[u8] constants in protocols/src/vmess/aead.rs, copied from Xray’s proxy/vmess/aead/consts.go:

Constant Value Derives
SALT_VMESS_AEAD_KDF VMess AEAD KDF The innermost HMAC key of every kdf call.
SALT_AUTHID_ENC_KEY AES Auth ID Encryption The AES-128 key for auth ids, from the cmd key.
SALT_HEADER_PAYLOAD_LEN_AEAD_KEY VMess Header AEAD Key_Length GcmKey::request_len
SALT_HEADER_PAYLOAD_LEN_AEAD_IV VMess Header AEAD Nonce_Length GcmNonce::request_len
SALT_HEADER_PAYLOAD_AEAD_KEY VMess Header AEAD Key GcmKey::request_payload
SALT_HEADER_PAYLOAD_AEAD_IV VMess Header AEAD Nonce GcmNonce::request_payload
SALT_AEAD_RESP_HEADER_LEN_KEY AEAD Resp Header Len Key GcmKey::response_len
SALT_AEAD_RESP_HEADER_LEN_IV AEAD Resp Header Len IV GcmNonce::response_len
SALT_AEAD_RESP_HEADER_PAYLOAD_KEY AEAD Resp Header Key GcmKey::response_payload
SALT_AEAD_RESP_HEADER_PAYLOAD_IV AEAD Resp Header IV GcmNonce::response_payload
flowchart TB
  uuid["user UUID"] -->|"MD5 with CMD_KEY_MAGIC"| cmd["CmdKey"]
  cmd -->|"kdf16: AES Auth ID Encryption"| aid["auth-id AES-128 key"]
  cmd --> req["request header: GcmKey and GcmNonce request_len, request_payload"]
  authid["AuthId (wire)"] --> req
  conn["ConnNonce (wire)"] --> req
  bk["BodyKey (random, inside header)"] -->|"SHA-256, first 16"| rbk["response BodyKey"]
  biv["BodyIv (random, inside header)"] -->|"SHA-256, first 16"| rbiv["response BodyIv"]
  rbk --> resp["response header: GcmKey response_len, response_payload"]
  rbiv --> respn["response header: GcmNonce response_len, response_payload"]
  biv --> shake["request-direction Shake128"]
  rbiv --> rshake["response-direction Shake128"]

The request-header keys depend on the cmd key and on two values that travel in the clear: the auth id and the connection nonce. The body key and IV are chosen at random by the client (BodyKey::random, BodyIv::random in protocols/src/vmess/session.rs → OutboundSession::new) and carried inside the sealed header. Both ends derive the response direction from them with protocols/src/vmess/protocol.rs → RequestSession::response, which calls BodyKey::response and BodyIv::response: the client when it builds the session, the server after it has opened the request header. The response-header keys and nonces are derived from those response values. How the body key becomes an AES-128-GCM or ChaCha20-Poly1305 chunk cipher is covered on VMess: wire format and core.

The auth id is the first 16 bytes of every VMess connection: one AES-128-ECB block, encrypted with the per-user key kdf16(cmd_key, [SALT_AUTHID_ENC_KEY]).

Offset Size Field Meaning
0 8 time Seconds since the Unix epoch, signed, big-endian (i64::to_be_bytes).
8 4 random Four random bytes, so two ids in the same second differ.
12 4 CRC32 crc32fast::hash (IEEE CRC-32) of bytes 0 to 11, big-endian.
pub fn now_unix() -> i64
pub fn auth_id_cipher(cmd_key: &CmdKey) -> Aes128
pub fn create_auth_id_with_cipher(cipher: &Aes128, time: i64) -> AuthId
pub fn create_auth_id(cmd_key: &CmdKey, time: i64) -> AuthId
pub fn auth_id_decipher(cmd_key: &CmdKey) -> Aes128Dec
#[inline(always)]
pub fn decode_auth_id_dec(cipher: &Aes128Dec, authid: &AuthId) -> AuthIdPlain

create_auth_id_with_cipher fills the block, computes the CRC over the first 12 bytes and encrypts it in place. The client calls create_auth_id(cmd_key, now_unix()) through seal_vmess_aead_header. now_unix returns 0 if the system clock reads earlier than the epoch.

The server side uses the decrypt-only Aes128Dec, which holds only the decryption round keys. decode_auth_id_dec decrypts one block and returns an AuthIdPlain. It is #[inline(always)], so the decrypt is compiled into each caller, the validator’s full-scan loop included.

protocols/src/vmess/accounts.rs → decipher_matches is the per-key test that every step of the validator’s search runs (see Search order):

  1. Decrypt the block with the user’s Aes128Dec.
  2. AuthIdPlain::crc_ok(): the stored CRC32 must equal the CRC32 of the first 12 bytes. Decrypting with the wrong user’s key produces noise, which passes this check with probability 2^-32. Passing it is what identifies the owning account.
  3. ClockCheck::admits(stamp, now), with stamp = AuthIdPlain::timestamp(). The validator’s ClockCheck is one of:
    • Window, the default: the stamp must not be negative, now.checked_sub(stamp) must not overflow, and its absolute value must be at most AUTHID_WINDOW_SECS (120). The bound is inclusive and symmetric, so a client clock up to 120 s fast or slow is accepted.
    • Plausible, with the clock check off: 0 <= stamp < PLAUSIBLE_STAMP_LIMIT, where the limit is 2^33 seconds, the year 2242.

An id that clears the CRC but fails the clock check does not end the search. A wrong key clears the CRC with probability 2^-32, and stopping there would refuse the real owner, who may come later. decipher_matches records the first such skew (the stamp minus now, so a client whose clock runs behind has a negative skew), and the validator reports it as AuthFailure::Skewed { skew } only when no user matches.

now is the server’s wall clock in seconds. VMessCore::new takes it as a now: fn() -> i64 parameter, and the core calls (self.now)() when the first 16 bytes arrive. supervisor/src/serve.rs → serve_connection, which serves VMess for every front end, passes aead::now_unix. The core tests a_client_with_a_wrong_clock_is_refused_by_its_skew and a_client_with_a_wrong_clock_connects_with_the_clock_check_off pass a clock eight hours ahead of it.

The check is a property of the validator, set once with AccountValidator::with_clock_check(on) and fixed for its life. Each front end exposes it per VMess inbound:

Layer Setting Default Where
etemenanki-app clock_check in a VMess inbound’s settings true app/src/config.rs → VmessInboundSettings; lowered by app/src/lower.rs → lower_inbound
katana disable_vmess_clock_check in [node.controller] false katana src/config.rs; src/lower/inbound.rs → lower_stream_protocol sets clock_check: !disable_vmess_clock_check
Spec InboundProtocolSpec::Vmess { transport, clock_check } none supervisor/src/topology/spec_plan/inbound.rs

supervisor/src/build/inbound.rs → build_handler builds AccountValidator::from_users(users).with_clock_check(clock_check); anything but an explicit false in the spec keeps the check. clock_check is a VMess key only: a VLESS inbound in etemenanki-app refuses it as an unknown field (a_vmess_inbound_can_turn_the_clock_check_off, app/tests/unit/lower.rs). Changing it builds a new handler, which is swapped in without disrupting the listener or its sessions (a_vmess_clock_check_change_swaps_the_handler_without_disruption, supervisor/tests/unit/plan.rs).

PLAUSIBLE_STAMP_LIMIT is what keeps a false match out of reach with the check off. Noise from a wrong key clears the CRC with probability 2^-32, and its stamp must also fall under the limit, which noise does with probability 2^-31. The replay set is unchanged by the switch: it still refuses an id seen within 240 s (with_the_clock_check_off_replays_are_still_refused).

seal_vmess_aead_header wraps the inner request header (built by encode_request_header in protocols/src/vmess/protocol.rs) in this envelope:

Field Size Meaning
auth id 16 create_auth_id(cmd_key, now_unix()), sent in the clear.
sealed length 18 The inner header length as a big-endian u16, sealed with AES-128-GCM: 2 bytes of ciphertext plus the 16-byte tag.
connection nonce 8 ConnNonce::random(), sent in the clear.
sealed payload L + 16 The inner header (L bytes), sealed with AES-128-GCM, plus the tag.

Both seals use the 16 auth-id bytes as associated data, so the length and the payload are bound to the auth id they arrived with.

Every key is kdf16 and every nonce is the first 12 bytes of a full kdf digest (GcmNonce::from_kdf).

Part Key Nonce AAD
Request length kdf16(cmd_key, [Key_Length salt, auth_id, conn_nonce]) kdf(cmd_key, [Nonce_Length salt, auth_id, conn_nonce])[..12] auth id
Request payload kdf16(cmd_key, [Key salt, auth_id, conn_nonce]) kdf(cmd_key, [Nonce salt, auth_id, conn_nonce])[..12] auth id
Response length kdf16(response BodyKey, [Resp Header Len Key salt]) kdf(response BodyIv, [Resp Header Len IV salt])[..12] empty
Response payload kdf16(response BodyKey, [Resp Header Key salt]) kdf(response BodyIv, [Resp Header IV salt])[..12] empty

The salt names in the table are abbreviations of the constants listed under Salts. Each derived key and nonce pair seals exactly one message: the request pair changes with every auth id and connection nonce, and the response pair with every random body key and IV.

The header types are declared with byte_newtype! from protocols/src/macros.rs, which produces a Copy tuple struct with a private field and a const fn as_bytes(&self) -> &[u8; N]:

pub struct GcmKey([u8; 16]);
pub struct GcmNonce([u8; 12]);
pub struct ConnNonce([u8; 8]);
impl GcmKey {
pub fn request_len(cmd_key: &CmdKey, auth_id: &AuthId, conn_nonce: &ConnNonce) -> Self
pub fn request_payload(cmd_key: &CmdKey, auth_id: &AuthId, conn_nonce: &ConnNonce) -> Self
pub fn response_len(body_key: &BodyKey) -> Self
pub fn response_payload(body_key: &BodyKey) -> Self
}
impl GcmNonce {
fn from_kdf(digest: [u8; 32]) -> Self
pub fn request_len(cmd_key: &CmdKey, auth_id: &AuthId, conn_nonce: &ConnNonce) -> Self
pub fn request_payload(cmd_key: &CmdKey, auth_id: &AuthId, conn_nonce: &ConnNonce) -> Self
pub fn response_len(body_iv: &BodyIv) -> Self
pub fn response_payload(body_iv: &BodyIv) -> Self
}
impl ConnNonce {
pub fn random() -> Self
pub const fn from_bytes(raw: [u8; 8]) -> Self
}

GcmKey and GcmNonce have no public byte constructor. Outside aead.rs the only way to obtain one is a role-named constructor, so no call site picks a salt by hand. The length and payload keys have the same type and size; their constructors, not the type, keep them apart.

pub const TAG_SIZE: usize = 16;
pub fn gcm_seal(key: &GcmKey, nonce: &GcmNonce, aad: &[u8], plaintext: &[u8]) -> Vec<u8>
pub fn gcm_open(key: &GcmKey, nonce: &GcmNonce, aad: &[u8], ciphertext: &[u8]) -> io::Result<Vec<u8>>
pub fn seal_vmess_aead_header(cmd_key: &CmdKey, data: &[u8]) -> Vec<u8>
pub fn open_vmess_aead_header_slice(
cmd_key: &CmdKey,
authid: &AuthId,
buf: &[u8],
) -> io::Result<Option<(Vec<u8>, usize)>>

open_vmess_aead_header_slice is the port of Xray’s OpenVMessAEADHeader (aead/encrypt.go), in the sans-I/O form that VMessCore and the tests use; it is the only opener. It expects a buffer that starts right after the 16-byte auth id, which the caller has already consumed and authenticated. It reads the 18-byte sealed length and the 8-byte connection nonce, opens the length first, then opens length + TAG_SIZE bytes of payload. The payload is never touched before the length has authenticated.

It returns Ok(None) while the buffer is too short for the length part, the nonce or the full payload. Once the length part and the nonce are present, it opens the length at once, so a bad length tag is an error even before the payload has arrived. It returns Ok(Some((inner, used))) once the whole header is present, where used counts the bytes after the auth id. The core then returns used as consumed and leaves any body bytes in the buffer. The async opener over an AsyncRead that the module used to keep was removed in protocols 3.0.0; see Protocol crate foundations.

The response header goes the other way: protocols/src/vmess/protocol.rs → encode_response_header seals the 4-byte payload [response_header, 0, 0, 0] with the response keys and an empty AAD, and the client’s decode_response_header_slice opens it and checks that the first byte echoes the response_header value it sent.

sequenceDiagram
  participant C as Client
  participant Core as VMessCore
  participant V as AccountValidator
  participant A as aead
  C->>Core: 16-byte auth id
  Core->>V: verify_from(authid, now, source, hint)
  V-->>Core: Ok(MatchedAccount) with cmd_key, uuid, user_data
  Note over Core: matched = hint(), state AuthId to Header, 16 bytes consumed
  C->>Core: sealed length, conn nonce, sealed payload
  Core->>A: open_vmess_aead_header_slice(cmd_key, authid, buf)
  A-->>Core: Some(inner, used)
  Note over Core: parse_request_header, chunk_streams, response_header
  Core-->>C: sealed response header (when the reply is due)

When verify_from returns an AuthFailure, VMessCore fails the connection with io::ErrorKind::PermissionDenied and the message vmess: followed by the failure’s Display:

AuthFailure Message
NoUser vmess: unknown user or invalid auth id
Skewed { skew } vmess: auth id stamped <n> s behind the server clock, or vmess: auth id stamped <n> s ahead of the server clock, with <n> the absolute skew
Replayed vmess: replayed auth id

PermissionDenied is the kind every core uses for a refused credential, so the supervisor’s drive reports each of them to its guard (supervisor/src/serve.rs).

The chunk framing needs the SHAKE128 extendable-output function, and the sha3 crate at the version in use moved it to a separate crate. Rather than add a dependency, aead.rs implements FIPS 202 directly: keccak_f1600 (24 rounds with the KECCAK_RC, KECCAK_RHO and KECCAK_PI tables) and a sponge with rate SHAKE128_RATE = 168 bytes.

pub struct Shake128 {
state: [u64; 25],
pos: usize,
}
impl Shake128 {
pub fn new(seed: &[u8]) -> Self
pub fn read(&mut self, out: &mut [u8])
pub fn next_u16(&mut self) -> u16
pub fn next_padding_len(&mut self) -> u16
}
  • new absorbs the seed in 168-byte blocks, applies the SHAKE pad10*1 padding with domain byte 0x1F and final bit 0x80, and permutes once. The instance is then squeeze-only.
  • read squeezes byte by byte and permutes again each time pos reaches 168. Output does not depend on how reads are split, which the chunk framing relies on because it pulls two bytes at a time.
  • next_u16 is the next two bytes, big-endian (Xray’s shakeSizeParser.next).
  • next_padding_len is next_u16() % 64 (shakeSizeParser.NextPaddingLen).

protocols/src/vmess/framing.rs → ChunkStream::new seeds one instance per direction with that direction’s 16-byte BodyIv. Per chunk it draws the padding length first (only with global padding negotiated) and then the 16-bit length mask (only with chunk masking negotiated). The order matters: both ends consume the same keystream, and swapping the two draws desynchronises them from the first chunk.

VMess handles many unrelated 16-byte values. As bare [u8; 16] they would be interchangeable, and swapping a key for an IV compiles and fails only against a real peer. protocols/src/vmess/keys.rs gives each meaning its own type. The key_bytes! macro declares the struct and its from_bytes, as_bytes and into_bytes; secret_traits! adds a constant-time PartialEq (subtle::ConstantTimeEq) and a Debug that prints Name(<redacted>).

pub struct CmdKey([u8; 16]);
pub struct BodyKey([u8; 16]);
pub struct BodyIv([u8; 16]);
pub struct AuthId([u8; 16]);
pub struct AuthIdPlain([u8; 16]);
// key_bytes! (CmdKey, BodyKey, BodyIv, AuthId)
pub const fn from_bytes(raw: [u8; 16]) -> Self
pub const fn as_bytes(&self) -> &[u8; 16]
pub const fn into_bytes(self) -> [u8; 16]
impl BodyKey {
pub fn random() -> Self
pub fn response(&self) -> Self
}
impl BodyIv {
pub fn random() -> Self
pub fn response(&self) -> Self
}
impl AuthId {
pub const fn shard_byte(&self) -> u8
}
impl AuthIdPlain {
pub const fn from_bytes(raw: [u8; 16]) -> Self
pub fn crc_ok(&self) -> bool
pub fn timestamp(&self) -> i64
}
Type Holds Equality Debug Extras
CmdKey MD5(uuid, magic), the root secret of an account constant-time redacted none
BodyKey Per-connection body key constant-time redacted random, response = SHA-256(key)[..16]
BodyIv Per-connection body IV constant-time redacted random, response = SHA-256(iv)[..16]
AuthId The auth-id ciphertext, as sent on the wire plain byte compare hex Hash (the replay-set key), shard_byte
AuthIdPlain The decrypted auth-id block none timestamp and crc_ok only crc_ok, timestamp

The request-to-response derivation lives in BodyKey::response and BodyIv::response rather than in a free function, so a response key and a response IV can no longer be swapped at a call site. AuthIdPlain is a separate type so a decrypted block can never be passed where a ciphertext is expected. Values that exist only inside one algorithm step, such as a KDF digest fed straight into a cipher, stay as raw arrays.

pub struct Account<T> {
pub uuid: Uuid,
pub cmd_key: CmdKey,
pub authid_cipher: Aes128,
pub user_data: Arc<T>,
}
impl<T> Account<T> {
pub fn from_uuid(uuid: &Uuid, user_data: Arc<T>) -> Self
}
pub struct MatchedAccount<T> {
pub cmd_key: CmdKey,
pub uuid: Uuid,
pub user_data: Arc<T>,
}
impl<T> MatchedAccount<T> {
pub fn hint(&self) -> UserHint
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct UserHint(Uuid);
pub enum AuthFailure {
NoUser,
Skewed { skew: i64 },
Replayed,
}
enum ClockCheck {
Window,
Plausible,
}
pub struct PreparedUsers<T>(Arc<Snapshot<T>>);
pub struct PreparedHotTier<T> {
read: Arc<Snapshot<T>>,
hot: Arc<Hot>,
}
pub struct AccountValidator<T> {
snapshot: ArcSwap<Snapshot<T>>,
cold_hits: AtomicU64,
hints: SourceHints,
replay: [Mutex<ReplayShard>; REPLAY_SHARDS],
clock: ClockCheck,
epoch: Instant,
}
impl<T> AccountValidator<T> {
pub fn new() -> Self
pub fn with_clock_check(self, on: bool) -> Self
pub fn from_users(users: impl IntoIterator<Item = (Uuid, Arc<T>)>) -> Self
pub fn add(&self, uuid: Uuid, user_data: Arc<T>)
pub fn set_users(&self, users: impl IntoIterator<Item = (Uuid, Arc<T>)>)
pub fn prepare_users(&self, users: impl IntoIterator<Item = (Uuid, Arc<T>)>) -> PreparedUsers<T>
pub fn install(&self, prepared: PreparedUsers<T>)
pub fn hot_tier_due(&self) -> bool
pub fn prepare_hot_tier(&self) -> PreparedHotTier<T>
pub fn install_hot_tier(&self, prepared: PreparedHotTier<T>)
pub fn authenticate(&self, authid: &AuthId, now: i64) -> Option<MatchedAccount<T>>
pub fn verify(&self, authid: &AuthId, now: i64) -> Result<MatchedAccount<T>, AuthFailure>
pub fn verify_from(
&self,
authid: &AuthId,
now: i64,
source: Option<IpAddr>,
hint: Option<UserHint>,
) -> Result<MatchedAccount<T>, AuthFailure>
fn find(
&self,
snapshot: &Snapshot<T>,
hint: Option<UserHint>,
key: Option<&HintKey>,
authid: &AuthId,
now: i64,
) -> Result<(usize, bool), AuthFailure>
fn stamp(&self, at: Instant) -> u64
}

T is the per-user payload the router sees: Principal (supervisor/src/topology/flow.rs) for every front end, since all of them serve VMess through etemenanki-supervisor; the tests use stand-ins such as () or the user’s own UUID. The auth id cannot be indexed, since its plaintext is time || rand || crc under a per-user key: its owner is found by trying users’ keys until one opens it. verify_from tries the users most likely to own the id first, and runs the full scan over every user only when none of them does (Search order).

verify is verify_from(authid, now, None, None), with no client address and no hint, and authenticate is verify(..).ok(). VMessCore calls verify_from with its client address and its user hint; the unit tests use all three.

UserHint names one user that matched before, so that a related handshake can try that user first. It is opaque: its field is private, MatchedAccount::hint is the only way to make one, and its Debug prints UserHint(<redacted>), never the UUID. A hint is not a credential. It only picks which key is tried first, and a hint naming a user the set no longer has, or a user that does not own the id, is passed over.

clock is fixed at construction: a validator is rebuilt, not edited, when its inbound’s settings change. epoch is the Instant the validator was created at; match times are counted from it.

Account bundles one user’s UUID, cmd key, encrypting Aes128 and payload, and from_uuid derives them. The validator does not store Account values: it keeps only each user’s decrypt-only key schedule, cmd key and payload.

struct Snapshot<T> {
users: Arc<Users<T>>,
hot: Arc<Hot>,
}
struct Users<T> {
deciphers: Box<[Aes128Dec]>,
last_hit: Box<[AtomicU64]>,
meta: Box<[UserMeta<T>]>,
slots: HashMap<Uuid, u32>,
}
struct UserMeta<T> {
uuid: Uuid,
cmd_key: CmdKey,
user_data: Arc<T>,
}
struct Hot {
deciphers: Box<[Aes128Dec]>,
slots: Box<[u32]>,
}
impl<T> Users<T> {
fn scan(&self, authid: &AuthId, now: i64, clock: ClockCheck, skewed: &mut Option<i64>) -> Option<usize>
}
struct UsersBuilder<T> { /* the four arrays of Users, as Vecs and a HashMap */ }
impl<T> UsersBuilder<T> {
fn with_capacity(users: usize) -> Self
fn push(&mut self, meta: UserMeta<T>, decipher: Aes128Dec, last_hit: u64) -> Option<u32>
fn push_new(&mut self, uuid: Uuid, user_data: Arc<T>)
fn push_all(&mut self, users: &Users<T>)
fn finish(self) -> Users<T>
}

A handshake reads one Snapshot: a user set and the hot tier over it, published together behind one ArcSwap, so a hot tier always names slots of the user set beside it. Both halves are immutable once published. Each sits in its own Arc, so a new hot tier shares the user set it was built over, and add carries the current hot tier into the snapshot it builds.

Users holds one entry per slot, a u32 index, in four aligned parts:

  • deciphers holds the decrypt-only key schedules, contiguous and in slot order. It is the only array the full scan reads until a key opens the id.
  • last_hit holds when each slot last matched, as a stamp: nanoseconds since the validator’s epoch, never 0. A slot that never matched holds 0. verify_from stores it with Ordering::Relaxed; a hot-tier refresh, add and prepare_users read it.
  • meta is read once, after a match, to copy out the cmd key, UUID and payload.
  • slots maps each UUID to its slot, so that a hinted user is tried by name.

UsersBuilder fills the four parts in step. push gives a user the next slot unless its UUID has one already, so a UUID listed twice keeps its first slot and its first payload, the one a scan would match. push_new derives the cmd key and the decrypt-only key schedule of a user new to the validator (aead::cmd_key, then aead::auth_id_decipher). push_all copies the slots of another set in order, with their key schedules and match times.

A set built by from_users keeps the order the users were given in: under the supervisor that is the order of its admissions map, a BTreeMap sorted by the front end’s user id. add appends to the end, and prepare_users puts the users that stay first, in their current order, and the new ones after them. No handshake reorders the slots.

Hot is the hot tier: the slots of the users that matched most recently, newest first, with copies of their key schedules in a contiguous array of its own (The hot tier). Users::scan returns the first slot whose key opens the id under the validator’s ClockCheck, or None, and leaves the first skew it records in skewed unless an earlier step already left one.

flowchart TB
  start["verify_from(authid, now, source, hint)"] --> load["arrived = Instant::now(), snapshot.load()"]
  load --> user{"hinted user opens the id?"}
  user -->|"no, or no hint"| addr{"a user recall(source) returns opens it?"}
  addr -->|"no, or no source"| hot{"a hot-tier key opens it?"}
  hot -->|"no"| scan{"Users::scan: any slot opens it?"}
  scan -->|"no"| none1["Err(NoUser or Skewed)"]
  scan -->|"yes, cold"| admit{"replay shard admit(authid, arrived)"}
  user -->|"yes"| admit
  addr -->|"yes"| admit
  hot -->|"yes"| admit
  admit -->|"already seen"| none2["Err(Replayed)"]
  admit -->|"new"| note["last_hit[slot] = stamp, remember(source, uuid), cold: cold_hits += 1"]
  note --> ok["Ok(MatchedAccount)"]
  1. Record the arrival time on the monotonic clock, before the search, and turn source into its HintKey.
  2. Load the current snapshot through ArcSwap::load. No lock is taken, and a concurrent add, install or hot-tier install cannot change the snapshot this call searches.
  3. find searches in the order below and returns the slot and whether the full scan found it. No match returns Err(NoUser) or Err(Skewed { skew }).
  4. Pick the replay shard from the auth id’s first byte and lock only that shard for one admit. A replay returns Err(Replayed).
  5. Only once the id is admitted: store the arrival time in last_hit[slot], call SourceHints::remember(key, uuid) when there is a source, add 1 to cold_hits when the full scan found the user, and copy out the MatchedAccount.

The search runs before the replay check, so only ids that decrypt under a configured user’s key, pass the CRC and pass the clock check ever reach the replay set. A refused id, whether no user, a skew or a replay, leaves the match times, the address hints and cold_hits as they were.

find tries keys in four steps. A key opens the id when decipher_matches passes: the CRC, then the clock check.

Step Keys tried Passed over
1. User hint The user hint names, looked up by UUID in Users::slots No hint, or a UUID the set does not have
2. Address hints The up to HINT_USERS (4) users SourceHints::recall returns for the source’s HintKey, most recent first No source; the hinted user, already tried in step 1; a UUID the set does not have
3. Hot tier Every key in Hot::deciphers, most recent match first Nothing
4. Full scan Users::scan: every slot, in slot order Nothing: it tries the users of the earlier steps again

The first key that opens the id ends the search, and the full scan runs only when steps 1 to 3 found no key that opens it. Steps 1 to 3 go through try_key, a #[inline(never)] wrapper around decipher_matches. decipher_matches and aead::decode_auth_id_dec are #[inline(always)], so Users::scan is the one caller whose loop holds the whole test inline.

A key that clears the CRC but whose stamp fails the clock check does not end the search in any step. find keeps the first such skew, from whichever step recorded it, and reports it as AuthFailure::Skewed { skew } only when nothing matches.

A guess only picks which key is tried. Whichever user a hint, an address hint or the hot tier names, the id must still clear that user’s CRC and clock check, and then pass the replay set, exactly as for a full scan. A stale or wrong guess therefore never admits another user: it is passed over, and the search goes on.

enum HintKey {
V4([u8; 4]),
V6([u16; 4]),
}
struct Hint {
key: HintKey,
users: [Option<Uuid>; HINT_USERS],
}
struct SourceHints {
sets: Box<[Mutex<Vec<Hint>>]>,
hasher: RandomState,
}
impl HintKey {
fn of(ip: IpAddr) -> Self
}
impl Hint {
fn promote(&mut self, user: Uuid)
}
impl SourceHints {
fn recall(&self, key: &HintKey) -> [Option<Uuid>; HINT_USERS]
fn remember(&self, key: HintKey, user: Uuid)
}

The address hints remember, for each recently seen client address, the users that last matched from it. Several users behind one address, such as a household or an office, each stay listed.

  • HintKey::of keys an address after IpAddr::to_canonical: an IPv4 address by its four octets, an IPv4-mapped IPv6 address as its IPv4 address, and any other IPv6 address by its /64 (its first four segments), the prefix inside which one subscriber’s privacy addresses rotate.
  • Hint keeps the last HINT_USERS = 4 users of one key, most recent first. promote moves a listed user to the front; a user not yet listed goes first and the last one drops out.
  • SourceHints is a set-associative cache of HINT_SETS = 1024 sets. Each set is a parking_lot::Mutex<Vec<Hint>> that keeps its HINT_WAYS = 16 most recently matched keys, least recent first. A key’s set is hasher.hash_one(key) & HINT_MASK, with a RandomState drawn per validator, so which addresses share a set cannot be predicted from outside. However many addresses connect, at most 16 384 keys are remembered.
  • recall locks the key’s set and copies out the key’s users, or none.
  • remember locks the key’s set and takes the key’s entry out, or, in a full set, evicts the least recent key and starts a new entry. It then promotes the user and puts the entry back as the set’s most recent.

The hints name users by UUID, not by slot or payload, and install leaves them alone. A UUID the new set lacks is passed over in step 2; a kept user is found in its new slot, with its new payload; and a user whose UUID changed is found by the full scan and remembered under the new UUID.

Under the supervisor, source is the client address the connection is served for (see VMess: wire format and core), and the user hint comes from the gRPC carrier: the next VMess stream of a gRPC connection tries the user the connection’s last authenticated stream matched.

impl Hot {
fn empty() -> Self
fn from_entries(entries: impl IntoIterator<Item = (u32, Aes128Dec)>) -> Self
fn recent<T>(users: &Users<T>) -> Self
}

The hot tier holds the users that matched most recently, as a separate array of their key schedules, so step 3 tries them one after another without looking up slots. Handshakes never change it: a refresh builds a new tier aside, and installing it is the only way the tier changes.

Item What it does
cold_hits Counts the admitted matches that the full scan found since the last refresh was prepared.
hot_tier_due() cold_hits >= COLD_HITS_PER_REFRESH (16), one Relaxed atomic load, so a caller can poll it.
prepare_hot_tier() Resets cold_hits to 0, loads the current snapshot and builds Hot::recent over its users. It changes nothing else.
Hot::recent Reads every slot’s last_hit and keeps the up to HOT_USERS = 4096 slots with the newest non-zero match times, newest first (select_nth_unstable_by, then a sort; equal times land in no particular order). It copies their key schedules: no key is derived, and the user set is not copied.
install_hot_tier(prepared) One ArcSwap::compare_and_swap, no lock, from the snapshot the tier was built from to a snapshot of the same Users and the new Hot. If the snapshot has changed in the meantime (an install, an add, another hot-tier install), the prepared tier is dropped: its slots may name other users in the set now current, which came with a tier of its own.

A validator starts with an empty tier and keeps it until a refresh is installed. A user set installed by install brings the survivors of the old tier along (Building the validator).

The supervisor drives the refresh. supervisor/src/serve.rs → run_stream_inbound spawns refresh_hot_tiers on its tracker for every stream listener. Every HOT_TIER_POLL (1 s, with missed ticks delayed rather than bunched) the task reads the listener’s current handler. When that handler is a VMess one whose validator reports hot_tier_due(), refresh_hot_tier runs prepare_hot_tier on the blocking pool (supervisor/src/system/blocking.rs → off_runtime), as a user set is prepared, and then install_hot_tier. A listener therefore refreshes at most once per poll. The task returns when the listener’s stop token is cancelled.

#[derive(Default)]
struct ReplayShard {
seen: std::collections::HashSet<AuthId>,
order: std::collections::VecDeque<(Instant, AuthId)>,
}
impl ReplayShard {
fn admit(&mut self, authid: &AuthId, arrived: Instant) -> bool
}

The replay set is split into REPLAY_SHARDS = 64 shards, each a parking_lot::Mutex<ReplayShard>. The shard index is authid.shard_byte() as usize & REPLAY_MASK. The auth id is AES output, so its first byte is uniform and needs no further hashing; REPLAY_SHARDS must stay a power of two for the mask to work.

admit first expires the front of order: while the oldest entry’s age, measured from arrived, exceeds REPLAY_TTL, it is removed from both order and seen. admit then inserts the id into seen, returning false if it was already there, and otherwise appends (arrived, authid) to order. The timestamps are monotonic Instant values, so a wall-clock jump does not disturb the queue, and expiry from the front is amortised O(1). Expiry is lazy: a shard sheds old entries only when admit runs on it, which happens for every id that matched a user and maps to that shard, replays included.

REPLAY_TTL is 2 * AUTHID_WINDOW_SECS = 240 s. The window is symmetric, so an id stamped 120 s in the future keeps passing the time check until the server clock reaches its stamp plus 120 s, 240 s after it first arrived. Any shorter TTL would let such an id be replayed after its entry expired. Eviction is by age only, never by count, so no volume of other traffic can push out an id that the validator admitted less than 240 s ago. The TTL is the same with the clock check off, and whichever step of the search matched the id.

Constructor or method Work Match times and hot tier Used by
new() An empty user set and hot tier, 1024 empty hint sets under a fresh RandomState, 64 empty replay shards, cold_hits at 0, the clock check on (ClockCheck::Window) and epoch set to now. none Default, add-based setup
with_clock_check(on) No work: sets clock to Window for true and Plausible for false. unchanged build_handler, after from_users
from_users(users) Builds one Users with UsersBuilder::push_new, which derives each user’s cmd key (MD5) and decrypt-only key schedule (one KDF plus a decrypt key expansion). A UUID listed twice keeps its first payload. all 0; empty hot tier supervisor/src/build/inbound.rs → build_handler, as StreamProtocol::Vmess(Arc::new(AccountValidator::from_users(users).with_clock_check(clock_check)))
add(uuid, user_data) Rebuilds the whole user set through ArcSwap::rcu: push_all copies every slot with its key schedule and match time, then push_new appends the new user. A UUID already registered keeps its slot and payload. A set installed or a tier refreshed meanwhile is added to, not overwritten. kept for every slot, 0 for the new one; the hot tier is kept, since every slot keeps its user Unit tests; meant for configuration time only
prepare_users(users) Builds the snapshot users would make from the current one, without changing anything and without a lock. A surviving UUID keeps its key schedule and cmd key and takes its new payload; only a new UUID goes through push_new. kept for survivors, 0 for new users; survivors keep their places in the hot tier supervisor/src/build/inbound.rs → UserTable::prepare_for, while an apply is staged
install(prepared) One pointer store (ArcSwap::store), no lock. as prepared UserTable::store_into, for a UserTable::VmessPrepared
set_users(users) install(prepare_users(users)). as prepare_users UserTable::store_into, for a UserTable::Vmess that was not prepared

prepare_users builds the new user set in two passes. The first walks the current set in slot order and keeps each user that is still listed, with its key schedule, cmd key and match time, under its new payload, and notes the slot it moves to. The second appends the users that are new, in the order given. A UUID listed twice is kept once, and its first listing’s payload wins. The current hot tier is then carried over: each entry whose user stays keeps its place in the tier’s order, under its new slot, and the others drop out. Matches between prepare_users and install are not carried over; they only order the hot tier.

install leaves the replay shards alone: an auth id seen before the swap is still a replay after it. It leaves the address hints alone too (The address hints). Handshakes in flight finish against whichever snapshot they loaded, and a hot tier prepared before the install is dropped by install_hot_tier rather than installed over the new set (a_refresh_racing_an_install_is_dropped).

The supervisor keeps an inbound’s validator as StreamProtocol::Vmess(Arc<AccountValidator<Principal>>) (supervisor/src/topology/inbound/mod.rs) and never swaps the validator itself on a user change, which is why the replay state and the address hints survive user changes. The part of a change that walks every user runs while the apply is staged, off the runtime (supervisor/src/supervisor.rs → stage): Listener::user_target takes the running handler as a UserTarget, and UserTarget::prepare calls UserTable::prepare_for, which turns a UserTable::Vmess into a UserTable::VmessPrepared with prepare_users (supervisor/src/system/listener.rs). At commit, UserTable::store_into only calls install. An inbound whose other settings change, the clock check included, gets a new handler, and with it a new validator. Before any of this, supervisor/src/build/validate.rs → validate_admission refuses two users of one inbound with the exact same UUID (users <a> and <b> present the same credential).

Field Primitive Written by Read by
snapshot ArcSwap<Snapshot<T>> from_users (store, before the validator is shared), add (rcu), install and so set_users (store), install_hot_tier (compare_and_swap) verify_from (load), prepare_users and prepare_hot_tier (load_full), without a lock
cold_hits AtomicU64, Relaxed verify_from (fetch_add, after a full-scan match is admitted), prepare_hot_tier (reset to 0) hot_tier_due
hints SourceHints: 1024 sets, each a parking_lot::Mutex<Vec<Hint>> verify_from → remember, after admission verify_from → recall, in step 2
replay [Mutex<ReplayShard>; 64] verify_from, one shard per call verify_from
clock ClockCheck, a plain field new, with_clock_check, before the validator is shared verify_from
epoch Instant, a plain field new stamp
Users::last_hit AtomicU64 per slot, Relaxed verify_from, after admission Hot::recent, add, prepare_users

verify_from takes &self, so one Arc<AccountValidator<T>> is shared by every connection of an inbound. The only locks on the matching path are the source’s hint set, taken by recall and later by remember, and one replay shard, taken for one admit. The user set, its slot map and the hot tier are read without a lock.

Invariant Enforced by Pinned by
The KDF’s base level is plain HMAC-SHA256 keyed with "VMess AEAD KDF". hmac_chain at level 0 hmac_base_level_matches_reference (protocols/tests/unit/vmess/aead.rs)
An auth id round-trips through its user’s cipher with a valid CRC and the original timestamp. create_auth_id_with_cipher, AuthIdPlain auth_id_roundtrips_within_window (aead.rs tests)
A user matches its own fresh id. decipher_matches user_found_for_own_authid_within_window (protocols/tests/unit/vmess/accounts.rs)
An id made with another user’s key never matches. AuthIdPlain::crc_ok user_not_found_for_wrong_id (accounts.rs tests)
An id stamped outside ±120 s is rejected, in the past and in the future, and the bound is inclusive. AUTHID_WINDOW_SECS in ClockCheck::admits user_not_found_outside_time_window (accounts.rs tests, ids 1000 s off); an_out_of_window_id_reports_its_skew (120 s behind passes, 121 s ahead fails)
An id a user’s key opens but whose stamp fails is reported with its skew, not as an unknown user. decipher_matches records the first skew; find returns AuthFailure::Skewed when no user matches an_out_of_window_id_reports_its_skew (skews −28 800 and 121 and their texts); a_hint_never_admits_another_user (the hinted user’s own id an hour off); a_client_with_a_wrong_clock_is_refused_by_its_skew (protocols/tests/unit/vmess/core.rs)
With the clock check off, any stamp in 0..2^33 passes and any other is refused. ClockCheck::Plausible with_the_clock_check_off_any_plausible_stamp_passes (eight hours either way, 1, the years 2000 and 2100 and PLAUSIBLE_STAMP_LIMIT - 1 pass; −1, i64::MIN, the limit and i64::MAX are Skewed); a_client_with_a_wrong_clock_connects_with_the_clock_check_off (core.rs)
A second use of an id is rejected, with the clock check on or off, and whichever step matched it. ReplayShard::admit, after every step of the search replayed_authid_is_rejected (accounts.rs tests, expects AuthFailure::Replayed); with_the_clock_check_off_replays_are_still_refused; a_replay_through_the_hint_is_still_refused; a_replayed_auth_id_is_refused (protocols/tests/unit/vmess/core.rs, expects PermissionDenied)
No volume of other traffic evicts a live replay entry. Age-only eviction with REPLAY_TTL replay_survives_heavy_traffic (accounts.rs tests, 20 000 distinct ids)
Entries older than REPLAY_TTL leave the set. Front-of-queue expiry in admit expired_ids_leave_the_set (accounts.rs tests). The test drives expire_all, a test-only copy of the expiry loop, not admit itself.
A guess only picks which key is tried: a user hint, an address hint or the hot tier never admits another user, and a guess that fails is passed over for the next step. find runs decipher_matches on every candidate; the replay set comes after a_hint_never_admits_another_user, a_wrong_or_stale_user_hint_falls_through, handshakes_racing_installs_match_only_their_owner (accounts.rs tests)
The hinted user is tried first, then the source address’s users, then the hot tier, and the full scan runs only when none of them matched. The step order in find a_user_named_twice_is_tried_once, a_wrong_or_stale_user_hint_falls_through, the_hot_tier_changes_only_when_a_refresh_is_installed (accounts.rs tests)
A user that both the hint and the address name is tried once by the guesses. Step 2 skips the hinted user a_user_named_twice_is_tried_once (accounts.rs tests)
A hint names a UUID: a hint for a user the set no longer has is skipped, a kept user is found with its new payload, and a changed UUID is found afresh. The UUID lookup in Users::slots a_hint_for_a_removed_user_is_skipped, a_kept_user_takes_its_new_payload_through_the_hint, a_hint_for_a_user_whose_uuid_changed, a_wrong_or_stale_user_hint_falls_through (accounts.rs tests)
A UserHint never shows its UUID. The hand-written Debug a_user_hint_never_shows_its_uuid (accounts.rs tests)
An address keeps its last four users, most recent first; an IPv6 hint covers its /64, and an IPv4-mapped address is its IPv4 address. Hint::promote, HintKey::of an_address_remembers_its_last_few_users, an_ipv6_hint_covers_its_64_and_mapped_ipv4_is_ipv4 (accounts.rs tests)
The address hints are bounded: at most HINT_WAYS keys per set and HINT_SETS * HINT_WAYS in all, and the newest key stays. SourceHints::remember evicts a full set’s least recent key the_hints_are_bounded (accounts.rs tests)
Handshakes never change the hot tier; it changes only when a prepared refresh is installed, and a refresh is due after COLD_HITS_PER_REFRESH full-scan matches. cold_hits, prepare_hot_tier, install_hot_tier the_hot_tier_changes_only_when_a_refresh_is_installed (accounts.rs tests); a_due_hot_tier_is_refreshed_by_the_listener (supervisor/tests/unit/serve.rs)
The hot tier is the HOT_USERS most recently matched users, newest first, and a user that never matched is not in it. Hot::recent the_hot_tier_is_the_most_recent_users_newest_first (accounts.rs tests)
A UUID listed twice is kept once, with its first payload. UsersBuilder::push, prepare_users a_uuid_listed_twice_keeps_its_first_payload, set_users_replaces_the_set_but_not_the_replay_state (accounts.rs tests)
A user added after construction is matchable, and add keeps the hot tier. add rebuilds and publishes the snapshot add_after_construction_is_matchable, add_keeps_the_hot_tier (accounts.rs tests)
Replacing the user set drops removed users, admits new ones, gives a kept user its new payload, and keeps the replay state. prepare_users rebuilds the snapshot; install leaves replay alone set_users_replaces_the_set_but_not_the_replay_state (accounts.rs tests)
Users that survive a set change keep their places in the hot tier, in order, under their new slots. prepare_users remaps the current tier set_users_carries_the_hot_tier_over (accounts.rs tests)
A prepared set changes nothing until it is installed. prepare_users only reads; install is the store a_prepared_set_takes_effect_only_when_installed (accounts.rs tests)
A hot tier prepared from a snapshot that was replaced is dropped, so its slots never name the new set’s users. install_hot_tier publishes with compare_and_swap a_refresh_racing_an_install_is_dropped (accounts.rs tests)
A clock check change reaches the inbound without disruption. The plan swaps the handler, which carries a new validator a_vmess_clock_check_change_swaps_the_handler_without_disruption (supervisor/tests/unit/plan.rs); a_vmess_inbound_can_turn_the_clock_check_off (app/tests/unit/lower.rs)
A sealed header opens to the original bytes. seal_vmess_aead_header, open_vmess_aead_header_slice header_seal_open_roundtrips (aead.rs tests), request_header_roundtrips, request_and_response_headers_open_from_slices (protocols/tests/unit/vmess/protocol.rs), stream_codec_seals_the_header_and_chunks_and_opens_the_response (protocols/tests/unit/vmess/codec.rs)
The slice opener returns None, not an error, while the header is incomplete, and reports exactly the bytes it used. open_vmess_aead_header_slice request_and_response_headers_open_from_slices (protocol.rs tests)
The response header seals and opens with the response keys, and the decoder accepts it only when the first byte echoes response_header. encode_response_header, decode_response_header_slice response_header_roundtrips (protocol.rs tests, fixed keys); request_and_response_headers_open_from_slices (keys from RequestSession::response). No test feeds a wrong echo byte.
Shake128 matches FIPS 202, and split reads equal one bulk read. keccak_f1600, sponge padding shake128_fips202_empty, shake128_streaming_matches_bulk (aead.rs tests)
All salts, the cmd-key magic and the SHAKE usage match Xray. Constants copied from Xray app_server_vmess_grpc_xray_client_tls, app_client_vmess_ws_xray_server_early_data_plain, app_server_vmess_ws_xray_client_early_data_plain (app/tests/integration/e2e_xray_vmess.rs). They build Xray from source with go and return early, passing, when go is missing or the build fails.
Keys, IVs, auth ids and decrypted blocks cannot be substituted for each other. Distinct newtypes in keys.rs; GcmKey and GcmNonce have no public byte constructor The compiler; no runtime test

The server core and the client codecs are also run against each other over real sockets in protocols/tests/pipeline/vmess.rs. new_server_vs_new_client_tcp runs AES-128-GCM with global padding and ChaCha20-Poly1305 without it; new_server_vs_new_client_udp runs AES-128-GCM with global padding.

Condition Where Result
Fewer than 16 bytes buffered VMessCore, State::AuthId Consumes 0 and waits for more.
No user’s key opens the id AccountValidator::verify_from returns AuthFailure::NoUser VMessCore fails with PermissionDenied, vmess: unknown user or invalid auth id.
A user’s key opens the id, but its stamp fails the clock check AuthFailure::Skewed { skew } PermissionDenied, vmess: auth id stamped <n> s behind the server clock (or ahead of).
The id was seen within the replay TTL AuthFailure::Replayed PermissionDenied, vmess: replayed auth id.
Header not yet complete open_vmess_aead_header_slice returns Ok(None) Consumes 0 and waits for more.
Length or payload tag does not verify gcm_open InvalidData, vmess: AEAD header open failed.
Length arithmetic overflows ProtocolError::Overflow("aead header length") InvalidData, integer overflow: aead header length. Unreachable in practice, since the length is a u16.
Response header tag fails, or its first byte differs decode_response_header_slice InvalidData (vmess: AEAD header open failed or vmess: unexpected response header).

gcm_seal cannot fail for header-sized inputs; if the AEAD library ever returned an error it yields an empty buffer rather than panicking. The code avoids panics on peer input by construction: every slice access that depends on received bytes or a received length goes through take_array or get, and arithmetic on peer-supplied lengths is checked. The remaining fixed-offset indexing is on arrays of known size. No test feeds malformed bytes to these functions specifically.

A failed handshake has no cancellation concerns of its own: every function on this page is synchronous, and the handshake deadline belongs to the core’s timing (see Server core).

Name Value Where
TAG_SIZE 16 bytes aead.rs; GCM and ChaCha20-Poly1305 tags
Auth id 16 bytes AuthId
ConnNonce 8 bytes aead.rs
Sealed length field 18 bytes (2 + TAG_SIZE) open_vmess_aead_header_slice → LEN_PART
Inner header length up to 65535 bytes (u16) sealed length field
SHAKE128_RATE 168 bytes aead.rs
next_padding_len 0 to 63 aead.rs
AUTHID_WINDOW_SECS 120 s, each direction accounts.rs
PLAUSIBLE_STAMP_LIMIT 2^33 s (the year 2242), the bound on a stamp with the clock check off accounts.rs
REPLAY_TTL 240 s accounts.rs
REPLAY_SHARDS 64 accounts.rs
REPLAY_MASK 63 accounts.rs
HOT_USERS 4096 users in the hot tier accounts.rs
COLD_HITS_PER_REFRESH 16 full-scan matches before a hot-tier refresh is due accounts.rs
HINT_SETS 1024 hint sets accounts.rs
HINT_MASK 1023 accounts.rs
HINT_WAYS 16 addresses per hint set accounts.rs
Address hints in all 16 384 addresses (HINT_SETS * HINT_WAYS) accounts.rs
HINT_USERS 4 users per address accounts.rs
HOT_TIER_POLL 1 s between a listener’s hot-tier checks supervisor/src/serve.rs
Test File Pins
shake128_fips202_empty protocols/tests/unit/vmess/aead.rs First 32 output bytes of SHAKE128("") match FIPS 202.
shake128_streaming_matches_bulk same 48 two-byte reads equal one 96-byte read.
hmac_base_level_matches_reference same KDF level 0 equals hmac::SimpleHmac<Sha256>.
auth_id_roundtrips_within_window same CRC and timestamp survive encrypt and decrypt.
header_seal_open_roundtrips same Seal, split off the auth id, open with open_vmess_aead_header_slice, and check that used covers the whole rest.
user_found_for_own_authid_within_window protocols/tests/unit/vmess/accounts.rs Match returns the right cmd key, UUID and payload.
add_after_construction_is_matchable same new then add produces a matchable user.
user_not_found_outside_time_window same Ids 1000 s in the past and future are rejected.
an_out_of_window_id_reports_its_skew same Eight hours behind and 121 s ahead are Skewed with those skews; 120 s behind passes; the two Display texts.
with_the_clock_check_off_any_plausible_stamp_passes same With the check off, stamps eight hours either way, 1, the years 2000 and 2100 and PLAUSIBLE_STAMP_LIMIT - 1 pass; −1, i64::MIN, the limit and i64::MAX are Skewed.
with_the_clock_check_off_replays_are_still_refused same An id eight hours old passes once, then is Replayed.
user_not_found_for_wrong_id same Another user’s id is rejected.
replayed_authid_is_rejected same Second use of an id returns AuthFailure::Replayed.
replay_survives_heavy_traffic same 20 000 other ids do not evict a live entry.
expired_ids_leave_the_set same Entries past REPLAY_TTL are removed.
a_uuid_listed_twice_keeps_its_first_payload same from_users and add keep one slot for a UUID listed twice, with its first payload, also when it matches through the address hint.
set_users_replaces_the_set_but_not_the_replay_state same A removed user no longer matches, a new one does, a kept user listed twice takes its first listing’s payload, and an id seen before the swap is still a replay.
a_prepared_set_takes_effect_only_when_installed same Before install the old user matches and the new one does not; after it, the reverse.
a_replay_through_the_hint_is_still_refused same An id matched through the address hint is Replayed the second time.
a_hint_never_admits_another_user same With the address hinting one of two users, the other’s id matches the other, an outsider’s is NoUser, and the hinted user’s own id stamped an hour behind is Skewed with that skew.
a_hint_for_a_removed_user_is_skipped same Once the hinted user is removed, its id is NoUser and only the full scan ran; a remaining user still matches from the same address.
a_hint_for_a_user_whose_uuid_changed same A user whose UUID changes under the same payload: the old UUID’s id is NoUser, the new one is found by the scan, and then by the address hint first.
a_kept_user_takes_its_new_payload_through_the_hint same A kept user matched through the address hint returns its new payload, and the hint is the first key tried.
an_address_remembers_its_last_few_users same Five users through one Hint: the first falls out and the rest are newest first; promoting a listed user moves it to the front and drops no one.
an_ipv6_hint_covers_its_64_and_mapped_ipv4_is_ipv4 same A hint for one IPv6 address answers for another in the same /64 and not for the next /64; an IPv4-mapped address shares its IPv4 address’s hint.
the_hints_are_bounded same Three times HINT_SETS * HINT_WAYS addresses: no set holds more than HINT_WAYS, the total stays within the capacity, and the newest address is still recalled.
the_hot_tier_changes_only_when_a_refresh_is_installed same Fifteen full-scan matches leave a refresh not due and the sixteenth makes it due, with the tier still empty. Preparing resets the count and changes nothing until it is installed. Then the tier’s user is found in the tier with no hint, a user outside it after the tier, and an unknown id is refused after the tier and the full scan.
the_hot_tier_is_the_most_recent_users_newest_first same HOT_USERS + 100 users with set match times, one of which never matched: the tier is exactly the HOT_USERS newest, newest first.
set_users_carries_the_hot_tier_over same A tier of three users; one leaves and a newcomer joins. The other two keep their tier order under their new slots, and the newcomer matches.
add_keeps_the_hot_tier same add leaves the tier as it was, and the added user matches.
a_refresh_racing_an_install_is_dropped same A tier prepared before set_users is dropped by install_hot_tier; the old user’s id does not open the user now in its old slot.
a_wrong_or_stale_user_hint_falls_through same A hint naming another user is tried and passed over, and the search finds the id’s owner; an unknown id with a hint is NoUser; a hint for a removed user is skipped, and only the full scan runs.
a_user_named_twice_is_tried_once same When the hint and the address name the same user, the guesses try it once before the full scan.
a_user_hint_never_shows_its_uuid same A UserHint’s Debug is UserHint(<redacted>) and holds no UUID text.
handshakes_racing_installs_match_only_their_owner same Four threads authenticate with addresses and hints while another alternates set_users and hot-tier refreshes: every match is the id’s owner, and a user out of the set is NoUser.
request_header_roundtrips protocols/tests/unit/vmess/protocol.rs Full request header through seal and open_vmess_aead_header_slice, with used.
response_header_roundtrips same Response header seal and decode_response_header_slice.
request_and_response_headers_open_from_slices same Slice openers on truncated and complete buffers.
stream_codec_seals_the_header_and_chunks_and_opens_the_response protocols/tests/unit/vmess/codec.rs A client codec’s header opens with open_vmess_aead_header_slice, and used points at the first body chunk.
a_replayed_auth_id_is_refused protocols/tests/unit/vmess/core.rs Two cores sharing a validator; the replay fails with PermissionDenied.
a_client_with_a_wrong_clock_is_refused_by_its_skew, a_client_with_a_wrong_clock_connects_with_the_clock_check_off same A server clock eight hours ahead refuses the client with s behind the server clock; with the check off the same client opens its flow.
a_vmess_clock_check_change_swaps_the_handler_without_disruption supervisor/tests/unit/plan.rs Turning the check off builds and swaps the handler, with no bind, stop, close or disruption.
a_due_hot_tier_is_refreshed_by_the_listener supervisor/tests/unit/serve.rs refresh_hot_tiers over a VMess handler refreshes a due hot tier within five polls, and returns within one poll once its token is cancelled.
a_vmess_inbound_can_turn_the_clock_check_off app/tests/unit/lower.rs clock_check = false lowers to InboundProtocolSpec::Vmess { clock_check: false, .. }; the key on a VLESS inbound is refused.
new_server_vs_new_client_tcp, new_server_vs_new_client_udp protocols/tests/pipeline/vmess.rs Server core against client codecs over sockets.
app_server_vmess_grpc_xray_client_tls and the two WebSocket early-data tests app/tests/integration/e2e_xray_vmess.rs Byte compatibility with a real Xray binary.

The accounts.rs tests use test-only helpers on AccountValidator (user_count, hot_users, which lists the tier’s users in order, refresh_hot_tier, which prepares and installs a tier, seen_len, expire_all) and on SourceHints (len). auth_id_with_nonce and its shorthand id build an id with a chosen random field, so tests can create many distinct, valid ids in the same second. decrypts reads a thread-local counter that decipher_matches bumps in test builds (tests::count_trial_decrypt), so a test can pin which steps of the search a handshake ran. Run the unit tests with cargo test -p etemenanki-protocols vmess.

protocols/benches/vmess_users.rs is a criterion bench over validators of 1 000, 10 000, 100 000 and 1 000 000 synthetic users, in two groups:

  • worst_case runs authenticate on an auth id no user owns, which takes the full scan to the end, and reports throughput in users scanned. A miss leaves the validator untouched (no replay insert, no match time, no hint), so every iteration measures the same full scan.
  • repeat_source runs verify_from with the last user’s auth id, from an address that user has already matched from, so the address hint names it. The id was admitted once before the measurement, so each iteration runs the search as for a fresh id and is then refused as Replayed, which again leaves the validator as it was.

Run it with cargo bench -p etemenanki-protocols --bench vmess_users.