Skip to content
Draft
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
11 changes: 8 additions & 3 deletions apps/auth-service/src/admin/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -312,6 +316,7 @@ impl From<AdminError> for ApiError {
| AdminError::InvalidInvitationEmail(_)
| AdminError::InvitationUnsendable(_)
| AdminError::InvalidHandoff
| AdminError::InvalidHandoffReturn(_)
| AdminError::InvalidSubject
| AdminError::InvalidBody
| AdminError::NoRecipients
Expand Down
10 changes: 9 additions & 1 deletion apps/auth-service/src/admin/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()?;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -366,6 +374,6 @@ impl DashboardSignIn {

/// The dashboard path `value` names, which cannot leave the dashboard's origin.
fn path(value: &str) -> Result<ReturnTo, AdminError> {
ReturnTo::parse(Some(value)).map_err(|_| AdminError::InvalidHandoff)
ReturnTo::parse(Some(value)).map_err(AdminError::InvalidHandoffReturn)
}
}
8 changes: 5 additions & 3 deletions apps/auth-service/src/audit/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/src/clients/owned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ impl ClientSettings {
id: ClientId,
kind: ClientKind,
) -> Result<ClientRegistration, InvalidSetting> {
#[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()
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/src/deletion/export/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>| {
(sender.send(Ok(chunk.into())).await).map_err(|_| ExportError::Closed)
};
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/src/deliveries/email/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,10 @@ impl<M: Mailer> EmailSender<M> {
};
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()
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/src/deliveries/outbound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,10 @@ impl OutboundClient {
/// that is not public. Names are checked when they resolve.
fn check(&self, destination: &str) -> Result<Url, DeliveryError> {
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),
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/src/emails/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,10 @@ impl AccountService {
request: RequestContext,
) -> Result<Verified, AccountError> {
// 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();
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/federation/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ impl From<FederationError> 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,
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/federation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/keys/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<KeyId, KeyError> {
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()
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/src/passkey/confirmation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ impl PasskeyApplication {
owner: &Owner,
assertion: &str,
) -> Result<AdminProof, ApiError> {
#[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();
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/src/pictures/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,10 @@ impl PictureApplication {
/// that does not parse names none.
async fn serve(State(app): State<Self>, Path(id): Path<String>) -> Result<Response, ApiError> {
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
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/src/recovery/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<OpenRecovery, AccountError> {
#[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();
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/src/security/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,10 @@ impl<const MAX_AGE: u32> Confirmed<MAX_AGE> {

/// 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
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/src/web/admin/announcements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ pub(super) async fn send(cx: &Cx, form: Option<Form<SendAnnouncement>>) -> Resul
let admin = App::confirmed(cx).await?;
let service = &App::of(cx).service;
let id = *path_param::<Announcement>(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);
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/web/admin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1310,7 +1310,7 @@ async fn sign_in(cx: &Cx) -> Result<Response> {
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 =>
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/src/web/settings/notifications.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<NotificationId, Failure> {
path_param::<Id>(cx).parse().map_err(|_| Failure::Missing)
}
Expand Down
4 changes: 4 additions & 0 deletions crates/auth-sdk/src/axum/login/extract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<P: AuthenticationPolicy>(&self) -> Result<(), StepUp> {
let authentication = &self.claims().authentication;
TokenError::require_authentication(
Expand Down
12 changes: 6 additions & 6 deletions crates/auth-sdk/src/issuer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<url::ParseError>),
/// The metadata endpoint could not be reached.
#[error(transparent)]
Network(#[from] NetworkError),
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -212,16 +212,16 @@ impl Issuer {

/// Where `issuer` publishes its metadata (OIDC Discovery 1.0 §4.1).
fn metadata_url(issuer: &str) -> Result<Url, DiscoveryError> {
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`.
Expand Down
11 changes: 5 additions & 6 deletions crates/auth-sdk/src/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -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<Self, TokenError> {
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)?,
})
}

Expand Down
18 changes: 11 additions & 7 deletions crates/auth-sdk/src/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand All @@ -18,6 +18,7 @@ use sourceorigin_common::{
step_up::StepUpRequirement,
},
};
use sourceorigin_crypto::Malformed;
use std::marker::PhantomData;
use thiserror::Error;

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -218,7 +222,7 @@ impl TokenError {
/// The account `sub` names.
pub(crate) fn account(sub: &str) -> Result<UserId, Self> {
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
Expand Down
Loading
Loading