Compare commits

..
Author SHA1 Message Date
Renovate Bot f5510aaddf chore(deps): update rust crate rustls to v0.23.48 2026-12-04 05:02:57 +00:00
10 changed files with 791 additions and 280 deletions

No files matched your search

Generated
+566 -110
View File
File diff suppressed because it is too large. Load diff
+12 -2
View File
@@ -166,6 +166,15 @@ features = [
"form", "form",
] ]
# Needed for as long as openidconnect is on an outdated reqwest
[workspace.dependencies.reqwest_0_12]
package = "reqwest"
version = "0.12"
default-features = false
features = [
"rustls-tls-native-roots-no-provider",
]
[workspace.dependencies.serde] [workspace.dependencies.serde]
version = "1.0.229" version = "1.0.229"
default-features = false default-features = false
@@ -413,9 +422,10 @@ default-features = false
version = "0.11.0" version = "0.11.0"
default-features = false default-features = false
[workspace.dependencies.openid] [workspace.dependencies.openidconnect]
version = "0.26.0" version = "4.1.0"
default-features = false default-features = false
features = ["reqwest"]
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring # optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
[workspace.dependencies.opentelemetry] [workspace.dependencies.opentelemetry]
+1 -1
View File
@@ -117,7 +117,7 @@ prometheus.workspace = true
lock_api.workspace = true lock_api.workspace = true
hyper-util.workspace = true hyper-util.workspace = true
resolvematrix.workspace = true resolvematrix.workspace = true
openid.workspace = true openidconnect.workspace = true
libmimalloc-sys.optional = true libmimalloc-sys.optional = true
libmimalloc-sys.workspace = true libmimalloc-sys.workspace = true
mimalloc.optional = true mimalloc.optional = true
+18 -5
View File
@@ -23,6 +23,7 @@ use figment::providers::{Env, Format, Toml};
pub use figment::{Figment, value::Value as FigmentValue}; pub use figment::{Figment, value::Value as FigmentValue};
use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter}; use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter};
use lettre::message::Mailbox; use lettre::message::Mailbox;
use openidconnect::{Audience, ClientId, ClientSecret, Scope};
use regex::RegexSet; use regex::RegexSet;
use ruma::{ use ruma::{
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId,
@@ -2801,15 +2802,15 @@ pub struct OidcConfig {
/// automatically fetch the identity provider's metadata from this URL. /// automatically fetch the identity provider's metadata from this URL.
/// Generally you should set this to the base domain your identity provider /// Generally you should set this to the base domain your identity provider
/// runs on. /// runs on.
pub discovery_url: Url, pub discovery_url: String,
/// The OAuth client ID for Continuwuity to use when communicating with the /// The OAuth client ID for Continuwuity to use when communicating with the
/// identity provider. /// identity provider.
pub client_id: String, pub client_id: ClientId,
/// The OAuth client secret for Continuwuity to use when communicating with /// The OAuth client secret for Continuwuity to use when communicating with
/// the identity provider. /// the identity provider.
pub client_secret: Option<String>, pub client_secret: Option<ClientSecret>,
/// A path to a file which Continuwuity will read the client secret from. /// A path to a file which Continuwuity will read the client secret from.
/// If this option is set, it will override `client_secret`. /// If this option is set, it will override `client_secret`.
@@ -2825,7 +2826,19 @@ pub struct OidcConfig {
/// ///
/// default: ["profile"] /// default: ["profile"]
#[serde(default = "default_additional_scopes")] #[serde(default = "default_additional_scopes")]
pub additional_scopes: Vec<String>, pub additional_scopes: Vec<Scope>,
/// Additional trusted audiences that Continuwuity will accept in the `aud`
/// claim of the OIDC token returned by the IDP. If your identity
/// provider includes other values in the `aud` claim in addition to the
/// client ID, they must be listed here for Continuwuity to accept them.
///
/// Most deployments will not need to set this, because most identity
/// providers only include the client ID in the `aud` claim by default.
///
/// default: []
#[serde(default)]
pub additional_trusted_audiences: BTreeSet<Audience>,
/// The name of the identity provider. If this is set, the login page's /// The name of the identity provider. If this is set, the login page's
/// button reads "Continue with <name>" instead of just "Continue". /// button reads "Continue with <name>" instead of just "Continue".
@@ -3431,7 +3444,7 @@ fn default_unauthenticated_request_ratelimit<K: Hash + Eq + Clone>() -> PerMinut
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap())) PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
} }
fn default_additional_scopes() -> Vec<String> { vec!["profile".to_owned()] } fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] }
// NOTE: This must be declared *after* every config struct in this file. The // NOTE: This must be declared *after* every config struct in this file. The
// example config generator writes sections in macro expansion order, and the // example config generator writes sections in macro expansion order, and the
+7 -1
View File
@@ -130,7 +130,10 @@ yansi.workspace = true
lettre.workspace = true lettre.workspace = true
resolvematrix.workspace = true resolvematrix.workspace = true
serde_urlencoded.workspace = true serde_urlencoded.workspace = true
openid.workspace = true openidconnect.workspace = true
# We use this to set TLS backend features on the outdated reqwest bundled by openidconnect,
# which is necessary to call `danger_accept_invalid_certs`.
reqwest_0_12.workspace = true
rand.workspace = true rand.workspace = true
[target.'cfg(all(unix, target_os = "linux"))'.dependencies] [target.'cfg(all(unix, target_os = "linux"))'.dependencies]
@@ -140,6 +143,9 @@ sd-notify.optional = true
[lints] [lints]
workspace = true workspace = true
[package.metadata.cargo-shear]
ignored = ["reqwest_0_12"]
[dev-dependencies] [dev-dependencies]
opentelemetry.workspace = true opentelemetry.workspace = true
rustls = { workspace = true, features = ["ring"] } rustls = { workspace = true, features = ["ring"] }
+15
View File
@@ -44,3 +44,18 @@ impl reqwest::dns::Resolve for DnsResolver {
}) })
} }
} }
// openidconnect is weird and vendors reqwest (?), therefore we have to
// completely re-implement Resolve with different types
impl openidconnect::reqwest::dns::Resolve for DnsResolver {
fn resolve(&self, name: openidconnect::reqwest::dns::Name) -> Resolving {
let resolver = self.resolver.clone();
Box::pin(async move {
let lookup = resolver.lookup_ip(name.as_str()).await?;
let addrs: Addrs = Box::new(SocketAddrs {
iter: lookup.iter().collect::<Vec<_>>().into_iter(),
});
Ok(addrs)
})
}
}
+163 -153
View File
@@ -1,19 +1,26 @@
use std::{ use std::{collections::HashMap, net::IpAddr, str::FromStr, sync::Arc, time::Duration};
collections::{HashMap, HashSet},
net::IpAddr,
str::FromStr,
sync::Arc,
};
use async_trait::async_trait; use async_trait::async_trait;
use conduwuit::{ use conduwuit::{
Result, SyncRwLock, Result, SyncRwLock,
config::{OidcConfig, OidcProfileKeyImportMode}, config::{OidcConfig, OidcProfileKeyImportMode},
debug, err, error, info, utils, warn, debug, err, error, info, warn,
}; };
use database::{Deserialized, Map}; use database::{Deserialized, Map};
use lettre::Address; use lettre::Address;
use openid::{Claims as _, Options, StandardClaims, Token}; use openidconnect::{
AdditionalClaims, AuthorizationCode, ClaimsVerificationError, ClientSecret, CsrfToken,
EmptyExtraTokenFields, EndpointMaybeSet, EndpointNotSet, EndpointSet, IdTokenClaims,
IdTokenFields, IssuerUrl, Nonce, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl,
SignatureVerificationError, StandardErrorResponse, StandardTokenResponse, TokenResponse,
core::{
CoreAuthDisplay, CoreAuthPrompt, CoreAuthenticationFlow, CoreErrorResponseType,
CoreGenderClaim, CoreJsonWebKey, CoreJweContentEncryptionAlgorithm,
CoreJwsSigningAlgorithm, CoreProviderMetadata, CoreRevocableToken,
CoreRevocationErrorResponse, CoreTokenIntrospectionResponse, CoreTokenType,
},
reqwest,
};
use ruma::{ use ruma::{
OwnedUserId, UserId, OwnedUserId, UserId,
api::client::profile::PropagateTo, api::client::profile::PropagateTo,
@@ -43,7 +50,6 @@ struct Data {
openidsubjectprofilefield_url: Arc<Map>, openidsubjectprofilefield_url: Arc<Map>,
} }
struct Services { struct Services {
client: Dep<client::Service>,
config: Dep<config::Service>, config: Dep<config::Service>,
globals: Dep<globals::Service>, globals: Dep<globals::Service>,
media: Dep<media::Service>, media: Dep<media::Service>,
@@ -52,61 +58,56 @@ struct Services {
} }
struct OidcClient { struct OidcClient {
client_secret: String,
config: OidcConfig, config: OidcConfig,
client: SetOnce<SyncRwLock<Arc<IdpClient>>>, client_secret: ClientSecret,
machine: SetOnce<SyncRwLock<Arc<OidcClientMachine>>>,
client: reqwest::Client,
} }
type IdpClient = openid::Client<openid::Discovered, Claims>; type OidcClientMachine = openidconnect::Client<
AllClaims,
CoreAuthDisplay,
CoreGenderClaim,
CoreJweContentEncryptionAlgorithm,
CoreJsonWebKey,
CoreAuthPrompt,
StandardErrorResponse<CoreErrorResponseType>,
StandardTokenResponse<
IdTokenFields<
AllClaims,
EmptyExtraTokenFields,
CoreGenderClaim,
CoreJweContentEncryptionAlgorithm,
CoreJwsSigningAlgorithm,
>,
CoreTokenType,
>,
CoreTokenIntrospectionResponse,
CoreRevocableToken,
CoreRevocationErrorResponse,
EndpointSet,
EndpointNotSet,
EndpointNotSet,
EndpointNotSet,
EndpointMaybeSet,
EndpointMaybeSet,
>;
pub type Claims = IdTokenClaims<AllClaims, CoreGenderClaim>;
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Claims { pub struct AllClaims {
#[serde(flatten)] #[serde(flatten)]
standard_claims: StandardClaims, pub claims: HashMap<String, Value>,
#[serde(flatten)]
other_claims: HashMap<String, Value>,
} }
impl Claims { impl AdditionalClaims for AllClaims {}
fn get(&self, key: &str) -> Option<&Value> { self.other_claims.get(key) }
}
macro_rules! standard {
($($field:ident: $type:ty),*$(,)?) => {
$(
fn $field(&self) -> $type {
self.standard_claims.$field()
}
)*
}
}
impl openid::Claims for Claims {
standard! {
userinfo: &openid::Userinfo,
c_hash: Option<&String>,
at_hash: Option<&String>,
iss: &Url,
sub: &str,
aud: &openid::SingleOrMultiple<String>,
exp: i64,
iat: i64,
auth_time: Option<i64>,
nonce: Option<&String>,
acr: Option<&String>,
amr: Option<&Vec<String>>,
azp: Option<&String>,
}
}
impl openid::CompactJson for Claims {}
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
pub struct PendingSession { pub struct PendingSession {
pkce_verifier: String, pkce_verifier: PkceCodeVerifier,
nonce: String, nonce: Nonce,
csrf_token: String, csrf_token: CsrfToken,
} }
pub enum SessionCompletionStatus { pub enum SessionCompletionStatus {
@@ -134,7 +135,6 @@ impl crate::Service for Service {
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> { fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
Ok(Arc::new(Self { Ok(Arc::new(Self {
services: Services { services: Services {
client: args.depend::<client::Service>("client"),
config: args.depend::<config::Service>("config"), config: args.depend::<config::Service>("config"),
globals: args.depend::<globals::Service>("globals"), globals: args.depend::<globals::Service>("globals"),
media: args.depend::<media::Service>("media"), media: args.depend::<media::Service>("media"),
@@ -146,21 +146,43 @@ impl crate::Service for Service {
openidsubject_localpart: args.db["openidsubject_localpart"].clone(), openidsubject_localpart: args.db["openidsubject_localpart"].clone(),
openidsubjectprofilefield_url: args.db["openidsubjectprofilefield_url"].clone(), openidsubjectprofilefield_url: args.db["openidsubjectprofilefield_url"].clone(),
}, },
client: args client: args.server.config.oauth.oidc.as_ref().map(|config| -> Result<OidcClient> {
.server Ok(OidcClient {
.config config: config.clone(),
.oauth client_secret: if let Some(client_secret_file) = &config.client_secret_file {
.oidc std::fs::read_to_string(client_secret_file)
.clone() .map(|client_secret| client_secret.trim().to_owned())
.map(Self::create_client) .map(ClientSecret::new)
.transpose()?, .map_err(|err| err!("Failed to read OIDC client secret file: {err}"))?
} else if let Some(client_secret) = &config.client_secret {
client_secret.clone()
} else {
// The config check function should cause an early exit before this happens
panic!("neither client secret or client secret file were set");
},
machine: SetOnce::new(),
// This isn't in the client service because it has to use the `reqwest` shipped by `openidconnect`
client: reqwest::ClientBuilder::new()
.dns_resolver(args.depend::<client::Service>("client").reqwest_resolver.clone())
.connect_timeout(Duration::from_secs(args.server.config.request_conn_timeout))
.read_timeout(Duration::from_secs(args.server.config.request_timeout))
.timeout(Duration::from_secs(args.server.config.request_total_timeout))
.pool_idle_timeout(Duration::from_secs(args.server.config.request_idle_timeout))
.pool_max_idle_per_host(args.server.config.request_idle_per_host.into())
.user_agent(conduwuit::user_agent())
.redirect(reqwest::redirect::Policy::none())
.danger_accept_invalid_certs(args.server.config.allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure)
.build()
.expect("client should build")
})}
).transpose()?,
})) }))
} }
async fn worker(self: Arc<Self>) -> Result { async fn worker(self: Arc<Self>) -> Result {
if let Some(OidcClient { client, .. }) = &self.client { if let Some(OidcClient { machine, .. }) = &self.client {
let discovered = self.discover().await?; let discovered = self.discover().await?;
client machine
.set(SyncRwLock::new(Arc::new(discovered))) .set(SyncRwLock::new(Arc::new(discovered)))
.expect("machine should be empty"); .expect("machine should be empty");
} }
@@ -176,36 +198,13 @@ impl Service {
// into the media repository. Keep this synced with the list in the // into the media repository. Keep this synced with the list in the
// doc comment for `profile_key_map` in the config. // doc comment for `profile_key_map` in the config.
const IMAGE_PROFILE_KEYS: &[&str] = &["avatar_url", "chat.commet.profile_banner"]; const IMAGE_PROFILE_KEYS: &[&str] = &["avatar_url", "chat.commet.profile_banner"];
const NONCE_SIZE: usize = 32;
const SERVER_MISCONFIGURED: &str = const SERVER_MISCONFIGURED: &str =
"Identity server is misconfigured. Contact your homeserver's administrator."; "Identity server is misconfigured. Contact your homeserver's administrator.";
fn create_nonce() -> String { utils::random_string(Self::NONCE_SIZE) }
fn create_client(config: OidcConfig) -> Result<OidcClient> {
let client_secret = if let Some(client_secret_file) = &config.client_secret_file {
std::fs::read_to_string(client_secret_file)
.map(|client_secret| client_secret.trim().to_owned())
.map_err(|err| err!("Failed to read OIDC client secret file: {err}"))?
} else if let Some(client_secret) = &config.client_secret {
client_secret.clone()
} else {
// The config check function should cause an early exit before this
// happens
panic!("neither client secret or client secret file were set");
};
Ok(OidcClient {
client_secret,
config,
client: SetOnce::new(),
})
}
pub fn enabled(&self) -> bool { self.client.is_some() } pub fn enabled(&self) -> bool { self.client.is_some() }
async fn discover(&self) -> Result<IdpClient> { async fn discover(&self) -> Result<OidcClientMachine> {
let OidcClient { config, client_secret, .. } = let OidcClient { config, client_secret, client, .. } =
self.client.as_ref().expect("oidc should be configured"); self.client.as_ref().expect("oidc should be configured");
let redirect_url = self let redirect_url = self
@@ -215,15 +214,20 @@ impl Service {
.join(&format!("{}/oidc/complete", conduwuit::ROUTE_PREFIX)) .join(&format!("{}/oidc/complete", conduwuit::ROUTE_PREFIX))
.expect("redirect url should be valid"); .expect("redirect url should be valid");
IdpClient::discover_with_client( let provider_metadata = CoreProviderMetadata::discover_async(
self.services.client.external_resource.clone(), IssuerUrl::new(config.discovery_url.clone())
config.client_id.clone(), .map_err(|err| err!("Failed to parse OIDC discovery URL: {err}"))?,
Some(client_secret.clone()), client,
Some(redirect_url.to_string()),
config.discovery_url.clone(),
) )
.await .await
.map_err(|err| err!("Failed to discover OIDC provider metadata: {err}")) .map_err(|err| err!("Failed to discover OIDC provider metadata: {err}"))?;
Ok(OidcClientMachine::from_provider_metadata(
provider_metadata,
config.client_id.clone(),
Some(client_secret.clone()),
)
.set_redirect_uri(RedirectUrl::from_url(redirect_url)))
} }
pub fn provider_name(&self) -> Option<String> { pub fn provider_name(&self) -> Option<String> {
@@ -252,32 +256,29 @@ impl Service {
} }
} }
pub async fn begin_session(&self, prompt: Option<openid::Prompt>) -> (PendingSession, Url) { pub async fn begin_session(&self, prompt: Option<CoreAuthPrompt>) -> (PendingSession, Url) {
let OidcClient { client, config, .. } = let OidcClient { machine, config, .. } =
self.client.as_ref().expect("oidc should be configured"); self.client.as_ref().expect("oidc should be configured");
let client = client.wait().await.read().clone(); let machine = machine.wait().await.read().clone();
let csrf_token = Self::create_nonce(); let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
let nonce = Self::create_nonce();
let (auth_url, pkce) = client.auth_url_with_new_pkce(&Options { let mut auth_url = machine
// The client will add the `openid` scope for us. .authorize_url(
scope: Some(config.additional_scopes.join(" ")), CoreAuthenticationFlow::AuthorizationCode,
state: Some(csrf_token.clone()), CsrfToken::new_random,
nonce: Some(nonce.clone()), Nonce::new_random,
prompt: prompt.map(|prompt| HashSet::from_iter([prompt])),
..Default::default()
});
(
PendingSession {
pkce_verifier: pkce.code_verifier().to_owned(),
nonce,
csrf_token,
},
auth_url,
) )
.add_scopes(config.additional_scopes.iter().cloned())
.set_pkce_challenge(pkce_challenge);
if let Some(prompt) = prompt {
auth_url = auth_url.add_prompt(prompt);
}
let (auth_url, csrf_token, nonce) = auth_url.url();
(PendingSession { pkce_verifier, nonce, csrf_token }, auth_url)
} }
pub async fn exchange_code( pub async fn exchange_code(
@@ -285,77 +286,78 @@ impl Service {
session: PendingSession, session: PendingSession,
response: AuthorizationCodeResponse, response: AuthorizationCodeResponse,
) -> Result<Claims, &'static str> { ) -> Result<Claims, &'static str> {
let Some(OidcClient { client, .. }) = self.client.as_ref() else { let Some(OidcClient { machine, client, config, .. }) = self.client.as_ref() else {
return Err("Delegated authentication is not enabled on this server."); return Err("Delegated authentication is not enabled on this server.");
}; };
let current = client.wait().await.read().clone(); let current = machine.wait().await.read().clone();
if session.csrf_token != response.state { if session.csrf_token.into_secret() != response.state {
return Err("State mismatch."); return Err("State mismatch.");
} }
let token_response = current let token_response = current
.request_token_pkce(&response.code, Some(&session.pkce_verifier)) .exchange_code(AuthorizationCode::new(response.code))
.expect("machine should be configured correctly")
.set_pkce_verifier(session.pkce_verifier)
.request_async(client)
.await .await
.map(Token::<Claims>::from)
.map_err(|err| { .map_err(|err| {
error!(error=?err, "Failed to exchange OIDC authorization code"); error!(error=?err, "Failed to exchange OIDC authorization code");
"Code exchange failed. The identity provider may be unreachable. Contact your \ "Code exchange failed. The identity provider may be unreachable. Contact your \
homeserver's administrator." homeserver's administrator."
})?; })?;
let Some(mut id_token) = token_response.id_token else { let Some(id_token) = token_response.id_token() else {
error!("Identity server did not return an id token"); error!("Identity server did not return an id token");
return Err(Self::SERVER_MISCONFIGURED); return Err(Self::SERVER_MISCONFIGURED);
}; };
if let Err(err) = current.decode_token(&mut id_token) { let verify = |machine: &OidcClientMachine| {
error!(error=?err, "Failed to decode ID token"); let verifier =
return Err(Self::SERVER_MISCONFIGURED); machine
} .id_token_verifier()
.set_other_audience_verifier_fn(|audience| {
config.additional_trusted_audiences.contains(audience)
});
let verify = |client: &IdpClient| { id_token
client.validate_token(&id_token, Some(session.nonce.as_str()), None) .claims(&verifier, &session.nonce)
.map(ToOwned::to_owned)
}; };
let mut result = verify(&current); let mut result = verify(&current);
if matches!( if matches!(
result, result,
Err(openid::error::Error::Jose(openid::error::Jose::ValidationError( Err(ClaimsVerificationError::SignatureVerification(
openid::biscuit::errors::ValidationError::KeyNotFound SignatureVerificationError::NoMatchingKey
))) ))
) { ) {
match self.discover().await { match self.discover().await {
| Ok(discovered) => { | Ok(discovered) => {
info!("Refreshed OIDC provider metadata after an unknown signing key"); info!("Refreshed OIDC provider metadata after an unknown signing key");
result = verify(&discovered); result = verify(&discovered);
*client.wait().await.write() = Arc::new(discovered); *machine.wait().await.write() = Arc::new(discovered);
}, },
| Err(err) => warn!("Failed to refresh OIDC provider metadata: {err}"), | Err(err) => warn!("Failed to refresh OIDC provider metadata: {err}"),
} }
} }
match result { let claims = result.map_err(|err| {
| Ok(()) => { error!("Failed to verify id token claims: {err}");
let (_, claims) = id_token.unwrap_decoded(); Self::SERVER_MISCONFIGURED
})?;
info!(subject = claims.sub(), "Authenticated subject"); info!(subject = claims.subject().as_str(), "Authenticated subject");
Ok(claims) Ok(claims)
},
| Err(err) => {
error!("Failed to verify id token claims: {err}");
Err(Self::SERVER_MISCONFIGURED)
},
}
} }
#[tracing::instrument(skip(self, claims), fields(subject = claims.sub().to_owned()))] #[tracing::instrument(skip(self, claims), fields(subject = claims.subject().to_string()))]
pub async fn complete_session( pub async fn complete_session(
&self, &self,
claims: Claims, claims: &Claims,
supplied_user_id: Option<OwnedUserId>, supplied_user_id: Option<OwnedUserId>,
client_ip: &IpAddr, client_ip: &IpAddr,
) -> Result<SessionCompletionStatus, &'static str> { ) -> Result<SessionCompletionStatus, &'static str> {
@@ -363,14 +365,21 @@ impl Service {
return Err("Delegated authentication is not enabled on this server."); return Err("Delegated authentication is not enabled on this server.");
}; };
debug!(claims = ?claims.other_claims, "Got claims from the identity provider"); // this is a truly awful hack but we really need all the claims in a map
let all_claims = serde_json::to_value(claims)
.expect("should be able to serialize claims")
.as_object()
.expect("claims should be an object")
.to_owned();
let subject = claims.sub().to_owned(); debug!(?all_claims, "Got claims from the identity provider");
let subject = claims.subject().as_str();
let user_id = if let Ok(localpart) = self let user_id = if let Ok(localpart) = self
.db .db
.openidsubject_localpart .openidsubject_localpart
.get(&subject) .get(subject)
.await .await
.deserialized::<String>() .deserialized::<String>()
{ {
@@ -382,7 +391,7 @@ impl Service {
} else { } else {
return Ok(SessionCompletionStatus::NeedsUserId); return Ok(SessionCompletionStatus::NeedsUserId);
} }
} else if let Some(preferred_username) = claims } else if let Some(preferred_username) = all_claims
.get(&config.preferred_username_claim) .get(&config.preferred_username_claim)
.and_then(|claim| claim.as_str()) .and_then(|claim| claim.as_str())
{ {
@@ -426,7 +435,7 @@ impl Service {
}, },
}; };
self.link_user(&user_id, &subject); self.link_user(&user_id, subject);
// Import profile fields // Import profile fields
if matches!(config.profile_key_import_mode, OidcProfileKeyImportMode::OnLogin) if matches!(config.profile_key_import_mode, OidcProfileKeyImportMode::OnLogin)
@@ -436,7 +445,7 @@ impl Service {
) && new_account_registered) ) && new_account_registered)
{ {
if let Some(email_claim) = &config.email_claim { if let Some(email_claim) = &config.email_claim {
if let Some(email) = claims.get(email_claim).and_then(|email| email.as_str()) if let Some(email) = claims.email().map(|email| email.as_str())
&& let Ok(address) = Address::from_str(email) && let Ok(address) = Address::from_str(email)
{ {
if let Err(err) = self if let Err(err) = self
@@ -456,6 +465,7 @@ impl Service {
} }
let user_id = user_id.clone(); let user_id = user_id.clone();
let subject = claims.subject().to_string();
let profile_key_map = config.profile_key_map.clone(); let profile_key_map = config.profile_key_map.clone();
let openidsubjectprofilefield_url = self.db.openidsubjectprofilefield_url.clone(); let openidsubjectprofilefield_url = self.db.openidsubjectprofilefield_url.clone();
let users = self.services.users.clone(); let users = self.services.users.clone();
@@ -465,7 +475,7 @@ impl Service {
// TODO: once we get support for full profile replacement, use // TODO: once we get support for full profile replacement, use
// that logic instead // that logic instead
for (field, claim) in &profile_key_map { for (field, claim) in &profile_key_map {
let Some(value) = claims.get(claim).cloned() else { let Some(value) = all_claims.get(claim).cloned() else {
warn!(?field, ?claim, "IDP provided no value for this mapped claim"); warn!(?field, ?claim, "IDP provided no value for this mapped claim");
continue; continue;
}; };
+1 -1
View File
@@ -31,7 +31,7 @@ form_urlencoded = "1.2.2"
futures.workspace = true futures.workspace = true
lettre.workspace = true lettre.workspace = true
memory-serve = "2.4.0" memory-serve = "2.4.0"
openid.workspace = true openidconnect.workspace = true
ruma.workspace = true ruma.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
+3 -3
View File
@@ -7,7 +7,7 @@ use axum::{
routing::{get, on}, routing::{get, on},
}; };
use conduwuit_api::client::handle_login; use conduwuit_api::client::handle_login;
use openid::Prompt; use openidconnect::core::CoreAuthPrompt;
use ruma::{ use ruma::{
OwnedUserId, OwnedUserId,
api::client::uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier}, api::client::uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
@@ -86,8 +86,8 @@ async fn route_login(
let (session, redirect_url) = services let (session, redirect_url) = services
.oidc .oidc
.begin_session(match intent { .begin_session(match intent {
| Some(LoginIntent::SwitchAccounts) => Some(Prompt::SelectAccount), | Some(LoginIntent::SwitchAccounts) => Some(CoreAuthPrompt::SelectAccount),
| _ if reauthenticate => Some(Prompt::Consent), | _ if reauthenticate => Some(CoreAuthPrompt::Consent),
| _ => None, | _ => None,
}) })
.await; .await;
+5 -4
View File
@@ -106,7 +106,10 @@ async fn route_complete(
.await .await
.expect("should be able to serialize oidc session"); .expect("should be able to serialize oidc session");
Box::pin(services.oidc.complete_session(claims, None, &client_ip)).await services
.oidc
.complete_session(&claims, None, &client_ip)
.await
}, },
| OidcSessionState::Authorized { claims } => { | OidcSessionState::Authorized { claims } => {
let supplied_user_id = if let Some(form) = form { let supplied_user_id = if let Some(form) = form {
@@ -163,11 +166,9 @@ async fn route_complete(
None None
}; };
Box::pin(
services services
.oidc .oidc
.complete_session(*claims, supplied_user_id, &client_ip), .complete_session(&claims, supplied_user_id, &client_ip)
)
.await .await
}, },
} }