Compare commits

..
Author SHA1 Message Date
Ginger 84b5316117 chore: News fragment 2026-12-02 23:12:06 -05:00
Ginger d59ae90fc9 refactor: Remove element_hacks 2026-12-02 23:06:01 -05:00
17 changed files with 20 additions and 282 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
Continuwuity now supports the OAuth 2.0 client credentials grant type, allowing secure automated access to the Matrix homeserver admin API, as well as future administrative functionality. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
The `element_hacks` build feature, which has done almost nothing for many versions, has been removed completely. Contributed by @ginger.
-42
View File
@@ -2675,48 +2675,6 @@
# env: CONTINUWUITY_OAUTH__OIDC__PROFILE_KEY_IMPORT_MODE
#profile_key_import_mode = "on_registration"
#[global.oauth.clients."$id"]
# Use this section to add static OAuth clients for bots and automation.
# Clients added here may use the client credentials OAuth grant to authorize
# themselves with Continuwuity.
#
# Make sure to replace `$id` in the header with your client ID of choice! You can
# add more copies of this section with different IDs to add multiple clients.
#
# Because the client credentials grant authorizes the client as itself, without
# an attached user, clients that use it will not be able to access most of the Matrix
# client-server API. Administrative functionality that does not require a user
# will still be available.
# The client's client secret.
#
# This must be supplied as the `client_secret` parameter when requesting
# an access token with the OAuth 2.0 token endpoint. Continuwuity does
# not check the `Authorization` header for requests to this endpoint.
#
#client_secret =
# A list of scopes that the client may request. Continuwuity allows static
# clients to request the following scopes:
#
# - "urn:matrix:client:cc.c10y.msc4484.server_administration" (MSC4484):
# This scope grants access to the Matrix server administration APIs, as
# well as Continuwuity's internal admin API (currently a work in
# progress).
# - "urn:matrix:client:api:*": This scope grants access to the Matrix
# client-server API. Most endpoints require an authenticated Matrix user
# and thus will not be usable by static clients.
#
# The `urn:matrix:client:device:<id>` scope may not be requested by static
# clients.
#
# Scopes listed here are not granted by default. The client must
# explicitly include them in the `scope` parameter of its access token
# request.
#
#scopes = []
[global.experiments]
# Continuwuity's experimental features are frequently updated.
# If you got this configuration via a package manager, chances are it's outdated.
+1 -1
View File
@@ -102,7 +102,7 @@ look like this:
RUSTFLAGS="--cfg tokio_unstable" cargo +nightly build \
--release \
--no-default-features \
--features=systemd,element_hacks,gzip_compression,brotli_compression,zstd_compression,tokio_console
--features=systemd,gzip_compression,brotli_compression,zstd_compression,tokio_console
```
You will also need to enable the `tokio_console` config option in Continuwuity
+1 -1
View File
@@ -146,7 +146,7 @@ cargo clippy \
--locked \
--profile test \
--no-default-features \
--features=console,systemd,element_hacks,direct_tls,perf_measurements,brotli_compression \
--features=console,systemd,direct_tls,perf_measurements,brotli_compression \
--color=always \
-- \
-D warnings
-3
View File
@@ -21,9 +21,6 @@ brotli_compression = [
"conduwuit-service/brotli_compression",
"reqwest/brotli",
]
element_hacks = [
"conduwuit-service/element_hacks",
]
gzip_compression = [
"conduwuit-core/gzip_compression",
"conduwuit-service/gzip_compression",
+1 -1
View File
@@ -61,7 +61,7 @@ pub(crate) async fn authorization_server_metadata(services: &Services) -> Value
"authorization_endpoint": endpoint_base.join(AUTH_CODE_PATH).unwrap(),
"code_challenge_methods_supported": ["S256"],
"device_authorization_endpoint": endpoint_base.join(DEVICE_AUTHORIZATION_PATH).unwrap(),
"grant_types_supported": ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code", "client_credentials"],
"grant_types_supported": ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code"],
"issuer": services.config.get_client_domain(),
"jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(),
"prompt_values_supported": prompt_values_supported,
+1 -25
View File
@@ -47,7 +47,6 @@ pub(crate) enum ClientIdentity {
sender_device: Option<OwnedDeviceId>,
appservice_info: Box<RegistrationInfo>,
},
StaticClient,
}
impl ClientIdentity {
@@ -55,7 +54,6 @@ impl ClientIdentity {
match self {
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
Some(sender_user),
| Self::StaticClient => None,
}
}
@@ -63,8 +61,6 @@ impl ClientIdentity {
match self {
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
Ok(sender_user),
| Self::StaticClient =>
Err!(Request(Forbidden("Static clients cannot use this endpoint."))),
}
}
@@ -72,7 +68,6 @@ impl ClientIdentity {
match self {
| Self::User { sender_device, .. } => Some(sender_device),
| Self::Appservice { sender_device, .. } => sender_device.as_deref(),
| Self::StaticClient => None,
}
}
@@ -82,14 +77,12 @@ impl ClientIdentity {
| Self::Appservice { sender_device: Some(sender_device), .. } => Ok(sender_device),
| Self::Appservice { sender_device: None, .. } =>
Err!(Request(Forbidden("Appservices must masquerade to use this endpoint."))),
| Self::StaticClient =>
Err!(Request(Forbidden("Static clients cannot use this endpoint."))),
}
}
pub(crate) fn appservice_info(&self) -> Option<&RegistrationInfo> {
match self {
| Self::User { .. } | Self::StaticClient => None,
| Self::User { .. } => None,
| Self::Appservice { appservice_info, .. } => Some(appservice_info),
}
}
@@ -432,23 +425,6 @@ async fn check_access_token(
sender_device,
appservice_info: Box::new(appservice_info),
})
} else if let Some(session) = services.oauth.get_client_credentials_session(token) {
if !required_scopes
.iter()
.any(|scope| session.scopes.contains(scope))
{
return Err(Error::Request(
ErrorKind::InsufficientUserAuthentication(Box::new(
assign!(InsufficientUserAuthenticationErrorData::new(), {
scope: required_scopes.iter().cloned().collect()
}),
)),
"You do not have permission to access this endpoint.".into(),
StatusCode::UNAUTHORIZED,
));
}
Ok(ClientIdentity::StaticClient)
} else if services.users.is_previous_token(token).await {
// Return a soft-logout for previous tokens. This is necessary
// to make token refreshing idempotent.
-9
View File
@@ -346,15 +346,6 @@ pub fn check(config: &Config) -> Result {
}
})?;
for (id, client) in &config.oauth.clients {
if client.scopes.is_empty() {
warn!(
"The static OAuth client `{id}` has no scopes configured. It will not be able \
to access any API endpoints."
);
}
}
Ok(())
}
-54
View File
@@ -29,7 +29,6 @@ use ruma::{
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId,
RoomVersionId, ServerName,
api::{
OAuthClientScope,
client::{discovery::discover_support::ContactRole, rtc::RtcTransport},
federation::discovery::OldVerifyKey,
},
@@ -2751,12 +2750,7 @@ pub struct OauthConfig {
compatibility_mode: OAuthMode,
/// display: hidden
#[serde(default)]
pub oidc: Option<OidcConfig>,
/// display: hidden
#[serde(default)]
pub clients: HashMap<String, OAuthClient>,
}
impl OauthConfig {
@@ -2998,54 +2992,6 @@ impl<'de, K: Hash + Eq + Clone> Deserialize<'de> for PerMinuteRatelimiter<K> {
}
}
#[derive(Clone, Debug, Deserialize)]
#[config_example_generator(
filename = "conduwuit-example.toml",
section = "global.oauth.clients.\"$id\"",
optional = "true",
subheader = "\
# Use this section to add static OAuth clients for bots and automation.
# Clients added here may use the client credentials OAuth grant to authorize
# themselves with Continuwuity.
#
# Make sure to replace `$id` in the header with your client ID of choice! You can
# add more copies of this section with different IDs to add multiple clients.
#
# Because the client credentials grant authorizes the client as itself, without
# an attached user, clients that use it will not be able to access most of the Matrix
# client-server API. Administrative functionality that does not require a user
# will still be available."
)]
pub struct OAuthClient {
/// The client's client secret.
///
/// This must be supplied as the `client_secret` parameter when requesting
/// an access token with the OAuth 2.0 token endpoint. Continuwuity does
/// not check the `Authorization` header for requests to this endpoint.
pub client_secret: String,
/// A list of scopes that the client may request. Continuwuity allows static
/// clients to request the following scopes:
///
/// - "urn:matrix:client:cc.c10y.msc4484.server_administration" (MSC4484):
/// This scope grants access to the Matrix server administration APIs, as
/// well as Continuwuity's internal admin API (currently a work in
/// progress).
/// - "urn:matrix:client:api:*": This scope grants access to the Matrix
/// client-server API. Most endpoints require an authenticated Matrix user
/// and thus will not be usable by static clients.
///
/// The `urn:matrix:client:device:<id>` scope may not be requested by static
/// clients.
///
/// Scopes listed here are not granted by default. The client must
/// explicitly include them in the `scope` parameter of its access token
/// request.
///
/// default: []
pub scopes: BTreeSet<OAuthClientScope>,
}
const DEPRECATED_KEYS: &[&str] = &[
"allow_check_for_updates",
"allow_moderators_to_view_redacted_content",
-5
View File
@@ -55,7 +55,6 @@ default = [
standard = [
"brotli_compression",
"direct_tls",
"element_hacks",
"gzip_compression",
"io_uring",
"jemalloc_conf",
@@ -86,10 +85,6 @@ console = [
direct_tls = [
"conduwuit-router/direct_tls"
]
element_hacks = [
"conduwuit-service/element_hacks",
"conduwuit-router/element_hacks",
]
gzip_compression = [
"conduwuit-core/gzip_compression",
"conduwuit-router/gzip_compression",
-3
View File
@@ -27,9 +27,6 @@ direct_tls = [
"axum-server/tls-rustls-no-provider",
"dep:axum-server-dual-protocol",
]
element_hacks = [
"conduwuit-api/element_hacks",
]
gzip_compression = [
"conduwuit-admin/gzip_compression",
"conduwuit-api/gzip_compression",
-1
View File
@@ -30,7 +30,6 @@ console = [
"dep:rustyline-async",
"dep:termimad",
]
element_hacks = []
gzip_compression = [
"conduwuit-core/gzip_compression",
"reqwest/gzip",
-7
View File
@@ -125,12 +125,6 @@ impl ClientMetadata {
}
}
if self.grant_types.contains(&GrantType::ClientCredentials) {
return Err(
"Dynamically registered clients may not use the client credentials grant."
);
}
Ok(())
}
}
@@ -150,7 +144,6 @@ pub enum GrantType {
#[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
DeviceCode,
RefreshToken,
ClientCredentials,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]
+2 -8
View File
@@ -102,7 +102,7 @@ impl Display for RequestedScopes {
}
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RawScopes(String);
impl RawScopes {
@@ -257,11 +257,6 @@ pub enum TokenRequestType {
RefreshToken {
refresh_token: String,
},
ClientCredentials {
client_secret: String,
#[serde(default)]
scope: RawScopes,
},
}
impl TokenRequestType {
@@ -271,7 +266,6 @@ impl TokenRequestType {
| Self::AuthorizationCode { .. } => GrantType::AuthorizationCode,
| Self::DeviceCode { .. } => GrantType::DeviceCode,
| Self::RefreshToken { .. } => GrantType::RefreshToken,
| Self::ClientCredentials { .. } => GrantType::ClientCredentials,
}
}
}
@@ -281,7 +275,7 @@ pub struct TokenResponse {
pub access_token: String,
pub token_type: TokenType,
pub expires_in: u64,
pub refresh_token: Option<String>,
pub refresh_token: String,
pub scope: String,
}
+12 -119
View File
@@ -7,10 +7,10 @@ use std::{
use base64::Engine;
use conduwuit::{
Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard,
Result, SyncMutex,
config::experiments::ToggledExperiment,
error, info,
utils::{self, MutexMap, hash::sha256, string::constant_time_eq},
utils::{self, MutexMap, hash::sha256},
warn,
};
use database::{Deserialized, Json, Map};
@@ -27,9 +27,8 @@ use crate::{
client_metadata::{ApplicationType, ClientMetadata, GrantType, ResponseType},
grant::{
AuthorizationCodeQuery, AuthorizationCodeResponse, CodeChallengeMethod,
DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RawScopes,
RequestedScopes, ResponseMode, TokenRequest, TokenRequestType, TokenResponse,
TokenType,
DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RequestedScopes,
ResponseMode, TokenRequest, TokenRequestType, TokenResponse, TokenType,
},
},
users::{self, DeviceToken, PreviousTokenAction},
@@ -54,7 +53,6 @@ pub struct Service {
tickets: SyncMutex<HashMap<String, HashMap<OAuthTicket, SystemTime>>>,
pending_auth_code_grants: SyncMutex<LruCache<String, PendingAuthCodeGrant>>,
pending_device_code_grants: SyncMutex<LruCache<String, PendingDeviceCodeGrant>>,
client_credential_sessions: SyncMutex<HashMap<String, ClientCredentialsSession>>,
}
struct Data {
@@ -108,12 +106,6 @@ struct RefreshTokenInfo {
device_id: OwnedDeviceId,
}
pub struct ClientCredentialsSession {
pub client_id: String,
pub scopes: BTreeSet<OAuthClientScope>,
created_at: SystemTime,
}
struct PendingAuthCodeGrant {
authorizing_user: OwnedUserId,
requested_scopes: RequestedScopes,
@@ -209,7 +201,6 @@ impl crate::Service for Service {
tickets: SyncMutex::default(),
pending_auth_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)),
pending_device_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)),
client_credential_sessions: SyncMutex::default(),
}))
}
@@ -506,25 +497,12 @@ impl Service {
pub async fn issue_token(&self, request: TokenRequest) -> Result<TokenResponse, OAuthError> {
let TokenRequest { client_id, request } = request;
if !matches!(request, TokenRequestType::ClientCredentials { .. }) {
// The client credentials grant can only be used by statically
// registered clients, and the other grant types can
// only be used by dynamically registered clients, so we
// don't look up the dynamic client metadata if the token request is
// for the client credentials grant.
let Some(client_metadata) = self.get_client_metadata(&client_id).await else {
return Err(OAuthError::new_static(ErrorCode::InvalidClient, "Invalid client ID"));
};
let Some(client_metadata) = self.get_client_metadata(&client_id).await else {
return Err(OAuthError::new_static(
ErrorCode::InvalidClient,
"Invalid client ID",
));
};
if !client_metadata.grant_types.contains(&request.grant_type()) {
return Err(OAuthError::unauthorized_client(
"Client cannot request this grant type",
));
}
if !client_metadata.grant_types.contains(&request.grant_type()) {
return Err(OAuthError::unauthorized_client("Client cannot request this grant type"));
}
match request {
@@ -596,8 +574,6 @@ impl Service {
},
| TokenRequestType::RefreshToken { refresh_token } =>
self.refresh_session(client_id, refresh_token).await,
| TokenRequestType::ClientCredentials { client_secret, scope: scopes } =>
self.create_client_credentials_token(&client_id, &client_secret, &scopes),
}
}
@@ -614,12 +590,8 @@ impl Service {
self.services.users.find_from_token(&token).await
{
(user_id, device_id)
} else if self.get_client_credentials_session(&token).is_some() {
return Err(OAuthError::invalid_grant(
"Access tokens for static clients cannot be revoked.",
));
} else {
return Err(OAuthError::invalid_grant("Invalid access or refresh token."));
return Err(OAuthError::invalid_grant("Invalid access or refersh token"));
};
// This will also call [`Self::remove_session`]
@@ -756,7 +728,7 @@ impl Service {
token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope: response_scope,
refresh_token: Some(refresh_token),
refresh_token,
})
}
@@ -883,89 +855,10 @@ impl Service {
token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope,
refresh_token: Some(new_refresh_token),
refresh_token: new_refresh_token,
})
}
fn create_client_credentials_token(
&self,
client_id: &str,
client_secret: &str,
scopes: &RawScopes,
) -> Result<TokenResponse, OAuthError> {
let now = SystemTime::now();
let Some(client) = self.services.config.oauth.clients.get(client_id) else {
return Err(OAuthError::new_static(ErrorCode::InvalidClient, "Unknown client ID"));
};
let RequestedScopes { device_id, scopes } = scopes
.to_scopes()
.map_err(|err| OAuthError::new(ErrorCode::InvalidGrant, err))?;
if device_id.is_some() {
return Err(OAuthError::new_static(
ErrorCode::InvalidGrant,
"Static clients may not request a device ID",
));
}
if !constant_time_eq(client_secret, &client.client_secret) {
return Err(OAuthError::new_static(
ErrorCode::InvalidClient,
"Client secret does not match",
));
}
if !scopes.is_subset(&client.scopes) {
return Err(OAuthError::new_static(
ErrorCode::InvalidScope,
"This client may not request those scopes",
));
}
let mut sessions = self.client_credential_sessions.lock();
// Clear expired sessions while we're at it
sessions.retain(|_, session| {
now.duration_since(session.created_at)
.is_ok_and(|age| age <= Self::ACCESS_TOKEN_MAX_AGE)
});
let access_token = Self::generate_token();
let scope = scopes.iter().join(" ");
sessions.insert(access_token.clone(), ClientCredentialsSession {
client_id: client_id.to_owned(),
scopes,
created_at: now,
});
Ok(TokenResponse {
access_token,
token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
refresh_token: None,
scope,
})
}
pub fn get_client_credentials_session(
&self,
token: &str,
) -> Option<SyncMappedMutexGuard<'_, ClientCredentialsSession>> {
let sessions = self.client_credential_sessions.lock();
SyncMutexGuard::try_map(sessions, |sessions| {
sessions.get_mut(token).filter(|session| {
SystemTime::now()
.duration_since(session.created_at)
.is_ok_and(|age| age <= Self::ACCESS_TOKEN_MAX_AGE)
})
})
.ok()
}
pub async fn remove_session(&self, user_id: &UserId, device_id: &DeviceId) {
let _lock = self.session_mutex.lock(&(user_id, device_id)).await;
let session_info = self.get_session_info_for_device(user_id, device_id).await;
+1 -2
View File
@@ -75,8 +75,7 @@ impl Service {
"lazy loading should be enabled by your options"
);
let include_redundant = cfg!(feature = "element_hacks")
|| ctx.options.is_some_and(Options::include_redundant_members);
let include_redundant = ctx.options.is_some_and(Options::include_redundant_members);
let witness = self
.witness(ctx, senders.iter().map(AsRef::as_ref))