1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-07-31 09:24:31 +03:00

Convert many match/if expressions to let-else

This commit is contained in:
Quentin Gliech
2023-02-01 10:15:35 +01:00
parent d9649975b9
commit 792d3c793b
22 changed files with 51 additions and 107 deletions

View File

@ -560,8 +560,7 @@ mod tests {
// Signed with client_secret = "client-secret" // Signed with client_secret = "client-secret"
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjbGllbnQtaWQiLCJzdWIiOiJjbGllbnQtaWQiLCJhdWQiOiJodHRwczovL2V4YW1wbGUuY29tL29hdXRoMi9pbnRyb3NwZWN0IiwianRpIjoiYWFiYmNjIiwiZXhwIjoxNTE2MjM5MzIyLCJpYXQiOjE1MTYyMzkwMjJ9.XTaACG_Rww0GPecSZvkbem-AczNy9LLNBueCLCiQajU"; let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjbGllbnQtaWQiLCJzdWIiOiJjbGllbnQtaWQiLCJhdWQiOiJodHRwczovL2V4YW1wbGUuY29tL29hdXRoMi9pbnRyb3NwZWN0IiwianRpIjoiYWFiYmNjIiwiZXhwIjoxNTE2MjM5MzIyLCJpYXQiOjE1MTYyMzkwMjJ9.XTaACG_Rww0GPecSZvkbem-AczNy9LLNBueCLCiQajU";
let body = Bytes::from(format!( let body = Bytes::from(format!(
"client_assertion_type={}&client_assertion={}&foo=bar", "client_assertion_type={JWT_BEARER_CLIENT_ASSERTION}&client_assertion={jwt}&foo=bar",
JWT_BEARER_CLIENT_ASSERTION, jwt,
)); ));
let req = Request::builder() let req = Request::builder()
@ -578,10 +577,7 @@ mod tests {
.unwrap(); .unwrap();
assert_eq!(authz.form, Some(serde_json::json!({"foo": "bar"}))); assert_eq!(authz.form, Some(serde_json::json!({"foo": "bar"})));
let (client_id, jwt) = let Credentials::ClientAssertionJwtBearer { client_id, jwt } = authz.credentials else {
if let Credentials::ClientAssertionJwtBearer { client_id, jwt } = authz.credentials {
(client_id, jwt)
} else {
panic!("expected a JWT client_assertion"); panic!("expected a JWT client_assertion");
}; };

View File

@ -47,9 +47,7 @@ impl SessionInfo {
&self, &self,
repo: &mut impl RepositoryAccess<Error = E>, repo: &mut impl RepositoryAccess<Error = E>,
) -> Result<Option<BrowserSession>, E> { ) -> Result<Option<BrowserSession>, E> {
let session_id = if let Some(id) = self.current { let Some(session_id) = self.current else {
id
} else {
return Ok(None); return Ok(None);
}; };

View File

@ -89,9 +89,8 @@ impl<F: Send> UserAuthorization<F> {
repo: &mut impl RepositoryAccess<Error = E>, repo: &mut impl RepositoryAccess<Error = E>,
clock: &impl Clock, clock: &impl Clock,
) -> Result<(Session, F), AuthorizationVerificationError<E>> { ) -> Result<(Session, F), AuthorizationVerificationError<E>> {
let form = match self.form { let Some(form) = self.form else {
Some(f) => f, return Err(AuthorizationVerificationError::MissingForm);
None => return Err(AuthorizationVerificationError::MissingForm),
}; };
let (token, session) = self.access_token.fetch(repo).await?; let (token, session) = self.access_token.fetch(repo).await?;

View File

@ -71,9 +71,7 @@ pub async fn get(
let maybe_session = session_info.load_session(&mut repo).await?; let maybe_session = session_info.load_session(&mut repo).await?;
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
// If there is no session, redirect to the login or register screen // If there is no session, redirect to the login or register screen
let url = match params.action { let url = match params.action {
Some(CompatLoginSsoAction::Register) => { Some(CompatLoginSsoAction::Register) => {
@ -140,9 +138,7 @@ pub async fn post(
let maybe_session = session_info.load_session(&mut repo).await?; let maybe_session = session_info.load_session(&mut repo).await?;
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
// If there is no session, redirect to the login or register screen // If there is no session, redirect to the login or register screen
let url = match params.action { let url = match params.action {
Some(CompatLoginSsoAction::Register) => { Some(CompatLoginSsoAction::Register) => {

View File

@ -107,9 +107,7 @@ pub(crate) async fn get(
let callback_destination = CallbackDestination::try_from(&grant)?; let callback_destination = CallbackDestination::try_from(&grant)?;
let continue_grant = PostAuthAction::continue_grant(grant.id); let continue_grant = PostAuthAction::continue_grant(grant.id);
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
// If there is no session, redirect to the login screen, redirecting here after // If there is no session, redirect to the login screen, redirecting here after
// logout // logout
return Ok((cookie_jar, mas_router::Login::and_then(continue_grant).go()).into_response()); return Ok((cookie_jar, mas_router::Login::and_then(continue_grant).go()).into_response());

View File

@ -166,9 +166,7 @@ pub(crate) async fn post(
.ok_or(RouteError::GrantNotFound)?; .ok_or(RouteError::GrantNotFound)?;
let next = PostAuthAction::continue_grant(grant_id); let next = PostAuthAction::continue_grant(grant_id);
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
let login = mas_router::Login::and_then(next); let login = mas_router::Login::and_then(next);
return Ok((cookie_jar, login.go()).into_response()); return Ok((cookie_jar, login.go()).into_response());
}; };

View File

@ -154,9 +154,7 @@ pub(crate) async fn post(
.verify(&http_client_factory, &encrypter, method, &client) .verify(&http_client_factory, &encrypter, method, &client)
.await?; .await?;
let form = if let Some(form) = client_authorization.form { let Some(form) = client_authorization.form else {
form
} else {
return Err(RouteError::BadRequest); return Err(RouteError::BadRequest);
}; };

View File

@ -49,9 +49,7 @@ pub(crate) async fn get(
let maybe_session = session_info.load_session(&mut repo).await?; let maybe_session = session_info.load_session(&mut repo).await?;
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
let login = mas_router::Login::default(); let login = mas_router::Login::default();
return Ok((cookie_jar, login.go()).into_response()); return Ok((cookie_jar, login.go()).into_response());
}; };
@ -80,9 +78,7 @@ pub(crate) async fn post(
let maybe_session = session_info.load_session(&mut repo).await?; let maybe_session = session_info.load_session(&mut repo).await?;
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
let login = mas_router::Login::default(); let login = mas_router::Login::default();
return Ok((cookie_jar, login.go()).into_response()); return Ok((cookie_jar, login.go()).into_response());
}; };

View File

@ -136,9 +136,7 @@ pub(crate) async fn post(
let maybe_session = session_info.load_session(&mut repo).await?; let maybe_session = session_info.load_session(&mut repo).await?;
let mut session = if let Some(session) = maybe_session { let Some(mut session) = maybe_session else {
session
} else {
let login = mas_router::Login::default(); let login = mas_router::Login::default();
return Ok((cookie_jar, login.go()).into_response()); return Ok((cookie_jar, login.go()).into_response());
}; };

View File

@ -56,9 +56,7 @@ pub(crate) async fn get(
let maybe_session = session_info.load_session(&mut repo).await?; let maybe_session = session_info.load_session(&mut repo).await?;
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
let login = mas_router::Login::default(); let login = mas_router::Login::default();
return Ok((cookie_jar, login.go()).into_response()); return Ok((cookie_jar, login.go()).into_response());
}; };
@ -104,9 +102,7 @@ pub(crate) async fn post(
let maybe_session = session_info.load_session(&mut repo).await?; let maybe_session = session_info.load_session(&mut repo).await?;
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
let login = mas_router::Login::default(); let login = mas_router::Login::default();
return Ok((cookie_jar, login.go()).into_response()); return Ok((cookie_jar, login.go()).into_response());
}; };

View File

@ -42,9 +42,7 @@ pub(crate) async fn get(
let maybe_session = session_info.load_session(&mut repo).await?; let maybe_session = session_info.load_session(&mut repo).await?;
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
let login = mas_router::Login::default(); let login = mas_router::Login::default();
return Ok((cookie_jar, login.go()).into_response()); return Ok((cookie_jar, login.go()).into_response());
}; };

View File

@ -97,9 +97,7 @@ pub(crate) async fn post(
let maybe_session = session_info.load_session(&mut repo).await?; let maybe_session = session_info.load_session(&mut repo).await?;
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
let login = mas_router::Login::and_then(mas_router::PostAuthAction::ChangePassword); let login = mas_router::Login::and_then(mas_router::PostAuthAction::ChangePassword);
return Ok((cookie_jar, login.go()).into_response()); return Ok((cookie_jar, login.go()).into_response());
}; };

View File

@ -54,9 +54,7 @@ pub(crate) async fn get(
let maybe_session = session_info.load_session(&mut repo).await?; let maybe_session = session_info.load_session(&mut repo).await?;
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
// If there is no session, redirect to the login screen, keeping the // If there is no session, redirect to the login screen, keeping the
// PostAuthAction // PostAuthAction
let login = mas_router::Login::from(query.post_auth_action); let login = mas_router::Login::from(query.post_auth_action);
@ -93,9 +91,7 @@ pub(crate) async fn post(
let maybe_session = session_info.load_session(&mut repo).await?; let maybe_session = session_info.load_session(&mut repo).await?;
let session = if let Some(session) = maybe_session { let Some(session) = maybe_session else {
session
} else {
// If there is no session, redirect to the login screen, keeping the // If there is no session, redirect to the login screen, keeping the
// PostAuthAction // PostAuthAction
let login = mas_router::Login::from(query.post_auth_action); let login = mas_router::Login::from(query.post_auth_action);

View File

@ -111,9 +111,7 @@ use serde_with::{{DeserializeFromStr, SerializeDisplay}};"#,
)?; )?;
for section in &self.sections { for section in &self.sections {
let list = if let Some(list) = self.items.get(section.key) { let Some(list) = self.items.get(section.key) else {
list
} else {
continue; continue;
}; };

View File

@ -351,9 +351,8 @@ mod ec_impls {
{ {
fn from(key: &SecretKey<C>) -> Self { fn from(key: &SecretKey<C>) -> Self {
let point = key.public_key().to_encoded_point(false); let point = key.public_key().to_encoded_point(false);
let (x, y) = match point.coordinates() { let Coordinates::Uncompressed { x, y } = point.coordinates() else {
Coordinates::Uncompressed { x, y } => (x, y), unreachable!()
_ => unreachable!(),
}; };
let d = key.to_be_bytes(); let d = key.to_be_bytes();
EcPrivateParameters { EcPrivateParameters {

View File

@ -306,9 +306,8 @@ mod ec_impls {
{ {
fn from(key: &PublicKey<C>) -> Self { fn from(key: &PublicKey<C>) -> Self {
let point = key.to_encoded_point(false); let point = key.to_encoded_point(false);
let (x, y) = match point.coordinates() { let Coordinates::Uncompressed { x, y } = point.coordinates() else {
Coordinates::Uncompressed { x, y } => (x, y), unreachable!()
_ => unreachable!(),
}; };
EcPublicParameters { EcPublicParameters {
crv: C::CRV, crv: C::CRV,

View File

@ -235,17 +235,13 @@ impl<'a, T> Jwt<'a, T> {
let candidates = constraints.filter(&**jwks); let candidates = constraints.filter(&**jwks);
for candidate in candidates { for candidate in candidates {
let key = match crate::jwa::AsymmetricVerifyingKey::from_jwk_and_alg( let Ok(key) = crate::jwa::AsymmetricVerifyingKey::from_jwk_and_alg(
candidate.params(), candidate.params(),
self.header().alg(), self.header().alg(),
) { ) else { continue };
Ok(v) => v,
Err(_) => continue,
};
match self.verify(&key) { if self.verify(&key).is_ok() {
Ok(_) => return Ok(()), return Ok(());
Err(_) => continue,
} }
} }

View File

@ -74,14 +74,11 @@ impl ProxyProtocolV1Info {
} }
// Let's check in the first 108 bytes if we find a CRLF // Let's check in the first 108 bytes if we find a CRLF
let crlf = if let Some(crlf) = buf let Some(crlf) = buf
.as_ref() .as_ref()
.windows(2) .windows(2)
.take(108) .take(108)
.position(|needle| needle == [0x0D, 0x0A]) .position(|needle| needle == [0x0D, 0x0A]) else {
{
crlf
} else {
// If not, it might be because we don't have enough bytes // If not, it might be because we don't have enough bytes
return if buf.remaining() < 108 { return if buf.remaining() < 108 {
Err(E::NotEnoughBytes) Err(E::NotEnoughBytes)

View File

@ -255,7 +255,7 @@ where
// Then look for connections to accept // Then look for connections to accept
res = accept_all.next(), if !accept_all.is_empty() => { res = accept_all.next(), if !accept_all.is_empty() => {
// SAFETY: We shouldn't reach this branch if the unordered future set is empty // SAFETY: We shouldn't reach this branch if the unordered future set is empty
let res = if let Some(res) = res { res } else { unreachable!() }; let Some(res) = res else { unreachable!() };
// Spawn the connection in the set, so we don't have to wait for the handshake to // Spawn the connection in the set, so we don't have to wait for the handshake to
// accept the next connection. This allows us to keep track of active connections // accept the next connection. This allows us to keep track of active connections

View File

@ -59,9 +59,8 @@ impl<T> Localized<T> {
where where
T: DeserializeOwned, T: DeserializeOwned,
{ {
let map = match map.remove(field_name) { let Some(map) = map.remove(field_name) else {
Some(map) => map, return Ok(None);
None => return Ok(None),
}; };
let mut non_localized = None; let mut non_localized = None;

View File

@ -190,12 +190,8 @@ pub fn verify_id_token<'a>(
// Subject identifier must be present. // Subject identifier must be present.
let sub = claims::SUB.extract_required(&mut claims)?; let sub = claims::SUB.extract_required(&mut claims)?;
// No more checks if there is no previous ID token. // More checks if there is a previous ID token.
let auth_id_token = match auth_id_token { if let Some(auth_id_token) = auth_id_token {
Some(id_token) => id_token,
None => return Ok(id_token),
};
let mut auth_claims = auth_id_token.payload().clone(); let mut auth_claims = auth_id_token.payload().clone();
// Subject identifier must always be the same. // Subject identifier must always be the same.
@ -212,6 +208,7 @@ pub fn verify_id_token<'a>(
return Err(IdTokenError::WrongAuthTime); return Err(IdTokenError::WrongAuthTime);
} }
} }
}
Ok(id_token) Ok(id_token)
} }

View File

@ -28,14 +28,8 @@ where
} }
pub fn http_all_error_status_codes() -> impl RangeBounds<StatusCode> { pub fn http_all_error_status_codes() -> impl RangeBounds<StatusCode> {
let client_errors_start_code = match StatusCode::from_u16(400) { let Ok(client_errors_start_code) = StatusCode::from_u16(400) else { unreachable!() };
Ok(code) => code, let Ok(server_errors_end_code) = StatusCode::from_u16(599) else { unreachable!() };
Err(_) => unreachable!(),
};
let server_errors_end_code = match StatusCode::from_u16(599) {
Ok(code) => code,
Err(_) => unreachable!(),
};
client_errors_start_code..=server_errors_end_code client_errors_start_code..=server_errors_end_code
} }