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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.Map;

/**
Expand Down Expand Up @@ -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
* <p>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<String, String> changePassword(@Valid @RequestBody ChangePasswordRequest request) {
authService.changePassword(request);
return Map.of("message", "Password changed");
public Map<String, Object> 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<String, Object> 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;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -25,6 +29,7 @@
* SNS then HTTP-POSTs those events to this endpoint. We:
* <ol>
* <li>Verify the SNS message signature to prevent spoofing.</li>
* <li>Accept only the topics in {@code SES_SNS_TOPIC_ARNS}, when it is set.</li>
* <li>Handle subscription confirmation (first-time setup).</li>
* <li>Process notifications by creating {@link TrackingEvent} rows.</li>
* </ol>
Expand All @@ -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<String> 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<String> allowedTopics() {
return allowedTopicArns == null ? List.of()
: allowedTopicArns.stream().map(String::trim).filter(arn -> !arn.isEmpty()).toList();
}

/**
* Receives and processes an SNS notification from AWS.
*
Expand Down Expand Up @@ -93,6 +120,13 @@ public ResponseEntity<String> handleSesWebhook(HttpServletRequest request) {
JsonNode root = objectMapper.readTree(body);
String type = root.path("Type").asText();

List<String> 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();
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/com/mailengine/mailengine/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions src/main/java/com/mailengine/mailengine/security/JwtService.java
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -29,13 +30,38 @@
* <li>{@code sub} — user ID (String, used as the JWT subject)</li>
* <li>{@code role} — user's role name (e.g. "admin")</li>
* <li>{@code email} — user's email address</li>
* <li>{@code ver} — the user's token version; changing the password raises it, which revokes the token</li>
* <li>{@code iat} — issued-at timestamp</li>
* <li>{@code exp} — expiry timestamp</li>
* </ul>
*/
@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.
*
* <p>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;
Expand All @@ -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
Expand Down
15 changes: 14 additions & 1 deletion src/main/java/com/mailengine/mailengine/service/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down
35 changes: 13 additions & 22 deletions src/main/java/com/mailengine/mailengine/service/S3Service.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand All @@ -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);
Expand All @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Loading
Loading