# Authentication and Authorization

# Authentication and Authorization

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [src/modules/auth/README.md](src/modules/auth/README.md)
- [src/modules/auth/auth.middleware.ts](src/modules/auth/auth.middleware.ts)
- [src/modules/auth/oidc-client.ts](src/modules/auth/oidc-client.ts)
- [src/modules/auth/permissions.ts](src/modules/auth/permissions.ts)
- [src/modules/auth/rbac.middleware.ts](src/modules/auth/rbac.middleware.ts)
- [src/modules/auth/user-profile-repo.ts](src/modules/auth/user-profile-repo.ts)

</details>



The Primebrick backend implements a robust Authentication and Role-Based Access Control (RBAC) system designed to be Identity Provider (IdP) agnostic while maintaining strict internal data integrity. The system supports two primary operational modes: **STANDALONE** (direct JWT validation) and **GATEWAY** (trusting upstream proxy headers).

### Core Components and Flow

The authentication process transforms external identity claims (from JWTs or Gateway headers) into a standardized internal `AuthUser` context. This context is then used by the RBAC middleware to enforce granular permissions defined in the `Permission` enum.

#### Authentication Flow Overview
The following diagram illustrates how a request is authenticated and how the user context is established.

**Sequence: Request Authentication and Context Initialization**
```mermaid
sequenceDiagram
    participant Client as "Client / Gateway"
    participant RM as "rbac.middleware.ts"
    participant AM as "auth.middleware.ts"
    participant TN as "token-normalizer.ts"
    participant UPR as "user-profile-repo.ts"
    participant SC as "session-context.ts"
    participant DB as "PostgreSQL (user_profiles)"

    Client->>RM: HTTP Request
    RM->>AM: authMiddleware()
    
    alt STANDALONE Mode
        AM->>AM: Extract Bearer Token / Cookie
        AM->>AM: verifyAccessToken() (OIDC/JWKS)
    else GATEWAY Mode
        AM->>AM: Verify X-Gateway-Secret
        AM->>AM: Read X-User-* Headers
    end

    AM->>TN: normalizeIdpToken(claims)
    TN-->>AM: Normalized Identity (idp_code, roles, etc.)

    AM->>UPR: resolveInternalUuid(identity)
    UPR->>DB: SELECT/INSERT (JIT Provisioning)
    DB-->>UPR: Internal UUID
    UPR-->>AM: Internal UUID

    AM->>SC: runWithSession(session)
    Note over SC: Stores user in AsyncLocalStorage
    SC->>RM: next()
    RM->>RM: Evaluate Permissions
```
**Sources:** [src/modules/auth/auth.middleware.ts:68-93](), [src/modules/auth/user-profile-repo.ts:68-100](), [src/modules/auth/README.md:9-15]()

---

### Sub-Systems Overview

#### 3.1 Authentication Middleware and Token Normalization
The system handles identity verification through two mutually exclusive paths:
- **STANDALONE**: Validates Bearer JWTs using OIDC discovery and JWKS via the `jose` library [src/modules/auth/oidc-client.ts:83-109]().
- **GATEWAY**: Trusts identity headers (e.g., `X-User-Id`) injected by a proxy like Kong or APISIX, protected by a shared `GATEWAY_SECRET` [src/modules/auth/auth.middleware.ts:144-154]().

The `normalizeIdpToken` function uses the `AUTH_ROLES_PATH` environment variable to extract roles from various JWT structures (e.g., Casdoor, Keycloak, or Entra ID) [src/modules/auth/token-normalizer.ts:129-129]().

For details, see [Authentication Middleware and Token Normalization](#3.1).

#### 3.2 RBAC Middleware and Permission System
Permissions are managed as a flat list of strings in the `Permission` enum [src/modules/auth/permissions.ts:34-87](). The `rbacHandler` middleware enforces these permissions with the following features:
- **OR/AND Semantics**: Supports "any-of" (default) or "all-of" permission checks [src/modules/auth/rbac.middleware.ts:82-90]().
- **Wildcard Matching**: Supports patterns like `customers.*` [src/modules/auth/permissions.ts:116-123]().
- **Admin Bypass**: Roles marked with `is_admin=true` in the `role_mappings` table bypass all checks [src/modules/auth/permissions.ts:171-175]().
- **Sentinels**: Special permissions like `_public` and `_authenticated_user` handle anonymous and basic auth paths [src/modules/auth/permissions.ts:34-39]().

For details, see [RBAC Middleware and Permission System](#3.2).

#### 3.3 Auth Router: Login, Token Refresh, and User Management
The `auth` module provides endpoints for session management and administrative user control. This includes proxying login requests to Casdoor, handling token refreshes, and managing `user_profiles` [src/modules/auth/README.md:14-15](). A key feature is **Just-In-Time (JIT) Provisioning**, where a local `user_profiles` record is created or updated automatically upon the first successful login of an IdP user [src/modules/auth/user-profile-repo.ts:102-132]().

For details, see [Auth Router: Login, Token Refresh, and User Management API](#3.3).

#### 3.4 Organizations Module
The organizations module manages the multi-tenant structure of the system. It follows a **Casdoor-first write strategy**, ensuring that organizational data is synchronized between the IdP and the local Primebrick database [src/modules/auth/auth.middleware.ts:134-135](). This module uses `idp_code` and `idp_org` to maintain the link between external entities and internal data [src/modules/auth/user-profile-repo.ts:50-56]().

For details, see [Organizations Module](#3.4).

---

### Session Context Propagation

To avoid passing user IDs through every function signature, the system uses `AsyncLocalStorage` via `session-context.ts`.

**Code-to-Entity Mapping: Session Management**
```mermaid
classDiagram
    class Session {
        +UUID actor
        +string[] roles
        +string idpCode
        +string idpOrg
    }
    class sessionContext {
        +runWithSession(Session, fn)
        +getSession()
        +requireActor()
    }
    class authMiddleware {
        +fromStandalone()
        +fromGateway()
    }
    
    authMiddleware ..> Session : creates
    authMiddleware --> sessionContext : calls runWithSession
    sessionContext ..> Session : wraps in AsyncLocalStorage
```
**Sources:** [src/modules/auth/session-context.ts:1-40](), [src/modules/auth/auth.middleware.ts:81-88]()

### Key Files Summary

| File | Purpose |
| :--- | :--- |
| `auth.middleware.ts` | Entry point for identity verification and session initialization. |
| `rbac.middleware.ts` | Guard for route-level permission enforcement. |
| `permissions.ts` | Registry of all system permissions and wildcard matching logic. |
| `user-profile-repo.ts` | Handles internal UUID mapping and JIT provisioning of users. |
| `token-normalizer.ts` | Transforms various IdP JWT shapes into a standard internal format. |
| `oidc-client.ts` | Low-level OIDC discovery and JWKS verification logic. |

**Sources:** [src/modules/auth/README.md:1-15](), [src/modules/auth/auth.middleware.ts:1-30]()

---
