Skip to main content

🏗️ Boilerplate Enhancements – Solution Architecture

Purpose: This document defines the system design for the Boilerplate Enhancements capability in Constellation.

This architecture document explains how boilerplate enhancements are structured, why design decisions were made, and how they integrate with the Constellation platform. For step-by-step implementation instructions, see the Implementation Guides.

Epic Reference: This architecture implements the Boilerplate Enhancements Epic.


Architecture Overview

What We're Building

Security and infrastructure enhancements that make Constellation secure, stable, production-ready, and developer-friendly:

  • Security Hardening - Fix critical vulnerabilities (CORS, JWT, CSRF, passwords, rate limiting)
  • Reliability Improvements - Fix unsafe patterns (Optional, transactions, exception handling)
  • Configuration Cleanup - Fix production configuration (URLs, secrets, profiles)
  • Test Coverage Enhancement - Comprehensive tests (integration, unit, API endpoint, frontend)
  • API Contract & Documentation - OpenAPI specs, Swagger UI, contract tests
  • Database Schema & Validation - Ensures schema integrity and prevents drift
  • Production Infrastructure - Connection pooling, monitoring, JSON serialization
  • Code Quality & Developer Experience - Code quality enforcement, workflow tools, debugging
  • Code Generation Infrastructure - OpenAPI Generator foundation for future APIs
  • Test Infrastructure - Clean test execution setup

What Makes These Enhancements Reusable

  • Zero business logic - Pure infrastructure, no domain-specific code
  • Production-proven - All changes validated in CBT Buddy POC
  • Standards-based - Uses Spring Boot, Hibernate, Gradle best practices
  • Extensible - Foundation for future features, not just current needs

Design Principles

Security First

All enhancements prioritize security:

  • Fix critical vulnerabilities before adding features
  • CORS uses allowedOriginPatterns (not wildcard)
  • JWT validation prevents token forgery
  • CSRF protection prevents state-changing attacks
  • Password policies prevent weak passwords
  • Rate limiting prevents brute force attacks
  • Secrets externalized to environment variables

Production Safety

All enhancements prioritize production stability and safety:

  • Schema validation prevents accidental schema changes
  • Connection pooling prevents resource exhaustion
  • Monitoring enables production observability
  • Proper configuration prevents runtime errors
  • Transaction management prevents data inconsistency
  • Proper exception handling prevents silent failures

Developer Experience

Enhancements improve developer workflow:

  • Code quality enforcement catches issues early
  • Schema generation workflow simplifies database development
  • Better logging aids debugging
  • Clear tooling reduces cognitive load

Minimal, Proven Changes

  • Only port changes proven in POC
  • No invention, only proven patterns
  • Conservative approach: fix what's broken, add what's needed
  • Avoid over-engineering

Foundation for Future Features

  • Enhancements enable future features (including Text Intelligence)
  • Code generation infrastructure available for future APIs
  • Production readiness enables all features
  • Stable foundation reduces risk

System Boundaries

What's Included

Security Hardening:

  • WebSecurityConfig CORS configuration fix
  • JwtTokenProvider validation implementation
  • CSRF configuration with cookie-based tokens
  • PasswordValidator implementation
  • RateLimitingConfig for auth endpoints
  • Secret externalization pattern
  • Input validation annotations

Reliability Improvements:

  • Optional.get() to orElseThrow() refactoring
  • @Transactional annotations on service methods
  • Exception handling improvements
  • Null check additions in critical paths

Configuration Cleanup:

  • environment.prod.ts URL fixes
  • Profile-based devtools configuration
  • Logging configuration (exclude sensitive data)
  • .env.template creation

Test Coverage Enhancement:

  • Integration test classes for auth, payments, user management
  • Unit test classes for service layer
  • Repository tests with H2 database
  • API endpoint tests with MockMvc/RestAssured
  • Frontend component tests with Jasmine/Karma
  • Test data builders and fixtures

API Contract & Documentation:

  • OpenAPI 3.0 specification files
  • SpringDoc annotations on controllers
  • Spring Cloud Contract or Pact configuration
  • Swagger UI configuration
  • API versioning strategy

Database Schema & Validation:

  • V3 schema synchronization migration
  • Hibernate ddl-auto: validate configuration
  • DDL generation Spring profile
  • DDL generation Gradle task

Production Infrastructure:

  • Hikari connection pool configuration
  • Spring Boot Actuator dependency and configuration
  • JacksonConfiguration JavaTimeModule registration
  • Production-ready configuration patterns

Code Quality & Developer Experience:

  • Checkstyle plugin configuration (strict enforcement)
  • Checkstyle suppressions file (exclude generated sources)
  • DDL generation workflow (task + profile)
  • Hibernate logging configuration
  • Detailed logging configuration

Code Generation Infrastructure:

  • OpenAPI Generator Gradle plugin
  • Basic configuration (generalized, not AI-specific)
  • SourceSets configuration for generated sources
  • Test with toy OpenAPI spec
  • Checkstyle suppressions for generated code

Test Infrastructure:

  • Test profile Flyway disable configuration
  • Clean test execution setup

What's NOT Included

AI Capabilities (Text Intelligence Epic):

  • ❌ ChatModel beans, Ollama configuration
  • ❌ LangChain4j integration
  • ❌ AI migrations (V4-V6)
  • ❌ AI Spring profiles

Product-Specific Logic:

  • ❌ Business logic
  • ❌ Domain entities (beyond schema sync)
  • ❌ Frontend changes

Already Implemented:

  • ❌ Authentication, Payments, Email (already in Springular)
  • ❌ Basic CI/CD (already present, only enhancements would be added)
  • ❌ Basic Docker setup (already present)

Component Design

Feature 1: Database Schema & Validation

Purpose: Ensure database schema matches JPA entities and prevent schema drift.

Components:

  • V3__sync_entity_schema.sql - Migration that syncs schema with entities
  • application.yml - Hibernate ddl-auto: validate configuration
  • application.yml - ddl-generate Spring profile
  • build.gradle - DDL generation task

Patterns:

  • Flyway as single source of truth for schema
  • Hibernate validates against Flyway migrations
  • DDL generation profile for developer workflow
  • Schema sync migration ensures entity expectations match database

Dependencies:

  • Requires Flyway (already in Springular)
  • Requires Hibernate (already in Springular)

Feature 2: Production Infrastructure

Purpose: Production-ready infrastructure and monitoring.

Components:

  • application.yml - Hikari connection pool configuration
  • build.gradle - Spring Boot Actuator dependency
  • application.yml - Actuator configuration
  • JacksonConfiguration.java - JavaTimeModule registration
  • build.gradle - Jackson JSR310 dependency

Patterns:

  • Connection pooling for production stability
  • Actuator for health checks and monitoring
  • JavaTimeModule for proper date/time JSON serialization
  • Configuration-driven (all via application.yml)

Dependencies:

  • Requires Spring Boot Actuator dependency
  • Requires Jackson JSR310 dependency
  • Requires existing JacksonConfiguration class

Feature 3: Code Quality & Developer Experience

Purpose: Enforce code quality and improve developer workflow.

Components:

  • build.gradle - Checkstyle plugin configuration
  • config/checkstyle/checkstyle-suppressions.xml - Suppressions file
  • application.yml - Hibernate logging configuration
  • application.yml - Detailed logging configuration

Patterns:

  • Checkstyle strict enforcement (maxWarnings = 0)
  • Suppressions file for generated sources
  • Enhanced logging for debugging

Dependencies:

  • Requires Checkstyle plugin
  • Works with OpenAPI Generator (exclude generated code via suppressions file)

Feature 4: Code Generation Infrastructure

Purpose: General-purpose code generation setup for future APIs.

Components:

  • build.gradle - OpenAPI Generator plugin
  • build.gradle - OpenAPI Generator configuration (generalized)
  • build.gradle - SourceSets configuration
  • src/main/resources/api/toy-api-openapi.yml - Test spec
  • config/checkstyle/checkstyle-suppressions.xml - Exclude generated code

Patterns:

  • General-purpose setup (not AI-specific)
  • Test with toy spec to verify infrastructure
  • Generated code excluded from checkstyle
  • Documented pattern for future use

Dependencies:

  • Requires Checkstyle suppressions (Feature 3)
  • Used by Text Intelligence Epic (optional, can use manual DTOs)

Feature 5: Test Infrastructure

Purpose: Clean test execution setup.

Components:

  • application.yml - Test profile Flyway disable configuration

Patterns:

  • H2 auto-creates schema in tests
  • Flyway disabled in test profile
  • Clean separation of concerns

Dependencies:

  • Requires H2 test database (already in Springular)
  • Works with Flyway migrations

Feature 6: Security Hardening

Purpose: Fix critical security vulnerabilities identified in code analysis.

Components:

  • WebSecurityConfig.java - CORS and CSRF configuration
  • JwtTokenProvider.java - JWT token validation
  • PasswordValidator.java - Password complexity validation (NEW)
  • RateLimitingConfig.java - Rate limiting configuration (NEW)
  • application.yml - Secret externalization pattern
  • DTOs with @Valid annotations - Input validation

Patterns:

  • CORS uses allowedOriginPatterns with environment variables
  • JWT validation with proper exception handling
  • CSRF cookie-based tokens (exclude /webhook endpoints)
  • Password policy enforced at service layer with @Pattern
  • Rate limiting with Bucket4j or Spring rate limiting
  • Secrets from environment variables only
  • @Valid on controller method parameters

Dependencies:

  • Requires Spring Security (already in Springular)
  • Requires Bucket4j dependency (NEW) or Spring rate limiting
  • Requires validation annotations

Security Improvements:

  • Fixes CORS wildcard vulnerability (CRITICAL)
  • Adds JWT validation (CRITICAL)
  • Enables CSRF protection (CRITICAL)
  • Adds password complexity (HIGH)
  • Adds rate limiting (HIGH)
  • Externalizes secrets (HIGH)

Feature 7: Reliability Improvements

Purpose: Fix unsafe patterns that cause runtime errors.

Components:

  • Service layer methods - @Transactional annotations
  • Repository usage - Optional.orElseThrow() pattern
  • Exception handlers - Specific exception types
  • Validation classes - Null checks in critical paths

Patterns:

  • @Transactional on all state-changing service methods
  • Optional.orElseThrow(() -> new CustomException(...))
  • Catch specific exceptions (StripeException, JwtException, etc.)
  • Null checks before dereferencing
  • @Valid and validation annotations

Dependencies:

  • Requires custom exception classes
  • Requires validation framework (already in Spring)

Reliability Improvements:

  • Fixes unsafe Optional.get() (CRITICAL)
  • Adds transaction management (HIGH)
  • Improves exception handling (MEDIUM)
  • Adds null safety (HIGH)

Feature 8: Configuration Cleanup

Purpose: Fix production configuration issues.

Components:

  • client/src/environments/environment.prod.ts - Production API URLs
  • application.yml - Profile-based devtools configuration
  • application.yml - Logging configuration (exclude sensitive data)
  • .env.template - Environment variable template (NEW)

Patterns:

  • Production environment uses correct backend URLs
  • Devtools only enabled in dev profile
  • Logging excludes passwords, tokens, and sensitive data
  • .env.template documents required environment variables
  • Profile-based configuration (dev, staging, prod)

Dependencies:

  • Requires profile system (already in Spring)
  • Requires environment variable support

Configuration Improvements:

  • Fixes production URL mismatch (CRITICAL)
  • Removes devtools from production (HIGH)
  • Secures logging (MEDIUM)
  • Documents environment variables (MEDIUM)

Feature 9: Test Coverage Enhancement

Purpose: Add comprehensive test coverage for quality assurance.

Components:

Backend Tests:

  • AuthenticationServiceTest.java - Unit tests for auth logic (NEW)
  • StripeServiceTest.java - Unit tests for payment processing (NEW)
  • EmailServiceTest.java - Unit tests for email sending (NEW)
  • UserRepositoryTest.java - Repository tests with H2 (NEW)
  • AuthenticationControllerIT.java - Integration test for auth flow (NEW)
  • StripeControllerIT.java - Integration test for payment flow (NEW)
  • UserManagementIT.java - Integration test for user operations (NEW)
  • TestDataBuilder.java - Builder pattern for test data (NEW)

Frontend Tests:

  • Component tests for auth pages (login, register, password reset)
  • Component tests for payment pages (checkout, subscription)
  • Service tests for API calls
  • Guard tests for route protection
  • Interceptor tests for JWT handling

Patterns:

  • Unit tests with mocks (Mockito)
  • Integration tests with @SpringBootTest and test database
  • API endpoint tests with MockMvc or RestAssured
  • Test data builders for clean test setup
  • @BeforeEach setup and @AfterEach cleanup
  • Test naming convention: methodName_Scenario_ExpectedBehavior

Dependencies:

  • Requires JUnit 5 (already in Springular)
  • Requires Mockito (already in Springular)
  • Requires H2 test database (already in Springular)
  • Requires MockMvc or RestAssured
  • Requires Jasmine/Karma for frontend (already in Springular)

Test Coverage Goals:

  • 70% coverage for critical paths (auth, payments, user management)

  • 100% coverage for security-critical code (JWT validation, CORS, CSRF)
  • Integration tests for all user-facing flows
  • API contract tests for frontend/backend compatibility

Feature 10: API Contract & Documentation

Purpose: Establish API contracts and generate comprehensive documentation.

Components:

OpenAPI Specifications:

  • auth-api-openapi.yml - Authentication endpoints spec (NEW)
  • user-api-openapi.yml - User management endpoints spec (NEW)
  • payment-api-openapi.yml - Stripe payment endpoints spec (NEW)
  • Or single api-openapi.yml with all endpoints

Controller Annotations:

  • @Operation annotations with summary and description
  • @ApiResponse annotations for all response codes
  • @Parameter annotations for path/query parameters
  • @Schema annotations on DTOs
  • @Tag annotations for endpoint grouping

Contract Testing:

  • Spring Cloud Contract or Pact configuration
  • Contract test classes for each API
  • Provider-side contract tests (backend)
  • Consumer-side contract tests (frontend)

Swagger UI:

  • SpringDoc configuration for /swagger-ui path
  • API grouping by tags
  • Request/response examples
  • Try-it-out functionality enabled

Patterns:

  • OpenAPI 3.0 specification (not 2.0)
  • API versioning via URL path (/api/v1/)
  • Consistent error response schema
  • Request/response validation against schema
  • Contract-first or code-first approach (recommend code-first with annotations)

Dependencies:

  • Requires SpringDoc OpenAPI (already in Springular)
  • Requires Spring Cloud Contract or Pact (NEW dependency)
  • Requires OpenAPI Generator (Feature 4)

API Documentation Goals:

  • All endpoints documented in OpenAPI spec
  • Swagger UI accessible at /swagger-ui
  • API contract tests prevent breaking changes
  • Request/response examples for all endpoints
  • Clear error response documentation

Patterns

Configuration-Driven

All enhancements use configuration files (application.yml, build.gradle) rather than code changes where possible:

  • Hikari pool settings in application.yml
  • Actuator configuration in application.yml
  • Logging levels in application.yml
  • Checkstyle configuration in build.gradle

Migration-Based Schema Changes

Database schema changes use Flyway migrations:

  • V3 migration syncs schema with entities
  • Migrations are versioned and ordered
  • Hibernate validates against migrations

Generated Code Exclusion

Generated code is excluded from code quality checks:

  • Checkstyle suppressions file excludes build/generated-sources/
  • OpenAPI generated code is excluded
  • DDL generated code is excluded

Profile-Based Configuration

Spring profiles separate concerns:

  • ddl-generate profile for schema generation
  • test profile for test execution
  • Default profile for production

Design Decisions

Why Security Hardening First?

Decision: Prioritize security fixes (Feature 6) above all other enhancements.

Rationale:

  • Critical vulnerabilities expose the application to attacks
  • CORS wildcard allows any origin to make requests
  • Missing JWT validation allows token forgery
  • Disabled CSRF enables state-changing attacks
  • Security fixes are prerequisite for production deployment

Tradeoff: Security work delays other features, but this is non-negotiable for production use.


Why CORS allowedOriginPatterns Instead of Wildcard?

Decision: Use allowedOriginPatterns() with environment variables instead of allowedOrigins("*").

Rationale:

  • Wildcard (*) allows requests from ANY origin
  • Enables CSRF attacks from malicious sites
  • Violates security best practices
  • Environment-driven origins support multiple environments

Tradeoff: Requires environment configuration, but this is critical for security.

Implementation:

corsConfiguration.setAllowedOriginPatterns(securityProperties.getAuthorizedRedirectOrigins());
corsConfiguration.setAllowCredentials(true);

Why Enable CSRF Protection?

Decision: Enable CSRF with cookie-based tokens, exclude webhook endpoints.

Rationale:

  • CSRF protection prevents state-changing attacks from malicious sites
  • Cookie-based tokens work with JWT stateless authentication
  • Webhook endpoints must be excluded (external services can't provide CSRF tokens)
  • Production safety critical

Tradeoff: Requires frontend to send CSRF tokens, but this is standard practice.

Implementation:

.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers("/webhook/**")
)

Why Rate Limiting on Auth Endpoints?

Decision: Add rate limiting to authentication endpoints (login, register, password reset).

Rationale:

  • Prevents brute force attacks on passwords
  • Prevents credential stuffing attacks
  • Prevents account enumeration
  • Standard security practice for authentication

Tradeoff: Adds complexity and dependency (Bucket4j), but critical for security.


Why Optional.orElseThrow() Instead of get()?

Decision: Replace all Optional.get() with Optional.orElseThrow(() -> new CustomException(...)).

Rationale:

  • get() throws NoSuchElementException if empty (generic, unhelpful)
  • orElseThrow() provides custom exception with context
  • Better error messages for debugging
  • Prevents silent failures

Tradeoff: More verbose code, but significantly improves reliability and debugging.

Implementation:

// Before (unsafe)
var user = userRepository.findById(id).get();

// After (safe)
var user = userRepository.findById(id)
.orElseThrow(() -> new UserOperationException("User not found", HttpStatus.NOT_FOUND));

Why @Transactional on Service Methods?

Decision: Add @Transactional to all state-changing service methods.

Rationale:

  • Prevents partial updates on errors
  • Ensures data consistency
  • Prevents connection leaks
  • Standard Spring best practice

Tradeoff: None significant - this should have been done from the start.


Why Hibernate ddl-auto: validate?

Decision: Change from update to validate to enforce Flyway as single source of truth.

Rationale:

  • Prevents accidental schema changes in production
  • Catches schema mismatches early
  • Enforces migration-based schema management
  • Production safety critical

Tradeoff: Developers must use migrations for all schema changes (no auto-updates), but this is safer and more predictable.


Why OpenAPI Generator Foundation?

Decision: Add foundational setup in Epic 2, keep AI-specific usage in Text Intelligence Epic.

Rationale:

  • OpenAPI Generator is general-purpose (not AI-specific)
  • Infrastructure setup is boilerplate enhancement
  • Text Intelligence can use it, but doesn't require it
  • Foundation available for future non-AI APIs

Tradeoff: Adds infrastructure that may not be immediately used, but enables future APIs and Text Intelligence.


Why Checkstyle Strict Enforcement?

Decision: maxWarnings = 0 (strict enforcement).

Rationale:

  • Prevents code style drift
  • Catches issues in CI/CD
  • Consistency across codebase
  • Better code quality

Tradeoff: Requires all code to pass checkstyle (including fixing existing issues), but ensures consistent quality.


Why DDL Generation Workflow?

Decision: Add Gradle task + Spring profile for DDL generation.

Rationale:

  • Helps developers understand entity expectations
  • Validates schema against migrations
  • Documents workflow in build system
  • Improves developer experience

Tradeoff: Adds complexity to build system, but significantly improves workflow for database development.


Extension Points

Adding New Code Generation Tools

The pattern established for OpenAPI Generator can be extended:

  • Add plugin to build.gradle
  • Configure sourceSets for generated sources
  • Add checkstyle suppressions
  • Document pattern

Adding New Spring Profiles

The profile pattern can be extended for new use cases:

  • Development profiles
  • Staging profiles
  • Feature-specific profiles

Adding New Monitoring Endpoints

Actuator can be extended with custom health checks:

  • Add custom health indicators
  • Configure exposure in application.yml
  • Document custom endpoints

Constraints and Tradeoffs

Migration Ordering

Constraint: V3 migration must come after V1 and V2 (Flyway versioning).

Impact: Migration numbering must respect existing migrations.

Solution: Use V3 (next available version).


Checkstyle Strictness

Constraint: maxWarnings = 0 requires all code to pass checkstyle.

Impact: May require fixing existing code style issues.

Solution: Fix existing issues as part of Epic 2 implementation, or add suppressions for existing code if needed.


OpenAPI Generator Optional

Constraint: OpenAPI Generator foundation is optional for Text Intelligence.

Impact: Text Intelligence can proceed without it (uses manual DTOs).

Solution: Epic 2 provides foundation, Text Intelligence can use it if ready, or proceed without it.


Integration Points

With Existing Springular Features

Authentication, Payments, Email:

  • All enhancements are infrastructure-only, no changes to existing features
  • Schema sync (V3) ensures existing entities work correctly
  • Connection pooling benefits all features
  • Monitoring (Actuator) monitors all features

With Text Intelligence Epic

Optional Dependencies:

  • OpenAPI Generator foundation (optional, Text Intelligence can use manual DTOs)
  • JacksonConfiguration JavaTimeModule (recommended, but Text Intelligence can add if needed)

No Conflicts:

  • Epic 2 infrastructure enhancements don't conflict with Text Intelligence
  • Text Intelligence can build on Epic 2 foundation
  • Both epics are independent (Epic 2 has no dependencies)

Implementation Guides

For step-by-step implementation instructions, see (in recommended order):

  1. Security Hardening - CORS, JWT, CSRF, passwords, rate limiting, secrets
  2. Reliability Improvements - Optional, transactions, exceptions, null checks
  3. Configuration Cleanup - Production URLs, profiles, logging, env templates
  4. Test Coverage Enhancement - Integration tests, unit tests, API tests, frontend tests
  5. API Contract & Documentation - OpenAPI specs, Swagger UI, contract tests
  6. Database Schema & Validation - Migration, ddl-auto configuration, DDL generation workflow
  7. Production Infrastructure - Connection pooling, Actuator, JacksonConfiguration
  8. Code Quality & Developer Experience - Checkstyle, logging, workflow tools
  9. Code Generation Infrastructure - OpenAPI Generator foundational setup
  10. Test Infrastructure - Test profile configuration

Implementation Order: Sequential (1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10)

Rationale:

  • Features 1-3 (Security, Reliability, Configuration) fix critical production blockers
  • Features 4-5 (Tests, API Docs) validate fixes and ensure quality
  • Features 6-10 (Infrastructure) provide foundation for future development