forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

machine_auth.rs108 lines, 4.0 KiBHistoryRawDownload
1//! Checks the client-credentials tokens that family services present to `im` (contracts 2.6).
2//!
3//! `im` verifies its own tokens: the signature against the published keys, `iss` exactly, `aud` exactly
4//! the string `im` (an array is refused, because `im` never issues one), `exp` and `iat`. Then the token
5//! must be a machine token: `sub` is `client:<azp>`, `svc` names a family key, and it carries no `sid`.
6//! The client it names must still exist, be enabled, and be registered under that family key. A user's
7//! access token and an ID token fail one of these checks, so they never open a machine route.
8
9use http::header::AUTHORIZATION;
10use im_core::jwt;
11use im_core::oauth::is_valid_family_key;
12use im_core::time::unix_now;
13use serde_json::Value;
14use topcoat::Result;
15use topcoat::context::Cx;
16use topcoat::router::StatusCode;
17use topcoat::router::request::headers;
18use topcoat::router::response::Response;
19
20use super::{SCOPE_CHALLENGE, TOKEN_CHALLENGE, api_error};
21use crate::oidc::userinfo::bearer;
22use crate::oidc::{issuer, signing};
23use crate::state::AppState;
24
25/// The scope of the people directory, its stream and the photos (contracts 2.6 and 3).
26pub const DIRECTORY_READ: &str = "directory.read";
27
28/// The audience every directory, photo and family route requires.
29pub const MACHINE_AUDIENCE: &str = "im";
30
31/// A verified machine caller.
32#[derive(Debug, Clone)]
33pub struct Machine {
34 /// The client the token was issued to (`azp`).
35 pub client_id: String,
36 /// The family key of the caller (`svc`).
37 pub caller: String,
38 /// When the token expires, in Unix seconds. A stream ends no later than this.
39 pub expires_at: i64,
40}
41
42/// Verifies the bearer token of the request for `scope`. The outer `Result` is a server failure; the
43/// inner one is the refusal, ready to send as the answer.
44pub async fn require(
45 app: &AppState,
46 cx: &Cx,
47 scope: &str,
48) -> Result<std::result::Result<Machine, Response>> {
49 let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else {
50 return Ok(Err(refused()));
51 };
52 let Some(claims) = signing::verify_access(&app.store, token).await? else {
53 return Ok(Err(refused()));
54 };
55 // The audience must be exactly the string `im`. `check_claims` also checks it, and the exp and iat.
56 if jwt::single_audience(&claims) != Some(MACHINE_AUDIENCE) {
57 return Ok(Err(refused()));
58 }
59 if jwt::check_claims(&claims, issuer(app), MACHINE_AUDIENCE, unix_now()).is_err() {
60 return Ok(Err(refused()));
61 }
62 let text = |name: &str| claims.get(name).and_then(Value::as_str);
63 let (Some(client_id), Some(sub), Some(caller), Some(expires_at)) = (
64 text("azp"),
65 text("sub"),
66 text("svc"),
67 claims.get("exp").and_then(Value::as_i64),
68 ) else {
69 return Ok(Err(refused()));
70 };
71 // A person's token carries a session (`sid`) and a person's id as `sub`; neither is a machine token.
72 if sub != format!("client:{client_id}")
73 || claims.contains_key("sid")
74 || !is_valid_family_key(caller)
75 {
76 return Ok(Err(refused()));
77 }
78 let Some(client) = app.store.client_by_id(client_id).await? else {
79 return Ok(Err(refused()));
80 };
81 if client.is_disabled() || client.service_key.as_deref() != Some(caller) {
82 return Ok(Err(refused()));
83 }
84 let granted = text("scope").unwrap_or_default();
85 if !granted.split_whitespace().any(|word| word == scope) {
86 return Ok(Err(api_error(
87 StatusCode::FORBIDDEN,
88 "insufficient_scope",
89 "The token does not grant the scope this route needs.",
90 Some(SCOPE_CHALLENGE),
91 )));
92 }
93 Ok(Ok(Machine {
94 client_id: client.id,
95 caller: caller.to_owned(),
96 expires_at,
97 }))
98}
99
100/// `401 invalid_token`. One answer for every reason, so the reason is not disclosed.
101fn refused() -> Response {
102 api_error(
103 StatusCode::UNAUTHORIZED,
104 "invalid_token",
105 "The access token is missing, invalid, expired, or not issued for this service.",
106 Some(TOKEN_CHALLENGE),
107 )
108}