0
Fork 0
mirror of https://github.com/mastra-ai/mastra.git synced 2026-11-17 08:44:46 +00:00
mastra/auth/cloud/cloud-auth.md
Ryan Hansen 6dbeeb94a8
feat: auth core, server RBAC, and adapter permission enforcement (#13163)
## Summary

PR 1 of 3 from the `auth-rbac-cms` branch split. This PR adds all
backend plumbing for auth/RBAC. PRs 2 (auth providers) and 3 (playground
UI) depend on this and can land in parallel once this merges.

- **New `@mastra/core/auth` export** — interfaces for RBAC, sessions,
SSO, credentials, ACL, and user management, plus default implementations
(static RBAC provider, cookie/memory session providers, built-in roles)
- **Server auth handlers** — login, signup, logout, session management,
and SSO flows with Zod-validated schemas
- **Route-level permission enforcement** — `requiresPermission` on route
configs with convention-based derivation from path/method (e.g. `GET
/agents/:id` → `agents:read`)
- **Server adapter RBAC middleware** (Hono, Express, Fastify, Koa) —
resolves user permissions via RBAC provider, cookie auth fallthrough for
session-based auth
- **Authorization policy fix** — `isProtectedPath` now uses
`isProtectedCustomRoute` instead of `!isCustomRoutePublic`, fixing a bug
where studio UI couldn't load in production
- **Deployer updates** — `MASTRA_PACKAGES_FILE` env var injection,
dynamic CORS origin when auth configured
- **Client SDK** — `getFullUrl` helper, `AuthCapabilities` type export

### Key behavioral changes

| Change | Risk | Mitigation |
|---|---|---|
| `SimpleAuth<TUser>` → `SimpleAuth<TUser extends EEUser>` | Medium —
requires `id` + `email` fields | Intentional; compile-time catch |
| `isProtectedPath` logic change | Medium — authorization policy | New
tests cover this; required for studio login in prod |
| Cookie fallthrough in Hono auth middleware | Low | Falls back to 401
if no user found |
| No RBAC → authenticated users get full access | Low — intentional |
Auth-only mode preserved |
| CORS dynamic origin when auth configured | Low | Only activates with
auth config; user can override |

### Deviation from plan

`deployers/cloud/package.json` — the plan called for adding
`@mastra/auth-cloud` dependency, but that package is created in PR 2.
Omitted here to avoid workspace resolution failure; PR 2 will add it.

### Fixed pre-existing test bug

All 4 adapter RBAC tests had a failing test ("should derive permissions
from route path/method when not explicitly set") that registered an API
handler at `/agents/test` with no prefix. That's a frontend/SPA path —
real API handlers are always under `/api/*`. Fixed the test to use
`prefix: '/api'` so the route is at `/api/agents/test`, matching how
routes are actually registered. Verified the bug exists on
`auth-rbac-cms` with clean install + build.

## Test plan

- [x] `pnpm build:packages` — 35/35 tasks pass
- [x] Core auth tests (cookie.test.ts) — 16/16 pass
- [x] Server tests (permissions, helpers, system) — 177/177 pass
- [x] Hono RBAC tests — 21/21 pass
- [x] Express RBAC tests — 15/15 pass
- [x] Fastify RBAC tests — 15/15 pass
- [x] Koa RBAC tests — 15/15 pass
- [x] Client SDK tests (base.test.ts) — 5/5 pass
- [ ] Verify no auth configured → all existing behavior identical (no
403s, no auth prompts)
- [ ] Verify pre-commit hooks pass (eslint + prettier)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Enterprise auth: SSO and credentials sign-in/sign-up, login/logout,
cookie and in-memory sessions, auth capabilities and current-user
endpoints.
* RBAC: default roles, static RBAC provider, route-level permission
enforcement and middleware across adapters.
  * Client: full-URL helper; system responses include isDev.
* Deploy/build: bundling emits package metadata; deployers set runtime
packages file and adjust CORS when auth is enabled.

* **Bug Fixes**
  * Studio UI loads correctly in production.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Shane Thomas <shane@codekarate.com>
Co-authored-by: Mastra Code (anthropic/claude-opus-4-6) <noreply@mastra.ai>
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com>
2026-03-03 22:49:10 +01:00

5.6 KiB

TL;DR - OAuth 2.0 + PKCE flow against Mastra Cloud - Cookie-based sessions with Bearer token fallback - RBAC via role→permission mapping

TL;DR

  • OAuth 2.0 + PKCE flow against Mastra Cloud
  • Cookie-based sessions with Bearer token fallback
  • RBAC via role→permission mapping

HIGH-LEVEL FLOW

flowchart TB subgraph Client Browser[Browser/Client] end

  subgraph "Your Server"
      Provider[MastraCloudAuthProvider]
      RBAC[MastraRBACCloud]
  end

  subgraph "Mastra Cloud"
      AuthAPI[/auth/* endpoints]
  end

  Browser -->|1. GET /login| Provider
  Provider -->|2. Redirect w/ PKCE| AuthAPI
  AuthAPI -->|3. User authenticates| AuthAPI
  AuthAPI -->|4. Redirect /callback| Provider
  Provider -->|5. Exchange code| AuthAPI
  Provider -->|6. Verify token| AuthAPI
  Provider -->|7. Set session cookie| Browser

  Browser -->|8. API request + cookie| Provider
  Provider -->|9. Verify session| AuthAPI
  Provider -->|10. Check permission| RBAC

MODULE STRUCTURE

graph LR subgraph Public["Public API"] MCA[MastraCloudAuth] MCAP[MastraCloudAuthProvider] RBAC[MastraRBACCloud] end

  subgraph Internal["Internal Modules"]
      OAuth[oauth/]
      PKCE[pkce/]
      Session[session/]
  end

  MCAP --> MCA
  MCA --> OAuth
  MCA --> PKCE
  MCA --> Session

  OAuth --> PKCE

LOGIN FLOW (PKCE)

sequenceDiagram participant B as Browser participant S as Server (Provider) participant C as Mastra Cloud

  B->>S: GET /auth/login
  S->>S: Generate verifier + challenge
  S->>S: Generate CSRF token
  S->>S: Encode state (CSRF + returnTo)
  S->>B: Set PKCE cookie (5m) + Redirect
  B->>C: /auth/oss?challenge=X&state=Y
  C->>C: User login (WorkOS)
  C->>B: Redirect /callback?code=Z&state=Y
  B->>S: GET /callback?code=Z&state=Y
  S->>S: Validate PKCE cookie
  S->>S: Verify CSRF in state
  S->>C: POST /auth/callback (code + verifier)
  C-->>S: { accessToken }
  S->>C: POST /auth/verify (Bearer token)
  C-->>S: { user, role }
  S->>B: Set session cookie (24h) + Redirect

AUTHENTICATION FLOW (Per Request)

sequenceDiagram participant B as Browser participant S as Server (Provider) participant C as Mastra Cloud participant R as RBAC

  B->>S: API Request + Session Cookie
  S->>S: Parse cookie → token
  S->>C: POST /auth/verify (token)
  C-->>S: { user, role }
  S->>R: hasPermission(user, "agents:read")
  R-->>S: true/false
  alt Has Permission
      S-->>B: 200 + Response
  else No Permission
      S-->>B: 403 Forbidden
  end

CLASS HIERARCHY

classDiagram class MastraAuthProvider { <> +authenticateToken() +authorizeUser() +getLoginUrl() +handleCallback() }

  class MastraCloudAuthProvider {
      -client: MastraCloudAuth
      +authenticateToken(req)
      +getLoginUrl(returnTo)
      +handleCallback(req)
      +logout(req)
  }

  class MastraCloudAuth {
      -cloudUrl: string
      -clientId: string
      -redirectUrl: string
      +getLoginUrl(returnTo)
      +handleCallback(req)
      +verifyToken(token)
      +destroySession(token)
  }

  class MastraRBACCloud {
      -roleMapping: Map
      +getRoles(user)
      +getPermissions(user)
      +hasPermission(user, perm)
  }

  MastraAuthProvider <|-- MastraCloudAuthProvider
  MastraCloudAuthProvider --> MastraCloudAuth

KEY ENDPOINTS (Mastra Cloud) ┌────────────────────────┬──────────────────────────────┐ │ Endpoint │ Purpose │ ├────────────────────────┼──────────────────────────────┤ │ /auth/oss │ OAuth authorization redirect │ ├────────────────────────┼──────────────────────────────┤ │ /auth/callback │ Code → token exchange │ ├────────────────────────┼──────────────────────────────┤ │ /auth/verify │ Token → user info │ ├────────────────────────┼──────────────────────────────┤ │ /auth/session/validate │ Session validity check │ ├────────────────────────┼──────────────────────────────┤ │ /auth/session/destroy │ Server-side logout │ ├────────────────────────┼──────────────────────────────┤ │ /auth/logout │ Logout redirect URL │ └────────────────────────┴──────────────────────────────┘


COOKIE LIFECYCLE

timeline title Cookie Lifecycle section PKCE Cookie (5 min) Login Start : Set cookie with verifier + CSRF Callback : Read & validate cookie After Callback : Clear cookie section Session Cookie (24 hr) Callback Success : Set cookie with access token Each Request : Read & verify token Logout : Clear cookie


SECURITY LAYERS

  1. PKCE - Prevents code interception attacks
  2. CSRF - State param with random token
  3. Open Redirect - returnTo URL validation
  4. HttpOnly cookies - No JS access
  5. SameSite=Lax - CSRF protection
  6. Secure flag - HTTPS in prod