Compare commits

...
Author SHA1 Message Date
Ginger 76d90f09f2 refactor: Replace openidconnect crate with openid crate 2026-12-04 14:54:10 -05:00
10 changed files with 286 additions and 797 deletions

No files matched your search

Generated
+108 -564
View File
File diff suppressed because it is too large. Load diff
+2 -12
View File
@@ -166,15 +166,6 @@ features = [
"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]
version = "1.0.229"
default-features = false
@@ -422,10 +413,9 @@ default-features = false
version = "0.11.0"
default-features = false
[workspace.dependencies.openidconnect]
version = "4.1.0"
[workspace.dependencies.openid]
version = "0.26.0"
default-features = false
features = ["reqwest"]
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
[workspace.dependencies.opentelemetry]
+1 -1
View File
@@ -117,7 +117,7 @@ prometheus.workspace = true
lock_api.workspace = true
hyper-util.workspace = true
resolvematrix.workspace = true
openidconnect.workspace = true
openid.workspace = true
libmimalloc-sys.optional = true
libmimalloc-sys.workspace = true
mimalloc.optional = true
+5 -18
View File
@@ -23,7 +23,6 @@ use figment::providers::{Env, Format, Toml};
pub use figment::{Figment, value::Value as FigmentValue};
use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter};
use lettre::message::Mailbox;
use openidconnect::{Audience, ClientId, ClientSecret, Scope};
use regex::RegexSet;
use ruma::{
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId,
@@ -2802,15 +2801,15 @@ pub struct OidcConfig {
/// automatically fetch the identity provider's metadata from this URL.
/// Generally you should set this to the base domain your identity provider
/// runs on.
pub discovery_url: String,
pub discovery_url: Url,
/// The OAuth client ID for Continuwuity to use when communicating with the
/// identity provider.
pub client_id: ClientId,
pub client_id: String,
/// The OAuth client secret for Continuwuity to use when communicating with
/// the identity provider.
pub client_secret: Option<ClientSecret>,
pub client_secret: Option<String>,
/// A path to a file which Continuwuity will read the client secret from.
/// If this option is set, it will override `client_secret`.
@@ -2826,19 +2825,7 @@ pub struct OidcConfig {
///
/// default: ["profile"]
#[serde(default = "default_additional_scopes")]
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>,
pub additional_scopes: Vec<String>,
/// The name of the identity provider. If this is set, the login page's
/// button reads "Continue with <name>" instead of just "Continue".
@@ -3444,7 +3431,7 @@ fn default_unauthenticated_request_ratelimit<K: Hash + Eq + Clone>() -> PerMinut
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
}
fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] }
fn default_additional_scopes() -> Vec<String> { vec!["profile".to_owned()] }
// NOTE: This must be declared *after* every config struct in this file. The
// example config generator writes sections in macro expansion order, and the
+1 -7
View File
@@ -130,10 +130,7 @@ yansi.workspace = true
lettre.workspace = true
resolvematrix.workspace = true
serde_urlencoded.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
openid.workspace = true
rand.workspace = true
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
@@ -143,9 +140,6 @@ sd-notify.optional = true
[lints]
workspace = true
[package.metadata.cargo-shear]
ignored = ["reqwest_0_12"]
[dev-dependencies]
opentelemetry.workspace = true
rustls = { workspace = true, features = ["ring"] }
-15
View File
@@ -44,18 +44,3 @@ 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)
})
}
}
+158 -168
View File
@@ -1,26 +1,19 @@
use std::{collections::HashMap, net::IpAddr, str::FromStr, sync::Arc, time::Duration};
use std::{
collections::{HashMap, HashSet},
net::IpAddr,
str::FromStr,
sync::Arc,
};
use async_trait::async_trait;
use conduwuit::{
Result, SyncRwLock,
config::{OidcConfig, OidcProfileKeyImportMode},
debug, err, error, info, warn,
debug, err, error, info, utils, warn,
};
use database::{Deserialized, Map};
use lettre::Address;
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 openid::{Claims as _, Options, StandardClaims, Token};
use ruma::{
OwnedUserId, UserId,
api::client::profile::PropagateTo,
@@ -50,6 +43,7 @@ struct Data {
openidsubjectprofilefield_url: Arc<Map>,
}
struct Services {
client: Dep<client::Service>,
config: Dep<config::Service>,
globals: Dep<globals::Service>,
media: Dep<media::Service>,
@@ -58,56 +52,61 @@ struct Services {
}
struct OidcClient {
client_secret: String,
config: OidcConfig,
client_secret: ClientSecret,
machine: SetOnce<SyncRwLock<Arc<OidcClientMachine>>>,
client: reqwest::Client,
client: SetOnce<SyncRwLock<Arc<IdpClient>>>,
}
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>;
type IdpClient = openid::Client<openid::Discovered, Claims>;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AllClaims {
pub struct Claims {
#[serde(flatten)]
pub claims: HashMap<String, Value>,
standard_claims: StandardClaims,
#[serde(flatten)]
other_claims: HashMap<String, Value>,
}
impl AdditionalClaims for AllClaims {}
impl Claims {
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)]
pub struct PendingSession {
pkce_verifier: PkceCodeVerifier,
nonce: Nonce,
csrf_token: CsrfToken,
pkce_verifier: String,
nonce: String,
csrf_token: String,
}
pub enum SessionCompletionStatus {
@@ -135,54 +134,33 @@ impl crate::Service for Service {
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
Ok(Arc::new(Self {
services: Services {
client: args.depend::<client::Service>("client"),
config: args.depend::<config::Service>("config"),
globals: args.depend::<globals::Service>("globals"),
globals: args.depend::<globals::Service>("globals"),
media: args.depend::<media::Service>("media"),
threepid: args.depend::<threepid::Service>("threepid"),
users: args.depend::<users::Service>("users"),
threepid: args.depend::<threepid::Service>("threepid"),
users: args.depend::<users::Service>("users"),
},
runtime: args.server.runtime().clone(),
db: Data {
openidsubject_localpart: args.db["openidsubject_localpart"].clone(),
db: Data {
openidsubject_localpart: args.db["openidsubject_localpart"].clone(),
openidsubjectprofilefield_url: args.db["openidsubjectprofilefield_url"].clone(),
},
client: args.server.config.oauth.oidc.as_ref().map(|config| -> Result<OidcClient> {
Ok(OidcClient {
config: config.clone(),
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(ClientSecret::new)
.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()?,
},
client: args
.server
.config
.oauth
.oidc
.clone()
.map(Self::create_client)
.transpose()?,
}))
}
async fn worker(self: Arc<Self>) -> Result {
if let Some(OidcClient { machine, .. }) = &self.client {
if let Some(OidcClient { client, .. }) = &self.client {
let discovered = self.discover().await?;
machine
client
.set(SyncRwLock::new(Arc::new(discovered)))
.expect("machine should be empty");
}
@@ -198,13 +176,36 @@ impl Service {
// into the media repository. Keep this synced with the list in the
// doc comment for `profile_key_map` in the config.
const IMAGE_PROFILE_KEYS: &[&str] = &["avatar_url", "chat.commet.profile_banner"];
const NONCE_SIZE: usize = 32;
const SERVER_MISCONFIGURED: &str =
"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() }
async fn discover(&self) -> Result<OidcClientMachine> {
let OidcClient { config, client_secret, client, .. } =
async fn discover(&self) -> Result<IdpClient> {
let OidcClient { config, client_secret, .. } =
self.client.as_ref().expect("oidc should be configured");
let redirect_url = self
@@ -214,20 +215,15 @@ impl Service {
.join(&format!("{}/oidc/complete", conduwuit::ROUTE_PREFIX))
.expect("redirect url should be valid");
let provider_metadata = CoreProviderMetadata::discover_async(
IssuerUrl::new(config.discovery_url.clone())
.map_err(|err| err!("Failed to parse OIDC discovery URL: {err}"))?,
client,
)
.await
.map_err(|err| err!("Failed to discover OIDC provider metadata: {err}"))?;
Ok(OidcClientMachine::from_provider_metadata(
provider_metadata,
IdpClient::discover_with_client(
self.services.client.external_resource.clone(),
config.client_id.clone(),
Some(client_secret.clone()),
Some(redirect_url.to_string()),
config.discovery_url.clone(),
)
.set_redirect_uri(RedirectUrl::from_url(redirect_url)))
.await
.map_err(|err| err!("Failed to discover OIDC provider metadata: {err}"))
}
pub fn provider_name(&self) -> Option<String> {
@@ -256,29 +252,32 @@ impl Service {
}
}
pub async fn begin_session(&self, prompt: Option<CoreAuthPrompt>) -> (PendingSession, Url) {
let OidcClient { machine, config, .. } =
pub async fn begin_session(&self, prompt: Option<openid::Prompt>) -> (PendingSession, Url) {
let OidcClient { client, config, .. } =
self.client.as_ref().expect("oidc should be configured");
let machine = machine.wait().await.read().clone();
let client = client.wait().await.read().clone();
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
let csrf_token = Self::create_nonce();
let nonce = Self::create_nonce();
let mut auth_url = machine
.authorize_url(
CoreAuthenticationFlow::AuthorizationCode,
CsrfToken::new_random,
Nonce::new_random,
)
.add_scopes(config.additional_scopes.iter().cloned())
.set_pkce_challenge(pkce_challenge);
let (auth_url, pkce) = client.auth_url_with_new_pkce(&Options {
// The client will add the `openid` scope for us.
scope: Some(config.additional_scopes.join(" ")),
state: Some(csrf_token.clone()),
nonce: Some(nonce.clone()),
prompt: prompt.map(|prompt| HashSet::from_iter([prompt])),
if let Some(prompt) = prompt {
auth_url = auth_url.add_prompt(prompt);
}
..Default::default()
});
let (auth_url, csrf_token, nonce) = auth_url.url();
(PendingSession { pkce_verifier, nonce, csrf_token }, auth_url)
(
PendingSession {
pkce_verifier: pkce.code_verifier().to_owned(),
nonce,
csrf_token,
},
auth_url,
)
}
pub async fn exchange_code(
@@ -286,78 +285,77 @@ impl Service {
session: PendingSession,
response: AuthorizationCodeResponse,
) -> Result<Claims, &'static str> {
let Some(OidcClient { machine, client, config, .. }) = self.client.as_ref() else {
let Some(OidcClient { client, .. }) = self.client.as_ref() else {
return Err("Delegated authentication is not enabled on this server.");
};
let current = machine.wait().await.read().clone();
let current = client.wait().await.read().clone();
if session.csrf_token.into_secret() != response.state {
if session.csrf_token != response.state {
return Err("State mismatch.");
}
let token_response = current
.exchange_code(AuthorizationCode::new(response.code))
.expect("machine should be configured correctly")
.set_pkce_verifier(session.pkce_verifier)
.request_async(client)
.request_token_pkce(&response.code, Some(&session.pkce_verifier))
.await
.map(Token::<Claims>::from)
.map_err(|err| {
error!(error=?err, "Failed to exchange OIDC authorization code");
"Code exchange failed. The identity provider may be unreachable. Contact your \
homeserver's administrator."
})?;
let Some(id_token) = token_response.id_token() else {
let Some(mut id_token) = token_response.id_token else {
error!("Identity server did not return an id token");
return Err(Self::SERVER_MISCONFIGURED);
};
let verify = |machine: &OidcClientMachine| {
let verifier =
machine
.id_token_verifier()
.set_other_audience_verifier_fn(|audience| {
config.additional_trusted_audiences.contains(audience)
});
if let Err(err) = current.decode_token(&mut id_token) {
error!(error=?err, "Failed to decode ID token");
return Err(Self::SERVER_MISCONFIGURED);
}
id_token
.claims(&verifier, &session.nonce)
.map(ToOwned::to_owned)
let verify = |client: &IdpClient| {
client.validate_token(&id_token, Some(session.nonce.as_str()), None)
};
let mut result = verify(&current);
if matches!(
result,
Err(ClaimsVerificationError::SignatureVerification(
SignatureVerificationError::NoMatchingKey
))
Err(openid::error::Error::Jose(openid::error::Jose::ValidationError(
openid::biscuit::errors::ValidationError::KeyNotFound
)))
) {
match self.discover().await {
| Ok(discovered) => {
info!("Refreshed OIDC provider metadata after an unknown signing key");
result = verify(&discovered);
*machine.wait().await.write() = Arc::new(discovered);
*client.wait().await.write() = Arc::new(discovered);
},
| Err(err) => warn!("Failed to refresh OIDC provider metadata: {err}"),
}
}
let claims = result.map_err(|err| {
error!("Failed to verify id token claims: {err}");
Self::SERVER_MISCONFIGURED
})?;
match result {
| Ok(()) => {
let (_, claims) = id_token.unwrap_decoded();
info!(subject = claims.subject().as_str(), "Authenticated subject");
info!(subject = claims.sub(), "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.subject().to_string()))]
#[tracing::instrument(skip(self, claims), fields(subject = claims.sub().to_owned()))]
pub async fn complete_session(
&self,
claims: &Claims,
claims: Claims,
supplied_user_id: Option<OwnedUserId>,
client_ip: &IpAddr,
) -> Result<SessionCompletionStatus, &'static str> {
@@ -365,21 +363,14 @@ impl Service {
return Err("Delegated authentication is not enabled on this server.");
};
// 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();
debug!(claims = ?claims.other_claims, "Got claims from the identity provider");
debug!(?all_claims, "Got claims from the identity provider");
let subject = claims.subject().as_str();
let subject = claims.sub().to_owned();
let user_id = if let Ok(localpart) = self
.db
.openidsubject_localpart
.get(subject)
.get(&subject)
.await
.deserialized::<String>()
{
@@ -391,7 +382,7 @@ impl Service {
} else {
return Ok(SessionCompletionStatus::NeedsUserId);
}
} else if let Some(preferred_username) = all_claims
} else if let Some(preferred_username) = claims
.get(&config.preferred_username_claim)
.and_then(|claim| claim.as_str())
{
@@ -435,7 +426,7 @@ impl Service {
},
};
self.link_user(&user_id, subject);
self.link_user(&user_id, &subject);
// Import profile fields
if matches!(config.profile_key_import_mode, OidcProfileKeyImportMode::OnLogin)
@@ -445,7 +436,7 @@ impl Service {
) && new_account_registered)
{
if let Some(email_claim) = &config.email_claim {
if let Some(email) = claims.email().map(|email| email.as_str())
if let Some(email) = claims.get(email_claim).and_then(|email| email.as_str())
&& let Ok(address) = Address::from_str(email)
{
if let Err(err) = self
@@ -465,7 +456,6 @@ impl Service {
}
let user_id = user_id.clone();
let subject = claims.subject().to_string();
let profile_key_map = config.profile_key_map.clone();
let openidsubjectprofilefield_url = self.db.openidsubjectprofilefield_url.clone();
let users = self.services.users.clone();
@@ -475,7 +465,7 @@ impl Service {
// TODO: once we get support for full profile replacement, use
// that logic instead
for (field, claim) in &profile_key_map {
let Some(value) = all_claims.get(claim).cloned() else {
let Some(value) = claims.get(claim).cloned() else {
warn!(?field, ?claim, "IDP provided no value for this mapped claim");
continue;
};
+1 -1
View File
@@ -31,7 +31,7 @@ form_urlencoded = "1.2.2"
futures.workspace = true
lettre.workspace = true
memory-serve = "2.4.0"
openidconnect.workspace = true
openid.workspace = true
ruma.workspace = true
serde.workspace = true
serde_json.workspace = true
+3 -3
View File
@@ -7,7 +7,7 @@ use axum::{
routing::{get, on},
};
use conduwuit_api::client::handle_login;
use openidconnect::core::CoreAuthPrompt;
use openid::Prompt;
use ruma::{
OwnedUserId,
api::client::uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
@@ -86,8 +86,8 @@ async fn route_login(
let (session, redirect_url) = services
.oidc
.begin_session(match intent {
| Some(LoginIntent::SwitchAccounts) => Some(CoreAuthPrompt::SelectAccount),
| _ if reauthenticate => Some(CoreAuthPrompt::Consent),
| Some(LoginIntent::SwitchAccounts) => Some(Prompt::SelectAccount),
| _ if reauthenticate => Some(Prompt::Consent),
| _ => None,
})
.await;
+7 -8
View File
@@ -106,10 +106,7 @@ async fn route_complete(
.await
.expect("should be able to serialize oidc session");
services
.oidc
.complete_session(&claims, None, &client_ip)
.await
Box::pin(services.oidc.complete_session(claims, None, &client_ip)).await
},
| OidcSessionState::Authorized { claims } => {
let supplied_user_id = if let Some(form) = form {
@@ -166,10 +163,12 @@ async fn route_complete(
None
};
services
.oidc
.complete_session(&claims, supplied_user_id, &client_ip)
.await
Box::pin(
services
.oidc
.complete_session(*claims, supplied_user_id, &client_ip),
)
.await
},
}
.map_err(|err| WebError::BadRequest(err.to_owned()))?;