Files
query-orchestration/internal/cognitoauth/summary.md
T
jay brown d0bcf7b0d2 cleanup
2025-04-16 12:04:47 -07:00

111 lines
5.2 KiB
Markdown

# Cognito RBAC Design and Integration
## Overview
This package uses AWS Cognito for authentication and implements Role-Based Access Control (RBAC) for API endpoints. The integration is tightly coupled with the Echo web framework and the OpenAPI (swagger) generated API code.
## Key Components
### 1. Cognito Auth Package (`internal/cognitoauth`)
- **auth.go**: Main exports for the package.
- **handler.go**: HTTP handlers for login, callback, logout, and home.
- **middleware.go**: Echo middleware for JWT extraction, validation, and RBAC enforcement.
- **jwks.go**: Handles JWKS key fetching and JWT signature validation.
- **token.go**: Token verification and management.
- **models.go**: Data models and types for tokens, users, etc.
- **utils.go**: Helper functions.
- **config.go**: Configuration structures for the auth system.
### 2. Service Config (`internal/serviceconfig`)
- **auth/config.go**: Loads and manages authentication-related configuration, including RBAC route permissions.
- **common.go**: Shared config logic.
### 3. API Layer (`api/queryAPI`)
- **api.gen.go**: Swagger-generated API handlers.
- **authHandlers.go**: Bridges generated code to Cognito logic; delegates to middleware for most flows.
- **homehandler.go**: Displays authentication status.
- **controllers.go**: Wires up controllers, but does not directly handle auth.
### 4. Server Setup (`internal/server/api/listener.go`)
- Creates the Echo server.
- Sets up config and logging middleware.
- Sets up Prometheus and OpenAPI validation middleware.
- **Registers Cognito RBAC middleware and routes before registering API handlers.**
- Sets route-level permissions via a map of route to allowed groups.
## Cognito client user group setup
The cognito client must be setup to redirect back to /login-callback for PKCE flow to work.
## Integration Flow
1. **Config Initialization**: Auth config and route permissions are loaded at startup.
2. **Echo Server Setup**: The Echo instance is created and set on the config.
3. **RBAC Middleware Registration**:
- `cognitoauth.RegisterRoutes(echoRouter, config)` is called.
- This registers login, callback, logout, and home endpoints.
- It also registers JWT extraction and validation middleware.
- Route permissions are enforced via middleware that checks the user's Cognito groups/roles against the configured permissions map.
4. **API Handler Registration**:
- OpenAPI-generated handlers are registered after the RBAC middleware.
- All API endpoints are thus protected by the RBAC middleware.
5. **Request Flow**:
- User requests a protected endpoint.
- Middleware extracts JWT from cookies, validates it, and checks group membership.
- If authorized, the request proceeds to the handler (which may be swagger-generated).
- If not, a 401/403 is returned.
## Example
```go
// Set route permissions
routePermissions := map[string][]string{
"/users": {"exporters", "uploaders", "querybuilders"},
"/orders": {"exporters"},
// ...
}
config.SetAuthRoutePermissions(routePermissions)
// Register Cognito auth routes and middleware
cognitoauth.RegisterRoutes(echoRouter, config)
// Register API handlers (swagger-generated)
RegisterHandlers(echoRouter, controllers)
```
## Customization
- Paths for login, callback, logout, and home can be configured.
- Route permissions are fully customizable.
- Middleware can be extended or replaced for fine-grained control.
- User info is accessible in handlers via helper functions.
## Cognito auth flow (mermaid)
For a live graph of the auto flow go [here.](https://mermaid.live/edit#pako:eNp9VE2P2jAQ_SsjH3pisyQQAlHLimVXvfQDle0eKqTK6wxgAXZqO7sFxH_vOISvhZKDFdvPb968GXvNhM6QpczinwKVwAfJJ4YvRgroy7lxUsicKwf3Rr9ZNOcbvTwfonlFA9zCgxarZS-X94_nwL6eKOn0dmM7VqQ33e6eJYUwgM-PT3A71xOptrhv2iFoH-MIFxEOFRpOez6L37QqxxLNxxdz2z3dElM-n6Oa4JZvz0KRKw0pNAL4gZk0KBw4fSr3ILRaTqFZydS8cNPo1o_ayBXeBUFwKeYhhz1FHMDAaIHWgj8OxhfBui2-Qh0rbAW7VfjizYEB37FfEJgE8JOWQBjMUDnJ5_a_StoBPPO5zErD3uMvKOkcefUmSbrP-FpN68dFvRHkzAsXszt_7BMZdqXMYehjOSPx9V2dz2u5zyek5hh8Hx7K4_QMVdkYu5AfTrguiTiwNY7toWPAVQanMg4mHWunJnnykS3V1uZaWbyWKfXDsyddQinXlnr7UxQzyNEspLWSKK60cEgd0qN8ffkEd4QGWwjfYONizmpsQSxcZnTf155lxAi6wBFL6TfjZjZiI7UhHHmmh0slWOpMgTVmdDGZsnRMLUGzIvdGVC_FDkJX_JfW-yk1h9Pm6_ZxKd-YGpsYH7piRJWh6etCOZZ2yuMsXbO_LA3rSdAMw7DRiOJOUo86cY0tWZokQb3ZbMRRFLWjsBVvamxVxqsH7aSexO1WHLX8X9TZ_AMOB5n7)
```mermaid
sequenceDiagram
participant Browser
participant AppServer as DoczyApiBE
participant Cognito
Browser->>AppServer: 1. GET /login
Note over AppServer: 2. Generate code_verifier<br/>Generate code_challenge
AppServer->>Browser: 3. Redirect to Cognito
Browser->>Cognito: 4. GET /oauth2/authorize?...code_challenge
Note over Cognito: 5. Process auth request
Cognito->>Browser: 6. Cognito Login Page
Browser->>Cognito: 7. User credentials
Note over Cognito: 8. Validate credentials
Cognito->>Browser: 9. Redirect with code
Browser->>AppServer: 10. GET /login-callback?code=...
Note over AppServer: 11. Retrieve code_verifier
AppServer->>Cognito: 12. POST /oauth2/token<br/>code=...&code_verifier=...
Note over Cognito: 13. Validate code and verifier
Cognito->>AppServer: 14. Tokens response
Note over AppServer: 15. Verify tokens<br/>Check permissions
AppServer->>Browser: 16. Authentication successful
```