cedrus-core 0.2.0

Business logic and authorization engine for Cedrus.
Documentation
# Cedrus Core

Business logic and authorization engine for Cedrus.

## Overview

`cedrus-core` is the core library that implements the Cedar Policy authorization engine with multi-tenant support. It provides:

- **Multi-project isolation**: Each project has its own schemas, entities, policies, and templates
- **Authorization engine**: Real-time policy evaluation using Cedar
- **Caching layer**: Fast in-memory access powered by DashMap
- **Database abstraction**: Pluggable storage backend powered by Nitrite DB (`mango-query-rs`)
- **Thread-safe operations**: Concurrent access using DashMap and async Tokio runtime

## Architecture

### Core Components

```text
┌─────────────────────────────────────────────────────────┐
│                    Cedrus Core                          │
├─────────────────────────────────────────────────────────┤
│  Authorization Engine (Cedar Policy Evaluation)         │
├─────────────────────────────────────────────────────────┤
│  Cache Layer (DashMap In-Memory Cache)                  │
├─────────────────────────────────────────────────────────┤
│  Database Layer (Nitrite DB / mango-query-rs)           │
└─────────────────────────────────────────────────────────┘
```

### Storage Traits

The library defines key traits for storage and caching:

#### Database Trait (`crate::db::Database`)

Persists Cedar policies, entities, schemas, templates, template links, and projects:

- **Implementation**: `NitriteDb` (embedded document storage)
- **Operations**: CRUD for projects, schemas, entities, policies, templates, template links, API keys
- **Query support**: MangoQuery filtering (`mango-query-rs`) and pagination

#### Cache Trait (`crate::cache::Cache`)

Provides fast in-memory access to authorization data:

- **Implementation**: `DashMapCache`
- **Purpose**: Reduce database lookups and improve authorization evaluation performance
- **Scope**: Per-project caching of schemas, entities, policies, and templates

## Multi-Tenant Model

### Admin Project

Cedrus uses Cedar policies to control access to itself:

- **Project ID**: `00000000-0000-0000-0000-000000000000` (nil UUID)
- **Purpose**: Manages users, projects, and administrative access
- **Entities**: 
  - `Cedrus::User`: Represents users
  - `Cedrus::Project`: Represents tenant projects
  - `Cedrus::Group`: User groups (e.g., "Admins")
  - `Cedrus::ApiKey`: Admin and project API keys

### User Projects

Each project is an isolated tenant with:

- **Unique ID**: UUID v7
- **API Key**: Base64-encoded key for service-to-service authentication
- **Owner**: User entity who owns the project
- **Roles**: Template-based role assignments
- **Isolated data**: Own schemas, entities, policies, and templates

### Authorization Flow

1. **Authentication**: User authenticates via OIDC (JWT token) or API key
2. **Token mapping**: Map token claims to `EntityUid`, parent groups, and entity attributes
3. **Admin check**: Verify if user is in "Admins" group or holds admin API key
4. **Project authorization**: Evaluate Cedar policies in Admin Project
5. **Resource authorization**: Evaluate Cedar policies in target project

## Key Features

### Real-Time Authorization

```rust,ignore
// Check if principal can perform action on resource
let response = cedrus.is_authorized(
    &project_id,
    principal,  // EntityUid
    action,     // EntityUid
    resource,   // EntityUid
    context,    // Option<Context>
    entities,   // Vec<Entity>
).await?;

match response.decision {
    Decision::Allow => { /* authorized */ },
    Decision::Deny => { /* forbidden */ },
}
```

### Batch Authorization

```rust,ignore
// Check multiple requests concurrently
let requests = vec![
    Request { principal: p1, action: a1, resource: r1, context: None },
    Request { principal: p2, action: a2, resource: r2, context: None },
];

let responses = cedrus.is_authorized_batch(&project_id, requests, entities).await?;
```

### Entity Hierarchy

Entities support parent relationships for group membership (e.g. OIDC `cognito:groups` mapped to `Group::"X"`):

```rust,ignore
let mut parents = HashSet::new();
parents.insert(EntityUid::new("Cedrus::Group".to_string(), "Admins".to_string()));

let entity = Entity::new(
    EntityUid::new("Cedrus::User".to_string(), "alice".to_string()),
    attrs,
    parents,
);
```

### Policy Templates

Reusable policy patterns with slots:

```rust,ignore
// Template with ?principal and ?resource slots
let template = Template { /* ... */ };

// Link template to specific entities
let link = TemplateLink {
    template_id: "AdminRole".into(),
    new_id: "alice-admin".into(),
    values: HashMap::from([
        (SlotId::Principal, EntityValue::EntityUid(alice)),
        (SlotId::Resource, EntityValue::EntityUid(project)),
    ]),
};
```

## Initialization

```rust,ignore
use cedrus_core::{
    cedrus::Cedrus,
    db::Database,
    cache::Cache,
};

// 1. Initialize DB and Cache backends
let db = Box::new(nitritedb::NitriteDb::new(&config.db)?);
let cache = Box::new(dashmap::DashMapCache::new());

// 2. Instantiate Cedrus authorization engine
let mut cedrus = Cedrus::new(db, cache, config.server.exclude_policy_annotation).await;

// 3. Initialize Admin Project (on first startup)
cedrus.init_admin_project(config.identity_source, admin_api_key).await?;
```

## Performance Considerations

### Caching Strategy

- **Schemas**: Cached per project (loaded concurrently during evaluation)
- **Entities**: Cached per project and loaded alongside request entities
- **Policies & Templates**: Cached per project
- **Concurrent evaluation**: `is_authorized` fetches policies and entities concurrently using `tokio::try_join!`

### Batch Operations

Use batch operations for high-throughput evaluation:

- `project_entities_add()`: Add multiple entities at once
- `project_policies_add()`: Add multiple policies at once
- `is_authorized_batch()`: Evaluate multiple authorization requests at once

## Integration

This library is used by:

- **cedrus**: REST API server that exposes Cedrus functionality over HTTP/OpenAPI
- **Custom applications**: Can embed Cedrus Core directly into Rust microservices

## Dependencies

- `cedrus-cedar`: Type definitions, serialization, and Cedar bindings
- `cedar-policy`: Official Cedar policy engine
- `mango-query-rs`: Query filtering engine for Nitrite DB
- `dashmap`: Concurrent in-memory hash map
- `jwt-authorizer`: JWT token validation
- `tokio`: Async runtime