Skip to content
Merged
27 changes: 18 additions & 9 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
- **Check formatting**: `mvn spotless:check`

### Authentication Testing
- **Admin credentials**: `admin` / `admin123` (full CRUD access)
- **User credentials**: `user` / `user123` (read-only access)
- **Login endpoint**: `POST /api/v1/auth/login`
- **Bootstrap Required**: Initial admin user setup required on first deployment
- **Database-Managed Users**: All authentication managed via database (V4 schema)
- **Login endpoint**: `POST /api/v1/auth/login`
- **JWT token required**: All product endpoints require `Authorization: Bearer <token>`
- **Data Seeding**: Handled by application bootstrap service (task-14), not migrations

## Multi-Environment Architecture

Expand All @@ -58,7 +59,7 @@ This is an **enterprise-grade Spring Boot 3.5.4 REST API** for product catalog m
### Key Components - Enhanced
- **Product Entity**: Advanced model with inventory, categories, soft deletes, versioning
- **JWT Authentication**: Stateless auth with role-based access (ADMIN/USER)
- **Database**: PostgreSQL with 3 Flyway migrations and strategic indexing
- **Database**: PostgreSQL with 4 Flyway migrations and strategic indexing
- **Audit System**: Asynchronous audit logging for all CRUD operations
- **Testing Strategy**: 28+ tests (Unit, Integration, E2E) with 100% pass rate
- **API Documentation**: Enhanced Swagger UI with JWT security schemas
Expand Down Expand Up @@ -91,18 +92,26 @@ This is an **enterprise-grade Spring Boot 3.5.4 REST API** for product catalog m
## Development Notes - Enterprise Features

### Database Schema - Enhanced
- **Flyway Migrations**: 3 production-ready migrations with automatic execution
- **Flyway Migrations**: 4 production-ready migrations with automatic execution
- **Products Table**: Enhanced with inventory, categories, audit fields, soft delete
- **Strategic Indexing**: Indexes on `sku`, `category`, `stock_quantity`, `deleted`
- **User Management Tables** (V4 Migration):
- **Roles Table**: Normalized role management with granular permissions arrays (ADMIN, USER, MANAGER, READONLY)
- **Users Table**: Database-managed users with role-based access control, MCP access flags, BCrypt password hashing
- **API Keys Table**: Scoped API key management with expiration, usage tracking, and user association
- **User Role History**: Complete audit trail for all role changes with timestamps and change reasons
- **Strategic Indexing**: Indexes on `sku`, `category`, `stock_quantity`, `deleted`, plus 8 user management indexes
- **Data Types**: UUID primary keys, BigDecimal for prices, timestamps for auditing
- **Soft Delete**: Logical deletion preserving data integrity and audit trails

### Authentication & Security
- **JWT Implementation**: Stateless authentication with configurable expiration
- **Role-Based Access**: `ADMIN` (full CRUD) vs `USER` (read-only) permissions
- **Database-Managed Users**: V4 migration provides schema foundation; user data managed by application bootstrap (task-14)
- **Role-Based Access**: Enhanced with 4 roles - `ADMIN` (full CRUD), `USER` (read-only), `MANAGER` (write access), `READONLY` (minimal)
- **Granular Permissions**: Permission arrays including READ, WRITE, DELETE, USER_MANAGEMENT, MCP_TOOLS, API_KEY_MANAGEMENT
- **Security Filters**: JWT validation on all protected endpoints
- **Hardcoded Users**: Demo credentials for development and testing
- **Password Security**: Production-ready for external authentication integration
- **BCrypt Password Hashing**: Secure password storage with industry-standard encryption
- **API Key Management**: Scoped API keys with expiration and usage tracking
- **Audit Trail**: Complete role change history for compliance and security monitoring

### Testing Patterns - Comprehensive
- **Unit Tests**: `@ExtendWith(MockitoExtension.class)` with service layer isolation
Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ This project implements a **comprehensive, enterprise-grade RESTful API** for pr
* **Framework**: Spring Boot 3.5.4 with Spring Security
* **AI Framework**: Spring AI
* **Build Tool**: Maven
* **Database**: PostgreSQL with advanced indexing
* **Schema Migration**: Flyway (3 migrations)
* **Database**: PostgreSQL with advanced indexing and user management
* **Schema Migration**: Flyway (4 migrations)
* **Authentication**: JWT (JSON Web Tokens)
* **Containerization**: Docker & Docker Compose
* **Testing**: JUnit 5, Mockito, Testcontainers, RestAssured
Expand All @@ -20,7 +20,7 @@ This project implements a **comprehensive, enterprise-grade RESTful API** for pr
* **Logging**: Structured logging with audit trails

## πŸš€ Key Features
* πŸ” **Secure by Design**: Stateless JWT authentication with role-based access control (ADMIN vs. USER).
* πŸ” **Secure by Design**: Database-managed users with JWT authentication and granular role-based access control (ADMIN, USER, MANAGER, READONLY).
* πŸ“Š **Advanced Product Management**: Soft deletes, optimistic locking, inventory tracking, and custom validations.
* πŸ” **Powerful API**: Pagination, sorting, and advanced filtering capabilities.
* πŸ€– **Comprehensive AI Integration**: Natural language interface for catalog management via Spring AI's MCP Server.
Expand Down Expand Up @@ -62,9 +62,9 @@ For a detailed guide on every aspect of this project, please refer to the docume

### βœ… **Completed Features**
- Full CRUD API with advanced filtering
- JWT authentication with role-based authorization (ADMIN/USER)
- Database-managed users with JWT authentication and enhanced role-based authorization (ADMIN/USER/MANAGER/READONLY)
- Comprehensive test suite (28+ tests)
- Database optimization with indexing and soft deletes
- Database optimization with indexing, soft deletes, and user management audit trails
- Custom actuator endpoints for business metrics and health monitoring
- Docker containerization and multi-environment deployment
- Interactive API documentation and enhanced error handling
Expand Down
12 changes: 6 additions & 6 deletions backlog/config.yml
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
project_name: "product-catalog-spring"
project_name: "product-catalog"
default_status: "To Do"
statuses: ["To Do", "In Progress", "Pending Review", "Blocked", "Done"]
labels: []
statuses: ["To Do", "In Progress", "PR for Integration", "PR for Stage", "PR for Production", "Blocked", "Done"]
labels: ["database", "migration", "security", "foundation", "filters", "authentication", "validation", "controller", "api", "rest-api", "endpoints", "dto", "serialization", "seeding", "data", "production", "testing", "integration", "e2e", "configuration", "documentation", "deployment", "jpa", "entities", "domain", "repository", "data-access", "queries", "services", "jwt", "mcp", "tools", "admin", "user-management", "roles", "permissions", "self-service", "user-profile", "resources", "providers", "authorization"]
milestones: []
date_format: yyyy-mm-dd
max_column_width: 20
auto_open_browser: true
default_port: 6420
remote_operations: false
remote_operations: true
auto_commit: false
bypass_git_hooks: false
check_active_branches: false
active_branch_days: 30
check_active_branches: true
active_branch_days: 30
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ title: 'Database Schema Design & Migration - Users, Roles, and API Keys'
status: Pending Review
assignee: []
created_date: '2025-08-21 11:30'
updated_date: '2025-08-21 12:05'
updated_date: '2025-08-21 12:39'
labels:
- database
- migration
Expand Down Expand Up @@ -33,3 +33,7 @@ Create normalized database schema with separate tables for users, roles, and API
## Implementation Plan

1. Checkout develop branch and create feature/database-schema-users-roles-apikeys branch,2. Create V4__Create_users_roles_and_api_keys_tables.sql migration file,3. Implement roles table with id name description permissions timestamps,4. Implement users table with role_id foreign key and authentication fields,5. Implement api_keys table with user relationship and scoping,6. Implement user_role_history for audit trail,7. Add strategic indexes for performance optimization,8. Insert default roles with appropriate permissions,9. Migrate existing hardcoded users to database,10. Test migration locally with flyway,11. Commit and push changes,12. Create PR to develop branch

## Implementation Notes

Implementation complete: V4 migration follows enterprise best practices with schema-only approach. All data seeding removed from migration and moved to application bootstrap service (task-14) for security. Tables created: roles, users, api_keys, user_role_history. Architectural improvement: eliminates hardcoded credentials in version control, enables environment-specific user setup, and separates schema evolution from business data. Awaiting PR #34 review.
116 changes: 0 additions & 116 deletions docker-compose.vps-stage.yml

This file was deleted.

9 changes: 7 additions & 2 deletions docs/01-GETTING_STARTED.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,17 @@ mvn spring-boot:run

Once the application is running, you can interact with it using `cURL` or any API client.

1. **Get an Admin JWT Token**
1. **Initial Setup Required**

The application uses database-managed users with BCrypt password hashing (V4 schema).

**⚠️ First-Time Setup**: On first deployment, you'll need to create an initial admin user through the application's bootstrap process (implemented in task-14).

**After Bootstrap Setup:**
```bash
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"admin123"}'
-d '{"username":"your-admin-user","password":"your-secure-password"}'
```

This will return a JSON object with an `accessToken`. Copy the token for the next step.
Expand Down
36 changes: 22 additions & 14 deletions docs/03-API_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,17 @@ This document provides a detailed reference for all available API endpoints.

## πŸ” Authentication

### Default Credentials:
- **Admin**: `admin` / `admin123` (Full CRUD access)
- **User**: `user` / `user123` (Read-only access)
### Database-Managed Users (V4 Schema)
The authentication system uses database-managed users with BCrypt password hashing, replacing the previous hardcoded system.

### User Bootstrap Process:
The application requires initial user setup through a bootstrap service (implemented in task-14). No default users are seeded in migrations following enterprise security best practices.

### Available Roles:
- **ADMIN**: Full CRUD operations, user management, role management, API key management, MCP access
- **MANAGER**: Write operations, delete operations, API key management, MCP access (no user management)
- **USER**: Read operations, MCP tools and resources, SSE access
- **READONLY**: Minimal read-only access, limited MCP resources

| Method | Path | Description | Authorization |
|--------|-------------------------|----------------------------------|---------------|
Expand All @@ -17,12 +25,12 @@ This document provides a detailed reference for all available API endpoints.
## πŸ“¦ Product Management
| Method | Path | Description | Authorization |
|--------|--------------------------------|---------------------------------------|---------------|
| `POST` | `/products` | Create a new product | ADMIN |
| `GET` | `/products/{id}` | Retrieve a product by ID | USER/ADMIN |
| `GET` | `/products` | Retrieve products with pagination | USER/ADMIN |
| `GET` | `/products/low-stock` | Get products below minimum stock | USER/ADMIN |
| `PUT` | `/products/{id}` | Update an existing product | ADMIN |
| `DELETE`| `/products/{id}` | Soft delete a product | ADMIN |
| `POST` | `/products` | Create a new product | ADMIN/MANAGER |
| `GET` | `/products/{id}` | Retrieve a product by ID | All roles |
| `GET` | `/products` | Retrieve products with pagination | All roles |
| `GET` | `/products/low-stock` | Get products below minimum stock | All roles |
| `PUT` | `/products/{id}` | Update an existing product | ADMIN/MANAGER |
| `DELETE`| `/products/{id}` | Soft delete a product | ADMIN/MANAGER |

### πŸ” Advanced Query Parameters
The `GET /products` endpoint supports the following query parameters for filtering, sorting, and pagination:
Expand All @@ -40,11 +48,11 @@ The `GET /products` endpoint supports the following query parameters for filteri
| Method | Path | Description | Authorization |
|--------|--------------------------------|---------------------------------------|---------------|
| `GET` | `/actuator/health` | Application health status with custom product health | Public |
| `GET` | `/actuator/info` | Enhanced application information with features | USER/ADMIN |
| `GET` | `/actuator/metrics` | Standard Spring Boot metrics | USER/ADMIN |
| `GET` | `/actuator/productmetrics` | Custom product catalog metrics | USER/ADMIN |
| `GET` | `/actuator/audit` | Audit log summary and recent entries | USER/ADMIN |
| `GET` | `/actuator/audit/{entityId}` | Audit logs for specific entity | USER/ADMIN |
| `GET` | `/actuator/info` | Enhanced application information with features | All roles |
| `GET` | `/actuator/metrics` | Standard Spring Boot metrics | All roles |
| `GET` | `/actuator/productmetrics` | Custom product catalog metrics | All roles |
| `GET` | `/actuator/audit` | Audit log summary and recent entries | ADMIN only |
| `GET` | `/actuator/audit/{entityId}` | Audit logs for specific entity | ADMIN only |
| `GET` | `/swagger-ui/index.html` | Interactive API documentation | Public |
| `GET` | `/v3/api-docs` | OpenAPI specification (JSON) | Public |

Expand Down
2 changes: 1 addition & 1 deletion docs/05-ARCHITECTURE_AND_DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ com.thedavestack.productcatalog/

## πŸ”’ Security Architecture
- **JWT Stateless Authentication**: No server-side session storage, making the application scalable.
- **Role-Based Access Control**: Clear separation of duties between `ADMIN` (full CRUD) and `USER` (read-only) roles.
- **Enhanced Role-Based Access Control**: Database-managed users with 4 granular roles - `ADMIN` (full management), `MANAGER` (write access), `USER` (read + MCP), and `READONLY` (minimal access).
- **Input Validation**: Multi-layer validation using Bean Validation annotations (`@Valid`) and custom validators for business rules.
- **Developer-Friendly Errors**: 401 (Unauthorized) and 404 (Not Found) errors provide helpful links and guidance to the developer.

Expand Down
Loading
Loading