From d9fba6adcc8993e33f8da9793b956d02ecf9cdb1 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 20:34:33 +0100 Subject: [PATCH] chore(lint): errors keep their source instead of discarding it in map_err --- Cargo.toml | 1 + apps/auth-service/src/admin/error.rs | 11 ++++-- apps/auth-service/src/admin/sign_in.rs | 10 +++++- apps/auth-service/src/audit/verify.rs | 8 +++-- apps/auth-service/src/clients/owned.rs | 4 +++ apps/auth-service/src/deletion/export/mod.rs | 4 +++ apps/auth-service/src/deliveries/email/mod.rs | 4 +++ apps/auth-service/src/deliveries/outbound.rs | 4 +++ apps/auth-service/src/emails/mod.rs | 4 +++ apps/auth-service/src/federation/error.rs | 2 +- apps/auth-service/src/federation/mod.rs | 2 +- apps/auth-service/src/keys/mod.rs | 2 +- apps/auth-service/src/passkey/confirmation.rs | 4 +++ apps/auth-service/src/pictures/mod.rs | 4 +++ apps/auth-service/src/recovery/mod.rs | 4 +++ apps/auth-service/src/security/session.rs | 4 +++ .../src/web/admin/announcements.rs | 4 +++ apps/auth-service/src/web/admin/mod.rs | 2 +- .../src/web/settings/notifications.rs | 4 +++ crates/auth-sdk/src/axum/login/extract.rs | 4 +++ crates/auth-sdk/src/issuer.rs | 12 +++---- crates/auth-sdk/src/keys.rs | 11 +++--- crates/auth-sdk/src/token.rs | 18 ++++++---- crates/common/src/config/mod.rs | 4 +++ crates/common/src/lib.rs | 11 ++++-- crates/common/src/protocol/challenge/mod.rs | 34 +++++++++++++------ crates/common/src/protocol/challenge/tests.rs | 4 +-- crates/crypto/src/jws.rs | 14 +++++--- crates/crypto/src/lib.rs | 16 ++++++++- crates/crypto/src/note.rs | 26 +++++++++++--- crates/crypto/src/sealing/mod.rs | 4 +++ crates/crypto/src/signing/mod.rs | 6 ++-- crates/telemetry/src/lib.rs | 4 +-- 33 files changed, 190 insertions(+), 60 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 16baab021..b73de439a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,7 @@ unwrap_used = "warn" expect_used = "warn" panic = "warn" todo = "warn" +map_err_ignore = "warn" unimplemented = "warn" dbg_macro = "warn" # Every exception names its lint with `#[expect]` and says why. diff --git a/apps/auth-service/src/admin/error.rs b/apps/auth-service/src/admin/error.rs index e717e2a28..e82d2b548 100644 --- a/apps/auth-service/src/admin/error.rs +++ b/apps/auth-service/src/admin/error.rs @@ -2,8 +2,8 @@ use super::UserRef; use crate::{ - ClientRegistryError, KeyError, deletion::DeletionError, handles::HandlesError, - security::ApiError, + ClientRegistryError, KeyError, deletion::DeletionError, federation::InvalidReturnTo, + handles::HandlesError, security::ApiError, }; use sourceorigin_common::{ DeliveryId, PasskeyId, email::InvalidEmail, protocol::step_up::StepUpRequirement, @@ -28,6 +28,10 @@ pub enum AdminError { /// used, expired or for another browser, or its request is malformed. #[error("this sign-in to the dashboard did not work; sign in again")] InvalidHandoff, + /// A sign-in to the dashboard was handed off with a return path that leaves + /// the dashboard. + #[error("this sign-in to the dashboard did not work; sign in again")] + InvalidHandoffReturn(#[source] InvalidReturnTo), /// No account has this ID or handle, or no active one this verified email. #[error("no account has this ID, handle or verified email")] UserNotFound, @@ -227,7 +231,7 @@ impl AdminError { Self::SessionEnded => "session_ended", Self::NotAdministrator => "not_administrator", Self::StepUpRequired(_) => "step_up_required", - Self::InvalidHandoff => "invalid_handoff", + Self::InvalidHandoff | Self::InvalidHandoffReturn(_) => "invalid_handoff", Self::UserNotFound => "user_not_found", Self::InvitationNotFound => "invitation_not_found", Self::ClientNotFound => "client_not_found", @@ -312,6 +316,7 @@ impl From for ApiError { | AdminError::InvalidInvitationEmail(_) | AdminError::InvitationUnsendable(_) | AdminError::InvalidHandoff + | AdminError::InvalidHandoffReturn(_) | AdminError::InvalidSubject | AdminError::InvalidBody | AdminError::NoRecipients diff --git a/apps/auth-service/src/admin/sign_in.rs b/apps/auth-service/src/admin/sign_in.rs index 6169d9337..d9f3a4397 100644 --- a/apps/auth-service/src/admin/sign_in.rs +++ b/apps/auth-service/src/admin/sign_in.rs @@ -171,6 +171,10 @@ impl DashboardSignIn { if proof.session_id() != session.id { return Err(AdminError::SessionEnded); } + #[expect( + clippy::map_err_ignore, + reason = "Secret::parse names a byte of the handoff's state, a secret" + )] let state = Secret::parse(&handoff.state).map_err(|_| AdminError::InvalidHandoff)?; let return_to = Self::path(&handoff.return_to)?; let code = Secret::generate()?; @@ -212,6 +216,10 @@ impl DashboardSignIn { let state = BrowserCookie::DashboardState .read(headers) .ok_or(AdminError::InvalidHandoff)?; + #[expect( + clippy::map_err_ignore, + reason = "Secret::parse names a byte of the handoff's code, a secret" + )] let code = Secret::parse(code).map_err(|_| AdminError::InvalidHandoff)?; let mut tx = self.database.begin().await?; let user_id = (tx @@ -366,6 +374,6 @@ impl DashboardSignIn { /// The dashboard path `value` names, which cannot leave the dashboard's origin. fn path(value: &str) -> Result { - ReturnTo::parse(Some(value)).map_err(|_| AdminError::InvalidHandoff) + ReturnTo::parse(Some(value)).map_err(AdminError::InvalidHandoffReturn) } } diff --git a/apps/auth-service/src/audit/verify.rs b/apps/auth-service/src/audit/verify.rs index 98afb64e7..0c0c2e47c 100644 --- a/apps/auth-service/src/audit/verify.rs +++ b/apps/auth-service/src/audit/verify.rs @@ -68,9 +68,11 @@ impl AuditKeys { Some(text) if text.head == stored && text.time == checkpoint.created_at => None, _ => Some(ChainProblem::CheckpointMalformed), }, - Err(CryptoError::NoteFormat | CryptoError::NoteText) => { - Some(ChainProblem::CheckpointMalformed) - } + Err( + CryptoError::NoteFormat + | CryptoError::NoteSignatureEncoding(_) + | CryptoError::NoteText, + ) => Some(ChainProblem::CheckpointMalformed), Err(CryptoError::NoteSignature | CryptoError::NoteUnverified) => { Some(ChainProblem::CheckpointSignature) } diff --git a/apps/auth-service/src/clients/owned.rs b/apps/auth-service/src/clients/owned.rs index 36c8b900a..dc97cea70 100644 --- a/apps/auth-service/src/clients/owned.rs +++ b/apps/auth-service/src/clients/owned.rs @@ -165,6 +165,10 @@ impl ClientSettings { id: ClientId, kind: ClientKind, ) -> Result { + #[expect( + clippy::map_err_ignore, + reason = "The message names the scope and the allowed ones, which `InvalidScope` does not" + )] let scopes = self .allowed_scopes .iter() diff --git a/apps/auth-service/src/deletion/export/mod.rs b/apps/auth-service/src/deletion/export/mod.rs index b6f06d8ac..1d61e4b65 100644 --- a/apps/auth-service/src/deletion/export/mod.rs +++ b/apps/auth-service/src/deletion/export/mod.rs @@ -530,6 +530,10 @@ impl AccountExport { clients, permit, } = self; + #[expect( + clippy::map_err_ignore, + reason = "A failed send returns the unsent chunk, which is the account's own data" + )] let send = async |chunk: Vec| { (sender.send(Ok(chunk.into())).await).map_err(|_| ExportError::Closed) }; diff --git a/apps/auth-service/src/deliveries/email/mod.rs b/apps/auth-service/src/deliveries/email/mod.rs index abe14e3ba..89a7d98ad 100644 --- a/apps/auth-service/src/deliveries/email/mod.rs +++ b/apps/auth-service/src/deliveries/email/mod.rs @@ -406,6 +406,10 @@ impl EmailSender { }; let mail = content.said.mail(); let html = mail.html().await.map_err(|error| built(&*error))?; + #[expect( + clippy::map_err_ignore, + reason = "A delivery's failure is stored as its `Failure` kind alone, never what a parser said of the address" + )] let to: Address = content .address .parse() diff --git a/apps/auth-service/src/deliveries/outbound.rs b/apps/auth-service/src/deliveries/outbound.rs index cefe2b1bb..175d724cf 100644 --- a/apps/auth-service/src/deliveries/outbound.rs +++ b/apps/auth-service/src/deliveries/outbound.rs @@ -155,6 +155,10 @@ impl OutboundClient { /// that is not public. Names are checked when they resolve. fn check(&self, destination: &str) -> Result { let invalid = DeliveryError::Permanent(Failure::InvalidDestination); + #[expect( + clippy::map_err_ignore, + reason = "A delivery's failure is stored as its `Failure` kind alone, never what a parser said of the destination" + )] let url = Url::parse(destination).map_err(|_| invalid)?; let address = match url.host() { _ if url.scheme() != "https" => return Err(invalid), diff --git a/apps/auth-service/src/emails/mod.rs b/apps/auth-service/src/emails/mod.rs index b1ce28bf7..bd98b8a54 100644 --- a/apps/auth-service/src/emails/mod.rs +++ b/apps/auth-service/src/emails/mod.rs @@ -520,6 +520,10 @@ impl AccountService { request: RequestContext, ) -> Result { // A token that does not parse cannot match: answer as for an unknown one. + #[expect( + clippy::map_err_ignore, + reason = "Secret::parse names a byte of the token, a secret; the answer is the one for an unknown token" + )] let digest = Secret::parse(token) .map_err(|_| EmailError::InvalidToken)? .digest(); diff --git a/apps/auth-service/src/federation/error.rs b/apps/auth-service/src/federation/error.rs index f1def7510..95d01ddae 100644 --- a/apps/auth-service/src/federation/error.rs +++ b/apps/auth-service/src/federation/error.rs @@ -171,7 +171,7 @@ impl From for ApiError { /// Why a `return_to` address is refused. Each message names the rule it breaks. #[derive(Debug, Error)] -pub(crate) enum InvalidReturnTo { +pub enum InvalidReturnTo { /// Anything but a path, such as an absolute URL, even one on auth. #[error("return_to must be a path on auth, starting with /")] NotAPath, diff --git a/apps/auth-service/src/federation/mod.rs b/apps/auth-service/src/federation/mod.rs index 587bfd257..7441ea812 100644 --- a/apps/auth-service/src/federation/mod.rs +++ b/apps/auth-service/src/federation/mod.rs @@ -37,7 +37,7 @@ mod error; mod identities; pub use error::FederationConfigError; pub(crate) use error::FederationError; -use error::InvalidReturnTo; +pub use error::InvalidReturnTo; pub(crate) use identities::{PendingKind, PendingView}; /// Provider protocol facts and verified identity exchange. mod providers; diff --git a/apps/auth-service/src/keys/mod.rs b/apps/auth-service/src/keys/mod.rs index e34be23ab..3641bdc3c 100644 --- a/apps/auth-service/src/keys/mod.rs +++ b/apps/auth-service/src/keys/mod.rs @@ -531,7 +531,7 @@ impl<'t, 'c> Change<'t, 'c> { /// Seals and stores `key` in `state`. async fn insert(&mut self, key: &Rs256Key, state: SigningKeyState) -> Result { let key_type = SigningKeyType::Rsa; - let id: KeyId = key.kid().parse().map_err(|_| CryptoError::KeyId)?; + let id: KeyId = key.kid().parse().map_err(CryptoError::KeyId)?; let sealed_private_key = self.store.seal(key, &id, key_type)?; self.tx .signing_keys() diff --git a/apps/auth-service/src/passkey/confirmation.rs b/apps/auth-service/src/passkey/confirmation.rs index e7edc280f..1e939cb94 100644 --- a/apps/auth-service/src/passkey/confirmation.rs +++ b/apps/auth-service/src/passkey/confirmation.rs @@ -145,6 +145,10 @@ impl PasskeyApplication { owner: &Owner, assertion: &str, ) -> Result { + #[expect( + clippy::map_err_ignore, + reason = "serde_json's message can quote the passkey assertion, which the response must not" + )] let input: AuthenticationFinish = serde_json::from_str(assertion) .map_err(|_| ApiError::bad_request("The passkey proof is malformed. Try again."))?; let session = owner.session(); diff --git a/apps/auth-service/src/pictures/mod.rs b/apps/auth-service/src/pictures/mod.rs index 30a379f2f..bac58b4db 100644 --- a/apps/auth-service/src/pictures/mod.rs +++ b/apps/auth-service/src/pictures/mod.rs @@ -282,6 +282,10 @@ impl PictureApplication { /// that does not parse names none. async fn serve(State(app): State, Path(id): Path) -> Result { let missing = || ApiError::not_found("There is no such picture."); + #[expect( + clippy::map_err_ignore, + reason = "A path that is no picture ID is answered as a missing picture, as an unknown ID is" + )] let id: PictureId = id.parse().map_err(|_| missing())?; let image = app .database diff --git a/apps/auth-service/src/recovery/mod.rs b/apps/auth-service/src/recovery/mod.rs index 353c6656d..5a484d1ba 100644 --- a/apps/auth-service/src/recovery/mod.rs +++ b/apps/auth-service/src/recovery/mod.rs @@ -387,6 +387,10 @@ impl AccountService { /// account is active. A token that does not parse cannot match, so it answers /// as an unknown one. pub(crate) async fn open_recovery(&self, token: &str) -> Result { + #[expect( + clippy::map_err_ignore, + reason = "Secret::parse names a byte of the token, a secret; the answer is the one for an unknown token" + )] let digest = Secret::parse(token) .map_err(|_| RecoveryError::InvalidLink)? .digest(); diff --git a/apps/auth-service/src/security/session.rs b/apps/auth-service/src/security/session.rs index 161f23626..2358d86b6 100644 --- a/apps/auth-service/src/security/session.rs +++ b/apps/auth-service/src/security/session.rs @@ -569,6 +569,10 @@ impl Confirmed { /// Rejects a session without a recent enough passkey confirmation. Handlers /// that need one only for some changes call it on the session they locked. + #[expect( + clippy::map_err_ignore, + reason = "`StepUpRequired` says what to ask the user for, which is all the handler needs of the unmet requirement" + )] pub(crate) fn check(session: &StoredSession) -> Result<(), SessionError> { let authentication = SessionAuthentication::from(session); Self::REQUIREMENT diff --git a/apps/auth-service/src/web/admin/announcements.rs b/apps/auth-service/src/web/admin/announcements.rs index 2acb7b92d..262657572 100644 --- a/apps/auth-service/src/web/admin/announcements.rs +++ b/apps/auth-service/src/web/admin/announcements.rs @@ -139,6 +139,10 @@ pub(super) async fn send(cx: &Cx, form: Option>) -> Resul let admin = App::confirmed(cx).await?; let service = &App::of(cx).service; let id = *path_param::(cx)?; + #[expect( + clippy::map_err_ignore, + reason = "The answer names what the form lacks, and a query's parse error can quote what was sent" + )] let checked: SendAnnouncement = parse_query_params(cx) .map_err(|_| Error::from(bad_request("name the revision the draft's page showed")))?; let back = href!(show, Announcement(id)).resolve(cx); diff --git a/apps/auth-service/src/web/admin/mod.rs b/apps/auth-service/src/web/admin/mod.rs index 7ee05418f..975880f6c 100644 --- a/apps/auth-service/src/web/admin/mod.rs +++ b/apps/auth-service/src/web/admin/mod.rs @@ -1310,7 +1310,7 @@ async fn sign_in(cx: &Cx) -> Result { cookie.set_on(&mut response)?; Ok(response) } - Err(refused @ AdminError::InvalidHandoff) => { + Err(refused @ (AdminError::InvalidHandoff | AdminError::InvalidHandoffReturn(_))) => { refused.log_refusal(); let retry = href!(overview::overview).resolve(cx); let page = view! { cx => diff --git a/apps/auth-service/src/web/settings/notifications.rs b/apps/auth-service/src/web/settings/notifications.rs index 0f2059d05..2d3cef3b2 100644 --- a/apps/auth-service/src/web/settings/notifications.rs +++ b/apps/auth-service/src/web/settings/notifications.rs @@ -150,6 +150,10 @@ impl NotificationPage { } /// The notification the path names, which is missing if it is not an ID. + #[expect( + clippy::map_err_ignore, + reason = "A path that is no notification ID is answered as a missing notification, as an unknown ID is" + )] fn id(cx: &Cx) -> Result { path_param::(cx).parse().map_err(|_| Failure::Missing) } diff --git a/crates/auth-sdk/src/axum/login/extract.rs b/crates/auth-sdk/src/axum/login/extract.rs index b31abd6f1..8e68b694b 100644 --- a/crates/auth-sdk/src/axum/login/extract.rs +++ b/crates/auth-sdk/src/axum/login/extract.rs @@ -123,6 +123,10 @@ impl SignedIn { /// /// # Errors /// The [`StepUp`] asking for `P`'s requirement. + #[expect( + clippy::map_err_ignore, + reason = "The `StepUp` answer asks to sign in again, which says why; the unmet requirement adds nothing for the app" + )] pub fn require(&self) -> Result<(), StepUp> { let authentication = &self.claims().authentication; TokenError::require_authentication( diff --git a/crates/auth-sdk/src/issuer.rs b/crates/auth-sdk/src/issuer.rs index 85e6edc5f..591df39c5 100644 --- a/crates/auth-sdk/src/issuer.rs +++ b/crates/auth-sdk/src/issuer.rs @@ -32,7 +32,7 @@ use url::Url; pub enum DiscoveryError { /// The configured issuer is not an `https` URL without query or fragment. #[error("issuer {0:?} must be an https URL without query or fragment")] - InvalidIssuer(String), + InvalidIssuer(String, #[source] Option), /// The metadata endpoint could not be reached. #[error(transparent)] Network(#[from] NetworkError), @@ -61,7 +61,7 @@ impl DiscoveryError { #[must_use] pub const fn code(&self) -> SdkError { match self { - Self::InvalidIssuer(_) => SdkError::category(ErrorCategory::Discovery), + Self::InvalidIssuer(..) => SdkError::category(ErrorCategory::Discovery), Self::Network(_) => SdkError::category(ErrorCategory::Network), Self::InvalidDocument(_) | Self::InsecureEndpoint(_) => { SdkError::new(ErrorCategory::Discovery, ErrorReason::InvalidDocument) @@ -212,16 +212,16 @@ impl Issuer { /// Where `issuer` publishes its metadata (OIDC Discovery 1.0 §4.1). fn metadata_url(issuer: &str) -> Result { - let invalid = || DiscoveryError::InvalidIssuer(issuer.to_owned()); - let url = Url::parse(issuer).map_err(|_| invalid())?; + let invalid = |source| DiscoveryError::InvalidIssuer(issuer.to_owned(), source); + let url = Url::parse(issuer).map_err(|source| invalid(Some(source)))?; if url.scheme() != "https" || url.query().is_some() || url.fragment().is_some() { - return Err(invalid()); + return Err(invalid(None)); } Url::parse(&format!( "{}{OPENID_CONFIGURATION_PATH}", issuer.trim_end_matches('/') )) - .map_err(|_| invalid()) + .map_err(|source| invalid(Some(source))) } /// Parses a metadata document and checks it belongs to `issuer`. diff --git a/crates/auth-sdk/src/keys.rs b/crates/auth-sdk/src/keys.rs index d567e9dae..432fbe02c 100644 --- a/crates/auth-sdk/src/keys.rs +++ b/crates/auth-sdk/src/keys.rs @@ -16,7 +16,7 @@ use sourceorigin_common::protocol::{ sdk::{ErrorCategory, ErrorReason, SdkError}, }; pub use sourceorigin_crypto::KeyDefect; -use sourceorigin_crypto::{Compact, Malformed, Rs256VerifyingKey, VerifyError}; +use sourceorigin_crypto::{Compact, Rs256VerifyingKey, VerifyError}; use std::{ fmt, sync::{Arc, Mutex, MutexGuard, PoisonError}, @@ -101,16 +101,15 @@ impl<'a> Jws<'a> { /// 16 KiB, with a JSON header; [`TokenError::UnsupportedCriticalHeader`] if that /// header sets `crit`. pub fn parse(token: &'a str) -> Result { - let malformed = |malformed: Malformed| TokenError::Malformed(malformed.0); - let split = Compact::split(token).map_err(malformed)?; - let header: JwsHeader = serde_json::from_slice(split.header()) - .map_err(|_| TokenError::Malformed("the header is not a JWS header"))?; + let split = Compact::split(token).map_err(TokenError::Malformed)?; + let header: JwsHeader = + serde_json::from_slice(split.header()).map_err(TokenError::MalformedHeader)?; if header.crit.is_some() { return Err(TokenError::UnsupportedCriticalHeader); } Ok(Self { header, - compact: split.decode().map_err(malformed)?, + compact: split.decode().map_err(TokenError::Malformed)?, }) } diff --git a/crates/auth-sdk/src/token.rs b/crates/auth-sdk/src/token.rs index f371549fe..ab22f38c6 100644 --- a/crates/auth-sdk/src/token.rs +++ b/crates/auth-sdk/src/token.rs @@ -4,7 +4,7 @@ use crate::{Issuer, KeyError, keys::Jws, scope::ScopeSet}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use sourceorigin_common::{ - ClientId, SessionId, TokenId, UserId, + ClientId, InvalidValue, SessionId, TokenId, UserId, protocol::{ challenge::{BearerChallenge, BearerError}, claims::{ @@ -18,6 +18,7 @@ use sourceorigin_common::{ step_up::StepUpRequirement, }, }; +use sourceorigin_crypto::Malformed; use std::marker::PhantomData; use thiserror::Error; @@ -51,8 +52,11 @@ use thiserror::Error; #[derive(Debug, Error)] pub enum TokenError { /// The token is not a compact JWS. - #[error("token is malformed: {0}")] - Malformed(&'static str), + #[error("token is malformed")] + Malformed(#[source] Malformed), + /// The header is not a JWS header. + #[error("token header is not a JWS header")] + MalformedHeader(#[source] serde_json::Error), /// The header lists `crit` extensions, which this SDK does not understand. #[error("token requires header extensions this SDK does not understand")] UnsupportedCriticalHeader, @@ -81,7 +85,7 @@ pub enum TokenError { InvalidClaims(#[source] serde_json::Error), /// `sub` is neither an account ID nor the client. #[error("token subject {0:?} is not an account ID")] - InvalidSubject(String), + InvalidSubject(String, #[source] InvalidValue), /// `iss` is not the issuer. #[error("token issuer is {found:?}, expected {expected:?}")] WrongIssuer { @@ -173,13 +177,13 @@ impl TokenError { Self::InsufficientUserAuthentication(_) => { return SdkError::category(ErrorCategory::InsufficientUserAuthentication); } - Self::Malformed(_) => ErrorReason::Malformed, + Self::Malformed(_) | Self::MalformedHeader(_) => ErrorReason::Malformed, Self::UnsupportedCriticalHeader => ErrorReason::UnsupportedCriticalHeader, Self::WrongType { .. } => ErrorReason::WrongType, Self::UnsupportedAlgorithm(_) => ErrorReason::UnsupportedAlgorithm, Self::UnknownKey(_) => ErrorReason::UnknownKey, Self::BadSignature => ErrorReason::BadSignature, - Self::InvalidClaims(_) | Self::InvalidSubject(_) | Self::NoLogoutTarget => { + Self::InvalidClaims(_) | Self::InvalidSubject(..) | Self::NoLogoutTarget => { ErrorReason::InvalidClaims } Self::WrongIssuer { .. } => ErrorReason::IssuerMismatch, @@ -218,7 +222,7 @@ impl TokenError { /// The account `sub` names. pub(crate) fn account(sub: &str) -> Result { sub.parse() - .map_err(|_| Self::InvalidSubject(sub.to_owned())) + .map_err(|source| Self::InvalidSubject(sub.to_owned(), source)) } /// Requires the authentication `acr` and `auth_time` describe to meet diff --git a/crates/common/src/config/mod.rs b/crates/common/src/config/mod.rs index 1368360d0..fcdec4a4b 100644 --- a/crates/common/src/config/mod.rs +++ b/crates/common/src/config/mod.rs @@ -278,6 +278,10 @@ impl SecretReference { /// /// # Errors /// Reports a missing, non-UTF-8, unreadable or empty secret. + #[expect( + clippy::map_err_ignore, + reason = "The error of a non-UTF-8 variable returns the secret's own bytes" + )] pub fn resolve(&self) -> Result { let bytes = match &self.0 { // var_os keeps the value out of the error, unlike env::var. diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index d0808b0c2..49bed249c 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -500,9 +500,14 @@ impl FromStr for TraceId { return Err(invalid()); } let mut bytes = [0; 16]; - for (byte, pair) in bytes.iter_mut().zip(value.as_bytes().as_chunks::<2>().0) { - let pair = std::str::from_utf8(pair).map_err(|_| invalid())?; - *byte = u8::from_str_radix(pair, 16).map_err(|_| invalid())?; + let digit = |digit: u8| { + char::from(digit) + .to_digit(16) + .and_then(|digit| u8::try_from(digit).ok()) + .ok_or_else(invalid) + }; + for (byte, [high, low]) in bytes.iter_mut().zip(value.as_bytes().as_chunks().0) { + *byte = digit(*high)? << 4 | digit(*low)?; } Self::from_bytes(bytes).ok_or_else(invalid) } diff --git a/crates/common/src/protocol/challenge/mod.rs b/crates/common/src/protocol/challenge/mod.rs index bb04f0b82..1a94f7564 100644 --- a/crates/common/src/protocol/challenge/mod.rs +++ b/crates/common/src/protocol/challenge/mod.rs @@ -34,11 +34,15 @@ use super::{ claims::Acr, - oauth::{ErrorDescription, Scopes}, + oauth::{ErrorDescription, InvalidDescription, Scopes}, step_up::StepUpRequirement, }; use serde::{Deserialize, Serialize}; -use std::{fmt, str::FromStr}; +use std::{ + fmt, + num::ParseIntError, + str::{FromStr, Utf8Error}, +}; use thiserror::Error; use url::Url; @@ -101,6 +105,9 @@ pub enum ChallengeError { /// The header breaks the RFC 9110 §11 challenge grammar. #[error("WWW-Authenticate is malformed at byte {0}")] Syntax(usize), + /// A quoted string starting at this byte is not UTF-8. + #[error("WWW-Authenticate is malformed at byte {0}")] + NotUtf8(usize, #[source] Utf8Error), /// No challenge uses the `Bearer` scheme. #[error("WWW-Authenticate has no Bearer challenge")] NotBearer, @@ -110,6 +117,15 @@ pub enum ChallengeError { /// A known parameter has an invalid value. #[error("Bearer challenge has an invalid {0}")] InvalidValue(&'static str), + /// The `error_description` is not printable ASCII without `"` or `\`. + #[error("Bearer challenge has an invalid error_description")] + InvalidErrorDescription(#[source] InvalidDescription), + /// The `max_age` is not a number of seconds. + #[error("Bearer challenge has an invalid max_age")] + InvalidMaxAge(#[source] ParseIntError), + /// The `resource_metadata` is not a URL. + #[error("Bearer challenge has an invalid resource_metadata")] + InvalidResourceMetadata(#[source] url::ParseError), } impl BearerChallenge { @@ -175,7 +191,7 @@ impl BearerChallenge { challenge.error_description = Some( value .parse() - .map_err(|_| ChallengeError::InvalidValue("error_description"))?, + .map_err(ChallengeError::InvalidErrorDescription)?, ); } // RFC 6750 §3: scope tokens separated by single spaces. @@ -193,17 +209,14 @@ impl BearerChallenge { // knows, as auth picks it (OIDC Core §3.1.2.1). "acr_values" => challenge.step_up.acr = Acr::select(&value), "max_age" => { - challenge.step_up.max_age = Some( - value - .parse() - .map_err(|_| ChallengeError::InvalidValue("max_age"))?, - ); + challenge.step_up.max_age = + Some(value.parse().map_err(ChallengeError::InvalidMaxAge)?); } "resource_metadata" => { challenge.resource_metadata = Some( value .parse() - .map_err(|_| ChallengeError::InvalidValue("resource_metadata"))?, + .map_err(ChallengeError::InvalidResourceMetadata)?, ); } _ => {} @@ -422,7 +435,8 @@ impl<'a> Parser<'a> { match self.peek() { Some(b'"') => { self.position += 1; - return String::from_utf8(value).map_err(|_| ChallengeError::Syntax(start)); + return String::from_utf8(value) + .map_err(|error| ChallengeError::NotUtf8(start, error.utf8_error())); } Some(b'\\') => { self.position += 1; diff --git a/crates/common/src/protocol/challenge/tests.rs b/crates/common/src/protocol/challenge/tests.rs index 67382dd27..f0b299917 100644 --- a/crates/common/src/protocol/challenge/tests.rs +++ b/crates/common/src/protocol/challenge/tests.rs @@ -53,11 +53,11 @@ fn rejects_invalid_headers() { ), ( "Bearer max_age=soon", - ChallengeError::InvalidValue("max_age"), + ChallengeError::InvalidMaxAge("soon".parse::().expect_err("not a number")), ), ( "Bearer error_description=\"say \\\"hi\\\"\"", - ChallengeError::InvalidValue("error_description"), + ChallengeError::InvalidErrorDescription(InvalidDescription), ), ] { assert_eq!(header.parse::(), Err(expected), "{header}"); diff --git a/crates/crypto/src/jws.rs b/crates/crypto/src/jws.rs index b9de5e433..f8c4385c9 100644 --- a/crates/crypto/src/jws.rs +++ b/crates/crypto/src/jws.rs @@ -35,9 +35,9 @@ use thiserror::Error; const EXPONENT: [u8; 3] = [1, 0, 1]; /// Why a compact token cannot be split, as a sentence for the caller's error. -#[derive(Clone, Copy, Debug, Error, PartialEq, Eq)] +#[derive(Clone, Debug, Error, PartialEq, Eq)] #[error("{0}")] -pub struct Malformed(pub &'static str); +pub struct Malformed(pub &'static str, #[source] pub Option); /// A compact JWS split into its three segments, with only its header decoded. /// The caller checks the header first, then decodes the rest, so a header that @@ -79,7 +79,7 @@ impl<'a> Split<'a> { fn decode(segment: &str) -> Result, Malformed> { URL_SAFE_NO_PAD .decode(segment) - .map_err(|_| Malformed("a segment is not base64url")) + .map_err(|error| Malformed("a segment is not base64url", Some(error))) } /// A compact JWS (RFC 7515 §7.1) split into its decoded parts. Nothing is @@ -105,7 +105,7 @@ impl<'a> Compact<'a> { /// that is not unpadded base64url. pub fn split(token: &'a str) -> Result, Malformed> { if token.len() > MAX_TOKEN_BYTES { - return Err(Malformed("the token exceeds 16 KiB")); + return Err(Malformed("the token exceeds 16 KiB", None)); } let mut segments = token.split('.'); let (Some(header), Some(payload), Some(signature), None) = ( @@ -114,7 +114,7 @@ impl<'a> Compact<'a> { segments.next(), segments.next(), ) else { - return Err(Malformed("the token is not three segments")); + return Err(Malformed("the token is not three segments", None)); }; Ok(Split { header: decode(header)?, @@ -248,6 +248,10 @@ impl Rs256VerifyingKey { /// # Errors /// [`VerifyError::Unusable`] for a key with a [`KeyDefect`], whatever the /// signature; [`VerifyError::BadSignature`] when the signature does not verify. + #[expect( + clippy::map_err_ignore, + reason = "The provider's `Unspecified` carries nothing, by design" + )] pub fn verify(&self, signing_input: &str, signature: &[u8]) -> Result<(), VerifyError> { let key = self .parsed diff --git a/crates/crypto/src/lib.rs b/crates/crypto/src/lib.rs index a00607eb0..ed0cadd15 100644 --- a/crates/crypto/src/lib.rs +++ b/crates/crypto/src/lib.rs @@ -23,6 +23,7 @@ use aws_lc_rs::{ }; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use secrecy::{ExposeSecret, SecretBox, SecretString, zeroize::Zeroizing}; +use sourceorigin_common::protocol::jwt::InvalidKeyId; use std::fmt; use thiserror::Error; @@ -61,7 +62,10 @@ pub enum CryptoError { UnusableKey(#[source] KeyDefect), /// The key identifier cannot safely appear in JWT headers. #[error("signing key ID must contain 1 to 128 characters without whitespace")] - KeyId, + KeyId(#[source] InvalidKeyId), + /// A token's compact framing is malformed. + #[error("JWT framing is invalid")] + MalformedToken(#[source] Malformed), /// A JWT segment contains malformed JSON. #[error("invalid JWT JSON")] Json(#[from] serde_json::Error), @@ -98,12 +102,18 @@ pub enum CryptoError { /// A verifier key is malformed, not Ed25519, or has the wrong key ID. #[error("note verifier key must be ++")] NoteVerifierKey, + /// A verifier key's base64 is malformed. + #[error("note verifier key is not valid base64")] + NoteVerifierKeyEncoding(#[source] base64::DecodeError), /// Note text does not end with a newline, or holds another control character. #[error("note text must end with a newline and contain no other control characters")] NoteText, /// A note has no signature block, or a malformed signature line. #[error("signed note is malformed")] NoteFormat, + /// A signature line's base64 is malformed. + #[error("signed note's signature is not valid base64")] + NoteSignatureEncoding(#[source] base64::DecodeError), /// A signature by a known key does not verify. #[error("note signature is invalid")] NoteSignature, @@ -153,6 +163,10 @@ impl Secret { /// Rejects invalid encoding and lengths other than 32 bytes. pub fn parse(value: &str) -> Result { let bytes = Zeroizing::new(URL_SAFE_NO_PAD.decode(value)?); + #[expect( + clippy::map_err_ignore, + reason = "`TryFromSliceError` carries nothing beyond the length mismatch `SecretLength` names" + )] let bytes: &[u8; SECRET_BYTES] = bytes .as_slice() .try_into() diff --git a/crates/crypto/src/note.rs b/crates/crypto/src/note.rs index 6970c094b..ec970aa2b 100644 --- a/crates/crypto/src/note.rs +++ b/crates/crypto/src/note.rs @@ -48,8 +48,14 @@ impl NoteKey { // `from_str_radix` never sees the sign it would otherwise accept. let mut seed = Zeroizing::new([0; SEED_BYTES]); for (index, byte) in seed.iter_mut().enumerate() { - *byte = u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16) - .map_err(|_| CryptoError::NoteKeySeed)?; + #[expect( + clippy::map_err_ignore, + reason = "The seed was checked to be hex digits above, so this cannot fail" + )] + { + *byte = u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16) + .map_err(|_| CryptoError::NoteKeySeed)?; + } } Self::from_seed(name, &seed) } @@ -65,6 +71,10 @@ impl NoteKey { /// Builds the key and its verifier from a 32-byte seed. fn from_seed(name: &str, seed: &[u8; SEED_BYTES]) -> Result { let key = Ed25519KeyPair::from_seed_unchecked(seed)?; + #[expect( + clippy::map_err_ignore, + reason = "`TryFromSliceError` carries nothing, and an Ed25519 public key always has 32 bytes" + )] let public = key .public_key() .as_ref() @@ -187,10 +197,14 @@ impl FromStr for NoteVerifier { }; let key = STANDARD .decode(key) - .map_err(|_| CryptoError::NoteVerifierKey)?; + .map_err(CryptoError::NoteVerifierKeyEncoding)?; let Some((&ED25519_ID, public)) = key.split_first() else { return Err(CryptoError::NoteVerifierKey); }; + #[expect( + clippy::map_err_ignore, + reason = "`TryFromSliceError` carries nothing beyond the length mismatch `NoteVerifierKey` names" + )] let public = public .try_into() .map_err(|_| CryptoError::NoteVerifierKey)?; @@ -286,11 +300,15 @@ impl NoteVerifiers { .ok_or(CryptoError::NoteFormat)?; let signature = STANDARD .decode(signature) - .map_err(|_| CryptoError::NoteFormat)?; + .map_err(CryptoError::NoteSignatureEncoding)?; if signature.len() <= KEY_ID_BYTES { return Err(CryptoError::NoteFormat); } let (id, signature) = signature.split_at(KEY_ID_BYTES); + #[expect( + clippy::map_err_ignore, + reason = "`TryFromSliceError` carries nothing beyond the length mismatch `NoteFormat` names" + )] let id = u32::from_be_bytes(id.try_into().map_err(|_| CryptoError::NoteFormat)?); for verifier in self.0.iter().filter(|key| key.name == name && key.id == id) { if !verifier.verifies(text, signature) { diff --git a/crates/crypto/src/sealing/mod.rs b/crates/crypto/src/sealing/mod.rs index 5a1ddf62b..4a13f6003 100644 --- a/crates/crypto/src/sealing/mod.rs +++ b/crates/crypto/src/sealing/mod.rs @@ -67,6 +67,10 @@ impl SealingKey { let nonce = Nonce::try_assume_unique_for_key(nonce)?; let mut opened = Zeroizing::new(rest.to_vec()); // A failed tag check says nothing more than this variant does. + #[expect( + clippy::map_err_ignore, + reason = "The provider's `Unspecified` carries nothing, by design" + )] let length = self .0 .open_in_place(nonce, Aad::from(aad), &mut opened) diff --git a/crates/crypto/src/signing/mod.rs b/crates/crypto/src/signing/mod.rs index a8a936c39..dbae64ada 100644 --- a/crates/crypto/src/signing/mod.rs +++ b/crates/crypto/src/signing/mod.rs @@ -54,10 +54,10 @@ struct Token<'a> { impl<'a> Token<'a> { /// Splits a bounded token into exactly three parts and parses its header. fn parse(token: &'a str) -> Result { - let split = Compact::split(token).map_err(|_| CryptoError::InvalidToken)?; + let split = Compact::split(token).map_err(CryptoError::MalformedToken)?; Ok(Self { header: serde_json::from_slice(split.header())?, - compact: split.decode().map_err(|_| CryptoError::InvalidToken)?, + compact: split.decode().map_err(CryptoError::MalformedToken)?, }) } } @@ -78,7 +78,7 @@ impl PublicKey { /// Rejects malformed keys, keys every SDK would refuse to verify with, and /// invalid key identifiers. pub fn from_jwk(jwk: Jwk) -> Result { - jwk.kid.parse::().map_err(|_| CryptoError::KeyId)?; + jwk.kid.parse::().map_err(CryptoError::KeyId)?; let key = match jwk.kty { KeyType::Rsa => Rs256VerifyingKey::new( &URL_SAFE_NO_PAD.decode(&jwk.n)?, diff --git a/crates/telemetry/src/lib.rs b/crates/telemetry/src/lib.rs index 95ee59da1..0e1eba440 100644 --- a/crates/telemetry/src/lib.rs +++ b/crates/telemetry/src/lib.rs @@ -102,7 +102,7 @@ pub enum TelemetryError { Panicked(#[from] tokio::sync::oneshot::error::RecvError), /// The flush did not finish in time, so what was still pending is lost. #[error("telemetry flush did not finish within {0:?}")] - TimedOut(Duration), + TimedOut(Duration, #[source] tokio::time::error::Elapsed), } /// A service's installed telemetry. Spans always get trace IDs; exporters exist @@ -205,7 +205,7 @@ impl Telemetry { }); let flushed = tokio::time::timeout(within, result) .await - .map_err(|_| TelemetryError::TimedOut(within))?; + .map_err(|source| TelemetryError::TimedOut(within, source))?; Ok(flushed??) }