Skip to main content

moq_auth/
error.rs

1/// Renders an error and its `source()` chain into a single message.
2///
3/// Dependency errors are stored as messages so their crates stay out of this crate's public
4/// API. Several of them keep the actionable half in `source()` and nothing but a category in
5/// `Display`, so a plain `to_string()` would drop the only detail worth reporting.
6pub(crate) fn message(err: impl std::error::Error) -> String {
7	use std::fmt::Write;
8
9	let mut out = err.to_string();
10	let mut source = err.source();
11	while let Some(err) = source {
12		let _ = write!(out, ": {err}");
13		source = err.source();
14	}
15	out
16}
17
18/// Errors related to key configuration and cryptographic operations.
19#[derive(Debug, thiserror::Error)]
20#[non_exhaustive]
21pub enum KeyError {
22	#[error("invalid algorithm for key type")]
23	InvalidAlgorithm,
24
25	#[error("invalid algorithm for {0} curve")]
26	InvalidAlgorithmForCurve(&'static str),
27
28	#[error("invalid coordinate length for {0}")]
29	InvalidCoordinateLength(&'static str),
30
31	#[error("invalid curve for {0} key")]
32	InvalidCurve(&'static str),
33
34	#[error("missing private key")]
35	MissingPrivateKey,
36
37	#[error("oct key secret must be at least {0} bytes")]
38	SecretTooShort(usize),
39
40	#[error("OCT key cannot be converted to public key")]
41	NoPublicKey,
42
43	#[error("key does not support verification")]
44	VerifyUnsupported,
45
46	#[error("key does not support signing")]
47	SignUnsupported,
48
49	#[error("cannot find signing key")]
50	NoSigningKey,
51
52	#[error("cannot find key with kid {0}")]
53	KeyNotFound(String),
54
55	#[error("missing kid in JWT header")]
56	MissingKid,
57
58	#[error("missing x() point in EC key")]
59	MissingEcX,
60
61	#[error("missing y() point in EC key")]
62	MissingEcY,
63}
64
65/// Top-level error type for moq-auth.
66#[derive(Debug, thiserror::Error)]
67#[non_exhaustive]
68pub enum Error {
69	#[error(transparent)]
70	Key(#[from] KeyError),
71
72	#[error("no publish or subscribe allowed; token is useless")]
73	UselessToken,
74
75	#[error("path `{0}` does not overlap the token root")]
76	RootMismatch(String),
77
78	#[error("token grants no access to path `{0}`")]
79	NoAccess(String),
80
81	#[error("no publish or subscribe allowed; key scope is useless")]
82	UselessScope,
83
84	#[error("token capabilities exceed the key scope")]
85	ScopeExceeded,
86
87	#[error("invalid algorithm: {0}")]
88	InvalidAlgorithm(String),
89
90	#[error("token has expired")]
91	TokenExpired,
92
93	#[error("token is not valid yet")]
94	TokenNotYetValid,
95
96	#[error(transparent)]
97	Pattern(#[from] moq_pattern::InvalidPattern),
98
99	#[error("grant names nothing; the session is refused")]
100	UselessGrant,
101
102	#[error("grant asks to be revalidated but never expires")]
103	UnboundedRevalidate,
104
105	#[error("session limits need a revalidate cadence, which ages out the slots of a relay that died")]
106	LimitsWithoutRevalidate,
107
108	#[error("grant asks to be revalidated at no interval")]
109	ZeroRevalidate,
110
111	#[error("grant has already expired")]
112	GrantExpired,
113
114	#[error("the auth server refused the session")]
115	Refused,
116
117	#[error("auth server unavailable: {0}")]
118	Unavailable(String),
119
120	#[error("auth URL must be https://, unix://, or http:// to a loopback address: {0}")]
121	InsecureUrl(String),
122
123	#[error("invalid auth URL: {0}")]
124	InvalidUrl(String),
125
126	/// A JWK or claims document couldn't be parsed or serialized.
127	#[error("{0}")]
128	Json(String),
129
130	#[error(transparent)]
131	Io(#[from] std::io::Error),
132
133	/// A base64url field (a JWK coordinate, a JWT segment) isn't valid base64.
134	#[error("{0}")]
135	Base64(String),
136
137	#[error(transparent)]
138	Utf8(#[from] std::string::FromUtf8Error),
139
140	/// The JWT itself couldn't be signed, decoded, or verified.
141	#[error("{0}")]
142	Jwt(String),
143
144	/// A key couldn't be parsed, imported, or used by the crypto backend.
145	#[error("{0}")]
146	Crypto(String),
147
148	/// Fetching a remote JWKS failed.
149	#[error("{0}")]
150	Other(String),
151}
152
153// Dependency errors are flattened to their message so their crates stay out of this crate's
154// public API. Every one of them is opaque to a caller anyway: there is nothing to match on,
155// only something to report.
156macro_rules! from_message {
157	($($ty:ty => $variant:ident),* $(,)?) => {
158		$(
159			impl From<$ty> for Error {
160				fn from(err: $ty) -> Self {
161					Self::$variant(message(err))
162				}
163			}
164		)*
165	};
166}
167
168from_message! {
169	serde_json::Error => Json,
170	base64::DecodeError => Base64,
171	jsonwebtoken::errors::Error => Jwt,
172	p256::elliptic_curve::pkcs8::Error => Crypto,
173	p256::elliptic_curve::Error => Crypto,
174	rsa::Error => Crypto,
175	rsa::pkcs1::Error => Crypto,
176	aws_lc_rs::error::Unspecified => Crypto,
177	aws_lc_rs::error::KeyRejected => Crypto,
178}
179
180#[cfg(feature = "client")]
181impl From<reqwest::Error> for Error {
182	fn from(err: reqwest::Error) -> Self {
183		// reqwest prints the full URL in its error, and a dialed URL can carry
184		// credentials in its query or userinfo.
185		Self::Unavailable(message(err.without_url()))
186	}
187}
188
189pub type Result<T> = std::result::Result<T, Error>;
190
191#[cfg(test)]
192mod tests {
193	use super::*;
194
195	/// A dependency that reports only a category in `Display` and keeps the real cause in
196	/// `source()` (reqwest is the one that matters here) must not lose it on conversion.
197	#[test]
198	fn message_flattens_the_source_chain() {
199		#[derive(Debug, thiserror::Error)]
200		#[error("inner")]
201		struct Inner;
202
203		#[derive(Debug, thiserror::Error)]
204		#[error("outer")]
205		struct Outer(#[source] Inner);
206
207		assert_eq!(message(Outer(Inner)), "outer: inner");
208	}
209}