# MACAW Identity Flow Architecture V2 🏗️

*A Research Report on MACAW's Layered Identity Architecture*

## Executive Summary

This document presents MACAW's evolved identity architecture that achieves **transparent security** through clean separation of concerns. By leveraging the original MACAW `security_context` design with modern JWT integration, we've created an architecture that is both **enterprise-grade secure** and **developer-friendly simple**.

**Key Achievement**: Applications can implement enterprise identity integration by simply passing a JWT token, while maintaining complete multi-user safety and policy enforcement.

## Architecture Overview

### The Layer Cake Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    APPLICATION LAYER                         │
│  ┌─────────────────┐    ┌─────────────────┐    ┌─────────────┐ │
│  │ Financial       │    │ Document        │    │ Data        │ │
│  │ Analyzer        │    │ Processor       │    │ Orchestrator │ │
│  │                 │    │                 │    │             │ │
│  │ • Business      │    │ • Business      │    │ • Business  │ │
│  │   Logic Only    │    │   Logic Only    │    │   Logic     │ │
│  │ • No Auth Code  │    │ • No Auth Code  │    │ • Multi-User │ │
│  └─────────────────┘    └─────────────────┘    └─────────────┘ │
└─────────────┬───────────────────┬───────────────────┬─────────┘
              │ JWT Token         │ JWT Token         │ JWT Token
              ▼                   ▼                   ▼
┌─────────────────────────────────────────────────────────────┐
│                     ADAPTER LAYER                           │
│  ┌─────────────────┐    ┌─────────────────┐    ┌─────────────┐ │
│  │ SecureOpenAI    │    │ SecureClaude    │    │ SecureAPI   │ │
│  │                 │    │                 │    │             │ │
│  │ • Identity      │    │ • Identity      │    │ • Identity  │ │
│  │   Agnostic      │    │   Agnostic      │    │   Agnostic  │ │
│  │ • Just Stores   │    │ • Just Stores   │    │ • Just      │ │
│  │   JWT           │    │   JWT           │    │   Stores    │ │
│  │ • Normal API    │    │ • Normal API    │    │   JWT       │ │
│  └─────────────────┘    └─────────────────┘    └─────────────┘ │
└─────────────┬───────────────────┬───────────────────┬─────────┘
              │ JWT Token         │ JWT Token         │ JWT Token
              ▼                   ▼                   ▼
┌─────────────────────────────────────────────────────────────┐
│                  MACAW CLIENT LAYER                         │
│  ┌───────────────────────────────────────────────────────┐   │
│  │                 MACAWClient                           │   │
│  │                                                       │   │
│  │  ┌─────────────────────────────────────────────────┐  │   │
│  │  │        JWT → security_context Conversion        │  │   │
│  │  │                                                 │  │   │
│  │  │ jwt_claims = validate_jwt_token(jwt)           │  │   │
│  │  │ security_context = {                           │  │   │
│  │  │   "company": jwt_claims["organization"],       │  │   │
│  │  │   "business_unit": jwt_claims["bu"],           │  │   │
│  │  │   "team": jwt_claims["team"],                  │  │   │
│  │  │   "user": jwt_claims["sub"]                    │  │   │
│  │  │ }                                              │  │   │
│  │  └─────────────────────────────────────────────────┘  │   │
│  └───────────────────────────────────────────────────────┘   │
└─────────────┬───────────────────────────────────────────────┘
              │ security_context
              ▼
┌─────────────────────────────────────────────────────────────┐
│                   MACAW AGENT LAYER                         │
│  ┌───────────────────────────────────────────────────────┐   │
│  │                   MACAWAgent                          │   │
│  │                                                       │   │
│  │  invoke_tool_via_local_agent(                        │   │
│  │    tool_name, operation, params,                     │   │
│  │    security_context=security_context  ← ORIGINAL!    │   │
│  │  )                                                   │   │
│  │                                                       │   │
│  │  # UNCHANGED - Uses existing flow                     │   │
│  │  security_metadata.update(security_context)          │   │
│  └───────────────────────────────────────────────────────┘   │
└─────────────┬───────────────────────────────────────────────┘
              │ security_metadata (with user context)
              ▼
┌─────────────────────────────────────────────────────────────┐
│                 POLICY & ENFORCEMENT                        │
│  ┌─────────────────┐              ┌─────────────────────────┐ │
│  │ PolicyResolver  │              │ Policy Enforcement      │ │
│  │                 │              │ Point (PEP)             │ │
│  │ • Hierarchical  │ ←──────────→ │                        │ │
│  │   Lookup        │              │ • Alice: GPT-3.5       │ │
│  │ • org → BU →    │              │   500 tokens           │ │
│  │   team → role   │              │ • Bob: GPT-4           │ │
│  │ • Dynamic       │              │   2000 tokens          │ │
│  │   Context       │              │ • Audit Logging        │ │
│  └─────────────────┘              └─────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```

## Identity Flow Patterns

### Pattern 1: Single User Application

```
Alice's Workflow:
─────────────────

Step 1: Authentication
┌─────────────┐  JWT     ┌─────────────────┐
│ Alice logs  │─────────▶│ Financial       │
│ into        │          │ Analyzer        │
│ Keycloak    │          │                 │
│             │          │ analyzer.       │
│ alice_jwt   │          │ connect_with_   │
│             │          │ jwt(alice_jwt)  │
└─────────────┘          └─────────────────┘

Step 2: Business Operation
┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│ Alice requests  │────▶│ Normal OpenAI   │────▶│ MACAW applies   │
│ Q4 analysis     │     │ API call        │     │ Alice's policies│
│                 │     │                 │     │                 │
│ analyzer.       │     │ client.chat.    │     │ • GPT-3.5 only  │
│ analyze_report  │     │ completions.    │     │ • 500 tokens    │
│ ("Q4")          │     │ create(...)     │     │ • Audit logged  │
└─────────────────┘     └─────────────────┘     └─────────────────┘

Result: Alice gets appropriate analysis within her policy constraints
```

### Pattern 2: Multi-User Orchestrator (SECURE)

```
Concurrent Multi-User Safety:
────────────────────────────

Time T1: Alice's Request
┌─────────────┐  alice_jwt  ┌─────────────────┐  security_context  ┌─────────────────┐
│ Alice       │────────────▶│ Shared          │───────────────────▶│ Alice's policies│
│ Financial   │             │ Orchestrator    │                   │ applied         │
│ Request     │             │                 │                   │                 │
└─────────────┘             │ Each request    │                   └─────────────────┘
                            │ creates fresh   │
Time T2: Bob's Request      │ security_context│
┌─────────────┐  bob_jwt    │                 │  security_context  ┌─────────────────┐
│ Bob         │────────────▶│ Same Instance!  │───────────────────▶│ Bob's policies  │
│ Analysis    │             │                 │                   │ applied         │
│ Request     │             │ NO STORED STATE │                   │                 │
└─────────────┘             └─────────────────┘                   └─────────────────┘

Key: NO identity bleed possible - each request is isolated
```

### Pattern 3: Agent Chain with Delegation

```
Multi-Hop Agent Chain:
─────────────────────

Alice → Orchestrator → Tool A → Tool B

┌─────────────┐  alice_jwt  ┌─────────────────┐  alice_context  ┌─────────────────┐
│ Alice       │────────────▶│ Orchestrator    │────────────────▶│ Tool Agent A    │
│             │             │                 │                │                 │
│ "Process    │             │ security_context│                │ Uses Alice's    │
│  my data"   │             │ = {             │                │ permissions     │
│             │             │  company: "FC", │                │                 │
│             │             │  bu: "Analytics"│  alice_context │ ┌─────────────┐ │
│             │             │  user: "alice"  │───────────────▶│ │Tool Agent B │ │
│             │             │ }               │                │ │             │ │
│             │             │                 │                │ │Uses Alice's │ │
│             │             │                 │                │ │permissions  │ │
└─────────────┘             └─────────────────┘                │ └─────────────┘ │
                                                              └─────────────────┘

Result: Alice's identity and policies flow through entire chain
```

## Technical Deep Dive

### JWT to Security Context Conversion

The heart of the new architecture is the clean conversion from JWT tokens to MACAW's native `security_context` format using the claims mapper:

```python
# Using the claims mapper for JWT to security_context conversion
from macaw_agent.claims_mapper import ClaimsMapper

def _jwt_to_security_context(self, jwt_token: str) -> Dict[str, Any]:
    """Convert JWT to MACAW security_context format using claims mapper"""

    # 1. Use claims mapper to handle multi-IDP conversion
    claims_mapper = ClaimsMapper()
    security_context = claims_mapper.map_jwt_to_security_context(jwt_token)

    # 2. The claims mapper handles:
    #    - JWT validation and signature verification
    #    - Multi-provider detection (Keycloak, Azure AD, Okta, etc.)
    #    - Claims mapping per .claims-config.yaml configuration
    #    - Organization → company mapping for policy hierarchy
    #    - Role normalization across providers

    return security_context
```

### Original MACAW Flow Integration

The beauty of this architecture is that it leverages MACAW's **existing** security infrastructure without modification:

```python
# In MACAWAgent.invoke_tool_via_local_agent() - UNCHANGED!
def invoke_tool_via_local_agent(self, tool_name, operation, params,
                               security_context=None):
    """Original MACAW method - no changes needed"""

    # ... existing logic in _prepare_invocation() ...

    # This line already existed and handles our JWT-derived context!
    if security_context:
        security_metadata.update(security_context)

    # Context flows to PolicyResolver automatically
    invocation.security_metadata = security_metadata
```

### Policy Resolution with Dynamic Context

The `security_context` flows seamlessly through the policy resolution hierarchy:

```
PolicyResolver Hierarchical Lookup:
───────────────────────────────────

security_context = {
  "company": "FinTech Corp",
  "business_unit": "Analytics",
  "team": "Reporting",
  "user": "alice@fintech.com",
  "roles": ["analyst"]
}

Lookup Chain:
1. base:role:analyst               → GPT-3.5, 500 tokens (starting point)
2. restrict:org:fintech-corp       → No secrets, audit required
3. restrict:bu:analytics           → Low temperature, consistency mode
4. restrict:team:reporting         → 9-6 EST only, specific data sources
5. filter:clearance:standard       → No executive data access

Final Policy (Most Restrictive):
- Model: GPT-3.5 ONLY
- Tokens: 500 MAX
- Hours: 9-6 EST
- Data: Standard clearance only
- Audit: Full logging required
```

## Multi-User Security Analysis

### The Previous Vulnerability (Now Fixed)

**Before**: Delegation stored on agent instances
```python
# DANGEROUS - Multiple users could interfere
alice_app.authenticate_with_delegation(alice_jwt)  # Stores on instance
# ... later ...
bob_app.authenticate_with_delegation(bob_jwt)      # OVERWRITES Alice!
# ... even later ...
alice_request()  # Uses Bob's identity! 🚨 SECURITY BREACH
```

**After**: Stateless per-request identity
```python
# SAFE - Each request isolated
alice_app.connect_with_jwt(alice_jwt)     # Just stores JWT
alice_request()  # Creates fresh security_context for Alice

bob_app.connect_with_jwt(bob_jwt)         # Different instance or same
bob_request()    # Creates fresh security_context for Bob

# IMPOSSIBLE for interference - no shared state
```

### Concurrent User Safety Proof

The architecture ensures multi-user safety through **stateless design**:

1. **No Shared State**: JWT tokens stored per-adapter-instance
2. **Per-Request Context**: `security_context` created fresh for each call
3. **Isolated Processing**: Each request thread has its own context
4. **Clean Separation**: Adapter layer remains identity-agnostic

**Proof by Design**: Even if 1000 users hit the same orchestrator simultaneously, each request gets its own `security_context` derived from its own JWT, preventing any possibility of identity bleed.

## Integration with IAM Setup

### Two-Layer Identity Architecture

The wizard's IAM setup and runtime JWT flow work in perfect synergy:

#### Layer 1: Service Identity (Setup Time)
```yaml
# macaw-agent.yaml (from wizard)
iam_provider: keycloak
iam_config:
  domain: auth.company.com
  client_id: macaw-service
  client_secret: service-secret-key

Purpose:
- Establishes MACAW service identity
- Enables JWT validation capability
- Sets up trust with identity providers
```

#### Layer 2: User Identity (Runtime)
```python
# Application code
analyzer.connect_with_jwt(alice_jwt)  # Alice from Keycloak
analyzer.analyze_report("Q4")         # Alice's policies applied

Purpose:
- Dynamic user identification per request
- User-specific policy enforcement
- Audit trail with correct attribution
```

### The Complete Flow

```
Setup Phase (Admin):
┌─────────────┐    ┌─────────────────┐    ┌─────────────────┐
│ Admin runs  │───▶│ Wizard          │───▶│ MACAW Service   │
│ wizard      │    │ configures      │    │ trusts          │
│             │    │ Keycloak        │    │ Keycloak        │
└─────────────┘    └─────────────────┘    └─────────────────┘

Runtime Phase (Users):
┌─────────────┐    ┌─────────────────┐    ┌─────────────────┐
│ Alice logs  │───▶│ Gets JWT from   │───▶│ App passes to   │
│ into app    │    │ trusted         │    │ MACAW (which    │
│             │    │ Keycloak        │    │ can validate)   │
└─────────────┘    └─────────────────┘    └─────────────────┘
```

**Result**: Service setup enables user validation. No conflict, perfect synergy.

## Benefits Analysis

### For Developers

**Before**: Complex delegation management
```python
# Developer had to understand:
client.authenticate_with_delegation(jwt)
client.invoke_tool_with_jwt(tool, params, jwt)  # REMOVED - not in original SDK
response = client.macaw_client.complex_internal_method(...)

# Security vulnerabilities possible
# Multi-user scenarios dangerous
# Lots of MACAW-specific knowledge required
```

**After**: Simple, transparent security
```python
# Developer just needs to understand:
analyzer = FinancialAnalyzer()
analyzer.connect_with_jwt(jwt)  # Pass JWT once
result = analyzer.analyze_report("Q4")  # Normal business logic

# Security automatic
# Multi-user safe
# No MACAW knowledge required
```

### For Security Teams

1. **Cryptographically Secure**: JWT validation with proper signature verification
2. **Non-Bypassable**: All requests flow through MACAW policy enforcement
3. **Auditable**: Complete trail with correct user attribution
4. **Scalable**: Works with any number of concurrent users
5. **Standard Compliant**: Uses industry-standard JWT/OIDC flows

### For Operations Teams

1. **Simple Deployment**: Standard JWT integration patterns
2. **Zero Vendor Lock-in**: Works with any OIDC/JWT provider
3. **Monitoring Ready**: Full audit trails and policy enforcement logs
4. **Debug Friendly**: Clear separation of concerns makes troubleshooting easy

## Future Extensions

This architecture provides a solid foundation for future enhancements:

### 1. Advanced Policy Features
```python
# Future: Dynamic policy adjustment
security_context["risk_score"] = calculate_user_risk(user_history)
security_context["data_classification"] = detect_data_sensitivity(request)
```

### 2. Additional Identity Providers
```python
# Future: Multi-IdP support
security_context = self._jwt_to_security_context(jwt_token, idp_hint="github")
```

### 3. Federation Scenarios
```python
# Future: Cross-organization workflows
security_context["federation"] = {
    "home_org": "FinTech Corp",
    "visiting_org": "Partner Inc",
    "delegation_scope": ["read_reports"]
}
```

## Conclusion

The Identity Flow Architecture V2 represents a significant evolution in MACAW's security model. By **leveraging existing design patterns** while **adding modern JWT integration**, we've achieved:

- **Developer Simplicity**: Pass JWT once, get transparent security
- **Enterprise Security**: Cryptographic validation with policy enforcement
- **Multi-User Safety**: Stateless design prevents identity bleed
- **Operational Excellence**: Clear patterns with excellent debuggability

**Most importantly**, this architecture respects MACAW's original design philosophy of **transparent security**. Applications remain focused on business logic while MACAW handles all security concerns invisibly but thoroughly.

The result is an architecture that is both **beautiful in its simplicity** and **robust in its security guarantees** - exactly what enterprise-grade developer tools should aspire to be.

---

*This document represents the culmination of extensive architectural analysis and represents the current state-of-the-art for MACAW's identity integration capabilities.*
---

Copyright MACAW Security. All rights reserved.
