mirror of
https://forgejo.ellis.link/continuwuation/continuwuity/
synced 2026-07-13 07:59:04 +00:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6ad3e679bc | |||
| 65812bb246 | |||
| 9f3a7994c7 | |||
| baef3289fe |
@@ -1,3 +1,12 @@
|
||||
# Continuwuity 26.6.2 (2026-07-12)
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Fixed the server returning 500 errors if `admin_console_automatic` is enabled and no TTY is available. Contributed by @s1lv3r. (#1975)
|
||||
- Fixed `global.oauth.compatibility_mode` being required, despite being ignored, when the `[global.oauth.oidc]` config section is provided.
|
||||
- Fixed an issue with a migration that could cause user accounts imported from an identity provider to be marked as deactivated when the server started. If you have accounts affected by this issue, use `!admin users reset-password --convert-to-local-account` to reactivate them.
|
||||
|
||||
|
||||
# Continuwuity 26.6.1 (2026-07-12)
|
||||
|
||||
## Features
|
||||
|
||||
Generated
+12
-12
@@ -826,7 +826,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"clap",
|
||||
@@ -864,7 +864,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_admin"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"assign",
|
||||
"clap",
|
||||
@@ -890,7 +890,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_api"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"assign",
|
||||
"async-trait",
|
||||
@@ -928,7 +928,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_build_metadata"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"built",
|
||||
"cargo_metadata",
|
||||
@@ -936,7 +936,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_core"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"arrayvec",
|
||||
@@ -1004,7 +1004,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_database"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"conduwuit_core",
|
||||
@@ -1025,7 +1025,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_macros"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"cargo_toml",
|
||||
"itertools 0.15.0",
|
||||
@@ -1036,7 +1036,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_router"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"assign",
|
||||
"axum",
|
||||
@@ -1074,7 +1074,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_service"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"askama",
|
||||
"assign",
|
||||
@@ -1126,7 +1126,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_web"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"askama",
|
||||
"assign",
|
||||
@@ -4799,7 +4799,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruminuwuity"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"assign",
|
||||
"ruma",
|
||||
@@ -6972,7 +6972,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
dependencies = [
|
||||
"askama",
|
||||
"cargo_metadata",
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ license = "Apache-2.0"
|
||||
# See also `rust-toolchain.toml`
|
||||
readme = "README.md"
|
||||
repository = "https://forgejo.ellis.link/continuwuation/continuwuity"
|
||||
version = "26.6.1"
|
||||
version = "26.6.2"
|
||||
|
||||
[workspace.metadata.crane]
|
||||
name = "conduwuit"
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
Added support for the OAuth2 device authorization flow. Contributed by @ginger
|
||||
@@ -1 +0,0 @@
|
||||
Fixed `global.oauth.compatibility_mode` being required, despite being ignored, when the `[global.oauth.oidc]` config section is provided.
|
||||
@@ -1 +0,0 @@
|
||||
Fixed an issue with a migration that could cause user accounts imported from an identity provider to be marked as deactivated when the server started. If you have accounts affected by this issue, use `!admin users reset-password --convert-to-local-account` to reactivate them.
|
||||
@@ -1,13 +0,0 @@
|
||||
use axum::{Form, Json, extract::State, response::IntoResponse};
|
||||
use http::StatusCode;
|
||||
use service::oauth::grant::DeviceCodeRequest;
|
||||
|
||||
pub(crate) async fn device_authorization_route(
|
||||
State(services): State<crate::State>,
|
||||
Form(request): Form<DeviceCodeRequest>,
|
||||
) -> impl IntoResponse {
|
||||
match services.oauth.request_device_code(request).await {
|
||||
| Ok(response) => Ok(Json(response)),
|
||||
| Err(err) => Err((StatusCode::BAD_REQUEST, Json(err))),
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@
|
||||
use serde_json::json;
|
||||
pub(crate) use server_metadata::*;
|
||||
|
||||
mod device;
|
||||
mod register_client;
|
||||
mod server_metadata;
|
||||
mod token;
|
||||
@@ -21,7 +20,6 @@
|
||||
const CLIENT_REGISTER_PATH: &str = "client/register";
|
||||
const TOKEN_REVOKE_PATH: &str = "client/revoke";
|
||||
const TOKEN_PATH: &str = "grant/token";
|
||||
const DEVICE_AUTHORIZATION_PATH: &str = "device";
|
||||
const ACCOUNT_MANAGEMENT_PATH: &str = concat!(conduwuit_core::ROUTE_PREFIX, "/account/deeplink");
|
||||
|
||||
pub(crate) fn router(state: crate::State) -> Router<crate::State> {
|
||||
@@ -55,5 +53,4 @@ fn oauth_router() -> Router<crate::State> {
|
||||
.route(concat!("/", JWKS_URI_PATH), get(async || Json(json!({"keys": []}))))
|
||||
.route(concat!("/", TOKEN_PATH), post(token::token_route))
|
||||
.route(concat!("/", TOKEN_REVOKE_PATH), post(token::revoke_token_route))
|
||||
.route(concat!("/", DEVICE_AUTHORIZATION_PATH), post(device::device_authorization_route))
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
use crate::{
|
||||
Ruma,
|
||||
client::oauth::{
|
||||
ACCOUNT_MANAGEMENT_PATH, AUTH_CODE_PATH, CLIENT_REGISTER_PATH, DEVICE_AUTHORIZATION_PATH,
|
||||
JWKS_URI_PATH, TOKEN_PATH, TOKEN_REVOKE_PATH,
|
||||
ACCOUNT_MANAGEMENT_PATH, AUTH_CODE_PATH, CLIENT_REGISTER_PATH, JWKS_URI_PATH, TOKEN_PATH,
|
||||
TOKEN_REVOKE_PATH,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -49,8 +49,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"],
|
||||
"grant_types_supported": ["authorization_code", "refresh_token"],
|
||||
"issuer": services.config.get_client_domain(),
|
||||
"jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(),
|
||||
"prompt_values_supported": ["create"],
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use conduwuit::{Err, Result, debug, debug_info, error, info};
|
||||
use std::io::IsTerminal;
|
||||
|
||||
use conduwuit::{Err, Result, debug, debug_info, error, info, warn};
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
use tokio::time::{Duration, sleep};
|
||||
|
||||
@@ -7,10 +9,16 @@
|
||||
pub(super) const SIGNAL: &str = "SIGUSR2";
|
||||
|
||||
impl super::Service {
|
||||
/// Possibly spawn the terminal console at startup if configured.
|
||||
/// Possibly spawn the terminal console at startup if configured and a TTY
|
||||
/// is available.
|
||||
pub(super) async fn console_auto_start(&self) {
|
||||
#[cfg(feature = "console")]
|
||||
if self.services.server.config.admin_console_automatic {
|
||||
if !std::io::stdin().is_terminal() {
|
||||
warn!("Console enabled without a tty available; Not enabling console");
|
||||
return;
|
||||
}
|
||||
|
||||
// Allow more of the startup sequence to execute before spawning
|
||||
tokio::task::yield_now().await;
|
||||
self.console.start().await;
|
||||
|
||||
@@ -132,8 +132,6 @@ pub enum ApplicationType {
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum GrantType {
|
||||
AuthorizationCode,
|
||||
#[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
|
||||
DeviceCode,
|
||||
RefreshToken,
|
||||
}
|
||||
|
||||
|
||||
+17
-61
@@ -13,7 +13,6 @@
|
||||
use url::Url;
|
||||
|
||||
use super::client_metadata::ResponseType;
|
||||
use crate::oauth::client_metadata::GrantType;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct AuthorizationCodeQuery {
|
||||
@@ -30,33 +29,6 @@ pub struct AuthorizationCodeQuery {
|
||||
pub prompt: Option<Prompt>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct AuthorizationCodeResponse {
|
||||
pub state: String,
|
||||
pub code: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct DeviceCodeRequest {
|
||||
pub client_id: String,
|
||||
pub scope: RawScopes,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct DeviceCodeResponse {
|
||||
pub device_code: String,
|
||||
pub user_code: String,
|
||||
pub verification_uri: Url,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub verification_uri_complete: Option<Url>,
|
||||
pub expires_in: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct DeviceCodeVerifyQuery {
|
||||
pub user_code: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[non_exhaustive]
|
||||
@@ -154,29 +126,19 @@ pub struct OAuthError {
|
||||
|
||||
impl OAuthError {
|
||||
#[must_use]
|
||||
pub fn new(error: ErrorCode, error_description: String) -> Self {
|
||||
pub const fn invalid_request(error_description: &'static str) -> Self {
|
||||
Self {
|
||||
error,
|
||||
error_description: Cow::Owned(error_description),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn new_static(error: ErrorCode, error_description: &'static str) -> Self {
|
||||
Self {
|
||||
error,
|
||||
error: ErrorCode::InvalidRequest,
|
||||
error_description: Cow::Borrowed(error_description),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn invalid_request(error_description: &'static str) -> Self {
|
||||
Self::new_static(ErrorCode::InvalidRequest, error_description)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn invalid_grant(error_description: &'static str) -> Self {
|
||||
Self::new_static(ErrorCode::InvalidGrant, error_description)
|
||||
Self {
|
||||
error: ErrorCode::InvalidGrant,
|
||||
error_description: Cow::Borrowed(error_description),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,41 +158,35 @@ pub enum ErrorCode {
|
||||
InvalidScope,
|
||||
InvalidGrant,
|
||||
InvalidClientMetadata,
|
||||
AuthorizationPending,
|
||||
ExpiredToken,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TokenRequest {
|
||||
pub client_id: String,
|
||||
#[serde(flatten)]
|
||||
pub request: TokenRequestType,
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct AuthorizationCodeResponse {
|
||||
pub state: String,
|
||||
pub code: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "grant_type", rename_all = "snake_case")]
|
||||
pub enum TokenRequestType {
|
||||
pub enum TokenRequest {
|
||||
AuthorizationCode {
|
||||
code: String,
|
||||
redirect_uri: Url,
|
||||
client_id: String,
|
||||
code_verifier: String,
|
||||
},
|
||||
#[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
|
||||
DeviceCode {
|
||||
device_code: String,
|
||||
},
|
||||
RefreshToken {
|
||||
client_id: String,
|
||||
refresh_token: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl TokenRequestType {
|
||||
impl TokenRequest {
|
||||
#[must_use]
|
||||
pub fn grant_type(&self) -> GrantType {
|
||||
pub fn client_id(&self) -> &str {
|
||||
match self {
|
||||
| Self::AuthorizationCode { .. } => GrantType::AuthorizationCode,
|
||||
| Self::DeviceCode { .. } => GrantType::DeviceCode,
|
||||
| Self::RefreshToken { .. } => GrantType::RefreshToken,
|
||||
| Self::AuthorizationCode { client_id, .. }
|
||||
| Self::RefreshToken { client_id, .. } => client_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+30
-226
@@ -12,19 +12,17 @@
|
||||
use database::{Deserialized, Json, Map};
|
||||
use itertools::Itertools;
|
||||
use lru_cache::LruCache;
|
||||
use rand::distr::{Distribution, slice::Choose};
|
||||
use ruma::{DeviceId, OwnedDeviceId, OwnedUserId, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
Dep, config,
|
||||
Dep,
|
||||
oauth::{
|
||||
client_metadata::{ApplicationType, ClientMetadata, ResponseType},
|
||||
grant::{
|
||||
AuthorizationCodeQuery, AuthorizationCodeResponse, CodeChallengeMethod,
|
||||
DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, ResponseMode, Scope,
|
||||
TokenRequest, TokenRequestType, TokenResponse, TokenType,
|
||||
AuthorizationCodeQuery, AuthorizationCodeResponse, CodeChallengeMethod, ErrorCode,
|
||||
OAuthError, ResponseMode, Scope, TokenRequest, TokenResponse, TokenType,
|
||||
},
|
||||
},
|
||||
users,
|
||||
@@ -37,8 +35,7 @@ pub struct Service {
|
||||
services: Services,
|
||||
db: Data,
|
||||
tickets: Mutex<HashMap<String, HashMap<OAuthTicket, SystemTime>>>,
|
||||
pending_auth_code_grants: tokio::sync::Mutex<LruCache<String, PendingAuthCodeGrant>>,
|
||||
pending_device_code_grants: tokio::sync::Mutex<LruCache<String, PendingDeviceCodeGrant>>,
|
||||
pending_code_grants: tokio::sync::Mutex<LruCache<String, PendingCodeGrant>>,
|
||||
}
|
||||
|
||||
struct Data {
|
||||
@@ -49,7 +46,6 @@ struct Data {
|
||||
|
||||
struct Services {
|
||||
users: Dep<users::Service>,
|
||||
config: Dep<config::Service>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
@@ -66,7 +62,7 @@ struct RefreshTokenInfo {
|
||||
device_id: OwnedDeviceId,
|
||||
}
|
||||
|
||||
struct PendingAuthCodeGrant {
|
||||
struct PendingCodeGrant {
|
||||
authorizing_user: OwnedUserId,
|
||||
requested_scopes: BTreeSet<Scope>,
|
||||
client_name: Option<String>,
|
||||
@@ -76,8 +72,12 @@ struct PendingAuthCodeGrant {
|
||||
requested_at: SystemTime,
|
||||
}
|
||||
|
||||
impl PendingAuthCodeGrant {
|
||||
impl PendingCodeGrant {
|
||||
const MAX_AGE: Duration = Duration::from_mins(1);
|
||||
const RANDOM_CODE_LENGTH: usize = 32;
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn generate_code() -> String { utils::random_string(Self::RANDOM_CODE_LENGTH) }
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn is_valid_for(&self, client_id: &str) -> bool {
|
||||
@@ -90,43 +90,6 @@ pub(crate) fn is_valid_for(&self, client_id: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingDeviceCodeGrant {
|
||||
state: DeviceCodeGrantState,
|
||||
requested_scopes: BTreeSet<Scope>,
|
||||
client_name: Option<String>,
|
||||
client_id: String,
|
||||
requested_at: SystemTime,
|
||||
}
|
||||
|
||||
enum DeviceCodeGrantState {
|
||||
Unverified {
|
||||
user_code: String,
|
||||
},
|
||||
Verified {
|
||||
authorizing_user: OwnedUserId,
|
||||
},
|
||||
}
|
||||
|
||||
impl PendingDeviceCodeGrant {
|
||||
const MAX_AGE: Duration = Duration::from_mins(1);
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn is_valid_for(&self, client_id: &str) -> bool {
|
||||
let now = SystemTime::now();
|
||||
|
||||
self.client_id == client_id
|
||||
&& now
|
||||
.duration_since(self.requested_at)
|
||||
.is_ok_and(|age| age < Self::MAX_AGE)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DeviceCodeGrantInfo {
|
||||
pub device_code: String,
|
||||
pub client_metadata: ClientMetadata,
|
||||
pub requested_scopes: BTreeSet<Scope>,
|
||||
}
|
||||
|
||||
/// A time-limited grant for a client to perform some sensitive action.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum OAuthTicket {
|
||||
@@ -149,7 +112,6 @@ fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||
Ok(Arc::new(Self {
|
||||
services: Services {
|
||||
users: args.depend::<users::Service>("users"),
|
||||
config: args.depend::<config::Service>("config"),
|
||||
},
|
||||
db: Data {
|
||||
clientid_clientmetadata: args.db["clientid_clientmetadata"].clone(),
|
||||
@@ -157,11 +119,8 @@ fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||
refreshtoken_refreshtokeninfo: args.db["refreshtoken_refreshtokeninfo"].clone(),
|
||||
},
|
||||
tickets: Mutex::default(),
|
||||
pending_auth_code_grants: tokio::sync::Mutex::new(LruCache::new(
|
||||
Self::MAX_PENDING_GRANTS,
|
||||
)),
|
||||
pending_device_code_grants: tokio::sync::Mutex::new(LruCache::new(
|
||||
Self::MAX_PENDING_GRANTS,
|
||||
pending_code_grants: tokio::sync::Mutex::new(LruCache::new(
|
||||
Self::MAX_PENDING_CODE_GRANTS,
|
||||
)),
|
||||
}))
|
||||
}
|
||||
@@ -174,21 +133,11 @@ impl Service {
|
||||
// Maximum number of pending code grants which will be held in memory at once,
|
||||
// to prevent unbounded memory use if someone decides to repeatedly reload the
|
||||
// grant page.
|
||||
const MAX_PENDING_GRANTS: usize = 100;
|
||||
const MAX_PENDING_CODE_GRANTS: usize = 100;
|
||||
const RANDOM_TOKEN_LENGTH: usize = 32;
|
||||
const USER_CODE_CHARACTERS: &[char] = &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
|
||||
const USER_CODE_LENGTH: usize = 6;
|
||||
|
||||
fn generate_token() -> String { utils::random_string(Self::RANDOM_TOKEN_LENGTH) }
|
||||
|
||||
fn generate_user_code() -> String {
|
||||
Choose::new(Self::USER_CODE_CHARACTERS)
|
||||
.unwrap()
|
||||
.sample_iter(&mut rand::rng())
|
||||
.take(Self::USER_CODE_LENGTH)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn register_client(&self, metadata: &ClientMetadata) -> Result<String, OAuthError> {
|
||||
metadata.validate().map_err(|error| OAuthError {
|
||||
error: ErrorCode::InvalidClientMetadata,
|
||||
@@ -282,14 +231,14 @@ pub async fn request_authorization_code(
|
||||
| ResponseMode::Query => '?',
|
||||
};
|
||||
|
||||
let code = Self::generate_token();
|
||||
let code = PendingCodeGrant::generate_code();
|
||||
|
||||
info!(
|
||||
client_id = &query.client_id,
|
||||
client_name = &client_metadata.client_name,
|
||||
?requested_scopes,
|
||||
?authorizing_user,
|
||||
"Issuing OAuth authorization code"
|
||||
"Issuing oauth authorization code"
|
||||
);
|
||||
|
||||
let redirect_uri = format!(
|
||||
@@ -303,7 +252,7 @@ pub async fn request_authorization_code(
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let pending_grant = PendingAuthCodeGrant {
|
||||
let pending_grant = PendingCodeGrant {
|
||||
authorizing_user,
|
||||
requested_scopes,
|
||||
client_name: client_metadata.client_name,
|
||||
@@ -313,7 +262,7 @@ pub async fn request_authorization_code(
|
||||
requested_at: SystemTime::now(),
|
||||
};
|
||||
|
||||
self.pending_auth_code_grants
|
||||
self.pending_code_grants
|
||||
.lock()
|
||||
.await
|
||||
.insert(code, pending_grant);
|
||||
@@ -321,129 +270,15 @@ pub async fn request_authorization_code(
|
||||
Ok(redirect_uri)
|
||||
}
|
||||
|
||||
pub async fn request_device_code(
|
||||
&self,
|
||||
query: DeviceCodeRequest,
|
||||
) -> Result<DeviceCodeResponse, OAuthError> {
|
||||
let Some(client_metadata) = self.get_client_metadata(&query.client_id).await else {
|
||||
return Err(OAuthError::invalid_grant("Invalid client ID"));
|
||||
};
|
||||
|
||||
let requested_scopes = query
|
||||
.scope
|
||||
.to_scopes()
|
||||
.map_err(|err| OAuthError::new(ErrorCode::InvalidGrant, err))?;
|
||||
|
||||
let device_code = Self::generate_token();
|
||||
let user_code = Self::generate_user_code();
|
||||
|
||||
let verification_uri = self
|
||||
.services
|
||||
.config
|
||||
.get_client_domain()
|
||||
.join(&format!("{}/oauth2/grant/device_code", conduwuit::ROUTE_PREFIX))
|
||||
.unwrap();
|
||||
|
||||
let mut verification_uri_complete = verification_uri.clone();
|
||||
verification_uri_complete
|
||||
.query_pairs_mut()
|
||||
.append_pair("user_code", &user_code);
|
||||
|
||||
info!(
|
||||
client_id = &query.client_id,
|
||||
client_name = &client_metadata.client_name,
|
||||
?requested_scopes,
|
||||
"Issuing OAuth device code"
|
||||
);
|
||||
|
||||
let pending_grant = PendingDeviceCodeGrant {
|
||||
state: DeviceCodeGrantState::Unverified { user_code: user_code.clone() },
|
||||
requested_scopes,
|
||||
client_name: client_metadata.client_name,
|
||||
client_id: query.client_id,
|
||||
requested_at: SystemTime::now(),
|
||||
};
|
||||
|
||||
self.pending_device_code_grants
|
||||
.lock()
|
||||
.await
|
||||
.insert(device_code.clone(), pending_grant);
|
||||
|
||||
Ok(DeviceCodeResponse {
|
||||
device_code,
|
||||
user_code,
|
||||
verification_uri,
|
||||
verification_uri_complete: Some(verification_uri_complete),
|
||||
expires_in: PendingDeviceCodeGrant::MAX_AGE.as_secs(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn grant_info_for_user_code(
|
||||
&self,
|
||||
supplied_user_code: &str,
|
||||
) -> Option<DeviceCodeGrantInfo> {
|
||||
let pending_grants = self.pending_device_code_grants.lock().await;
|
||||
|
||||
let (device_code, grant) = pending_grants
|
||||
.iter()
|
||||
.find(|(_, grant)| {
|
||||
matches!(&grant.state, DeviceCodeGrantState::Unverified { user_code } if user_code == supplied_user_code)
|
||||
})?;
|
||||
|
||||
let client_metadata = self
|
||||
.get_client_metadata(&grant.client_id)
|
||||
.await
|
||||
.expect("client should exist");
|
||||
|
||||
Some(DeviceCodeGrantInfo {
|
||||
device_code: device_code.clone(),
|
||||
client_metadata,
|
||||
requested_scopes: grant.requested_scopes.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn validate_device_code(
|
||||
&self,
|
||||
authorizing_user: OwnedUserId,
|
||||
device_code: &str,
|
||||
) -> Result<(), String> {
|
||||
let mut pending_grants = self.pending_device_code_grants.lock().await;
|
||||
|
||||
let Some(pending_grant) = pending_grants.get_mut(device_code) else {
|
||||
return Err("Invalid device code".to_owned());
|
||||
};
|
||||
|
||||
match &mut pending_grant.state {
|
||||
| state @ DeviceCodeGrantState::Unverified { .. } => {
|
||||
*state = DeviceCodeGrantState::Verified { authorizing_user };
|
||||
|
||||
Ok(())
|
||||
},
|
||||
| DeviceCodeGrantState::Verified {
|
||||
authorizing_user: previous_authorizing_user,
|
||||
} =>
|
||||
if *previous_authorizing_user == authorizing_user {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Device code is already verified".to_owned())
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn issue_token(&self, request: TokenRequest) -> Result<TokenResponse, OAuthError> {
|
||||
let TokenRequest { client_id, request } = request;
|
||||
|
||||
let Some(client_metadata) = self.get_client_metadata(&client_id).await else {
|
||||
return Err(OAuthError::invalid_request("Invalid client ID"));
|
||||
};
|
||||
|
||||
if !client_metadata.grant_types.contains(&request.grant_type()) {
|
||||
return Err(OAuthError::invalid_grant("Client cannot request this grant type"));
|
||||
}
|
||||
|
||||
match request {
|
||||
| TokenRequestType::AuthorizationCode { code, redirect_uri, code_verifier } => {
|
||||
let mut pending_grants = self.pending_auth_code_grants.lock().await;
|
||||
| TokenRequest::AuthorizationCode {
|
||||
code,
|
||||
redirect_uri,
|
||||
client_id,
|
||||
code_verifier,
|
||||
} => {
|
||||
let mut pending_grants = self.pending_code_grants.lock().await;
|
||||
|
||||
let Some(pending_grant) = pending_grants
|
||||
.remove(&code)
|
||||
@@ -470,39 +305,7 @@ pub async fn issue_token(&self, request: TokenRequest) -> Result<TokenResponse,
|
||||
)
|
||||
.await
|
||||
},
|
||||
| TokenRequestType::DeviceCode { device_code } => {
|
||||
let mut pending_grants = self.pending_device_code_grants.lock().await;
|
||||
|
||||
let Some(pending_grant) = pending_grants
|
||||
.remove(&device_code)
|
||||
.filter(|grant| grant.is_valid_for(&client_id))
|
||||
else {
|
||||
return Err(OAuthError::new_static(
|
||||
ErrorCode::ExpiredToken,
|
||||
"Invalid device code",
|
||||
));
|
||||
};
|
||||
|
||||
match &pending_grant.state {
|
||||
| DeviceCodeGrantState::Unverified { .. } => {
|
||||
pending_grants.insert(device_code, pending_grant);
|
||||
|
||||
Err(OAuthError::new_static(
|
||||
ErrorCode::AuthorizationPending,
|
||||
"Authorization is pending",
|
||||
))
|
||||
},
|
||||
| DeviceCodeGrantState::Verified { authorizing_user } =>
|
||||
self.create_session(
|
||||
authorizing_user.to_owned(),
|
||||
pending_grant.requested_scopes,
|
||||
pending_grant.client_name,
|
||||
client_id,
|
||||
)
|
||||
.await,
|
||||
}
|
||||
},
|
||||
| TokenRequestType::RefreshToken { refresh_token } =>
|
||||
| TokenRequest::RefreshToken { client_id, refresh_token } =>
|
||||
self.refresh_session(client_id, refresh_token).await,
|
||||
}
|
||||
}
|
||||
@@ -561,10 +364,11 @@ async fn create_session(
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
return Err(OAuthError::new_static(
|
||||
ErrorCode::InvalidScope,
|
||||
"A device with the supplied ID already exists for this user",
|
||||
));
|
||||
return Err(OAuthError {
|
||||
error: ErrorCode::InvalidScope,
|
||||
error_description: "A device with the supplied ID already exists for this user"
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
|
||||
self.services
|
||||
|
||||
@@ -65,17 +65,17 @@ pub(super) async fn for_local_user(services: &Services, user_id: &UserId) -> Sel
|
||||
}
|
||||
|
||||
pub(super) fn for_device(
|
||||
client_metadata: Option<&ClientMetadata>,
|
||||
oauth_metadata: Option<&ClientMetadata>,
|
||||
display_name: Option<&str>,
|
||||
) -> Self {
|
||||
let avatar_src = client_metadata
|
||||
let avatar_src = oauth_metadata
|
||||
.and_then(|metadata| metadata.logo_uri.as_ref())
|
||||
.map(|uri| uri.as_str().to_owned());
|
||||
|
||||
let avatar_type = if let Some(avatar_src) = avatar_src {
|
||||
AvatarType::Image(avatar_src)
|
||||
} else if let Some(initial) = display_name.and_then(|name| name.chars().next()) {
|
||||
if client_metadata.is_some() {
|
||||
if oauth_metadata.is_some() {
|
||||
AvatarType::Initial(initial)
|
||||
} else {
|
||||
AvatarType::Initial('❖')
|
||||
@@ -86,20 +86,6 @@ pub(super) fn for_device(
|
||||
|
||||
Self { avatar_type }
|
||||
}
|
||||
|
||||
pub(super) fn for_client(client_metadata: &ClientMetadata) -> Self {
|
||||
let avatar_type = if let Some(logo) = &client_metadata.logo_uri {
|
||||
AvatarType::Image(logo.to_string())
|
||||
} else if let Some(name) = &client_metadata.client_name
|
||||
&& let Some(char) = name.chars().next()
|
||||
{
|
||||
AvatarType::Initial(char)
|
||||
} else {
|
||||
AvatarType::Initial('?')
|
||||
};
|
||||
|
||||
Self { avatar_type }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Template)]
|
||||
|
||||
+36
-108
@@ -4,12 +4,9 @@
|
||||
response::Redirect,
|
||||
routing::on,
|
||||
};
|
||||
use conduwuit_service::oauth::{
|
||||
client_metadata::ClientMetadata,
|
||||
grant::{AuthorizationCodeQuery, DeviceCodeVerifyQuery, Prompt},
|
||||
};
|
||||
use conduwuit_service::oauth::grant::{AuthorizationCodeQuery, Prompt};
|
||||
use ruma::OwnedUserId;
|
||||
use serde::Deserialize;
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
ROUTE_PREFIX, WebError,
|
||||
@@ -17,7 +14,7 @@
|
||||
pages::{
|
||||
GET_POST, Result, TemplateContext,
|
||||
account::register::{RegisterQuery, RequestedRegistrationFlow},
|
||||
components::{Avatar, ClientScopes, UserCard},
|
||||
components::{Avatar, AvatarType, ClientScopes},
|
||||
},
|
||||
response,
|
||||
session::{LoginIntent, LoginQuery, LoginTarget, User},
|
||||
@@ -25,9 +22,7 @@
|
||||
};
|
||||
|
||||
pub(crate) fn build() -> Router<crate::State> {
|
||||
Router::new()
|
||||
.route("/authorization_code", on(GET_POST, route_authorization_code))
|
||||
.route("/device_code", on(GET_POST, route_device_code))
|
||||
Router::new().route("/authorization_code", on(GET_POST, route_authorization_code))
|
||||
}
|
||||
|
||||
template! {
|
||||
@@ -35,9 +30,12 @@ struct Grant use "grant.html.j2" {
|
||||
logout_query: String,
|
||||
user_id: OwnedUserId,
|
||||
user_avatar: Avatar,
|
||||
client_metadata: ClientMetadata,
|
||||
scopes: ClientScopes,
|
||||
device_code: Option<String>
|
||||
client_uri: Url,
|
||||
client_name: String,
|
||||
client_avatar: Avatar,
|
||||
policy_uri: Option<Url>,
|
||||
tos_uri: Option<Url>,
|
||||
scopes: ClientScopes
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +102,27 @@ async fn route_authorization_code(
|
||||
|
||||
let scopes = query.scope.to_scopes().map_err(WebError::BadRequest)?;
|
||||
|
||||
let client_name = if let Some(name) = &client.client_name {
|
||||
name
|
||||
} else {
|
||||
"Unknown application"
|
||||
}
|
||||
.to_owned();
|
||||
|
||||
let client_avatar = {
|
||||
let avatar_type = if let Some(logo) = &client.logo_uri {
|
||||
AvatarType::Image(logo.to_string())
|
||||
} else if let Some(name) = &client.client_name
|
||||
&& let Some(char) = name.chars().next()
|
||||
{
|
||||
AvatarType::Initial(char)
|
||||
} else {
|
||||
AvatarType::Initial('?')
|
||||
};
|
||||
|
||||
Avatar { avatar_type }
|
||||
};
|
||||
|
||||
let user_avatar = Avatar::for_local_user(&services, &user_id).await;
|
||||
|
||||
response!(Grant::new(
|
||||
@@ -116,102 +135,11 @@ async fn route_authorization_code(
|
||||
.unwrap(),
|
||||
user_id,
|
||||
user_avatar,
|
||||
client,
|
||||
client.client_uri.clone(),
|
||||
client_name,
|
||||
client_avatar,
|
||||
client.policy_uri.clone(),
|
||||
client.tos_uri.clone(),
|
||||
ClientScopes { scopes },
|
||||
None,
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "stage", rename_all = "snake_case")]
|
||||
enum DeviceCodeForm {
|
||||
Lookup {
|
||||
user_code: String,
|
||||
},
|
||||
Confirm {
|
||||
device_code: String,
|
||||
},
|
||||
}
|
||||
|
||||
template! {
|
||||
struct DeviceCodeGrant use "device_code_grant.html.j2" {
|
||||
user_card: UserCard,
|
||||
body: DeviceCodeGrantBody
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum DeviceCodeGrantBody {
|
||||
Lookup {
|
||||
user_code_error: bool,
|
||||
},
|
||||
Success,
|
||||
}
|
||||
|
||||
async fn route_device_code(
|
||||
State(services): State<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
user: User<true>,
|
||||
Expect(Query(query)): Expect<Query<DeviceCodeVerifyQuery>>,
|
||||
PostForm(form): PostForm<DeviceCodeForm>,
|
||||
) -> Result {
|
||||
let user_id = if let Some(user) = user.into_session() {
|
||||
user.user_id
|
||||
} else {
|
||||
let next = LoginTarget::DeviceCode(query.clone());
|
||||
|
||||
let uri = format!(
|
||||
"{}/account/login?{}",
|
||||
ROUTE_PREFIX,
|
||||
serde_urlencoded::to_string(LoginQuery { next: Some(next), ..Default::default() })
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
return response!(Redirect::to(&uri));
|
||||
};
|
||||
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
|
||||
match (form, query.user_code.clone()) {
|
||||
| (None, Some(user_code)) | (Some(DeviceCodeForm::Lookup { user_code }), _) => {
|
||||
let Some(grant_info) = services.oauth.grant_info_for_user_code(&user_code).await
|
||||
else {
|
||||
return response!(DeviceCodeGrant::new(
|
||||
context,
|
||||
user_card,
|
||||
DeviceCodeGrantBody::Lookup { user_code_error: true }
|
||||
));
|
||||
};
|
||||
|
||||
let user_avatar = Avatar::for_local_user(&services, &user_id).await;
|
||||
|
||||
response!(Grant::new(
|
||||
context,
|
||||
serde_urlencoded::to_string(LoginQuery {
|
||||
next: Some(LoginTarget::DeviceCode(query)),
|
||||
intent: Some(LoginIntent::SwitchAccounts),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap(),
|
||||
user_id,
|
||||
user_avatar,
|
||||
grant_info.client_metadata,
|
||||
ClientScopes { scopes: grant_info.requested_scopes },
|
||||
Some(grant_info.device_code),
|
||||
))
|
||||
},
|
||||
| (Some(DeviceCodeForm::Confirm { device_code }), _) => {
|
||||
services
|
||||
.oauth
|
||||
.validate_device_code(user_id, &device_code)
|
||||
.await
|
||||
.map_err(WebError::BadRequest)?;
|
||||
|
||||
response!(DeviceCodeGrant::new(context, user_card, DeviceCodeGrantBody::Success))
|
||||
},
|
||||
| (None, None) =>
|
||||
response!(DeviceCodeGrant::new(context, user_card, DeviceCodeGrantBody::Lookup {
|
||||
user_code_error: false
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,17 +20,3 @@
|
||||
font-style: italic;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.user-code {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
|
||||
input {
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
font-size: 200%;
|
||||
padding: 0.2em;
|
||||
width: 6em !important;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
{% extends "_layout.html.j2" %}
|
||||
|
||||
{%- block head -%}
|
||||
<link rel="stylesheet" href="{{ crate::ROUTE_PREFIX }}/resources/grant.css">
|
||||
{%- endblock -%}
|
||||
|
||||
{%- block title -%}
|
||||
Authorize client
|
||||
{%- endblock -%}
|
||||
|
||||
{%- block content -%}
|
||||
<div class="panel narrow">
|
||||
<h1>Authorize device</h1>
|
||||
{{ user_card }}
|
||||
{% match body %}
|
||||
{% when DeviceCodeGrantBody::Lookup { user_code_error } %}
|
||||
<p>
|
||||
Enter the code displayed on your device, or in the app you're signing into.
|
||||
</p>
|
||||
<p>
|
||||
<em class="negative">Never enter a code given to you by someone else.</em>
|
||||
Your homeserver administrator will never ask you to enter a code on this page.
|
||||
</p>
|
||||
|
||||
<form method="post">
|
||||
<p>
|
||||
<div class="user-code">
|
||||
<label for="user_code">Validation code</label>
|
||||
<input
|
||||
type="text"
|
||||
id="user_code"
|
||||
name="user_code"
|
||||
maxlength="6"
|
||||
spellcheck="false"
|
||||
pattern="\d{6}"
|
||||
title="Enter the six-digit validation code"
|
||||
>
|
||||
</div>
|
||||
{% if user_code_error %}
|
||||
<small class="error">Invalid code</small>
|
||||
{% endif %}
|
||||
</p>
|
||||
<input type="hidden" name="stage" value="lookup">
|
||||
<button type="submit">Continue</button>
|
||||
</form>
|
||||
{% when DeviceCodeGrantBody::Success %}
|
||||
<p>Success! 🎉 You can close this tab and return to your device.</p>
|
||||
{% endmatch %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -9,7 +9,6 @@ Authorize client
|
||||
{%- endblock -%}
|
||||
|
||||
{%- block content -%}
|
||||
{% let client_name = client_metadata.client_name.as_deref().unwrap_or("Unknown application") %}
|
||||
<div class="panel narrow">
|
||||
<h1>Authorize {{ client_name }}</h1>
|
||||
<div class="avatars">
|
||||
@@ -19,17 +18,17 @@ Authorize client
|
||||
<div class="separator" aria-hidden="true">
|
||||
⇄
|
||||
</div>
|
||||
{{ Avatar::for_client(client_metadata) }}
|
||||
{{ client_avatar }}
|
||||
</div>
|
||||
<div class="identity">
|
||||
Signed in as <code>{{ user_id }}</code>. <a href="{{ crate::ROUTE_PREFIX }}/account/logout?{{ logout_query }}">Switch accounts</a>
|
||||
</div>
|
||||
<p>
|
||||
<b>{{ client_name }}</b> (<a href="{{ client_metadata.client_uri }}">{{ client_metadata.client_uri.domain().unwrap() }}</a>) would like
|
||||
<b>{{ client_name }}</b> (<a href="{{ client_uri }}">{{ client_uri.domain().unwrap() }}</a>) would like
|
||||
your permission to:
|
||||
{{ scopes }}
|
||||
</p>
|
||||
{% match (&client_metadata.policy_uri, &client_metadata.tos_uri) %}
|
||||
{% match (&policy_uri, &tos_uri) %}
|
||||
{% when (Some(policy_uri), Some(tos_uri)) %}
|
||||
<p>
|
||||
{{ client_name }}'s <a href="{{ policy_uri }}">policies</a>
|
||||
@@ -50,10 +49,6 @@ Authorize client
|
||||
{% endmatch %}
|
||||
|
||||
<form method="post">
|
||||
<input type="hidden" name="stage" value="confirm">
|
||||
{% if let Some(device_code) = device_code %}
|
||||
<input type="hidden" name="device_code" value="{{ device_code }}">
|
||||
{% endif %}
|
||||
<button type="submit">Continue</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
http::request::Parts,
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
};
|
||||
use conduwuit_service::oauth::grant::{AuthorizationCodeQuery, DeviceCodeVerifyQuery};
|
||||
use conduwuit_service::oauth::grant::AuthorizationCodeQuery;
|
||||
use ruma::{OwnedUserId, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tower_sessions::Session;
|
||||
@@ -38,7 +38,6 @@ pub(crate) enum LoginTarget {
|
||||
ChangeEmail,
|
||||
CrossSigningReset,
|
||||
Deactivate,
|
||||
DeviceCode(DeviceCodeVerifyQuery),
|
||||
DeviceInfo(DevicePath),
|
||||
RemoveDevice(DevicePath),
|
||||
}
|
||||
@@ -60,9 +59,6 @@ pub(crate) fn target_path(&self) -> String {
|
||||
| Self::ChangeEmail => "account/email/change/".into(),
|
||||
| Self::CrossSigningReset => "account/cross_signing_reset".into(),
|
||||
| Self::Deactivate => "account/deactivate".into(),
|
||||
| Self::DeviceCode(code) =>
|
||||
format!("oauth2/grant/device_code?{}", serde_urlencoded::to_string(code).unwrap())
|
||||
.into(),
|
||||
| Self::DeviceInfo(path) => format!("account/device/{}/", path.device).into(),
|
||||
| Self::RemoveDevice(path) => format!("account/device/{}/remove", path.device).into(),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user