mirror of
https://github.com/fluxerapp/fluxer.git
synced 2026-11-20 01:01:18 -08:00
fix(api): tighten oauth2 token and session handling (4223)
This commit is contained in:
1 parent
f4702e3b80
commit
97d282152c
17 files changed
+354
-234
No files matched your search
Generated
+5
-2
@@ -16190,14 +16190,17 @@
|
||||
"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"},
|
||||
"refresh_token": {
|
||||
"description": "The refresh token for obtaining new access tokens. Not issued to every client",
|
||||
"type": "string"
|
||||
},
|
||||
"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"],
|
||||
"required": ["access_token", "token_type", "expires_in", "scope", "user_id"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"AdminSsoIdentityMigrateRequest": {
|
||||
|
||||
@@ -16,13 +16,15 @@ pub struct UserInfo {
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
pub fn authorize_url(config: &AdminConfig, state: &str) -> String {
|
||||
pub fn authorize_url(config: &AdminConfig, state: &str, code_challenge: &str) -> String {
|
||||
let params = [
|
||||
("client_id", config.oauth_client_id.as_str()),
|
||||
("redirect_uri", config.oauth_redirect_uri.as_str()),
|
||||
("response_type", "code"),
|
||||
("scope", ADMIN_OAUTH_SCOPE),
|
||||
("state", state),
|
||||
("code_challenge", code_challenge),
|
||||
("code_challenge_method", "S256"),
|
||||
];
|
||||
let query = params
|
||||
.iter()
|
||||
@@ -36,6 +38,7 @@ pub async fn exchange_code(
|
||||
http_client: &reqwest::Client,
|
||||
config: &AdminConfig,
|
||||
code: &str,
|
||||
code_verifier: &str,
|
||||
) -> anyhow::Result<TokenResponse> {
|
||||
let response = with_proxy_client_ip_header(
|
||||
http_client.post(format!("{}/oauth2/token", config.api_endpoint)),
|
||||
@@ -49,6 +52,7 @@ pub async fn exchange_code(
|
||||
("redirect_uri", config.oauth_redirect_uri.as_str()),
|
||||
("client_id", config.oauth_client_id.as_str()),
|
||||
("client_secret", config.oauth_client_secret.as_str()),
|
||||
("code_verifier", code_verifier),
|
||||
]
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{}={}", k, urlencoding::encode(v)))
|
||||
|
||||
+127
-47
@@ -6,11 +6,11 @@ use crate::{
|
||||
middleware::csrf,
|
||||
oauth2,
|
||||
session::{
|
||||
self, SESSION_COOKIE_NAME, SESSION_MAX_AGE, admin_cookie_path, append_cookies,
|
||||
clear_cookie_values,
|
||||
self, SESSION_COOKIE_NAME, SESSION_MAX_AGE, admin_cookie_path, append_cookie,
|
||||
append_cookies, clear_cookie_values,
|
||||
},
|
||||
sso,
|
||||
state::AppState,
|
||||
state::{AppState, SIGN_IN_FLOW_TTL},
|
||||
templates::{layout_scripts::HISTORY_CACHE_CLEAR_SCRIPT, pages::login},
|
||||
};
|
||||
use axum::{
|
||||
@@ -29,13 +29,14 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
const OAUTH_STATE_MAX_AGE_SECONDS: u64 = 1800;
|
||||
const OAUTH_STATE_NONCE_BYTES: usize = 16;
|
||||
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_FLOW_COOKIE: &str = "admin_oauth_flow";
|
||||
const SSO_FLOW_COOKIE: &str = "admin_sso_flow";
|
||||
const OAUTH_FINISH_HEADER: &str = "x-fluxer-admin-oauth";
|
||||
const OAUTH_STATE_PURPOSE: &str = "oauth";
|
||||
const SSO_STATE_PURPOSE: &str = "sso";
|
||||
@@ -59,7 +60,6 @@ struct CallbackQuery {
|
||||
struct CallbackFinishBody {
|
||||
code: String,
|
||||
state: String,
|
||||
verifier: String,
|
||||
iss: Option<String>,
|
||||
}
|
||||
|
||||
@@ -108,16 +108,21 @@ async fn auth_start(State(state): State<AppState>) -> Response {
|
||||
}
|
||||
let verifier = random_nonce();
|
||||
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(
|
||||
let authorize_url =
|
||||
oauth2::authorize_url(config, &oauth_state, &sso::code_challenge(&verifier));
|
||||
let mut response = Html(oauth_start_page(
|
||||
config,
|
||||
OAUTH_FLOW_STORAGE_KEY,
|
||||
OAUTH_FAILED,
|
||||
&authorize_url,
|
||||
&oauth_state,
|
||||
&verifier,
|
||||
))
|
||||
.into_response()
|
||||
.into_response();
|
||||
append_cookie(
|
||||
&mut response,
|
||||
&flow_cookie(config, OAUTH_FLOW_COOKIE, OAUTH_STATE_PURPOSE, &verifier),
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
async fn sso_start(State(state): State<AppState>) -> Response {
|
||||
@@ -144,15 +149,19 @@ async fn sso_start(State(state): State<AppState>) -> Response {
|
||||
return Redirect::to(&format!("{base}/login?error={SSO_UNAVAILABLE}")).into_response();
|
||||
}
|
||||
};
|
||||
Html(oauth_start_page(
|
||||
let mut response = Html(oauth_start_page(
|
||||
config,
|
||||
SSO_FLOW_STORAGE_KEY,
|
||||
SSO_FAILED,
|
||||
&authorize_url,
|
||||
&sso_state,
|
||||
&verifier,
|
||||
))
|
||||
.into_response()
|
||||
.into_response();
|
||||
append_cookie(
|
||||
&mut response,
|
||||
&flow_cookie(config, SSO_FLOW_COOKIE, SSO_STATE_PURPOSE, &verifier),
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
async fn sso_callback_page(
|
||||
@@ -178,6 +187,19 @@ async fn sso_callback_finish(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<CallbackFinishBody>,
|
||||
) -> Response {
|
||||
let mut response = sso_callback_attempt(&state, &headers, body).await;
|
||||
append_cookies(
|
||||
&mut response,
|
||||
&clear_cookie_values(SSO_FLOW_COOKIE, state.config()),
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
async fn sso_callback_attempt(
|
||||
state: &AppState,
|
||||
headers: &HeaderMap,
|
||||
body: CallbackFinishBody,
|
||||
) -> Response {
|
||||
let config = state.config();
|
||||
let base = &config.base_path;
|
||||
@@ -188,18 +210,19 @@ async fn sso_callback_finish(
|
||||
let Some(sso_config) = config.sso.as_ref() else {
|
||||
return failed(StatusCode::NOT_FOUND, SSO_FAILED);
|
||||
};
|
||||
if !has_finish_header(&headers) {
|
||||
if !has_finish_header(headers) {
|
||||
return failed(StatusCode::FORBIDDEN, SSO_FAILED);
|
||||
}
|
||||
if !verify_oauth_state(
|
||||
&config.secret_key_base,
|
||||
let Some(verifier) = claim_sign_in_flow(
|
||||
state,
|
||||
headers,
|
||||
SSO_FLOW_COOKIE,
|
||||
SSO_STATE_PURPOSE,
|
||||
&body.state,
|
||||
&body.verifier,
|
||||
) {
|
||||
tracing::error!("SSO state token is invalid, expired, or malformed");
|
||||
) else {
|
||||
tracing::error!("SSO state token is missing, reused, 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('/')
|
||||
{
|
||||
@@ -214,7 +237,7 @@ async fn sso_callback_finish(
|
||||
&metadata,
|
||||
sso_config,
|
||||
&body.code,
|
||||
&body.verifier,
|
||||
&verifier,
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -224,7 +247,7 @@ async fn sso_callback_finish(
|
||||
return failed(StatusCode::BAD_REQUEST, SSO_FAILED);
|
||||
}
|
||||
};
|
||||
let nonce = sso::nonce(&config.secret_key_base, &body.verifier);
|
||||
let nonce = sso::nonce(&config.secret_key_base, &verifier);
|
||||
let signed_in = match sso::sign_in(state.http_client(), config, &id_token, &nonce).await {
|
||||
Ok(signed_in) => signed_in,
|
||||
Err(err) => {
|
||||
@@ -237,7 +260,7 @@ async fn sso_callback_finish(
|
||||
return failed(StatusCode::BAD_GATEWAY, code);
|
||||
}
|
||||
};
|
||||
finish_admin_sign_in(&state, &signed_in.user_id, &signed_in.access_token).await
|
||||
finish_admin_sign_in(state, &signed_in.user_id, &signed_in.access_token).await
|
||||
}
|
||||
|
||||
fn has_finish_header(headers: &HeaderMap) -> bool {
|
||||
@@ -270,6 +293,19 @@ async fn oauth2_callback_finish(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<CallbackFinishBody>,
|
||||
) -> Response {
|
||||
let mut response = oauth2_callback_attempt(&state, &headers, body).await;
|
||||
append_cookies(
|
||||
&mut response,
|
||||
&clear_cookie_values(OAUTH_FLOW_COOKIE, state.config()),
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
async fn oauth2_callback_attempt(
|
||||
state: &AppState,
|
||||
headers: &HeaderMap,
|
||||
body: CallbackFinishBody,
|
||||
) -> Response {
|
||||
let config = state.config();
|
||||
let base = &config.base_path;
|
||||
@@ -282,7 +318,7 @@ async fn oauth2_callback_finish(
|
||||
);
|
||||
}
|
||||
|
||||
if !has_finish_header(&headers) {
|
||||
if !has_finish_header(headers) {
|
||||
return oauth_finish_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
&format!("{base}/login?error=oauth_failed"),
|
||||
@@ -290,32 +326,34 @@ async fn oauth2_callback_finish(
|
||||
);
|
||||
}
|
||||
|
||||
if !verify_oauth_state(
|
||||
&config.secret_key_base,
|
||||
let Some(verifier) = claim_sign_in_flow(
|
||||
state,
|
||||
headers,
|
||||
OAUTH_FLOW_COOKIE,
|
||||
OAUTH_STATE_PURPOSE,
|
||||
&body.state,
|
||||
&body.verifier,
|
||||
) {
|
||||
tracing::error!("OAuth2 state token is invalid, expired, or malformed");
|
||||
) else {
|
||||
tracing::error!("OAuth2 state token is missing, reused, invalid, expired, or malformed");
|
||||
return oauth_finish_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
&format!("{base}/login?error=oauth_failed"),
|
||||
&[],
|
||||
);
|
||||
}
|
||||
|
||||
let token = match oauth2::exchange_code(state.http_client(), config, &body.code).await {
|
||||
Ok(t) => t,
|
||||
Err(err) => {
|
||||
tracing::error!(%err, "OAuth2 token exchange failed");
|
||||
return oauth_finish_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
&format!("{base}/login?error=oauth_failed"),
|
||||
&[],
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let token =
|
||||
match oauth2::exchange_code(state.http_client(), config, &body.code, &verifier).await {
|
||||
Ok(t) => t,
|
||||
Err(err) => {
|
||||
tracing::error!(%err, "OAuth2 token exchange failed");
|
||||
return oauth_finish_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
&format!("{base}/login?error=oauth_failed"),
|
||||
&[],
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let user = match oauth2::fetch_user_info(state.http_client(), config, &token.access_token).await
|
||||
{
|
||||
Ok(u) => u,
|
||||
@@ -329,7 +367,51 @@ async fn oauth2_callback_finish(
|
||||
}
|
||||
};
|
||||
|
||||
finish_admin_sign_in(&state, &user.id, &token.access_token).await
|
||||
finish_admin_sign_in(state, &user.id, &token.access_token).await
|
||||
}
|
||||
|
||||
fn flow_cookie_purpose(purpose: &str) -> String {
|
||||
format!("{purpose}-cookie")
|
||||
}
|
||||
|
||||
fn flow_cookie_value(secret_key: &str, purpose: &str, verifier: &str) -> String {
|
||||
let signed = generate_oauth_state(secret_key, &flow_cookie_purpose(purpose), verifier);
|
||||
format!("{verifier}.{signed}")
|
||||
}
|
||||
|
||||
fn issued_flow_verifier(secret_key: &str, purpose: &str, cookie_value: &str) -> Option<String> {
|
||||
let (verifier, signed) = cookie_value.split_once('.')?;
|
||||
verify_oauth_state(secret_key, &flow_cookie_purpose(purpose), signed, verifier)
|
||||
.then(|| verifier.to_owned())
|
||||
}
|
||||
|
||||
fn flow_cookie(config: &AdminConfig, name: &str, purpose: &str, verifier: &str) -> String {
|
||||
let secure = if config.secure_cookies() {
|
||||
"; Secure"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let value = flow_cookie_value(&config.secret_key_base, purpose, verifier);
|
||||
format!(
|
||||
"{name}={value}; Path={}; HttpOnly; SameSite=Lax; Max-Age={}{secure}",
|
||||
admin_cookie_path(config),
|
||||
SIGN_IN_FLOW_TTL.as_secs()
|
||||
)
|
||||
}
|
||||
|
||||
fn claim_sign_in_flow(
|
||||
state: &AppState,
|
||||
headers: &HeaderMap,
|
||||
cookie_name: &str,
|
||||
purpose: &str,
|
||||
oauth_state: &str,
|
||||
) -> Option<String> {
|
||||
let secret_key = &state.config().secret_key_base;
|
||||
let verifier =
|
||||
issued_flow_verifier(secret_key, purpose, &extract_cookie(headers, cookie_name)?)?;
|
||||
(verify_oauth_state(secret_key, purpose, oauth_state, &verifier)
|
||||
&& state.claim_sign_in_flow(&verifier))
|
||||
.then_some(verifier)
|
||||
}
|
||||
|
||||
async fn finish_admin_sign_in(state: &AppState, user_id: &str, access_token: &str) -> Response {
|
||||
@@ -421,13 +503,11 @@ fn oauth_start_page(
|
||||
failure_code: &str,
|
||||
authorize_url: &str,
|
||||
state: &str,
|
||||
verifier: &str,
|
||||
) -> String {
|
||||
let storage_key = json_string(storage_key);
|
||||
let authorize_url = json_string(authorize_url);
|
||||
let login_url = json_string(&format!("{}/login?error={failure_code}", config.base_path));
|
||||
let state = json_string(state);
|
||||
let verifier = json_string(verifier);
|
||||
format!(
|
||||
r#"<!doctype html>
|
||||
<html lang="en">
|
||||
@@ -441,7 +521,7 @@ fn oauth_start_page(
|
||||
<script>
|
||||
{HISTORY_CACHE_CLEAR_SCRIPT}
|
||||
(function () {{
|
||||
var flow = {{state: {state}, verifier: {verifier}, createdAt: Date.now()}};
|
||||
var flow = {{state: {state}, createdAt: Date.now()}};
|
||||
try {{
|
||||
window.sessionStorage.setItem({storage_key}, JSON.stringify(flow));
|
||||
window.location.replace({authorize_url});
|
||||
@@ -501,7 +581,7 @@ fn oauth_callback_page(
|
||||
}} catch (error) {{
|
||||
flow = null;
|
||||
}}
|
||||
if (!flow || flow.state !== state || !flow.verifier) {{
|
||||
if (!flow || flow.state !== state) {{
|
||||
fail(false);
|
||||
return;
|
||||
}}
|
||||
@@ -513,7 +593,7 @@ fn oauth_callback_page(
|
||||
'Content-Type': 'application/json',
|
||||
'X-Fluxer-Admin-OAuth': '1'
|
||||
}},
|
||||
body: JSON.stringify({{code: code, state: state, verifier: flow.verifier, iss: iss}})
|
||||
body: JSON.stringify({{code: code, state: state, iss: iss}})
|
||||
}})
|
||||
.then(function (response) {{
|
||||
return response.json().catch(function () {{ return null; }});
|
||||
@@ -609,7 +689,7 @@ fn verify_oauth_state(secret_key: &str, purpose: &str, state: &str, verifier: &s
|
||||
return false;
|
||||
}
|
||||
let now = now_seconds();
|
||||
issued_at <= now && now - issued_at <= OAUTH_STATE_MAX_AGE_SECONDS
|
||||
issued_at <= now && now - issued_at <= SIGN_IN_FLOW_TTL.as_secs()
|
||||
}
|
||||
|
||||
fn encode_oauth_state_payload(
|
||||
|
||||
@@ -12,7 +12,9 @@ use crate::{
|
||||
sso::{self, ProviderMetadata},
|
||||
};
|
||||
use anyhow::Context as _;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
collections::{HashSet, VecDeque},
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
@@ -21,6 +23,8 @@ 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);
|
||||
pub const SIGN_IN_FLOW_TTL: Duration = Duration::from_secs(600);
|
||||
const MAX_CLAIMED_SIGN_IN_FLOWS: usize = 100_000;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
@@ -35,6 +39,34 @@ struct AppStateInner {
|
||||
account_identity: Mutex<Option<(Instant, AccountIdentitySettings)>>,
|
||||
report_reasons: Mutex<Option<Arc<[ReportReasonEntry]>>>,
|
||||
sso_provider: Mutex<Option<(Instant, ProviderMetadata)>>,
|
||||
claimed_sign_in_flows: Mutex<ClaimedSignInFlows>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClaimedSignInFlows {
|
||||
keys: HashSet<[u8; 32]>,
|
||||
by_expiry: VecDeque<(Instant, [u8; 32])>,
|
||||
}
|
||||
|
||||
impl ClaimedSignInFlows {
|
||||
fn claim(&mut self, key: [u8; 32], now: Instant) -> bool {
|
||||
while let Some(&(expires_at, expired)) = self.by_expiry.front() {
|
||||
if expires_at > now {
|
||||
break;
|
||||
}
|
||||
self.by_expiry.pop_front();
|
||||
self.keys.remove(&expired);
|
||||
}
|
||||
if self.keys.contains(&key) {
|
||||
return false;
|
||||
}
|
||||
if self.keys.len() >= MAX_CLAIMED_SIGN_IN_FLOWS {
|
||||
return true;
|
||||
}
|
||||
self.keys.insert(key);
|
||||
self.by_expiry.push_back((now + SIGN_IN_FLOW_TTL, key));
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -57,6 +89,7 @@ impl AppState {
|
||||
account_identity: Mutex::new(None),
|
||||
report_reasons: Mutex::new(None),
|
||||
sso_provider: Mutex::new(None),
|
||||
claimed_sign_in_flows: Mutex::new(ClaimedSignInFlows::default()),
|
||||
}),
|
||||
})
|
||||
}
|
||||
@@ -73,6 +106,15 @@ impl AppState {
|
||||
&self.inner.sso_http_client
|
||||
}
|
||||
|
||||
pub fn claim_sign_in_flow(&self, verifier: &str) -> bool {
|
||||
let key: [u8; 32] = Sha256::digest(verifier.as_bytes()).into();
|
||||
self.inner
|
||||
.claimed_sign_in_flows
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
.claim(key, Instant::now())
|
||||
}
|
||||
|
||||
pub fn cached_premium_branding(&self) -> Option<PremiumBranding> {
|
||||
let cache = self
|
||||
.inner
|
||||
|
||||
@@ -70,7 +70,7 @@ import {deleteChannelMessageSearchDocuments} from '@app/api/search/MessageSearch
|
||||
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
|
||||
import {serializeChannelForAudit} from '@app/api/utils/AuditSerializationUtils';
|
||||
import {applyProtectedOverwriteBits, permissionWriteMask, protectedThreadBits} from '@app/api/utils/featureUtils';
|
||||
import {overwriteAppliesToTarget, overwriteGrantedBits} from '@app/api/utils/PermissionUtils';
|
||||
import {overwriteGrantedBits} from '@app/api/utils/PermissionUtils';
|
||||
import {isRegionPickable, type VoiceAvailabilityService} from '@app/api/voice/VoiceAvailabilityService';
|
||||
import type {VoiceRegionAvailability} from '@app/api/voice/VoiceModel';
|
||||
import type {WebhookRepository} from '@app/api/webhook/WebhookRepository';
|
||||
@@ -365,35 +365,25 @@ export class ChannelOperationsService {
|
||||
});
|
||||
const writeMask = permissionWriteMask(actor);
|
||||
const channelPermissions = actor.threadBits ? withImplicitThreadBits(gatewayPermissions) : gatewayPermissions;
|
||||
const roleIds = await this.listRoleIds(guildId);
|
||||
permissionOverwrites = new Map();
|
||||
for (const [index, overwrite] of (data.permission_overwrites ?? []).entries()) {
|
||||
const type = overwrite.id === guildId ? 0 : overwrite.type;
|
||||
const targetId = type === 0 ? createRoleID(overwrite.id) : createUserID(overwrite.id);
|
||||
for (const overwrite of data.permission_overwrites ?? []) {
|
||||
const targetId = overwrite.type === 0 ? createRoleID(overwrite.id) : createUserID(overwrite.id);
|
||||
const existing = previousPermissionOverwrites?.get(targetId);
|
||||
const sameType = existing?.type === type;
|
||||
if (!sameType && !overwriteAppliesToTarget({id: overwrite.id, type}, guildId, roleIds)) {
|
||||
throw InputValidationError.fromCode(
|
||||
`permission_overwrites.${index}.id`,
|
||||
ValidationErrorCodes.INVALID_ROLE_ID,
|
||||
{roleId: overwrite.id.toString()},
|
||||
);
|
||||
}
|
||||
const protectedBits = applyProtectedOverwriteBits(
|
||||
{
|
||||
allow: (overwrite.allow ? BigInt(overwrite.allow) : 0n) & writeMask,
|
||||
deny: (overwrite.deny ? BigInt(overwrite.deny) : 0n) & writeMask,
|
||||
},
|
||||
{
|
||||
allow: sameType ? existing.allow : 0n,
|
||||
deny: sameType ? existing.deny : 0n,
|
||||
allow: existing?.allow ?? 0n,
|
||||
deny: existing?.deny ?? 0n,
|
||||
},
|
||||
actor,
|
||||
);
|
||||
permissionOverwrites.set(
|
||||
targetId,
|
||||
new ChannelPermissionOverwrite({
|
||||
type,
|
||||
type: overwrite.type,
|
||||
allow_: protectedBits.allow,
|
||||
deny_: protectedBits.deny,
|
||||
}),
|
||||
@@ -415,11 +405,9 @@ export class ChannelOperationsService {
|
||||
if (!isOwner) {
|
||||
const targetIds = new Set([...(previousPermissionOverwrites?.keys() ?? []), ...permissionOverwrites.keys()]);
|
||||
for (const targetId of targetIds) {
|
||||
const previous = previousPermissionOverwrites?.get(targetId);
|
||||
const grantedBits = overwriteGrantedBits(
|
||||
previous,
|
||||
previousPermissionOverwrites?.get(targetId),
|
||||
permissionOverwrites.get(targetId),
|
||||
previous ? overwriteAppliesToTarget({id: targetId, type: previous.type}, guildId, roleIds) : true,
|
||||
);
|
||||
if ((grantedBits & ~keptBits & ~channelPermissions) !== 0n) {
|
||||
throw new MissingPermissionsError();
|
||||
@@ -867,11 +855,6 @@ export class ChannelOperationsService {
|
||||
}
|
||||
}
|
||||
|
||||
private async listRoleIds(guildId: GuildID): Promise<Set<bigint>> {
|
||||
const roles = await this.guildRepository.listRoles(guildId);
|
||||
return new Set(roles.map((role) => role.id));
|
||||
}
|
||||
|
||||
private async checkOverwritePermission(params: {
|
||||
guildId: GuildID;
|
||||
userId: UserID;
|
||||
@@ -906,16 +889,8 @@ export class ChannelOperationsService {
|
||||
userId: params.userId,
|
||||
channelId: channel.id,
|
||||
});
|
||||
const type = params.overwriteId === channel.guildId ? 0 : params.overwrite.type;
|
||||
const targetId = type === 0 ? createRoleID(params.overwriteId) : createUserID(params.overwriteId);
|
||||
const targetId = params.overwrite.type === 0 ? createRoleID(params.overwriteId) : createUserID(params.overwriteId);
|
||||
const existing = channel.permissionOverwrites?.get(targetId);
|
||||
const sameType = existing?.type === type;
|
||||
const roleIds = await this.listRoleIds(channel.guildId);
|
||||
if (!sameType && !overwriteAppliesToTarget({id: params.overwriteId, type}, channel.guildId, roleIds)) {
|
||||
throw InputValidationError.fromCode('overwrite_id', ValidationErrorCodes.INVALID_ROLE_ID, {
|
||||
roleId: params.overwriteId.toString(),
|
||||
});
|
||||
}
|
||||
const actor = await resolveProtectedBitActor({
|
||||
guildId: channel.guildId,
|
||||
userId: params.userId,
|
||||
@@ -930,25 +905,19 @@ export class ChannelOperationsService {
|
||||
deny: params.overwrite.deny_ & writeMask,
|
||||
},
|
||||
{
|
||||
allow: sameType ? existing.allow : 0n,
|
||||
deny: sameType ? existing.deny : 0n,
|
||||
allow: existing?.allow ?? 0n,
|
||||
deny: existing?.deny ?? 0n,
|
||||
},
|
||||
actor,
|
||||
);
|
||||
const sanitizedAllow = protectedBits.allow;
|
||||
const sanitizedDeny = protectedBits.deny;
|
||||
const hasAdministrator = (userPermissions & Permissions.ADMINISTRATOR) !== 0n;
|
||||
const grantedBits = overwriteGrantedBits(
|
||||
existing,
|
||||
{type, allow: sanitizedAllow, deny: sanitizedDeny},
|
||||
existing
|
||||
? overwriteAppliesToTarget({id: params.overwriteId, type: existing.type}, channel.guildId, roleIds)
|
||||
: true,
|
||||
);
|
||||
const grantedBits = overwriteGrantedBits(existing, {allow: sanitizedAllow, deny: sanitizedDeny});
|
||||
const effectivePermissions = actor.threadBits ? withImplicitThreadBits(userPermissions) : userPermissions;
|
||||
if (!hasAdministrator && (grantedBits & ~effectivePermissions) !== 0n) throw new MissingPermissionsError();
|
||||
const nextOverwrite = new ChannelPermissionOverwrite({
|
||||
type,
|
||||
type: params.overwrite.type,
|
||||
allow_: sanitizedAllow,
|
||||
deny_: sanitizedDeny,
|
||||
});
|
||||
|
||||
@@ -36,7 +36,6 @@ import type {Channel} from '@app/api/models/Channel';
|
||||
import {ChannelPermissionOverwrite} from '@app/api/models/ChannelPermissionOverwrite';
|
||||
import {serializeChannelForAudit} from '@app/api/utils/AuditSerializationUtils';
|
||||
import {applyProtectedOverwriteBits, permissionWriteMask, protectedThreadBits} from '@app/api/utils/featureUtils';
|
||||
import {overwriteAppliesToTarget, overwriteGrantedBits} from '@app/api/utils/PermissionUtils';
|
||||
import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
|
||||
import {ALL_PERMISSIONS, ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
|
||||
import {ContentWarningLevel, GuildFeatures, resolveVoiceChannelBitrate} from '@fluxer/constants/src/GuildConstants';
|
||||
@@ -96,11 +95,7 @@ export class ChannelOperationsService {
|
||||
}
|
||||
const newPosition = ChannelHelpers.getNextGlobalChannelPosition(params.data.type, parentId, channels);
|
||||
let permissionOverwrites: Map<RoleID | UserID, PermissionOverwrite> | null = null;
|
||||
const requestedOverwrites =
|
||||
params.data.permission_overwrites?.map((overwrite) => ({
|
||||
...overwrite,
|
||||
type: overwrite.id === params.guildId ? 0 : overwrite.type,
|
||||
})) ?? null;
|
||||
const requestedOverwrites = params.data.permission_overwrites ?? null;
|
||||
if (requestedOverwrites) {
|
||||
const canManageRoles = await this.gatewayService.checkPermission({
|
||||
guildId: params.guildId,
|
||||
@@ -109,17 +104,6 @@ export class ChannelOperationsService {
|
||||
channelId: parentId ?? undefined,
|
||||
});
|
||||
if (!canManageRoles) throw new MissingPermissionsError();
|
||||
const roles = await this.guildRepository.listRoles(params.guildId);
|
||||
const roleIds = new Set(roles.map((role) => role.id));
|
||||
for (const [index, overwrite] of requestedOverwrites.entries()) {
|
||||
if (overwrite.type === 1 && !overwriteAppliesToTarget(overwrite, params.guildId, roleIds)) {
|
||||
throw InputValidationError.fromCode(
|
||||
`permission_overwrites.${index}.id`,
|
||||
ValidationErrorCodes.INVALID_ROLE_ID,
|
||||
{roleId: overwrite.id.toString()},
|
||||
);
|
||||
}
|
||||
}
|
||||
const basePermissions = await this.gatewayService.getUserPermissions({
|
||||
guildId: params.guildId,
|
||||
userId: params.userId,
|
||||
@@ -517,16 +501,13 @@ export class ChannelOperationsService {
|
||||
}),
|
||||
)
|
||||
: parent.permissionOverwrites;
|
||||
const roleIds = new Set((await this.guildRepository.listRoles(params.guildId)).map((role) => role.id));
|
||||
const targetIds = new Set([...child.permissionOverwrites.keys(), ...incomingOverwrites.keys()]);
|
||||
for (const targetId of targetIds) {
|
||||
const existing = child.permissionOverwrites.get(targetId);
|
||||
const grantedBits = overwriteGrantedBits(
|
||||
existing,
|
||||
incomingOverwrites.get(targetId),
|
||||
existing ? overwriteAppliesToTarget({id: targetId, type: existing.type}, params.guildId, roleIds) : true,
|
||||
);
|
||||
if ((grantedBits & ~userPermissions) !== 0n) throw new MissingPermissionsError();
|
||||
for (const [targetId, existing] of child.permissionOverwrites) {
|
||||
const incomingDeny = incomingOverwrites.get(targetId)?.deny ?? 0n;
|
||||
if ((existing.deny & ~incomingDeny & ~userPermissions) !== 0n) throw new MissingPermissionsError();
|
||||
}
|
||||
for (const [targetId, incoming] of incomingOverwrites) {
|
||||
const existingAllow = child.permissionOverwrites.get(targetId)?.allow ?? 0n;
|
||||
if ((incoming.allow & ~existingAllow & ~userPermissions) !== 0n) throw new MissingPermissionsError();
|
||||
}
|
||||
await this.channelRepository.channelData.upsert({
|
||||
...child.toRow(),
|
||||
|
||||
@@ -9,7 +9,7 @@ import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
|
||||
import {SudoModeMiddleware} from '@app/api/middleware/SudoModeMiddleware';
|
||||
import {parseOAuth2Scope} from '@app/api/oauth/OAuth2ScopeUtils';
|
||||
import {RateLimitConfigs} from '@app/api/RateLimitConfig';
|
||||
import type {HonoApp} from '@app/api/types/HonoEnv';
|
||||
import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';
|
||||
import {Validator} from '@app/api/Validator';
|
||||
import {SudoVerificationSchema} from '@fluxer/schema/src/domains/auth/AuthSchemas';
|
||||
import {
|
||||
@@ -34,6 +34,13 @@ import {
|
||||
RevokeRequestForm,
|
||||
TokenRequest,
|
||||
} from '@fluxer/schema/src/domains/oauth/OAuthSchemas';
|
||||
import type {Context} from 'hono';
|
||||
|
||||
function sessionUserFromCtx(ctx: Context<HonoEnv>) {
|
||||
if (ctx.get('authTokenType') !== 'session') return null;
|
||||
const user = ctx.get('user');
|
||||
return user && !user.isBot ? user : null;
|
||||
}
|
||||
|
||||
export function OAuth2Controller(app: HonoApp) {
|
||||
app.get(
|
||||
@@ -43,7 +50,7 @@ export function OAuth2Controller(app: HonoApp) {
|
||||
async (ctx) => {
|
||||
const q = ctx.req.valid('query');
|
||||
if (q.prompt === 'none') {
|
||||
const user = ctx.get('user');
|
||||
const user = sessionUserFromCtx(ctx);
|
||||
const errorRedirectBase = await ctx
|
||||
.get('oauth2Service')
|
||||
.resolveErrorRedirectBase(q.client_id.toString(), q.redirect_uri ?? undefined);
|
||||
@@ -53,11 +60,10 @@ export function OAuth2Controller(app: HonoApp) {
|
||||
errorUrl.searchParams.set('error', 'login_required');
|
||||
return ctx.redirect(errorUrl.toString(), 302);
|
||||
}
|
||||
const requestedScopes = new Set(parseOAuth2Scope(q.scope));
|
||||
const nonBotScopes = [...requestedScopes].filter((s) => s !== 'bot');
|
||||
if (nonBotScopes.length > 0) {
|
||||
const requestedScopes = parseOAuth2Scope(q.scope);
|
||||
const authorizedScopes = new Set<string>();
|
||||
if (!requestedScopes.includes('bot')) {
|
||||
const refreshTokens = await ctx.get('oauth2TokenRepository').listRefreshTokensForUser(user.id);
|
||||
const authorizedScopes = new Set<string>();
|
||||
for (const token of refreshTokens) {
|
||||
if (token.applicationId.toString() === q.client_id.toString()) {
|
||||
for (const scope of token.scope) {
|
||||
@@ -65,10 +71,10 @@ export function OAuth2Controller(app: HonoApp) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!nonBotScopes.every((s) => authorizedScopes.has(s))) {
|
||||
errorUrl.searchParams.set('error', 'consent_required');
|
||||
return ctx.redirect(errorUrl.toString(), 302);
|
||||
}
|
||||
}
|
||||
if (!requestedScopes.every((s) => authorizedScopes.has(s))) {
|
||||
errorUrl.searchParams.set('error', 'consent_required');
|
||||
return ctx.redirect(errorUrl.toString(), 302);
|
||||
}
|
||||
try {
|
||||
const {redirectTo} = await ctx.get('oauth2Service').authorizeAndConsent({
|
||||
@@ -77,7 +83,7 @@ export function OAuth2Controller(app: HonoApp) {
|
||||
scope: q.scope,
|
||||
state: q.state ?? undefined,
|
||||
codeChallenge: q.code_challenge,
|
||||
codeChallengeMethod: q.code_challenge_method as 'S256' | 'plain' | undefined,
|
||||
codeChallengeMethod: q.code_challenge_method,
|
||||
userId: user.id,
|
||||
});
|
||||
return ctx.redirect(redirectTo, 302);
|
||||
@@ -254,7 +260,7 @@ export function OAuth2Controller(app: HonoApp) {
|
||||
}),
|
||||
async (ctx) => {
|
||||
const appId = ctx.req.valid('param').id;
|
||||
const user = ctx.get('user');
|
||||
const user = sessionUserFromCtx(ctx);
|
||||
const response = await ctx.get('oauth2RequestService').getApplicationPublic(appId, user?.id);
|
||||
return ctx.json(response);
|
||||
},
|
||||
|
||||
@@ -136,7 +136,7 @@ export class OAuth2RequestService {
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
scope?: string;
|
||||
refresh_token: string;
|
||||
refresh_token?: string;
|
||||
}): OAuth2TokenResponse {
|
||||
if (!response.scope) {
|
||||
throw new InvalidGrantError();
|
||||
@@ -145,7 +145,7 @@ export class OAuth2RequestService {
|
||||
access_token: response.access_token,
|
||||
token_type: response.token_type,
|
||||
expires_in: response.expires_in,
|
||||
refresh_token: response.refresh_token,
|
||||
...(response.refresh_token ? {refresh_token: response.refresh_token} : {}),
|
||||
scope: response.scope,
|
||||
};
|
||||
}
|
||||
@@ -245,7 +245,7 @@ export class OAuth2RequestService {
|
||||
scope: params.body.scope,
|
||||
state: params.body.state ?? undefined,
|
||||
codeChallenge: params.body.code_challenge,
|
||||
codeChallengeMethod: params.body.code_challenge_method as 'S256' | 'plain' | undefined,
|
||||
codeChallengeMethod: params.body.code_challenge_method,
|
||||
userId: params.userId,
|
||||
});
|
||||
const authCode = (() => {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import {createHash} from 'node:crypto';
|
||||
import type {ApiContext} from '@app/api/ApiContext';
|
||||
import type {ApplicationID, UserID} from '@app/api/BrandedTypes';
|
||||
import {type ApplicationID, createApplicationID, type UserID} from '@app/api/BrandedTypes';
|
||||
import {Config} from '@app/api/Config';
|
||||
import type {
|
||||
OAuth2AccessTokenRow,
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
} from '@app/api/database/types/OAuth2Types';
|
||||
import {Logger} from '@app/api/Logger';
|
||||
import type {Application} from '@app/api/models/Application';
|
||||
import type {OAuth2AuthorizationCode} from '@app/api/models/OAuth2AuthorizationCode';
|
||||
import {filterOAuth2ScopeSet, isOAuth2Scope, parseOAuth2Scope, sortOAuth2Scopes} from '@app/api/oauth/OAuth2ScopeUtils';
|
||||
import {ACCESS_TOKEN_TTL_SECONDS} from '@app/api/oauth/OAuth2TokenConstants';
|
||||
import type {ApplicationRepository} from '@app/api/oauth/repositories/ApplicationRepository';
|
||||
@@ -19,6 +20,7 @@ import {isSignInRefused} from '@app/api/user/UserHelpers';
|
||||
import {mapUserToOAuthResponse} from '@app/api/user/UserMappers';
|
||||
import {randomBase64Url} from '@app/api/utils/SecretHash';
|
||||
import type {StoredSecretVerifier} from '@app/api/utils/StoredSecret';
|
||||
import {ADMIN_OAUTH2_APPLICATION_ID} from '@fluxer/constants/src/Core';
|
||||
import {InvalidRequestError} from '@fluxer/errors/src/domains/core/InvalidRequestError';
|
||||
import {InvalidTokenError} from '@fluxer/errors/src/domains/core/InvalidTokenError';
|
||||
import {BotIsPrivateError} from '@fluxer/errors/src/domains/oauth/BotIsPrivateError';
|
||||
@@ -31,6 +33,30 @@ import {MissingClientSecretError} from '@fluxer/errors/src/domains/oauth/Missing
|
||||
import {MissingRedirectUriError} from '@fluxer/errors/src/domains/oauth/MissingRedirectUriError';
|
||||
|
||||
const ADMIN_SSO_TOKEN_SCOPES = ['identify', 'email'];
|
||||
const ADMIN_APPLICATION_ID = createApplicationID(ADMIN_OAUTH2_APPLICATION_ID);
|
||||
const S256_CODE_CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
|
||||
|
||||
function normalizeRedirectUri(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
return new URL(value).toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function validateCodeChallenge(challenge: string | undefined, method: 'S256' | undefined): void {
|
||||
if (challenge === undefined && method === undefined) return;
|
||||
if (method !== 'S256' || challenge === undefined || !S256_CODE_CHALLENGE.test(challenge)) {
|
||||
throw new InvalidRequestError();
|
||||
}
|
||||
}
|
||||
|
||||
function codeVerifierMatches(authCode: OAuth2AuthorizationCode, verifier: string | undefined): boolean {
|
||||
if (!authCode.codeChallenge) return true;
|
||||
if (authCode.codeChallengeMethod !== 'S256' || !verifier) return false;
|
||||
return createHash('sha256').update(verifier).digest('base64url') === authCode.codeChallenge;
|
||||
}
|
||||
|
||||
interface OAuth2ServiceDeps {
|
||||
applicationRepository: ApplicationRepository;
|
||||
@@ -96,7 +122,7 @@ export class OAuth2Service {
|
||||
scope: string;
|
||||
state?: string;
|
||||
codeChallenge?: string;
|
||||
codeChallengeMethod?: 'S256' | 'plain';
|
||||
codeChallengeMethod?: 'S256';
|
||||
userId: UserID;
|
||||
}): Promise<{
|
||||
redirectTo: string;
|
||||
@@ -111,6 +137,7 @@ export class OAuth2Service {
|
||||
if (!application) {
|
||||
throw new InvalidClientError();
|
||||
}
|
||||
validateCodeChallenge(params.codeChallenge, params.codeChallengeMethod);
|
||||
const scopeSet = new Set<string>(parseOAuth2Scope(params.scope));
|
||||
for (const s of scopeSet) {
|
||||
if (!isOAuth2Scope(s)) {
|
||||
@@ -179,7 +206,7 @@ export class OAuth2Service {
|
||||
|
||||
private async issueTokens(args: {application: Application; userId: UserID; scope: Set<string>}): Promise<{
|
||||
accessToken: OAuth2AccessTokenRow;
|
||||
refreshToken: OAuth2RefreshTokenRow;
|
||||
refreshToken: OAuth2RefreshTokenRow | null;
|
||||
token_type: 'Bearer';
|
||||
expires_in: number;
|
||||
scope?: string;
|
||||
@@ -193,24 +220,33 @@ export class OAuth2Service {
|
||||
created_at: new Date(),
|
||||
};
|
||||
const createdAccess = await this.tokens.createAccessToken(accessToken);
|
||||
const row: OAuth2RefreshTokenRow = {
|
||||
token_: randomBase64Url(32),
|
||||
application_id: args.application.applicationId,
|
||||
user_id: args.userId,
|
||||
scope,
|
||||
created_at: new Date(),
|
||||
};
|
||||
const created = await this.tokens.createRefreshToken(row);
|
||||
const refreshToken = created.toRow();
|
||||
return {
|
||||
accessToken: createdAccess.toRow(),
|
||||
refreshToken,
|
||||
refreshToken: await this.issueRefreshToken(args.application, args.userId, scope),
|
||||
token_type: 'Bearer',
|
||||
expires_in: ACCESS_TOKEN_TTL_SECONDS,
|
||||
scope: sortOAuth2Scopes(scope).join(' '),
|
||||
};
|
||||
}
|
||||
|
||||
private async issueRefreshToken(
|
||||
application: Application,
|
||||
userId: UserID,
|
||||
scope: Set<string>,
|
||||
): Promise<OAuth2RefreshTokenRow | null> {
|
||||
if (application.applicationId === ADMIN_APPLICATION_ID) {
|
||||
return null;
|
||||
}
|
||||
const created = await this.tokens.createRefreshToken({
|
||||
token_: randomBase64Url(32),
|
||||
application_id: application.applicationId,
|
||||
user_id: userId,
|
||||
scope,
|
||||
created_at: new Date(),
|
||||
});
|
||||
return created.toRow();
|
||||
}
|
||||
|
||||
async authenticateClient(args: {
|
||||
authorizationHeader?: string;
|
||||
clientId?: string;
|
||||
@@ -255,7 +291,6 @@ export class OAuth2Service {
|
||||
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 {
|
||||
@@ -263,7 +298,6 @@ export class OAuth2Service {
|
||||
token_type: 'Bearer',
|
||||
expires_in: res.expires_in,
|
||||
scope: res.scope ?? '',
|
||||
refresh_token: res.refreshToken.token_,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -281,7 +315,7 @@ export class OAuth2Service {
|
||||
token_type: 'Bearer';
|
||||
expires_in: number;
|
||||
scope?: string;
|
||||
refresh_token: string;
|
||||
refresh_token?: string;
|
||||
}> {
|
||||
Logger.debug(
|
||||
{
|
||||
@@ -313,31 +347,24 @@ export class OAuth2Service {
|
||||
);
|
||||
throw new InvalidGrantError();
|
||||
}
|
||||
const expectedRedirectUri = authCode.redirectUri ?? '';
|
||||
const providedRedirectUri = params.redirectUri ?? '';
|
||||
if (expectedRedirectUri !== providedRedirectUri) {
|
||||
if (!(await this.tokens.consumeAuthorizationCode(code, authCode.applicationId))) {
|
||||
Logger.debug({code_len: code.length}, 'OAuth2 tokenExchange: authorization code already redeemed');
|
||||
throw new InvalidGrantError();
|
||||
}
|
||||
const expectedRedirectUri = normalizeRedirectUri(authCode.redirectUri);
|
||||
const providedRedirectUri = normalizeRedirectUri(params.redirectUri);
|
||||
if (expectedRedirectUri === null || expectedRedirectUri !== providedRedirectUri) {
|
||||
Logger.debug(
|
||||
{expected: expectedRedirectUri, got: providedRedirectUri},
|
||||
'OAuth2 tokenExchange: redirect_uri mismatch',
|
||||
);
|
||||
throw new InvalidGrantError();
|
||||
}
|
||||
if (authCode.codeChallenge) {
|
||||
const verifier = params.codeVerifier;
|
||||
if (!verifier) {
|
||||
throw new InvalidGrantError();
|
||||
}
|
||||
const method = authCode.codeChallengeMethod ?? 'plain';
|
||||
const expected = method === 'S256' ? createHash('sha256').update(verifier).digest('base64url') : verifier;
|
||||
if (expected !== authCode.codeChallenge) {
|
||||
throw new InvalidGrantError();
|
||||
}
|
||||
}
|
||||
if (!(await this.findActiveUser(authCode.userId))) {
|
||||
if (!codeVerifierMatches(authCode, params.codeVerifier)) {
|
||||
Logger.debug({code_len: code.length}, 'OAuth2 tokenExchange: code_verifier mismatch');
|
||||
throw new InvalidGrantError();
|
||||
}
|
||||
if (!(await this.tokens.consumeAuthorizationCode(code, authCode.applicationId))) {
|
||||
Logger.debug({code_len: code.length}, 'OAuth2 tokenExchange: authorization code already redeemed');
|
||||
if (!(await this.findActiveUser(authCode.userId))) {
|
||||
throw new InvalidGrantError();
|
||||
}
|
||||
const res = await this.issueTokens({
|
||||
@@ -345,19 +372,13 @@ export class OAuth2Service {
|
||||
userId: authCode.userId,
|
||||
scope: authCode.scope,
|
||||
});
|
||||
return {
|
||||
access_token: res.accessToken.token_,
|
||||
token_type: 'Bearer',
|
||||
expires_in: res.expires_in,
|
||||
scope: res.scope,
|
||||
refresh_token: res.refreshToken.token_,
|
||||
};
|
||||
return this.tokenResponse(res);
|
||||
}
|
||||
const refresh = await this.tokens.getRefreshToken(params.refreshToken!);
|
||||
if (!refresh) {
|
||||
throw new InvalidGrantError();
|
||||
}
|
||||
if (refresh.applicationId !== application.applicationId) {
|
||||
if (refresh.applicationId !== application.applicationId || refresh.applicationId === ADMIN_APPLICATION_ID) {
|
||||
throw new InvalidGrantError();
|
||||
}
|
||||
if (!(await this.findActiveUser(refresh.userId))) {
|
||||
@@ -371,12 +392,22 @@ export class OAuth2Service {
|
||||
userId: refresh.userId,
|
||||
scope: refresh.scope,
|
||||
});
|
||||
return this.tokenResponse(res);
|
||||
}
|
||||
|
||||
private tokenResponse(res: Awaited<ReturnType<OAuth2Service['issueTokens']>>): {
|
||||
access_token: string;
|
||||
token_type: 'Bearer';
|
||||
expires_in: number;
|
||||
scope?: string;
|
||||
refresh_token?: string;
|
||||
} {
|
||||
return {
|
||||
access_token: res.accessToken.token_,
|
||||
token_type: 'Bearer',
|
||||
expires_in: res.expires_in,
|
||||
scope: res.scope,
|
||||
refresh_token: res.refreshToken.token_,
|
||||
...(res.refreshToken ? {refresh_token: res.refreshToken.token_} : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -4,3 +4,4 @@ import {seconds} from 'itty-time';
|
||||
|
||||
export const ACCESS_TOKEN_TTL_SECONDS = seconds('7 days');
|
||||
export const AUTHORIZATION_CODE_TTL_SECONDS = seconds('10 minutes');
|
||||
export const REFRESH_TOKEN_TTL_SECONDS = seconds('30 days');
|
||||
@@ -19,7 +19,11 @@ import type {
|
||||
import {OAuth2AccessToken} from '@app/api/models/OAuth2AccessToken';
|
||||
import {OAuth2AuthorizationCode} from '@app/api/models/OAuth2AuthorizationCode';
|
||||
import {OAuth2RefreshToken} from '@app/api/models/OAuth2RefreshToken';
|
||||
import {ACCESS_TOKEN_TTL_SECONDS, AUTHORIZATION_CODE_TTL_SECONDS} from '@app/api/oauth/OAuth2TokenConstants';
|
||||
import {
|
||||
ACCESS_TOKEN_TTL_SECONDS,
|
||||
AUTHORIZATION_CODE_TTL_SECONDS,
|
||||
REFRESH_TOKEN_TTL_SECONDS,
|
||||
} from '@app/api/oauth/OAuth2TokenConstants';
|
||||
import {
|
||||
OAuth2AccessTokens,
|
||||
OAuth2AccessTokensByUser,
|
||||
@@ -32,6 +36,10 @@ function isAccessTokenExpired(createdAt: Date): boolean {
|
||||
return Date.now() - createdAt.getTime() > ACCESS_TOKEN_TTL_SECONDS * 1000;
|
||||
}
|
||||
|
||||
function isRefreshTokenExpired(createdAt: Date): boolean {
|
||||
return Date.now() - createdAt.getTime() > REFRESH_TOKEN_TTL_SECONDS * 1000;
|
||||
}
|
||||
|
||||
function isAuthorizationCodeExpired(createdAt: Date): boolean {
|
||||
return Date.now() - createdAt.getTime() > AUTHORIZATION_CODE_TTL_SECONDS * 1000;
|
||||
}
|
||||
@@ -126,8 +134,10 @@ export class OAuth2TokenRepository {
|
||||
}
|
||||
|
||||
async createRefreshToken(data: OAuth2RefreshTokenRow): Promise<OAuth2RefreshToken> {
|
||||
await upsertOne(OAuth2RefreshTokensByUser.insert({user_id: data.user_id, token_: data.token_}));
|
||||
if (!(await executeConditional(OAuth2RefreshTokens.insertIfNotExists(data)))) {
|
||||
await upsertOne(
|
||||
OAuth2RefreshTokensByUser.insertWithTtl({user_id: data.user_id, token_: data.token_}, REFRESH_TOKEN_TTL_SECONDS),
|
||||
);
|
||||
if (!(await executeConditional(OAuth2RefreshTokens.insertIfNotExistsWithTtl(data, REFRESH_TOKEN_TTL_SECONDS)))) {
|
||||
throw new Error('OAuth2 refresh token already exists');
|
||||
}
|
||||
return new OAuth2RefreshToken(data);
|
||||
@@ -135,7 +145,10 @@ export class OAuth2TokenRepository {
|
||||
|
||||
async getRefreshToken(token: string): Promise<OAuth2RefreshToken | null> {
|
||||
const row = await fetchOne<OAuth2RefreshTokenRow>(SELECT_REFRESH_TOKEN, {token_: token});
|
||||
return row ? new OAuth2RefreshToken(row) : null;
|
||||
if (!row || isRefreshTokenExpired(row.created_at)) {
|
||||
return null;
|
||||
}
|
||||
return new OAuth2RefreshToken(row);
|
||||
}
|
||||
|
||||
async consumeRefreshToken(token: string, applicationId: ApplicationID, userId: UserID): Promise<boolean> {
|
||||
@@ -174,9 +187,9 @@ export class OAuth2TokenRepository {
|
||||
const staleRefs: Array<string> = [];
|
||||
for (const tokenRef of tokenRefs) {
|
||||
const row = await fetchOne<OAuth2RefreshTokenRow>(SELECT_REFRESH_TOKEN, {token_: tokenRef.token_});
|
||||
if (row) {
|
||||
if (row && !isRefreshTokenExpired(row.created_at)) {
|
||||
tokens.push(new OAuth2RefreshToken(row));
|
||||
} else {
|
||||
} else if (!row) {
|
||||
staleRefs.push(tokenRef.token_);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ describe('OAuth2 grants follow the account standing', () => {
|
||||
await setStanding(endUser.userId, {addFlags: UserFlags.DELETED});
|
||||
expect(await bearerStatus('/oauth2/userinfo', tokens.access_token)).toBe(HTTP_STATUS.UNAUTHORIZED);
|
||||
expect(await bearerStatus('/oauth2/@me', tokens.access_token)).toBe(HTTP_STATUS.UNAUTHORIZED);
|
||||
expect(await refreshStatus(application, tokens.refresh_token)).toBe(HTTP_STATUS.BAD_REQUEST);
|
||||
expect(await refreshStatus(application, tokens.refresh_token!)).toBe(HTTP_STATUS.BAD_REQUEST);
|
||||
const introspected = await introspectOAuth2Token(harness, {
|
||||
client_id: application.id,
|
||||
client_secret: application.client_secret,
|
||||
@@ -92,7 +92,7 @@ describe('OAuth2 grants follow the account standing', () => {
|
||||
const introspectedRefresh = await introspectOAuth2Token(harness, {
|
||||
client_id: application.id,
|
||||
client_secret: application.client_secret,
|
||||
token: tokens.refresh_token,
|
||||
token: tokens.refresh_token!,
|
||||
});
|
||||
expect(introspectedRefresh.active).toBe(false);
|
||||
});
|
||||
@@ -122,12 +122,12 @@ describe('OAuth2 grants follow the account standing', () => {
|
||||
tempBannedUntil: new Date(Date.now() + HOUR_MS),
|
||||
});
|
||||
expect(await bearerStatus('/oauth2/userinfo', tokens.access_token)).toBe(HTTP_STATUS.UNAUTHORIZED);
|
||||
expect(await refreshStatus(application, tokens.refresh_token)).toBe(HTTP_STATUS.BAD_REQUEST);
|
||||
expect(await refreshStatus(application, tokens.refresh_token!)).toBe(HTTP_STATUS.BAD_REQUEST);
|
||||
await setStanding(endUser.userId, {tempBannedUntil: new Date(Date.now() - HOUR_MS)});
|
||||
const refreshed = await refreshOAuth2Token(harness, {
|
||||
client_id: application.id,
|
||||
client_secret: application.client_secret,
|
||||
refresh_token: tokens.refresh_token,
|
||||
refresh_token: tokens.refresh_token!,
|
||||
});
|
||||
expect(await bearerStatus('/oauth2/userinfo', refreshed.access_token)).toBe(HTTP_STATUS.OK);
|
||||
});
|
||||
|
||||
Generated
+8
-7
@@ -34967,10 +34967,13 @@
|
||||
"description": "The number of seconds until the access token expires",
|
||||
"$ref": "#/components/schemas/Int32Type"
|
||||
},
|
||||
"refresh_token": {"type": "string", "description": "The refresh token for obtaining new access tokens"},
|
||||
"refresh_token": {
|
||||
"description": "The refresh token for obtaining new access tokens. Not issued to every client",
|
||||
"type": "string"
|
||||
},
|
||||
"scope": {"type": "string", "description": "The space-separated list of granted scopes"}
|
||||
},
|
||||
"required": ["access_token", "token_type", "expires_in", "refresh_token", "scope"],
|
||||
"required": ["access_token", "token_type", "expires_in", "scope"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"IntrospectRequestForm": {
|
||||
@@ -35016,11 +35019,9 @@
|
||||
"permissions": {"description": "The bot permissions to request", "type": "string"},
|
||||
"code_challenge": {"description": "The PKCE code challenge", "type": "string"},
|
||||
"code_challenge_method": {
|
||||
"description": "The PKCE code challenge method",
|
||||
"x-enumNames": ["S256", "PLAIN"],
|
||||
"x-enumDescriptions": ["SHA-256 hash of code verifier", "Plain text code verifier"],
|
||||
"enum": ["S256", "plain"],
|
||||
"type": "string"
|
||||
"description": "The PKCE code challenge method, must be \"S256\"",
|
||||
"type": "string",
|
||||
"const": "S256"
|
||||
}
|
||||
},
|
||||
"required": ["client_id", "scope"]
|
||||
|
||||
@@ -48,29 +48,10 @@ export async function requirePermission(
|
||||
}
|
||||
}
|
||||
|
||||
interface OverwriteBits {
|
||||
type?: number;
|
||||
allow: bigint;
|
||||
deny: bigint;
|
||||
}
|
||||
|
||||
export function overwriteAppliesToTarget(
|
||||
overwrite: {id: bigint; type: number},
|
||||
guildId: bigint,
|
||||
roleIds: ReadonlySet<bigint>,
|
||||
): boolean {
|
||||
const isRole = overwrite.id === guildId || roleIds.has(overwrite.id);
|
||||
return overwrite.type === 0 ? isRole : !isRole;
|
||||
}
|
||||
|
||||
export function overwriteGrantedBits(
|
||||
before: OverwriteBits | null | undefined,
|
||||
after: OverwriteBits | null | undefined,
|
||||
beforeApplies = true,
|
||||
before: {allow: bigint; deny: bigint} | null | undefined,
|
||||
after: {allow: bigint; deny: bigint} | null | undefined,
|
||||
): bigint {
|
||||
if (before && after && before.type !== undefined && after.type !== undefined && before.type !== after.type) {
|
||||
return after.allow | (beforeApplies ? before.deny : 0n);
|
||||
}
|
||||
const beforeAllow = before?.allow ?? 0n;
|
||||
const beforeDeny = before?.deny ?? 0n;
|
||||
const afterAllow = after?.allow ?? 0n;
|
||||
|
||||
@@ -11,16 +11,20 @@ OAuth2 lets a user give an application access to their account, and the same con
|
||||
## Authorization code grant
|
||||
|
||||
1. Send the user's browser to [Authorize application](#authorize-application). When the user approves on the consent screen, Fluxer sends the browser to your `redirect_uri` with a `code` and your `state`.
|
||||
2. Exchange the code at [Exchange OAuth2 token](#exchange-oauth2-token) with your client credentials to get an access token and a refresh token.
|
||||
2. Exchange the code at [Exchange OAuth2 token](#exchange-oauth2-token) with your client credentials to get an access token and a refresh token. Every third-party application gets a refresh token.
|
||||
3. Send the access token as `Authorization: Bearer <token>`. Before the access token expires, exchange the refresh token for a new pair.
|
||||
|
||||
| Credential | Lifetime |
|
||||
| --- | --- |
|
||||
| Authorization code | 10 minutes, single use |
|
||||
| Access token | 7 days |
|
||||
| Refresh token | 30 days, single use. Each refresh returns a new one |
|
||||
| Refresh token | 30 days, single use. Each refresh returns a new one that lasts another 30 days |
|
||||
|
||||
PKCE supports the `S256` and `plain` methods. A `code_challenge` with no `code_challenge_method` uses `plain`. When the code has a challenge, the token exchange needs a matching `code_verifier`.
|
||||
A code works for one token exchange. Once your application is authenticated, its first exchange of a code uses the code up, even if the `redirect_uri` or `code_verifier` is wrong, so after such a failure you need a new code. A code sent by another application or with a wrong client secret isn't used up.
|
||||
|
||||
If you don't refresh within 30 days, the refresh token expires and the user has to authorize your application again. Once the user has no refresh token left for your application, the application drops out of their authorized applications and `prompt=none` returns `consent_required`.
|
||||
|
||||
PKCE supports only the `S256` method. Send `code_challenge` together with `code_challenge_method=S256`. Fluxer rejects `plain` with a validation error. At [Grant OAuth2 consent](#grant-oauth2-consent), a challenge without a method or a method without a challenge gets `invalid_request`. With `prompt=none`, the same mistakes redirect with `error=consent_required`. When the code has a challenge, the token exchange needs the matching `code_verifier`.
|
||||
|
||||
The token, introspection and revocation routes take an `application/x-www-form-urlencoded` or `multipart/form-data` body. Authenticate your application with HTTP Basic or with the `client_id` and `client_secret` fields. Introspection and revocation return `invalid_request` when credentials are in both the `Authorization` header and the body.
|
||||
|
||||
@@ -68,7 +72,7 @@ The token, consent, introspection and revocation routes return this body with st
|
||||
|
||||
| Value | Description |
|
||||
| --- | --- |
|
||||
| invalid_request | The redirect URI, response type or permission mask is wrong, or credentials were sent in both places |
|
||||
| invalid_request | The redirect URI, response type, PKCE challenge or permission mask is wrong, or credentials were sent in both places |
|
||||
| invalid_client | The application is unknown or the client secret is missing or wrong |
|
||||
| invalid_grant | The code, refresh token, redirect URI or PKCE verifier doesn't match a valid grant |
|
||||
| invalid_scope | A requested scope isn't in [OAuth2 scopes](#oauth2-scopes) |
|
||||
@@ -84,7 +88,7 @@ The token pair a successful exchange returns.
|
||||
| access_token | string | The bearer token |
|
||||
| token_type | string | Always `Bearer` |
|
||||
| expires_in | integer | The access token lifetime in seconds, 604800 |
|
||||
| refresh_token | string | The refresh token for the next exchange |
|
||||
| refresh_token | string | The refresh token for the next exchange. Every third-party application gets one |
|
||||
| scope | string | The granted scopes, separated by spaces |
|
||||
|
||||
### Example
|
||||
@@ -252,7 +256,7 @@ Starts the grant and redirects the browser to the Fluxer consent screen with the
|
||||
| permissions? | string | The permissions to give the bot, as an integer string |
|
||||
| disable_guild_select? | string | `true` to stop the user from picking another guild |
|
||||
| code_challenge? | string | The PKCE challenge |
|
||||
| code_challenge_method? | string | The PKCE method, `S256` or `plain` |
|
||||
| code_challenge_method? | string | The PKCE method, `S256` |
|
||||
|
||||
### Response
|
||||
|
||||
@@ -260,7 +264,13 @@ Starts the grant and redirects the browser to the Fluxer consent screen with the
|
||||
| --- | --- | --- |
|
||||
| 302 | empty | The `Location` header has the consent screen or your callback |
|
||||
|
||||
With `prompt=none`, Fluxer skips the consent screen when the signed-in user has already granted every requested scope, and redirects to your `redirect_uri` with a `code`. Otherwise it redirects with `error=login_required` when nobody is signed in, or `error=consent_required`. If `redirect_uri` isn't registered on the application, the error goes to the Fluxer web app.
|
||||
With `prompt=none`, Fluxer skips the consent screen only when the request comes with a signed-in user session and that user has already authorized your application for every requested scope. Fluxer then redirects to your `redirect_uri` with a `code`. Otherwise it redirects with an `error`:
|
||||
|
||||
- `login_required` when there is no signed-in user session.
|
||||
- `consent_required` when the user hasn't authorized every requested scope, or when the request includes the `bot` scope, which always needs the consent screen.
|
||||
- `consent_required` also when the request has a problem the consent screen would reject, such as a missing or unregistered `redirect_uri` or a PKCE challenge without a method.
|
||||
|
||||
If `redirect_uri` isn't registered on the application, the error goes to the Fluxer web app.
|
||||
|
||||
The rate limit is 60 requests per minute, on the `oauth:authorize` bucket.
|
||||
|
||||
@@ -283,7 +293,7 @@ Records the user's consent and returns an [OAuth2 consent response](#oauth2-cons
|
||||
| guild_id?<sup>3</sup> | snowflake | The guild to install the bot into |
|
||||
| channel_id?<sup>3</sup> | snowflake | The group DM to install the bot into |
|
||||
| code_challenge? | string | The PKCE challenge |
|
||||
| code_challenge_method? | string | The PKCE method, `S256` or `plain` |
|
||||
| code_challenge_method? | string | The PKCE method, `S256` |
|
||||
|
||||
<sup>1</sup> Required unless the only scope is `bot` and the application doesn't set `bot_require_code_grant`
|
||||
|
||||
@@ -296,7 +306,7 @@ Records the user's consent and returns an [OAuth2 consent response](#oauth2-cons
|
||||
| Status | Body | Condition |
|
||||
| --- | --- | --- |
|
||||
| 200 | [OAuth2 consent response](#oauth2-consent-response-object) object | Consent was recorded |
|
||||
| 400 | [OAuth2 error](#oauth2-error-response-object) object | The application, scope, redirect URI, response type or permission mask was rejected |
|
||||
| 400 | [OAuth2 error](#oauth2-error-response-object) object | The application, scope, redirect URI, response type, PKCE challenge or permission mask was rejected |
|
||||
| 400 | [error response](/http-api/#error-response) | `NOT_A_BOT_APPLICATION`, `BOT_ALREADY_IN_GUILD` or `INVALID_CHANNEL_TYPE` |
|
||||
| 400 | [error response](/http-api/#error-response) | `MAX_GUILD_MEMBERS`, `MAX_GUILD_ROLES` or `MAX_GROUP_DM_RECIPIENTS` |
|
||||
| 403 | [error response](/http-api/#error-response) | `BOT_IS_PRIVATE` when you don't own a private bot's application |
|
||||
@@ -323,7 +333,7 @@ If you lose the response to a refresh, the user has to authorize your applicatio
|
||||
| --- | --- | --- |
|
||||
| grant_type | string | The grant type, `authorization_code` or `refresh_token` |
|
||||
| code | string | The code from the callback, for `authorization_code` |
|
||||
| redirect_uri | string | The code's redirect URI, normalized, so `https://example.com` is sent as `https://example.com/` |
|
||||
| redirect_uri | string | The redirect URI the code was issued for. Fluxer compares normalized URLs, so `https://example.com` and `https://example.com/` match |
|
||||
| code_verifier? | string | The PKCE verifier, when the code has a challenge |
|
||||
| refresh_token | string | The refresh token, for `refresh_token` |
|
||||
| client_id? | snowflake | The ID of the application, if you don't use HTTP Basic |
|
||||
|
||||
@@ -64,13 +64,7 @@ export const AuthorizeRequest = z.object({
|
||||
permissions: z.string().optional().describe('The bot permissions to request'),
|
||||
disable_guild_select: DisableGuildSelectType.optional(),
|
||||
code_challenge: createStringType(1).optional().describe('The PKCE code challenge'),
|
||||
code_challenge_method: createNamedStringLiteralUnion(
|
||||
[
|
||||
['S256', 'S256', 'SHA-256 hash of code verifier'],
|
||||
['plain', 'PLAIN', 'Plain text code verifier'],
|
||||
] as const,
|
||||
'The PKCE code challenge method',
|
||||
).optional(),
|
||||
code_challenge_method: z.literal('S256').optional().describe('The PKCE code challenge method, must be "S256"'),
|
||||
});
|
||||
|
||||
export type AuthorizeRequest = z.infer<typeof AuthorizeRequest>;
|
||||
@@ -190,7 +184,10 @@ export const OAuth2TokenResponse = z.object({
|
||||
access_token: z.string().describe('The access token for API authorization'),
|
||||
token_type: z.string().describe('The type of token, typically "Bearer"'),
|
||||
expires_in: Int32Type.describe('The number of seconds until the access token expires'),
|
||||
refresh_token: z.string().describe('The refresh token for obtaining new access tokens'),
|
||||
refresh_token: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('The refresh token for obtaining new access tokens. Not issued to every client'),
|
||||
scope: z.string().describe('The space-separated list of granted scopes'),
|
||||
});
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ describe.each([
|
||||
it('normalizes shared fields without adding optional defaults', () => {
|
||||
expect(schema.parse({client_id: ' 123 ', scope: ' identify '})).toEqual({client_id: 123n, scope: 'identify'});
|
||||
});
|
||||
it.each(['S256', 'plain'])('preserves the PKCE method %s and shared fields', (method) => {
|
||||
it.each(['S256'])('preserves the PKCE method %s and shared fields', (method) => {
|
||||
expect(
|
||||
schema.parse({
|
||||
...required,
|
||||
@@ -78,6 +78,7 @@ describe.each([
|
||||
{redirect_uri: '/relative'},
|
||||
{code_challenge: ''},
|
||||
{code_challenge_method: 's256'},
|
||||
{code_challenge_method: 'plain'},
|
||||
])('rejects malformed shared fields %j', (fields) => {
|
||||
expect(schema.safeParse({...required, ...fields}).success).toBe(false);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user