diff --git a/README.md b/README.md
index b714fb0..6344fcc 100644
--- a/README.md
+++ b/README.md
@@ -297,6 +297,7 @@ All optional. Without them the app starts, SES is skipped, and image uploads ret
| `AWS_ACCESS_KEY_ID` | `AKIA…` | IAM access key. Leave both keys unset to use the AWS SDK's default credentials chain (for example an IAM role) |
| `AWS_SECRET_ACCESS_KEY` | `…` | IAM secret key |
| `AWS_S3_BUCKET` | `mailengine-assets` | S3 bucket for template images and uploads |
+| `SES_SNS_TOPIC_ARNS` | `arn:aws:sns:eu-north-1:123456789012:ses-events` | Comma-separated SNS topics allowed to post to `/webhooks/ses`. Set it: unset, any SNS topic is accepted (a warning is logged at startup) |
### Optional
@@ -703,9 +704,11 @@ Setup (one-time in AWS console):
1. Create an SNS topic
2. Add an HTTP subscription pointing to `{APP_BASE_URL}/webhooks/ses`
3. Set the SNS topic as the SES notification destination for Bounces and Complaints
+4. Set `SES_SNS_TOPIC_ARNS` to the topic's ARN
On each webhook:
- The controller verifies the AWS SNS signature to prevent spoofing
+- Messages from a topic not in `SES_SNS_TOPIC_ARNS` get 403: a valid signature proves only that the message came from SNS, not from your topic
- Events are correlated to the right campaign + recipient via `email_queue.message_id` (the SES message ID stored when each email is sent)
- **Bounce** → `recipient.status = BOUNCED`, add to `suppression_list`
- **Complaint** → `recipient.status = COMPLAINED`, add to `suppression_list`
diff --git a/src/main/java/com/mailengine/mailengine/controller/AuthController.java b/src/main/java/com/mailengine/mailengine/controller/AuthController.java
index ada77a1..c6213a1 100644
--- a/src/main/java/com/mailengine/mailengine/controller/AuthController.java
+++ b/src/main/java/com/mailengine/mailengine/controller/AuthController.java
@@ -10,6 +10,7 @@
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
+import java.util.LinkedHashMap;
import java.util.Map;
/**
@@ -114,12 +115,22 @@ public AuthResponse login(@Valid @RequestBody LoginRequest request) {
* prevent account takeover if an attacker already has a session.
*
* @param request current password and desired new password
- * @return success message
+ *
Signs the user out everywhere (all earlier tokens stop working) and returns a new token,
+ * with the same fields as login, next to the message.
+ *
+ * @return success message and the new token
*/
@PostMapping("/change-password")
- public Map changePassword(@Valid @RequestBody ChangePasswordRequest request) {
- authService.changePassword(request);
- return Map.of("message", "Password changed");
+ public Map changePassword(@Valid @RequestBody ChangePasswordRequest request) {
+ AuthResponse fresh = authService.changePassword(request);
+ // Every earlier token, this request's included, stops working: the client must keep the new one
+ Map body = new LinkedHashMap<>();
+ body.put("message", "Password changed");
+ body.put("token", fresh.token());
+ body.put("user", fresh.user());
+ body.put("expiresIn", fresh.expiresIn());
+ body.put("mustChangePassword", fresh.mustChangePassword());
+ return body;
}
/**
diff --git a/src/main/java/com/mailengine/mailengine/controller/SesWebhookController.java b/src/main/java/com/mailengine/mailengine/controller/SesWebhookController.java
index eadce8d..2534678 100644
--- a/src/main/java/com/mailengine/mailengine/controller/SesWebhookController.java
+++ b/src/main/java/com/mailengine/mailengine/controller/SesWebhookController.java
@@ -11,7 +11,11 @@
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
+import jakarta.annotation.PostConstruct;
+import org.springframework.beans.factory.annotation.Value;
+
import java.io.BufferedReader;
+import java.util.List;
/**
* Receives AWS SNS webhook notifications about SES email events.
@@ -25,6 +29,7 @@
* SNS then HTTP-POSTs those events to this endpoint. We:
*
*
Verify the SNS message signature to prevent spoofing.
+ *
Accept only the topics in {@code SES_SNS_TOPIC_ARNS}, when it is set.
Process notifications by creating {@link TrackingEvent} rows.
*
@@ -50,6 +55,28 @@ public class SesWebhookController {
private final ObjectMapper objectMapper;
private final SesEventService sesEventService;
+ /**
+ * The SNS topics allowed to post here ({@code SES_SNS_TOPIC_ARNS}, comma-separated). A valid signature only
+ * proves a message came from SNS: from any AWS account's topic. Without this list, someone could subscribe
+ * this endpoint to a topic of their own and post forged bounces that suppress any address. Empty: any topic
+ * is accepted (with a warning at startup), as before the setting existed.
+ */
+ @Value("${app.ses.sns-topic-arns:}")
+ private List allowedTopicArns = List.of();
+
+ @PostConstruct
+ void warnIfAnyTopicIsAccepted() {
+ if (allowedTopics().isEmpty()) {
+ log.warn("SES_SNS_TOPIC_ARNS is not set: /webhooks/ses accepts messages from any SNS topic. "
+ + "Set it to your SES notification topic ARN(s).");
+ }
+ }
+
+ private List allowedTopics() {
+ return allowedTopicArns == null ? List.of()
+ : allowedTopicArns.stream().map(String::trim).filter(arn -> !arn.isEmpty()).toList();
+ }
+
/**
* Receives and processes an SNS notification from AWS.
*
@@ -93,6 +120,13 @@ public ResponseEntity handleSesWebhook(HttpServletRequest request) {
JsonNode root = objectMapper.readTree(body);
String type = root.path("Type").asText();
+ List allowed = allowedTopics();
+ String topicArn = root.path("TopicArn").asText();
+ if (!allowed.isEmpty() && !allowed.contains(topicArn)) {
+ log.warn("Rejected SNS message from unknown topic {}", topicArn);
+ return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Unknown topic");
+ }
+
if ("SubscriptionConfirmation".equals(type)) {
// Log the URL; in production you would programmatically visit it
String subscribeUrl = root.path("SubscribeURL").asText();
diff --git a/src/main/java/com/mailengine/mailengine/entity/User.java b/src/main/java/com/mailengine/mailengine/entity/User.java
index 6b76103..ca54f3b 100644
--- a/src/main/java/com/mailengine/mailengine/entity/User.java
+++ b/src/main/java/com/mailengine/mailengine/entity/User.java
@@ -65,6 +65,16 @@ public class User implements UserDetails {
@Column(name = "locked_until")
private Instant lockedUntil;
+ /** Raised on every password change; tokens issued with an older version are refused (see JwtAuthFilter). */
+ @ColumnDefault("0")
+ @Column(name = "token_version", nullable = false)
+ private Integer tokenVersion = 0;
+
+ /** Signs the user out everywhere: every token issued so far stops working. */
+ public void revokeTokens() {
+ tokenVersion = (tokenVersion == null ? 0 : tokenVersion) + 1;
+ }
+
@CreatedDate
@Column(name = "created_at", updatable = false)
private Instant createdAt;
diff --git a/src/main/java/com/mailengine/mailengine/security/JwtAuthFilter.java b/src/main/java/com/mailengine/mailengine/security/JwtAuthFilter.java
index e238b9a..04e4a25 100644
--- a/src/main/java/com/mailengine/mailengine/security/JwtAuthFilter.java
+++ b/src/main/java/com/mailengine/mailengine/security/JwtAuthFilter.java
@@ -51,15 +51,17 @@ protected void doFilterInternal(
final String jwt = authHeader.substring(7);
try {
- if (!jwtService.isTokenValid(jwt)) {
+ JwtService.TokenClaims claims = jwtService.parse(jwt); // throws if invalid or expired
+ User user = userRepository.findById(claims.userId())
+ .orElseThrow(() -> new RuntimeException("User not found"));
+
+ // The password changed since this token was issued: it was revoked
+ int currentVersion = user.getTokenVersion() == null ? 0 : user.getTokenVersion();
+ if (claims.tokenVersion() != currentVersion) {
sendUnauthorized(response, "Invalid or expired token");
return;
}
- String userId = jwtService.extractUserId(jwt);
- User user = userRepository.findById(Long.parseLong(userId))
- .orElseThrow(() -> new RuntimeException("User not found"));
-
// Enforce mustChangePwd — only allow change-password endpoint
if (Boolean.TRUE.equals(user.getMustChangePwd())) {
// Path within the application = URI minus context path, so the check holds
diff --git a/src/main/java/com/mailengine/mailengine/security/JwtService.java b/src/main/java/com/mailengine/mailengine/security/JwtService.java
index 162daec..a593089 100644
--- a/src/main/java/com/mailengine/mailengine/security/JwtService.java
+++ b/src/main/java/com/mailengine/mailengine/security/JwtService.java
@@ -1,6 +1,7 @@
package com.mailengine.mailengine.security;
import com.mailengine.mailengine.entity.User;
+import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
@@ -29,6 +30,7 @@
*
{@code sub} — user ID (String, used as the JWT subject)
*
{@code role} — user's role name (e.g. "admin")
*
{@code email} — user's email address
+ *
{@code ver} — the user's token version; changing the password raises it, which revokes the token
*
{@code iat} — issued-at timestamp
*
{@code exp} — expiry timestamp
*
@@ -36,6 +38,30 @@
@Service
public class JwtService {
+ /** The user's token version when the token was issued; see {@link User#revokeTokens()}. */
+ static final String VERSION_CLAIM = "ver";
+
+ /** Who a verified token belongs to, and the token version it was issued with. */
+ public record TokenClaims(Long userId, int tokenVersion) {
+ }
+
+ /**
+ * Verifies the token (signature and expiry) and reads its claims in one parse.
+ *
+ *
A token without a version, issued before versions existed, counts as version 0.
+ *
+ * @throws JwtException if the token is invalid or expired
+ */
+ public TokenClaims parse(String token) {
+ Claims claims = Jwts.parser()
+ .verifyWith(getSigningKey())
+ .build()
+ .parseSignedClaims(token)
+ .getPayload();
+ Integer version = claims.get(VERSION_CLAIM, Integer.class);
+ return new TokenClaims(Long.parseLong(claims.getSubject()), version == null ? 0 : version);
+ }
+
/** Base64-encoded HMAC-SHA256 signing key — sourced from {@code JWT_SECRET} env var. */
@Value("${jwt.secret}")
private String secretKey;
@@ -58,6 +84,7 @@ public String generateToken(User user) {
.subject(user.getId().toString()) // Who this token belongs to
.claim("rid", user.getRole().ordinal()) // Embedded role for future role-based access
.claim("email", user.getEmail()) // Convenience claim for the frontend
+ .claim(VERSION_CLAIM, user.getTokenVersion() == null ? 0 : user.getTokenVersion())
.issuedAt(new Date()) // When it was created
.expiration(new Date(System.currentTimeMillis() + expirationMs)) // When it expires
.signWith(getSigningKey()) // Sign with HMAC-SHA256
diff --git a/src/main/java/com/mailengine/mailengine/service/AuthService.java b/src/main/java/com/mailengine/mailengine/service/AuthService.java
index b5f71fd..28b174a 100644
--- a/src/main/java/com/mailengine/mailengine/service/AuthService.java
+++ b/src/main/java/com/mailengine/mailengine/service/AuthService.java
@@ -120,7 +120,11 @@ public AuthResponse login(LoginRequest request) {
);
}
- public void changePassword(ChangePasswordRequest request) {
+ /**
+ * Changes the password and signs the user out everywhere, then returns a fresh token for this session,
+ * so whoever made the change stays logged in.
+ */
+ public AuthResponse changePassword(ChangePasswordRequest request) {
User user = SecurityUtils.currentUser();
if (!passwordEncoder.matches(request.getCurrentPassword(), user.getPasswordHash())) {
throw new BadRequestException("Current password is incorrect");
@@ -130,7 +134,15 @@ public void changePassword(ChangePasswordRequest request) {
}
user.setPasswordHash(passwordEncoder.encode(request.getNewPassword()));
user.setMustChangePwd(false);
+ user.revokeTokens();
userRepository.save(user);
+
+ return new AuthResponse(
+ jwtService.generateToken(user),
+ new AuthResponse.UserDto(user.getId(), user.getName(), user.getEmail(), user.getRole()),
+ jwtService.getExpirationTime(),
+ false
+ );
}
public void forgotPassword(ForgotPasswordRequest request) {
@@ -158,6 +170,7 @@ public void resetPassword(ResetPasswordRequest request) {
User user = prt.getUser();
user.setPasswordHash(passwordEncoder.encode(request.getNewPassword()));
user.setMustChangePwd(false);
+ user.revokeTokens(); // a reset is often because of a suspected compromise: end every session
userRepository.save(user);
prt.setUsed(true);
passwordResetTokenRepository.save(prt);
diff --git a/src/main/java/com/mailengine/mailengine/service/S3Service.java b/src/main/java/com/mailengine/mailengine/service/S3Service.java
index 8d3da89..6021b87 100644
--- a/src/main/java/com/mailengine/mailengine/service/S3Service.java
+++ b/src/main/java/com/mailengine/mailengine/service/S3Service.java
@@ -5,14 +5,12 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
-import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
-import java.io.IOException;
import java.util.UUID;
/**
@@ -33,33 +31,34 @@ public class S3Service {
private String region;
/**
- * Uploads a file to S3 and returns the public URL.
+ * Stores bytes in S3 under a random name and returns the public URL.
*
- * @param file the file to upload
- * @param folder the folder path within the bucket (e.g., "templates/images")
- * @return the public URL of the uploaded file
+ * @param contentType served as the object's Content-Type; the caller decides it, never the uploading client
+ * @param extension the file extension for the key, e.g. ".png"
+ * @param folder the folder path within the bucket (e.g., "templates/images")
*/
- public String uploadFile(MultipartFile file, String folder) {
+ /** @throws NotConfiguredException (503) if no bucket is set, so callers can say so before doing any work */
+ public void requireConfigured() {
if (bucketName == null || bucketName.isBlank()) {
throw new NotConfiguredException("File uploads are not configured on this server (AWS_S3_BUCKET is not set)");
}
- String fileName = generateFileName(file.getOriginalFilename());
- String key = folder + "/" + fileName;
+ }
+ public String uploadBytes(byte[] data, String contentType, String extension, String folder) {
+ requireConfigured();
+ String key = folder + "/" + UUID.randomUUID() + extension;
try {
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(key)
- .contentType(file.getContentType())
+ .contentType(contentType)
+ .contentDisposition("inline")
.build();
- s3Client.putObject(putObjectRequest, RequestBody.fromBytes(file.getBytes()));
+ s3Client.putObject(putObjectRequest, RequestBody.fromBytes(data));
log.info("File uploaded to S3: {}", key);
return getPublicUrl(key);
- } catch (IOException e) {
- log.error("Failed to read file bytes", e);
- throw new RuntimeException("Failed to upload file to S3", e);
} catch (S3Exception e) {
log.error("S3 upload failed", e);
throw new RuntimeException("S3 upload failed: " + e.awsErrorDetails().errorMessage(), e);
@@ -82,14 +81,6 @@ public void deleteFile(String fileUrl) {
log.info("File deleted from S3: {}", key);
}
- private String generateFileName(String originalFilename) {
- String extension = "";
- if (originalFilename != null && originalFilename.contains(".")) {
- extension = originalFilename.substring(originalFilename.lastIndexOf("."));
- }
- return UUID.randomUUID() + extension;
- }
-
private String getPublicUrl(String key) {
return String.format("https://%s.s3.%s.amazonaws.com/%s", bucketName, region, key);
}
diff --git a/src/main/java/com/mailengine/mailengine/service/TemplateService.java b/src/main/java/com/mailengine/mailengine/service/TemplateService.java
index ff9b6d6..38f819b 100644
--- a/src/main/java/com/mailengine/mailengine/service/TemplateService.java
+++ b/src/main/java/com/mailengine/mailengine/service/TemplateService.java
@@ -17,6 +17,9 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
+import com.mailengine.mailengine.util.ImageTypes;
+
+import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
@@ -32,9 +35,22 @@ public class TemplateService {
private final CampaignRepository campaignRepository;
private final S3Service s3Service;
+ /**
+ * Stores a template image in the public bucket. Only PNG, JPEG, GIF and WebP are accepted, recognised from the
+ * file's content; the stored name and content type come from that, never from what the client sent.
+ */
public String uploadImage(MultipartFile file) {
- log.info("Uploading image to S3: {}", file.getOriginalFilename());
- return s3Service.uploadFile(file, "templates/images");
+ s3Service.requireConfigured(); // "not configured" (503) beats "not an image" (400)
+ byte[] data;
+ try {
+ data = file.getBytes();
+ } catch (IOException e) {
+ throw new BadRequestException("The file could not be read");
+ }
+ ImageTypes.ImageType type = ImageTypes.detect(data)
+ .orElseThrow(() -> new BadRequestException("Only PNG, JPEG, GIF or WebP images can be uploaded"));
+ log.info("Uploading {} image to S3 ({} bytes)", type, data.length);
+ return s3Service.uploadBytes(data, type.contentType(), type.extension(), "templates/images");
}
@Transactional(readOnly = true)
diff --git a/src/main/java/com/mailengine/mailengine/service/UserService.java b/src/main/java/com/mailengine/mailengine/service/UserService.java
index 21a4fa1..cfbca2d 100644
--- a/src/main/java/com/mailengine/mailengine/service/UserService.java
+++ b/src/main/java/com/mailengine/mailengine/service/UserService.java
@@ -88,6 +88,7 @@ public void adminResetPassword(Long id) {
String tempPassword = "Tmp-" + UUID.randomUUID().toString().substring(0, 8);
target.setPasswordHash(passwordEncoder.encode(tempPassword));
target.setMustChangePwd(true);
+ target.revokeTokens(); // the user's sessions end at once
userRepository.save(target);
emailService.sendAdminPasswordResetEmail(target.getEmail(), tempPassword);
}
diff --git a/src/main/java/com/mailengine/mailengine/util/ImageTypes.java b/src/main/java/com/mailengine/mailengine/util/ImageTypes.java
new file mode 100644
index 0000000..0204b0a
--- /dev/null
+++ b/src/main/java/com/mailengine/mailengine/util/ImageTypes.java
@@ -0,0 +1,62 @@
+package com.mailengine.mailengine.util;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Optional;
+
+/**
+ * Recognises the image formats template images may be uploaded in, from the file's own first bytes.
+ *
+ *