OAuth token revocation (RFC 7009) #438
No files matched your search
@@ -72,6 +72,25 @@ impl Server {
|
||||
account_id: u32,
|
||||
revision: u64,
|
||||
revision_account: u64,
|
||||
) -> trc::Result<AccessTokenInner> {
|
||||
let mut token = self
|
||||
.build_access_token_inner(account, account_id, revision, revision_account)
|
||||
.await?;
|
||||
// inbuxa: K-S4: the account's revoked OAuth tokens are cached with
|
||||
// it, so revoking one only has to drop this entry on every node
|
||||
token.revoked_tokens = self
|
||||
.revoked_oauth_tokens(account_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
Ok(token.update_size())
|
||||
}
|
||||
|
||||
async fn build_access_token_inner(
|
||||
&self,
|
||||
account: Account,
|
||||
account_id: u32,
|
||||
revision: u64,
|
||||
revision_account: u64,
|
||||
) -> trc::Result<AccessTokenInner> {
|
||||
// inbuxa: AL-2, AL-5: whether this account is locked, and which
|
||||
// locked accounts are handed to it. The token is their cache: every
|
||||
@@ -310,6 +329,7 @@ impl Server {
|
||||
locked,
|
||||
shared_mailbox,
|
||||
delegations: delegations.clone(),
|
||||
revoked_tokens: Default::default(),
|
||||
revision,
|
||||
revision_account,
|
||||
credential_version,
|
||||
@@ -364,6 +384,7 @@ impl Server {
|
||||
locked,
|
||||
shared_mailbox,
|
||||
delegations: delegations.clone(),
|
||||
revoked_tokens: Default::default(),
|
||||
revision,
|
||||
revision_account,
|
||||
credential_version: 0,
|
||||
@@ -402,16 +423,15 @@ impl Server {
|
||||
Collection = "accessToken",
|
||||
);
|
||||
|
||||
let token: Arc<AccessTokenInner> = if let Some(account) =
|
||||
let mut token: AccessTokenInner = if let Some(account) =
|
||||
self.registry().object::<Account>(account_id.into()).await?
|
||||
{
|
||||
let revision = rand::random::<u64>();
|
||||
let revision_account = hash_account(&account);
|
||||
self.build_access_token(account, account_id, revision, revision_account)
|
||||
.await?
|
||||
.into()
|
||||
} else if account_id == RECOVERY_ADMIN_ID {
|
||||
AccessTokenInner::new_admin().into()
|
||||
AccessTokenInner::new_admin()
|
||||
} else {
|
||||
return Err(trc::SecurityEvent::Unauthorized
|
||||
.into_err()
|
||||
@@ -420,6 +440,16 @@ impl Server {
|
||||
.caused_by(trc::location!()));
|
||||
};
|
||||
|
||||
if account_id == RECOVERY_ADMIN_ID {
|
||||
// inbuxa: K-S4: the recovery admin's tokens can be revoked too
|
||||
token.revoked_tokens = self
|
||||
.revoked_oauth_tokens(account_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
token = token.update_size();
|
||||
}
|
||||
let token: Arc<AccessTokenInner> = token.into();
|
||||
|
||||
let _ = guard.insert(token.clone());
|
||||
Ok(token)
|
||||
}
|
||||
@@ -746,6 +776,7 @@ impl AccessToken {
|
||||
locked: old_inner.locked,
|
||||
shared_mailbox: old_inner.shared_mailbox,
|
||||
delegations: old_inner.delegations.clone(),
|
||||
revoked_tokens: old_inner.revoked_tokens.clone(),
|
||||
};
|
||||
|
||||
access_token = AccessToken {
|
||||
@@ -1051,6 +1082,7 @@ impl AccessToken {
|
||||
locked: false,
|
||||
shared_mailbox: false,
|
||||
delegations: Default::default(),
|
||||
revoked_tokens: Default::default(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -1086,11 +1118,17 @@ impl AccessTokenInner {
|
||||
self
|
||||
}
|
||||
|
||||
/// inbuxa: K-S4: whether this OAuth token of the account was revoked.
|
||||
pub fn is_oauth_token_revoked(&self, token_id: u128) -> bool {
|
||||
self.revoked_tokens.binary_search(&token_id).is_ok()
|
||||
}
|
||||
|
||||
pub fn update_size(mut self) -> Self {
|
||||
self.obj_size = (std::mem::size_of::<AccessToken>()
|
||||
+ (self.member_of.len() * std::mem::size_of::<u32>())
|
||||
+ (self.access_to.len() * (std::mem::size_of::<u32>() + std::mem::size_of::<u64>()))
|
||||
+ (self.scopes.len() * std::mem::size_of::<AccessScope>()))
|
||||
+ (self.scopes.len() * std::mem::size_of::<AccessScope>())
|
||||
+ (self.revoked_tokens.len() * std::mem::size_of::<u128>()))
|
||||
as u64;
|
||||
self
|
||||
}
|
||||
@@ -1112,6 +1150,7 @@ impl AccessTokenInner {
|
||||
locked: false,
|
||||
shared_mailbox: false,
|
||||
delegations: Default::default(),
|
||||
revoked_tokens: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -158,6 +158,8 @@ pub struct AccessTokenInner {
|
||||
pub(crate) shared_mailbox: bool,
|
||||
// inbuxa: AL-5: locked accounts handed to this one
|
||||
pub(crate) delegations: Box<[Delegation]>,
|
||||
// inbuxa: K-S4: this account's revoked OAuth tokens, sorted (RFC 7009)
|
||||
pub(crate) revoked_tokens: Box<[u128]>,
|
||||
}
|
||||
|
||||
/// inbuxa: a locked account this one may open, and how (AL-5, AL-6).
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*
|
||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
||||
*/
|
||||
|
||||
pub mod client_id;
|
||||
@@ -10,6 +12,8 @@ pub mod crypto;
|
||||
pub mod introspect;
|
||||
pub mod oidc;
|
||||
pub mod registration;
|
||||
// inbuxa: K-S4
|
||||
pub mod revoke;
|
||||
pub mod token;
|
||||
|
||||
pub const DEVICE_CODE_LEN: usize = 40;
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
//! inbuxa: K-S4: revoking OAuth tokens (RFC 7009).
|
||||
//!
|
||||
//! Tokens are sealed, not stored, so revoking one means remembering it until
|
||||
//! it would have expired anyway. Each account keeps one list in the
|
||||
//! in-memory store, which every node shares. The list is read with the
|
||||
//! account's access token and cached with it; revoking a token rewrites the
|
||||
//! list and then drops that cache entry on every node, so the next request
|
||||
//! anywhere reads the new list.
|
||||
//!
|
||||
//! A refresh token is also checked against the store itself when it is
|
||||
//! redeemed, so a node that was rebuilding its cache entry while the
|
||||
//! revocation went in can't mint a new access token from it.
|
||||
|
||||
use crate::{
|
||||
KV_OAUTH_REVOKED, Server, cache::invalidate::CacheInvalidationBuilder, ipc::CacheInvalidation,
|
||||
};
|
||||
use std::time::Duration;
|
||||
use store::{dispatch::lookup::KeyValue, write::now};
|
||||
use trc::AddContext;
|
||||
use xxhash_rust::xxh3;
|
||||
|
||||
/// How many unexpired revocations one account may hold. Each needs a token
|
||||
/// of that account that is still valid, so only its owner (or whoever holds
|
||||
/// its tokens) can fill it, and they expire with the tokens.
|
||||
pub const MAX_REVOKED_PER_ACCOUNT: usize = 2048;
|
||||
|
||||
const LOCK_TRIES: usize = 20;
|
||||
const LOCK_SECONDS: u64 = 10;
|
||||
|
||||
/// What a revoked token is remembered by.
|
||||
pub fn oauth_token_id(token: &str) -> u128 {
|
||||
xxh3::xxh3_128(token.as_bytes())
|
||||
}
|
||||
|
||||
fn list_key(account_id: u32) -> Vec<u8> {
|
||||
let mut key = Vec::with_capacity(5);
|
||||
key.push(b'R');
|
||||
key.extend_from_slice(&account_id.to_be_bytes());
|
||||
key
|
||||
}
|
||||
|
||||
fn lock_key(account_id: u32) -> Vec<u8> {
|
||||
let mut key = Vec::with_capacity(5);
|
||||
key.push(b'L');
|
||||
key.extend_from_slice(&account_id.to_be_bytes());
|
||||
key
|
||||
}
|
||||
|
||||
/// One revocation: the token's id and when the token expires, in seconds
|
||||
/// since the Unix epoch.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Revoked {
|
||||
pub id: u128,
|
||||
pub expires: u64,
|
||||
}
|
||||
|
||||
/// Parses a stored list, keeping the entries that haven't expired. Lines
|
||||
/// that don't parse are skipped: a damaged entry can't revoke anything.
|
||||
pub fn parse_revoked(text: &str, now: u64) -> Vec<Revoked> {
|
||||
text.lines()
|
||||
.filter_map(|line| {
|
||||
let (id, expires) = line.split_once(':')?;
|
||||
let id = u128::from_str_radix(id, 16).ok()?;
|
||||
let expires = expires.parse::<u64>().ok()?;
|
||||
(expires > now).then_some(Revoked { id, expires })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn serialize_revoked(list: &[Revoked]) -> String {
|
||||
let mut text = String::with_capacity(list.len() * 44);
|
||||
for entry in list {
|
||||
text.push_str(&format!("{:032x}:{}\n", entry.id, entry.expires));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The ids of a list, sorted for a binary search.
|
||||
pub fn revoked_ids(list: &[Revoked]) -> Box<[u128]> {
|
||||
let mut ids = list.iter().map(|entry| entry.id).collect::<Vec<_>>();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
ids.into_boxed_slice()
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum RevokeOutcome {
|
||||
Revoked,
|
||||
AlreadyRevoked,
|
||||
/// The account already holds [`MAX_REVOKED_PER_ACCOUNT`] revocations.
|
||||
Full,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
async fn read_revoked(&self, account_id: u32) -> trc::Result<Vec<Revoked>> {
|
||||
Ok(self
|
||||
.in_memory_store()
|
||||
.key_get::<String>(KeyValue::<()>::build_key(
|
||||
KV_OAUTH_REVOKED,
|
||||
list_key(account_id),
|
||||
))
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.map(|text| parse_revoked(&text, now()))
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// This account's revoked tokens, for its cached access token.
|
||||
pub async fn revoked_oauth_tokens(&self, account_id: u32) -> trc::Result<Box<[u128]>> {
|
||||
self.read_revoked(account_id)
|
||||
.await
|
||||
.map(|list| revoked_ids(&list))
|
||||
}
|
||||
|
||||
/// Whether the store holds this token as revoked, bypassing the cache.
|
||||
pub async fn is_oauth_token_revoked_in_store(
|
||||
&self,
|
||||
account_id: u32,
|
||||
token_id: u128,
|
||||
) -> trc::Result<bool> {
|
||||
self.read_revoked(account_id)
|
||||
.await
|
||||
.map(|list| list.iter().any(|entry| entry.id == token_id))
|
||||
}
|
||||
|
||||
/// Remembers a token as revoked until `expires` (Unix seconds), then has
|
||||
/// every node drop the account's cached access token.
|
||||
pub async fn revoke_oauth_token(
|
||||
&self,
|
||||
account_id: u32,
|
||||
token_id: u128,
|
||||
expires: u64,
|
||||
) -> trc::Result<RevokeOutcome> {
|
||||
let store = self.in_memory_store();
|
||||
let lock = lock_key(account_id);
|
||||
|
||||
// One writer per account at a time, so two revocations can't each
|
||||
// write a list missing the other's token
|
||||
let mut locked = false;
|
||||
for _ in 0..LOCK_TRIES {
|
||||
if store
|
||||
.try_lock(KV_OAUTH_REVOKED, &lock, LOCK_SECONDS)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
locked = true;
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
if !locked {
|
||||
return Err(trc::StoreEvent::UnexpectedError
|
||||
.into_err()
|
||||
.details("Timed out waiting to revoke a token")
|
||||
.account_id(account_id)
|
||||
.caused_by(trc::location!()));
|
||||
}
|
||||
|
||||
let result = self
|
||||
.revoke_oauth_token_locked(account_id, token_id, expires)
|
||||
.await;
|
||||
let unlock = store.remove_lock(KV_OAUTH_REVOKED, &lock).await;
|
||||
let outcome = result?;
|
||||
unlock.caused_by(trc::location!())?;
|
||||
|
||||
if outcome == RevokeOutcome::Revoked {
|
||||
let mut changes = CacheInvalidationBuilder::default();
|
||||
changes.invalidate(CacheInvalidation::AccessToken(account_id));
|
||||
self.invalidate_caches(changes)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
async fn revoke_oauth_token_locked(
|
||||
&self,
|
||||
account_id: u32,
|
||||
token_id: u128,
|
||||
expires: u64,
|
||||
) -> trc::Result<RevokeOutcome> {
|
||||
let now = now();
|
||||
if expires <= now {
|
||||
// Expired already: nothing left to refuse
|
||||
return Ok(RevokeOutcome::AlreadyRevoked);
|
||||
}
|
||||
|
||||
let mut list = self.read_revoked(account_id).await?;
|
||||
if list.iter().any(|entry| entry.id == token_id) {
|
||||
return Ok(RevokeOutcome::AlreadyRevoked);
|
||||
}
|
||||
if list.len() >= MAX_REVOKED_PER_ACCOUNT {
|
||||
return Ok(RevokeOutcome::Full);
|
||||
}
|
||||
list.push(Revoked {
|
||||
id: token_id,
|
||||
expires,
|
||||
});
|
||||
|
||||
// The list lives as long as its longest-lived entry
|
||||
let ttl = list
|
||||
.iter()
|
||||
.map(|entry| entry.expires)
|
||||
.max()
|
||||
.unwrap_or(expires)
|
||||
- now;
|
||||
self.in_memory_store()
|
||||
.key_set(
|
||||
KeyValue::with_prefix(
|
||||
KV_OAUTH_REVOKED,
|
||||
list_key(account_id),
|
||||
serialize_revoked(&list).into_bytes(),
|
||||
)
|
||||
.expires(ttl),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
Ok(RevokeOutcome::Revoked)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn list_round_trips_and_drops_expired() {
|
||||
let list = vec![
|
||||
Revoked {
|
||||
id: oauth_token_id("sw1.a"),
|
||||
expires: 2_000,
|
||||
},
|
||||
Revoked {
|
||||
id: 7,
|
||||
expires: 900,
|
||||
},
|
||||
];
|
||||
let text = serialize_revoked(&list);
|
||||
assert_eq!(parse_revoked(&text, 0), list);
|
||||
assert_eq!(parse_revoked(&text, 1_000), vec![list[0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_lines_are_skipped() {
|
||||
let text = "zz:10\n00000000000000000000000000000005:abc\n\
|
||||
00000000000000000000000000000006:50\nnot a line\n";
|
||||
assert_eq!(parse_revoked(text, 0), vec![Revoked { id: 6, expires: 50 }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_are_sorted_for_search() {
|
||||
let list = [9u128, 3, 9, 1].map(|id| Revoked { id, expires: 10 });
|
||||
let ids = revoked_ids(&list);
|
||||
assert_eq!(&*ids, &[1, 3, 9]);
|
||||
assert!(ids.binary_search(&3).is_ok());
|
||||
assert!(ids.binary_search(&4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_ids_differ() {
|
||||
assert_ne!(oauth_token_id("sw1.a"), oauth_token_id("sw1.b"));
|
||||
assert_eq!(oauth_token_id("sw1.a"), oauth_token_id("sw1.a"));
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*
|
||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
||||
*/
|
||||
|
||||
use super::{GrantType, crypto::SymmetricEncrypt};
|
||||
@@ -9,6 +11,7 @@ use crate::Server;
|
||||
use base64::{Engine, engine::general_purpose};
|
||||
use std::time::SystemTime;
|
||||
use store::rand::{RngExt, rng};
|
||||
use trc::AddContext;
|
||||
use utils::codec::leb128::{Leb128Iterator, Leb128Vec};
|
||||
|
||||
pub const FAILED_TO_DECODE_TOKEN: &str = concat!(
|
||||
@@ -102,17 +105,42 @@ impl Server {
|
||||
}
|
||||
|
||||
// Enforce credential revocation for long lived tokens
|
||||
if token.credential_version != 0 {
|
||||
let current = self
|
||||
// inbuxa: K-S4: and revocation of the token itself (RFC 7009). Access
|
||||
// and refresh tokens are always checked, whatever their credential
|
||||
// version: an account with no password still has revocable tokens.
|
||||
let revocable = matches!(
|
||||
token.grant_type,
|
||||
GrantType::AccessToken | GrantType::RefreshToken
|
||||
);
|
||||
if token.credential_version != 0 || revocable {
|
||||
let account = self
|
||||
.access_token(token.account_id)
|
||||
.await
|
||||
.map_err(|err| trc::AuthEvent::Error.into_err().ctx(trc::Key::Details, err))?
|
||||
.credential_version();
|
||||
if current != token.credential_version {
|
||||
.map_err(|err| trc::AuthEvent::Error.into_err().ctx(trc::Key::Details, err))?;
|
||||
if token.credential_version != 0
|
||||
&& account.credential_version() != token.credential_version
|
||||
{
|
||||
return Err(trc::AuthEvent::TokenExpired
|
||||
.into_err()
|
||||
.details("Token revoked"));
|
||||
}
|
||||
if revocable {
|
||||
let token_id = super::revoke::oauth_token_id(token_);
|
||||
// A refresh token mints new access tokens, so it is checked
|
||||
// against the store too, past a cache entry that may have
|
||||
// been rebuilt while the revocation went in
|
||||
if account.is_oauth_token_revoked(token_id)
|
||||
|| (token.grant_type == GrantType::RefreshToken
|
||||
&& self
|
||||
.is_oauth_token_revoked_in_store(token.account_id, token_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?)
|
||||
{
|
||||
return Err(trc::AuthEvent::TokenExpired
|
||||
.into_err()
|
||||
.details("Token revoked"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(TokenInfo {
|
||||
|
||||
@@ -148,6 +148,8 @@ pub const KV_PORT_REACHABILITY: u8 = 200;
|
||||
// inbuxa: device-flow codes live apart from authorization codes, so neither
|
||||
// grant can redeem the other's code.
|
||||
pub const KV_OAUTH_DEVICE: u8 = 201;
|
||||
// inbuxa: K-S4: revoked OAuth tokens, one list per account
|
||||
pub const KV_OAUTH_REVOKED: u8 = 202;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Server {
|
||||
|
||||
@@ -57,6 +57,9 @@ pub struct OAuthMetadata {
|
||||
pub device_authorization_endpoint: String,
|
||||
pub registration_endpoint: String,
|
||||
pub introspection_endpoint: String,
|
||||
// inbuxa: K-S4: RFC 7009, advertised as RFC 8414 describes
|
||||
pub revocation_endpoint: String,
|
||||
pub revocation_endpoint_auth_methods_supported: &'static [&'static str],
|
||||
pub grant_types_supported: &'static [&'static str],
|
||||
pub response_types_supported: &'static [&'static str],
|
||||
pub scopes_supported: &'static [&'static str],
|
||||
@@ -583,6 +586,12 @@ impl OAuthApiHandler for Server {
|
||||
token_endpoint: format!("{base_url}/auth/token"),
|
||||
device_authorization_endpoint: format!("{base_url}/auth/device"),
|
||||
introspection_endpoint: format!("{base_url}/auth/introspect"),
|
||||
revocation_endpoint: format!("{base_url}/auth/revoke"),
|
||||
revocation_endpoint_auth_methods_supported: &[
|
||||
"none",
|
||||
"client_secret_post",
|
||||
"client_secret_basic",
|
||||
],
|
||||
registration_endpoint: format!("{base_url}/auth/register"),
|
||||
grant_types_supported: &[
|
||||
"authorization_code",
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*
|
||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
||||
*/
|
||||
|
||||
use http_proto::{HttpRequest, request::fetch_body};
|
||||
@@ -171,6 +173,11 @@ pub enum ErrorType {
|
||||
AccessDenied,
|
||||
#[serde(rename = "expired_token")]
|
||||
ExpiredToken,
|
||||
// inbuxa: K-S4: RFC 7009 section 2.2.1
|
||||
#[serde(rename = "unsupported_token_type")]
|
||||
UnsupportedTokenType,
|
||||
#[serde(rename = "temporarily_unavailable")]
|
||||
TemporarilyUnavailable,
|
||||
}
|
||||
|
||||
impl TokenResponse {
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*
|
||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
||||
*/
|
||||
|
||||
use common::{Server, auth::oauth::SUPPORTED_SCOPES, auth::oauth::oidc::Userinfo};
|
||||
@@ -18,6 +20,9 @@ pub struct OpenIdMetadata {
|
||||
pub jwks_uri: String,
|
||||
pub registration_endpoint: String,
|
||||
pub device_authorization_endpoint: String,
|
||||
// inbuxa: K-S4
|
||||
pub revocation_endpoint: String,
|
||||
pub revocation_endpoint_auth_methods_supported: &'static [&'static str],
|
||||
pub scopes_supported: &'static [&'static str],
|
||||
pub response_types_supported: &'static [&'static str],
|
||||
pub subject_types_supported: &'static [&'static str],
|
||||
@@ -79,6 +84,12 @@ impl OpenIdHandler for Server {
|
||||
jwks_uri: format!("{base_url}/auth/jwks.json"),
|
||||
registration_endpoint: format!("{base_url}/auth/register"),
|
||||
device_authorization_endpoint: format!("{base_url}/auth/device"),
|
||||
revocation_endpoint: format!("{base_url}/auth/revoke"),
|
||||
revocation_endpoint_auth_methods_supported: &[
|
||||
"none",
|
||||
"client_secret_post",
|
||||
"client_secret_basic",
|
||||
],
|
||||
response_types_supported: &["code"],
|
||||
grant_types_supported: &[
|
||||
"authorization_code",
|
||||
|
||||
@@ -17,7 +17,11 @@ use base64::{
|
||||
};
|
||||
use common::{
|
||||
KV_OAUTH, KV_OAUTH_DEVICE, Server,
|
||||
auth::oauth::{GrantType, oidc::StandardClaims},
|
||||
auth::oauth::{
|
||||
GrantType,
|
||||
oidc::StandardClaims,
|
||||
revoke::{RevokeOutcome, oauth_token_id},
|
||||
},
|
||||
};
|
||||
use http_proto::*;
|
||||
use hyper::StatusCode;
|
||||
@@ -42,6 +46,13 @@ pub trait TokenHandler: Sync + Send {
|
||||
session_id: u64,
|
||||
) -> impl Future<Output = trc::Result<HttpResponse>> + Send;
|
||||
|
||||
// inbuxa: K-S4
|
||||
fn handle_token_revoke(
|
||||
&self,
|
||||
req: &mut HttpRequest,
|
||||
session_id: u64,
|
||||
) -> impl Future<Output = trc::Result<HttpResponse>> + Send;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn issue_token(
|
||||
&self,
|
||||
@@ -331,6 +342,85 @@ impl TokenHandler for Server {
|
||||
.map(|response| JsonResponse::new(response).no_cache().into_http_response())
|
||||
}
|
||||
|
||||
/// inbuxa: K-S4: RFC 7009. A token that doesn't validate is answered as
|
||||
/// revoked, as the RFC asks; a valid one is refused from then on, on
|
||||
/// every node, until it would have expired. A token issued to a client
|
||||
/// is revoked only by that client, with its secret if it has one.
|
||||
async fn handle_token_revoke(
|
||||
&self,
|
||||
req: &mut HttpRequest,
|
||||
session_id: u64,
|
||||
) -> trc::Result<HttpResponse> {
|
||||
let params = FormData::from_request(req, MAX_POST_LEN, session_id).await?;
|
||||
let (client_id, client_secret) = client_credentials(req, ¶ms);
|
||||
let Some(token) = params.get("token").filter(|token| !token.is_empty()) else {
|
||||
return Ok(revoke_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
ErrorType::InvalidRequest,
|
||||
));
|
||||
};
|
||||
|
||||
let info = match self.validate_access_token(None, token).await {
|
||||
Ok(info) => info,
|
||||
Err(err)
|
||||
if matches!(
|
||||
err.event_type(),
|
||||
trc::EventType::Auth(trc::AuthEvent::Error)
|
||||
| trc::EventType::Auth(trc::AuthEvent::TokenExpired)
|
||||
) =>
|
||||
{
|
||||
return Ok(HttpResponse::new(StatusCode::OK));
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if !matches!(
|
||||
info.grant_type,
|
||||
GrantType::AccessToken | GrantType::RefreshToken
|
||||
) {
|
||||
return Ok(revoke_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
ErrorType::UnsupportedTokenType,
|
||||
));
|
||||
}
|
||||
|
||||
// AU-5: the token names the client it was issued to. As with a
|
||||
// refresh, naming no client stands for the token's own, and a
|
||||
// confidential one authenticates
|
||||
if let Some(issued_to) = info.claims.as_deref().filter(|c| !c.is_empty()) {
|
||||
if client_id.as_deref().is_some_and(|id| id != issued_to)
|
||||
|| self
|
||||
.verify_client_secret(issued_to, client_secret.as_deref())
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
return Ok(revoke_error(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
ErrorType::InvalidClient,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
match self
|
||||
.revoke_oauth_token(info.account_id, oauth_token_id(token), info.expiry)
|
||||
.await?
|
||||
{
|
||||
RevokeOutcome::Revoked | RevokeOutcome::AlreadyRevoked => {
|
||||
Ok(HttpResponse::new(StatusCode::OK))
|
||||
}
|
||||
RevokeOutcome::Full => {
|
||||
trc::event!(
|
||||
Auth(trc::AuthEvent::Error),
|
||||
AccountId = info.account_id,
|
||||
Reason = "Too many revoked tokens held for this account",
|
||||
);
|
||||
Ok(revoke_error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
ErrorType::TemporarilyUnavailable,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn issue_token(
|
||||
&self,
|
||||
account_id: u32,
|
||||
@@ -404,6 +494,12 @@ impl TokenHandler for Server {
|
||||
}
|
||||
}
|
||||
|
||||
fn revoke_error(status: StatusCode, error: ErrorType) -> HttpResponse {
|
||||
JsonResponse::with_status(status, TokenResponse::error(error))
|
||||
.no_cache()
|
||||
.into_http_response()
|
||||
}
|
||||
|
||||
fn client_credentials<'x>(
|
||||
req: &'x HttpRequest,
|
||||
params: &'x FormData,
|
||||
|
||||
@@ -447,6 +447,13 @@ impl ParseHttp for Server {
|
||||
|
||||
return self.handle_token_request(&mut req, session).await;
|
||||
}
|
||||
// inbuxa: K-S4: RFC 7009
|
||||
("revoke", &Method::POST) => {
|
||||
self.is_http_anonymous_request_allowed(session.remote_ip)
|
||||
.await?;
|
||||
|
||||
return self.handle_token_revoke(&mut req, session.session_id).await;
|
||||
}
|
||||
("introspect", &Method::POST) => {
|
||||
// Authenticate request
|
||||
let (_in_flight, _) = self.authenticate_headers(&req, &session).await?;
|
||||
|
||||
@@ -28,6 +28,16 @@ Observed in the source at `v0.16.22` and against a running inbuxa-server on
|
||||
which INBUXA Admin uses to find the endpoints.
|
||||
- **There's no revocation endpoint.** Tokens are stateless and sealed, so a
|
||||
token can only be invalidated by changing the account's password.
|
||||
*27.1 adds one* (K-S4): `/auth/revoke` (RFC 7009), listed as
|
||||
`revocation_endpoint` in both discovery documents. A revoked access or
|
||||
refresh token is refused on every node until it would have expired. Each
|
||||
account keeps a list of revoked tokens in the in-memory store; the list is
|
||||
cached with the account and the cache entry is dropped cluster-wide on a
|
||||
revocation. A token issued to a client is revoked only by that client
|
||||
(with its secret, if it has one). A token that doesn't validate is
|
||||
answered `200`, as the RFC asks. Revoking a refresh token doesn't revoke
|
||||
the access tokens it minted, since nothing links them; a client revokes
|
||||
both.
|
||||
- **Clients aren't required to be registered, by default.**
|
||||
`x:OidcProvider.requireClientRegistration` defaults to `false`. With it off,
|
||||
any `client_id` with any redirect URI is accepted (HTTP ones only with PKCE).
|
||||
|
||||
+179
-1
@@ -57,6 +57,8 @@ pub struct OAuthMetadata {
|
||||
pub device_authorization_endpoint: String,
|
||||
pub registration_endpoint: String,
|
||||
pub introspection_endpoint: String,
|
||||
pub revocation_endpoint: String,
|
||||
pub revocation_endpoint_auth_methods_supported: Vec<String>,
|
||||
pub grant_types_supported: Vec<String>,
|
||||
pub response_types_supported: Vec<String>,
|
||||
pub scopes_supported: Vec<String>,
|
||||
@@ -882,7 +884,133 @@ pub async fn test(test: &mut TestServer) {
|
||||
¶ms,
|
||||
)
|
||||
.await;
|
||||
unwrap_token_response(granted);
|
||||
let (revoke_access, revoke_refresh, _) = unwrap_token_response(granted);
|
||||
let revoke_refresh = revoke_refresh.expect("offline_access grants a refresh token");
|
||||
|
||||
// ------------------------
|
||||
// inbuxa: K-S4: token revocation (RFC 7009)
|
||||
// ------------------------
|
||||
assert_eq!(
|
||||
metadata.revocation_endpoint,
|
||||
"https://127.0.0.1:8899/auth/revoke"
|
||||
);
|
||||
assert!(
|
||||
metadata
|
||||
.revocation_endpoint_auth_methods_supported
|
||||
.contains(&"client_secret_basic".to_string())
|
||||
);
|
||||
let revoke_form = |token: &str, client_id: Option<&str>, secret: Option<&str>| {
|
||||
let mut form = AHashMap::from_iter([("token".to_string(), token.to_string())]);
|
||||
if let Some(client_id) = client_id {
|
||||
form.insert("client_id".to_string(), client_id.to_string());
|
||||
}
|
||||
if let Some(secret) = secret {
|
||||
form.insert("client_secret".to_string(), secret.to_string());
|
||||
}
|
||||
form
|
||||
};
|
||||
|
||||
// A confidential client's token is revoked only with its secret, and
|
||||
// never by another client
|
||||
for (client_id, secret, why) in [
|
||||
(None, None, "no secret"),
|
||||
(Some(confidential_id.as_str()), None, "no secret"),
|
||||
(
|
||||
Some(confidential_id.as_str()),
|
||||
Some("not-the-secret"),
|
||||
"a wrong secret",
|
||||
),
|
||||
(Some(client_id.as_str()), None, "another client"),
|
||||
] {
|
||||
assert_eq!(
|
||||
post_status(
|
||||
&metadata.revocation_endpoint,
|
||||
&revoke_form(&revoke_access, client_id, secret)
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
401,
|
||||
"revoked with {why}"
|
||||
);
|
||||
}
|
||||
// (Access tokens here live 5 seconds, so each check uses the server
|
||||
// itself rather than another token that may have expired)
|
||||
assert_authorized("https://127.0.0.1:8899", &revoke_access).await;
|
||||
|
||||
// Revoked with the secret in the body: refused from then on
|
||||
assert_eq!(
|
||||
post_status(
|
||||
&metadata.revocation_endpoint,
|
||||
&revoke_form(
|
||||
&revoke_access,
|
||||
Some(&confidential_id),
|
||||
Some(&confidential_secret)
|
||||
)
|
||||
)
|
||||
.await,
|
||||
(200, Bytes::new())
|
||||
);
|
||||
assert_unauthorized("https://127.0.0.1:8899", &revoke_access).await;
|
||||
// Again, and a token that was never valid: both answered as revoked
|
||||
for revoked in [revoke_access.as_str(), "sw1.not-a-token"] {
|
||||
assert_eq!(
|
||||
post_status(
|
||||
&metadata.revocation_endpoint,
|
||||
&revoke_form(revoked, Some(&confidential_id), Some(&confidential_secret))
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
200
|
||||
);
|
||||
}
|
||||
// No token at all is a bad request
|
||||
assert_eq!(
|
||||
post_status(&metadata.revocation_endpoint, &AHashMap::new())
|
||||
.await
|
||||
.0,
|
||||
400
|
||||
);
|
||||
|
||||
// Revoking the access token left its refresh token working
|
||||
let refresh_form = AHashMap::from_iter([
|
||||
("grant_type".to_string(), "refresh_token".to_string()),
|
||||
("refresh_token".to_string(), revoke_refresh.clone()),
|
||||
]);
|
||||
let (refreshed, _, _) = unwrap_token_response(
|
||||
post_form_basic(
|
||||
&metadata.token_endpoint,
|
||||
&confidential_id,
|
||||
&confidential_secret,
|
||||
&refresh_form,
|
||||
)
|
||||
.await,
|
||||
);
|
||||
assert_authorized("https://127.0.0.1:8899", &refreshed).await;
|
||||
|
||||
// A refresh token revoked with client_secret_basic mints nothing more
|
||||
assert_eq!(
|
||||
post_form_basic_status(
|
||||
&metadata.revocation_endpoint,
|
||||
&confidential_id,
|
||||
&confidential_secret,
|
||||
&revoke_form(&revoke_refresh, None, None),
|
||||
)
|
||||
.await,
|
||||
200
|
||||
);
|
||||
assert_eq!(
|
||||
post_form_basic::<TokenResponse>(
|
||||
&metadata.token_endpoint,
|
||||
&confidential_id,
|
||||
&confidential_secret,
|
||||
&refresh_form,
|
||||
)
|
||||
.await,
|
||||
TokenResponse::Error {
|
||||
error: ErrorType::InvalidGrant
|
||||
},
|
||||
"a revoked refresh token was redeemed"
|
||||
);
|
||||
|
||||
// A confidential client created through the management API must have its
|
||||
// secret hashed before storage; authenticating with the plaintext secret
|
||||
@@ -1252,6 +1380,43 @@ async fn post_json_raw(url: &str, body: &impl Serialize) -> (u16, serde_json::Va
|
||||
(status, value)
|
||||
}
|
||||
|
||||
/// inbuxa: K-S4: the status and body of a form POST.
|
||||
async fn post_status(url: &str, params: &AHashMap<String, String>) -> (u16, Bytes) {
|
||||
let response = reqwest::Client::builder()
|
||||
.timeout(Duration::from_millis(500))
|
||||
.danger_accept_invalid_certs(true)
|
||||
.build()
|
||||
.unwrap_or_default()
|
||||
.post(url)
|
||||
.form(params)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status().as_u16();
|
||||
(status, response.bytes().await.unwrap())
|
||||
}
|
||||
|
||||
async fn post_form_basic_status(
|
||||
url: &str,
|
||||
username: &str,
|
||||
password: &str,
|
||||
params: &AHashMap<String, String>,
|
||||
) -> u16 {
|
||||
reqwest::Client::builder()
|
||||
.timeout(Duration::from_millis(500))
|
||||
.danger_accept_invalid_certs(true)
|
||||
.build()
|
||||
.unwrap_or_default()
|
||||
.post(url)
|
||||
.basic_auth(username, Some(password))
|
||||
.form(params)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status()
|
||||
.as_u16()
|
||||
}
|
||||
|
||||
async fn post_login_raw(body: &impl Serialize) -> (u16, serde_json::Value) {
|
||||
post_json_raw("https://127.0.0.1:8899/api/auth", body).await
|
||||
}
|
||||
@@ -1286,6 +1451,19 @@ async fn get<T: DeserializeOwned>(url: &str) -> T {
|
||||
serde_json::from_slice(&get_bytes(url).await).unwrap()
|
||||
}
|
||||
|
||||
/// inbuxa: K-S4: the token signs in to JMAP.
|
||||
async fn assert_authorized(base_url: &str, token: &str) {
|
||||
if let Err(err) = Client::new()
|
||||
.credentials(Credentials::bearer(token))
|
||||
.accept_invalid_certs(true)
|
||||
.follow_redirects(["127.0.0.1"])
|
||||
.connect(base_url)
|
||||
.await
|
||||
{
|
||||
panic!("expected the token to sign in, got {err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_unauthorized(base_url: &str, token: &str) {
|
||||
match Client::new()
|
||||
.credentials(Credentials::bearer(token))
|
||||
|
||||
Reference in new issue
Block a user