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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//! User, role, and credential management for MongrelDB's catalog-level auth.
//!
//! Users and roles are stored in the engine's `Catalog` struct (alongside
//! procedures and triggers), persisted via `catalog::write_atomic`. This
//! module provides the types and the Argon2id password hashing layer.
//!
//! The daemon (`mongreldb-server`) authenticates HTTP requests via HTTP Basic
//! auth (username:password) when `--auth-users` is enabled. Each authenticated
//! request carries a [`Principal`] in its extensions; permission checks use
//! [`Database::check_permission`].
use serde::{Deserialize, Serialize};
/// A stored user with Argon2id-hashed credentials.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserEntry {
/// Stable, monotonic user id.
pub id: u64,
/// Unique username (case-sensitive).
pub username: String,
/// Argon2id PHC string (includes salt + params; verifiable via
/// `PasswordVerifier::verify`).
#[serde(skip_serializing_if = "String::is_empty", default)]
pub password_hash: String,
/// Role names granted to this user.
#[serde(default)]
pub roles: Vec<String>,
/// Bypasses all permission checks (full admin).
#[serde(default)]
pub is_admin: bool,
/// Epoch at which the user was created.
pub created_epoch: u64,
}
/// A named collection of permissions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoleEntry {
/// Unique role name (case-sensitive).
pub name: String,
/// Permissions granted to this role.
#[serde(default)]
pub permissions: Vec<Permission>,
/// Epoch at which the role was created.
pub created_epoch: u64,
}
/// A permission granted to a role. Mirrors SQL `GRANT` / `REVOKE`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Permission {
/// All permissions on all tables (`GRANT ALL`).
All,
/// `SELECT` on a specific table.
Select { table: String },
/// `INSERT` on a specific table.
Insert { table: String },
/// `UPDATE` on a specific table.
Update { table: String },
/// `DELETE` on a specific table.
Delete { table: String },
/// `SELECT` limited to named columns.
SelectColumns { table: String, columns: Vec<String> },
/// `INSERT` limited to named columns.
InsertColumns { table: String, columns: Vec<String> },
/// `UPDATE` limited to named columns.
UpdateColumns { table: String, columns: Vec<String> },
/// DDL: `CREATE` / `DROP` / `ALTER TABLE`.
Ddl,
/// Admin: `CREATE USER` / `GRANT` / `REVOKE` / `CREATE ROLE`.
Admin,
}
impl Permission {
/// Check whether this permission satisfies a required permission.
///
/// `All` satisfies every non-admin permission (DDL + all table-level
/// operations) but does **not** satisfy `Admin` — user/role management
/// is gated behind `is_admin = true` on the principal, not grantable via
/// `Permission::All` (spec §9 decision 2). `Select { table: "*" }` is
/// not wildcarded (it matches a table literally named `*`).
pub fn satisfies(&self, required: &Permission) -> bool {
match (self, required) {
// All grants every non-admin permission.
(Permission::All, Permission::Admin) => false,
(Permission::All, _) => true,
(Permission::Admin, Permission::Admin) => true,
(Permission::Ddl, Permission::Ddl) => true,
(Permission::Select { table: a }, Permission::Select { table: b }) => a == b,
(Permission::Insert { table: a }, Permission::Insert { table: b }) => a == b,
(Permission::Update { table: a }, Permission::Update { table: b }) => a == b,
(Permission::Delete { table: a }, Permission::Delete { table: b }) => a == b,
(
Permission::SelectColumns {
table: a,
columns: granted,
},
Permission::SelectColumns {
table: b,
columns: required,
},
)
| (
Permission::InsertColumns {
table: a,
columns: granted,
},
Permission::InsertColumns {
table: b,
columns: required,
},
)
| (
Permission::UpdateColumns {
table: a,
columns: granted,
},
Permission::UpdateColumns {
table: b,
columns: required,
},
) => a == b && required.iter().all(|column| granted.contains(column)),
_ => false,
}
}
}
impl std::fmt::Display for Permission {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Permission::All => write!(f, "ALL"),
Permission::Admin => write!(f, "ADMIN"),
Permission::Ddl => write!(f, "DDL"),
Permission::Select { table } => write!(f, "SELECT ON {table}"),
Permission::Insert { table } => write!(f, "INSERT ON {table}"),
Permission::Update { table } => write!(f, "UPDATE ON {table}"),
Permission::Delete { table } => write!(f, "DELETE ON {table}"),
Permission::SelectColumns { table, columns } => {
write!(f, "SELECT ({}) ON {table}", columns.join(", "))
}
Permission::InsertColumns { table, columns } => {
write!(f, "INSERT ({}) ON {table}", columns.join(", "))
}
Permission::UpdateColumns { table, columns } => {
write!(f, "UPDATE ({}) ON {table}", columns.join(", "))
}
}
}
}
/// The authenticated identity for a single HTTP request. Injected by the
/// auth middleware into request extensions.
#[derive(Debug, Clone)]
pub struct Principal {
pub username: String,
pub is_admin: bool,
pub roles: Vec<String>,
/// All permissions from all roles the user belongs to, pre-resolved.
pub permissions: Vec<Permission>,
}
impl Principal {
/// Check whether this principal has the required permission.
pub fn has_permission(&self, required: &Permission) -> bool {
if self.is_admin {
return true;
}
self.permissions.iter().any(|p| p.satisfies(required))
}
pub fn column_access(&self, table: &str, operation: ColumnOperation) -> ColumnAccess {
if self.is_admin
|| self
.permissions
.iter()
.any(|permission| matches!(permission, Permission::All))
{
return ColumnAccess::All;
}
let full = self
.permissions
.iter()
.any(|permission| match (operation, permission) {
(ColumnOperation::Select, Permission::Select { table: granted })
| (ColumnOperation::Insert, Permission::Insert { table: granted })
| (ColumnOperation::Update, Permission::Update { table: granted }) => {
granted == table
}
_ => false,
});
if full {
return ColumnAccess::All;
}
let mut columns = Vec::new();
for permission in &self.permissions {
let grant = match (operation, permission) {
(
ColumnOperation::Select,
Permission::SelectColumns {
table: granted,
columns,
},
)
| (
ColumnOperation::Insert,
Permission::InsertColumns {
table: granted,
columns,
},
)
| (
ColumnOperation::Update,
Permission::UpdateColumns {
table: granted,
columns,
},
) if granted == table => Some(columns),
_ => None,
};
if let Some(grant) = grant {
for column in grant {
if !columns.contains(column) {
columns.push(column.clone());
}
}
}
}
if columns.is_empty() {
ColumnAccess::Denied
} else {
ColumnAccess::Columns(columns)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColumnOperation {
Select,
Insert,
Update,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColumnAccess {
All,
Columns(Vec<String>),
Denied,
}
// ── Password hashing (Argon2id) ──────────────────────────────────────────
/// Hash a password using Argon2id with a fresh random salt.
///
/// Returns a PHC string that encodes the algorithm, version, parameters, salt,
/// and hash — suitable for storage as `UserEntry::password_hash` and verifiable
/// via [`verify_password`].
pub fn hash_password(password: &str) -> Result<String, String> {
use argon2::{
password_hash::{PasswordHasher, SaltString},
Algorithm, Argon2, Version,
};
use getrandom::getrandom;
// Reuse the same OWASP-minimum parameters as the encryption KEK derivation.
let params = argon2::Params::new(19 * 1024, 2, 1, None).map_err(|e| e.to_string())?;
let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
// Generate salt via getrandom (always available in core, no feature gate).
let mut salt_bytes = [0u8; 32];
getrandom(&mut salt_bytes).map_err(|e| e.to_string())?;
let salt = SaltString::encode_b64(&salt_bytes).map_err(|e| e.to_string())?;
let hash = argon2
.hash_password(password.as_bytes(), &salt)
.map_err(|e| e.to_string())?;
Ok(hash.to_string())
}
/// Verify a password against a stored PHC hash. Returns `Ok(true)` on match,
/// `Ok(false)` on mismatch, `Err` on malformed hash.
pub fn verify_password(password: &str, phc_hash: &str) -> Result<bool, String> {
use argon2::{password_hash::PasswordVerifier, Argon2};
let parsed_hash =
argon2::PasswordHash::new(phc_hash).map_err(|e| format!("malformed hash: {e}"))?;
Ok(Argon2::default()
.verify_password(password.as_bytes(), &parsed_hash)
.is_ok())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn password_hash_round_trip() {
let password = "correct horse battery staple";
let hash = hash_password(password).unwrap();
assert!(verify_password(password, &hash).unwrap());
assert!(!verify_password("wrong password", &hash).unwrap());
}
#[test]
fn permission_satisfies() {
// All satisfies DDL and table-level permissions...
assert!(Permission::All.satisfies(&Permission::Ddl));
assert!(Permission::All.satisfies(&Permission::Select { table: "t".into() }));
assert!(Permission::All.satisfies(&Permission::Insert { table: "t".into() }));
// ...but NOT Admin (spec §9 decision 2 — only is_admin grants admin).
assert!(!Permission::All.satisfies(&Permission::Admin));
// Exact table match.
assert!(Permission::Select { table: "t".into() }
.satisfies(&Permission::Select { table: "t".into() }));
assert!(
!Permission::Select { table: "t".into() }.satisfies(&Permission::Select {
table: "other".into()
})
);
// Cross-kind never satisfies.
assert!(!Permission::Select { table: "t".into() }
.satisfies(&Permission::Insert { table: "t".into() }));
// Ddl does not satisfy Admin either.
assert!(!Permission::Ddl.satisfies(&Permission::Admin));
}
#[test]
fn principal_admin_bypasses_checks() {
let principal = Principal {
username: "admin".into(),
is_admin: true,
roles: vec![],
permissions: vec![],
};
assert!(principal.has_permission(&Permission::Admin));
assert!(principal.has_permission(&Permission::Select {
table: "anything".into()
}));
}
}