Skip to main content

lean_ctx_ext/core/trust/
identity.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Stable identity value types shared by local and enterprise deployments.
3
4use serde::{Deserialize, Serialize};
5use std::fmt;
6
7macro_rules! identity_id {
8    ($name:ident, $documentation:literal) => {
9        #[doc = $documentation]
10        #[derive(
11            Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize,
12        )]
13        #[serde(transparent)]
14        pub struct $name(String);
15
16        impl $name {
17            /// Creates an identifier from its opaque string representation.
18            #[must_use]
19            pub fn new(value: impl Into<String>) -> Self {
20                Self(value.into())
21            }
22
23            /// Returns the opaque identifier without allocating.
24            #[must_use]
25            pub fn as_str(&self) -> &str {
26                &self.0
27            }
28
29            /// Returns whether the identifier is empty.
30            #[must_use]
31            pub fn is_empty(&self) -> bool {
32                self.0.is_empty()
33            }
34        }
35
36        impl From<&str> for $name {
37            fn from(value: &str) -> Self {
38                Self::new(value)
39            }
40        }
41
42        impl From<String> for $name {
43            fn from(value: String) -> Self {
44                Self::new(value)
45            }
46        }
47
48        impl AsRef<str> for $name {
49            fn as_ref(&self) -> &str {
50                self.as_str()
51            }
52        }
53
54        impl fmt::Display for $name {
55            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
56                formatter.write_str(self.as_str())
57            }
58        }
59    };
60}
61
62identity_id!(
63    TenantId,
64    "Opaque identifier for the tenant that owns an execution or data object."
65);
66identity_id!(
67    ProjectId,
68    "Opaque identifier for a project within a tenant."
69);
70identity_id!(
71    AgentId,
72    "Opaque identifier for an agent execution identity."
73);
74identity_id!(
75    HumanActorId,
76    "Opaque identifier for the human actor responsible for an action."
77);
78identity_id!(
79    ServiceId,
80    "Opaque identifier for a service acting on behalf of a tenant."
81);
82
83/// Scope at which an identity or reference is valid.
84#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
85pub enum IdentityScope {
86    /// Valid only inside one local runtime or process.
87    #[default]
88    Local,
89    /// Valid for one tenant and its authorized projects.
90    Tenant,
91    /// Explicitly spans more than one tenant and requires enterprise policy.
92    CrossTenant,
93}
94
95/// Identity attributes carried with a request, evidence entry, or policy
96/// evaluation.
97#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
98pub struct IdentityContext {
99    /// Owning tenant. This is mandatory even for local contexts.
100    pub tenant: TenantId,
101    /// Optional project within the tenant.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub project: Option<ProjectId>,
104    /// Optional agent execution identity.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub agent: Option<AgentId>,
107    /// Optional human actor who initiated or approved the action.
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub human_actor: Option<HumanActorId>,
110    /// Optional service identity used for a delegated operation.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub service: Option<ServiceId>,
113    /// Optional session or trace-local identity.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub session: Option<String>,
116}
117
118impl IdentityContext {
119    /// Creates a context with only its required tenant identity.
120    #[must_use]
121    pub fn new(tenant: impl Into<TenantId>) -> Self {
122        Self {
123            tenant: tenant.into(),
124            project: None,
125            agent: None,
126            human_actor: None,
127            service: None,
128            session: None,
129        }
130    }
131
132    /// Sets the project scope.
133    #[must_use]
134    pub fn with_project(mut self, project: impl Into<ProjectId>) -> Self {
135        self.project = Some(project.into());
136        self
137    }
138
139    /// Sets the agent identity.
140    #[must_use]
141    pub fn with_agent(mut self, agent: impl Into<AgentId>) -> Self {
142        self.agent = Some(agent.into());
143        self
144    }
145
146    /// Sets the human actor identity.
147    #[must_use]
148    pub fn with_human_actor(mut self, human_actor: impl Into<HumanActorId>) -> Self {
149        self.human_actor = Some(human_actor.into());
150        self
151    }
152
153    /// Sets the delegated service identity.
154    #[must_use]
155    pub fn with_service(mut self, service: impl Into<ServiceId>) -> Self {
156        self.service = Some(service.into());
157        self
158    }
159
160    /// Sets the session identity.
161    #[must_use]
162    pub fn with_session(mut self, session: impl Into<String>) -> Self {
163        self.session = Some(session.into());
164        self
165    }
166
167    /// Returns the tenant without exposing mutable identity state.
168    #[must_use]
169    pub fn tenant_id(&self) -> &TenantId {
170        &self.tenant
171    }
172
173    /// Returns the most specific declared scope for this context.
174    #[must_use]
175    pub fn scope(&self) -> IdentityScope {
176        if self.tenant.is_empty() {
177            IdentityScope::Local
178        } else {
179            IdentityScope::Tenant
180        }
181    }
182}