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
9pub use conversation_api::ClientPrincipal;
10
11/// `appClientId` identifies the installation, `credentialId` its current
12/// enrollment. Neither is a secret. A connection ID is a separate routing key.
13/// Personal Pods have a User principal and an enrollment credential, just as
14/// Space Pods do; a normal user login need not have an enrollment credential.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "camelCase", deny_unknown_fields)]
17pub struct AuthenticatedClient {
18    pub app_client_id: String,
19    pub principal: ClientPrincipal,
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub credential_id: Option<String>,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum ClientIdentityError {
26    InvalidIdentifier,
27    MissingEnrollment,
28    SpaceMismatch,
29}
30
31impl std::fmt::Display for ClientIdentityError {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.write_str(match self {
34            Self::InvalidIdentifier => "Invalid authenticated Client identifier",
35            Self::MissingEnrollment => "Space Client enrollment is required",
36            Self::SpaceMismatch => "Client belongs to a different Space",
37        })
38    }
39}
40
41impl std::error::Error for ClientIdentityError {}
42
43impl AuthenticatedClient {
44    /// Structural and target binding validation, after credential verification.
45    /// A User principal still requires current membership/role authorization at
46    /// the operation boundary. This check never grants access by itself.
47    pub fn validate_for(&self, tenant_id: &str, scope_id: &str) -> Result<(), ClientIdentityError> {
48        let subject = self.app_client_id.strip_prefix("a:");
49        if !valid_id(tenant_id)
50            || !valid_id(scope_id)
51            || !subject.is_some_and(|value| {
52                valid_id(value) && !value.starts_with("a:") && !value.starts_with("p:")
53            })
54            || self
55                .credential_id
56                .as_deref()
57                .is_some_and(|id| !valid_id(id))
58        {
59            return Err(ClientIdentityError::InvalidIdentifier);
60        }
61        match &self.principal {
62            ClientPrincipal::User { user_id } if !valid_id(user_id) => {
63                Err(ClientIdentityError::InvalidIdentifier)
64            }
65            ClientPrincipal::User { .. } => Ok(()),
66            ClientPrincipal::Space {
67                tenant_id: bound_tenant,
68                scope_id: bound_scope,
69            } => {
70                if self.credential_id.is_none() {
71                    return Err(ClientIdentityError::MissingEnrollment);
72                }
73                if bound_tenant != tenant_id || bound_scope != scope_id {
74                    return Err(ClientIdentityError::SpaceMismatch);
75                }
76                Ok(())
77            }
78        }
79    }
80
81    /// Resolve the authenticated Client's catalog. Device/enrollment identity is
82    /// validated but never included in the shared Space group's storage key.
83    pub fn conversation_surface(
84        &self,
85        tenant_id: &str,
86        scope_id: &str,
87    ) -> Result<conversation_api::ConversationSurface, ClientIdentityError> {
88        self.validate_for(tenant_id, scope_id)?;
89        self.principal
90            .client_surface(tenant_id, scope_id)
91            .map_err(|_| ClientIdentityError::InvalidIdentifier)
92    }
93
94    /// No initializer/owner fallback: a Space Client has no acting user.
95    pub fn user_id(&self) -> Option<&str> {
96        match &self.principal {
97            ClientPrincipal::User { user_id } => Some(user_id),
98            ClientPrincipal::Space { .. } => None,
99        }
100    }
101
102    pub fn is_space_client(&self) -> bool {
103        matches!(self.principal, ClientPrincipal::Space { .. })
104    }
105}
106
107fn valid_id(value: &str) -> bool {
108    !value.is_empty()
109        && value.len() <= 256
110        && value.trim() == value
111        && !value.chars().any(char::is_control)
112}