# Control Center - Cedar Policy Engine

A comprehensive Cedar policy engine implementation with advanced security features, compliance checking, and anomaly detection.

## Features

### 🔐 Cedar Policy Engine

- **Policy Evaluation**: High-performance policy evaluation with context injection
- **Versioning**: Complete policy versioning with rollback capabilities
- **Templates**: Configuration-driven policy templates with variable substitution
- **Validation**: Comprehensive policy validation with syntax and semantic checking

### 🛡️ Security & Authentication

- **JWT Authentication**: Secure token-based authentication
- **Multi-Factor Authentication**: MFA support for sensitive operations
- **Role-Based Access Control**: Flexible RBAC with policy integration
- **Session Management**: Secure session handling with timeouts

### 📊 Compliance Framework

- **SOC2 Type II**: Complete SOC2 compliance validation
- **HIPAA**: Healthcare data protection compliance
- **Audit Trail**: Comprehensive audit logging and reporting
- **Impact Analysis**: Policy change impact assessment

### 🔍 Anomaly Detection

- **Statistical Analysis**: Multiple statistical methods (Z-Score, IQR, Isolation Forest)
- **Real-time Detection**: Continuous monitoring of policy evaluations
- **Alert Management**: Configurable alerting through multiple channels
- **Baseline Learning**: Adaptive baseline calculation for improved accuracy

### 🗄️ Storage & Persistence

- **SurrealDB Integration**: High-performance graph database backend
- **Policy Storage**: Versioned policy storage with metadata
- **Metrics Storage**: Policy evaluation metrics and analytics
- **Compliance Records**: Complete compliance audit trails

## Quick Start

### 1. Installation

```bash
cd src/control-center
cargo build --release
```

### 2. Configuration

Copy the example configuration:

```toml
cp config.toml.example config.toml
```

Edit `config.toml` for your environment:

```toml
[database]
url = "surreal://localhost:8000"  # Your SurrealDB instance
username = "root"
password = "your-password"

[auth]
jwt_secret = "your-super-secret-key"
require_mfa = true

[compliance.soc2]
enabled = true

[anomaly]
enabled = true
detection_threshold = 2.5
```

### 3. Start the Server

```bash
./target/release/control-center server --port 8080
```

### 4. Test Policy Evaluation

```bash
curl -X POST http://localhost:8080/policies/evaluate 
  -H "Content-Type: application/json" 
  -d '{
    "principal": {"id": "user123", "roles": ["Developer"]},
    "action": {"id": "access"},
    "resource": {"id": "sensitive-db", "classification": "confidential"},
    "context": {"mfa_enabled": true, "location": "US"}
  }'
```

## Policy Examples

### Multi-Factor Authentication Policy

```bash
// Require MFA for sensitive resources
permit(
    principal,
    action == Action::"access",
    resource
) when {
    resource has classification &&
    resource.classification in ["sensitive", "confidential"] &&
    principal has mfa_enabled &&
    principal.mfa_enabled == true
};
```

### Production Approval Policy

```bash
// Require approval for production operations
permit(
    principal,
    action in [Action::"deploy", Action::"modify", Action::"delete"],
    resource
) when {
    resource has environment &&
    resource.environment == "production" &&
    principal has approval &&
    principal.approval.approved_by in ["ProductionAdmin", "SRE"]
};
```

### Geographic Restrictions

```bash
// Allow access only from approved countries
permit(
    principal,
    action,
    resource
) when {
    context has geo &&
    context.geo has country &&
    context.geo.country in ["US", "CA", "GB", "DE"]
};
```

## CLI Commands

### Policy Management

```bash
# Validate policies
control-center policy validate policies/

# Test policy with test data
control-center policy test policies/mfa.cedar tests/data/mfa_test.json

# Analyze policy impact
control-center policy impact policies/new_policy.cedar
```

### Compliance Checking

```bash
# Check SOC2 compliance
control-center compliance soc2

# Check HIPAA compliance
control-center compliance hipaa

# Generate compliance report
control-center compliance report --format html
```

## API Endpoints

### Policy Evaluation

- `POST /policies/evaluate` - Evaluate policy decision
- `GET /policies` - List all policies
- `POST /policies` - Create new policy
- `PUT /policies/{id}` - Update policy
- `DELETE /policies/{id}` - Delete policy

### Policy Versions

- `GET /policies/{id}/versions` - List policy versions
- `GET /policies/{id}/versions/{version}` - Get specific version
- `POST /policies/{id}/rollback/{version}` - Rollback to version

### Compliance

- `GET /compliance/soc2` - SOC2 compliance check
- `GET /compliance/hipaa` - HIPAA compliance check
- `GET /compliance/report` - Generate compliance report

### Anomaly Detection

- `GET /anomalies` - List detected anomalies
- `GET /anomalies/{id}` - Get anomaly details
- `POST /anomalies/detect` - Trigger anomaly detection

## Testing

### Run Unit Tests

```bash
cargo test
```

### Run Integration Tests

```bash
cargo test --test integration_tests
```

### Run Policy Tests

```bash
cargo test --test policy_tests
```

### Run Compliance Tests

```bash
cargo test --test compliance_tests
```

## Architecture

### Core Components

1. **Policy Engine** (`src/policies/engine.rs`)
   - Cedar policy evaluation
   - Context injection
   - Caching and optimization

2. **Storage Layer** (`src/storage/`)
   - SurrealDB integration
   - Policy versioning
   - Metrics storage

3. **Compliance Framework** (`src/compliance/`)
   - SOC2 checker
   - HIPAA validator
   - Report generation

4. **Anomaly Detection** (`src/anomaly/`)
   - Statistical analysis
   - Real-time monitoring
   - Alert management

5. **Authentication** (`src/auth.rs`)
   - JWT token management
   - Password hashing
   - Session handling

### Configuration-Driven Design

The system follows PAP (Project Architecture Principles) with:

- **No hardcoded values**: All behavior controlled via configuration
- **Dynamic loading**: Policies and rules loaded from configuration
- **Template-based**: Policy generation through templates
- **Environment-aware**: Different configs for dev/test/prod

### Security Features

- **Audit Logging**: All policy evaluations logged
- **Encryption**: Data encrypted at rest and in transit
- **Rate Limiting**: Protection against abuse
- **Input Validation**: Comprehensive validation of all inputs
- **Error Handling**: Secure error handling without information leakage

## Production Deployment

### Docker

```bash
FROM rust:1.75 as builder
WORKDIR /app
COPY . .
RUN cargo build --release

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates
COPY --from=builder /app/target/release/control-center /usr/local/bin/
EXPOSE 8080
CMD ["control-center", "server"]
```

### Kubernetes

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: control-center
spec:
  replicas: 3
  selector:
    matchLabels:
      app: control-center
  template:
    metadata:
      labels:
        app: control-center
    spec:
      containers:
      - name: control-center
        image: control-center:latest
        ports:
        - containerPort: 8080
        env:
        - name: DATABASE_URL
          value: "surreal://surrealdb:8000"
```

### Environment Variables

```bash
# Override config values with environment variables
export CONTROL_CENTER_SERVER_PORT=8080
export CONTROL_CENTER_DATABASE_URL="surreal://prod-db:8000"
export CONTROL_CENTER_AUTH_JWT_SECRET="production-secret"
export CONTROL_CENTER_COMPLIANCE_SOC2_ENABLED=true
```

## Monitoring & Observability

### Metrics

- Policy evaluation latency
- Policy decision distribution
- Anomaly detection rates
- Compliance scores

### Logging

```bash
// Structured logging with tracing
tracing::info!(
    policy_id = %policy.id,
    principal = %context.principal.id,
    decision = ?result.decision,
    duration_ms = evaluation_time,
    "Policy evaluation completed"
);
```

### Health Checks

```bash
curl http://localhost:8080/health
```

## Contributing

1. Follow the PAP principles documented in the codebase
2. Add tests for new features
3. Update documentation
4. Ensure compliance checks pass
5. Add appropriate logging and monitoring

## License

This project follows the licensing specified in the parent repository.

## Support

For questions and support, refer to the project documentation or create an issue in the repository.
