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
18 changes: 15 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
133 changes: 93 additions & 40 deletions README.md

Large diffs are not rendered by default.

8 changes: 5 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
37 changes: 37 additions & 0 deletions src/main/java/com/mailengine/mailengine/config/CacheConfig.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
* <p>POST /api/auth/register
*
* <p>Flow:
* <ol>
* <li>Creates an {@code Account} (company) and a {@code User} with role ADMIN.</li>
* <li>Sends a verification email with a 24-hour token.</li>
* <li>User must click the link before they can log in.</li>
* </ol>
*
* @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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public ResponseEntity<byte[]> 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<Void> trackClick(
Expand All @@ -92,10 +92,8 @@ public ResponseEntity<Void> 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
Expand Down
Original file line number Diff line number Diff line change
@@ -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:
* <ul>
* <li>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.</li>
* <li>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.</li>
* </ul>
* 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;
};
}
}
38 changes: 38 additions & 0 deletions src/main/java/com/mailengine/mailengine/security/RateLimiter.java
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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<String, Bucket> 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);
}
}
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
Expand All @@ -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"));
Expand Down Expand Up @@ -101,6 +104,7 @@ public CampaignAnalyticsOverview getCampaignOverview(Long campaignId) {
/**
* Returns opens, clicks, and unsubscribes grouped by hour.
*/
@Cacheable(CacheConfig.TIMELINE)
public List<TimelineDataPoint> getTimeline(Long campaignId) {
String sql = """
SELECT
Expand Down Expand Up @@ -153,6 +157,7 @@ private static Instant utcInstant(Object value) {
/**
* Returns click counts per unique link.
*/
@Cacheable(CacheConfig.LINKS)
public List<LinkPerformance> getLinkPerformance(Long campaignId) {
Campaign campaign = campaignRepository.findById(campaignId)
.orElseThrow(() -> new ResourceNotFoundException("Campaign not found"));
Expand Down Expand Up @@ -197,6 +202,7 @@ public List<LinkPerformance> getLinkPerformance(Long campaignId) {
/**
* Returns the distribution of opens and clicks by device type.
*/
@Cacheable(CacheConfig.DEVICES)
public List<DeviceBreakdown> getDeviceBreakdown(Long campaignId) {
String sql = """
SELECT
Expand Down Expand Up @@ -241,6 +247,7 @@ public List<DeviceBreakdown> getDeviceBreakdown(Long campaignId) {
/**
* Returns opens and clicks aggregated by country and city.
*/
@Cacheable(CacheConfig.GEOGRAPHY)
public List<GeographyDataPoint> getGeographyData(Long campaignId) {
String sql = """
SELECT
Expand Down
12 changes: 12 additions & 0 deletions src/main/java/com/mailengine/mailengine/service/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -26,6 +29,7 @@
@Service
@RequiredArgsConstructor
@Transactional
@Slf4j
public class AuthService {

private static final int MAX_FAILED_ATTEMPTS = 5;
Expand All @@ -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.");
}
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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)
Expand All @@ -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<EngagementScoreResponse> getScores() {
return engagementScoreRepository.findAll().stream()
.map(s -> new EngagementScoreResponse(
Expand Down
Loading
Loading