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
64impl KeyId {
65 pub const fn new(generation: Generation, slot: SlotIndex) -> Self {
66 Self(((generation.0 as u64) << 32) | slot.0 as u64)
67 }
68
69 pub const fn generation(self) -> Generation {
70 Generation((self.0 >> 32) as u32)
71 }
72
73 pub const fn slot(self) -> SlotIndex {
74 SlotIndex(self.0 as u32)
75 }
76
77 pub const fn is_admin(self) -> bool {
78 self.0 == ADMIN_KEY_ID.0
79 }
80
81 /// The bytes mixed into the credential's key derivation.
82 pub const fn to_be_bytes(self) -> [u8; 8] {
83 self.0.to_be_bytes()
84 }
85
86 pub const fn as_u64(self) -> u64 {
87 self.0
88 }
89
90 pub const fn from_u64(raw: u64) -> Self {
91 Self(raw)
92 }
93
94 /// The namespace a key with this id lives in: the one it was issued into, or
95 /// else the one its own id names.
96 pub const fn namespace(self, issued_into: Option<u64>) -> u64 {
97 match issued_into {
98 Some(namespace) => namespace,
99 None => self.0,
100 }
101 }
102}
103
104impl Generation {
105 pub const FIRST: Self = Self(0);
106
107 /// The generation for a reissue of this row, or `None` once the row has been
108 /// cycled `u32::MAX` times and can no longer produce a fresh identity.
109 pub fn next(self) -> Option<Self> {
110 self.0.checked_add(1).map(Self)
111 }
112
113 pub const fn as_u32(self) -> u32 {
114 self.0
115 }
116
117 pub const fn from_u32(raw: u32) -> Self {
118 Self(raw)
119 }
120}
121
122impl SlotIndex {
123 pub const fn as_index(self) -> usize {
124 self.0 as usize
125 }
126
127 /// # Panics
128 ///
129 /// If `index` exceeds `u32::MAX`. `MAX_TEMP_KEY_CAPACITY` caps the table far
130 /// below that, so a real index cannot reach it; panicking keeps a future
131 /// capacity change from silently wrapping into another row's identity.
132 pub fn from_index(index: usize) -> Self {
133 match u32::try_from(index) {
134 Ok(index) => Self(index),
135 Err(_) => panic!("slot index exceeds the addressable slot table"),
136 }
137 }
138}
139
140impl fmt::Display for KeyId {
141 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
142 self.0.fmt(formatter)
143 }
144}
145
146impl fmt::Display for Generation {
147 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
148 self.0.fmt(formatter)
149 }
150}
151
152impl fmt::Display for SlotIndex {
153 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
154 self.0.fmt(formatter)
155 }
156}