feat: reword phase to epic, update mkdocs

This commit is contained in:
2025-11-05 09:28:33 +01:00
parent 65a428534c
commit ace9678f6c
64 changed files with 214 additions and 208 deletions

View File

@@ -0,0 +1,139 @@
# Story 2.1: JWT Authentication System
## Metadata
- **Story ID**: 2.1
- **Title**: JWT Authentication System
- **Epic**: 2 - Authentication & Authorization
- **Status**: Pending
- **Priority**: High
- **Estimated Time**: 6-8 hours
- **Dependencies**: 1.2, 1.5
## Goal
Implement a complete JWT-based authentication system with access tokens, refresh tokens, and secure token management.
## Description
This story implements the complete JWT authentication system including token generation, verification, authentication middleware, and login/refresh endpoints. The system supports short-lived access tokens and long-lived refresh tokens for secure authentication.
## Deliverables
### 1. Authentication Interfaces (`pkg/auth/auth.go`)
- `Authenticator` interface for token generation and verification
- `TokenClaims` struct with user ID, roles, tenant ID, expiration
- Token validation utilities
### 2. JWT Implementation (`internal/auth/jwt_auth.go`)
- Generate short-lived access tokens (15 minutes default)
- Generate long-lived refresh tokens (7 days default)
- Token signature verification using HMAC or RSA
- Token expiration validation
- Claims extraction and validation
### 3. Authentication Middleware (`internal/auth/middleware.go`)
- Extract JWT from `Authorization: Bearer <token>` header
- Verify token validity (signature and expiration)
- Inject authenticated user into request context
- Helper function: `auth.FromContext(ctx) *User`
- Handle authentication errors appropriately
### 4. Authentication Endpoints
- `POST /api/v1/auth/login` - Authenticate user and return tokens
- Validate email and password
- Return access + refresh tokens
- Log login attempts
- `POST /api/v1/auth/refresh` - Refresh access token using refresh token
- Validate refresh token
- Issue new access token
- Optionally rotate refresh token
### 5. gRPC Server (Microservices)
- Expose gRPC server for authentication service
- gRPC service definition in `api/proto/auth.proto`
- gRPC server implementation in `internal/auth/grpc/server.go`
- Service registration in service registry
### 6. Integration
- Integration with DI container
- Use `IdentityServiceClient` for user operations (if Identity service is separate)
- Integration with HTTP server
- Integration with user repository
- Integration with audit logging
## Implementation Steps
1. **Install Dependencies**
```bash
go get github.com/golang-jwt/jwt/v5
```
2. **Create Authentication Interfaces**
- Create `pkg/auth/auth.go`
- Define Authenticator interface
- Define TokenClaims struct
3. **Implement JWT Authentication**
- Create `internal/auth/jwt_auth.go`
- Implement token generation
- Implement token verification
- Handle token expiration
4. **Create Authentication Middleware**
- Create `internal/auth/middleware.go`
- Implement token extraction
- Implement token verification
- Inject user into context
5. **Create Authentication Endpoints**
- Create login handler
- Create refresh handler
- Add routes to HTTP server
6. **Integrate with DI**
- Create provider function
- Register in container
## Acceptance Criteria
- [ ] Users can login and receive access and refresh tokens
- [ ] Access tokens expire after configured duration
- [ ] Refresh tokens can be used to obtain new access tokens
- [ ] Invalid tokens are rejected with appropriate errors
- [ ] Authenticated user is available in request context
- [ ] Login attempts are logged (success and failure)
- [ ] Token secrets are configurable
- [ ] Token claims include user ID, roles, and tenant ID
## Related ADRs
- [ADR-0017: JWT Token Strategy](../../adr/0017-jwt-token-strategy.md)
- [ADR-0029: Microservices Architecture](../../adr/0029-microservices-architecture.md)
- [ADR-0030: Service Communication Strategy](../../adr/0030-service-communication-strategy.md)
## Implementation Notes
- Use JWT v5 library
- Support both HMAC and RSA signing
- Token secrets should be configurable
- Consider token blacklisting for logout (future enhancement)
- Refresh tokens should be stored securely (database or cache)
## Testing
```bash
# Test authentication
go test ./internal/auth/...
# Test login endpoint
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"password"}'
# Test refresh endpoint
curl -X POST http://localhost:8080/api/v1/auth/refresh \
-H "Authorization: Bearer <refresh_token>"
```
## Files to Create/Modify
- `pkg/auth/auth.go` - Authentication interfaces
- `internal/auth/jwt_auth.go` - JWT implementation
- `internal/auth/middleware.go` - Authentication middleware
- `internal/auth/handler.go` - Authentication handlers
- `internal/di/providers.go` - Add auth provider
- `config/default.yaml` - Add JWT configuration

View File

@@ -0,0 +1,82 @@
# Story 2.2: Identity Management System
## Metadata
- **Story ID**: 2.2
- **Title**: Identity Management System
- **Epic**: 2 - Authentication & Authorization
- **Status**: Pending
- **Priority**: High
- **Estimated Time**: 8-10 hours
- **Dependencies**: 1.2, 2.1
## Goal
Build a complete user identity management system with registration, email verification, password management, and user CRUD operations.
## Description
This story implements the complete user identity management system including user registration, email verification, password reset, password change, and user profile management. All operations are secured and audited.
## Deliverables
### 1. Identity Interfaces (`pkg/identity/identity.go`)
- `UserRepository` interface for user data access
- `UserService` interface for user business logic
- User domain models
### 2. User Repository (`internal/identity/user_repo.go`)
- CRUD operations using Ent
- Password hashing (bcrypt or argon2)
- Email uniqueness validation
- User lookup by ID and email
- User search and pagination
### 3. User Service (`internal/identity/user_service.go`)
- User registration with email verification token generation
- Email verification flow
- Password reset flow (token-based, time-limited)
- Password change with old password verification
- User profile updates
- User deletion (soft delete option)
### 4. User Management API Endpoints
- `POST /api/v1/users` - Register new user
- `GET /api/v1/users/:id` - Get user profile (authorized)
- `PUT /api/v1/users/:id` - Update user profile (authorized)
- `DELETE /api/v1/users/:id` - Delete user (admin only)
- `POST /api/v1/users/verify-email` - Verify email with token
- `POST /api/v1/users/reset-password` - Request password reset
- `POST /api/v1/users/change-password` - Change password
### 5. gRPC Server (Microservices)
- Expose gRPC server for identity service
- gRPC service definition in `api/proto/identity.proto`
- gRPC server implementation in `internal/identity/grpc/server.go`
- Service registration in service registry
### 6. Integration
- Integration with email notification system (Epic 5 placeholder)
- Integration with audit logging
- Integration with authentication system
- Identity service is an independent service that can be deployed separately
## Acceptance Criteria
- [ ] Users can register with email and password
- [ ] Passwords are securely hashed
- [ ] Email verification tokens are generated and validated
- [ ] Password reset flow works end-to-end
- [ ] Users can update their profiles
- [ ] User operations require proper authentication
- [ ] All user actions are audited
- [ ] Email uniqueness is enforced
## Related ADRs
- [ADR-0018: Password Hashing](../../adr/0018-password-hashing.md)
- [ADR-0029: Microservices Architecture](../../adr/0029-microservices-architecture.md)
- [ADR-0030: Service Communication Strategy](../../adr/0030-service-communication-strategy.md)
## Files to Create/Modify
- `pkg/identity/identity.go` - Identity interfaces
- `internal/identity/user_repo.go` - User repository
- `internal/identity/user_service.go` - User service
- `internal/identity/handler.go` - User handlers
- `internal/di/providers.go` - Add identity providers

View File

@@ -0,0 +1,70 @@
# Story 2.3: Role-Based Access Control (RBAC) System
## Metadata
- **Story ID**: 2.3
- **Title**: Role-Based Access Control (RBAC) System
- **Epic**: 2 - Authentication & Authorization
- **Status**: Pending
- **Priority**: High
- **Estimated Time**: 6-8 hours
- **Dependencies**: 1.2, 2.1
## Goal
Implement a complete RBAC system with permissions, role management, and authorization middleware.
## Description
This story implements the complete RBAC system including permission definitions, permission resolution, authorization checking, and middleware for protecting routes.
## Deliverables
### 1. Permission System (`pkg/perm/perm.go`)
- `Permission` type (string format: "module.resource.action")
- Core permission constants (system, user, role permissions)
- Permission validation utilities
### 2. Permission Resolver (`pkg/perm/resolver.go` & `internal/perm/in_memory_resolver.go`)
- `PermissionResolver` interface
- Implementation that loads user roles and permissions from database
- Permission checking with caching
- Permission inheritance via roles
### 3. Authorization System (`pkg/auth/authz.go` & `internal/auth/rbac_authorizer.go`)
- `Authorizer` interface
- RBAC authorizer implementation
- Extract user from context
- Check permissions
- Return authorization errors
### 4. Authorization Middleware
- `RequirePermission(perm Permission) gin.HandlerFunc` decorator
- Integration with route registration
- Proper error responses for unauthorized access
### 5. gRPC Server (Microservices)
- Expose gRPC server for authorization service
- gRPC service definition in `api/proto/authz.proto`
- gRPC server implementation in `internal/auth/grpc/authz_server.go`
- Service registration in service registry
- Uses `IdentityServiceClient` for user operations
## Acceptance Criteria
- [ ] Permissions are defined and can be checked
- [ ] Users inherit permissions through roles
- [ ] Authorization middleware protects routes
- [ ] Unauthorized requests return 403 errors
- [ ] Permission checks are cached for performance
- [ ] Permission system is extensible by modules
## Related ADRs
- [ADR-0019: Permission DSL Format](../../adr/0019-permission-dsl-format.md)
- [ADR-0029: Microservices Architecture](../../adr/0029-microservices-architecture.md)
- [ADR-0030: Service Communication Strategy](../../adr/0030-service-communication-strategy.md)
## Files to Create/Modify
- `pkg/perm/perm.go` - Permission types
- `pkg/perm/resolver.go` - Permission resolver interface
- `internal/perm/in_memory_resolver.go` - Permission resolver implementation
- `pkg/auth/authz.go` - Authorization interface
- `internal/auth/rbac_authorizer.go` - RBAC authorizer
- `internal/auth/middleware.go` - Add authorization middleware

View File

@@ -0,0 +1,64 @@
# Story 2.4: Role Management API
## Metadata
- **Story ID**: 2.4
- **Title**: Role Management API
- **Epic**: 2 - Authentication & Authorization
- **Status**: Pending
- **Priority**: High
- **Estimated Time**: 5-6 hours
- **Dependencies**: 1.2, 2.3
## Goal
Provide complete API for managing roles, assigning permissions to roles, and assigning roles to users.
## Description
This story implements the complete role management API allowing administrators to create, update, and delete roles, assign permissions to roles, and assign roles to users.
## Deliverables
### 1. Role Repository (`internal/identity/role_repo.go`)
- CRUD operations for roles
- Assign permissions to roles (many-to-many)
- Assign roles to users (many-to-many)
- List roles with permissions
- List users with roles
### 2. Role Management API Endpoints
- `POST /api/v1/roles` - Create new role
- `GET /api/v1/roles` - List all roles (with pagination)
- `GET /api/v1/roles/:id` - Get role details with permissions
- `PUT /api/v1/roles/:id` - Update role
- `DELETE /api/v1/roles/:id` - Delete role
- `POST /api/v1/roles/:id/permissions` - Assign permissions to role
- `DELETE /api/v1/roles/:id/permissions/:permId` - Remove permission from role
- `POST /api/v1/users/:id/roles` - Assign roles to user
- `DELETE /api/v1/users/:id/roles/:roleId` - Remove role from user
### 3. Authorization and Validation
- All endpoints protected (admin only)
- Input validation
- Error handling
### 4. gRPC Server (Microservices)
- Expose role management via existing Authz service gRPC server
- Role management methods in `api/proto/authz.proto`
- Service registration in service registry
## Acceptance Criteria
- [ ] Admin users can create and manage roles
- [ ] Permissions can be assigned to roles
- [ ] Roles can be assigned to users
- [ ] Role changes affect user permissions immediately
- [ ] All role operations are audited
- [ ] API endpoints are protected with proper permissions
## Related ADRs
- [ADR-0029: Microservices Architecture](../../adr/0029-microservices-architecture.md)
- [ADR-0030: Service Communication Strategy](../../adr/0030-service-communication-strategy.md)
## Files to Create/Modify
- `internal/identity/role_repo.go` - Role repository
- `internal/identity/role_handler.go` - Role handlers
- `internal/server/routes.go` - Add role routes

View File

@@ -0,0 +1,74 @@
# Story 2.5: Audit Logging System
## Metadata
- **Story ID**: 2.5
- **Title**: Audit Logging System
- **Epic**: 2 - Authentication & Authorization
- **Status**: Pending
- **Priority**: High
- **Estimated Time**: 5-6 hours
- **Dependencies**: 1.2, 2.1
## Goal
Implement comprehensive audit logging that records all security-sensitive actions for compliance and security monitoring.
## Description
This story implements a complete audit logging system that records all authenticated actions with full context including actor, action, target, and metadata.
## Deliverables
### 1. Audit Interface (`pkg/audit/audit.go`)
- `Auditor` interface with `Record(ctx, action)` method
- `AuditAction` struct with actor, action, target, metadata
### 2. Audit Implementation (`internal/audit/ent_auditor.go`)
- Write audit logs to `audit_log` table
- Capture actor from request context
- Include request metadata (ID, IP, user agent, timestamp)
- Store action details and target information
- Support JSON metadata for flexible logging
### 3. Audit Middleware
- Intercept all authenticated requests
- Record action (HTTP method + path)
- Extract user and request context
- Store audit log entry
### 4. gRPC Server (Microservices)
- Expose gRPC server for audit service
- gRPC service definition in `api/proto/audit.proto`
- gRPC server implementation in `internal/audit/grpc/server.go`
- Service registration in service registry
### 5. Integration
- Integration with authentication endpoints
- Log login attempts (success and failure)
- Log password changes
- Log role assignments and removals
- Log permission changes
- Log user registration
### 5. Audit Log Query API
- `GET /api/v1/audit-logs` - Query audit logs with filters (admin only)
- Support filtering by actor, action, date range
- Pagination support
## Acceptance Criteria
- [ ] All authenticated actions are logged
- [ ] Audit logs include complete context (actor, action, target, metadata)
- [ ] Audit logs are immutable (no updates/deletes)
- [ ] Audit logs can be queried and filtered
- [ ] Audit logging has minimal performance impact
- [ ] Audit logs are stored securely
## Related ADRs
- [ADR-0020: Audit Logging Storage](../../adr/0020-audit-logging-storage.md)
- [ADR-0029: Microservices Architecture](../../adr/0029-microservices-architecture.md)
- [ADR-0030: Service Communication Strategy](../../adr/0030-service-communication-strategy.md)
## Files to Create/Modify
- `pkg/audit/audit.go` - Audit interface
- `internal/audit/ent_auditor.go` - Audit implementation
- `internal/audit/middleware.go` - Audit middleware
- `internal/audit/handler.go` - Audit query handler

View File

@@ -0,0 +1,57 @@
# Story 2.6: Database Seeding and Initialization
## Metadata
- **Story ID**: 2.6
- **Title**: Database Seeding and Initialization
- **Epic**: 2 - Authentication & Authorization
- **Status**: Pending
- **Priority**: Medium
- **Estimated Time**: 3-4 hours
- **Dependencies**: 1.2, 2.3, 2.4
## Goal
Provide database seeding functionality to create initial admin user, default roles, and core permissions.
## Description
This story implements a seeding system that creates the initial admin user, default roles (admin, user, guest), and assigns core permissions to enable the platform to be used immediately after setup.
## Deliverables
### 1. Seed Script (`internal/seed/seed.go`)
- Create default admin user (if doesn't exist)
- Create default roles (admin, user, guest)
- Assign core permissions to roles
- Set up initial role hierarchy
- Idempotent operations (safe to run multiple times)
### 2. Seed Command (`cmd/seed/main.go`)
- Command-line interface for seeding
- Configuration via environment variables
- Dry-run mode
- Verbose logging
### 3. Integration
- Optional: Auto-seed on first startup in development
- Manual seeding in production
- Integration with application startup
## Acceptance Criteria
- [ ] Seed script creates admin user successfully
- [ ] Default roles are created with proper permissions
- [ ] Seeding is idempotent (can run multiple times safely)
- [ ] Seed script can be run via CLI
- [ ] Admin user can login and manage system
## Related ADRs
- [ADR-0029: Microservices Architecture](../../adr/0029-microservices-architecture.md)
## Implementation Notes
- Seeding is typically done once per environment
- Can be run as a separate service or as part of deployment
- Uses service clients if accessing services (e.g., IdentityServiceClient for user creation)
## Files to Create/Modify
- `internal/seed/seed.go` - Seed functions
- `cmd/seed/main.go` - Seed command
- `Makefile` - Add seed command

View File

@@ -0,0 +1,52 @@
# Epic 2: Authentication & Authorization
## Overview
Implement complete JWT-based authentication system, build comprehensive identity management with user lifecycle, create role-based access control (RBAC) system, implement authorization middleware and permission checks, add comprehensive audit logging for security compliance, and provide database seeding for initial setup. All core services (Auth, Identity, Authz, Audit) are independent microservices that expose gRPC servers and register with the service registry.
## Stories
### 2.1 JWT Authentication System
- [Story: 2.1 - JWT Authentication](./2.1-jwt-authentication.md)
- **Goal:** Implement a complete JWT-based authentication system with access tokens, refresh tokens, and secure token management.
- **Deliverables:** Authentication interfaces, JWT implementation, authentication middleware, login/refresh endpoints
### 2.2 Identity Management System
- [Story: 2.2 - Identity Management](./2.2-identity-management.md)
- **Goal:** Build a complete user identity management system with registration, email verification, password management, and user CRUD operations.
- **Deliverables:** Identity interfaces, user repository, user service, user management API endpoints
### 2.3 Role-Based Access Control (RBAC) System
- [Story: 2.3 - RBAC System](./2.3-rbac-system.md)
- **Goal:** Implement a complete RBAC system with permissions, role management, and authorization middleware.
- **Deliverables:** Permission system, permission resolver, authorization system, authorization middleware
### 2.4 Role Management API
- [Story: 2.4 - Role Management](./2.4-role-management.md)
- **Goal:** Provide complete API for managing roles, assigning permissions to roles, and assigning roles to users.
- **Deliverables:** Role repository, role management API endpoints, authorization and validation
### 2.5 Audit Logging System
- [Story: 2.5 - Audit Logging](./2.5-audit-logging.md)
- **Goal:** Implement comprehensive audit logging that records all security-sensitive actions for compliance and security monitoring.
- **Deliverables:** Audit interface, audit implementation, audit middleware, audit log query API
### 2.6 Database Seeding and Initialization
- [Story: 2.6 - Database Seeding](./2.6-database-seeding.md)
- **Goal:** Provide database seeding functionality to create initial admin user, default roles, and core permissions.
- **Deliverables:** Seed script, seed command, integration with application startup
## Deliverables Checklist
- [ ] JWT authentication with access/refresh tokens
- [ ] User CRUD with email verification
- [ ] Role and permission management
- [ ] Authorization middleware
- [ ] Audit logging for all actions
- [ ] Seed script for initial data
## Acceptance Criteria
- User can register and login
- JWT tokens are validated on protected routes
- Users without permission get 403
- All actions are logged in audit table
- Admin can create roles and assign permissions
- Integration test: user without permission cannot access protected resource