forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

machine_auth.rs214 lines, 8.1 KiBHistoryRawDownload
1//! Machine authentication of the object API (contracts.md 2.6 and 5). A family service calls `in` with an
2//! access token that `im` issued through the client-credentials grant. This module decides whether that
3//! token may be used here, and names the caller's namespace.
4//!
5//! A call passes these checks, in this order, and each refusal is JSON with the status of contracts.md 7:
6//! 1. The `Authorization: Bearer` token verifies against `im`'s keys (EdDSA, `iss`, `exp` with 60 s leeway,
7//! `iat` at most 5 minutes ahead), and its `aud` is exactly `in`. Otherwise `401 invalid_token`.
8//! 2. It is a client token: `sub` starts with `client:` and `svc` is present. A user's access token or an ID
9//! token has neither, so it is `401 invalid_token`.
10//! 3. Its scopes contain `files.service`. Otherwise `403 insufficient_scope`.
11//! 4. `svc` is a family key (`im`, `in` or `iz`). Otherwise `403 insufficient_scope`.
12//!
13//! The namespace is `svc` from the verified token and nothing else. No URL segment and no header can
14//! change it, so a service cannot reach another service's objects by sending its ids.
15//!
16//! When the call passes, the service row is created on first use with the default service quota
17//! (architecture section 3), so a family service needs no registration.
18//!
19//! When `[oidc]` is not configured there is no key set to check against, so every machine call is
20//! `503 unavailable`. Nothing is accepted without verification.
21
22use http::header::{AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, WWW_AUTHENTICATE};
23use http::{HeaderValue, StatusCode};
24use serde_json::{Value, json};
25use topcoat::Result;
26use topcoat::context::{Cx, app_context};
27use topcoat::router::request::headers;
28use topcoat::router::response::Response;
29use topcoat::router::{Body, HeaderMap};
30
31use crate::oidc::{FAMILY_KEY, FILES_SERVICE_SCOPE, OidcError};
32use crate::state::AppState;
33
34/// The family keys that may call the object API (contracts.md 1). `in` is listed so that the rule reads the
35/// same as the table; it is not a caller in practice.
36pub const FAMILY_KEYS: [&str; 3] = ["im", "in", "iz"];
37
38/// The prefix of a client-credentials token's subject (contracts.md 2.6).
39const CLIENT_SUBJECT_PREFIX: &str = "client:";
40
41/// A verified caller of the object API. Only `service` is trusted; it comes from the verified `svc` claim.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Caller {
44 /// The caller's family key. It names the caller's namespace.
45 pub service: String,
46}
47
48/// A refused call: the status and the stable error word of contracts.md 7, with an English message for logs.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct Refusal {
51 /// HTTP status of the answer.
52 pub status: StatusCode,
53 /// The stable machine word, such as `invalid_token`.
54 pub error: &'static str,
55 /// English text for logs and developers. It may change.
56 pub message: &'static str,
57}
58
59impl Refusal {
60 /// The JSON answer of this refusal, with `WWW-Authenticate` on `401`.
61 pub fn answer(&self) -> Response {
62 let mut response = json_response(
63 self.status,
64 &json!({ "error": self.error, "message": self.message }),
65 );
66 if self.status == StatusCode::UNAUTHORIZED {
67 response.headers_mut().insert(
68 WWW_AUTHENTICATE,
69 HeaderValue::from_static("Bearer error=\"invalid_token\""),
70 );
71 }
72 response
73 }
74}
75
76/// A refusal shorthand.
77const fn refuse(status: StatusCode, error: &'static str, message: &'static str) -> Refusal {
78 Refusal {
79 status,
80 error,
81 message,
82 }
83}
84
85/// A JSON response of the object API. Answers are never cached.
86pub fn json_response(status: StatusCode, value: &Value) -> Response {
87 let body = serde_json::to_vec(value).unwrap_or_default();
88 let mut response = http::Response::new(Body::from(body));
89 *response.status_mut() = status;
90 response
91 .headers_mut()
92 .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
93 response
94 .headers_mut()
95 .insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
96 response
97}
98
99/// The bearer token of an `Authorization` header: the scheme is matched without regard to case, and the
100/// token must be non-empty with no spaces.
101pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
102 let value = headers.get(AUTHORIZATION)?.to_str().ok()?;
103 let (scheme, token) = value.split_once(' ')?;
104 if !scheme.eq_ignore_ascii_case("bearer") || token.is_empty() || token.contains(' ') {
105 return None;
106 }
107 Some(token)
108}
109
110/// The default quota of a new service: the `default_service_quota_bytes` setting when it holds a positive
111/// number, else [`DEFAULT_SERVICE_QUOTA`].
112async fn default_service_quota(state: &AppState) -> Result<i64> {
113 let resolved = in_core::settings::resolve(
114 &state.store,
115 &state.config.limits,
116 in_core::settings::DEFAULT_SERVICE_QUOTA_KEY,
117 )
118 .await?;
119 Ok(resolved.value)
120}
121
122/// Checks the bearer token of the request in `cx` and returns the caller, or the refusal to send.
123///
124/// Errors that are not refusals (a database failure) are returned as `Err` and answered as `500` by the
125/// router.
126pub async fn machine_caller(cx: &Cx) -> Result<std::result::Result<Caller, Refusal>> {
127 let state = app_context::<AppState>(cx);
128 let Some(token) = bearer_token(headers(cx)) else {
129 return Ok(Err(refuse(
130 StatusCode::UNAUTHORIZED,
131 "invalid_token",
132 "a bearer token is required",
133 )));
134 };
135 let Some(oidc) = &state.oidc else {
136 return Ok(Err(refuse(
137 StatusCode::SERVICE_UNAVAILABLE,
138 "unavailable",
139 "the identity provider is not configured",
140 )));
141 };
142 let claims = match oidc.verify_machine_token(token, FAMILY_KEY).await {
143 Ok(claims) => claims,
144 Err(OidcError::Token(_)) => {
145 return Ok(Err(refuse(
146 StatusCode::UNAUTHORIZED,
147 "invalid_token",
148 "the token is not valid for this API",
149 )));
150 }
151 Err(error) => {
152 tracing::warn!(error = %error, "machine auth: the keys could not be checked");
153 return Ok(Err(refuse(
154 StatusCode::SERVICE_UNAVAILABLE,
155 "unavailable",
156 "the identity provider is unavailable",
157 )));
158 }
159 };
160 // A user's token or an ID token has no client subject and no `svc`, so it fails here, before any scope
161 // is read.
162 let Some(svc) = claims
163 .svc
164 .as_deref()
165 .filter(|_| claims.subject.starts_with(CLIENT_SUBJECT_PREFIX))
166 else {
167 return Ok(Err(refuse(
168 StatusCode::UNAUTHORIZED,
169 "invalid_token",
170 "the token is not a service token",
171 )));
172 };
173 if !claims
174 .scopes
175 .iter()
176 .any(|scope| scope == FILES_SERVICE_SCOPE)
177 {
178 return Ok(Err(refuse(
179 StatusCode::FORBIDDEN,
180 "insufficient_scope",
181 "the token lacks the files.service scope",
182 )));
183 }
184 if !FAMILY_KEYS.contains(&svc) {
185 return Ok(Err(refuse(
186 StatusCode::FORBIDDEN,
187 "insufficient_scope",
188 "the caller is not a family service",
189 )));
190 }
191 let quota = default_service_quota(state).await?;
192 state.store.ensure_service(svc, quota).await?;
193 Ok(Ok(Caller {
194 service: svc.to_owned(),
195 }))
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201
202 #[test]
203 fn the_bearer_scheme_is_case_blind_and_one_token_only() {
204 let mut headers = HeaderMap::new();
205 headers.insert(AUTHORIZATION, HeaderValue::from_static("bearer abc.def"));
206 assert_eq!(bearer_token(&headers), Some("abc.def"));
207 headers.insert(AUTHORIZATION, HeaderValue::from_static("Basic abc"));
208 assert_eq!(bearer_token(&headers), None);
209 headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer a b"));
210 assert_eq!(bearer_token(&headers), None);
211 headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer "));
212 assert_eq!(bearer_token(&headers), None);
213 }
214}