cf-authz-resolver-sdk 0.2.13

SDK for authz_resolver module: evaluation API, constraints, PEP compiler
Documentation
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! PEP constraint compiler.
//!
//! Compiles PDP evaluation responses into `AccessScope` for the secure ORM.
//!
//! ## Compilation Matrix (decision=true assumed)
//!
//! | `require_constraints` | constraints | Result |
//! |-------------------|-------------|--------|
//! | false             | empty       | `allow_all()` |
//! | false             | present     | Compile constraints → `AccessScope` |
//! | true              | empty       | `ConstraintsRequiredButAbsent` |
//! | true              | present     | Compile constraints → `AccessScope` |
//!
//! Unknown/unsupported properties fail that constraint (fail-closed).
//!
//! When `require_constraints=false`, empty constraints are treated as
//! `allow_all()` (legitimate PDP "yes, no row-level filtering"). When
//! `require_constraints=true`, empty constraints are an error (fail-closed).
//! If the PDP returns constraints regardless of the flag, they are compiled.

use modkit_security::{AccessScope, ScopeConstraint, ScopeFilter, ScopeValue};

use crate::constraints::{Constraint, Predicate};
use crate::models::EvaluationResponse;

/// Error during constraint compilation.
#[derive(Debug, thiserror::Error)]
pub enum ConstraintCompileError {
    /// Constraints were required but the PDP returned none.
    ///
    /// Per the design Decision Matrix, this is a deny: the PEP asked for
    /// row-level constraints but received an empty set. Fail-closed.
    #[error("constraints required but PDP returned none (fail-closed)")]
    ConstraintsRequiredButAbsent,

    /// All constraints contained unknown predicates (fail-closed).
    #[error("all constraints failed compilation (fail-closed): {reason}")]
    AllConstraintsFailed { reason: String },
}

/// Compile constraints from an evaluation response into an `AccessScope`.
///
/// **Precondition:** the caller has already verified `response.decision == true`.
/// This function only handles constraint compilation:
/// - `require_constraints=false, constraints=[]` → `Ok(allow_all())`
/// - `require_constraints=false, constraints=[..]` → compile predicates
/// - `require_constraints=true, constraints=[]` → `Err(ConstraintsRequiredButAbsent)`
/// - `require_constraints=true, constraints=[..]` → compile predicates
///
/// Each PDP constraint compiles to a `ScopeConstraint` (AND of filters).
/// Multiple constraints become `AccessScope::from_constraints` (OR-ed).
///
/// The compiler is property-agnostic: it validates predicates against the
/// provided `supported_properties` list and converts them structurally.
/// Unknown properties fail that constraint (fail-closed).
/// If ALL constraints fail compilation, returns `AllConstraintsFailed`.
///
/// # Errors
///
/// - `ConstraintsRequiredButAbsent` if constraints were required but empty
/// - `AllConstraintsFailed` if all constraints have unsupported predicates
pub fn compile_to_access_scope(
    response: &EvaluationResponse,
    require_constraints: bool,
    supported_properties: &[&str],
) -> Result<AccessScope, ConstraintCompileError> {
    // Step 1: Handle empty constraints based on require_constraints flag.
    if response.context.constraints.is_empty() {
        if require_constraints {
            return Err(ConstraintCompileError::ConstraintsRequiredButAbsent);
        }
        return Ok(AccessScope::allow_all());
    }

    // Step 2: Compile each constraint
    let mut constraints = Vec::new();
    let mut fail_reasons: Vec<String> = Vec::new();

    for constraint in &response.context.constraints {
        match compile_constraint(constraint, supported_properties) {
            Ok(sc) => constraints.push(sc),
            Err(reason) => {
                tracing::warn!(
                    reason = %reason,
                    "constraint compilation failed (fail-closed), possible PDP contract violation",
                );
                fail_reasons.push(reason);
            }
        }
    }

    // If no constraint compiled successfully, fail-closed
    if constraints.is_empty() {
        return Err(ConstraintCompileError::AllConstraintsFailed {
            reason: fail_reasons.join("; "),
        });
    }

    // If all compiled constraints are empty (no filters), it means allow-all
    if constraints.iter().all(ScopeConstraint::is_empty) {
        return Ok(AccessScope::allow_all());
    }

    Ok(AccessScope::from_constraints(constraints))
}

/// Compile a single PDP constraint into a `ScopeConstraint`.
///
/// Each predicate becomes a `ScopeFilter`. If any predicate's property
/// is not in `supported_properties`, the entire constraint fails (fail-closed).
fn compile_constraint(
    constraint: &Constraint,
    supported_properties: &[&str],
) -> Result<ScopeConstraint, String> {
    let mut filters = Vec::new();

    for predicate in &constraint.predicates {
        let (property, filter) = match predicate {
            Predicate::Eq(eq) => {
                let value = json_to_scope_value(&eq.value)?;
                (eq.property.as_str(), ScopeFilter::eq(&eq.property, value))
            }
            Predicate::In(p) => {
                let values: Vec<ScopeValue> = p
                    .values
                    .iter()
                    .map(json_to_scope_value)
                    .collect::<Result<_, _>>()?;
                (p.property.as_str(), ScopeFilter::r#in(&p.property, values))
            }
        };

        if !supported_properties.contains(&property) {
            return Err(format!("unsupported property: {property}"));
        }

        filters.push(filter);
    }

    Ok(ScopeConstraint::new(filters))
}

/// Convert a `serde_json::Value` to a `ScopeValue`.
///
/// UUID strings are detected and stored as `ScopeValue::Uuid`;
/// other strings become `ScopeValue::String`.
fn json_to_scope_value(v: &serde_json::Value) -> Result<ScopeValue, String> {
    match v {
        serde_json::Value::String(s) => {
            if let Ok(uuid) = uuid::Uuid::parse_str(s) {
                Ok(ScopeValue::Uuid(uuid))
            } else {
                Ok(ScopeValue::String(s.clone()))
            }
        }
        serde_json::Value::Number(n) => n.as_i64().map(ScopeValue::Int).ok_or_else(|| {
            format!("only integer JSON numbers are supported for scope filters, got: {n}")
        }),
        serde_json::Value::Bool(b) => Ok(ScopeValue::Bool(*b)),
        other => Err(format!(
            "unsupported JSON value type for scope filter: {other}"
        )),
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use crate::constraints::{EqPredicate, InPredicate};
    use crate::models::EvaluationResponseContext;
    use modkit_security::pep_properties;
    use serde_json::json;
    use uuid::Uuid;

    fn uuid(s: &str) -> Uuid {
        Uuid::parse_str(s).unwrap()
    }

    /// Helper: UUID string as `serde_json::Value`.
    fn jid(s: &str) -> serde_json::Value {
        json!(s)
    }

    const T1: &str = "11111111-1111-1111-1111-111111111111";
    const T2: &str = "22222222-2222-2222-2222-222222222222";
    const R1: &str = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";

    const DEFAULT_PROPS: &[&str] = &[pep_properties::OWNER_TENANT_ID, pep_properties::RESOURCE_ID];

    // === Constraint Compilation Matrix Tests ===

    #[test]
    fn no_require_constraints_empty_returns_allow_all() {
        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext::default(),
        };

        let scope = compile_to_access_scope(&response, false, DEFAULT_PROPS).unwrap();
        assert!(scope.is_unconstrained());
    }

    #[test]
    fn no_require_constraints_with_constraints_compiles_them() {
        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext {
                constraints: vec![Constraint {
                    predicates: vec![Predicate::Eq(EqPredicate {
                        property: pep_properties::OWNER_TENANT_ID.to_owned(),
                        value: jid(T1),
                    })],
                }],
                ..Default::default()
            },
        };

        let scope = compile_to_access_scope(&response, false, DEFAULT_PROPS).unwrap();
        assert!(!scope.is_unconstrained());
        assert_eq!(
            scope.all_uuid_values_for(pep_properties::OWNER_TENANT_ID),
            &[uuid(T1)]
        );
    }

    #[test]
    fn decision_true_require_constraints_empty_returns_error() {
        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext::default(),
        };

        let result = compile_to_access_scope(&response, true, DEFAULT_PROPS);
        assert!(matches!(
            result,
            Err(ConstraintCompileError::ConstraintsRequiredButAbsent)
        ));
    }

    // === Constraint Compilation Tests ===

    #[test]
    fn single_tenant_eq_constraint() {
        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext {
                constraints: vec![Constraint {
                    predicates: vec![Predicate::Eq(EqPredicate {
                        property: pep_properties::OWNER_TENANT_ID.to_owned(),
                        value: jid(T1),
                    })],
                }],
                ..Default::default()
            },
        };

        let scope = compile_to_access_scope(&response, true, DEFAULT_PROPS).unwrap();
        assert_eq!(
            scope.all_uuid_values_for(pep_properties::OWNER_TENANT_ID),
            &[uuid(T1)]
        );
        assert!(
            scope
                .all_uuid_values_for(pep_properties::RESOURCE_ID)
                .is_empty()
        );

        // Verify Predicate::Eq produces ScopeFilter::Eq (not In)
        let filter = &scope.constraints()[0].filters()[0];
        assert!(matches!(filter, ScopeFilter::Eq(_)));
    }

    #[test]
    fn multiple_tenants_in_constraint() {
        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext {
                constraints: vec![Constraint {
                    predicates: vec![Predicate::In(InPredicate {
                        property: pep_properties::OWNER_TENANT_ID.to_owned(),
                        values: vec![jid(T1), jid(T2)],
                    })],
                }],
                ..Default::default()
            },
        };

        let scope = compile_to_access_scope(&response, true, DEFAULT_PROPS).unwrap();
        assert_eq!(
            scope.all_uuid_values_for(pep_properties::OWNER_TENANT_ID),
            &[uuid(T1), uuid(T2)]
        );
    }

    #[test]
    fn resource_id_eq_constraint() {
        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext {
                constraints: vec![Constraint {
                    predicates: vec![Predicate::Eq(EqPredicate {
                        property: pep_properties::RESOURCE_ID.to_owned(),
                        value: jid(R1),
                    })],
                }],
                ..Default::default()
            },
        };

        let scope = compile_to_access_scope(&response, true, DEFAULT_PROPS).unwrap();
        assert!(
            scope
                .all_uuid_values_for(pep_properties::OWNER_TENANT_ID)
                .is_empty()
        );
        assert_eq!(
            scope.all_uuid_values_for(pep_properties::RESOURCE_ID),
            &[uuid(R1)]
        );

        // Verify Predicate::Eq produces ScopeFilter::Eq
        let filter = &scope.constraints()[0].filters()[0];
        assert!(matches!(filter, ScopeFilter::Eq(_)));
    }

    #[test]
    fn multiple_constraints_produce_or_scope() {
        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext {
                constraints: vec![
                    Constraint {
                        predicates: vec![Predicate::In(InPredicate {
                            property: pep_properties::OWNER_TENANT_ID.to_owned(),
                            values: vec![jid(T1)],
                        })],
                    },
                    Constraint {
                        predicates: vec![Predicate::In(InPredicate {
                            property: pep_properties::OWNER_TENANT_ID.to_owned(),
                            values: vec![jid(T2)],
                        })],
                    },
                ],
                ..Default::default()
            },
        };

        let scope = compile_to_access_scope(&response, true, DEFAULT_PROPS).unwrap();
        // Each constraint is a separate ScopeConstraint (ORed)
        assert_eq!(scope.constraints().len(), 2);
        // Both tenants accessible
        assert!(scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uuid(T1)));
        assert!(scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uuid(T2)));
    }

    #[test]
    fn unknown_predicate_fails_constraint() {
        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext {
                constraints: vec![Constraint {
                    predicates: vec![Predicate::Eq(EqPredicate {
                        property: "unknown_property".to_owned(),
                        value: jid(T1),
                    })],
                }],
                ..Default::default()
            },
        };

        let result = compile_to_access_scope(&response, true, DEFAULT_PROPS);
        assert!(matches!(
            result,
            Err(ConstraintCompileError::AllConstraintsFailed { .. })
        ));
    }

    #[test]
    fn mixed_known_and_unknown_constraints() {
        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext {
                constraints: vec![
                    // This constraint has an unknown property → fails
                    Constraint {
                        predicates: vec![Predicate::Eq(EqPredicate {
                            property: "group_id".to_owned(),
                            value: jid(T1),
                        })],
                    },
                    // This constraint is valid → succeeds
                    Constraint {
                        predicates: vec![Predicate::In(InPredicate {
                            property: pep_properties::OWNER_TENANT_ID.to_owned(),
                            values: vec![jid(T2)],
                        })],
                    },
                ],
                ..Default::default()
            },
        };

        // Should succeed — the second constraint compiled
        let scope = compile_to_access_scope(&response, true, DEFAULT_PROPS).unwrap();
        assert_eq!(
            scope.all_uuid_values_for(pep_properties::OWNER_TENANT_ID),
            &[uuid(T2)]
        );
    }

    #[test]
    fn both_tenant_and_resource_in_single_constraint() {
        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext {
                constraints: vec![Constraint {
                    predicates: vec![
                        Predicate::In(InPredicate {
                            property: pep_properties::OWNER_TENANT_ID.to_owned(),
                            values: vec![jid(T1)],
                        }),
                        Predicate::Eq(EqPredicate {
                            property: pep_properties::RESOURCE_ID.to_owned(),
                            value: jid(R1),
                        }),
                    ],
                }],
                ..Default::default()
            },
        };

        let scope = compile_to_access_scope(&response, true, DEFAULT_PROPS).unwrap();
        // Single constraint with both properties (AND)
        assert_eq!(scope.constraints().len(), 1);
        assert_eq!(
            scope.all_uuid_values_for(pep_properties::OWNER_TENANT_ID),
            &[uuid(T1)]
        );
        assert_eq!(
            scope.all_uuid_values_for(pep_properties::RESOURCE_ID),
            &[uuid(R1)]
        );
    }

    #[test]
    fn mixed_shape_constraints_produce_or_scope() {
        // T1+R1 (AND) OR T2 — two different-shaped constraints
        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext {
                constraints: vec![
                    Constraint {
                        predicates: vec![
                            Predicate::In(InPredicate {
                                property: pep_properties::OWNER_TENANT_ID.to_owned(),
                                values: vec![jid(T1)],
                            }),
                            Predicate::Eq(EqPredicate {
                                property: pep_properties::RESOURCE_ID.to_owned(),
                                value: jid(R1),
                            }),
                        ],
                    },
                    Constraint {
                        predicates: vec![Predicate::In(InPredicate {
                            property: pep_properties::OWNER_TENANT_ID.to_owned(),
                            values: vec![jid(T2)],
                        })],
                    },
                ],
                ..Default::default()
            },
        };

        let scope = compile_to_access_scope(&response, true, DEFAULT_PROPS).unwrap();
        assert_eq!(scope.constraints().len(), 2);
        // First constraint has 2 filters (AND), second has 1 filter
        assert_eq!(scope.constraints()[0].filters().len(), 2);
        assert_eq!(scope.constraints()[1].filters().len(), 1);
    }

    #[test]
    fn supported_properties_validation() {
        // Only owner_tenant_id is supported — id should fail
        let limited_props: &[&str] = &[pep_properties::OWNER_TENANT_ID];

        let response = EvaluationResponse {
            decision: true,
            context: EvaluationResponseContext {
                constraints: vec![Constraint {
                    predicates: vec![Predicate::Eq(EqPredicate {
                        property: pep_properties::RESOURCE_ID.to_owned(),
                        value: jid(R1),
                    })],
                }],
                ..Default::default()
            },
        };

        let result = compile_to_access_scope(&response, true, limited_props);
        assert!(matches!(
            result,
            Err(ConstraintCompileError::AllConstraintsFailed { .. })
        ));
    }
}