Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
57 changes: 57 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
5 changes: 4 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
32 changes: 18 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -258,36 +258,40 @@ 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 |
| `MAIL_PASSWORD` | `re_xxxxxxxxxxxx` | SMTP password / API key |

### 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_<PACKAGE>` | `LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_SECURITY=DEBUG` | Raise logging for one package while debugging. Everything logs at `INFO` by default |

---

Expand Down Expand Up @@ -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_<PACKAGE>=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.

Expand All @@ -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
```

Expand Down
25 changes: 6 additions & 19 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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) ─────────────────────────────────

Expand All @@ -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'
Expand Down
20 changes: 16 additions & 4 deletions src/main/java/com/mailengine/mailengine/config/AwsConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}

Expand All @@ -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));
}
}
37 changes: 0 additions & 37 deletions src/main/java/com/mailengine/mailengine/config/CorsConfig.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* <p>Supports Brevo (formerly Sendinblue), Gmail, or any SMTP provider by
* changing the host/port in the environment variables below.
*
* <p>Required environment variables:
* <p>Environment variables (only needed when emails actually go out over SMTP):
* <pre>
* MAIL_HOST — SMTP server hostname (e.g. smtp-relay.brevo.com)
* MAIL_PORT — SMTP port (587 for STARTTLS, 465 for SSL)
Expand All @@ -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;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,13 @@ public ResponseEntity<ErrorResponse> handleConflict(ConflictException ex) {
.body(new ErrorResponse(409, ex.getMessage(), null));
}

// ── Feature whose settings are not configured on this server ─────────────
@ExceptionHandler(NotConfiguredException.class)
public ResponseEntity<ErrorResponse> 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<ErrorResponse> handleBadRequest(BadRequestException ex) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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); }
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
Loading
Loading