mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-12-04 14:21:50 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eabed74d6e | ||
|
|
614f8adb48 | ||
|
|
304850147c |
No files matched your search
Generated
+56
-622
File diff suppressed because it is too large.
Load diff
@@ -403,9 +403,6 @@ default-features = false
|
|||||||
version = "0.11.0"
|
version = "0.11.0"
|
||||||
default-features = false
|
default-features = false
|
||||||
|
|
||||||
[workspace.dependencies.openidconnect]
|
|
||||||
version = "4.0.1"
|
|
||||||
|
|
||||||
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
|
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
|
||||||
[workspace.dependencies.opentelemetry]
|
[workspace.dependencies.opentelemetry]
|
||||||
version = "0.32.0"
|
version = "0.32.0"
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
Added support for linking an external identity provider with OIDC. Contributed by @ginger.
|
|
||||||
@@ -2028,96 +2028,3 @@
|
|||||||
# legacy authentication will be unable to log in.
|
# legacy authentication will be unable to log in.
|
||||||
#
|
#
|
||||||
#compatibility_mode = "hybrid"
|
#compatibility_mode = "hybrid"
|
||||||
|
|
||||||
#[global.oauth.oidc]
|
|
||||||
# Uncommenting this section will enable Continuwuity's support for
|
|
||||||
# authenticating users using an OpenID Connect-compatible identity provider.
|
|
||||||
# This is referred to as "delegated authentication".
|
|
||||||
#
|
|
||||||
# IMPORTANT NOTE: When delegated authentication is active, Continuwuity will behave as if
|
|
||||||
# the `global.oauth.compatibility_mode` setting is set to `exclusive`.
|
|
||||||
# Matrix clients which do not support OAuth login (also referred to as "next-gen auth") will NOT be able
|
|
||||||
# to log in while delegated authentication is active.
|
|
||||||
|
|
||||||
|
|
||||||
# The OIDC issuer URL. Continuwuity will use OpenID Connect Discovery to
|
|
||||||
# automatically fetch the identity provider's metadata from this URL.
|
|
||||||
# Generally you should set this to the base domain your identity provider
|
|
||||||
# runs on.
|
|
||||||
#
|
|
||||||
#discovery_url =
|
|
||||||
|
|
||||||
# The OAuth client ID for Continuwuity to use when communicating with the
|
|
||||||
# identity provider.
|
|
||||||
#
|
|
||||||
#client_id =
|
|
||||||
|
|
||||||
# The OAuth client secret for Continuwuity to use when communicating with
|
|
||||||
# the identity provider.
|
|
||||||
#
|
|
||||||
#client_secret =
|
|
||||||
|
|
||||||
# A path to a file which Continuwuity will read the client secret from.
|
|
||||||
# If this option is set, it will override `client_secret`.
|
|
||||||
#
|
|
||||||
# The server will fail to start if the file cannot be read.
|
|
||||||
#
|
|
||||||
#client_secret_file =
|
|
||||||
|
|
||||||
# Additional scopes Continuwuity should request from the IDP. This may be
|
|
||||||
# necessary to access certain claims. Continuwuity always requests the
|
|
||||||
# `openid` scope.
|
|
||||||
#
|
|
||||||
#additional_scopes = []
|
|
||||||
|
|
||||||
# Whether the user should be prompted to choose a localpart
|
|
||||||
# when signing in for the first time. If this is `false`, Continuwuity
|
|
||||||
# will attempt to use the value of the `preferred_username_claim`
|
|
||||||
# (see below) as the user's localpart. Authentication will
|
|
||||||
# fail if this claim is missing or is not a valid localpart.
|
|
||||||
#
|
|
||||||
#prompt_for_localpart = true
|
|
||||||
|
|
||||||
# The claim to use for the user's localpart, if `prompt_for_localpart` is
|
|
||||||
# false.
|
|
||||||
#
|
|
||||||
#preferred_username_claim = "preferred_username"
|
|
||||||
|
|
||||||
# The claim which will be used to set the user's email address,
|
|
||||||
# either on initial registration or on every login depending on
|
|
||||||
# the value of `profile_key_import_mode`. Continuwuity assumes that
|
|
||||||
# the IDP has taken care of verifying that the user controls the email
|
|
||||||
# address it provides.
|
|
||||||
#
|
|
||||||
# This option does nothing if SMTP is not configured.
|
|
||||||
#
|
|
||||||
# If this option is set, and `profile_key_import_mode` is `on_login`,
|
|
||||||
# users will not be able to change their email addresses themselves.
|
|
||||||
#
|
|
||||||
#email_claim = "email"
|
|
||||||
|
|
||||||
# Defines how claims returned from the IDP should be mapped to a user's
|
|
||||||
# profile data. The profile field named in each key will be set from the
|
|
||||||
# claim named in the corresponding value when the user first registers,
|
|
||||||
# and possibly on subsequent logins as well, depending on the value of
|
|
||||||
# `profile_key_import_mode` (see below).
|
|
||||||
#
|
|
||||||
# Per-room overrides to the user's display name or avatar will be
|
|
||||||
# preserved by the import process.
|
|
||||||
#
|
|
||||||
# SECURITY NOTE: If the `avatar_url` field is set, Continuwuity will
|
|
||||||
# perform a HTTP GET to the URL in the mapped claim and use the returned
|
|
||||||
# file as the user's profile picture. Make sure your users are not able
|
|
||||||
# to set the value of the mapped claim to an arbitrary URL.
|
|
||||||
#
|
|
||||||
#profile_key_map = { displayname = "name" }
|
|
||||||
|
|
||||||
# When profile keys should be imported from the IDP's claims.
|
|
||||||
#
|
|
||||||
# - "on_registration": Listed keys will be imported once, when the user
|
|
||||||
# logs in for the first time and their shadow account is created.
|
|
||||||
# - "on_login": Listed keys will be imported every time the user logs in.
|
|
||||||
# Additionally, users will not be able to manually edit any listed keys
|
|
||||||
# through their Matrix client.
|
|
||||||
#
|
|
||||||
#profile_key_import_mode = "on_registration"
|
|
||||||
@@ -10,13 +10,7 @@ Echo input of admin command
|
|||||||
|
|
||||||
## `!admin debug get-auth-chain`
|
## `!admin debug get-auth-chain`
|
||||||
|
|
||||||
Loads the auth_chain of a PDU, reporting how long it took
|
Get the auth_chain of a PDU
|
||||||
|
|
||||||
## `!admin debug show-auth-chain`
|
|
||||||
|
|
||||||
Walks & displays the auth_chain of a PDU in a mermaid graph format.
|
|
||||||
|
|
||||||
This is useless to basically anyone but developers, and is also probably slow and memory hungry.
|
|
||||||
|
|
||||||
## `!admin debug parse-pdu`
|
## `!admin debug parse-pdu`
|
||||||
|
|
||||||
@@ -50,12 +44,6 @@ This is functionally equivalent to `GET /_matrix/client/v3/rooms/{roomid}/state`
|
|||||||
|
|
||||||
Of course the check is still done on the actual client API.
|
Of course the check is still done on the actual client API.
|
||||||
|
|
||||||
## `!admin debug get-state-at`
|
|
||||||
|
|
||||||
Gets all the room state events at the specified event.
|
|
||||||
|
|
||||||
State at event might not be available for some PDUs, such as rejected ones.
|
|
||||||
|
|
||||||
## `!admin debug get-signing-keys`
|
## `!admin debug get-signing-keys`
|
||||||
|
|
||||||
Get and display signing keys from local cache or remote server
|
Get and display signing keys from local cache or remote server
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ Admin commands allow server administrators to manage the server from within thei
|
|||||||
- [`!admin appservices`](appservices/): Commands for managing appservices
|
- [`!admin appservices`](appservices/): Commands for managing appservices
|
||||||
- [`!admin users`](users/): Commands for managing local users
|
- [`!admin users`](users/): Commands for managing local users
|
||||||
- [`!admin token`](token/): Commands for managing registration tokens
|
- [`!admin token`](token/): Commands for managing registration tokens
|
||||||
- [`!admin oidc`](oidc/): Commands for managing OIDC
|
|
||||||
- [`!admin rooms`](rooms/): Commands for managing rooms
|
- [`!admin rooms`](rooms/): Commands for managing rooms
|
||||||
- [`!admin federation`](federation/): Commands for managing federation
|
- [`!admin federation`](federation/): Commands for managing federation
|
||||||
- [`!admin server`](server/): Commands for managing the server
|
- [`!admin server`](server/): Commands for managing the server
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
<!-- This file is generated by `cargo xtask generate-docs`. Do not edit. -->
|
|
||||||
# `!admin oidc`
|
|
||||||
|
|
||||||
Commands for managing OIDC
|
|
||||||
|
|
||||||
|
|
||||||
## `!admin oidc link`
|
|
||||||
|
|
||||||
Link a user ID to the given subject claim
|
|
||||||
|
|
||||||
## `!admin oidc unlink`
|
|
||||||
|
|
||||||
Unlink the given subject claim from its associated user ID
|
|
||||||
@@ -12,6 +12,10 @@ Create a new user
|
|||||||
|
|
||||||
Reset user password
|
Reset user password
|
||||||
|
|
||||||
|
## `!admin users issue-password-reset-link`
|
||||||
|
|
||||||
|
Issue a self-service password reset link for a user
|
||||||
|
|
||||||
## `!admin users get-email`
|
## `!admin users get-email`
|
||||||
|
|
||||||
Get a user's associated email address
|
Get a user's associated email address
|
||||||
@@ -92,14 +96,6 @@ Disables login for the specified user without deactivating or locking their acco
|
|||||||
|
|
||||||
List local users in the database
|
List local users in the database
|
||||||
|
|
||||||
## `!admin users list-invited-rooms`
|
|
||||||
|
|
||||||
Lists all the rooms (local and remote) that the specified user is invited to
|
|
||||||
|
|
||||||
## `!admin users reject-all-invites`
|
|
||||||
|
|
||||||
Manually make a user reject all current invites
|
|
||||||
|
|
||||||
## `!admin users list-joined-rooms`
|
## `!admin users list-joined-rooms`
|
||||||
|
|
||||||
Lists all the rooms (local and remote) that the specified user is joined in
|
Lists all the rooms (local and remote) that the specified user is joined in
|
||||||
|
|||||||
+10
-25
@@ -1,5 +1,5 @@
|
|||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use conduwuit::{Err, Result};
|
use conduwuit::Result;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
appservice::{self, AppserviceCommand},
|
appservice::{self, AppserviceCommand},
|
||||||
@@ -8,7 +8,6 @@ use crate::{
|
|||||||
debug::{self, DebugCommand},
|
debug::{self, DebugCommand},
|
||||||
federation::{self, FederationCommand},
|
federation::{self, FederationCommand},
|
||||||
media::{self, MediaCommand},
|
media::{self, MediaCommand},
|
||||||
oidc::{self, OidcCommand},
|
|
||||||
query::{self, QueryCommand},
|
query::{self, QueryCommand},
|
||||||
room::{self, RoomCommand},
|
room::{self, RoomCommand},
|
||||||
server::{self, ServerCommand},
|
server::{self, ServerCommand},
|
||||||
@@ -19,48 +18,44 @@ use crate::{
|
|||||||
#[derive(Debug, Parser)]
|
#[derive(Debug, Parser)]
|
||||||
#[command(name = conduwuit_core::BRANDING, version = conduwuit_core::version())]
|
#[command(name = conduwuit_core::BRANDING, version = conduwuit_core::version())]
|
||||||
pub enum AdminCommand {
|
pub enum AdminCommand {
|
||||||
/// Commands for managing appservices
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
/// Commands for managing appservices
|
||||||
Appservices(AppserviceCommand),
|
Appservices(AppserviceCommand),
|
||||||
|
|
||||||
/// Commands for managing local users
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
/// Commands for managing local users
|
||||||
Users(UserCommand),
|
Users(UserCommand),
|
||||||
|
|
||||||
/// Commands for managing registration tokens
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
/// Commands for managing registration tokens
|
||||||
Token(TokenCommand),
|
Token(TokenCommand),
|
||||||
|
|
||||||
/// Commands for managing OIDC
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Oidc(OidcCommand),
|
|
||||||
|
|
||||||
/// Commands for managing rooms
|
/// Commands for managing rooms
|
||||||
#[command(subcommand)]
|
|
||||||
Rooms(RoomCommand),
|
Rooms(RoomCommand),
|
||||||
|
|
||||||
/// Commands for managing federation
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
/// Commands for managing federation
|
||||||
Federation(FederationCommand),
|
Federation(FederationCommand),
|
||||||
|
|
||||||
/// Commands for managing the server
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
/// Commands for managing the server
|
||||||
Server(ServerCommand),
|
Server(ServerCommand),
|
||||||
|
|
||||||
/// Commands for managing media
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
/// Commands for managing media
|
||||||
Media(MediaCommand),
|
Media(MediaCommand),
|
||||||
|
|
||||||
/// Commands for checking integrity
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
/// Commands for checking integrity
|
||||||
Check(CheckCommand),
|
Check(CheckCommand),
|
||||||
|
|
||||||
/// Commands for debugging things
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
/// Commands for debugging things
|
||||||
Debug(DebugCommand),
|
Debug(DebugCommand),
|
||||||
|
|
||||||
/// Low-level queries for database getters and iterators
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
/// Low-level queries for database getters and iterators
|
||||||
Query(QueryCommand),
|
Query(QueryCommand),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,16 +80,6 @@ pub(super) async fn process(command: AdminCommand, context: &Context<'_>) -> Res
|
|||||||
context.bail_restricted()?;
|
context.bail_restricted()?;
|
||||||
token::process(command, context).await
|
token::process(command, context).await
|
||||||
},
|
},
|
||||||
| Oidc(command) => {
|
|
||||||
// OIDC commands are all restricted
|
|
||||||
context.bail_restricted()?;
|
|
||||||
|
|
||||||
if !context.services.oidc.enabled() {
|
|
||||||
return Err!("OIDC is not configured");
|
|
||||||
}
|
|
||||||
|
|
||||||
oidc::process(command, context).await
|
|
||||||
},
|
|
||||||
| Rooms(command) => room::process(command, context).await,
|
| Rooms(command) => room::process(command, context).await,
|
||||||
| Federation(command) => federation::process(command, context).await,
|
| Federation(command) => federation::process(command, context).await,
|
||||||
| Server(command) => server::process(command, context).await,
|
| Server(command) => server::process(command, context).await,
|
||||||
|
|||||||
@@ -6,12 +6,7 @@ use crate::Context;
|
|||||||
impl Context<'_> {
|
impl Context<'_> {
|
||||||
pub(super) async fn check_all_users(&self) -> Result {
|
pub(super) async fn check_all_users(&self) -> Result {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let users = self
|
let users = self.services.users.stream().collect::<Vec<_>>().await;
|
||||||
.services
|
|
||||||
.users
|
|
||||||
.stream_local_users()
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.await;
|
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
let total = users.len();
|
let total = users.len();
|
||||||
|
|||||||
@@ -612,7 +612,7 @@ impl crate::Context<'_> {
|
|||||||
// Force E2EE device list updates for all users
|
// Force E2EE device list updates for all users
|
||||||
self.services
|
self.services
|
||||||
.users
|
.users
|
||||||
.stream_local_users()
|
.stream()
|
||||||
.for_each(async |user_id| self.services.users.mark_device_key_update(&user_id).await)
|
.for_each(async |user_id| self.services.users.mark_device_key_update(&user_id).await)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ pub(crate) mod check;
|
|||||||
pub(crate) mod debug;
|
pub(crate) mod debug;
|
||||||
pub(crate) mod federation;
|
pub(crate) mod federation;
|
||||||
pub(crate) mod media;
|
pub(crate) mod media;
|
||||||
pub(crate) mod oidc;
|
|
||||||
pub(crate) mod query;
|
pub(crate) mod query;
|
||||||
pub(crate) mod room;
|
pub(crate) mod room;
|
||||||
pub(crate) mod server;
|
pub(crate) mod server;
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
use conduwuit::Result;
|
|
||||||
|
|
||||||
use crate::utils::parse_active_local_user_id;
|
|
||||||
|
|
||||||
impl crate::Context<'_> {
|
|
||||||
pub(super) async fn oidc_link(&self, user_id: String, subject: String) -> Result {
|
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
|
||||||
|
|
||||||
self.services.oidc.link_user(&user_id, &subject);
|
|
||||||
|
|
||||||
self.write_str(&format!("Subject `{subject}` linked to account `{user_id}`."))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) async fn oidc_unlink(&self, subject: String) -> Result {
|
|
||||||
self.services.oidc.unlink_user(&subject);
|
|
||||||
|
|
||||||
self.write_str(&format!("Subject `{subject}` unlinked."))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
mod commands;
|
|
||||||
|
|
||||||
use clap::Subcommand;
|
|
||||||
use conduwuit::Result;
|
|
||||||
use conduwuit_macros::admin_command_dispatch;
|
|
||||||
|
|
||||||
#[admin_command_dispatch]
|
|
||||||
#[derive(Debug, Subcommand)]
|
|
||||||
pub enum OidcCommand {
|
|
||||||
/// Link a user ID to the given subject claim.
|
|
||||||
#[clap(name = "link")]
|
|
||||||
OidcLink {
|
|
||||||
user_id: String,
|
|
||||||
subject: String,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// Unlink the given subject claim from its associated user ID.
|
|
||||||
#[clap(name = "unlink")]
|
|
||||||
OidcUnlink {
|
|
||||||
subject: String,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -191,13 +191,8 @@ impl crate::Context<'_> {
|
|||||||
|
|
||||||
async fn iter_users(&self) -> Result {
|
async fn iter_users(&self) -> Result {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result: Vec<OwnedUserId> = self
|
let result: Vec<OwnedUserId> =
|
||||||
.services
|
self.services.users.stream().map(Into::into).collect().await;
|
||||||
.users
|
|
||||||
.stream_local_users()
|
|
||||||
.map(Into::into)
|
|
||||||
.collect()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
@@ -207,7 +202,7 @@ impl crate::Context<'_> {
|
|||||||
|
|
||||||
async fn iter_users2(&self) -> Result {
|
async fn iter_users2(&self) -> Result {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result: Vec<_> = self.services.users.stream_local_users().collect().await;
|
let result: Vec<_> = self.services.users.stream().collect().await;
|
||||||
let result: Vec<_> = result
|
let result: Vec<_> = result
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|user_id| String::from_utf8_lossy(user_id.as_bytes()).into_owned())
|
.map(|user_id| String::from_utf8_lossy(user_id.as_bytes()).into_owned())
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ impl crate::Context<'_> {
|
|||||||
.services
|
.services
|
||||||
.config
|
.config
|
||||||
.oauth
|
.oauth
|
||||||
.compatibility_mode()
|
.compatibility_mode
|
||||||
.oauth_available()
|
.oauth_available()
|
||||||
{
|
{
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
|
|||||||
+63
-53
@@ -20,7 +20,7 @@ use ruma::{
|
|||||||
tag::{TagEvent, TagEventContent, TagInfo},
|
tag::{TagEvent, TagEventContent, TagInfo},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use service::users::{AccountStatus, HashedPassword};
|
use service::users::HashedPassword;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
get_room_info,
|
get_room_info,
|
||||||
@@ -54,16 +54,16 @@ impl crate::Context<'_> {
|
|||||||
.determine_registration_user_id(Some(username), None, None)
|
.determine_registration_user_id(Some(username), None, None)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let password =
|
let password = HashedPassword::new(
|
||||||
&password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
|
&password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH)),
|
||||||
|
)?;
|
||||||
|
|
||||||
self.services
|
self.services
|
||||||
.users
|
.users
|
||||||
.create_local_account(&user_id, Some(HashedPassword::new(password)?), None)
|
.create_local_account(&user_id, password, None)
|
||||||
.await?;
|
.await;
|
||||||
|
|
||||||
self.write_str(&format!("Created user {user_id} with password `{password}`"))
|
self.write_str(&format!("Created user {user_id}")).await
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) async fn deactivate(&self, no_leave_rooms: bool, user_id: String) -> Result {
|
pub(super) async fn deactivate(&self, no_leave_rooms: bool, user_id: String) -> Result {
|
||||||
@@ -103,12 +103,15 @@ impl crate::Context<'_> {
|
|||||||
|
|
||||||
pub(super) async fn suspend(&self, user_id: String) -> Result {
|
pub(super) async fn suspend(&self, user_id: String) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
|
||||||
if user_id == self.services.globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Err!("Not allowed to suspend the server service account.",);
|
return Err!("Not allowed to suspend the server service account.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !self.services.users.exists(&user_id).await {
|
||||||
|
return Err!("User {user_id} does not exist.");
|
||||||
|
}
|
||||||
if self.services.users.is_admin(&user_id).await {
|
if self.services.users.is_admin(&user_id).await {
|
||||||
return Err!("Admin users cannot be suspended.");
|
return Err!("Admin users cannot be suspended.");
|
||||||
}
|
}
|
||||||
@@ -124,12 +127,15 @@ impl crate::Context<'_> {
|
|||||||
|
|
||||||
pub(super) async fn unsuspend(&self, user_id: String) -> Result {
|
pub(super) async fn unsuspend(&self, user_id: String) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
|
||||||
if user_id == self.services.globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Err!("Not allowed to unsuspend the server service account.",);
|
return Err!("Not allowed to unsuspend the server service account.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !self.services.users.exists(&user_id).await {
|
||||||
|
return Err!("User {user_id} does not exist.");
|
||||||
|
}
|
||||||
self.services.users.unsuspend_account(&user_id).await;
|
self.services.users.unsuspend_account(&user_id).await;
|
||||||
|
|
||||||
self.write_str(&format!("User {user_id} has been unsuspended."))
|
self.write_str(&format!("User {user_id} has been unsuspended."))
|
||||||
@@ -141,7 +147,6 @@ impl crate::Context<'_> {
|
|||||||
logout: bool,
|
logout: bool,
|
||||||
username: String,
|
username: String,
|
||||||
password: Option<String>,
|
password: Option<String>,
|
||||||
convert_to_local_account: bool,
|
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let user_id = parse_local_user_id(self.services, &username)?;
|
let user_id = parse_local_user_id(self.services, &username)?;
|
||||||
|
|
||||||
@@ -154,37 +159,15 @@ impl crate::Context<'_> {
|
|||||||
|
|
||||||
let new_password =
|
let new_password =
|
||||||
password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
|
password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
|
||||||
let new_password_hash = HashedPassword::new(&new_password)?;
|
|
||||||
|
|
||||||
if convert_to_local_account {
|
self.services
|
||||||
self.services
|
.users
|
||||||
.users
|
.set_password(&user_id, Some(HashedPassword::new(&new_password)?));
|
||||||
.convert_to_local_account(&user_id, new_password_hash)
|
|
||||||
.await?;
|
|
||||||
} else {
|
|
||||||
match self.services.users.status(&user_id).await {
|
|
||||||
| AccountStatus::Active if !self.services.users.is_shadow(&user_id).await => {
|
|
||||||
self.services
|
|
||||||
.users
|
|
||||||
.set_password(&user_id, new_password_hash)
|
|
||||||
.await?;
|
|
||||||
},
|
|
||||||
| AccountStatus::NotFound => {
|
|
||||||
return Err!("The provided user does not exist.");
|
|
||||||
},
|
|
||||||
| _ => {
|
|
||||||
return Err!(
|
|
||||||
"The provided user is a shadow or deactivated account. To convert it to \
|
|
||||||
a local account, pass the --convert-to-local-account flag."
|
|
||||||
);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
"Successfully reset the password for user {user_id}: `{new_password}`"
|
"Successfully reset the password for user {user_id}: `{new_password}`"
|
||||||
))
|
))
|
||||||
.await?;
|
.await?;
|
||||||
}
|
|
||||||
|
|
||||||
if logout {
|
if logout {
|
||||||
self.services
|
self.services
|
||||||
@@ -936,16 +919,21 @@ impl crate::Context<'_> {
|
|||||||
|
|
||||||
pub(super) async fn lock(&self, user_id: String) -> Result {
|
pub(super) async fn lock(&self, user_id: String) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
assert!(
|
||||||
|
self.services.globals.user_is_local(&user_id),
|
||||||
|
"Parsed user_id must be a local user"
|
||||||
|
);
|
||||||
if user_id == self.services.globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Err!("Not allowed to lock the server service account.",);
|
return Err!("Not allowed to lock the server service account.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !self.services.users.exists(&user_id).await {
|
||||||
|
return Err!("User {user_id} does not exist.");
|
||||||
|
}
|
||||||
if self.services.users.is_admin(&user_id).await {
|
if self.services.users.is_admin(&user_id).await {
|
||||||
return Err!("Admin users cannot be locked.");
|
return Err!("Admin users cannot be locked.");
|
||||||
}
|
}
|
||||||
|
|
||||||
self.services
|
self.services
|
||||||
.users
|
.users
|
||||||
.lock_account(&user_id, self.sender_or_service_user())
|
.lock_account(&user_id, self.sender_or_service_user())
|
||||||
@@ -957,8 +945,11 @@ impl crate::Context<'_> {
|
|||||||
|
|
||||||
pub(super) async fn unlock(&self, user_id: String) -> Result {
|
pub(super) async fn unlock(&self, user_id: String) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
assert!(
|
||||||
|
self.services.globals.user_is_local(&user_id),
|
||||||
|
"Parsed user_id must be a local user"
|
||||||
|
);
|
||||||
self.services.users.unlock_account(&user_id).await;
|
self.services.users.unlock_account(&user_id).await;
|
||||||
|
|
||||||
self.write_str(&format!("User {user_id} has been unlocked."))
|
self.write_str(&format!("User {user_id} has been unlocked."))
|
||||||
@@ -967,16 +958,21 @@ impl crate::Context<'_> {
|
|||||||
|
|
||||||
pub(super) async fn logout(&self, user_id: String) -> Result {
|
pub(super) async fn logout(&self, user_id: String) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
assert!(
|
||||||
|
self.services.globals.user_is_local(&user_id),
|
||||||
|
"Parsed user_id must be a local user"
|
||||||
|
);
|
||||||
if user_id == self.services.globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Err!("Not allowed to log out the server service account.",);
|
return Err!("Not allowed to log out the server service account.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !self.services.users.exists(&user_id).await {
|
||||||
|
return Err!("User {user_id} does not exist.");
|
||||||
|
}
|
||||||
if self.services.users.is_admin(&user_id).await {
|
if self.services.users.is_admin(&user_id).await {
|
||||||
return Err!("You cannot forcefully log out admin users.");
|
return Err!("You cannot forcefully log out admin users.");
|
||||||
}
|
}
|
||||||
|
|
||||||
self.services
|
self.services
|
||||||
.users
|
.users
|
||||||
.all_device_ids(&user_id)
|
.all_device_ids(&user_id)
|
||||||
@@ -993,12 +989,18 @@ impl crate::Context<'_> {
|
|||||||
|
|
||||||
pub(super) async fn disable_login(&self, user_id: String) -> Result {
|
pub(super) async fn disable_login(&self, user_id: String) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
assert!(
|
||||||
|
self.services.globals.user_is_local(&user_id),
|
||||||
|
"Parsed user_id must be a local user"
|
||||||
|
);
|
||||||
if user_id == self.services.globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Err!("Not allowed to disable login for the server service account.",);
|
return Err!("Not allowed to disable login for the server service account.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !self.services.users.exists(&user_id).await {
|
||||||
|
return Err!("User {user_id} does not exist.");
|
||||||
|
}
|
||||||
if self.services.users.is_admin(&user_id).await {
|
if self.services.users.is_admin(&user_id).await {
|
||||||
return Err!("Admin users cannot have their login disallowed.");
|
return Err!("Admin users cannot have their login disallowed.");
|
||||||
}
|
}
|
||||||
@@ -1012,8 +1014,14 @@ impl crate::Context<'_> {
|
|||||||
|
|
||||||
pub(super) async fn enable_login(&self, user_id: String) -> Result {
|
pub(super) async fn enable_login(&self, user_id: String) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
assert!(
|
||||||
|
self.services.globals.user_is_local(&user_id),
|
||||||
|
"Parsed user_id must be a local user"
|
||||||
|
);
|
||||||
|
if !self.services.users.exists(&user_id).await {
|
||||||
|
return Err!("User {user_id} does not exist.");
|
||||||
|
}
|
||||||
self.services.users.enable_login(&user_id);
|
self.services.users.enable_login(&user_id);
|
||||||
|
|
||||||
self.write_str(&format!("{user_id} can now log in.")).await
|
self.write_str(&format!("{user_id} can now log in.")).await
|
||||||
@@ -1121,8 +1129,10 @@ impl crate::Context<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) async fn reset_push_rules(&self, user_id: String) -> Result {
|
pub(super) async fn reset_push_rules(&self, user_id: String) -> Result {
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
if !self.services.users.is_active(&user_id).await {
|
||||||
|
return Err!("User is not active.");
|
||||||
|
}
|
||||||
recreate_push_rules_and_return(self.services, &user_id).await?;
|
recreate_push_rules_and_return(self.services, &user_id).await?;
|
||||||
self.write_str("Reset user's push rules to the server default.")
|
self.write_str("Reset user's push rules to the server default.")
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -27,9 +27,6 @@ pub enum UserCommand {
|
|||||||
username: String,
|
username: String,
|
||||||
/// New password for the user, if unspecified one is generated
|
/// New password for the user, if unspecified one is generated
|
||||||
password: Option<String>,
|
password: Option<String>,
|
||||||
|
|
||||||
#[arg(long)]
|
|
||||||
convert_to_local_account: bool,
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Get a user's associated email address.
|
/// Get a user's associated email address.
|
||||||
|
|||||||
+8
-1
@@ -54,7 +54,14 @@ pub(crate) async fn parse_active_local_user_id(
|
|||||||
user_id: &str,
|
user_id: &str,
|
||||||
) -> Result<OwnedUserId> {
|
) -> Result<OwnedUserId> {
|
||||||
let user_id = parse_local_user_id(services, user_id)?;
|
let user_id = parse_local_user_id(services, user_id)?;
|
||||||
services.users.status(&user_id).await.ensure_active()?;
|
|
||||||
|
if !services.users.exists(&user_id).await {
|
||||||
|
return Err!("User {user_id:?} does not exist on this server.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if services.users.is_deactivated(&user_id).await? {
|
||||||
|
return Err!("User {user_id:?} is deactivated.");
|
||||||
|
}
|
||||||
|
|
||||||
Ok(user_id)
|
Ok(user_id)
|
||||||
}
|
}
|
||||||
@@ -128,8 +128,7 @@ pub(crate) async fn change_password_route(
|
|||||||
|
|
||||||
services
|
services
|
||||||
.users
|
.users
|
||||||
.set_password(&sender_user, HashedPassword::new(&body.new_password)?)
|
.set_password(&sender_user, Some(HashedPassword::new(&body.new_password)?));
|
||||||
.await?;
|
|
||||||
|
|
||||||
if body.logout_devices {
|
if body.logout_devices {
|
||||||
// Logout all devices except the current one
|
// Logout all devices except the current one
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ pub(crate) async fn register_route(
|
|||||||
.determine_registration_user_id(body.username.clone(), None, Some(appservice_info))
|
.determine_registration_user_id(body.username.clone(), None, Some(appservice_info))
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
services.users.create_shadow_account(&user_id).await?;
|
services.users.create(&user_id, None)?;
|
||||||
|
|
||||||
user_id
|
user_id
|
||||||
} else {
|
} else {
|
||||||
@@ -97,8 +97,8 @@ pub(crate) async fn register_route(
|
|||||||
|
|
||||||
services
|
services
|
||||||
.users
|
.users
|
||||||
.create_local_account(&user_id, Some(password), identity.email)
|
.create_local_account(&user_id, password, identity.email)
|
||||||
.await?;
|
.await;
|
||||||
|
|
||||||
user_id
|
user_id
|
||||||
};
|
};
|
||||||
@@ -106,7 +106,7 @@ pub(crate) async fn register_route(
|
|||||||
let (token, device) = if !body.inhibit_login {
|
let (token, device) = if !body.inhibit_login {
|
||||||
// If UIAA is disabled, we can't create a device. In that case only appservices
|
// If UIAA is disabled, we can't create a device. In that case only appservices
|
||||||
// can reach this point in the first place, so we return an error for them.
|
// can reach this point in the first place, so we return an error for them.
|
||||||
if !services.config.oauth.compatibility_mode().uiaa_available() {
|
if !services.config.oauth.compatibility_mode.uiaa_available() {
|
||||||
return Err!(Request(AppserviceLoginUnsupported(
|
return Err!(Request(AppserviceLoginUnsupported(
|
||||||
"User-interactive appservice registration is not available on this server."
|
"User-interactive appservice registration is not available on this server."
|
||||||
)));
|
)));
|
||||||
|
|||||||
@@ -25,10 +25,6 @@ pub(crate) async fn third_party_route(
|
|||||||
let sender_user = body.identity.expect_sender_user()?;
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
let mut threepids = vec![];
|
let mut threepids = vec![];
|
||||||
|
|
||||||
if !services.threepid.email_requirement().may_view() {
|
|
||||||
return Ok(get_3pids::v3::Response::new(vec![]));
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(email) = services
|
if let Some(email) = services
|
||||||
.threepid
|
.threepid
|
||||||
.get_email_for_localpart(sender_user.localpart())
|
.get_email_for_localpart(sender_user.localpart())
|
||||||
|
|||||||
@@ -12,18 +12,20 @@ pub(crate) async fn get_lock_status(
|
|||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<is_user_locked::v1::Request>,
|
body: Ruma<is_user_locked::v1::Request>,
|
||||||
) -> Result<is_user_locked::v1::Response> {
|
) -> Result<is_user_locked::v1::Response> {
|
||||||
let (admin, status) = join(
|
let (admin, active) = join(
|
||||||
services.users.is_admin(body.identity.expect_sender_user()?),
|
services.users.is_admin(body.identity.expect_sender_user()?),
|
||||||
services.users.status(&body.user_id),
|
services.users.is_active(&body.user_id),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
if !admin {
|
if !admin {
|
||||||
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
||||||
}
|
}
|
||||||
|
if !services.globals.user_is_local(&body.user_id) {
|
||||||
status.ensure_active()?;
|
return Err!(Request(InvalidParam("Can only check the lock status of local users")));
|
||||||
|
}
|
||||||
|
if !active {
|
||||||
|
return Err!(Request(NotFound("Unknown user")));
|
||||||
|
}
|
||||||
Ok(is_user_locked::v1::Response::new(
|
Ok(is_user_locked::v1::Response::new(
|
||||||
services.users.is_locked(&body.user_id).await?,
|
services.users.is_locked(&body.user_id).await?,
|
||||||
))
|
))
|
||||||
@@ -38,9 +40,9 @@ pub(crate) async fn put_lock_status(
|
|||||||
) -> Result<lock_user::v1::Response> {
|
) -> Result<lock_user::v1::Response> {
|
||||||
let sender_user = body.identity.expect_sender_user()?;
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
|
|
||||||
let (sender_admin, status, target_admin) = join3(
|
let (sender_admin, active, target_admin) = join3(
|
||||||
services.users.is_admin(sender_user),
|
services.users.is_admin(sender_user),
|
||||||
services.users.status(&body.user_id),
|
services.users.is_active(&body.user_id),
|
||||||
services.users.is_admin(&body.user_id),
|
services.users.is_admin(&body.user_id),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -48,17 +50,18 @@ pub(crate) async fn put_lock_status(
|
|||||||
if !sender_admin {
|
if !sender_admin {
|
||||||
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
||||||
}
|
}
|
||||||
|
if !services.globals.user_is_local(&body.user_id) {
|
||||||
status.ensure_active()?;
|
return Err!(Request(InvalidParam("Can only set the lock status of local users")));
|
||||||
|
}
|
||||||
|
if !active {
|
||||||
|
return Err!(Request(NotFound("Unknown user")));
|
||||||
|
}
|
||||||
if body.user_id == *sender_user {
|
if body.user_id == *sender_user {
|
||||||
return Err!(Request(Forbidden("You cannot lock yourself")));
|
return Err!(Request(Forbidden("You cannot lock yourself")));
|
||||||
}
|
}
|
||||||
|
|
||||||
if target_admin {
|
if target_admin {
|
||||||
return Err!(Request(Forbidden("You cannot lock another server administrator")));
|
return Err!(Request(Forbidden("You cannot lock another server administrator")));
|
||||||
}
|
}
|
||||||
|
|
||||||
if services.users.is_locked(&body.user_id).await? == body.locked {
|
if services.users.is_locked(&body.user_id).await? == body.locked {
|
||||||
// No change
|
// No change
|
||||||
return Ok(lock_user::v1::Response::new(body.locked));
|
return Ok(lock_user::v1::Response::new(body.locked));
|
||||||
|
|||||||
@@ -12,18 +12,20 @@ pub(crate) async fn get_suspended_status(
|
|||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<is_user_suspended::v1::Request>,
|
body: Ruma<is_user_suspended::v1::Request>,
|
||||||
) -> Result<is_user_suspended::v1::Response> {
|
) -> Result<is_user_suspended::v1::Response> {
|
||||||
let (admin, status) = join(
|
let (admin, active) = join(
|
||||||
services.users.is_admin(body.identity.expect_sender_user()?),
|
services.users.is_admin(body.identity.expect_sender_user()?),
|
||||||
services.users.status(&body.user_id),
|
services.users.is_active(&body.user_id),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
if !admin {
|
if !admin {
|
||||||
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
||||||
}
|
}
|
||||||
|
if !services.globals.user_is_local(&body.user_id) {
|
||||||
status.ensure_active()?;
|
return Err!(Request(InvalidParam("Can only check the suspended status of local users")));
|
||||||
|
}
|
||||||
|
if !active {
|
||||||
|
return Err!(Request(NotFound("Unknown user")));
|
||||||
|
}
|
||||||
Ok(is_user_suspended::v1::Response::new(
|
Ok(is_user_suspended::v1::Response::new(
|
||||||
services.users.is_suspended(&body.user_id).await?,
|
services.users.is_suspended(&body.user_id).await?,
|
||||||
))
|
))
|
||||||
@@ -38,9 +40,9 @@ pub(crate) async fn put_suspended_status(
|
|||||||
) -> Result<suspend_user::v1::Response> {
|
) -> Result<suspend_user::v1::Response> {
|
||||||
let sender_user = body.identity.expect_sender_user()?;
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
|
|
||||||
let (sender_admin, status, target_admin) = join3(
|
let (sender_admin, active, target_admin) = join3(
|
||||||
services.users.is_admin(sender_user),
|
services.users.is_admin(sender_user),
|
||||||
services.users.status(&body.user_id),
|
services.users.is_active(&body.user_id),
|
||||||
services.users.is_admin(&body.user_id),
|
services.users.is_admin(&body.user_id),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -48,17 +50,18 @@ pub(crate) async fn put_suspended_status(
|
|||||||
if !sender_admin {
|
if !sender_admin {
|
||||||
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
||||||
}
|
}
|
||||||
|
if !services.globals.user_is_local(&body.user_id) {
|
||||||
status.ensure_active()?;
|
return Err!(Request(InvalidParam("Can only set the suspended status of local users")));
|
||||||
|
}
|
||||||
|
if !active {
|
||||||
|
return Err!(Request(NotFound("Unknown user")));
|
||||||
|
}
|
||||||
if body.user_id == *sender_user {
|
if body.user_id == *sender_user {
|
||||||
return Err!(Request(Forbidden("You cannot suspend yourself")));
|
return Err!(Request(Forbidden("You cannot suspend yourself")));
|
||||||
}
|
}
|
||||||
|
|
||||||
if target_admin {
|
if target_admin {
|
||||||
return Err!(Request(Forbidden("You cannot suspend another server administrator")));
|
return Err!(Request(Forbidden("You cannot suspend another server administrator")));
|
||||||
}
|
}
|
||||||
|
|
||||||
if services.users.is_suspended(&body.user_id).await? == body.suspended {
|
if services.users.is_suspended(&body.user_id).await? == body.suspended {
|
||||||
// No change
|
// No change
|
||||||
return Ok(suspend_user::v1::Response::new(body.suspended));
|
return Ok(suspend_user::v1::Response::new(body.suspended));
|
||||||
|
|||||||
@@ -7,11 +7,10 @@ use ruma::{
|
|||||||
api::client::discovery::get_capabilities::{
|
api::client::discovery::get_capabilities::{
|
||||||
self,
|
self,
|
||||||
v3::{
|
v3::{
|
||||||
Capabilities, GetLoginTokenCapability, ProfileFieldsCapability, RoomVersionStability,
|
Capabilities, GetLoginTokenCapability, RoomVersionStability, RoomVersionsCapability,
|
||||||
RoomVersionsCapability, ThirdPartyIdChangesCapability,
|
ThirdPartyIdChangesCapability,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
assign,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::Ruma;
|
use crate::Ruma;
|
||||||
@@ -51,9 +50,5 @@ pub(crate) async fn get_capabilities_route(
|
|||||||
capabilities.account_moderation.suspend = true;
|
capabilities.account_moderation.suspend = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
capabilities.profile_fields = Some(
|
|
||||||
assign!(ProfileFieldsCapability::new(true), { disallowed: Some(services.oidc.restricted_profile_fields()) }),
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(get_capabilities::v3::Response::new(capabilities))
|
Ok(get_capabilities::v3::Response::new(capabilities))
|
||||||
}
|
}
|
||||||
@@ -37,7 +37,7 @@ pub(crate) fn router(state: crate::State) -> Router<crate::State> {
|
|||||||
.layer(middleware::from_fn_with_state(
|
.layer(middleware::from_fn_with_state(
|
||||||
state,
|
state,
|
||||||
async |State(state): State<crate::State>, request: Request, next: Next| -> Response {
|
async |State(state): State<crate::State>, request: Request, next: Next| -> Response {
|
||||||
if state.config.oauth.compatibility_mode().oauth_available() {
|
if state.config.oauth.compatibility_mode.oauth_available() {
|
||||||
next.run(request).await
|
next.run(request).await
|
||||||
} else {
|
} else {
|
||||||
(StatusCode::NOT_FOUND, "OAuth is unavailable on this server").into_response()
|
(StatusCode::NOT_FOUND, "OAuth is unavailable on this server").into_response()
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ pub(crate) async fn get_authorization_server_metadata_route(
|
|||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
_body: Ruma<get_authorization_server_metadata::v1::Request>,
|
_body: Ruma<get_authorization_server_metadata::v1::Request>,
|
||||||
) -> Result<get_authorization_server_metadata::v1::Response> {
|
) -> Result<get_authorization_server_metadata::v1::Response> {
|
||||||
if !services.config.oauth.compatibility_mode().oauth_available() {
|
if !services.config.oauth.compatibility_mode.oauth_available() {
|
||||||
return Err!(Request(Unrecognized("OAuth is unavailable on this server")));
|
return Err!(Request(Unrecognized("OAuth is unavailable on this server")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+289
-58
@@ -1,8 +1,9 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use axum::extract::State;
|
use axum::extract::State;
|
||||||
use conduwuit::{Err, Result};
|
use conduwuit::{Err, Result, matrix::pdu::PartialPdu, utils::to_canonical_object};
|
||||||
use conduwuit_service::Services;
|
use conduwuit_service::Services;
|
||||||
|
use futures::StreamExt;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
UserId,
|
UserId,
|
||||||
api::{
|
api::{
|
||||||
@@ -12,10 +13,11 @@ use ruma::{
|
|||||||
federation,
|
federation,
|
||||||
},
|
},
|
||||||
assign,
|
assign,
|
||||||
|
events::room::member::MembershipState,
|
||||||
|
presence::PresenceState,
|
||||||
profile::{ProfileFieldName, ProfileFieldValue},
|
profile::{ProfileFieldName, ProfileFieldValue},
|
||||||
};
|
};
|
||||||
use serde_json::Value;
|
use serde_json::{Value, to_value};
|
||||||
use service::users::ProfileFieldChange;
|
|
||||||
|
|
||||||
use crate::Ruma;
|
use crate::Ruma;
|
||||||
|
|
||||||
@@ -63,24 +65,13 @@ pub(crate) async fn set_profile_field_route(
|
|||||||
return Err!(Request(InvalidParam("You may not change a remote user's profile data.")));
|
return Err!(Request(InvalidParam("You may not change a remote user's profile data.")));
|
||||||
}
|
}
|
||||||
|
|
||||||
if services
|
set_profile_field(
|
||||||
.oidc
|
&services,
|
||||||
.restricted_profile_fields()
|
&body.user_id,
|
||||||
.contains(&body.value.field_name())
|
ProfileFieldChange::Set(body.value.clone()),
|
||||||
{
|
body.propagate_to.clone(),
|
||||||
return Err!(Request(Forbidden(
|
)
|
||||||
"This profile field is controlled by your identity provider."
|
.await?;
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
services
|
|
||||||
.users
|
|
||||||
.set_profile_field(
|
|
||||||
&body.user_id,
|
|
||||||
ProfileFieldChange::Set(body.value.clone()),
|
|
||||||
body.propagate_to.clone(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(set_profile_field::v3::Response::new())
|
Ok(set_profile_field::v3::Response::new())
|
||||||
}
|
}
|
||||||
@@ -103,24 +94,13 @@ pub(crate) async fn delete_profile_field_route(
|
|||||||
return Err!(Request(InvalidParam("You may not change a remote user's profile data.")));
|
return Err!(Request(InvalidParam("You may not change a remote user's profile data.")));
|
||||||
}
|
}
|
||||||
|
|
||||||
if services
|
set_profile_field(
|
||||||
.oidc
|
&services,
|
||||||
.restricted_profile_fields()
|
&body.user_id,
|
||||||
.contains(&body.field)
|
ProfileFieldChange::Delete(body.field.clone()),
|
||||||
{
|
body.propagate_to.clone(),
|
||||||
return Err!(Request(Forbidden(
|
)
|
||||||
"This profile field is controlled by your identity provider."
|
.await?;
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
services
|
|
||||||
.users
|
|
||||||
.set_profile_field(
|
|
||||||
&body.user_id,
|
|
||||||
ProfileFieldChange::Delete(body.field.clone()),
|
|
||||||
body.propagate_to.clone(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(delete_profile_field::v3::Response::new())
|
Ok(delete_profile_field::v3::Response::new())
|
||||||
}
|
}
|
||||||
@@ -130,8 +110,8 @@ async fn fetch_full_profile(
|
|||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
) -> Option<BTreeMap<String, Value>> {
|
) -> Option<BTreeMap<String, Value>> {
|
||||||
// If the user exists locally, fetch their local profile
|
// If the user exists locally, fetch their local profile
|
||||||
if services.users.status(user_id).await.is_found() {
|
if services.users.exists(user_id).await {
|
||||||
return Some(services.users.get_local_profile(user_id).await);
|
return Some(get_local_profile(services, user_id).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Otherwise ask their homeserver
|
// Otherwise ask their homeserver
|
||||||
@@ -155,10 +135,13 @@ async fn fetch_full_profile(
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
let _ = services
|
let _ = set_profile_field(
|
||||||
.users
|
services,
|
||||||
.set_profile_field(user_id, ProfileFieldChange::Set(value), PropagateTo::None)
|
user_id,
|
||||||
.await;
|
ProfileFieldChange::Set(value),
|
||||||
|
PropagateTo::None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
Some(BTreeMap::from_iter(response))
|
Some(BTreeMap::from_iter(response))
|
||||||
@@ -171,7 +154,7 @@ async fn fetch_profile_field(
|
|||||||
) -> Result<Option<ProfileFieldValue>> {
|
) -> Result<Option<ProfileFieldValue>> {
|
||||||
// If the user exists locally, fetch their local profile field
|
// If the user exists locally, fetch their local profile field
|
||||||
if services.globals.user_is_local(user_id) {
|
if services.globals.user_is_local(user_id) {
|
||||||
return Ok(services.users.get_local_profile_field(user_id, field).await);
|
return Ok(get_local_profile_field(services, user_id, field).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Otherwise ask their homeserver
|
// Otherwise ask their homeserver
|
||||||
@@ -192,14 +175,13 @@ async fn fetch_profile_field(
|
|||||||
|
|
||||||
if let Some(value) = response.get(field.as_str()).map(ToOwned::to_owned) {
|
if let Some(value) = response.get(field.as_str()).map(ToOwned::to_owned) {
|
||||||
if let Ok(value) = ProfileFieldValue::new(field.as_str(), value) {
|
if let Ok(value) = ProfileFieldValue::new(field.as_str(), value) {
|
||||||
let _ = services
|
let _ = set_profile_field(
|
||||||
.users
|
services,
|
||||||
.set_profile_field(
|
user_id,
|
||||||
user_id,
|
ProfileFieldChange::Set(value.clone()),
|
||||||
ProfileFieldChange::Set(value.clone()),
|
PropagateTo::None,
|
||||||
PropagateTo::None,
|
)
|
||||||
)
|
.await;
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(Some(value))
|
Ok(Some(value))
|
||||||
} else {
|
} else {
|
||||||
@@ -208,11 +190,260 @@ async fn fetch_profile_field(
|
|||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let _ = services
|
let _ = set_profile_field(
|
||||||
.users
|
services,
|
||||||
.set_profile_field(user_id, ProfileFieldChange::Delete(field), PropagateTo::None)
|
user_id,
|
||||||
.await;
|
ProfileFieldChange::Delete(field),
|
||||||
|
PropagateTo::None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn get_local_profile(
|
||||||
|
services: &Services,
|
||||||
|
user_id: &UserId,
|
||||||
|
) -> BTreeMap<String, Value> {
|
||||||
|
let mut profile = BTreeMap::new();
|
||||||
|
|
||||||
|
// Get displayname and avatar_url independently because `all_profile_keys`
|
||||||
|
// doesn't include them
|
||||||
|
for field in [ProfileFieldName::AvatarUrl, ProfileFieldName::DisplayName] {
|
||||||
|
let key = field.as_str().to_owned();
|
||||||
|
|
||||||
|
if let Some(value) = get_local_profile_field(services, user_id, field).await {
|
||||||
|
profile.insert(key, value.value().into_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert all other profile fields
|
||||||
|
let mut all_fields = services.users.all_profile_keys(user_id);
|
||||||
|
|
||||||
|
while let Some((key, value)) = all_fields.next().await {
|
||||||
|
profile.insert(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
profile
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn get_local_profile_field(
|
||||||
|
services: &Services,
|
||||||
|
user_id: &UserId,
|
||||||
|
field: ProfileFieldName,
|
||||||
|
) -> Option<ProfileFieldValue> {
|
||||||
|
let value = match field.clone() {
|
||||||
|
| ProfileFieldName::AvatarUrl => services
|
||||||
|
.users
|
||||||
|
.avatar_url(user_id)
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.map(to_value)
|
||||||
|
.transpose()
|
||||||
|
.expect("converting avatar url to value should succeed"),
|
||||||
|
| ProfileFieldName::DisplayName => services
|
||||||
|
.users
|
||||||
|
.displayname(user_id)
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.map(to_value)
|
||||||
|
.transpose()
|
||||||
|
.expect("converting displayname to value should succeed"),
|
||||||
|
| other => services
|
||||||
|
.users
|
||||||
|
.profile_key(user_id, other.as_str())
|
||||||
|
.await
|
||||||
|
.ok(),
|
||||||
|
}?;
|
||||||
|
|
||||||
|
Some(
|
||||||
|
ProfileFieldValue::new(field.as_str(), value)
|
||||||
|
.expect("local profile field should be valid"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
enum ProfileFieldChange {
|
||||||
|
Set(ProfileFieldValue),
|
||||||
|
Delete(ProfileFieldName),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProfileFieldChange {
|
||||||
|
fn field_name(&self) -> ProfileFieldName {
|
||||||
|
match self {
|
||||||
|
| &Self::Delete(ref name) => name.clone(),
|
||||||
|
| &Self::Set(ref value) => value.field_name(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn value(&self) -> Option<Value> {
|
||||||
|
if let Self::Set(value) = self {
|
||||||
|
Some(value.value().into_owned())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_profile_field(
|
||||||
|
services: &Services,
|
||||||
|
user_id: &UserId,
|
||||||
|
change: ProfileFieldChange,
|
||||||
|
propagate_to: PropagateTo,
|
||||||
|
) -> Result<()> {
|
||||||
|
const MAX_KEY_LENGTH_BYTES: usize = 255;
|
||||||
|
const MAX_PROFILE_LENGTH_BYTES: usize = 65536;
|
||||||
|
|
||||||
|
let field_name = change.field_name();
|
||||||
|
|
||||||
|
// TODO: The spec mentions special error codes (M_PROFILE_TOO_LARGE,
|
||||||
|
// M_KEY_TOO_LARGE) for profile field size limits, but they're not in its list
|
||||||
|
// of error codes and Ruma doesn't have them. Should we return those, or is
|
||||||
|
// M_TOO_LARGE okay?
|
||||||
|
if field_name.as_str().len() > MAX_KEY_LENGTH_BYTES {
|
||||||
|
return Err!(Request(TooLarge(
|
||||||
|
"Individual profile keys must not exceed {MAX_KEY_LENGTH_BYTES} bytes in length."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize the entire profile as canonical JSON, including the new change,
|
||||||
|
// to check if it exceeds 64 KiB
|
||||||
|
{
|
||||||
|
let mut full_profile = get_local_profile(services, user_id).await;
|
||||||
|
|
||||||
|
match &change {
|
||||||
|
| ProfileFieldChange::Set(value) => {
|
||||||
|
full_profile.insert(
|
||||||
|
value.field_name().as_str().to_owned(),
|
||||||
|
value.value().clone().into_owned(),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
| ProfileFieldChange::Delete(key) => {
|
||||||
|
full_profile.remove(key.as_str());
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Ok(canonical_profile) = to_canonical_object(full_profile) {
|
||||||
|
if serde_json::to_string(&canonical_profile)
|
||||||
|
.expect("should be able to serialize to string")
|
||||||
|
.len() > MAX_PROFILE_LENGTH_BYTES
|
||||||
|
{
|
||||||
|
return Err!(
|
||||||
|
"Profile data must not exceed {MAX_PROFILE_LENGTH_BYTES} bytes in length."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err!(Request(BadJson("Failed to canonicalize profile.")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the user is local and changed their displayname or avatar_url, update it
|
||||||
|
// in all their joined rooms. This is done before updating their profile data
|
||||||
|
// so we can check the old value of the field if `propagate_to` is `unchanged`.
|
||||||
|
if matches!(field_name, ProfileFieldName::AvatarUrl | ProfileFieldName::DisplayName)
|
||||||
|
&& matches!(propagate_to, PropagateTo::All | PropagateTo::Unchanged)
|
||||||
|
&& services.globals.user_is_local(user_id)
|
||||||
|
{
|
||||||
|
let current_displayname = services.users.displayname(user_id).await.ok();
|
||||||
|
let current_avatar_url = services.users.avatar_url(user_id).await.ok();
|
||||||
|
|
||||||
|
let mut all_joined_rooms = services.rooms.state_cache.rooms_joined(user_id);
|
||||||
|
|
||||||
|
while let Some(room_id) = all_joined_rooms.next().await {
|
||||||
|
// TODO: this clobbers any custom fields on the event content
|
||||||
|
let mut current_membership = services
|
||||||
|
.rooms
|
||||||
|
.state_accessor
|
||||||
|
.get_member(&room_id, user_id)
|
||||||
|
.await
|
||||||
|
.expect("should be able to fetch membership event for joined room");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
current_membership.membership,
|
||||||
|
MembershipState::Join,
|
||||||
|
"user should be joined"
|
||||||
|
);
|
||||||
|
|
||||||
|
// If `propagate_to` is `unchanged`, and the current value of the field we're
|
||||||
|
// updating was changed from its global value in this room, skip it.
|
||||||
|
if matches!(propagate_to, PropagateTo::Unchanged) {
|
||||||
|
let field_changed_from_global = match field_name {
|
||||||
|
| ProfileFieldName::AvatarUrl =>
|
||||||
|
current_membership.avatar_url.as_ref() != current_avatar_url.as_ref(),
|
||||||
|
| ProfileFieldName::DisplayName =>
|
||||||
|
current_membership.displayname.as_ref() != current_displayname.as_ref(),
|
||||||
|
| _ => unreachable!(),
|
||||||
|
};
|
||||||
|
|
||||||
|
if field_changed_from_global {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let state_lock = services.rooms.state.mutex.lock(room_id.as_str()).await;
|
||||||
|
|
||||||
|
// Preserve keys in accordance with the key copying rules
|
||||||
|
current_membership.reason = None;
|
||||||
|
current_membership.join_authorized_via_users_server = None;
|
||||||
|
match &change {
|
||||||
|
| ProfileFieldChange::Set(ProfileFieldValue::AvatarUrl(avatar_url)) => {
|
||||||
|
current_membership.avatar_url = Some(avatar_url.clone());
|
||||||
|
},
|
||||||
|
| ProfileFieldChange::Set(ProfileFieldValue::DisplayName(displayname)) => {
|
||||||
|
current_membership.displayname = Some(displayname.clone());
|
||||||
|
},
|
||||||
|
| ProfileFieldChange::Delete(ProfileFieldName::AvatarUrl) => {
|
||||||
|
current_membership.avatar_url = None;
|
||||||
|
},
|
||||||
|
| ProfileFieldChange::Delete(ProfileFieldName::DisplayName) => {
|
||||||
|
current_membership.displayname = None;
|
||||||
|
},
|
||||||
|
| _ => unreachable!(),
|
||||||
|
}
|
||||||
|
|
||||||
|
let _ = services
|
||||||
|
.rooms
|
||||||
|
.timeline
|
||||||
|
.build_and_append_pdu(
|
||||||
|
PartialPdu::state(user_id.to_string(), ¤t_membership),
|
||||||
|
user_id,
|
||||||
|
Some(&room_id),
|
||||||
|
&state_lock,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
if services.config.allow_local_presence {
|
||||||
|
// Send a presence EDU to indicate the profile changed
|
||||||
|
let _ = services
|
||||||
|
.presence
|
||||||
|
.ping_presence(user_id, &PresenceState::Online)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match change {
|
||||||
|
| ProfileFieldChange::Set(ProfileFieldValue::DisplayName(displayname)) => {
|
||||||
|
services
|
||||||
|
.users
|
||||||
|
.set_displayname(user_id, Some(displayname).filter(|dn| !dn.is_empty()));
|
||||||
|
},
|
||||||
|
| ProfileFieldChange::Set(ProfileFieldValue::AvatarUrl(avatar_url)) => {
|
||||||
|
services
|
||||||
|
.users
|
||||||
|
.set_avatar_url(user_id, Some(avatar_url).filter(|av| av.is_valid()));
|
||||||
|
},
|
||||||
|
| ProfileFieldChange::Delete(ProfileFieldName::DisplayName) => {
|
||||||
|
services.users.set_displayname(user_id, None);
|
||||||
|
},
|
||||||
|
| ProfileFieldChange::Delete(ProfileFieldName::AvatarUrl) => {
|
||||||
|
services.users.set_avatar_url(user_id, None);
|
||||||
|
},
|
||||||
|
| other =>
|
||||||
|
services
|
||||||
|
.users
|
||||||
|
.set_profile_key(user_id, other.field_name().as_str(), other.value()),
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -149,7 +149,7 @@ pub(crate) async fn report_user_route(
|
|||||||
|
|
||||||
delay_response().await;
|
delay_response().await;
|
||||||
|
|
||||||
if !services.users.status(&body.user_id).await.is_found() {
|
if !services.users.is_active_local(&body.user_id).await {
|
||||||
// return 200 as to not reveal if the user exists. Recommended by spec.
|
// return 200 as to not reveal if the user exists. Recommended by spec.
|
||||||
return Ok(report_user::v3::Response::new());
|
return Ok(report_user::v3::Response::new());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ pub(crate) async fn get_login_types_route(
|
|||||||
ClientIp(client): ClientIp,
|
ClientIp(client): ClientIp,
|
||||||
_body: Ruma<get_login_types::v3::Request>,
|
_body: Ruma<get_login_types::v3::Request>,
|
||||||
) -> Result<get_login_types::v3::Response> {
|
) -> Result<get_login_types::v3::Response> {
|
||||||
if !services.config.oauth.compatibility_mode().uiaa_available() {
|
if !services.config.oauth.compatibility_mode.uiaa_available() {
|
||||||
return Err!(Request(Unrecognized(
|
return Err!(Request(Unrecognized(
|
||||||
"User-interactive authentication is not available on this server."
|
"User-interactive authentication is not available on this server."
|
||||||
)));
|
)));
|
||||||
@@ -88,6 +88,14 @@ pub async fn handle_login(
|
|||||||
UserId::parse_with_server_name(user_id_or_localpart, &services.config.server_name)
|
UserId::parse_with_server_name(user_id_or_localpart, &services.config.server_name)
|
||||||
.map_err(|_| err!(Request(InvalidUsername("User ID is malformed"))))?;
|
.map_err(|_| err!(Request(InvalidUsername("User ID is malformed"))))?;
|
||||||
|
|
||||||
|
if !services.globals.user_is_local(&user_id) {
|
||||||
|
return Err!(Request(InvalidParam("User ID does not belong to this homeserver")));
|
||||||
|
}
|
||||||
|
|
||||||
|
if services.users.is_deactivated(&user_id).await? {
|
||||||
|
return Err!(Request(UserDeactivated("This account has been deactivated.")));
|
||||||
|
}
|
||||||
|
|
||||||
if services.users.is_locked(&user_id).await? {
|
if services.users.is_locked(&user_id).await? {
|
||||||
return Err!(Request(UserLocked("This account has been locked.")));
|
return Err!(Request(UserLocked("This account has been locked.")));
|
||||||
}
|
}
|
||||||
@@ -120,7 +128,7 @@ pub(crate) async fn login_route(
|
|||||||
ClientIp(client): ClientIp,
|
ClientIp(client): ClientIp,
|
||||||
body: Ruma<login::v3::Request>,
|
body: Ruma<login::v3::Request>,
|
||||||
) -> Result<login::v3::Response> {
|
) -> Result<login::v3::Response> {
|
||||||
if !services.config.oauth.compatibility_mode().uiaa_available() {
|
if !services.config.oauth.compatibility_mode.uiaa_available() {
|
||||||
return match body.login_info {
|
return match body.login_info {
|
||||||
| LoginInfo::ApplicationService(_) => {
|
| LoginInfo::ApplicationService(_) => {
|
||||||
Err!(Request(AppserviceLoginUnsupported(
|
Err!(Request(AppserviceLoginUnsupported(
|
||||||
|
|||||||
@@ -32,26 +32,22 @@ pub(crate) async fn search_users_route(
|
|||||||
.min(LIMIT_MAX);
|
.min(LIMIT_MAX);
|
||||||
|
|
||||||
let search_term = body.search_term.to_lowercase();
|
let search_term = body.search_term.to_lowercase();
|
||||||
|
let mut users = services.users.stream().broad_filter_map(async |user_id| {
|
||||||
|
let display_name = services.users.displayname(&user_id).await.ok();
|
||||||
|
|
||||||
let mut users = services
|
let user_id_matches = user_id.as_str().to_lowercase().contains(&search_term);
|
||||||
.users
|
|
||||||
.stream_local_users()
|
|
||||||
.chain(services.users.stream_remote_users())
|
|
||||||
.broad_filter_map(async |user_id| {
|
|
||||||
let display_name = services.users.displayname(&user_id).await.ok();
|
|
||||||
|
|
||||||
let user_id_matches = user_id.as_str().to_lowercase().contains(&search_term);
|
let display_name_matches = display_name
|
||||||
|
.as_deref()
|
||||||
|
.map(str::to_lowercase)
|
||||||
|
.is_some_and(|display_name| display_name.contains(&search_term));
|
||||||
|
|
||||||
let display_name_matches = display_name
|
if !user_id_matches && !display_name_matches {
|
||||||
.as_deref()
|
return None;
|
||||||
.map(str::to_lowercase)
|
}
|
||||||
.is_some_and(|display_name| display_name.contains(&search_term));
|
|
||||||
|
|
||||||
if !user_id_matches && !display_name_matches {
|
let user_in_public_room =
|
||||||
return None;
|
services
|
||||||
}
|
|
||||||
|
|
||||||
let user_in_public_room = services
|
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.rooms_joined(&user_id)
|
.rooms_joined(&user_id)
|
||||||
@@ -64,22 +60,22 @@ pub(crate) async fn search_users_route(
|
|||||||
.await
|
.await
|
||||||
});
|
});
|
||||||
|
|
||||||
let user_sees_user = services
|
let user_sees_user = services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.user_sees_user(sender_user, &user_id);
|
.user_sees_user(sender_user, &user_id);
|
||||||
|
|
||||||
pin_mut!(user_in_public_room, user_sees_user);
|
pin_mut!(user_in_public_room, user_sees_user);
|
||||||
|
|
||||||
if user_in_public_room.or(user_sees_user).await {
|
if user_in_public_room.or(user_sees_user).await {
|
||||||
Some(assign!(search_users::v3::User::new(user_id.clone()), {
|
Some(assign!(search_users::v3::User::new(user_id.clone()), {
|
||||||
display_name,
|
display_name,
|
||||||
avatar_url: services.users.avatar_url(&user_id).await.ok(),
|
avatar_url: services.users.avatar_url(&user_id).await.ok(),
|
||||||
}))
|
}))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let results = users.by_ref().take(limit).collect().await;
|
let results = users.by_ref().take(limit).collect().await;
|
||||||
let limited = users.next().await.is_some();
|
let limited = users.next().await.is_some();
|
||||||
|
|||||||
@@ -7,7 +7,10 @@ use ruma::{
|
|||||||
api::federation::query::{get_profile_information, get_room_information},
|
api::federation::query::{get_profile_information, get_room_information},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::Ruma;
|
use crate::{
|
||||||
|
Ruma,
|
||||||
|
client::{get_local_profile, get_local_profile_field},
|
||||||
|
};
|
||||||
|
|
||||||
/// # `GET /_matrix/federation/v1/query/directory`
|
/// # `GET /_matrix/federation/v1/query/directory`
|
||||||
///
|
///
|
||||||
@@ -72,19 +75,15 @@ pub(crate) async fn get_profile_information_route(
|
|||||||
let response = if let Some(field) = &body.field {
|
let response = if let Some(field) = &body.field {
|
||||||
let mut response = get_profile_information::v1::Response::new();
|
let mut response = get_profile_information::v1::Response::new();
|
||||||
|
|
||||||
if let Some(value) = services
|
if let Some(value) =
|
||||||
.users
|
get_local_profile_field(&services, &body.user_id, field.to_owned()).await
|
||||||
.get_local_profile_field(&body.user_id, field.to_owned())
|
|
||||||
.await
|
|
||||||
{
|
{
|
||||||
response.set(value.field_name().as_str().to_owned(), value.value().into_owned());
|
response.set(value.field_name().as_str().to_owned(), value.value().into_owned());
|
||||||
}
|
}
|
||||||
|
|
||||||
response
|
response
|
||||||
} else {
|
} else {
|
||||||
services
|
get_local_profile(&services, &body.user_id)
|
||||||
.users
|
|
||||||
.get_local_profile(&body.user_id)
|
|
||||||
.await
|
.await
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.collect()
|
.collect()
|
||||||
|
|||||||
@@ -620,9 +620,8 @@ async fn handle_edu_direct_to_device(
|
|||||||
.broad_filter_map(|(target_user_id, map)| async move {
|
.broad_filter_map(|(target_user_id, map)| async move {
|
||||||
services
|
services
|
||||||
.users
|
.users
|
||||||
.status(&target_user_id)
|
.is_active_local(&target_user_id)
|
||||||
.await
|
.await
|
||||||
.is_active()
|
|
||||||
.then_some((target_user_id, map))
|
.then_some((target_user_id, map))
|
||||||
})
|
})
|
||||||
.for_each_concurrent(automatic_width(), |(target_user_id, map)| {
|
.for_each_concurrent(automatic_width(), |(target_user_id, map)| {
|
||||||
|
|||||||
@@ -118,7 +118,6 @@ url.workspace = true
|
|||||||
parking_lot.workspace = true
|
parking_lot.workspace = true
|
||||||
lock_api.workspace = true
|
lock_api.workspace = true
|
||||||
hyper-util.workspace = true
|
hyper-util.workspace = true
|
||||||
openidconnect.workspace = true
|
|
||||||
|
|
||||||
[target.'cfg(unix)'.dependencies]
|
[target.'cfg(unix)'.dependencies]
|
||||||
nix.workspace = true
|
nix.workspace = true
|
||||||
|
|||||||
@@ -289,15 +289,6 @@ pub fn check(config: &Config) -> Result {
|
|||||||
| _ => (),
|
| _ => (),
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(oidc) = &config.oauth.oidc
|
|
||||||
&& oidc.client_secret.is_none()
|
|
||||||
&& oidc.client_secret_file.is_none()
|
|
||||||
{
|
|
||||||
return Err!(
|
|
||||||
"Either `client_secret` or `client_secret_file` must be set if OIDC is configured."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-140
@@ -4,7 +4,7 @@ pub mod manager;
|
|||||||
pub mod proxy;
|
pub mod proxy;
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, BTreeSet, HashMap},
|
collections::{BTreeMap, BTreeSet},
|
||||||
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
|
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
};
|
};
|
||||||
@@ -17,12 +17,10 @@ use either::{
|
|||||||
use figment::providers::{Env, Format, Toml};
|
use figment::providers::{Env, Format, Toml};
|
||||||
pub use figment::{Figment, value::Value as FigmentValue};
|
pub use figment::{Figment, value::Value as FigmentValue};
|
||||||
use lettre::message::Mailbox;
|
use lettre::message::Mailbox;
|
||||||
use openidconnect::{ClientId, ClientSecret, Scope};
|
|
||||||
use regex::RegexSet;
|
use regex::RegexSet;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomVersionId,
|
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomVersionId,
|
||||||
api::client::{discovery::discover_support::ContactRole, rtc::RtcTransport},
|
api::client::{discovery::discover_support::ContactRole, rtc::RtcTransport},
|
||||||
profile::ProfileFieldName,
|
|
||||||
serde::Base64,
|
serde::Base64,
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize, de::IgnoredAny};
|
use serde::{Deserialize, Serialize, de::IgnoredAny};
|
||||||
@@ -2421,24 +2419,10 @@ pub struct OauthConfig {
|
|||||||
/// legacy authentication will be unable to log in.
|
/// legacy authentication will be unable to log in.
|
||||||
///
|
///
|
||||||
/// default: "hybrid"
|
/// default: "hybrid"
|
||||||
compatibility_mode: OAuthMode,
|
pub compatibility_mode: OAuthMode,
|
||||||
|
|
||||||
/// display: hidden
|
|
||||||
pub oidc: Option<OidcConfig>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl OauthConfig {
|
#[derive(Clone, Debug, Default, Deserialize)]
|
||||||
#[must_use]
|
|
||||||
pub fn compatibility_mode(&self) -> OAuthMode {
|
|
||||||
if self.oidc.is_some() {
|
|
||||||
OAuthMode::Exclusive
|
|
||||||
} else {
|
|
||||||
self.compatibility_mode
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, Deserialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum OAuthMode {
|
pub enum OAuthMode {
|
||||||
Disabled,
|
Disabled,
|
||||||
@@ -2455,121 +2439,6 @@ impl OAuthMode {
|
|||||||
pub fn oauth_available(&self) -> bool { matches!(self, Self::Hybrid | Self::Exclusive) }
|
pub fn oauth_available(&self) -> bool { matches!(self, Self::Hybrid | Self::Exclusive) }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize)]
|
|
||||||
#[config_example_generator(
|
|
||||||
filename = "conduwuit-example.toml",
|
|
||||||
section = "global.oauth.oidc",
|
|
||||||
optional = "true",
|
|
||||||
subheader = "\
|
|
||||||
# Uncommenting this section will enable Continuwuity's support for
|
|
||||||
# authenticating users using an OpenID Connect-compatible identity provider.
|
|
||||||
# This is referred to as \"delegated authentication\".
|
|
||||||
#
|
|
||||||
# IMPORTANT NOTE: When delegated authentication is active, Continuwuity will behave as if
|
|
||||||
# the `global.oauth.compatibility_mode` setting is set to `exclusive`.
|
|
||||||
# Matrix clients which do not support OAuth login (also referred to as \"next-gen auth\") will \
|
|
||||||
NOT be able
|
|
||||||
# to log in while delegated authentication is active."
|
|
||||||
)]
|
|
||||||
pub struct OidcConfig {
|
|
||||||
/// The OIDC issuer URL. Continuwuity will use OpenID Connect Discovery to
|
|
||||||
/// 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,
|
|
||||||
|
|
||||||
/// The OAuth client ID for Continuwuity to use when communicating with the
|
|
||||||
/// identity provider.
|
|
||||||
pub client_id: ClientId,
|
|
||||||
|
|
||||||
/// The OAuth client secret for Continuwuity to use when communicating with
|
|
||||||
/// the identity provider.
|
|
||||||
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`.
|
|
||||||
///
|
|
||||||
/// The server will fail to start if the file cannot be read.
|
|
||||||
pub client_secret_file: Option<PathBuf>,
|
|
||||||
|
|
||||||
/// Additional scopes Continuwuity should request from the IDP. This may be
|
|
||||||
/// necessary to access certain claims. Continuwuity always requests the
|
|
||||||
/// `openid` scope.
|
|
||||||
///
|
|
||||||
/// default: []
|
|
||||||
#[serde(default)]
|
|
||||||
pub additional_scopes: Vec<Scope>,
|
|
||||||
|
|
||||||
/// Whether the user should be prompted to choose a localpart
|
|
||||||
/// when signing in for the first time. If this is `false`, Continuwuity
|
|
||||||
/// will attempt to use the value of the `preferred_username_claim`
|
|
||||||
/// (see below) as the user's localpart. Authentication will
|
|
||||||
/// fail if this claim is missing or is not a valid localpart.
|
|
||||||
///
|
|
||||||
/// default: true
|
|
||||||
#[serde(default = "true_fn")]
|
|
||||||
pub prompt_for_localpart: bool,
|
|
||||||
|
|
||||||
/// The claim to use for the user's localpart, if `prompt_for_localpart` is
|
|
||||||
/// false.
|
|
||||||
///
|
|
||||||
/// default: "preferred_username"
|
|
||||||
#[serde(default = "default_preferred_username_claim")]
|
|
||||||
pub preferred_username_claim: String,
|
|
||||||
|
|
||||||
/// The claim which will be used to set the user's email address,
|
|
||||||
/// either on initial registration or on every login depending on
|
|
||||||
/// the value of `profile_key_import_mode`. Continuwuity assumes that
|
|
||||||
/// the IDP has taken care of verifying that the user controls the email
|
|
||||||
/// address it provides.
|
|
||||||
///
|
|
||||||
/// This option does nothing if SMTP is not configured.
|
|
||||||
///
|
|
||||||
/// If this option is set, and `profile_key_import_mode` is `on_login`,
|
|
||||||
/// users will not be able to change their email addresses themselves.
|
|
||||||
///
|
|
||||||
/// default: "email"
|
|
||||||
pub email_claim: Option<String>,
|
|
||||||
|
|
||||||
/// Defines how claims returned from the IDP should be mapped to a user's
|
|
||||||
/// profile data. The profile field named in each key will be set from the
|
|
||||||
/// claim named in the corresponding value when the user first registers,
|
|
||||||
/// and possibly on subsequent logins as well, depending on the value of
|
|
||||||
/// `profile_key_import_mode` (see below).
|
|
||||||
///
|
|
||||||
/// Per-room overrides to the user's display name or avatar will be
|
|
||||||
/// preserved by the import process.
|
|
||||||
///
|
|
||||||
/// SECURITY NOTE: If the `avatar_url` field is set, Continuwuity will
|
|
||||||
/// perform a HTTP GET to the URL in the mapped claim and use the returned
|
|
||||||
/// file as the user's profile picture. Make sure your users are not able
|
|
||||||
/// to set the value of the mapped claim to an arbitrary URL.
|
|
||||||
///
|
|
||||||
/// default: { displayname = "name" }
|
|
||||||
#[serde(default = "default_profile_key_map")]
|
|
||||||
pub profile_key_map: HashMap<String, String>,
|
|
||||||
|
|
||||||
/// When profile keys should be imported from the IDP's claims.
|
|
||||||
///
|
|
||||||
/// - "on_registration": Listed keys will be imported once, when the user
|
|
||||||
/// logs in for the first time and their shadow account is created.
|
|
||||||
/// - "on_login": Listed keys will be imported every time the user logs in.
|
|
||||||
/// Additionally, users will not be able to manually edit any listed keys
|
|
||||||
/// through their Matrix client.
|
|
||||||
///
|
|
||||||
/// default: "on_registration"
|
|
||||||
#[serde(default)]
|
|
||||||
pub profile_key_import_mode: OidcProfileKeyImportMode,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Default)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub enum OidcProfileKeyImportMode {
|
|
||||||
#[default]
|
|
||||||
OnRegistration,
|
|
||||||
OnLogin,
|
|
||||||
}
|
|
||||||
|
|
||||||
const DEPRECATED_KEYS: &[&str] = &[
|
const DEPRECATED_KEYS: &[&str] = &[
|
||||||
"cache_capacity",
|
"cache_capacity",
|
||||||
"conduit_cache_capacity_modifier",
|
"conduit_cache_capacity_modifier",
|
||||||
@@ -2954,9 +2823,3 @@ fn default_client_shutdown_timeout() -> u64 { 15 }
|
|||||||
fn default_sender_shutdown_timeout() -> u64 { 5 }
|
fn default_sender_shutdown_timeout() -> u64 { 5 }
|
||||||
|
|
||||||
fn default_terms_language() -> String { "en".to_owned() }
|
fn default_terms_language() -> String { "en".to_owned() }
|
||||||
|
|
||||||
fn default_preferred_username_claim() -> String { "preferred_username".to_owned() }
|
|
||||||
|
|
||||||
fn default_profile_key_map() -> HashMap<String, String> {
|
|
||||||
HashMap::from_iter([(ProfileFieldName::DisplayName.to_string(), "name".to_owned())])
|
|
||||||
}
|
|
||||||
@@ -124,14 +124,6 @@ pub(super) static MAPS: &[Descriptor] = &[
|
|||||||
name: "onetimekeyid_onetimekeys",
|
name: "onetimekeyid_onetimekeys",
|
||||||
..descriptor::RANDOM_SMALL
|
..descriptor::RANDOM_SMALL
|
||||||
},
|
},
|
||||||
Descriptor {
|
|
||||||
name: "openidsubject_localpart",
|
|
||||||
..descriptor::RANDOM_SMALL
|
|
||||||
},
|
|
||||||
Descriptor {
|
|
||||||
name: "openidsubject_currentpictureurl",
|
|
||||||
..descriptor::RANDOM_SMALL
|
|
||||||
},
|
|
||||||
Descriptor {
|
Descriptor {
|
||||||
name: "fallbackkeyid_fallbackkey",
|
name: "fallbackkeyid_fallbackkey",
|
||||||
..descriptor::RANDOM_SMALL
|
..descriptor::RANDOM_SMALL
|
||||||
@@ -177,10 +169,6 @@ pub(super) static MAPS: &[Descriptor] = &[
|
|||||||
name: "registrationtoken_info",
|
name: "registrationtoken_info",
|
||||||
..descriptor::RANDOM_SMALL
|
..descriptor::RANDOM_SMALL
|
||||||
},
|
},
|
||||||
Descriptor {
|
|
||||||
name: "remoteuserid_remoteuser",
|
|
||||||
..descriptor::RANDOM
|
|
||||||
},
|
|
||||||
Descriptor {
|
Descriptor {
|
||||||
name: "roomid_invitedcount",
|
name: "roomid_invitedcount",
|
||||||
..descriptor::RANDOM_SMALL
|
..descriptor::RANDOM_SMALL
|
||||||
@@ -410,10 +398,6 @@ pub(super) static MAPS: &[Descriptor] = &[
|
|||||||
name: "userid_blurhash",
|
name: "userid_blurhash",
|
||||||
..descriptor::DROPPED
|
..descriptor::DROPPED
|
||||||
},
|
},
|
||||||
Descriptor {
|
|
||||||
name: "userid_deactivated",
|
|
||||||
..descriptor::RANDOM_SMALL
|
|
||||||
},
|
|
||||||
Descriptor {
|
Descriptor {
|
||||||
name: "userid_dehydrateddevice",
|
name: "userid_dehydrateddevice",
|
||||||
..descriptor::RANDOM_SMALL
|
..descriptor::RANDOM_SMALL
|
||||||
|
|||||||
@@ -81,12 +81,6 @@ fn generate_example(input: &ItemStruct, args: &[Meta], write: bool) -> Result<To
|
|||||||
};
|
};
|
||||||
file.write_fmt(format_args!("{section_header}"))
|
file.write_fmt(format_args!("{section_header}"))
|
||||||
.expect("written to config file");
|
.expect("written to config file");
|
||||||
|
|
||||||
if let Some(subheader) = settings.get("subheader") {
|
|
||||||
file.write_all(subheader.as_bytes())
|
|
||||||
.expect("written to config file");
|
|
||||||
file.write_all(b"\n\n").expect("written to config file");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut summary: Vec<TokenStream2> = Vec::new();
|
let mut summary: Vec<TokenStream2> = Vec::new();
|
||||||
|
|||||||
@@ -120,7 +120,6 @@ reqwest_recaptcha = { package = "reqwest", version = "0.12.28", default-features
|
|||||||
yansi.workspace = true
|
yansi.workspace = true
|
||||||
lettre.workspace = true
|
lettre.workspace = true
|
||||||
serde_urlencoded.workspace = true
|
serde_urlencoded.workspace = true
|
||||||
openidconnect.workspace = true
|
|
||||||
|
|
||||||
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
|
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
|
||||||
sd-notify.workspace = true
|
sd-notify.workspace = true
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ pub async fn create_admin_room(services: &Services) -> Result {
|
|||||||
|
|
||||||
// Create a user for the server
|
// Create a user for the server
|
||||||
let server_user = services.globals.server_user.as_ref();
|
let server_user = services.globals.server_user.as_ref();
|
||||||
services.users.create_shadow_account(server_user).await?;
|
services.users.create(server_user, None)?;
|
||||||
|
|
||||||
let mut create_content = if room_version_rules.authorization.use_room_create_sender {
|
let mut create_content = if room_version_rules.authorization.use_room_create_sender {
|
||||||
RoomCreateEventContent::new_v1(server_user.into())
|
RoomCreateEventContent::new_v1(server_user.into())
|
||||||
|
|||||||
@@ -108,17 +108,17 @@ impl Service {
|
|||||||
self.services.globals.server_name(),
|
self.services.globals.server_name(),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
if !self
|
if !self.services.users.exists(&appservice_user_id).await {
|
||||||
|
self.services.users.create(&appservice_user_id, None)?;
|
||||||
|
} else if self
|
||||||
.services
|
.services
|
||||||
.users
|
.users
|
||||||
.status(&appservice_user_id)
|
.is_deactivated(&appservice_user_id)
|
||||||
.await
|
.await
|
||||||
.is_found()
|
.unwrap_or(false)
|
||||||
{
|
{
|
||||||
self.services
|
// Reactivate the appservice user if it was accidentally deactivated
|
||||||
.users
|
self.services.users.set_password(&appservice_user_id, None);
|
||||||
.create_shadow_account(&appservice_user_id)
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.registration_info
|
self.registration_info
|
||||||
|
|||||||
@@ -54,22 +54,15 @@ impl Service {
|
|||||||
async fn set_emergency_access(&self) -> Result {
|
async fn set_emergency_access(&self) -> Result {
|
||||||
let server_user = &self.services.globals.server_user;
|
let server_user = &self.services.globals.server_user;
|
||||||
|
|
||||||
match &self.services.config.emergency_password {
|
self.services.users.set_password(
|
||||||
| Some(emergency_password) => {
|
server_user,
|
||||||
let emergency_password = HashedPassword::new(emergency_password)?;
|
self.services
|
||||||
|
.config
|
||||||
self.services
|
.emergency_password
|
||||||
.users
|
.as_deref()
|
||||||
.convert_to_local_account(server_user, emergency_password)
|
.map(HashedPassword::new)
|
||||||
.await?;
|
.transpose()?,
|
||||||
},
|
);
|
||||||
| None => {
|
|
||||||
self.services
|
|
||||||
.users
|
|
||||||
.convert_to_shadow_account(server_user)
|
|
||||||
.await?;
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
let (ruleset, pwd_set) = match self.services.config.emergency_password {
|
let (ruleset, pwd_set) = match self.services.config.emergency_password {
|
||||||
| Some(_) => (Ruleset::server_default(server_user), true),
|
| Some(_) => (Ruleset::server_default(server_user), true),
|
||||||
|
|||||||
@@ -211,6 +211,7 @@ impl Service {
|
|||||||
Ok(preview_data)
|
Ok(preview_data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "url_preview")]
|
||||||
pub async fn download_media(&self, url: &str) -> Result<(OwnedMxcUri, usize)> {
|
pub async fn download_media(&self, url: &str) -> Result<(OwnedMxcUri, usize)> {
|
||||||
use conduwuit::utils::random_string;
|
use conduwuit::utils::random_string;
|
||||||
use http::header::CONTENT_TYPE;
|
use http::header::CONTENT_TYPE;
|
||||||
@@ -267,6 +268,11 @@ impl Service {
|
|||||||
Err!(FeatureDisabled("url_preview"))
|
Err!(FeatureDisabled("url_preview"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "url_preview"))]
|
||||||
|
pub async fn download_media(&self, _url: &str) -> Result<UrlPreviewData> {
|
||||||
|
Err!(FeatureDisabled("url_preview"))
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(feature = "url_preview")]
|
#[cfg(feature = "url_preview")]
|
||||||
async fn download_html(&self, url: &str) -> Result<UrlPreviewData> {
|
async fn download_html(&self, url: &str) -> Result<UrlPreviewData> {
|
||||||
use webpage::HTML;
|
use webpage::HTML;
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ pub(crate) async fn migrations(services: &Services) -> Result<()> {
|
|||||||
// requires recreating the database from scratch.
|
// requires recreating the database from scratch.
|
||||||
if users_count > 0 {
|
if users_count > 0 {
|
||||||
let server_user = &services.globals.server_user;
|
let server_user = &services.globals.server_user;
|
||||||
if !services.users.status(server_user).await.is_found() {
|
if !services.users.exists(server_user).await {
|
||||||
error!("The {server_user} server user does not exist, and the database is not new.");
|
error!("The {server_user} server user does not exist, and the database is not new.");
|
||||||
return Err!(Database(
|
return Err!(Database(
|
||||||
"Cannot reuse an existing database after changing the server name, please \
|
"Cannot reuse an existing database after changing the server name, please \
|
||||||
@@ -228,18 +228,6 @@ async fn migrate(services: &Services) -> Result<()> {
|
|||||||
.map_err(|e| err!("Failed to run 'fix_local_invite_state' migration': {e}"))?;
|
.map_err(|e| err!("Failed to run 'fix_local_invite_state' migration': {e}"))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if services.globals.db.database_version().await < 18 {
|
|
||||||
services.globals.db.bump_database_version(18);
|
|
||||||
info!("Migration: Bumped database version to 18");
|
|
||||||
}
|
|
||||||
|
|
||||||
if db["global"].get(SPLIT_USERID_PASSWORD).await.is_not_found() {
|
|
||||||
info!("Running migration 'split_userid_password'");
|
|
||||||
split_userid_password(services)
|
|
||||||
.await
|
|
||||||
.map_err(|e| err!("Failed to run 'split_userid_password' migration': {e}"))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
services.globals.db.database_version().await,
|
services.globals.db.database_version().await,
|
||||||
DATABASE_VERSION,
|
DATABASE_VERSION,
|
||||||
@@ -254,9 +242,9 @@ async fn migrate(services: &Services) -> Result<()> {
|
|||||||
if !patterns.is_empty() {
|
if !patterns.is_empty() {
|
||||||
services
|
services
|
||||||
.users
|
.users
|
||||||
.stream_local_users()
|
.stream()
|
||||||
.filter_map(async |user_id| {
|
.filter_map(async |user_id| {
|
||||||
if services.users.status(&user_id).await.is_found() {
|
if services.users.is_active_local(&user_id).await {
|
||||||
Some(user_id)
|
Some(user_id)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@@ -786,7 +774,7 @@ async fn fix_local_invite_state(services: &Services) -> Result {
|
|||||||
|
|
||||||
let db = &services.db;
|
let db = &services.db;
|
||||||
let cork = db.cork_and_sync();
|
let cork = db.cork_and_sync();
|
||||||
let userroomid_invitestate = db["userroomid_invitestate"].clone();
|
let userroomid_invitestate = services.db["userroomid_invitestate"].clone();
|
||||||
|
|
||||||
// for each user invited to a room
|
// for each user invited to a room
|
||||||
let fixed = userroomid_invitestate.stream()
|
let fixed = userroomid_invitestate.stream()
|
||||||
@@ -830,44 +818,3 @@ async fn fix_local_invite_state(services: &Services) -> Result {
|
|||||||
db.db.sort()?;
|
db.db.sort()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
const SPLIT_USERID_PASSWORD: &str = "split_userid_password";
|
|
||||||
async fn split_userid_password(services: &Services) -> Result {
|
|
||||||
// Split remote and deactivated users out from the `userid_password` table
|
|
||||||
|
|
||||||
let db = &services.db;
|
|
||||||
let cork = db.cork_and_sync();
|
|
||||||
let userid_password = db["userid_password"].clone();
|
|
||||||
let remoteuserid_remoteuser = db["remoteuserid_remoteuser"].clone();
|
|
||||||
let userid_deactivated = db["userid_deactivated"].clone();
|
|
||||||
|
|
||||||
let remote_users = userid_password
|
|
||||||
.stream::<OwnedUserId, String>()
|
|
||||||
.ignore_err()
|
|
||||||
.fold(0_usize, async |mut remote_users, (user_id, hash)| {
|
|
||||||
if !services.globals.user_is_local(&user_id) {
|
|
||||||
assert!(hash.is_empty(), "non-empty hash {hash} for remote user {user_id}");
|
|
||||||
|
|
||||||
remoteuserid_remoteuser.insert(&user_id, "");
|
|
||||||
userid_password.remove(&user_id);
|
|
||||||
remote_users = remote_users.saturating_add(1);
|
|
||||||
} else if hash.is_empty() {
|
|
||||||
if !(services.appservice.is_exclusive_user_id(&user_id).await
|
|
||||||
|| user_id == services.globals.server_user)
|
|
||||||
{
|
|
||||||
info!("Marking {user_id} as deactivated");
|
|
||||||
userid_deactivated.insert(&user_id, "");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
remote_users
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
drop(cork);
|
|
||||||
info!(?remote_users, "Split userid_password.");
|
|
||||||
|
|
||||||
db["global"].insert(FIXED_LOCAL_INVITE_STATE_MARKER, []);
|
|
||||||
db.db.sort()?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -28,7 +28,6 @@ pub mod mailer;
|
|||||||
pub mod media;
|
pub mod media;
|
||||||
pub mod moderation;
|
pub mod moderation;
|
||||||
pub mod oauth;
|
pub mod oauth;
|
||||||
pub mod oidc;
|
|
||||||
pub mod presence;
|
pub mod presence;
|
||||||
pub mod pusher;
|
pub mod pusher;
|
||||||
pub mod registration_tokens;
|
pub mod registration_tokens;
|
||||||
|
|||||||
@@ -160,7 +160,7 @@ pub enum ErrorCode {
|
|||||||
InvalidClientMetadata,
|
InvalidClientMetadata,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize)]
|
||||||
pub struct AuthorizationCodeResponse {
|
pub struct AuthorizationCodeResponse {
|
||||||
pub state: String,
|
pub state: String,
|
||||||
pub code: String,
|
pub code: String,
|
||||||
|
|||||||
@@ -1,484 +0,0 @@
|
|||||||
use std::{collections::HashMap, str::FromStr, sync::Arc, time::Duration};
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use conduwuit::{
|
|
||||||
Result,
|
|
||||||
config::{OidcConfig, OidcProfileKeyImportMode},
|
|
||||||
debug, err, error, info, warn,
|
|
||||||
};
|
|
||||||
use database::{Deserialized, Map};
|
|
||||||
use lettre::Address;
|
|
||||||
use openidconnect::{
|
|
||||||
AdditionalClaims, AuthorizationCode, ClientSecret, CsrfToken, EmptyExtraTokenFields,
|
|
||||||
EndpointMaybeSet, EndpointNotSet, EndpointSet, IdTokenClaims, IdTokenFields, IssuerUrl,
|
|
||||||
Nonce, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, 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,
|
|
||||||
profile::{ProfileFieldName, ProfileFieldValue},
|
|
||||||
};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use serde_json::Value;
|
|
||||||
use tokio::{runtime, sync::SetOnce};
|
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
Dep, config, globals, media,
|
|
||||||
oauth::grant::AuthorizationCodeResponse,
|
|
||||||
threepid,
|
|
||||||
users::{self, AccountStatus, ProfileFieldChange},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct Service {
|
|
||||||
services: Services,
|
|
||||||
runtime: runtime::Handle,
|
|
||||||
db: Data,
|
|
||||||
client: Option<OidcClient>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Data {
|
|
||||||
openidsubject_localpart: Arc<Map>,
|
|
||||||
openidsubject_currentpictureurl: Arc<Map>,
|
|
||||||
}
|
|
||||||
struct Services {
|
|
||||||
config: Dep<config::Service>,
|
|
||||||
globals: Dep<globals::Service>,
|
|
||||||
media: Dep<media::Service>,
|
|
||||||
threepid: Dep<threepid::Service>,
|
|
||||||
users: Dep<users::Service>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct OidcClient {
|
|
||||||
config: OidcConfig,
|
|
||||||
client_secret: ClientSecret,
|
|
||||||
machine: SetOnce<OidcClientMachine>,
|
|
||||||
client: reqwest::Client,
|
|
||||||
}
|
|
||||||
|
|
||||||
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 AllClaims {
|
|
||||||
#[serde(flatten)]
|
|
||||||
pub claims: HashMap<String, Value>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AdditionalClaims for AllClaims {}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
|
||||||
pub struct PendingSession {
|
|
||||||
pkce_verifier: PkceCodeVerifier,
|
|
||||||
nonce: Nonce,
|
|
||||||
csrf_token: CsrfToken,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub enum SessionCompletionStatus {
|
|
||||||
NeedsUserId,
|
|
||||||
Complete(OwnedUserId),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl crate::Service for Service {
|
|
||||||
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
|
||||||
Ok(Arc::new(Self {
|
|
||||||
services: Services {
|
|
||||||
config: args.depend::<config::Service>("config"),
|
|
||||||
globals: args.depend::<globals::Service>("globals"),
|
|
||||||
media: args.depend::<media::Service>("media"),
|
|
||||||
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(),
|
|
||||||
openidsubject_currentpictureurl: args.db["openidsubject_currentpictureurl"].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(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()
|
|
||||||
.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 { config, client_secret, machine, client }) = &self.client {
|
|
||||||
let redirect_url = self
|
|
||||||
.services
|
|
||||||
.config
|
|
||||||
.get_client_domain()
|
|
||||||
.join(&format!("{}/oidc/complete", conduwuit::ROUTE_PREFIX))
|
|
||||||
.expect("redirect url should be valid");
|
|
||||||
|
|
||||||
let provider_metadata = CoreProviderMetadata::discover_async(
|
|
||||||
IssuerUrl::from_url(config.discovery_url.clone()),
|
|
||||||
client,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.map_err(|err| err!("Failed to discover OIDC provider metadata: {err}"))?;
|
|
||||||
|
|
||||||
machine
|
|
||||||
.set(
|
|
||||||
OidcClientMachine::from_provider_metadata(
|
|
||||||
provider_metadata,
|
|
||||||
config.client_id.clone(),
|
|
||||||
Some(client_secret.clone()),
|
|
||||||
)
|
|
||||||
.set_redirect_uri(RedirectUrl::from_url(redirect_url)),
|
|
||||||
)
|
|
||||||
.expect("machine should be empty");
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Service {
|
|
||||||
const SERVER_MISCONFIGURED: &str =
|
|
||||||
"Identity server is misconfigured. Contact your homeserver's administrator.";
|
|
||||||
|
|
||||||
pub fn enabled(&self) -> bool { self.client.is_some() }
|
|
||||||
|
|
||||||
pub fn restricted_profile_fields(&self) -> Vec<ProfileFieldName> {
|
|
||||||
if let Some(config) = self.client.as_ref().map(|client| &client.config)
|
|
||||||
&& matches!(config.profile_key_import_mode, OidcProfileKeyImportMode::OnLogin)
|
|
||||||
{
|
|
||||||
config
|
|
||||||
.profile_key_map
|
|
||||||
.keys()
|
|
||||||
.map(|key| ProfileFieldName::from(key.as_str()))
|
|
||||||
.collect()
|
|
||||||
} else {
|
|
||||||
vec![]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 machine = machine.wait().await;
|
|
||||||
|
|
||||||
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
|
|
||||||
|
|
||||||
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);
|
|
||||||
|
|
||||||
if let Some(prompt) = prompt {
|
|
||||||
auth_url = auth_url.add_prompt(prompt);
|
|
||||||
}
|
|
||||||
|
|
||||||
let (auth_url, csrf_token, nonce) = auth_url.url();
|
|
||||||
|
|
||||||
(PendingSession { pkce_verifier, nonce, csrf_token }, auth_url)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn exchange_code(
|
|
||||||
&self,
|
|
||||||
session: PendingSession,
|
|
||||||
response: AuthorizationCodeResponse,
|
|
||||||
) -> Result<Claims, &'static str> {
|
|
||||||
let Some(OidcClient { machine, client, .. }) = self.client.as_ref() else {
|
|
||||||
return Err("Delegated authentication is not enabled on this server.");
|
|
||||||
};
|
|
||||||
|
|
||||||
let machine = machine.wait().await;
|
|
||||||
|
|
||||||
if session.csrf_token.into_secret() != response.state {
|
|
||||||
return Err("State mismatch.");
|
|
||||||
}
|
|
||||||
|
|
||||||
let token_response = machine
|
|
||||||
.exchange_code(AuthorizationCode::new(response.code))
|
|
||||||
.expect("machine should be configured correctly")
|
|
||||||
.set_pkce_verifier(session.pkce_verifier)
|
|
||||||
.request_async(client)
|
|
||||||
.await
|
|
||||||
.map_err(|err| {
|
|
||||||
error!("Failed to exchange OIDC authorization code: {err}");
|
|
||||||
"Code exchange failed."
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let Some(id_token) = token_response.id_token() else {
|
|
||||||
error!("Identity server did not return an id token");
|
|
||||||
return Err(Self::SERVER_MISCONFIGURED);
|
|
||||||
};
|
|
||||||
|
|
||||||
let claims = id_token
|
|
||||||
.claims(&machine.id_token_verifier(), &session.nonce)
|
|
||||||
.map_err(|err| {
|
|
||||||
error!("Failed to verify id token claims: {err}");
|
|
||||||
Self::SERVER_MISCONFIGURED
|
|
||||||
})?
|
|
||||||
.to_owned();
|
|
||||||
|
|
||||||
info!(subject = claims.subject().as_str(), "Authenticated subject");
|
|
||||||
|
|
||||||
Ok(claims)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tracing::instrument(skip(self, claims), fields(subject = claims.subject().to_string()))]
|
|
||||||
pub async fn complete_session(
|
|
||||||
&self,
|
|
||||||
claims: &Claims,
|
|
||||||
supplied_user_id: Option<OwnedUserId>,
|
|
||||||
) -> Result<SessionCompletionStatus, &'static str> {
|
|
||||||
let Some(OidcClient { config, .. }) = self.client.as_ref() else {
|
|
||||||
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!(?all_claims);
|
|
||||||
|
|
||||||
let subject = claims.subject().as_str();
|
|
||||||
|
|
||||||
let user_id = if let Ok(localpart) = self
|
|
||||||
.db
|
|
||||||
.openidsubject_localpart
|
|
||||||
.get(subject)
|
|
||||||
.await
|
|
||||||
.deserialized::<String>()
|
|
||||||
{
|
|
||||||
UserId::parse(format!("@{localpart}:{}", self.services.globals.server_name()))
|
|
||||||
.expect("saved localpart should be valid")
|
|
||||||
} else if config.prompt_for_localpart {
|
|
||||||
if let Some(supplied_user_id) = supplied_user_id {
|
|
||||||
supplied_user_id
|
|
||||||
} else {
|
|
||||||
return Ok(SessionCompletionStatus::NeedsUserId);
|
|
||||||
}
|
|
||||||
} else if let Some(preferred_username) = all_claims
|
|
||||||
.get(&config.preferred_username_claim)
|
|
||||||
.and_then(|claim| claim.as_str())
|
|
||||||
{
|
|
||||||
self.services
|
|
||||||
.users
|
|
||||||
.determine_registration_user_id(Some(preferred_username.to_owned()), None, None)
|
|
||||||
.await
|
|
||||||
.map_err(|err| {
|
|
||||||
error!("Preferred username claim is not a valid localpart: {err}");
|
|
||||||
"Your preferred username is not a valid Matrix user ID localpart. Contact \
|
|
||||||
your homeserver's administrator."
|
|
||||||
})?
|
|
||||||
} else {
|
|
||||||
error!("Preferred username claim was not present or was not a string");
|
|
||||||
return Err(Self::SERVER_MISCONFIGURED);
|
|
||||||
};
|
|
||||||
|
|
||||||
info!(?subject, ?user_id, "User {user_id} successfully authorized with OIDC");
|
|
||||||
|
|
||||||
// Create a shadow account for the user if necessary
|
|
||||||
let new_account_registered = match self.services.users.status(&user_id).await {
|
|
||||||
| AccountStatus::Active => {
|
|
||||||
// Do nothing, an account already exists
|
|
||||||
false
|
|
||||||
},
|
|
||||||
| AccountStatus::NotFound => {
|
|
||||||
// Create a new shadow user
|
|
||||||
self.services
|
|
||||||
.users
|
|
||||||
.create_local_account(&user_id, None, None)
|
|
||||||
.await
|
|
||||||
.map_err(|err| {
|
|
||||||
error!("Failed to create a shadow user for {user_id}: {err}");
|
|
||||||
Self::SERVER_MISCONFIGURED
|
|
||||||
})?;
|
|
||||||
|
|
||||||
info!(?subject, ?user_id, "Shadow user created for {user_id}");
|
|
||||||
true
|
|
||||||
},
|
|
||||||
| AccountStatus::Deactivated => {
|
|
||||||
return Err("Your account has been deactivated.");
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
self.link_user(&user_id, subject);
|
|
||||||
|
|
||||||
// Import profile fields
|
|
||||||
if matches!(config.profile_key_import_mode, OidcProfileKeyImportMode::OnLogin)
|
|
||||||
|| (matches!(
|
|
||||||
config.profile_key_import_mode,
|
|
||||||
OidcProfileKeyImportMode::OnRegistration
|
|
||||||
) && new_account_registered)
|
|
||||||
{
|
|
||||||
if let Some(email_claim) = &config.email_claim {
|
|
||||||
if let Some(email) = claims.email().map(|email| email.as_str())
|
|
||||||
&& let Ok(address) = Address::from_str(email)
|
|
||||||
{
|
|
||||||
if let Err(err) = self
|
|
||||||
.services
|
|
||||||
.threepid
|
|
||||||
.associate_localpart_email(user_id.localpart(), &address)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
warn!(?email_claim, ?address, "Failed to associate email address: {err}");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
warn!(
|
|
||||||
?email_claim,
|
|
||||||
"Email claim was not present or was not a valid email address"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let user_id = user_id.clone();
|
|
||||||
let subject = claims.subject().to_string();
|
|
||||||
let profile_key_map = config.profile_key_map.clone();
|
|
||||||
let openidsubject_currentpictureurl = self.db.openidsubject_currentpictureurl.clone();
|
|
||||||
let users = self.services.users.clone();
|
|
||||||
let media = self.services.media.clone();
|
|
||||||
|
|
||||||
let import_task = self.runtime.spawn(async move {
|
|
||||||
for (field, claim) in &profile_key_map {
|
|
||||||
let Some(value) = all_claims.get(claim).cloned() else {
|
|
||||||
warn!(?field, ?claim, "IDP provided no value for this mapped claim");
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
let value = if let Some(picture_url) = value.as_str()
|
|
||||||
&& field == ProfileFieldName::AvatarUrl.as_str()
|
|
||||||
&& openidsubject_currentpictureurl
|
|
||||||
.get(&subject)
|
|
||||||
.await
|
|
||||||
.deserialized::<String>()
|
|
||||||
.ok()
|
|
||||||
.is_none_or(|current_picture| current_picture != picture_url)
|
|
||||||
{
|
|
||||||
match media.download_media(picture_url).await {
|
|
||||||
| Ok((mxc, size)) => {
|
|
||||||
openidsubject_currentpictureurl.insert(&subject, picture_url);
|
|
||||||
info!(?picture_url, ?mxc, ?size, "Downloaded profile picture");
|
|
||||||
|
|
||||||
ProfileFieldValue::AvatarUrl(mxc)
|
|
||||||
},
|
|
||||||
| Err(err) => {
|
|
||||||
warn!(
|
|
||||||
?claim,
|
|
||||||
?picture_url,
|
|
||||||
"Failed to download profile picture: {err}"
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
},
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
match ProfileFieldValue::new(field, value.clone()) {
|
|
||||||
| Ok(value) => value,
|
|
||||||
| Err(err) => {
|
|
||||||
warn!(
|
|
||||||
?field,
|
|
||||||
?claim,
|
|
||||||
?value,
|
|
||||||
"Failed to parse claim value for profile field: {err}"
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
},
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Err(err) = users
|
|
||||||
.set_profile_field(
|
|
||||||
&user_id,
|
|
||||||
ProfileFieldChange::Set(value),
|
|
||||||
PropagateTo::Unchanged,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
warn!(?field, ?claim, "Error while setting profile field: {err}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
info!("Profile import complete");
|
|
||||||
});
|
|
||||||
|
|
||||||
// Only wait for import to complete if this is a new account,
|
|
||||||
// so they see the correct profile information in the account panel
|
|
||||||
if new_account_registered {
|
|
||||||
let _ = import_task.await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(SessionCompletionStatus::Complete(user_id))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn link_user(&self, user_id: &UserId, subject: &str) {
|
|
||||||
self.db
|
|
||||||
.openidsubject_localpart
|
|
||||||
.insert(subject, user_id.localpart());
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn unlink_user(&self, subject: &str) { self.db.openidsubject_localpart.remove(subject); }
|
|
||||||
}
|
|
||||||
@@ -248,7 +248,7 @@ impl Service {
|
|||||||
) -> impl Stream<Item = OwnedUserId> + Send + 'a {
|
) -> impl Stream<Item = OwnedUserId> + Send + 'a {
|
||||||
self.local_users_in_room(room_id)
|
self.local_users_in_room(room_id)
|
||||||
.filter_map(async |user_id| {
|
.filter_map(async |user_id| {
|
||||||
if self.services.users.status(&user_id).await.is_active() {
|
if self.services.users.is_active(&user_id).await {
|
||||||
Some(user_id)
|
Some(user_id)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
|
|||||||
@@ -30,8 +30,15 @@ impl super::Service {
|
|||||||
) -> Result {
|
) -> Result {
|
||||||
let membership = pdu.get_content::<RoomMemberEventContent>()?;
|
let membership = pdu.get_content::<RoomMemberEventContent>()?;
|
||||||
|
|
||||||
if !self.services.globals.user_is_local(user_id) {
|
// Keep track what remote users exist by adding them as "deactivated" users
|
||||||
self.services.users.record_remote_user(user_id);
|
//
|
||||||
|
// TODO: use futures to update remote profiles without blocking the membership
|
||||||
|
// update
|
||||||
|
#[allow(clippy::collapsible_if)]
|
||||||
|
if !self.services.globals.user_is_local(user_id)
|
||||||
|
&& !self.services.users.exists(user_id).await
|
||||||
|
{
|
||||||
|
self.services.users.create(user_id, None)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
match &membership.membership {
|
match &membership.membership {
|
||||||
|
|||||||
@@ -255,13 +255,7 @@ impl super::Service {
|
|||||||
if let Some(state_key) = pdu.state_key() {
|
if let Some(state_key) = pdu.state_key() {
|
||||||
match UserId::parse(state_key) {
|
match UserId::parse(state_key) {
|
||||||
| Ok(target_user_id) => {
|
| Ok(target_user_id) => {
|
||||||
if self
|
if self.services.users.is_active_local(&target_user_id).await {
|
||||||
.services
|
|
||||||
.users
|
|
||||||
.status(&target_user_id)
|
|
||||||
.await
|
|
||||||
.is_active()
|
|
||||||
{
|
|
||||||
push_targets.insert(target_user_id.clone());
|
push_targets.insert(target_user_id.clone());
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -10,11 +10,13 @@ use std::{
|
|||||||
|
|
||||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
debug_info, debug_warn, info, utils::time::exponential_backoff::min_exp_backoff_duration,
|
debug_info, debug_warn, defer, info,
|
||||||
|
utils::time::exponential_backoff::min_exp_backoff_duration,
|
||||||
};
|
};
|
||||||
use conduwuit_core::{
|
use conduwuit_core::{
|
||||||
Error, Event, Result, at, debug, err, error,
|
Error, Event, Result, at, debug, err, error,
|
||||||
result::LogErr,
|
result::LogErr,
|
||||||
|
trace,
|
||||||
utils::{
|
utils::{
|
||||||
ReadyExt, calculate_hash, continue_exponential_backoff_secs,
|
ReadyExt, calculate_hash, continue_exponential_backoff_secs,
|
||||||
future::TryExtExt,
|
future::TryExtExt,
|
||||||
@@ -51,6 +53,7 @@ use ruma::{
|
|||||||
uint,
|
uint,
|
||||||
};
|
};
|
||||||
use serde_json::value::{RawValue as RawJsonValue, to_raw_value};
|
use serde_json::value::{RawValue as RawJsonValue, to_raw_value};
|
||||||
|
use tokio::{select, time::interval};
|
||||||
|
|
||||||
use super::{Destination, EduBuf, EduVec, Msg, SendingEvent, Service, data::QueueItem};
|
use super::{Destination, EduBuf, EduVec, Msg, SendingEvent, Service, data::QueueItem};
|
||||||
|
|
||||||
@@ -168,8 +171,21 @@ impl Service {
|
|||||||
futures: &mut SendingFutures<'a>,
|
futures: &mut SendingFutures<'a>,
|
||||||
statuses: &mut CurTransactionStatus,
|
statuses: &mut CurTransactionStatus,
|
||||||
) {
|
) {
|
||||||
|
let monitor = self.new_progress_monitor(
|
||||||
|
format!("Handle OK response from {dest:?}"),
|
||||||
|
Duration::from_secs(70),
|
||||||
|
);
|
||||||
|
defer! {{ monitor.notify_one(); }}
|
||||||
|
let start = Instant::now();
|
||||||
let _cork = self.db.db.cork();
|
let _cork = self.db.db.cork();
|
||||||
self.db.delete_all_active_requests_for(dest).await;
|
self.db.delete_all_active_requests_for(dest).await;
|
||||||
|
if start.elapsed().as_secs() > 1 {
|
||||||
|
warn!(
|
||||||
|
elapsed=?start.elapsed(),
|
||||||
|
"Deleting all active requests for {dest:?} took a long time"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let start = Instant::now();
|
||||||
|
|
||||||
// Find events that have been added since starting the last request
|
// Find events that have been added since starting the last request
|
||||||
let new_events = self
|
let new_events = self
|
||||||
@@ -178,6 +194,12 @@ impl Service {
|
|||||||
.take(DEQUEUE_LIMIT)
|
.take(DEQUEUE_LIMIT)
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.await;
|
.await;
|
||||||
|
if start.elapsed().as_secs() > 1 {
|
||||||
|
warn!(
|
||||||
|
elapsed=?start.elapsed(),
|
||||||
|
"Fetching queued requests for {dest:?} took a long time"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Insert any pdus we found
|
// Insert any pdus we found
|
||||||
if !new_events.is_empty() {
|
if !new_events.is_empty() {
|
||||||
@@ -201,6 +223,11 @@ impl Service {
|
|||||||
futures: &mut SendingFutures<'a>,
|
futures: &mut SendingFutures<'a>,
|
||||||
statuses: &mut CurTransactionStatus,
|
statuses: &mut CurTransactionStatus,
|
||||||
) {
|
) {
|
||||||
|
let monitor = self.new_progress_monitor(
|
||||||
|
format!("Handle send request {:?}", msg.queue_id),
|
||||||
|
Duration::from_secs(70),
|
||||||
|
);
|
||||||
|
defer! {{ monitor.notify_one(); }}
|
||||||
let iv = vec![(msg.queue_id, msg.event)];
|
let iv = vec![(msg.queue_id, msg.event)];
|
||||||
if let Ok(Some(events)) = self.select_events(&msg.dest, iv, statuses).await {
|
if let Ok(Some(events)) = self.select_events(&msg.dest, iv, statuses).await {
|
||||||
if !events.is_empty() {
|
if !events.is_empty() {
|
||||||
@@ -257,6 +284,10 @@ impl Service {
|
|||||||
futures: &mut SendingFutures<'a>,
|
futures: &mut SendingFutures<'a>,
|
||||||
statuses: &mut CurTransactionStatus,
|
statuses: &mut CurTransactionStatus,
|
||||||
) {
|
) {
|
||||||
|
let monitor = self.new_progress_monitor(
|
||||||
|
format!("Startup netburst on shard {id}"),
|
||||||
|
Duration::from_mins(2),
|
||||||
|
);
|
||||||
let keep =
|
let keep =
|
||||||
usize::try_from(self.server.config.startup_netburst_keep).unwrap_or(usize::MAX);
|
usize::try_from(self.server.config.startup_netburst_keep).unwrap_or(usize::MAX);
|
||||||
let mut txns = HashMap::<Destination, Vec<SendingEvent>>::new();
|
let mut txns = HashMap::<Destination, Vec<SendingEvent>>::new();
|
||||||
@@ -287,6 +318,7 @@ impl Service {
|
|||||||
futures.push(self.send_events(dest.clone(), events));
|
futures.push(self.send_events(dest.clone(), events));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
monitor.notify_one();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Selects any new events to send to the given destination.
|
/// Selects any new events to send to the given destination.
|
||||||
@@ -317,11 +349,16 @@ impl Service {
|
|||||||
|
|
||||||
// Must retry any previous transaction for this remote.
|
// Must retry any previous transaction for this remote.
|
||||||
if retry {
|
if retry {
|
||||||
|
let active_requests_task = self.new_progress_monitor(
|
||||||
|
format!("Fetch previous transactions for {dest:?}"),
|
||||||
|
Duration::from_secs(1),
|
||||||
|
);
|
||||||
self.db
|
self.db
|
||||||
.active_requests_for(dest)
|
.active_requests_for(dest)
|
||||||
.ready_for_each(|(_, e)| events.push(e))
|
.ready_for_each(|(_, e)| events.push(e))
|
||||||
.await;
|
.await;
|
||||||
|
active_requests_task.notify_one();
|
||||||
|
info!(?dest, "Attempting to retry destination with {} previous events", events.len());
|
||||||
return Ok(Some(events));
|
return Ok(Some(events));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -387,6 +424,11 @@ impl Service {
|
|||||||
/// Selects a number of EDUs to send to the target.
|
/// Selects a number of EDUs to send to the target.
|
||||||
#[tracing::instrument(name = "edus", level = "debug", skip_all)]
|
#[tracing::instrument(name = "edus", level = "debug", skip_all)]
|
||||||
async fn select_edus(&self, server_name: &ServerName) -> Result<(EduVec, u64)> {
|
async fn select_edus(&self, server_name: &ServerName) -> Result<(EduVec, u64)> {
|
||||||
|
let monitor = self.new_progress_monitor(
|
||||||
|
format!("Select EDUs for {server_name}"),
|
||||||
|
Duration::from_secs(1),
|
||||||
|
);
|
||||||
|
defer! {{ monitor.notify_one(); }}
|
||||||
// selection window
|
// selection window
|
||||||
let since = self.db.get_latest_educount(server_name).await;
|
let since = self.db.get_latest_educount(server_name).await;
|
||||||
let since_upper = self.services.globals.current_count()?;
|
let since_upper = self.services.globals.current_count()?;
|
||||||
@@ -435,6 +477,11 @@ impl Service {
|
|||||||
max_edu_count: &AtomicU64,
|
max_edu_count: &AtomicU64,
|
||||||
events_len: &AtomicUsize,
|
events_len: &AtomicUsize,
|
||||||
) -> EduVec {
|
) -> EduVec {
|
||||||
|
let monitor = self.new_progress_monitor(
|
||||||
|
format!("Select device list update EDUs for {server_name}"),
|
||||||
|
Duration::from_secs(1),
|
||||||
|
);
|
||||||
|
defer! {{ monitor.notify_one(); }}
|
||||||
let mut events = EduVec::new();
|
let mut events = EduVec::new();
|
||||||
let server_rooms = self.services.state_cache.server_rooms(server_name);
|
let server_rooms = self.services.state_cache.server_rooms(server_name);
|
||||||
|
|
||||||
@@ -492,6 +539,11 @@ impl Service {
|
|||||||
since: (u64, u64),
|
since: (u64, u64),
|
||||||
max_edu_count: &AtomicU64,
|
max_edu_count: &AtomicU64,
|
||||||
) -> Option<EduBuf> {
|
) -> Option<EduBuf> {
|
||||||
|
let monitor = self.new_progress_monitor(
|
||||||
|
format!("Select read receipt EDUs for {server_name}"),
|
||||||
|
Duration::from_secs(1),
|
||||||
|
);
|
||||||
|
defer! {{ monitor.notify_one(); }}
|
||||||
let mut num = 0;
|
let mut num = 0;
|
||||||
let receipts: BTreeMap<OwnedRoomId, ReceiptMap> = self
|
let receipts: BTreeMap<OwnedRoomId, ReceiptMap> = self
|
||||||
.services
|
.services
|
||||||
@@ -598,6 +650,11 @@ impl Service {
|
|||||||
since: (u64, u64),
|
since: (u64, u64),
|
||||||
max_edu_count: &AtomicU64,
|
max_edu_count: &AtomicU64,
|
||||||
) -> Option<EduBuf> {
|
) -> Option<EduBuf> {
|
||||||
|
let monitor = self.new_progress_monitor(
|
||||||
|
format!("Select presence EDUs for {server_name}"),
|
||||||
|
Duration::from_secs(1),
|
||||||
|
);
|
||||||
|
defer! {{ monitor.notify_one(); }}
|
||||||
let presence_since = self.services.presence.presence_since(since.0);
|
let presence_since = self.services.presence.presence_since(since.0);
|
||||||
|
|
||||||
pin_mut!(presence_since);
|
pin_mut!(presence_since);
|
||||||
@@ -679,6 +736,21 @@ impl Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Creates a new progress monitor with the given name, returning a marker
|
||||||
|
/// that can be used to mark the progress monitor as finished.
|
||||||
|
fn new_progress_monitor(
|
||||||
|
&self,
|
||||||
|
task_name: String,
|
||||||
|
tolerance: Duration,
|
||||||
|
) -> Arc<tokio::sync::Notify> {
|
||||||
|
let marker = Arc::new(tokio::sync::Notify::new());
|
||||||
|
let monitor_marker = marker.clone();
|
||||||
|
self.server.runtime().spawn(async move {
|
||||||
|
progress_monitor(&task_name, tolerance, monitor_marker).await;
|
||||||
|
});
|
||||||
|
marker
|
||||||
|
}
|
||||||
|
|
||||||
#[tracing::instrument(
|
#[tracing::instrument(
|
||||||
name = "appservice",
|
name = "appservice",
|
||||||
level = "debug",
|
level = "debug",
|
||||||
@@ -692,7 +764,12 @@ impl Service {
|
|||||||
id: String,
|
id: String,
|
||||||
events: Vec<SendingEvent>,
|
events: Vec<SendingEvent>,
|
||||||
) -> SendingResult {
|
) -> SendingResult {
|
||||||
|
let monitor = self.new_progress_monitor(
|
||||||
|
format!("Send {} events to appservice {}", events.len(), id),
|
||||||
|
Duration::from_secs(self.server.config.sender_timeout),
|
||||||
|
);
|
||||||
let Some(appservice) = self.services.appservice.get_registration(&id).await else {
|
let Some(appservice) = self.services.appservice.get_registration(&id).await else {
|
||||||
|
monitor.notify_one();
|
||||||
return Err((
|
return Err((
|
||||||
Destination::Appservice(id.clone()),
|
Destination::Appservice(id.clone()),
|
||||||
err!(Database(warn!(?id, "Missing appservice registration"))),
|
err!(Database(warn!(?id, "Missing appservice registration"))),
|
||||||
@@ -741,7 +818,10 @@ impl Service {
|
|||||||
request.ephemeral = edu_jsons;
|
request.ephemeral = edu_jsons;
|
||||||
request.to_device = Vec::new(); // TODO
|
request.to_device = Vec::new(); // TODO
|
||||||
|
|
||||||
match self.send_appservice_request(appservice, request).await {
|
let result = self.send_appservice_request(appservice, request).await;
|
||||||
|
monitor.notify_one();
|
||||||
|
|
||||||
|
match result {
|
||||||
| Ok(_) => Ok(Destination::Appservice(id)),
|
| Ok(_) => Ok(Destination::Appservice(id)),
|
||||||
| Err(e) => Err((Destination::Appservice(id), e)),
|
| Err(e) => Err((Destination::Appservice(id), e)),
|
||||||
}
|
}
|
||||||
@@ -767,6 +847,10 @@ impl Service {
|
|||||||
err!(Database(error!(%user_id, ?pushkey, "Missing pusher"))),
|
err!(Database(error!(%user_id, ?pushkey, "Missing pusher"))),
|
||||||
));
|
));
|
||||||
};
|
};
|
||||||
|
let monitor = self.new_progress_monitor(
|
||||||
|
format!("Send {} events to pusher {} for {user_id}", pusher.ids.app_id, events.len()),
|
||||||
|
Duration::from_secs(self.server.config.sender_timeout),
|
||||||
|
);
|
||||||
|
|
||||||
let mut pdus = Vec::with_capacity(
|
let mut pdus = Vec::with_capacity(
|
||||||
events
|
events
|
||||||
@@ -819,6 +903,7 @@ impl Service {
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| (Destination::Push(user_id.clone(), pushkey.clone()), e));
|
.map_err(|e| (Destination::Push(user_id.clone(), pushkey.clone()), e));
|
||||||
}
|
}
|
||||||
|
monitor.notify_one();
|
||||||
|
|
||||||
Ok(Destination::Push(user_id, pushkey))
|
Ok(Destination::Push(user_id, pushkey))
|
||||||
}
|
}
|
||||||
@@ -828,6 +913,18 @@ impl Service {
|
|||||||
server: OwnedServerName,
|
server: OwnedServerName,
|
||||||
events: Vec<SendingEvent>,
|
events: Vec<SendingEvent>,
|
||||||
) -> SendingResult {
|
) -> SendingResult {
|
||||||
|
let master_monitor = self.new_progress_monitor(
|
||||||
|
format!("Dispatch {} events to {server} (overall)", events.len()),
|
||||||
|
Duration::from_secs(self.server.config.sender_timeout),
|
||||||
|
);
|
||||||
|
defer! {{
|
||||||
|
master_monitor.notify_one();
|
||||||
|
}}
|
||||||
|
|
||||||
|
let monitor = self.new_progress_monitor(
|
||||||
|
format!("Get {} events to send to {server}", events.len()),
|
||||||
|
Duration::from_secs(5),
|
||||||
|
);
|
||||||
let pdus: Vec<_> = events
|
let pdus: Vec<_> = events
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|pdu| match pdu {
|
.filter_map(|pdu| match pdu {
|
||||||
@@ -850,6 +947,7 @@ impl Service {
|
|||||||
.filter_map(Result::ok)
|
.filter_map(Result::ok)
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
monitor.notify_one();
|
||||||
if pdus.is_empty() && edus.is_empty() {
|
if pdus.is_empty() && edus.is_empty() {
|
||||||
return Ok(Destination::Federation(server));
|
return Ok(Destination::Federation(server));
|
||||||
}
|
}
|
||||||
@@ -878,6 +976,15 @@ impl Service {
|
|||||||
"Sending transaction to remote"
|
"Sending transaction to remote"
|
||||||
);
|
);
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
|
let monitor = self.new_progress_monitor(
|
||||||
|
format!(
|
||||||
|
"Send {} events ({} PDUs, {} EDUs) to {server}",
|
||||||
|
events.len(),
|
||||||
|
request.pdus.len(),
|
||||||
|
request.edus.len(),
|
||||||
|
),
|
||||||
|
Duration::from_secs(self.server.config.sender_timeout),
|
||||||
|
);
|
||||||
let result = self
|
let result = self
|
||||||
.services
|
.services
|
||||||
.federation
|
.federation
|
||||||
@@ -902,6 +1009,7 @@ impl Service {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
monitor.notify_one();
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
| Err(error) => Err((Destination::Federation(server), error)),
|
| Err(error) => Err((Destination::Federation(server), error)),
|
||||||
@@ -929,3 +1037,59 @@ impl Service {
|
|||||||
to_raw_value(&pdu_json).expect("CanonicalJson is valid serde_json::Value")
|
to_raw_value(&pdu_json).expect("CanonicalJson is valid serde_json::Value")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Monitors progress by alerting every 10 seconds that elapse after 60
|
||||||
|
/// seconds if the progress monitor is not marked as finished via the
|
||||||
|
/// marker.
|
||||||
|
/// Progress monitoring starts immediately.
|
||||||
|
async fn progress_monitor(
|
||||||
|
task_name: &str,
|
||||||
|
tolerance: Duration,
|
||||||
|
marker: Arc<tokio::sync::Notify>,
|
||||||
|
) {
|
||||||
|
// TODO: this might be useful in more places than the sender service.
|
||||||
|
// Only temporary for diagnostic purposes rn
|
||||||
|
let start = Instant::now();
|
||||||
|
let mut interval = interval(Duration::from_secs(10));
|
||||||
|
loop {
|
||||||
|
select! {
|
||||||
|
_ = interval.tick() => {
|
||||||
|
let elapsed = start.elapsed();
|
||||||
|
if elapsed > tolerance {
|
||||||
|
warn!(
|
||||||
|
%task_name,
|
||||||
|
?elapsed,
|
||||||
|
?tolerance,
|
||||||
|
"Task has been running for a long time (stuck?)"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
trace!(
|
||||||
|
%task_name,
|
||||||
|
?elapsed,
|
||||||
|
?tolerance,
|
||||||
|
"Task is still running"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
() = marker.notified() => {
|
||||||
|
let elapsed = start.elapsed();
|
||||||
|
if elapsed > tolerance {
|
||||||
|
warn!(
|
||||||
|
%task_name,
|
||||||
|
?elapsed,
|
||||||
|
?tolerance,
|
||||||
|
"Task took a long time (but didn't get stuck)"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
trace!(
|
||||||
|
%task_name,
|
||||||
|
?elapsed,
|
||||||
|
?tolerance,
|
||||||
|
"Task finished"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,8 +11,8 @@ use crate::{
|
|||||||
account_data, admin, announcements, antispam, appservice, client, config, emergency,
|
account_data, admin, announcements, antispam, appservice, client, config, emergency,
|
||||||
federation, firstrun, globals, key_backups, mailer,
|
federation, firstrun, globals, key_backups, mailer,
|
||||||
manager::Manager,
|
manager::Manager,
|
||||||
media, moderation, oauth, oidc, presence, pusher, registration_tokens, resolver, rooms,
|
media, moderation, oauth, presence, pusher, registration_tokens, resolver, rooms, sending,
|
||||||
sending, server_keys,
|
server_keys,
|
||||||
service::{self, Args, Map, Service},
|
service::{self, Args, Map, Service},
|
||||||
sync, threepid, transactions, uiaa, users,
|
sync, threepid, transactions, uiaa, users,
|
||||||
};
|
};
|
||||||
@@ -28,7 +28,6 @@ pub struct Services {
|
|||||||
pub key_backups: Arc<key_backups::Service>,
|
pub key_backups: Arc<key_backups::Service>,
|
||||||
pub media: Arc<media::Service>,
|
pub media: Arc<media::Service>,
|
||||||
pub oauth: Arc<oauth::Service>,
|
pub oauth: Arc<oauth::Service>,
|
||||||
pub oidc: Arc<oidc::Service>,
|
|
||||||
pub mailer: Arc<mailer::Service>,
|
pub mailer: Arc<mailer::Service>,
|
||||||
pub presence: Arc<presence::Service>,
|
pub presence: Arc<presence::Service>,
|
||||||
pub pusher: Arc<pusher::Service>,
|
pub pusher: Arc<pusher::Service>,
|
||||||
@@ -86,7 +85,6 @@ impl Services {
|
|||||||
key_backups: build!(key_backups::Service),
|
key_backups: build!(key_backups::Service),
|
||||||
media: build!(media::Service),
|
media: build!(media::Service),
|
||||||
oauth: build!(oauth::Service),
|
oauth: build!(oauth::Service),
|
||||||
oidc: build!(oidc::Service),
|
|
||||||
mailer: build!(mailer::Service),
|
mailer: build!(mailer::Service),
|
||||||
presence: build!(presence::Service),
|
presence: build!(presence::Service),
|
||||||
pusher: build!(pusher::Service),
|
pusher: build!(pusher::Service),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::{borrow::Cow, collections::HashMap, sync::Arc};
|
use std::{borrow::Cow, collections::HashMap, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{Err, Error, Result, config::OidcProfileKeyImportMode, result::FlatOk};
|
use conduwuit::{Err, Error, Result, result::FlatOk};
|
||||||
use database::{Deserialized, Map};
|
use database::{Deserialized, Map};
|
||||||
use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter};
|
use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter};
|
||||||
use lettre::{Address, message::Mailbox};
|
use lettre::{Address, message::Mailbox};
|
||||||
@@ -33,9 +33,7 @@ pub enum EmailRequirement {
|
|||||||
Required,
|
Required,
|
||||||
/// Users may change or remove their email.
|
/// Users may change or remove their email.
|
||||||
Optional,
|
Optional,
|
||||||
/// Users may see their email, but may not change it.
|
/// Users may not change their email at all.
|
||||||
Locked,
|
|
||||||
/// Email features are disabled.
|
|
||||||
Unavailable,
|
Unavailable,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,9 +43,6 @@ impl EmailRequirement {
|
|||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn may_remove(&self) -> bool { matches!(self, Self::Optional) }
|
pub fn may_remove(&self) -> bool { matches!(self, Self::Optional) }
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn may_view(&self) -> bool { !matches!(self, Self::Unavailable) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Data {
|
struct Data {
|
||||||
@@ -92,14 +87,7 @@ impl Service {
|
|||||||
/// Check if users are required to have an email address.
|
/// Check if users are required to have an email address.
|
||||||
pub fn email_requirement(&self) -> EmailRequirement {
|
pub fn email_requirement(&self) -> EmailRequirement {
|
||||||
if let Some(smtp) = &self.services.config.smtp {
|
if let Some(smtp) = &self.services.config.smtp {
|
||||||
if let Some(oidc) = &self.services.config.oauth.oidc
|
if smtp.require_email_for_registration || smtp.require_email_for_token_registration {
|
||||||
&& matches!(oidc.profile_key_import_mode, OidcProfileKeyImportMode::OnLogin)
|
|
||||||
&& oidc.email_claim.is_some()
|
|
||||||
{
|
|
||||||
EmailRequirement::Locked
|
|
||||||
} else if smtp.require_email_for_registration
|
|
||||||
|| smtp.require_email_for_token_registration
|
|
||||||
{
|
|
||||||
EmailRequirement::Required
|
EmailRequirement::Required
|
||||||
} else {
|
} else {
|
||||||
EmailRequirement::Optional
|
EmailRequirement::Optional
|
||||||
|
|||||||
@@ -314,7 +314,7 @@ impl Service {
|
|||||||
.services
|
.services
|
||||||
.config
|
.config
|
||||||
.oauth
|
.oauth
|
||||||
.compatibility_mode()
|
.compatibility_mode
|
||||||
.uiaa_available()
|
.uiaa_available()
|
||||||
{
|
{
|
||||||
return Err!(Request(Unrecognized(
|
return Err!(Request(Unrecognized(
|
||||||
|
|||||||
+88
-150
@@ -6,23 +6,21 @@ use conduwuit::{
|
|||||||
warn,
|
warn,
|
||||||
};
|
};
|
||||||
use database::{Deserialized, Json};
|
use database::{Deserialized, Json};
|
||||||
use futures::{FutureExt, Stream, StreamExt};
|
use futures::{FutureExt, Stream, StreamExt, TryFutureExt};
|
||||||
use lettre::Address;
|
use lettre::Address;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, UserId,
|
MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, UserId,
|
||||||
api::client::profile::PropagateTo,
|
|
||||||
events::{
|
events::{
|
||||||
GlobalAccountDataEventType, ignored_user_list::IgnoredUserListEvent,
|
GlobalAccountDataEventType, ignored_user_list::IgnoredUserListEvent,
|
||||||
push_rules::PushRulesEvent, room::message::RoomMessageEventContent,
|
push_rules::PushRulesEvent, room::message::RoomMessageEventContent,
|
||||||
},
|
},
|
||||||
profile::ProfileFieldValue,
|
|
||||||
push::Ruleset,
|
push::Ruleset,
|
||||||
};
|
};
|
||||||
use ruminuwuity::invite_permission_config::{FilterLevel, InvitePermissionConfigEvent};
|
use ruminuwuity::invite_permission_config::{FilterLevel, InvitePermissionConfigEvent};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
appservice::RegistrationInfo,
|
appservice::RegistrationInfo,
|
||||||
users::{HashedPassword, UserSuspension, profile::ProfileFieldChange},
|
users::{HashedPassword, UserSuspension},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The status of an access token.
|
/// The status of an access token.
|
||||||
@@ -31,30 +29,6 @@ pub enum AccessTokenStatus {
|
|||||||
Expired,
|
Expired,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The status of a user account.
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
pub enum AccountStatus {
|
|
||||||
NotFound,
|
|
||||||
Active,
|
|
||||||
Deactivated,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AccountStatus {
|
|
||||||
#[must_use]
|
|
||||||
pub fn is_found(&self) -> bool { !matches!(self, Self::NotFound) }
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn is_active(&self) -> bool { matches!(self, Self::Active) }
|
|
||||||
|
|
||||||
pub fn ensure_active(&self) -> Result<()> {
|
|
||||||
match self {
|
|
||||||
| Self::Active => Ok(()),
|
|
||||||
| Self::Deactivated => Err!(Request(UserDeactivated("This account is deactivated."))),
|
|
||||||
| Self::NotFound => Err!(Request(NotFound("This account does not exist."))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl super::Service {
|
impl super::Service {
|
||||||
/// Returns true/false based on whether the recipient/receiving user has
|
/// Returns true/false based on whether the recipient/receiving user has
|
||||||
/// ignored the sender.
|
/// ignored the sender.
|
||||||
@@ -115,33 +89,29 @@ impl super::Service {
|
|||||||
self.services.admin.user_is_admin(user_id).await
|
self.services.admin.user_is_admin(user_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a new shadow user account on this server. Shadow accounts
|
/// Create a new user account on this homeserver. Set the password to `None`
|
||||||
/// have no password and cannot be logged into.
|
/// to create a non-local user. Non-local users with a password will return
|
||||||
pub async fn create_shadow_account(&self, user_id: &UserId) -> Result<()> {
|
/// an error.
|
||||||
assert!(self.services.globals.user_is_local(user_id), "user id must be local");
|
#[inline]
|
||||||
|
pub fn create(&self, user_id: &UserId, password: Option<HashedPassword>) -> Result<()> {
|
||||||
if self.status(user_id).await.is_found() {
|
if !self.services.globals.user_is_local(user_id) && password.is_some() {
|
||||||
return Err!(Request(UserInUse("An account with this user ID already exists.")));
|
return Err!("Cannot create a nonlocal user with a set password");
|
||||||
}
|
}
|
||||||
|
|
||||||
self.db.userid_password.insert(user_id, "");
|
self.set_password(user_id, password);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a new account for a local human or bot user. If `password` is
|
/// Create a new account for a local human or bot user.
|
||||||
/// None, the account will be a shadow account.
|
|
||||||
pub async fn create_local_account(
|
pub async fn create_local_account(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
password: Option<HashedPassword>,
|
password: HashedPassword,
|
||||||
email: Option<Address>,
|
email: Option<Address>,
|
||||||
) -> Result<()> {
|
) {
|
||||||
self.create_shadow_account(user_id).await?;
|
self.create(user_id, Some(password))
|
||||||
|
.expect("should be able to save a new local user. what happened?");
|
||||||
if let Some(password) = password {
|
|
||||||
self.convert_to_local_account(user_id, password).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set an initial display name
|
// Set an initial display name
|
||||||
{
|
{
|
||||||
@@ -153,13 +123,7 @@ impl super::Service {
|
|||||||
displayname.push_str(suffix);
|
displayname.push_str(suffix);
|
||||||
}
|
}
|
||||||
|
|
||||||
self.set_profile_field(
|
self.set_displayname(user_id, Some(displayname));
|
||||||
user_id,
|
|
||||||
ProfileFieldChange::Set(ProfileFieldValue::DisplayName(displayname)),
|
|
||||||
PropagateTo::None,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.expect("should be able to set display name");
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Set default push rules
|
// Set default push rules
|
||||||
@@ -266,8 +230,6 @@ impl super::Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
info!("Created new user account for {user_id}");
|
info!("Created new user account for {user_id}");
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn determine_registration_user_id(
|
pub async fn determine_registration_user_id(
|
||||||
@@ -306,7 +268,28 @@ impl super::Service {
|
|||||||
&supplied_username,
|
&supplied_username,
|
||||||
self.services.globals.server_name(),
|
self.services.globals.server_name(),
|
||||||
) {
|
) {
|
||||||
| Ok(user_id) => user_id,
|
| Ok(user_id) => {
|
||||||
|
if let Err(e) = user_id.validate_strict() {
|
||||||
|
// Unless we are in emergency mode, we should follow synapse's behaviour
|
||||||
|
// on not allowing things like spaces and UTF-8 characters in
|
||||||
|
// usernames
|
||||||
|
if !emergency_mode_enabled {
|
||||||
|
return Err!(Request(InvalidUsername(debug_warn!(
|
||||||
|
"Username {supplied_username} contains disallowed characters or \
|
||||||
|
spaces: {e}"
|
||||||
|
))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Don't allow registration with user IDs that aren't local
|
||||||
|
if !self.services.globals.user_is_local(&user_id) {
|
||||||
|
return Err!(Request(InvalidUsername(
|
||||||
|
"Username {supplied_username} is not local to this server"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
user_id
|
||||||
|
},
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
return Err!(Request(InvalidUsername(debug_warn!(
|
return Err!(Request(InvalidUsername(debug_warn!(
|
||||||
"Username {supplied_username} is not valid: {e}"
|
"Username {supplied_username} is not valid: {e}"
|
||||||
@@ -314,27 +297,8 @@ impl super::Service {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Err(e) = user_id.validate_strict() {
|
if self.exists(&user_id).await {
|
||||||
// Unless we are in emergency mode, we should follow synapse's behaviour
|
return Err!(Request(UserInUse("User ID is not available.")));
|
||||||
// on not allowing things like spaces and UTF-8 characters in
|
|
||||||
// usernames
|
|
||||||
if !emergency_mode_enabled {
|
|
||||||
return Err!(Request(InvalidUsername(debug_warn!(
|
|
||||||
"Username {supplied_username} contains disallowed characters or spaces: \
|
|
||||||
{e}"
|
|
||||||
))));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Don't allow registration with user IDs that aren't local
|
|
||||||
if !self.services.globals.user_is_local(&user_id) {
|
|
||||||
return Err!(Request(InvalidUsername(
|
|
||||||
"Username {supplied_username} is not local to this server"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.status(&user_id).await.is_found() {
|
|
||||||
return Err!(Request(UserInUse("Username is not available.")));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check that the user ID is/is not in an appservice's namespace
|
// Check that the user ID is/is not in an appservice's namespace
|
||||||
@@ -365,24 +329,26 @@ impl super::Service {
|
|||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
if !self.status(&user_id).await.is_found() {
|
if !self.exists(&user_id).await {
|
||||||
break Ok(user_id);
|
break Ok(user_id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Deactivates an account, removing all of their device IDs.
|
/// Deactivates an account, removing all of their device IDs and unsetting
|
||||||
|
/// their password.
|
||||||
pub async fn deactivate_account(&self, user_id: &UserId) -> Result<()> {
|
pub async fn deactivate_account(&self, user_id: &UserId) -> Result<()> {
|
||||||
self.status(user_id).await.ensure_active()?;
|
|
||||||
|
|
||||||
// Remove all associated devices
|
// Remove all associated devices
|
||||||
self.all_device_ids(user_id)
|
self.all_device_ids(user_id)
|
||||||
.for_each(async |device_id| self.remove_device(user_id, &device_id).await)
|
.for_each(async |device_id| self.remove_device(user_id, &device_id).await)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
// Mark user as deactivated
|
// Set the password to "" to indicate a deactivated account. Hashes will never
|
||||||
self.db.userid_deactivated.insert(user_id, "");
|
// result in an empty string, so the user will not be able to log in again.
|
||||||
|
// Systems like changing the password without logging in should check if the
|
||||||
|
// account is deactivated.
|
||||||
|
self.set_password(user_id, None);
|
||||||
|
|
||||||
// TODO: Unhook 3PID
|
// TODO: Unhook 3PID
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -427,6 +393,25 @@ impl super::Service {
|
|||||||
/// Unlocks an account, allowing the user to log in and use it again.
|
/// Unlocks an account, allowing the user to log in and use it again.
|
||||||
pub async fn unlock_account(&self, user_id: &UserId) { self.db.userid_lock.remove(user_id); }
|
pub async fn unlock_account(&self, user_id: &UserId) { self.db.userid_lock.remove(user_id); }
|
||||||
|
|
||||||
|
/// Check if the provided user ID belongs to an existing (possibly
|
||||||
|
/// deactivated) account on this homeserver.
|
||||||
|
#[inline]
|
||||||
|
pub async fn exists(&self, user_id: &UserId) -> bool {
|
||||||
|
self.services.globals.user_is_local(user_id)
|
||||||
|
&& self.db.userid_password.get(user_id).await.is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if account is deactivated (has an empty password). Returns a
|
||||||
|
/// NotFound error if the user does not exist.
|
||||||
|
pub async fn is_deactivated(&self, user_id: &UserId) -> Result<bool> {
|
||||||
|
self.db
|
||||||
|
.userid_password
|
||||||
|
.get(user_id)
|
||||||
|
.map_ok(|val| val.is_empty())
|
||||||
|
.map_err(|_| err!(Request(NotFound("User does not exist."))))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
/// Check if account is suspended. Returns false if the user does not exist.
|
/// Check if account is suspended. Returns false if the user does not exist.
|
||||||
pub async fn is_suspended(&self, user_id: &UserId) -> Result<bool> {
|
pub async fn is_suspended(&self, user_id: &UserId) -> Result<bool> {
|
||||||
match self
|
match self
|
||||||
@@ -484,33 +469,18 @@ impl super::Service {
|
|||||||
.is_ok()
|
.is_ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks the activation status of the provided user ID's account.
|
/// Check if account is active (not deactivated)
|
||||||
pub async fn status(&self, user_id: &UserId) -> AccountStatus {
|
pub async fn is_active(&self, user_id: &UserId) -> bool {
|
||||||
if !self.services.globals.user_is_local(user_id) {
|
!self.is_deactivated(user_id).await.unwrap_or(true)
|
||||||
AccountStatus::NotFound
|
|
||||||
} else if self.db.userid_password.exists(user_id).await.is_ok() {
|
|
||||||
if self.db.userid_deactivated.exists(user_id).await.is_ok() {
|
|
||||||
AccountStatus::Deactivated
|
|
||||||
} else {
|
|
||||||
AccountStatus::Active
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
AccountStatus::NotFound
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks if a user is a shadow.
|
/// Check if account is a local user, and is active (not deactivated)
|
||||||
pub async fn is_shadow(&self, user_id: &UserId) -> bool {
|
pub async fn is_active_local(&self, user_id: &UserId) -> bool {
|
||||||
self.db
|
self.services.globals.user_is_local(user_id) && self.is_active(user_id).await
|
||||||
.userid_password
|
|
||||||
.get(user_id)
|
|
||||||
.await
|
|
||||||
.deserialized::<String>()
|
|
||||||
.is_ok_and(|hash| hash.is_empty())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the number of users registered on this server, including
|
/// Returns the number of users registered on this server, including
|
||||||
/// deactivated and shadow users.
|
/// deactivated users.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub async fn count(&self) -> usize { self.db.userid_password.count().await }
|
pub async fn count(&self) -> usize { self.db.userid_password.count().await }
|
||||||
|
|
||||||
@@ -552,8 +522,8 @@ impl super::Service {
|
|||||||
Some((user_id, device_id, AccessTokenStatus::Valid))
|
Some((user_id, device_id, AccessTokenStatus::Valid))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns an iterator over all local users on this homeserver.
|
/// Returns an iterator over all users on this homeserver.
|
||||||
pub fn stream_local_users(&self) -> impl Stream<Item = OwnedUserId> + Send {
|
pub fn stream(&self) -> impl Stream<Item = OwnedUserId> + Send {
|
||||||
self.db.userid_password.keys().ignore_err()
|
self.db.userid_password.keys().ignore_err()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -570,49 +540,16 @@ impl super::Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Set a user's password.
|
/// Set a user's password.
|
||||||
pub async fn set_password(&self, user_id: &UserId, password: HashedPassword) -> Result {
|
pub fn set_password(&self, user_id: &UserId, password: Option<HashedPassword>) {
|
||||||
self.status(user_id).await.ensure_active()?;
|
if let Some(hash) = password {
|
||||||
|
self.db.userid_password.insert(user_id, hash.0);
|
||||||
self.db.userid_password.insert(user_id, password.0);
|
} else {
|
||||||
|
self.db.userid_password.insert(user_id, b"");
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Convert an existing user to an active local account. This will turn
|
|
||||||
/// shadow accounts into normal accounts and will clear the deactivation
|
|
||||||
/// flag on the user if it is set.
|
|
||||||
pub async fn convert_to_local_account(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
password: HashedPassword,
|
|
||||||
) -> Result {
|
|
||||||
if !self.status(user_id).await.is_found() {
|
|
||||||
return Err!(Request(NotFound("This account does not exist.")));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.db.userid_deactivated.remove(user_id);
|
|
||||||
self.db.userid_password.insert(user_id, password.0);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Convert an existing user to a shadow account. This will clear their
|
|
||||||
/// password and reactivate them if they are deactivated.
|
|
||||||
pub async fn convert_to_shadow_account(&self, user_id: &UserId) -> Result {
|
|
||||||
if !self.status(user_id).await.is_found() {
|
|
||||||
return Err!(Request(NotFound("This account does not exist.")));
|
|
||||||
}
|
|
||||||
|
|
||||||
self.db.userid_deactivated.remove(user_id);
|
|
||||||
self.db.userid_password.insert(user_id, "");
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check a user's password.
|
/// Check a user's password.
|
||||||
pub async fn check_password(&self, user_id: &UserId, password: &str) -> Result<OwnedUserId> {
|
pub async fn check_password(&self, user_id: &UserId, password: &str) -> Result<OwnedUserId> {
|
||||||
self.status(user_id).await.ensure_active()?;
|
|
||||||
|
|
||||||
let (hash, user_id): (String, OwnedUserId) =
|
let (hash, user_id): (String, OwnedUserId) =
|
||||||
if let Ok(hash) = self.db.userid_password.get(user_id).await.deserialized() {
|
if let Ok(hash) = self.db.userid_password.get(user_id).await.deserialized() {
|
||||||
(hash, user_id.to_owned())
|
(hash, user_id.to_owned())
|
||||||
@@ -621,20 +558,21 @@ impl super::Service {
|
|||||||
// better
|
// better
|
||||||
let lowercase_user_id = UserId::parse(user_id.as_str().to_lowercase()).unwrap();
|
let lowercase_user_id = UserId::parse(user_id.as_str().to_lowercase()).unwrap();
|
||||||
|
|
||||||
let hash = self
|
if let Ok(hash) = self
|
||||||
.db
|
.db
|
||||||
.userid_password
|
.userid_password
|
||||||
.get(lowercase_user_id.as_str())
|
.get(lowercase_user_id.as_str())
|
||||||
.await
|
.await
|
||||||
.deserialized()
|
.deserialized()
|
||||||
.expect("user should exist");
|
{
|
||||||
|
(hash, lowercase_user_id)
|
||||||
(hash, lowercase_user_id)
|
} else {
|
||||||
|
return Err!(Request(Forbidden("This user cannot log in with a password.")));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if hash.is_empty() {
|
if hash.is_empty() {
|
||||||
// Cannot log into shadow users
|
return Err!(Request(UserDeactivated("This user is deactivated")));
|
||||||
return Err!(Request(Forbidden("This user cannot log in with a password.")));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
utils::hash::verify_password(password, &hash)
|
utils::hash::verify_password(password, &hash)
|
||||||
|
|||||||
@@ -21,7 +21,10 @@ pub struct DehydratedDevice {
|
|||||||
impl super::Service {
|
impl super::Service {
|
||||||
/// Creates or recreates the user's dehydrated device.
|
/// Creates or recreates the user's dehydrated device.
|
||||||
pub async fn set_dehydrated_device(&self, user_id: &UserId, request: Request) -> Result {
|
pub async fn set_dehydrated_device(&self, user_id: &UserId, request: Request) -> Result {
|
||||||
self.status(user_id).await.ensure_active()?;
|
assert!(
|
||||||
|
self.exists(user_id).await,
|
||||||
|
"Tried to create dehydrated device for non-existent user"
|
||||||
|
);
|
||||||
|
|
||||||
let existing_id = self.get_dehydrated_device_id(user_id).await;
|
let existing_id = self.get_dehydrated_device_id(user_id).await;
|
||||||
|
|
||||||
|
|||||||
+21
-12
@@ -4,8 +4,8 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Err, Result,
|
Err, utils,
|
||||||
utils::{self, ReadyExt, stream::TryIgnore},
|
utils::{ReadyExt, stream::TryIgnore},
|
||||||
};
|
};
|
||||||
use database::{Deserialized, Ignore, Interfix, Json};
|
use database::{Deserialized, Ignore, Interfix, Json};
|
||||||
use futures::{Stream, StreamExt};
|
use futures::{Stream, StreamExt};
|
||||||
@@ -18,7 +18,8 @@ use serde_json::json;
|
|||||||
use crate::users::increment;
|
use crate::users::increment;
|
||||||
|
|
||||||
impl super::Service {
|
impl super::Service {
|
||||||
/// Adds a new device to a user.
|
/// Adds a new device to a user. The user must exist, otherwise InvalidParam
|
||||||
|
/// is returned.
|
||||||
pub async fn create_device(
|
pub async fn create_device(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -27,8 +28,12 @@ impl super::Service {
|
|||||||
token_max_age: Option<Duration>,
|
token_max_age: Option<Duration>,
|
||||||
initial_device_display_name: Option<String>,
|
initial_device_display_name: Option<String>,
|
||||||
client_ip: Option<String>,
|
client_ip: Option<String>,
|
||||||
) -> Result<()> {
|
) -> conduwuit::Result<()> {
|
||||||
self.status(user_id).await.ensure_active()?;
|
if !self.exists(user_id).await {
|
||||||
|
return Err!(Request(InvalidParam(error!(
|
||||||
|
"Called create_device for non-existent user {user_id}"
|
||||||
|
))));
|
||||||
|
}
|
||||||
|
|
||||||
let key = (user_id, device_id);
|
let key = (user_id, device_id);
|
||||||
let mut device = Device::new(device_id.into());
|
let mut device = Device::new(device_id.into());
|
||||||
@@ -45,7 +50,7 @@ impl super::Service {
|
|||||||
/// Removes a device from a user.
|
/// Removes a device from a user.
|
||||||
pub async fn remove_device(&self, user_id: &UserId, device_id: &DeviceId) {
|
pub async fn remove_device(&self, user_id: &UserId, device_id: &DeviceId) {
|
||||||
// Remove dehydrated device if this is the dehydrated device
|
// Remove dehydrated device if this is the dehydrated device
|
||||||
let _ = self
|
let _: conduwuit::Result<_> = self
|
||||||
.remove_dehydrated_device(user_id, Some(device_id))
|
.remove_dehydrated_device(user_id, Some(device_id))
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
@@ -92,7 +97,11 @@ impl super::Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Gets the access token associated with a device.
|
/// Gets the access token associated with a device.
|
||||||
pub async fn get_token(&self, user_id: &UserId, device_id: &DeviceId) -> Result<String> {
|
pub async fn get_token(
|
||||||
|
&self,
|
||||||
|
user_id: &UserId,
|
||||||
|
device_id: &DeviceId,
|
||||||
|
) -> conduwuit::Result<String> {
|
||||||
let key = (user_id, device_id);
|
let key = (user_id, device_id);
|
||||||
self.db.userdeviceid_token.qry(&key).await.deserialized()
|
self.db.userdeviceid_token.qry(&key).await.deserialized()
|
||||||
}
|
}
|
||||||
@@ -122,7 +131,7 @@ impl super::Service {
|
|||||||
device_id: &DeviceId,
|
device_id: &DeviceId,
|
||||||
token: &str,
|
token: &str,
|
||||||
token_max_age: Option<Duration>,
|
token_max_age: Option<Duration>,
|
||||||
) -> Result<()> {
|
) -> conduwuit::Result<()> {
|
||||||
let key = (user_id, device_id);
|
let key = (user_id, device_id);
|
||||||
if self.db.userdeviceid_metadata.qry(&key).await.is_err() {
|
if self.db.userdeviceid_metadata.qry(&key).await.is_err() {
|
||||||
return Err!(Database(error!(
|
return Err!(Database(error!(
|
||||||
@@ -250,7 +259,7 @@ impl super::Service {
|
|||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
device_id: &DeviceId,
|
device_id: &DeviceId,
|
||||||
device: &Device,
|
device: &Device,
|
||||||
) -> Result<()> {
|
) -> conduwuit::Result<()> {
|
||||||
increment(&self.db.userid_devicelistversion, user_id.as_bytes());
|
increment(&self.db.userid_devicelistversion, user_id.as_bytes());
|
||||||
self.update_device_metadata_no_increment(user_id, device_id, device)
|
self.update_device_metadata_no_increment(user_id, device_id, device)
|
||||||
}
|
}
|
||||||
@@ -264,7 +273,7 @@ impl super::Service {
|
|||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
device_id: &DeviceId,
|
device_id: &DeviceId,
|
||||||
device: &Device,
|
device: &Device,
|
||||||
) -> Result<()> {
|
) -> conduwuit::Result<()> {
|
||||||
let key = (user_id, device_id);
|
let key = (user_id, device_id);
|
||||||
self.db.userdeviceid_metadata.put(key, Json(device));
|
self.db.userdeviceid_metadata.put(key, Json(device));
|
||||||
|
|
||||||
@@ -303,7 +312,7 @@ impl super::Service {
|
|||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
device_id: &DeviceId,
|
device_id: &DeviceId,
|
||||||
) -> Result<Device> {
|
) -> conduwuit::Result<Device> {
|
||||||
self.db
|
self.db
|
||||||
.userdeviceid_metadata
|
.userdeviceid_metadata
|
||||||
.qry(&(user_id, device_id))
|
.qry(&(user_id, device_id))
|
||||||
@@ -312,7 +321,7 @@ impl super::Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Gets the most recent device list version for a user.
|
/// Gets the most recent device list version for a user.
|
||||||
pub async fn get_devicelist_version(&self, user_id: &UserId) -> Result<u64> {
|
pub async fn get_devicelist_version(&self, user_id: &UserId) -> conduwuit::Result<u64> {
|
||||||
self.db
|
self.db
|
||||||
.userid_devicelistversion
|
.userid_devicelistversion
|
||||||
.get(user_id)
|
.get(user_id)
|
||||||
|
|||||||
@@ -4,22 +4,20 @@ pub(super) mod device;
|
|||||||
pub(super) mod filters;
|
pub(super) mod filters;
|
||||||
pub(super) mod keys;
|
pub(super) mod keys;
|
||||||
pub(super) mod profile;
|
pub(super) mod profile;
|
||||||
pub(super) mod remote;
|
|
||||||
|
|
||||||
use std::{mem, sync::Arc};
|
use std::{mem, sync::Arc};
|
||||||
|
|
||||||
pub use account::{AccessTokenStatus, AccountStatus};
|
pub use account::AccessTokenStatus;
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Err, Error, Result, err,
|
Err, Error, Result, err,
|
||||||
utils::{self},
|
utils::{self},
|
||||||
};
|
};
|
||||||
use database::Map;
|
use database::Map;
|
||||||
pub use profile::ProfileFieldChange;
|
|
||||||
use ruma::{UserId, api::error::ErrorKind, encryption::CrossSigningKey, serde::Raw};
|
use ruma::{UserId, api::error::ErrorKind, encryption::CrossSigningKey, serde::Raw};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Dep, account_data, admin, appservice, config, firstrun, globals, oauth, presence,
|
Dep, account_data, admin, appservice, config, firstrun, globals, oauth,
|
||||||
rooms::{self, alias, membership},
|
rooms::{self, alias, membership},
|
||||||
threepid,
|
threepid,
|
||||||
};
|
};
|
||||||
@@ -63,12 +61,9 @@ struct Services {
|
|||||||
globals: Dep<globals::Service>,
|
globals: Dep<globals::Service>,
|
||||||
membership: Dep<membership::Service>,
|
membership: Dep<membership::Service>,
|
||||||
oauth: Dep<oauth::Service>,
|
oauth: Dep<oauth::Service>,
|
||||||
presence: Dep<presence::Service>,
|
|
||||||
state: Dep<rooms::state::Service>,
|
|
||||||
state_accessor: Dep<rooms::state_accessor::Service>,
|
state_accessor: Dep<rooms::state_accessor::Service>,
|
||||||
state_cache: Dep<rooms::state_cache::Service>,
|
state_cache: Dep<rooms::state_cache::Service>,
|
||||||
threepid: Dep<threepid::Service>,
|
threepid: Dep<threepid::Service>,
|
||||||
timeline: Dep<rooms::timeline::Service>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Data {
|
struct Data {
|
||||||
@@ -80,13 +75,11 @@ struct Data {
|
|||||||
logintoken_expiresatuserid: Arc<Map>,
|
logintoken_expiresatuserid: Arc<Map>,
|
||||||
todeviceid_events: Arc<Map>,
|
todeviceid_events: Arc<Map>,
|
||||||
token_userdeviceid: Arc<Map>,
|
token_userdeviceid: Arc<Map>,
|
||||||
remoteuserid_remoteuser: Arc<Map>,
|
|
||||||
userdeviceid_tokenexpires: Arc<Map>,
|
userdeviceid_tokenexpires: Arc<Map>,
|
||||||
userdeviceid_metadata: Arc<Map>,
|
userdeviceid_metadata: Arc<Map>,
|
||||||
userdeviceid_token: Arc<Map>,
|
userdeviceid_token: Arc<Map>,
|
||||||
userfilterid_filter: Arc<Map>,
|
userfilterid_filter: Arc<Map>,
|
||||||
userid_avatarurl: Arc<Map>,
|
userid_avatarurl: Arc<Map>,
|
||||||
userid_deactivated: Arc<Map>,
|
|
||||||
userid_dehydrateddevice: Arc<Map>,
|
userid_dehydrateddevice: Arc<Map>,
|
||||||
userid_devicelistversion: Arc<Map>,
|
userid_devicelistversion: Arc<Map>,
|
||||||
userid_displayname: Arc<Map>,
|
userid_displayname: Arc<Map>,
|
||||||
@@ -114,13 +107,10 @@ impl crate::Service for Service {
|
|||||||
globals: args.depend::<globals::Service>("globals"),
|
globals: args.depend::<globals::Service>("globals"),
|
||||||
membership: args.depend::<membership::Service>("membership"),
|
membership: args.depend::<membership::Service>("membership"),
|
||||||
oauth: args.depend::<oauth::Service>("oauth"),
|
oauth: args.depend::<oauth::Service>("oauth"),
|
||||||
presence: args.depend::<presence::Service>("presence"),
|
|
||||||
state: args.depend::<rooms::state::Service>("rooms::state"),
|
|
||||||
state_accessor: args
|
state_accessor: args
|
||||||
.depend::<rooms::state_accessor::Service>("rooms::state_accessor"),
|
.depend::<rooms::state_accessor::Service>("rooms::state_accessor"),
|
||||||
state_cache: args.depend::<rooms::state_cache::Service>("rooms::state_cache"),
|
state_cache: args.depend::<rooms::state_cache::Service>("rooms::state_cache"),
|
||||||
threepid: args.depend::<threepid::Service>("threepid"),
|
threepid: args.depend::<threepid::Service>("threepid"),
|
||||||
timeline: args.depend::<rooms::timeline::Service>("rooms::timeline"),
|
|
||||||
},
|
},
|
||||||
db: Data {
|
db: Data {
|
||||||
keychangeid_userid: args.db["keychangeid_userid"].clone(),
|
keychangeid_userid: args.db["keychangeid_userid"].clone(),
|
||||||
@@ -131,12 +121,10 @@ impl crate::Service for Service {
|
|||||||
logintoken_expiresatuserid: args.db["logintoken_expiresatuserid"].clone(),
|
logintoken_expiresatuserid: args.db["logintoken_expiresatuserid"].clone(),
|
||||||
todeviceid_events: args.db["todeviceid_events"].clone(),
|
todeviceid_events: args.db["todeviceid_events"].clone(),
|
||||||
token_userdeviceid: args.db["token_userdeviceid"].clone(),
|
token_userdeviceid: args.db["token_userdeviceid"].clone(),
|
||||||
remoteuserid_remoteuser: args.db["remoteuserid_remoteuser"].clone(),
|
|
||||||
userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
|
userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
|
||||||
userdeviceid_token: args.db["userdeviceid_token"].clone(),
|
userdeviceid_token: args.db["userdeviceid_token"].clone(),
|
||||||
userfilterid_filter: args.db["userfilterid_filter"].clone(),
|
userfilterid_filter: args.db["userfilterid_filter"].clone(),
|
||||||
userid_avatarurl: args.db["userid_avatarurl"].clone(),
|
userid_avatarurl: args.db["userid_avatarurl"].clone(),
|
||||||
userid_deactivated: args.db["userid_deactivated"].clone(),
|
|
||||||
userid_dehydrateddevice: args.db["userid_dehydrateddevice"].clone(),
|
userid_dehydrateddevice: args.db["userid_dehydrateddevice"].clone(),
|
||||||
userid_devicelistversion: args.db["userid_devicelistversion"].clone(),
|
userid_devicelistversion: args.db["userid_devicelistversion"].clone(),
|
||||||
userid_displayname: args.db["userid_displayname"].clone(),
|
userid_displayname: args.db["userid_displayname"].clone(),
|
||||||
|
|||||||
+14
-269
@@ -1,276 +1,17 @@
|
|||||||
use std::{borrow::Cow, collections::BTreeMap};
|
use conduwuit::utils::{ReadyExt, stream::TryIgnore};
|
||||||
|
|
||||||
use conduwuit::{
|
|
||||||
Err, Result,
|
|
||||||
pdu::PartialPdu,
|
|
||||||
utils::{ReadyExt, stream::TryIgnore, to_canonical_object},
|
|
||||||
};
|
|
||||||
use database::{Deserialized, Ignore, Interfix, Json};
|
use database::{Deserialized, Ignore, Interfix, Json};
|
||||||
use futures::{Stream, StreamExt};
|
use futures::{Stream, StreamExt};
|
||||||
use ruma::{
|
use ruma::{OwnedMxcUri, UserId};
|
||||||
OwnedMxcUri, UserId,
|
|
||||||
api::client::profile::PropagateTo,
|
|
||||||
events::room::member::MembershipState,
|
|
||||||
presence::PresenceState,
|
|
||||||
profile::{ProfileFieldName, ProfileFieldValue},
|
|
||||||
};
|
|
||||||
use serde_json::{Value, to_value};
|
|
||||||
|
|
||||||
pub enum ProfileFieldChange {
|
|
||||||
Set(ProfileFieldValue),
|
|
||||||
Delete(ProfileFieldName),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ProfileFieldChange {
|
|
||||||
fn field_name(&self) -> ProfileFieldName {
|
|
||||||
match self {
|
|
||||||
| &Self::Delete(ref name) => name.clone(),
|
|
||||||
| &Self::Set(ref value) => value.field_name(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn value(&self) -> Option<Cow<'_, Value>> {
|
|
||||||
if let Self::Set(value) = self {
|
|
||||||
Some(value.value())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl super::Service {
|
impl super::Service {
|
||||||
pub async fn set_profile_field(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
change: ProfileFieldChange,
|
|
||||||
propagate_to: PropagateTo,
|
|
||||||
) -> Result<()> {
|
|
||||||
const MAX_KEY_LENGTH_BYTES: usize = 255;
|
|
||||||
const MAX_PROFILE_LENGTH_BYTES: usize = 65536;
|
|
||||||
|
|
||||||
let field_name = change.field_name();
|
|
||||||
|
|
||||||
// TODO: The spec mentions special error codes (M_PROFILE_TOO_LARGE,
|
|
||||||
// M_KEY_TOO_LARGE) for profile field size limits, but they're not in its list
|
|
||||||
// of error codes and Ruma doesn't have them. Should we return those, or is
|
|
||||||
// M_TOO_LARGE okay?
|
|
||||||
if field_name.as_str().len() > MAX_KEY_LENGTH_BYTES {
|
|
||||||
return Err!(Request(TooLarge(
|
|
||||||
"Individual profile keys must not exceed {MAX_KEY_LENGTH_BYTES} bytes in length."
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Serialize the entire profile as canonical JSON, including the new change,
|
|
||||||
// to check if it exceeds 64 KiB
|
|
||||||
{
|
|
||||||
let mut full_profile = self.get_local_profile(user_id).await;
|
|
||||||
|
|
||||||
match &change {
|
|
||||||
| ProfileFieldChange::Set(value) => {
|
|
||||||
full_profile.insert(
|
|
||||||
value.field_name().as_str().to_owned(),
|
|
||||||
value.value().clone().into_owned(),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Delete(key) => {
|
|
||||||
full_profile.remove(key.as_str());
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(canonical_profile) = to_canonical_object(full_profile) {
|
|
||||||
if serde_json::to_string(&canonical_profile)
|
|
||||||
.expect("should be able to serialize to string")
|
|
||||||
.len() > MAX_PROFILE_LENGTH_BYTES
|
|
||||||
{
|
|
||||||
return Err!(
|
|
||||||
"Profile data must not exceed {MAX_PROFILE_LENGTH_BYTES} bytes in \
|
|
||||||
length."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Err!(Request(BadJson("Failed to canonicalize profile.")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if this change would be a no-op
|
|
||||||
if self
|
|
||||||
.get_local_profile_field(user_id, field_name.clone())
|
|
||||||
.await
|
|
||||||
.is_some_and(|value| Some(value.value()) == change.value())
|
|
||||||
{
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the user is local and changed their displayname or avatar_url, update it
|
|
||||||
// in all their joined rooms. This is done before updating their profile data
|
|
||||||
// so we can check the old value of the field if `propagate_to` is `unchanged`.
|
|
||||||
if matches!(field_name, ProfileFieldName::AvatarUrl | ProfileFieldName::DisplayName)
|
|
||||||
&& matches!(propagate_to, PropagateTo::All | PropagateTo::Unchanged)
|
|
||||||
&& self.services.globals.user_is_local(user_id)
|
|
||||||
{
|
|
||||||
let current_displayname = self.displayname(user_id).await.ok();
|
|
||||||
let current_avatar_url = self.avatar_url(user_id).await.ok();
|
|
||||||
|
|
||||||
let mut all_joined_rooms = self.services.state_cache.rooms_joined(user_id);
|
|
||||||
|
|
||||||
while let Some(room_id) = all_joined_rooms.next().await {
|
|
||||||
// TODO: this clobbers any custom fields on the event content
|
|
||||||
let mut current_membership = self
|
|
||||||
.services
|
|
||||||
.state_accessor
|
|
||||||
.get_member(&room_id, user_id)
|
|
||||||
.await
|
|
||||||
.expect("should be able to fetch membership event for joined room");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
current_membership.membership,
|
|
||||||
MembershipState::Join,
|
|
||||||
"user should be joined"
|
|
||||||
);
|
|
||||||
|
|
||||||
// If `propagate_to` is `unchanged`, and the current value of the field we're
|
|
||||||
// updating was changed from its global value in this room, skip it.
|
|
||||||
if matches!(propagate_to, PropagateTo::Unchanged) {
|
|
||||||
let field_changed_from_global = match field_name {
|
|
||||||
| ProfileFieldName::AvatarUrl =>
|
|
||||||
current_membership.avatar_url.as_ref() != current_avatar_url.as_ref(),
|
|
||||||
| ProfileFieldName::DisplayName =>
|
|
||||||
current_membership.displayname.as_ref()
|
|
||||||
!= current_displayname.as_ref(),
|
|
||||||
| _ => unreachable!(),
|
|
||||||
};
|
|
||||||
|
|
||||||
if field_changed_from_global {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let state_lock = self.services.state.mutex.lock(room_id.as_str()).await;
|
|
||||||
|
|
||||||
// Preserve keys in accordance with the key copying rules
|
|
||||||
current_membership.reason = None;
|
|
||||||
current_membership.join_authorized_via_users_server = None;
|
|
||||||
match &change {
|
|
||||||
| ProfileFieldChange::Set(ProfileFieldValue::AvatarUrl(avatar_url)) => {
|
|
||||||
current_membership.avatar_url = Some(avatar_url.clone());
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Set(ProfileFieldValue::DisplayName(displayname)) => {
|
|
||||||
current_membership.displayname = Some(displayname.clone());
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Delete(ProfileFieldName::AvatarUrl) => {
|
|
||||||
current_membership.avatar_url = None;
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Delete(ProfileFieldName::DisplayName) => {
|
|
||||||
current_membership.displayname = None;
|
|
||||||
},
|
|
||||||
| _ => unreachable!(),
|
|
||||||
}
|
|
||||||
|
|
||||||
let _ = self
|
|
||||||
.services
|
|
||||||
.timeline
|
|
||||||
.build_and_append_pdu(
|
|
||||||
PartialPdu::state(user_id.to_string(), ¤t_membership),
|
|
||||||
user_id,
|
|
||||||
Some(&room_id),
|
|
||||||
&state_lock,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.services.config.allow_local_presence {
|
|
||||||
// Send a presence EDU to indicate the profile changed
|
|
||||||
let _ = self
|
|
||||||
.services
|
|
||||||
.presence
|
|
||||||
.ping_presence(user_id, &PresenceState::Online)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
match change {
|
|
||||||
| ProfileFieldChange::Set(ProfileFieldValue::DisplayName(displayname)) => {
|
|
||||||
self.set_displayname(user_id, Some(displayname).filter(|dn| !dn.is_empty()));
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Set(ProfileFieldValue::AvatarUrl(avatar_url)) => {
|
|
||||||
self.set_avatar_url(user_id, Some(avatar_url).filter(|av| av.is_valid()));
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Delete(ProfileFieldName::DisplayName) => {
|
|
||||||
self.set_displayname(user_id, None);
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Delete(ProfileFieldName::AvatarUrl) => {
|
|
||||||
self.set_avatar_url(user_id, None);
|
|
||||||
},
|
|
||||||
| other => self.set_profile_key(
|
|
||||||
user_id,
|
|
||||||
other.field_name().as_str(),
|
|
||||||
other.value().map(Cow::into_owned),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_local_profile(&self, user_id: &UserId) -> BTreeMap<String, Value> {
|
|
||||||
let mut profile = BTreeMap::new();
|
|
||||||
|
|
||||||
// Get displayname and avatar_url independently because `all_profile_keys`
|
|
||||||
// doesn't include them
|
|
||||||
for field in [ProfileFieldName::AvatarUrl, ProfileFieldName::DisplayName] {
|
|
||||||
let key = field.as_str().to_owned();
|
|
||||||
|
|
||||||
if let Some(value) = self.get_local_profile_field(user_id, field).await {
|
|
||||||
profile.insert(key, value.value().into_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Insert all other profile fields
|
|
||||||
let mut all_fields = self.all_profile_keys(user_id);
|
|
||||||
|
|
||||||
while let Some((key, value)) = all_fields.next().await {
|
|
||||||
profile.insert(key, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
profile
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_local_profile_field(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
field: ProfileFieldName,
|
|
||||||
) -> Option<ProfileFieldValue> {
|
|
||||||
let value = match field.clone() {
|
|
||||||
| ProfileFieldName::AvatarUrl => self
|
|
||||||
.avatar_url(user_id)
|
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.map(to_value)
|
|
||||||
.transpose()
|
|
||||||
.expect("converting avatar url to value should succeed"),
|
|
||||||
| ProfileFieldName::DisplayName => self
|
|
||||||
.displayname(user_id)
|
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.map(to_value)
|
|
||||||
.transpose()
|
|
||||||
.expect("converting displayname to value should succeed"),
|
|
||||||
| other => self.profile_key(user_id, other.as_str()).await.ok(),
|
|
||||||
}?;
|
|
||||||
|
|
||||||
Some(
|
|
||||||
ProfileFieldValue::new(field.as_str(), value)
|
|
||||||
.expect("local profile field should be valid"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the displayname of a user on this homeserver.
|
/// Returns the displayname of a user on this homeserver.
|
||||||
pub async fn displayname(&self, user_id: &UserId) -> Result<String> {
|
pub async fn displayname(&self, user_id: &UserId) -> conduwuit::Result<String> {
|
||||||
self.db.userid_displayname.get(user_id).await.deserialized()
|
self.db.userid_displayname.get(user_id).await.deserialized()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets a new displayname or removes it if displayname is None. You still
|
/// Sets a new displayname or removes it if displayname is None. You still
|
||||||
/// need to notify all rooms of this change.
|
/// need to notify all rooms of this change.
|
||||||
fn set_displayname(&self, user_id: &UserId, displayname: Option<String>) {
|
pub fn set_displayname(&self, user_id: &UserId, displayname: Option<String>) {
|
||||||
if let Some(displayname) = displayname {
|
if let Some(displayname) = displayname {
|
||||||
self.db.userid_displayname.insert(user_id, displayname);
|
self.db.userid_displayname.insert(user_id, displayname);
|
||||||
} else {
|
} else {
|
||||||
@@ -279,12 +20,12 @@ impl super::Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Get the `avatar_url` of a user.
|
/// Get the `avatar_url` of a user.
|
||||||
pub async fn avatar_url(&self, user_id: &UserId) -> Result<OwnedMxcUri> {
|
pub async fn avatar_url(&self, user_id: &UserId) -> conduwuit::Result<OwnedMxcUri> {
|
||||||
self.db.userid_avatarurl.get(user_id).await.deserialized()
|
self.db.userid_avatarurl.get(user_id).await.deserialized()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets a new avatar_url or removes it if avatar_url is None.
|
/// Sets a new avatar_url or removes it if avatar_url is None.
|
||||||
fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option<OwnedMxcUri>) {
|
pub fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option<OwnedMxcUri>) {
|
||||||
match avatar_url {
|
match avatar_url {
|
||||||
| Some(avatar_url) => {
|
| Some(avatar_url) => {
|
||||||
self.db.userid_avatarurl.insert(user_id, &avatar_url);
|
self.db.userid_avatarurl.insert(user_id, &avatar_url);
|
||||||
@@ -296,7 +37,11 @@ impl super::Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Gets a specific user profile key
|
/// Gets a specific user profile key
|
||||||
pub async fn profile_key(&self, user_id: &UserId, profile_key: &str) -> Result<Value> {
|
pub async fn profile_key(
|
||||||
|
&self,
|
||||||
|
user_id: &UserId,
|
||||||
|
profile_key: &str,
|
||||||
|
) -> conduwuit::Result<serde_json::Value> {
|
||||||
let key = (user_id, profile_key);
|
let key = (user_id, profile_key);
|
||||||
self.db
|
self.db
|
||||||
.useridprofilekey_value
|
.useridprofilekey_value
|
||||||
@@ -309,7 +54,7 @@ impl super::Service {
|
|||||||
pub fn all_profile_keys<'a>(
|
pub fn all_profile_keys<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
user_id: &'a UserId,
|
user_id: &'a UserId,
|
||||||
) -> impl Stream<Item = (String, Value)> + 'a + Send {
|
) -> impl Stream<Item = (String, serde_json::Value)> + 'a + Send {
|
||||||
type KeyVal<'a> = ((Ignore, String), &'a [u8]);
|
type KeyVal<'a> = ((Ignore, String), &'a [u8]);
|
||||||
|
|
||||||
let prefix = (user_id, Interfix);
|
let prefix = (user_id, Interfix);
|
||||||
@@ -322,11 +67,11 @@ impl super::Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Sets a new profile key value, removes the key if value is None
|
/// Sets a new profile key value, removes the key if value is None
|
||||||
fn set_profile_key(
|
pub fn set_profile_key(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
profile_key: &str,
|
profile_key: &str,
|
||||||
profile_key_value: Option<Value>,
|
profile_key_value: Option<serde_json::Value>,
|
||||||
) {
|
) {
|
||||||
let key = (user_id, profile_key);
|
let key = (user_id, profile_key);
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
use conduwuit::utils::stream::TryIgnore;
|
|
||||||
use futures::Stream;
|
|
||||||
use ruma::{OwnedUserId, UserId};
|
|
||||||
|
|
||||||
impl super::Service {
|
|
||||||
/// Record the existence of a remote user.
|
|
||||||
pub fn record_remote_user(&self, user_id: &UserId) {
|
|
||||||
assert!(!self.services.globals.user_is_local(user_id), "user is not remote");
|
|
||||||
|
|
||||||
self.db.remoteuserid_remoteuser.insert(user_id, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a stream over all remote users this server has ever seen.
|
|
||||||
pub fn stream_remote_users(&self) -> impl Stream<Item = OwnedUserId> + Send {
|
|
||||||
self.db.remoteuserid_remoteuser.keys().ignore_err()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -49,7 +49,6 @@ url.workspace = true
|
|||||||
recaptcha-verify = { version = "0.2.0", default-features = false }
|
recaptcha-verify = { version = "0.2.0", default-features = false }
|
||||||
reqwest_recaptcha = { package = "reqwest", version = "0.12.28", default-features = false, features = ["rustls-tls-native-roots-no-provider"] } # As long as recaptcha-verify's reqwest is outdated
|
reqwest_recaptcha = { package = "reqwest", version = "0.12.28", default-features = false, features = ["rustls-tls-native-roots-no-provider"] } # As long as recaptcha-verify's reqwest is outdated
|
||||||
form_urlencoded = "1.2.2"
|
form_urlencoded = "1.2.2"
|
||||||
openidconnect.workspace = true
|
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
memory-serve = "2.1.0"
|
memory-serve = "2.1.0"
|
||||||
|
|||||||
@@ -133,7 +133,6 @@ pub fn build(services: &Services) -> Router<state::State> {
|
|||||||
.nest("/account/", account::build())
|
.nest("/account/", account::build())
|
||||||
.merge(debug::build())
|
.merge(debug::build())
|
||||||
.nest("/oauth2/", oauth::build())
|
.nest("/oauth2/", oauth::build())
|
||||||
.nest("/oidc/", oidc::build())
|
|
||||||
.merge(resources::build())
|
.merge(resources::build())
|
||||||
.merge(threepid::build())
|
.merge(threepid::build())
|
||||||
.fallback(async || WebError::NotFound),
|
.fallback(async || WebError::NotFound),
|
||||||
|
|||||||
@@ -81,10 +81,6 @@ async fn route_change_email(
|
|||||||
) -> Result {
|
) -> Result {
|
||||||
let user_id = user.expect_recent(LoginTarget::ChangeEmail)?;
|
let user_id = user.expect_recent(LoginTarget::ChangeEmail)?;
|
||||||
|
|
||||||
if !services.threepid.email_requirement().may_change() {
|
|
||||||
return Err(WebError::Forbidden("You may not change your email address.".to_owned()));
|
|
||||||
}
|
|
||||||
|
|
||||||
let Some(form) = form else {
|
let Some(form) = form else {
|
||||||
return response!(ChangeEmail::new(
|
return response!(ChangeEmail::new(
|
||||||
context.clone(),
|
context.clone(),
|
||||||
|
|||||||
@@ -7,14 +7,12 @@ use axum::{
|
|||||||
routing::{get, on},
|
routing::{get, on},
|
||||||
};
|
};
|
||||||
use conduwuit_api::client::handle_login;
|
use conduwuit_api::client::handle_login;
|
||||||
use openidconnect::core::CoreAuthPrompt;
|
|
||||||
use ruma::{
|
use ruma::{
|
||||||
OwnedUserId,
|
OwnedUserId,
|
||||||
api::client::uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
|
api::client::uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
|
||||||
};
|
};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use tower_sessions::Session;
|
use tower_sessions::Session;
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
ROUTE_PREFIX, WebError,
|
ROUTE_PREFIX, WebError,
|
||||||
@@ -23,10 +21,9 @@ use crate::{
|
|||||||
GET_POST, Result, TemplateContext,
|
GET_POST, Result, TemplateContext,
|
||||||
account::register::{TrustedFlowStatus, UntrustedFlowStatus, registration_flow_status},
|
account::register::{TrustedFlowStatus, UntrustedFlowStatus, registration_flow_status},
|
||||||
components::UserCard,
|
components::UserCard,
|
||||||
oidc::{OIDC_SESSION_ID_KEY, OidcSession, OidcSessionState},
|
|
||||||
},
|
},
|
||||||
response,
|
response,
|
||||||
session::{LoginIntent, LoginQuery, LoginTarget, User, UserSession},
|
session::{LoginQuery, LoginTarget, User, UserSession},
|
||||||
template,
|
template,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -39,7 +36,6 @@ pub(crate) fn build() -> Router<crate::State> {
|
|||||||
template! {
|
template! {
|
||||||
struct Login use "login.html.j2" {
|
struct Login use "login.html.j2" {
|
||||||
body: LoginBody,
|
body: LoginBody,
|
||||||
login_type: LoginType,
|
|
||||||
login_error: Option<String>
|
login_error: Option<String>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -48,6 +44,7 @@ template! {
|
|||||||
enum LoginBody {
|
enum LoginBody {
|
||||||
Unauthenticated {
|
Unauthenticated {
|
||||||
server_name: String,
|
server_name: String,
|
||||||
|
registration_available: bool,
|
||||||
next: Option<LoginTarget>,
|
next: Option<LoginTarget>,
|
||||||
},
|
},
|
||||||
Authenticated {
|
Authenticated {
|
||||||
@@ -55,16 +52,6 @@ enum LoginBody {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
enum LoginType {
|
|
||||||
Interactive {
|
|
||||||
registration_available: bool,
|
|
||||||
},
|
|
||||||
Oidc {
|
|
||||||
redirect_url: Url,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct LoginForm {
|
struct LoginForm {
|
||||||
identifier: Option<String>,
|
identifier: Option<String>,
|
||||||
@@ -74,46 +61,27 @@ struct LoginForm {
|
|||||||
async fn route_login(
|
async fn route_login(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
Extension(context): Extension<TemplateContext>,
|
Extension(context): Extension<TemplateContext>,
|
||||||
Expect(Query(LoginQuery { next, reauthenticate, intent })): Expect<Query<LoginQuery>>,
|
Expect(Query(LoginQuery { next, reauthenticate })): Expect<Query<LoginQuery>>,
|
||||||
session_store: Session,
|
session_store: Session,
|
||||||
user: User<true>,
|
user: User<true>,
|
||||||
PostForm(form): PostForm<LoginForm>,
|
PostForm(form): PostForm<LoginForm>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let user_id = user.into_session().map(|session| session.user_id);
|
let user_id = user.into_session().map(|session| session.user_id);
|
||||||
|
|
||||||
let login_type = if services.oidc.enabled() {
|
|
||||||
let (session, redirect_url) = services
|
|
||||||
.oidc
|
|
||||||
.begin_session(match intent {
|
|
||||||
| Some(LoginIntent::SwitchAccounts) => Some(CoreAuthPrompt::SelectAccount),
|
|
||||||
| _ if reauthenticate => Some(CoreAuthPrompt::Consent),
|
|
||||||
| _ => None,
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
session_store
|
|
||||||
.insert(OIDC_SESSION_ID_KEY, OidcSession {
|
|
||||||
next: next.clone().unwrap_or_default(),
|
|
||||||
state: OidcSessionState::CodeExchange { expected_user: user_id.clone(), session },
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.expect("should be able to serialize OIDC session");
|
|
||||||
|
|
||||||
LoginType::Oidc { redirect_url }
|
|
||||||
} else {
|
|
||||||
let (trusted_flow_status, untrusted_flow_status) =
|
|
||||||
registration_flow_status(&services).await;
|
|
||||||
|
|
||||||
let registration_available = matches!(trusted_flow_status, TrustedFlowStatus::Available)
|
|
||||||
|| matches!(untrusted_flow_status, UntrustedFlowStatus::Available { .. });
|
|
||||||
|
|
||||||
LoginType::Interactive { registration_available }
|
|
||||||
};
|
|
||||||
|
|
||||||
let body = match &user_id {
|
let body = match &user_id {
|
||||||
| None => LoginBody::Unauthenticated {
|
| None => {
|
||||||
server_name: services.globals.server_name().to_string(),
|
let (trusted_flow_status, untrusted_flow_status) =
|
||||||
next: next.clone(),
|
registration_flow_status(&services).await;
|
||||||
|
|
||||||
|
let registration_available =
|
||||||
|
matches!(trusted_flow_status, TrustedFlowStatus::Available)
|
||||||
|
|| matches!(untrusted_flow_status, UntrustedFlowStatus::Available { .. });
|
||||||
|
|
||||||
|
LoginBody::Unauthenticated {
|
||||||
|
server_name: services.globals.server_name().to_string(),
|
||||||
|
registration_available,
|
||||||
|
next: next.clone(),
|
||||||
|
}
|
||||||
},
|
},
|
||||||
| Some(user_id) => {
|
| Some(user_id) => {
|
||||||
if !reauthenticate {
|
if !reauthenticate {
|
||||||
@@ -126,7 +94,7 @@ async fn route_login(
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut template = Login::new(context, body, login_type, None);
|
let mut template = Login::new(context, body, None);
|
||||||
|
|
||||||
if let Some(form) = form {
|
if let Some(form) = form {
|
||||||
let login_result = match (user_id, form.identifier) {
|
let login_result = match (user_id, form.identifier) {
|
||||||
|
|||||||
@@ -66,7 +66,6 @@ template! {
|
|||||||
enum AccountBody {
|
enum AccountBody {
|
||||||
Unlocked {
|
Unlocked {
|
||||||
suspended: bool,
|
suspended: bool,
|
||||||
oidc_enabled: bool,
|
|
||||||
email_requirement: EmailRequirement,
|
email_requirement: EmailRequirement,
|
||||||
email: Option<String>,
|
email: Option<String>,
|
||||||
devices: Vec<DeviceCard>,
|
devices: Vec<DeviceCard>,
|
||||||
@@ -129,7 +128,6 @@ async fn get_account(
|
|||||||
|
|
||||||
response!(Account::new(context, user_card, AccountBody::Unlocked {
|
response!(Account::new(context, user_card, AccountBody::Unlocked {
|
||||||
suspended,
|
suspended,
|
||||||
oidc_enabled: services.oidc.enabled(),
|
|
||||||
email_requirement,
|
email_requirement,
|
||||||
email,
|
email,
|
||||||
devices: device_cards
|
devices: device_cards
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ use ruma::UserId;
|
|||||||
use validator::{Validate, ValidationError, ValidationErrors};
|
use validator::{Validate, ValidationError, ValidationErrors};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
WebError,
|
|
||||||
extract::PostForm,
|
extract::PostForm,
|
||||||
form,
|
form,
|
||||||
pages::{
|
pages::{
|
||||||
@@ -66,17 +65,11 @@ async fn route_change_password(
|
|||||||
user: User,
|
user: User,
|
||||||
PostForm(form): PostForm<ChangePasswordForm>,
|
PostForm(form): PostForm<ChangePasswordForm>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
if services.oidc.enabled() {
|
|
||||||
return Err(WebError::BadRequest(
|
|
||||||
"Password changing is not available on this server".to_owned(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let user_id = user.expect(LoginTarget::ChangePassword)?;
|
let user_id = user.expect(LoginTarget::ChangePassword)?;
|
||||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||||
|
|
||||||
let body = if let Some(form) = form {
|
let body = if let Some(form) = form {
|
||||||
match change_password(&services, &user_id, form).await? {
|
match change_password(&services, &user_id, form).await {
|
||||||
| Ok(()) => ChangePasswordBody::Success,
|
| Ok(()) => ChangePasswordBody::Success,
|
||||||
| Err(errors) =>
|
| Err(errors) =>
|
||||||
ChangePasswordBody::Form(ChangePasswordForm::with_errors(context.clone(), errors)),
|
ChangePasswordBody::Form(ChangePasswordForm::with_errors(context.clone(), errors)),
|
||||||
@@ -92,7 +85,7 @@ async fn change_password(
|
|||||||
services: &crate::State,
|
services: &crate::State,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
form: ChangePasswordForm,
|
form: ChangePasswordForm,
|
||||||
) -> Result<Result<(), ValidationErrors>> {
|
) -> Result<(), ValidationErrors> {
|
||||||
form.validate()?;
|
form.validate()?;
|
||||||
|
|
||||||
if services
|
if services
|
||||||
@@ -107,12 +100,12 @@ async fn change_password(
|
|||||||
ValidationError::new("wrong").with_message("Incorrect password".into()),
|
ValidationError::new("wrong").with_message("Incorrect password".into()),
|
||||||
);
|
);
|
||||||
|
|
||||||
return Ok(Err(errors));
|
return Err(errors);
|
||||||
}
|
}
|
||||||
|
|
||||||
match HashedPassword::new(&form.new_password) {
|
match HashedPassword::new(&form.new_password) {
|
||||||
| Ok(hash) => {
|
| Ok(hash) => {
|
||||||
services.users.set_password(user_id, hash).await?;
|
services.users.set_password(user_id, Some(hash));
|
||||||
},
|
},
|
||||||
| Err(err) => {
|
| Err(err) => {
|
||||||
let mut errors = ValidationErrors::new();
|
let mut errors = ValidationErrors::new();
|
||||||
@@ -121,9 +114,9 @@ async fn change_password(
|
|||||||
ValidationError::new("malformed").with_message(err.message().into()),
|
ValidationError::new("malformed").with_message(err.message().into()),
|
||||||
);
|
);
|
||||||
|
|
||||||
return Ok(Err(errors));
|
return Err(errors);
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Ok(()))
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -65,13 +65,6 @@ async fn route_reset_password(
|
|||||||
return response!(ResetPassword::new(context, ResetPasswordBody::Unavailable));
|
return response!(ResetPassword::new(context, ResetPasswordBody::Unavailable));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if OIDC is enabled
|
|
||||||
if services.oidc.enabled() {
|
|
||||||
return Err(WebError::BadRequest(
|
|
||||||
"Password resets are not available on this server".to_owned(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let Some(form) = form else {
|
let Some(form) = form else {
|
||||||
// For GET requests return the reset request form
|
// For GET requests return the reset request form
|
||||||
return response!(ResetPassword::new(
|
return response!(ResetPassword::new(
|
||||||
@@ -221,7 +214,7 @@ async fn route_reset_password_validate(
|
|||||||
| Ok(hash) => {
|
| Ok(hash) => {
|
||||||
let _ = session.consume();
|
let _ = session.consume();
|
||||||
|
|
||||||
services.users.set_password(&user_id, hash).await?;
|
services.users.set_password(&user_id, Some(hash));
|
||||||
|
|
||||||
ResetPasswordValidateBody::ResetSuccess { user_card }
|
ResetPasswordValidateBody::ResetSuccess { user_card }
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -134,15 +134,13 @@ async fn route_register(
|
|||||||
) -> Result {
|
) -> Result {
|
||||||
let is_first_run = services.firstrun.is_first_run();
|
let is_first_run = services.firstrun.is_first_run();
|
||||||
|
|
||||||
if services.oidc.enabled()
|
if session_store
|
||||||
|| session_store
|
.get::<IgnoredAny>(User::KEY)
|
||||||
.get::<IgnoredAny>(User::KEY)
|
.await
|
||||||
.await
|
.unwrap()
|
||||||
.unwrap()
|
.is_some()
|
||||||
.is_some()
|
|
||||||
{
|
{
|
||||||
// Redirect to the account panel if the user is already logged in
|
// Redirect already logged-in users to the account panel
|
||||||
// or OIDC is enabled
|
|
||||||
return response!(Redirect::to(&LoginTarget::Account.target_path()));
|
return response!(Redirect::to(&LoginTarget::Account.target_path()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -312,7 +310,7 @@ async fn get_register_email_validate(
|
|||||||
|
|
||||||
response!(
|
response!(
|
||||||
complete_registration(&services, session_store, completed_registration, Some(email))
|
complete_registration(&services, session_store, completed_registration, Some(email))
|
||||||
.await?
|
.await
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -504,7 +502,7 @@ async fn begin_registration(
|
|||||||
} else {
|
} else {
|
||||||
// If email isn't required we can immediately complete registration
|
// If email isn't required we can immediately complete registration
|
||||||
Ok(response!(
|
Ok(response!(
|
||||||
complete_registration(services, session_store, completed_registration, None).await?
|
complete_registration(services, session_store, completed_registration, None).await
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -519,11 +517,11 @@ async fn complete_registration(
|
|||||||
next,
|
next,
|
||||||
}: CompletedRegistration,
|
}: CompletedRegistration,
|
||||||
email: Option<Address>,
|
email: Option<Address>,
|
||||||
) -> Result<Redirect> {
|
) -> Redirect {
|
||||||
services
|
services
|
||||||
.users
|
.users
|
||||||
.create_local_account(&user_id, Some(password_hash), email)
|
.create_local_account(&user_id, password_hash, email)
|
||||||
.await?;
|
.await;
|
||||||
|
|
||||||
if let Some(registration_token) = registration_token {
|
if let Some(registration_token) = registration_token {
|
||||||
services
|
services
|
||||||
@@ -538,7 +536,7 @@ async fn complete_registration(
|
|||||||
.await
|
.await
|
||||||
.expect("should be able to serialize user session");
|
.expect("should be able to serialize user session");
|
||||||
|
|
||||||
Ok(Redirect::to(&next.unwrap_or_default().target_path()))
|
Redirect::to(&next.unwrap_or_default().target_path())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) async fn registration_flow_status(
|
pub(super) async fn registration_flow_status(
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ mod components;
|
|||||||
pub(super) mod debug;
|
pub(super) mod debug;
|
||||||
pub(super) mod index;
|
pub(super) mod index;
|
||||||
pub(super) mod oauth;
|
pub(super) mod oauth;
|
||||||
pub(super) mod oidc;
|
|
||||||
pub(super) mod resources;
|
pub(super) mod resources;
|
||||||
pub(super) mod threepid;
|
pub(super) mod threepid;
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ use crate::{
|
|||||||
components::{Avatar, AvatarType, ClientScopes},
|
components::{Avatar, AvatarType, ClientScopes},
|
||||||
},
|
},
|
||||||
response,
|
response,
|
||||||
session::{LoginIntent, LoginQuery, LoginTarget, User},
|
session::{LoginQuery, LoginTarget, User},
|
||||||
template,
|
template,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -129,8 +129,7 @@ async fn route_authorization_code(
|
|||||||
context,
|
context,
|
||||||
serde_urlencoded::to_string(LoginQuery {
|
serde_urlencoded::to_string(LoginQuery {
|
||||||
next: Some(LoginTarget::AuthorizationCode(query)),
|
next: Some(LoginTarget::AuthorizationCode(query)),
|
||||||
intent: Some(LoginIntent::SwitchAccounts),
|
reauthenticate: false,
|
||||||
..Default::default()
|
|
||||||
})
|
})
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
user_id,
|
user_id,
|
||||||
|
|||||||
@@ -1,196 +0,0 @@
|
|||||||
use std::time::SystemTime;
|
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Extension, Router,
|
|
||||||
extract::{Query, State},
|
|
||||||
response::Redirect,
|
|
||||||
routing::on,
|
|
||||||
};
|
|
||||||
use conduwuit_service::{oauth::grant::AuthorizationCodeResponse, oidc::SessionCompletionStatus};
|
|
||||||
use futures::FutureExt;
|
|
||||||
use ruma::{OwnedServerName, UserId};
|
|
||||||
use serde::{Deserialize, de::IgnoredAny};
|
|
||||||
use tower_sessions::Session;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
WebError,
|
|
||||||
extract::{Expect, PostForm},
|
|
||||||
pages::{
|
|
||||||
GET_POST, Result, TemplateContext,
|
|
||||||
components::UserCard,
|
|
||||||
oidc::{OIDC_SESSION_ID_KEY, OidcSession, OidcSessionState},
|
|
||||||
},
|
|
||||||
response,
|
|
||||||
session::{User, UserSession},
|
|
||||||
template,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub(crate) fn build() -> Router<crate::State> {
|
|
||||||
Router::new().route("/", on(GET_POST, route_complete))
|
|
||||||
}
|
|
||||||
|
|
||||||
template! {
|
|
||||||
struct OidcComplete use "oidc_complete.html.j2" {
|
|
||||||
body: OidcCompleteBody
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
enum OidcCompleteBody {
|
|
||||||
UsernamePrompt {
|
|
||||||
server_name: OwnedServerName,
|
|
||||||
username_error: Option<String>,
|
|
||||||
},
|
|
||||||
PasswordPrompt {
|
|
||||||
username: String,
|
|
||||||
user_card: UserCard,
|
|
||||||
password_error: bool,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct LoginForm {
|
|
||||||
username: String,
|
|
||||||
password: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn route_complete(
|
|
||||||
State(services): State<crate::State>,
|
|
||||||
Extension(context): Extension<TemplateContext>,
|
|
||||||
Expect(Query(query)): Expect<Query<AuthorizationCodeResponse>>,
|
|
||||||
session_store: Session,
|
|
||||||
user: User<true>,
|
|
||||||
PostForm(form): PostForm<LoginForm>,
|
|
||||||
) -> Result {
|
|
||||||
let user_id = user.into_session().map(|session| session.user_id);
|
|
||||||
|
|
||||||
let Some(session) = session_store
|
|
||||||
.get::<OidcSession>(OIDC_SESSION_ID_KEY)
|
|
||||||
.await
|
|
||||||
.expect("should be able to deserialize oidc session")
|
|
||||||
else {
|
|
||||||
return response!(WebError::BadRequest(
|
|
||||||
"No OIDC session found. What are you doing here?".to_owned()
|
|
||||||
));
|
|
||||||
};
|
|
||||||
|
|
||||||
let session_completion_status = match session.state {
|
|
||||||
| OidcSessionState::CodeExchange { expected_user, session: pending_session } => {
|
|
||||||
if let (Some(user_id), Some(expected_user)) = (&user_id, &expected_user)
|
|
||||||
&& user_id != expected_user
|
|
||||||
{
|
|
||||||
return response!(WebError::BadRequest(
|
|
||||||
"Identity mismatch. You may have switched accounts at your identity \
|
|
||||||
provider. Please log out and back in to continue."
|
|
||||||
.to_owned()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let claims = services
|
|
||||||
.oidc
|
|
||||||
.exchange_code(pending_session, query)
|
|
||||||
.boxed()
|
|
||||||
.await
|
|
||||||
.map_err(|err| WebError::BadRequest(err.to_owned()))?;
|
|
||||||
|
|
||||||
session_store
|
|
||||||
.insert(OIDC_SESSION_ID_KEY, OidcSession {
|
|
||||||
next: session.next.clone(),
|
|
||||||
state: OidcSessionState::Authorized { claims: Box::new(claims.clone()) },
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.expect("Should be able to serialize oidc session");
|
|
||||||
|
|
||||||
services.oidc.complete_session(&claims, None).await
|
|
||||||
},
|
|
||||||
| OidcSessionState::Authorized { claims } => {
|
|
||||||
let supplied_user_id = if let Some(form) = form {
|
|
||||||
if let Ok(user_id) = UserId::parse(format!(
|
|
||||||
"@{}:{}",
|
|
||||||
&form.username,
|
|
||||||
services.globals.server_name()
|
|
||||||
)) && services.users.status(&user_id).await.is_active()
|
|
||||||
{
|
|
||||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
|
||||||
|
|
||||||
if let Some(password) = form.password {
|
|
||||||
if services
|
|
||||||
.users
|
|
||||||
.check_password(&user_id, &password)
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
Some(user_id)
|
|
||||||
} else {
|
|
||||||
return response!(OidcComplete::new(
|
|
||||||
context,
|
|
||||||
OidcCompleteBody::PasswordPrompt {
|
|
||||||
username: form.username,
|
|
||||||
user_card,
|
|
||||||
password_error: true
|
|
||||||
}
|
|
||||||
));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return response!(OidcComplete::new(
|
|
||||||
context,
|
|
||||||
OidcCompleteBody::PasswordPrompt {
|
|
||||||
username: form.username,
|
|
||||||
user_card,
|
|
||||||
password_error: false,
|
|
||||||
}
|
|
||||||
));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
match services
|
|
||||||
.users
|
|
||||||
.determine_registration_user_id(Some(form.username), None, None)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
| Ok(user_id) => Some(user_id),
|
|
||||||
| Err(err) => {
|
|
||||||
return response!(OidcComplete::new(
|
|
||||||
context,
|
|
||||||
OidcCompleteBody::UsernamePrompt {
|
|
||||||
server_name: services.globals.server_name().to_owned(),
|
|
||||||
username_error: Some(err.message()),
|
|
||||||
}
|
|
||||||
));
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
services
|
|
||||||
.oidc
|
|
||||||
.complete_session(&claims, supplied_user_id)
|
|
||||||
.await
|
|
||||||
},
|
|
||||||
}
|
|
||||||
.map_err(|err| WebError::BadRequest(err.to_owned()))?;
|
|
||||||
|
|
||||||
match session_completion_status {
|
|
||||||
| SessionCompletionStatus::Complete(user_id) => {
|
|
||||||
let _ = session_store
|
|
||||||
.remove::<IgnoredAny>(OIDC_SESSION_ID_KEY)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let user_session = UserSession { user_id, last_login: SystemTime::now() };
|
|
||||||
|
|
||||||
session_store
|
|
||||||
.insert(User::KEY, user_session)
|
|
||||||
.await
|
|
||||||
.expect("should be able to serialize user session");
|
|
||||||
|
|
||||||
response!(Redirect::to(&session.next.target_path()))
|
|
||||||
},
|
|
||||||
| SessionCompletionStatus::NeedsUserId => {
|
|
||||||
response!(OidcComplete::new(context, OidcCompleteBody::UsernamePrompt {
|
|
||||||
server_name: services.globals.server_name().to_owned(),
|
|
||||||
username_error: None
|
|
||||||
}))
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
use axum::Router;
|
|
||||||
use conduwuit_service::oidc::{self, Claims};
|
|
||||||
use ruma::OwnedUserId;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::session::LoginTarget;
|
|
||||||
|
|
||||||
mod complete;
|
|
||||||
|
|
||||||
pub(crate) const OIDC_SESSION_ID_KEY: &str = "oidc_session";
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
|
||||||
pub(crate) struct OidcSession {
|
|
||||||
pub next: LoginTarget,
|
|
||||||
pub state: OidcSessionState,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
|
||||||
pub(crate) enum OidcSessionState {
|
|
||||||
CodeExchange {
|
|
||||||
expected_user: Option<OwnedUserId>,
|
|
||||||
session: oidc::PendingSession,
|
|
||||||
},
|
|
||||||
Authorized {
|
|
||||||
claims: Box<Claims>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn build() -> Router<crate::State> {
|
|
||||||
#[allow(clippy::wildcard_imports)]
|
|
||||||
use self::*;
|
|
||||||
|
|
||||||
Router::new().nest("/complete", complete::build())
|
|
||||||
}
|
|
||||||
@@ -341,8 +341,18 @@ ul.bullet-separated {
|
|||||||
margin-top: 0;
|
margin-top: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.mobile-hidden {
|
ul.bullet-separated {
|
||||||
display: none;
|
display: block;
|
||||||
|
padding-left: inherit;
|
||||||
|
|
||||||
|
li {
|
||||||
|
display: list-item;
|
||||||
|
list-style-type: disc;
|
||||||
|
|
||||||
|
&::before {
|
||||||
|
content: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -33,7 +33,6 @@
|
|||||||
padding: 0.5em;
|
padding: 0.5em;
|
||||||
margin-bottom: 0.5em;
|
margin-bottom: 0.5em;
|
||||||
line-height: 1;
|
line-height: 1;
|
||||||
align-items: baseline;
|
|
||||||
|
|
||||||
border-radius: var(--border-radius-sm);
|
border-radius: var(--border-radius-sm);
|
||||||
border: 2px solid var(--secondary);
|
border: 2px solid var(--secondary);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
</span>
|
</span>
|
||||||
{% if style == DeviceCardStyle::Detailed %}
|
{% if style == DeviceCardStyle::Detailed %}
|
||||||
<span class="id">
|
<span class="id">
|
||||||
<span class="mobile-hidden">•</span>
|
•
|
||||||
<ul class="bullet-separated">
|
<ul class="bullet-separated">
|
||||||
<li>{{ device_id }}</li>
|
<li>{{ device_id }}</li>
|
||||||
<li>
|
<li>
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ Your account
|
|||||||
<h1>Manage your account</h1>
|
<h1>Manage your account</h1>
|
||||||
{{ user_card }}
|
{{ user_card }}
|
||||||
{% match body %}
|
{% match body %}
|
||||||
{% when AccountBody::Unlocked { suspended, email_requirement, email, devices, oidc_enabled } %}
|
{% when AccountBody::Unlocked { suspended, email_requirement, email, devices } %}
|
||||||
{% if suspended %}
|
{% if suspended %}
|
||||||
<p class="card danger">
|
<p class="card danger">
|
||||||
⚠️ Your account has been suspended by your homeserver's administrator.
|
⚠️ Your account has been suspended by your homeserver's administrator.
|
||||||
@@ -17,23 +17,19 @@ Your account
|
|||||||
</p>
|
</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<section>
|
<section>
|
||||||
{% if email_requirement.may_view() %}
|
{% if email_requirement.may_change() %}
|
||||||
<p>
|
<p>
|
||||||
{% if let Some(email) = email %}
|
{% if let Some(email) = email %}
|
||||||
Your account's associated email address is <code>{{ email }}</code>.
|
Your account's associated email address is <code>{{ email }}</code>.
|
||||||
{% else %}
|
{% else %}
|
||||||
Your account has no associated email address.
|
Your account has no associated email address.
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if email_requirement.may_change() %}
|
<a href="email/change/">Change your email</a>
|
||||||
<a href="email/change/">Change your email</a>\
|
|
||||||
{% endif %}
|
|
||||||
</p>
|
|
||||||
{% endif %}
|
|
||||||
{% if !oidc_enabled %}
|
|
||||||
<p>
|
|
||||||
<a href="password/change">Change your password</a>
|
|
||||||
</p>
|
</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
<p>
|
||||||
|
<a href="password/change">Change your password</a>
|
||||||
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section>
|
<section>
|
||||||
|
|||||||
@@ -9,14 +9,9 @@ Log in
|
|||||||
{%- endblock -%}
|
{%- endblock -%}
|
||||||
|
|
||||||
{%- block content -%}
|
{%- block content -%}
|
||||||
{% match login_type %}
|
|
||||||
{% when LoginType::Interactive { .. } %}
|
|
||||||
<div class="panel narrow">
|
<div class="panel narrow">
|
||||||
{% when LoginType::Oidc { .. } %}
|
|
||||||
<div class="panel narrow middle"/>
|
|
||||||
{% endmatch %}
|
|
||||||
{% match body %}
|
{% match body %}
|
||||||
{% when LoginBody::Unauthenticated { server_name, next } %}
|
{% when LoginBody::Unauthenticated { server_name, registration_available, next } %}
|
||||||
<h1 class="with-matrix-icon">
|
<h1 class="with-matrix-icon">
|
||||||
{% if next.is_some() %}
|
{% if next.is_some() %}
|
||||||
Log in to continue
|
Log in to continue
|
||||||
@@ -30,49 +25,39 @@ Log in
|
|||||||
<p>
|
<p>
|
||||||
You're about to log in to your account on <em>{{ server_name }}</em>
|
You're about to log in to your account on <em>{{ server_name }}</em>
|
||||||
</p>
|
</p>
|
||||||
{% match login_type %}
|
<hr>
|
||||||
{% when LoginType::Interactive { registration_available } %}
|
<form method="post">
|
||||||
<hr>
|
<p>
|
||||||
<form method="post">
|
<label for="identifier">Username or email address</label>
|
||||||
<p>
|
<input type="text" id="identifier" name="identifier" autocomplete="username">
|
||||||
<label for="identifier">Username or email address</label>
|
</p>
|
||||||
<input type="text" id="identifier" name="identifier" autocomplete="username">
|
<p>
|
||||||
</p>
|
<label for="password">Password</label>
|
||||||
<p>
|
<input type="password" id="password" name="password" autocomplete="current-password">
|
||||||
<label for="password">Password</label>
|
</p>
|
||||||
<input type="password" id="password" name="password" autocomplete="current-password">
|
<button type="submit">Log in</button>
|
||||||
</p>
|
</form>
|
||||||
<button type="submit">Log in</button>
|
<div class="centered-links">
|
||||||
</form>
|
{% if registration_available %}
|
||||||
<div class="centered-links">
|
{% let query = next.as_ref().map(serde_urlencoded::to_string).transpose().unwrap().unwrap_or_default() %}
|
||||||
{% if registration_available %}
|
<a href="{{ crate::ROUTE_PREFIX }}/account/register/?{{ query }}">Sign up</a>
|
||||||
{% let query = next.as_ref().map(serde_urlencoded::to_string).transpose().unwrap().unwrap_or_default() %}
|
{% endif %}
|
||||||
<a href="{{ crate::ROUTE_PREFIX }}/account/register/?{{ query }}">Sign up</a>
|
<a href="{{ crate::ROUTE_PREFIX }}/account/password/reset/">Forgot your password?</a>
|
||||||
{% endif %}
|
</div>
|
||||||
<a href="{{ crate::ROUTE_PREFIX }}/account/password/reset/">Forgot your password?</a>
|
|
||||||
</div>
|
|
||||||
{% when LoginType::Oidc { redirect_url } %}
|
|
||||||
<a class="button" href="{{ redirect_url }}">Continue</a>
|
|
||||||
{% endmatch %}
|
|
||||||
{% when LoginBody::Authenticated { user_card } %}
|
{% when LoginBody::Authenticated { user_card } %}
|
||||||
<h1>Confirm your identity</h1>
|
<h1>Confirm your identity</h1>
|
||||||
{{ user_card }}
|
{{ user_card }}
|
||||||
{% match login_type %}
|
<p>Enter your password to continue.</p>
|
||||||
{% when LoginType::Interactive { .. } %}
|
<form method="post">
|
||||||
<p>Enter your password to continue.</p>
|
<p>
|
||||||
<form method="post">
|
<label for="password">Password</label>
|
||||||
<p>
|
<input type="password" id="password" name="password" autocomplete="current-password">
|
||||||
<label for="password">Password</label>
|
</p>
|
||||||
<input type="password" id="password" name="password" autocomplete="current-password">
|
<button type="submit">Continue</button>
|
||||||
</p>
|
</form>
|
||||||
<button type="submit">Continue</button>
|
<div class="centered-links">
|
||||||
</form>
|
<a href="{{ crate::ROUTE_PREFIX }}/account/password/reset/">Forgot your password?</a>
|
||||||
<div class="centered-links">
|
</div>
|
||||||
<a href="{{ crate::ROUTE_PREFIX }}/account/password/reset/">Forgot your password?</a>
|
|
||||||
</div>
|
|
||||||
{% when LoginType::Oidc { redirect_url } %}
|
|
||||||
<a class="button" href="{{ redirect_url }}">Continue</a>
|
|
||||||
{% endmatch %}
|
|
||||||
{% endmatch %}
|
{% endmatch %}
|
||||||
{% if let Some(error) = login_error %}
|
{% if let Some(error) = login_error %}
|
||||||
<small class="error">{{ error }}</small>
|
<small class="error">{{ error }}</small>
|
||||||
|
|||||||
@@ -1,59 +0,0 @@
|
|||||||
{% extends "_layout.html.j2" %}
|
|
||||||
{% import "_components/form.html.j2" as form %}
|
|
||||||
|
|
||||||
{%- block head -%}
|
|
||||||
<link rel="stylesheet" href="{{ crate::ROUTE_PREFIX }}/resources/login.css">
|
|
||||||
{%- endblock -%}
|
|
||||||
|
|
||||||
{%- block title -%}
|
|
||||||
Link your account
|
|
||||||
{%- endblock -%}
|
|
||||||
|
|
||||||
{%- block content -%}
|
|
||||||
<div class="panel narrow">
|
|
||||||
<h1 class="with-matrix-icon">
|
|
||||||
Link your account
|
|
||||||
<a href="https://matrix.org" target="_blank" noreferer>
|
|
||||||
<img class="matrix-icon" alt="Matrix logo" aria-ignore src="{{ crate::ROUTE_PREFIX }}/resources/matrix-icon.svg">
|
|
||||||
</a>
|
|
||||||
</h1>
|
|
||||||
{% match body %}
|
|
||||||
{% when OidcCompleteBody::UsernamePrompt { server_name, username_error } %}
|
|
||||||
<form method="post">
|
|
||||||
<p>
|
|
||||||
To finish linking your account to Matrix, choose a username.
|
|
||||||
<br>If you have an existing Matrix account, enter its user ID to link it.
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<label for="username">Username</label>
|
|
||||||
<span class="username-input">
|
|
||||||
<span>@</span>
|
|
||||||
<input type="text" id="username" name="username" autocomplete="username" required>
|
|
||||||
<span>:{{ server_name }}</span>
|
|
||||||
</span>
|
|
||||||
{% if let Some(username_error) = username_error %}
|
|
||||||
<small class="error">
|
|
||||||
{{ username_error }}
|
|
||||||
</small>
|
|
||||||
{% endif %}
|
|
||||||
<small>Your username cannot be changed after you link your account.</small>
|
|
||||||
</p>
|
|
||||||
<button type="submit">Continue</button>
|
|
||||||
</form>
|
|
||||||
{% when OidcCompleteBody::PasswordPrompt { username, user_card, password_error } %}
|
|
||||||
{{ user_card }}
|
|
||||||
<form method="post">
|
|
||||||
<p>To link this legacy account, enter the password you used to use when logging in.</p>
|
|
||||||
<p>
|
|
||||||
<label for="password">Password</label>
|
|
||||||
<input type="password" id="password" name="password" autocomplete="current-password">
|
|
||||||
{% if password_error %}
|
|
||||||
<small class="error">Incorrect password</small>
|
|
||||||
{% endif %}
|
|
||||||
</p>
|
|
||||||
<input type="hidden" name="username" value="{{ username }}">
|
|
||||||
<button type="submit">Continue</button>
|
|
||||||
</form>
|
|
||||||
{% endmatch %}
|
|
||||||
</div>
|
|
||||||
{% endblock %}
|
|
||||||
+6
-13
@@ -24,8 +24,6 @@ pub(crate) struct LoginQuery {
|
|||||||
pub next: Option<LoginTarget>,
|
pub next: Option<LoginTarget>,
|
||||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||||
pub reauthenticate: bool,
|
pub reauthenticate: bool,
|
||||||
#[serde(default)]
|
|
||||||
pub intent: Option<LoginIntent>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||||
@@ -67,12 +65,6 @@ impl LoginTarget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub(crate) enum LoginIntent {
|
|
||||||
SwitchAccounts,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An extractor that fetches the authenticated user.
|
/// An extractor that fetches the authenticated user.
|
||||||
pub(crate) struct User<const ALLOW_LOCKED: bool = false>(Option<UserSession>);
|
pub(crate) struct User<const ALLOW_LOCKED: bool = false>(Option<UserSession>);
|
||||||
|
|
||||||
@@ -115,7 +107,7 @@ impl<const ALLOW_LOCKED: bool> User<ALLOW_LOCKED> {
|
|||||||
} else {
|
} else {
|
||||||
Err(WebError::LoginRequired(LoginQuery {
|
Err(WebError::LoginRequired(LoginQuery {
|
||||||
next: Some(or_else),
|
next: Some(or_else),
|
||||||
..Default::default()
|
reauthenticate: false,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -130,13 +122,12 @@ impl<const ALLOW_LOCKED: bool> User<ALLOW_LOCKED> {
|
|||||||
Err(WebError::LoginRequired(LoginQuery {
|
Err(WebError::LoginRequired(LoginQuery {
|
||||||
next: Some(or_else),
|
next: Some(or_else),
|
||||||
reauthenticate: true,
|
reauthenticate: true,
|
||||||
..Default::default()
|
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Err(WebError::LoginRequired(LoginQuery {
|
Err(WebError::LoginRequired(LoginQuery {
|
||||||
next: Some(or_else),
|
next: Some(or_else),
|
||||||
..Default::default()
|
reauthenticate: false,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -171,8 +162,10 @@ pub(crate) async fn require_active(
|
|||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
allow_locked: bool,
|
allow_locked: bool,
|
||||||
) -> Result<(), Response> {
|
) -> Result<(), Response> {
|
||||||
if let Err(err) = services.users.status(user_id).await.ensure_active() {
|
if !services.users.is_active(user_id).await {
|
||||||
return Err(WebError::Forbidden(err.message()).into_response());
|
return Err(
|
||||||
|
WebError::Forbidden("Your account is deactivated.".to_owned()).into_response()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if !allow_locked
|
if !allow_locked
|
||||||
|
|||||||
Reference in new issue
Block a user