mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-12-04 22:31:47 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76d90f09f2 | ||
|
|
2f356eaa91 | ||
|
|
e6afb63648 | ||
|
|
ac7f79bd26 | ||
|
|
5f2b73db9d | ||
|
|
1a616146d0 |
No files matched your search
@@ -17,7 +17,7 @@ go to "files changed", and click on the "+" symbol in the line number gutter,
|
||||
and attach comments to the lines that you think would benefit from some clarification.
|
||||
-->
|
||||
|
||||
This pull request...
|
||||
This pull request... <!-- do not forget to write here! -->
|
||||
|
||||
<!-- Example:
|
||||
This pull request allows us to warp through time and space ten times faster than before by
|
||||
@@ -26,8 +26,8 @@ efficient. This resolves the common issue where we have to wait more than 10 mil
|
||||
engage, use, and disengage the warp drive when travelling between galaxies.
|
||||
-->
|
||||
|
||||
<!-- Closes: #... -->
|
||||
<!-- Fixes: #... -->
|
||||
<!-- Closes #... -->
|
||||
<!-- Fixes #... -->
|
||||
<!-- Uncomment the above line(s) if your pull request fixes an issue or closes another pull request
|
||||
by superseding it. Replace `#...` with the issue/pr number, such as `#123`. -->
|
||||
|
||||
@@ -73,6 +73,7 @@ Notes on these requirements:
|
||||
main, it's difficult to get out cleanly, so put on your best dress, smile for the cameras!
|
||||
-->
|
||||
|
||||
<!-- Do not delete below this line -->
|
||||
[c1]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md
|
||||
[c2]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/docs/development/code_style.mdx
|
||||
[c1pc]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md#pre-commit-checks
|
||||
|
||||
@@ -64,7 +64,7 @@ repos:
|
||||
- pre-push
|
||||
|
||||
- repo: https://code.forgejo.org/forgejo/runner
|
||||
rev: v13.2.1
|
||||
rev: v13.3.0
|
||||
hooks:
|
||||
- id: forgejo-runner-validate
|
||||
stages:
|
||||
|
||||
Generated
+119
-575
File diff suppressed because it is too large.
Load diff
+2
-12
@@ -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 +0,0 @@
|
||||
Continuwuity now understands [MSC4198](https://github.com/matrix-org/matrix-spec-proposals/pull/4198) login hints. With a supported client, this will keep you from being prompted for your user ID redundantly when logging in, and will allow you to easily switch accounts if you open the account manager while logged into your client as a different user. Contributed by @ginger.
|
||||
@@ -0,0 +1 @@
|
||||
The `element_hacks` build feature, which has done almost nothing for many versions, has been removed completely. Contributed by @ginger.
|
||||
@@ -1 +0,0 @@
|
||||
When logging in with an OIDC identity provider, if Continuwuity knows the ID of the user trying to log in, it will pass their localpart on to the IDP with the `login_hint` query parameter.
|
||||
+3
-17
@@ -2579,10 +2579,9 @@
|
||||
|
||||
# Additional scopes Continuwuity should request from the IDP. This may be
|
||||
# necessary to access certain claims. Continuwuity always requests the
|
||||
# `openid` scope, regardless of the value of this option.
|
||||
#
|
||||
# Defaults to only the `profile` scope, as recommended by the OIDC
|
||||
# specification.
|
||||
# `openid` scope, regardless of the contents of this option,
|
||||
# and will also request the `profile` scope by default if this option is
|
||||
# not set.
|
||||
#
|
||||
# env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_SCOPES
|
||||
#additional_scopes = ["profile"]
|
||||
@@ -2598,19 +2597,6 @@
|
||||
# env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_TRUSTED_AUDIENCES
|
||||
#additional_trusted_audiences = []
|
||||
|
||||
# If `true`, Continuwuity will pass on the Matrix ID of the user trying to
|
||||
# log in to the identity provider where applicable.
|
||||
#
|
||||
# If Continuwuity knows the Matrix ID of the user trying to log in, it
|
||||
# will set the authorization URL's `login_hint` query parameter to the
|
||||
# _localpart_ of that ID (everything between the @ sign and the colon).
|
||||
#
|
||||
# Defaults to `true`. Set this to `false` if supplying the `login_hint`
|
||||
# causes your identity provider to behave undesirably.
|
||||
#
|
||||
# env: CONTINUWUITY_OAUTH__OIDC__SUPPLY_LOGIN_HINT
|
||||
#supply_login_hint = true
|
||||
|
||||
# The name of the identity provider. If this is set, the login page's
|
||||
# button reads "Continue with <name>" instead of just "Continue".
|
||||
#
|
||||
|
||||
@@ -102,7 +102,7 @@ look like this:
|
||||
RUSTFLAGS="--cfg tokio_unstable" cargo +nightly build \
|
||||
--release \
|
||||
--no-default-features \
|
||||
--features=systemd,element_hacks,gzip_compression,brotli_compression,zstd_compression,tokio_console
|
||||
--features=systemd,gzip_compression,brotli_compression,zstd_compression,tokio_console
|
||||
```
|
||||
|
||||
You will also need to enable the `tokio_console` config option in Continuwuity
|
||||
|
||||
+1
-1
@@ -146,7 +146,7 @@ cargo clippy \
|
||||
--locked \
|
||||
--profile test \
|
||||
--no-default-features \
|
||||
--features=console,systemd,element_hacks,direct_tls,perf_measurements,brotli_compression \
|
||||
--features=console,systemd,direct_tls,perf_measurements,brotli_compression \
|
||||
--color=always \
|
||||
-- \
|
||||
-D warnings
|
||||
|
||||
@@ -21,9 +21,6 @@ brotli_compression = [
|
||||
"conduwuit-service/brotli_compression",
|
||||
"reqwest/brotli",
|
||||
]
|
||||
element_hacks = [
|
||||
"conduwuit-service/element_hacks",
|
||||
]
|
||||
gzip_compression = [
|
||||
"conduwuit-core/gzip_compression",
|
||||
"conduwuit-service/gzip_compression",
|
||||
|
||||
@@ -75,6 +75,7 @@ pub(super) use report::*;
|
||||
pub(super) use room::*;
|
||||
pub(super) use search::*;
|
||||
pub(super) use send::*;
|
||||
pub use session::handle_login;
|
||||
pub(super) use session::*;
|
||||
pub(super) use space::*;
|
||||
pub(super) use state::*;
|
||||
|
||||
@@ -70,9 +70,5 @@ pub(crate) async fn authorization_server_metadata(services: &Services) -> Value
|
||||
"response_types_supported": ["code"],
|
||||
"revocation_endpoint": endpoint_base.join(TOKEN_REVOKE_PATH).unwrap(),
|
||||
"token_endpoint": endpoint_base.join(TOKEN_PATH).unwrap(),
|
||||
// NOTE: This isn't gated behind an experiment because MSC4198 is extremely simple, only specifying
|
||||
// a couple query parameters and a syntax for login hints.
|
||||
// The actual account-switching behavior it enables is implementation-defined and thus at no risk of drifting away from the MSC.
|
||||
"org.matrix.msc4198.login_hint_types_supported": ["mxid"],
|
||||
})
|
||||
}
|
||||
@@ -29,18 +29,10 @@ pub(crate) async fn get_profile_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<get_profile::v3::Request>,
|
||||
) -> Result<get_profile::v3::Response> {
|
||||
let querying_user = body
|
||||
.identity
|
||||
.as_ref()
|
||||
.and_then(|identity| identity.sender_user())
|
||||
.into();
|
||||
|
||||
if !services
|
||||
.users
|
||||
.user_can_see_profile(&body.user_id, querying_user)
|
||||
.await
|
||||
{
|
||||
return Err!(Request(Unauthorized("You cannot access this user's profile.")));
|
||||
if services.config.require_auth_for_profile_requests && body.identity.is_none() {
|
||||
return Err!(Request(Unauthorized(
|
||||
"This server requires authentication to access user profiles."
|
||||
)));
|
||||
}
|
||||
|
||||
let Some(profile) = fetch_full_profile(&services, &body.user_id).await else {
|
||||
@@ -54,18 +46,10 @@ pub(crate) async fn get_profile_field_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<get_profile_field::v3::Request>,
|
||||
) -> Result<get_profile_field::v3::Response> {
|
||||
let querying_user = body
|
||||
.identity
|
||||
.as_ref()
|
||||
.and_then(|identity| identity.sender_user())
|
||||
.into();
|
||||
|
||||
if !services
|
||||
.users
|
||||
.user_can_see_profile(&body.user_id, querying_user)
|
||||
.await
|
||||
{
|
||||
return Err!(Request(Unauthorized("You cannot access this user's profile.")));
|
||||
if services.config.require_auth_for_profile_requests && body.identity.is_none() {
|
||||
return Err!(Request(Unauthorized(
|
||||
"This server requires authentication to access user profiles."
|
||||
)));
|
||||
}
|
||||
|
||||
let value = fetch_profile_field(&services, &body.user_id, body.field.clone()).await?;
|
||||
|
||||
+29
-14
@@ -8,6 +8,7 @@ use conduwuit::{
|
||||
};
|
||||
use conduwuit_service::Services;
|
||||
use futures::StreamExt;
|
||||
use lettre::Address;
|
||||
use ruma::{
|
||||
OwnedUserId, UserId,
|
||||
api::client::{
|
||||
@@ -23,7 +24,7 @@ use ruma::{
|
||||
},
|
||||
logout, logout_all,
|
||||
},
|
||||
uiaa::{MatrixUserIdentifier, UserIdentifier},
|
||||
uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
|
||||
},
|
||||
assign,
|
||||
};
|
||||
@@ -55,29 +56,43 @@ pub(crate) async fn get_login_types_route(
|
||||
]))
|
||||
}
|
||||
|
||||
async fn handle_login(
|
||||
pub async fn handle_login(
|
||||
services: &Services,
|
||||
identifier: Option<UserIdentifier>,
|
||||
identifier: Option<&UserIdentifier>,
|
||||
password: &str,
|
||||
user: Option<&String>,
|
||||
) -> Result<OwnedUserId> {
|
||||
debug!("Got password login type");
|
||||
|
||||
let user_id = if let Some(identifier) = identifier {
|
||||
services.users.lookup_by_identifier(identifier).await
|
||||
} else if let Some(user) = user {
|
||||
UserId::parse_with_server_name(user, &services.config.server_name).ok()
|
||||
} else {
|
||||
None
|
||||
let user_id_or_localpart = match (identifier, user) {
|
||||
| (Some(UserIdentifier::Matrix(MatrixUserIdentifier { user, .. })), _)
|
||||
| (None, Some(user)) => user,
|
||||
| (Some(UserIdentifier::Email(EmailUserIdentifier { address, .. })), _) => {
|
||||
let email = Address::try_from(address.to_owned())
|
||||
.map_err(|_| err!(Request(InvalidParam("Email is malformed"))))?;
|
||||
|
||||
&services
|
||||
.threepid
|
||||
.get_localpart_for_email(&email)
|
||||
.await
|
||||
.ok_or_else(|| err!(Request(Forbidden("Invalid identifier or password"))))?
|
||||
},
|
||||
| _ => {
|
||||
return Err!(Request(InvalidParam("Identifier type not recognized")));
|
||||
},
|
||||
};
|
||||
|
||||
let Some(user_id) = user_id else {
|
||||
return Err!(Request(InvalidUsername("User ID is malformed.")));
|
||||
};
|
||||
let user_id =
|
||||
UserId::parse_with_server_name(user_id_or_localpart, &services.config.server_name)
|
||||
.map_err(|_| err!(Request(InvalidUsername("User ID is malformed"))))?;
|
||||
|
||||
if services.users.is_locked(&user_id).await? {
|
||||
return Err!(Request(UserLocked("This account has been locked.")));
|
||||
}
|
||||
|
||||
if services.users.is_login_disabled(&user_id).await {
|
||||
warn!(%user_id, "user attempted to log in with a login-disabled account");
|
||||
return Err!(Request(Forbidden("This account is blocked from logging in.")));
|
||||
return Err!(Request(Forbidden("This account is not permitted to log in.")));
|
||||
}
|
||||
|
||||
services.users.check_password(&user_id, password).await
|
||||
@@ -124,7 +139,7 @@ pub(crate) async fn login_route(
|
||||
let user_id = match &body.login_info {
|
||||
#[allow(deprecated)]
|
||||
| LoginInfo::Password(login::v3::Password { identifier, password, user, .. }) =>
|
||||
handle_login(&services, identifier.to_owned(), password, user.as_ref()).await?,
|
||||
handle_login(&services, identifier.as_ref(), password, user.as_ref()).await?,
|
||||
| LoginInfo::Token(login::v3::Token { token, .. }) => {
|
||||
debug!("Got token login type");
|
||||
if !services.server.config.login_via_existing_session {
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
+8
-36
@@ -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`.
|
||||
@@ -2820,40 +2819,13 @@ pub struct OidcConfig {
|
||||
|
||||
/// Additional scopes Continuwuity should request from the IDP. This may be
|
||||
/// necessary to access certain claims. Continuwuity always requests the
|
||||
/// `openid` scope, regardless of the value of this option.
|
||||
///
|
||||
/// Defaults to only the `profile` scope, as recommended by the OIDC
|
||||
/// specification.
|
||||
/// `openid` scope, regardless of the contents of this option,
|
||||
/// and will also request the `profile` scope by default if this option is
|
||||
/// not set.
|
||||
///
|
||||
/// 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>,
|
||||
|
||||
/// If `true`, Continuwuity will pass on the Matrix ID of the user trying to
|
||||
/// log in to the identity provider where applicable.
|
||||
///
|
||||
/// If Continuwuity knows the Matrix ID of the user trying to log in, it
|
||||
/// will set the authorization URL's `login_hint` query parameter to the
|
||||
/// _localpart_ of that ID (everything between the @ sign and the colon).
|
||||
///
|
||||
/// Defaults to `true`. Set this to `false` if supplying the `login_hint`
|
||||
/// causes your identity provider to behave undesirably.
|
||||
///
|
||||
/// default: true
|
||||
#[serde(default = "true_fn")]
|
||||
pub supply_login_hint: bool,
|
||||
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".
|
||||
@@ -3459,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
|
||||
|
||||
@@ -55,7 +55,6 @@ default = [
|
||||
standard = [
|
||||
"brotli_compression",
|
||||
"direct_tls",
|
||||
"element_hacks",
|
||||
"gzip_compression",
|
||||
"io_uring",
|
||||
"jemalloc_conf",
|
||||
@@ -86,10 +85,6 @@ console = [
|
||||
direct_tls = [
|
||||
"conduwuit-router/direct_tls"
|
||||
]
|
||||
element_hacks = [
|
||||
"conduwuit-service/element_hacks",
|
||||
"conduwuit-router/element_hacks",
|
||||
]
|
||||
gzip_compression = [
|
||||
"conduwuit-core/gzip_compression",
|
||||
"conduwuit-router/gzip_compression",
|
||||
|
||||
@@ -27,9 +27,6 @@ direct_tls = [
|
||||
"axum-server/tls-rustls-no-provider",
|
||||
"dep:axum-server-dual-protocol",
|
||||
]
|
||||
element_hacks = [
|
||||
"conduwuit-api/element_hacks",
|
||||
]
|
||||
gzip_compression = [
|
||||
"conduwuit-admin/gzip_compression",
|
||||
"conduwuit-api/gzip_compression",
|
||||
|
||||
@@ -15,6 +15,7 @@ use opentelemetry_instrumentation_tower::http::server::LayerBuilder as OtelHttpL
|
||||
use tower::ServiceBuilder;
|
||||
use tower_http::{
|
||||
catch_panic::CatchPanicLayer,
|
||||
cors::{self, CorsLayer},
|
||||
sensitive_headers::SetSensitiveHeadersLayer,
|
||||
set_header::SetResponseHeaderLayer,
|
||||
timeout::{RequestBodyTimeoutLayer, ResponseBodyTimeoutLayer, TimeoutLayer},
|
||||
@@ -100,6 +101,7 @@ pub(crate) fn build(services: &Arc<Services>) -> Result<(Router, Guard)> {
|
||||
header::CONTENT_SECURITY_POLICY,
|
||||
HeaderValue::from_str(&CONDUWUIT_CSP.join(";"))?,
|
||||
))
|
||||
.layer(cors_layer(server))
|
||||
.layer(body_limit_layer(server))
|
||||
.layer(CatchPanicLayer::custom(move |panic| catch_panic(panic, services_.clone())));
|
||||
|
||||
@@ -145,6 +147,32 @@ fn compression_layer(server: &Server) -> tower_http::compression::CompressionLay
|
||||
compression_layer
|
||||
}
|
||||
|
||||
fn cors_layer(_server: &Server) -> CorsLayer {
|
||||
const METHODS: [Method; 7] = [
|
||||
Method::GET,
|
||||
Method::HEAD,
|
||||
Method::PATCH,
|
||||
Method::POST,
|
||||
Method::PUT,
|
||||
Method::DELETE,
|
||||
Method::OPTIONS,
|
||||
];
|
||||
|
||||
let headers: [HeaderName; 5] = [
|
||||
header::ORIGIN,
|
||||
HeaderName::from_lowercase(b"x-requested-with").unwrap(),
|
||||
header::CONTENT_TYPE,
|
||||
header::ACCEPT,
|
||||
header::AUTHORIZATION,
|
||||
];
|
||||
|
||||
CorsLayer::new()
|
||||
.allow_origin(cors::Any)
|
||||
.allow_methods(METHODS)
|
||||
.allow_headers(headers)
|
||||
.max_age(Duration::from_hours(24))
|
||||
}
|
||||
|
||||
/// Methods outside the standard set can never match a route; record them as
|
||||
/// `_OTHER`, as the semantic conventions ask, so clients cannot create new
|
||||
/// metric attribute values.
|
||||
|
||||
+2
-30
@@ -1,11 +1,10 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{Router, response::IntoResponse};
|
||||
use conduwuit::Error;
|
||||
use conduwuit_service::{Services, state, state::Guard};
|
||||
use http::{HeaderName, Method, StatusCode, Uri, header};
|
||||
use http::{StatusCode, Uri};
|
||||
use ruma::api::error::ErrorKind;
|
||||
use tower_http::cors::{self, CorsLayer};
|
||||
|
||||
pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) {
|
||||
let router = Router::<state::State>::new();
|
||||
@@ -15,7 +14,6 @@ pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) {
|
||||
// is dropped.
|
||||
let (state, guard) = unsafe { state::create(services.clone()) };
|
||||
let router = conduwuit_api::router::build(router, state)
|
||||
.layer(api_cors_layer())
|
||||
.merge(conduwuit_web::build(services))
|
||||
.fallback(not_found)
|
||||
.with_state(state);
|
||||
@@ -26,29 +24,3 @@ pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) {
|
||||
async fn not_found(_uri: Uri) -> impl IntoResponse {
|
||||
Error::Request(ErrorKind::Unrecognized, "not found :(".into(), StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
fn api_cors_layer() -> CorsLayer {
|
||||
const METHODS: [Method; 7] = [
|
||||
Method::GET,
|
||||
Method::HEAD,
|
||||
Method::PATCH,
|
||||
Method::POST,
|
||||
Method::PUT,
|
||||
Method::DELETE,
|
||||
Method::OPTIONS,
|
||||
];
|
||||
|
||||
let headers: [HeaderName; 5] = [
|
||||
header::ORIGIN,
|
||||
HeaderName::from_lowercase(b"x-requested-with").unwrap(),
|
||||
header::CONTENT_TYPE,
|
||||
header::ACCEPT,
|
||||
header::AUTHORIZATION,
|
||||
];
|
||||
|
||||
CorsLayer::new()
|
||||
.allow_origin(cors::Any)
|
||||
.allow_methods(METHODS)
|
||||
.allow_headers(headers)
|
||||
.max_age(Duration::from_hours(24))
|
||||
}
|
||||
@@ -30,7 +30,6 @@ console = [
|
||||
"dep:rustyline-async",
|
||||
"dep:termimad",
|
||||
]
|
||||
element_hacks = []
|
||||
gzip_compression = [
|
||||
"conduwuit-core/gzip_compression",
|
||||
"reqwest/gzip",
|
||||
@@ -131,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]
|
||||
@@ -144,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"] }
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,10 @@ use std::{
|
||||
collections::BTreeSet,
|
||||
error::Error,
|
||||
fmt::{Debug, Display},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
use regex::regex;
|
||||
use ruma::{OwnedDeviceId, OwnedUserId, api::OAuthClientScope};
|
||||
use ruma::{OwnedDeviceId, api::OAuthClientScope};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
@@ -27,8 +26,6 @@ pub struct AuthorizationCodeQuery {
|
||||
pub code_challenge_method: CodeChallengeMethod,
|
||||
#[serde(default)]
|
||||
pub prompt: Option<Prompt>,
|
||||
#[serde(default)]
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
@@ -41,8 +38,6 @@ pub struct AuthorizationCodeResponse {
|
||||
pub struct DeviceCodeRequest {
|
||||
pub client_id: String,
|
||||
pub scope: RawScopes,
|
||||
#[serde(default, rename = "org.matrix.msc4198.login_hint")]
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
@@ -58,8 +53,6 @@ pub struct DeviceCodeResponse {
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct DeviceCodeVerifyQuery {
|
||||
pub user_code: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "core::ops::Not::not")]
|
||||
pub ignore_login_hint: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
@@ -181,30 +174,6 @@ impl RawScopes {
|
||||
}
|
||||
}
|
||||
|
||||
pub enum LoginHint {
|
||||
Mxid(OwnedUserId),
|
||||
}
|
||||
|
||||
impl FromStr for LoginHint {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s.split_once(':') {
|
||||
| Some(("mxid", user_id)) if let Ok(user_id) = user_id.parse::<OwnedUserId>() =>
|
||||
Ok(Self::Mxid(user_id)),
|
||||
| _ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for LoginHint {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
| Self::Mxid(user_id) => write!(f, "mxid:{user_id}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, Clone)]
|
||||
pub struct OAuthError {
|
||||
pub error: ErrorCode,
|
||||
|
||||
@@ -135,7 +135,6 @@ struct PendingDeviceCodeGrant {
|
||||
requested_scopes: RequestedScopes,
|
||||
client_name: Option<String>,
|
||||
client_id: String,
|
||||
login_hint: Option<String>,
|
||||
requested_at: SystemTime,
|
||||
}
|
||||
|
||||
@@ -166,7 +165,6 @@ pub struct DeviceCodeGrantInfo {
|
||||
pub device_code: String,
|
||||
pub client_metadata: ClientMetadata,
|
||||
pub requested_scopes: RequestedScopes,
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
/// A time-limited grant for a client to perform some sensitive action.
|
||||
@@ -424,7 +422,6 @@ impl Service {
|
||||
requested_scopes,
|
||||
client_name: client_metadata.client_name,
|
||||
client_id: query.client_id,
|
||||
login_hint: query.login_hint,
|
||||
requested_at: SystemTime::now(),
|
||||
};
|
||||
|
||||
@@ -445,7 +442,7 @@ impl Service {
|
||||
&self,
|
||||
supplied_user_code: &str,
|
||||
) -> Option<DeviceCodeGrantInfo> {
|
||||
let (device_code, client_id, requested_scopes, login_hint) = {
|
||||
let (device_code, client_id, requested_scopes) = {
|
||||
let pending_grants = self.pending_device_code_grants.lock();
|
||||
|
||||
let (device_code, grant) = pending_grants
|
||||
@@ -454,12 +451,7 @@ impl Service {
|
||||
matches!(&grant.state, DeviceCodeGrantState::Unverified { user_code } if user_code == supplied_user_code)
|
||||
})?;
|
||||
|
||||
(
|
||||
device_code.clone(),
|
||||
grant.client_id.clone(),
|
||||
grant.requested_scopes.clone(),
|
||||
grant.login_hint.clone(),
|
||||
)
|
||||
(device_code.clone(), grant.client_id.clone(), grant.requested_scopes.clone())
|
||||
};
|
||||
|
||||
let client_metadata = self
|
||||
@@ -471,7 +463,6 @@ impl Service {
|
||||
device_code,
|
||||
client_metadata,
|
||||
requested_scopes,
|
||||
login_hint,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+158
-179
@@ -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,40 +252,32 @@ impl Service {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn begin_session(
|
||||
&self,
|
||||
prompt: Option<CoreAuthPrompt>,
|
||||
login_hint: Option<&UserId>,
|
||||
) -> (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()
|
||||
});
|
||||
|
||||
if let Some(user_id) = login_hint
|
||||
&& config.supply_login_hint
|
||||
{
|
||||
auth_url = auth_url
|
||||
.set_login_hint(openidconnect::LoginHint::new(user_id.localpart().to_owned()));
|
||||
}
|
||||
|
||||
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(
|
||||
@@ -297,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(¤t);
|
||||
|
||||
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> {
|
||||
@@ -376,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>()
|
||||
{
|
||||
@@ -402,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())
|
||||
{
|
||||
@@ -446,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)
|
||||
@@ -456,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
|
||||
@@ -476,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();
|
||||
@@ -486,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;
|
||||
};
|
||||
|
||||
@@ -75,8 +75,7 @@ impl Service {
|
||||
"lazy loading should be enabled by your options"
|
||||
);
|
||||
|
||||
let include_redundant = cfg!(feature = "element_hacks")
|
||||
|| ctx.options.is_some_and(Options::include_redundant_members);
|
||||
let include_redundant = ctx.options.is_some_and(Options::include_redundant_members);
|
||||
|
||||
let witness = self
|
||||
.witness(ctx, senders.iter().map(AsRef::as_ref))
|
||||
|
||||
@@ -15,10 +15,7 @@ use futures::{FutureExt, Stream, StreamExt};
|
||||
use lettre::Address;
|
||||
use ruma::{
|
||||
MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, UserId,
|
||||
api::client::{
|
||||
profile::PropagateTo,
|
||||
uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
|
||||
},
|
||||
api::client::profile::PropagateTo,
|
||||
events::{
|
||||
GlobalAccountDataEventType, ignored_user_list::IgnoredUserListEvent,
|
||||
invite_permission_config::InvitePermissionAction, push_rules::PushRulesEvent,
|
||||
@@ -724,33 +721,6 @@ impl super::Service {
|
||||
Ok(user_id)
|
||||
}
|
||||
|
||||
/// Look up a user identifier. If a user ID is returned, it will be local to
|
||||
/// this server, but may refer to a nonexistent account.
|
||||
pub async fn lookup_by_identifier(&self, identifier: UserIdentifier) -> Option<OwnedUserId> {
|
||||
match identifier {
|
||||
| UserIdentifier::Email(EmailUserIdentifier { address, .. }) => {
|
||||
let address = address.parse().ok()?;
|
||||
|
||||
let localpart = self
|
||||
.services
|
||||
.threepid
|
||||
.get_localpart_for_email(&address)
|
||||
.await?;
|
||||
|
||||
Some(
|
||||
UserId::parse(format!(
|
||||
"@{localpart}:{}",
|
||||
self.services.globals.server_name()
|
||||
))
|
||||
.unwrap(),
|
||||
)
|
||||
},
|
||||
| UserIdentifier::Matrix(MatrixUserIdentifier { user, .. }) =>
|
||||
UserId::parse_with_server_name(user, self.services.globals.server_name()).ok(),
|
||||
| _ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an OpenID token, which can be used to prove that a user has
|
||||
/// access to an account (primarily for integrations)
|
||||
pub fn create_openid_token(&self, user_id: &UserId, token: &str) -> Result<u64> {
|
||||
|
||||
@@ -12,7 +12,7 @@ pub use account::{AccessTokenStatus, AccountStatus};
|
||||
use conduwuit::{Err, Error, Result, err, utils};
|
||||
use database::Map;
|
||||
pub use device::{DeviceToken, PreviousTokenAction};
|
||||
pub use profile::{ProfileFieldChange, ProfileQuerier};
|
||||
pub use profile::ProfileFieldChange;
|
||||
use ruma::{UserId, api::error::ErrorKind, encryption::CrossSigningKey, serde::Raw};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
|
||||
@@ -39,30 +39,6 @@ impl ProfileFieldChange {
|
||||
}
|
||||
}
|
||||
|
||||
/// The entity querying a user's profile.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub enum ProfileQuerier<'id> {
|
||||
/// The user owning the profile. This variant exists to improve the
|
||||
/// ergonomics of code that looks up a user's own profile, so the user's
|
||||
/// ID doesn't need to be passed twice.
|
||||
Owner,
|
||||
/// Another user, possibly but not necessarily the user owning the profile.
|
||||
Other(&'id UserId),
|
||||
/// An anonymous entity.
|
||||
#[default]
|
||||
Anonymous,
|
||||
}
|
||||
|
||||
impl<'id> From<Option<&'id UserId>> for ProfileQuerier<'id> {
|
||||
fn from(value: Option<&'id UserId>) -> Self {
|
||||
if let Some(user_id) = value {
|
||||
Self::Other(user_id)
|
||||
} else {
|
||||
Self::Anonymous
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Service {
|
||||
pub async fn set_profile_field(
|
||||
&self,
|
||||
@@ -384,31 +360,4 @@ impl super::Service {
|
||||
.ready_for_each(|(key, _)| self.set_profile_key(user_id, &key, None))
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Check if a user can access another user's profile.
|
||||
// This function doesn't do much of anything right now, but future MSCs that
|
||||
// add profile access controls should be implemented here.
|
||||
pub fn user_can_see_profile(
|
||||
&self,
|
||||
target_user: &UserId,
|
||||
querying_user: ProfileQuerier<'_>,
|
||||
) -> impl Future<Output = bool> {
|
||||
std::future::ready(match querying_user {
|
||||
| ProfileQuerier::Anonymous => {
|
||||
// For unauthenticated requests we check the relevant config
|
||||
// option.
|
||||
!self.services.config.require_auth_for_profile_requests
|
||||
},
|
||||
| ProfileQuerier::Other(querying_user) if querying_user != target_user => {
|
||||
// Currently users can't control their own profile visibility,
|
||||
// so we always return true for authenticated
|
||||
// requests from other users.
|
||||
true
|
||||
},
|
||||
| ProfileQuerier::Owner | ProfileQuerier::Other(_) => {
|
||||
// Users can always query their own profile.
|
||||
true
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use axum::{Extension, Router, extract::State, routing::on};
|
||||
use conduwuit_service::{oauth::OAuthTicket, users::ProfileQuerier};
|
||||
use conduwuit_service::oauth::OAuthTicket;
|
||||
|
||||
use crate::{
|
||||
extract::PostForm,
|
||||
@@ -33,8 +33,7 @@ async fn route_cross_signing_reset(
|
||||
PostForm(form): PostForm<()>,
|
||||
) -> Result {
|
||||
let user_id = user.expect_recent(LoginTarget::CrossSigningReset)?;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
|
||||
if form.is_some() {
|
||||
services
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use axum::{Extension, Router, extract::State, routing::on};
|
||||
use conduwuit_api::client::full_user_deactivate;
|
||||
use conduwuit_service::users::ProfileQuerier;
|
||||
use futures::StreamExt;
|
||||
use ruma::{OwnedRoomId, OwnedUserId, UserId};
|
||||
use tower_sessions::Session;
|
||||
@@ -66,8 +65,7 @@ async fn route_deactivate(
|
||||
PostForm(form): PostForm<DeactivateForm>,
|
||||
) -> Result {
|
||||
let user_id = user.expect_recent(LoginTarget::Deactivate)?;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
|
||||
let body = {
|
||||
if !services.config.allow_deactivation || services.oidc.enabled() {
|
||||
|
||||
@@ -4,9 +4,7 @@ use axum::{
|
||||
routing::{get, on, post},
|
||||
};
|
||||
use conduwuit_core::warn;
|
||||
use conduwuit_service::{
|
||||
mailer::messages, threepid::session::ValidationSessions, users::ProfileQuerier,
|
||||
};
|
||||
use conduwuit_service::{mailer::messages, threepid::session::ValidationSessions};
|
||||
use lettre::{Address, message::Mailbox};
|
||||
use ruma::{ClientSecret, OwnedClientSecret, OwnedSessionId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -90,7 +88,7 @@ async fn route_change_email(
|
||||
let Some(form) = form else {
|
||||
return response!(ChangeEmail::new(
|
||||
context.clone(),
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await,
|
||||
UserCard::for_local_user(&services, user_id.clone()).await,
|
||||
services
|
||||
.threepid
|
||||
.get_email_for_localpart(user_id.localpart())
|
||||
@@ -136,7 +134,7 @@ async fn route_change_email(
|
||||
|
||||
response!(ChangeEmailValidate::new(
|
||||
context,
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await,
|
||||
UserCard::for_local_user(&services, user_id).await,
|
||||
ChangeEmailValidateBody::ValidationPending {
|
||||
session_id,
|
||||
client_secret,
|
||||
@@ -160,8 +158,7 @@ async fn get_change_email_validate(
|
||||
user: User,
|
||||
) -> Result {
|
||||
let user_id = user.expect(LoginTarget::ChangeEmail)?;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
|
||||
if !services.threepid.email_requirement().may_change() {
|
||||
return Err(WebError::Forbidden("You may not change your email address.".to_owned()));
|
||||
@@ -201,8 +198,7 @@ async fn post_delete_email(
|
||||
user: User,
|
||||
) -> Result {
|
||||
let user_id = user.expect(LoginTarget::ChangeEmail)?;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
|
||||
if !services.threepid.email_requirement().may_remove() {
|
||||
return Err(WebError::Forbidden("You may not remove your email address.".to_owned()));
|
||||
|
||||
@@ -6,9 +6,8 @@ use axum::{
|
||||
response::{IntoResponse, Redirect},
|
||||
routing::{get, on},
|
||||
};
|
||||
use conduwuit_core::{error, result::FlatOk};
|
||||
use conduwuit_service::{oauth::grant::LoginHint, users::ProfileQuerier};
|
||||
use openidconnect::core::CoreAuthPrompt;
|
||||
use conduwuit_api::client::handle_login;
|
||||
use openid::Prompt;
|
||||
use ruma::{
|
||||
OwnedUserId,
|
||||
api::client::uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
|
||||
@@ -76,44 +75,27 @@ struct LoginForm {
|
||||
async fn route_login(
|
||||
State(services): State<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
Expect(Query(LoginQuery { next, reauthenticate, intent, login_hint })): Expect<
|
||||
Query<LoginQuery>,
|
||||
>,
|
||||
Expect(Query(LoginQuery { next, reauthenticate, intent })): Expect<Query<LoginQuery>>,
|
||||
session_store: Session,
|
||||
user: User<true>,
|
||||
PostForm(form): PostForm<LoginForm>,
|
||||
) -> Result {
|
||||
let current_user = user.into_session().map(|session| session.user_id);
|
||||
let login_hint = login_hint.as_deref().map(str::parse::<LoginHint>).flat_ok();
|
||||
|
||||
if let Some(LoginHint::Mxid(hint_user)) = &login_hint
|
||||
&& !services.globals.user_is_local(hint_user)
|
||||
{
|
||||
return Err(WebError::BadRequest("Login hint is not a local user.".to_owned()));
|
||||
}
|
||||
let user_id = user.into_session().map(|session| session.user_id);
|
||||
|
||||
let login_type = if services.oidc.enabled() {
|
||||
let prompt = match intent {
|
||||
| Some(LoginIntent::SwitchAccounts) => Some(CoreAuthPrompt::SelectAccount),
|
||||
| _ if reauthenticate => Some(CoreAuthPrompt::Consent),
|
||||
| _ => None,
|
||||
};
|
||||
|
||||
let login_hint = if let Some(LoginHint::Mxid(user_id)) = &login_hint {
|
||||
Some(user_id.as_ref())
|
||||
} else {
|
||||
current_user.as_deref()
|
||||
};
|
||||
|
||||
let (session, redirect_url) = services.oidc.begin_session(prompt, login_hint).await;
|
||||
let (session, redirect_url) = services
|
||||
.oidc
|
||||
.begin_session(match intent {
|
||||
| Some(LoginIntent::SwitchAccounts) => Some(Prompt::SelectAccount),
|
||||
| _ if reauthenticate => Some(Prompt::Consent),
|
||||
| _ => None,
|
||||
})
|
||||
.await;
|
||||
|
||||
session_store
|
||||
.insert(OIDC_SESSION_ID_KEY, OidcSession {
|
||||
next: next.clone().unwrap_or_default(),
|
||||
state: OidcSessionState::CodeExchange {
|
||||
expected_user: current_user.clone(),
|
||||
session,
|
||||
},
|
||||
state: OidcSessionState::CodeExchange { expected_user: user_id.clone(), session },
|
||||
})
|
||||
.await
|
||||
.expect("should be able to serialize OIDC session");
|
||||
@@ -133,28 +115,17 @@ async fn route_login(
|
||||
}
|
||||
};
|
||||
|
||||
let body = match (¤t_user, &login_hint) {
|
||||
| (None, None) => LoginBody::Unauthenticated {
|
||||
let body = match &user_id {
|
||||
| None => LoginBody::Unauthenticated {
|
||||
server_name: services.globals.server_name().to_string(),
|
||||
next: next.clone(),
|
||||
},
|
||||
| (None, Some(LoginHint::Mxid(new_user))) => {
|
||||
let user_card = UserCard::for_local_user(
|
||||
&services,
|
||||
new_user.to_owned(),
|
||||
ProfileQuerier::Anonymous,
|
||||
)
|
||||
.await;
|
||||
|
||||
LoginBody::Authenticated { user_card }
|
||||
},
|
||||
| (Some(user_id), _) => {
|
||||
| Some(user_id) => {
|
||||
if !reauthenticate {
|
||||
return response!(Redirect::to(&next.unwrap_or_default().target_path()));
|
||||
}
|
||||
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.to_owned()).await;
|
||||
|
||||
LoginBody::Authenticated { user_card }
|
||||
},
|
||||
@@ -163,10 +134,41 @@ async fn route_login(
|
||||
let mut template = Login::new(context, body, login_type, None);
|
||||
|
||||
if let Some(form) = form {
|
||||
let user_id = match perform_login(&services, current_user, login_hint, form).await {
|
||||
let login_result = match (user_id, form.identifier) {
|
||||
| (Some(user_id), _) => {
|
||||
// The user is already authenticated, we need to check their
|
||||
// password
|
||||
services
|
||||
.users
|
||||
.check_password(&user_id, &form.password)
|
||||
.await
|
||||
},
|
||||
| (None, Some(identifier)) => {
|
||||
// The user isn't authenticated, we need to log them in
|
||||
let identifier = if identifier.parse::<lettre::Address>().is_ok() {
|
||||
UserIdentifier::Email(EmailUserIdentifier::new(identifier))
|
||||
} else {
|
||||
UserIdentifier::Matrix(MatrixUserIdentifier::new(identifier))
|
||||
};
|
||||
|
||||
handle_login(&services, Some(&identifier), &form.password, None).await
|
||||
},
|
||||
| (None, None) => {
|
||||
// The user isn't authenticated and didn't supply an identity
|
||||
return response!(WebError::BadRequest("No identity provided".to_owned()));
|
||||
},
|
||||
};
|
||||
|
||||
let user_id = match login_result {
|
||||
| Ok(user_id) => user_id,
|
||||
| Err(err) => {
|
||||
template.login_error = Some(err);
|
||||
let error_message = if let conduwuit_core::Error::Request(_, message, _) = err {
|
||||
message.into_owned()
|
||||
} else {
|
||||
"Internal login error".to_owned()
|
||||
};
|
||||
|
||||
template.login_error = Some(error_message);
|
||||
return response!(template);
|
||||
},
|
||||
};
|
||||
@@ -184,50 +186,6 @@ async fn route_login(
|
||||
response!(template)
|
||||
}
|
||||
|
||||
async fn perform_login(
|
||||
services: &crate::State,
|
||||
current_user: Option<OwnedUserId>,
|
||||
login_hint: Option<LoginHint>,
|
||||
form: LoginForm,
|
||||
) -> Result<OwnedUserId, String> {
|
||||
let logging_in_user = if let Some(current_user) = current_user {
|
||||
current_user
|
||||
} else if let Some(LoginHint::Mxid(hint_user)) = login_hint {
|
||||
hint_user
|
||||
} else if let Some(identifier) = form.identifier {
|
||||
let identifier = if identifier.parse::<lettre::Address>().is_ok() {
|
||||
UserIdentifier::Email(EmailUserIdentifier::new(identifier))
|
||||
} else {
|
||||
UserIdentifier::Matrix(MatrixUserIdentifier::new(identifier))
|
||||
};
|
||||
|
||||
if let Some(identified_user) = services.users.lookup_by_identifier(identifier).await {
|
||||
identified_user
|
||||
} else {
|
||||
return Err("Failed to parse username or email address.".to_owned());
|
||||
}
|
||||
} else {
|
||||
return Err("No identity provided.".to_owned());
|
||||
};
|
||||
|
||||
if services.users.is_login_disabled(&logging_in_user).await {
|
||||
return Err("This account is blocked from logging in.".to_owned());
|
||||
}
|
||||
|
||||
match services
|
||||
.users
|
||||
.check_password(&logging_in_user, &form.password)
|
||||
.await
|
||||
{
|
||||
| Ok(user_id) => Ok(user_id),
|
||||
| Err(conduwuit_core::Error::Request(_, message, _)) => Err(message.into_owned()),
|
||||
| Err(err) => {
|
||||
error!(?logging_in_user, "Internal error logging in: {err}");
|
||||
Err("Internal error.".to_owned())
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_logout(session: Session, RawQuery(query): RawQuery) -> impl IntoResponse {
|
||||
let _ = session.remove::<OwnedUserId>(User::KEY).await;
|
||||
|
||||
|
||||
@@ -5,12 +5,11 @@ use axum::{
|
||||
routing::get,
|
||||
};
|
||||
use conduwuit_core::utils::{IterStream, ReadyExt, stream::TryExpect};
|
||||
use conduwuit_service::{threepid::EmailRequirement, users::ProfileQuerier};
|
||||
use conduwuit_service::threepid::EmailRequirement;
|
||||
use futures::StreamExt;
|
||||
use ruma::{
|
||||
OwnedClientSecret, OwnedDeviceId, OwnedSessionId,
|
||||
api::client::discovery::get_authorization_server_metadata::v1::AccountManagementAction,
|
||||
assign,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -20,10 +19,9 @@ use crate::{
|
||||
pages::{
|
||||
Result, TemplateContext,
|
||||
components::{DeviceCard, DeviceCardStyle, UserCard},
|
||||
switch_account::{LoginHintQuery, prompt_to_switch_account},
|
||||
},
|
||||
response,
|
||||
session::{LoginQuery, LoginTarget, User},
|
||||
session::{LoginTarget, User},
|
||||
template,
|
||||
};
|
||||
|
||||
@@ -84,8 +82,7 @@ async fn get_account(
|
||||
) -> Result {
|
||||
let user_id = user.expect(LoginTarget::Account)?;
|
||||
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
|
||||
if services.users.is_locked(&user_id).await.unwrap() {
|
||||
return response!(Account::new(context, user_card, AccountBody::Locked));
|
||||
@@ -141,49 +138,15 @@ async fn get_account(
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub(crate) struct AccountDeeplinkQuery {
|
||||
pub action: Option<AccountManagementAction>,
|
||||
pub device_id: Option<OwnedDeviceId>,
|
||||
#[serde(default)]
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
impl LoginHintQuery for AccountDeeplinkQuery {
|
||||
fn into_login_target(self) -> LoginTarget { LoginTarget::AccountDeeplink(self) }
|
||||
|
||||
fn suppress_login_hint(&self) -> Self { assign!(self.clone(), { login_hint: None }) }
|
||||
#[derive(Deserialize)]
|
||||
struct AccountDeeplinkQuery {
|
||||
action: Option<AccountManagementAction>,
|
||||
device_id: Option<OwnedDeviceId>,
|
||||
}
|
||||
|
||||
async fn get_account_deeplink(
|
||||
State(services): State<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
Expect(Query(query)): Expect<Query<AccountDeeplinkQuery>>,
|
||||
user: User<true>,
|
||||
) -> Result {
|
||||
if let Some(current_user) = user.into_session() {
|
||||
if let Some(switcher) = prompt_to_switch_account(
|
||||
&services,
|
||||
context,
|
||||
¤t_user.user_id,
|
||||
query.login_hint.as_deref(),
|
||||
&query,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(switcher);
|
||||
}
|
||||
} else {
|
||||
// We redirect to the login page ourselves instead of letting the
|
||||
// handler for the deeplink's target do it so that we can pass the login
|
||||
// hint to the login page.
|
||||
return Err(WebError::LoginRequired(LoginQuery {
|
||||
next: Some(LoginTarget::AccountDeeplink(query.suppress_login_hint())),
|
||||
login_hint: query.login_hint,
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
|
||||
let redirect_target = match query.action.unwrap_or(AccountManagementAction::Profile) {
|
||||
| AccountManagementAction::AccountDeactivate => "deactivate".to_owned(),
|
||||
| AccountManagementAction::CrossSigningReset => "cross_signing_reset".to_owned(),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use axum::{Extension, Router, extract::State, routing::on};
|
||||
use conduwuit_service::users::{HashedPassword, ProfileQuerier};
|
||||
use conduwuit_service::users::HashedPassword;
|
||||
use ruma::UserId;
|
||||
use validator::{Validate, ValidationError, ValidationErrors};
|
||||
|
||||
@@ -73,8 +73,7 @@ async fn route_change_password(
|
||||
}
|
||||
|
||||
let user_id = user.expect(LoginTarget::ChangePassword)?;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
|
||||
let body = if let Some(form) = form {
|
||||
match change_password(&services, &user_id, form).await? {
|
||||
|
||||
@@ -5,9 +5,7 @@ use axum::{
|
||||
};
|
||||
use conduwuit_core::warn;
|
||||
use conduwuit_service::{
|
||||
mailer::messages,
|
||||
threepid::session::ValidationSessions,
|
||||
users::{HashedPassword, ProfileQuerier},
|
||||
mailer::messages, threepid::session::ValidationSessions, users::HashedPassword,
|
||||
};
|
||||
use lettre::{Address, message::Mailbox};
|
||||
use ruma::{ClientSecret, OwnedClientSecret, OwnedSessionId, UserId};
|
||||
@@ -209,8 +207,7 @@ async fn route_reset_password_validate(
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
|
||||
if let Some(form) = form {
|
||||
if let Err(err) = form.validate() {
|
||||
|
||||
@@ -2,9 +2,7 @@ use std::{collections::BTreeSet, time::SystemTime};
|
||||
|
||||
use askama::{Template, filters::HtmlSafe};
|
||||
use conduwuit_core::utils;
|
||||
use conduwuit_service::{
|
||||
Services, oauth::client_metadata::ClientMetadata, users::ProfileQuerier,
|
||||
};
|
||||
use conduwuit_service::{Services, oauth::client_metadata::ClientMetadata};
|
||||
use ruma::{
|
||||
OwnedDeviceId, OwnedUserId, UserId,
|
||||
api::{OAuthClientScope, client::device::Device},
|
||||
@@ -27,39 +25,18 @@ pub(super) struct Avatar {
|
||||
impl HtmlSafe for Avatar {}
|
||||
|
||||
impl Avatar {
|
||||
pub(super) async fn for_local_user(
|
||||
services: &Services,
|
||||
user_id: &UserId,
|
||||
querying_user: ProfileQuerier<'_>,
|
||||
) -> Self {
|
||||
let avatar_type = {
|
||||
let localpart_initial = user_id
|
||||
.localpart()
|
||||
.chars()
|
||||
.next()
|
||||
.unwrap()
|
||||
.to_ascii_uppercase();
|
||||
pub(super) async fn for_local_user(services: &Services, user_id: &UserId) -> Self {
|
||||
let display_name = services.users.displayname(user_id).await.ok();
|
||||
|
||||
if services
|
||||
.users
|
||||
.user_can_see_profile(user_id, querying_user)
|
||||
.await
|
||||
{
|
||||
let display_name = services.users.displayname(user_id).await.ok();
|
||||
|
||||
if services.users.avatar_url(user_id).await.is_ok() {
|
||||
AvatarType::Image(profile_media_url(user_id, "avatar_url"))
|
||||
} else if let Some(initial) = display_name
|
||||
.as_ref()
|
||||
.and_then(|display_name| display_name.chars().next())
|
||||
{
|
||||
AvatarType::Initial(initial)
|
||||
} else {
|
||||
AvatarType::Initial(localpart_initial)
|
||||
}
|
||||
} else {
|
||||
AvatarType::Initial(localpart_initial)
|
||||
}
|
||||
let avatar_type = if services.users.avatar_url(user_id).await.is_ok() {
|
||||
AvatarType::Image(profile_media_url(user_id, "avatar_url"))
|
||||
} else if let Some(initial) = display_name
|
||||
.as_ref()
|
||||
.and_then(|display_name| display_name.chars().next())
|
||||
{
|
||||
AvatarType::Initial(initial)
|
||||
} else {
|
||||
AvatarType::Initial(user_id.localpart().chars().next().unwrap())
|
||||
};
|
||||
|
||||
Self { avatar_type }
|
||||
@@ -120,30 +97,14 @@ impl HtmlSafe for UserCard {}
|
||||
impl UserCard {
|
||||
const BANNER_KEY: &str = "chat.commet.profile_banner";
|
||||
|
||||
pub(super) async fn for_local_user(
|
||||
services: &Services,
|
||||
user_id: OwnedUserId,
|
||||
querying_user: ProfileQuerier<'_>,
|
||||
) -> Self {
|
||||
let can_see_profile = services
|
||||
pub(super) async fn for_local_user(services: &Services, user_id: OwnedUserId) -> Self {
|
||||
let display_name = services.users.displayname(&user_id).await.ok();
|
||||
let avatar = Avatar::for_local_user(services, &user_id).await;
|
||||
let banner = if services
|
||||
.users
|
||||
.user_can_see_profile(&user_id, querying_user)
|
||||
.await;
|
||||
|
||||
let avatar = Avatar::for_local_user(services, &user_id, querying_user).await;
|
||||
|
||||
let display_name = if can_see_profile {
|
||||
services.users.displayname(&user_id).await.ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let banner = if can_see_profile
|
||||
&& services
|
||||
.users
|
||||
.get_local_profile_field(&user_id, Self::BANNER_KEY.into())
|
||||
.await
|
||||
.is_some()
|
||||
.get_local_profile_field(&user_id, Self::BANNER_KEY.into())
|
||||
.await
|
||||
.is_some()
|
||||
{
|
||||
Some(profile_media_url(&user_id, Self::BANNER_KEY))
|
||||
} else {
|
||||
|
||||
@@ -25,14 +25,13 @@ async fn get_profile_media(
|
||||
State(services): State<crate::State>,
|
||||
Expect(Path(ProfileMediaPath { user_id, field })): Expect<Path<ProfileMediaPath>>,
|
||||
headers: HeaderMap,
|
||||
querying_user: User<true>,
|
||||
requesting_user: User<true>,
|
||||
) -> Result {
|
||||
let querying_user = querying_user.into_session().map(|session| session.user_id);
|
||||
|
||||
if !services
|
||||
.users
|
||||
.user_can_see_profile(&user_id, querying_user.as_deref().into())
|
||||
.await
|
||||
if requesting_user
|
||||
.into_session()
|
||||
.map(|session| session.user_id)
|
||||
.as_ref()
|
||||
!= Some(&user_id)
|
||||
{
|
||||
return Err(WebError::Forbidden(
|
||||
"You may not access this user's profile media.".to_owned(),
|
||||
|
||||
@@ -20,7 +20,6 @@ pub(super) mod media;
|
||||
pub(super) mod oauth;
|
||||
pub(super) mod oidc;
|
||||
pub(super) mod resources;
|
||||
mod switch_account;
|
||||
pub(super) mod threepid;
|
||||
|
||||
type Result<T = Response, E = WebError> = std::result::Result<T, E>;
|
||||
|
||||
@@ -4,15 +4,12 @@ use axum::{
|
||||
response::Redirect,
|
||||
routing::on,
|
||||
};
|
||||
use conduwuit_service::{
|
||||
oauth::{
|
||||
SessionInfo,
|
||||
client_metadata::ClientMetadata,
|
||||
grant::{AuthorizationCodeQuery, DeviceCodeVerifyQuery, Prompt, RequestedScopes},
|
||||
},
|
||||
users::ProfileQuerier,
|
||||
use conduwuit_service::oauth::{
|
||||
SessionInfo,
|
||||
client_metadata::ClientMetadata,
|
||||
grant::{AuthorizationCodeQuery, DeviceCodeVerifyQuery, Prompt, RequestedScopes},
|
||||
};
|
||||
use ruma::{OwnedUserId, api::OAuthClientScope, assign};
|
||||
use ruma::{OwnedUserId, api::OAuthClientScope};
|
||||
use serde::{Deserialize, de::IgnoredAny};
|
||||
|
||||
use crate::{
|
||||
@@ -22,7 +19,6 @@ use crate::{
|
||||
GET_POST, Result, TemplateContext,
|
||||
account::register::{RegisterQuery, RequestedRegistrationFlow},
|
||||
components::{Avatar, ClientScopes, UserCard},
|
||||
switch_account::{LoginHintQuery, prompt_to_switch_account},
|
||||
},
|
||||
response,
|
||||
session::{LoginIntent, LoginQuery, LoginTarget, User},
|
||||
@@ -47,12 +43,6 @@ template! {
|
||||
}
|
||||
}
|
||||
|
||||
impl LoginHintQuery for AuthorizationCodeQuery {
|
||||
fn into_login_target(self) -> LoginTarget { LoginTarget::AuthorizationCode(self) }
|
||||
|
||||
fn suppress_login_hint(&self) -> Self { assign!(self.clone(), { login_hint: None }) }
|
||||
}
|
||||
|
||||
async fn route_authorization_code(
|
||||
State(services): State<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
@@ -64,7 +54,7 @@ async fn route_authorization_code(
|
||||
user.user_id
|
||||
} else {
|
||||
let is_first_run = services.firstrun.is_first_run();
|
||||
let next = LoginTarget::AuthorizationCode(query.suppress_login_hint());
|
||||
let next = LoginTarget::AuthorizationCode(query.clone());
|
||||
|
||||
let uri = if query
|
||||
.prompt
|
||||
@@ -91,7 +81,6 @@ async fn route_authorization_code(
|
||||
ROUTE_PREFIX,
|
||||
serde_urlencoded::to_string(LoginQuery {
|
||||
next: Some(next),
|
||||
login_hint: query.login_hint,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap()
|
||||
@@ -101,18 +90,6 @@ async fn route_authorization_code(
|
||||
return response!(Redirect::to(&uri));
|
||||
};
|
||||
|
||||
if let Some(switcher) = prompt_to_switch_account(
|
||||
&services,
|
||||
context.clone(),
|
||||
&user_id,
|
||||
query.login_hint.as_deref(),
|
||||
&query,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(switcher);
|
||||
}
|
||||
|
||||
if form.is_some() {
|
||||
let redirect_uri = services
|
||||
.oauth
|
||||
@@ -145,7 +122,7 @@ async fn route_authorization_code(
|
||||
scopes.retain(|scope| !existing_scopes.contains(scope));
|
||||
}
|
||||
|
||||
let user_avatar = Avatar::for_local_user(&services, &user_id, ProfileQuerier::Owner).await;
|
||||
let user_avatar = Avatar::for_local_user(&services, &user_id).await;
|
||||
|
||||
response!(Grant::new(
|
||||
context,
|
||||
@@ -190,12 +167,6 @@ enum DeviceCodeGrantBody {
|
||||
Success,
|
||||
}
|
||||
|
||||
impl LoginHintQuery for DeviceCodeVerifyQuery {
|
||||
fn into_login_target(self) -> LoginTarget { LoginTarget::DeviceCode(self) }
|
||||
|
||||
fn suppress_login_hint(&self) -> Self { assign!(self.clone(), { ignore_login_hint: true }) }
|
||||
}
|
||||
|
||||
async fn route_device_code(
|
||||
State(services): State<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
@@ -206,32 +177,19 @@ async fn route_device_code(
|
||||
let user_id = if let Some(user) = user.into_session() {
|
||||
user.user_id
|
||||
} else {
|
||||
let next = LoginTarget::DeviceCode(query.suppress_login_hint());
|
||||
|
||||
let login_hint = if let Some(user_code) = &query.user_code
|
||||
&& let Some(grant_info) = services.oauth.grant_info_for_user_code(user_code).await
|
||||
{
|
||||
grant_info.login_hint
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let next = LoginTarget::DeviceCode(query.clone());
|
||||
|
||||
let uri = format!(
|
||||
"{}/account/login?{}",
|
||||
ROUTE_PREFIX,
|
||||
serde_urlencoded::to_string(LoginQuery {
|
||||
next: Some(next),
|
||||
login_hint,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap()
|
||||
serde_urlencoded::to_string(LoginQuery { next: Some(next), ..Default::default() })
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
return response!(Redirect::to(&uri));
|
||||
};
|
||||
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
|
||||
match (form, query.user_code.clone()) {
|
||||
| (None, Some(user_code)) | (Some(DeviceCodeForm::Lookup { user_code }), _) => {
|
||||
@@ -244,19 +202,6 @@ async fn route_device_code(
|
||||
));
|
||||
};
|
||||
|
||||
if !query.ignore_login_hint
|
||||
&& let Some(switcher) = prompt_to_switch_account(
|
||||
&services,
|
||||
context.clone(),
|
||||
&user_id,
|
||||
grant_info.login_hint.as_deref(),
|
||||
&query,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(switcher);
|
||||
}
|
||||
|
||||
let RequestedScopes { device_id, mut scopes } = grant_info.requested_scopes;
|
||||
|
||||
let existing_session_info = if let Some(device_id) = &device_id {
|
||||
@@ -275,8 +220,7 @@ async fn route_device_code(
|
||||
scopes.retain(|scope| !existing_scopes.contains(scope));
|
||||
}
|
||||
|
||||
let user_avatar =
|
||||
Avatar::for_local_user(&services, &user_id, ProfileQuerier::Owner).await;
|
||||
let user_avatar = Avatar::for_local_user(&services, &user_id).await;
|
||||
|
||||
response!(Grant::new(
|
||||
context,
|
||||
|
||||
@@ -10,7 +10,6 @@ use conduwuit_api::client_ip::ClientIp;
|
||||
use conduwuit_service::{
|
||||
oauth::grant::AuthorizationCodeResponse,
|
||||
oidc::{ClaimedLocalUser, SessionCompletionStatus},
|
||||
users::ProfileQuerier,
|
||||
};
|
||||
use futures::FutureExt;
|
||||
use ruma::OwnedServerName;
|
||||
@@ -107,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 {
|
||||
@@ -120,12 +116,8 @@ async fn route_complete(
|
||||
.await
|
||||
{
|
||||
| Ok(ClaimedLocalUser::Existing(user_id)) => {
|
||||
let user_card = UserCard::for_local_user(
|
||||
&services,
|
||||
user_id.clone(),
|
||||
ProfileQuerier::Owner,
|
||||
)
|
||||
.await;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
|
||||
if let Some(password) = form.password {
|
||||
if services
|
||||
@@ -171,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()))?;
|
||||
@@ -185,12 +179,6 @@ async fn route_complete(
|
||||
.remove::<IgnoredAny>(OIDC_SESSION_ID_KEY)
|
||||
.await;
|
||||
|
||||
if services.users.is_login_disabled(&user_id).await {
|
||||
return Err(WebError::Forbidden(
|
||||
"This account is blocked from logging in.".to_owned(),
|
||||
));
|
||||
}
|
||||
|
||||
let user_session = UserSession { user_id, last_login: SystemTime::now() };
|
||||
|
||||
session_store
|
||||
|
||||
@@ -392,17 +392,6 @@ ul.list-group {
|
||||
}
|
||||
}
|
||||
|
||||
.button-group {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
|
||||
> a, button {
|
||||
text-align: center;
|
||||
flex: 1 fit-content;
|
||||
}
|
||||
}
|
||||
|
||||
.bi {
|
||||
display: inline-block;
|
||||
vertical-align: -.125em;
|
||||
|
||||
@@ -43,11 +43,6 @@
|
||||
font-weight: normal;
|
||||
font-size: small;
|
||||
font-family: monospace;
|
||||
|
||||
&:only-child {
|
||||
color: var(--text-color);
|
||||
font-size: inherit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,23 +92,3 @@
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.avatar-pair {
|
||||
justify-content: center;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
|
||||
.separator {
|
||||
align-self: center;
|
||||
margin-inline: 1em;
|
||||
color: var(--secondary);
|
||||
font-size: x-large;
|
||||
user-select: none;
|
||||
|
||||
svg {
|
||||
vertical-align: middle;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,23 @@
|
||||
.avatars {
|
||||
justify-content: center;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
|
||||
.separator {
|
||||
align-self: center;
|
||||
margin-inline: 1em;
|
||||
color: var(--secondary);
|
||||
font-size: x-large;
|
||||
user-select: none;
|
||||
|
||||
svg {
|
||||
vertical-align: middle;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.identity {
|
||||
margin-block: 1em;
|
||||
color: var(--secondary);
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
.account-chooser {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
|
||||
@media (max-width: 425px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
a {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-decoration: none;
|
||||
text-align: center;
|
||||
color: var(--text-color);
|
||||
|
||||
border: 1px solid var(--c1);
|
||||
border-radius: var(--border-radius-sm);
|
||||
|
||||
padding: 1rem 0;
|
||||
|
||||
.avatar {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
code {
|
||||
font-size: small;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background-color: var(--card-bg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use conduwuit_core::result::FlatOk;
|
||||
use conduwuit_service::{oauth::grant::LoginHint, users::ProfileQuerier};
|
||||
use ruma::UserId;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
pages::{TemplateContext, components::Avatar},
|
||||
session::{LoginQuery, LoginTarget},
|
||||
template,
|
||||
};
|
||||
|
||||
template! {
|
||||
struct SwitchAccount<'a> use "switch_account.html.j2" {
|
||||
current_user_avatar: Avatar,
|
||||
new_user_avatar: Avatar,
|
||||
current_user_name: String,
|
||||
new_user_name: String,
|
||||
current_user_id: &'a UserId,
|
||||
new_user_id: &'a UserId,
|
||||
switch_account_query: String,
|
||||
continue_query: String
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn prompt_to_switch_account<Query: LoginHintQuery>(
|
||||
services: &crate::State,
|
||||
context: TemplateContext,
|
||||
current_user: &UserId,
|
||||
login_hint: Option<&str>,
|
||||
query: &Query,
|
||||
) -> Option<Response> {
|
||||
let Some(LoginHint::Mxid(new_user)) = login_hint.map(str::parse).flat_ok() else {
|
||||
return None;
|
||||
};
|
||||
|
||||
if current_user == new_user {
|
||||
return None;
|
||||
}
|
||||
|
||||
let switch_account_query = serde_urlencoded::to_string(LoginQuery {
|
||||
next: Some(query.suppress_login_hint().into_login_target()),
|
||||
login_hint: Some(LoginHint::Mxid(new_user.clone()).to_string()),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let continue_query = serde_urlencoded::to_string(query.suppress_login_hint()).unwrap();
|
||||
|
||||
let can_see_new_user_profile = services
|
||||
.users
|
||||
.user_can_see_profile(&new_user, ProfileQuerier::Other(current_user))
|
||||
.await;
|
||||
|
||||
let current_user_name = services
|
||||
.users
|
||||
.displayname(current_user)
|
||||
.await
|
||||
.unwrap_or_else(|_| current_user.localpart().to_owned());
|
||||
let current_user_avatar =
|
||||
Avatar::for_local_user(services, current_user, ProfileQuerier::Owner).await;
|
||||
|
||||
let new_user_name = if can_see_new_user_profile {
|
||||
services
|
||||
.users
|
||||
.displayname(&new_user)
|
||||
.await
|
||||
.unwrap_or_else(|_| new_user.localpart().to_owned())
|
||||
} else {
|
||||
new_user.localpart().to_owned()
|
||||
};
|
||||
|
||||
let new_user_avatar =
|
||||
Avatar::for_local_user(services, &new_user, ProfileQuerier::Other(current_user)).await;
|
||||
|
||||
Some(
|
||||
SwitchAccount::new(
|
||||
context,
|
||||
current_user_avatar,
|
||||
new_user_avatar,
|
||||
current_user_name,
|
||||
new_user_name,
|
||||
current_user,
|
||||
&new_user,
|
||||
switch_account_query,
|
||||
continue_query,
|
||||
)
|
||||
.into_response(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A trait for query parameter structs that have a login hint.
|
||||
pub(super) trait LoginHintQuery: Serialize + Sync {
|
||||
/// Modify this query parameter struct to suppress
|
||||
/// the login hint. The resulting query should keep the
|
||||
/// page it belongs to from prompting the user to switch accounts.
|
||||
fn suppress_login_hint(&self) -> Self;
|
||||
|
||||
/// Wrap this query parameter struct in its particular variant of
|
||||
/// [`LoginTarget`].
|
||||
fn into_login_target(self) -> LoginTarget;
|
||||
}
|
||||
@@ -23,10 +23,3 @@
|
||||
<path fill-rule="evenodd" d="M1 11.5a.5.5 0 0 0 .5.5h11.793l-3.147 3.146a.5.5 0 0 0 .708.708l4-4a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 11H1.5a.5.5 0 0 0-.5.5m14-7a.5.5 0 0 1-.5.5H2.707l3.147 3.146a.5.5 0 1 1-.708.708l-4-4a.5.5 0 0 1 0-.708l4-4a.5.5 0 1 1 .708.708L2.707 4H14.5a.5.5 0 0 1 .5.5"/>
|
||||
</svg>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro box_arrow_right() %}
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-box-arrow-right" viewBox="0 0 16 16">
|
||||
<path fill-rule="evenodd" d="M10 12.5a.5.5 0 0 1-.5.5h-8a.5.5 0 0 1-.5-.5v-9a.5.5 0 0 1 .5-.5h8a.5.5 0 0 1 .5.5v2a.5.5 0 0 0 1 0v-2A1.5 1.5 0 0 0 9.5 2h-8A1.5 1.5 0 0 0 0 3.5v9A1.5 1.5 0 0 0 1.5 14h8a1.5 1.5 0 0 0 1.5-1.5v-2a.5.5 0 0 0-1 0z"/>
|
||||
<path fill-rule="evenodd" d="M15.854 8.354a.5.5 0 0 0 0-.708l-3-3a.5.5 0 0 0-.708.708L14.293 7.5H5.5a.5.5 0 0 0 0 1h8.793l-2.147 2.146a.5.5 0 0 0 .708.708z"/>
|
||||
</svg>
|
||||
{% endmacro %}
|
||||
@@ -13,7 +13,7 @@ Authorize client
|
||||
{% let client_name = client_metadata.client_name.as_deref().unwrap_or("Unknown application") %}
|
||||
<div class="panel narrow">
|
||||
<h1>Authorize {{ client_name }}</h1>
|
||||
<div class="avatar-pair">
|
||||
<div class="avatars">
|
||||
<div class="red-avatar">
|
||||
{{ user_avatar }}
|
||||
</div>
|
||||
@@ -24,7 +24,7 @@ Authorize client
|
||||
</div>
|
||||
|
||||
<div class="identity">
|
||||
Logged in as <code>{{ user_id }}</code>. <a href="{{ crate::ROUTE_PREFIX }}/account/logout?{{ logout_query }}">Switch accounts</a>
|
||||
Signed in as <code>{{ user_id }}</code>. <a href="{{ crate::ROUTE_PREFIX }}/account/logout?{{ logout_query }}">Switch accounts</a>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
{% extends "_layout.html.j2" %}
|
||||
{% import "_icons.html.j2" as icons %}
|
||||
|
||||
{%- block head -%}
|
||||
<link rel="stylesheet" href="{{ crate::ROUTE_PREFIX }}/resources/switch-account.css">
|
||||
{%- endblock -%}
|
||||
|
||||
{%- block title -%}
|
||||
Select an account
|
||||
{%- endblock -%}
|
||||
|
||||
{%- block content -%}
|
||||
<div class="panel narrow">
|
||||
<h1>Select an account</h1>
|
||||
|
||||
<p>
|
||||
Welcome back! Which account would you like to continue with?
|
||||
</p>
|
||||
|
||||
<div class="account-chooser red-avatar">
|
||||
<a href="?{{ continue_query }}">
|
||||
{{ current_user_avatar }}
|
||||
<span>Continue as <b>{{ current_user_name }}</b></span>
|
||||
<code>{{ current_user_id }}</code>
|
||||
</a>
|
||||
<a href="{{ crate::ROUTE_PREFIX }}/account/logout?{{ switch_account_query }}">
|
||||
{{ new_user_avatar }}
|
||||
<span>Continue as <b>{{ new_user_name }}</b></span>
|
||||
<code>{{ new_user_id }}</code>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{%- endblock -%}
|
||||
+6
-11
@@ -15,10 +15,7 @@ use ruma::{OwnedUserId, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tower_sessions::Session;
|
||||
|
||||
use crate::{
|
||||
ROUTE_PREFIX, WebError,
|
||||
pages::account::{AccountDeeplinkQuery, device::DevicePath},
|
||||
};
|
||||
use crate::{ROUTE_PREFIX, WebError, pages::account::device::DevicePath};
|
||||
|
||||
pub(crate) mod store;
|
||||
|
||||
@@ -30,8 +27,6 @@ pub(crate) struct LoginQuery {
|
||||
pub reauthenticate: bool,
|
||||
#[serde(default)]
|
||||
pub intent: Option<LoginIntent>,
|
||||
#[serde(default)]
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
@@ -40,7 +35,6 @@ pub(crate) enum LoginTarget {
|
||||
AuthorizationCode(AuthorizationCodeQuery),
|
||||
#[default]
|
||||
Account,
|
||||
AccountDeeplink(AccountDeeplinkQuery),
|
||||
ChangePassword,
|
||||
ChangeEmail,
|
||||
CrossSigningReset,
|
||||
@@ -63,8 +57,6 @@ impl LoginTarget {
|
||||
)
|
||||
.into(),
|
||||
| Self::Account => "account/".into(),
|
||||
| Self::AccountDeeplink(query) =>
|
||||
format!("account/deeplink?{}", serde_urlencoded::to_string(query).unwrap()).into(),
|
||||
| Self::ChangePassword => "account/password/change".into(),
|
||||
| Self::ChangeEmail => "account/email/change/".into(),
|
||||
| Self::CrossSigningReset => "account/cross_signing_reset".into(),
|
||||
@@ -125,11 +117,14 @@ impl<const ALLOW_LOCKED: bool> User<ALLOW_LOCKED> {
|
||||
|
||||
/// Extract the user ID, redirecting to the login page if the user isn't
|
||||
/// logged in.
|
||||
pub(crate) fn expect(self, or: LoginTarget) -> Result<OwnedUserId, WebError> {
|
||||
pub(crate) fn expect(self, or_else: LoginTarget) -> Result<OwnedUserId, WebError> {
|
||||
if let Some(session) = self.0 {
|
||||
Ok(session.user_id)
|
||||
} else {
|
||||
Err(WebError::LoginRequired(LoginQuery { next: Some(or), ..Default::default() }))
|
||||
Err(WebError::LoginRequired(LoginQuery {
|
||||
next: Some(or_else),
|
||||
..Default::default()
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user