Skip to content

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

TypeScript fluxerfluxerapp

fix(admin): tighten single sign-on provider settings (#3834)

Hampusdc5dd7b117ec
diff --git a/fluxer_admin/src/config/mod.rs b/fluxer_admin/src/config/mod.rs
index 7017dc8bf..4ac105d7e 100644
--- a/fluxer_admin/src/config/mod.rs
+++ b/fluxer_admin/src/config/mod.rs
@@ -172,6 +172,7 @@ fn sso_config_from_env(admin_endpoint: &str) -> anyhow::Result<Option<SsoConfig>
"set FLUXER_ADMIN_SSO_ISSUER, FLUXER_ADMIN_SSO_CLIENT_ID and FLUXER_ADMIN_SSO_CLIENT_SECRET together, or none of them"
),
};
+ crate::sso::validate_issuer_url(&issuer)?;
let redirect_uri = normalize_public_endpoint_from_env(&read_env(
"FLUXER_ADMIN_SSO_REDIRECT_URI",
&format!("{admin_endpoint}/sso/callback"),
diff --git a/fluxer_admin/src/routes/auth.rs b/fluxer_admin/src/routes/auth.rs
index 4cc55e3cc..8bef457ec 100644
--- a/fluxer_admin/src/routes/auth.rs
+++ b/fluxer_admin/src/routes/auth.rs
@@ -206,7 +206,7 @@ async fn sso_callback_finish(
return failed(StatusCode::BAD_GATEWAY, SSO_UNAVAILABLE);
};
let id_token = match sso::exchange_code(
- state.http_client(),
+ state.sso_http_client(),
&metadata,
sso_config,
&body.code,
diff --git a/fluxer_admin/src/sso.rs b/fluxer_admin/src/sso.rs
index e6f6573c8..386005ea9 100644
--- a/fluxer_admin/src/sso.rs
+++ b/fluxer_admin/src/sso.rs
@@ -12,6 +12,7 @@ use base64::{
use hmac::{Hmac, KeyInit, Mac};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
+use std::time::Duration;
pub const SSO_SCOPE: &str = "openid profile";
@@ -44,7 +45,46 @@ pub struct SsoSignInResponse {
pub access_token: String,
}
+pub(crate) fn http_client(build_version: &str) -> reqwest::Client {
+ reqwest::Client::builder()
+ .user_agent(format!("FluxerAdmin/{build_version} (Rust)"))
+ .https_only(true)
+ .redirect(reqwest::redirect::Policy::none())
+ .timeout(Duration::from_secs(15))
+ .build()
+ .expect("failed to create SSO HTTP client")
+}
+
+fn parse_https_url(value: &str) -> anyhow::Result<url::Url> {
+ let url = url::Url::parse(value)?;
+ anyhow::ensure!(
+ url.scheme() == "https"
+ && url.has_host()
+ && url.username().is_empty()
+ && url.password().is_none()
+ && url.fragment().is_none(),
+ "SSO URLs must use https and contain no credentials or fragment"
+ );
+ Ok(url)
+}
+
+pub(crate) fn validate_issuer_url(issuer: &str) -> anyhow::Result<()> {
+ let url = parse_https_url(issuer)?;
+ anyhow::ensure!(url.query().is_none(), "SSO issuer must contain no query");
+ Ok(())
+}
+
+fn validate_metadata(metadata: &ProviderMetadata, issuer: &str) -> anyhow::Result<()> {
+ if metadata.issuer.trim_end_matches('/') != issuer.trim_end_matches('/') {
+ anyhow::bail!("provider discovery returned a different issuer");
+ }
+ parse_https_url(&metadata.authorization_endpoint)?;
+ parse_https_url(&metadata.token_endpoint)?;
+ Ok(())
+}
+
pub async fn discover(http: &reqwest::Client, sso: &SsoConfig) -> anyhow::Result<ProviderMetadata> {
+ validate_issuer_url(&sso.issuer)?;
let issuer = sso.issuer.trim_end_matches('/');
let response = http
.get(format!("{issuer}/.well-known/openid-configuration"))
@@ -56,15 +96,7 @@ pub async fn discover(http: &reqwest::Client, sso: &SsoConfig) -> anyhow::Result
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");
- }
+ validate_metadata(&metadata, issuer)?;
Ok(metadata)
}
@@ -75,7 +107,7 @@ pub fn authorize_url(
nonce: &str,
code_challenge: &str,
) -> anyhow::Result<String> {
- let mut url = url::Url::parse(&metadata.authorization_endpoint)?;
+ let mut url = parse_https_url(&metadata.authorization_endpoint)?;
url.query_pairs_mut()
.append_pair("response_type", "code")
.append_pair("client_id", &sso.client_id)
@@ -174,3 +206,80 @@ pub async fn sign_in(
.await
.map_err(|error| ApiError::Parse(error.to_string()))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn provider_client_refuses_http_before_connecting() {
+ let error = http_client("test")
+ .get("http://127.0.0.1/")
+ .send()
+ .await
+ .expect_err("plaintext provider requests must fail");
+ assert!(error.is_builder());
+ }
+
+ #[test]
+ fn issuer_requires_https_without_credentials_query_or_fragment() {
+ for issuer in [
+ "http://id.example.com",
+ "ftp://id.example.com",
+ "id.example.com",
+ "https://user:[email protected]",
+ "https://id.example.com?tenant=staff",
+ "https://id.example.com#tenant",
+ ] {
+ assert!(validate_issuer_url(issuer).is_err(), "{issuer}");
+ }
+ for issuer in [
+ "https://id.example.com",
+ "https://id.example.com/",
+ "https://id.example.com/realms/staff",
+ ] {
+ assert!(validate_issuer_url(issuer).is_ok(), "{issuer}");
+ }
+ }
+
+ #[test]
+ fn discovery_rejects_insecure_or_ambiguous_endpoints() {
+ let issuer = "https://id.example.com";
+ let valid = ProviderMetadata {
+ issuer: issuer.to_owned(),
+ authorization_endpoint: format!("{issuer}/authorize?tenant=staff"),
+ token_endpoint: format!("{issuer}/token"),
+ };
+ assert!(validate_metadata(&valid, issuer).is_ok());
+ for endpoint in [
+ "http://id.example.com/endpoint",
+ "https://",
+ "https://user:[email protected]/endpoint",
+ "https://id.example.com/endpoint#fragment",
+ ] {
+ let authorization = ProviderMetadata {
+ authorization_endpoint: endpoint.to_owned(),
+ ..valid.clone()
+ };
+ let token = ProviderMetadata {
+ token_endpoint: endpoint.to_owned(),
+ ..valid.clone()
+ };
+ assert!(
+ validate_metadata(&authorization, issuer).is_err(),
+ "{endpoint}"
+ );
+ assert!(validate_metadata(&token, issuer).is_err(), "{endpoint}");
+ }
+ }
+
+ #[test]
+ fn discovery_rejects_a_different_issuer() {
+ let metadata = ProviderMetadata {
+ issuer: "https://other.example.com".to_owned(),
+ authorization_endpoint: "https://id.example.com/authorize".to_owned(),
+ token_endpoint: "https://id.example.com/token".to_owned(),
+ };
+ assert!(validate_metadata(&metadata, "https://id.example.com").is_err());
+ }
+}
diff --git a/fluxer_admin/src/state.rs b/fluxer_admin/src/state.rs
index 353912525..9a40f1d12 100644
--- a/fluxer_admin/src/state.rs
+++ b/fluxer_admin/src/state.rs
@@ -29,6 +29,7 @@ pub struct AppState {
struct AppStateInner {
pub config: AdminConfig,
pub http_client: reqwest::Client,
+ sso_http_client: reqwest::Client,
premium_branding: Mutex<Option<(Instant, PremiumBranding)>>,
account_identity: Mutex<Option<(Instant, AccountIdentitySettings)>>,
report_reasons: Mutex<Option<Arc<[ReportReasonEntry]>>>,
@@ -41,10 +42,12 @@ impl AppState {
.user_agent(format!("FluxerAdmin/{} (Rust)", config.build_version))
.build()
.expect("failed to create HTTP client");
+ let sso_http_client = sso::http_client(&config.build_version);
Self {
inner: Arc::new(AppStateInner {
config,
http_client,
+ sso_http_client,
premium_branding: Mutex::new(None),
account_identity: Mutex::new(None),
report_reasons: Mutex::new(None),
@@ -61,6 +64,10 @@ impl AppState {
&self.inner.http_client
}
+ pub fn sso_http_client(&self) -> &reqwest::Client {
+ &self.inner.sso_http_client
+ }
+
pub fn cached_premium_branding(&self) -> Option<PremiumBranding> {
let cache = self
.inner
@@ -192,7 +199,7 @@ impl AppState {
if let Some(metadata) = cached {
return Some(metadata);
}
- let metadata = match sso::discover(self.http_client(), sso).await {
+ let metadata = match sso::discover(self.sso_http_client(), sso).await {
Ok(metadata) => metadata,
Err(error) => {
tracing::error!(%error, issuer = %sso.issuer, "SSO provider discovery failed");
diff --git a/fluxer_api/src/api/admin/AdminSsoSignIn.ts b/fluxer_api/src/api/admin/AdminSsoSignIn.ts
index a3e5d6971..ba6275507 100644
--- a/fluxer_api/src/api/admin/AdminSsoSignIn.ts
+++ b/fluxer_api/src/api/admin/AdminSsoSignIn.ts
@@ -71,7 +71,11 @@ class AdminSsoTokenRejected extends Error {}
function adminSsoConfig(): AdminSsoConfig | null {
const {issuer, clientId} = Config.admin.sso;
- return issuer && clientId ? {issuer, clientId} : null;
+ if (!issuer || !clientId) return null;
+ if (!isHttpsSsoUrl(issuer) || issuer.includes('?')) {
+ throw misconfigured('issuer must be an https URL without credentials, query or fragment');
+ }
+ return {issuer, clientId};
}
function misconfigured(reason: string): InputValidationError {
@@ -153,7 +157,9 @@ async function verifyAdminSsoIdToken(
maxTokenAge: '10 minutes',
requiredClaims: ['iat', 'exp', 'nonce'],
});
- if (Array.isArray(payload.aud) && payload.aud.length > 1 && payload['azp'] !== config.clientId) {
+ const authorizedParty = payload['azp'];
+ const requiresAuthorizedParty = Array.isArray(payload.aud) && payload.aud.length > 1;
+ if ((authorizedParty !== undefined || requiresAuthorizedParty) && authorizedParty !== config.clientId) {
throw new AdminSsoTokenRejected('azp does not match the client ID');
}
if (!nonceMatches(payload['nonce'], expectedNonce)) {
diff --git a/fluxer_api/src/api/admin/tests/AdminSsoSignIn.test.ts b/fluxer_api/src/api/admin/tests/AdminSsoSignIn.test.ts
index 3f41856ba..7300235fc 100644
--- a/fluxer_api/src/api/admin/tests/AdminSsoSignIn.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminSsoSignIn.test.ts
@@ -2,6 +2,7 @@
import {
ADMIN_CLIENT_BASIC_AUTH,
+ ADMIN_SSO_ISSUER,
ADMIN_SSO_KID,
ADMIN_SSO_NONCE,
type AdminSsoProvider,
@@ -12,8 +13,10 @@ import {
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 {server} from '@app/api/test/msw/server';
import {ADMIN_OAUTH2_APPLICATION_ID} from '@fluxer/constants/src/Core';
import {generateKeyPair} from 'jose';
+import {HttpResponse, http} from 'msw';
import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface SignInBody {
@@ -83,6 +86,15 @@ describe('Admin SSO sign-in', () => {
expect(body.user_id).toBe(admin.userId);
});
+ it.each([
+ {aud: 'admin-sso-test-client'},
+ {aud: ['admin-sso-test-client']},
+ {aud: ['admin-sso-test-client', 'other-client']},
+ ])('accepts the admin client as the authorized party with audience %j', async ({aud}) => {
+ const {status} = await signIn(idTokenClaimsJson(admin.userId, {aud, azp: 'admin-sso-test-client'}));
+ expect(status).toBe(200);
+ });
+
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);
@@ -103,6 +115,12 @@ describe('Admin SSO sign-in', () => {
['a missing nonce', {nonce: undefined}],
['an access token', {type: 'access-token'}],
['a second audience without azp', {aud: ['admin-sso-test-client', 'other-client']}],
+ ['another authorized party with a string audience', {azp: 'other-client'}],
+ ['another authorized party with a single audience array', {aud: ['admin-sso-test-client'], azp: 'other-client'}],
+ [
+ 'another authorized party with multiple audiences',
+ {aud: ['admin-sso-test-client', 'other-client'], azp: 'other-client'},
+ ],
])('refuses %s', async (_label, overrides) => {
const {status} = await signIn(idTokenClaimsJson(admin.userId, overrides));
expect(status).toBe(400);
@@ -191,4 +209,45 @@ describe('Admin SSO sign-in', () => {
Config.admin.sso.issuer = previous;
}
});
+
+ it('refuses signing keys supplied through unauthenticated HTTP discovery', async () => {
+ const previous = Config.admin.sso.issuer;
+ const issuer = ADMIN_SSO_ISSUER.replace('https:', 'http:');
+ let discoveryRequests = 0;
+ server.use(
+ http.get(`${issuer}/.well-known/openid-configuration`, () => {
+ discoveryRequests += 1;
+ return HttpResponse.json({
+ issuer,
+ jwks_uri: `${ADMIN_SSO_ISSUER}/jwks.json`,
+ id_token_signing_alg_values_supported: ['RS256'],
+ });
+ }),
+ );
+ Config.admin.sso.issuer = issuer;
+ try {
+ const {status} = await signIn(idTokenClaimsJson(admin.userId, {iss: issuer}));
+ expect(status).toBe(400);
+ expect(discoveryRequests).toBe(0);
+ expect(provider.jwksRequests()).toBe(0);
+ } finally {
+ Config.admin.sso.issuer = previous;
+ }
+ });
+
+ it.each(['http://1.1.1.1/admin-sso', 'https://1.1.1.1/admin-sso?tenant=admin'])(
+ 'refuses insecure or invalid issuer %s',
+ async (issuer) => {
+ const previous = Config.admin.sso.issuer;
+ Config.admin.sso.issuer = issuer;
+ try {
+ const {status, body} = await signIn(idTokenClaimsJson(admin.userId));
+ expect(status).toBe(400);
+ expect(body.code).toBe('INVALID_FORM_BODY');
+ expect(provider.jwksRequests()).toBe(0);
+ } finally {
+ Config.admin.sso.issuer = previous;
+ }
+ },
+ );
});
diff --git a/fluxer_docs/src/content/docs/operator/environment.mdx b/fluxer_docs/src/content/docs/operator/environment.mdx
index 9f517bc47..c84ac2ca8 100644
--- a/fluxer_docs/src/content/docs/operator/environment.mdx
+++ b/fluxer_docs/src/content/docs/operator/environment.mdx
@@ -668,7 +668,7 @@ Every origin where passkeys work, separated by commas. When it's empty, Docker C
### `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`.
+The HTTPS issuer URL of an OpenID Connect provider that staff can also use to sign in to the admin panel. The issuer must not contain credentials, a query or a fragment. Discovery and token endpoints must serve responses directly without redirects. 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. Only trusted provider administrators may set this claim; users must not be able to change it. With rexctl, use `rexctl config set FLUXER_ADMIN_SSO_ISSUER`.
### `FLUXER_ADMIN_SSO_CLIENT_ID`
diff --git a/fluxer_rexctl/internal/instance/envvars.go b/fluxer_rexctl/internal/instance/envvars.go
index 02783982b..f74cb1eb8 100644
--- a/fluxer_rexctl/internal/instance/envvars.go
+++ b/fluxer_rexctl/internal/instance/envvars.go
@@ -186,7 +186,7 @@ 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_ISSUER", "sso", "The HTTPS issuer URL of an OpenID Connect provider that staff can also use to sign in to the admin panel. The issuer must not contain credentials, a query or a fragment. Discovery and token endpoints must serve responses directly without redirects. 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. Only trusted provider administrators may set this claim; users must not be able to change it."},
{"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`."},
diff --git a/fluxer_rexctl/internal/instance/shipped.json b/fluxer_rexctl/internal/instance/shipped.json
index 180a660e9..4ca2cdf96 100644
--- a/fluxer_rexctl/internal/instance/shipped.json
+++ b/fluxer_rexctl/internal/instance/shipped.json
@@ -6,6 +6,7 @@
"04a85d483aeaf1425fbd2134f6914ebac513646f160300e0c968ea7d6b0f33a4",
"05b25c72202e242812464427ea26d4467f3b74ce8f9c92d4eda611d95b25566b",
"0b718956b039a8d8402bd9c6102322fb273159f2834509fdf23a95459c7537b9",
+ "0bf78a055c45ede0c115c39d033f8691087b1025a7308ee81bdb82168a60d488",
"0e54ce3bfec7340d76214240c4bb9dc8dd9a33dc9ce57eff70d8d15f909cf7ab",
"1263f66b22074f380e55198a32d759ae5196bb9b44d8a62473c6f41dfb770905",
"1335c63f715dab6fa0b77d012aead1343ea027e8e047357e2c1df0b653eac7e8",
diff --git a/fluxer_rexctl/internal/stack/files/.env.example b/fluxer_rexctl/internal/stack/files/.env.example
index 6704d91f4..7455f0fdc 100644
--- a/fluxer_rexctl/internal/stack/files/.env.example
+++ b/fluxer_rexctl/internal/stack/files/.env.example
@@ -953,14 +953,17 @@ 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
+# The HTTPS issuer URL of an OpenID Connect provider that staff can also use
+# to sign in to the admin panel. The issuer must not contain credentials, a
+# query or a fragment. Discovery and token endpoints must serve responses
+# directly without redirects. 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.
+# admin ACLs of that account. Only trusted provider administrators may set
+# this claim; users must not be able to change it.
# rexctl: rexctl config set FLUXER_ADMIN_SSO_ISSUER
# FLUXER_ADMIN_SSO_ISSUER=