Skip to main content

core_api/
client_identity.rs

1//! Authenticated application identity, independent of transport and device form.
2//!
3//! These types carry the result of credential verification. Deserializing them
4//! never authenticates a caller. Only trusted ingress may attach them to a
5//! request; ordinary request bodies and MWS clientInfo cannot select identity.
6
7use serde::{Deserialize, Serialize};
8
9/// The authority under which a Client acts. A Space principal is a restricted
10/// Client enrolled in one Space, not an owner or the Space's Core service.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
13pub enum ClientPrincipal {
14    User {
15        #[serde(rename = "userId")]
16        user_id: String,
17    },
18    Space {
19        #[serde(rename = "tenantId")]
20        tenant_id: String,
21        #[serde(rename = "scopeId")]
22        scope_id: String,
23    },
24}
25
26/// `appClientId` identifies the installation, `credentialId` its current
27/// enrollment. Neither is a secret. A connection ID is a separate routing key.
28/// Personal Pods have a User principal and an enrollment credential, just as
29/// Space Pods do; a normal user login need not have an enrollment credential.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(rename_all = "camelCase", deny_unknown_fields)]
32pub struct AuthenticatedClient {
33    pub app_client_id: String,
34    pub principal: ClientPrincipal,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub credential_id: Option<String>,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum ClientIdentityError {
41    InvalidIdentifier,
42    MissingEnrollment,
43    SpaceMismatch,
44}
45
46impl std::fmt::Display for ClientIdentityError {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.write_str(match self {
49            Self::InvalidIdentifier => "Invalid authenticated Client identifier",
50            Self::MissingEnrollment => "Space Client enrollment is required",
51            Self::SpaceMismatch => "Client belongs to a different Space",
52        })
53    }
54}
55
56impl std::error::Error for ClientIdentityError {}
57
58impl AuthenticatedClient {
59    /// Structural and target binding validation, after credential verification.
60    /// A User principal still requires current membership/role authorization at
61    /// the operation boundary. This check never grants access by itself.
62    pub fn validate_for(&self, tenant_id: &str, scope_id: &str) -> Result<(), ClientIdentityError> {
63        let subject = self.app_client_id.strip_prefix("a:");
64        if !valid_id(tenant_id)
65            || !valid_id(scope_id)
66            || !subject.is_some_and(|value| {
67                valid_id(value) && !value.starts_with("a:") && !value.starts_with("p:")
68            })
69            || self
70                .credential_id
71                .as_deref()
72                .is_some_and(|id| !valid_id(id))
73        {
74            return Err(ClientIdentityError::InvalidIdentifier);
75        }
76        match &self.principal {
77            ClientPrincipal::User { user_id } if !valid_id(user_id) => {
78                Err(ClientIdentityError::InvalidIdentifier)
79            }
80            ClientPrincipal::User { .. } => Ok(()),
81            ClientPrincipal::Space {
82                tenant_id: bound_tenant,
83                scope_id: bound_scope,
84            } => {
85                if self.credential_id.is_none() {
86                    return Err(ClientIdentityError::MissingEnrollment);
87                }
88                if bound_tenant != tenant_id || bound_scope != scope_id {
89                    return Err(ClientIdentityError::SpaceMismatch);
90                }
91                Ok(())
92            }
93        }
94    }
95
96    /// No initializer/owner fallback: a Space Client has no acting user.
97    pub fn user_id(&self) -> Option<&str> {
98        match &self.principal {
99            ClientPrincipal::User { user_id } => Some(user_id),
100            ClientPrincipal::Space { .. } => None,
101        }
102    }
103
104    pub fn is_space_client(&self) -> bool {
105        matches!(self.principal, ClientPrincipal::Space { .. })
106    }
107}
108
109fn valid_id(value: &str) -> bool {
110    !value.is_empty()
111        && value.len() <= 256
112        && value.trim() == value
113        && !value.chars().any(char::is_control)
114}