Skip to main content

uqa_sql/catalog/roles/
identity.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Role incarnations and authorization subjects over an explicit role catalog.
8
9use super::RoleDefinition;
10use crate::SQLError;
11use serde::{Deserialize, Serialize};
12use std::{collections::BTreeMap, sync::Arc};
13pub use uqa_core::catalog_role::RoleIdentity;
14use uqa_core::memory::ProductionControl;
15
16/// A selected role keeps its incarnation even if another role later reuses its name or OID.
17#[derive(Debug, Serialize, Deserialize)]
18pub struct RoleBinding {
19    pub name: String,
20    pub oid: u32,
21    pub object_id: [u8; 16],
22    #[serde(skip)]
23    memory: Option<uqa_core::memory::MemoryReservation>,
24}
25
26impl Clone for RoleBinding {
27    fn clone(&self) -> Self {
28        Self::new(self.name.clone(), self.oid, self.object_id)
29    }
30}
31impl PartialEq for RoleBinding {
32    fn eq(&self, other: &Self) -> bool {
33        self.name == other.name && self.oid == other.oid && self.object_id == other.object_id
34    }
35}
36impl Eq for RoleBinding {}
37
38/// Explicit SQL names are resolved against the current catalog; captured authority retains its incarnation.
39#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(untagged)]
41pub enum RoleReference {
42    Named(String),
43    Bound(Arc<RoleBinding>),
44}
45
46impl From<String> for RoleReference {
47    fn from(name: String) -> Self {
48        Self::Named(name)
49    }
50}
51
52impl From<&str> for RoleReference {
53    fn from(name: &str) -> Self {
54        Self::Named(name.into())
55    }
56}
57
58impl RoleReference {
59    pub fn from_identity_with_control(
60        identity: RoleIdentity,
61        roles: &BTreeMap<String, RoleDefinition>,
62        control: &ProductionControl<'_>,
63    ) -> Result<Self, SQLError> {
64        let role = identity
65            .role_definition_with_control(roles, control)?
66            .ok_or_else(|| {
67                SQLError::Internal(
68                    "role identity references a missing or replaced incarnation".into(),
69                )
70            })?;
71        Self::from_definition_with_control(role, control)
72    }
73
74    pub(crate) fn from_definition_with_control(
75        role: &RoleDefinition,
76        control: &ProductionControl<'_>,
77    ) -> Result<Self, SQLError> {
78        control.check()?;
79        let oid = RoleBinding::validated_oid(role)?;
80        let header = control.reserve(std::mem::size_of::<RoleBinding>())?;
81        let (name, memory) = control.copy_text(&role.name)?.into_parts();
82        control.check()?;
83        Ok(Self::Bound(Arc::new(RoleBinding {
84            name,
85            oid,
86            object_id: role.object_id,
87            memory: control.combine(header, memory),
88        })))
89    }
90
91    pub fn clone_with_control(
92        &self,
93        control: &ProductionControl<'_>,
94    ) -> Result<uqa_core::memory::Produced<Self>, SQLError> {
95        control.check()?;
96        let (reference, memory) = match self {
97            Self::Named(name) => {
98                let (name, memory) = control.copy_text(name)?.into_parts();
99                (Self::Named(name), memory)
100            }
101            Self::Bound(role) => (Self::Bound(role.clone()), control.empty_reservation()),
102        };
103        Ok(control.finish(reference, memory)?)
104    }
105
106    pub fn from_identity(
107        identity: RoleIdentity,
108        roles: &BTreeMap<String, RoleDefinition>,
109    ) -> Result<Self, SQLError> {
110        let name = identity.role_name(roles).ok_or_else(|| {
111            SQLError::Internal("role identity references a missing or replaced incarnation".into())
112        })?;
113        Ok(Self::Bound(Arc::new(RoleBinding::from_definition(
114            &roles[name],
115        )?)))
116    }
117
118    pub fn require_name<'a>(
119        &'a self,
120        roles: &'a BTreeMap<String, RoleDefinition>,
121    ) -> Result<&'a str, SQLError> {
122        match self {
123            Self::Named(name) => {
124                super::require_role_exists(roles, name)?;
125                Ok(name)
126            }
127            Self::Bound(role) => role.require_name(roles),
128        }
129    }
130
131    pub fn catalog_name(
132        &self,
133        roles: &BTreeMap<String, RoleDefinition>,
134    ) -> Result<String, SQLError> {
135        match self {
136            Self::Named(name) => Ok(name.clone()),
137            Self::Bound(role) => role.require_name(roles).map(str::to_owned),
138        }
139    }
140
141    pub fn bind(&self, roles: &BTreeMap<String, RoleDefinition>) -> Result<RoleBinding, SQLError> {
142        let name = self.require_name(roles)?;
143        RoleBinding::from_definition(&roles[name])
144    }
145}
146
147impl RoleSubject for RoleReference {
148    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
149        match self {
150            Self::Named(name) => name.role_name(roles),
151            Self::Bound(role) => role.role_name(roles),
152        }
153    }
154
155    fn role_definition<'a>(
156        &self,
157        roles: &'a BTreeMap<String, RoleDefinition>,
158    ) -> Option<&'a RoleDefinition> {
159        match self {
160            Self::Named(name) => name.role_definition(roles),
161            Self::Bound(role) => role.role_definition(roles),
162        }
163    }
164
165    fn role_definition_with_control<'a>(
166        &self,
167        roles: &'a BTreeMap<String, RoleDefinition>,
168        control: &ProductionControl<'_>,
169    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
170        match self {
171            Self::Named(name) => name.role_definition_with_control(roles, control),
172            Self::Bound(role) => role.role_definition_with_control(roles, control),
173        }
174    }
175}
176
177impl RoleBinding {
178    pub fn new(name: String, oid: u32, object_id: [u8; 16]) -> Self {
179        Self {
180            name,
181            oid,
182            object_id,
183            memory: None,
184        }
185    }
186
187    pub fn reserved_bytes(&self) -> usize {
188        self.memory
189            .as_ref()
190            .map_or(0, uqa_core::memory::MemoryReservation::bytes)
191    }
192
193    pub fn identity(&self) -> RoleIdentity {
194        RoleIdentity {
195            oid: i64::from(self.oid),
196            object_id: self.object_id,
197        }
198    }
199
200    pub fn from_definition(role: &RoleDefinition) -> Result<Self, SQLError> {
201        let oid = Self::validated_oid(role)?;
202        Ok(Self::new(role.name.clone(), oid, role.object_id))
203    }
204
205    fn validated_oid(role: &RoleDefinition) -> Result<u32, SQLError> {
206        if role.oid <= 0 {
207            return Err(SQLError::Internal("invalid role OID".into()));
208        }
209        if role.object_id == [0; 16] {
210            return Err(SQLError::Internal("role has no object identity".into()));
211        }
212        u32::try_from(role.oid).map_err(|_| SQLError::Internal("invalid role OID".into()))
213    }
214
215    /// Retain the original incarnation through name changes before publishing a stored role reference.
216    pub fn revalidate(&self, roles: &BTreeMap<String, RoleDefinition>) -> Result<(), SQLError> {
217        if self.role_definition(roles).is_some() {
218            Ok(())
219        } else {
220            Err(SQLError::Routine {
221                sqlstate: "42704".into(),
222                message: format!("role {} was concurrently dropped", self.oid),
223            })
224        }
225    }
226
227    fn matches_definition(&self, role: &RoleDefinition) -> bool {
228        role.oid == i64::from(self.oid) && role.object_id == self.object_id
229    }
230
231    pub fn require_name<'a>(
232        &self,
233        roles: &'a BTreeMap<String, RoleDefinition>,
234    ) -> Result<&'a str, SQLError> {
235        self.role_definition(roles)
236            .map(|role| role.name.as_str())
237            .ok_or_else(|| SQLError::Routine {
238                sqlstate: "42704".into(),
239                message: format!("invalid role OID: {}", self.oid),
240            })
241    }
242}
243
244/// A named SQL argument and an already selected session role have different lookup semantics. An absent bound role contributes no inherited privileges; PUBLIC ACLs remain applicable.
245pub trait RoleSubject {
246    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str>;
247
248    fn role_definition<'a>(
249        &self,
250        roles: &'a BTreeMap<String, RoleDefinition>,
251    ) -> Option<&'a RoleDefinition>;
252
253    /// Native captured identities poll while searching a renamed incarnation. External subjects retain their existing lookup semantics.
254    fn role_definition_with_control<'a>(
255        &self,
256        roles: &'a BTreeMap<String, RoleDefinition>,
257        control: &ProductionControl<'_>,
258    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
259        control.check()?;
260        let role = self.role_definition(roles);
261        control.check()?;
262        Ok(role)
263    }
264}
265
266impl<T: RoleSubject + ?Sized> RoleSubject for Arc<T> {
267    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
268        self.as_ref().role_name(roles)
269    }
270    fn role_definition<'a>(
271        &self,
272        roles: &'a BTreeMap<String, RoleDefinition>,
273    ) -> Option<&'a RoleDefinition> {
274        self.as_ref().role_definition(roles)
275    }
276
277    fn role_definition_with_control<'a>(
278        &self,
279        roles: &'a BTreeMap<String, RoleDefinition>,
280        control: &ProductionControl<'_>,
281    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
282        self.as_ref().role_definition_with_control(roles, control)
283    }
284}
285
286impl<T: RoleSubject + ?Sized> RoleSubject for &T {
287    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
288        (*self).role_name(roles)
289    }
290
291    fn role_definition<'a>(
292        &self,
293        roles: &'a BTreeMap<String, RoleDefinition>,
294    ) -> Option<&'a RoleDefinition> {
295        (*self).role_definition(roles)
296    }
297
298    fn role_definition_with_control<'a>(
299        &self,
300        roles: &'a BTreeMap<String, RoleDefinition>,
301        control: &ProductionControl<'_>,
302    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
303        (*self).role_definition_with_control(roles, control)
304    }
305}
306
307impl RoleSubject for str {
308    fn role_name<'a>(&'a self, _roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
309        Some(self)
310    }
311
312    fn role_definition<'a>(
313        &self,
314        roles: &'a BTreeMap<String, RoleDefinition>,
315    ) -> Option<&'a RoleDefinition> {
316        roles.get(self)
317    }
318}
319
320impl RoleSubject for String {
321    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
322        self.as_str().role_name(roles)
323    }
324
325    fn role_definition<'a>(
326        &self,
327        roles: &'a BTreeMap<String, RoleDefinition>,
328    ) -> Option<&'a RoleDefinition> {
329        self.as_str().role_definition(roles)
330    }
331}
332
333impl RoleSubject for uqa_core::catalog_acl::AclGrantee {
334    fn role_name<'a>(&'a self, _roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
335        self.role_name()
336    }
337
338    fn role_definition<'a>(
339        &self,
340        roles: &'a BTreeMap<String, RoleDefinition>,
341    ) -> Option<&'a RoleDefinition> {
342        self.role_name().and_then(|name| roles.get(name))
343    }
344}
345
346impl RoleSubject for RoleBinding {
347    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
348        self.role_definition(roles).map(|role| role.name.as_str())
349    }
350
351    fn role_definition<'a>(
352        &self,
353        roles: &'a BTreeMap<String, RoleDefinition>,
354    ) -> Option<&'a RoleDefinition> {
355        roles
356            .get(&self.name)
357            .filter(|role| self.matches_definition(role))
358            .or_else(|| roles.values().find(|role| self.matches_definition(role)))
359    }
360
361    fn role_definition_with_control<'a>(
362        &self,
363        roles: &'a BTreeMap<String, RoleDefinition>,
364        control: &ProductionControl<'_>,
365    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
366        control.check()?;
367        if let Some(role) = roles
368            .get(&self.name)
369            .filter(|role| self.matches_definition(role))
370        {
371            return Ok(Some(role));
372        }
373        for role in roles.values() {
374            control.check()?;
375            if self.matches_definition(role) {
376                return Ok(Some(role));
377            }
378        }
379        Ok(None)
380    }
381}
382
383impl RoleSubject for RoleIdentity {
384    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
385        self.role_definition(roles).map(|role| role.name.as_str())
386    }
387
388    fn role_definition<'a>(
389        &self,
390        roles: &'a BTreeMap<String, RoleDefinition>,
391    ) -> Option<&'a RoleDefinition> {
392        if !self.is_valid() {
393            return None;
394        }
395        roles.values().find(|role| role.identity() == *self)
396    }
397
398    fn role_definition_with_control<'a>(
399        &self,
400        roles: &'a BTreeMap<String, RoleDefinition>,
401        control: &ProductionControl<'_>,
402    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
403        control.check()?;
404        if !self.is_valid() {
405            return Ok(None);
406        }
407        for role in roles.values() {
408            control.check()?;
409            if role.identity() == *self {
410                return Ok(Some(role));
411            }
412        }
413        Ok(None)
414    }
415}
416
417#[cfg(test)]
418mod tests;