From ae71b57907748823dcd29f2271e94a0e56b1f2e2 Mon Sep 17 00:00:00 2001 From: op-techy Date: Thu, 3 Dec 2026 00:45:01 +0100 Subject: [PATCH] fix: user deletion, column mapping, upload and test-send validation, hashed tokens - Deleting a user who created templates or campaigns no longer fails with 409: created_by (and invited_by) are set to NULL (V24). - Column mapping works: an upload whose headers aren't email/first_name/last_name keeps its file (pending_upload_files, cleaned up after a day) and reports needsMapping with a first-row preview. POST /api/uploads/{id}/map imports it with the mapping and returns the real counts; bad mappings get 400, an imported upload 409, a full import pool 503. - POST /api/templates/upload-html accepts only .html/.htm text files (else 400). - Campaign test send validates testEmails (non-empty, valid addresses). - Password reset and email verification tokens are stored as SHA-256 hashes; existing tokens are cleared by V25. - The mock email sender logs the email's text and links, so the invite's temporary password is visible in mock mode. --- README.md | 13 +- .../controller/CampaignController.java | 5 +- .../controller/UploadController.java | 19 +- .../dto/response/UploadStatusResponse.java | 8 +- .../mailengine/entity/PendingUploadFile.java | 34 +++ .../repository/FileUploadRepository.java | 9 + .../PendingUploadFileRepository.java | 16 ++ .../mailengine/security/TokenHashing.java | 26 ++ .../mailengine/service/AuthService.java | 10 +- .../mailengine/service/FileUploadService.java | 232 +++++++++++++++--- .../mailengine/service/MockEmailSender.java | 40 ++- .../service/PendingUploadCleanup.java | 24 ++ .../mailengine/service/TemplateService.java | 19 +- .../V24__keep_content_when_user_deleted.sql | 14 ++ .../V25__hash_tokens_and_pending_uploads.sql | 14 ++ .../ColumnMappingIntegrationTest.java | 170 +++++++++++++ .../SweepFixesIntegrationTest.java | 67 +++++ .../mailengine/security/SecurityWebTest.java | 2 + .../mailengine/service/AuthServiceTest.java | 26 +- .../service/FileUploadServiceTest.java | 4 +- .../service/MockEmailSenderTextTest.java | 30 +++ 21 files changed, 718 insertions(+), 64 deletions(-) create mode 100644 src/main/java/com/mailengine/mailengine/entity/PendingUploadFile.java create mode 100644 src/main/java/com/mailengine/mailengine/repository/PendingUploadFileRepository.java create mode 100644 src/main/java/com/mailengine/mailengine/security/TokenHashing.java create mode 100644 src/main/java/com/mailengine/mailengine/service/PendingUploadCleanup.java create mode 100644 src/main/resources/db/migration/V24__keep_content_when_user_deleted.sql create mode 100644 src/main/resources/db/migration/V25__hash_tokens_and_pending_uploads.sql create mode 100644 src/test/java/com/mailengine/mailengine/integration/ColumnMappingIntegrationTest.java create mode 100644 src/test/java/com/mailengine/mailengine/integration/SweepFixesIntegrationTest.java create mode 100644 src/test/java/com/mailengine/mailengine/service/MockEmailSenderTextTest.java diff --git a/README.md b/README.md index 2a2190c..763ec31 100644 --- a/README.md +++ b/README.md @@ -518,7 +518,7 @@ Authorization: Bearer | Method | Path | Description | |---|---|---| | GET | `/{uploadId}/status` | Poll file import progress and stats | -| POST | `/{uploadId}/map` | Apply column mapping after initial upload | +| POST | `/{uploadId}/map` | Import an upload whose headers didn't match, using a column mapping (see File Import) | ### Templates — `/api/templates` @@ -530,7 +530,7 @@ Authorization: Bearer | PUT | `/{id}` | Update template | | DELETE | `/{id}` | Delete template | | POST | `/{id}/duplicate` | Clone template (appends " (Copy)") | -| POST | `/upload-html` | Parse a raw `.html` file, returns the HTML string | +| POST | `/upload-html` | Read an `.html`/`.htm` file (UTF-8), returns the HTML string; other files get 400 | ### Image Upload — `/api/upload` @@ -699,6 +699,15 @@ Once an email is in the suppression list it can never be imported or sent to aga - **XLS:** legacy format, at most 65,536 rows. Formulas are evaluated. - **Columns:** `email`, `first_name` and `last_name` are required. Case and order don't matter, and extra columns are ignored. +**Column mapping.** If the headers don't include those three, nothing is imported yet: the upload ends `failed` with `needsMapping: true`, and the status lists the file's `columns` with a `preview` of the first row's values. The file is kept (for up to a day) until it is mapped: + +``` +POST /api/uploads/{uploadId}/map +{"mapping": {"E-mail": "email", "Given Name": "first_name", "Surname": "last_name", "Notes": "ignore"}} +``` + +Keys are the file's headers (any case) and values the fields; the other direction (`{"email": "E-mail", ...}`) works too. The import then runs with the mapping and the response has the real counts (`imported`, `skipped`, `duplicates`). A mapping naming a column that isn't in the file, or leaving a field unmapped, gets 400 and the upload can be mapped again; an upload that is already imported gets 409. + **Per row**, each row is handled on its own, so one bad row never fails the file: ``` diff --git a/src/main/java/com/mailengine/mailengine/controller/CampaignController.java b/src/main/java/com/mailengine/mailengine/controller/CampaignController.java index fb23b58..69c016d 100644 --- a/src/main/java/com/mailengine/mailengine/controller/CampaignController.java +++ b/src/main/java/com/mailengine/mailengine/controller/CampaignController.java @@ -9,6 +9,7 @@ import com.mailengine.mailengine.service.CampaignService; import jakarta.validation.Valid; import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; @@ -115,7 +116,7 @@ public ResponseEntity> sendCampaign(@PathVariable Long id) { @PostMapping("/{id}/test") public ResponseEntity> sendTestEmail( @PathVariable Long id, - @RequestBody TestEmailRequest request + @Valid @RequestBody TestEmailRequest request ) { campaignSendingService.sendTestEmail(id, request.testEmails()); return ResponseEntity.ok(Map.of("message", "Test email sent")); @@ -160,6 +161,6 @@ public ResponseEntity> resumeCampaign(@PathVariable Long id) // Request body for the test send endpoint. // A Java record keeps it concise — no need for a separate file. record TestEmailRequest( - @NotEmpty List<@Email String> testEmails + @NotEmpty List<@NotBlank @Email String> testEmails ) {} } \ No newline at end of file diff --git a/src/main/java/com/mailengine/mailengine/controller/UploadController.java b/src/main/java/com/mailengine/mailengine/controller/UploadController.java index c48b447..bf512d2 100644 --- a/src/main/java/com/mailengine/mailengine/controller/UploadController.java +++ b/src/main/java/com/mailengine/mailengine/controller/UploadController.java @@ -4,10 +4,14 @@ import com.mailengine.mailengine.entity.FileUpload; import com.mailengine.mailengine.exception.BadRequestException; import com.mailengine.mailengine.exception.ResourceNotFoundException; +import com.mailengine.mailengine.entity.enums.UploadStatus; import com.mailengine.mailengine.repository.FileUploadRepository; +import com.mailengine.mailengine.repository.PendingUploadFileRepository; import com.mailengine.mailengine.service.FileUploadService; import com.mailengine.mailengine.service.TemplateService; import lombok.RequiredArgsConstructor; +import org.springframework.core.task.TaskRejectedException; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -29,6 +33,7 @@ public class UploadController { private final TemplateService templateService; private final FileUploadService fileUploadService; private final FileUploadRepository fileUploadRepository; + private final PendingUploadFileRepository pendingUploadFileRepository; @PostMapping("/upload/image") public ResponseEntity> uploadImage( @@ -73,7 +78,8 @@ public ResponseEntity getUploadStatus(@PathVariable Long u upload.getTotalRows(), upload.getImportedRows(), upload.getSkippedRows(), - upload.getDuplicateRows() + upload.getDuplicateRows(), + upload.getStatus() == UploadStatus.failed && pendingUploadFileRepository.existsById(uploadId) )); } @@ -92,7 +98,7 @@ public ResponseEntity getUploadStatus(@PathVariable Long u * @throws BadRequestException if the "mapping" key in the request body is null or empty */ @PostMapping("/uploads/{uploadId}/map") - public ResponseEntity> applyColumnMapping( + public ResponseEntity applyColumnMapping( @PathVariable Long uploadId, @RequestBody Map> body) { @@ -101,7 +107,14 @@ public ResponseEntity> applyColumnMapping( throw new BadRequestException("mapping is required"); } - FileUploadService.ImportResult result = fileUploadService.applyMapping(uploadId, mapping); + FileUploadService.ImportResult result; + try { + result = fileUploadService.applyMapping(uploadId, mapping); + } catch (TaskRejectedException busy) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(Map.of( + "uploadId", uploadId, + "message", "Too many imports are in progress. Please try again in a few minutes.")); + } return ResponseEntity.ok(Map.of( "imported", result.imported() != null ? result.imported() : 0, diff --git a/src/main/java/com/mailengine/mailengine/dto/response/UploadStatusResponse.java b/src/main/java/com/mailengine/mailengine/dto/response/UploadStatusResponse.java index a9e7af0..e5956fb 100644 --- a/src/main/java/com/mailengine/mailengine/dto/response/UploadStatusResponse.java +++ b/src/main/java/com/mailengine/mailengine/dto/response/UploadStatusResponse.java @@ -13,7 +13,7 @@ public class UploadStatusResponse { private UploadStatus status; - /** First 5 rows of the uploaded file for the column-mapping UI. */ + /** Each column with its value in the file's first data row, for the column-mapping UI. */ private List> preview; /** Detected column headers — frontend maps these to system fields. */ @@ -23,4 +23,10 @@ public class UploadStatusResponse { private Integer importedRows; private Integer skippedRows; private Integer duplicateRows; + + /** + * The file's headers aren't email/first_name/last_name: nothing was imported yet. Map its {@code columns} + * with POST /api/uploads/{id}/map to import it. + */ + private boolean needsMapping; } diff --git a/src/main/java/com/mailengine/mailengine/entity/PendingUploadFile.java b/src/main/java/com/mailengine/mailengine/entity/PendingUploadFile.java new file mode 100644 index 0000000..1c1d289 --- /dev/null +++ b/src/main/java/com/mailengine/mailengine/entity/PendingUploadFile.java @@ -0,0 +1,34 @@ +package com.mailengine.mailengine.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** The file of an upload waiting for its columns to be mapped (see FileUploadService#applyMapping). */ +@Getter +@Setter +@NoArgsConstructor +@Entity +@Table(name = "pending_upload_files") +public class PendingUploadFile { + + @Id + @Column(name = "upload_id") + private Long uploadId; + + @Column(name = "file_name") + private String fileName; + + @Column(name = "content", nullable = false) + private byte[] content; + + public PendingUploadFile(Long uploadId, String fileName, byte[] content) { + this.uploadId = uploadId; + this.fileName = fileName; + this.content = content; + } +} diff --git a/src/main/java/com/mailengine/mailengine/repository/FileUploadRepository.java b/src/main/java/com/mailengine/mailengine/repository/FileUploadRepository.java index 9ec4e2b..85cf2aa 100644 --- a/src/main/java/com/mailengine/mailengine/repository/FileUploadRepository.java +++ b/src/main/java/com/mailengine/mailengine/repository/FileUploadRepository.java @@ -18,4 +18,13 @@ public interface FileUploadRepository extends JpaRepository { @Modifying @Query("update FileUpload u set u.status = :to where u.status = :from") int updateStatus(@Param("from") UploadStatus from, @Param("to") UploadStatus to); + + /** + * Moves one upload from {@code from} to {@code to} only if it is still in {@code from}; returns 1 if this + * caller won. Two requests to map the same upload at once: only one of them gets to import it. + */ + @Transactional + @Modifying + @Query("update FileUpload u set u.status = :to where u.id = :id and u.status = :from") + int claim(@Param("id") Long id, @Param("from") UploadStatus from, @Param("to") UploadStatus to); } diff --git a/src/main/java/com/mailengine/mailengine/repository/PendingUploadFileRepository.java b/src/main/java/com/mailengine/mailengine/repository/PendingUploadFileRepository.java new file mode 100644 index 0000000..b78448a --- /dev/null +++ b/src/main/java/com/mailengine/mailengine/repository/PendingUploadFileRepository.java @@ -0,0 +1,16 @@ +package com.mailengine.mailengine.repository; + +import com.mailengine.mailengine.entity.PendingUploadFile; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.transaction.annotation.Transactional; + +public interface PendingUploadFileRepository extends JpaRepository { + + /** Files nobody mapped within a day (the comparison runs in the database, in its own clock). */ + @Transactional + @Modifying + @Query(value = "DELETE FROM pending_upload_files WHERE created_at < NOW() - INTERVAL '1 day'", nativeQuery = true) + int deleteOlderThanOneDay(); +} diff --git a/src/main/java/com/mailengine/mailengine/security/TokenHashing.java b/src/main/java/com/mailengine/mailengine/security/TokenHashing.java new file mode 100644 index 0000000..6809f16 --- /dev/null +++ b/src/main/java/com/mailengine/mailengine/security/TokenHashing.java @@ -0,0 +1,26 @@ +package com.mailengine.mailengine.security; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** + * One-time tokens (password reset, email verification) are stored as their SHA-256, never as sent: + * someone who can read the database cannot use what they find there. The tokens are long random + * values, so a plain (unsalted) hash is enough to look them up by. + */ +public final class TokenHashing { + + private TokenHashing() { + } + + public static String sha256Hex(String token) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is always available", e); + } + } +} diff --git a/src/main/java/com/mailengine/mailengine/service/AuthService.java b/src/main/java/com/mailengine/mailengine/service/AuthService.java index 3d95abe..b806b8a 100644 --- a/src/main/java/com/mailengine/mailengine/service/AuthService.java +++ b/src/main/java/com/mailengine/mailengine/service/AuthService.java @@ -12,6 +12,7 @@ import com.mailengine.mailengine.repository.UserRepository; import com.mailengine.mailengine.security.JwtService; import com.mailengine.mailengine.security.SecurityUtils; +import com.mailengine.mailengine.security.TokenHashing; import lombok.RequiredArgsConstructor; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @@ -42,7 +43,7 @@ public void register(RegisterRequest request) { } public void verifyEmail(String token) { - EmailVerificationToken evt = verificationTokenRepository.findByToken(token) + EmailVerificationToken evt = verificationTokenRepository.findByToken(TokenHashing.sha256Hex(token)) .orElseThrow(() -> new BadRequestException("Invalid or expired verification link")); if (evt.isUsed() || evt.isExpired()) { @@ -129,14 +130,15 @@ public void forgotPassword(ForgotPasswordRequest request) { userRepository.findByEmailIgnoreCase(normalizeEmail(request.getEmail())).ifPresent(user -> { passwordResetTokenRepository.deleteByUserId(user.getId()); String token = UUID.randomUUID().toString(); - passwordResetTokenRepository.save( - new PasswordResetToken(token, user, Instant.now().plus(1, ChronoUnit.HOURS))); + // Only the hash is stored; the token itself exists only in the email + passwordResetTokenRepository.save(new PasswordResetToken( + TokenHashing.sha256Hex(token), user, Instant.now().plus(1, ChronoUnit.HOURS))); emailService.sendPasswordResetEmail(user.getEmail(), token); }); } public void resetPassword(ResetPasswordRequest request) { - PasswordResetToken prt = passwordResetTokenRepository.findByToken(request.getToken()) + PasswordResetToken prt = passwordResetTokenRepository.findByToken(TokenHashing.sha256Hex(request.getToken())) .orElseThrow(() -> new BadRequestException("Invalid or expired reset link")); if (prt.isUsed() || prt.isExpired()) { throw new BadRequestException("Reset link has expired or already been used"); diff --git a/src/main/java/com/mailengine/mailengine/service/FileUploadService.java b/src/main/java/com/mailengine/mailengine/service/FileUploadService.java index dba22f4..0a6b2be 100644 --- a/src/main/java/com/mailengine/mailengine/service/FileUploadService.java +++ b/src/main/java/com/mailengine/mailengine/service/FileUploadService.java @@ -5,10 +5,11 @@ import com.mailengine.mailengine.entity.enums.RecipientStatus; import com.mailengine.mailengine.entity.enums.UploadStatus; import com.mailengine.mailengine.exception.BadRequestException; +import com.mailengine.mailengine.exception.ConflictException; +import com.mailengine.mailengine.exception.ResourceNotFoundException; import com.mailengine.mailengine.repository.*; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; -import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.poi.openxml4j.opc.OPCPackage; @@ -19,6 +20,9 @@ import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler; import org.apache.poi.xssf.usermodel.XSSFComment; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @@ -30,6 +34,8 @@ import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; import java.util.regex.Pattern; /** @@ -59,48 +65,152 @@ public class FileUploadService { private static final List REQUIRED_COLUMNS = List.of("email", "first_name", "last_name"); + /** Mapping values that mean "don't import this column". */ + private static final Set IGNORE = Set.of("", "ignore", "skip", "none"); + + /** Longest value shown per column in the upload preview. */ + private static final int PREVIEW_LENGTH = 100; + private final FileUploadRepository fileUploadRepository; private final RecipientRepository recipientRepository; private final RecipientListRepository recipientListRepository; private final RecipientListMemberRepository recipientListMemberRepository; private final SuppressionListRepository suppressionListRepository; + private final PendingUploadFileRepository pendingUploadFileRepository; private final DataFormatter dataFormatter = new DataFormatter(); + /** Mapped imports run on the same bounded pool as uploads (see {@link #applyMapping}). */ + @Autowired + @Qualifier(ImportExecutorConfig.IMPORT_EXECUTOR) + private AsyncTaskExecutor importExecutor; + @Async(ImportExecutorConfig.IMPORT_EXECUTOR) public void processImport(Long fileUploadId, byte[] fileContent, String originalFilename, Long listId) { + runImport(fileUploadId, fileContent, originalFilename, listId, null, null); + } + + /** + * Imports a file into the list. {@code fieldToColumn} (email/first_name/last_name -> file column) is given + * when the user mapped the columns; without it the file's headers must be those names. A file whose headers + * don't match is kept for {@link #applyMapping}. Returns the run, or null if it could not even start. + */ + private ImportRun runImport(Long fileUploadId, byte[] fileContent, String originalFilename, Long listId, + Map fieldToColumn, Map requestedMapping) { try { + ImportRun run = start(fileUploadId, listId); + run.fieldToColumn = fieldToColumn; + if (requestedMapping != null) run.upload.setColumnMapping(new LinkedHashMap<>(requestedMapping)); String name = originalFilename == null ? "" : originalFilename.toLowerCase(Locale.ROOT); if (name.endsWith(".xlsx")) { - doProcessXlsx(fileUploadId, fileContent, listId); + doProcessXlsx(run, fileContent); } else if (name.endsWith(".xls")) { - doProcessXls(fileUploadId, fileContent, listId); + doProcessXls(run, fileContent); } else { - doProcessCsv(fileUploadId, fileContent, listId); + doProcessCsv(run, fileContent); } + if (run.needsMapping) keepForMapping(fileUploadId, originalFilename, fileContent); + return run; } catch (RuntimeException | Error e) { // Anything the per-format handlers couldn't record themselves (e.g. a failure before the // import started, or an Error): make sure the upload doesn't stay 'processing'. log.error("Import of upload {} failed unexpectedly", fileUploadId, e); markFailed(fileUploadId); if (e instanceof Error error) throw error; + return null; + } + } + + private void keepForMapping(Long fileUploadId, String fileName, byte[] content) { + try { + pendingUploadFileRepository.save(new PendingUploadFile(fileUploadId, fileName, content)); + log.info("Upload {} needs its columns mapped; file kept until then", fileUploadId); + } catch (RuntimeException e) { + log.error("Could not keep the file of upload {} for column mapping", fileUploadId, e); } } - @Transactional + /** + * Imports an upload whose headers didn't match, using the user's column mapping. Accepts + * {@code {"E-mail": "email", ...}} (file column -> field) or {@code {"email": "E-mail", ...}} (field -> file + * column); a column mapped to "" or "ignore" is left out. Runs on the import pool and waits for the result. + */ public ImportResult applyMapping(Long uploadId, Map mapping) { FileUpload upload = fileUploadRepository.findById(uploadId) - .orElseThrow(() -> new BadRequestException("Upload not found")); - upload.setColumnMapping(new java.util.HashMap<>(mapping)); - fileUploadRepository.save(upload); - return new ImportResult( - upload.getTotalRows(), upload.getImportedRows(), - upload.getSkippedRows(), upload.getDuplicateRows()); + .orElseThrow(() -> new ResourceNotFoundException("Upload not found")); + PendingUploadFile file = pendingUploadFileRepository.findById(uploadId).orElseThrow(() -> + upload.getStatus() == UploadStatus.completed + ? new ConflictException("This upload has already been imported") + : new BadRequestException("This upload has no file waiting for column mapping. Upload the file again.")); + Set columns = upload.getColumnPreview() == null ? Set.of() : upload.getColumnPreview().keySet(); + Map fieldToColumn = toFieldToColumn(mapping, columns); + Long listId = upload.getRecipientList().getId(); + + if (fileUploadRepository.claim(uploadId, UploadStatus.failed, UploadStatus.processing) == 0) { + throw new ConflictException("This upload is already being imported"); + } + Future result; + try { + result = importExecutor.submit(() -> + runImport(uploadId, file.getContent(), file.getFileName(), listId, fieldToColumn, mapping)); + } catch (RuntimeException busy) { // TaskRejectedException: the import pool and its queue are full + fileUploadRepository.claim(uploadId, UploadStatus.processing, UploadStatus.failed); + throw busy; + } + ImportRun run; + try { + run = result.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while importing upload " + uploadId, e); + } catch (ExecutionException e) { + throw new IllegalStateException("Import of upload " + uploadId + " failed", e.getCause()); + } + if (run != null && run.upload.getStatus() == UploadStatus.completed) { + pendingUploadFileRepository.deleteById(uploadId); + } + FileUpload done = fileUploadRepository.findById(uploadId).orElseThrow(); + return new ImportResult(done.getTotalRows(), done.getImportedRows(), done.getSkippedRows(), done.getDuplicateRows()); + } + + /** Turns the user's mapping into field -> normalized file column, or explains what's wrong with it. */ + private static Map toFieldToColumn(Map mapping, Set columns) { + Map fieldToColumn = new LinkedHashMap<>(); + for (Map.Entry entry : mapping.entrySet()) { + String key = normalizeHeader(entry.getKey()); + String value = normalizeHeader(entry.getValue()); + String field; + String column; + if (columns.contains(key) && (REQUIRED_COLUMNS.contains(value) || IGNORE.contains(value))) { + field = value; // file column -> field + column = key; + } else if (REQUIRED_COLUMNS.contains(key) && (columns.contains(value) || IGNORE.contains(value))) { + field = key; // field -> file column + column = value; + } else { + throw new BadRequestException(String.format( + "Cannot map '%s' to '%s'. Columns in the file: %s. Fields: %s", + entry.getKey(), entry.getValue(), String.join(", ", columns), String.join(", ", REQUIRED_COLUMNS))); + } + if (IGNORE.contains(field) || IGNORE.contains(column)) continue; + if (fieldToColumn.putIfAbsent(field, column) != null) { + throw new BadRequestException("More than one column is mapped to '" + field + "'"); + } + } + List missing = REQUIRED_COLUMNS.stream() + .filter(f -> !fieldToColumn.containsKey(f) && !columns.contains(f)).toList(); + if (!missing.isEmpty()) { + throw new BadRequestException("Map a column to each of: " + String.join(", ", missing)); + } + return fieldToColumn; + } + + private static String normalizeHeader(String header) { + return header == null ? "" : header.replace("\uFEFF", "").trim().toLowerCase(Locale.ROOT); } // ── Formats ───────────────────────────────────────────────────────────── - private void doProcessCsv(Long fileUploadId, byte[] fileContent, Long listId) { - ImportRun run = start(fileUploadId, listId); + private void doProcessCsv(ImportRun run, byte[] fileContent) { // Excel's "CSV UTF-8" starts with a byte-order mark; skip it so the first header reads "email" int offset = hasUtf8Bom(fileContent) ? 3 : 0; try (CSVReader reader = new CSVReaderBuilder(new InputStreamReader( @@ -116,10 +226,9 @@ private void doProcessCsv(Long fileUploadId, byte[] fileContent, Long listId) { String[] row = next; run.row(i -> i < row.length ? row[i] : null); } - complete(run); + end(run); } catch (Exception e) { - log.error("CSV import failed for upload {}", fileUploadId, e); - fail(run); + failed(run, e, "CSV"); } } @@ -128,8 +237,7 @@ private void doProcessCsv(Long fileUploadId, byte[] fileContent, Long listId) { * file has (the previous WorkbookFactory approach loaded the whole sheet and ran out of heap * at ~100-200k rows, far below the 10 MB upload limit). Formula cells yield their cached result. */ - private void doProcessXlsx(Long fileUploadId, byte[] fileContent, Long listId) { - ImportRun run = start(fileUploadId, listId); + private void doProcessXlsx(ImportRun run, byte[] fileContent) { try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(fileContent))) { XSSFReader reader = new XSSFReader(pkg); Iterator sheets = reader.getSheetsData(); @@ -143,16 +251,14 @@ private void doProcessXlsx(Long fileUploadId, byte[] fileContent, Long listId) { parser.parse(new InputSource(sheet)); } if (!collector.headerSeen) throw new IllegalArgumentException("Excel file has no header row"); - complete(run); + end(run); } catch (Exception e) { - log.error("Excel import failed for upload {}", fileUploadId, e); - fail(run); + failed(run, e, "Excel"); } } /** Legacy .xls (max 65,536 rows, so loading the workbook is fine). Formulas are evaluated. */ - private void doProcessXls(Long fileUploadId, byte[] fileContent, Long listId) { - ImportRun run = start(fileUploadId, listId); + private void doProcessXls(ImportRun run, byte[] fileContent) { try (Workbook wb = WorkbookFactory.create(new ByteArrayInputStream(fileContent))) { if (wb.getNumberOfSheets() == 0) throw new IllegalArgumentException("No sheets found in Excel file"); Sheet sheet = wb.getSheetAt(0); @@ -175,10 +281,9 @@ private void doProcessXls(Long fileUploadId, byte[] fileContent, Long listId) { return cell == null ? null : dataFormatter.formatCellValue(cell, evaluator); }); } - complete(run); + end(run); } catch (Exception e) { - log.error("Excel import failed for upload {}", fileUploadId, e); - fail(run); + failed(run, e, "Excel"); } } @@ -279,6 +384,23 @@ private void fail(ImportRun run) { finish(run, UploadStatus.failed); } + /** End of the file: a file whose columns still need mapping is 'failed' until the user maps them. */ + private void end(ImportRun run) { + if (run.needsMapping) fail(run); + else complete(run); + } + + private void failed(ImportRun run, Exception e, String fileType) { + for (Throwable t = e; t != null; t = t.getCause()) { + if (t instanceof StopReading) { // first row read for the preview of a file that needs mapping + end(run); + return; + } + } + log.error("{} import failed for upload {}", fileType, run.upload.getId(), e); + fail(run); + } + private void finish(ImportRun run, UploadStatus status) { // Rows imported before a failure stay imported, so the count must reflect them either way recipientListRepository.refreshRecipientCount(run.listId); @@ -318,7 +440,12 @@ private final class ImportRun { final RecipientList list; final Long listId; final ImportStats stats = new ImportStats(); + /** email/first_name/last_name -> normalized file column, when the user mapped the columns. */ + Map fieldToColumn; + /** The headers don't contain email/first_name/last_name and no mapping was given. */ + boolean needsMapping; private Map columns = Map.of(); + private List headerNames = List.of(); ImportRun(FileUpload upload, RecipientList list, Long listId) { this.upload = upload; @@ -329,25 +456,55 @@ private final class ImportRun { void setHeaders(List headers, String fileType) { Map index = new LinkedHashMap<>(); Map preview = new LinkedHashMap<>(); + List names = new ArrayList<>(); for (int i = 0; i < headers.size(); i++) { - String h = headers.get(i) == null ? "" : headers.get(i).replace("", "").trim().toLowerCase(Locale.ROOT); + String h = normalizeHeader(headers.get(i)); index.putIfAbsent(h, i); - preview.put(h, ""); + preview.putIfAbsent(h, ""); + names.add(h); } upload.setColumnPreview(preview); - for (String required : REQUIRED_COLUMNS) { - if (!index.containsKey(required)) { - throw new BadRequestException(String.format( - "%s file is missing required column: '%s'. Expected columns: email, first_name, last_name", - fileType, required)); + headerNames = names; + if (fieldToColumn != null) { + for (Map.Entry mapped : fieldToColumn.entrySet()) { + Integer column = index.get(mapped.getValue()); + if (column == null) { + throw new BadRequestException("Column '" + mapped.getValue() + "' is not in the file"); + } + index.put(mapped.getKey(), column); } } + List missing = REQUIRED_COLUMNS.stream().filter(r -> !index.containsKey(r)).toList(); + if (!missing.isEmpty()) { + if (fieldToColumn != null) { + throw new BadRequestException("Map a column to each of: " + String.join(", ", missing)); + } + log.info("{} upload {} is missing column(s) {}: waiting for a column mapping", + fileType, upload.getId(), missing); + needsMapping = true; + } columns = index; } + /** Shows the first data row's values next to each header, for the column-mapping screen. */ + private void fillPreview(java.util.function.IntFunction valueAt) { + Map preview = new LinkedHashMap<>(); + for (int i = 0; i < headerNames.size(); i++) { + String v = valueAt.apply(i); + v = v == null ? "" : v.trim(); + preview.putIfAbsent(headerNames.get(i), v.length() > PREVIEW_LENGTH ? v.substring(0, PREVIEW_LENGTH) : v); + } + upload.setColumnPreview(preview); + } + /** Handles one data row; a failure is logged and counted as skipped, never fatal. */ void row(java.util.function.IntFunction valueAt) { + if (needsMapping) { + fillPreview(valueAt); + throw StopReading.INSTANCE; // nothing is imported until the columns are mapped + } stats.totalRows++; + if (stats.totalRows == 1) fillPreview(valueAt); String email = value(valueAt, "email"); try { processRow(this, email, value(valueAt, "first_name"), value(valueAt, "last_name")); @@ -406,6 +563,15 @@ public void endRow(int rowNum) { } } + /** Stops reading a file once its preview row is read, when its columns need mapping first. */ + private static final class StopReading extends RuntimeException { + static final StopReading INSTANCE = new StopReading(); + + private StopReading() { + super("columns need mapping", null, false, false); + } + } + private static class ImportStats { int totalRows, imported, skipped, duplicates; } diff --git a/src/main/java/com/mailengine/mailengine/service/MockEmailSender.java b/src/main/java/com/mailengine/mailengine/service/MockEmailSender.java index 311aa44..9c5823c 100644 --- a/src/main/java/com/mailengine/mailengine/service/MockEmailSender.java +++ b/src/main/java/com/mailengine/mailengine/service/MockEmailSender.java @@ -5,7 +5,13 @@ import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * A no-op {@link EmailSender} implementation for local development and testing. @@ -42,13 +48,37 @@ public String send(String toEmail, String fromName, String fromEmail, log.info("From: {} <{}>", fromName, fromEmail); log.info("Subject: {}", subject); log.info("HTML Length: {} characters", htmlContent.length()); - // Log only the first 200 characters to avoid flooding the log - String snippet = htmlContent.length() > 200 - ? htmlContent.substring(0, 200) + "..." - : htmlContent; - log.info("HTML Snippet: {}", snippet); + // The readable text and the links, so a developer can use what the email carries (an invite's + // temporary password, a reset link) without a mail server. Development only: never run with + // mock-email where real people get emails. + log.info("Text: {}", textOf(htmlContent)); + List links = linksOf(htmlContent); + if (!links.isEmpty()) log.info("Links: {}", String.join(" ", links)); log.info("======================================"); // Return a unique fake message ID so the worker can store it on the queue row return "mock-" + UUID.randomUUID(); } + + private static final int MAX_TEXT = 1000; + private static final int MAX_LINKS = 5; + private static final Pattern NON_TEXT = Pattern.compile("(?is)<(script|style|head)[^>]*>.*?"); + private static final Pattern TAG = Pattern.compile("<[^>]+>"); + private static final Pattern HREF = Pattern.compile("(?i)href\\s*=\\s*[\"']([^\"']+)[\"']"); + + static String textOf(String html) { + String text = TAG.matcher(NON_TEXT.matcher(html).replaceAll(" ")).replaceAll(" ") + .replace(" ", " ").replace("<", "<").replace(">", ">") + .replace(""", "\"").replace("'", "'").replace("&", "&") + .replaceAll("\\s+", " ").trim(); + return text.length() > MAX_TEXT ? text.substring(0, MAX_TEXT) + "..." : text; + } + + static List linksOf(String html) { + Set links = new LinkedHashSet<>(); + Matcher m = HREF.matcher(html); + while (m.find() && links.size() < MAX_LINKS) { + links.add(m.group(1).replace("&", "&")); + } + return new ArrayList<>(links); + } } diff --git a/src/main/java/com/mailengine/mailengine/service/PendingUploadCleanup.java b/src/main/java/com/mailengine/mailengine/service/PendingUploadCleanup.java new file mode 100644 index 0000000..18173c0 --- /dev/null +++ b/src/main/java/com/mailengine/mailengine/service/PendingUploadCleanup.java @@ -0,0 +1,24 @@ +package com.mailengine.mailengine.service; + +import com.mailengine.mailengine.repository.PendingUploadFileRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** Deletes files kept for column mapping that nobody mapped within a day (each can be up to 10 MB). */ +@Slf4j +@Component +@RequiredArgsConstructor +public class PendingUploadCleanup { + + private final PendingUploadFileRepository pendingUploadFileRepository; + + @Scheduled(initialDelayString = "PT5M", fixedDelayString = "PT1H") + public void deleteAbandonedFiles() { + int deleted = pendingUploadFileRepository.deleteOlderThanOneDay(); + if (deleted > 0) { + log.info("Deleted {} upload file(s) whose columns were never mapped", deleted); + } + } +} diff --git a/src/main/java/com/mailengine/mailengine/service/TemplateService.java b/src/main/java/com/mailengine/mailengine/service/TemplateService.java index 8a31347..6ca2b1b 100644 --- a/src/main/java/com/mailengine/mailengine/service/TemplateService.java +++ b/src/main/java/com/mailengine/mailengine/service/TemplateService.java @@ -4,6 +4,7 @@ import com.mailengine.mailengine.dto.response.TemplateResponse; import com.mailengine.mailengine.entity.Template; import com.mailengine.mailengine.entity.User; +import com.mailengine.mailengine.exception.BadRequestException; import com.mailengine.mailengine.exception.ResourceNotFoundException; import com.mailengine.mailengine.repository.TemplateRepository; import lombok.RequiredArgsConstructor; @@ -15,6 +16,8 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; +import java.nio.charset.StandardCharsets; +import java.util.Locale; import java.util.Map; @Slf4j @@ -73,11 +76,21 @@ public TemplateResponse duplicateTemplate(Long id) { } public String parseUploadedHtml(MultipartFile file) { + String name = file.getOriginalFilename() == null ? "" : file.getOriginalFilename().toLowerCase(Locale.ROOT); + if (!name.endsWith(".html") && !name.endsWith(".htm")) { + throw new BadRequestException("Only .html or .htm files can be uploaded as templates"); + } + byte[] bytes; try { - return new String(file.getBytes()); - } catch (Exception e) { - throw new RuntimeException("Failed to parse HTML file", e); + bytes = file.getBytes(); + } catch (java.io.IOException e) { + throw new BadRequestException("Could not read the uploaded file"); + } + // NUL bytes never occur in an HTML text file: this is a binary file with an .html name + for (byte b : bytes) { + if (b == 0) throw new BadRequestException("The uploaded file is not a text HTML file"); } + return new String(bytes, StandardCharsets.UTF_8); } public void deleteTemplate(Long id) { diff --git a/src/main/resources/db/migration/V24__keep_content_when_user_deleted.sql b/src/main/resources/db/migration/V24__keep_content_when_user_deleted.sql new file mode 100644 index 0000000..3a7ca9c --- /dev/null +++ b/src/main/resources/db/migration/V24__keep_content_when_user_deleted.sql @@ -0,0 +1,14 @@ +-- Deleting a user failed (foreign key violation, shown as a 409) as soon as they had created a template or a +-- campaign. Their templates and campaigns now stay and simply lose their creator. +ALTER TABLE templates + DROP CONSTRAINT templates_created_by_fkey, + ADD CONSTRAINT templates_created_by_fkey FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL; + +ALTER TABLE campaigns + DROP CONSTRAINT campaigns_created_by_fkey, + ADD CONSTRAINT campaigns_created_by_fkey FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL; + +-- Users this user invited keep their accounts too (UserService also clears it, this makes it hold everywhere) +ALTER TABLE users + DROP CONSTRAINT users_invited_by_fkey, + ADD CONSTRAINT users_invited_by_fkey FOREIGN KEY (invited_by) REFERENCES users (id) ON DELETE SET NULL; diff --git a/src/main/resources/db/migration/V25__hash_tokens_and_pending_uploads.sql b/src/main/resources/db/migration/V25__hash_tokens_and_pending_uploads.sql new file mode 100644 index 0000000..c9ba092 --- /dev/null +++ b/src/main/resources/db/migration/V25__hash_tokens_and_pending_uploads.sql @@ -0,0 +1,14 @@ +-- One-time tokens are now stored as their SHA-256 (see TokenHashing). Tokens issued before this change were +-- stored as sent and could be read from the database; they are removed (a reset link lives one hour, so +-- anyone affected just asks for a new one). +DELETE FROM password_reset_tokens; +DELETE FROM email_verification_tokens; + +-- An upload whose headers don't match email/first_name/last_name keeps its file here until the user maps +-- the columns (POST /api/uploads/{id}/map). Removed once imported, and after a day if never mapped. +CREATE TABLE pending_upload_files ( + upload_id BIGINT PRIMARY KEY REFERENCES file_uploads (id) ON DELETE CASCADE, + file_name VARCHAR(255), + content BYTEA NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); diff --git a/src/test/java/com/mailengine/mailengine/integration/ColumnMappingIntegrationTest.java b/src/test/java/com/mailengine/mailengine/integration/ColumnMappingIntegrationTest.java new file mode 100644 index 0000000..d45048e --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/integration/ColumnMappingIntegrationTest.java @@ -0,0 +1,170 @@ +package com.mailengine.mailengine.integration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.web.servlet.MockMvc; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; + +/** Uploads whose headers aren't email/first_name/last_name are kept and imported once the user maps them. */ +class ColumnMappingIntegrationTest extends PostgresIntegrationSupport { + + private static final String ODD_CSV = "E-mail,Given Name,Surname,Notes\n" + + "map1@example.test,Mia,One,vip\n" + + "map2@example.test,Max,Two,\n"; + + @Autowired MockMvc mvc; + @Autowired ObjectMapper json; + @Autowired JdbcTemplate jdbc; + + private long listId; + + @BeforeEach + void newList() { + jdbc.update("delete from recipients where email like 'map%@example.test'"); + listId = jdbc.queryForObject("insert into recipient_lists (name) values ('Mapping') returning id", Long.class); + } + + @Test + void oddHeadersWaitForAMappingThenImport() throws Exception { + long upload = upload("people.csv", ODD_CSV.getBytes(StandardCharsets.UTF_8), "text/csv"); + + JsonNode status = status(upload); + assertThat(status.get("status").asText()).isEqualTo("failed"); + assertThat(status.get("needsMapping").asBoolean()).isTrue(); + assertThat(status.get("columns")).extracting(JsonNode::asText) + .containsExactlyInAnyOrder("e-mail", "given name", "surname", "notes"); + assertThat(status.get("preview").get(0).get("e-mail").asText()) + .as("the mapping screen shows a sample value per column").isEqualTo("map1@example.test"); + assertThat(members()).isZero(); + + MockHttpServletResponse mapped = map(upload, Map.of("E-mail", "email", "Given Name", "first_name", + "Surname", "last_name", "Notes", "ignore")); + + assertThat(mapped.getStatus()).isEqualTo(200); + assertThat(json.readTree(mapped.getContentAsString()).get("imported").asInt()).isEqualTo(2); + assertThat(members()).isEqualTo(2); + assertThat(jdbc.queryForObject("select first_name from recipients where email = 'map1@example.test'", String.class)) + .isEqualTo("Mia"); + JsonNode after = status(upload); + assertThat(after.get("status").asText()).isEqualTo("completed"); + assertThat(after.get("needsMapping").asBoolean()).isFalse(); + assertThat(jdbc.queryForObject("select count(*) from pending_upload_files where upload_id = ?", Integer.class, upload)) + .as("the kept file is deleted once imported").isZero(); + + assertThat(map(upload, Map.of("E-mail", "email", "Given Name", "first_name", "Surname", "last_name")).getStatus()) + .as("mapping an imported upload again").isEqualTo(409); + } + + @Test + void fieldToColumnDirectionWorksToo() throws Exception { + long upload = upload("people.csv", ODD_CSV.getBytes(StandardCharsets.UTF_8), "text/csv"); + + MockHttpServletResponse mapped = map(upload, Map.of("email", "E-mail", "first_name", "Given Name", "last_name", "Surname")); + + assertThat(mapped.getStatus()).isEqualTo(200); + assertThat(members()).isEqualTo(2); + } + + @Test + void aBadMappingIsExplainedAndTheUploadCanStillBeMapped() throws Exception { + long upload = upload("people.csv", ODD_CSV.getBytes(StandardCharsets.UTF_8), "text/csv"); + + MockHttpServletResponse unknownColumn = map(upload, Map.of("Mail", "email", "Given Name", "first_name", "Surname", "last_name")); + MockHttpServletResponse missingField = map(upload, Map.of("E-mail", "email", "Given Name", "first_name")); + MockHttpServletResponse twice = map(upload, Map.of("E-mail", "email", "Notes", "email", + "Given Name", "first_name", "Surname", "last_name")); + + assertThat(unknownColumn.getStatus()).isEqualTo(400); + assertThat(unknownColumn.getContentAsString()).contains("Mail", "e-mail"); + assertThat(missingField.getStatus()).isEqualTo(400); + assertThat(missingField.getContentAsString()).contains("last_name"); + assertThat(twice.getStatus()).isEqualTo(400); + assertThat(members()).isZero(); + assertThat(map(upload, Map.of("E-mail", "email", "Given Name", "first_name", "Surname", "last_name")).getStatus()) + .isEqualTo(200); + assertThat(members()).isEqualTo(2); + } + + @Test + void excelFilesCanBeMappedToo() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + var sheet = wb.createSheet(); + String[][] rows = {{"Email Address", "First", "Last"}, {"map3@example.test", "Ava", "Three"}}; + for (int r = 0; r < rows.length; r++) { + var row = sheet.createRow(r); + for (int c = 0; c < rows[r].length; c++) row.createCell(c).setCellValue(rows[r][c]); + } + wb.write(out); + } + long upload = upload("people.xlsx", out.toByteArray(), + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + assertThat(status(upload).get("needsMapping").asBoolean()).isTrue(); + + MockHttpServletResponse mapped = map(upload, Map.of("Email Address", "email", "First", "first_name", "Last", "last_name")); + + assertThat(mapped.getStatus()).isEqualTo(200); + assertThat(members()).isEqualTo(1); + } + + @Test + void uploadsWithTheExpectedHeadersDoNotNeedMapping() throws Exception { + long upload = upload("ok.csv", "email,first_name,last_name\nmap4@example.test,Ola,Four\n" + .getBytes(StandardCharsets.UTF_8), "text/csv"); + + JsonNode status = status(upload); + assertThat(status.get("status").asText()).isEqualTo("completed"); + assertThat(status.get("needsMapping").asBoolean()).isFalse(); + assertThat(status.get("preview").get(0).get("first_name").asText()).isEqualTo("Ola"); + assertThat(map(upload, Map.of("email", "email")).getStatus()).as("nothing to map").isEqualTo(409); + } + + @Test + void mappingAnUnknownUploadIs404() throws Exception { + assertThat(map(999_999L, Map.of("E-mail", "email")).getStatus()).isEqualTo(404); + } + + // ── helpers ───────────────────────────────────────────────────────────── + + private long upload(String name, byte[] content, String type) throws Exception { + String body = mvc.perform(multipart("/api/recipient-lists/{id}/upload", listId) + .file(new MockMultipartFile("file", name, type, content)).with(authentication(ADMIN))) + .andReturn().getResponse().getContentAsString(); + long id = json.readTree(body).get("uploadId").asLong(); + for (int i = 0; i < 100 && "processing".equals(status(id).get("status").asText()); i++) { + Thread.sleep(100); // imports run on the import pool + } + return id; + } + + private JsonNode status(long uploadId) throws Exception { + return json.readTree(mvc.perform(get("/api/uploads/{id}/status", uploadId).with(authentication(ADMIN))) + .andReturn().getResponse().getContentAsString()); + } + + private MockHttpServletResponse map(long uploadId, Map mapping) throws Exception { + return mvc.perform(post("/api/uploads/{id}/map", uploadId).with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsString(Map.of("mapping", mapping)))) + .andReturn().getResponse(); + } + + private int members() { + return jdbc.queryForObject("select count(*) from recipient_list_members where recipient_list_id = ?", + Integer.class, listId); + } +} diff --git a/src/test/java/com/mailengine/mailengine/integration/SweepFixesIntegrationTest.java b/src/test/java/com/mailengine/mailengine/integration/SweepFixesIntegrationTest.java new file mode 100644 index 0000000..ff55f32 --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/integration/SweepFixesIntegrationTest.java @@ -0,0 +1,67 @@ +package com.mailengine.mailengine.integration; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.web.servlet.MockMvc; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** Regressions found by the end-to-end sweep, checked through the real API against Postgres. */ +class SweepFixesIntegrationTest extends PostgresIntegrationSupport { + + @Autowired MockMvc mvc; + @Autowired JdbcTemplate jdbc; + + @Test + void deletingAUserKeepsTheirTemplatesAndCampaigns() throws Exception { + long user = jdbc.queryForObject("insert into users (name, email, password_hash, role) " + + "values ('Leaver', 'leaver@example.test', 'x', 'editor') returning id", Long.class); + long invited = jdbc.queryForObject("insert into users (name, email, password_hash, role, invited_by) " + + "values ('Invitee', 'invitee@example.test', 'x', 'viewer', ?) returning id", Long.class, user); + long template = jdbc.queryForObject("insert into templates (name, html_content, created_by) " + + "values ('Kept', '

hi

', ?) returning id", Long.class, user); + long campaign = jdbc.queryForObject("insert into campaigns (name, subject_line, from_name, from_email, created_by) " + + "values ('Kept', 'S', 'F', 'f@example.test', ?) returning id", Long.class, user); + + mvc.perform(delete("/api/users/{id}", user).with(authentication(ADMIN))).andExpect(status().isNoContent()); + + assertThat(jdbc.queryForObject("select created_by from templates where id = ?", Long.class, template)).isNull(); + assertThat(jdbc.queryForObject("select created_by from campaigns where id = ?", Long.class, campaign)).isNull(); + assertThat(jdbc.queryForObject("select invited_by from users where id = ?", Long.class, invited)).isNull(); + mvc.perform(get("/api/templates/{id}", template).with(authentication(ADMIN))).andExpect(status().isOk()); + mvc.perform(get("/api/campaigns/{id}", campaign).with(authentication(ADMIN))).andExpect(status().isOk()); + } + + @Test + void onlyHtmlFilesAreAcceptedAsTemplates() throws Exception { + mvc.perform(multipart("/api/templates/upload-html") + .file(new MockMultipartFile("file", "welcome.HTML", "text/html", + "

Héllo

".getBytes(StandardCharsets.UTF_8))).with(authentication(ADMIN))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.htmlContent").value("

Héllo

")); + mvc.perform(multipart("/api/templates/upload-html") + .file(new MockMultipartFile("file", "photo.png", "image/png", new byte[]{(byte) 0x89, 'P', 'N', 'G'})).with(authentication(ADMIN))) + .andExpect(status().isBadRequest()); + mvc.perform(multipart("/api/templates/upload-html") + .file(new MockMultipartFile("file", "fake.html", "text/html", new byte[]{'<', 0, 0, 1})).with(authentication(ADMIN))) + .andExpect(status().isBadRequest()); + } + + @Test + void testSendNeedsValidAddresses() throws Exception { + for (String body : new String[]{"{}", "{\"testEmails\": []}", "{\"testEmails\": [\"not-an-email\"]}", + "{\"testEmails\": [\"\"]}"}) { + mvc.perform(post("/api/campaigns/{id}/test", 1).with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON).content(body)) + .andExpect(status().isBadRequest()); + } + } +} diff --git a/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java b/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java index e47dde4..ff29995 100644 --- a/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java +++ b/src/test/java/com/mailengine/mailengine/security/SecurityWebTest.java @@ -4,6 +4,7 @@ import com.mailengine.mailengine.entity.enums.Role; import com.mailengine.mailengine.repository.EmailQueueRepository; import com.mailengine.mailengine.repository.FileUploadRepository; +import com.mailengine.mailengine.repository.PendingUploadFileRepository; import com.mailengine.mailengine.repository.RecipientListRepository; import com.mailengine.mailengine.repository.TrackingEventRepository; import com.mailengine.mailengine.repository.UserRepository; @@ -82,6 +83,7 @@ class SecurityWebTest { @MockitoBean TrackingEventRepository trackingEventRepository; @MockitoBean EmailQueueRepository emailQueueRepository; @MockitoBean FileUploadRepository fileUploadRepository; + @MockitoBean PendingUploadFileRepository pendingUploadFileRepository; @MockitoBean RecipientListRepository recipientListRepository; private final Map users = Map.of( diff --git a/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java b/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java index 07f0cd1..df33db0 100644 --- a/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java +++ b/src/test/java/com/mailengine/mailengine/service/AuthServiceTest.java @@ -16,6 +16,7 @@ import com.mailengine.mailengine.repository.PasswordResetTokenRepository; import com.mailengine.mailengine.repository.UserRepository; import com.mailengine.mailengine.security.JwtService; +import com.mailengine.mailengine.security.TokenHashing; import com.mailengine.mailengine.support.Requests; import com.mailengine.mailengine.support.TestUsers; import org.junit.jupiter.api.AfterEach; @@ -44,6 +45,7 @@ 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; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -304,17 +306,21 @@ void knownEmailReplacesOldTokensAndMailsAOneHourToken() { verify(passwordResetTokenRepository).save(saved.capture()); PasswordResetToken token = saved.getValue(); assertThat(token.getUser()).isSameAs(user); - assertThat(token.getToken()).hasSizeGreaterThanOrEqualTo(32); assertThat(token.getExpiresAt()) .isCloseTo(Instant.now().plus(Duration.ofHours(1)), within(Duration.ofSeconds(5))); - verify(emailService).sendPasswordResetEmail("editor@example.com", token.getToken()); + ArgumentCaptor emailed = ArgumentCaptor.forClass(String.class); + verify(emailService).sendPasswordResetEmail(eq("editor@example.com"), emailed.capture()); + assertThat(emailed.getValue()).hasSizeGreaterThanOrEqualTo(32); + // Only the hash is stored, so a database reader can't use the link + assertThat(token.getToken()).isEqualTo(TokenHashing.sha256Hex(emailed.getValue())) + .isNotEqualTo(emailed.getValue()); } @Test void validTokenResetsPasswordOnceAndClearsForcedChange() { user.setMustChangePwd(true); PasswordResetToken token = new PasswordResetToken("tok", user, Instant.now().plusSeconds(600)); - when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + when(passwordResetTokenRepository.findByToken(TokenHashing.sha256Hex("tok"))).thenReturn(Optional.of(token)); authService.resetPassword(reset("tok", "BrandNewPass9")); @@ -326,7 +332,7 @@ void validTokenResetsPasswordOnceAndClearsForcedChange() { @Test void unknownTokenIsRejected() { - when(passwordResetTokenRepository.findByToken("nope")).thenReturn(Optional.empty()); + when(passwordResetTokenRepository.findByToken(TokenHashing.sha256Hex("nope"))).thenReturn(Optional.empty()); assertThatThrownBy(() -> authService.resetPassword(reset("nope", "BrandNewPass9"))) .isInstanceOf(BadRequestException.class); @@ -337,7 +343,7 @@ void unknownTokenIsRejected() { void usedTokenCannotBeReplayed() { PasswordResetToken token = new PasswordResetToken("tok", user, Instant.now().plusSeconds(600)); token.setUsed(true); - when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + when(passwordResetTokenRepository.findByToken(TokenHashing.sha256Hex("tok"))).thenReturn(Optional.of(token)); String before = user.getPasswordHash(); assertThatThrownBy(() -> authService.resetPassword(reset("tok", "BrandNewPass9"))) @@ -348,7 +354,7 @@ void usedTokenCannotBeReplayed() { @Test void expiredTokenIsRejected() { PasswordResetToken token = new PasswordResetToken("tok", user, Instant.now().minusSeconds(1)); - when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + when(passwordResetTokenRepository.findByToken(TokenHashing.sha256Hex("tok"))).thenReturn(Optional.of(token)); assertThatThrownBy(() -> authService.resetPassword(reset("tok", "BrandNewPass9"))) .isInstanceOf(BadRequestException.class); @@ -365,7 +371,7 @@ class VerificationAndRegistration { void validTokenVerifiesEmailAndIsConsumed() { user.setEmailVerified(false); EmailVerificationToken token = new EmailVerificationToken("v", user, Instant.now().plusSeconds(600)); - when(verificationTokenRepository.findByToken("v")).thenReturn(Optional.of(token)); + when(verificationTokenRepository.findByToken(TokenHashing.sha256Hex("v"))).thenReturn(Optional.of(token)); authService.verifyEmail("v"); @@ -378,9 +384,9 @@ void usedOrExpiredVerificationTokensAreRejected() { EmailVerificationToken used = new EmailVerificationToken("u", user, Instant.now().plusSeconds(600)); used.setUsed(true); EmailVerificationToken expired = new EmailVerificationToken("e", user, Instant.now().minusSeconds(1)); - when(verificationTokenRepository.findByToken("u")).thenReturn(Optional.of(used)); - when(verificationTokenRepository.findByToken("e")).thenReturn(Optional.of(expired)); - when(verificationTokenRepository.findByToken("x")).thenReturn(Optional.empty()); + when(verificationTokenRepository.findByToken(TokenHashing.sha256Hex("u"))).thenReturn(Optional.of(used)); + when(verificationTokenRepository.findByToken(TokenHashing.sha256Hex("e"))).thenReturn(Optional.of(expired)); + when(verificationTokenRepository.findByToken(TokenHashing.sha256Hex("x"))).thenReturn(Optional.empty()); assertThatThrownBy(() -> authService.verifyEmail("u")).isInstanceOf(BadRequestException.class); assertThatThrownBy(() -> authService.verifyEmail("e")).isInstanceOf(BadRequestException.class); diff --git a/src/test/java/com/mailengine/mailengine/service/FileUploadServiceTest.java b/src/test/java/com/mailengine/mailengine/service/FileUploadServiceTest.java index 630575d..5d207fb 100644 --- a/src/test/java/com/mailengine/mailengine/service/FileUploadServiceTest.java +++ b/src/test/java/com/mailengine/mailengine/service/FileUploadServiceTest.java @@ -7,6 +7,7 @@ import com.mailengine.mailengine.entity.enums.RecipientStatus; import com.mailengine.mailengine.entity.enums.UploadStatus; import com.mailengine.mailengine.repository.FileUploadRepository; +import com.mailengine.mailengine.repository.PendingUploadFileRepository; import com.mailengine.mailengine.repository.RecipientListMemberRepository; import com.mailengine.mailengine.repository.RecipientListRepository; import com.mailengine.mailengine.repository.RecipientRepository; @@ -72,6 +73,7 @@ class FileUploadServiceTest { @Mock RecipientListRepository recipientListRepository; @Mock RecipientListMemberRepository memberRepository; @Mock SuppressionListRepository suppressionRepository; + @Mock PendingUploadFileRepository pendingUploadFileRepository; private FileUploadService service; private FileUpload upload; @@ -88,7 +90,7 @@ class FileUploadServiceTest { @BeforeEach void setUp() { service = new FileUploadService(fileUploadRepository, recipientRepository, - recipientListRepository, memberRepository, suppressionRepository); + recipientListRepository, memberRepository, suppressionRepository, pendingUploadFileRepository); list = new RecipientList(); list.setId(LIST_ID); diff --git a/src/test/java/com/mailengine/mailengine/service/MockEmailSenderTextTest.java b/src/test/java/com/mailengine/mailengine/service/MockEmailSenderTextTest.java new file mode 100644 index 0000000..400f383 --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/service/MockEmailSenderTextTest.java @@ -0,0 +1,30 @@ +package com.mailengine.mailengine.service; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** In mock-email mode the log has to show what the email says (an invite's temporary password, a reset link). */ +class MockEmailSenderTextTest { + + private static final String INVITE = "" + + "

Hi Ada,

Your temporary password is Tmp-1a2b3c4d

" + + "Log in"; + + @Test + void textLeavesOutTagsAndStylesButKeepsThePassword() { + String text = MockEmailSender.textOf(INVITE); + + assertThat(text).isEqualTo("Hi Ada, Your temporary password is Tmp-1a2b3c4d Log in"); + } + + @Test + void linksAreListedDecoded() { + assertThat(MockEmailSender.linksOf(INVITE)).containsExactly("http://localhost:8080/login?x=1&y=2"); + } + + @Test + void longTextIsCut() { + assertThat(MockEmailSender.textOf("

" + "a".repeat(5000) + "

")).hasSize(1003).endsWith("..."); + } +}