mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-12-04 22:31:47 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72177cba8c |
No files matched your search
Generated
+575
-119
File diff suppressed because it is too large.
Load diff
+13
-3
@@ -166,6 +166,15 @@ 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
|
||||
@@ -348,7 +357,7 @@ version = "1.1.1"
|
||||
# Used for matrix spec type definitions and helpers
|
||||
[workspace.dependencies.ruma]
|
||||
git = "https://github.com/ruma/ruma.git"
|
||||
rev = "d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
|
||||
rev = "1bb5d0663e8e64f096be3715aff7ee793d521e15"
|
||||
features = [
|
||||
"appservice-api-c",
|
||||
"client-api",
|
||||
@@ -413,9 +422,10 @@ default-features = false
|
||||
version = "0.11.0"
|
||||
default-features = false
|
||||
|
||||
[workspace.dependencies.openid]
|
||||
version = "0.26.0"
|
||||
[workspace.dependencies.openidconnect]
|
||||
version = "4.1.0"
|
||||
default-features = false
|
||||
features = ["reqwest"]
|
||||
|
||||
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
|
||||
[workspace.dependencies.opentelemetry]
|
||||
|
||||
+1
-1
@@ -117,7 +117,7 @@ prometheus.workspace = true
|
||||
lock_api.workspace = true
|
||||
hyper-util.workspace = true
|
||||
resolvematrix.workspace = true
|
||||
openid.workspace = true
|
||||
openidconnect.workspace = true
|
||||
libmimalloc-sys.optional = true
|
||||
libmimalloc-sys.workspace = true
|
||||
mimalloc.optional = true
|
||||
|
||||
+18
-5
@@ -23,6 +23,7 @@ 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,
|
||||
@@ -2801,15 +2802,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: Url,
|
||||
pub discovery_url: String,
|
||||
|
||||
/// The OAuth client ID for Continuwuity to use when communicating with the
|
||||
/// identity provider.
|
||||
pub client_id: String,
|
||||
pub client_id: ClientId,
|
||||
|
||||
/// The OAuth client secret for Continuwuity to use when communicating with
|
||||
/// 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.
|
||||
/// If this option is set, it will override `client_secret`.
|
||||
@@ -2825,7 +2826,19 @@ pub struct OidcConfig {
|
||||
///
|
||||
/// default: ["profile"]
|
||||
#[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
|
||||
/// 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()))
|
||||
}
|
||||
|
||||
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
|
||||
// example config generator writes sections in macro expansion order, and the
|
||||
|
||||
@@ -130,7 +130,10 @@ yansi.workspace = true
|
||||
lettre.workspace = true
|
||||
resolvematrix.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
|
||||
|
||||
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
|
||||
@@ -140,6 +143,9 @@ 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"] }
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
+169
-159
@@ -1,19 +1,26 @@
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
net::IpAddr,
|
||||
str::FromStr,
|
||||
sync::Arc,
|
||||
};
|
||||
use std::{collections::HashMap, net::IpAddr, str::FromStr, sync::Arc, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use conduwuit::{
|
||||
Result, SyncRwLock,
|
||||
config::{OidcConfig, OidcProfileKeyImportMode},
|
||||
debug, err, error, info, utils, warn,
|
||||
debug, err, error, info, warn,
|
||||
};
|
||||
use database::{Deserialized, Map};
|
||||
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::{
|
||||
OwnedUserId, UserId,
|
||||
api::client::profile::PropagateTo,
|
||||
@@ -43,7 +50,6 @@ struct Data {
|
||||
openidsubjectprofilefield_url: Arc<Map>,
|
||||
}
|
||||
struct Services {
|
||||
client: Dep<client::Service>,
|
||||
config: Dep<config::Service>,
|
||||
globals: Dep<globals::Service>,
|
||||
media: Dep<media::Service>,
|
||||
@@ -52,61 +58,56 @@ struct Services {
|
||||
}
|
||||
|
||||
struct OidcClient {
|
||||
client_secret: String,
|
||||
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)]
|
||||
pub struct Claims {
|
||||
pub struct AllClaims {
|
||||
#[serde(flatten)]
|
||||
standard_claims: StandardClaims,
|
||||
|
||||
#[serde(flatten)]
|
||||
other_claims: HashMap<String, Value>,
|
||||
pub claims: HashMap<String, Value>,
|
||||
}
|
||||
|
||||
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 {}
|
||||
impl AdditionalClaims for AllClaims {}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct PendingSession {
|
||||
pkce_verifier: String,
|
||||
nonce: String,
|
||||
csrf_token: String,
|
||||
pkce_verifier: PkceCodeVerifier,
|
||||
nonce: Nonce,
|
||||
csrf_token: CsrfToken,
|
||||
}
|
||||
|
||||
pub enum SessionCompletionStatus {
|
||||
@@ -134,33 +135,54 @@ 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
|
||||
.clone()
|
||||
.map(Self::create_client)
|
||||
.transpose()?,
|
||||
},
|
||||
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()?,
|
||||
}))
|
||||
}
|
||||
|
||||
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?;
|
||||
client
|
||||
machine
|
||||
.set(SyncRwLock::new(Arc::new(discovered)))
|
||||
.expect("machine should be empty");
|
||||
}
|
||||
@@ -176,36 +198,13 @@ 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<IdpClient> {
|
||||
let OidcClient { config, client_secret, .. } =
|
||||
async fn discover(&self) -> Result<OidcClientMachine> {
|
||||
let OidcClient { config, client_secret, client, .. } =
|
||||
self.client.as_ref().expect("oidc should be configured");
|
||||
|
||||
let redirect_url = self
|
||||
@@ -215,15 +214,20 @@ impl Service {
|
||||
.join(&format!("{}/oidc/complete", conduwuit::ROUTE_PREFIX))
|
||||
.expect("redirect url should be valid");
|
||||
|
||||
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(),
|
||||
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}"))
|
||||
.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> {
|
||||
@@ -252,32 +256,29 @@ impl Service {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn begin_session(&self, prompt: Option<openid::Prompt>) -> (PendingSession, Url) {
|
||||
let OidcClient { client, config, .. } =
|
||||
pub async fn begin_session(&self, prompt: Option<CoreAuthPrompt>) -> (PendingSession, Url) {
|
||||
let OidcClient { machine, config, .. } =
|
||||
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 nonce = Self::create_nonce();
|
||||
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
|
||||
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])),
|
||||
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);
|
||||
|
||||
..Default::default()
|
||||
});
|
||||
if let Some(prompt) = prompt {
|
||||
auth_url = auth_url.add_prompt(prompt);
|
||||
}
|
||||
|
||||
(
|
||||
PendingSession {
|
||||
pkce_verifier: pkce.code_verifier().to_owned(),
|
||||
nonce,
|
||||
csrf_token,
|
||||
},
|
||||
auth_url,
|
||||
)
|
||||
let (auth_url, csrf_token, nonce) = auth_url.url();
|
||||
|
||||
(PendingSession { pkce_verifier, nonce, csrf_token }, auth_url)
|
||||
}
|
||||
|
||||
pub async fn exchange_code(
|
||||
@@ -285,77 +286,78 @@ impl Service {
|
||||
session: PendingSession,
|
||||
response: AuthorizationCodeResponse,
|
||||
) -> 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.");
|
||||
};
|
||||
|
||||
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.");
|
||||
}
|
||||
|
||||
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
|
||||
.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(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");
|
||||
return Err(Self::SERVER_MISCONFIGURED);
|
||||
};
|
||||
|
||||
if let Err(err) = current.decode_token(&mut id_token) {
|
||||
error!(error=?err, "Failed to decode 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)
|
||||
});
|
||||
|
||||
let verify = |client: &IdpClient| {
|
||||
client.validate_token(&id_token, Some(session.nonce.as_str()), None)
|
||||
id_token
|
||||
.claims(&verifier, &session.nonce)
|
||||
.map(ToOwned::to_owned)
|
||||
};
|
||||
|
||||
let mut result = verify(¤t);
|
||||
|
||||
if matches!(
|
||||
result,
|
||||
Err(openid::error::Error::Jose(openid::error::Jose::ValidationError(
|
||||
openid::biscuit::errors::ValidationError::KeyNotFound
|
||||
)))
|
||||
Err(ClaimsVerificationError::SignatureVerification(
|
||||
SignatureVerificationError::NoMatchingKey
|
||||
))
|
||||
) {
|
||||
match self.discover().await {
|
||||
| Ok(discovered) => {
|
||||
info!("Refreshed OIDC provider metadata after an unknown signing key");
|
||||
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}"),
|
||||
}
|
||||
}
|
||||
|
||||
match result {
|
||||
| Ok(()) => {
|
||||
let (_, claims) = id_token.unwrap_decoded();
|
||||
let claims = result.map_err(|err| {
|
||||
error!("Failed to verify id token claims: {err}");
|
||||
Self::SERVER_MISCONFIGURED
|
||||
})?;
|
||||
|
||||
info!(subject = claims.sub(), "Authenticated subject");
|
||||
info!(subject = claims.subject().as_str(), "Authenticated subject");
|
||||
|
||||
Ok(claims)
|
||||
},
|
||||
| Err(err) => {
|
||||
error!("Failed to verify id token claims: {err}");
|
||||
Err(Self::SERVER_MISCONFIGURED)
|
||||
},
|
||||
}
|
||||
Ok(claims)
|
||||
}
|
||||
|
||||
#[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(
|
||||
&self,
|
||||
claims: Claims,
|
||||
claims: &Claims,
|
||||
supplied_user_id: Option<OwnedUserId>,
|
||||
client_ip: &IpAddr,
|
||||
) -> Result<SessionCompletionStatus, &'static str> {
|
||||
@@ -363,14 +365,21 @@ impl Service {
|
||||
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
|
||||
.db
|
||||
.openidsubject_localpart
|
||||
.get(&subject)
|
||||
.get(subject)
|
||||
.await
|
||||
.deserialized::<String>()
|
||||
{
|
||||
@@ -382,7 +391,7 @@ impl Service {
|
||||
} else {
|
||||
return Ok(SessionCompletionStatus::NeedsUserId);
|
||||
}
|
||||
} else if let Some(preferred_username) = claims
|
||||
} else if let Some(preferred_username) = all_claims
|
||||
.get(&config.preferred_username_claim)
|
||||
.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
|
||||
if matches!(config.profile_key_import_mode, OidcProfileKeyImportMode::OnLogin)
|
||||
@@ -436,7 +445,7 @@ impl Service {
|
||||
) && new_account_registered)
|
||||
{
|
||||
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)
|
||||
{
|
||||
if let Err(err) = self
|
||||
@@ -456,6 +465,7 @@ 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();
|
||||
@@ -465,7 +475,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) = 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");
|
||||
continue;
|
||||
};
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ form_urlencoded = "1.2.2"
|
||||
futures.workspace = true
|
||||
lettre.workspace = true
|
||||
memory-serve = "2.4.0"
|
||||
openid.workspace = true
|
||||
openidconnect.workspace = true
|
||||
ruma.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
@@ -7,7 +7,7 @@ use axum::{
|
||||
routing::{get, on},
|
||||
};
|
||||
use conduwuit_api::client::handle_login;
|
||||
use openid::Prompt;
|
||||
use openidconnect::core::CoreAuthPrompt;
|
||||
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(Prompt::SelectAccount),
|
||||
| _ if reauthenticate => Some(Prompt::Consent),
|
||||
| Some(LoginIntent::SwitchAccounts) => Some(CoreAuthPrompt::SelectAccount),
|
||||
| _ if reauthenticate => Some(CoreAuthPrompt::Consent),
|
||||
| _ => None,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -106,7 +106,10 @@ async fn route_complete(
|
||||
.await
|
||||
.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 } => {
|
||||
let supplied_user_id = if let Some(form) = form {
|
||||
@@ -163,12 +166,10 @@ async fn route_complete(
|
||||
None
|
||||
};
|
||||
|
||||
Box::pin(
|
||||
services
|
||||
.oidc
|
||||
.complete_session(*claims, supplied_user_id, &client_ip),
|
||||
)
|
||||
.await
|
||||
services
|
||||
.oidc
|
||||
.complete_session(&claims, supplied_user_id, &client_ip)
|
||||
.await
|
||||
},
|
||||
}
|
||||
.map_err(|err| WebError::BadRequest(err.to_owned()))?;
|
||||
|
||||
Reference in new issue
Block a user