Skip to main content

pb_mapper_auth/
ids.rs

1//! Identity types for temporary credentials.
2//!
3//! ```text
4//!  KeyId (u64) — what a client presents
5//! ┌──────────────────────────┬──────────────────────────┐
6//! │ Generation (high 32)     │ SlotIndex (low 32)       │
7//! └──────────────────────────┴──────────────────────────┘
8//!      which tenant of the row       which row of the table
9//! ```
10//!
11//! These were all bare integers, which made `make_key_id(generation, slot)`
12//! accept its arguments in either order and let a slot index be compared against
13//! a generation without complaint. Separate types make both a compile error, and
14//! keep a `KeyId` from being used as an array index by mistake — the only way to
15//! get one is [`KeyId::slot`], which is also the only place the truncation to a
16//! row number is expressed.
17//!
18//! All three are `#[serde(transparent)]`, so persisted snapshots and the admin
19//! wire protocol keep the plain-integer encoding they already had.
20//!
21//! # Namespaces
22//!
23//! A namespace is a bare `u64`, because the wire and the routing keys already
24//! treat it as one. Two kinds share that space without being able to meet:
25//!
26//! ```text
27//!  a key's own      generation >= 1 | slot      named by the key that owns it
28//!  allocated        generation 0    | counter   shared by every key issued into it
29//!  administrator    0
30//! ```
31//!
32//! [`Generation::next`] is the only source of a key's generation and starts at 1,
33//! so no key id can ever have the bit pattern of an allocated namespace.
34
35use std::fmt;
36
37use serde::{Deserialize, Serialize};
38
39/// The identity a client presents: a [`SlotIndex`] paired with the
40/// [`Generation`] of the row it was issued from.
41#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
42#[serde(transparent)]
43pub struct KeyId(u64);
44
45/// Which tenant of a slot a credential belongs to. Bumped every time the row is
46/// reissued, and never reset, so a retired credential can never match the row
47/// that replaced it.
48#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
49#[serde(transparent)]
50pub struct Generation(u32);
51
52/// Which row of the slot table a credential lives in.
53#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
54#[serde(transparent)]
55pub struct SlotIndex(u32);
56
57/// The administrator, which owns no slot and never expires.
58pub const ADMIN_KEY_ID: KeyId = KeyId(0);
59
60/// The last namespace the allocator can hand out: the top of generation 0, which
61/// no key id uses. See the module docs.
62pub const MAX_ALLOCATED_NAMESPACE: u64 = u32::MAX as u64;
63
64const _: () = assert!(
65    MAX_ALLOCATED_NAMESPACE < 1 << 32,
66    "allocated namespaces stay in generation 0, which no key id uses"
67);
68
69impl KeyId {
70    pub const fn new(generation: Generation, slot: SlotIndex) -> Self {
71        Self(((generation.0 as u64) << 32) | slot.0 as u64)
72    }
73
74    pub const fn generation(self) -> Generation {
75        Generation((self.0 >> 32) as u32)
76    }
77
78    pub const fn slot(self) -> SlotIndex {
79        SlotIndex(self.0 as u32)
80    }
81
82    pub const fn is_admin(self) -> bool {
83        self.0 == ADMIN_KEY_ID.0
84    }
85
86    /// The bytes mixed into the credential's key derivation.
87    pub const fn to_be_bytes(self) -> [u8; 8] {
88        self.0.to_be_bytes()
89    }
90
91    pub const fn as_u64(self) -> u64 {
92        self.0
93    }
94
95    pub const fn from_u64(raw: u64) -> Self {
96        Self(raw)
97    }
98
99    /// The namespace a key with this id lives in: the one it was issued into, or
100    /// else the one its own id names.
101    pub const fn namespace(self, issued_into: Option<u64>) -> u64 {
102        match issued_into {
103            Some(namespace) => namespace,
104            None => self.0,
105        }
106    }
107}
108
109impl Generation {
110    pub const FIRST: Self = Self(0);
111
112    /// The generation for a reissue of this row, or `None` once the row has been
113    /// cycled `u32::MAX` times and can no longer produce a fresh identity.
114    pub fn next(self) -> Option<Self> {
115        self.0.checked_add(1).map(Self)
116    }
117
118    pub const fn as_u32(self) -> u32 {
119        self.0
120    }
121
122    pub const fn from_u32(raw: u32) -> Self {
123        Self(raw)
124    }
125}
126
127impl SlotIndex {
128    pub const fn as_index(self) -> usize {
129        self.0 as usize
130    }
131
132    /// # Panics
133    ///
134    /// If `index` exceeds `u32::MAX`. `MAX_TEMP_KEY_CAPACITY` caps the table far
135    /// below that, so a real index cannot reach it; panicking keeps a future
136    /// capacity change from silently wrapping into another row's identity.
137    pub fn from_index(index: usize) -> Self {
138        match u32::try_from(index) {
139            Ok(index) => Self(index),
140            Err(_) => panic!("slot index exceeds the addressable slot table"),
141        }
142    }
143}
144
145impl fmt::Display for KeyId {
146    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
147        self.0.fmt(formatter)
148    }
149}
150
151impl fmt::Display for Generation {
152    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
153        self.0.fmt(formatter)
154    }
155}
156
157impl fmt::Display for SlotIndex {
158    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
159        self.0.fmt(formatter)
160    }
161}