update summary for auth docs

This commit is contained in:
jay brown
2025-07-11 12:45:52 -07:00
parent 2ff6e05ffc
commit 0b84122ab7
+90 -31
View File
@@ -1,25 +1,27 @@
# Cognito RBAC Design and Integration
# Cognito Auth + Permit.io Authorization 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.
This package uses AWS Cognito for authentication and Permit.io for dynamic authorization of 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.
- **auth.go**: Main exports for the package and middleware registration.
- **handler.go**: HTTP handlers for login, callback, logout, and home.
- **middleware.go**: Echo middleware for JWT extraction, validation, and RBAC enforcement.
- **middleware.go**: Echo middleware for JWT extraction, validation, and Permit.io authorization 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.
- **permitio.go**: Permit.io client integration and authorization logic.
- **mapping.go**: Route-to-resource and HTTP method-to-action mapping.
- **validation.go**: Startup validation for Permit.io configuration.
- **validation_unit_test.go**: Unit tests for validation functions.
### 2. Service Config (`internal/serviceconfig`)
- **auth/config.go**: Loads and manages authentication-related configuration, including RBAC route permissions.
- **auth/config.go**: Loads and manages authentication-related configuration and Permit.io settings.
- **common.go**: Shared config logic.
### 3. API Layer (`api/queryAPI`)
@@ -34,57 +36,114 @@ This package uses AWS Cognito for authentication and implements Role-Based Acces
- 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.
- **Registers Cognito authentication middleware and routes before registering API handlers.**
- **Validates Permit.io configuration at startup.**
## 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**:
1. **Config Initialization**: Auth config and Permit.io settings are loaded at startup.
2. **Startup Validation**: `ValidatePermitIOConfiguration()` validates PDP connectivity and API key.
3. **Echo Server Setup**: The Echo instance is created and set on the config.
4. **Auth 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**:
- It registers two middleware components: JWT extraction and token validation.
- Authorization is enforced via Permit.io Policy Decision Point (PDP) queries.
5. **API Handler Registration**:
- OpenAPI-generated handlers are registered after the auth middleware.
- All API endpoints are protected by the authentication and authorization middleware.
6. **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.
- Middleware extracts JWT from cookies/headers and validates it.
- Route is mapped to resource (first path segment) and HTTP method to action.
- Permit.io PDP is queried: `CheckPermission(user_subject, action, resource)`.
- If authorized, the request proceeds to the handler.
- If not, a JSON error response is returned (401/403).
## Example
## Environment Configuration
```bash
# AWS Cognito Authentication
COGNITO_CLIENT_ID=your-client-id
COGNITO_CLIENT_SECRET=your-client-secret
COGNITO_USER_POOL_ID=your-pool-id
COGNITO_DOMAIN=https://your-domain.auth.region.amazoncognito.com
AWS_REGION=us-east-2
# Permit.io Authorization
PERMIT_IO_API_KEY=permit_key_...
PERMIT_IO_PDP_URL=http://localhost:7766
# Feature Flags
DISABLE_AUTH=false
NO_JWT_VALIDATION=false # Only for testing
```
## Integration Example
```go
// Set route permissions
routePermissions := map[string][]string{
"/users": {"exporters", "uploaders", "querybuilders"},
"/orders": {"exporters"},
// ...
// Validate Permit.io configuration at startup
if err := cognitoauth.ValidatePermitIOConfiguration(); err != nil {
log.Fatal("Permit.io validation failed:", err)
}
config.SetAuthRoutePermissions(routePermissions)
// Register Cognito auth routes and middleware
cognitoauth.RegisterRoutes(echoRouter, config)
// Register API handlers (swagger-generated)
// Register API handlers (swagger-generated)
RegisterHandlers(echoRouter, controllers)
```
## Customization
- Paths for login, callback, logout, and home can be configured.
- Route permissions are fully customizable.
- Permit.io resources and actions are automatically mapped but can be customized.
- Middleware can be extended or replaced for fine-grained control.
- User info is accessible in handlers via helper functions.
- Authorization policies are managed through Permit.io dashboard/API.
## Cognito auth flow (mermaid)
## Authorization Flow
The system performs two-stage security enforcement:
1. **Authentication** (AWS Cognito):
- JWT token validation
- User identity verification
- Claims extraction (subject, groups, etc.)
2. **Authorization** (Permit.io):
- Route → Resource mapping (`/document/123``document`)
- HTTP Method → Action mapping (`GET``get`)
- PDP Query: `CheckPermission(user_subject, action, resource)`
- Dynamic policy evaluation
### Error Responses
**Authentication Error** (401):
```json
{
"error": "Authorization required",
"message": "This endpoint requires authentication. Please obtain a valid JWT token.",
"login_url": "/login"
}
```
**Authorization Error** (403):
```json
{
"error": "Insufficient permissions",
"message": "Access denied by authorization service",
"user": "user-subject-id",
"resource": "document",
"action": "get"
}
```
## Cognito Authentication 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