mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-11-23 17:07:32 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c07e7ae32 | ||
|
|
4a4c25843b | ||
|
|
9a3ed04eb6 |
No files matched your search
@@ -0,0 +1 @@
|
||||
Network issues while refreshing an access token will no longer cause OAuth-compatible clients to be forcibly logged out. Contributed by @ginger.
|
||||
@@ -1 +0,0 @@
|
||||
Continuwuity will now request the `profile` OIDC scope from identity providers by default to improve compatibility with identity providers that require it to access users' profile claims, as recommended by the OIDC specification. Contributed by @ginger.
|
||||
@@ -1 +0,0 @@
|
||||
Attempting to start a UIAA session on a homeserver with UIAA disabled will now return `403 M_UNAUTHORIZED` instead of `404 M_UNSUPPORTED`. Contributed by @ginger.
|
||||
@@ -2582,12 +2582,10 @@
|
||||
|
||||
# Additional scopes Continuwuity should request from the IDP. This may be
|
||||
# necessary to access certain claims. Continuwuity always requests the
|
||||
# `openid` scope, regardless of the contents of this option,
|
||||
# and will also request the `profile` scope by default if this option is
|
||||
# not set.
|
||||
# `openid` scope.
|
||||
#
|
||||
# env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_SCOPES
|
||||
#additional_scopes = ["profile"]
|
||||
#additional_scopes = []
|
||||
|
||||
# Additional trusted audiences that Continuwuity will accept in the `aud`
|
||||
# claim of the OIDC token returned by the IDP. If your identity
|
||||
|
||||
+22
-6
@@ -319,6 +319,19 @@ async fn check_access_token(
|
||||
));
|
||||
}
|
||||
|
||||
let session_info = services
|
||||
.oauth
|
||||
.get_session_info_for_device(&sender_user, &sender_device)
|
||||
.await;
|
||||
|
||||
if let Some(session_info) = &session_info {
|
||||
services.oauth.clear_previous_refresh_token(
|
||||
&sender_user,
|
||||
&sender_device,
|
||||
session_info,
|
||||
);
|
||||
}
|
||||
|
||||
// Locked users can only use /logout and /logout/all
|
||||
if services
|
||||
.users
|
||||
@@ -333,12 +346,6 @@ async fn check_access_token(
|
||||
}
|
||||
}
|
||||
|
||||
let session_info = services
|
||||
.oauth
|
||||
.get_session_info_for_device(&sender_user, &sender_device)
|
||||
.await
|
||||
.map(Box::new);
|
||||
|
||||
// Make sure the user has the right scopes to use the route
|
||||
let mut user_scopes = if let Some(session_info) = &session_info {
|
||||
session_info.scopes()
|
||||
@@ -416,6 +423,15 @@ async fn check_access_token(
|
||||
sender_device,
|
||||
appservice_info: Box::new(appservice_info),
|
||||
})
|
||||
} else if services.users.is_previous_token(token).await {
|
||||
// Return a soft-logout for previous tokens. This is necessary
|
||||
// to make token refreshing idempotent.
|
||||
|
||||
Err(Error::Request(
|
||||
ErrorKind::UnknownToken(assign!(UnknownTokenErrorData::new(), { soft_logout: true })),
|
||||
"This token has expired".into(),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
))
|
||||
} else {
|
||||
Err(Error::Request(
|
||||
ErrorKind::UnknownToken(UnknownTokenErrorData::new()),
|
||||
|
||||
@@ -2823,12 +2823,10 @@ pub struct OidcConfig {
|
||||
|
||||
/// Additional scopes Continuwuity should request from the IDP. This may be
|
||||
/// necessary to access certain claims. Continuwuity always requests the
|
||||
/// `openid` scope, regardless of the contents of this option,
|
||||
/// and will also request the `profile` scope by default if this option is
|
||||
/// not set.
|
||||
/// `openid` scope.
|
||||
///
|
||||
/// default: ["profile"]
|
||||
#[serde(default = "default_additional_scopes")]
|
||||
/// default: []
|
||||
#[serde(default)]
|
||||
pub additional_scopes: Vec<Scope>,
|
||||
|
||||
/// Additional trusted audiences that Continuwuity will accept in the `aud`
|
||||
@@ -3448,8 +3446,6 @@ fn default_unauthenticated_request_ratelimit<K: Hash + Eq + Clone>() -> PerMinut
|
||||
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
|
||||
}
|
||||
|
||||
fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] }
|
||||
|
||||
// NOTE: This must be declared *after* every config struct in this file. The
|
||||
// example config generator writes sections in macro expansion order, and the
|
||||
// `global` section truncates the file, so declaring this module any earlier
|
||||
|
||||
@@ -407,6 +407,10 @@ pub(super) static MAPS: &[Descriptor] = &[
|
||||
name: "userdeviceid_token",
|
||||
..descriptor::RANDOM_SMALL
|
||||
},
|
||||
Descriptor {
|
||||
name: "userdeviceid_previoustoken",
|
||||
..descriptor::RANDOM_SMALL
|
||||
},
|
||||
Descriptor {
|
||||
name: "userdevicesessionid_uiaainfo",
|
||||
..descriptor::RANDOM_SMALL
|
||||
|
||||
+77
-10
@@ -1,5 +1,6 @@
|
||||
use std::{
|
||||
collections::{BTreeSet, HashMap},
|
||||
fmt::Write,
|
||||
sync::Arc,
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
@@ -55,7 +56,7 @@ struct Services {
|
||||
config: Dep<config::Service>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct SessionInfo {
|
||||
pub client_id: String,
|
||||
#[serde(deserialize_with = "client_metadata::btreeset_skip_err")]
|
||||
@@ -64,6 +65,8 @@ pub struct SessionInfo {
|
||||
temporary_scopes: BTreeSet<OAuthClientScope>,
|
||||
#[serde(default)]
|
||||
current_refresh_token: String,
|
||||
#[serde(default)]
|
||||
previous_refresh_token: Option<String>,
|
||||
}
|
||||
|
||||
impl SessionInfo {
|
||||
@@ -71,6 +74,15 @@ impl SessionInfo {
|
||||
pub fn scopes(&self) -> BTreeSet<OAuthClientScope> {
|
||||
self.scopes.union(&self.temporary_scopes).cloned().collect()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn scope_string(&self, device_id: &DeviceId) -> String {
|
||||
let mut scopes = self.scopes().iter().join(" ");
|
||||
|
||||
let _ = write!(scopes, " urn:matrix:client:device:{device_id}");
|
||||
|
||||
scopes
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
@@ -246,6 +258,24 @@ impl Service {
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Clear a session's previous refresh token, if it has one.
|
||||
pub fn clear_previous_refresh_token(
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
device_id: &DeviceId,
|
||||
session_info: &SessionInfo,
|
||||
) {
|
||||
if session_info.previous_refresh_token.is_some() {
|
||||
let mut session_info = session_info.clone();
|
||||
|
||||
session_info.previous_refresh_token = None;
|
||||
|
||||
self.db
|
||||
.userdeviceid_oauthsessioninfo
|
||||
.put((user_id, device_id), Json(session_info));
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn request_authorization_code(
|
||||
&self,
|
||||
authorizing_user: OwnedUserId,
|
||||
@@ -645,6 +675,7 @@ impl Service {
|
||||
SessionInfo {
|
||||
client_id: client_id.clone(),
|
||||
current_refresh_token: Self::generate_token(),
|
||||
previous_refresh_token: None,
|
||||
scopes: requested_scopes.scopes,
|
||||
temporary_scopes: BTreeSet::new(),
|
||||
}
|
||||
@@ -702,15 +733,53 @@ impl Service {
|
||||
|
||||
assert_eq!(&client_id, &session_info.client_id, "session info client id mismatch");
|
||||
|
||||
// TODO: this doesn't include the device ID "scope", do any clients rely
|
||||
// on that?
|
||||
let scope = session_info.scopes.iter().join(" ");
|
||||
let new_refresh_token = Self::generate_token();
|
||||
|
||||
if refresh_token == session_info.current_refresh_token {
|
||||
// The client is refreshing with their current refresh token.
|
||||
// We need to generate a new refresh token and save this token as
|
||||
// the previous one.
|
||||
|
||||
session_info
|
||||
.current_refresh_token
|
||||
.clone_from(&new_refresh_token);
|
||||
|
||||
// Remove the old previous token if it's set. This can only happen
|
||||
// if the client decides to refresh twice in a row without using its
|
||||
// new access token, since we'll also do this when the new access
|
||||
// token is used for the first time.
|
||||
if let Some(previous_refresh_token) = session_info.previous_refresh_token {
|
||||
self.db
|
||||
.refreshtoken_refreshtokeninfo
|
||||
.remove(&previous_refresh_token);
|
||||
}
|
||||
|
||||
session_info.previous_refresh_token = Some(refresh_token);
|
||||
} else if Some(&refresh_token) == session_info.previous_refresh_token.as_ref() {
|
||||
// The client is refreshing with their previous refresh token,
|
||||
// probably because they didn't get the new one we made for them. We
|
||||
// need to make a second new one, but we don't touch the existing
|
||||
// previous one in case they don't get the second new one either.
|
||||
|
||||
// Wipe the current token, we're going to make a new one.
|
||||
self.db
|
||||
.refreshtoken_refreshtokeninfo
|
||||
.remove(&session_info.current_refresh_token);
|
||||
|
||||
session_info
|
||||
.current_refresh_token
|
||||
.clone_from(&new_refresh_token);
|
||||
} else {
|
||||
// The client is trying to use a refresh token that isn't their
|
||||
// current or previous one, but still has information in the
|
||||
// database. This is definitely not a legal state, so we need to
|
||||
// bail out.
|
||||
panic!("refresh token is not current or previous for its session");
|
||||
}
|
||||
|
||||
let scope = session_info.scope_string(&refresh_token_info.device_id);
|
||||
|
||||
let new_access_token = DeviceToken::new_random().with_max_age(Self::ACCESS_TOKEN_MAX_AGE);
|
||||
let new_refresh_token = Self::generate_token();
|
||||
session_info
|
||||
.current_refresh_token
|
||||
.clone_from(&new_refresh_token);
|
||||
|
||||
self.services
|
||||
.users
|
||||
@@ -729,8 +798,6 @@ impl Service {
|
||||
Json(session_info),
|
||||
);
|
||||
|
||||
self.db.refreshtoken_refreshtokeninfo.remove(&refresh_token);
|
||||
drop(refresh_token);
|
||||
self.db
|
||||
.refreshtoken_refreshtokeninfo
|
||||
.raw_put(&new_refresh_token, Json(refresh_token_info));
|
||||
|
||||
@@ -348,8 +348,8 @@ impl Service {
|
||||
.compatibility_mode()
|
||||
.uiaa_available()
|
||||
{
|
||||
return Err!(Request(Forbidden(
|
||||
"User-interactive authentication is not available on this server."
|
||||
return Err!(Request(Unrecognized(
|
||||
"User-interactive authentication is unavailable on this server"
|
||||
)));
|
||||
}
|
||||
|
||||
|
||||
@@ -632,6 +632,12 @@ impl super::Service {
|
||||
}
|
||||
}
|
||||
|
||||
// Discard this device's previous token entry if the current token
|
||||
// isn't expired.
|
||||
self.db
|
||||
.userdeviceid_previoustoken
|
||||
.del((&user_id, &device_id));
|
||||
|
||||
Some((user_id, device_id, AccessTokenStatus::Valid))
|
||||
}
|
||||
|
||||
|
||||
@@ -184,8 +184,13 @@ impl super::Service {
|
||||
// Remove old token
|
||||
if let Ok(old_token) = self.db.userdeviceid_token.qry(&key).await {
|
||||
self.db.token_userdeviceid.remove(&old_token);
|
||||
self.db.userdeviceid_tokenexpires.remove(&old_token);
|
||||
// It will be removed from userdeviceid_token by the insert later
|
||||
|
||||
// Save the previous token only if we don't already have one saved
|
||||
// for this device.
|
||||
if !self.db.userdeviceid_previoustoken.contains(&key).await {
|
||||
self.db.userdeviceid_previoustoken.put_raw(key, &old_token);
|
||||
}
|
||||
}
|
||||
|
||||
// Assign token to user device combination
|
||||
@@ -207,6 +212,17 @@ impl super::Service {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns whether the provided token was previously used by a device
|
||||
/// before a token refresh, and therefore should cause a soft-logout.
|
||||
pub async fn is_previous_token(&self, token: &str) -> bool {
|
||||
self.db
|
||||
.userdeviceid_previoustoken
|
||||
.stream::<Ignore, String>()
|
||||
.ignore_err()
|
||||
.ready_any(|(_, previous_token)| previous_token == token)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Pushes a new to-device event into a device's inbox.
|
||||
pub async fn add_to_device_event(
|
||||
&self,
|
||||
|
||||
@@ -83,6 +83,7 @@ struct Data {
|
||||
userdeviceid_tokenexpires: Arc<Map>,
|
||||
userdeviceid_metadata: Arc<Map>,
|
||||
userdeviceid_token: Arc<Map>,
|
||||
userdeviceid_previoustoken: Arc<Map>,
|
||||
userfilterid_filter: Arc<Map>,
|
||||
userid_avatarurl: Arc<Map>,
|
||||
userid_deactivated: Arc<Map>,
|
||||
@@ -134,6 +135,7 @@ impl crate::Service for Service {
|
||||
remoteuserid_remoteuser: args.db["remoteuserid_remoteuser"].clone(),
|
||||
userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
|
||||
userdeviceid_token: args.db["userdeviceid_token"].clone(),
|
||||
userdeviceid_previoustoken: args.db["userdeviceid_previoustoken"].clone(),
|
||||
userfilterid_filter: args.db["userfilterid_filter"].clone(),
|
||||
userid_avatarurl: args.db["userid_avatarurl"].clone(),
|
||||
userid_deactivated: args.db["userid_deactivated"].clone(),
|
||||
|
||||
Reference in new issue
Block a user