Skip to main content

core_api/
local_client.rs

1//! Lion-issued local credentials. Signature, issuer, audience and lifetime must
2//! be checked by the Core before these claims become an authenticated identity.
3use crate::client_identity::{AuthenticatedClient, ClientIdentityError, ClientPrincipal};
4use serde::{Deserialize, Serialize};
5
6pub const LOCAL_CLIENT_AUDIENCE: &str = "mhome:local-client";
7pub const USER_TOKEN_TYPE: &str = "local_client_access";
8pub const SPACE_TOKEN_TYPE: &str = "local_space_client_access";
9pub const REGISTER_SPACE_CLIENT_TARGET: &str = "/hub/client/space/register";
10
11#[derive(Clone, Serialize, Deserialize)]
12pub struct LocalClientClaims {
13    pub sub: String,
14    pub token_type: String,
15    pub tenant_id: String,
16    // Signed credentials retain their fixed private claim schema.
17    #[serde(rename = "scope_id")]
18    pub space_id: String,
19    pub hub_id: String,
20    pub jti: String,
21    pub exp: usize,
22    pub iat: usize,
23    #[serde(default)]
24    pub is_test: bool,
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub app_client_id: Option<String>,
27}
28
29impl LocalClientClaims {
30    /// The registered installation comes from Core's credential store, never
31    /// from an ordinary request's clientInfo or identity-shaped payload fields.
32    pub fn client(&self, registered_id: &str) -> Result<AuthenticatedClient, ClientIdentityError> {
33        let principal = match self.token_type.as_str() {
34            USER_TOKEN_TYPE if self.app_client_id.is_none() => ClientPrincipal::User {
35                user_id: self.sub.clone(),
36            },
37            SPACE_TOKEN_TYPE
38                if self.sub == self.space_id
39                    && self.app_client_id.as_deref() == Some(registered_id) =>
40            {
41                ClientPrincipal::Space {
42                    tenant_id: self.tenant_id.clone(),
43                    space_id: self.space_id.clone(),
44                }
45            }
46            _ => return Err(ClientIdentityError::InvalidIdentifier),
47        };
48        let client = AuthenticatedClient {
49            app_client_id: registered_id.to_owned(),
50            principal,
51            credential_id: Some(self.jti.clone()),
52        };
53        client.validate_for(&self.tenant_id, &self.space_id)?;
54        Ok(client)
55    }
56}
57
58/// Accepted only on the authenticated Lion-to-Core bridge. The signed token
59/// binds the Space, Hub, installation and enrollment; the other fields are labels.
60#[derive(Clone, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase", deny_unknown_fields)]
62pub struct RegisterSpaceClientRequest {
63    pub jwt_token: String,
64    pub client_source: String,
65}
66
67#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
68#[serde(rename_all = "camelCase", deny_unknown_fields)]
69pub struct SpaceClientCredentialStatus {
70    pub credential_id: String,
71    pub status: String,
72    pub activate_before: i64,
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    fn claims(kind: &str) -> LocalClientClaims {
80        LocalClientClaims {
81            sub: "scope".into(),
82            token_type: kind.into(),
83            tenant_id: "tenant".into(),
84            space_id: "scope".into(),
85            hub_id: "hub".into(),
86            jti: "enrollment".into(),
87            exp: 100,
88            iat: 1,
89            is_test: false,
90            app_client_id: Some("a:device".into()),
91        }
92    }
93
94    #[test]
95    fn space_credential_has_no_user_and_binds_its_installation() {
96        let claims = claims(SPACE_TOKEN_TYPE);
97        let client = claims.client("a:device").unwrap();
98        assert_eq!(client.user_id(), None);
99        assert!(client.is_space_client());
100        assert!(claims.client("a:another").is_err());
101        assert!(client.validate_for("tenant", "another").is_err());
102    }
103
104    #[test]
105    fn user_and_space_claims_cannot_be_mixed() {
106        let mut claims = claims(USER_TOKEN_TYPE);
107        assert!(claims.client("a:device").is_err());
108        claims.app_client_id = None;
109        claims.sub = "user".into();
110        assert_eq!(claims.client("a:device").unwrap().user_id(), Some("user"));
111        claims.token_type = SPACE_TOKEN_TYPE.into();
112        assert!(claims.client("a:device").is_err());
113        claims.app_client_id = Some("a:device".into());
114        assert!(claims.client("a:device").is_err());
115    }
116}
117
118#[cfg(test)]
119mod stored_claim_regression {
120    use super::*;
121    #[test]
122    fn opaque_credentials_keep_the_private_scope_claim() {
123        let old = serde_json::json!({"sub":"home","token_type":SPACE_TOKEN_TYPE,"tenant_id":"tenant","scope_id":"home","hub_id":"hub","jti":"id","exp":100,"iat":1,"app_client_id":"a:pod"});
124        let claims: LocalClientClaims = serde_json::from_value(old).unwrap();
125        assert!(claims.client("a:pod").is_ok());
126        let encoded = serde_json::to_value(claims).unwrap();
127        assert_eq!(encoded["scope_id"], "home");
128        assert!(encoded.get("space_id").is_none());
129    }
130}