1use std::sync::Arc;
8
9use axum::{
10 extract::State,
11 http::{header, StatusCode},
12 response::{IntoResponse, Response},
13 Extension, Json,
14};
15use hyprstream_pds::repo_authority::is_path_form_did_web;
16use serde::{Deserialize, Serialize};
17
18use super::state::OAuthState;
19use crate::server::middleware::AuthenticatedUser;
20
21pub const MOUNT_TICKET_TTL: i64 = 5 * 60;
22pub const MOUNT_CAP_PREFIX: &str = "mount@9p://";
23
24#[derive(Debug, Deserialize)]
25pub struct MountTicketRequest {
26 pub plane: String,
28 pub namespace_path: String,
31 #[serde(default)]
34 pub pubkey: Option<String>,
35}
36
37#[derive(Debug, Serialize)]
38pub struct MountTicketResponse {
39 pub ticket: String,
40 pub token_type: &'static str,
41 pub expires_in: i64,
42 pub audience: String,
43 pub capability: String,
44}
45
46pub async fn issue_mount_ticket(
48 State(state): State<Arc<OAuthState>>,
49 Extension(user): Extension<AuthenticatedUser>,
50 Json(body): Json<MountTicketRequest>,
51) -> Response {
52 if !valid_plane(&body.plane) {
53 return oauth_error(
54 StatusCode::BAD_REQUEST,
55 "invalid_request",
56 Some("plane must contain only [A-Za-z0-9._-]"),
57 );
58 }
59 if body.pubkey.is_some() {
67 return oauth_error(
68 StatusCode::BAD_REQUEST,
69 "invalid_request",
70 Some(
71 "sender-bound mount tickets are not supported until 9P attach verifies proof-of-possession",
72 ),
73 );
74 }
75 let normalized_path = match normalize_namespace_path(&body.namespace_path) {
76 Some(path) => path,
77 None => {
78 return oauth_error(
79 StatusCode::BAD_REQUEST,
80 "invalid_request",
81 Some("namespace_path must be absolute and must not contain '..'"),
82 );
83 }
84 };
85 if normalized_path != "/" {
86 return oauth_error(
87 StatusCode::FORBIDDEN,
88 "insufficient_scope",
89 Some(
90 "non-root namespace_path tickets require namespace authorization and are not enabled yet",
91 ),
92 );
93 }
94
95 if is_path_form_did_web(&user.user) {
96 return oauth_error(
97 StatusCode::BAD_REQUEST,
98 "invalid_grant",
99 Some(
100 "path-form did:web account subjects are frozen; host-form account minting is not available yet (#1159)",
101 ),
102 );
103 }
104
105 let key = match state.active_jwt_signing_key().await {
106 Some(k) => k,
107 None => {
108 return oauth_error(
109 StatusCode::SERVICE_UNAVAILABLE,
110 "temporarily_unavailable",
111 Some("mount-ticket issuance not available"),
112 );
113 }
114 };
115
116 let now = chrono::Utc::now().timestamp();
117 let exp = now + MOUNT_TICKET_TTL;
118 let audience = state.issuer_url.clone();
119 let capability = ticket_capability(&body.plane, &normalized_path);
120 let domain = match user.authorization_domain() {
121 Ok(domain) => domain,
122 Err(_) => {
123 return oauth_error(
124 StatusCode::FORBIDDEN,
125 "insufficient_scope",
126 Some("Verified hosted-account tenant binding required"),
127 );
128 }
129 };
130 let source_claims = match user
135 .token
136 .as_deref()
137 .and_then(|token| hyprstream_rpc::auth::decode_unverified(token).ok())
138 {
139 Some(claims)
140 if claims.sub == user.user
141 && claims.tenant.as_deref() == user.verified_tenant.as_deref() =>
142 {
143 claims
144 }
145 _ => {
146 return oauth_error(
147 StatusCode::FORBIDDEN,
148 "insufficient_scope",
149 Some("verified source Claims required for MAC-bound mount ticket"),
150 );
151 }
152 };
153 let Some(clearance) = source_claims.clearance else {
154 return oauth_error(
155 StatusCode::FORBIDDEN,
156 "insufficient_scope",
157 Some("source credential has no authority-stamped MAC clearance"),
158 );
159 };
160 let Some(client_id) = source_claims
165 .client_id
166 .clone()
167 .filter(|c| !c.trim().is_empty())
168 else {
169 return oauth_error(
170 StatusCode::FORBIDDEN,
171 "insufficient_scope",
172 Some("source credential has no RFC 9068 client_id to bind the mount ticket to"),
173 );
174 };
175 let mut claims = hyprstream_rpc::auth::Claims::new(user.user.clone(), now, exp)
176 .with_jti()
177 .with_issuer(state.issuer_url.clone())
178 .with_audience(Some(audience.clone()))
179 .with_cap(capability.clone())
180 .with_client_id(client_id)
181 .with_credential_clearance(clearance);
182 if domain != "*" {
183 claims = claims.with_tenant(domain);
184 }
185 let ticket = hyprstream_rpc::auth::jwt::encode(&claims, &key);
186
187 tracing::info!(
188 sub = %user.user,
189 plane = %body.plane,
190 namespace_path = %normalized_path,
191 "9P mount ticket issued"
192 );
193
194 (
195 StatusCode::OK,
196 [
197 (header::CACHE_CONTROL, "no-store"),
198 (header::PRAGMA, "no-cache"),
199 ],
200 Json(MountTicketResponse {
201 ticket,
202 token_type: "mount-ticket+jwt",
203 expires_in: MOUNT_TICKET_TTL,
204 audience,
205 capability,
206 }),
207 )
208 .into_response()
209}
210
211#[cfg(test)]
212#[allow(clippy::unwrap_used, clippy::expect_used)]
213mod freeze_tests {
214 use super::*;
215 use crate::config::OAuthConfig;
216 use axum::extract::Extension;
217 use hyprstream_rpc::rpc_client::RpcClientImpl;
218 use hyprstream_rpc::signer::LocalSigner;
219 use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
220 use hyprstream_rpc_std::discovery_client::DiscoveryClient;
221 use hyprstream_rpc_std::policy_client::PolicyClient;
222
223 fn test_state() -> Arc<OAuthState> {
224 let key = ed25519_dalek::SigningKey::from_bytes(&[0x75; 32]);
225 let dummy = std::path::PathBuf::from("/dev/null/mount-ticket-freeze-test.sock");
226 let make_client = || {
227 Arc::new(
228 RpcClientImpl::new(
229 LocalSigner::new(key.clone()),
230 LazyUdsTransport::new(dummy.clone()),
231 Some(key.verifying_key()),
232 )
233 .with_response_verify_policy(hyprstream_rpc::crypto::CryptoPolicy::Classical),
234 )
235 };
236 Arc::new(
237 OAuthState::new(
238 &OAuthConfig::default(),
239 PolicyClient::new(make_client()),
240 DiscoveryClient::new(make_client()),
241 key.verifying_key().to_bytes(),
242 )
243 .with_ca_jwt_key(key),
244 )
245 }
246
247 fn request() -> MountTicketRequest {
248 MountTicketRequest {
249 plane: "webtransport".to_owned(),
250 namespace_path: "/".to_owned(),
251 pubkey: None,
252 }
253 }
254
255 fn source_claims() -> hyprstream_rpc::auth::Claims {
256 hyprstream_rpc::auth::Claims::new(
257 "alice".to_owned(),
258 chrono::Utc::now().timestamp(),
259 chrono::Utc::now().timestamp() + 300,
260 )
261 .with_issuer(test_state().issuer_url.clone())
262 .with_tenant("tenant-a.example".to_owned())
263 .with_client_id("hyprstream-oauth-client-1")
264 .with_clearance(hyprstream_rpc::auth::mac::SecurityLabel::new(
265 hyprstream_rpc::auth::mac::Level::Secret,
266 hyprstream_rpc::auth::mac::Assurance::Classical,
267 hyprstream_rpc::auth::mac::CompartmentSet::EMPTY,
268 ))
269 }
270
271 async fn issue_for_source_claims(claims: hyprstream_rpc::auth::Claims) -> Response {
272 let source_token =
273 crate::auth::jwt::encode(&claims, &ed25519_dalek::SigningKey::from_bytes(&[0x75; 32]));
274 issue_mount_ticket(
275 State(test_state()),
276 Extension(AuthenticatedUser {
277 user: "alice".to_owned(),
278 verified_tenant: Some("tenant-a.example".to_owned()),
279 token: Some(source_token),
280 exp: None,
281 }),
282 Json(request()),
283 )
284 .await
285 }
286
287 #[tokio::test]
288 async fn mount_ticket_rejects_path_form_authenticated_user_before_signing() {
289 let response = issue_mount_ticket(
290 State(test_state()),
291 Extension(AuthenticatedUser {
292 user: "did:web:accounts.example:users:alice".to_owned(),
293 verified_tenant: Some("tenant-a.example".to_owned()),
294 token: None,
295 exp: None,
296 }),
297 Json(request()),
298 )
299 .await;
300
301 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
302 }
303
304 #[tokio::test]
305 async fn mount_ticket_rejects_sender_bound_ticket_request() {
306 let mut req = request();
307 req.pubkey = Some("ed25519:AAAA".to_owned());
308 let response = issue_mount_ticket(
309 State(test_state()),
310 Extension(AuthenticatedUser {
311 user: "alice".to_owned(),
312 verified_tenant: Some("tenant-a.example".to_owned()),
313 token: None,
314 exp: None,
315 }),
316 Json(req),
317 )
318 .await;
319
320 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
321 }
322
323 #[tokio::test]
324 async fn mount_ticket_allows_ordinary_authenticated_user() {
325 let response = issue_for_source_claims(source_claims()).await;
326
327 assert_eq!(response.status(), StatusCode::OK);
328 let body = axum::body::to_bytes(response.into_body(), usize::MAX)
329 .await
330 .unwrap();
331 let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
332 let claims = crate::auth::jwt::decode(
333 json["ticket"].as_str().unwrap(),
334 &ed25519_dalek::SigningKey::from_bytes(&[0x75; 32]).verifying_key(),
335 None,
336 )
337 .unwrap();
338 assert!(claims.jti.is_some(), "issued mount tickets must be one-use");
339 assert_eq!(claims.tenant.as_deref(), Some("tenant-a.example"));
340 assert_eq!(claims.clearance, source_claims().clearance);
341 }
342
343 #[tokio::test]
347 async fn mount_ticket_allows_dpop_bound_source_token() {
348 let mut claims = source_claims();
349 claims.cnf = Some(hyprstream_rpc::auth::Cnf {
350 jkt: Some("AQIDBAUGBwgJCgsMDQ4PEA".to_owned()),
351 ..Default::default()
352 });
353 let response = issue_for_source_claims(claims).await;
354
355 assert_eq!(response.status(), StatusCode::OK);
356 }
357}
358
359pub fn ticket_capability(plane: &str, namespace_path: &str) -> String {
360 format!("{MOUNT_CAP_PREFIX}{plane}{namespace_path}")
361}
362
363pub fn is_mount_ticket_claims(claims: &hyprstream_rpc::auth::Claims) -> bool {
364 claims
365 .cap
366 .as_deref()
367 .is_some_and(|cap| cap.starts_with(MOUNT_CAP_PREFIX))
368}
369
370pub fn is_mount_ticket_for(
371 claims: &hyprstream_rpc::auth::Claims,
372 plane: &str,
373 namespace_path: &str,
374) -> bool {
375 claims
376 .cap
377 .as_deref()
378 .is_some_and(|cap| cap == ticket_capability(plane, namespace_path))
379}
380
381fn valid_plane(value: &str) -> bool {
382 !value.is_empty()
383 && value
384 .chars()
385 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
386}
387
388pub(crate) fn normalize_namespace_path(value: &str) -> Option<String> {
389 if !value.starts_with('/') {
390 return None;
391 }
392 let mut out = Vec::new();
393 for component in value.split('/') {
394 if component.is_empty() || component == "." {
395 continue;
396 }
397 if component == ".." {
398 return None;
399 }
400 out.push(component);
401 }
402 Some(format!("/{}", out.join("/")))
403}
404
405fn oauth_error(status: StatusCode, error: &str, description: Option<&str>) -> Response {
406 let mut body = serde_json::Map::new();
407 body.insert(
408 "error".to_owned(),
409 serde_json::Value::String(error.to_owned()),
410 );
411 if let Some(description) = description {
412 body.insert(
413 "error_description".to_owned(),
414 serde_json::Value::String(description.to_owned()),
415 );
416 }
417 (
418 status,
419 [
420 (header::CACHE_CONTROL, "no-store"),
421 (header::PRAGMA, "no-cache"),
422 ],
423 Json(serde_json::Value::Object(body)),
424 )
425 .into_response()
426}
427
428#[cfg(test)]
429mod tests {
430 use super::*;
431
432 #[test]
433 fn namespace_path_must_be_absolute_and_contained() {
434 assert_eq!(
435 normalize_namespace_path("/tenant/./data"),
436 Some("/tenant/data".to_owned())
437 );
438 assert_eq!(normalize_namespace_path("/"), Some("/".to_owned()));
439 assert_eq!(normalize_namespace_path("tenant/data"), None);
440 assert_eq!(normalize_namespace_path("/tenant/../root"), None);
441 }
442
443 #[test]
444 fn mount_capability_is_plane_and_path_bound() {
445 assert_eq!(
446 ticket_capability("webtransport", "/tenant/a"),
447 "mount@9p://webtransport/tenant/a"
448 );
449 }
450
451 #[test]
452 fn mount_capability_match_is_exact() {
453 let claims = hyprstream_rpc::auth::Claims::new("alice".to_owned(), 1, 2)
454 .with_cap(ticket_capability("webtransport", "/"));
455 assert!(is_mount_ticket_for(&claims, "webtransport", "/"));
456 assert!(!is_mount_ticket_for(&claims, "ws", "/"));
457 assert!(!is_mount_ticket_for(&claims, "webtransport", "/tenant/a"));
458 }
459}