inferadb 0.1.5

Official Rust SDK for InferaDB
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
# Debugging Authorization

Techniques for diagnosing and resolving authorization issues.

## Quick Diagnosis Checklist

When a user reports "I can't access X", work through this checklist:

1. **Verify identity** - Is the subject correct? (`user:alice` vs `user:Alice`)
2. **Check relationship exists** - Does the expected relationship exist?
3. **Verify permission path** - Does the schema define a path from relationship to permission?
4. **Check hierarchy** - If using parent resources, is the chain complete?
5. **Inspect ABAC context** - Are runtime conditions being met?

## Using explain_permission()

The `explain_permission()` API shows why access was granted or denied.

### Basic Usage

```rust
let explanation = vault
    .explain_permission("user:alice", "edit", "document:readme")
    .await?;

println!("Allowed: {}", explanation.allowed);
println!("Reason: {:?}", explanation.reason);

if explanation.allowed {
    println!("Access granted via:");
    for step in &explanation.resolution_path {
        println!("  -> {}", step);
    }
} else {
    println!("Denial reasons:");
    for reason in &explanation.denial_reasons {
        println!("  - {}", reason);
    }
}
```

### Example Output

```text
Allowed: true
Access granted via:
  -> document:readme#editor <- user:alice
  -> edit = editor | owner
```

```text
Allowed: false
Denial reasons:
  - No relationship found: user:alice -> document:secret
  - Permission 'edit' requires: editor | owner
  - Checked relations: viewer, editor, owner - none matched
```

## Decision Traces

For complex permission structures, use decision traces to see the full evaluation tree.

### Enable Tracing

```rust
let decision = vault
    .check("user:alice", "edit", "document:readme")
    .trace(true)
    .await?;

println!("Allowed: {}", decision.allowed);

if let Some(trace) = &decision.trace {
    // Render as tree
    println!("{}", trace.render_tree());
}
```

### Trace Output

```text
edit (ALLOWED)
├── editor (NOT_FOUND)
│   └── Direct lookup: user:alice -> document:readme#editor ✗
├── owner (FOUND)
│   └── Direct lookup: user:alice -> document:readme#owner ✓
└── parent->edit (NOT_EVALUATED)
    └── Skipped: already satisfied by 'owner'
```

### Analyzing Traces

```rust
if let Some(trace) = &decision.trace {
    // Find what granted access
    let satisfied = trace.find_satisfied_paths();
    for path in satisfied {
        println!("Granted via: {}", path.description());
    }

    // Find failed paths (useful for debugging denials)
    let failed = trace.find_failed_paths();
    for path in failed {
        println!("Failed path: {} - {}", path.description(), path.failure_reason());
    }

    // Find slow operations
    let slow = trace.find_nodes_slower_than(Duration::from_millis(10));
    for node in slow {
        println!("Slow: {:?} took {:?}", node.operation, node.metrics.duration);
    }
}
```

## Common Issues

### Issue: Relationship Exists But Access Denied

**Symptoms**: You've written a relationship, but `check()` returns `false`.

**Diagnosis**:

```rust
// 1. Verify the relationship exists
let relationships = vault
    .relationships()
    .list()
    .subject("user:alice")
    .resource("document:readme")
    .collect()
    .await?;

println!("Found relationships: {:?}", relationships);

// 2. Check the exact permission being tested
let explanation = vault
    .explain_permission("user:alice", "edit", "document:readme")
    .await?;

println!("Explanation: {:?}", explanation);
```

**Common Causes**:

1. **Wrong relation name**: Wrote `viewer` but checking `edit` permission
2. **Case sensitivity**: `user:Alice` != `user:alice`
3. **Missing permission definition**: Schema doesn't include the relation in permission
4. **Stale read**: Check consistency tokens for read-after-write

```rust
// Ensure read-after-write consistency
let token = vault.relationships()
    .write(Relationship::new("document:readme", "editor", "user:alice"))
    .await?
    .consistency_token;

// Use token for subsequent read
let allowed = vault
    .check("user:alice", "edit", "document:readme")
    .at_least_as_fresh_as(&token)
    .await?;
```

### Issue: Inherited Permission Not Working

**Symptoms**: Parent has permission, but child resource check fails.

**Diagnosis**:

```rust
// Check the parent relationship exists
let parent = vault
    .relationships()
    .list()
    .resource("document:readme")
    .relation("parent")
    .collect()
    .await?;

println!("Parent: {:?}", parent);

// Check parent permission directly
let parent_allowed = vault
    .check("user:alice", "edit", "folder:docs")
    .await?;

println!("Parent edit permission: {}", parent_allowed);
```

**Common Causes**:

1. **Missing parent relationship**: Document not linked to folder
2. **Wrong parent relation name**: Schema uses `folder` but you wrote `parent`
3. **Schema missing inheritance**: Permission doesn't include `parent->edit`

### Issue: Group Membership Not Resolving

**Symptoms**: User is in group, group has access, but user check fails.

**Diagnosis**:

```rust
// Verify group membership
let in_group = vault
    .check("user:alice", "member", "group:engineering")
    .await?;
println!("In group: {}", in_group);

// Verify group has access
let group_access = vault
    .check("group:engineering#member", "view", "document:readme")
    .await?;
println!("Group has access: {}", group_access);

// Check relationship is using correct userset syntax
let rels = vault
    .relationships()
    .list()
    .resource("document:readme")
    .collect()
    .await?;

for rel in &rels {
    println!("{} -> {} -> {}", rel.subject, rel.relation, rel.resource);
}
```

**Common Causes**:

1. **Wrong userset syntax**: Used `group:engineering` instead of `group:engineering#member`
2. **Missing member relation**: User not added to group
3. **Schema type mismatch**: Relation expects `group#member` but got `group`

### Issue: ABAC Context Not Evaluated

**Symptoms**: Condition should be met, but access is denied.

**Diagnosis**:

```rust
// Check with explicit context
let allowed = vault
    .check("user:alice", "view_confidential", "document:secret")
    .with_context(Context::new()
        .insert("ip_in_allowlist", true)
        .insert("mfa_verified", true))
    .trace(true)
    .await?;

if let Some(trace) = &allowed.trace {
    // Look for condition evaluation
    for node in trace.all_nodes() {
        if let Some(condition) = &node.condition {
            println!("Condition '{}': {}", condition.expression, condition.result);
        }
    }
}
```

**Common Causes**:

1. **Missing context key**: Schema expects `ip_address` but you passed `ip`
2. **Type mismatch**: Schema expects boolean but got string
3. **Context not passed**: Forgot `.with_context()` on the check

## Logging Strategies

### Structured Logging for Authorization

```rust
use tracing::{info, warn, error, instrument};

#[instrument(skip(vault), fields(request_id))]
async fn check_access(
    vault: &VaultClient,
    subject: &str,
    permission: &str,
    resource: &str,
) -> Result<bool, Error> {
    let result = vault.check(subject, permission, resource).await;

    match &result {
        Ok(allowed) => {
            info!(
                subject = subject,
                permission = permission,
                resource = resource,
                allowed = allowed,
                "Authorization check completed"
            );
        }
        Err(e) => {
            error!(
                subject = subject,
                permission = permission,
                resource = resource,
                error = %e,
                request_id = ?e.request_id(),
                "Authorization check failed"
            );
        }
    }

    result
}
```

### Audit Logging for Compliance

```rust
async fn audited_check(
    vault: &VaultClient,
    audit_log: &AuditLog,
    actor: &str,
    subject: &str,
    permission: &str,
    resource: &str,
) -> Result<bool, Error> {
    let start = std::time::Instant::now();
    let result = vault.check(subject, permission, resource).await;
    let duration = start.elapsed();

    audit_log.record(AuditEntry {
        timestamp: Utc::now(),
        actor: actor.to_string(),
        subject: subject.to_string(),
        permission: permission.to_string(),
        resource: resource.to_string(),
        allowed: result.as_ref().ok().copied(),
        error: result.as_ref().err().map(|e| e.to_string()),
        duration_ms: duration.as_millis() as u64,
    }).await;

    result
}
```

## Debugging in Production

### Request ID Tracking

Every error includes a request ID for support:

```rust
match vault.check(subject, permission, resource).await {
    Err(e) => {
        // Log request ID for support tickets
        error!(
            request_id = ?e.request_id(),
            error = %e,
            "Authorization failed"
        );

        // Include in error response (for API consumers)
        return Err(ApiError {
            message: "Authorization check failed".into(),
            request_id: e.request_id().map(|id| id.to_string()),
        });
    }
    Ok(allowed) => { /* ... */ }
}
```

### Sampling Explain Calls

In production, selectively run explain for debugging:

```rust
async fn check_with_sampling(
    vault: &VaultClient,
    subject: &str,
    permission: &str,
    resource: &str,
    sample_rate: f64,
) -> Result<bool, Error> {
    let allowed = vault.check(subject, permission, resource).await?;

    // Sample explain calls for denied access
    if !allowed && rand::random::<f64>() < sample_rate {
        if let Ok(explanation) = vault
            .explain_permission(subject, permission, resource)
            .await
        {
            tracing::debug!(
                subject = subject,
                permission = permission,
                resource = resource,
                explanation = ?explanation,
                "Sampled denial explanation"
            );
        }
    }

    Ok(allowed)
}
```

### Health Check with Authorization Test

```rust
async fn authz_health_check(vault: &VaultClient) -> Result<(), Error> {
    // Use a known-good check to verify service health
    let result = vault
        .check("healthcheck:probe", "access", "system:health")
        .await;

    match result {
        Ok(_) => Ok(()),
        Err(e) if e.is_retriable() => {
            tracing::warn!(error = %e, "Authorization service degraded");
            Err(e)
        }
        Err(e) => {
            tracing::error!(error = %e, "Authorization service unhealthy");
            Err(e)
        }
    }
}
```

## Testing and Validation

### Unit Testing Authorization Logic

```rust
use inferadb::testing::InMemoryClient;

#[tokio::test]
async fn test_editor_can_edit() {
    let client = InMemoryClient::new();

    // Setup
    client.write_batch([
        Relationship::new("document:test", "editor", "user:alice"),
    ]).await.unwrap();

    // Test
    assert!(client.check("user:alice", "edit", "document:test").await.unwrap());
    assert!(!client.check("user:bob", "edit", "document:test").await.unwrap());
}

#[tokio::test]
async fn test_hierarchy_inheritance() {
    let client = InMemoryClient::new();

    // Setup hierarchy
    client.write_batch([
        Relationship::new("folder:root", "editor", "user:alice"),
        Relationship::new("document:readme", "parent", "folder:root"),
    ]).await.unwrap();

    // Test inheritance
    assert!(client.check("user:alice", "edit", "document:readme").await.unwrap());
}
```

### Simulation Testing

Test changes before deploying:

```rust
// Test new schema against existing relationships
let simulation = vault
    .simulate()
    .with_schema(include_str!("schema_v2.ipl"))
    .build();

// Run critical checks against simulation
let checks = [
    ("user:admin", "manage", "organization:main"),
    ("user:alice", "edit", "document:important"),
];

for (subject, permission, resource) in checks {
    let prod = vault.check(subject, permission, resource).await?;
    let sim = simulation.check(subject, permission, resource).await?;

    if prod != sim {
        panic!(
            "Schema change affects {} {} {}: {} -> {}",
            subject, permission, resource, prod, sim
        );
    }
}
```

## Tools Reference

| Tool                     | Use Case                                 |
| ------------------------ | ---------------------------------------- |
| `explain_permission()`   | Understand why access was granted/denied |
| `check().trace(true)`    | Get detailed decision tree               |
| `relationships().list()` | Verify relationships exist               |
| `simulate()`             | Test schema changes safely               |
| Request ID               | Debug production issues with support     |

## Best Practices

1. **Use explain first** - Before diving deep, use `explain_permission()` for quick diagnosis
2. **Check relationships** - Verify the relationship actually exists with the exact values
3. **Watch for case sensitivity** - Entity IDs are case-sensitive
4. **Log request IDs** - Essential for production debugging
5. **Test with simulation** - Validate schema changes before deploying
6. **Use structured logging** - Include subject, permission, resource in all auth logs
7. **Sample explain in production** - Get visibility into denials without overhead