core_api/
client_identity.rs1use serde::{Deserialize, Serialize};
8
9pub use conversation_api::ClientPrincipal;
10
11#[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 pub fn validate_for(&self, tenant_id: &str, space_id: &str) -> Result<(), ClientIdentityError> {
48 let subject = self.app_client_id.strip_prefix("a:");
49 if !valid_id(tenant_id)
50 || !valid_id(space_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 space_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 != space_id {
74 return Err(ClientIdentityError::SpaceMismatch);
75 }
76 Ok(())
77 }
78 }
79 }
80
81 pub fn conversation_surface(
84 &self,
85 tenant_id: &str,
86 space_id: &str,
87 ) -> Result<conversation_api::ConversationSurface, ClientIdentityError> {
88 self.validate_for(tenant_id, space_id)?;
89 self.principal
90 .client_surface(tenant_id, space_id)
91 .map_err(|_| ClientIdentityError::InvalidIdentifier)
92 }
93
94 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}