# Employee Permission Schema & RBAC Engine

## Overview

This module provides a comprehensive Role-Based Access Control (RBAC) system for DBIS, SCB, and FI employees. It defines roles, actions, screen visibility rules, and audit constraints for the entire employee-facing UI system.

## Architecture

The RBAC system consists of three main components:

1. **Permission Schema** (`permission-schema.json`) - Master JSON schema defining all roles, actions, screens, and constraints
2. **Type Definitions** (`permission-types.ts`) - TypeScript types matching the schema structure
3. **RBAC Engine** (`rbac-engine.service.ts`) - Core service for permission checking, screen visibility, and action authorization

## Participants

The system supports three participant types:

- **DBIS** - Digital Bank of International Settlements
- **SCB** - Sovereign Central Banks
- **FI** - Financial Institutions

## Roles

### DBIS Roles

- **Governor** - Supreme authority with full system access (tier_1)
- **MSC_Officer** - Monetary & Settlement Council Officer (tier_2)
- **CAA_Auditor** - Compliance & Audit Authority Auditor (tier_2)
- **Sovereign_Relations_Director** - Sovereign Relations Director (tier_3)
- **Crisis_Operations_Commander** - Crisis Operations Commander (tier_1)

### SCB Roles

- **SCB_Governor** - Sovereign Central Bank Governor (tier_1)
- **SCB_Monetary_Officer** - SCB Monetary Policy Officer (tier_2)
- **SCB_Compliance_Officer** - SCB Compliance Officer (tier_2)
- **SCB_Settlement_Manager** - SCB Settlement Manager (tier_3)
- **SCB_Liquidity_Manager** - SCB Liquidity Manager (tier_3)

### FI Roles

- **FI_Treasury_Manager** - Financial Institution Treasury Manager (tier_3)
- **FI_Compliance_Officer** - Financial Institution Compliance Officer (tier_3)
- **FI_Settlement_Officer** - Financial Institution Settlement Officer (tier_4)
- **FI_Operations_Manager** - Financial Institution Operations Manager (tier_3)
- **FI_Risk_Officer** - Financial Institution Risk Officer (tier_3)

## Screens

The system defines the following screens/modules:

- **dashboard** - Main employee dashboard
- **operations** - Operational management screens
- **governance** - Constitutional and governance screens
- **compliance** - Compliance and regulatory screens
- **risk** - Risk assessment and monitoring
- **settlement** - Settlement and clearing screens
- **cbdc** - Central Bank Digital Currency management
- **treasury** - Treasury and liquidity management
- **fx** - Foreign exchange and currency management
- **accounting** - Accounting and reporting
- **quantum** - Quantum-safe cryptography management
- **crisis** - Crisis protocols and emergency operations
- **reports** - Reporting and analytics
- **admin** - System administration

## Actions

The following actions are supported:

- **view** - View/read access
- **create** - Create new resources
- **update** - Update existing resources
- **delete** - Delete resources
- **approve** - Approve actions/transactions
- **reject** - Reject actions/transactions
- **execute** - Execute operations
- **export** - Export data
- **audit** - Audit access
- **escalate** - Escalate issues

## Usage

### Check Permission

```typescript
import { roleManagementService } from '@/core/operations/role-management.service';

const result = await roleManagementService.checkPermission(
  employeeId,
  'settlement',
  'create',
  { amount: 1000000, currency: 'USD' }
);

if (result.allowed) {
  if (result.requiresApproval) {
    // Request approval from result.approverRole
  } else {
    // Proceed with action
  }
}
```

### Check Screen Access

```typescript
const screenAccess = await roleManagementService.checkScreenAccess(
  employeeId,
  'settlement'
);

if (screenAccess.visible) {
  // Show screen
  // screenAccess.components contains component visibility
}
```

### Get Accessible Screens

```typescript
const screens = await roleManagementService.getAccessibleScreens(employeeId);
// Returns array of ScreenName that employee can access
```

### Get Allowed Actions

```typescript
const actions = await roleManagementService.getAllowedActions(
  employeeId,
  'settlement'
);
// Returns array of Action that employee can perform
```

## Permission Constraints

### Separation of Duties

Roles can define separation of duties constraints to prevent conflicts of interest. For example, an auditor cannot also be a monetary officer.

### Approval Requirements

Actions may require approval based on:
- **Amount thresholds** - Transactions above a certain amount require approval
- **Approver role** - Specific role that must approve

### Time-Based Permissions

Future support for time-based permissions (e.g., only during business hours).

## Role Inheritance

Roles can inherit permissions from other roles. When a role inherits from another:
- Screen access is merged using OR logic (if either role has access, merged role has access)
- Actions are merged using union (all actions from both roles are available)

## Audit Logging

All permission checks are logged for audit purposes:
- Permission checks
- Screen access attempts
- Action attempts
- Results and reasons

Audit logs are retained for the period specified in the schema (default: 2555 days).

## Integration

The RBAC engine integrates with:

- **RoleManagementService** - Extended with RBAC methods
- **EmployeeCredential** - Database model for employee credentials
- **DbisRole** - Database model for roles

## Schema Validation

The RBAC engine validates the schema on load:

```typescript
const validation = rbacEngineService.validateSchema();
if (!validation.valid) {
  console.error('Schema validation errors:', validation.errors);
}
```

## Hot Reloading

In development, the schema can be reloaded without restarting the service:

```typescript
rbacEngineService.reloadSchema();
```

## Extending the Schema

To add new roles, screens, or actions:

1. Update `permission-schema.json`
2. Update `permission-types.ts` if new types are needed
3. Reload the schema or restart the service

## Best Practices

1. **Use specific permissions** - Prefer specific module/action combinations over wildcards
2. **Define clear constraints** - Use separation of duties and approval requirements appropriately
3. **Document role purposes** - Keep role descriptions clear and up-to-date
4. **Test permission changes** - Validate schema changes before deploying
5. **Monitor audit logs** - Regularly review audit logs for security issues

## Security Considerations

- Permission checks are performed server-side
- All checks are logged for audit
- Role definitions are loaded from a trusted JSON file
- Employee status is checked before granting permissions
- Separation of duties is enforced

## Future Enhancements

- Component-level visibility rules
- Time-based permissions
- Dynamic role assignment
- Permission delegation
- Multi-factor authentication integration
- Resource-level permissions (e.g., own transactions vs. all transactions)

