@feltdb/core 0.4.15 → 0.4.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +1 -1
- package/dist/create/package-versions.js +1 -1
- package/dist/create/server-source/crates/feltdb/Cargo.toml +1 -1
- package/dist/create/server-source/crates/feltdb/src/application.rs +93 -0
- package/dist/create/server-source/crates/feltdb/src/authorization_security_tests.rs +787 -0
- package/dist/create/server-source/crates/feltdb/src/lib.rs +139 -0
- package/dist/create/server-source/crates/feltdb/src/policy_evaluation.rs +1669 -0
- package/dist/create/server-source/crates/feltdb/src/state_contract.rs +1269 -15
- package/dist/create/server-source/crates/feltdb/tests/pr7_self_authorization_proof.rs +406 -0
- package/dist/create/server-source/crates/feltdb/tests/pr8_vocabulary_assessment.rs +908 -0
- package/dist/create/server-source/crates/feltdb/tests/pr9_phase2_boundary_tests.rs +1028 -0
- package/dist/create/server-source/crates/feltdb/tests/pr9_phase3a_path_a_tests.rs +332 -0
- package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_authorized_mutations.rs +342 -0
- package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_role_based_authorization.rs +313 -0
- package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_simple_auth_delete.rs +90 -0
- package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_team_delete_role_authorization.rs +571 -0
- package/dist/create/server-source/crates/feltdb/tests/pr9_teams_role_based_access.rs +506 -0
- package/dist/create/server-source/crates/feltdb/tests/saas_authorization_integration.rs +81 -0
- package/dist/create/server-source/crates/feltdb/tests/saas_invitation_lifecycle.rs +434 -0
- package/dist/create/server-source/crates/feltdb-server/src/main.rs +130 -23
- package/dist/create/server-source/crates/feltdb-wasm/src/lib.rs +2 -2
- package/dist/db.d.ts +10 -0
- package/dist/db.d.ts.map +1 -1
- package/dist/db.js +3 -1
- package/dist/file-db.d.ts +69 -0
- package/dist/file-db.d.ts.map +1 -0
- package/dist/file-db.js +355 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/studio-app/assets/{feltdb_wasm-CJEJryDx.js → feltdb_wasm-CBGD0zRu.js} +1 -1
- package/dist/studio-app/assets/feltdb_wasm_bg-C6ATF9mJ.wasm +0 -0
- package/dist/studio-app/assets/{index-D_p8T7nO.js → index-D74dfBgZ.js} +9 -9
- package/dist/studio-app/index.html +1 -1
- package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
- package/package.json +7 -2
- package/dist/studio-app/assets/feltdb_wasm_bg-BJxQXtoo.wasm +0 -0
|
@@ -0,0 +1,1669 @@
|
|
|
1
|
+
//! Runtime policy enforcement for FlowSpec policies.
|
|
2
|
+
//!
|
|
3
|
+
//! This module implements the runtime semantics for FlowSpec policy declarations,
|
|
4
|
+
//! allowing applications to declare authorization rules at the schema level and have
|
|
5
|
+
//! them enforced at the runtime boundary.
|
|
6
|
+
//!
|
|
7
|
+
//! FlowSpec policies declare authorization rules like:
|
|
8
|
+
//!
|
|
9
|
+
//! ```text
|
|
10
|
+
//! policy Project {
|
|
11
|
+
//! read: authenticated
|
|
12
|
+
//! write: owner
|
|
13
|
+
//! }
|
|
14
|
+
//! ```
|
|
15
|
+
//!
|
|
16
|
+
//! This module provides:
|
|
17
|
+
//! - Policy subject types (authenticated, owner, etc.)
|
|
18
|
+
//! - Authorization context with actor information
|
|
19
|
+
//! - Policy evaluation engine
|
|
20
|
+
//! - Stable authorization errors
|
|
21
|
+
|
|
22
|
+
use serde::{Deserialize, Serialize};
|
|
23
|
+
use serde_json::Value;
|
|
24
|
+
use std::collections::BTreeMap;
|
|
25
|
+
use std::sync::Arc;
|
|
26
|
+
|
|
27
|
+
/// An actor attempting to access a resource.
|
|
28
|
+
///
|
|
29
|
+
/// Represents the identity performing a request. The `id` is typically a user ID,
|
|
30
|
+
/// agent ID, or other stable identifier.
|
|
31
|
+
///
|
|
32
|
+
/// `None` represents an unauthenticated/anonymous actor.
|
|
33
|
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
34
|
+
pub struct Actor {
|
|
35
|
+
pub id: String,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
impl Actor {
|
|
39
|
+
pub fn new(id: impl Into<String>) -> Self {
|
|
40
|
+
Self { id: id.into() }
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// Authorization context for policy evaluation.
|
|
45
|
+
///
|
|
46
|
+
/// Contains the actor performing the operation and additional context needed
|
|
47
|
+
/// to evaluate policies.
|
|
48
|
+
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
49
|
+
pub struct PolicyContext {
|
|
50
|
+
/// The actor attempting the operation, or None if unauthenticated
|
|
51
|
+
pub actor: Option<Actor>,
|
|
52
|
+
|
|
53
|
+
/// The resource being accessed (collection name and record ID)
|
|
54
|
+
pub resource_collection: String,
|
|
55
|
+
pub resource_id: String,
|
|
56
|
+
|
|
57
|
+
/// Additional attributes that can be used in policy evaluation
|
|
58
|
+
/// For example: owner_id for owner policy checks
|
|
59
|
+
pub resource_attributes: BTreeMap<String, String>,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
impl PolicyContext {
|
|
63
|
+
pub fn new(
|
|
64
|
+
actor: Option<Actor>,
|
|
65
|
+
collection: impl Into<String>,
|
|
66
|
+
resource_id: impl Into<String>,
|
|
67
|
+
) -> Self {
|
|
68
|
+
Self {
|
|
69
|
+
actor,
|
|
70
|
+
resource_collection: collection.into(),
|
|
71
|
+
resource_id: resource_id.into(),
|
|
72
|
+
resource_attributes: BTreeMap::new(),
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
pub fn with_attributes(mut self, attrs: BTreeMap<String, String>) -> Self {
|
|
77
|
+
self.resource_attributes = attrs;
|
|
78
|
+
self
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
pub fn set_attribute(&mut self, key: impl Into<String>, value: impl Into<String>) {
|
|
82
|
+
self.resource_attributes.insert(key.into(), value.into());
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// Policy subject - the authorization rule that determines access.
|
|
87
|
+
///
|
|
88
|
+
/// Subjects represent different types of authorization checks that can be performed.
|
|
89
|
+
/// `authenticated`, `owner`, `member`, and `self` are supported.
|
|
90
|
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
91
|
+
#[serde(rename_all = "snake_case")]
|
|
92
|
+
pub enum PolicySubject {
|
|
93
|
+
/// Allows access when actor is authenticated (not None).
|
|
94
|
+
Authenticated,
|
|
95
|
+
|
|
96
|
+
/// Allows access when actor owns the resource.
|
|
97
|
+
/// The resource's owner is determined by the owner_id field in the record.
|
|
98
|
+
Owner,
|
|
99
|
+
|
|
100
|
+
/// Allows access when actor is a member of the organization that owns the resource.
|
|
101
|
+
/// The resource's organization is determined by the organization reference field.
|
|
102
|
+
/// Membership is verified by checking: membership.user_id == actor.id AND membership.organization_id == resource.organization_id
|
|
103
|
+
Member,
|
|
104
|
+
|
|
105
|
+
/// Allows access when the specified field value identifies the actor by stable ID.
|
|
106
|
+
/// The field value must equal actor.id. Typically used with reference fields.
|
|
107
|
+
/// If the field is missing or null, access is denied.
|
|
108
|
+
Self_ { field: String },
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
impl PolicySubject {
|
|
112
|
+
pub fn as_str(&self) -> &'static str {
|
|
113
|
+
match self {
|
|
114
|
+
PolicySubject::Authenticated => "authenticated",
|
|
115
|
+
PolicySubject::Owner => "owner",
|
|
116
|
+
PolicySubject::Member => "member",
|
|
117
|
+
PolicySubject::Self_ { .. } => "self",
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/// Parse a policy subject from a string.
|
|
122
|
+
/// For self policies, the field name must be included in format: "self(field_name)"
|
|
123
|
+
/// Returns None if the subject is not recognized.
|
|
124
|
+
pub fn from_str(s: &str) -> Option<Self> {
|
|
125
|
+
if let Some(field) = s.strip_prefix("self(").and_then(|s| s.strip_suffix(")")) {
|
|
126
|
+
return Some(PolicySubject::Self_ { field: field.to_string() });
|
|
127
|
+
}
|
|
128
|
+
match s {
|
|
129
|
+
"authenticated" => Some(PolicySubject::Authenticated),
|
|
130
|
+
"owner" => Some(PolicySubject::Owner),
|
|
131
|
+
"member" => Some(PolicySubject::Member),
|
|
132
|
+
_ => None,
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/// Authorization decision - the result of policy evaluation.
|
|
138
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
139
|
+
pub enum AuthorizationDecision {
|
|
140
|
+
/// Access is allowed
|
|
141
|
+
Allow,
|
|
142
|
+
/// Access is denied
|
|
143
|
+
Deny,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/// Error type for authorization failures.
|
|
147
|
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
148
|
+
pub struct PolicyAuthorizationError {
|
|
149
|
+
pub code: String,
|
|
150
|
+
pub message: String,
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
impl PolicyAuthorizationError {
|
|
154
|
+
pub fn new(code: &str, message: impl Into<String>) -> Self {
|
|
155
|
+
Self {
|
|
156
|
+
code: code.into(),
|
|
157
|
+
message: message.into(),
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
pub fn unauthenticated(reason: impl Into<String>) -> Self {
|
|
162
|
+
Self::new("UNAUTHENTICATED", reason)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
pub fn unauthorized(reason: impl Into<String>) -> Self {
|
|
166
|
+
Self::new("UNAUTHORIZED", reason)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
impl std::fmt::Display for PolicyAuthorizationError {
|
|
171
|
+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
172
|
+
write!(f, "{}: {}", self.code, self.message)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
impl std::error::Error for PolicyAuthorizationError {}
|
|
177
|
+
|
|
178
|
+
/// Immutable authorization state for policy evaluation.
|
|
179
|
+
///
|
|
180
|
+
/// Provides read-only access to the schema metadata and the immutable snapshot
|
|
181
|
+
/// required for record-level policy evaluation. Policies can access authoritative
|
|
182
|
+
/// database state without ability to mutate it.
|
|
183
|
+
///
|
|
184
|
+
/// The snapshot must correspond to the same snapshot boundary used to evaluate
|
|
185
|
+
/// the protected record, ensuring snapshot consistency during authorization.
|
|
186
|
+
#[derive(Debug, Clone)]
|
|
187
|
+
pub struct AuthorizationState {
|
|
188
|
+
/// Schema metadata including field definitions and references.
|
|
189
|
+
/// Used for discovering relationships between collections (e.g., Project → Organization).
|
|
190
|
+
pub schema: Arc<crate::state_contract::StateSchema>,
|
|
191
|
+
|
|
192
|
+
/// State namespace (e.g., "tenant:123") used to construct capability keys
|
|
193
|
+
/// when querying the snapshot.
|
|
194
|
+
pub state_namespace: String,
|
|
195
|
+
|
|
196
|
+
/// Immutable snapshot of persisted records at the authorization boundary.
|
|
197
|
+
/// Contains StoredRow entries with keys in format "capability:record_id".
|
|
198
|
+
/// Used by policies to verify relationships (e.g., membership, ownership).
|
|
199
|
+
///
|
|
200
|
+
/// This is the same snapshot used to load the protected record being authorized,
|
|
201
|
+
/// guaranteeing snapshot consistency for policy decisions.
|
|
202
|
+
pub snapshot_rows: Arc<Vec<crate::StoredRow>>,
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
impl AuthorizationState {
|
|
206
|
+
/// Create a new authorization state.
|
|
207
|
+
pub fn new(
|
|
208
|
+
schema: Arc<crate::state_contract::StateSchema>,
|
|
209
|
+
state_namespace: impl Into<String>,
|
|
210
|
+
snapshot_rows: Arc<Vec<crate::StoredRow>>,
|
|
211
|
+
) -> Self {
|
|
212
|
+
Self {
|
|
213
|
+
schema,
|
|
214
|
+
state_namespace: state_namespace.into(),
|
|
215
|
+
snapshot_rows,
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/// Lookup a record in the snapshot by collection and key.
|
|
220
|
+
/// Returns None if the record doesn't exist or is marked deleted.
|
|
221
|
+
pub fn lookup_record(&self, collection: &str, key: &str) -> Option<Value> {
|
|
222
|
+
let capability = format!("{}:{}", self.state_namespace, collection);
|
|
223
|
+
self.snapshot_rows
|
|
224
|
+
.iter()
|
|
225
|
+
.find(|row| {
|
|
226
|
+
row.capability == capability && row.key == key && !row.deleted
|
|
227
|
+
})
|
|
228
|
+
.map(|row| row.value.clone())
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/// Iterate over all records in a collection within the snapshot.
|
|
232
|
+
pub fn records_in_collection(&self, collection: &str) -> Vec<Value> {
|
|
233
|
+
let capability = format!("{}:{}", self.state_namespace, collection);
|
|
234
|
+
self.snapshot_rows
|
|
235
|
+
.iter()
|
|
236
|
+
.filter(|row| row.capability == capability && !row.deleted)
|
|
237
|
+
.map(|row| row.value.clone())
|
|
238
|
+
.collect()
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/// Find a field in a collection that references another collection.
|
|
242
|
+
/// Returns the field name if found.
|
|
243
|
+
pub fn find_reference_field(&self, from_collection: &str, to_collection: &str) -> Option<String> {
|
|
244
|
+
let collection = self.schema.collections
|
|
245
|
+
.iter()
|
|
246
|
+
.find(|c| c.name == from_collection)?;
|
|
247
|
+
|
|
248
|
+
collection.fields
|
|
249
|
+
.iter()
|
|
250
|
+
.find_map(|field| {
|
|
251
|
+
if let crate::state_contract::FieldType::Reference { collection: ref_col } = &field.field_type {
|
|
252
|
+
if ref_col == to_collection {
|
|
253
|
+
return Some(field.name.clone());
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
None
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/// Find which collection contains membership information (references both User and Organization).
|
|
261
|
+
/// Returns the collection name if found.
|
|
262
|
+
pub fn find_membership_collection(&self) -> Option<String> {
|
|
263
|
+
// Look for a collection that has references to both User and Organization
|
|
264
|
+
for collection in &self.schema.collections {
|
|
265
|
+
let has_user_ref = collection.fields.iter().any(|f| {
|
|
266
|
+
if let crate::state_contract::FieldType::Reference { collection: ref_col } = &f.field_type {
|
|
267
|
+
ref_col == "User" || ref_col == "Users"
|
|
268
|
+
} else {
|
|
269
|
+
false
|
|
270
|
+
}
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
let has_org_ref = collection.fields.iter().any(|f| {
|
|
274
|
+
if let crate::state_contract::FieldType::Reference { collection: ref_col } = &f.field_type {
|
|
275
|
+
ref_col == "Organization" || ref_col == "Organizations"
|
|
276
|
+
} else {
|
|
277
|
+
false
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
if has_user_ref && has_org_ref {
|
|
282
|
+
return Some(collection.name.clone());
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
None
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/// Find field names for user and organization references within a collection.
|
|
289
|
+
/// Returns (user_field, org_field) if both are found.
|
|
290
|
+
pub fn find_membership_fields(&self, collection_name: &str) -> Option<(String, String)> {
|
|
291
|
+
let collection = self.schema.collections
|
|
292
|
+
.iter()
|
|
293
|
+
.find(|c| c.name == collection_name)?;
|
|
294
|
+
|
|
295
|
+
let mut user_field = None;
|
|
296
|
+
let mut org_field = None;
|
|
297
|
+
|
|
298
|
+
for field in &collection.fields {
|
|
299
|
+
if let crate::state_contract::FieldType::Reference { collection: ref_col } = &field.field_type {
|
|
300
|
+
if (ref_col == "User" || ref_col == "Users") && user_field.is_none() {
|
|
301
|
+
user_field = Some(field.name.clone());
|
|
302
|
+
}
|
|
303
|
+
if (ref_col == "Organization" || ref_col == "Organizations") && org_field.is_none() {
|
|
304
|
+
org_field = Some(field.name.clone());
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
match (user_field, org_field) {
|
|
310
|
+
(Some(u), Some(o)) => Some((u, o)),
|
|
311
|
+
_ => None,
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/// Record authorization context for record-level policy evaluation.
|
|
317
|
+
///
|
|
318
|
+
/// Contains an actual persisted or proposed record and metadata needed to evaluate
|
|
319
|
+
/// policies that depend on individual record state (e.g., member, owner).
|
|
320
|
+
///
|
|
321
|
+
/// All record data is derived from FeltDB state, never from caller attributes.
|
|
322
|
+
#[derive(Debug, Clone)]
|
|
323
|
+
pub struct RecordAuthorizationContext {
|
|
324
|
+
/// The actor attempting the operation, or None if unauthenticated
|
|
325
|
+
pub actor: Option<Actor>,
|
|
326
|
+
/// The collection containing the record
|
|
327
|
+
pub collection: String,
|
|
328
|
+
/// The record ID
|
|
329
|
+
pub record_id: String,
|
|
330
|
+
/// The actual record data as persisted/proposed in FeltDB
|
|
331
|
+
/// This is authoritative for derived values (organization, ownership, etc.)
|
|
332
|
+
pub record_value: serde_json::Value,
|
|
333
|
+
/// Optional authorization state for policies that need to verify relationships.
|
|
334
|
+
/// Provides read-only access to schema metadata and the immutable snapshot.
|
|
335
|
+
/// None for policies that only check caller authentication or direct field values (authenticated, owner).
|
|
336
|
+
pub authorization_state: Option<AuthorizationState>,
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
impl RecordAuthorizationContext {
|
|
340
|
+
/// Create a new record authorization context.
|
|
341
|
+
///
|
|
342
|
+
/// Parameters:
|
|
343
|
+
/// - actor: The authenticated actor attempting the operation
|
|
344
|
+
/// - collection: The collection name
|
|
345
|
+
/// - record_id: The record's ID
|
|
346
|
+
/// - record_value: The actual record value from FeltDB
|
|
347
|
+
pub fn new(
|
|
348
|
+
actor: Option<Actor>,
|
|
349
|
+
collection: impl Into<String>,
|
|
350
|
+
record_id: impl Into<String>,
|
|
351
|
+
record_value: serde_json::Value,
|
|
352
|
+
) -> Self {
|
|
353
|
+
Self {
|
|
354
|
+
actor,
|
|
355
|
+
collection: collection.into(),
|
|
356
|
+
record_id: record_id.into(),
|
|
357
|
+
record_value,
|
|
358
|
+
authorization_state: None,
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/// Builder method to attach authorization state.
|
|
363
|
+
pub fn with_state(mut self, state: AuthorizationState) -> Self {
|
|
364
|
+
self.authorization_state = Some(state);
|
|
365
|
+
self
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/// Extract a field value from the record.
|
|
369
|
+
pub fn field(&self, name: &str) -> Option<&serde_json::Value> {
|
|
370
|
+
self.record_value.get(name)
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/// Policy evaluator - determines if a subject allows access.
|
|
375
|
+
pub struct PolicyEvaluator;
|
|
376
|
+
|
|
377
|
+
impl PolicyEvaluator {
|
|
378
|
+
/// Evaluate a single policy subject against a context.
|
|
379
|
+
///
|
|
380
|
+
/// Returns `Allow` if the policy subject permits access, `Deny` otherwise.
|
|
381
|
+
/// Note: Self policies are only supported at record level (evaluate_record).
|
|
382
|
+
pub fn evaluate(
|
|
383
|
+
subject: PolicySubject,
|
|
384
|
+
context: &PolicyContext,
|
|
385
|
+
) -> Result<AuthorizationDecision, PolicyAuthorizationError> {
|
|
386
|
+
match subject {
|
|
387
|
+
PolicySubject::Authenticated => Self::evaluate_authenticated(context),
|
|
388
|
+
PolicySubject::Owner => Self::evaluate_owner(context),
|
|
389
|
+
PolicySubject::Member => Self::evaluate_member(context),
|
|
390
|
+
PolicySubject::Self_ { .. } => {
|
|
391
|
+
Err(PolicyAuthorizationError::new(
|
|
392
|
+
"INVALID_POLICY_CONTEXT",
|
|
393
|
+
"self policies require record-level context; use evaluate_record instead",
|
|
394
|
+
))
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/// Evaluate a policy subject against a record-level authorization context.
|
|
400
|
+
///
|
|
401
|
+
/// This is used at query and mutation execution time to make per-record
|
|
402
|
+
/// authorization decisions based on the actual persisted record state.
|
|
403
|
+
///
|
|
404
|
+
/// Unlike evaluate(), which checks caller-supplied attributes, this method
|
|
405
|
+
/// derives all authorization facts from FeltDB state.
|
|
406
|
+
pub fn evaluate_record(
|
|
407
|
+
subject: PolicySubject,
|
|
408
|
+
context: &RecordAuthorizationContext,
|
|
409
|
+
) -> Result<AuthorizationDecision, PolicyAuthorizationError> {
|
|
410
|
+
match subject {
|
|
411
|
+
PolicySubject::Authenticated => Self::evaluate_record_authenticated(context),
|
|
412
|
+
PolicySubject::Owner => Self::evaluate_record_owner(context),
|
|
413
|
+
PolicySubject::Member => Self::evaluate_record_member(context),
|
|
414
|
+
PolicySubject::Self_ { field } => Self::evaluate_record_self(&field, context),
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/// Authenticated subject: allows access when actor is present.
|
|
419
|
+
fn evaluate_authenticated(
|
|
420
|
+
context: &PolicyContext,
|
|
421
|
+
) -> Result<AuthorizationDecision, PolicyAuthorizationError> {
|
|
422
|
+
if context.actor.is_some() {
|
|
423
|
+
Ok(AuthorizationDecision::Allow)
|
|
424
|
+
} else {
|
|
425
|
+
Err(PolicyAuthorizationError::unauthenticated(
|
|
426
|
+
"authenticated policy requires an authenticated actor",
|
|
427
|
+
))
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/// Owner subject: allows access when actor is the resource owner.
|
|
432
|
+
fn evaluate_owner(
|
|
433
|
+
context: &PolicyContext,
|
|
434
|
+
) -> Result<AuthorizationDecision, PolicyAuthorizationError> {
|
|
435
|
+
let actor = context.actor.as_ref().ok_or_else(|| {
|
|
436
|
+
PolicyAuthorizationError::unauthenticated(
|
|
437
|
+
"owner policy requires an authenticated actor",
|
|
438
|
+
)
|
|
439
|
+
})?;
|
|
440
|
+
|
|
441
|
+
let owner_id = context.resource_attributes.get("owner_id").ok_or_else(|| {
|
|
442
|
+
PolicyAuthorizationError::new(
|
|
443
|
+
"OWNERSHIP_NOT_DEFINED",
|
|
444
|
+
"resource does not have an owner_id attribute; ownership is not supported for this collection",
|
|
445
|
+
)
|
|
446
|
+
})?;
|
|
447
|
+
|
|
448
|
+
if actor.id == *owner_id {
|
|
449
|
+
Ok(AuthorizationDecision::Allow)
|
|
450
|
+
} else {
|
|
451
|
+
Err(PolicyAuthorizationError::unauthorized(
|
|
452
|
+
format!(
|
|
453
|
+
"actor {} is not the owner ({})",
|
|
454
|
+
actor.id, owner_id
|
|
455
|
+
),
|
|
456
|
+
))
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/// Member subject: allows access when actor is a member of the resource's organization.
|
|
461
|
+
fn evaluate_member(
|
|
462
|
+
context: &PolicyContext,
|
|
463
|
+
) -> Result<AuthorizationDecision, PolicyAuthorizationError> {
|
|
464
|
+
let actor = context.actor.as_ref().ok_or_else(|| {
|
|
465
|
+
PolicyAuthorizationError::unauthenticated(
|
|
466
|
+
"member policy requires an authenticated actor",
|
|
467
|
+
)
|
|
468
|
+
})?;
|
|
469
|
+
|
|
470
|
+
let organization_id = context.resource_attributes.get("organization_id").ok_or_else(|| {
|
|
471
|
+
PolicyAuthorizationError::new(
|
|
472
|
+
"ORGANIZATION_NOT_DEFINED",
|
|
473
|
+
"resource does not have an organization_id attribute; member policy cannot be evaluated",
|
|
474
|
+
)
|
|
475
|
+
})?;
|
|
476
|
+
|
|
477
|
+
let is_member = context.resource_attributes.get("is_member")
|
|
478
|
+
.map(|v| v == "true")
|
|
479
|
+
.unwrap_or(false);
|
|
480
|
+
|
|
481
|
+
if is_member {
|
|
482
|
+
Ok(AuthorizationDecision::Allow)
|
|
483
|
+
} else {
|
|
484
|
+
Err(PolicyAuthorizationError::unauthorized(
|
|
485
|
+
format!(
|
|
486
|
+
"actor {} is not a member of organization {}",
|
|
487
|
+
actor.id, organization_id
|
|
488
|
+
),
|
|
489
|
+
))
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// Record-level authorization evaluation methods
|
|
494
|
+
// These evaluate policies based on actual persisted record state,
|
|
495
|
+
// deriving all authorization facts from FeltDB, not from caller attributes.
|
|
496
|
+
|
|
497
|
+
/// Authenticated subject at record level: allows if actor is present.
|
|
498
|
+
fn evaluate_record_authenticated(
|
|
499
|
+
context: &RecordAuthorizationContext,
|
|
500
|
+
) -> Result<AuthorizationDecision, PolicyAuthorizationError> {
|
|
501
|
+
if context.actor.is_some() {
|
|
502
|
+
Ok(AuthorizationDecision::Allow)
|
|
503
|
+
} else {
|
|
504
|
+
Err(PolicyAuthorizationError::unauthenticated(
|
|
505
|
+
"authenticated policy requires an authenticated actor",
|
|
506
|
+
))
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/// Owner subject at record level: allows if actor owns the resource.
|
|
511
|
+
/// Ownership is determined by the owner_id field in the record.
|
|
512
|
+
fn evaluate_record_owner(
|
|
513
|
+
context: &RecordAuthorizationContext,
|
|
514
|
+
) -> Result<AuthorizationDecision, PolicyAuthorizationError> {
|
|
515
|
+
let actor = context.actor.as_ref().ok_or_else(|| {
|
|
516
|
+
PolicyAuthorizationError::unauthenticated(
|
|
517
|
+
"owner policy requires an authenticated actor",
|
|
518
|
+
)
|
|
519
|
+
})?;
|
|
520
|
+
|
|
521
|
+
let owner_id = context.field("owner_id")
|
|
522
|
+
.and_then(|v| v.as_str())
|
|
523
|
+
.ok_or_else(|| {
|
|
524
|
+
PolicyAuthorizationError::new(
|
|
525
|
+
"OWNERSHIP_NOT_DEFINED",
|
|
526
|
+
"record does not have an owner_id field; ownership is not supported for this collection",
|
|
527
|
+
)
|
|
528
|
+
})?;
|
|
529
|
+
|
|
530
|
+
if actor.id == owner_id {
|
|
531
|
+
Ok(AuthorizationDecision::Allow)
|
|
532
|
+
} else {
|
|
533
|
+
Err(PolicyAuthorizationError::unauthorized(
|
|
534
|
+
format!(
|
|
535
|
+
"actor {} is not the owner ({})",
|
|
536
|
+
actor.id, owner_id
|
|
537
|
+
),
|
|
538
|
+
))
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/// Member subject at record level: allows if actor is a member of the resource's organization.
|
|
543
|
+
/// Organization is determined by resolving the organization reference from the record.
|
|
544
|
+
/// Membership is verified by checking the Membership collection in the snapshot.
|
|
545
|
+
fn evaluate_record_member(
|
|
546
|
+
context: &RecordAuthorizationContext,
|
|
547
|
+
) -> Result<AuthorizationDecision, PolicyAuthorizationError> {
|
|
548
|
+
let actor = context.actor.as_ref().ok_or_else(|| {
|
|
549
|
+
PolicyAuthorizationError::unauthenticated(
|
|
550
|
+
"member policy requires an authenticated actor",
|
|
551
|
+
)
|
|
552
|
+
})?;
|
|
553
|
+
|
|
554
|
+
let auth_state = context.authorization_state.as_ref().ok_or_else(|| {
|
|
555
|
+
PolicyAuthorizationError::new(
|
|
556
|
+
"AUTHORIZATION_STATE_NOT_AVAILABLE",
|
|
557
|
+
"member policy requires access to database state (authorization_state not provided)",
|
|
558
|
+
)
|
|
559
|
+
})?;
|
|
560
|
+
|
|
561
|
+
// Find the reference field from this collection to Organization
|
|
562
|
+
let org_ref_field = auth_state.find_reference_field(&context.collection, "Organization")
|
|
563
|
+
.or_else(|| auth_state.find_reference_field(&context.collection, "Organizations"))
|
|
564
|
+
.ok_or_else(|| {
|
|
565
|
+
PolicyAuthorizationError::new(
|
|
566
|
+
"ORGANIZATION_NOT_DEFINED",
|
|
567
|
+
"resource collection does not have a reference to Organization",
|
|
568
|
+
)
|
|
569
|
+
})?;
|
|
570
|
+
|
|
571
|
+
// Extract the organization ID from the record
|
|
572
|
+
let organization_id = context.field(&org_ref_field)
|
|
573
|
+
.and_then(|v| v.as_str())
|
|
574
|
+
.ok_or_else(|| {
|
|
575
|
+
PolicyAuthorizationError::new(
|
|
576
|
+
"ORGANIZATION_NOT_DEFINED",
|
|
577
|
+
format!("record does not have a valid {} field", org_ref_field),
|
|
578
|
+
)
|
|
579
|
+
})?;
|
|
580
|
+
|
|
581
|
+
// Find the membership collection
|
|
582
|
+
let membership_collection = auth_state.find_membership_collection()
|
|
583
|
+
.ok_or_else(|| {
|
|
584
|
+
PolicyAuthorizationError::new(
|
|
585
|
+
"MEMBERSHIP_NOT_DEFINED",
|
|
586
|
+
"schema does not define a membership collection (collection with references to both User and Organization)",
|
|
587
|
+
)
|
|
588
|
+
})?;
|
|
589
|
+
|
|
590
|
+
// Find the field names for user and organization references in the membership collection
|
|
591
|
+
let (user_field, org_field) = auth_state.find_membership_fields(&membership_collection)
|
|
592
|
+
.ok_or_else(|| {
|
|
593
|
+
PolicyAuthorizationError::new(
|
|
594
|
+
"MEMBERSHIP_NOT_DEFINED",
|
|
595
|
+
"membership collection does not have both user and organization references",
|
|
596
|
+
)
|
|
597
|
+
})?;
|
|
598
|
+
|
|
599
|
+
// Query for matching membership record
|
|
600
|
+
let membership_records = auth_state.records_in_collection(&membership_collection);
|
|
601
|
+
|
|
602
|
+
let has_membership = membership_records.iter().any(|record| {
|
|
603
|
+
if let Some(obj) = record.as_object() {
|
|
604
|
+
let user_match = obj
|
|
605
|
+
.get(&user_field)
|
|
606
|
+
.and_then(|v| v.as_str())
|
|
607
|
+
.map(|u| u == actor.id)
|
|
608
|
+
.unwrap_or(false);
|
|
609
|
+
|
|
610
|
+
let org_match = obj
|
|
611
|
+
.get(&org_field)
|
|
612
|
+
.and_then(|v| v.as_str())
|
|
613
|
+
.map(|o| o == organization_id)
|
|
614
|
+
.unwrap_or(false);
|
|
615
|
+
|
|
616
|
+
user_match && org_match
|
|
617
|
+
} else {
|
|
618
|
+
false
|
|
619
|
+
}
|
|
620
|
+
});
|
|
621
|
+
|
|
622
|
+
if has_membership {
|
|
623
|
+
Ok(AuthorizationDecision::Allow)
|
|
624
|
+
} else {
|
|
625
|
+
Err(PolicyAuthorizationError::unauthorized(
|
|
626
|
+
format!(
|
|
627
|
+
"actor {} is not a member of organization {}",
|
|
628
|
+
actor.id, organization_id
|
|
629
|
+
),
|
|
630
|
+
))
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/// Self subject at record level: allows if record field identifies the actor.
|
|
635
|
+
/// The field value must equal actor.id (stable identity matching).
|
|
636
|
+
/// If the field is missing or null, access is denied.
|
|
637
|
+
fn evaluate_record_self(
|
|
638
|
+
field: &str,
|
|
639
|
+
context: &RecordAuthorizationContext,
|
|
640
|
+
) -> Result<AuthorizationDecision, PolicyAuthorizationError> {
|
|
641
|
+
let actor = context.actor.as_ref().ok_or_else(|| {
|
|
642
|
+
PolicyAuthorizationError::unauthenticated(
|
|
643
|
+
"self policy requires an authenticated actor",
|
|
644
|
+
)
|
|
645
|
+
})?;
|
|
646
|
+
|
|
647
|
+
let field_value = context.field(field)
|
|
648
|
+
.and_then(|v| v.as_str())
|
|
649
|
+
.ok_or_else(|| {
|
|
650
|
+
PolicyAuthorizationError::new(
|
|
651
|
+
"IDENTITY_NOT_FOUND",
|
|
652
|
+
format!("record does not have a valid {} field", field),
|
|
653
|
+
)
|
|
654
|
+
})?;
|
|
655
|
+
|
|
656
|
+
if actor.id == field_value {
|
|
657
|
+
Ok(AuthorizationDecision::Allow)
|
|
658
|
+
} else {
|
|
659
|
+
Err(PolicyAuthorizationError::unauthorized(
|
|
660
|
+
format!(
|
|
661
|
+
"actor {} does not match identity field {}",
|
|
662
|
+
actor.id, field
|
|
663
|
+
),
|
|
664
|
+
))
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
#[cfg(test)]
|
|
670
|
+
mod tests {
|
|
671
|
+
use super::*;
|
|
672
|
+
|
|
673
|
+
#[test]
|
|
674
|
+
fn authenticated_allows_with_actor() {
|
|
675
|
+
let context = PolicyContext::new(Some(Actor::new("user123")), "Todo", "todo-1");
|
|
676
|
+
let result = PolicyEvaluator::evaluate(PolicySubject::Authenticated, &context);
|
|
677
|
+
assert_eq!(result, Ok(AuthorizationDecision::Allow));
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
#[test]
|
|
681
|
+
fn authenticated_denies_without_actor() {
|
|
682
|
+
let context = PolicyContext::new(None, "Todo", "todo-1");
|
|
683
|
+
let result = PolicyEvaluator::evaluate(PolicySubject::Authenticated, &context);
|
|
684
|
+
assert!(result.is_err());
|
|
685
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHENTICATED");
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
#[test]
|
|
689
|
+
fn owner_allows_when_actor_is_owner() {
|
|
690
|
+
let mut context = PolicyContext::new(Some(Actor::new("user123")), "Project", "project-1");
|
|
691
|
+
context.set_attribute("owner_id", "user123");
|
|
692
|
+
let result = PolicyEvaluator::evaluate(PolicySubject::Owner, &context);
|
|
693
|
+
assert_eq!(result, Ok(AuthorizationDecision::Allow));
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
#[test]
|
|
697
|
+
fn owner_denies_when_actor_is_not_owner() {
|
|
698
|
+
let mut context = PolicyContext::new(Some(Actor::new("user123")), "Project", "project-1");
|
|
699
|
+
context.set_attribute("owner_id", "user456");
|
|
700
|
+
let result = PolicyEvaluator::evaluate(PolicySubject::Owner, &context);
|
|
701
|
+
assert!(result.is_err());
|
|
702
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHORIZED");
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
#[test]
|
|
706
|
+
fn owner_denies_without_actor() {
|
|
707
|
+
let context = PolicyContext::new(None, "Project", "project-1");
|
|
708
|
+
let result = PolicyEvaluator::evaluate(PolicySubject::Owner, &context);
|
|
709
|
+
assert!(result.is_err());
|
|
710
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHENTICATED");
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
#[test]
|
|
714
|
+
fn owner_denies_without_owner_id_attribute() {
|
|
715
|
+
let context = PolicyContext::new(Some(Actor::new("user123")), "Project", "project-1");
|
|
716
|
+
let result = PolicyEvaluator::evaluate(PolicySubject::Owner, &context);
|
|
717
|
+
assert!(result.is_err());
|
|
718
|
+
assert_eq!(result.unwrap_err().code, "OWNERSHIP_NOT_DEFINED");
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
#[test]
|
|
722
|
+
fn policy_subject_from_str() {
|
|
723
|
+
assert_eq!(PolicySubject::from_str("authenticated"), Some(PolicySubject::Authenticated));
|
|
724
|
+
assert_eq!(PolicySubject::from_str("owner"), Some(PolicySubject::Owner));
|
|
725
|
+
assert_eq!(PolicySubject::from_str("member"), Some(PolicySubject::Member));
|
|
726
|
+
assert_eq!(PolicySubject::from_str("invalid"), None);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
#[test]
|
|
730
|
+
fn member_allows_when_actor_is_member() {
|
|
731
|
+
let mut context = PolicyContext::new(Some(Actor::new("user123")), "Project", "project-1");
|
|
732
|
+
context.set_attribute("organization_id", "org-abc");
|
|
733
|
+
context.set_attribute("is_member", "true");
|
|
734
|
+
let result = PolicyEvaluator::evaluate(PolicySubject::Member, &context);
|
|
735
|
+
assert_eq!(result, Ok(AuthorizationDecision::Allow));
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
#[test]
|
|
739
|
+
fn member_denies_when_actor_is_not_member() {
|
|
740
|
+
let mut context = PolicyContext::new(Some(Actor::new("user123")), "Project", "project-1");
|
|
741
|
+
context.set_attribute("organization_id", "org-abc");
|
|
742
|
+
context.set_attribute("is_member", "false");
|
|
743
|
+
let result = PolicyEvaluator::evaluate(PolicySubject::Member, &context);
|
|
744
|
+
assert!(result.is_err());
|
|
745
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHORIZED");
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
#[test]
|
|
749
|
+
fn member_denies_when_is_member_attribute_missing() {
|
|
750
|
+
let mut context = PolicyContext::new(Some(Actor::new("user123")), "Project", "project-1");
|
|
751
|
+
context.set_attribute("organization_id", "org-abc");
|
|
752
|
+
let result = PolicyEvaluator::evaluate(PolicySubject::Member, &context);
|
|
753
|
+
assert!(result.is_err());
|
|
754
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHORIZED");
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
#[test]
|
|
758
|
+
fn member_denies_without_actor() {
|
|
759
|
+
let mut context = PolicyContext::new(None, "Project", "project-1");
|
|
760
|
+
context.set_attribute("organization_id", "org-abc");
|
|
761
|
+
context.set_attribute("is_member", "true");
|
|
762
|
+
let result = PolicyEvaluator::evaluate(PolicySubject::Member, &context);
|
|
763
|
+
assert!(result.is_err());
|
|
764
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHENTICATED");
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
#[test]
|
|
768
|
+
fn member_denies_without_organization_id_attribute() {
|
|
769
|
+
let mut context = PolicyContext::new(Some(Actor::new("user123")), "Project", "project-1");
|
|
770
|
+
context.set_attribute("is_member", "true");
|
|
771
|
+
let result = PolicyEvaluator::evaluate(PolicySubject::Member, &context);
|
|
772
|
+
assert!(result.is_err());
|
|
773
|
+
assert_eq!(result.unwrap_err().code, "ORGANIZATION_NOT_DEFINED");
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// Substrate tests for AuthorizationState (Phase 4A)
|
|
777
|
+
// These tests verify that RecordAuthorizationContext can carry authorization state
|
|
778
|
+
// and that the state provides read-only access to schema and snapshot.
|
|
779
|
+
|
|
780
|
+
fn make_stored_row(collection: &str, key: &str, value: Value) -> crate::StoredRow {
|
|
781
|
+
crate::StoredRow {
|
|
782
|
+
capability: format!("tenant:123:{}", collection),
|
|
783
|
+
key: key.into(),
|
|
784
|
+
rust_type: "json".into(),
|
|
785
|
+
value,
|
|
786
|
+
unix_ms: 0,
|
|
787
|
+
content_hash: None,
|
|
788
|
+
flow_ref: None,
|
|
789
|
+
deleted: false,
|
|
790
|
+
operation: None,
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
#[test]
|
|
795
|
+
fn record_context_without_state() {
|
|
796
|
+
let record = serde_json::json!({"_id": "rec1", "title": "Test"});
|
|
797
|
+
let context = RecordAuthorizationContext::new(
|
|
798
|
+
Some(Actor::new("user1")),
|
|
799
|
+
"TestCollection",
|
|
800
|
+
"rec1",
|
|
801
|
+
record,
|
|
802
|
+
);
|
|
803
|
+
assert!(context.authorization_state.is_none());
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
#[test]
|
|
807
|
+
fn record_context_with_state_builder() {
|
|
808
|
+
use crate::state_contract::StateSchema;
|
|
809
|
+
|
|
810
|
+
let record = serde_json::json!({"_id": "rec1", "title": "Test"});
|
|
811
|
+
let schema = Arc::new(StateSchema {
|
|
812
|
+
contract_version: 1,
|
|
813
|
+
schema_version: 1,
|
|
814
|
+
application_id: "app".into(),
|
|
815
|
+
revision_id: "rev".into(),
|
|
816
|
+
collections: vec![],
|
|
817
|
+
});
|
|
818
|
+
|
|
819
|
+
let auth_state = AuthorizationState {
|
|
820
|
+
schema: schema.clone(),
|
|
821
|
+
state_namespace: "tenant:123".into(),
|
|
822
|
+
snapshot_rows: Arc::new(vec![]),
|
|
823
|
+
};
|
|
824
|
+
|
|
825
|
+
let context = RecordAuthorizationContext::new(
|
|
826
|
+
Some(Actor::new("user1")),
|
|
827
|
+
"TestCollection",
|
|
828
|
+
"rec1",
|
|
829
|
+
record,
|
|
830
|
+
)
|
|
831
|
+
.with_state(auth_state.clone());
|
|
832
|
+
|
|
833
|
+
assert!(context.authorization_state.is_some());
|
|
834
|
+
assert_eq!(
|
|
835
|
+
context.authorization_state.unwrap().state_namespace,
|
|
836
|
+
"tenant:123"
|
|
837
|
+
);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
#[test]
|
|
841
|
+
fn authorization_state_lookup_record() {
|
|
842
|
+
use crate::state_contract::StateSchema;
|
|
843
|
+
|
|
844
|
+
let schema = Arc::new(StateSchema {
|
|
845
|
+
contract_version: 1,
|
|
846
|
+
schema_version: 1,
|
|
847
|
+
application_id: "app".into(),
|
|
848
|
+
revision_id: "rev".into(),
|
|
849
|
+
collections: vec![],
|
|
850
|
+
});
|
|
851
|
+
|
|
852
|
+
let record1 = serde_json::json!({"_id": "id1", "name": "Alice"});
|
|
853
|
+
let stored_row = make_stored_row("Users", "id1", record1.clone());
|
|
854
|
+
|
|
855
|
+
let snapshot_rows = Arc::new(vec![stored_row]);
|
|
856
|
+
let state = AuthorizationState::new(schema, "tenant:123", snapshot_rows);
|
|
857
|
+
|
|
858
|
+
let found = state.lookup_record("Users", "id1");
|
|
859
|
+
assert_eq!(found, Some(record1));
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
#[test]
|
|
863
|
+
fn authorization_state_lookup_missing_record() {
|
|
864
|
+
use crate::state_contract::StateSchema;
|
|
865
|
+
|
|
866
|
+
let schema = Arc::new(StateSchema {
|
|
867
|
+
contract_version: 1,
|
|
868
|
+
schema_version: 1,
|
|
869
|
+
application_id: "app".into(),
|
|
870
|
+
revision_id: "rev".into(),
|
|
871
|
+
collections: vec![],
|
|
872
|
+
});
|
|
873
|
+
|
|
874
|
+
let snapshot_rows = Arc::new(vec![]);
|
|
875
|
+
let state = AuthorizationState::new(schema, "tenant:123", snapshot_rows);
|
|
876
|
+
|
|
877
|
+
let found = state.lookup_record("Users", "nonexistent");
|
|
878
|
+
assert_eq!(found, None);
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
#[test]
|
|
882
|
+
fn authorization_state_lookup_deleted_record() {
|
|
883
|
+
use crate::state_contract::StateSchema;
|
|
884
|
+
|
|
885
|
+
let schema = Arc::new(StateSchema {
|
|
886
|
+
contract_version: 1,
|
|
887
|
+
schema_version: 1,
|
|
888
|
+
application_id: "app".into(),
|
|
889
|
+
revision_id: "rev".into(),
|
|
890
|
+
collections: vec![],
|
|
891
|
+
});
|
|
892
|
+
|
|
893
|
+
let record1 = serde_json::json!({"_id": "id1", "name": "Alice"});
|
|
894
|
+
let mut stored_row = make_stored_row("Users", "id1", record1);
|
|
895
|
+
stored_row.deleted = true; // Mark as deleted
|
|
896
|
+
|
|
897
|
+
let snapshot_rows = Arc::new(vec![stored_row]);
|
|
898
|
+
let state = AuthorizationState::new(schema, "tenant:123", snapshot_rows);
|
|
899
|
+
|
|
900
|
+
let found = state.lookup_record("Users", "id1");
|
|
901
|
+
assert_eq!(found, None); // Deleted records are not visible
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
#[test]
|
|
905
|
+
fn authorization_state_records_in_collection() {
|
|
906
|
+
use crate::state_contract::StateSchema;
|
|
907
|
+
|
|
908
|
+
let schema = Arc::new(StateSchema {
|
|
909
|
+
contract_version: 1,
|
|
910
|
+
schema_version: 1,
|
|
911
|
+
application_id: "app".into(),
|
|
912
|
+
revision_id: "rev".into(),
|
|
913
|
+
collections: vec![],
|
|
914
|
+
});
|
|
915
|
+
|
|
916
|
+
let record1 = serde_json::json!({"_id": "id1", "name": "Alice"});
|
|
917
|
+
let record2 = serde_json::json!({"_id": "id2", "name": "Bob"});
|
|
918
|
+
|
|
919
|
+
let snapshot_rows = Arc::new(vec![
|
|
920
|
+
make_stored_row("Users", "id1", record1.clone()),
|
|
921
|
+
make_stored_row("Users", "id2", record2.clone()),
|
|
922
|
+
]);
|
|
923
|
+
|
|
924
|
+
let state = AuthorizationState::new(schema, "tenant:123", snapshot_rows);
|
|
925
|
+
let records = state.records_in_collection("Users");
|
|
926
|
+
|
|
927
|
+
assert_eq!(records.len(), 2);
|
|
928
|
+
assert!(records.contains(&record1));
|
|
929
|
+
assert!(records.contains(&record2));
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
#[test]
|
|
933
|
+
fn existing_owner_policy_works_with_state() {
|
|
934
|
+
let record = serde_json::json!({"_id": "rec1", "owner_id": "user123"});
|
|
935
|
+
let context = RecordAuthorizationContext::new(
|
|
936
|
+
Some(Actor::new("user123")),
|
|
937
|
+
"Project",
|
|
938
|
+
"rec1",
|
|
939
|
+
record,
|
|
940
|
+
);
|
|
941
|
+
|
|
942
|
+
// Should work even though authorization_state is None
|
|
943
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Owner, &context);
|
|
944
|
+
assert_eq!(result, Ok(AuthorizationDecision::Allow));
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
#[test]
|
|
948
|
+
fn existing_authenticated_policy_works_with_state() {
|
|
949
|
+
let record = serde_json::json!({"_id": "rec1"});
|
|
950
|
+
let context = RecordAuthorizationContext::new(
|
|
951
|
+
Some(Actor::new("user123")),
|
|
952
|
+
"Project",
|
|
953
|
+
"rec1",
|
|
954
|
+
record,
|
|
955
|
+
);
|
|
956
|
+
|
|
957
|
+
// Should work even though authorization_state is None
|
|
958
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Authenticated, &context);
|
|
959
|
+
assert_eq!(result, Ok(AuthorizationDecision::Allow));
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
// Phase 4B: Member policy tests
|
|
963
|
+
// These tests verify that member policy is enforced using database state,
|
|
964
|
+
// not caller-supplied attributes.
|
|
965
|
+
|
|
966
|
+
fn make_schema_with_collections(collections: Vec<crate::state_contract::CollectionSchema>) -> Arc<crate::state_contract::StateSchema> {
|
|
967
|
+
Arc::new(crate::state_contract::StateSchema {
|
|
968
|
+
contract_version: 1,
|
|
969
|
+
schema_version: 1,
|
|
970
|
+
application_id: "app".into(),
|
|
971
|
+
revision_id: "rev".into(),
|
|
972
|
+
collections,
|
|
973
|
+
})
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
fn make_collection(name: &str, fields: Vec<crate::state_contract::FieldSchema>) -> crate::state_contract::CollectionSchema {
|
|
977
|
+
crate::state_contract::CollectionSchema {
|
|
978
|
+
name: name.into(),
|
|
979
|
+
version: 1,
|
|
980
|
+
fields,
|
|
981
|
+
indexes: vec![],
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
fn make_field(name: &str, field_type: crate::state_contract::FieldType) -> crate::state_contract::FieldSchema {
|
|
986
|
+
crate::state_contract::FieldSchema {
|
|
987
|
+
name: name.into(),
|
|
988
|
+
field_type,
|
|
989
|
+
nullable: false,
|
|
990
|
+
required: true,
|
|
991
|
+
default: None,
|
|
992
|
+
constraints: crate::state_contract::FieldConstraints::default(),
|
|
993
|
+
computed: None,
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
#[test]
|
|
998
|
+
fn member_policy_allows_authenticated_member() {
|
|
999
|
+
use crate::state_contract::FieldType;
|
|
1000
|
+
|
|
1001
|
+
let schema = make_schema_with_collections(vec![
|
|
1002
|
+
make_collection("Project", vec![
|
|
1003
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1004
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1005
|
+
]),
|
|
1006
|
+
make_collection("Membership", vec![
|
|
1007
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1008
|
+
make_field("user", FieldType::Reference { collection: "User".into() }),
|
|
1009
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1010
|
+
]),
|
|
1011
|
+
]);
|
|
1012
|
+
|
|
1013
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org1"});
|
|
1014
|
+
let membership = serde_json::json!({"_id": "mem1", "user": "alice", "organization": "org1"});
|
|
1015
|
+
|
|
1016
|
+
let snapshot = Arc::new(vec![
|
|
1017
|
+
make_stored_row("Project", "proj1", project),
|
|
1018
|
+
make_stored_row("Membership", "mem1", membership),
|
|
1019
|
+
]);
|
|
1020
|
+
|
|
1021
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1022
|
+
let context = RecordAuthorizationContext::new(
|
|
1023
|
+
Some(Actor::new("alice")),
|
|
1024
|
+
"Project",
|
|
1025
|
+
"proj1",
|
|
1026
|
+
serde_json::json!({"_id": "proj1", "organization": "org1"}),
|
|
1027
|
+
)
|
|
1028
|
+
.with_state(auth_state);
|
|
1029
|
+
|
|
1030
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1031
|
+
assert_eq!(result, Ok(AuthorizationDecision::Allow));
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
#[test]
|
|
1035
|
+
fn member_policy_denies_unauthenticated() {
|
|
1036
|
+
use crate::state_contract::FieldType;
|
|
1037
|
+
|
|
1038
|
+
let schema = make_schema_with_collections(vec![
|
|
1039
|
+
make_collection("Project", vec![
|
|
1040
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1041
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1042
|
+
]),
|
|
1043
|
+
make_collection("Membership", vec![
|
|
1044
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1045
|
+
make_field("user", FieldType::Reference { collection: "User".into() }),
|
|
1046
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1047
|
+
]),
|
|
1048
|
+
]);
|
|
1049
|
+
|
|
1050
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org1"});
|
|
1051
|
+
let membership = serde_json::json!({"_id": "mem1", "user": "alice", "organization": "org1"});
|
|
1052
|
+
|
|
1053
|
+
let snapshot = Arc::new(vec![
|
|
1054
|
+
make_stored_row("Project", "proj1", project),
|
|
1055
|
+
make_stored_row("Membership", "mem1", membership),
|
|
1056
|
+
]);
|
|
1057
|
+
|
|
1058
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1059
|
+
let context = RecordAuthorizationContext::new(
|
|
1060
|
+
None, // No actor
|
|
1061
|
+
"Project",
|
|
1062
|
+
"proj1",
|
|
1063
|
+
serde_json::json!({"_id": "proj1", "organization": "org1"}),
|
|
1064
|
+
)
|
|
1065
|
+
.with_state(auth_state);
|
|
1066
|
+
|
|
1067
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1068
|
+
assert!(result.is_err());
|
|
1069
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHENTICATED");
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
#[test]
|
|
1073
|
+
fn member_policy_denies_non_member() {
|
|
1074
|
+
use crate::state_contract::FieldType;
|
|
1075
|
+
|
|
1076
|
+
let schema = make_schema_with_collections(vec![
|
|
1077
|
+
make_collection("Project", vec![
|
|
1078
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1079
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1080
|
+
]),
|
|
1081
|
+
make_collection("Membership", vec![
|
|
1082
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1083
|
+
make_field("user", FieldType::Reference { collection: "User".into() }),
|
|
1084
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1085
|
+
]),
|
|
1086
|
+
]);
|
|
1087
|
+
|
|
1088
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org1"});
|
|
1089
|
+
let membership = serde_json::json!({"_id": "mem1", "user": "alice", "organization": "org1"});
|
|
1090
|
+
|
|
1091
|
+
let snapshot = Arc::new(vec![
|
|
1092
|
+
make_stored_row("Project", "proj1", project),
|
|
1093
|
+
make_stored_row("Membership", "mem1", membership),
|
|
1094
|
+
]);
|
|
1095
|
+
|
|
1096
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1097
|
+
let context = RecordAuthorizationContext::new(
|
|
1098
|
+
Some(Actor::new("bob")), // Different actor
|
|
1099
|
+
"Project",
|
|
1100
|
+
"proj1",
|
|
1101
|
+
serde_json::json!({"_id": "proj1", "organization": "org1"}),
|
|
1102
|
+
)
|
|
1103
|
+
.with_state(auth_state);
|
|
1104
|
+
|
|
1105
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1106
|
+
assert!(result.is_err());
|
|
1107
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHORIZED");
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
#[test]
|
|
1111
|
+
fn member_policy_cross_org_isolation() {
|
|
1112
|
+
use crate::state_contract::FieldType;
|
|
1113
|
+
|
|
1114
|
+
let schema = make_schema_with_collections(vec![
|
|
1115
|
+
make_collection("Project", vec![
|
|
1116
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1117
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1118
|
+
]),
|
|
1119
|
+
make_collection("Membership", vec![
|
|
1120
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1121
|
+
make_field("user", FieldType::Reference { collection: "User".into() }),
|
|
1122
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1123
|
+
]),
|
|
1124
|
+
]);
|
|
1125
|
+
|
|
1126
|
+
// Alice is member of org1, project is in org2
|
|
1127
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org2"});
|
|
1128
|
+
let membership = serde_json::json!({"_id": "mem1", "user": "alice", "organization": "org1"});
|
|
1129
|
+
|
|
1130
|
+
let snapshot = Arc::new(vec![
|
|
1131
|
+
make_stored_row("Project", "proj1", project),
|
|
1132
|
+
make_stored_row("Membership", "mem1", membership),
|
|
1133
|
+
]);
|
|
1134
|
+
|
|
1135
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1136
|
+
let context = RecordAuthorizationContext::new(
|
|
1137
|
+
Some(Actor::new("alice")),
|
|
1138
|
+
"Project",
|
|
1139
|
+
"proj1",
|
|
1140
|
+
serde_json::json!({"_id": "proj1", "organization": "org2"}),
|
|
1141
|
+
)
|
|
1142
|
+
.with_state(auth_state);
|
|
1143
|
+
|
|
1144
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1145
|
+
assert!(result.is_err());
|
|
1146
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHORIZED");
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
#[test]
|
|
1150
|
+
fn member_policy_no_state_fails() {
|
|
1151
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org1"});
|
|
1152
|
+
let context = RecordAuthorizationContext::new(
|
|
1153
|
+
Some(Actor::new("alice")),
|
|
1154
|
+
"Project",
|
|
1155
|
+
"proj1",
|
|
1156
|
+
project,
|
|
1157
|
+
); // No state attached
|
|
1158
|
+
|
|
1159
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1160
|
+
assert!(result.is_err());
|
|
1161
|
+
assert_eq!(result.unwrap_err().code, "AUTHORIZATION_STATE_NOT_AVAILABLE");
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
#[test]
|
|
1165
|
+
fn member_policy_missing_organization_reference() {
|
|
1166
|
+
use crate::state_contract::FieldType;
|
|
1167
|
+
|
|
1168
|
+
let schema = make_schema_with_collections(vec![
|
|
1169
|
+
make_collection("Project", vec![
|
|
1170
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1171
|
+
// No organization reference
|
|
1172
|
+
]),
|
|
1173
|
+
make_collection("Membership", vec![
|
|
1174
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1175
|
+
make_field("user", FieldType::Reference { collection: "User".into() }),
|
|
1176
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1177
|
+
]),
|
|
1178
|
+
]);
|
|
1179
|
+
|
|
1180
|
+
let project = serde_json::json!({"_id": "proj1"});
|
|
1181
|
+
let snapshot = Arc::new(vec![
|
|
1182
|
+
make_stored_row("Project", "proj1", project),
|
|
1183
|
+
]);
|
|
1184
|
+
|
|
1185
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1186
|
+
let context = RecordAuthorizationContext::new(
|
|
1187
|
+
Some(Actor::new("alice")),
|
|
1188
|
+
"Project",
|
|
1189
|
+
"proj1",
|
|
1190
|
+
serde_json::json!({"_id": "proj1"}),
|
|
1191
|
+
)
|
|
1192
|
+
.with_state(auth_state);
|
|
1193
|
+
|
|
1194
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1195
|
+
assert!(result.is_err());
|
|
1196
|
+
assert_eq!(result.unwrap_err().code, "ORGANIZATION_NOT_DEFINED");
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
#[test]
|
|
1200
|
+
fn member_policy_missing_organization_field_in_record() {
|
|
1201
|
+
use crate::state_contract::FieldType;
|
|
1202
|
+
|
|
1203
|
+
let schema = make_schema_with_collections(vec![
|
|
1204
|
+
make_collection("Project", vec![
|
|
1205
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1206
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1207
|
+
]),
|
|
1208
|
+
make_collection("Membership", vec![
|
|
1209
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1210
|
+
make_field("user", FieldType::Reference { collection: "User".into() }),
|
|
1211
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1212
|
+
]),
|
|
1213
|
+
]);
|
|
1214
|
+
|
|
1215
|
+
let project = serde_json::json!({"_id": "proj1"}); // Missing organization field
|
|
1216
|
+
let snapshot = Arc::new(vec![
|
|
1217
|
+
make_stored_row("Project", "proj1", project),
|
|
1218
|
+
]);
|
|
1219
|
+
|
|
1220
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1221
|
+
let context = RecordAuthorizationContext::new(
|
|
1222
|
+
Some(Actor::new("alice")),
|
|
1223
|
+
"Project",
|
|
1224
|
+
"proj1",
|
|
1225
|
+
serde_json::json!({"_id": "proj1"}),
|
|
1226
|
+
)
|
|
1227
|
+
.with_state(auth_state);
|
|
1228
|
+
|
|
1229
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1230
|
+
assert!(result.is_err());
|
|
1231
|
+
assert_eq!(result.unwrap_err().code, "ORGANIZATION_NOT_DEFINED");
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
#[test]
|
|
1235
|
+
fn member_policy_deleted_membership_not_honored() {
|
|
1236
|
+
use crate::state_contract::FieldType;
|
|
1237
|
+
|
|
1238
|
+
let schema = make_schema_with_collections(vec![
|
|
1239
|
+
make_collection("Project", vec![
|
|
1240
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1241
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1242
|
+
]),
|
|
1243
|
+
make_collection("Membership", vec![
|
|
1244
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1245
|
+
make_field("user", FieldType::Reference { collection: "User".into() }),
|
|
1246
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1247
|
+
]),
|
|
1248
|
+
]);
|
|
1249
|
+
|
|
1250
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org1"});
|
|
1251
|
+
let mut membership = make_stored_row("Membership", "mem1",
|
|
1252
|
+
serde_json::json!({"_id": "mem1", "user": "alice", "organization": "org1"}));
|
|
1253
|
+
membership.deleted = true; // Mark as deleted
|
|
1254
|
+
|
|
1255
|
+
let snapshot = Arc::new(vec![
|
|
1256
|
+
make_stored_row("Project", "proj1", project),
|
|
1257
|
+
membership,
|
|
1258
|
+
]);
|
|
1259
|
+
|
|
1260
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1261
|
+
let context = RecordAuthorizationContext::new(
|
|
1262
|
+
Some(Actor::new("alice")),
|
|
1263
|
+
"Project",
|
|
1264
|
+
"proj1",
|
|
1265
|
+
serde_json::json!({"_id": "proj1", "organization": "org1"}),
|
|
1266
|
+
)
|
|
1267
|
+
.with_state(auth_state);
|
|
1268
|
+
|
|
1269
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1270
|
+
assert!(result.is_err());
|
|
1271
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHORIZED");
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
#[test]
|
|
1275
|
+
fn member_policy_multiple_memberships_finds_match() {
|
|
1276
|
+
use crate::state_contract::FieldType;
|
|
1277
|
+
|
|
1278
|
+
let schema = make_schema_with_collections(vec![
|
|
1279
|
+
make_collection("Project", vec![
|
|
1280
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1281
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1282
|
+
]),
|
|
1283
|
+
make_collection("Membership", vec![
|
|
1284
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1285
|
+
make_field("user", FieldType::Reference { collection: "User".into() }),
|
|
1286
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1287
|
+
]),
|
|
1288
|
+
]);
|
|
1289
|
+
|
|
1290
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org2"});
|
|
1291
|
+
|
|
1292
|
+
let snapshot = Arc::new(vec![
|
|
1293
|
+
make_stored_row("Project", "proj1", project),
|
|
1294
|
+
make_stored_row("Membership", "mem1", serde_json::json!({"_id": "mem1", "user": "alice", "organization": "org1"})),
|
|
1295
|
+
make_stored_row("Membership", "mem2", serde_json::json!({"_id": "mem2", "user": "alice", "organization": "org2"})),
|
|
1296
|
+
make_stored_row("Membership", "mem3", serde_json::json!({"_id": "mem3", "user": "bob", "organization": "org2"})),
|
|
1297
|
+
]);
|
|
1298
|
+
|
|
1299
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1300
|
+
let context = RecordAuthorizationContext::new(
|
|
1301
|
+
Some(Actor::new("alice")),
|
|
1302
|
+
"Project",
|
|
1303
|
+
"proj1",
|
|
1304
|
+
serde_json::json!({"_id": "proj1", "organization": "org2"}),
|
|
1305
|
+
)
|
|
1306
|
+
.with_state(auth_state);
|
|
1307
|
+
|
|
1308
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1309
|
+
assert_eq!(result, Ok(AuthorizationDecision::Allow));
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
#[test]
|
|
1313
|
+
fn member_policy_spoofing_fake_is_member_attribute() {
|
|
1314
|
+
use crate::state_contract::FieldType;
|
|
1315
|
+
|
|
1316
|
+
let schema = make_schema_with_collections(vec![
|
|
1317
|
+
make_collection("Project", vec![
|
|
1318
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1319
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1320
|
+
]),
|
|
1321
|
+
make_collection("Membership", vec![
|
|
1322
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1323
|
+
make_field("user", FieldType::Reference { collection: "User".into() }),
|
|
1324
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1325
|
+
]),
|
|
1326
|
+
]);
|
|
1327
|
+
|
|
1328
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org1", "is_member": "true"});
|
|
1329
|
+
let snapshot = Arc::new(vec![
|
|
1330
|
+
make_stored_row("Project", "proj1", project),
|
|
1331
|
+
]);
|
|
1332
|
+
|
|
1333
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1334
|
+
let context = RecordAuthorizationContext::new(
|
|
1335
|
+
Some(Actor::new("alice")),
|
|
1336
|
+
"Project",
|
|
1337
|
+
"proj1",
|
|
1338
|
+
serde_json::json!({"_id": "proj1", "organization": "org1", "is_member": "true"}),
|
|
1339
|
+
)
|
|
1340
|
+
.with_state(auth_state);
|
|
1341
|
+
|
|
1342
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1343
|
+
// Should deny because no actual membership record exists
|
|
1344
|
+
assert!(result.is_err());
|
|
1345
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHORIZED");
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
#[test]
|
|
1349
|
+
fn member_policy_spoofing_fake_organization_id() {
|
|
1350
|
+
use crate::state_contract::FieldType;
|
|
1351
|
+
|
|
1352
|
+
let schema = make_schema_with_collections(vec![
|
|
1353
|
+
make_collection("Project", vec![
|
|
1354
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1355
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1356
|
+
]),
|
|
1357
|
+
make_collection("Membership", vec![
|
|
1358
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1359
|
+
make_field("user", FieldType::Reference { collection: "User".into() }),
|
|
1360
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1361
|
+
]),
|
|
1362
|
+
]);
|
|
1363
|
+
|
|
1364
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org1"});
|
|
1365
|
+
let membership = serde_json::json!({"_id": "mem1", "user": "alice", "organization": "org1"});
|
|
1366
|
+
|
|
1367
|
+
let snapshot = Arc::new(vec![
|
|
1368
|
+
make_stored_row("Project", "proj1", project),
|
|
1369
|
+
make_stored_row("Membership", "mem1", membership),
|
|
1370
|
+
]);
|
|
1371
|
+
|
|
1372
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1373
|
+
|
|
1374
|
+
// Caller tries to spoof a different organization
|
|
1375
|
+
let context = RecordAuthorizationContext::new(
|
|
1376
|
+
Some(Actor::new("alice")),
|
|
1377
|
+
"Project",
|
|
1378
|
+
"proj1",
|
|
1379
|
+
serde_json::json!({"_id": "proj1", "organization": "org2"}), // Spoofed org
|
|
1380
|
+
)
|
|
1381
|
+
.with_state(auth_state);
|
|
1382
|
+
|
|
1383
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1384
|
+
// Should deny because actual record has org1, membership is for org1, but caller sent org2
|
|
1385
|
+
// The authoritative record value is from the snapshot, not the caller's input
|
|
1386
|
+
assert!(result.is_err());
|
|
1387
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHORIZED");
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
#[test]
|
|
1391
|
+
fn member_policy_discovers_user_field_variations() {
|
|
1392
|
+
use crate::state_contract::FieldType;
|
|
1393
|
+
|
|
1394
|
+
let schema = make_schema_with_collections(vec![
|
|
1395
|
+
make_collection("Project", vec![
|
|
1396
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1397
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1398
|
+
]),
|
|
1399
|
+
make_collection("Membership", vec![
|
|
1400
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1401
|
+
make_field("user_id", FieldType::Reference { collection: "User".into() }), // Variation: user_id not user
|
|
1402
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1403
|
+
]),
|
|
1404
|
+
]);
|
|
1405
|
+
|
|
1406
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org1"});
|
|
1407
|
+
let membership = serde_json::json!({"_id": "mem1", "user_id": "alice", "organization": "org1"});
|
|
1408
|
+
|
|
1409
|
+
let snapshot = Arc::new(vec![
|
|
1410
|
+
make_stored_row("Project", "proj1", project),
|
|
1411
|
+
make_stored_row("Membership", "mem1", membership),
|
|
1412
|
+
]);
|
|
1413
|
+
|
|
1414
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1415
|
+
let context = RecordAuthorizationContext::new(
|
|
1416
|
+
Some(Actor::new("alice")),
|
|
1417
|
+
"Project",
|
|
1418
|
+
"proj1",
|
|
1419
|
+
serde_json::json!({"_id": "proj1", "organization": "org1"}),
|
|
1420
|
+
)
|
|
1421
|
+
.with_state(auth_state);
|
|
1422
|
+
|
|
1423
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1424
|
+
// Should work because find_membership_fields looks for "User" references regardless of field name
|
|
1425
|
+
// But wait - it looks for field names, not references. Let me check the implementation...
|
|
1426
|
+
// Actually the test shows user_id references "User", so it should find it.
|
|
1427
|
+
// But my implementation looks for the first Reference to User, so it will find user_id
|
|
1428
|
+
assert_eq!(result, Ok(AuthorizationDecision::Allow));
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
#[test]
|
|
1432
|
+
fn member_policy_spoofing_fake_role_attribute() {
|
|
1433
|
+
use crate::state_contract::FieldType;
|
|
1434
|
+
|
|
1435
|
+
let schema = make_schema_with_collections(vec![
|
|
1436
|
+
make_collection("Project", vec![
|
|
1437
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1438
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1439
|
+
]),
|
|
1440
|
+
make_collection("Membership", vec![
|
|
1441
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1442
|
+
make_field("user", FieldType::Reference { collection: "User".into() }),
|
|
1443
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1444
|
+
]),
|
|
1445
|
+
]);
|
|
1446
|
+
|
|
1447
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org1", "role": "admin"});
|
|
1448
|
+
let snapshot = Arc::new(vec![
|
|
1449
|
+
make_stored_row("Project", "proj1", project),
|
|
1450
|
+
]);
|
|
1451
|
+
|
|
1452
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1453
|
+
let context = RecordAuthorizationContext::new(
|
|
1454
|
+
Some(Actor::new("alice")),
|
|
1455
|
+
"Project",
|
|
1456
|
+
"proj1",
|
|
1457
|
+
serde_json::json!({"_id": "proj1", "organization": "org1", "role": "admin"}),
|
|
1458
|
+
)
|
|
1459
|
+
.with_state(auth_state);
|
|
1460
|
+
|
|
1461
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1462
|
+
// Should deny because no actual membership record exists
|
|
1463
|
+
assert!(result.is_err());
|
|
1464
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHORIZED");
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
#[test]
|
|
1468
|
+
fn member_policy_no_membership_collection() {
|
|
1469
|
+
use crate::state_contract::FieldType;
|
|
1470
|
+
|
|
1471
|
+
let schema = make_schema_with_collections(vec![
|
|
1472
|
+
make_collection("Project", vec![
|
|
1473
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1474
|
+
make_field("organization", FieldType::Reference { collection: "Organization".into() }),
|
|
1475
|
+
]),
|
|
1476
|
+
// No membership collection defined
|
|
1477
|
+
]);
|
|
1478
|
+
|
|
1479
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org1"});
|
|
1480
|
+
let snapshot = Arc::new(vec![
|
|
1481
|
+
make_stored_row("Project", "proj1", project),
|
|
1482
|
+
]);
|
|
1483
|
+
|
|
1484
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1485
|
+
let context = RecordAuthorizationContext::new(
|
|
1486
|
+
Some(Actor::new("alice")),
|
|
1487
|
+
"Project",
|
|
1488
|
+
"proj1",
|
|
1489
|
+
serde_json::json!({"_id": "proj1", "organization": "org1"}),
|
|
1490
|
+
)
|
|
1491
|
+
.with_state(auth_state);
|
|
1492
|
+
|
|
1493
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1494
|
+
assert!(result.is_err());
|
|
1495
|
+
assert_eq!(result.unwrap_err().code, "MEMBERSHIP_NOT_DEFINED");
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
#[test]
|
|
1499
|
+
fn member_policy_handles_plural_collection_names() {
|
|
1500
|
+
use crate::state_contract::FieldType;
|
|
1501
|
+
|
|
1502
|
+
let schema = make_schema_with_collections(vec![
|
|
1503
|
+
make_collection("Project", vec![
|
|
1504
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1505
|
+
make_field("organization", FieldType::Reference { collection: "Organizations".into() }), // Plural
|
|
1506
|
+
]),
|
|
1507
|
+
make_collection("Membership", vec![
|
|
1508
|
+
make_field("_id", FieldType::Primitive { primitive: crate::state_contract::PrimitiveType::String }),
|
|
1509
|
+
make_field("user", FieldType::Reference { collection: "Users".into() }), // Plural
|
|
1510
|
+
make_field("organization", FieldType::Reference { collection: "Organizations".into() }), // Plural
|
|
1511
|
+
]),
|
|
1512
|
+
]);
|
|
1513
|
+
|
|
1514
|
+
let project = serde_json::json!({"_id": "proj1", "organization": "org1"});
|
|
1515
|
+
let membership = serde_json::json!({"_id": "mem1", "user": "alice", "organization": "org1"});
|
|
1516
|
+
|
|
1517
|
+
let snapshot = Arc::new(vec![
|
|
1518
|
+
make_stored_row("Project", "proj1", project),
|
|
1519
|
+
make_stored_row("Membership", "mem1", membership),
|
|
1520
|
+
]);
|
|
1521
|
+
|
|
1522
|
+
let auth_state = AuthorizationState::new(schema, "tenant:123", snapshot);
|
|
1523
|
+
let context = RecordAuthorizationContext::new(
|
|
1524
|
+
Some(Actor::new("alice")),
|
|
1525
|
+
"Project",
|
|
1526
|
+
"proj1",
|
|
1527
|
+
serde_json::json!({"_id": "proj1", "organization": "org1"}),
|
|
1528
|
+
)
|
|
1529
|
+
.with_state(auth_state);
|
|
1530
|
+
|
|
1531
|
+
let result = PolicyEvaluator::evaluate_record(PolicySubject::Member, &context);
|
|
1532
|
+
assert_eq!(result, Ok(AuthorizationDecision::Allow));
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
// Tests for self() policy
|
|
1536
|
+
#[test]
|
|
1537
|
+
fn self_allows_when_field_matches_actor_id() {
|
|
1538
|
+
let context = RecordAuthorizationContext::new(
|
|
1539
|
+
Some(Actor::new("user-bob")),
|
|
1540
|
+
"Invitation",
|
|
1541
|
+
"inv-1",
|
|
1542
|
+
serde_json::json!({"_id": "inv-1", "user": "user-bob"}),
|
|
1543
|
+
);
|
|
1544
|
+
|
|
1545
|
+
let result = PolicyEvaluator::evaluate_record(
|
|
1546
|
+
PolicySubject::Self_ { field: "user".to_string() },
|
|
1547
|
+
&context,
|
|
1548
|
+
);
|
|
1549
|
+
assert_eq!(result, Ok(AuthorizationDecision::Allow));
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
#[test]
|
|
1553
|
+
fn self_denies_when_field_does_not_match_actor_id() {
|
|
1554
|
+
let context = RecordAuthorizationContext::new(
|
|
1555
|
+
Some(Actor::new("user-bob")),
|
|
1556
|
+
"Invitation",
|
|
1557
|
+
"inv-1",
|
|
1558
|
+
serde_json::json!({"_id": "inv-1", "user": "user-alice"}),
|
|
1559
|
+
);
|
|
1560
|
+
|
|
1561
|
+
let result = PolicyEvaluator::evaluate_record(
|
|
1562
|
+
PolicySubject::Self_ { field: "user".to_string() },
|
|
1563
|
+
&context,
|
|
1564
|
+
);
|
|
1565
|
+
assert!(result.is_err());
|
|
1566
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHORIZED");
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
#[test]
|
|
1570
|
+
fn self_denies_without_actor() {
|
|
1571
|
+
let context = RecordAuthorizationContext::new(
|
|
1572
|
+
None,
|
|
1573
|
+
"Invitation",
|
|
1574
|
+
"inv-1",
|
|
1575
|
+
serde_json::json!({"_id": "inv-1", "user": "user-bob"}),
|
|
1576
|
+
);
|
|
1577
|
+
|
|
1578
|
+
let result = PolicyEvaluator::evaluate_record(
|
|
1579
|
+
PolicySubject::Self_ { field: "user".to_string() },
|
|
1580
|
+
&context,
|
|
1581
|
+
);
|
|
1582
|
+
assert!(result.is_err());
|
|
1583
|
+
assert_eq!(result.unwrap_err().code, "UNAUTHENTICATED");
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
#[test]
|
|
1587
|
+
fn self_denies_when_field_is_missing() {
|
|
1588
|
+
let context = RecordAuthorizationContext::new(
|
|
1589
|
+
Some(Actor::new("user-bob")),
|
|
1590
|
+
"Invitation",
|
|
1591
|
+
"inv-1",
|
|
1592
|
+
serde_json::json!({"_id": "inv-1"}),
|
|
1593
|
+
);
|
|
1594
|
+
|
|
1595
|
+
let result = PolicyEvaluator::evaluate_record(
|
|
1596
|
+
PolicySubject::Self_ { field: "user".to_string() },
|
|
1597
|
+
&context,
|
|
1598
|
+
);
|
|
1599
|
+
assert!(result.is_err());
|
|
1600
|
+
assert_eq!(result.unwrap_err().code, "IDENTITY_NOT_FOUND");
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
#[test]
|
|
1604
|
+
fn self_denies_when_field_is_null() {
|
|
1605
|
+
let context = RecordAuthorizationContext::new(
|
|
1606
|
+
Some(Actor::new("user-bob")),
|
|
1607
|
+
"Invitation",
|
|
1608
|
+
"inv-1",
|
|
1609
|
+
serde_json::json!({"_id": "inv-1", "user": null}),
|
|
1610
|
+
);
|
|
1611
|
+
|
|
1612
|
+
let result = PolicyEvaluator::evaluate_record(
|
|
1613
|
+
PolicySubject::Self_ { field: "user".to_string() },
|
|
1614
|
+
&context,
|
|
1615
|
+
);
|
|
1616
|
+
assert!(result.is_err());
|
|
1617
|
+
assert_eq!(result.unwrap_err().code, "IDENTITY_NOT_FOUND");
|
|
1618
|
+
}
|
|
1619
|
+
|
|
1620
|
+
#[test]
|
|
1621
|
+
fn self_works_with_different_field_names() {
|
|
1622
|
+
let context = RecordAuthorizationContext::new(
|
|
1623
|
+
Some(Actor::new("user-alice")),
|
|
1624
|
+
"APIKey",
|
|
1625
|
+
"key-1",
|
|
1626
|
+
serde_json::json!({"_id": "key-1", "owner": "user-alice"}),
|
|
1627
|
+
);
|
|
1628
|
+
|
|
1629
|
+
let result = PolicyEvaluator::evaluate_record(
|
|
1630
|
+
PolicySubject::Self_ { field: "owner".to_string() },
|
|
1631
|
+
&context,
|
|
1632
|
+
);
|
|
1633
|
+
assert_eq!(result, Ok(AuthorizationDecision::Allow));
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
#[test]
|
|
1637
|
+
fn self_denies_wrong_actor() {
|
|
1638
|
+
let context = RecordAuthorizationContext::new(
|
|
1639
|
+
Some(Actor::new("user-alice")),
|
|
1640
|
+
"APIKey",
|
|
1641
|
+
"key-1",
|
|
1642
|
+
serde_json::json!({"_id": "key-1", "owner": "user-bob"}),
|
|
1643
|
+
);
|
|
1644
|
+
|
|
1645
|
+
let result = PolicyEvaluator::evaluate_record(
|
|
1646
|
+
PolicySubject::Self_ { field: "owner".to_string() },
|
|
1647
|
+
&context,
|
|
1648
|
+
);
|
|
1649
|
+
assert!(result.is_err());
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
#[test]
|
|
1653
|
+
fn policy_subject_parses_self_syntax() {
|
|
1654
|
+
let subject = PolicySubject::from_str("self(user)");
|
|
1655
|
+
assert!(matches!(subject, Some(PolicySubject::Self_ { field }) if field == "user"));
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
#[test]
|
|
1659
|
+
fn policy_subject_parses_self_with_different_field() {
|
|
1660
|
+
let subject = PolicySubject::from_str("self(owner)");
|
|
1661
|
+
assert!(matches!(subject, Some(PolicySubject::Self_ { field }) if field == "owner"));
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
#[test]
|
|
1665
|
+
fn policy_subject_as_str_for_self() {
|
|
1666
|
+
let subject = PolicySubject::Self_ { field: "user".to_string() };
|
|
1667
|
+
assert_eq!(subject.as_str(), "self");
|
|
1668
|
+
}
|
|
1669
|
+
}
|