# Contract: Entra Auth Flow

This document describes the OIDC authentication flow for Entra sign-in.

## Sequence Diagram

```mermaid
sequenceDiagram
    participant User
    participant Browser
    participant TenantPilot
    participant MicrosoftEntra

    User->>Browser: Access /admin/login
    Browser->>TenantPilot: GET /admin/login
    TenantPilot-->>Browser: Show "Sign in with Microsoft" button
    User->>Browser: Click "Sign in with Microsoft"
    Browser->>TenantPilot: GET /auth/entra/redirect
    TenantPilot->>Browser: HTTP 302 Redirect to Microsoft Entra
    Browser->>MicrosoftEntra: GET /authorize... (with OIDC params)
    MicrosoftEntra-->>Browser: Show Microsoft login page
    User->>Browser: Enter credentials
    Browser->>MicrosoftEntra: POST credentials
    MicrosoftEntra-->>Browser: HTTP 302 Redirect to /auth/entra/callback (with auth code)
    Browser->>TenantPilot: GET /auth/entra/callback?code=...&state=...
    TenantPilot->>MicrosoftEntra: POST /token (exchange code for ID token)
    MicrosoftEntra-->>TenantPilot: Return ID Token (JWT)
    TenantPilot->>TenantPilot: Validate token, decode claims (tid, oid, etc.)
    TenantPilot->>TenantPilot: Upsert user in DB using (tid, oid)
    TenantPilot->>TenantPilot: Regenerate session, log user in
    TenantPilot->>TenantPilot: Check user's tenant memberships
    alt 0 memberships
        TenantPilot->>Browser: HTTP 302 Redirect to /admin/no-access
    else 1 membership
        TenantPilot->>Browser: HTTP 302 Redirect to tenant dashboard
    else >1 memberships
        TenantPilot->>Browser: HTTP 302 Redirect to /admin/choose-tenant
    end
```
