From e82ac27dad5ccbe1b6661e0bc015517f351d495c Mon Sep 17 00:00:00 2001 From: op-techy Date: Fri, 4 Dec 2026 05:16:51 +0100 Subject: [PATCH] fix: real client IP, Apple proxy by network, one eligibility query, expiring temp passwords - Tracking records request.getRemoteAddr() (resolved by Tomcat's RemoteIpValve) instead of reading X-Forwarded-For, which anyone could forge. - Apple Mail Privacy Protection opens are flagged by Apple's network, 17.0.0.0/8; the User-Agent check never matched Apple's proxy. - Sending collects eligible recipients in one query instead of one suppression lookup per list member. - Temporary passwords are 16 SecureRandom characters and expire (V4): 7 days for invites, 24 hours for admin resets. Login refuses expired ones; changing or resetting clears it. --- README.md | 5 +- .../mailengine/entity/TrackingEvent.java | 4 +- .../mailengine/mailengine/entity/User.java | 11 +++ .../repository/RecipientRepository.java | 24 ++++- .../mailengine/service/AuthService.java | 7 ++ .../service/CampaignSendingService.java | 30 +----- .../mailengine/service/EmailService.java | 7 +- .../mailengine/service/TrackingService.java | 49 +++++----- .../mailengine/service/UserService.java | 9 +- .../mailengine/util/TemporaryPasswords.java | 36 ++++++++ .../db/migration/V4__temp_password_expiry.sql | 3 + .../CampaignPipelineIntegrationTest.java | 92 +++++++++++++++++-- .../mailengine/service/AuthServiceTest.java | 47 ++++++++++ .../TrackingServiceAppleProxyTest.java | 25 +++++ .../mailengine/service/UserServiceTest.java | 10 +- .../util/TemporaryPasswordsTest.java | 37 ++++++++ 16 files changed, 324 insertions(+), 72 deletions(-) create mode 100644 src/main/java/com/mailengine/mailengine/util/TemporaryPasswords.java create mode 100644 src/main/resources/db/migration/V4__temp_password_expiry.sql create mode 100644 src/test/java/com/mailengine/mailengine/service/TrackingServiceAppleProxyTest.java create mode 100644 src/test/java/com/mailengine/mailengine/util/TemporaryPasswordsTest.java diff --git a/README.md b/README.md index d13762f..4845319 100644 --- a/README.md +++ b/README.md @@ -464,6 +464,7 @@ Every user has one role. Spring Security enforces these rules in `SecurityConfig - **No token, or an invalid or expired one:** `401`. - **Public, no token needed:** `/api/auth/**` (except `change-password`), `/track/**`, `/webhooks/**`, Swagger, `/ready`, and `GET /api/recipient-lists/template/**`. - **Forced password change:** a user with `mustChangePwd` (newly invited, or reset by an admin) can only call `POST /api/auth/change-password`. Everything else returns `403` until they change it. +- **Temporary passwords** (invites and admin resets) are 16 random characters and expire: after 7 days for an invite, 24 hours for an admin reset. Login then refuses them with `401` "Temporary password has expired"; an admin issues a new one with `POST /api/users/{id}/reset-password`. The seeded admin's first password doesn't expire. - **Role changes take effect on the next request**, because the user and their role are loaded from the database for every request, not taken from the token. - **Admins can't change their own role or delete themselves**, so at least one admin always remains. - `UserService` repeats the admin check as a second line of defence. @@ -668,7 +669,7 @@ When the email client loads this image, `TrackingService.handleOpen()` fires: - Resolves campaign + recipient from `pixelToken` - Extracts IP from `X-Forwarded-For` → looks up country/city in the MaxMind database (offline) - Parses User-Agent via Yauaa for device type, OS, email client -- Sets `isAppleProxy = true` if the User-Agent contains "Apple" and "Mail" (Apple Mail Privacy Protection pre-fetches images, so these opens are flagged and can be filtered out of open rates) +- Sets `isAppleProxy = true` when the open comes from Apple's network, `17.0.0.0/8`. Apple Mail Privacy Protection pre-fetches every image through Apple's proxies, so these opens don't mean a person read the email. The flag is stored on each open event; analytics doesn't use it yet. - Saves a `TrackingEvent(type=open)` - Returns the 67-byte PNG so the email renders normally @@ -944,7 +945,7 @@ To get the current user in a service, use `SecurityUtils.currentUser()`. It retu 6. **Single instance:** startup import recovery assumes one app instance. If you run several against the same database, revisit `ImportRecovery` first. -7. **`server.forward-headers-strategy: native`** — Already configured. This ensures `X-Forwarded-For` and `X-Forwarded-Proto` are trusted when running behind a reverse proxy (Railway, Heroku, nginx, etc.). +7. **`server.forward-headers-strategy: native`** — Already configured. Tracking records the client IP that Tomcat works out from `X-Forwarded-For`, and Tomcat only trusts that header when it comes from an internal proxy address (private ranges such as `10.x`, `172.16–31.x`, `192.168.x` and localhost). If your reverse proxy or load balancer reaches the app from a public IP, every open and click is recorded with the proxy's IP: add the proxy's address to `server.tomcat.remoteip.internal-proxies` (a regex). 8. **Never run with `SPRING_PROFILES_ACTIVE=mock-email` in production:** emails aren't sent, and temporary passwords and reset links are written to the log. diff --git a/src/main/java/com/mailengine/mailengine/entity/TrackingEvent.java b/src/main/java/com/mailengine/mailengine/entity/TrackingEvent.java index f934f11..dd4edc9 100644 --- a/src/main/java/com/mailengine/mailengine/entity/TrackingEvent.java +++ b/src/main/java/com/mailengine/mailengine/entity/TrackingEvent.java @@ -85,8 +85,8 @@ public class TrackingEvent { @Column(name = "user_agent", length = Integer.MAX_VALUE) private String userAgent; - // True if the open came from Apple Mail's image pre-fetcher, not a real human open. - // Used to calculate the adjusted open rate in analytics. + // True if the open came from Apple Mail's image pre-fetcher (Apple's 17.0.0.0/8 network), not a real human open. + // Stored for analytics; nothing reads it yet. @ColumnDefault("false") @Column(name = "is_apple_proxy") private Boolean isAppleProxy; diff --git a/src/main/java/com/mailengine/mailengine/entity/User.java b/src/main/java/com/mailengine/mailengine/entity/User.java index ca54f3b..dc1c1c2 100644 --- a/src/main/java/com/mailengine/mailengine/entity/User.java +++ b/src/main/java/com/mailengine/mailengine/entity/User.java @@ -70,6 +70,17 @@ public class User implements UserDetails { @Column(name = "token_version", nullable = false) private Integer tokenVersion = 0; + /** When the current temporary password stops working; null when the password isn't temporary or never expires. */ + @Column(name = "temp_password_expires_at") + private Instant tempPasswordExpiresAt; + + /** True when the user is still on a temporary password whose time is up. */ + public boolean isTemporaryPasswordExpired() { + return Boolean.TRUE.equals(mustChangePwd) + && tempPasswordExpiresAt != null + && !Instant.now().isBefore(tempPasswordExpiresAt); + } + /** Signs the user out everywhere: every token issued so far stops working. */ public void revokeTokens() { tokenVersion = (tokenVersion == null ? 0 : tokenVersion) + 1; diff --git a/src/main/java/com/mailengine/mailengine/repository/RecipientRepository.java b/src/main/java/com/mailengine/mailengine/repository/RecipientRepository.java index 34c88ee..b25eba9 100644 --- a/src/main/java/com/mailengine/mailengine/repository/RecipientRepository.java +++ b/src/main/java/com/mailengine/mailengine/repository/RecipientRepository.java @@ -8,6 +8,7 @@ import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import java.util.List; import java.util.Optional; @Repository @@ -21,4 +22,25 @@ public interface RecipientRepository extends JpaRepository { @Query("SELECT r FROM Recipient r JOIN RecipientListMember rlm ON r.id = rlm.recipient.id WHERE rlm.recipientList.id = :listId AND (LOWER(r.email) LIKE LOWER(CONCAT('%', :search, '%')) OR LOWER(r.firstName) LIKE LOWER(CONCAT('%', :search, '%')) OR LOWER(r.lastName) LIKE LOWER(CONCAT('%', :search, '%')))") Page searchByRecipientListId(@Param("listId") Long listId, @Param("search") String search, Pageable pageable); -} \ No newline at end of file + + /** + * Everyone a campaign may be sent to, in one query: active recipients in any of the campaign's lists whose + * address isn't on the suppression list. An address in several lists (or spelt with different case) appears + * once, as its lowest-id recipient. Ordered by id so the queue is built in a stable order. + */ + @Query(value = """ + SELECT r.* FROM recipients r + WHERE r.id IN ( + SELECT DISTINCT ON (lower(trim(r2.email))) r2.id + FROM recipients r2 + JOIN recipient_list_members m ON m.recipient_id = r2.id + JOIN campaign_recipient_lists c ON c.recipient_list_id = m.recipient_list_id + WHERE c.campaign_id = :campaignId + AND r2.status = 'active' + AND NOT EXISTS (SELECT 1 FROM suppression_list s WHERE s.email = lower(trim(r2.email))) + ORDER BY lower(trim(r2.email)), r2.id + ) + ORDER BY r.id + """, nativeQuery = true) + List findEligibleForCampaign(@Param("campaignId") Long campaignId); +} diff --git a/src/main/java/com/mailengine/mailengine/service/AuthService.java b/src/main/java/com/mailengine/mailengine/service/AuthService.java index 28b174a..5c9f520 100644 --- a/src/main/java/com/mailengine/mailengine/service/AuthService.java +++ b/src/main/java/com/mailengine/mailengine/service/AuthService.java @@ -104,6 +104,11 @@ public AuthResponse login(LoginRequest request) { throw new UnauthorizedException("Please verify your email before logging in"); } + // Also only after the password matches. Not a failed attempt: the password was right, just too old. + if (user.isTemporaryPasswordExpired()) { + throw new UnauthorizedException("Temporary password has expired. Ask an administrator for a new one."); + } + user.setFailedLoginAttempts(0); user.setLockedUntil(null); user.setLastLogin(Instant.now()); @@ -134,6 +139,7 @@ public AuthResponse changePassword(ChangePasswordRequest request) { } user.setPasswordHash(passwordEncoder.encode(request.getNewPassword())); user.setMustChangePwd(false); + user.setTempPasswordExpiresAt(null); user.revokeTokens(); userRepository.save(user); @@ -170,6 +176,7 @@ public void resetPassword(ResetPasswordRequest request) { User user = prt.getUser(); user.setPasswordHash(passwordEncoder.encode(request.getNewPassword())); user.setMustChangePwd(false); + user.setTempPasswordExpiresAt(null); user.revokeTokens(); // a reset is often because of a suspected compromise: end every session userRepository.save(user); prt.setUsed(true); diff --git a/src/main/java/com/mailengine/mailengine/service/CampaignSendingService.java b/src/main/java/com/mailengine/mailengine/service/CampaignSendingService.java index 32aa7e8..d89d794 100644 --- a/src/main/java/com/mailengine/mailengine/service/CampaignSendingService.java +++ b/src/main/java/com/mailengine/mailengine/service/CampaignSendingService.java @@ -24,11 +24,9 @@ public class CampaignSendingService { private final CampaignRepository campaignRepository; private final CampaignJobRepository campaignJobRepository; - private final CampaignRecipientListRepository campaignRecipientListRepository; - private final RecipientListMemberRepository recipientListMemberRepository; private final EmailQueueRepository emailQueueRepository; + private final RecipientRepository recipientRepository; private final EmailSender emailSender; - private final SuppressionService suppressionService; private final TrackingUrls trackingUrls; // ───────────────────────────────────────────────────────────────────────────── @@ -209,31 +207,9 @@ public void resumeCampaign(Long campaignId) { // PRIVATE HELPERS // ───────────────────────────────────────────────────────────────────────────── + /** Active, not suppressed, each address once: see {@link RecipientRepository#findEligibleForCampaign}. */ private List collectEligibleRecipients(Campaign campaign) { - List campaignLists = - campaignRecipientListRepository.findByCampaignId(campaign.getId()); - - Set seenEmails = new HashSet<>(); - List eligible = new ArrayList<>(); - - for (CampaignRecipientList crl : campaignLists) { - List members = - recipientListMemberRepository.findByRecipientListId( - crl.getRecipientList().getId()); - - for (RecipientListMember member : members) { - Recipient r = member.getRecipient(); - String email = r.getEmail().toLowerCase(); - - if (seenEmails.contains(email)) continue; - if (r.getStatus() != RecipientStatus.active) continue; - if (suppressionService.isSuppressed(email)) continue; - - seenEmails.add(email); - eligible.add(r); - } - } - return eligible; + return recipientRepository.findEligibleForCampaign(campaign.getId()); } private String personaliseHtml(String html, Recipient recipient, diff --git a/src/main/java/com/mailengine/mailengine/service/EmailService.java b/src/main/java/com/mailengine/mailengine/service/EmailService.java index a19a8f7..b54fa2b 100644 --- a/src/main/java/com/mailengine/mailengine/service/EmailService.java +++ b/src/main/java/com/mailengine/mailengine/service/EmailService.java @@ -1,5 +1,6 @@ package com.mailengine.mailengine.service; +import com.mailengine.mailengine.util.TemporaryPasswords; import jakarta.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; @@ -51,7 +52,8 @@ public void sendInvitationEmail(String toEmail, String tempPassword, String invi + " Email: " + toEmail + "\n" + " Password: " + tempPassword + "\n\n" + "Log in at: " + baseUrl + "/login\n\n" - + "You will be asked to change your password on first login."); + + "This password expires in " + TemporaryPasswords.describe(TemporaryPasswords.INVITE_VALIDITY) + + ". You will be asked to change it on first login."); } @Async @@ -61,7 +63,8 @@ public void sendAdminPasswordResetEmail(String toEmail, String tempPassword) { "An administrator has reset your password.\n\n" + "Your temporary password: " + tempPassword + "\n\n" + "Log in at: " + baseUrl + "/login\n\n" - + "You will be asked to set a new password on login."); + + "This password expires in " + TemporaryPasswords.describe(TemporaryPasswords.ADMIN_RESET_VALIDITY) + + ". You will be asked to set a new password on login."); } private void send(String to, String subject, String body) { diff --git a/src/main/java/com/mailengine/mailengine/service/TrackingService.java b/src/main/java/com/mailengine/mailengine/service/TrackingService.java index 70dd844..7f07164 100644 --- a/src/main/java/com/mailengine/mailengine/service/TrackingService.java +++ b/src/main/java/com/mailengine/mailengine/service/TrackingService.java @@ -81,8 +81,8 @@ public class TrackingService { * *

Apple Mail Privacy Protection (iOS 15+) pre-fetches all images before * the user opens the email, inflating open rates by ~15-20%. This method - * detects Apple proxy opens ({@code isAppleProxy = true}) so analytics can - * report both raw and adjusted open rates. + * flags opens from Apple's proxy network ({@code isAppleProxy = true}) so they can + * be told apart from real opens. * * @param pixelToken unique UUID identifying the queued email; embedded in the pixel URL * @param request HTTP request — used to extract the client IP and User-Agent @@ -92,9 +92,9 @@ public class TrackingService { public byte[] handleOpen(String pixelToken, HttpServletRequest request) { // Use ifPresent so we silently ignore expired or unknown tokens emailQueueRepository.findByPixelToken(pixelToken).ifPresent(queued -> { - String ipAddress = extractIp(request); + String ipAddress = clientIp(request); String userAgent = request.getHeader("User-Agent"); - boolean isAppleProxy = isAppleMailProxy(userAgent); + boolean isAppleProxy = isAppleMailProxy(ipAddress); TrackingEvent event = new TrackingEvent(); event.setCampaign(queued.getCampaign()); @@ -161,7 +161,7 @@ public String handleClick(String clickToken, HttpServletRequest request) { return null; } - String ipAddress = extractIp(request); + String ipAddress = clientIp(request); String userAgent = request.getHeader("User-Agent"); TrackingEvent event = new TrackingEvent(); @@ -256,34 +256,33 @@ private void enrichEventWithGeoAndDevice(TrackingEvent event, } /** - * Extracts the real client IP address, honouring the {@code X-Forwarded-For} - * header set by reverse proxies and CDNs. The first IP in the chain is the - * original client — subsequent IPs are intermediate proxies. + * The client's IP address. * - * @param request the HTTP request - * @return the client IP address string + *

Tomcat's {@code RemoteIpValve} ({@code server.forward-headers-strategy: native}) has already set it from + * {@code X-Forwarded-For}, trusting that header only when it comes from an internal proxy. Reading the header + * here instead would let anyone choose the IP (and so the location) that gets recorded. */ - private String extractIp(HttpServletRequest request) { - String forwarded = request.getHeader("X-Forwarded-For"); - if (forwarded != null && !forwarded.isEmpty()) { - return forwarded.split(",")[0].trim(); - } + private static String clientIp(HttpServletRequest request) { return request.getRemoteAddr(); } /** - * Detects whether an open event was triggered by Apple Mail Privacy Protection. - * - *

Since iOS 15, Apple Mail pre-fetches all email images through Apple's - * proxy before the user opens the email. This artificially inflates open rates - * by 15-20%. We detect these by checking the User-Agent string. + * Whether an open came from Apple Mail Privacy Protection, which fetches every image in an email through + * Apple's own proxies before (or without) the person opening it. * - * @param userAgent the raw User-Agent header value - * @return {@code true} if the request appears to be Apple's proxy + *

Those proxies send a generic browser User-Agent, so they are recognised by network instead: they fetch + * from {@code 17.0.0.0/8}, which Apple owns outright. The IP comes from {@link #clientIp}, so it can't be faked + * with a header. */ - private boolean isAppleMailProxy(String userAgent) { - if (userAgent == null) return false; - return userAgent.contains("Apple") && userAgent.contains("Mail"); + static boolean isAppleMailProxy(String ip) { + if (ip == null) return false; + String[] octets = ip.trim().split("\\.", -1); + if (octets.length != 4) return false; + for (String octet : octets) { + if (octet.isEmpty() || octet.length() > 3 || !octet.chars().allMatch(Character::isDigit)) return false; + if (Integer.parseInt(octet) > 255) return false; + } + return Integer.parseInt(octets[0]) == 17; } /** diff --git a/src/main/java/com/mailengine/mailengine/service/UserService.java b/src/main/java/com/mailengine/mailengine/service/UserService.java index cfbca2d..c88d0ad 100644 --- a/src/main/java/com/mailengine/mailengine/service/UserService.java +++ b/src/main/java/com/mailengine/mailengine/service/UserService.java @@ -10,15 +10,16 @@ import com.mailengine.mailengine.exception.ResourceNotFoundException; import com.mailengine.mailengine.repository.UserRepository; import com.mailengine.mailengine.security.SecurityUtils; +import com.mailengine.mailengine.util.TemporaryPasswords; import lombok.RequiredArgsConstructor; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.time.Instant; import java.util.List; import java.util.Locale; -import java.util.UUID; @Service @RequiredArgsConstructor @@ -46,7 +47,7 @@ public UserResponse inviteUser(InviteUserRequest request) { throw new ConflictException("A user with this email already exists"); } - String tempPassword = "Tmp-" + UUID.randomUUID().toString().substring(0, 8); + String tempPassword = TemporaryPasswords.generate(); User invited = new User(); invited.setName(request.getName()); @@ -56,6 +57,7 @@ public UserResponse inviteUser(InviteUserRequest request) { invited.setInvitedBy(current); invited.setEmailVerified(true); invited.setMustChangePwd(true); + invited.setTempPasswordExpiresAt(Instant.now().plus(TemporaryPasswords.INVITE_VALIDITY)); userRepository.save(invited); emailService.sendInvitationEmail(email, tempPassword, current.getName()); @@ -85,9 +87,10 @@ public void deleteUser(Long id) { public void adminResetPassword(Long id) { User current = requireAdmin("Only admins can reset user passwords"); User target = findOrThrow(id); - String tempPassword = "Tmp-" + UUID.randomUUID().toString().substring(0, 8); + String tempPassword = TemporaryPasswords.generate(); target.setPasswordHash(passwordEncoder.encode(tempPassword)); target.setMustChangePwd(true); + target.setTempPasswordExpiresAt(Instant.now().plus(TemporaryPasswords.ADMIN_RESET_VALIDITY)); 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/TemporaryPasswords.java b/src/main/java/com/mailengine/mailengine/util/TemporaryPasswords.java new file mode 100644 index 0000000..168c6c9 --- /dev/null +++ b/src/main/java/com/mailengine/mailengine/util/TemporaryPasswords.java @@ -0,0 +1,36 @@ +package com.mailengine.mailengine.util; + +import java.security.SecureRandom; +import java.time.Duration; + +/** Temporary passwords for invites and admin resets: how they are made and how long they last. */ +public final class TemporaryPasswords { + + /** An invited user may not see the email for a few days. */ + public static final Duration INVITE_VALIDITY = Duration.ofDays(7); + /** A reset is asked for by someone who is waiting to log in. */ + public static final Duration ADMIN_RESET_VALIDITY = Duration.ofHours(24); + + static final int LENGTH = 16; + /** Letters and digits without the ones that are easy to misread (0/O, 1/l/I): 57 symbols, about 93 bits. */ + static final String ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"; + + private static final SecureRandom RANDOM = new SecureRandom(); + + private TemporaryPasswords() { + } + + public static String generate() { + StringBuilder password = new StringBuilder(LENGTH); + for (int i = 0; i < LENGTH; i++) { + password.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length()))); + } + return password.toString(); + } + + /** "7 days", "24 hours": for the emails that carry the password. */ + public static String describe(Duration validity) { + long hours = validity.toHours(); + return hours >= 48 && hours % 24 == 0 ? hours / 24 + " days" : hours + (hours == 1 ? " hour" : " hours"); + } +} diff --git a/src/main/resources/db/migration/V4__temp_password_expiry.sql b/src/main/resources/db/migration/V4__temp_password_expiry.sql new file mode 100644 index 0000000..4fd1363 --- /dev/null +++ b/src/main/resources/db/migration/V4__temp_password_expiry.sql @@ -0,0 +1,3 @@ +-- When the temporary password from an invite or an admin reset stops working. Login refuses it after this time; +-- changing or resetting the password clears it. NULL means no expiry, which covers the seeded admin's first login. +ALTER TABLE users ADD COLUMN temp_password_expires_at TIMESTAMP; diff --git a/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java b/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java index 1ca2523..6f96737 100644 --- a/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java +++ b/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java @@ -496,6 +496,77 @@ void engagementScoresRefreshCountsRecentOpens() throws Exception { recipientId)).containsEntry("campaigns_sent", 1).containsEntry("campaigns_opened", 1); } + @Test + void sendQueuesEachEligibleAddressOnceAcrossLists() throws Exception { + RecipientList first = listWith(0); + RecipientList second = listWith(0); + Recipient inBoth = recipient("both"); + Recipient suppressed = recipient("Suppressed"); + Recipient unsubscribed = recipient("unsub"); + unsubscribed.setStatus(RecipientStatus.unsubscribed); + recipientRepository.save(unsubscribed); + Recipient lower = recipient("case"); + Recipient upper = new Recipient(); + upper.setEmail(lower.getEmail().toUpperCase(Locale.ROOT)); + upper.setFirstName("First"); + upper.setStatus(RecipientStatus.active); + upper = recipientRepository.save(upper); + // the suppression list holds addresses lower-cased; the recipient's own spelling must still match + jdbc.update("insert into suppression_list (email, reason) values (?, 'bounced')", + suppressed.getEmail().toLowerCase(Locale.ROOT)); + + addMember(first, inBoth); + addMember(second, inBoth); + addMember(first, suppressed); + addMember(second, unsubscribed); + addMember(first, upper); + addMember(second, lower); + + CampaignRequest req = new CampaignRequest(); + req.setName("C" + SEQ.incrementAndGet()); + req.setSubjectLine("Hello"); + req.setFromName("Team"); + req.setFromEmail("team@example.test"); + req.setTemplateId(template().getId()); + req.setRecipientListIds(List.of(first.getId(), second.getId())); + long id = campaignService.createCampaign(req).getId(); + + sendingService.sendCampaign(id); + + assertThat(jdbc.queryForList("select recipient_id from email_queue where campaign_id = ? order by recipient_id", + Long.class, id)) + .as("in both lists once; suppressed and unsubscribed left out; one of the two spellings, the older") + .containsExactly(inBoth.getId(), lower.getId()); + } + + @Test + void openRecordsTheConnectionsIpNotAForgedForwardedHeader() throws Exception { + long id = sentCampaign(1); + drainQueue(); + String pixel = jdbc.queryForObject("select pixel_token from email_queue where campaign_id = ?", String.class, id); + + // MockMvc has no proxy in front, so the forged header must simply be ignored + mvc.perform(get("/track/open/{token}", pixel).header("X-Forwarded-For", "17.1.2.3")); + + assertThat(jdbc.queryForMap("select ip_address, is_apple_proxy from tracking_events where campaign_id = ?", id)) + .containsEntry("ip_address", "127.0.0.1") + .containsEntry("is_apple_proxy", false); + } + + @Test + void openFromApplesNetworkIsFlaggedAsTheMailPrivacyProxy() throws Exception { + long id = sentCampaign(1); + drainQueue(); + String pixel = jdbc.queryForObject("select pixel_token from email_queue where campaign_id = ?", String.class, id); + + mvc.perform(get("/track/open/{token}", pixel) + .header("User-Agent", "Mozilla/5.0") + .with(request -> { request.setRemoteAddr("17.58.63.1"); return request; })); + + assertThat(jdbc.queryForObject("select is_apple_proxy from tracking_events where campaign_id = ?", + Boolean.class, id)).isTrue(); + } + // ── helpers ───────────────────────────────────────────────────────────── private static final AtomicInteger SEQ = new AtomicInteger(); @@ -521,19 +592,22 @@ private RecipientList listWith(int recipients) { list.setRecipientCount(recipients); list = listRepository.save(list); for (int i = 0; i < recipients; i++) { - Recipient r = recipient("r"); - RecipientListMemberId mid = new RecipientListMemberId(); - mid.setRecipientListId(list.getId()); - mid.setRecipientId(r.getId()); - RecipientListMember m = new RecipientListMember(); - m.setId(mid); - m.setRecipientList(list); - m.setRecipient(r); - memberRepository.save(m); + addMember(list, recipient("r")); } return list; } + private void addMember(RecipientList list, Recipient r) { + RecipientListMemberId mid = new RecipientListMemberId(); + mid.setRecipientListId(list.getId()); + mid.setRecipientId(r.getId()); + RecipientListMember m = new RecipientListMember(); + m.setId(mid); + m.setRecipientList(list); + m.setRecipient(r); + memberRepository.save(m); + } + private long draftCampaign(int recipients) { CampaignRequest req = new CampaignRequest(); req.setName("C" + SEQ.incrementAndGet()); diff --git a/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java b/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java index 0322165..bd82768 100644 --- a/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java +++ b/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java @@ -220,6 +220,49 @@ void unverifiedAccountWithCorrectPasswordIsToldToVerify() { verifyNoInteractions(jwtService); } + @Test + void expiredTemporaryPasswordIsRefusedWithoutCountingAsAFailure() { + user.setMustChangePwd(true); + user.setTempPasswordExpiresAt(Instant.now().minusSeconds(1)); + givenUserExists(); + + assertThatThrownBy(() -> authService.login(login("editor@example.com", PASSWORD))) + .isInstanceOf(UnauthorizedException.class) + .hasMessage("Temporary password has expired. Ask an administrator for a new one."); + assertThat(user.getFailedLoginAttempts()).isZero(); + verifyNoInteractions(jwtService); + } + + @Test + void expiredTemporaryPasswordStillGetsTheGenericMessageWhenWrong() { + user.setMustChangePwd(true); + user.setTempPasswordExpiresAt(Instant.now().minusSeconds(1)); + givenUserExists(); + + assertThatThrownBy(() -> authService.login(login("editor@example.com", "wrong-password"))) + .isInstanceOf(UnauthorizedException.class) + .hasMessage("Invalid email or password"); + } + + @Test + void unexpiredTemporaryPasswordLogsIn() { + user.setMustChangePwd(true); + user.setTempPasswordExpiresAt(Instant.now().plus(Duration.ofHours(1))); + givenUserExists(); + when(jwtService.generateToken(user)).thenReturn("jwt"); + + assertThat(authService.login(login("editor@example.com", PASSWORD)).mustChangePassword()).isTrue(); + } + + @Test + void temporaryPasswordWithoutExpiryLogsIn() { + user.setMustChangePwd(true); // the seeded admin: no expiry recorded + givenUserExists(); + when(jwtService.generateToken(user)).thenReturn("jwt"); + + assertThat(authService.login(login("editor@example.com", PASSWORD)).token()).isEqualTo("jwt"); + } + private void givenUserExists() { when(userRepository.findByEmailIgnoreCase("editor@example.com")).thenReturn(Optional.of(user)); } @@ -233,9 +276,11 @@ class ChangePassword { @Test void successStoresNewHashAndClearsForcedChange() { user.setMustChangePwd(true); + user.setTempPasswordExpiresAt(Instant.now().plus(Duration.ofHours(1))); Requests.authenticateAs(user); authService.changePassword(change(PASSWORD, "BrandNewPass9")); + assertThat(user.getTempPasswordExpiresAt()).isNull(); assertThat(passwordEncoder.matches("BrandNewPass9", user.getPasswordHash())).isTrue(); assertThat(user.getPasswordHash()).isNotEqualTo("BrandNewPass9"); @@ -344,6 +389,7 @@ void resetEmailsToOneAddressAreLimitedWithoutChangingTheAnswer() { @Test void validTokenResetsPasswordOnceAndClearsForcedChange() { user.setMustChangePwd(true); + user.setTempPasswordExpiresAt(Instant.now().minusSeconds(1)); PasswordResetToken token = new PasswordResetToken("tok", user, Instant.now().plusSeconds(600)); when(passwordResetTokenRepository.findByToken(TokenHashing.sha256Hex("tok"))).thenReturn(Optional.of(token)); @@ -351,6 +397,7 @@ void validTokenResetsPasswordOnceAndClearsForcedChange() { assertThat(passwordEncoder.matches("BrandNewPass9", user.getPasswordHash())).isTrue(); assertThat(user.getMustChangePwd()).isFalse(); + assertThat(user.getTempPasswordExpiresAt()).isNull(); assertThat(token.isUsed()).isTrue(); verify(passwordResetTokenRepository).save(token); } diff --git a/src/test/java/com/mailengine/mailengine/service/TrackingServiceAppleProxyTest.java b/src/test/java/com/mailengine/mailengine/service/TrackingServiceAppleProxyTest.java new file mode 100644 index 0000000..01d89fe --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/service/TrackingServiceAppleProxyTest.java @@ -0,0 +1,25 @@ +package com.mailengine.mailengine.service; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.assertj.core.api.Assertions.assertThat; + +/** Apple Mail Privacy Protection opens are recognised by Apple's network, 17.0.0.0/8. */ +class TrackingServiceAppleProxyTest { + + @ParameterizedTest + @ValueSource(strings = {"17.58.63.1", "17.0.0.0", "17.255.255.255", " 17.1.2.3 "}) + void addressesInApplesNetworkAreFlagged(String ip) { + assertThat(TrackingService.isAppleMailProxy(ip)).isTrue(); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {"171.1.2.3", "117.1.2.3", "8.8.8.8", "16.255.255.255", "18.0.0.0", + "2620:149::1", "17.1.2", "17.1.2.3.4", "17.1.2.256", "17.a.b.c", "17..2.3", "junk"}) + void otherAddressesAreNot(String ip) { + assertThat(TrackingService.isAppleMailProxy(ip)).isFalse(); + } +} diff --git a/src/test/java/com/mailengine/mailengine/service/UserServiceTest.java b/src/test/java/com/mailengine/mailengine/service/UserServiceTest.java index fba41ac..e3c3d99 100644 --- a/src/test/java/com/mailengine/mailengine/service/UserServiceTest.java +++ b/src/test/java/com/mailengine/mailengine/service/UserServiceTest.java @@ -29,12 +29,15 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +import java.time.Duration; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.within; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -150,7 +153,9 @@ void createsVerifiedUserWhoMustChangePasswordAndEmailsTempPassword() { ArgumentCaptor tempPassword = ArgumentCaptor.forClass(String.class); verify(emailService).sendInvitationEmail(eq("new.person@example.com"), tempPassword.capture(), eq(admin.getName())); - assertThat(tempPassword.getValue()).hasSizeGreaterThanOrEqualTo(8); + assertThat(tempPassword.getValue()).matches("[A-HJ-NP-Za-km-z2-9]{16}"); + assertThat(invited.getTempPasswordExpiresAt()) + .isCloseTo(Instant.now().plus(Duration.ofDays(7)), within(Duration.ofMinutes(1))); assertThat(invited.getPasswordHash()) .as("temp password must be stored hashed, never in plain text") .isNotEqualTo(tempPassword.getValue()); @@ -248,6 +253,9 @@ void adminResetIssuesHashedTempPasswordAndForcesChange() { assertThat(target.getPasswordHash()).isNotEqualTo(oldHash).isNotEqualTo(temp.getValue()); assertThat(passwordEncoder.matches(temp.getValue(), target.getPasswordHash())).isTrue(); assertThat(target.getMustChangePwd()).isTrue(); + assertThat(temp.getValue()).matches("[A-HJ-NP-Za-km-z2-9]{16}"); + assertThat(target.getTempPasswordExpiresAt()) + .isCloseTo(Instant.now().plus(Duration.ofHours(24)), within(Duration.ofMinutes(1))); } @Test diff --git a/src/test/java/com/mailengine/mailengine/util/TemporaryPasswordsTest.java b/src/test/java/com/mailengine/mailengine/util/TemporaryPasswordsTest.java new file mode 100644 index 0000000..bdd0b8a --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/util/TemporaryPasswordsTest.java @@ -0,0 +1,37 @@ +package com.mailengine.mailengine.util; + +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.HashSet; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +class TemporaryPasswordsTest { + + @Test + void passwordsAreSixteenUnambiguousCharacters() { + for (int i = 0; i < 200; i++) { + String password = TemporaryPasswords.generate(); + assertThat(password).hasSize(16).doesNotContainAnyWhitespaces(); + assertThat(password.chars()).allMatch(c -> TemporaryPasswords.ALPHABET.indexOf(c) >= 0); + } + assertThat(TemporaryPasswords.ALPHABET).doesNotContain("0", "O", "1", "l", "I"); + } + + @Test + void passwordsDoNotRepeat() { + Set seen = new HashSet<>(); + for (int i = 0; i < 1000; i++) { + assertThat(seen.add(TemporaryPasswords.generate())).isTrue(); + } + } + + @Test + void validityIsDescribedForTheEmails() { + assertThat(TemporaryPasswords.describe(TemporaryPasswords.INVITE_VALIDITY)).isEqualTo("7 days"); + assertThat(TemporaryPasswords.describe(TemporaryPasswords.ADMIN_RESET_VALIDITY)).isEqualTo("24 hours"); + assertThat(TemporaryPasswords.describe(Duration.ofHours(1))).isEqualTo("1 hour"); + } +}