Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ web-transport-iroh = "0.7"
# aws-lc-rs / ring features.
# The WebTransport adapter released with moq-noq, from the same repository.
web-transport-moq = { version = "1.3.5", default-features = false }
web-transport-proto = "0.6"
web-transport-proto = "0.6.4"
web-transport-trait = "0.4"
web-transport-wasm = "0.6"
x11rb = { version = "0.14.0", features = ["randr", "xfixes"] }
Expand Down
1 change: 1 addition & 0 deletions rs/moq-auth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,5 @@ moq-auth = { path = ".", features = ["client", "serve"] }
moq-token = "0.7"
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util"] }
tracing-test = { workspace = true }
wiremock = "0.6"
4 changes: 2 additions & 2 deletions rs/moq-auth/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ pub enum Error {
#[error("no publish or subscribe allowed; token is useless")]
UselessToken,

#[error("path `{0}` does not overlap the token root")]
#[error("path {0:?} does not overlap the token root")]
RootMismatch(String),

#[error("token grants no access to path `{0}`")]
#[error("token grants no access to path {0:?}")]
NoAccess(String),

#[error("no publish or subscribe allowed; key scope is useless")]
Expand Down
31 changes: 29 additions & 2 deletions rs/moq-auth/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::lease::Reason;
/// query parameter is special and a credential can be whatever the server understands. The same shape carries
/// every [`Event`]; an `end` adds what the session did.
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[derive(Clone, Serialize, Deserialize, PartialEq)]
#[non_exhaustive]
pub struct Request {
/// Random 128-bit hex, unique per session; the key every event for it shares.
Expand Down Expand Up @@ -58,6 +58,27 @@ pub struct Request {
pub tls: Option<Peer>,
}

impl std::fmt::Debug for Request {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Request")
.field("id", &self.id)
.field("event", &self.event)
.field("node", &self.node)
.field("transport", &self.transport)
.field("remote", &self.remote)
.field("local", &self.local)
.field("server_name", &self.server_name)
.field("alpn", &self.alpn)
.field("path", &self.path)
// The contract permits credentials under any query key.
.field("query", &self.query.as_ref().map(|_| "..."))
.field("token", &self.token)
.field("role", &self.role)
.field("tls", &self.tls)
.finish()
}
}

impl Request {
/// A `connect` for a fresh session, minting a random 128-bit hex id.
///
Expand Down Expand Up @@ -87,7 +108,7 @@ impl Request {

/// A credential from a moq-transport SETUP's `AUTHORIZATION TOKEN` option, unparsed.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Token {
/// The moq-transport Token Type, naming how [`value`](Self::value) is encoded.
pub kind: u64,
Expand All @@ -96,6 +117,12 @@ pub struct Token {
pub value: Vec<u8>,
}

impl std::fmt::Debug for Token {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Token(kind={}, <{} bytes>)", self.kind, self.value.len())
}
}

impl Token {
/// Token Type 0: a format negotiated out of band; `moq auth serve` reads it as a JWT.
pub const OUT_OF_BAND: u64 = 0x0;
Expand Down
59 changes: 56 additions & 3 deletions rs/moq-auth/src/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,9 @@ pub enum Refusal {
UnknownKey,
#[error("the token is invalid: {0}")]
InvalidToken(String),
#[error("the token root `{root}` does not overlap the dialed path `{path}`")]
#[error("the token root {root:?} does not overlap the dialed path {path:?}")]
RootMismatch { root: String, path: String },
#[error("nothing is granted at `{path}`")]
#[error("nothing is granted at {path:?}")]
NoAccess { path: String },
#[error("a certificate was presented but nothing is granted to certificates")]
NoMtlsGrant,
Expand Down Expand Up @@ -394,7 +394,7 @@ async fn handle(State(server): State<Server>, Json(request): Json<Request>) -> R
// The reason rides in the body, so an operator reading the relay's log knows
// which rule refused without the server saying anything to the client.
Err(refusal) => {
tracing::debug!(id = %request.id, path = %request.path, %refusal, "refused");
tracing::debug!(id = ?request.id, path = ?request.path, ?refusal, "refused");
(StatusCode::FORBIDDEN, refusal.to_string()).into_response()
}
}
Expand Down Expand Up @@ -425,6 +425,59 @@ mod tests {
request
}

#[tokio::test(start_paused = true)]
#[tracing_test::traced_test]
async fn refusal_fields_are_escaped_and_credentials_are_redacted() {
let secret = "credential-that-must-not-be-logged";
let mut facts = with_token(request("/room\nforged-record\r\x1b[31m"), secret);
facts.id = "id\nforged-id".into();
facts.token = Some(Token {
kind: Token::OUT_OF_BAND,
value: secret.as_bytes().to_vec(),
});
tracing::trace!(request = ?facts, "admission diagnostics");
let response = handle(State(Server::new(Policy::default()).unwrap()), Json(facts)).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert!(logs_contain("refused"));
assert!(!logs_contain(secret));
let decimal = format!("{:?}", secret.as_bytes());
assert!(!logs_contain(&decimal[1..decimal.len() - 1]));
assert!(!logs_contain("\nforged-record"));
assert!(!logs_contain("\nforged-id"));

let (dir, key) = key_dir();
let root = "root\nforged-root\r\x1b[31m";
let jwt = sign(&key, root, &["**"], &[], None);
let policy = Policy {
keys: Some(Keys::Dir(dir.path().into())),
..Default::default()
};
let response = handle(
State(Server::new(policy).unwrap()),
Json(with_token(request("/elsewhere"), &jwt)),
)
.await;
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert!(logs_contain("RootMismatch"));
assert!(!logs_contain(&jwt));
assert!(!logs_contain("\nforged-root"));
for err in [
Refusal::RootMismatch {
root: root.into(),
path: "path\nforged-path".into(),
}
.to_string(),
Refusal::NoAccess {
path: "path\nforged-path".into(),
}
.to_string(),
crate::Error::RootMismatch("path\nforged-path".into()).to_string(),
crate::Error::NoAccess("path\nforged-path".into()).to_string(),
] {
assert!(!err.contains('\n'));
}
}

fn with_peer(mut request: Request, expires: Option<SystemTime>) -> Request {
request.tls = Some(Peer {
name: "edge0".into(),
Expand Down
1 change: 1 addition & 0 deletions rs/moq-net/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ serde_json = { workspace = true }
# test-util (tokio::time::pause/advance) is test-only and is NOT supported on
# wasm, so it must not leak into the normal dependency feature set.
tokio = { workspace = true, features = ["macros", "io-util", "sync", "test-util", "time", "rt"] }
tracing-test = { workspace = true, features = ["no-env-filter"] }

# Model checks for the kio-backed model layer (tests/loom.rs). `cfg(loom)` is only
# set by `just rs loom`, and the whole test file compiles away without it.
Expand Down
11 changes: 10 additions & 1 deletion rs/moq-net/src/goaway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const MAX_TIMEOUT_MS: u64 = (1 << 62) - 1;

/// A GOAWAY: the sender intends to close the session soon and the peer should
/// migrate its subscriptions elsewhere.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Goaway {
/// Where the peer should reconnect, including any credentials it needs.
/// Empty means reconnect to the same endpoint.
Expand All @@ -44,6 +44,15 @@ pub struct Goaway {
pub(crate) timeout: Option<Duration>,
}

impl std::fmt::Debug for Goaway {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Goaway")
.field("uri_len", &self.uri.len())
.field("timeout", &self.timeout)
.finish()
}
}

impl Goaway {
/// Tell the peer to reconnect to the same endpoint.
pub fn new() -> Self {
Expand Down
12 changes: 11 additions & 1 deletion rs/moq-net/src/ietf/goaway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,23 @@ use super::Message;
use super::Version;

/// GoAway message (0x10)
#[derive(Clone, Debug)]
#[derive(Clone)]
pub struct GoAway<'a> {
pub new_session_uri: Cow<'a, str>,
/// Draft-17: timeout in milliseconds before closing the session
pub timeout: u64,
}

impl std::fmt::Debug for GoAway<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// The new session URI carries whatever credentials the peer needs to dial it.
f.debug_struct("GoAway")
.field("new_session_uri_len", &self.new_session_uri.len())
.field("timeout", &self.timeout)
.finish()
}
}

impl Message for GoAway<'_> {
const ID: u64 = 0x10;

Expand Down
3 changes: 2 additions & 1 deletion rs/moq-net/src/ietf/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ impl<T: Message> Decode<Version> for T {
Ok(result)
}
Err(e) => {
tracing::warn!(%e, ?raw, "decode failed");
// A malformed message can contain credentials too.
tracing::warn!(%e, "decode failed");
Err(e)
}
}
Expand Down
19 changes: 18 additions & 1 deletion rs/moq-net/src/ietf/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,29 @@ pub enum ParameterBytes {
Unknown(u64),
}

#[derive(Default, Debug, Clone)]
#[derive(Default, Clone)]
pub struct Parameters {
vars: HashMap<ParameterVarInt, u64>,
bytes: HashMap<ParameterBytes, Vec<u8>>,
}

impl std::fmt::Debug for Parameters {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Parameters")
.field("vars", &self.vars)
// Values can carry credentials, so only their lengths.
.field(
"bytes",
&self
.bytes
.iter()
.map(|(kind, value)| (kind, value.len()))
.collect::<Vec<_>>(),
)
.finish()
}
}

impl Decode<Version> for Parameters {
fn decode<R: bytes::Buf>(mut r: &mut R, version: Version) -> Result<Self, DecodeError> {
let mut vars = HashMap::new();
Expand Down
9 changes: 8 additions & 1 deletion rs/moq-net/src/lite/goaway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@ use super::{Message, Version};
/// Sent to gracefully shut down a session and optionally redirect to a new URI.
///
/// Lite04+ only.
#[derive(Clone, Debug)]
#[derive(Clone)]
pub struct Goaway<'a> {
pub uri: Cow<'a, str>,
}

impl std::fmt::Debug for Goaway<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// The redirect carries whatever credentials the peer needs to dial it.
f.debug_struct("Goaway").field("uri_len", &self.uri.len()).finish()
}
}

impl Message for Goaway<'_> {
const CONTROL: Option<crate::stats::Control> = Some(crate::stats::Control::Goaway);
fn decode_msg<R: bytes::Buf>(r: &mut R, version: Version) -> Result<Self, DecodeError> {
Expand Down
3 changes: 2 additions & 1 deletion rs/moq-net/src/lite/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ impl<T: Message> Decode<Version> for T {
Ok(result)
}
Err(e) => {
tracing::warn!(%e, ?raw, "decode failed");
// A malformed message can contain credentials too.
tracing::warn!(%e, "decode failed");
Err(e)
}
}
Expand Down
10 changes: 9 additions & 1 deletion rs/moq-net/src/lite/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,17 @@ const MAX_PARAMS: u64 = 64;
/// A bag of `id -> raw bytes` parameters, the body shared by SETUP (and any other
/// parameterized message). Encoded as a varint count followed by `id, length, value`
/// triples; duplicate ids are rejected on decode.
#[derive(Default, Debug, Clone)]
#[derive(Default, Clone)]
pub struct Parameters(HashMap<u64, Vec<u8>>);

impl std::fmt::Debug for Parameters {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map()
.entries(self.0.iter().map(|(kind, value)| (kind, value.len())))
.finish()
}
}

impl Parameters {
/// Set a parameter to a raw byte value, replacing any existing entry.
pub fn set_bytes(&mut self, id: u64, value: Vec<u8>) {
Expand Down
4 changes: 2 additions & 2 deletions rs/moq-net/src/lite/publisher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ impl<S: crate::transport::poll::Session> Control<S> {
// malformed GOAWAY must not tear down the session it is trying to drain.
let mut cx = Context::from_waker(waiter.waker());
let msg = ready!(stream.reader.poll_decode::<lite::Goaway>(&mut cx))?;
tracing::info!(uri = %msg.uri, "received goaway");
tracing::info!(uri_len = msg.uri.len(), "received goaway");

let uri = msg.uri.into_owned();
let goaway = crate::goaway::Goaway {
Expand All @@ -337,7 +337,7 @@ impl<S: crate::transport::poll::Session> Control<S> {
// A second Goaway stream is a protocol violation. The control loop only
// logs per-stream errors, so close the session here rather than letting a
// peer silently replace a redirect an observer may already be acting on.
tracing::warn!(%uri, "duplicate GOAWAY received; closing session");
tracing::warn!(uri_len = uri.len(), "duplicate GOAWAY received; closing session");
self.shared
.session
.clone()
Expand Down
18 changes: 17 additions & 1 deletion rs/moq-net/src/lite/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ impl std::fmt::Display for Role {
/// lite-05+ only. The two endpoints' SETUP messages are independent: neither side
/// blocks on the peer's before opening other streams, but a stream whose encoding
/// depends on a negotiated capability (e.g. PROBE) must wait for it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Setup {
/// The probe capability this endpoint supports. [`ProbeLevel::None`] when absent.
pub probe: ProbeLevel,
Expand Down Expand Up @@ -184,6 +184,22 @@ pub struct Setup {
pub hop: Option<crate::Hop>,
}

impl std::fmt::Debug for Setup {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Setup")
.field("probe", &self.probe)
// Native transports carry the JWT in this request target.
.field(
"path",
&self.path.as_deref().map(|path| path.split('?').next().unwrap()),
)
.field("role", &self.role)
.field("cost", &self.cost)
.field("hop", &self.hop)
.finish()
}
}

impl Message for Setup {
const CONTROL: Option<crate::stats::Control> = Some(crate::stats::Control::Session);
const MAX_SIZE: usize = crate::setup::MAX_SETUP_SIZE;
Expand Down
Loading
Loading