oxify-authz 0.1.0

ReBAC (Relationship-Based Access Control) authorization engine - Google Zanzibar implementation
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
# OxiFY AuthZ - Best Practices & Security Patterns

This guide provides production-ready patterns, security recommendations, and anti-patterns to avoid when implementing relationship-based access control (ReBAC) with oxify-authz.

---

## Table of Contents

1. [Security Patterns]#security-patterns
2. [Anti-Patterns to Avoid]#anti-patterns-to-avoid
3. [Performance Optimization]#performance-optimization
4. [Multi-Tenancy Best Practices]#multi-tenancy-best-practices
5. [Monitoring & Observability]#monitoring--observability
6. [Testing Strategies]#testing-strategies
7. [Incident Response]#incident-response

---

## Security Patterns

### 1. Principle of Least Privilege

**✅ DO:**
```rust
// Grant minimal permissions needed
engine.write_tuple(RelationTuple::new(
    "document", "viewer", "123",
    Subject::User("alice".to_string()),
)).await?;

// Use hierarchical permissions for automatic inheritance
engine.write_tuple(RelationTuple::new(
    "folder", "viewer", "reports",
    Subject::User("alice".to_string()),
)).await?;
```

**❌ DON'T:**
```rust
// Avoid granting admin rights when only read access is needed
engine.write_tuple(RelationTuple::new(
    "document", "admin", "123",  // Too permissive!
    Subject::User("alice".to_string()),
)).await?;
```

### 2. Time-Limited Access

**✅ DO:**
```rust
use chrono::{Utc, Duration};
use oxify_authz::{RelationTuple, RelationshipCondition};

// Grant temporary access that expires
let expires_at = Utc::now() + Duration::hours(24);
let tuple = RelationTuple::with_condition(
    "document", "123", "viewer",
    Subject::User("contractor".to_string()),
    RelationshipCondition::TimeWindow {
        not_before: None,
        not_after: Some(expires_at),
    },
);
engine.write_tuple(tuple).await?;
```

**❌ DON'T:**
```rust
// Avoid permanent access for temporary needs
engine.write_tuple(RelationTuple::new(
    "document", "viewer", "123",
    Subject::User("contractor".to_string()),  // No expiration!
)).await?;
```

### 3. Audit Trail Requirements

**✅ DO:**
```rust
use oxify_authz::{AuditLogger, AuditConfig};

// Enable comprehensive audit logging
let audit_config = AuditConfig {
    sample_rate: 1.0,  // Log 100% of checks in sensitive systems
    log_denied: true,  // Always log denials
    log_mutations: true,  // Track all permission changes
    ..Default::default()
};

let audit_logger = AuditLogger::new(pool.clone(), audit_config);
engine.set_audit_logger(Some(audit_logger));

// Query audit trail for compliance
let report = audit_logger.compliance_report(
    start_time,
    end_time,
    Some("user:admin"),
).await?;
```

**❌ DON'T:**
```rust
// Don't disable audit logging in production
let config = AuditConfig {
    sample_rate: 0.0,  // No logging! Security risk!
    ..Default::default()
};
```

### 4. Defense in Depth

**✅ DO:**
```rust
// Layer 1: API authentication (JWT, API key)
// Layer 2: ReBAC authorization check
let allowed = engine.check(CheckRequest {
    namespace: "document".to_string(),
    object_id: doc_id,
    relation: "edit".to_string(),
    subject: Subject::User(user_id),
    context: Some(RequestContext::new()
        .with_client_ip(client_ip)
        .with_attribute("device_type", "laptop")),
}).await?;

// Layer 3: Application-level validation
if allowed.allowed {
    // Layer 4: Database-level row security (if available)
    update_document(doc_id, changes).await?;
}
```

### 5. Conditional Access Policies

**✅ DO:**
```rust
use std::net::IpAddr;

// Restrict access by IP range (e.g., corporate network)
let tuple = RelationTuple::with_condition(
    "admin_panel", "root", "access",
    Subject::User("admin".to_string()),
    RelationshipCondition::IpAddress {
        allowed_ips: vec![
            "10.0.0.0/8".to_string(),      // Internal network
            "192.168.1.0/24".to_string(),  // VPN
        ],
    },
);

// Combine multiple conditions
let tuple = RelationTuple::with_condition(
    "financial_data", "quarterly_reports", "view",
    Subject::User("auditor".to_string()),
    RelationshipCondition::All {
        conditions: vec![
            RelationshipCondition::TimeWindow {
                not_before: Some(audit_start),
                not_after: Some(audit_end),
            },
            RelationshipCondition::Attribute {
                key: "mfa_verified".to_string(),
                value: "true".to_string(),
            },
        ],
    },
);
```

---

## Anti-Patterns to Avoid

### 1. ❌ Over-Granting Permissions

**Problem:**
```rust
// Granting admin access instead of specific permissions
for user in all_users {
    engine.write_tuple(RelationTuple::new(
        "organization", "admin", "acme-corp",
        Subject::User(user),
    )).await?;
}
```

**Solution:**
```rust
// Use specific roles and groups
for user in managers {
    engine.write_tuple(RelationTuple::new(
        "team", "manager", "engineering",
        Subject::User(user),
    )).await?;
}

for user in engineers {
    engine.write_tuple(RelationTuple::new(
        "team", "member", "engineering",
        Subject::User(user),
    )).await?;
}
```

### 2. ❌ Bypassing Authorization Checks

**Problem:**
```rust
// Directly querying database without authorization
let document = db.query_document(doc_id).await?;
```

**Solution:**
```rust
// Always check permissions first
let allowed = engine.check(CheckRequest::new(
    "document", doc_id, "view",
    Subject::User(user_id),
)).await?;

if !allowed.allowed {
    return Err(AuthzError::PermissionDenied(
        format!("User {} cannot view document {}", user_id, doc_id)
    ));
}

let document = db.query_document(doc_id).await?;
```

### 3. ❌ Storing Sensitive Data in Tuple IDs

**Problem:**
```rust
// Exposing sensitive data in object IDs
engine.write_tuple(RelationTuple::new(
    "medical_record",
    "viewer",
    "patient-john-doe-ssn-123-45-6789",  // PII in ID!
    Subject::User("doctor".to_string()),
)).await?;
```

**Solution:**
```rust
// Use opaque identifiers
engine.write_tuple(RelationTuple::new(
    "medical_record",
    "viewer",
    "mrn-uuid-a1b2c3d4",  // Anonymous ID
    Subject::User("doctor".to_string()),
)).await?;
```

### 4. ❌ Ignoring Denial Events

**Problem:**
```rust
// Silently failing authorization checks
let allowed = engine.check(request).await?;
if !allowed.allowed {
    // No logging, no alert - attacker can probe freely
    return Ok(());
}
```

**Solution:**
```rust
let allowed = engine.check(request).await?;
if !allowed.allowed {
    // Log denial for security monitoring
    warn!(
        "Authorization denied: user={} resource={} action={}",
        request.subject, request.object_id, request.relation
    );

    // Check for anomalies
    if let Some(anomaly) = anomaly_detector.check_anomaly(&event) {
        alert_security_team(anomaly);
    }

    return Err(AuthzError::PermissionDenied("Access denied".to_string()));
}
```

### 5. ❌ Hardcoding Permission Logic

**Problem:**
```rust
// Hardcoded business logic in application
if user.role == "admin" || user.id == resource.owner_id {
    allow_access();
}
```

**Solution:**
```rust
// Centralize in ReBAC engine
let allowed = engine.check(CheckRequest::new(
    "resource", resource.id, "edit",
    Subject::User(user.id),
)).await?;

if allowed.allowed {
    allow_access();
}
```

---

## Performance Optimization

### 1. Batch Operations

**✅ DO:**
```rust
// Batch multiple checks into single query
let subjects = vec![
    Subject::User("alice".to_string()),
    Subject::User("bob".to_string()),
    Subject::User("charlie".to_string()),
];

let results = engine.batch_check(
    "document",
    "123",
    "viewer",
    subjects,
).await?;
```

**❌ DON'T:**
```rust
// Individual queries in a loop (N+1 problem)
for user in users {
    let allowed = engine.check(CheckRequest::new(
        "document", "123", "viewer",
        Subject::User(user),
    )).await?;  // Separate DB query each time!
}
```

### 2. Cache Warming

**✅ DO:**
```rust
use oxify_authz::warming::{WarmingStrategy, WarmingConfig};

// Pre-load hot paths on startup
let warming_config = WarmingConfig {
    strategies: vec![
        WarmingStrategy::HotPath {
            namespaces: vec!["document".to_string(), "team".to_string()],
            relations: vec!["viewer".to_string(), "member".to_string()],
        },
        WarmingStrategy::CriticalTenant {
            tenant_ids: vec!["enterprise-customer-1".to_string()],
        },
    ],
    ..Default::default()
};

engine.warm_cache(warming_config).await?;
```

### 3. Use Leopard Index for Transitive Checks

**✅ DO:**
```rust
// Enable Leopard index for O(1) reachability checks
let hybrid_engine = HybridRebacEngine::new(
    pool.clone(),
    PermissionCache::new(10000),
    Some(LeopardIndex::new()),  // Enable reachability index
).await?;

// Transitive checks are now O(1) instead of graph traversal
let allowed = hybrid_engine.check(CheckRequest::new(
    "organization", "acme-corp", "member",
    Subject::User("alice".to_string()),
)).await?;  // Fast lookup via index
```

---

## Multi-Tenancy Best Practices

### 1. Strict Tenant Isolation

**✅ DO:**
```rust
use oxify_authz::multitenancy::{MultiTenantEngine, TenantContext};

// Always use tenant-aware operations
let tenant_ctx = TenantContext::new("tenant-123".to_string());
let engine = MultiTenantEngine::new(base_engine, tenant_ctx);

// All operations are automatically scoped to tenant
engine.write_tuple(tuple).await?;  // Tenant ID added automatically
```

**❌ DON'T:**
```rust
// Manually managing tenant IDs (error-prone)
let tuple = RelationTuple::new(
    &format!("tenant_{}_document", tenant_id),  // Fragile!
    "viewer",
    "123",
    Subject::User(user_id),
);
```

### 2. Per-Tenant Quotas

**✅ DO:**
```rust
// Enforce resource limits per tenant
let quota_config = QuotaConfig {
    max_tuples: 100_000,
    max_checks_per_minute: 10_000,
    max_subjects_per_resource: 1_000,
};

engine.set_quota(tenant_id, quota_config).await?;
```

### 3. Cross-Tenant Access Audit

**✅ DO:**
```rust
// Explicitly track cross-tenant sharing
if source_tenant != target_tenant {
    audit_logger.log_cross_tenant_access(
        source_tenant,
        target_tenant,
        resource_id,
        user_id,
    ).await?;
}
```

---

## Monitoring & Observability

### 1. Metrics Collection

**✅ DO:**
```rust
use oxify_authz::metrics::AuthzMetrics;

let metrics = engine.get_metrics();
println!("Cache hit rate: {:.2}%", metrics.cache_hit_rate() * 100.0);
println!("Avg check latency: {:?}", metrics.avg_check_latency());
println!("Total checks: {}", metrics.total_checks);

// Export to Prometheus
let json = metrics.to_json()?;
prometheus_exporter.export(json);
```

### 2. Anomaly Detection

**✅ DO:**
```rust
use oxify_authz::anomaly::{AnomalyDetector, AnomalyConfig};

let anomaly_config = AnomalyConfig {
    min_baseline_events: 100,
    zscore_threshold: 3.0,
    enable_privilege_escalation: true,
    ..Default::default()
};

let mut detector = AnomalyDetector::new(anomaly_config);

// Check each access event
let event = AccessEvent {
    subject_id: user_id.to_string(),
    resource_id: resource_id.to_string(),
    relation: relation.to_string(),
    granted: allowed,
    timestamp: SystemTime::now(),
};

if let Some(anomaly) = detector.check_anomaly(&event) {
    match anomaly.severity {
        s if s > 0.8 => alert_security_team_urgent(anomaly),
        s if s > 0.5 => log_security_warning(anomaly),
        _ => log_info(anomaly),
    }
}
```

### 3. Permission Recommendations

**✅ DO:**
```rust
use oxify_authz::recommendations::{RecommendationEngine, RecommendationConfig};

// Regularly analyze permission usage
let rec_engine = RecommendationEngine::new(RecommendationConfig::default());

// Track usage
rec_engine.add_tuple(&tuple);
rec_engine.record_access(user_id, resource_id, relation);

// Generate optimization recommendations monthly
let recommendations = rec_engine.generate_recommendations();
for rec in recommendations.iter().filter(|r| r.priority >= Priority::High) {
    println!("[{}] {}", rec.priority, rec.description);
    println!("  Action: {}", rec.suggested_action);
    println!("  Impact: {}", rec.estimated_impact);
}
```

---

## Testing Strategies

### 1. Property-Based Testing

**✅ DO:**
```rust
use oxify_authz::proptest_helpers::*;
use proptest::prelude::*;

proptest! {
    #[test]
    fn test_permission_symmetry(
        tuple in relation_tuple_strategy()
    ) {
        // If we write a tuple, we should be able to read it back
        runtime.block_on(async {
            engine.write_tuple(tuple.clone()).await?;
            let result = engine.check(CheckRequest::new(
                &tuple.namespace,
                &tuple.object_id,
                &tuple.relation,
                tuple.subject,
            )).await?;
            assert!(result.allowed);
        });
    }
}
```

### 2. Chaos Engineering

**✅ DO:**
```rust
use oxify_authz::chaos::{ChaosTest, FailureScenario};

// Test resilience to database failures
let chaos = ChaosTest::new(engine.clone());
chaos.inject_failure(FailureScenario::DatabaseDown).await?;

// System should gracefully degrade (use cache)
let result = engine.check(request).await;
assert!(result.is_ok() || result.err().unwrap().is_retriable());
```

### 3. Load Testing

**✅ DO:**
```bash
# Use included k6 load test
cd loadtest
k6 run --vus 100 --duration 5m authz_load_test.js

# Verify performance targets
# - p95 < 100ms for cached checks
# - p99 < 500ms for uncached checks
# - Throughput > 10,000 checks/sec
```

---

## Incident Response

### 1. Permission Breach Response

**Immediate Actions:**
```rust
// 1. Revoke compromised permissions
engine.delete_tuple(&compromised_tuple).await?;

// 2. Audit who had access
let audit_events = audit_logger.query_by_resource(
    "document",
    compromised_doc_id,
    incident_timeframe,
).await?;

// 3. Check for unauthorized access
for event in audit_events {
    if !event.allowed && event.timestamp > breach_time {
        investigate_denial_attempt(event);
    }
}

// 4. Invalidate caches
engine.invalidate_cache_for_resource("document", compromised_doc_id).await?;
```

### 2. Privilege Escalation Detection

**Response Playbook:**
```rust
// Automated response to privilege escalation attempts
if anomaly.anomaly_type == AnomalyType::PrivilegeEscalation {
    // 1. Temporarily disable account
    security_service.suspend_user(event.subject_id).await?;

    // 2. Alert SOC team
    alert_security_team(format!(
        "Privilege escalation detected: {} attempted {} access to {}",
        event.subject_id, event.relation, event.resource_id
    ));

    // 3. Freeze related permissions
    engine.freeze_subject_permissions(event.subject_id).await?;

    // 4. Initiate investigation workflow
    incident_tracker.create_ticket(
        IncidentType::PrivilegeEscalation,
        anomaly,
    ).await?;
}
```

### 3. Performance Degradation

**Diagnosis Steps:**
```rust
// 1. Check metrics
let metrics = engine.get_metrics();
if metrics.avg_check_latency() > Duration::from_millis(100) {
    // 2. Analyze cache performance
    println!("Cache hit rate: {:.2}%", metrics.cache_hit_rate() * 100.0);

    // 3. Check database load
    let pool_stats = engine.get_pool_stats().await?;
    println!("Active connections: {}/{}",
        pool_stats.active_connections,
        pool_stats.max_connections
    );

    // 4. Review slow queries
    let slow_queries = engine.get_slow_queries(Duration::from_secs(1)).await?;

    // 5. Scale horizontally if needed
    if pool_stats.active_connections >= pool_stats.max_connections * 0.9 {
        scale_out_read_replicas().await?;
    }
}
```

---

## Summary Checklist

### Security
- [ ] Principle of least privilege enforced
- [ ] Time-limited access for temporary permissions
- [ ] Audit logging enabled (100% for sensitive operations)
- [ ] Conditional access policies for sensitive resources
- [ ] Regular permission reviews scheduled

### Performance
- [ ] Batch operations used for multiple checks
- [ ] Cache warming configured for hot paths
- [ ] Leopard index enabled for transitive checks
- [ ] Connection pooling optimized
- [ ] Load testing performed

### Operations
- [ ] Monitoring and alerting configured
- [ ] Anomaly detection enabled
- [ ] Incident response playbooks documented
- [ ] Regular backup and recovery tested
- [ ] Multi-tenancy isolation verified

### Development
- [ ] Property-based tests written
- [ ] Chaos engineering tests passed
- [ ] Integration tests cover critical paths
- [ ] Documentation up to date
- [ ] Code review checklist includes authz verification

---

**Last Updated:** 2026-01-19
**Version:** 1.0
**Maintainer:** OxiFY Authorization Team