Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(admin): sign in with an external OpenID Connect provider (#3833)

Hampusc27c1ccf2bc3
diff --git a/deploy/helm/fluxer/values.yaml b/deploy/helm/fluxer/values.yaml
index 1d9ba6734..0b742379d 100644
--- a/deploy/helm/fluxer/values.yaml
+++ b/deploy/helm/fluxer/values.yaml
@@ -153,6 +153,8 @@ secrets:
# FLUXER_PUSH_APNS_PRIVATE_KEY: ""
# FCM private key for Android push.
# FLUXER_PUSH_FCM_PRIVATE_KEY: ""
+ # Client secret of the admin single sign-on provider.
+ # FLUXER_ADMIN_SSO_CLIENT_SECRET: ""
# Extra non-secret settings for every Fluxer service, as NAME: value. The names
# and meanings are on the configuration page of the operator docs. An empty
diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.json
index 635b1cfdf..0ff05b4e5 100644
--- a/fluxer_admin/openapi-admin.json
+++ b/fluxer_admin/openapi-admin.json
@@ -8607,6 +8607,54 @@
}
}
},
+ "/admin/sso/sign-in": {
+ "post": {
+ "operationId": "exchange_admin_sso_token",
+ "summary": "Exchange admin SSO ID token",
+ "tags": ["Admin"],
+ "responses": {
+ "200": {
+ "description": "Success",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AdminSsoSignInResponse"}}}
+ },
+ "400": {
+ "description": "Bad Request - The request was malformed or contained invalid data",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
+ },
+ "429": {
+ "description": "Too Many Requests - You are being rate limited",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ThrottledError"}}},
+ "headers": {
+ "Retry-After": {
+ "description": "Number of seconds to wait before retrying (only on 429)",
+ "schema": {"type": "integer"}
+ },
+ "X-RateLimit-Limit": {
+ "description": "The number of requests that can be made in the current window",
+ "schema": {"type": "integer"}
+ },
+ "X-RateLimit-Remaining": {
+ "description": "The number of remaining requests that can be made",
+ "schema": {"type": "integer"}
+ },
+ "X-RateLimit-Reset": {
+ "description": "Unix timestamp when the rate limit resets",
+ "schema": {"type": "integer"}
+ }
+ }
+ },
+ "500": {
+ "description": "Internal Server Error - An unexpected error occurred",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
+ }
+ },
+ "description": "Verifies an ID token from the admin sign-on provider and returns an admin panel access token for the Fluxer account in its fluxer_id claim. Only the admin panel calls it, with its OAuth2 client ID and secret as HTTP Basic auth. The account must already have admin:authenticate.",
+ "requestBody": {
+ "required": true,
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AdminSsoSignInRequest"}}}
+ }
+ }
+ },
"/admin/system-dms": {
"post": {
"operationId": "create_admin_system_dm",
@@ -16096,6 +16144,43 @@
"required": ["recipient_count"],
"additionalProperties": false
},
+ "AdminSsoSignInRequest": {
+ "type": "object",
+ "properties": {
+ "id_token": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 16384,
+ "description": "The ID token the admin panel got from the sign-on provider"
+ },
+ "nonce": {
+ "type": "string",
+ "minLength": 16,
+ "maxLength": 256,
+ "description": "The nonce the admin panel sent to the sign-on provider, which the ID token must have"
+ }
+ },
+ "required": ["id_token", "nonce"]
+ },
+ "AdminSsoSignInResponse": {
+ "type": "object",
+ "properties": {
+ "access_token": {"type": "string", "description": "The access token for API authorization"},
+ "token_type": {"type": "string", "description": "The type of token, typically \"Bearer\""},
+ "expires_in": {
+ "description": "The number of seconds until the access token expires",
+ "allOf": [{"$ref": "#/components/schemas/Int32Type"}]
+ },
+ "refresh_token": {"type": "string", "description": "The refresh token for obtaining new access tokens"},
+ "scope": {"type": "string", "description": "The space-separated list of granted scopes"},
+ "user_id": {
+ "description": "The account the admin signed in as",
+ "allOf": [{"$ref": "#/components/schemas/SnowflakeStringType"}]
+ }
+ },
+ "required": ["access_token", "token_type", "expires_in", "refresh_token", "scope", "user_id"],
+ "additionalProperties": false
+ },
"AdminSsoIdentityMigrateRequest": {
"type": "object",
"properties": {
diff --git a/fluxer_admin/src/config/mod.rs b/fluxer_admin/src/config/mod.rs
index e41e35aed..7017dc8bf 100644
--- a/fluxer_admin/src/config/mod.rs
+++ b/fluxer_admin/src/config/mod.rs
@@ -27,6 +27,16 @@ pub struct AdminConfig {
pub build_version: String,
pub self_hosted: bool,
pub proxy: ProxyConfig,
+ pub sso: Option<SsoConfig>,
+}
+
+#[derive(Clone, Debug)]
+pub struct SsoConfig {
+ pub issuer: String,
+ pub client_id: String,
+ pub client_secret: String,
+ pub redirect_uri: String,
+ pub display_name: Option<String>,
}
#[derive(Clone, Debug)]
@@ -46,6 +56,7 @@ impl AdminConfig {
"FLUXER_ADMIN_OAUTH_REDIRECT_URI",
&format!("{admin_endpoint}/oauth2_callback"),
));
+ let sso = sso_config_from_env(&admin_endpoint)?;
let secret_key_base = read_env("FLUXER_ADMIN_SECRET_KEY_BASE", "");
anyhow::ensure!(
!secret_key_base.trim().is_empty(),
@@ -97,6 +108,7 @@ impl AdminConfig {
.trim()
.to_ascii_lowercase(),
},
+ sso,
})
}
@@ -148,6 +160,32 @@ impl AdminConfig {
}
}
+fn sso_config_from_env(admin_endpoint: &str) -> anyhow::Result<Option<SsoConfig>> {
+ let issuer =
+ env_value("FLUXER_ADMIN_SSO_ISSUER").map(|value| trim_trailing_slash(value.trim()));
+ let client_id = env_value("FLUXER_ADMIN_SSO_CLIENT_ID");
+ let client_secret = env_value("FLUXER_ADMIN_SSO_CLIENT_SECRET");
+ let (issuer, client_id, client_secret) = match (issuer, client_id, client_secret) {
+ (Some(issuer), Some(client_id), Some(client_secret)) => (issuer, client_id, client_secret),
+ (None, None, None) => return Ok(None),
+ _ => anyhow::bail!(
+ "set FLUXER_ADMIN_SSO_ISSUER, FLUXER_ADMIN_SSO_CLIENT_ID and FLUXER_ADMIN_SSO_CLIENT_SECRET together, or none of them"
+ ),
+ };
+ let redirect_uri = normalize_public_endpoint_from_env(&read_env(
+ "FLUXER_ADMIN_SSO_REDIRECT_URI",
+ &format!("{admin_endpoint}/sso/callback"),
+ ));
+ Ok(Some(SsoConfig {
+ issuer,
+ client_id: client_id.trim().to_owned(),
+ client_secret,
+ redirect_uri,
+ display_name: env_value("FLUXER_ADMIN_SSO_DISPLAY_NAME")
+ .map(|value| value.trim().to_owned()),
+ }))
+}
+
fn endpoint_origin(endpoint: &str) -> Option<String> {
let origin = url::Url::parse(endpoint).ok()?.origin();
origin.is_tuple().then(|| origin.ascii_serialization())
diff --git a/fluxer_admin/src/lib.rs b/fluxer_admin/src/lib.rs
index f2852b087..7e559c305 100644
--- a/fluxer_admin/src/lib.rs
+++ b/fluxer_admin/src/lib.rs
@@ -10,6 +10,7 @@ pub mod middleware;
pub mod oauth2;
pub mod routes;
pub mod session;
+pub mod sso;
pub mod state;
pub mod templates;
pub mod utils;
diff --git a/fluxer_admin/src/middleware/auth.rs b/fluxer_admin/src/middleware/auth.rs
index 87ad5ca24..4222d584d 100644
--- a/fluxer_admin/src/middleware/auth.rs
+++ b/fluxer_admin/src/middleware/auth.rs
@@ -42,7 +42,12 @@ pub async fn require_auth(
let config = state.config();
let session = extract_session(&request, &config.secret_key_base);
let Some(session) = session else {
- return Redirect::to(&format!("{}/auth/start", config.base_path)).into_response();
+ let entry = if config.sso.is_some() {
+ "login"
+ } else {
+ "auth/start"
+ };
+ return Redirect::to(&format!("{}/{entry}", config.base_path)).into_response();
};
let (admin_user, pending_registration_count) =
match fetch_admin_user(state.http_client(), config, &session).await {
diff --git a/fluxer_admin/src/oauth2.rs b/fluxer_admin/src/oauth2.rs
index 0cf8e0712..6dbec4ab4 100644
--- a/fluxer_admin/src/oauth2.rs
+++ b/fluxer_admin/src/oauth2.rs
@@ -95,19 +95,22 @@ pub async fn fetch_user_info(
Ok(user)
}
+pub(crate) fn admin_client_basic_auth(config: &AdminConfig) -> String {
+ let credentials = format!("{}:{}", config.oauth_client_id, config.oauth_client_secret);
+ format!("Basic {}", STANDARD.encode(credentials.as_bytes()))
+}
+
pub async fn revoke_token(
http_client: &reqwest::Client,
config: &AdminConfig,
token: &str,
) -> anyhow::Result<()> {
- let credentials = format!("{}:{}", config.oauth_client_id, config.oauth_client_secret);
- let basic = format!("Basic {}", STANDARD.encode(credentials.as_bytes()));
let response = with_proxy_client_ip_header(
http_client.post(format!("{}/oauth2/token/revoke", config.api_endpoint)),
config,
)
.header("Content-Type", "application/x-www-form-urlencoded")
- .header("Authorization", basic)
+ .header("Authorization", admin_client_basic_auth(config))
.body(format!(
"token={}&token_type_hint=access_token",
urlencoding::encode(token)
diff --git a/fluxer_admin/src/routes/auth.rs b/fluxer_admin/src/routes/auth.rs
index 3e6ccd6f7..4cc55e3cc 100644
--- a/fluxer_admin/src/routes/auth.rs
+++ b/fluxer_admin/src/routes/auth.rs
@@ -8,6 +8,7 @@ use crate::{
self, SESSION_COOKIE_NAME, SESSION_MAX_AGE, admin_cookie_path, append_cookies,
clear_cookie_values,
},
+ sso,
state::AppState,
templates::pages::login,
};
@@ -33,7 +34,13 @@ const OAUTH_STATE_VERIFIER_HASH_BYTES: usize = 32;
const OAUTH_STATE_PAYLOAD_BYTES: usize =
std::mem::size_of::<u64>() + OAUTH_STATE_NONCE_BYTES + OAUTH_STATE_VERIFIER_HASH_BYTES;
const OAUTH_FLOW_STORAGE_KEY: &str = "fluxer-admin-oauth-flow";
+const SSO_FLOW_STORAGE_KEY: &str = "fluxer-admin-sso-flow";
const OAUTH_FINISH_HEADER: &str = "x-fluxer-admin-oauth";
+const OAUTH_STATE_PURPOSE: &str = "oauth";
+const SSO_STATE_PURPOSE: &str = "sso";
+const OAUTH_FAILED: &str = "oauth_failed";
+const SSO_FAILED: &str = "sso_failed";
+const SSO_UNAVAILABLE: &str = "sso_unavailable";
#[derive(Deserialize)]
struct LoginQuery {
@@ -44,6 +51,7 @@ struct LoginQuery {
struct CallbackQuery {
code: Option<String>,
state: Option<String>,
+ iss: Option<String>,
}
#[derive(Deserialize)]
@@ -51,6 +59,7 @@ struct CallbackFinishBody {
code: String,
state: String,
verifier: String,
+ iss: Option<String>,
}
#[derive(Serialize)]
@@ -66,6 +75,11 @@ pub fn router() -> Router<AppState> {
"/oauth2_callback",
get(oauth2_callback_page).post(oauth2_callback_finish),
)
+ .route("/sso/start", get(sso_start))
+ .route(
+ "/sso/callback",
+ get(sso_callback_page).post(sso_callback_finish),
+ )
.route("/logout", post(logout))
.route("/logout", get(logout_get))
}
@@ -89,10 +103,12 @@ async fn login_page(
async fn auth_start(State(state): State<AppState>) -> Response {
let config = state.config();
let verifier = random_nonce();
- let oauth_state = generate_oauth_state(&config.secret_key_base, &verifier);
+ let oauth_state = generate_oauth_state(&config.secret_key_base, OAUTH_STATE_PURPOSE, &verifier);
let authorize_url = oauth2::authorize_url(config, &oauth_state);
Html(oauth_start_page(
config,
+ OAUTH_FLOW_STORAGE_KEY,
+ OAUTH_FAILED,
&authorize_url,
&oauth_state,
&verifier,
@@ -100,32 +116,158 @@ async fn auth_start(State(state): State<AppState>) -> Response {
.into_response()
}
-async fn oauth2_callback_page(
+async fn sso_start(State(state): State<AppState>) -> Response {
+ let config = state.config();
+ let base = &config.base_path;
+ let Some(sso_config) = config.sso.as_ref() else {
+ return Redirect::to(&format!("{base}/login")).into_response();
+ };
+ let Some(metadata) = state.sso_provider().await else {
+ return Redirect::to(&format!("{base}/login?error={SSO_UNAVAILABLE}")).into_response();
+ };
+ let verifier = random_nonce();
+ let sso_state = generate_oauth_state(&config.secret_key_base, SSO_STATE_PURPOSE, &verifier);
+ let authorize_url = match sso::authorize_url(
+ &metadata,
+ sso_config,
+ &sso_state,
+ &sso::nonce(&config.secret_key_base, &verifier),
+ &sso::code_challenge(&verifier),
+ ) {
+ Ok(url) => url,
+ Err(err) => {
+ tracing::error!(%err, "SSO authorization URL is invalid");
+ return Redirect::to(&format!("{base}/login?error={SSO_UNAVAILABLE}")).into_response();
+ }
+ };
+ Html(oauth_start_page(
+ config,
+ SSO_FLOW_STORAGE_KEY,
+ SSO_FAILED,
+ &authorize_url,
+ &sso_state,
+ &verifier,
+ ))
+ .into_response()
+}
+
+async fn sso_callback_page(
State(state): State<AppState>,
Query(query): Query<CallbackQuery>,
) -> Response {
let config = state.config();
+ if config.sso.is_none() {
+ return Redirect::to(&format!("{}/login", config.base_path)).into_response();
+ }
Html(oauth_callback_page(
config,
+ SSO_FLOW_STORAGE_KEY,
+ SSO_FAILED,
query.code.as_deref(),
query.state.as_deref(),
+ query.iss.as_deref(),
))
.into_response()
}
-async fn oauth2_callback_finish(
+async fn sso_callback_finish(
State(state): State<AppState>,
headers: HeaderMap,
Json(body): Json<CallbackFinishBody>,
) -> Response {
let config = state.config();
let base = &config.base_path;
+ let failed = |status: StatusCode, code: &str| {
+ oauth_finish_response(status, &format!("{base}/login?error={code}"), &[])
+ };
+
+ let Some(sso_config) = config.sso.as_ref() else {
+ return failed(StatusCode::NOT_FOUND, SSO_FAILED);
+ };
+ if !has_finish_header(&headers) {
+ return failed(StatusCode::FORBIDDEN, SSO_FAILED);
+ }
+ if !verify_oauth_state(
+ &config.secret_key_base,
+ SSO_STATE_PURPOSE,
+ &body.state,
+ &body.verifier,
+ ) {
+ tracing::error!("SSO state token is invalid, expired, or malformed");
+ return failed(StatusCode::BAD_REQUEST, SSO_FAILED);
+ }
+ if let Some(iss) = body.iss.as_deref().filter(|iss| !iss.is_empty())
+ && iss.trim_end_matches('/') != sso_config.issuer.trim_end_matches('/')
+ {
+ tracing::error!("SSO callback came from a different issuer");
+ return failed(StatusCode::BAD_REQUEST, SSO_FAILED);
+ }
+ let Some(metadata) = state.sso_provider().await else {
+ return failed(StatusCode::BAD_GATEWAY, SSO_UNAVAILABLE);
+ };
+ let id_token = match sso::exchange_code(
+ state.http_client(),
+ &metadata,
+ sso_config,
+ &body.code,
+ &body.verifier,
+ )
+ .await
+ {
+ Ok(id_token) => id_token,
+ Err(err) => {
+ tracing::error!(%err, "SSO token exchange failed");
+ return failed(StatusCode::BAD_REQUEST, SSO_FAILED);
+ }
+ };
+ let nonce = sso::nonce(&config.secret_key_base, &body.verifier);
+ let signed_in = match sso::sign_in(state.http_client(), config, &id_token, &nonce).await {
+ Ok(signed_in) => signed_in,
+ Err(err) => {
+ let code = sso_sign_in_error_code(&err);
+ if code == "missing_admin_acl" {
+ tracing::warn!(%err, "SSO sign-in refused by the API");
+ return failed(StatusCode::FORBIDDEN, code);
+ }
+ tracing::error!(%err, "SSO sign-in through the API failed");
+ return failed(StatusCode::BAD_GATEWAY, code);
+ }
+ };
+ finish_admin_sign_in(&state, &signed_in.user_id, &signed_in.access_token).await
+}
- if headers
+fn has_finish_header(headers: &HeaderMap) -> bool {
+ headers
.get(OAUTH_FINISH_HEADER)
.and_then(|value| value.to_str().ok())
- != Some("1")
- {
+ == Some("1")
+}
+
+async fn oauth2_callback_page(
+ State(state): State<AppState>,
+ Query(query): Query<CallbackQuery>,
+) -> Response {
+ let config = state.config();
+ Html(oauth_callback_page(
+ config,
+ OAUTH_FLOW_STORAGE_KEY,
+ OAUTH_FAILED,
+ query.code.as_deref(),
+ query.state.as_deref(),
+ None,
+ ))
+ .into_response()
+}
+
+async fn oauth2_callback_finish(
+ State(state): State<AppState>,
+ headers: HeaderMap,
+ Json(body): Json<CallbackFinishBody>,
+) -> Response {
+ let config = state.config();
+ let base = &config.base_path;
+
+ if !has_finish_header(&headers) {
return oauth_finish_response(
StatusCode::FORBIDDEN,
&format!("{base}/login?error=oauth_failed"),
@@ -133,7 +275,12 @@ async fn oauth2_callback_finish(
);
}
- if !verify_oauth_state(&config.secret_key_base, &body.state, &body.verifier) {
+ if !verify_oauth_state(
+ &config.secret_key_base,
+ OAUTH_STATE_PURPOSE,
+ &body.state,
+ &body.verifier,
+ ) {
tracing::error!("OAuth2 state token is invalid, expired, or malformed");
return oauth_finish_response(
StatusCode::BAD_REQUEST,
@@ -167,26 +314,32 @@ async fn oauth2_callback_finish(
}
};
+ finish_admin_sign_in(&state, &user.id, &token.access_token).await
+}
+
+async fn finish_admin_sign_in(state: &AppState, user_id: &str, access_token: &str) -> Response {
+ let config = state.config();
+ let base = &config.base_path;
let temp_session = session::Session {
- user_id: user.id.clone(),
- access_token: token.access_token.clone(),
+ user_id: user_id.to_owned(),
+ access_token: access_token.to_owned(),
created_at: 0,
};
let api_client = AdminApiClient::new(state.http_client(), config, &temp_session);
if let Err(err) = api_client.get_current_admin().await {
let code = admin_check_error_code(&err);
let status = if code == "missing_admin_acl" {
- tracing::warn!(%err, user_id = %user.id, "Admin access check denied");
+ tracing::warn!(%err, %user_id, "Admin access check denied");
StatusCode::FORBIDDEN
} else {
- tracing::error!(%err, user_id = %user.id, "Admin access check failed");
+ tracing::error!(%err, %user_id, "Admin access check failed");
StatusCode::BAD_GATEWAY
};
return oauth_finish_response(status, &format!("{base}/login?error={code}"), &[]);
}
let session_cookie_value =
- session::create_session(&user.id, &token.access_token, &config.secret_key_base);
+ session::create_session(user_id, access_token, &config.secret_key_base);
let secure = if config.secure_cookies() {
"; Secure"
} else {
@@ -246,13 +399,15 @@ fn extract_cookie(headers: &axum::http::HeaderMap, name: &str) -> Option<String>
fn oauth_start_page(
config: &AdminConfig,
+ storage_key: &str,
+ failure_code: &str,
authorize_url: &str,
state: &str,
verifier: &str,
) -> String {
- let storage_key = json_string(OAUTH_FLOW_STORAGE_KEY);
+ let storage_key = json_string(storage_key);
let authorize_url = json_string(authorize_url);
- let login_url = json_string(&format!("{}/login?error=oauth_failed", config.base_path));
+ let login_url = json_string(&format!("{}/login?error={failure_code}", config.base_path));
let state = json_string(state);
let verifier = json_string(verifier);
format!(
@@ -281,11 +436,19 @@ fn oauth_start_page(
)
}
-fn oauth_callback_page(config: &AdminConfig, code: Option<&str>, state: Option<&str>) -> String {
- let storage_key = json_string(OAUTH_FLOW_STORAGE_KEY);
- let login_url = json_string(&format!("{}/login?error=oauth_failed", config.base_path));
+fn oauth_callback_page(
+ config: &AdminConfig,
+ storage_key: &str,
+ failure_code: &str,
+ code: Option<&str>,
+ state: Option<&str>,
+ iss: Option<&str>,
+) -> String {
+ let storage_key = json_string(storage_key);
+ let login_url = json_string(&format!("{}/login?error={failure_code}", config.base_path));
let code = json_string(code.unwrap_or_default());
let state = json_string(state.unwrap_or_default());
+ let iss = iss.map_or_else(|| "null".to_owned(), json_string);
format!(
r#"<!doctype html>
<html lang="en">
@@ -302,6 +465,7 @@ fn oauth_callback_page(config: &AdminConfig, code: Option<&str>, state: Option<&
var loginUrl = {login_url};
var code = {code};
var state = {state};
+ var iss = {iss};
function fail(clearFlow) {{
if (clearFlow) {{
try {{ window.sessionStorage.removeItem(storageKey); }} catch (error) {{}}
@@ -330,7 +494,7 @@ fn oauth_callback_page(config: &AdminConfig, code: Option<&str>, state: Option<&
'Content-Type': 'application/json',
'X-Fluxer-Admin-OAuth': '1'
}},
- body: JSON.stringify({{code: code, state: state, verifier: flow.verifier}})
+ body: JSON.stringify({{code: code, state: state, verifier: flow.verifier, iss: iss}})
}})
.then(function (response) {{
return response.json().catch(function () {{ return null; }});
@@ -376,28 +540,35 @@ fn oauth_finish_response(status: StatusCode, redirect_to: &str, cookies: &[Strin
response
}
-fn generate_oauth_state(secret_key: &str, verifier: &str) -> String {
- sign_oauth_state(secret_key, now_seconds(), random_state_nonce(), verifier)
+fn generate_oauth_state(secret_key: &str, purpose: &str, verifier: &str) -> String {
+ sign_oauth_state(
+ secret_key,
+ purpose,
+ now_seconds(),
+ random_state_nonce(),
+ verifier,
+ )
}
fn sign_oauth_state(
secret_key: &str,
+ purpose: &str,
issued_at: u64,
nonce: [u8; OAUTH_STATE_NONCE_BYTES],
verifier: &str,
) -> String {
let encoded_payload = encode_oauth_state_payload(issued_at, nonce, verifier);
- let signature = sign_oauth_state_payload(secret_key, &encoded_payload);
+ let signature = sign_oauth_state_payload(secret_key, purpose, &encoded_payload);
format!("{encoded_payload}.{signature}")
}
-fn verify_oauth_state(secret_key: &str, state: &str, verifier: &str) -> bool {
+fn verify_oauth_state(secret_key: &str, purpose: &str, state: &str, verifier: &str) -> bool {
let Some((payload, signature)) = state.rsplit_once('.') else {
return false;
};
if !constant_time_eq(
signature.as_bytes(),
- sign_oauth_state_payload(secret_key, payload).as_bytes(),
+ sign_oauth_state_payload(secret_key, purpose, payload).as_bytes(),
) {
return false;
}
@@ -444,10 +615,10 @@ fn verifier_hash_bytes(verifier: &str) -> [u8; OAUTH_STATE_VERIFIER_HASH_BYTES]
bytes
}
-fn sign_oauth_state_payload(secret_key: &str, payload: &str) -> String {
+fn sign_oauth_state_payload(secret_key: &str, purpose: &str, payload: &str) -> String {
let mut mac =
HmacSha256::new_from_slice(secret_key.as_bytes()).expect("HMAC can take key of any size");
- mac.update(b"fluxer-admin-oauth-state:");
+ mac.update(format!("fluxer-admin-{purpose}-state:").as_bytes());
mac.update(payload.as_bytes());
URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes())
}
@@ -494,9 +665,32 @@ fn admin_check_error_code(err: &ApiError) -> &'static str {
}
}
+fn sso_sign_in_error_code(err: &ApiError) -> &'static str {
+ match err {
+ ApiError::Http {
+ status: 403,
+ message,
+ ..
+ } if message.contains("FEATURE_TEMPORARILY_DISABLED") => SSO_FAILED,
+ ApiError::Http { status: 403, .. } => "missing_admin_acl",
+ ApiError::Http {
+ status: 400 | 401, ..
+ } => SSO_FAILED,
+ ApiError::Http { status: 503, .. } => SSO_UNAVAILABLE,
+ ApiError::Http {
+ status: 404 | 405, ..
+ }
+ | ApiError::Parse(_) => "admin_api_mismatch",
+ ApiError::Network(_) => "admin_api_unreachable",
+ ApiError::Http { .. } => "admin_check_failed",
+ }
+}
+
fn login_error_message(code: &str) -> &'static str {
match code {
"oauth_failed" => "Authentication failed. Please try again.",
+ "sso_failed" => "Single sign-on failed. Try again.",
+ "sso_unavailable" => "Could not reach the sign-on provider. Try again in a moment.",
"missing_admin_acl" => {
"Access denied: missing admin:authenticate permission. \
Ask an administrator to grant access."
@@ -516,3 +710,40 @@ fn login_error_message(code: &str) -> &'static str {
_ => "Login error. Please try again.",
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn state_signed_for_one_flow_fails_for_the_other() {
+ let secret = "test-secret";
+ let verifier = random_nonce();
+ let oauth_state = generate_oauth_state(secret, OAUTH_STATE_PURPOSE, &verifier);
+ let sso_state = generate_oauth_state(secret, SSO_STATE_PURPOSE, &verifier);
+ assert!(verify_oauth_state(
+ secret,
+ OAUTH_STATE_PURPOSE,
+ &oauth_state,
+ &verifier
+ ));
+ assert!(verify_oauth_state(
+ secret,
+ SSO_STATE_PURPOSE,
+ &sso_state,
+ &verifier
+ ));
+ assert!(!verify_oauth_state(
+ secret,
+ SSO_STATE_PURPOSE,
+ &oauth_state,
+ &verifier
+ ));
+ assert!(!verify_oauth_state(
+ secret,
+ OAUTH_STATE_PURPOSE,
+ &sso_state,
+ &verifier
+ ));
+ }
+}
diff --git a/fluxer_admin/src/sso.rs b/fluxer_admin/src/sso.rs
new file mode 100644
index 000000000..e6f6573c8
--- /dev/null
+++ b/fluxer_admin/src/sso.rs
@@ -0,0 +1,176 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+use crate::{
+ api::client::{ApiError, with_proxy_client_ip_header},
+ config::{AdminConfig, SsoConfig},
+ oauth2::admin_client_basic_auth,
+};
+use base64::{
+ Engine as _,
+ engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
+};
+use hmac::{Hmac, KeyInit, Mac};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+
+pub const SSO_SCOPE: &str = "openid profile";
+
+#[derive(Clone, Debug, Deserialize)]
+pub struct ProviderMetadata {
+ pub issuer: String,
+ pub authorization_endpoint: String,
+ pub token_endpoint: String,
+}
+
+#[derive(Deserialize)]
+struct TokenResponse {
+ id_token: String,
+}
+
+#[derive(Deserialize)]
+struct TokenErrorResponse {
+ error: Option<String>,
+}
+
+#[derive(Serialize)]
+struct SignInRequest<'a> {
+ id_token: &'a str,
+ nonce: &'a str,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct SsoSignInResponse {
+ pub user_id: String,
+ pub access_token: String,
+}
+
+pub async fn discover(http: &reqwest::Client, sso: &SsoConfig) -> anyhow::Result<ProviderMetadata> {
+ let issuer = sso.issuer.trim_end_matches('/');
+ let response = http
+ .get(format!("{issuer}/.well-known/openid-configuration"))
+ .header("Accept", "application/json")
+ .send()
+ .await?;
+ let status = response.status();
+ if !status.is_success() {
+ anyhow::bail!("provider discovery failed with status {status}");
+ }
+ let metadata: ProviderMetadata = response.json().await?;
+ if metadata.issuer.trim_end_matches('/') != issuer {
+ anyhow::bail!("provider discovery returned a different issuer");
+ }
+ if issuer.starts_with("https://")
+ && !(metadata.authorization_endpoint.starts_with("https://")
+ && metadata.token_endpoint.starts_with("https://"))
+ {
+ anyhow::bail!("provider discovery returned an endpoint that is not https");
+ }
+ Ok(metadata)
+}
+
+pub fn authorize_url(
+ metadata: &ProviderMetadata,
+ sso: &SsoConfig,
+ state: &str,
+ nonce: &str,
+ code_challenge: &str,
+) -> anyhow::Result<String> {
+ let mut url = url::Url::parse(&metadata.authorization_endpoint)?;
+ url.query_pairs_mut()
+ .append_pair("response_type", "code")
+ .append_pair("client_id", &sso.client_id)
+ .append_pair("redirect_uri", &sso.redirect_uri)
+ .append_pair("scope", SSO_SCOPE)
+ .append_pair("state", state)
+ .append_pair("nonce", nonce)
+ .append_pair("code_challenge", code_challenge)
+ .append_pair("code_challenge_method", "S256");
+ Ok(url.into())
+}
+
+pub fn code_challenge(verifier: &str) -> String {
+ URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
+}
+
+pub fn nonce(secret_key_base: &str, verifier: &str) -> String {
+ let mut mac = Hmac::<Sha256>::new_from_slice(secret_key_base.as_bytes())
+ .expect("HMAC can take key of any size");
+ mac.update(b"fluxer-admin-sso-nonce:");
+ mac.update(verifier.as_bytes());
+ URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes())
+}
+
+fn form_encode(pairs: &[(&str, &str)]) -> String {
+ url::form_urlencoded::Serializer::new(String::new())
+ .extend_pairs(pairs)
+ .finish()
+}
+
+fn client_secret_basic(sso: &SsoConfig) -> String {
+ let id = urlencoding::encode(&sso.client_id);
+ let secret = urlencoding::encode(&sso.client_secret);
+ format!("Basic {}", STANDARD.encode(format!("{id}:{secret}")))
+}
+
+pub async fn exchange_code(
+ http: &reqwest::Client,
+ metadata: &ProviderMetadata,
+ sso: &SsoConfig,
+ code: &str,
+ verifier: &str,
+) -> anyhow::Result<String> {
+ let response = http
+ .post(&metadata.token_endpoint)
+ .header("Content-Type", "application/x-www-form-urlencoded")
+ .header("Accept", "application/json")
+ .header("Authorization", client_secret_basic(sso))
+ .body(form_encode(&[
+ ("grant_type", "authorization_code"),
+ ("code", code),
+ ("redirect_uri", sso.redirect_uri.as_str()),
+ ("code_verifier", verifier),
+ ]))
+ .send()
+ .await?;
+ let status = response.status();
+ if !status.is_success() {
+ let error = response
+ .json::<TokenErrorResponse>()
+ .await
+ .ok()
+ .and_then(|body| body.error)
+ .unwrap_or_default();
+ anyhow::bail!("provider token exchange failed with status {status} and error {error:?}");
+ }
+ let token: TokenResponse = response
+ .json()
+ .await
+ .map_err(|_| anyhow::anyhow!("provider token response has no id_token"))?;
+ Ok(token.id_token)
+}
+
+pub async fn sign_in(
+ http: &reqwest::Client,
+ config: &AdminConfig,
+ id_token: &str,
+ nonce: &str,
+) -> Result<SsoSignInResponse, ApiError> {
+ let response = with_proxy_client_ip_header(
+ http.post(format!("{}/admin/sso/sign-in", config.api_endpoint)),
+ config,
+ )
+ .header("Authorization", admin_client_basic_auth(config))
+ .json(&SignInRequest { id_token, nonce })
+ .send()
+ .await
+ .map_err(|error| ApiError::Network(error.to_string()))?;
+ let status = response.status();
+ if !status.is_success() {
+ let body = response.text().await.unwrap_or_default();
+ return Err(ApiError::http(status.as_u16(), body));
+ }
+ response
+ .json()
+ .await
+ .map_err(|error| ApiError::Parse(error.to_string()))
+}
diff --git a/fluxer_admin/src/state.rs b/fluxer_admin/src/state.rs
index 53fcce0b5..353912525 100644
--- a/fluxer_admin/src/state.rs
+++ b/fluxer_admin/src/state.rs
@@ -9,6 +9,7 @@ use crate::{
},
},
config::AdminConfig,
+ sso::{self, ProviderMetadata},
};
use std::{
sync::{Arc, Mutex},
@@ -18,6 +19,7 @@ use std::{
const PREMIUM_BRANDING_TTL: Duration = Duration::from_secs(60);
const ACCOUNT_IDENTITY_TTL: Duration = Duration::from_secs(60);
const ACCOUNT_IDENTITY_RETRY_TTL: Duration = Duration::from_secs(10);
+const SSO_DISCOVERY_TTL: Duration = Duration::from_secs(3600);
#[derive(Clone)]
pub struct AppState {
@@ -30,6 +32,7 @@ struct AppStateInner {
premium_branding: Mutex<Option<(Instant, PremiumBranding)>>,
account_identity: Mutex<Option<(Instant, AccountIdentitySettings)>>,
report_reasons: Mutex<Option<Arc<[ReportReasonEntry]>>>,
+ sso_provider: Mutex<Option<(Instant, ProviderMetadata)>>,
}
impl AppState {
@@ -45,6 +48,7 @@ impl AppState {
premium_branding: Mutex::new(None),
account_identity: Mutex::new(None),
report_reasons: Mutex::new(None),
+ sso_provider: Mutex::new(None),
}),
}
}
@@ -175,6 +179,35 @@ impl AppState {
settings
}
+ pub async fn sso_provider(&self) -> Option<ProviderMetadata> {
+ let sso = self.config().sso.as_ref()?;
+ let cached = self
+ .inner
+ .sso_provider
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .as_ref()
+ .filter(|(fetched_at, _)| fetched_at.elapsed() < SSO_DISCOVERY_TTL)
+ .map(|(_, metadata)| metadata.clone());
+ if let Some(metadata) = cached {
+ return Some(metadata);
+ }
+ let metadata = match sso::discover(self.http_client(), sso).await {
+ Ok(metadata) => metadata,
+ Err(error) => {
+ tracing::error!(%error, issuer = %sso.issuer, "SSO provider discovery failed");
+ return None;
+ }
+ };
+ *self
+ .inner
+ .sso_provider
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner()) =
+ Some((Instant::now(), metadata.clone()));
+ Some(metadata)
+ }
+
pub async fn report_reasons(
&self,
client: &AdminApiClient,
diff --git a/fluxer_admin/src/templates/pages/login.rs b/fluxer_admin/src/templates/pages/login.rs
index 748cd9718..36a647690 100644
--- a/fluxer_admin/src/templates/pages/login.rs
+++ b/fluxer_admin/src/templates/pages/login.rs
@@ -43,14 +43,25 @@ pub fn login_page(
div { (error) }
}
}
- a href={(base) "/auth/start"} role="button"
- class="inline-flex items-center justify-center gap-2 \
- font-medium rounded-lg transition-all duration-150 \
- focus:outline-none focus:ring-2 focus:ring-offset-2 \
- bg-neutral-900 text-white hover:bg-neutral-800 \
- px-4 py-2 text-base w-full sm:w-fit \
- focus:ring-offset-white" {
- span { "Sign in with " (product_name(branding)) }
+ @if let Some(sso) = &config.sso {
+ div class="flex flex-col gap-3 items-center w-full" {
+ (fluxer_sign_in_button(base, branding))
+ a href={(base) "/sso/start"} role="button"
+ class="inline-flex items-center justify-center gap-2 \
+ font-medium rounded-lg transition-all duration-150 \
+ focus:outline-none focus:ring-2 focus:ring-offset-2 \
+ bg-neutral-50 text-neutral-700 hover:text-neutral-900 \
+ border border-neutral-300 hover:border-neutral-400 \
+ px-4 py-2 text-base w-full sm:w-fit \
+ focus:ring-offset-white" {
+ span {
+ "Sign in with "
+ (sso.display_name.as_deref().unwrap_or("single sign-on"))
+ }
+ }
+ }
+ } @else {
+ (fluxer_sign_in_button(base, branding))
}
}
}
@@ -60,3 +71,17 @@ pub fn login_page(
}
}
}
+
+fn fluxer_sign_in_button(base: &str, branding: Option<&PremiumBranding>) -> Markup {
+ html! {
+ a href={(base) "/auth/start"} role="button"
+ class="inline-flex items-center justify-center gap-2 \
+ font-medium rounded-lg transition-all duration-150 \
+ focus:outline-none focus:ring-2 focus:ring-offset-2 \
+ bg-neutral-900 text-white hover:bg-neutral-800 \
+ px-4 py-2 text-base w-full sm:w-fit \
+ focus:ring-offset-white" {
+ span { "Sign in with " (product_name(branding)) }
+ }
+ }
+}
diff --git a/fluxer_api/src/api/Config.ts b/fluxer_api/src/api/Config.ts
index f4487dd22..8c1d4c41e 100644
--- a/fluxer_api/src/api/Config.ts
+++ b/fluxer_api/src/api/Config.ts
@@ -575,6 +575,10 @@ export function buildAPIConfigFromMaster(master: MasterConfig): APIConfig {
},
admin: {
oauthClientSecret: master.services.admin.oauth_client_secret,
+ sso: {
+ issuer: master.services.admin.sso.issuer,
+ clientId: master.services.admin.sso.client_id,
+ },
},
auth: {
sudoModeSecret: master.auth.sudo_mode_secret,
diff --git a/fluxer_api/src/api/admin/AdminSsoSignIn.ts b/fluxer_api/src/api/admin/AdminSsoSignIn.ts
new file mode 100644
index 000000000..a3e5d6971
--- /dev/null
+++ b/fluxer_api/src/api/admin/AdminSsoSignIn.ts
@@ -0,0 +1,230 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createHash, timingSafeEqual} from 'node:crypto';
+import {recordAdminWrite} from '@app/api/admin/AdminAuditRecorder';
+import {getOidcJwks} from '@app/api/auth/services/OidcJwks';
+import {acceptedIssuers, tryDiscoverOidcProviderMetadata} from '@app/api/auth/services/SsoUtils';
+import {createApplicationID, createUserID, type UserID} from '@app/api/BrandedTypes';
+import {Config} from '@app/api/Config';
+import {isHttpsSsoUrl} from '@app/api/instance/SsoConfigValidation';
+import {Logger} from '@app/api/Logger';
+import type {HonoEnv} from '@app/api/types/HonoEnv';
+import {isAccountClosed, isAccountDisabled, isTemporarilyBanned} from '@app/api/user/UserHelpers';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {ADMIN_OAUTH2_APPLICATION_ID} from '@fluxer/constants/src/Core';
+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
+import {SsoProviderUnavailableError} from '@fluxer/errors/src/domains/auth/SsoProviderUnavailableError';
+import {FeatureTemporarilyDisabledError} from '@fluxer/errors/src/domains/core/FeatureTemporarilyDisabledError';
+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
+import {MissingPermissionsError} from '@fluxer/errors/src/domains/core/MissingPermissionsError';
+import {InvalidClientError} from '@fluxer/errors/src/domains/oauth/InvalidClientError';
+import type {AdminSsoSignInResponse} from '@fluxer/schema/src/domains/admin/AdminSsoSchemas';
+import type {Context} from 'hono';
+import {ms} from 'itty-time';
+import {errors as JoseErrors, jwtVerify} from 'jose';
+
+interface AdminSsoConfig {
+ issuer: string;
+ clientId: string;
+}
+
+interface AdminSsoProvider {
+ jwksUri: string;
+ algorithms: Array<string>;
+}
+
+interface DiscoveryCacheEntry {
+ provider: AdminSsoProvider | null;
+ fetchedAt: number;
+}
+
+const ALLOWED_ID_TOKEN_ALGS = new Set([
+ 'RS256',
+ 'RS384',
+ 'RS512',
+ 'PS256',
+ 'PS384',
+ 'PS512',
+ 'ES256',
+ 'ES384',
+ 'ES512',
+ 'EdDSA',
+]);
+const DISCOVERY_FRESH_MS = ms('1 hour');
+const DISCOVERY_FAILURE_FRESH_MS = ms('1 minute');
+const CLOCK_TOLERANCE_SECONDS = 10;
+const ID_TOKEN_TYPE = 'id-token';
+const FLUXER_ID_CLAIM = 'fluxer_id';
+const FLUXER_ID_PATTERN = /^[1-9][0-9]{0,19}$/;
+const MAX_SNOWFLAKE = 0xffffffffffffffffn;
+const ADMIN_APPLICATION_ID = createApplicationID(ADMIN_OAUTH2_APPLICATION_ID);
+
+const discoveryCache = new Map<string, DiscoveryCacheEntry>();
+const discoveryRefreshes = new Map<string, Promise<AdminSsoProvider | null>>();
+
+export function resetAdminSsoCachesForTests(): void {
+ discoveryCache.clear();
+ discoveryRefreshes.clear();
+}
+
+class AdminSsoTokenRejected extends Error {}
+
+function adminSsoConfig(): AdminSsoConfig | null {
+ const {issuer, clientId} = Config.admin.sso;
+ return issuer && clientId ? {issuer, clientId} : null;
+}
+
+function misconfigured(reason: string): InputValidationError {
+ Logger.error({reason}, 'Admin SSO provider is misconfigured');
+ return InputValidationError.fromCode('sso', ValidationErrorCodes.SSO_MISCONFIGURED);
+}
+
+async function discoverProvider(issuer: string): Promise<AdminSsoProvider | null> {
+ const metadata = await tryDiscoverOidcProviderMetadata(issuer);
+ if (!metadata) return null;
+ if (!metadata.jwks_uri || !isHttpsSsoUrl(metadata.jwks_uri)) {
+ throw misconfigured('discovery has no https jwks_uri');
+ }
+ const algorithms = (metadata.id_token_signing_alg_values_supported ?? []).filter((alg) =>
+ ALLOWED_ID_TOKEN_ALGS.has(alg),
+ );
+ if (algorithms.length === 0) {
+ throw misconfigured('discovery advertises no supported ID token signing algorithm');
+ }
+ return {jwksUri: metadata.jwks_uri, algorithms};
+}
+
+async function loadProvider(issuer: string): Promise<AdminSsoProvider> {
+ const cached = discoveryCache.get(issuer);
+ const freshFor = cached?.provider ? DISCOVERY_FRESH_MS : DISCOVERY_FAILURE_FRESH_MS;
+ let provider = cached && Date.now() - cached.fetchedAt < freshFor ? cached.provider : undefined;
+ if (provider === undefined) {
+ let refresh = discoveryRefreshes.get(issuer);
+ if (!refresh) {
+ refresh = discoverProvider(issuer)
+ .then((discovered) => {
+ discoveryCache.set(issuer, {provider: discovered, fetchedAt: Date.now()});
+ return discovered;
+ })
+ .finally(() => discoveryRefreshes.delete(issuer));
+ discoveryRefreshes.set(issuer, refresh);
+ }
+ provider = await refresh;
+ }
+ if (!provider) {
+ throw new SsoProviderUnavailableError();
+ }
+ return provider;
+}
+
+function nonceMatches(actual: unknown, expected: string): boolean {
+ if (typeof actual !== 'string') return false;
+ const actualBytes = Buffer.from(actual, 'utf8');
+ const expectedBytes = Buffer.from(expected, 'utf8');
+ return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
+}
+
+function readFluxerIdClaim(idToken: string): UserID {
+ const segment = idToken.split('.')[1] ?? '';
+ const text = Buffer.from(segment, 'base64url').toString('utf8');
+ const parsed: unknown = JSON.parse(text, (key: string, value: unknown, context?: {source?: string}) =>
+ key === FLUXER_ID_CLAIM && typeof value === 'number' ? context?.source : value,
+ );
+ const raw =
+ typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>)[FLUXER_ID_CLAIM] : undefined;
+ if (typeof raw !== 'string' || !FLUXER_ID_PATTERN.test(raw) || BigInt(raw) > MAX_SNOWFLAKE) {
+ throw new AdminSsoTokenRejected('fluxer_id claim is not a snowflake');
+ }
+ return createUserID(BigInt(raw));
+}
+
+async function verifyAdminSsoIdToken(
+ config: AdminSsoConfig,
+ idToken: string,
+ expectedNonce: string,
+): Promise<{userId: UserID; expiresAt: number}> {
+ try {
+ const provider = await loadProvider(config.issuer);
+ const {payload} = await jwtVerify(idToken, await getOidcJwks(provider.jwksUri), {
+ issuer: acceptedIssuers(config.issuer),
+ audience: config.clientId,
+ algorithms: provider.algorithms,
+ clockTolerance: CLOCK_TOLERANCE_SECONDS,
+ maxTokenAge: '10 minutes',
+ requiredClaims: ['iat', 'exp', 'nonce'],
+ });
+ if (Array.isArray(payload.aud) && payload.aud.length > 1 && payload['azp'] !== config.clientId) {
+ throw new AdminSsoTokenRejected('azp does not match the client ID');
+ }
+ if (!nonceMatches(payload['nonce'], expectedNonce)) {
+ throw new AdminSsoTokenRejected('nonce mismatch');
+ }
+ if (payload['type'] !== undefined && payload['type'] !== ID_TOKEN_TYPE) {
+ throw new AdminSsoTokenRejected('token is not an ID token');
+ }
+ return {userId: readFluxerIdClaim(idToken), expiresAt: payload.exp ?? 0};
+ } catch (error) {
+ if (error instanceof SsoProviderUnavailableError || error instanceof InputValidationError) throw error;
+ if (error instanceof AdminSsoTokenRejected) {
+ Logger.warn({reason: error.message}, 'Admin SSO ID token refused');
+ } else if (error instanceof JoseErrors.JOSEError) {
+ Logger.warn(
+ {code: error.code, claim: error instanceof JoseErrors.JWTClaimValidationFailed ? error.claim : undefined},
+ 'Admin SSO ID token refused',
+ );
+ } else {
+ Logger.warn({reason: error instanceof Error ? error.name : 'unknown'}, 'Admin SSO ID token refused');
+ }
+ throw InputValidationError.fromCode('id_token', ValidationErrorCodes.INVALID_SSO_TOKEN);
+ }
+}
+
+async function claimNonceOnce(ctx: Context<HonoEnv>, nonce: string, expiresAt: number): Promise<void> {
+ const digest = createHash('sha256').update(nonce).digest('hex');
+ const ttl = Math.max(1, expiresAt - Math.floor(Date.now() / 1000) + CLOCK_TOLERANCE_SECONDS);
+ const lock = await ctx.get('apiContext').services.cache.acquireLock(`admin-sso:nonce:${digest}`, ttl);
+ if (lock === null) {
+ Logger.warn({reason: 'ID token already used'}, 'Admin SSO ID token refused');
+ throw InputValidationError.fromCode('id_token', ValidationErrorCodes.INVALID_SSO_TOKEN);
+ }
+}
+
+function refuse(userId: UserID, reason: string): never {
+ Logger.warn({user_id: userId.toString(), reason}, 'Admin SSO sign-in refused');
+ throw new MissingPermissionsError();
+}
+
+export async function signInWithAdminSso(
+ ctx: Context<HonoEnv>,
+ args: {authorizationHeader?: string; idToken: string; nonce: string},
+): Promise<AdminSsoSignInResponse> {
+ const config = adminSsoConfig();
+ if (!config) {
+ throw new FeatureTemporarilyDisabledError();
+ }
+ const oauth2Service = ctx.get('oauth2Service');
+ const application = await oauth2Service.authenticateClient({authorizationHeader: args.authorizationHeader});
+ if (application.applicationId !== ADMIN_APPLICATION_ID || !application.clientSecretHash) {
+ throw new InvalidClientError();
+ }
+ const {userId, expiresAt} = await verifyAdminSsoIdToken(config, args.idToken, args.nonce);
+ await claimNonceOnce(ctx, args.nonce, expiresAt);
+ const user = await ctx.get('apiContext').services.users.findUnique(userId);
+ if (!user) refuse(userId, 'unknown user');
+ if (user.isBot) refuse(userId, 'bot account');
+ if (isAccountClosed(user) || isAccountDisabled(user) || isTemporarilyBanned(user)) {
+ refuse(userId, 'account closed, disabled or banned');
+ }
+ if (!user.acls.has(AdminACLs.AUTHENTICATE) && !user.acls.has(AdminACLs.WILDCARD)) {
+ refuse(userId, 'missing admin:authenticate');
+ }
+ ctx.set('adminUserId', user.id);
+ await recordAdminWrite(ctx, {
+ targetType: 'user',
+ targetId: user.id,
+ action: 'sso_sign_in',
+ metadata: {provider_id: config.issuer},
+ });
+ const tokens = await oauth2Service.issueAdminSsoTokens(application, user.id);
+ return {user_id: user.id.toString(), ...tokens};
+}
diff --git a/fluxer_api/src/api/admin/controllers/AdminSsoAdminController.ts b/fluxer_api/src/api/admin/controllers/AdminSsoAdminController.ts
new file mode 100644
index 000000000..71427232d
--- /dev/null
+++ b/fluxer_api/src/api/admin/controllers/AdminSsoAdminController.ts
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {signInWithAdminSso} from '@app/api/admin/AdminSsoSignIn';
+import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';
+import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
+import {RateLimitConfigs} from '@app/api/RateLimitConfig';
+import type {HonoApp} from '@app/api/types/HonoEnv';
+import {Validator} from '@app/api/Validator';
+import {AdminSsoSignInRequest, AdminSsoSignInResponse} from '@fluxer/schema/src/domains/admin/AdminSsoSchemas';
+
+export function AdminSsoAdminController(app: HonoApp) {
+ app.post(
+ '/admin/sso/sign-in',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_SSO_SIGN_IN),
+ Validator('json', AdminSsoSignInRequest),
+ OpenAPI({
+ operationId: 'exchange_admin_sso_token',
+ summary: 'Exchange admin SSO ID token',
+ responseSchema: AdminSsoSignInResponse,
+ statusCode: 200,
+ security: [],
+ tags: 'Admin',
+ description:
+ 'Verifies an ID token from the admin sign-on provider and returns an admin panel access token for the Fluxer account in its fluxer_id claim. Only the admin panel calls it, with its OAuth2 client ID and secret as HTTP Basic auth. The account must already have admin:authenticate.',
+ }),
+ async (ctx) => {
+ const body = ctx.req.valid('json');
+ const result = await signInWithAdminSso(ctx, {
+ authorizationHeader: ctx.req.header('authorization') ?? undefined,
+ idToken: body.id_token,
+ nonce: body.nonce,
+ });
+ return ctx.json(result);
+ },
+ );
+}
diff --git a/fluxer_api/src/api/admin/controllers/index.ts b/fluxer_api/src/api/admin/controllers/index.ts
index fe9aabcd4..8a6a7191d 100644
--- a/fluxer_api/src/api/admin/controllers/index.ts
+++ b/fluxer_api/src/api/admin/controllers/index.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {AdminApiKeyAdminController} from '@app/api/admin/controllers/AdminApiKeyAdminController';
+import {AdminSsoAdminController} from '@app/api/admin/controllers/AdminSsoAdminController';
import {ApplicationAdminController} from '@app/api/admin/controllers/ApplicationAdminController';
import {ArchiveAdminController} from '@app/api/admin/controllers/ArchiveAdminController';
import {AssetAdminController} from '@app/api/admin/controllers/AssetAdminController';
@@ -32,6 +33,7 @@ import type {HonoApp} from '@app/api/types/HonoEnv';
export function registerAdminControllers(app: HonoApp) {
AdminApiKeyAdminController(app);
+ AdminSsoAdminController(app);
ApplicationAdminController(app);
UserAdminController(app);
BadgeAdminController(app);
diff --git a/fluxer_api/src/api/admin/tests/AdminSsoSignIn.test.ts b/fluxer_api/src/api/admin/tests/AdminSsoSignIn.test.ts
new file mode 100644
index 000000000..3f41856ba
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/AdminSsoSignIn.test.ts
@@ -0,0 +1,194 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {
+ ADMIN_CLIENT_BASIC_AUTH,
+ ADMIN_SSO_KID,
+ ADMIN_SSO_NONCE,
+ type AdminSsoProvider,
+ adminSsoSignInRequest,
+ idTokenClaimsJson,
+ useAdminSsoProvider,
+} from '@app/api/admin/tests/AdminSsoTestUtils';
+import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {Config} from '@app/api/Config';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {ADMIN_OAUTH2_APPLICATION_ID} from '@fluxer/constants/src/Core';
+import {generateKeyPair} from 'jose';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+interface SignInBody {
+ user_id: string;
+ access_token: string;
+ token_type: string;
+ expires_in: number;
+ scope: string;
+ code?: string;
+ error?: string;
+}
+
+function isDoubleExact(id: string): boolean {
+ return Number(BigInt(id)).toString() === id;
+}
+
+describe('Admin SSO sign-in', () => {
+ let harness: ApiTestHarness;
+ let provider: AdminSsoProvider;
+ let admin: TestAccount;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+ beforeEach(async () => {
+ await harness.reset();
+ provider = await useAdminSsoProvider();
+ admin = await createTestAccount(harness);
+ while (isDoubleExact(admin.userId)) {
+ admin = await createTestAccount(harness);
+ }
+ admin = await setUserACLs(harness, admin, ['admin:authenticate']);
+ });
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
+
+ async function signIn(claimsJson: string, options: {nonce?: string; alg?: string; key?: CryptoKey} = {}) {
+ const idToken = await provider.signRawClaims(claimsJson, {alg: options.alg, key: options.key});
+ const response = await adminSsoSignInRequest(harness, {idToken, nonce: options.nonce});
+ return {status: response.status, body: (await response.json()) as SignInBody, idToken};
+ }
+
+ it('signs in an admin and returns a working admin bearer token', async () => {
+ const {status, body} = await signIn(idTokenClaimsJson(admin.userId));
+ expect(status).toBe(200);
+ expect(body.user_id).toBe(admin.userId);
+ expect(body.token_type).toBe('Bearer');
+ expect(body.scope).toBe('identify email');
+ const me = await harness.requestJson({
+ path: '/admin/users/@me',
+ headers: {Authorization: `Bearer ${body.access_token}`},
+ });
+ expect(me.status).toBe(200);
+ });
+
+ it('keeps every digit of a fluxer_id sent as a bare JSON number', async () => {
+ expect(isDoubleExact(admin.userId)).toBe(false);
+ const {status, body} = await signIn(idTokenClaimsJson(admin.userId));
+ expect(status).toBe(200);
+ expect(body.user_id).toBe(admin.userId);
+ });
+
+ it('accepts fluxer_id as a decimal string', async () => {
+ const {status, body} = await signIn(idTokenClaimsJson(`"${admin.userId}"`));
+ expect(status).toBe(200);
+ expect(body.user_id).toBe(admin.userId);
+ });
+
+ it.each(['1.5', '-1', '1e21', '"abc"', '"0"', 'null'])('refuses fluxer_id %s', async (fluxerId) => {
+ const {status, body} = await signIn(idTokenClaimsJson(fluxerId));
+ expect(status).toBe(400);
+ expect(body.code).toBe('INVALID_FORM_BODY');
+ });
+
+ it('refuses a token signed by another key with the same kid', async () => {
+ const other = await generateKeyPair('RS256');
+ const {status} = await signIn(idTokenClaimsJson(admin.userId), {key: other.privateKey});
+ expect(status).toBe(400);
+ });
+
+ it.each([
+ ['a wrong issuer', {iss: 'https://1.1.1.1/other'}],
+ ['a wrong audience', {aud: 'someone-else'}],
+ ['an expired token', {exp: Math.floor(Date.now() / 1000) - 60}],
+ ['a future nbf', {nbf: Math.floor(Date.now() / 1000) + 600}],
+ ['a missing nonce', {nonce: undefined}],
+ ['an access token', {type: 'access-token'}],
+ ['a second audience without azp', {aud: ['admin-sso-test-client', 'other-client']}],
+ ])('refuses %s', async (_label, overrides) => {
+ const {status} = await signIn(idTokenClaimsJson(admin.userId, overrides));
+ expect(status).toBe(400);
+ });
+
+ it('refuses a nonce that does not match', async () => {
+ const {status} = await signIn(idTokenClaimsJson(admin.userId), {nonce: 'admin-sso-other-nonce-0001'});
+ expect(status).toBe(400);
+ });
+
+ it('refuses an unsigned token', async () => {
+ const header = Buffer.from(JSON.stringify({alg: 'none', typ: 'JWT'})).toString('base64url');
+ const payload = Buffer.from(idTokenClaimsJson(admin.userId)).toString('base64url');
+ const response = await adminSsoSignInRequest(harness, {idToken: `${header}.${payload}.`});
+ expect(response.status).toBe(400);
+ });
+
+ it('refuses an algorithm the provider does not advertise', async () => {
+ const rs384 = await generateKeyPair('RS384');
+ const {status} = await signIn(idTokenClaimsJson(admin.userId), {alg: 'RS384', key: rs384.privateKey});
+ expect(status).toBe(400);
+ });
+
+ it('loads the key set again when the provider rotates its key', async () => {
+ expect((await signIn(idTokenClaimsJson(admin.userId))).status).toBe(200);
+ const before = provider.jwksRequests();
+ const rotatedKey = await provider.rotate();
+ const nonce = 'admin-sso-test-nonce-0002';
+ const idToken = await provider.signRawClaims(idTokenClaimsJson(admin.userId, {nonce}), {
+ key: rotatedKey,
+ kid: `${ADMIN_SSO_KID}-rotated`,
+ });
+ const response = await adminSsoSignInRequest(harness, {idToken, nonce});
+ expect(response.status).toBe(200);
+ expect(provider.jwksRequests()).toBeGreaterThan(before);
+ });
+
+ it('refuses the same token twice', async () => {
+ const {status, idToken} = await signIn(idTokenClaimsJson(admin.userId));
+ expect(status).toBe(200);
+ const replay = await adminSsoSignInRequest(harness, {idToken});
+ expect(replay.status).toBe(400);
+ });
+
+ it('refuses the same token again with its signature encoded another way', async () => {
+ const {status, idToken} = await signIn(idTokenClaimsJson(admin.userId));
+ expect(status).toBe(200);
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
+ const last = idToken.at(-1) ?? '';
+ const variant = `${idToken.slice(0, -1)}${alphabet[(alphabet.indexOf(last) ^ 1) % 64]}`;
+ const replay = await adminSsoSignInRequest(harness, {idToken: variant});
+ expect(replay.status).toBe(400);
+ });
+
+ it('refuses an account without admin ACLs', async () => {
+ const member = await createTestAccount(harness);
+ const {status, body} = await signIn(idTokenClaimsJson(member.userId));
+ expect(status).toBe(403);
+ expect(body.code).toBe('MISSING_PERMISSIONS');
+ });
+
+ it('refuses an unknown fluxer_id', async () => {
+ const {status, body} = await signIn(idTokenClaimsJson('1130650140672000001'));
+ expect(status).toBe(403);
+ expect(body.code).toBe('MISSING_PERMISSIONS');
+ });
+
+ it('refuses a wrong client secret before it looks at the token', async () => {
+ const idToken = await provider.signRawClaims(idTokenClaimsJson(admin.userId));
+ const auth = `Basic ${Buffer.from(`${ADMIN_OAUTH2_APPLICATION_ID}:wrong-secret`).toString('base64')}`;
+ const response = await adminSsoSignInRequest(harness, {idToken, auth});
+ expect(response.status).toBe(400);
+ expect(((await response.json()) as SignInBody).error).toBe('invalid_client');
+ expect(provider.jwksRequests()).toBe(0);
+ const retry = await adminSsoSignInRequest(harness, {idToken, auth: ADMIN_CLIENT_BASIC_AUTH});
+ expect(retry.status).toBe(200);
+ });
+
+ it('is off when the API has no admin SSO issuer', async () => {
+ const previous = Config.admin.sso.issuer;
+ Config.admin.sso.issuer = '';
+ try {
+ const {status} = await signIn(idTokenClaimsJson(admin.userId), {nonce: ADMIN_SSO_NONCE});
+ expect(status).toBe(403);
+ } finally {
+ Config.admin.sso.issuer = previous;
+ }
+ });
+});
diff --git a/fluxer_api/src/api/admin/tests/AdminSsoTestUtils.ts b/fluxer_api/src/api/admin/tests/AdminSsoTestUtils.ts
new file mode 100644
index 000000000..374ab7df1
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/AdminSsoTestUtils.ts
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {server} from '@app/api/test/msw/server';
+import {ADMIN_OAUTH2_APPLICATION_ID} from '@fluxer/constants/src/Core';
+import {CompactSign, exportJWK, generateKeyPair, type JWK} from 'jose';
+import {HttpResponse, http} from 'msw';
+
+export const ADMIN_SSO_ISSUER = 'https://1.1.1.1/admin-sso';
+const ADMIN_SSO_CLIENT_ID = 'admin-sso-test-client';
+export const ADMIN_SSO_KID = 'admin-sso-key';
+
+export const ADMIN_CLIENT_BASIC_AUTH = `Basic ${Buffer.from(
+ `${ADMIN_OAUTH2_APPLICATION_ID}:test-admin-oauth-secret`,
+).toString('base64')}`;
+
+interface SignOptions {
+ key?: CryptoKey;
+ alg?: string;
+ kid?: string;
+}
+
+export interface AdminSsoProvider {
+ privateKey: CryptoKey;
+ jwksRequests: () => number;
+ rotate: () => Promise<CryptoKey>;
+ signRawClaims: (json: string, options?: SignOptions) => Promise<string>;
+}
+
+export async function useAdminSsoProvider(): Promise<AdminSsoProvider> {
+ let {publicKey, privateKey} = await generateKeyPair('RS256');
+ let keys: Array<JWK> = [{...(await exportJWK(publicKey)), kid: ADMIN_SSO_KID, alg: 'RS256', use: 'sig'}];
+ let jwksRequests = 0;
+ server.use(
+ http.get(`${ADMIN_SSO_ISSUER}/.well-known/openid-configuration`, () =>
+ HttpResponse.json({
+ issuer: ADMIN_SSO_ISSUER,
+ authorization_endpoint: `${ADMIN_SSO_ISSUER}/authorize`,
+ token_endpoint: `${ADMIN_SSO_ISSUER}/token`,
+ jwks_uri: `${ADMIN_SSO_ISSUER}/jwks.json`,
+ id_token_signing_alg_values_supported: ['RS256'],
+ request_object_signing_alg_values_supported: ['none'],
+ }),
+ ),
+ http.get(`${ADMIN_SSO_ISSUER}/jwks.json`, () => {
+ jwksRequests += 1;
+ return HttpResponse.json({keys});
+ }),
+ );
+ const provider: AdminSsoProvider = {
+ privateKey,
+ jwksRequests: () => jwksRequests,
+ async rotate() {
+ ({publicKey, privateKey} = await generateKeyPair('RS256'));
+ keys = [{...(await exportJWK(publicKey)), kid: `${ADMIN_SSO_KID}-rotated`, alg: 'RS256', use: 'sig'}];
+ provider.privateKey = privateKey;
+ return privateKey;
+ },
+ async signRawClaims(json, options = {}) {
+ return new CompactSign(new TextEncoder().encode(json))
+ .setProtectedHeader({alg: options.alg ?? 'RS256', kid: options.kid ?? ADMIN_SSO_KID, typ: 'JWT'})
+ .sign(options.key ?? provider.privateKey);
+ },
+ };
+ return provider;
+}
+
+export function idTokenClaimsJson(fluxerId: string, overrides: Record<string, unknown> = {}): string {
+ const now = Math.floor(Date.now() / 1000);
+ const claims = {
+ iss: ADMIN_SSO_ISSUER,
+ aud: ADMIN_SSO_CLIENT_ID,
+ sub: `subject-${fluxerId}`,
+ iat: now,
+ exp: now + 300,
+ nonce: 'admin-sso-test-nonce-0001',
+ type: 'id-token',
+ name: 'Test Admin',
+ ...overrides,
+ };
+ const json = JSON.stringify({...claims, fluxer_id: '__FLUXER_ID__'});
+ return json.replace('"__FLUXER_ID__"', fluxerId);
+}
+
+export const ADMIN_SSO_NONCE = 'admin-sso-test-nonce-0001';
+
+export function adminSsoSignInRequest(
+ harness: ApiTestHarness,
+ args: {idToken: string; nonce?: string; auth?: string},
+): Promise<Response> {
+ return harness.requestJson({
+ path: '/admin/sso/sign-in',
+ method: 'POST',
+ headers: {Authorization: args.auth ?? ADMIN_CLIENT_BASIC_AUTH},
+ body: {id_token: args.idToken, nonce: args.nonce ?? ADMIN_SSO_NONCE},
+ });
+}
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/AdminAuditRouteCoverage.test.ts b/fluxer_api/src/api/admin/tests/audit_coverage/AdminAuditRouteCoverage.test.ts
index a7883081f..fd5dc07f3 100644
--- a/fluxer_api/src/api/admin/tests/audit_coverage/AdminAuditRouteCoverage.test.ts
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/AdminAuditRouteCoverage.test.ts
@@ -3,6 +3,7 @@
import {registerAdminControllers} from '@app/api/admin/controllers/index';
import {AdminApiKeyAdminAuditCases} from '@app/api/admin/tests/audit_coverage/AdminApiKeyAdminAuditCases';
import {adminAuditCaseShape} from '@app/api/admin/tests/audit_coverage/AdminAuditCoverage';
+import {AdminSsoAdminAuditCases} from '@app/api/admin/tests/audit_coverage/AdminSsoAdminAuditCases';
import {ApplicationAdminAuditCases} from '@app/api/admin/tests/audit_coverage/ApplicationAdminAuditCases';
import {ArchiveAdminAuditCases} from '@app/api/admin/tests/audit_coverage/ArchiveAdminAuditCases';
import {AssetAdminAuditCases} from '@app/api/admin/tests/audit_coverage/AssetAdminAuditCases';
@@ -36,6 +37,7 @@ import {describe, expect, test} from 'vitest';
const ALL_CASES = [
...AdminApiKeyAdminAuditCases,
+ ...AdminSsoAdminAuditCases,
...ApplicationAdminAuditCases,
...ArchiveAdminAuditCases,
...AssetAdminAuditCases,
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/AdminSsoAdminAuditCases.ts b/fluxer_api/src/api/admin/tests/audit_coverage/AdminSsoAdminAuditCases.ts
new file mode 100644
index 000000000..d053e566b
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/AdminSsoAdminAuditCases.ts
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {
+ ADMIN_CLIENT_BASIC_AUTH,
+ ADMIN_SSO_ISSUER,
+ ADMIN_SSO_NONCE,
+ idTokenClaimsJson,
+ useAdminSsoProvider,
+} from '@app/api/admin/tests/AdminSsoTestUtils';
+import type {AdminAuditCoverageCase} from '@app/api/admin/tests/audit_coverage/AdminAuditCoverage';
+
+export const AdminSsoAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> = [
+ {
+ method: 'POST',
+ route: '/admin/sso/sign-in',
+ async prepare({admin}) {
+ const provider = await useAdminSsoProvider();
+ const idToken = await provider.signRawClaims(idTokenClaimsJson(admin.userId));
+ return {
+ request: {
+ path: '/admin/sso/sign-in',
+ headers: {Authorization: ADMIN_CLIENT_BASIC_AUTH},
+ body: {id_token: idToken, nonce: ADMIN_SSO_NONCE},
+ },
+ expected: {
+ action: 'sso_sign_in',
+ targetType: 'user',
+ targetId: admin.userId,
+ metadata: {provider_id: ADMIN_SSO_ISSUER},
+ },
+ };
+ },
+ },
+];
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/AdminSsoAdminAuditCoverage.test.ts b/fluxer_api/src/api/admin/tests/audit_coverage/AdminSsoAdminAuditCoverage.test.ts
new file mode 100644
index 000000000..dfff15b6e
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/AdminSsoAdminAuditCoverage.test.ts
@@ -0,0 +1,6 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {describeAdminAuditCoverage} from '@app/api/admin/tests/audit_coverage/AdminAuditCoverage';
+import {AdminSsoAdminAuditCases} from '@app/api/admin/tests/audit_coverage/AdminSsoAdminAuditCases';
+
+describeAdminAuditCoverage('AdminSsoAdminController', AdminSsoAdminAuditCases);
diff --git a/fluxer_api/src/api/auth/services/OidcJwks.ts b/fluxer_api/src/api/auth/services/OidcJwks.ts
new file mode 100644
index 000000000..3a95e2edc
--- /dev/null
+++ b/fluxer_api/src/api/auth/services/OidcJwks.ts
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {sendProviderRequest} from '@app/api/auth/services/SsoUtils';
+import {Logger} from '@app/api/Logger';
+import {EXTERNAL_RESPONSE_LIMITS} from '@app/api/utils/ExternalResponseLimits';
+import * as FetchUtils from '@app/api/utils/FetchUtils';
+import {isJsonRecord, parseJsonWithGuard} from '@app/api/utils/JsonBoundaryUtils';
+import {SsoProviderUnavailableError} from '@fluxer/errors/src/domains/auth/SsoProviderUnavailableError';
+import {formatUrlForDiagnostics} from '@pkgs/http_client/src/HttpClientDiagnostics';
+import {ms} from 'itty-time';
+import {
+ type CryptoKey,
+ createLocalJWKSet,
+ type FlattenedJWSInput,
+ errors as JoseErrors,
+ type JSONWebKeySet,
+ type JWSHeaderParameters,
+} from 'jose';
+
+interface RemoteJwkSetResolver {
+ (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput): Promise<CryptoKey>;
+ coolingDown: boolean;
+ fresh: boolean;
+ reloading: boolean;
+ reload: () => Promise<void>;
+ jwks: () => JSONWebKeySet | undefined;
+}
+
+interface JwksCacheEntry {
+ jwks: RemoteJwkSetResolver;
+ cachedAt: number;
+}
+
+const JWKS_CACHE_TTL_MS = ms('1 hour');
+const JWKS_CACHE_SWEEP_SIZE = 10;
+
+const jwksCache = new Map<string, JwksCacheEntry>();
+const jwksCreations = new Map<string, Promise<RemoteJwkSetResolver>>();
+
+export function resetOidcJwksCachesForTests(): void {
+ jwksCache.clear();
+ jwksCreations.clear();
+}
+
+function isJsonWebKeySet(value: unknown): value is JSONWebKeySet {
+ if (!isJsonRecord(value)) return false;
+ const keys = value['keys'];
+ return Array.isArray(keys) && keys.every(isJsonRecord);
+}
+
+export async function getOidcJwks(jwksUrl: string): Promise<RemoteJwkSetResolver> {
+ const cached = jwksCache.get(jwksUrl);
+ if (cached && Date.now() - cached.cachedAt < JWKS_CACHE_TTL_MS) {
+ return cached.jwks;
+ }
+ let creation = jwksCreations.get(jwksUrl);
+ if (!creation) {
+ creation = createJwks(jwksUrl).finally(() => jwksCreations.delete(jwksUrl));
+ jwksCreations.set(jwksUrl, creation);
+ }
+ return creation;
+}
+
+async function fetchJwks(jwksUrl: string): Promise<JSONWebKeySet> {
+ const response = await sendProviderRequest({
+ url: jwksUrl,
+ method: 'GET',
+ headers: {Accept: 'application/json'},
+ timeout: ms('15 seconds'),
+ serviceName: 'sso_jwks',
+ });
+ if (response.status < 200 || response.status >= 300) {
+ FetchUtils.discardResponseBody(response.stream, response.status);
+ if (response.status >= 500) {
+ Logger.warn({status: response.status, url: formatUrlForDiagnostics(jwksUrl)}, 'SSO keys request failed');
+ throw new SsoProviderUnavailableError();
+ }
+ throw new Error(`Failed to fetch JWKS: HTTP ${response.status}`);
+ }
+ const rawBody = await FetchUtils.streamToStringWithLimit(response.stream, {
+ maxBytes: EXTERNAL_RESPONSE_LIMITS.ssoJwksBytes,
+ headers: response.headers,
+ url: jwksUrl,
+ description: 'SSO JWKS response',
+ });
+ const parsed = parseJsonWithGuard(rawBody, isJsonWebKeySet);
+ if (!parsed) {
+ throw new Error('SSO JWKS response was not a JSON Web Key Set');
+ }
+ return parsed;
+}
+
+async function createJwks(jwksUrl: string): Promise<RemoteJwkSetResolver> {
+ const now = Date.now();
+ let currentJwks = await fetchJwks(jwksUrl);
+ let currentResolver = createLocalJWKSet(currentJwks);
+ let fetchedAt = now;
+ let pendingReload: Promise<void> | null = null;
+ let jwks!: RemoteJwkSetResolver;
+ const reload = async (): Promise<void> => {
+ pendingReload ??= (async () => {
+ currentJwks = await fetchJwks(jwksUrl);
+ currentResolver = createLocalJWKSet(currentJwks);
+ fetchedAt = Date.now();
+ jwksCache.set(jwksUrl, {jwks, cachedAt: fetchedAt});
+ })().finally(() => {
+ pendingReload = null;
+ });
+ await pendingReload;
+ };
+ jwks = (async (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput) => {
+ if (Date.now() - fetchedAt >= JWKS_CACHE_TTL_MS) {
+ await reload();
+ }
+ try {
+ return await currentResolver(protectedHeader, token);
+ } catch (error) {
+ if (error instanceof JoseErrors.JWKSNoMatchingKey) {
+ await reload();
+ return currentResolver(protectedHeader, token);
+ }
+ throw error;
+ }
+ }) as RemoteJwkSetResolver;
+ Object.defineProperties(jwks, {
+ coolingDown: {
+ get: () => false,
+ enumerable: true,
+ configurable: false,
+ },
+ fresh: {
+ get: () => Date.now() - fetchedAt < JWKS_CACHE_TTL_MS,
+ enumerable: true,
+ configurable: false,
+ },
+ reloading: {
+ get: () => pendingReload != null,
+ enumerable: true,
+ configurable: false,
+ },
+ reload: {
+ value: reload,
+ enumerable: true,
+ configurable: false,
+ writable: false,
+ },
+ jwks: {
+ value: () => currentJwks,
+ enumerable: true,
+ configurable: false,
+ writable: false,
+ },
+ });
+ jwksCache.set(jwksUrl, {jwks, cachedAt: now});
+ if (jwksCache.size > JWKS_CACHE_SWEEP_SIZE) {
+ for (const [url, entry] of jwksCache.entries()) {
+ if (now - entry.cachedAt >= JWKS_CACHE_TTL_MS) {
+ jwksCache.delete(url);
+ }
+ }
+ }
+ return jwks;
+}
diff --git a/fluxer_api/src/api/auth/services/SsoService.ts b/fluxer_api/src/api/auth/services/SsoService.ts
index 62e28897c..e04aecf52 100644
--- a/fluxer_api/src/api/auth/services/SsoService.ts
+++ b/fluxer_api/src/api/auth/services/SsoService.ts
@@ -8,6 +8,7 @@ import {assertAccountCreationPastSetup, maybeAutoJoinInvite} from '@app/api/auth
import * as AuthSession from '@app/api/auth/AuthSession';
import * as AuthUtility from '@app/api/auth/AuthUtility';
import {assertEmailNotBlocklisted, isEmailBlocklisted} from '@app/api/auth/EmailBlocklist';
+import {getOidcJwks, resetOidcJwksCachesForTests} from '@app/api/auth/services/OidcJwks';
import {
isLinkedToSsoProvider,
ssoIdentityTrait,
@@ -20,6 +21,7 @@ import {
type DiscoveredOidcProviderMetadata,
parseTokenEndpointResponse,
sanitizeSsoRedirectTo,
+ sendProviderRequest,
tryDiscoverOidcProviderMetadata,
} from '@app/api/auth/services/SsoUtils';
import {userHasMfa} from '@app/api/auth/services/SudoMethods';
@@ -38,12 +40,7 @@ import {
REGISTRATION_PENDING_APPROVAL_TRAIT,
} from '@app/api/instance/InstanceConfigRepository';
import {canJoinSingleCommunity, type SingleCommunityService} from '@app/api/instance/SingleCommunityService';
-import {
- deriveSsoRedirectUri,
- getSsoRequestUrlPolicy,
- isHttpsSsoUrl,
- isTestSsoProvider,
-} from '@app/api/instance/SsoConfigValidation';
+import {deriveSsoRedirectUri, isHttpsSsoUrl, isTestSsoProvider} from '@app/api/instance/SsoConfigValidation';
import type {InviteService} from '@app/api/invite/InviteService';
import {Logger} from '@app/api/Logger';
import {profileSubstringBlocklistCache} from '@app/api/middleware/ProfileSubstringBlocklistCache';
@@ -65,7 +62,7 @@ import {USERNAME_MODE_DISCRIMINATOR} from '@app/api/user/UserTag';
import {DOB_DEFERRED_TRAIT} from '@app/api/user/UserTraits';
import {EXTERNAL_RESPONSE_LIMITS} from '@app/api/utils/ExternalResponseLimits';
import * as FetchUtils from '@app/api/utils/FetchUtils';
-import {isJsonRecord, parseJsonRecord, parseJsonWithGuard} from '@app/api/utils/JsonBoundaryUtils';
+import {parseJsonRecord} from '@app/api/utils/JsonBoundaryUtils';
import {randomBase64Url} from '@app/api/utils/SecretHash';
import {generateRandomUsername} from '@app/api/utils/UsernameGenerator';
import {deriveUsernameFromDisplayName} from '@app/api/utils/UsernameSuggestionUtils';
@@ -83,18 +80,8 @@ import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
import {EmailType} from '@fluxer/schema/src/primitives/UserValidators';
import {formatUrlForDiagnostics} from '@pkgs/http_client/src/HttpClientDiagnostics';
import type {StreamResponse} from '@pkgs/http_client/src/HttpClientTypes';
-import {HttpError, type HttpErrorType} from '@pkgs/http_client/src/HttpError';
import {ms, seconds} from 'itty-time';
-import {
- type CryptoKey,
- createLocalJWKSet,
- type FlattenedJWSInput,
- errors as JoseErrors,
- type JSONWebKeySet,
- type JWSHeaderParameters,
- type JWTPayload,
- jwtVerify,
-} from 'jose';
+import {type JWTPayload, jwtVerify} from 'jose';
interface SsoStatePayload {
codeVerifier: string;
@@ -164,26 +151,12 @@ interface ResolvedSsoClaims {
groupsOverage: boolean;
}
-interface RemoteJwkSetResolver {
- (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput): Promise<CryptoKey>;
- coolingDown: boolean;
- fresh: boolean;
- reloading: boolean;
- reload: () => Promise<void>;
- jwks: () => JSONWebKeySet | undefined;
-}
-
interface DiscoveryCacheEntry {
metadata: DiscoveredOidcProviderMetadata | null;
fetchedAt: number;
failed: boolean;
}
-interface JwksCacheEntry {
- jwks: RemoteJwkSetResolver;
- cachedAt: number;
-}
-
type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post';
interface TokenEndpointError {
@@ -208,18 +181,14 @@ const DISCOVERY_FAILURE_FRESH_MS = ms('1 minute');
const TOKEN_ERROR_BODY_MAX_BYTES = 4 * 1024;
const PROVIDER_ERROR_TEXT_MAX_LENGTH = 300;
const MISCONFIGURED_CLIENT_ERRORS = new Set(['invalid_client', 'unauthorized_client']);
-const PROVIDER_UNAVAILABLE_ERROR_TYPES = new Set<HttpErrorType>(['aborted', 'network_error', 'unresolvable_host']);
const discoveryRefreshes = new Map<string, Promise<DiscoveredOidcProviderMetadata | null>>();
-const jwksCache = new Map<string, JwksCacheEntry>();
-const jwksCreations = new Map<string, Promise<RemoteJwkSetResolver>>();
const workingClientAuthMethods = new Map<string, ClientAuthMethod>();
const MISSING_ISSUER_WARNING_INTERVAL_MS = ms('1 hour');
let missingIssuerWarnedAt = 0;
export function resetSsoProviderCachesForTests(): void {
- jwksCache.clear();
- jwksCreations.clear();
+ resetOidcJwksCachesForTests();
workingClientAuthMethods.clear();
}
@@ -273,20 +242,6 @@ function clientAuthMethodsToTry(tokenUrl: string, supported: Array<string> | nul
return [first, first === 'client_secret_post' ? 'client_secret_basic' : 'client_secret_post'];
}
-async function sendProviderRequest(
- request: Parameters<typeof FetchUtils.sendRequest>[0],
-): Promise<Awaited<ReturnType<typeof FetchUtils.sendRequest>>> {
- try {
- return await FetchUtils.sendRequest(request, {requestUrlPolicy: getSsoRequestUrlPolicy(), maxRedirects: 0});
- } catch (error) {
- getLogger().warn({url: formatUrlForDiagnostics(request.url), error}, 'SSO provider request failed');
- if (error instanceof HttpError && error.errorType && PROVIDER_UNAVAILABLE_ERROR_TYPES.has(error.errorType)) {
- throw new SsoProviderUnavailableError();
- }
- throw InputValidationError.fromCode('sso', ValidationErrorCodes.SSO_MISCONFIGURED);
- }
-}
-
function formEncode(value: string): string {
return new URLSearchParams({v: value}).toString().slice(2);
}
@@ -547,15 +502,8 @@ function warnAboutMissingIssuer(): void {
);
}
-function isJsonWebKeySet(value: unknown): value is JSONWebKeySet {
- if (!isJsonRecord(value)) return false;
- const keys = value['keys'];
- return Array.isArray(keys) && keys.every(isJsonRecord);
-}
-
export class SsoService {
private static readonly STATE_TTL_SECONDS = seconds('10 minutes');
- private static readonly JWKS_CACHE_TTL_MS = ms('1 hour');
private readonly ssoIdentityRepository = new SsoIdentityRepository();
constructor(
@@ -1271,7 +1219,7 @@ export class SsoService {
if (!config.jwksUrl || !config.issuerForVerification) {
throw new Error('id_token cannot be verified without a JWKS URL and an issuer');
}
- const jwks = await this.getOrCreateJwks(config.jwksUrl);
+ const jwks = await getOidcJwks(config.jwksUrl);
const {payload} = await jwtVerify(idToken, jwks, {
issuer: acceptedIssuers(config.issuerForVerification),
audience: config.clientId ?? undefined,
@@ -1293,119 +1241,6 @@ export class SsoService {
}
}
- private async getOrCreateJwks(jwksUrl: string): Promise<RemoteJwkSetResolver> {
- const cached = jwksCache.get(jwksUrl);
- if (cached && Date.now() - cached.cachedAt < SsoService.JWKS_CACHE_TTL_MS) {
- return cached.jwks;
- }
- let creation = jwksCreations.get(jwksUrl);
- if (!creation) {
- creation = this.createJwks(jwksUrl).finally(() => jwksCreations.delete(jwksUrl));
- jwksCreations.set(jwksUrl, creation);
- }
- return creation;
- }
-
- private async createJwks(jwksUrl: string): Promise<RemoteJwkSetResolver> {
- const now = Date.now();
- const fetchJwks = async (): Promise<JSONWebKeySet> => {
- const response = await sendProviderRequest({
- url: jwksUrl,
- method: 'GET',
- headers: {Accept: 'application/json'},
- timeout: ms('15 seconds'),
- serviceName: 'sso_jwks',
- });
- if (response.status < 200 || response.status >= 300) {
- FetchUtils.discardResponseBody(response.stream, response.status);
- if (response.status >= 500) {
- getLogger().warn({status: response.status, url: formatUrlForDiagnostics(jwksUrl)}, 'SSO keys request failed');
- throw new SsoProviderUnavailableError();
- }
- throw new Error(`Failed to fetch JWKS: HTTP ${response.status}`);
- }
- const rawBody = await FetchUtils.streamToStringWithLimit(response.stream, {
- maxBytes: EXTERNAL_RESPONSE_LIMITS.ssoJwksBytes,
- headers: response.headers,
- url: jwksUrl,
- description: 'SSO JWKS response',
- });
- const parsed = parseJsonWithGuard(rawBody, isJsonWebKeySet);
- if (!parsed) {
- throw new Error('SSO JWKS response was not a JSON Web Key Set');
- }
- return parsed;
- };
- let currentJwks = await fetchJwks();
- let currentResolver = createLocalJWKSet(currentJwks);
- let fetchedAt = now;
- let pendingReload: Promise<void> | null = null;
- let jwks!: RemoteJwkSetResolver;
- const reload = async (): Promise<void> => {
- pendingReload ??= (async () => {
- currentJwks = await fetchJwks();
- currentResolver = createLocalJWKSet(currentJwks);
- fetchedAt = Date.now();
- jwksCache.set(jwksUrl, {jwks, cachedAt: fetchedAt});
- })().finally(() => {
- pendingReload = null;
- });
- await pendingReload;
- };
- jwks = (async (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput) => {
- if (Date.now() - fetchedAt >= SsoService.JWKS_CACHE_TTL_MS) {
- await reload();
- }
- try {
- return await currentResolver(protectedHeader, token);
- } catch (error) {
- if (error instanceof JoseErrors.JWKSNoMatchingKey) {
- await reload();
- return currentResolver(protectedHeader, token);
- }
- throw error;
- }
- }) as RemoteJwkSetResolver;
- Object.defineProperties(jwks, {
- coolingDown: {
- get: () => false,
- enumerable: true,
- configurable: false,
- },
- fresh: {
- get: () => Date.now() - fetchedAt < SsoService.JWKS_CACHE_TTL_MS,
- enumerable: true,
- configurable: false,
- },
- reloading: {
- get: () => pendingReload != null,
- enumerable: true,
- configurable: false,
- },
- reload: {
- value: reload,
- enumerable: true,
- configurable: false,
- writable: false,
- },
- jwks: {
- value: () => currentJwks,
- enumerable: true,
- configurable: false,
- writable: false,
- },
- });
- jwksCache.set(jwksUrl, {jwks, cachedAt: now});
- if (jwksCache.size > 10) {
- for (const [url, entry] of jwksCache.entries()) {
- if (now - entry.cachedAt >= SsoService.JWKS_CACHE_TTL_MS) {
- jwksCache.delete(url);
- }
- }
- }
- return jwks;
- }
-
private async fetchUserInfo(userInfoUrl: string, accessToken: string): Promise<Record<string, unknown>> {
const resp = await sendProviderRequest({
url: userInfoUrl,
diff --git a/fluxer_api/src/api/auth/services/SsoUtils.ts b/fluxer_api/src/api/auth/services/SsoUtils.ts
index 8b091ad64..c98900253 100644
--- a/fluxer_api/src/api/auth/services/SsoUtils.ts
+++ b/fluxer_api/src/api/auth/services/SsoUtils.ts
@@ -5,7 +5,11 @@ import {Logger} from '@app/api/Logger';
import {EXTERNAL_RESPONSE_LIMITS} from '@app/api/utils/ExternalResponseLimits';
import * as FetchUtils from '@app/api/utils/FetchUtils';
import {parseJsonRecord} from '@app/api/utils/JsonBoundaryUtils';
+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
+import {SsoProviderUnavailableError} from '@fluxer/errors/src/domains/auth/SsoProviderUnavailableError';
+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {formatUrlForDiagnostics} from '@pkgs/http_client/src/HttpClientDiagnostics';
+import {HttpError, type HttpErrorType} from '@pkgs/http_client/src/HttpError';
import {ms} from 'itty-time';
export interface DiscoveredOidcProviderMetadata {
@@ -15,6 +19,23 @@ export interface DiscoveredOidcProviderMetadata {
userinfo_endpoint?: string;
jwks_uri?: string;
token_endpoint_auth_methods_supported?: Array<string>;
+ id_token_signing_alg_values_supported?: Array<string>;
+}
+
+const PROVIDER_UNAVAILABLE_ERROR_TYPES = new Set<HttpErrorType>(['aborted', 'network_error', 'unresolvable_host']);
+
+export async function sendProviderRequest(
+ request: Parameters<typeof FetchUtils.sendRequest>[0],
+): Promise<Awaited<ReturnType<typeof FetchUtils.sendRequest>>> {
+ try {
+ return await FetchUtils.sendRequest(request, {requestUrlPolicy: getSsoRequestUrlPolicy(), maxRedirects: 0});
+ } catch (error) {
+ Logger.warn({url: formatUrlForDiagnostics(request.url), error}, 'SSO provider request failed');
+ if (error instanceof HttpError && error.errorType && PROVIDER_UNAVAILABLE_ERROR_TYPES.has(error.errorType)) {
+ throw new SsoProviderUnavailableError();
+ }
+ throw InputValidationError.fromCode('sso', ValidationErrorCodes.SSO_MISCONFIGURED);
+ }
}
const SSO_REDIRECT_BASE = 'https://sso-redirect.invalid';
@@ -127,6 +148,7 @@ export async function tryDiscoverOidcProviderMetadata(issuer: string): Promise<D
userinfo_endpoint: typeof json['userinfo_endpoint'] === 'string' ? json['userinfo_endpoint'] : undefined,
jwks_uri: typeof json['jwks_uri'] === 'string' ? json['jwks_uri'] : undefined,
token_endpoint_auth_methods_supported: readStringList(json['token_endpoint_auth_methods_supported']),
+ id_token_signing_alg_values_supported: readStringList(json['id_token_signing_alg_values_supported']),
};
} catch (error) {
return discoveryFailed(issuer, 'request failed', {error});
diff --git a/fluxer_api/src/api/config/APIConfig.ts b/fluxer_api/src/api/config/APIConfig.ts
index ccf4da3de..c2944b42b 100644
--- a/fluxer_api/src/api/config/APIConfig.ts
+++ b/fluxer_api/src/api/config/APIConfig.ts
@@ -290,6 +290,10 @@ export interface APIConfig {
};
admin: {
oauthClientSecret?: string;
+ sso: {
+ issuer: string;
+ clientId: string;
+ };
};
auth: {
sudoModeSecret: string;
diff --git a/fluxer_api/src/api/middleware/UserMiddleware.ts b/fluxer_api/src/api/middleware/UserMiddleware.ts
index 86c9b8623..416d959ad 100644
--- a/fluxer_api/src/api/middleware/UserMiddleware.ts
+++ b/fluxer_api/src/api/middleware/UserMiddleware.ts
@@ -22,6 +22,7 @@ interface ParsedAuthHeader {
const SKIP_PATHS = new Set([
'/_health',
+ '/admin/sso/sign-in',
'/webhooks/livekit',
'/voice/join/preview',
'/voice/join',
diff --git a/fluxer_api/src/api/oauth/OAuth2Service.ts b/fluxer_api/src/api/oauth/OAuth2Service.ts
index 6606f7897..45afe6b19 100644
--- a/fluxer_api/src/api/oauth/OAuth2Service.ts
+++ b/fluxer_api/src/api/oauth/OAuth2Service.ts
@@ -30,6 +30,8 @@ import {InvalidScopeError} from '@fluxer/errors/src/domains/oauth/InvalidScopeEr
import {MissingClientSecretError} from '@fluxer/errors/src/domains/oauth/MissingClientSecretError';
import {MissingRedirectUriError} from '@fluxer/errors/src/domains/oauth/MissingRedirectUriError';
+const ADMIN_SSO_TOKEN_SCOPES = ['identify', 'email'];
+
interface OAuth2ServiceDeps {
applicationRepository: ApplicationRepository;
oauth2TokenRepository: OAuth2TokenRepository;
@@ -197,36 +199,14 @@ export class OAuth2Service {
};
}
- async tokenExchange(params: {
- headersAuthorization?: string;
- grantType: 'authorization_code' | 'refresh_token';
- code?: string;
- refreshToken?: string;
- redirectUri?: string;
+ async authenticateClient(args: {
+ authorizationHeader?: string;
clientId?: string;
clientSecret?: string;
- codeVerifier?: string;
- }): Promise<{
- access_token: string;
- token_type: 'Bearer';
- expires_in: number;
- scope?: string;
- refresh_token: string;
- }> {
- Logger.debug(
- {
- grant_type: params.grantType,
- client_id_present: !!params.clientId || /^Basic\s+/.test(params.headersAuthorization ?? ''),
- has_basic_auth: /^Basic\s+/.test(params.headersAuthorization ?? ''),
- code_present: !!params.code,
- refresh_token_present: !!params.refreshToken,
- redirect_uri_present: !!params.redirectUri,
- },
- 'OAuth2 tokenExchange start',
- );
- const basic = this.basicAuth(params.headersAuthorization);
- const clientId = params.clientId ?? basic?.clientId ?? '';
- const clientSecret = params.clientSecret ?? basic?.clientSecret;
+ }): Promise<Application> {
+ const basic = this.basicAuth(args.authorizationHeader);
+ const clientId = args.clientId ?? basic?.clientId ?? '';
+ const clientSecret = args.clientSecret ?? basic?.clientSecret;
let parsedClientId: ApplicationID;
try {
parsedClientId = BigInt(clientId) as ApplicationID;
@@ -235,13 +215,13 @@ export class OAuth2Service {
}
const application = await this.applications.getApplication(parsedClientId);
if (!application) {
- Logger.debug({client_id_len: clientId.length}, 'OAuth2 tokenExchange: unknown application');
+ Logger.debug({client_id_len: clientId.length}, 'OAuth2 client authentication: unknown application');
throw new InvalidClientError();
}
if (!clientSecret) {
Logger.debug(
{application_id: application.applicationId.toString()},
- 'OAuth2 tokenExchange: missing client_secret',
+ 'OAuth2 client authentication: missing client_secret',
);
throw new MissingClientSecretError();
}
@@ -250,11 +230,66 @@ export class OAuth2Service {
if (!ok) {
Logger.debug(
{application_id: application.applicationId.toString()},
- 'OAuth2 tokenExchange: client_secret verification failed',
+ 'OAuth2 client authentication: client_secret verification failed',
);
throw new InvalidClientSecretError();
}
}
+ return application;
+ }
+
+ async issueAdminSsoTokens(
+ application: Application,
+ userId: UserID,
+ ): Promise<{
+ access_token: string;
+ token_type: 'Bearer';
+ expires_in: number;
+ scope: string;
+ refresh_token: string;
+ }> {
+ const res = await this.issueTokens({application, userId, scope: new Set(ADMIN_SSO_TOKEN_SCOPES)});
+ return {
+ access_token: res.accessToken.token_,
+ token_type: 'Bearer',
+ expires_in: res.expires_in,
+ scope: res.scope ?? '',
+ refresh_token: res.refreshToken.token_,
+ };
+ }
+
+ async tokenExchange(params: {
+ headersAuthorization?: string;
+ grantType: 'authorization_code' | 'refresh_token';
+ code?: string;
+ refreshToken?: string;
+ redirectUri?: string;
+ clientId?: string;
+ clientSecret?: string;
+ codeVerifier?: string;
+ }): Promise<{
+ access_token: string;
+ token_type: 'Bearer';
+ expires_in: number;
+ scope?: string;
+ refresh_token: string;
+ }> {
+ Logger.debug(
+ {
+ grant_type: params.grantType,
+ client_id_present: !!params.clientId || /^Basic\s+/.test(params.headersAuthorization ?? ''),
+ has_basic_auth: /^Basic\s+/.test(params.headersAuthorization ?? ''),
+ code_present: !!params.code,
+ refresh_token_present: !!params.refreshToken,
+ redirect_uri_present: !!params.redirectUri,
+ },
+ 'OAuth2 tokenExchange start',
+ );
+ const application = await this.authenticateClient({
+ authorizationHeader: params.headersAuthorization,
+ clientId: params.clientId,
+ clientSecret: params.clientSecret,
+ });
if (params.grantType === 'authorization_code') {
const code = params.code!;
const authCode = await this.tokens.getAuthorizationCode(code);
diff --git a/fluxer_api/src/api/rate_limit_configs/AdminRateLimitConfig.ts b/fluxer_api/src/api/rate_limit_configs/AdminRateLimitConfig.ts
index 894083a72..c85aca886 100644
--- a/fluxer_api/src/api/rate_limit_configs/AdminRateLimitConfig.ts
+++ b/fluxer_api/src/api/rate_limit_configs/AdminRateLimitConfig.ts
@@ -4,6 +4,11 @@ import type {RouteRateLimitConfig} from '@app/api/middleware/RateLimitMiddleware
import {ms} from 'itty-time';
export const AdminRateLimitConfigs = {
+ ADMIN_SSO_SIGN_IN: {
+ bucket: 'admin:sso:sign_in',
+ config: {limit: 15, windowMs: ms('10 seconds')},
+ trustForwardedClientIp: true,
+ } as RouteRateLimitConfig,
ADMIN_LOOKUP: {
bucket: 'admin:lookup',
config: {limit: 200, windowMs: ms('1 minute')},
diff --git a/fluxer_api/src/api/test/ApiTestHarness.ts b/fluxer_api/src/api/test/ApiTestHarness.ts
index 3ddb8065f..feca19efd 100644
--- a/fluxer_api/src/api/test/ApiTestHarness.ts
+++ b/fluxer_api/src/api/test/ApiTestHarness.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createAPIApp} from '@app/api/App';
+import {resetAdminSsoCachesForTests} from '@app/api/admin/AdminSsoSignIn';
import {resetSsoProviderCachesForTests} from '@app/api/auth/services/SsoService';
import {Config} from '@app/api/Config';
import {resetApiServicesForTesting} from '@app/api/CreateApiContext';
@@ -112,6 +113,7 @@ export async function createApiTestHarness(options: CreateApiTestHarnessOptions
setInjectedUnfurlerService(undefined);
resetSharedListsForTests();
resetSsoProviderCachesForTests();
+ resetAdminSsoCachesForTests();
}
async function resetData(): Promise<void> {
resetGuildVisitorCachesForTesting();
diff --git a/fluxer_api/src/api/test/Setup.ts b/fluxer_api/src/api/test/Setup.ts
index 713b9b867..8b8ef82c7 100644
--- a/fluxer_api/src/api/test/Setup.ts
+++ b/fluxer_api/src/api/test/Setup.ts
@@ -64,6 +64,8 @@ function setDefaultTestEnv(): void {
FLUXER_MEDIA_PROXY_ATTACHMENT_URL_SECRETS_BASE64: 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=',
FLUXER_ADMIN_SECRET_KEY_BASE: 'test-admin-secret',
FLUXER_ADMIN_OAUTH_CLIENT_SECRET: 'test-admin-oauth-secret',
+ FLUXER_ADMIN_SSO_ISSUER: 'https://1.1.1.1/admin-sso',
+ FLUXER_ADMIN_SSO_CLIENT_ID: 'admin-sso-test-client',
FLUXER_GATEWAY_RPC_AUTH_TOKEN: 'test-gateway-rpc-token',
FLUXER_SUDO_MODE_SECRET: 'test-sudo-secret',
FLUXER_CONNECTION_INITIATION_SECRET: 'test-connection-secret',
diff --git a/fluxer_api/src/api/user/UserHelpers.ts b/fluxer_api/src/api/user/UserHelpers.ts
index cd93989f1..abcd82906 100644
--- a/fluxer_api/src/api/user/UserHelpers.ts
+++ b/fluxer_api/src/api/user/UserHelpers.ts
@@ -111,7 +111,7 @@ export function isTemporarilyBanned(user: Pick<User, 'flags' | 'tempBannedUntil'
);
}
-function isAccountDisabled(user: Pick<User, 'flags' | 'tempBannedUntil'>, now = Date.now()): boolean {
+export function isAccountDisabled(user: Pick<User, 'flags' | 'tempBannedUntil'>, now = Date.now()): boolean {
if ((user.flags & UserFlags.DISABLED) === 0n) return false;
return user.tempBannedUntil == null || user.tempBannedUntil.getTime() > now;
}
diff --git a/fluxer_docs/src/content/docs/admin-api/index.mdx b/fluxer_docs/src/content/docs/admin-api/index.mdx
index 2554b19b9..3dfa243d8 100644
--- a/fluxer_docs/src/content/docs/admin-api/index.mdx
+++ b/fluxer_docs/src/content/docs/admin-api/index.mdx
@@ -472,6 +472,7 @@ These entries have `access` set to `write`.
| set_traits | Account traits were replaced |
| shutdown_guild | One guild was stopped on the main Gateway |
| show_built_in_badge | A hidden built-in community badge was shown again |
+| sso_sign_in | An admin signed in to the admin panel through single sign-on |
| system_dm.send | A system DM broadcast was created |
| temp_ban | An account was suspended for a time or permanently |
| terminate_sessions | Every login session of an account was revoked |
diff --git a/fluxer_docs/src/content/docs/admin-api/users.mdx b/fluxer_docs/src/content/docs/admin-api/users.mdx
index 507079e7e..99fe48392 100644
--- a/fluxer_docs/src/content/docs/admin-api/users.mdx
+++ b/fluxer_docs/src/content/docs/admin-api/users.mdx
@@ -646,6 +646,31 @@ Returns a [sign-in link](#sign-in-link-object) for an account that has `*`. Only
The rate limit is 100 requests per minute, on the `admin:user:modify` bucket.
+## Exchange admin SSO ID token
+
+<RouteHeader method="POST" path="/v1/admin/sso/sign-in" />
+
+Checks an ID token from the admin single sign-on provider and returns an [OAuth2 token](/http-api/oauth2/#oauth2-token-object) object for the admin panel, with `user_id` added. Only the admin panel calls it, with its OAuth2 client ID and secret as HTTP Basic auth. The ID token must be signed by the provider, be for the admin panel's client ID and have a `fluxer_id` claim with the ID of an account that has `admin:authenticate`. Each ID token works once.
+
+### JSON body
+
+| Field | Type | Description |
+| --- | --- | --- |
+| id_token | string | The ID token the admin panel got from the provider (1-16384 characters) |
+| nonce | string | The nonce the admin panel sent to the provider (16-256 characters) |
+
+### Response
+
+| Status | Body | Condition |
+| --- | --- | --- |
+| 200 | [OAuth2 token](/http-api/oauth2/#oauth2-token-object) object with `user_id` | The admin was signed in |
+| 400 | [error response](/admin-api/#error-response) | `INVALID_FORM_BODY` with the validation code `INVALID_SSO_TOKEN` when the ID token was refused or already used, or `SSO_MISCONFIGURED` when the API can't use the provider's settings |
+| 400 | [OAuth2 error](/http-api/oauth2/#oauth2-error-response-object) object | `invalid_client` when the client ID or secret is wrong |
+| 403 | [error response](/admin-api/#error-response) | `MISSING_PERMISSIONS` when the account doesn't exist, can't sign in or lacks `admin:authenticate`, `FEATURE_TEMPORARILY_DISABLED` when admin single sign-on is off |
+| 503 | [error response](/admin-api/#error-response) | `SSO_PROVIDER_UNAVAILABLE` when the API can't get the provider's settings |
+
+The rate limit is 15 requests per 10 seconds, on the `admin:sso:sign_in` bucket.
+
## Revoke user recovery kit
<RouteHeader method="DELETE" path="/v1/admin/users/{user_id}/recovery-kit" auditReason />
diff --git a/fluxer_docs/src/content/docs/operator/environment.mdx b/fluxer_docs/src/content/docs/operator/environment.mdx
index c7303dccd..9f517bc47 100644
--- a/fluxer_docs/src/content/docs/operator/environment.mdx
+++ b/fluxer_docs/src/content/docs/operator/environment.mdx
@@ -174,7 +174,7 @@ The origin Fluxer serves static assets such as the favicon and app icons from. W
### `FLUXER_ADMIN_ENDPOINT`
-The public address of the admin panel. When it's empty, Fluxer uses the public origin followed by `FLUXER_ADMIN_BASE_PATH`. The admin sign-in redirect is this address followed by `/oauth2_callback`, and the admin panel uses secure cookies when the address starts with `https`. With rexctl, use `rexctl config set FLUXER_ADMIN_ENDPOINT`.
+The public address of the admin panel. When it's empty, Fluxer uses the public origin followed by `FLUXER_ADMIN_BASE_PATH`. The admin sign-in redirect is this address followed by `/oauth2_callback`, the single sign-on redirect is this address followed by `/sso/callback`, and the admin panel uses secure cookies when the address starts with `https`. With rexctl, use `rexctl config set FLUXER_ADMIN_ENDPOINT`.
### `FLUXER_MARKETING_ENDPOINT`
@@ -666,6 +666,22 @@ The title browsers show for Fluxer when someone creates or uses a passkey. When
Every origin where passkeys work, separated by commas. When it's empty, Docker Compose uses `FLUXER_PUBLIC_ORIGIN`, or `FLUXER_PUBLIC_SCHEME` followed by `://` and `FLUXER_DOMAIN`. A list you set replaces it and must include the web app origin. Set a list when `FLUXER_APP_ENDPOINT` is on another origin. Each entry is an http or https origin or an Android app, written as `android:apk-key-hash:` followed by its signing certificate's SHA-256 hash in unpadded base64url. With rexctl, use `rexctl config set FLUXER_PASSKEY_ADDITIONAL_ALLOWED_ORIGINS`.
+### `FLUXER_ADMIN_SSO_ISSUER`
+
+The issuer URL of an OpenID Connect provider that staff can also use to sign in to the admin panel. Admin single sign-on is on when `FLUXER_ADMIN_SSO_ISSUER`, `FLUXER_ADMIN_SSO_CLIENT_ID` and `FLUXER_ADMIN_SSO_CLIENT_SECRET` are all set. The admin service won't start when only some of them are set. The api and admin services must have the same issuer and client ID. The provider's ID token must have a `fluxer_id` claim with the ID of the Fluxer account, and access still comes from the admin ACLs of that account. With rexctl, use `rexctl config set FLUXER_ADMIN_SSO_ISSUER`.
+
+### `FLUXER_ADMIN_SSO_CLIENT_ID`
+
+The client ID of the admin panel at the provider in `FLUXER_ADMIN_SSO_ISSUER`. Register the admin address followed by `/sso/callback` as its redirect URL. With rexctl, use `rexctl config set FLUXER_ADMIN_SSO_CLIENT_ID`.
+
+### `FLUXER_ADMIN_SSO_CLIENT_SECRET`
+
+The client secret that goes with `FLUXER_ADMIN_SSO_CLIENT_ID`. Only the admin service uses it. Keep it secret. With rexctl, use `rexctl config set FLUXER_ADMIN_SSO_CLIENT_SECRET`.
+
+### `FLUXER_ADMIN_SSO_DISPLAY_NAME`
+
+The provider name on the single sign-on button of the admin panel. With `Ferret`, the button says `Sign in with Ferret`. When it's empty, the button says `Sign in with single sign-on`. With rexctl, use `rexctl config set FLUXER_ADMIN_SSO_DISPLAY_NAME`.
+
## Email
The admin panel can also save the delivery mode, the sender and the SMTP server. A value saved there is used first.
@@ -2145,6 +2161,10 @@ The OAuth2 client ID the admin panel signs in with. The stack uses the built-in
The OAuth2 redirect URL of the admin panel. The admin service works it out from its own address.
+### `FLUXER_ADMIN_SSO_REDIRECT_URI`
+
+The single sign-on redirect URL of the admin panel. The admin service works it out from its own address.
+
### `FLUXER_API_WORKER_LANE`
The job lane a worker runs when `FLUXER_API_WORKER_MODE` is `single_lane`. Each worker container in the stack runs every lane.
diff --git a/fluxer_rexctl/internal/instance/envvars.go b/fluxer_rexctl/internal/instance/envvars.go
index 007f5fc0a..02783982b 100644
--- a/fluxer_rexctl/internal/instance/envvars.go
+++ b/fluxer_rexctl/internal/instance/envvars.go
@@ -6,7 +6,7 @@ var envSecretVars = []string{
"FLUXER_SETUP_TOKEN", "POSTGRES_PASSWORD", "MEILI_MASTER_KEY", "FLUXER_S3_SECRET_KEY", "LIVEKIT_API_SECRET",
"FLUXER_SUDO_MODE_SECRET", "FLUXER_CONNECTION_INITIATION_SECRET", "FLUXER_PROFILE_PSEUDONYM_SECRET", "FLUXER_VAPID_PRIVATE_KEY",
"FLUXER_GATEWAY_RPC_AUTH_TOKEN", "FLUXER_MEDIA_PROXY_SECRET_KEY", "FLUXER_MEDIA_PROXY_UPLOAD_RELAY_SECRET_BASE64",
- "FLUXER_ADMIN_SECRET_KEY_BASE", "FLUXER_ADMIN_OAUTH_CLIENT_SECRET", "FLUXER_ERLANG_COOKIE", "FLUXER_ACTIVITYPUB_SIGNING_KEY_BASE64",
+ "FLUXER_ADMIN_SECRET_KEY_BASE", "FLUXER_ADMIN_OAUTH_CLIENT_SECRET", "FLUXER_ADMIN_SSO_CLIENT_SECRET", "FLUXER_ERLANG_COOKIE", "FLUXER_ACTIVITYPUB_SIGNING_KEY_BASE64",
"FLUXER_API_DONATION_PROXY_KEY", "FLUXER_API_TRUSTED_CALLERS", "FLUXER_CACHE_PURGE_HTTP_TOKEN", "FLUXER_CACHE_PURGE_CONTROLLER_TOKEN",
"FLUXER_NATS_AUTH_TOKEN", "FLUXER_SEARCH_PASSWORD", "FLUXER_AUTH_BLUESKY_KEYS", "FLUXER_EMAIL_WEBHOOK_SECRET",
"FLUXER_EMAIL_SMTP_PASSWORD", "FLUXER_EMAIL_FALLBACK_SMTP_PASSWORD", "FLUXER_PUSH_APNS_PRIVATE_KEY", "FLUXER_PUSH_FCM_PRIVATE_KEY",
@@ -71,7 +71,7 @@ var envVars = []envVar{
{"FLUXER_MEDIA_ENDPOINT", "address", "The public address of the media proxy. When it's empty, Fluxer uses the public origin followed by /media."},
{"FLUXER_MEDIA_PROXY_PUBLIC_ENDPOINT", "address", "The public media proxy address that the gifs, unfurl and media-proxy services use when they build media links. When it's empty, they use FLUXER_MEDIA_ENDPOINT, or the public origin followed by /media."},
{"FLUXER_STATIC_CDN_ENDPOINT", "address", "The origin Fluxer serves static assets such as the favicon and app icons from. When it's empty, the api and worker services derive it from FLUXER_STATIC_CDN_DOMAIN or the public origin, and the admin and gateway services use the public origin. The app-proxy service uses it only when it's set, and serves its own copies of the web app files otherwise."},
- {"FLUXER_ADMIN_ENDPOINT", "address", "The public address of the admin panel. When it's empty, Fluxer uses the public origin followed by FLUXER_ADMIN_BASE_PATH. The admin sign-in redirect is this address followed by /oauth2_callback, and the admin panel uses secure cookies when the address starts with `https`."},
+ {"FLUXER_ADMIN_ENDPOINT", "address", "The public address of the admin panel. When it's empty, Fluxer uses the public origin followed by FLUXER_ADMIN_BASE_PATH. The admin sign-in redirect is this address followed by /oauth2_callback, the single sign-on redirect is this address followed by /sso/callback, and the admin panel uses secure cookies when the address starts with `https`."},
{"FLUXER_MARKETING_ENDPOINT", "address", "The address of the marketing site, which Fluxer allows through CORS and uses in some links. When it's empty, Fluxer uses the public origin."},
{"FLUXER_INVITE_ENDPOINT", "address", "The base URL of invite links. When it's empty, Fluxer uses FLUXER_INVITE_DOMAIN or the public host, followed by /invite."},
{"FLUXER_GIFT_ENDPOINT", "address", "The base URL of gift links. When it's empty, Fluxer uses FLUXER_GIFT_DOMAIN or the public host, followed by /gift."},
@@ -186,6 +186,10 @@ var envVars = []envVar{
{"FLUXER_PASSKEY_RP_ID", "sso", "The relying party ID that passkeys are tied to, a domain such as `chat.example.com`. When it's empty, Fluxer uses FLUXER_DOMAIN. Changing it makes every passkey registered against the old value stop working."},
{"FLUXER_PASSKEY_RP_NAME", "sso", "The title browsers show for Fluxer when someone creates or uses a passkey. When it's empty, browsers show `Fluxer`."},
{"FLUXER_PASSKEY_ADDITIONAL_ALLOWED_ORIGINS", "sso", "Every origin where passkeys work, separated by commas. When it's empty, Docker Compose uses FLUXER_PUBLIC_ORIGIN, or FLUXER_PUBLIC_SCHEME followed by `://` and FLUXER_DOMAIN. A list you set replaces it and must include the web app origin. Set a list when FLUXER_APP_ENDPOINT is on another origin. Each entry is an http or https origin or an Android app, written as `android:apk-key-hash:` followed by its signing certificate's SHA-256 hash in unpadded base64url."},
+ {"FLUXER_ADMIN_SSO_ISSUER", "sso", "The issuer URL of an OpenID Connect provider that staff can also use to sign in to the admin panel. Admin single sign-on is on when FLUXER_ADMIN_SSO_ISSUER, FLUXER_ADMIN_SSO_CLIENT_ID and FLUXER_ADMIN_SSO_CLIENT_SECRET are all set. The admin service won't start when only some of them are set. The api and admin services must have the same issuer and client ID. The provider's ID token must have a `fluxer_id` claim with the ID of the Fluxer account, and access still comes from the admin ACLs of that account."},
+ {"FLUXER_ADMIN_SSO_CLIENT_ID", "sso", "The client ID of the admin panel at the provider in FLUXER_ADMIN_SSO_ISSUER. Register the admin address followed by /sso/callback as its redirect URL."},
+ {"FLUXER_ADMIN_SSO_CLIENT_SECRET", "sso", "The client secret that goes with FLUXER_ADMIN_SSO_CLIENT_ID. Only the admin service uses it."},
+ {"FLUXER_ADMIN_SSO_DISPLAY_NAME", "sso", "The provider name on the single sign-on button of the admin panel. With `Ferret`, the button says `Sign in with Ferret`. When it's empty, the button says `Sign in with single sign-on`."},
{"FLUXER_EMAIL_ENABLED", "email", "The older way to turn email on. Use FLUXER_EMAIL_DELIVERY."},
{"FLUXER_EMAIL_PROVIDER", "email", "The older way to pick the email transport, which takes `smtp` or `none`. Use FLUXER_EMAIL_DELIVERY."},
{"FLUXER_EMAIL_DELIVERY", "email", "How Fluxer sends email. Use `smtp` or `off`. When it's empty, FLUXER_EMAIL_ENABLED and FLUXER_EMAIL_PROVIDER decide, and email is off when those are empty too."},
@@ -539,6 +543,7 @@ var envVars = []envVar{
{"FLUXER_ADMIN_HOST", "internal", "The address the admin service listens on. When it's empty, it listens on `0.0.0.0`."},
{"FLUXER_ADMIN_OAUTH_CLIENT_ID", "internal", "The OAuth2 client ID the admin panel signs in with. The stack uses the built-in client ID of the admin service."},
{"FLUXER_ADMIN_OAUTH_REDIRECT_URI", "internal", "The OAuth2 redirect URL of the admin panel. The admin service works it out from its own address."},
+ {"FLUXER_ADMIN_SSO_REDIRECT_URI", "internal", "The single sign-on redirect URL of the admin panel. The admin service works it out from its own address."},
{"FLUXER_API_AUTOMATED_MESSAGE_DELETION_DELAY_DAYS", "hosted", "The delay before automated account actions delete messages, in days."},
{"FLUXER_API_WORKER_LANE", "internal", "The job lane a worker runs when FLUXER_API_WORKER_MODE is `single_lane`. Each worker container in the stack runs every lane."},
{"FLUXER_API_WORKER_METRICS_PORT", "internal", "The port the worker serves its metrics on. The stack doesn't collect worker metrics."},
diff --git a/fluxer_rexctl/internal/instance/shipped.json b/fluxer_rexctl/internal/instance/shipped.json
index e97f871aa..180a660e9 100644
--- a/fluxer_rexctl/internal/instance/shipped.json
+++ b/fluxer_rexctl/internal/instance/shipped.json
@@ -75,6 +75,7 @@
"a7915e920ff78b5e3ea4e70e44c69353b0af6d549c0fa5fe4cae919f5bad25ec",
"a90de9de8b3eee047b4bc975f5a2a63470baefd516276482601474c18b28cdca",
"ac698a81097d343c597c821a045605aaa9d96f20dc26bb49581553d3c440b398",
+ "b539962cf320c3e3ec45ea1ac2e42aba58b3c5d83e17e33096ef08246abe7283",
"b91a2a6f9f9b431a1c646a1798bb79b2d9374c0b1148047482a472b02f971a68",
"b9507ede5b95551c3036430f06cd4f571c836fc01776c98c8d58b90b05aec8c1",
"bb367376891f75673a4fc0c73fc2033c76f94c8b2b0984c577d2a66435f72c12",
@@ -229,6 +230,7 @@
"ae06d07690575bf4e6050e96536d59b3f107f3b08d9631c78c641e08f790167a",
"aed9fc69aba980e91ee8c568f4b85b638f485e9b2c2c4a04d101d89224e04d68",
"af22494276b2123b044ef4106c89352e4b6272cec5901bc35991d430d7241856",
+ "b250b6641d1019768296ef4128f7b526208236625b581694846d497c183e7b84",
"b28377933c7a463262c90953f7aaf43a9f870ea91e4c187a53157c9c17c3c802",
"b524f7ecffb515f12a8e9f8e3d1f5d6901c475ea6820aa47de93eec7e02c94cf",
"b99d517d75ff7b8f3b72ad3a1d6b830f030afb6c0f6de04f9451981ca2195e26",
diff --git a/fluxer_rexctl/internal/stack/files/.env.example b/fluxer_rexctl/internal/stack/files/.env.example
index 2cbd835e8..6704d91f4 100644
--- a/fluxer_rexctl/internal/stack/files/.env.example
+++ b/fluxer_rexctl/internal/stack/files/.env.example
@@ -295,8 +295,9 @@ FLUXER_VAPID_PRIVATE_KEY=
# The public address of the admin panel. When it's empty, Fluxer uses the
# public origin followed by FLUXER_ADMIN_BASE_PATH. The admin sign-in redirect
-# is this address followed by /oauth2_callback, and the admin panel uses
-# secure cookies when the address starts with https.
+# is this address followed by /oauth2_callback, the single sign-on redirect is
+# this address followed by /sso/callback, and the admin panel uses secure
+# cookies when the address starts with https.
# rexctl: rexctl config set FLUXER_ADMIN_ENDPOINT
# FLUXER_ADMIN_ENDPOINT=
@@ -952,6 +953,33 @@ FLUXER_VAPID_PRIVATE_KEY=
# rexctl: rexctl config set FLUXER_PASSKEY_ADDITIONAL_ALLOWED_ORIGINS
# FLUXER_PASSKEY_ADDITIONAL_ALLOWED_ORIGINS=
+# The issuer URL of an OpenID Connect provider that staff can also use to sign
+# in to the admin panel. Admin single sign-on is on when
+# FLUXER_ADMIN_SSO_ISSUER, FLUXER_ADMIN_SSO_CLIENT_ID and
+# FLUXER_ADMIN_SSO_CLIENT_SECRET are all set. The admin service won't start
+# when only some of them are set. The api and admin services must have the
+# same issuer and client ID. The provider's ID token must have a fluxer_id
+# claim with the ID of the Fluxer account, and access still comes from the
+# admin ACLs of that account.
+# rexctl: rexctl config set FLUXER_ADMIN_SSO_ISSUER
+# FLUXER_ADMIN_SSO_ISSUER=
+
+# The client ID of the admin panel at the provider in FLUXER_ADMIN_SSO_ISSUER.
+# Register the admin address followed by /sso/callback as its redirect URL.
+# rexctl: rexctl config set FLUXER_ADMIN_SSO_CLIENT_ID
+# FLUXER_ADMIN_SSO_CLIENT_ID=
+
+# The client secret that goes with FLUXER_ADMIN_SSO_CLIENT_ID. Only the admin
+# service uses it. Keep it secret.
+# rexctl: rexctl config set FLUXER_ADMIN_SSO_CLIENT_SECRET
+# FLUXER_ADMIN_SSO_CLIENT_SECRET=
+
+# The provider name on the single sign-on button of the admin panel. With
+# Ferret, the button says Sign in with Ferret. When it's empty, the button
+# says Sign in with single sign-on.
+# rexctl: rexctl config set FLUXER_ADMIN_SSO_DISPLAY_NAME
+# FLUXER_ADMIN_SSO_DISPLAY_NAME=
+
# ============================================================================
# EMAIL
diff --git a/fluxer_rexctl/internal/stack/files/docker-compose.yml b/fluxer_rexctl/internal/stack/files/docker-compose.yml
index 0e11977b6..21a1e24e3 100644
--- a/fluxer_rexctl/internal/stack/files/docker-compose.yml
+++ b/fluxer_rexctl/internal/stack/files/docker-compose.yml
@@ -219,6 +219,8 @@ x-fluxer-env: &fluxer-env
FLUXER_MEDIA_PROXY_ATTACHMENT_URL_SECRETS_BASE64: ${FLUXER_MEDIA_PROXY_ATTACHMENT_URL_SECRETS_BASE64:-}
FLUXER_ADMIN_SECRET_KEY_BASE: ${FLUXER_ADMIN_SECRET_KEY_BASE:-}
FLUXER_ADMIN_OAUTH_CLIENT_SECRET: ${FLUXER_ADMIN_OAUTH_CLIENT_SECRET:-}
+ FLUXER_ADMIN_SSO_ISSUER: ${FLUXER_ADMIN_SSO_ISSUER:-}
+ FLUXER_ADMIN_SSO_CLIENT_ID: ${FLUXER_ADMIN_SSO_CLIENT_ID:-}
FLUXER_INTERNAL_API_ENDPOINT: http://api:8080
FLUXER_INTERNAL_MEDIA_PROXY_ENDPOINT: http://media-proxy:8080
@@ -884,6 +886,8 @@ services:
FLUXER_API_ENDPOINT: http://api:8080
FLUXER_API_PUBLIC_ENDPOINT: ${FLUXER_API_ENDPOINT:-}
FLUXER_STATIC_CDN_ENDPOINT: ${FLUXER_STATIC_CDN_ENDPOINT:-${FLUXER_PUBLIC_ORIGIN:-${FLUXER_PUBLIC_SCHEME:-https}://${FLUXER_DOMAIN:-}}}
+ FLUXER_ADMIN_SSO_CLIENT_SECRET: ${FLUXER_ADMIN_SSO_CLIENT_SECRET:-}
+ FLUXER_ADMIN_SSO_DISPLAY_NAME: ${FLUXER_ADMIN_SSO_DISPLAY_NAME:-}
healthcheck:
test: ["CMD-SHELL", "bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080 && printf \"GET /_health HTTP/1.0\\r\\n\\r\\n\" >&3 && head -n 1 <&3 | grep -q \" 200 \"'"]
<<: *fluxer-app-healthcheck
diff --git a/packages/config/src/ConfigLoader.ts b/packages/config/src/ConfigLoader.ts
index 19c66dd14..cf3ca6506 100644
--- a/packages/config/src/ConfigLoader.ts
+++ b/packages/config/src/ConfigLoader.ts
@@ -149,6 +149,10 @@ function defaultConfig(): MasterConfig {
admin: {
secret_key_base: '',
oauth_client_secret: '',
+ sso: {
+ issuer: '',
+ client_id: '',
+ },
},
},
auth: {
diff --git a/packages/config/src/MasterConfig.ts b/packages/config/src/MasterConfig.ts
index 1a5c81898..906846371 100644
--- a/packages/config/src/MasterConfig.ts
+++ b/packages/config/src/MasterConfig.ts
@@ -170,6 +170,10 @@ export interface MasterConfig {
admin: {
secret_key_base: string;
oauth_client_secret: string;
+ sso: {
+ issuer: string;
+ client_id: string;
+ };
};
};
auth: {
diff --git a/packages/config/src/config_loader/EnvironmentOverrides.ts b/packages/config/src/config_loader/EnvironmentOverrides.ts
index 1eabe888b..aa72a286c 100644
--- a/packages/config/src/config_loader/EnvironmentOverrides.ts
+++ b/packages/config/src/config_loader/EnvironmentOverrides.ts
@@ -138,6 +138,8 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {
},
FLUXER_ADMIN_SECRET_KEY_BASE: {path: ['services', 'admin', 'secret_key_base']},
FLUXER_ADMIN_OAUTH_CLIENT_SECRET: {path: ['services', 'admin', 'oauth_client_secret']},
+ FLUXER_ADMIN_SSO_ISSUER: {path: ['services', 'admin', 'sso', 'issuer']},
+ FLUXER_ADMIN_SSO_CLIENT_ID: {path: ['services', 'admin', 'sso', 'client_id']},
FLUXER_GATEWAY_RPC_AUTH_TOKEN: {path: ['services', 'gateway', 'rpc_auth_token']},
FLUXER_SUDO_MODE_SECRET: {path: ['auth', 'sudo_mode_secret']},
FLUXER_CONNECTION_INITIATION_SECRET: {path: ['auth', 'connection_initiation_secret']},
diff --git a/packages/schema/src/domains/admin/AdminSsoSchemas.ts b/packages/schema/src/domains/admin/AdminSsoSchemas.ts
index 36cf48151..6e26be5c9 100644
--- a/packages/schema/src/domains/admin/AdminSsoSchemas.ts
+++ b/packages/schema/src/domains/admin/AdminSsoSchemas.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {OAuth2TokenResponse} from '@fluxer/schema/src/domains/oauth/OAuthSchemas';
import {SnowflakeStringType} from '@fluxer/schema/src/primitives/SchemaPrimitives';
import {z} from 'zod';
@@ -71,3 +72,20 @@ export const AdminSsoIdentityMigrateResponse = z.object({
});
export type AdminSsoIdentityMigrateResponse = z.infer<typeof AdminSsoIdentityMigrateResponse>;
+
+export const AdminSsoSignInRequest = z.object({
+ id_token: z.string().min(1).max(16384).describe('The ID token the admin panel got from the sign-on provider'),
+ nonce: z
+ .string()
+ .min(16)
+ .max(256)
+ .describe('The nonce the admin panel sent to the sign-on provider, which the ID token must have'),
+});
+
+export type AdminSsoSignInRequest = z.infer<typeof AdminSsoSignInRequest>;
+
+export const AdminSsoSignInResponse = OAuth2TokenResponse.extend({
+ user_id: SnowflakeStringType.describe('The account the admin signed in as'),
+});
+
+export type AdminSsoSignInResponse = z.infer<typeof AdminSsoSignInResponse>;