diff --git a/.env.example b/.env.example index 815c74a..70fdf0d 100644 --- a/.env.example +++ b/.env.example @@ -58,10 +58,22 @@ MAIL_PASSWORD=re_your_resend_api_key_here APP_BASE_URL=http://localhost:8080 # ----------------------------------------------------------------------------- -# IP ENRICHMENT +# IP GEOLOCATION (MaxMind GeoIP2, offline) # ----------------------------------------------------------------------------- -# Optional IPinfo token for IP -> country/city on tracking events -IPINFO_TOKEN=your-ipinfo-token +# Optional path to a GeoLite2-City.mmdb (free MaxMind account) or GeoIP2 database file. +# Without it, tracking events are stored without country/city. +# GEOIP_DATABASE_PATH=/path/to/GeoLite2-City.mmdb + +# ----------------------------------------------------------------------------- +# LIMITS (optional, defaults shown) +# ----------------------------------------------------------------------------- +# Emails per second the send worker may send (SES: 14 by default, 1 in the sandbox; 0 = no cap) +# SEND_RATE_PER_SECOND=14 +# Per client IP: login attempts per minute, and forgot/reset-password + verify-email requests per hour +# LOGIN_RATE_LIMIT_PER_MINUTE=20 +# ACCOUNT_EMAIL_RATE_LIMIT_PER_HOUR=10 +# How long analytics answers are cached +# ANALYTICS_CACHE_TTL=60s # ----------------------------------------------------------------------------- # CORS diff --git a/README.md b/README.md index d181b7b..ec52172 100644 --- a/README.md +++ b/README.md @@ -60,14 +60,16 @@ MailEngine lets you: | Email — fallback 2 | SMTP (JavaMailSender) | | File storage | AWS S3 | | Bounce / complaint webhooks | AWS SNS → SES | -| IP geolocation | IPinfo API | +| IP geolocation | MaxMind GeoIP2 (GeoLite2 database file, looked up offline) | | User-Agent parsing | Yauaa 7.28 | | CSV parsing | OpenCSV 5.9 | | Excel parsing | Apache POI 5.5 | -| Rate limiting | Bucket4j 8.10 | -| Caching | Caffeine (Spring Cache) | +| Rate limiting | Bucket4j 8.10 (worker send rate, public auth endpoints) | +| Caching | Caffeine via Spring Cache (analytics queries) | | API docs | SpringDoc / Swagger UI | | Testing | JUnit 6, Mockito, AssertJ, Spring Security Test, Testcontainers (PostgreSQL) | +| Container | Docker (multi-stage build, runs as a non-root user) | +| CI | GitHub Actions: all test suites and the Docker build on every pull request and push to `main` | --- @@ -96,13 +98,17 @@ MailEngine lets you: ┌───────────▼──────┐ ┌───────────▼──────┐ ┌───────▼────────┐ │ Repository Layer │ │ EmailSender │ │ External APIs │ │ (Spring Data JPA)│ │ (Composite) │ │ │ - │ │ │ 1. Resend │ │ IPinfo │ + │ │ │ 1. Resend │ │ MaxMind DB │ │ PostgreSQL │ │ 2. AWS SES │ │ Yauaa (UA) │ │ (Flyway schema) │ │ 3. SMTP │ │ AWS S3 │ └──────────────────┘ └──────────────────┘ └────────────────┘ Background: - EmailSenderWorker ──► polls email_queue every 3 s (SELECT … FOR UPDATE SKIP LOCKED) + EmailSenderWorker ──► polls email_queue every 3 s (SELECT … FOR UPDATE SKIP LOCKED) + ScheduledCampaignDispatcher ──► starts scheduled campaigns that are due (checks every 60 s) + EngagementScoreService ──► recalculates engagement scores nightly at 02:00 + PendingUploadCleanup ──► hourly, deletes upload files nobody mapped within a day + Import pool ──► CSV / XLSX / XLS imports (see File Import) Inbound webhooks: AWS SNS ──► POST /webhooks/ses ──► SesWebhookController @@ -119,7 +125,7 @@ Public tracking (no auth): ``` src/main/java/com/mailengine/mailengine/ -├── config/ # Spring beans: AwsConfig, SecurityConfig (incl. CORS), MailConfig, OpenApiConfig +├── config/ # Spring beans: AwsConfig, MailConfig, OpenApiConfig, CacheConfig, ImportExecutorConfig, JPA auditing ├── controller/ # REST controllers (one file per resource) ├── dto/ │ ├── request/ # Inbound JSON bodies @@ -127,15 +133,20 @@ src/main/java/com/mailengine/mailengine/ ├── entity/ # JPA entity classes (mapped to DB tables) ├── exception/ # Custom exceptions + GlobalExceptionHandler ├── repository/ # Spring Data JPA interfaces -├── security/ # JwtService, JwtAuthFilter -├── service/ # Business logic (one class per concern) -│ ├── email/ # EmailSender interface + Resend / SES / SMTP / Mock / Composite impls -└── worker/ # EmailSenderWorker (scheduled background task) +├── security/ # SecurityConfig (roles, CORS), JwtService, JwtAuthFilter, AuthRateLimitFilter, +│ # RateLimiter, SecurityUtils, TokenHashing +├── service/ # Business logic, including the EmailSender implementations +│ # (Resend / SES / SMTP / Mock, combined by CompositeEmailSender) +├── util/ # SnsMessageVerifier (checks AWS SNS webhook signatures) +└── worker/ # EmailSenderWorker, EmailQueueStore, ScheduledCampaignDispatcher src/main/resources/ ├── application.yaml # All config (reads from environment variables) ├── db/migration/ # Flyway SQL migrations (V1 is the full schema) └── templates/ # CSV / XLSX import templates served at /template/csv and /template/xlsx + +Dockerfile # Multi-stage image build (see Running the App) +.github/workflows/ci.yml # CI: test suites + Docker build ``` --- @@ -149,6 +160,7 @@ Install these before running the project locally: | Java JDK | 21 | `java -version` to check | | Gradle | 8 (wrapper included) | Use `./gradlew` — no global install needed | | PostgreSQL | 14+ | Must have a running instance | +| Docker | any recent | Needed for the integration and scale tests (Testcontainers) and to run the app as a container | | Git | any | — | **Optional but recommended for full functionality:** @@ -157,7 +169,7 @@ Install these before running the project locally: |---|---| | Resend account | Primary email sending | | AWS account | SES (email fallback), S3 (image storage), SNS (bounce/complaint webhooks) | -| IPinfo token | IP → country/city on open and click events | +| MaxMind GeoLite2 database | IP → country/city on open and click events (free account, offline file) | | ngrok | Expose local server so AWS SNS and email tracking links work | --- @@ -178,12 +190,13 @@ psql -U postgres ``` ```sql -CREATE DATABASE mailengine; CREATE USER mailengine_user WITH PASSWORD 'your-password'; -GRANT ALL PRIVILEGES ON DATABASE mailengine TO mailengine_user; +CREATE DATABASE mailengine OWNER mailengine_user; \q ``` +Making the user the database's owner lets Flyway create tables. (`GRANT ALL PRIVILEGES ON DATABASE` alone isn't enough on PostgreSQL 15+, where ordinary users can no longer create tables in the `public` schema.) + ### 3. Set up environment variables Copy the example file and fill in your values: @@ -289,7 +302,11 @@ All optional. Without them the app starts, SES is skipped, and image uploads ret | Variable | Example | Description | |---|---|---| | `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 | +| `GEOIP_DATABASE_PATH` | `/data/GeoLite2-City.mmdb` | MaxMind GeoLite2 / GeoIP2 City (or Country) database file for IP → country/city on tracking events, looked up offline. Without it, events are stored without location. See [IP geolocation](#ip-geolocation) | +| `SEND_RATE_PER_SECOND` | `14` | Emails per second the send worker may send. Match your provider's limit (SES: 14 by default, 1 in the sandbox). `0` turns the cap off. Default `14` | +| `LOGIN_RATE_LIMIT_PER_MINUTE` | `20` | Login attempts per client IP per minute (429 beyond). Default `20` | +| `ACCOUNT_EMAIL_RATE_LIMIT_PER_HOUR` | `10` | Forgot-password, reset-password and verify-email requests per client IP per hour. Default `10` | +| `ANALYTICS_CACHE_TTL` | `60s` | How long analytics answers are cached. Default `60s` | | `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 | @@ -331,8 +348,15 @@ Flyway applies it automatically on the next startup. **Never modify an already-a | `suppression_list` | Emails that must never be sent to again (bounces, complaints, unsubscribes) | | `campaign_jobs` | Tracks the progress of an in-flight send (sentCount, failedCount, status) | | `engagement_scores` | Per-recipient RFM engagement score, refreshed nightly | -| `file_uploads` | Tracks async CSV/XLSX import jobs | +| `file_uploads` | Tracks async CSV/XLSX/XLS import jobs; deleted with their list | +| `pending_upload_files` | The file of an upload waiting for a column mapping (deleted once imported, or after a day) | | `templates` | HTML email templates with optional JSON visual-editor state | +| `recipient_list_members` | Which recipients are in which list | +| `campaign_recipient_lists` | Which lists a campaign sends to | +| `read_duration_events` | Read-time checkpoints for opened emails | +| `password_reset_tokens`, `email_verification_tokens` | One-time tokens, stored as SHA-256 hashes (the token itself is only in the email) | + +Deleting a user keeps the templates and campaigns they created (`created_by` becomes empty). A template or list that a campaign uses can't be deleted: the API answers 409 and says how many campaigns use it. --- @@ -353,13 +377,24 @@ Spring DevTools is on the classpath — the app will restart automatically when java -jar build/libs/mailengine-0.0.1-SNAPSHOT.jar ``` -See [Testing](#testing). +### Docker + +The `Dockerfile` builds the app with JDK 21 and runs it on a JRE 21 image as a non-root user. Gradle downloads are kept in a BuildKit cache, so rebuilds are quick. + +```bash +docker build -t mailengine . +docker run -d --name mailengine -p 8080:8080 --env-file .env --stop-timeout 35 mailengine +``` + +For IP geolocation, mount the MaxMind file too (see [IP geolocation](#ip-geolocation)). In the env file, `DB_HOST` must be reachable from inside the container: use `host.docker.internal` for a database on your machine (Docker Desktop), or the database container's name when both are on the same Docker network. `--stop-timeout 35` gives running imports time to finish on shutdown (see [Deployment](#deployment)). + +See [Testing](#testing) for the test suites. --- ## Testing -Tests use **JUnit 6, Mockito and AssertJ**. There are two suites: +Tests use **JUnit 6, Mockito and AssertJ**. There are three suites: | Command | What runs | Needs | |---|---|---| @@ -376,10 +411,11 @@ Tests use **JUnit 6, Mockito and AssertJ**. There are two suites: Integration tests are tagged `integration`, and scale tests are tagged `scale`. Both are excluded from `./gradlew test`. Integration tests run with the JVM in a non-UTC time zone (`Africa/Lagos`) on purpose, to catch code that mixes UTC timestamps with the database's local `NOW()`. -Scale tests They start `postgres:16-alpine` with Testcontainers, upload generated CSV/XLSX files through the real endpoint, and print each measurement as a `SCALE |` line. The same lines are appended to `build/scale-results.txt`. +Scale tests start `postgres:16-alpine` with Testcontainers, upload generated CSV/XLSX files through the real endpoint, and print each measurement as a `SCALE |` line. The same lines are appended to `build/scale-results.txt`. Notes: - `MailengineApplicationTests.contextLoads` starts the whole app against PostgreSQL in Docker, so it runs with `./gradlew integrationTest` and doesn't need a local `.env`. +- CI (`.github/workflows/ci.yml`) runs all three suites and builds the Docker image on every pull request and every push to `main`. - `scaleTest` turns off Testcontainers' Ryuk cleanup container, because some Docker Desktop setups can't pull it. The tests stop their own container when the JVM exits. Where things live: @@ -391,7 +427,7 @@ Where things live: | `service/AuthServiceTest`, `service/UserServiceTest` | Login and lockout, password flows, admin-only user management | | `service/FileUploadServiceTest` | Import edge cases: headers and BOM, invalid rows, duplicates, Excel, failure paths | | `importscale/*` | Throughput, memory, bounded import pool, email isolation, restart recovery | -| `integration/*` | Campaign pipeline end to end on PostgreSQL; the `mock-email` profile starts | +| `integration/*` | Campaign pipeline end to end on PostgreSQL, column mapping, user/template/list deletion rules, upload and test-send validation; the `mock-email` profile starts | | `worker/*`, `service/SesEventServiceTest`, `util/SnsMessageVerifierTest` | Worker decisions, scheduled sends, bounce/complaint handling, SNS signature checks | --- @@ -404,7 +440,9 @@ To develop without real email infrastructure, set: SPRING_PROFILES_ACTIVE=mock-email ``` -This activates `MockEmailSender`, which logs every outbound email to the console (to address, subject, first 200 characters of HTML body) and returns a synthetic `mock-{UUID}` message ID. No external service is called. +This activates `MockEmailSender`, which logs every outbound email to the console instead of sending it: recipient, sender, subject, the email's readable text (tags stripped, up to 1,000 characters) and its links. That is enough to use invitations and password resets locally: the invite's temporary password and the reset link are right there in the log. It returns a synthetic `mock-{UUID}` message ID. No external service is called. + +Never use this profile where real people get emails: their temporary passwords and reset links end up in the log. All other functionality (queueing, tracking, analytics) works identically in this mode. @@ -430,7 +468,10 @@ Every user has one role. Spring Security enforces these rules in `SecurityConfig Account protections: - Emails are matched without regard to case (`Admin@x.com` is the same account as `admin@x.com`). - After 5 wrong passwords the account is locked for 15 minutes. Once the lock expires, the user gets a fresh 5 attempts. +- Rate limits per client IP (Bucket4j): 20 login attempts a minute, and 10 forgot-password / reset-password / verify-email requests an hour (`429` with `Retry-After` beyond). On top, at most 3 reset emails per address per hour, however many clients ask, so nobody can flood an inbox. Limits are kept in memory, per app instance. - "Please verify your email" is only shown after a correct password, so it can't be used to discover which addresses have accounts. +- Password reset and email verification links work once, and only their SHA-256 hash is stored, so someone who can read the database can't use them. Reset links expire after 1 hour. +- Self-registration is disabled (`POST /api/auth/register` returns 400): admins invite users. - Passwords must be 8–72 characters. BCrypt ignores anything after 72 bytes, so longer passwords are rejected rather than silently cut short. --- @@ -452,6 +493,7 @@ Authorization: Bearer | POST | `/forgot-password` | — | Sends password reset email (always 200 — no user enumeration) | | POST | `/reset-password` | — | Consumes single-use token, sets new password | | GET/POST | `/verify-email` | — | Verifies email address via one-time token | +| POST | `/register` | — | Disabled: always 400 (users are invited by an admin) | ### Users — `/api/users` (admin only — every endpoint) @@ -474,7 +516,7 @@ Authorization: Bearer | DELETE | `/{id}` | Delete (DRAFT only) | | POST | `/{id}/schedule` | Schedule for a future time | | POST | `/{id}/send` | Start the send pipeline immediately | -| POST | `/{id}/test` | Send a preview to a list of test email addresses | +| POST | `/{id}/test` | Send a preview to a list of test email addresses (`{"testEmails": [...]}`; 400 if empty or invalid) | | GET | `/{id}/job-status` | Poll send progress: progress %, ETA, sent/failed counts | | POST | `/{id}/pause` | Pause an in-progress send | | POST | `/{id}/resume` | Resume a paused send | @@ -486,7 +528,7 @@ Authorization: Bearer | GET | `/` | All lists | | POST | `/` | Create a list | | PUT | `/{id}` | Rename / update description | -| DELETE | `/{id}` | Delete a list | +| DELETE | `/{id}` | Delete a list and its upload history (409 if a campaign uses it) | | GET | `/{id}/export` | Download all recipients as CSV | | GET | `/{listId}/recipients` | Paginated recipients with optional `?search=` | | POST | `/{listId}/upload` | Upload a CSV, XLSX or XLS file (202, async — returns uploadId; 503 if the import queue is full) | @@ -508,7 +550,7 @@ Authorization: Bearer | POST | `/` | Create a template | | GET | `/{id}` | Get template | | PUT | `/{id}` | Update template | -| DELETE | `/{id}` | Delete template | +| DELETE | `/{id}` | Delete template (409 if a campaign uses it) | | POST | `/{id}/duplicate` | Clone template (appends " (Copy)") | | POST | `/upload-html` | Read an `.html`/`.htm` file (UTF-8), returns the HTML string; other files get 400 | @@ -535,7 +577,7 @@ Authorization: Bearer | Method | Path | Description | |---|---|---| | GET | `/open/{pixelToken}` | Called by email clients loading the 1×1 pixel | -| GET | `/click/{clickToken}` | Logs click, redirects to original URL | +| GET | `/click/{clickToken}` | Logs click, redirects to original URL (404 unless that link is in that email) | | GET | `/unsubscribe/{unsubToken}` | Marks recipient unsubscribed, returns HTML confirmation | ### Webhooks — `/webhooks` (public, no auth) @@ -584,11 +626,11 @@ When you call `POST /api/campaigns/{id}/send`, this is what happens: The background worker (`EmailSenderWorker`) then picks up from the queue: ``` -Every 3 seconds: +Every 3 seconds (at most app.sending.rate-per-second emails per second, default 14): SELECT * FROM email_queue WHERE status = 'pending' AND (locked_until IS NULL OR locked_until < NOW()) - LIMIT 20 + LIMIT 20 ← app.sending.batch-size FOR UPDATE SKIP LOCKED ← safe for multiple concurrent workers For each row: @@ -597,9 +639,9 @@ Every 3 seconds: Success → status = SENT, store SES messageId (for webhook correlation) Failure → increment attempts - attempts < 3: status = PENDING, retry with exponential backoff - (2 min → 4 min → 6 min) - attempts ≥ 3: status = FAILED + attempts < 3: status = PENDING, retry later + (2 min after the 1st failure, 4 min after the 2nd) + attempts = 3: status = FAILED Update campaign_job counters atomically (SQL INCREMENT) If 0 pending rows remain → job.status = COMPLETED @@ -615,9 +657,9 @@ Every email contains three invisible tracking mechanisms: ``` When the email client loads this image, `TrackingService.handleOpen()` fires: - Resolves campaign + recipient from `pixelToken` -- Extracts IP from `X-Forwarded-For` → calls IPinfo for country/city +- Extracts IP from `X-Forwarded-For` → looks up country/city in the MaxMind database (offline) - Parses User-Agent via Yauaa for device type, OS, email client -- Sets `isAppleProxy = true` if the User-Agent contains "Apple" and "Mail" (iOS Mail's privacy prefetch — these opens are flagged so you can filter them from open rates) +- Sets `isAppleProxy = true` if the User-Agent contains "Apple" and "Mail" (Apple Mail Privacy Protection pre-fetches images, so these opens are flagged and can be filtered out of open rates) - Saves a `TrackingEvent(type=open)` - Returns the 67-byte PNG so the email renders normally @@ -631,6 +673,12 @@ When the email client loads this image, `TrackingService.handleOpen()` fires: ``` The `?t=` value is the original URL base64url-encoded. On click: log event → 302 redirect → recipient lands on original URL. Transparent to the recipient. +Only links that are really in that recipient's email are followed: an unknown token, or a `?t=` that isn't in the email, gets 404. Otherwise the endpoint would be an open redirect (anyone could make a link on your domain that lands on a phishing page) and fake clicks could be recorded. + +#### IP geolocation + +Country and city come from a MaxMind database file read locally: no network call per event, no per-lookup cost. Create a free MaxMind account, download **GeoLite2 City** (`GeoLite2-City.mmdb`), and point `GEOIP_DATABASE_PATH` at it. MaxMind updates the database regularly; their `geoipupdate` tool fetches new versions, and the app loads the file at startup. A Country database works too (country only). The file is not in the repository (MaxMind's licence doesn't allow redistributing it). In Docker, mount it: `-v /path/GeoLite2-City.mmdb:/data/GeoLite2-City.mmdb:ro -e GEOIP_DATABASE_PATH=/data/GeoLite2-City.mmdb`. + **Unsubscribe tracking** — a link injected near the bottom of every email: ``` {APP_BASE_URL}/track/unsubscribe/{unsubToken} @@ -659,11 +707,11 @@ Once an email is in the suppression list it can never be imported or sent to aga ### Analytics -`AnalyticsService` aggregates `tracking_events` rows on demand. Results are cached with Caffeine (5-minute TTL) to avoid repeated expensive queries. +`AnalyticsService` aggregates `tracking_events` rows on demand. Each answer is cached per campaign in memory (Caffeine) for `ANALYTICS_CACHE_TTL` (default 60 s), so a dashboard refreshing every few seconds doesn't repeat the heavy queries; numbers can lag that much during a send. Engagement scores are cached too, and cleared whenever they are recalculated. | Endpoint | How it's calculated | |---|---| -| Overview rates | `openRate = opens / delivered × 100` (rounded to 2 dp) | +| Overview rates | `openRate = opens / delivered × 100` (rounded to 2 dp). `delivered` comes from SES delivery events, or sent − bounced without them | | Timeline | `DATE_TRUNC('hour', created_at)` buckets, one row per hour | | Link performance | Group by `link_url`, count total + `COUNT(DISTINCT recipient_id)` for uniques | | Device breakdown | Group by `device_type`, count opens and clicks, calculate `%` of total | @@ -714,7 +762,7 @@ Imports run on a dedicated thread pool, separate from the one that sends transac | `app.import.threads` | `4` | Imports processed at the same time | | `app.import.queue-capacity` | `10` | Uploads that may wait. When full, new uploads get **503** and are marked `failed` | -Each waiting upload holds its file (up to 10 MB) in memory, so `queue-capacity` also limits memory use. +Each waiting upload holds its file (up to 10 MB) in memory, so `queue-capacity` also limits memory use. `POST /api/uploads/{id}/map` runs on the same pool and answers once the import is done (503 if the pool is full). **Restarts:** on shutdown, Spring waits up to 30 s (`spring.lifecycle.timeout-per-shutdown-phase`) for running imports. Anything still unfinished can't record its result, so on the next startup `ImportRecovery` marks every upload left in `processing` as `failed`. Users can then simply upload again. *This assumes a single app instance.* @@ -737,7 +785,7 @@ Import templates (with the correct column headers) are downloadable at: `EngagementScoreService` runs a scheduled job every night at 02:00 and recalculates a score (0–100) for every recipient using an RFM-style model: ``` -recencyScore = (1 − min(daysSinceLastOpen, 90) / 90) × 40 (max 40 pts) +recencyScore = (1 − min(daysSinceLastActivity, 90) / 90) × 40 (max 40 pts; last click, else last open) frequencyScore = min(opened / sent, 1) × 30 (max 30 pts) clickScore = min(clicked / opened, 1) × 30 (max 30 pts) @@ -761,7 +809,7 @@ The typical pattern for adding a new resource (e.g. "Tags"): ### 1. Database migration ```sql --- src/main/resources/db/migration/V23__create_tags.sql +-- src/main/resources/db/migration/V2__create_tags.sql (the next free number) CREATE TABLE tags ( id BIGSERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, @@ -852,7 +900,7 @@ Use the existing custom exceptions — no new classes needed in most cases: | Malformed JSON, unknown enum value, non-numeric id, missing request parameter | 400 | | Unknown route | 404 | | Wrong HTTP method | 405 | -| Database constraint violation | 409 | +| Database constraint violation (prefer checking first and throwing `ConflictException` with a reason) | 409 | To get the current user in a service, use `SecurityUtils.currentUser()`. It returns 401 instead of crashing when nobody is logged in. @@ -869,7 +917,7 @@ To get the current user in a service, use `SecurityUtils.currentUser()`. It retu | AWS SES | Email sending fallback + bounce/complaint webhooks | | AWS S3 | Template image and file storage | | AWS SNS | Forwards SES events to `/webhooks/ses` | -| IPinfo | IP geolocation on tracking events | +| MaxMind GeoLite2 / GeoIP2 database file | IP geolocation on tracking events | ### Key configuration for production @@ -881,12 +929,16 @@ To get the current user in a service, use `SecurityUtils.currentUser()`. It retu 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. +5. **Imports and restarts:** give the app a stop grace period of at least 30 s (for example `docker run --stop-timeout 35`, or `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. 6. **Single instance:** startup import recovery assumes one app instance. If you run several against the same database, revisit `ImportRecovery` first. 7. **`server.forward-headers-strategy: native`** — Already configured. This ensures `X-Forwarded-For` and `X-Forwarded-Proto` are trusted when running behind a reverse proxy (Railway, Heroku, nginx, etc.). +8. **Never run with `SPRING_PROFILES_ACTIVE=mock-email` in production:** emails aren't sent, and temporary passwords and reset links are written to the log. + +9. **Container image:** build it with the `Dockerfile` (see [Docker](#docker)). It exposes port 8080 and runs as a non-root user. + ### Environment variable checklist for production ``` @@ -896,7 +948,8 @@ 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 +GEOIP_DATABASE_PATH (mount the .mmdb file) +SEND_RATE_PER_SECOND (your provider's limit) ``` ### Health check endpoint diff --git a/build.gradle b/build.gradle index a64d4e7..edc77fc 100644 --- a/build.gradle +++ b/build.gradle @@ -61,16 +61,18 @@ dependencies { implementation platform('software.amazon.awssdk:bom:2.25.27') implementation 'software.amazon.awssdk:s3' // template images and uploads implementation 'software.amazon.awssdk:ses' // sending + // Not called directly: the default credentials chain needs it for IAM roles assumed through STS + // (web identity / EKS service-account roles, role_arn profiles). SES bounce/complaint events arrive over HTTP + // from SNS and are verified by SnsMessageVerifier, so no SNS SDK module is needed. implementation 'software.amazon.awssdk:sts' - implementation 'software.amazon.awssdk:sns' // SES bounce/complaint webhooks // ── Ahmed's ADDITIONS (BE-3 & BE-4) ───────────────────────────────── // Rate limiting — controls how fast the worker sends emails to SES (BE-3) implementation 'com.bucket4j:bucket4j-core:8.10.1' - // IPinfo — converts an IP address to country + city on open/click events (BE-4) - implementation 'io.ipinfo:ipinfo-spring:0.3.1' + // MaxMind GeoIP2: offline IP -> country + city on open/click events, from a GeoLite2/GeoIP2 database file (BE-4) + implementation 'com.maxmind.geoip2:geoip2:4.2.0' // User-Agent parsing — detects device type, email client, OS from request headers (BE-4) implementation 'nl.basjes.parse.useragent:yauaa:7.28.1' diff --git a/src/main/java/com/mailengine/mailengine/config/CacheConfig.java b/src/main/java/com/mailengine/mailengine/config/CacheConfig.java new file mode 100644 index 0000000..f1696b8 --- /dev/null +++ b/src/main/java/com/mailengine/mailengine/config/CacheConfig.java @@ -0,0 +1,37 @@ +package com.mailengine.mailengine.config; + +import com.github.benmanes.caffeine.cache.Caffeine; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.caffeine.CaffeineCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.time.Duration; + +/** + * In-memory caching (Caffeine) for the analytics queries, which aggregate every tracking event of a campaign + * on each request: a dashboard refreshing every few seconds would otherwise repeat the same heavy queries. + * Entries expire {@code app.analytics.cache-ttl} after they are computed (default 60 s), so numbers can lag + * that much behind while a campaign sends. Per application instance. + */ +@Configuration +@EnableCaching +public class CacheConfig { + + public static final String OVERVIEW = "analyticsOverview"; + public static final String TIMELINE = "analyticsTimeline"; + public static final String LINKS = "analyticsLinks"; + public static final String DEVICES = "analyticsDevices"; + public static final String GEOGRAPHY = "analyticsGeography"; + public static final String ENGAGEMENT_SCORES = "engagementScores"; + + @Bean + public CacheManager cacheManager(@Value("${app.analytics.cache-ttl:60s}") Duration ttl) { + CaffeineCacheManager manager = new CaffeineCacheManager(OVERVIEW, TIMELINE, LINKS, DEVICES, GEOGRAPHY, ENGAGEMENT_SCORES); + manager.setCaffeine(Caffeine.newBuilder().expireAfterWrite(ttl).maximumSize(1_000)); + manager.setAllowNullValues(false); + return manager; + } +} diff --git a/src/main/java/com/mailengine/mailengine/controller/AuthController.java b/src/main/java/com/mailengine/mailengine/controller/AuthController.java index c4ebf7c..ada77a1 100644 --- a/src/main/java/com/mailengine/mailengine/controller/AuthController.java +++ b/src/main/java/com/mailengine/mailengine/controller/AuthController.java @@ -36,19 +36,13 @@ public class AuthController { private final AuthService authService; /** - * Registers a new company account and its first admin user. + * Self-registration is disabled: this is a single-organisation install, and admins invite users + * ({@code POST /api/users/invite}). Kept so old clients get a clear 400 instead of a 404. * *

POST /api/auth/register * - *

Flow: - *

    - *
  1. Creates an {@code Account} (company) and a {@code User} with role ADMIN.
  2. - *
  3. Sends a verification email with a 24-hour token.
  4. - *
  5. User must click the link before they can log in.
  6. - *
- * - * @param request registration details: name, email, password, companyName - * @return 201 Created with a message to check email + * @param request ignored + * @return 400 with an explanation */ @PostMapping("/register") @ResponseStatus(HttpStatus.BAD_REQUEST) diff --git a/src/main/java/com/mailengine/mailengine/controller/TrackingController.java b/src/main/java/com/mailengine/mailengine/controller/TrackingController.java index b58fd27..e7e5fb7 100644 --- a/src/main/java/com/mailengine/mailengine/controller/TrackingController.java +++ b/src/main/java/com/mailengine/mailengine/controller/TrackingController.java @@ -82,7 +82,7 @@ public ResponseEntity trackOpen( * * @param clickToken the unique token identifying this recipient's queued email * @param request HTTP request — used to read the {@code ?t=} param, IP, and User-Agent - * @return 302 redirect to the original URL, or to the homepage if the token is unknown + * @return 302 redirect to the original URL, or 404 if the token is unknown or the link isn't in that email */ @GetMapping("/click/{clickToken}") public ResponseEntity trackClick( @@ -92,10 +92,8 @@ public ResponseEntity trackClick( String originalUrl = trackingService.handleClick(clickToken, request); if (originalUrl == null) { - // Token not found — redirect to homepage rather than returning a 404 - return ResponseEntity.status(HttpStatus.FOUND) - .header("Location", "https://mailengine.com") - .build(); + // Unknown token, or a link that isn't in that email: never redirect somewhere we didn't send + return ResponseEntity.notFound().build(); } // 302 Found — browser follows the Location header automatically diff --git a/src/main/java/com/mailengine/mailengine/security/AuthRateLimitFilter.java b/src/main/java/com/mailengine/mailengine/security/AuthRateLimitFilter.java new file mode 100644 index 0000000..c658aa0 --- /dev/null +++ b/src/main/java/com/mailengine/mailengine/security/AuthRateLimitFilter.java @@ -0,0 +1,72 @@ +package com.mailengine.mailengine.security; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.time.Duration; + +/** + * Limits the public auth endpoints per client IP, answering 429 with Retry-After when a client goes over: + *
    + *
  • login: {@code app.rate-limit.login-per-minute} (default 20) per minute. The per-account lockout stops + * guessing one account's password; this stops one client trying many accounts, or keeping someone else's + * account locked.
  • + *
  • forgot-password, reset-password, verify-email: {@code app.rate-limit.account-emails-per-hour} (default 10) + * per hour, so nobody can flood inboxes or run up sending costs. AuthService also limits reset emails + * per address.
  • + *
+ * The client IP is {@code request.getRemoteAddr()}: behind a trusted proxy the server's forward-headers support + * already resolves it from X-Forwarded-For, and a client can't fake it by sending the header itself. + */ +@Slf4j +@Component +public class AuthRateLimitFilter extends OncePerRequestFilter { + + private final RateLimiter login; + private final RateLimiter accountEmails; + + public AuthRateLimitFilter(@Value("${app.rate-limit.login-per-minute:20}") long loginPerMinute, + @Value("${app.rate-limit.account-emails-per-hour:10}") long accountEmailsPerHour) { + this.login = new RateLimiter(loginPerMinute, Duration.ofMinutes(1)); + this.accountEmails = new RateLimiter(accountEmailsPerHour, Duration.ofHours(1)); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + RateLimiter limiter = limiterFor(request); + if (limiter != null) { + long retryAfter = limiter.tryAcquire(request.getRemoteAddr()); + if (retryAfter > 0) { + log.warn("Rate limit hit: {} {} from {}", request.getMethod(), request.getRequestURI(), request.getRemoteAddr()); + response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); + response.setHeader("Retry-After", String.valueOf(retryAfter)); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.getWriter().write("{\"message\":\"Too many requests. Try again in " + retryAfter + " seconds.\"}"); + return; + } + } + chain.doFilter(request, response); + } + + private RateLimiter limiterFor(HttpServletRequest request) { + String path = request.getRequestURI().substring(request.getContextPath().length()); + if (path.endsWith("/")) path = path.substring(0, path.length() - 1); + boolean post = "POST".equals(request.getMethod()); + return switch (path) { + case "/api/auth/login" -> post ? login : null; + case "/api/auth/forgot-password", "/api/auth/reset-password" -> post ? accountEmails : null; + case "/api/auth/verify-email" -> accountEmails; + default -> null; + }; + } +} diff --git a/src/main/java/com/mailengine/mailengine/security/RateLimiter.java b/src/main/java/com/mailengine/mailengine/security/RateLimiter.java new file mode 100644 index 0000000..257b264 --- /dev/null +++ b/src/main/java/com/mailengine/mailengine/security/RateLimiter.java @@ -0,0 +1,38 @@ +package com.mailengine.mailengine.security; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import io.github.bucket4j.Bandwidth; +import io.github.bucket4j.Bucket; +import io.github.bucket4j.ConsumptionProbe; + +import java.time.Duration; + +/** + * In-memory token buckets (Bucket4j), one per key: each key may do {@code limit} actions per {@code period}, and + * its allowance refills gradually. Buckets idle for longer than the period are forgotten (Caffeine), so memory + * stays bounded however many keys (IP addresses, email addresses) show up. + * + *

Per application instance: with several instances, each one counts on its own. + */ +public final class RateLimiter { + + private final long limit; + private final Duration period; + private final Cache buckets; + + public RateLimiter(long limit, Duration period) { + this.limit = limit; + this.period = period; + this.buckets = Caffeine.newBuilder().expireAfterAccess(period).maximumSize(100_000).build(); + } + + /** Takes one action from {@code key}'s allowance: 0 if allowed, otherwise the seconds until it is. */ + public long tryAcquire(String key) { + Bucket bucket = buckets.get(key, k -> Bucket.builder() + .addLimit(Bandwidth.builder().capacity(limit).refillGreedy(limit, period).build()) + .build()); + ConsumptionProbe probe = bucket.tryConsumeAndReturnRemaining(1); + return probe.isConsumed() ? 0 : Math.max(1, Duration.ofNanos(probe.getNanosToWaitForRefill()).toSeconds() + 1); + } +} diff --git a/src/main/java/com/mailengine/mailengine/service/AnalyticsService.java b/src/main/java/com/mailengine/mailengine/service/AnalyticsService.java index 2af840b..bf46d4c 100644 --- a/src/main/java/com/mailengine/mailengine/service/AnalyticsService.java +++ b/src/main/java/com/mailengine/mailengine/service/AnalyticsService.java @@ -1,5 +1,6 @@ package com.mailengine.mailengine.service; +import com.mailengine.mailengine.config.CacheConfig; import com.mailengine.mailengine.dto.response.analytics.*; import com.mailengine.mailengine.entity.Campaign; import com.mailengine.mailengine.exception.ResourceNotFoundException; @@ -10,6 +11,7 @@ import jakarta.persistence.Tuple; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.math.BigDecimal; @@ -36,6 +38,7 @@ public class AnalyticsService { /** * Returns high‑level statistics for a given campaign. */ + @Cacheable(CacheConfig.OVERVIEW) public CampaignAnalyticsOverview getCampaignOverview(Long campaignId) { Campaign campaign = campaignRepository.findById(campaignId) .orElseThrow(() -> new ResourceNotFoundException("Campaign not found")); @@ -101,6 +104,7 @@ public CampaignAnalyticsOverview getCampaignOverview(Long campaignId) { /** * Returns opens, clicks, and unsubscribes grouped by hour. */ + @Cacheable(CacheConfig.TIMELINE) public List getTimeline(Long campaignId) { String sql = """ SELECT @@ -153,6 +157,7 @@ private static Instant utcInstant(Object value) { /** * Returns click counts per unique link. */ + @Cacheable(CacheConfig.LINKS) public List getLinkPerformance(Long campaignId) { Campaign campaign = campaignRepository.findById(campaignId) .orElseThrow(() -> new ResourceNotFoundException("Campaign not found")); @@ -197,6 +202,7 @@ public List getLinkPerformance(Long campaignId) { /** * Returns the distribution of opens and clicks by device type. */ + @Cacheable(CacheConfig.DEVICES) public List getDeviceBreakdown(Long campaignId) { String sql = """ SELECT @@ -241,6 +247,7 @@ public List getDeviceBreakdown(Long campaignId) { /** * Returns opens and clicks aggregated by country and city. */ + @Cacheable(CacheConfig.GEOGRAPHY) public List getGeographyData(Long campaignId) { String sql = """ SELECT diff --git a/src/main/java/com/mailengine/mailengine/service/AuthService.java b/src/main/java/com/mailengine/mailengine/service/AuthService.java index b806b8a..b5f71fd 100644 --- a/src/main/java/com/mailengine/mailengine/service/AuthService.java +++ b/src/main/java/com/mailengine/mailengine/service/AuthService.java @@ -11,13 +11,16 @@ import com.mailengine.mailengine.repository.PasswordResetTokenRepository; import com.mailengine.mailengine.repository.UserRepository; import com.mailengine.mailengine.security.JwtService; +import com.mailengine.mailengine.security.RateLimiter; import com.mailengine.mailengine.security.SecurityUtils; import com.mailengine.mailengine.security.TokenHashing; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Locale; @@ -26,6 +29,7 @@ @Service @RequiredArgsConstructor @Transactional +@Slf4j public class AuthService { private static final int MAX_FAILED_ATTEMPTS = 5; @@ -38,6 +42,9 @@ public class AuthService { private final PasswordEncoder passwordEncoder; private final EmailService emailService; + /** At most 3 password reset emails per address per hour, however many clients ask (see AuthRateLimitFilter). */ + private final RateLimiter resetEmailsPerAddress = new RateLimiter(3, Duration.ofHours(1)); + public void register(RegisterRequest request) { throw new BadRequestException("Self-registration is disabled. Contact your administrator."); } @@ -128,6 +135,11 @@ public void changePassword(ChangePasswordRequest request) { public void forgotPassword(ForgotPasswordRequest request) { userRepository.findByEmailIgnoreCase(normalizeEmail(request.getEmail())).ifPresent(user -> { + // The answer stays the same either way, so this doesn't reveal whether the address has an account + if (resetEmailsPerAddress.tryAcquire(user.getEmail()) > 0) { + log.warn("Password reset emails to user {} are rate limited", user.getId()); + return; + } passwordResetTokenRepository.deleteByUserId(user.getId()); String token = UUID.randomUUID().toString(); // Only the hash is stored; the token itself exists only in the email diff --git a/src/main/java/com/mailengine/mailengine/service/EngagementScoreService.java b/src/main/java/com/mailengine/mailengine/service/EngagementScoreService.java index 8e7ce19..1c3c5e7 100644 --- a/src/main/java/com/mailengine/mailengine/service/EngagementScoreService.java +++ b/src/main/java/com/mailengine/mailengine/service/EngagementScoreService.java @@ -1,10 +1,13 @@ package com.mailengine.mailengine.service; +import com.mailengine.mailengine.config.CacheConfig; import com.mailengine.mailengine.dto.response.analytics.EngagementScoreResponse; import com.mailengine.mailengine.entity.EngagementScore; import com.mailengine.mailengine.repository.EngagementScoreRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -24,6 +27,7 @@ public class EngagementScoreService { @Scheduled(cron = "0 0 2 * * *") @Transactional + @CacheEvict(value = CacheConfig.ENGAGEMENT_SCORES, allEntries = true) public void updateAllScores() { log.info("Starting nightly engagement score update"); // UTC, like every timestamp Hibernate writes (see EmailQueueRepository) @@ -42,6 +46,7 @@ public void updateAllScores() { * database session had closed, which failed with a 500. */ @Transactional(readOnly = true) + @Cacheable(CacheConfig.ENGAGEMENT_SCORES) public List getScores() { return engagementScoreRepository.findAll().stream() .map(s -> new EngagementScoreResponse( diff --git a/src/main/java/com/mailengine/mailengine/service/GeoIpService.java b/src/main/java/com/mailengine/mailengine/service/GeoIpService.java index 1363f32..074ca0d 100644 --- a/src/main/java/com/mailengine/mailengine/service/GeoIpService.java +++ b/src/main/java/com/mailengine/mailengine/service/GeoIpService.java @@ -1,54 +1,102 @@ package com.mailengine.mailengine.service; -import io.ipinfo.api.IPinfo; -import io.ipinfo.api.model.IPResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import com.maxmind.db.CHMCache; +import com.maxmind.geoip2.DatabaseReader; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; +import java.util.regex.Pattern; + /** - * Service for geolocation lookups using the IPinfo API. - * This replaces the in-memory MaxMind GeoIP database to significantly - * reduce memory footprint. + * Country and city of an IP address, for open and click events: an offline lookup in a MaxMind GeoLite2 / + * GeoIP2 database file ({@code GEOIP_DATABASE_PATH}). No network call per event and no per-lookup cost. + * + *

Optional: without the file, lookups return null and events are stored without a location. A City + * database gives country and city; a Country database gives the country only. MaxMind publishes updates + * regularly (their {@code geoipupdate} tool fetches them); restart the app to load a new file. */ +@Slf4j @Service -public class GeoIpService { - - private static final Logger log = LoggerFactory.getLogger(GeoIpService.class); - - private final IPinfo ipInfo; - - /** - * Initializes the IPinfo client with the API token from configuration. - * - * @param token IPinfo API token (injected from application.yaml) - */ - 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)"); +public class GeoIpService implements DisposableBean { + + /** ISO country code (e.g. "NG") and city name, either of which may be null. */ + public record Location(String countryCode, String city) { + } + + /** Only IP literals: InetAddress.getByName would otherwise resolve a host name over DNS. */ + private static final Pattern IP_LITERAL = Pattern.compile("[0-9A-Fa-f:.]+"); + private static final int MAX_CITY = 100; // tracking_events.geo_city + + private final DatabaseReader reader; + private final boolean hasCities; + + @Autowired + public GeoIpService(@Value("${app.geoip.database-path:}") String databasePath) { + this(open(databasePath)); + } + + GeoIpService(DatabaseReader reader) { + this.reader = reader; + this.hasCities = reader != null && reader.getMetadata().getDatabaseType().contains("City"); + } + + private static DatabaseReader open(String path) { + if (path == null || path.isBlank()) { + log.info("GEOIP_DATABASE_PATH not set: tracking events are stored without country/city"); + return null; + } + File file = new File(path.trim()); + if (!file.isFile()) { + log.warn("GeoIP database {} not found: tracking events are stored without country/city", file); + return null; + } + try { + DatabaseReader reader = new DatabaseReader.Builder(file).withCache(new CHMCache()).build(); + log.info("GeoIP lookups from {} ({}, built {})", file, reader.getMetadata().getDatabaseType(), + reader.getMetadata().getBuildDate()); + return reader; + } catch (IOException | RuntimeException e) { + log.warn("GeoIP database {} could not be read ({}): tracking events are stored without country/city", + file, e.getMessage()); + return null; } } - /** - * Looks up geolocation information for a given IP address. - * - * @param ipAddress the IP address to look up (e.g., "8.8.8.8") - * @return IPResponse containing city, country, coordinates, etc., or null if lookup fails - */ - public IPResponse lookup(String ipAddress) { - if (ipInfo == null) return null; + /** The location of {@code ipAddress}, or null when unknown (no database, private address, not in it). */ + public Location lookup(String ipAddress) { + if (reader == null || ipAddress == null || !IP_LITERAL.matcher(ipAddress.trim()).matches()) { + return null; + } try { - return ipInfo.lookupIP(ipAddress); - } catch (Exception e) { - log.error("Failed to lookup IP address {}: {}", ipAddress, e.getMessage()); + InetAddress address = InetAddress.getByName(ipAddress.trim()); + if (address.isLoopbackAddress() || address.isSiteLocalAddress() || address.isLinkLocalAddress() + || address.isAnyLocalAddress()) { + return null; + } + if (hasCities) { + return reader.tryCity(address) + .map(r -> new Location(r.getCountry().getIsoCode(), truncate(r.getCity().getName()))) + .orElse(null); + } + return reader.tryCountry(address).map(r -> new Location(r.getCountry().getIsoCode(), null)).orElse(null); + } catch (Exception e) { // a lookup problem must never fail the tracking request + log.debug("GeoIP lookup of {} failed: {}", ipAddress, e.getMessage()); return null; } } -} \ No newline at end of file + + private static String truncate(String city) { + return city == null || city.length() <= MAX_CITY ? city : city.substring(0, MAX_CITY); + } + + @Override + public void destroy() throws IOException { + if (reader != null) reader.close(); + } +} diff --git a/src/main/java/com/mailengine/mailengine/service/TrackingService.java b/src/main/java/com/mailengine/mailengine/service/TrackingService.java index 050f115..c455486 100644 --- a/src/main/java/com/mailengine/mailengine/service/TrackingService.java +++ b/src/main/java/com/mailengine/mailengine/service/TrackingService.java @@ -7,7 +7,6 @@ import com.mailengine.mailengine.repository.EmailQueueRepository; import com.mailengine.mailengine.repository.RecipientRepository; import com.mailengine.mailengine.repository.TrackingEventRepository; -import io.ipinfo.api.model.IPResponse; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -32,7 +31,7 @@ *

Every event is enriched with: *

    *
  • The client IP address (respecting X-Forwarded-For for proxied requests)
  • - *
  • Country and city via {@link GeoIpService} (IPinfo API)
  • + *
  • Country and city via {@link GeoIpService} (MaxMind GeoIP2 database, offline)
  • *
  • Device type, OS, and email client via {@link UserAgentParserService} (Yauaa)
  • *
  • Apple Mail proxy detection (flags artificial opens caused by iOS privacy protection)
  • *
@@ -145,20 +144,22 @@ public byte[] handleOpen(String pixelToken, HttpServletRequest request) { public String handleClick(String clickToken, HttpServletRequest request) { EmailQueue queued = emailQueueRepository.findByClickToken(clickToken).orElse(null); - // Decode the original URL from the ?t= query parameter - String encodedUrl = request.getParameter("t"); - String originalUrl = decodeUrl(encodedUrl); - if (queued == null) { log.warn("Click token not found: {}", clickToken); - // Still redirect to the decoded URL if we have it — the user clicked a - // real link even if the token lookup failed - return originalUrl != null ? originalUrl : "https://mailengine.com"; + return null; } + // Only redirect to a link that really is in this email. Otherwise anyone holding one tracking link + // (or none) could use this server to redirect people anywhere (an open redirect, good for phishing), + // and could record fake clicks. + String encodedUrl = request.getParameter("t"); + if (encodedUrl == null || !linkIsInEmail(queued, clickToken, encodedUrl)) { + log.warn("Click on a link that isn't in the email (click token {})", clickToken); + return null; + } + String originalUrl = decodeUrl(encodedUrl); if (originalUrl == null) { - log.warn("Missing or invalid 't' parameter for click token: {}", clickToken); - originalUrl = "https://mailengine.com"; + return null; } String ipAddress = extractIp(request); @@ -244,10 +245,10 @@ private void enrichEventWithGeoAndDevice(TrackingEvent event, String ipAddress, String userAgent) { if (ipAddress != null && !ipAddress.isEmpty()) { - IPResponse ipResponse = geoIpService.lookup(ipAddress); - if (ipResponse != null) { - event.setGeoCountry(ipResponse.getCountryCode()); - event.setGeoCity(ipResponse.getCity()); + GeoIpService.Location location = geoIpService.lookup(ipAddress); + if (location != null) { + event.setGeoCountry(location.countryCode()); + event.setGeoCity(location.city()); } } if (userAgent != null && !userAgent.isEmpty()) { @@ -298,6 +299,12 @@ private boolean isAppleMailProxy(String userAgent) { * @param encoded the base64url string from the {@code ?t=} query parameter * @return the decoded UTF-8 URL string, or {@code null} if input is null/blank/malformed */ + /** The sent email holds each tracked link exactly as CampaignSendingService wrote it. */ + private static boolean linkIsInEmail(EmailQueue queued, String clickToken, String encodedUrl) { + String html = queued.getHtmlContent(); + return html != null && html.contains("/track/click/" + clickToken + "?t=" + encodedUrl + "\""); + } + private String decodeUrl(String encoded) { if (encoded == null || encoded.isBlank()) { return null; diff --git a/src/main/java/com/mailengine/mailengine/worker/EmailSenderWorker.java b/src/main/java/com/mailengine/mailengine/worker/EmailSenderWorker.java index c7c8f03..a21991a 100644 --- a/src/main/java/com/mailengine/mailengine/worker/EmailSenderWorker.java +++ b/src/main/java/com/mailengine/mailengine/worker/EmailSenderWorker.java @@ -2,12 +2,15 @@ import com.mailengine.mailengine.entity.EmailQueue; import com.mailengine.mailengine.service.EmailSender; +import io.github.bucket4j.Bandwidth; +import io.github.bucket4j.Bucket; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; +import java.time.Duration; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -33,6 +36,21 @@ public class EmailSenderWorker { @Value("${app.sending.batch-size:20}") private int batchSize; + /** Caps how fast emails go out; null (as in unit tests) means no cap. */ + private Bucket sendRate; + + /** + * Emails per second the worker may send ({@code app.sending.rate-per-second}, default 14: SES's default + * production limit; 1 in the SES sandbox). Going faster only gets throttling errors back, which turn into + * retries and failures. A Bucket4j token bucket that refills every second; 0 or less turns the cap off. + */ + @Value("${app.sending.rate-per-second:14}") + void setRatePerSecond(long ratePerSecond) { + sendRate = ratePerSecond <= 0 ? null : Bucket.builder() + .addLimit(Bandwidth.builder().capacity(ratePerSecond).refillGreedy(ratePerSecond, Duration.ofSeconds(1)).build()) + .build(); + } + /** fixedDelay: the next cycle starts {@code app.sending.delay-ms} after this one ends, so cycles never overlap. */ @Scheduled(fixedDelayString = "${app.sending.delay-ms:3000}") public void processEmailBatch() { @@ -41,7 +59,8 @@ public void processEmailBatch() { Map sentAndFailedByCampaign = new LinkedHashMap<>(); Set paused = new HashSet<>(); - for (EmailQueue queued : batch) { + for (int i = 0; i < batch.size(); i++) { + EmailQueue queued = batch.get(i); Long campaignId = queued.getCampaign() == null ? null : queued.getCampaign().getId(); // Checked before every email, so a pause takes effect mid-batch @@ -51,6 +70,11 @@ public void processEmailBatch() { continue; } + if (!awaitSendSlot()) { + // Shutting down: hand the rest back so the next worker sends them straight away + batch.subList(i, batch.size()).forEach(rest -> store.release(rest.getId())); + break; + } int[] tally = sentAndFailedByCampaign.computeIfAbsent(campaignId, id -> new int[2]); String messageId = send(queued); if (messageId != null) { @@ -68,6 +92,18 @@ public void processEmailBatch() { sentAndFailedByCampaign.keySet(), paused); } + /** Waits until the send rate allows one more email; false if interrupted (the app is stopping). */ + private boolean awaitSendSlot() { + if (sendRate == null) return true; + try { + sendRate.asBlocking().consume(1); + return true; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + /** A sender that throws is treated like one that refused: the email is retried. */ private String send(EmailQueue queued) { try { diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 183503c..f24696e 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -56,6 +56,20 @@ app: sending: batch-size: 20 delay-ms: 3000 + # Emails per second the worker may send: match your provider's limit (SES: 14 by default, 1 in the sandbox). + # 0 turns the cap off. + rate-per-second: ${SEND_RATE_PER_SECOND:14} + rate-limit: + # Per client IP, on the public auth endpoints (429 when exceeded) + login-per-minute: ${LOGIN_RATE_LIMIT_PER_MINUTE:20} + account-emails-per-hour: ${ACCOUNT_EMAIL_RATE_LIMIT_PER_HOUR:10} + analytics: + # How long analytics answers are cached (Caffeine). Numbers can be this far behind while a campaign sends. + cache-ttl: ${ANALYTICS_CACHE_TTL:60s} + geoip: + # MaxMind GeoLite2/GeoIP2 City (or Country) database file. Optional: without it, tracking events are stored + # without country/city. + database-path: ${GEOIP_DATABASE_PATH:} cors: # Comma-separated origins allowed to call the API from a browser, e.g. https://app.example.com allowed-origins: ${CORS_ALLOWED_ORIGINS:*} @@ -69,10 +83,6 @@ aws: s3: bucket: ${AWS_S3_BUCKET:} -ipinfo: - # 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 diff --git a/src/test/java/com/mailengine/mailengine/config/OptionalSettingsTest.java b/src/test/java/com/mailengine/mailengine/config/OptionalSettingsTest.java index ab5ec97..a6d9bb5 100644 --- a/src/test/java/com/mailengine/mailengine/config/OptionalSettingsTest.java +++ b/src/test/java/com/mailengine/mailengine/config/OptionalSettingsTest.java @@ -43,8 +43,16 @@ void smtpWithoutUsernameIsSkippedWithoutConnecting() { } @Test - void geoLookupWithoutTokenReturnsNothing() { - assertThat(new GeoIpService("").lookup("8.8.8.8")).isNull(); + void geoLookupWithoutAUsableDatabaseReturnsNothing() throws Exception { + java.nio.file.Path junk = java.nio.file.Files.createTempFile("geo", ".mmdb"); + java.nio.file.Files.writeString(junk, "not a maxmind database"); + try { + assertThat(new GeoIpService("").lookup("8.8.8.8")).as("not configured").isNull(); + assertThat(new GeoIpService("/nowhere/GeoLite2-City.mmdb").lookup("8.8.8.8")).as("missing file").isNull(); + assertThat(new GeoIpService(junk.toString()).lookup("8.8.8.8")).as("unreadable file").isNull(); + } finally { + java.nio.file.Files.delete(junk); + } } @Test diff --git a/src/test/java/com/mailengine/mailengine/importscale/ImportScaleSupport.java b/src/test/java/com/mailengine/mailengine/importscale/ImportScaleSupport.java index e3bff21..c36b30d 100644 --- a/src/test/java/com/mailengine/mailengine/importscale/ImportScaleSupport.java +++ b/src/test/java/com/mailengine/mailengine/importscale/ImportScaleSupport.java @@ -81,7 +81,6 @@ static void properties(DynamicPropertyRegistry r) { r.add("aws.secret-access-key", () -> "test"); r.add("aws.from-email", () -> "noreply@example.test"); r.add("aws.s3.bucket", () -> "test-bucket"); - r.add("ipinfo.token", () -> "test"); r.add("app.base-url", () -> "http://localhost:8080"); // Production config logs Spring at DEBUG; that would only make these runs slower and noisier r.add("logging.level.org.springframework", () -> "WARN"); diff --git a/src/test/java/com/mailengine/mailengine/integration/MinimalConfigIntegrationTest.java b/src/test/java/com/mailengine/mailengine/integration/MinimalConfigIntegrationTest.java index c0f8fca..eb1fe2f 100644 --- a/src/test/java/com/mailengine/mailengine/integration/MinimalConfigIntegrationTest.java +++ b/src/test/java/com/mailengine/mailengine/integration/MinimalConfigIntegrationTest.java @@ -23,7 +23,7 @@ /** * 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. + * mock-email profile: no Resend, SMTP, AWS or S3 credentials and no GeoIP database. * *

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. @@ -36,7 +36,7 @@ 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"); + "aws.access-key-id", "aws.secret-access-key", "aws.s3.bucket", "app.geoip.database-path"); @DynamicPropertySource static void requiredSettingsOnly(DynamicPropertyRegistry r) { diff --git a/src/test/java/com/mailengine/mailengine/integration/PostgresIntegrationSupport.java b/src/test/java/com/mailengine/mailengine/integration/PostgresIntegrationSupport.java index 9c3d7b1..f3616a0 100644 --- a/src/test/java/com/mailengine/mailengine/integration/PostgresIntegrationSupport.java +++ b/src/test/java/com/mailengine/mailengine/integration/PostgresIntegrationSupport.java @@ -55,7 +55,6 @@ static void properties(DynamicPropertyRegistry r) { r.add("aws.secret-access-key", () -> "test"); r.add("aws.from-email", () -> "noreply@example.test"); r.add("aws.s3.bucket", () -> "test-bucket"); - r.add("ipinfo.token", () -> "test"); r.add("app.base-url", () -> "http://localhost:8080"); // Tests run the worker and the dispatcher by hand; the schedulers would only race with them r.add("app.sending.delay-ms", () -> "3600000"); diff --git a/src/test/java/com/mailengine/mailengine/integration/SweepFixesIntegrationTest.java b/src/test/java/com/mailengine/mailengine/integration/SweepFixesIntegrationTest.java index d753368..dc72e42 100644 --- a/src/test/java/com/mailengine/mailengine/integration/SweepFixesIntegrationTest.java +++ b/src/test/java/com/mailengine/mailengine/integration/SweepFixesIntegrationTest.java @@ -86,6 +86,41 @@ void aListWithUploadsCanBeDeleted() throws Exception { assertThat(jdbc.queryForObject("select count(*) from pending_upload_files where upload_id = ?", Integer.class, upload)).isZero(); } + @Test + void clicksOnlyRedirectToLinksInThatEmail() throws Exception { + String token = java.util.UUID.randomUUID().toString(); + String sent = java.util.Base64.getUrlEncoder().withoutPadding() + .encodeToString("https://shop.example.test/sale".getBytes(StandardCharsets.UTF_8)); + String other = java.util.Base64.getUrlEncoder().withoutPadding() + .encodeToString("https://phish.example.test/login".getBytes(StandardCharsets.UTF_8)); + jdbc.update("insert into email_queue (to_email, html_content, subject_line, from_name, from_email, click_token, status) " + + "values ('c@example.test', ?, 'S', 'F', 'f@example.test', ?, 'sent')", + "Sale", token); + + mvc.perform(get("/track/click/{t}", token).param("t", sent)) + .andExpect(status().isFound()) + .andExpect(header().string("Location", "https://shop.example.test/sale")); + mvc.perform(get("/track/click/{t}", token).param("t", other)).andExpect(status().isNotFound()); + mvc.perform(get("/track/click/{t}", token)).andExpect(status().isNotFound()); + mvc.perform(get("/track/click/{t}", "no-such-token").param("t", other)).andExpect(status().isNotFound()); + assertThat(jdbc.queryForObject("select count(*) from tracking_events where link_url like 'https://phish%'", Integer.class)) + .as("no fake clicks recorded").isZero(); + } + + @Test + void analyticsAnswersAreCached() throws Exception { + long campaign = jdbc.queryForObject("insert into campaigns (name, subject_line, from_name, from_email, status, total_sent) " + + "values ('Cached', 'S', 'F', 'f@example.test', 'sent', 10) returning id", Long.class); + String first = mvc.perform(get("/api/analytics/campaigns/{id}/overview", campaign).with(authentication(ADMIN))) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + jdbc.update("insert into tracking_events (campaign_id, event_type) values (?, 'open')", campaign); + + mvc.perform(get("/api/analytics/campaigns/{id}/overview", campaign).with(authentication(ADMIN))) + .andExpect(status().isOk()) + .andExpect(content().json(first, org.springframework.test.json.JsonCompareMode.STRICT)); + } + @Test void testSendNeedsValidAddresses() throws Exception { for (String body : new String[]{"{}", "{\"testEmails\": []}", "{\"testEmails\": [\"not-an-email\"]}", diff --git a/src/test/java/com/mailengine/mailengine/security/AuthRateLimitFilterTest.java b/src/test/java/com/mailengine/mailengine/security/AuthRateLimitFilterTest.java new file mode 100644 index 0000000..b1abc5c --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/security/AuthRateLimitFilterTest.java @@ -0,0 +1,54 @@ +package com.mailengine.mailengine.security; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import static org.assertj.core.api.Assertions.assertThat; + +class AuthRateLimitFilterTest { + + private final AuthRateLimitFilter filter = new AuthRateLimitFilter(3, 2); + + private MockHttpServletResponse call(String method, String path, String ip) throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(method, path); + request.setRemoteAddr(ip); + MockHttpServletResponse response = new MockHttpServletResponse(); + filter.doFilter(request, response, new MockFilterChain()); + return response; + } + + @Test + void loginIsLimitedPerIp() throws Exception { + for (int i = 0; i < 3; i++) { + assertThat(call("POST", "/api/auth/login", "203.0.113.1").getStatus()).isEqualTo(200); + } + MockHttpServletResponse limited = call("POST", "/api/auth/login", "203.0.113.1"); + + assertThat(limited.getStatus()).isEqualTo(429); + assertThat(Long.parseLong(limited.getHeader("Retry-After"))).isBetween(1L, 60L); + assertThat(limited.getContentAsString()).contains("Too many requests"); + assertThat(call("POST", "/api/auth/login", "203.0.113.2").getStatus()).as("another client").isEqualTo(200); + } + + @Test + void accountEmailEndpointsShareAnHourlyAllowance() throws Exception { + assertThat(call("POST", "/api/auth/forgot-password", "198.51.100.7").getStatus()).isEqualTo(200); + assertThat(call("POST", "/api/auth/reset-password", "198.51.100.7").getStatus()).isEqualTo(200); + + assertThat(call("POST", "/api/auth/forgot-password/", "198.51.100.7").getStatus()).isEqualTo(429); + assertThat(call("GET", "/api/auth/verify-email", "198.51.100.7").getStatus()).isEqualTo(429); + assertThat(Long.parseLong(call("POST", "/api/auth/reset-password", "198.51.100.7").getHeader("Retry-After"))) + .isGreaterThan(60L); + } + + @Test + void otherRoutesAreNotLimited() throws Exception { + for (int i = 0; i < 10; i++) { + assertThat(call("GET", "/api/campaigns", "192.0.2.1").getStatus()).isEqualTo(200); + assertThat(call("POST", "/api/auth/change-password", "192.0.2.1").getStatus()).isEqualTo(200); + assertThat(call("GET", "/api/auth/login", "192.0.2.1").getStatus()).isEqualTo(200); + } + } +} diff --git a/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java b/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java index df33db0..d5d8b1b 100644 --- a/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java +++ b/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java @@ -47,6 +47,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -316,6 +317,17 @@ void knownEmailReplacesOldTokensAndMailsAOneHourToken() { .isNotEqualTo(emailed.getValue()); } + @Test + void resetEmailsToOneAddressAreLimitedWithoutChangingTheAnswer() { + when(userRepository.findByEmailIgnoreCase("editor@example.com")).thenReturn(Optional.of(user)); + + for (int i = 0; i < 5; i++) { + authService.forgotPassword(forgot("editor@example.com")); // no exception: same answer every time + } + + verify(emailService, times(3)).sendPasswordResetEmail(eq("editor@example.com"), anyString()); + } + @Test void validTokenResetsPasswordOnceAndClearsForcedChange() { user.setMustChangePwd(true); diff --git a/src/test/java/com/mailengine/mailengine/service/GeoIpServiceTest.java b/src/test/java/com/mailengine/mailengine/service/GeoIpServiceTest.java new file mode 100644 index 0000000..9cce28a --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/service/GeoIpServiceTest.java @@ -0,0 +1,70 @@ +package com.mailengine.mailengine.service; + +import com.maxmind.db.Metadata; +import com.maxmind.geoip2.DatabaseReader; +import com.maxmind.geoip2.model.CityResponse; +import com.maxmind.geoip2.model.CountryResponse; +import org.junit.jupiter.api.Test; + +import java.net.InetAddress; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +/** GeoIpService on a MaxMind database (the reader is mocked: GeoLite2 files need a MaxMind licence key). */ +class GeoIpServiceTest { + + private static DatabaseReader reader(String type) { + DatabaseReader reader = mock(DatabaseReader.class); + Metadata metadata = mock(Metadata.class); + when(metadata.getDatabaseType()).thenReturn(type); + when(reader.getMetadata()).thenReturn(metadata); + return reader; + } + + @Test + void cityDatabaseGivesCountryAndCity() throws Exception { + DatabaseReader reader = reader("GeoLite2-City"); + CityResponse city = mock(CityResponse.class, RETURNS_DEEP_STUBS); + when(city.getCountry().getIsoCode()).thenReturn("NG"); + when(city.getCity().getName()).thenReturn("Lagos"); + when(reader.tryCity(InetAddress.getByName("102.89.1.1"))).thenReturn(Optional.of(city)); + + assertThat(new GeoIpService(reader).lookup("102.89.1.1")).isEqualTo(new GeoIpService.Location("NG", "Lagos")); + } + + @Test + void countryDatabaseGivesTheCountryOnly() throws Exception { + DatabaseReader reader = reader("GeoLite2-Country"); + CountryResponse country = mock(CountryResponse.class, RETURNS_DEEP_STUBS); + when(country.getCountry().getIsoCode()).thenReturn("GH"); + when(reader.tryCountry(any())).thenReturn(Optional.of(country)); + + assertThat(new GeoIpService(reader).lookup("41.66.1.1")).isEqualTo(new GeoIpService.Location("GH", null)); + verify(reader, never()).tryCity(any()); + } + + @Test + void privateAndInvalidAddressesAreNotLookedUp() throws Exception { + DatabaseReader reader = reader("GeoLite2-City"); + GeoIpService geo = new GeoIpService(reader); + + for (String ip : new String[]{"127.0.0.1", "10.1.2.3", "192.168.0.9", "::1", "fe80::1", "example.com", "", null}) { + assertThat(geo.lookup(ip)).as(String.valueOf(ip)).isNull(); + } + verify(reader, never()).tryCity(any()); // and no DNS lookup for a host name + } + + @Test + void unknownAddressesAndReaderErrorsGiveNothing() throws Exception { + DatabaseReader reader = reader("GeoLite2-City"); + when(reader.tryCity(InetAddress.getByName("8.8.8.8"))).thenReturn(Optional.empty()); + when(reader.tryCity(InetAddress.getByName("8.8.4.4"))).thenThrow(new java.io.IOException("corrupt")); + GeoIpService geo = new GeoIpService(reader); + + assertThat(geo.lookup("8.8.8.8")).isNull(); + assertThat(geo.lookup("8.8.4.4")).isNull(); + } +} diff --git a/src/test/java/com/mailengine/mailengine/worker/EmailSenderWorkerTest.java b/src/test/java/com/mailengine/mailengine/worker/EmailSenderWorkerTest.java index 5feaad0..c9e3420 100644 --- a/src/test/java/com/mailengine/mailengine/worker/EmailSenderWorkerTest.java +++ b/src/test/java/com/mailengine/mailengine/worker/EmailSenderWorkerTest.java @@ -45,6 +45,38 @@ void emptyQueueDoesNothing() { verify(store, never()).recordProgress(anyLong(), anyInt(), anyInt()); } + @Test + void sendingIsCappedAtTheConfiguredRate() { + worker.setRatePerSecond(4); + when(store.claimBatch(20)).thenReturn(batch(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)); + when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn("id"); + + long start = System.nanoTime(); + worker.processEmailBatch(); + long millis = (System.nanoTime() - start) / 1_000_000; + + // 4 go straight away, the other 4 at 4 per second + assertThat(millis).isGreaterThanOrEqualTo(800); + verify(store).recordProgress(1L, 8, 0); + } + + @Test + void anInterruptedWorkerHandsTheRestOfTheBatchBack() { + worker.setRatePerSecond(1); + when(store.claimBatch(20)).thenReturn(batch(1L, 1L, 1L)); + when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString())).thenAnswer(i -> { + Thread.currentThread().interrupt(); // the app is stopping + return "id"; + }); + + worker.processEmailBatch(); + Thread.interrupted(); // clear the flag for the next test + + verify(sender, times(1)).send(anyString(), anyString(), anyString(), anyString(), anyString()); + verify(store).release(2L); + verify(store).release(3L); + } + @Test void resultsAreCountedPerCampaign() { when(store.claimBatch(20)).thenReturn(batch(1L, 1L, 2L, 2L, 2L));