//! Machine authentication of the object API (contracts.md 2.6 and 5). A family service calls `in` with an //! access token that `im` issued through the client-credentials grant. This module decides whether that //! token may be used here, and names the caller's namespace. //! //! A call passes these checks, in this order, and each refusal is JSON with the status of contracts.md 7: //! 1. The `Authorization: Bearer` token verifies against `im`'s keys (EdDSA, `iss`, `exp` with 60 s leeway, //! `iat` at most 5 minutes ahead), and its `aud` is exactly `in`. Otherwise `401 invalid_token`. //! 2. It is a client token: `sub` starts with `client:` and `svc` is present. A user's access token or an ID //! token has neither, so it is `401 invalid_token`. //! 3. Its scopes contain `files.service`. Otherwise `403 insufficient_scope`. //! 4. `svc` is a family key (`im`, `in` or `iz`). Otherwise `403 insufficient_scope`. //! //! The namespace is `svc` from the verified token and nothing else. No URL segment and no header can //! change it, so a service cannot reach another service's objects by sending its ids. //! //! When the call passes, the service row is created on first use with the default service quota //! (architecture section 3), so a family service needs no registration. //! //! When `[oidc]` is not configured there is no key set to check against, so every machine call is //! `503 unavailable`. Nothing is accepted without verification. use http::header::{AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, WWW_AUTHENTICATE}; use http::{HeaderValue, StatusCode}; use serde_json::{Value, json}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::request::headers; use topcoat::router::response::Response; use topcoat::router::{Body, HeaderMap}; use crate::oidc::{FAMILY_KEY, FILES_SERVICE_SCOPE, OidcError}; use crate::state::AppState; /// The family keys that may call the object API (contracts.md 1). `in` is listed so that the rule reads the /// same as the table; it is not a caller in practice. pub const FAMILY_KEYS: [&str; 3] = ["im", "in", "iz"]; /// The prefix of a client-credentials token's subject (contracts.md 2.6). const CLIENT_SUBJECT_PREFIX: &str = "client:"; /// A verified caller of the object API. Only `service` is trusted; it comes from the verified `svc` claim. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Caller { /// The caller's family key. It names the caller's namespace. pub service: String, } /// A refused call: the status and the stable error word of contracts.md 7, with an English message for logs. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Refusal { /// HTTP status of the answer. pub status: StatusCode, /// The stable machine word, such as `invalid_token`. pub error: &'static str, /// English text for logs and developers. It may change. pub message: &'static str, } impl Refusal { /// The JSON answer of this refusal, with `WWW-Authenticate` on `401`. pub fn answer(&self) -> Response { let mut response = json_response( self.status, &json!({ "error": self.error, "message": self.message }), ); if self.status == StatusCode::UNAUTHORIZED { response.headers_mut().insert( WWW_AUTHENTICATE, HeaderValue::from_static("Bearer error=\"invalid_token\""), ); } response } } /// A refusal shorthand. const fn refuse(status: StatusCode, error: &'static str, message: &'static str) -> Refusal { Refusal { status, error, message, } } /// A JSON response of the object API. Answers are never cached. pub fn json_response(status: StatusCode, value: &Value) -> Response { let body = serde_json::to_vec(value).unwrap_or_default(); let mut response = http::Response::new(Body::from(body)); *response.status_mut() = status; response .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); response .headers_mut() .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); response } /// The bearer token of an `Authorization` header: the scheme is matched without regard to case, and the /// token must be non-empty with no spaces. pub fn bearer_token(headers: &HeaderMap) -> Option<&str> { let value = headers.get(AUTHORIZATION)?.to_str().ok()?; let (scheme, token) = value.split_once(' ')?; if !scheme.eq_ignore_ascii_case("bearer") || token.is_empty() || token.contains(' ') { return None; } Some(token) } /// The default quota of a new service: the `default_service_quota_bytes` setting when it holds a positive /// number, else [`DEFAULT_SERVICE_QUOTA`]. async fn default_service_quota(state: &AppState) -> Result { let resolved = in_core::settings::resolve( &state.store, &state.config.limits, in_core::settings::DEFAULT_SERVICE_QUOTA_KEY, ) .await?; Ok(resolved.value) } /// Checks the bearer token of the request in `cx` and returns the caller, or the refusal to send. /// /// Errors that are not refusals (a database failure) are returned as `Err` and answered as `500` by the /// router. pub async fn machine_caller(cx: &Cx) -> Result> { let state = app_context::(cx); let Some(token) = bearer_token(headers(cx)) else { return Ok(Err(refuse( StatusCode::UNAUTHORIZED, "invalid_token", "a bearer token is required", ))); }; let Some(oidc) = &state.oidc else { return Ok(Err(refuse( StatusCode::SERVICE_UNAVAILABLE, "unavailable", "the identity provider is not configured", ))); }; let claims = match oidc.verify_machine_token(token, FAMILY_KEY).await { Ok(claims) => claims, Err(OidcError::Token(_)) => { return Ok(Err(refuse( StatusCode::UNAUTHORIZED, "invalid_token", "the token is not valid for this API", ))); } Err(error) => { tracing::warn!(error = %error, "machine auth: the keys could not be checked"); return Ok(Err(refuse( StatusCode::SERVICE_UNAVAILABLE, "unavailable", "the identity provider is unavailable", ))); } }; // A user's token or an ID token has no client subject and no `svc`, so it fails here, before any scope // is read. let Some(svc) = claims .svc .as_deref() .filter(|_| claims.subject.starts_with(CLIENT_SUBJECT_PREFIX)) else { return Ok(Err(refuse( StatusCode::UNAUTHORIZED, "invalid_token", "the token is not a service token", ))); }; if !claims .scopes .iter() .any(|scope| scope == FILES_SERVICE_SCOPE) { return Ok(Err(refuse( StatusCode::FORBIDDEN, "insufficient_scope", "the token lacks the files.service scope", ))); } if !FAMILY_KEYS.contains(&svc) { return Ok(Err(refuse( StatusCode::FORBIDDEN, "insufficient_scope", "the caller is not a family service", ))); } let quota = default_service_quota(state).await?; state.store.ensure_service(svc, quota).await?; Ok(Ok(Caller { service: svc.to_owned(), })) } #[cfg(test)] mod tests { use super::*; #[test] fn the_bearer_scheme_is_case_blind_and_one_token_only() { let mut headers = HeaderMap::new(); headers.insert(AUTHORIZATION, HeaderValue::from_static("bearer abc.def")); assert_eq!(bearer_token(&headers), Some("abc.def")); headers.insert(AUTHORIZATION, HeaderValue::from_static("Basic abc")); assert_eq!(bearer_token(&headers), None); headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer a b")); assert_eq!(bearer_token(&headers), None); headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ")); assert_eq!(bearer_token(&headers), None); } }