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: *

    *
  1. Verify the SNS message signature to prevent spoofing.
  2. + *
  3. Accept only the topics in {@code SES_SNS_TOPIC_ARNS}, when it is set.
  4. *
  5. Handle subscription confirmation (first-time setup).
  6. *
  7. Process notifications by creating {@link TrackingEvent} rows.
  8. *
@@ -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. + * + *

    The name and content type the client sends are never trusted: uploads land in a public bucket, and a file + * labelled "image/png" could be an HTML page. SVG is deliberately not accepted, because it can carry script. + */ +public final class ImageTypes { + + public enum ImageType { + PNG("image/png", ".png"), + JPEG("image/jpeg", ".jpg"), + GIF("image/gif", ".gif"), + WEBP("image/webp", ".webp"); + + private final String contentType; + private final String extension; + + ImageType(String contentType, String extension) { + this.contentType = contentType; + this.extension = extension; + } + + public String contentType() { + return contentType; + } + + public String extension() { + return extension; + } + } + + private static final byte[] PNG = {(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A}; + private static final byte[] JPEG = {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF}; + private static final byte[] GIF87 = "GIF87a".getBytes(StandardCharsets.US_ASCII); + private static final byte[] GIF89 = "GIF89a".getBytes(StandardCharsets.US_ASCII); + private static final byte[] RIFF = "RIFF".getBytes(StandardCharsets.US_ASCII); + private static final byte[] WEBP = "WEBP".getBytes(StandardCharsets.US_ASCII); + + private ImageTypes() { + } + + /** @return the image type the bytes start with, or empty if they are not a supported image */ + public static Optional detect(byte[] data) { + if (data == null) return Optional.empty(); + if (startsWith(data, 0, PNG)) return Optional.of(ImageType.PNG); + if (startsWith(data, 0, JPEG)) return Optional.of(ImageType.JPEG); + if (startsWith(data, 0, GIF87) || startsWith(data, 0, GIF89)) return Optional.of(ImageType.GIF); + if (startsWith(data, 0, RIFF) && startsWith(data, 8, WEBP)) return Optional.of(ImageType.WEBP); + return Optional.empty(); + } + + private static boolean startsWith(byte[] data, int offset, byte[] prefix) { + return data.length >= offset + prefix.length + && Arrays.equals(data, offset, offset + prefix.length, prefix, 0, prefix.length); + } +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index f24696e..aeefc02 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -73,6 +73,10 @@ app: cors: # Comma-separated origins allowed to call the API from a browser, e.g. https://app.example.com allowed-origins: ${CORS_ALLOWED_ORIGINS:*} + ses: + # Comma-separated ARNs of the SNS topics allowed to post SES events to /webhooks/ses. + # Empty: any topic is accepted (a warning is logged at startup). + sns-topic-arns: ${SES_SNS_TOPIC_ARNS:} aws: region: ${AWS_REGION:us-east-1} diff --git a/src/main/resources/db/migration/V3__user_token_version.sql b/src/main/resources/db/migration/V3__user_token_version.sql new file mode 100644 index 0000000..9490b4c --- /dev/null +++ b/src/main/resources/db/migration/V3__user_token_version.sql @@ -0,0 +1,4 @@ +-- Bumped whenever a user's password changes (change, forgot/reset, admin reset). Every JWT carries the version it +-- was issued with in its "ver" claim, and a token behind the user's current version is refused: changing a password +-- signs that user out everywhere. +ALTER TABLE users ADD COLUMN token_version INTEGER NOT NULL DEFAULT 0; diff --git a/src/test/java/com/mailengine/mailengine/controller/SesWebhookControllerTest.java b/src/test/java/com/mailengine/mailengine/controller/SesWebhookControllerTest.java new file mode 100644 index 0000000..b0be389 --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/controller/SesWebhookControllerTest.java @@ -0,0 +1,80 @@ +package com.mailengine.mailengine.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mailengine.mailengine.service.SesEventService; +import com.mailengine.mailengine.util.SnsMessageVerifier; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; + +/** A valid SNS signature only proves the message came from SNS: the topic must be ours as well. */ +@ExtendWith(MockitoExtension.class) +class SesWebhookControllerTest { + + static final String OURS = "arn:aws:sns:eu-north-1:111111111111:ses-events"; + static final String THEIRS = "arn:aws:sns:eu-north-1:999999999999:attacker"; + + @Mock SnsMessageVerifier verifier; + @Mock SesEventService sesEventService; + final ObjectMapper objectMapper = new ObjectMapper(); + SesWebhookController controller; + MockMvc mvc; + + @BeforeEach + void setUp() { + controller = new SesWebhookController(verifier, objectMapper, sesEventService); + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + when(verifier.verifySignature(anyString())).thenReturn(true); + } + + @Test + void notificationFromAnAllowedTopicIsHandled() throws Exception { + allow(" " + OURS + " ", ""); // trimmed, blanks ignored + + assertThat(postFrom(OURS)).isEqualTo(200); + verify(sesEventService).handle(any()); + } + + @Test + void notificationFromAnyOtherTopicIsRefused() throws Exception { + allow(OURS); + + assertThat(postFrom(THEIRS)).isEqualTo(403); + verifyNoInteractions(sesEventService); + } + + @Test + void withNoTopicsConfiguredEveryTopicIsAcceptedAsBefore() throws Exception { + allow(); + + assertThat(postFrom(THEIRS)).isEqualTo(200); + verify(sesEventService).handle(any()); + } + + private void allow(String... arns) { + ReflectionTestUtils.setField(controller, "allowedTopicArns", List.of(arns)); + } + + private int postFrom(String topicArn) throws Exception { + String message = objectMapper.writeValueAsString(Map.of("notificationType", "Delivery")); + String body = objectMapper.writeValueAsString(Map.of( + "Type", "Notification", "TopicArn", topicArn, "Message", message)); + return mvc.perform(post("/webhooks/ses").contentType(MediaType.TEXT_PLAIN).content(body)) + .andReturn().getResponse().getStatus(); + } +} diff --git a/src/test/java/com/mailengine/mailengine/integration/AuthIntegrationTest.java b/src/test/java/com/mailengine/mailengine/integration/AuthIntegrationTest.java index 7128667..f4dc5bf 100644 --- a/src/test/java/com/mailengine/mailengine/integration/AuthIntegrationTest.java +++ b/src/test/java/com/mailengine/mailengine/integration/AuthIntegrationTest.java @@ -1,5 +1,7 @@ package com.mailengine.mailengine.integration; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mailengine.mailengine.security.TokenHashing; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; @@ -10,6 +12,7 @@ import java.sql.Timestamp; import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -20,6 +23,7 @@ class AuthIntegrationTest extends PostgresIntegrationSupport { @Autowired MockMvc mvc; @Autowired JdbcTemplate jdbc; @Autowired PasswordEncoder passwordEncoder; + @Autowired ObjectMapper objectMapper; private String loginBody(String email, String password) { return "{\"email\":\"" + email + "\",\"password\":\"" + password + "\"}"; @@ -57,4 +61,61 @@ void wrongPasswordsAreCountedAndTheFifthLocksTheAccount() throws Exception { .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$.message").value("Account locked, try again later")); } + + // ── Changing a password signs the user out everywhere ─────────────────── + + @Test + void changingThePasswordRevokesEveryEarlierTokenAndReturnsAWorkingOne() throws Exception { + String email = editor("change"); + String laptop = login(email, "Right-pass-1"); + String phone = login(email, "Right-pass-1"); + + String body = mvc.perform(post("/api/auth/change-password").header("Authorization", "Bearer " + laptop) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"currentPassword\":\"Right-pass-1\",\"newPassword\":\"New-pass-22\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("Password changed")) + .andReturn().getResponse().getContentAsString(); + String fresh = objectMapper.readTree(body).get("token").asText(); + + assertThat(statusWith(laptop)).as("the token used for the change").isEqualTo(401); + assertThat(statusWith(phone)).as("another session").isEqualTo(401); + assertThat(statusWith(fresh)).as("the token returned by the change").isEqualTo(200); + } + + @Test + void resettingThePasswordRevokesEveryEarlierToken() throws Exception { + String email = editor("reset"); + String session = login(email, "Right-pass-1"); + Long userId = jdbc.queryForObject("SELECT id FROM users WHERE email = ?", Long.class, email); + jdbc.update("INSERT INTO password_reset_tokens (token, user_id, expires_at) VALUES (?, ?, NOW() + INTERVAL '1 hour')", + TokenHashing.sha256Hex("reset-tok-" + email), userId); + + mvc.perform(post("/api/auth/reset-password").contentType(MediaType.APPLICATION_JSON) + .content("{\"token\":\"reset-tok-" + email + "\",\"newPassword\":\"New-pass-22\"}")) + .andExpect(status().isOk()); + + assertThat(statusWith(session)).isEqualTo(401); + assertThat(statusWith(login(email, "New-pass-22"))).isEqualTo(200); + } + + private String editor(String tag) { + String email = tag + "-" + System.nanoTime() + "@example.test"; + jdbc.update("INSERT INTO users (name, email, password_hash, role, email_verified, must_change_pwd) " + + "VALUES ('Ed', ?, ?, 'editor', true, false)", email, passwordEncoder.encode("Right-pass-1")); + return email; + } + + private String login(String email, String password) throws Exception { + String body = mvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON) + .content(loginBody(email, password))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + return objectMapper.readTree(body).get("token").asText(); + } + + private int statusWith(String token) throws Exception { + return mvc.perform(get("/api/campaigns").header("Authorization", "Bearer " + token)) + .andReturn().getResponse().getStatus(); + } } diff --git a/src/test/java/com/mailengine/mailengine/security/JwtAuthFilterTest.java b/src/test/java/com/mailengine/mailengine/security/JwtAuthFilterTest.java index f38f91a..eb9804c 100644 --- a/src/test/java/com/mailengine/mailengine/security/JwtAuthFilterTest.java +++ b/src/test/java/com/mailengine/mailengine/security/JwtAuthFilterTest.java @@ -113,6 +113,30 @@ void validTokenAuthenticatesUserWithRoleAuthority(Role role) throws Exception { .containsExactly("ROLE_" + role.name()); } + @Test + void tokenIssuedBeforeAPasswordChangeIsRejectedWith401() throws Exception { + User user = TestUsers.user(5L, Role.editor); + String oldToken = bearer(user); // version 0 + user.revokeTokens(); // the password changed + when(userRepository.findById(5L)).thenReturn(Optional.of(user)); + + filter.doFilter(request("/api/campaigns", oldToken), response, chain); + + assertUnauthorized(); + } + + @Test + void tokenIssuedAfterThePasswordChangeIsAccepted() throws Exception { + User user = TestUsers.user(5L, Role.editor); + user.revokeTokens(); + when(userRepository.findById(5L)).thenReturn(Optional.of(user)); + + filter.doFilter(request("/api/campaigns", bearer(user)), response, chain); + + assertThat(chain.getRequest()).isNotNull(); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); + } + @Test void roleIsReadFromDatabaseNotFromToken() throws Exception { User demoted = TestUsers.user(5L, Role.viewer); diff --git a/src/test/java/com/mailengine/mailengine/security/JwtServiceTest.java b/src/test/java/com/mailengine/mailengine/security/JwtServiceTest.java index a1edd47..a370d1b 100644 --- a/src/test/java/com/mailengine/mailengine/security/JwtServiceTest.java +++ b/src/test/java/com/mailengine/mailengine/security/JwtServiceTest.java @@ -28,6 +28,27 @@ void generatedTokenIsValidAndCarriesUserIdAsSubject() { assertThat(jwtService.extractUserId(token)).isEqualTo("42"); } + @Test + void tokenCarriesTheUsersTokenVersion() { + admin.setTokenVersion(3); + + JwtService.TokenClaims claims = jwtService.parse(jwtService.generateToken(admin)); + + assertThat(claims.userId()).isEqualTo(42L); + assertThat(claims.tokenVersion()).isEqualTo(3); + } + + @Test + void tokenIssuedBeforeVersionsExistedCountsAsVersionZero() { + String legacy = io.jsonwebtoken.Jwts.builder().subject("42") + .expiration(new java.util.Date(System.currentTimeMillis() + 60_000)) + .signWith(io.jsonwebtoken.security.Keys.hmacShaKeyFor( + io.jsonwebtoken.io.Decoders.BASE64.decode(TestUsers.SECRET))) + .compact(); + + assertThat(jwtService.parse(legacy).tokenVersion()).isZero(); + } + @Test void expiredTokenIsRejected() { JwtService expiring = TestUsers.jwtService(TestUsers.SECRET, -1_000L); diff --git a/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java b/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java index ff29995..bfc03d8 100644 --- a/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java +++ b/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java @@ -9,6 +9,7 @@ import com.mailengine.mailengine.repository.TrackingEventRepository; import com.mailengine.mailengine.repository.UserRepository; import com.mailengine.mailengine.service.AnalyticsService; +import com.mailengine.mailengine.dto.response.AuthResponse; import com.mailengine.mailengine.service.AuthService; import com.mailengine.mailengine.service.CampaignSendingService; import com.mailengine.mailengine.service.CampaignService; @@ -261,6 +262,7 @@ void mustChangePasswordUserCanOnlyChangePassword() throws Exception { User user = TestUsers.user(11L, Role.admin); user.setMustChangePwd(true); when(userRepository.findById(11L)).thenReturn(Optional.of(user)); + when(authService.changePassword(org.mockito.ArgumentMatchers.any())).thenReturn(new AuthResponse("fresh", null, 60_000L, false)); assertThat(status("GET /api/campaigns", bearer(user))).isEqualTo(403); assertThat(status("GET /api/users", bearer(user))).isEqualTo(403); diff --git a/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java b/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java index d5d8b1b..0322165 100644 --- a/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java +++ b/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java @@ -243,6 +243,19 @@ void successStoresNewHashAndClearsForcedChange() { verify(userRepository).save(user); } + @Test + void changeSignsOutEverySessionAndReturnsAFreshToken() { + Requests.authenticateAs(user); + int before = user.getTokenVersion(); + when(jwtService.generateToken(user)).thenAnswer(i -> "token-v" + user.getTokenVersion()); + + AuthResponse fresh = authService.changePassword(change(PASSWORD, "BrandNewPass9")); + + assertThat(user.getTokenVersion()).isEqualTo(before + 1); + assertThat(fresh.token()).as("issued after the version was raised").isEqualTo("token-v" + (before + 1)); + assertThat(fresh.mustChangePassword()).isFalse(); + } + @Test void wrongCurrentPasswordIsRejected() { Requests.authenticateAs(user); @@ -342,6 +355,17 @@ void validTokenResetsPasswordOnceAndClearsForcedChange() { verify(passwordResetTokenRepository).save(token); } + @Test + void resetSignsOutEverySession() { + int before = user.getTokenVersion(); + PasswordResetToken token = new PasswordResetToken("tok", user, Instant.now().plusSeconds(600)); + when(passwordResetTokenRepository.findByToken(TokenHashing.sha256Hex("tok"))).thenReturn(Optional.of(token)); + + authService.resetPassword(reset("tok", "BrandNewPass9")); + + assertThat(user.getTokenVersion()).isEqualTo(before + 1); + } + @Test void unknownTokenIsRejected() { when(passwordResetTokenRepository.findByToken(TokenHashing.sha256Hex("nope"))).thenReturn(Optional.empty()); diff --git a/src/test/java/com/mailengine/mailengine/service/TemplateImageUploadTest.java b/src/test/java/com/mailengine/mailengine/service/TemplateImageUploadTest.java new file mode 100644 index 0000000..29580ca --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/service/TemplateImageUploadTest.java @@ -0,0 +1,64 @@ +package com.mailengine.mailengine.service; + +import com.mailengine.mailengine.exception.BadRequestException; +import com.mailengine.mailengine.repository.CampaignRepository; +import com.mailengine.mailengine.repository.TemplateRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockMultipartFile; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +/** Template images go to a public bucket: only real images, typed by the server. */ +@ExtendWith(MockitoExtension.class) +class TemplateImageUploadTest { + + @Mock TemplateRepository templateRepository; + @Mock CampaignRepository campaignRepository; + @Mock S3Service s3Service; + @InjectMocks TemplateService templateService; + + @Test + void svgIsRefusedAndNothingIsStored() { + MockMultipartFile svg = new MockMultipartFile("file", "logo.svg", "image/svg+xml", + "".getBytes(StandardCharsets.UTF_8)); + + assertThatThrownBy(() -> templateService.uploadImage(svg)).isInstanceOf(BadRequestException.class); + verify(s3Service, never()).uploadBytes(any(), anyString(), anyString(), anyString()); + } + + @Test + void htmlLabelledAsAnImageIsRefused() { + MockMultipartFile html = new MockMultipartFile("file", "photo.png", "image/png", + "phish".getBytes(StandardCharsets.UTF_8)); + + assertThatThrownBy(() -> templateService.uploadImage(html)).isInstanceOf(BadRequestException.class); + verify(s3Service, never()).uploadBytes(any(), anyString(), anyString(), anyString()); + } + + @Test + void emptyFileIsRefused() { + assertThatThrownBy(() -> templateService.uploadImage(new MockMultipartFile("file", new byte[0]))) + .isInstanceOf(BadRequestException.class); + } + + @Test + void realImageIsStoredWithTheTypeItReallyIsWhateverTheClientSaid() { + byte[] png = {(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D}; + when(s3Service.uploadBytes(any(), anyString(), anyString(), anyString())).thenReturn("https://bucket/x.png"); + + String url = templateService.uploadImage(new MockMultipartFile("file", "x.html", "text/html", png)); + + assertThat(url).isEqualTo("https://bucket/x.png"); + verify(s3Service).uploadBytes(png, "image/png", ".png", "templates/images"); + } +} diff --git a/src/test/java/com/mailengine/mailengine/service/UserServiceTest.java b/src/test/java/com/mailengine/mailengine/service/UserServiceTest.java index adb7696..fba41ac 100644 --- a/src/test/java/com/mailengine/mailengine/service/UserServiceTest.java +++ b/src/test/java/com/mailengine/mailengine/service/UserServiceTest.java @@ -250,6 +250,16 @@ void adminResetIssuesHashedTempPasswordAndForcesChange() { assertThat(target.getMustChangePwd()).isTrue(); } + @Test + void adminResetSignsTheUserOutEverywhere() { + User target = TestUsers.user(9L, Role.viewer); + when(userRepository.findById(9L)).thenReturn(Optional.of(target)); + + userService.adminResetPassword(9L); + + assertThat(target.getTokenVersion()).isEqualTo(1); + } + @Test void listingReturnsEveryUser() { when(userRepository.findAll()).thenReturn(List.of(admin, TestUsers.user(2L, Role.viewer))); diff --git a/src/test/java/com/mailengine/mailengine/util/ImageTypesTest.java b/src/test/java/com/mailengine/mailengine/util/ImageTypesTest.java new file mode 100644 index 0000000..0be5f02 --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/util/ImageTypesTest.java @@ -0,0 +1,43 @@ +package com.mailengine.mailengine.util; + +import com.mailengine.mailengine.util.ImageTypes.ImageType; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; + +class ImageTypesTest { + + static final byte[] PNG = {(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D}; + + @Test + void supportedImagesAreRecognisedByTheirFirstBytes() { + assertThat(ImageTypes.detect(PNG)).contains(ImageType.PNG); + assertThat(ImageTypes.detect(new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0})).contains(ImageType.JPEG); + assertThat(ImageTypes.detect(ascii("GIF89a...."))).contains(ImageType.GIF); + assertThat(ImageTypes.detect(ascii("GIF87a...."))).contains(ImageType.GIF); + assertThat(ImageTypes.detect(ascii("RIFF\0\0\0\0WEBPVP8 "))).contains(ImageType.WEBP); + } + + @Test + void anythingElseIsRefused() { + assertThat(ImageTypes.detect(ascii(""))).isEmpty(); + assertThat(ImageTypes.detect(ascii(""))).isEmpty(); + assertThat(ImageTypes.detect(ascii(""))).isEmpty(); + assertThat(ImageTypes.detect(ascii("RIFF\0\0\0\0WAVEfmt "))).as("a RIFF that isn't WebP").isEmpty(); + assertThat(ImageTypes.detect(new byte[0])).isEmpty(); + assertThat(ImageTypes.detect(new byte[]{(byte) 0x89, 'P'})).as("too short").isEmpty(); + assertThat(ImageTypes.detect(null)).isEmpty(); + } + + @Test + void typesCarryWhatS3ServesThemAs() { + assertThat(ImageType.PNG.contentType()).isEqualTo("image/png"); + assertThat(ImageType.JPEG.extension()).isEqualTo(".jpg"); + } + + private static byte[] ascii(String s) { + return s.getBytes(StandardCharsets.ISO_8859_1); + } +}