1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//! `DatabaseHandle`: a lightweight caller-specific object referencing one
//! `DatabaseCore` (spec §10.1, S1A-001).
//!
//! Handles are issued by [`crate::manager::DatabaseManager::open_shared`].
//! Every handle carries its own [`HandleIdentity`] and [`HandleAccess`], while
//! recovery, WAL opening, open-generation advancement, and table mounting all
//! happened exactly once on the shared core. Dropping one handle never closes
//! storage; the core closes when the last reference drops or when
//! [`DatabaseHandle::shutdown`] drains it (S1A-004).
//!
//! Handles expose only principal-aware operations. They never dereference to
//! the raw [`Database`] facade or return mutable table handles.
use std::sync::Arc;
use std::time::Duration;
use crate::core::{LifecycleState, OperationGuard};
use crate::database::Database;
use crate::error::{MongrelError, Result};
/// A password that zeroizes its allocation and never reveals itself through
/// `Debug` output.
pub struct SecretString(zeroize::Zeroizing<String>);
impl SecretString {
pub fn new(secret: impl Into<String>) -> Self {
Self(zeroize::Zeroizing::new(secret.into()))
}
pub(crate) fn expose(&self) -> &str {
self.0.as_str()
}
}
impl std::fmt::Debug for SecretString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("SecretString([REDACTED])")
}
}
/// The per-caller identity bound to one handle (spec §10.1, S1A-001).
///
/// Catalog identities pin one user generation and are re-resolved against the
/// live catalog on each authorized operation. Service identities carry only
/// their explicitly granted scopes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HandleIdentity {
/// No credentials were supplied for this handle.
Credentialless,
/// A user resolved from the database catalog. `user_id` +
/// `created_version` pin the exact catalog generation so username reuse
/// cannot revive a stale identity.
CatalogUser {
username: String,
user_id: u64,
created_version: u64,
},
/// A non-catalog principal (service account, daemon worker, test actor).
ServicePrincipal { principal_id: [u8; 16] },
}
/// The identity requested when attaching a shared handle (spec §2.2).
///
/// Catalog credentials are verified against the live shared catalog before a
/// handle is issued. The password allocation is zeroized when attach returns.
#[derive(Debug)]
pub enum OpenIdentity {
/// Attach without credentials. Rejected (fail closed) when the database
/// catalog has `require_auth` enabled.
Credentialless,
/// Attach as a non-catalog service principal.
ServicePrincipal { principal_id: [u8; 16] },
/// Attach as a service principal restricted to these exact permissions.
ScopedServicePrincipal {
principal_id: [u8; 16],
permissions: Vec<crate::auth::Permission>,
},
/// Authenticate one catalog user on the existing shared core.
CatalogCredentials {
username: String,
password: SecretString,
},
}
/// Per-handle access restriction (spec §2.2: "each handle may have its own
/// principal and read-only restriction").
///
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct HandleAccess {
read_only: bool,
}
impl HandleAccess {
/// A read-write handle (the Stage 1A default).
pub fn read_write() -> Self {
Self { read_only: false }
}
/// A read-only handle.
pub fn read_only() -> Self {
Self { read_only: true }
}
/// Whether this handle is restricted to reads.
pub fn is_read_only(&self) -> bool {
self.read_only
}
}
/// A lightweight caller-specific handle onto one shared [`DatabaseCore`]
/// (spec §10.1, S1A-001).
///
/// Obtained from [`crate::manager::DatabaseManager::open_shared`]. Cloning or
/// dropping a handle has no storage side effects; storage closes when the
/// last core reference drops or [`Self::shutdown`] runs.
pub struct DatabaseHandle {
/// The facade carrying this handle's live authorization context.
database: Database,
identity: HandleIdentity,
access: HandleAccess,
service_permissions: Option<Vec<crate::auth::Permission>>,
}
impl DatabaseHandle {
pub(crate) fn new(
database: Database,
identity: HandleIdentity,
access: HandleAccess,
service_permissions: Option<Vec<crate::auth::Permission>>,
) -> Self {
Self {
database,
identity,
access,
service_permissions,
}
}
/// The identity bound to this handle.
pub fn identity(&self) -> &HandleIdentity {
&self.identity
}
/// The access restriction bound to this handle.
pub fn access(&self) -> HandleAccess {
self.access
}
/// Whether two handles reference the exact same process-local core.
pub fn shares_core_with(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.database.core(), &other.database.core())
}
/// The current lifecycle state of the shared core (S1A-004).
pub fn lifecycle_state(&self) -> LifecycleState {
self.database.lifecycle_state()
}
/// Admit one operation against the shared core (S1A-004). The RAII guard
/// releases the operation slot on drop; new operations are rejected once
/// the core leaves [`LifecycleState::Open`].
pub fn operation_guard(&self) -> Result<OperationGuard> {
self.database.operation_guard()
}
fn authorize_write(&self, operation: &'static str) -> Result<()> {
if self.access.is_read_only() {
Err(MongrelError::ReadOnlyHandle { operation })
} else {
Ok(())
}
}
fn authorize_permission(&self, permission: &crate::auth::Permission) -> Result<()> {
if let Some(permissions) = &self.service_permissions {
if !permissions
.iter()
.any(|granted| granted.satisfies(permission))
{
return Err(MongrelError::PermissionDenied {
required: permission.clone(),
principal: match &self.identity {
HandleIdentity::ServicePrincipal { principal_id } => {
format!("service:{principal_id:02x?}")
}
_ => "service".into(),
},
});
}
}
self.database.require(permission)
}
/// Execute an authorized native query with live roles, RLS, masks, and
/// column grants.
pub fn query(
&self,
table: &str,
query: &crate::query::Query,
projection: Option<&[u16]>,
) -> Result<Vec<crate::memtable::Row>> {
self.database
.query_for_current_principal(table, query, projection)
}
/// Count rows visible to this handle after live authorization and RLS.
pub fn count(&self, table: &str) -> Result<u64> {
self.database
.count_for(table, self.database.principal().as_ref())
}
/// Return all rows visible to this handle after RLS and masks.
pub fn rows(&self, table: &str) -> Result<Vec<crate::memtable::Row>> {
self.database
.rows_for(table, self.database.principal().as_ref())
}
/// Create a table through this handle's live principal.
pub fn create_table(&self, name: &str, schema: crate::schema::Schema) -> Result<u64> {
self.authorize_write("create table")?;
self.authorize_permission(&crate::auth::Permission::Ddl)?;
self.database.create_table(name, schema)
}
/// Atomically insert one row through this handle's live principal.
pub fn put(
&self,
table: &str,
cells: Vec<(u16, crate::memtable::Value)>,
) -> Result<Option<i64>> {
self.authorize_write("put")?;
self.database
.transaction_for_current_principal(|transaction| transaction.put(table, cells))
}
/// Atomically delete one row through this handle's live principal.
pub fn delete(&self, table: &str, row_id: crate::RowId) -> Result<()> {
self.authorize_write("delete")?;
self.database
.transaction_for_current_principal(|transaction| transaction.delete(table, row_id))
}
/// Create a catalog user. Admin only.
pub fn create_user(&self, username: &str, password: &str) -> Result<crate::auth::UserEntry> {
self.authorize_write("create user")?;
self.authorize_permission(&crate::auth::Permission::Admin)?;
self.database.create_user(username, password)
}
/// Drop a catalog user. Admin only.
pub fn drop_user(&self, username: &str) -> Result<()> {
self.authorize_write("drop user")?;
self.authorize_permission(&crate::auth::Permission::Admin)?;
self.database.drop_user(username)
}
/// Create a role. Admin only.
pub fn create_role(&self, role: &str) -> Result<crate::auth::RoleEntry> {
self.authorize_write("create role")?;
self.authorize_permission(&crate::auth::Permission::Admin)?;
self.database.create_role(role)
}
/// Grant a role to a catalog user. Admin only.
pub fn grant_role(&self, username: &str, role: &str) -> Result<()> {
self.authorize_write("grant role")?;
self.authorize_permission(&crate::auth::Permission::Admin)?;
self.database.grant_role(username, role)
}
/// Revoke a role from a catalog user. Admin only.
pub fn revoke_role(&self, username: &str, role: &str) -> Result<()> {
self.authorize_write("revoke role")?;
self.authorize_permission(&crate::auth::Permission::Admin)?;
self.database.revoke_role(username, role)
}
/// Grant one permission to a role. Admin only.
pub fn grant_permission(&self, role: &str, permission: crate::auth::Permission) -> Result<()> {
self.authorize_write("grant permission")?;
self.authorize_permission(&crate::auth::Permission::Admin)?;
self.database.grant_permission(role, permission)
}
/// Revoke one permission from a role. Admin only.
pub fn revoke_permission(&self, role: &str, permission: crate::auth::Permission) -> Result<()> {
self.authorize_write("revoke permission")?;
self.authorize_permission(&crate::auth::Permission::Admin)?;
self.database.revoke_permission(role, permission)
}
/// Shut the shared core down (spec §10.1, S1A-004): drain in-flight
/// operations within `drain_deadline`, sync durable state, release the
/// file lock, and mark the core `Closed`. Every handle — including this
/// one — then rejects further operations. Dropping a handle never closes
/// storage; only this method or the last core drop does.
pub fn shutdown(&self, drain_deadline: Duration) -> Result<()> {
self.authorize_write("shutdown")?;
self.authorize_permission(&crate::auth::Permission::Admin)?;
self.database.core().shutdown(drain_deadline)
}
}
impl std::fmt::Debug for DatabaseHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DatabaseHandle")
.field("identity", &self.identity)
.field("access", &self.access)
.field("database", &self.database)
.finish()
}
}