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    pub scope_id: String,
17    pub hub_id: String,
18    pub jti: String,
19    pub exp: usize,
20    pub iat: usize,
21    #[serde(default)]
22    pub is_test: bool,
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub app_client_id: Option<String>,
25}
26
27impl LocalClientClaims {
28    /// The registered installation comes from Core's credential store, never
29    /// from an ordinary request's clientInfo or identity-shaped payload fields.
30    pub fn client(&self, registered_id: &str) -> Result<AuthenticatedClient, ClientIdentityError> {
31        let principal = match self.token_type.as_str() {
32            USER_TOKEN_TYPE if self.app_client_id.is_none() => ClientPrincipal::User {
33                user_id: self.sub.clone(),
34            },
35            SPACE_TOKEN_TYPE
36                if self.sub == self.scope_id
37                    && self.app_client_id.as_deref() == Some(registered_id) =>
38            {
39                ClientPrincipal::Space {
40                    tenant_id: self.tenant_id.clone(),
41                    scope_id: self.scope_id.clone(),
42                }
43            }
44            _ => return Err(ClientIdentityError::InvalidIdentifier),
45        };
46        let client = AuthenticatedClient {
47            app_client_id: registered_id.to_owned(),
48            principal,
49            credential_id: Some(self.jti.clone()),
50        };
51        client.validate_for(&self.tenant_id, &self.scope_id)?;
52        Ok(client)
53    }
54}
55
56/// Accepted only on the authenticated Lion-to-Core bridge. The signed token
57/// binds the Space, Hub, installation and enrollment; the other fields are labels.
58#[derive(Clone, Serialize, Deserialize)]
59#[serde(rename_all = "camelCase", deny_unknown_fields)]
60pub struct RegisterSpaceClientRequest {
61    pub jwt_token: String,
62    pub client_source: String,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
66#[serde(rename_all = "camelCase", deny_unknown_fields)]
67pub struct SpaceClientCredentialStatus {
68    pub credential_id: String,
69    pub status: String,
70    pub activate_before: i64,
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76
77    fn claims(kind: &str) -> LocalClientClaims {
78        LocalClientClaims {
79            sub: "scope".into(),
80            token_type: kind.into(),
81            tenant_id: "tenant".into(),
82            scope_id: "scope".into(),
83            hub_id: "hub".into(),
84            jti: "enrollment".into(),
85            exp: 100,
86            iat: 1,
87            is_test: false,
88            app_client_id: Some("a:device".into()),
89        }
90    }
91
92    #[test]
93    fn space_credential_has_no_user_and_binds_its_installation() {
94        let claims = claims(SPACE_TOKEN_TYPE);
95        let client = claims.client("a:device").unwrap();
96        assert_eq!(client.user_id(), None);
97        assert!(client.is_space_client());
98        assert!(claims.client("a:another").is_err());
99        assert!(client.validate_for("tenant", "another").is_err());
100    }
101
102    #[test]
103    fn user_and_space_claims_cannot_be_mixed() {
104        let mut claims = claims(USER_TOKEN_TYPE);
105        assert!(claims.client("a:device").is_err());
106        claims.app_client_id = None;
107        claims.sub = "user".into();
108        assert_eq!(claims.client("a:device").unwrap().user_id(), Some("user"));
109        claims.token_type = SPACE_TOKEN_TYPE.into();
110        assert!(claims.client("a:device").is_err());
111        claims.app_client_id = Some("a:device".into());
112        assert!(claims.client("a:device").is_err());
113    }
114}