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

Expand Down Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
11 changes: 11 additions & 0 deletions src/main/java/com/mailengine/mailengine/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -21,4 +22,25 @@ public interface RecipientRepository extends JpaRepository<Recipient, Long> {

@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<Recipient> searchByRecipientListId(@Param("listId") Long listId, @Param("search") String search, Pageable pageable);
}

/**
* 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<Recipient> findEligibleForCampaign(@Param("campaignId") Long campaignId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -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);

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

// ─────────────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -209,31 +207,9 @@ public void resumeCampaign(Long campaignId) {
// PRIVATE HELPERS
// ─────────────────────────────────────────────────────────────────────────────

/** Active, not suppressed, each address once: see {@link RecipientRepository#findEligibleForCampaign}. */
private List<Recipient> collectEligibleRecipients(Campaign campaign) {
List<CampaignRecipientList> campaignLists =
campaignRecipientListRepository.findByCampaignId(campaign.getId());

Set<String> seenEmails = new HashSet<>();
List<Recipient> eligible = new ArrayList<>();

for (CampaignRecipientList crl : campaignLists) {
List<RecipientListMember> 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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ public class TrackingService {
*
* <p>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
Expand All @@ -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());
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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
* <p>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.
*
* <p>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
* <p>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;
}

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