diff --git a/.env.example b/.env.example index 8f57483..815c74a 100644 --- a/.env.example +++ b/.env.example @@ -38,8 +38,8 @@ AWS_S3_BUCKET=your-s3-bucket-name # ----------------------------------------------------------------------------- # EMAIL CONFIGURATION (Resend API, SES, SMTP) # ----------------------------------------------------------------------------- -# RESEND_API_KEY, MAIL_USERNAME and MAIL_PASSWORD must be set even with -# SPRING_PROFILES_ACTIVE=mock-email (placeholder values are fine there). +# Optional: configure at least one sender (Resend, SES via AWS_*, or SMTP) to send real +# email. With SPRING_PROFILES_ACTIVE=mock-email none of them is needed. RESEND_API_KEY=re_your_resend_api_key_here # Sender email address (must be verified in Resend dashboard) @@ -60,5 +60,11 @@ APP_BASE_URL=http://localhost:8080 # ----------------------------------------------------------------------------- # IP ENRICHMENT # ----------------------------------------------------------------------------- -# IPinfo token for IP -> country/city on tracking events (placeholder is fine locally) +# Optional IPinfo token for IP -> country/city on tracking events IPINFO_TOKEN=your-ipinfo-token + +# ----------------------------------------------------------------------------- +# CORS +# ----------------------------------------------------------------------------- +# Comma-separated browser origins allowed to call the API (default: any origin) +# CORS_ALLOWED_ORIGINS=https://app.yourdomain.com diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3f3edfd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,57 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + tests: + name: Tests (unit, integration, scale) + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + + - uses: gradle/actions/setup-gradle@v4 + + # Integration and scale tests start PostgreSQL with Testcontainers; the runner has Docker. + - name: Run all test suites + run: ./gradlew test integrationTest scaleTest --console=plain + + - name: Upload test reports + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-reports + path: build/reports/tests/ + retention-days: 7 + + docker: + name: Docker image builds + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + + - uses: docker/setup-buildx-action@v3 + + - name: Build image (not pushed) + uses: docker/build-push-action@v6 + with: + context: . + push: false + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/Dockerfile b/Dockerfile index 966376c..f45ce0f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -19,6 +19,9 @@ RUN --mount=type=cache,target=/root/.gradle \ # Stage 2: Runtime with Java 21 JRE FROM eclipse-temurin:21-jre-alpine WORKDIR /app -COPY --from=build /app/build/libs/*.jar app.jar +# Run as an unprivileged user, not root +RUN addgroup -S app && adduser -S app -G app +COPY --from=build --chown=app:app /app/build/libs/*.jar app.jar +USER app EXPOSE 8080 ENTRYPOINT ["java", "-jar", "app.jar"] diff --git a/README.md b/README.md index 30066a5..2a2190c 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ Public tracking (no auth): ``` src/main/java/com/mailengine/mailengine/ -├── config/ # Spring beans: AwsConfig, SecurityConfig, MailConfig, CorsConfig, OpenApiConfig +├── config/ # Spring beans: AwsConfig, SecurityConfig (incl. CORS), MailConfig, OpenApiConfig ├── controller/ # REST controllers (one file per resource) ├── dto/ │ ├── request/ # Inbound JSON bodies @@ -258,16 +258,16 @@ The app reads all configuration from environment variables via `.env` (loaded by | `DB_PASSWORD` | `secret` | Database password | | `JWT_SECRET` | *(32-char base64 string)* | HMAC signing key for JWTs. Generate with `openssl rand -base64 32` | | `JWT_EXPIRATION` | `86400000` | Token TTL in milliseconds (86400000 = 24 h) | -| `APP_BASE_URL` | `http://localhost:8080` | Base URL used to build tracking links inside emails. Must be publicly reachable by email clients. Use your ngrok URL locally. | +| `APP_BASE_URL` | `http://localhost:8080` | Base URL used to build tracking links inside emails, and the server Swagger UI calls. Must be publicly reachable by email clients. Use your ngrok URL locally. | +| `AWS_FROM_EMAIL` | `hello@yourdomain.com` | Sender address for transactional emails (invites, password resets). Must be verified with your sender. | ### Email sending -At least one of the three senders must be configured. The `CompositeEmailSender` tries them in order: Resend → SES → SMTP. +To send real email, configure at least one of the three senders. The `CompositeEmailSender` tries them in order: Resend → SES → SMTP, and skips any that isn't configured. None of them is needed to start the app, and none is used with `SPRING_PROFILES_ACTIVE=mock-email`. | Variable | Example | Description | |---|---|---| | `RESEND_API_KEY` | `re_xxxxxxxxxxxx` | Resend API key (primary sender) | -| `AWS_FROM_EMAIL` | `hello@yourdomain.com` | Verified sender address (used by SES and as fallback From) | | `MAIL_HOST` | `smtp.resend.com` | SMTP host | | `MAIL_PORT` | `587` | SMTP port (STARTTLS) | | `MAIL_USERNAME` | `resend` | SMTP username | @@ -275,19 +275,23 @@ At least one of the three senders must be configured. The `CompositeEmailSender` ### AWS +All optional. Without them the app starts, SES is skipped, and image uploads return an error. + | Variable | Example | Description | |---|---|---| -| `AWS_REGION` | `eu-north-1` | AWS region for SES and S3 | -| `AWS_ACCESS_KEY_ID` | `AKIA…` | IAM access key | +| `AWS_REGION` | `eu-north-1` | AWS region for SES and S3 (default `us-east-1`) | +| `AWS_ACCESS_KEY_ID` | `AKIA…` | IAM access key. Leave both keys unset to use the AWS SDK's default credentials chain (for example an IAM role) | | `AWS_SECRET_ACCESS_KEY` | `…` | IAM secret key | | `AWS_S3_BUCKET` | `mailengine-assets` | S3 bucket for template images and uploads | -### Optional enrichment +### Optional | Variable | Example | Description | |---|---|---| -| `IPINFO_TOKEN` | `abc123def456` | IPinfo API token for IP → country/city lookup on tracking events | +| `CORS_ALLOWED_ORIGINS` | `https://app.yourdomain.com` | Comma-separated browser origins allowed to call the API. Default `*` (any origin) | +| `IPINFO_TOKEN` | `abc123def456` | IPinfo API token for IP → country/city lookup on tracking events. Without it, events are stored without location | | `SPRING_PROFILES_ACTIVE` | `mock-email` | Set to `mock-email` to log emails to console instead of sending them | +| `LOGGING_LEVEL_` | `LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_SECURITY=DEBUG` | Raise logging for one package while debugging. Everything logs at `INFO` by default | --- @@ -884,9 +888,9 @@ To get the current user in a service, use `SecurityUtils.currentUser()`. It retu 2. **`JWT_SECRET`** — Must be at minimum 32 characters. Rotate it only during a maintenance window (all existing tokens become invalid). -3. **CORS** — `application.yaml` currently allows all origins. Restrict `spring.mvc.cors.allowed-origins` to your frontend domain before going to production. +3. **CORS** — any origin may call the API by default. Set `CORS_ALLOWED_ORIGINS` to your frontend's domain(s) in production. Browsers never send cookies or other credentials: auth is the `Authorization: Bearer` header. -4. **Logging levels** — `application.yaml` has verbose DEBUG logging enabled for Spring Security, Web, and Data layers. Set these to `INFO` or `WARN` in production to avoid log volume and potential token leakage. +4. **Logging levels** — everything logs at `INFO`. Raise a package with `LOGGING_LEVEL_=DEBUG` only while debugging: Spring's DEBUG output includes request details. 5. **Imports and restarts:** give the app a stop grace period of at least 30 s (for example `docker stop -t 35`) so running imports can finish. Docker's default is 10 s. Anything cut off is marked `failed` at the next startup. Tune `app.import.threads` / `app.import.queue-capacity` to your memory and database capacity. @@ -899,10 +903,10 @@ To get the current user in a service, use `SecurityUtils.currentUser()`. It retu ``` DB_HOST, DB_PORT, DB_NAME, DB_USERNAME, DB_PASSWORD JWT_SECRET, JWT_EXPIRATION -APP_BASE_URL -RESEND_API_KEY (or MAIL_HOST/MAIL_PORT/MAIL_USERNAME/MAIL_PASSWORD for SMTP) -AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY -AWS_FROM_EMAIL, AWS_S3_BUCKET +APP_BASE_URL, AWS_FROM_EMAIL +CORS_ALLOWED_ORIGINS +RESEND_API_KEY (and/or SES via AWS_*, and/or MAIL_HOST/MAIL_PORT/MAIL_USERNAME/MAIL_PASSWORD for SMTP) +AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY (or an IAM role), AWS_S3_BUCKET IPINFO_TOKEN ``` diff --git a/build.gradle b/build.gradle index ff8ca75..a64d4e7 100644 --- a/build.gradle +++ b/build.gradle @@ -57,14 +57,12 @@ dependencies { // ── Dev Tools ───────────────────────────────────────────────────── developmentOnly 'org.springframework.boot:spring-boot-devtools' - // Import the BOM to manage AWS SDK versions - implementation platform('software.amazon.awssdk:bom:2.25.15') - - // S3 module - implementation 'software.amazon.awssdk:s3' - - // SES SDK - implementation 'software.amazon.awssdk:ses:2.25.15' + // ── AWS SDK: one BOM pins every module to the same version ─────── + implementation platform('software.amazon.awssdk:bom:2.25.27') + implementation 'software.amazon.awssdk:s3' // template images and uploads + implementation 'software.amazon.awssdk:ses' // sending + implementation 'software.amazon.awssdk:sts' + implementation 'software.amazon.awssdk:sns' // SES bounce/complaint webhooks // ── Ahmed's ADDITIONS (BE-3 & BE-4) ───────────────────────────────── @@ -84,17 +82,6 @@ dependencies { //env - creates and stores the .env file created implementation 'me.paulschwarz:spring-dotenv:4.0.0' - // AWS SES SDK — replaces spring-boot-starter-mail for sending - implementation 'software.amazon.awssdk:ses:2.25.27' - implementation 'software.amazon.awssdk:sts:2.25.27' - implementation 'software.amazon.awssdk:s3:2.25.27' - implementation 'software.amazon.awssdk:sns:2.25.27' - - // GeoIP2 - implementation 'com.maxmind.geoip2:geoip2:4.2.0' - // Yauaa (User-Agent analysis) - implementation 'nl.basjes.parse.useragent:yauaa:7.28.1' - // ── Test ────────────────────────────────────────────────────────── testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' diff --git a/src/main/java/com/mailengine/mailengine/config/AwsConfig.java b/src/main/java/com/mailengine/mailengine/config/AwsConfig.java index 7ef685e..835b0c8 100644 --- a/src/main/java/com/mailengine/mailengine/config/AwsConfig.java +++ b/src/main/java/com/mailengine/mailengine/config/AwsConfig.java @@ -4,6 +4,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; +import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; @@ -55,8 +57,7 @@ public S3Client s3Client() { return S3Client.builder() .region(Region.of(region)) // StaticCredentialsProvider uses the explicit key/secret from .env - .credentialsProvider(StaticCredentialsProvider.create( - AwsBasicCredentials.create(accessKeyId, secretAccessKey))) + .credentialsProvider(credentials()) .build(); } @@ -72,8 +73,19 @@ public S3Client s3Client() { public SesClient sesClient() { return SesClient.builder() .region(Region.of(region)) - .credentialsProvider(StaticCredentialsProvider.create( - AwsBasicCredentials.create(accessKeyId, secretAccessKey))) + .credentialsProvider(credentials()) .build(); } + + /** + * The explicit key pair when both are set; otherwise the SDK's default chain (AWS_* env vars, profile, + * IAM role). The chain is only consulted on the first AWS call, so the app starts without AWS access + * (e.g. with {@code SPRING_PROFILES_ACTIVE=mock-email}). + */ + private AwsCredentialsProvider credentials() { + if (accessKeyId == null || accessKeyId.isBlank() || secretAccessKey == null || secretAccessKey.isBlank()) { + return DefaultCredentialsProvider.builder().build(); + } + return StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKeyId, secretAccessKey)); + } } diff --git a/src/main/java/com/mailengine/mailengine/config/CorsConfig.java b/src/main/java/com/mailengine/mailengine/config/CorsConfig.java deleted file mode 100644 index f6d4a29..0000000 --- a/src/main/java/com/mailengine/mailengine/config/CorsConfig.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.mailengine.mailengine.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -/** - * Global CORS (Cross-Origin Resource Sharing) configuration. - * - *

In development all origins are permitted so the React frontend (typically - * running on {@code http://localhost:5173}) can call the API at - * {@code http://localhost:8080} without browser CORS errors. - * - *

Production note: Replace {@code allowedOrigins("*")} with - * your actual frontend domain (e.g. {@code https://app.mailengine.com}) before - * deploying. Wildcard origins cannot be combined with - * {@code allowCredentials(true)}. - */ -@Configuration -public class CorsConfig implements WebMvcConfigurer { - - /** - * Registers CORS rules for every endpoint ({@code /**}). - * - * @param registry the Spring MVC CORS registry to configure - */ - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - // Allow all origins in development; restrict in production - .allowedOrigins("*") - .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS") - .allowedHeaders("*") - // Must be false when allowedOrigins contains "*" - .allowCredentials(false); - } -} diff --git a/src/main/java/com/mailengine/mailengine/config/MailConfig.java b/src/main/java/com/mailengine/mailengine/config/MailConfig.java index 847443e..badaf02 100644 --- a/src/main/java/com/mailengine/mailengine/config/MailConfig.java +++ b/src/main/java/com/mailengine/mailengine/config/MailConfig.java @@ -16,7 +16,7 @@ *

Supports Brevo (formerly Sendinblue), Gmail, or any SMTP provider by * changing the host/port in the environment variables below. * - *

Required environment variables: + *

Environment variables (only needed when emails actually go out over SMTP): *

  *   MAIL_HOST      — SMTP server hostname (e.g. smtp-relay.brevo.com)
  *   MAIL_PORT      — SMTP port (587 for STARTTLS, 465 for SSL)
@@ -36,11 +36,11 @@ public class MailConfig {
     private int port;
 
     /** SMTP username for authentication. */
-    @Value("${MAIL_USERNAME}")
+    @Value("${MAIL_USERNAME:}")
     private String username;
 
     /** SMTP password or API key for authentication. */
-    @Value("${MAIL_PASSWORD}")
+    @Value("${MAIL_PASSWORD:}")
     private String password;
 
     /**
diff --git a/src/main/java/com/mailengine/mailengine/config/OpenApiConfig.java b/src/main/java/com/mailengine/mailengine/config/OpenApiConfig.java
index 326defb..61bf7e5 100644
--- a/src/main/java/com/mailengine/mailengine/config/OpenApiConfig.java
+++ b/src/main/java/com/mailengine/mailengine/config/OpenApiConfig.java
@@ -4,16 +4,22 @@
 import io.swagger.v3.oas.models.OpenAPI;
 import io.swagger.v3.oas.models.security.SecurityRequirement;
 import io.swagger.v3.oas.models.security.SecurityScheme;
+import io.swagger.v3.oas.models.servers.Server;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 
+import java.util.List;
+
 @Configuration
 public class OpenApiConfig {
 
     @Bean
-    public OpenAPI customOpenAPI() {
+    public OpenAPI customOpenAPI(@Value("${app.base-url:http://localhost:8080}") String baseUrl) {
         final String securitySchemeName = "bearerAuth";
         return new OpenAPI()
+                // Swagger UI sends "Try it out" requests here: the app's own public address
+                .servers(List.of(new Server().url(baseUrl)))
                 .addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
                 .components(new Components()
                         .addSecuritySchemes(securitySchemeName,
diff --git a/src/main/java/com/mailengine/mailengine/exception/GlobalExceptionHandler.java b/src/main/java/com/mailengine/mailengine/exception/GlobalExceptionHandler.java
index a06802a..28bafb4 100644
--- a/src/main/java/com/mailengine/mailengine/exception/GlobalExceptionHandler.java
+++ b/src/main/java/com/mailengine/mailengine/exception/GlobalExceptionHandler.java
@@ -55,6 +55,13 @@ public ResponseEntity handleConflict(ConflictException ex) {
                 .body(new ErrorResponse(409, ex.getMessage(), null));
     }
 
+    // ── Feature whose settings are not configured on this server ─────────────
+    @ExceptionHandler(NotConfiguredException.class)
+    public ResponseEntity handleNotConfigured(NotConfiguredException ex) {
+        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
+                .body(new ErrorResponse(503, ex.getMessage(), null));
+    }
+
     // ── Business-logic "bad request" ─────────────────────────────────────────
     @ExceptionHandler(BadRequestException.class)
     public ResponseEntity handleBadRequest(BadRequestException ex) {
diff --git a/src/main/java/com/mailengine/mailengine/exception/NotConfiguredException.java b/src/main/java/com/mailengine/mailengine/exception/NotConfiguredException.java
new file mode 100644
index 0000000..b1c09ac
--- /dev/null
+++ b/src/main/java/com/mailengine/mailengine/exception/NotConfiguredException.java
@@ -0,0 +1,6 @@
+package com.mailengine.mailengine.exception;
+
+/** A feature was used whose settings were left unset (e.g. file uploads without AWS_S3_BUCKET). Mapped to 503. */
+public class NotConfiguredException extends RuntimeException {
+    public NotConfiguredException(String message) { super(message); }
+}
diff --git a/src/main/java/com/mailengine/mailengine/repository/EngagementScoreRepository.java b/src/main/java/com/mailengine/mailengine/repository/EngagementScoreRepository.java
index 9f20a60..12eb136 100644
--- a/src/main/java/com/mailengine/mailengine/repository/EngagementScoreRepository.java
+++ b/src/main/java/com/mailengine/mailengine/repository/EngagementScoreRepository.java
@@ -25,21 +25,21 @@ INSERT INTO engagement_scores (recipient_id, campaigns_sent, campaigns_opened, c
             LEFT JOIN (
                 SELECT eq.recipient_id, COUNT(DISTINCT eq.campaign_id) AS sent
                 FROM email_queue eq
-                WHERE eq.created_at > :nowUtc - INTERVAL '90 days'
+                WHERE eq.created_at > CAST(:nowUtc AS timestamp) - INTERVAL '90 days'
                 GROUP BY eq.recipient_id
             ) sent_counts ON sent_counts.recipient_id = r.id
             LEFT JOIN (
                 SELECT te.recipient_id, COUNT(DISTINCT te.campaign_id) AS opened
                 FROM tracking_events te
                 WHERE te.event_type = 'open'
-                  AND te.created_at > :nowUtc - INTERVAL '90 days'
+                  AND te.created_at > CAST(:nowUtc AS timestamp) - INTERVAL '90 days'
                 GROUP BY te.recipient_id
             ) open_counts ON open_counts.recipient_id = r.id
             LEFT JOIN (
                 SELECT te.recipient_id, COUNT(DISTINCT te.campaign_id) AS clicked
                 FROM tracking_events te
                 WHERE te.event_type = 'click'
-                  AND te.created_at > :nowUtc - INTERVAL '90 days'
+                  AND te.created_at > CAST(:nowUtc AS timestamp) - INTERVAL '90 days'
                 GROUP BY te.recipient_id
             ) click_counts ON click_counts.recipient_id = r.id
             LEFT JOIN (
diff --git a/src/main/java/com/mailengine/mailengine/security/SecurityConfig.java b/src/main/java/com/mailengine/mailengine/security/SecurityConfig.java
index b64ea7f..9509ec5 100644
--- a/src/main/java/com/mailengine/mailengine/security/SecurityConfig.java
+++ b/src/main/java/com/mailengine/mailengine/security/SecurityConfig.java
@@ -3,6 +3,7 @@
 import com.mailengine.mailengine.entity.enums.Role;
 import jakarta.servlet.http.HttpServletResponse;
 import lombok.RequiredArgsConstructor;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.http.HttpMethod;
@@ -33,6 +34,10 @@ public class SecurityConfig {
 
     private final JwtAuthFilter jwtAuthFilter;
 
+    /** Browser origins allowed to call the API ({@code CORS_ALLOWED_ORIGINS}, comma-separated; {@code *} = any). */
+    @Value("${app.cors.allowed-origins:*}")
+    private List allowedOrigins;
+
     @Bean
     public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
         http
@@ -85,10 +90,11 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
     @Bean
     public CorsConfigurationSource corsConfigurationSource() {
         CorsConfiguration configuration = new CorsConfiguration();
-        configuration.setAllowedOriginPatterns(List.of("*"));
+        configuration.setAllowedOrigins(allowedOrigins.stream().map(String::trim).filter(o -> !o.isEmpty()).toList());
         configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
         configuration.setAllowedHeaders(List.of("*"));
-        configuration.setAllowCredentials(true);
+        // Auth is a Bearer token in a header, never a cookie, so browsers need not send credentials
+        configuration.setAllowCredentials(false);
 
         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
         source.registerCorsConfiguration("/**", configuration);
diff --git a/src/main/java/com/mailengine/mailengine/service/AnalyticsService.java b/src/main/java/com/mailengine/mailengine/service/AnalyticsService.java
index cf7eef1..2af840b 100644
--- a/src/main/java/com/mailengine/mailengine/service/AnalyticsService.java
+++ b/src/main/java/com/mailengine/mailengine/service/AnalyticsService.java
@@ -121,16 +121,31 @@ AND event_type IN ('open', 'click', 'unsubscribe')
                 .getResultList();
 
         return tuples.stream()
-                .map(t -> TimelineDataPoint.builder()
-                        .timestamp(t.get("hour_bucket", Instant.class))
-                        .period(t.get("hour_bucket", Instant.class).toString())
+                .map(t -> {
+                    Instant hour = utcInstant(t.get("hour_bucket"));
+                    return TimelineDataPoint.builder()
+                        .timestamp(hour)
+                        .period(hour.toString())
                         .opens(t.get("opens", Long.class).intValue())
                         .clicks(t.get("clicks", Long.class).intValue())
                         .unsubscribes(t.get("unsubs", Long.class).intValue())
-                        .build())
+                        .build();
+                })
                 .collect(Collectors.toList());
     }
 
+    /**
+     * tracking_events.created_at is a TIMESTAMP column holding UTC wall-clock time (Hibernate writes instants
+     * that way), so a value read back from a native query is read as UTC, not in the JVM's time zone.
+     */
+    private static Instant utcInstant(Object value) {
+        if (value instanceof java.sql.Timestamp ts) return ts.toLocalDateTime().toInstant(java.time.ZoneOffset.UTC);
+        if (value instanceof java.time.LocalDateTime ldt) return ldt.toInstant(java.time.ZoneOffset.UTC);
+        if (value instanceof java.time.OffsetDateTime odt) return odt.toInstant();
+        if (value instanceof Instant i) return i;
+        throw new IllegalStateException("Unexpected timestamp type: " + (value == null ? "null" : value.getClass()));
+    }
+
     // ─────────────────────────────────────────────────────────────────────────────
     // LINK PERFORMANCE
     // ─────────────────────────────────────────────────────────────────────────────
diff --git a/src/main/java/com/mailengine/mailengine/service/GeoIpService.java b/src/main/java/com/mailengine/mailengine/service/GeoIpService.java
index 8d1a805..1363f32 100644
--- a/src/main/java/com/mailengine/mailengine/service/GeoIpService.java
+++ b/src/main/java/com/mailengine/mailengine/service/GeoIpService.java
@@ -24,11 +24,16 @@ public class GeoIpService {
      *
      * @param token IPinfo API token (injected from application.yaml)
      */
-    public GeoIpService(@Value("${ipinfo.token}") String token) {
-        this.ipInfo = new IPinfo.Builder()
-                .setToken(token)
-                .build();
-        log.info("GeoIpService initialized with IPinfo API (no local database)");
+    public GeoIpService(@Value("${ipinfo.token:}") String token) {
+        if (token == null || token.isBlank()) {
+            this.ipInfo = null;
+            log.info("IPINFO_TOKEN not set: tracking events are stored without country/city");
+        } else {
+            this.ipInfo = new IPinfo.Builder()
+                    .setToken(token)
+                    .build();
+            log.info("GeoIpService initialized with IPinfo API (no local database)");
+        }
     }
 
     /**
@@ -38,6 +43,7 @@ public GeoIpService(@Value("${ipinfo.token}") String token) {
      * @return IPResponse containing city, country, coordinates, etc., or null if lookup fails
      */
     public IPResponse lookup(String ipAddress) {
+        if (ipInfo == null) return null;
         try {
             return ipInfo.lookupIP(ipAddress);
         } catch (Exception e) {
diff --git a/src/main/java/com/mailengine/mailengine/service/ResendEmailSender.java b/src/main/java/com/mailengine/mailengine/service/ResendEmailSender.java
index 9c249bd..ae1b092 100644
--- a/src/main/java/com/mailengine/mailengine/service/ResendEmailSender.java
+++ b/src/main/java/com/mailengine/mailengine/service/ResendEmailSender.java
@@ -15,13 +15,17 @@ public class ResendEmailSender implements EmailSender {
 
     private static final Logger log = LoggerFactory.getLogger(ResendEmailSender.class);
 
-    @Value("${RESEND_API_KEY}")
+    @Value("${RESEND_API_KEY:}")
     private String apiKey;
 
     private Resend resend;
 
     @PostConstruct
     public void init() {
+        if (apiKey == null || apiKey.isBlank()) {
+            log.info("RESEND_API_KEY not set: Resend is skipped and emails go to SES/SMTP");
+            return;
+        }
         this.resend = new Resend(apiKey);
         log.info("ResendEmailSender initialized with API key");
     }
@@ -29,6 +33,7 @@ public void init() {
     @Override
     public String send(String toEmail, String fromName, String fromEmail,
                        String subject, String htmlContent) {
+        if (resend == null) return null;   // not configured: the caller falls back to the next sender
         try {
             String from = String.format("%s <%s>", fromName, fromEmail);
 
diff --git a/src/main/java/com/mailengine/mailengine/service/S3Service.java b/src/main/java/com/mailengine/mailengine/service/S3Service.java
index 66ee44e..8d3da89 100644
--- a/src/main/java/com/mailengine/mailengine/service/S3Service.java
+++ b/src/main/java/com/mailengine/mailengine/service/S3Service.java
@@ -1,9 +1,9 @@
 package com.mailengine.mailengine.service;
 
+import com.mailengine.mailengine.exception.NotConfiguredException;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Profile;
 import org.springframework.stereotype.Service;
 import org.springframework.web.multipart.MultipartFile;
 import software.amazon.awssdk.core.sync.RequestBody;
@@ -22,12 +22,11 @@
 @Service
 @RequiredArgsConstructor
 @Slf4j
-//@Profile("!mock-email")   // <-- ADDED: disable in mock-email profile
 public class S3Service {
 
     private final S3Client s3Client;
 
-    @Value("${aws.s3.bucket}")
+    @Value("${aws.s3.bucket:}")
     private String bucketName;
 
     @Value("${aws.region}")
@@ -41,6 +40,9 @@ public class S3Service {
      * @return the public URL of the uploaded file
      */
     public String uploadFile(MultipartFile file, String folder) {
+        if (bucketName == null || bucketName.isBlank()) {
+            throw new NotConfiguredException("File uploads are not configured on this server (AWS_S3_BUCKET is not set)");
+        }
         String fileName = generateFileName(file.getOriginalFilename());
         String key = folder + "/" + fileName;
 
diff --git a/src/main/java/com/mailengine/mailengine/service/SmtpEmailSender.java b/src/main/java/com/mailengine/mailengine/service/SmtpEmailSender.java
index 1f1965d..e30865d 100644
--- a/src/main/java/com/mailengine/mailengine/service/SmtpEmailSender.java
+++ b/src/main/java/com/mailengine/mailengine/service/SmtpEmailSender.java
@@ -6,6 +6,7 @@
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.mail.javamail.JavaMailSender;
+import org.springframework.mail.javamail.JavaMailSenderImpl;
 import org.springframework.mail.javamail.MimeMessageHelper;
 import org.springframework.stereotype.Component;
 
@@ -34,6 +35,9 @@ public class SmtpEmailSender implements EmailSender {
 
     private final JavaMailSender javaMailSender;
 
+    private final java.util.concurrent.atomic.AtomicBoolean notConfiguredWarned =
+            new java.util.concurrent.atomic.AtomicBoolean();
+
     /**
      * Sends a single HTML email via SMTP.
      *
@@ -53,6 +57,14 @@ public class SmtpEmailSender implements EmailSender {
     @Override
     public String send(String toEmail, String fromName, String fromEmail,
                        String subject, String htmlContent) {
+        // MailConfig always turns SMTP auth on, so without MAIL_USERNAME there is no usable SMTP account
+        if (javaMailSender instanceof JavaMailSenderImpl impl
+                && (impl.getUsername() == null || impl.getUsername().isBlank())) {
+            if (notConfiguredWarned.compareAndSet(false, true)) {
+                log.warn("SMTP is not configured (MAIL_USERNAME unset): skipping SMTP sends");
+            }
+            return null;
+        }
         try {
             MimeMessage message = javaMailSender.createMimeMessage();
             // true = multipart message; "UTF-8" = charset for all parts
diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml
index 36e4069..183503c 100644
--- a/src/main/resources/application.yaml
+++ b/src/main/resources/application.yaml
@@ -20,10 +20,10 @@ spring:
     enabled: true
     locations: classpath:db/migration
   mail:
-    host: ${MAIL_HOST}
-    port: ${MAIL_PORT}
-    username: ${MAIL_USERNAME}
-    password: ${MAIL_PASSWORD}
+    host: ${MAIL_HOST:}
+    port: ${MAIL_PORT:587}
+    username: ${MAIL_USERNAME:}
+    password: ${MAIL_PASSWORD:}
     properties:
       mail:
         smtp:
@@ -34,17 +34,11 @@ spring:
     multipart:
       max-file-size: 10MB
       max-request-size: 10MB
-  mvc:
-    cors:
-      allowed-origins: "https://luvenia-unbargained-sergio.ngrok-free.dev"
-      allowed-methods: "*"
-      allowed-headers: "*"
-      allow-credentials: true
   # Ope's AWS SES Config (requires these property names)
   aws:
-    region: ${AWS_REGION}
-    access-key-id: ${AWS_ACCESS_KEY_ID}
-    secret-access-key: ${AWS_SECRET_ACCESS_KEY}
+    region: ${AWS_REGION:us-east-1}
+    access-key-id: ${AWS_ACCESS_KEY_ID:}
+    secret-access-key: ${AWS_SECRET_ACCESS_KEY:}
 
 server:
   forward-headers-strategy: native
@@ -62,28 +56,25 @@ app:
   sending:
     batch-size: 20
     delay-ms: 3000
+  cors:
+    # Comma-separated origins allowed to call the API from a browser, e.g. https://app.example.com
+    allowed-origins: ${CORS_ALLOWED_ORIGINS:*}
 
 aws:
-  region: ${AWS_REGION}
-  access-key-id: ${AWS_ACCESS_KEY_ID}
-  secret-access-key: ${AWS_SECRET_ACCESS_KEY}
+  region: ${AWS_REGION:us-east-1}
+  # Blank keys: the AWS SDK's default chain is used (AWS_* env vars, IAM role, ...)
+  access-key-id: ${AWS_ACCESS_KEY_ID:}
+  secret-access-key: ${AWS_SECRET_ACCESS_KEY:}
   from-email: ${AWS_FROM_EMAIL}
   s3:
-    bucket: ${AWS_S3_BUCKET}
+    bucket: ${AWS_S3_BUCKET:}
 
 ipinfo:
-  token: ${IPINFO_TOKEN}
+  # Optional: without a token, tracking events are stored without country/city
+  token: ${IPINFO_TOKEN:}
 
 logging:
+  # INFO by default. Turn on more per package with env vars when debugging, e.g.
+  # LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_SECURITY=DEBUG
   level:
-    org.springframework.security: DEBUG
-    org.springframework.web: DEBUG                # <-- ADD
-    org.springframework.web.servlet: DEBUG        # <-- ADD
-    org.springframework.data: DEBUG               # <-- ADD
-    org.hibernate.SQL: WARN                      # <-- ADD
-    org.hibernate.type.descriptor.sql: WARN      # <-- ADD
-
-springdoc:
-  api-docs:
-    server:
-      url: https://luvenia-unbargained-sergio.ngrok-free.dev
\ No newline at end of file
+    root: INFO
diff --git a/src/test/java/com/mailengine/mailengine/config/OptionalSettingsTest.java b/src/test/java/com/mailengine/mailengine/config/OptionalSettingsTest.java
new file mode 100644
index 0000000..ab5ec97
--- /dev/null
+++ b/src/test/java/com/mailengine/mailengine/config/OptionalSettingsTest.java
@@ -0,0 +1,71 @@
+package com.mailengine.mailengine.config;
+
+import com.mailengine.mailengine.security.SecurityConfig;
+import com.mailengine.mailengine.service.GeoIpService;
+import com.mailengine.mailengine.service.ResendEmailSender;
+import com.mailengine.mailengine.service.SmtpEmailSender;
+import org.junit.jupiter.api.Test;
+import org.springframework.mail.javamail.JavaMailSenderImpl;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.web.cors.CorsConfiguration;
+
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.never;
+import static org.mockito.ArgumentMatchers.any;
+
+/** Settings that may be left unset: the app starts and the feature is skipped instead of failing. */
+class OptionalSettingsTest {
+
+    @Test
+    void resendWithoutApiKeyIsSkipped() {
+        ResendEmailSender sender = new ResendEmailSender();
+        ReflectionTestUtils.setField(sender, "apiKey", "");
+        sender.init();
+
+        assertThat(sender.send("to@example.test", "Team", "team@example.test", "Hi", "

Hi

")) + .as("null lets CompositeEmailSender fall back to the next sender").isNull(); + } + + @Test + void smtpWithoutUsernameIsSkippedWithoutConnecting() { + JavaMailSenderImpl mail = spy(new JavaMailSenderImpl()); + mail.setHost("smtp.invalid"); + SmtpEmailSender sender = new SmtpEmailSender(mail); + + assertThat(sender.send("to@example.test", "Team", "team@example.test", "Hi", "

Hi

")).isNull(); + verify(mail, never()).send(any(jakarta.mail.internet.MimeMessage.class)); + } + + @Test + void geoLookupWithoutTokenReturnsNothing() { + assertThat(new GeoIpService("").lookup("8.8.8.8")).isNull(); + } + + @Test + void corsAllowsTheConfiguredOriginsAndNeverCredentials() { + CorsConfiguration cors = cors(List.of("https://app.example.com", " https://admin.example.com ")); + + assertThat(cors.checkOrigin("https://app.example.com")).isEqualTo("https://app.example.com"); + assertThat(cors.checkOrigin("https://admin.example.com")).as("spaces around entries are ignored") + .isEqualTo("https://admin.example.com"); + assertThat(cors.checkOrigin("https://evil.example.com")).isNull(); + assertThat(cors.getAllowCredentials()).isFalse(); + } + + @Test + void corsDefaultAllowsAnyOrigin() { + assertThat(cors(List.of("*")).checkOrigin("https://anything.example.com")).isEqualTo("*"); + } + + private static CorsConfiguration cors(List origins) { + SecurityConfig config = new SecurityConfig(mock(com.mailengine.mailengine.security.JwtAuthFilter.class)); + ReflectionTestUtils.setField(config, "allowedOrigins", origins); + return config.corsConfigurationSource().getCorsConfiguration(new MockHttpServletRequest("GET", "/api/campaigns")); + } +} diff --git a/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java b/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java index c97c512..5580637 100644 --- a/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java +++ b/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java @@ -391,6 +391,42 @@ void engagementScoresEndpointReturnsJson() throws Exception { assertThat(response.getContentAsString()).contains(r.getEmail(), "72.5", "high"); } + @Test + void openedCampaignShowsInTheTimelineAtTheRightHour() throws Exception { + long id = sentCampaign(1); + drainQueue(); + String pixel = jdbc.queryForObject("select pixel_token from email_queue where campaign_id = ?", String.class, id); + Instant before = Instant.now(); + + assertThat(mvc.perform(get("/track/open/{token}", pixel)).andReturn().getResponse().getStatus()).isEqualTo(200); + var response = mvc.perform(get("/api/analytics/campaigns/{id}/timeline", id).with(authentication(ADMIN))) + .andReturn().getResponse(); + + assertThat(response.getStatus()).isEqualTo(200); + var points = objectMapper.readTree(response.getContentAsString()); + assertThat(points).hasSize(1); + assertThat(points.get(0).get("opens").asInt()).isEqualTo(1); + // The JVM runs in Africa/Lagos here: reading the UTC column in local time would shift the hour by one + Instant hour = Instant.parse(points.get(0).get("period").asText()); + assertThat(hour).isIn(before.truncatedTo(ChronoUnit.HOURS), Instant.now().truncatedTo(ChronoUnit.HOURS)); + } + + @Test + void engagementScoresRefreshCountsRecentOpens() throws Exception { + long id = sentCampaign(1); + drainQueue(); + String pixel = jdbc.queryForObject("select pixel_token from email_queue where campaign_id = ?", String.class, id); + long recipientId = jdbc.queryForObject("select recipient_id from email_queue where campaign_id = ?", Long.class, id); + mvc.perform(get("/track/open/{token}", pixel)); + + var response = mvc.perform(post("/api/analytics/engagement-scores/refresh").with(authentication(ADMIN))) + .andReturn().getResponse(); + + assertThat(response.getStatus()).isEqualTo(200); + assertThat(jdbc.queryForMap("select campaigns_sent, campaigns_opened from engagement_scores where recipient_id = ?", + recipientId)).containsEntry("campaigns_sent", 1).containsEntry("campaigns_opened", 1); + } + // ── helpers ───────────────────────────────────────────────────────────── private static final AtomicInteger SEQ = new AtomicInteger(); diff --git a/src/test/java/com/mailengine/mailengine/integration/MinimalConfigIntegrationTest.java b/src/test/java/com/mailengine/mailengine/integration/MinimalConfigIntegrationTest.java new file mode 100644 index 0000000..c0f8fca --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/integration/MinimalConfigIntegrationTest.java @@ -0,0 +1,77 @@ +package com.mailengine.mailengine.integration; + +import com.mailengine.mailengine.service.EmailSender; +import com.mailengine.mailengine.service.MockEmailSender; +import com.mailengine.mailengine.support.TestUsers; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.env.Environment; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; + +/** + * The app starts with only the required settings (database, JWT, APP_BASE_URL, AWS_FROM_EMAIL) in the + * mock-email profile: no Resend, SMTP, AWS, S3 or IPinfo credentials. + * + *

Not a {@link PostgresIntegrationSupport} subclass, because that one fills every credential with a fake. + * The optional settings are set blank here, not left out, so a local {@code .env} can't fill them in. + */ +@Tag("integration") +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("mock-email") +class MinimalConfigIntegrationTest { + + private static final List OPTIONAL = List.of( + "RESEND_API_KEY", "MAIL_HOST", "MAIL_USERNAME", "MAIL_PASSWORD", + "aws.access-key-id", "aws.secret-access-key", "aws.s3.bucket", "ipinfo.token"); + + @DynamicPropertySource + static void requiredSettingsOnly(DynamicPropertyRegistry r) { + var postgres = PostgresIntegrationSupport.POSTGRES; + r.add("spring.datasource.url", postgres::getJdbcUrl); + r.add("spring.datasource.username", postgres::getUsername); + r.add("spring.datasource.password", postgres::getPassword); + r.add("jwt.secret", () -> TestUsers.SECRET); + r.add("jwt.expiration", () -> "3600000"); + r.add("app.base-url", () -> "http://localhost:8080"); + r.add("aws.from-email", () -> "noreply@example.test"); + r.add("app.sending.delay-ms", () -> "3600000"); + r.add("app.scheduling.check-ms", () -> "3600000"); + OPTIONAL.forEach(key -> r.add(key, () -> "")); + } + + @Autowired Environment environment; + @Autowired EmailSender emailSender; + @Autowired MockMvc mvc; + + @Test + void appStartsWithoutAnyOptionalCredentials() { + OPTIONAL.forEach(key -> assertThat(environment.getProperty(key)).as(key).isEmpty()); + assertThat(emailSender).isInstanceOf(MockEmailSender.class); + } + + @Test + void imageUploadWithoutABucketSaysItIsNotConfigured() throws Exception { + var image = new MockMultipartFile("file", "logo.png", "image/png", new byte[]{1, 2, 3}); + + var response = mvc.perform(multipart("/api/upload/image").file(image) + .with(authentication(PostgresIntegrationSupport.ADMIN))) + .andReturn().getResponse(); + + assertThat(response.getStatus()).isEqualTo(503); + assertThat(response.getContentAsString()).contains("AWS_S3_BUCKET"); + } +} diff --git a/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java b/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java index 2756c4a..e47dde4 100644 --- a/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java +++ b/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java @@ -175,6 +175,19 @@ void publicRoutesNeedNoToken(Route route) throws Exception { assertThat(perform(route, null).getResponse().getStatus()).isNotIn(401, 403); } + @Test + void corsPreflightIsAnsweredWithoutCredentials() throws Exception { + var response = mvc.perform(request(HttpMethod.OPTIONS, "/api/campaigns") + .header("Origin", "https://frontend.example.com") + .header("Access-Control-Request-Method", "POST") + .header("Access-Control-Request-Headers", "Authorization, Content-Type")) + .andReturn().getResponse(); + + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getHeader("Access-Control-Allow-Origin")).isEqualTo("*"); + assertThat(response.getHeader("Access-Control-Allow-Credentials")).isNull(); + } + @Test void sesWebhookIsReachableWithoutJwtButRejectsUnsignedMessages() throws Exception { // snsMessageVerifier is a mock -> verifySignature(..) returns false