What administrators and the server itself do to the control plane is now recorded, from inbuxa-drafts/specs/audit-hold-lock.md (AU-1 to AU-12): settings, accounts, domains, roles and every other registry change, with each field's before and after (secrets only as "changed"); the fork's own settings objects; administrator sign-ins (and failed ones to administrator accounts), master-user and recovery-admin sign-ins, once an hour per account, method and address; access to another account's data through impersonation or FetchAnyBlob, once an hour; exports and tamper checks; and registry writes the server makes on its own, named by subsystem (system:AcmeRenewal, system:auto-ban, system:directory-sync, ...), with a spam rules update as one summary record. No change without its record (AU-3): before a set method changes anything, a pending record per requested create, update and destroy is written; if that fails, the method is refused with serverFail. Its outcome follows as a later entry. A change interrupted by a crash stays "unfinished". Records live in the fork's subspace under L, as one SHA-256 hash chain per node. The chain's head is stored, never cached, and every append asserts it, so two writers can't take the same place. Nothing can edit or delete a record; the daily purge removes the oldest past the retention (default 730 days, minimum 90) and records where the chain now starts, so verification still passes. security.audit-recorded (647) copies each record to webhooks, OpenTelemetry and the log; security.audit-write-failed (648) reports a failed write. New JMAP objects under urn:inbuxa:jmap: inbuxa:AuditEvent/get and /query (filters: time, actor, action, target, account, tenant, outcome, address, text), inbuxa:AuditSettings, inbuxa:AuditExport (CSV or JSON Lines built on the server, each line with its chain hash, ending in a manifest; the created object names the blob and its SHA-256) and inbuxa:AuditVerification. New permissions sysAuditGet, sysAuditExport and sysAuditSettingsUpdate: the Administrator role gets all three, the Tenant Administrator role gets read and export, once, on existing installs too. A tenant administrator sees records whose actor or target is in its tenant, including a server administrator's changes there. Sign-in method on the session: access tokens now remember how they signed in (password, app password, API key, OAuth client, directory, master user, recovery admin), including across the HTTP credential cache. New OAuth access tokens carry their client id in the sealed claims; older ones show as client "unknown" until they expire. The schema gains the permissions, the two events and a Management > Compliance > Audit Log link. Stack: the request layer boxes every inner future where it's made. Without that, a debug build overflowed the default 2 MB worker stack on a registry set; measured with the same request, the branch and main now overflow at the same stack size (between 1856 and 1920 KiB, debug), so the layer adds nothing measurable. Tests: unit tests in inbuxa-features and jmap; system::audit::audit_log_tests (run with --ignored) passes on RocksDB, SQLite, PostgreSQL, PostgreSQL with a read replica, MySQL, MySQL with a replica and FoundationDB. The system, JMAP and SCIM suites pass. authorization.rs skipped fork permissions that guard no registry object; the audit suite checks a plain user is refused instead.
341 lines
11 KiB
Rust
341 lines
11 KiB
Rust
/*
|
|
* 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::ErrorType;
|
|
use crate::auth::authenticate::Authenticator;
|
|
use common::{
|
|
Server,
|
|
auth::{
|
|
BuildAccessToken,
|
|
oauth::{
|
|
client_id::{ClientMeta, decode_client_id, encode_client_id, scopes_to_mask},
|
|
registration::{
|
|
ClientRegistrationError, ClientRegistrationRequest, ClientRegistrationResponse,
|
|
TokenEndpointAuthMethod, redirect_uri_matches, validate_grant_metadata,
|
|
validate_redirect_uri,
|
|
},
|
|
},
|
|
},
|
|
};
|
|
use directory::core::secret::{hash_secret, verify_secret_hash};
|
|
use http_proto::{request::fetch_body, *};
|
|
use hyper::StatusCode;
|
|
use registry::schema::{
|
|
enums::{PasswordHashAlgorithm, Permission},
|
|
prelude::{ObjectType, Property, UTCDateTime},
|
|
structs::OAuthClient,
|
|
};
|
|
use std::future::Future;
|
|
use store::{
|
|
rand::{RngExt, distr::Alphanumeric, rng},
|
|
registry::write::{RegistryWrite, RegistryWriteResult},
|
|
write::now,
|
|
};
|
|
use trc::{AddContext, AuthEvent};
|
|
use types::id::Id;
|
|
|
|
pub trait ClientRegistrationHandler: Sync + Send {
|
|
fn handle_oauth_registration_request(
|
|
&self,
|
|
req: &mut HttpRequest,
|
|
session: HttpSessionData,
|
|
) -> impl Future<Output = trc::Result<HttpResponse>> + Send;
|
|
|
|
fn validate_client_registration(
|
|
&self,
|
|
client_id: &str,
|
|
redirect_uri: Option<&str>,
|
|
account_id: u32,
|
|
) -> impl Future<Output = trc::Result<Option<ErrorType>>> + Send;
|
|
|
|
fn verify_client_secret(
|
|
&self,
|
|
client_id: &str,
|
|
client_secret: Option<&str>,
|
|
) -> impl Future<Output = trc::Result<Option<ErrorType>>> + Send;
|
|
}
|
|
impl ClientRegistrationHandler for Server {
|
|
async fn handle_oauth_registration_request(
|
|
&self,
|
|
req: &mut HttpRequest,
|
|
session: HttpSessionData,
|
|
) -> trc::Result<HttpResponse> {
|
|
// Parse request
|
|
let body = fetch_body(req, 20 * 1024, session.session_id).await;
|
|
let request = serde_json::from_slice::<ClientRegistrationRequest>(
|
|
body.as_deref().unwrap_or_default(),
|
|
)
|
|
.map_err(|err| {
|
|
trc::EventType::Resource(trc::ResourceEvent::BadParameters).from_json_error(err)
|
|
})?;
|
|
|
|
// Validate redirect URIs and grant metadata (RFC 7591 + OAuth Public Clients profile)
|
|
if request.redirect_uris.is_empty() {
|
|
return Ok(registration_error(
|
|
ClientRegistrationError::invalid_redirect_uri(
|
|
"At least one redirect URI is required.",
|
|
),
|
|
));
|
|
}
|
|
for uri in &request.redirect_uris {
|
|
if let Err(err) = validate_redirect_uri(uri) {
|
|
return Ok(registration_error(err));
|
|
}
|
|
}
|
|
if let Err(err) = validate_grant_metadata(&request) {
|
|
return Ok(registration_error(err));
|
|
}
|
|
|
|
let is_public = matches!(
|
|
request.token_endpoint_auth_method,
|
|
None | Some(TokenEndpointAuthMethod::None)
|
|
);
|
|
|
|
if is_public {
|
|
// Public client: issue a stateless, self-describing client id with no database write
|
|
if self.core.oauth.allow_anonymous_client_registration {
|
|
self.is_http_anonymous_request_allowed(session.remote_ip)
|
|
.await?;
|
|
} else {
|
|
let (_, access_token) = self.authenticate_headers(req, &session).await?;
|
|
access_token.enforce_permission(Permission::OAuthClientRegistration)?;
|
|
}
|
|
|
|
let client_id = encode_client_id(
|
|
self.core.oauth.oauth_key.as_bytes(),
|
|
&ClientMeta {
|
|
redirect_uris: request.redirect_uris.clone(),
|
|
scope_mask: scopes_to_mask(request.scope.as_deref().unwrap_or_default()),
|
|
client_name: request.client_name.clone(),
|
|
},
|
|
)
|
|
.map_err(|err| {
|
|
trc::AuthEvent::Error
|
|
.into_err()
|
|
.details("Failed to encode client id.")
|
|
.reason(err)
|
|
.caused_by(trc::location!())
|
|
})?;
|
|
|
|
trc::event!(
|
|
Auth(AuthEvent::ClientRegistration),
|
|
Id = client_id.clone(),
|
|
RemoteIp = session.remote_ip
|
|
);
|
|
|
|
return Ok(JsonResponse::with_status(
|
|
StatusCode::CREATED,
|
|
ClientRegistrationResponse {
|
|
client_id_issued_at: Some(now()),
|
|
client_id,
|
|
request,
|
|
..Default::default()
|
|
},
|
|
)
|
|
.no_cache()
|
|
.into_http_response());
|
|
}
|
|
|
|
// Confidential client: authenticate and persist the registration
|
|
let (_, access_token) = self.authenticate_headers(req, &session).await?;
|
|
access_token.enforce_permission(Permission::OAuthClientRegistration)?;
|
|
let tenant_id = access_token.tenant_id();
|
|
|
|
// Generate client ID
|
|
let client_id = rng()
|
|
.sample_iter(Alphanumeric)
|
|
.take(20)
|
|
.map(|ch| char::from(ch.to_ascii_lowercase()))
|
|
.collect::<String>();
|
|
|
|
// Generate client secret
|
|
let client_secret = rng()
|
|
.sample_iter(Alphanumeric)
|
|
.take(48)
|
|
.map(char::from)
|
|
.collect::<String>();
|
|
let secret_hash = hash_secret(
|
|
PasswordHashAlgorithm::Argon2id,
|
|
client_secret.clone().into_bytes(),
|
|
)
|
|
.await
|
|
.caused_by(trc::location!())?;
|
|
|
|
// inbuxa: AU-1.10: a client registering itself
|
|
let result = inbuxa_features::audit::scope::system(
|
|
"oauth-registration",
|
|
self.registry().write(RegistryWrite::insert(
|
|
&OAuthClient {
|
|
client_id: client_id.clone(),
|
|
description: request.client_name.clone(),
|
|
contacts: request.contacts.clone().into(),
|
|
member_tenant_id: tenant_id.map(|id| Id::new(id as u64)),
|
|
redirect_uris: request.redirect_uris.clone().into(),
|
|
logo: request.logo_uri.clone(),
|
|
secret: Some(secret_hash),
|
|
created_at: UTCDateTime::now(),
|
|
..Default::default()
|
|
}
|
|
.into(),
|
|
)),
|
|
)
|
|
.await
|
|
.caused_by(trc::location!())?;
|
|
|
|
if !matches!(result, RegistryWriteResult::Success(_)) {
|
|
return Err(trc::StoreEvent::UnexpectedError
|
|
.into_err()
|
|
.details("Failed to register OAuth client.")
|
|
.reason(result.to_string())
|
|
.caused_by(trc::location!()));
|
|
}
|
|
|
|
trc::event!(
|
|
Auth(AuthEvent::ClientRegistration),
|
|
Id = client_id.to_string(),
|
|
RemoteIp = session.remote_ip
|
|
);
|
|
|
|
Ok(JsonResponse::with_status(
|
|
StatusCode::CREATED,
|
|
ClientRegistrationResponse {
|
|
client_id,
|
|
client_secret: Some(client_secret),
|
|
client_id_issued_at: Some(now()),
|
|
client_secret_expires_at: Some(0),
|
|
request,
|
|
..Default::default()
|
|
},
|
|
)
|
|
.no_cache()
|
|
.into_http_response())
|
|
}
|
|
|
|
async fn validate_client_registration(
|
|
&self,
|
|
client_id: &str,
|
|
redirect_uri: Option<&str>,
|
|
account_id: u32,
|
|
) -> trc::Result<Option<ErrorType>> {
|
|
// Stateless client ids are self-describing and validated at the authorization endpoint
|
|
if decode_client_id(self.core.oauth.oauth_key.as_bytes(), client_id).is_some() {
|
|
return Ok(None);
|
|
}
|
|
if !self.core.oauth.require_client_authentication {
|
|
return Ok(None);
|
|
}
|
|
|
|
// Fetch client registration
|
|
let found_registration = if let Some(client_id) = self
|
|
.registry()
|
|
.primary_key(
|
|
ObjectType::OAuthClient.into(),
|
|
Property::ClientId,
|
|
client_id.as_bytes().to_vec(),
|
|
)
|
|
.await?
|
|
{
|
|
if let Some(redirect_uri) = redirect_uri {
|
|
let client = self
|
|
.registry()
|
|
.object::<OAuthClient>(client_id.id())
|
|
.await?
|
|
.ok_or_else(|| {
|
|
trc::StoreEvent::UnexpectedError
|
|
.into_err()
|
|
.details("OAuth client not found.")
|
|
.caused_by(trc::location!())
|
|
.ctx(trc::Key::Id, client_id.id().id())
|
|
})?;
|
|
if client
|
|
.redirect_uris
|
|
.iter()
|
|
.any(|uri| redirect_uri_matches(uri, redirect_uri))
|
|
{
|
|
return Ok(None);
|
|
}
|
|
} else {
|
|
// Device flow does not require a redirect URI
|
|
|
|
return Ok(None);
|
|
}
|
|
|
|
true
|
|
} else {
|
|
false
|
|
};
|
|
|
|
// Check if the account is allowed to override client registration
|
|
if self
|
|
.access_token(account_id)
|
|
.await
|
|
.caused_by(trc::location!())?
|
|
.build()
|
|
.has_permission(Permission::OAuthClientOverride)
|
|
{
|
|
return Ok(None);
|
|
}
|
|
|
|
Ok(Some(if found_registration {
|
|
ErrorType::InvalidClient
|
|
} else {
|
|
ErrorType::InvalidRequest
|
|
}))
|
|
}
|
|
|
|
async fn verify_client_secret(
|
|
&self,
|
|
client_id: &str,
|
|
client_secret: Option<&str>,
|
|
) -> trc::Result<Option<ErrorType>> {
|
|
// Stateless and unregistered clients have no secret to verify
|
|
if decode_client_id(self.core.oauth.oauth_key.as_bytes(), client_id).is_some() {
|
|
return Ok(None);
|
|
}
|
|
let Some(client_id) = self
|
|
.registry()
|
|
.primary_key(
|
|
ObjectType::OAuthClient.into(),
|
|
Property::ClientId,
|
|
client_id.as_bytes().to_vec(),
|
|
)
|
|
.await?
|
|
else {
|
|
return Ok(None);
|
|
};
|
|
let Some(client) = self
|
|
.registry()
|
|
.object::<OAuthClient>(client_id.id())
|
|
.await
|
|
.caused_by(trc::location!())?
|
|
else {
|
|
return Ok(None);
|
|
};
|
|
|
|
match client.secret.as_deref() {
|
|
Some(hash) if !hash.is_empty() => match client_secret {
|
|
Some(secret)
|
|
if verify_secret_hash(hash, secret.as_bytes())
|
|
.await
|
|
.caused_by(trc::location!())? =>
|
|
{
|
|
Ok(None)
|
|
}
|
|
_ => Ok(Some(ErrorType::InvalidClient)),
|
|
},
|
|
_ => Ok(None),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn registration_error(error: ClientRegistrationError) -> HttpResponse {
|
|
JsonResponse::with_status(StatusCode::BAD_REQUEST, error)
|
|
.no_cache()
|
|
.into_http_response()
|
|
}
|