MailResources.java

1
/*
2
 * Copyright (c) P. Ottlinger
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *   https://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
package de.aikiit.mailversendala.template;
17
18
import de.aikiit.mailversendala.MailConfig;
19
import org.apache.commons.mail2.jakarta.EmailAttachment;
20
import org.apache.commons.mail2.core.EmailException;
21
import org.apache.commons.mail2.jakarta.HtmlEmail;
22
import org.jsoup.Jsoup;
23
import org.jsoup.nodes.Document;
24
import org.jsoup.nodes.Element;
25
26
import jakarta.mail.util.ByteArrayDataSource;
27
import java.io.IOException;
28
import java.net.URI;
29
import java.net.URISyntaxException;
30
import java.net.URLConnection;
31
import java.nio.file.Files;
32
import java.nio.file.Path;
33
import java.util.ArrayList;
34
import java.util.HashMap;
35
import java.util.LinkedHashMap;
36
import java.util.List;
37
import java.util.Map;
38
import java.util.Objects;
39
40
/**
41
 * Validates and snapshots local mail resources once per run. No network resolver is used.
42
 * Files are kept in memory so later filesystem changes cannot change a validated message.
43
 */
44
public final class MailResources {
45
    private final Path directory;
46
    private final Map<String, Asset> references = new HashMap<>();
47
    private final Map<Path, Asset> files = new HashMap<>();
48
    private final List<Asset> attachments = new ArrayList<>();
49
50
    /**
51
     * Load configured, comma-separated attachments relative to the real template directory.
52
     * @param configuration template directory and attachment references.
53
     * @throws IOException if a configured file is inaccessible or outside the directory.
54
     */
55
    public MailResources(MailConfig configuration) throws IOException {
56
        directory = Path.of(configuration.getTemplatePath()).toRealPath();
57 1 1. <init> : negated conditional → KILLED
        if (!Files.isDirectory(directory)) {
58
            throw new IOException("Template directory is not a directory: " + directory);
59
        }
60
        Map<Path, Asset> unique = new LinkedHashMap<>();
61
        for (String reference : Objects.requireNonNullElse(configuration.getAttachments(), "").split(",")) {
62 1 1. <init> : negated conditional → KILLED
            if (!reference.isBlank()) {
63
                Asset asset = load(reference.trim());
64
                unique.putIfAbsent(asset.path(), asset);
65
            }
66
        }
67
        attachments.addAll(unique.values());
68
    }
69
70
    /**
71
     * Validate every inline image in a rendered message before the first delivery.
72
     * @param template rendered message bodies.
73
     * @throws IOException for missing, external, unsupported or escaping image references.
74
     */
75
    public void validate(MailTemplate template) throws IOException {
76
        Document document = parse(template.getHtml());
77 1 1. validate : negated conditional → KILLED
        if (!document.select("[srcset]").isEmpty()) {
78
            throw new IOException("srcset is not supported; use local img src references");
79
        }
80
        for (Element image : document.select("img")) {
81
            Asset asset = load(image.attr("src"));
82 1 1. validate : negated conditional → KILLED
            if (!asset.contentType().startsWith("image/")) {
83
                throw new IOException("Inline resource is not an image: " + image.attr("src"));
84
            }
85
        }
86
    }
87
88
    /**
89
     * Embed local images using Content-IDs and add ordinary downloadable attachments.
90
     * @param email configured outgoing message.
91
     * @param template rendered HTML and plain-text alternatives.
92
     * @throws EmailException if resource validation or MIME construction fails.
93
     */
94
    public void applyTo(HtmlEmail email, MailTemplate template) throws EmailException {
95
        try {
96 1 1. applyTo : removed call to de/aikiit/mailversendala/template/MailResources::validate → SURVIVED
            validate(template);
97
            Document document = parse(template.getHtml());
98
            Map<Path, String> contentIds = new HashMap<>();
99
            for (Element image : document.select("img")) {
100
                Asset asset = load(image.attr("src"));
101
                String cid = contentIds.get(asset.path());
102 1 1. applyTo : negated conditional → KILLED
                if (cid == null) {
103
                    cid = email.embed(asset.dataSource(), directory.relativize(asset.path()).toString());
104
                    contentIds.put(asset.path(), cid);
105
                }
106
                image.attr("src", "cid:" + cid);
107
            }
108 1 1. applyTo : negated conditional → KILLED
            email.setHtmlMsg(contentIds.isEmpty() ? template.getHtml() : document.outerHtml());
109
            email.setTextMsg(template.getPlaintext());
110
            for (Asset asset : attachments) {
111
                email.attach(asset.dataSource(), asset.filename(), "", EmailAttachment.ATTACHMENT);
112
            }
113
        } catch (IOException e) {
114
            throw new EmailException("Cannot prepare local mail resources", e);
115
        }
116
    }
117
118
    private Document parse(String html) {
119
        Document document = Jsoup.parse(html);
120
        document.outputSettings().prettyPrint(false);
121 1 1. parse : replaced return value with null for de/aikiit/mailversendala/template/MailResources::parse → KILLED
        return document;
122
    }
123
124
    private Asset load(String reference) throws IOException {
125
        Asset cached = references.get(reference);
126 1 1. load : negated conditional → KILLED
        if (cached != null) {
127 1 1. load : replaced return value with null for de/aikiit/mailversendala/template/MailResources::load → KILLED
            return cached;
128
        }
129
        Path relative;
130
        try {
131
            URI uri = new URI(reference.replace(" ", "%20"));
132 3 1. load : negated conditional → KILLED
2. load : negated conditional → KILLED
3. load : negated conditional → KILLED
            if (reference.isBlank() || reference.contains("\\") || uri.isAbsolute()
133 3 1. load : negated conditional → KILLED
2. load : negated conditional → KILLED
3. load : negated conditional → KILLED
                    || uri.getRawAuthority() != null || uri.getRawQuery() != null || uri.getRawFragment() != null) {
134
                throw new IOException("Only relative local resource paths are allowed: " + reference);
135
            }
136
            String path = uri.getPath();
137 1 1. load : negated conditional → KILLED
            if (path == null) {
138
                throw new IOException("Resource path is missing: " + reference);
139
            }
140
            relative = Path.of(path);
141
        } catch (URISyntaxException | IllegalArgumentException e) {
142
            throw new IOException("Invalid local resource path: " + reference, e);
143
        }
144 1 1. load : negated conditional → KILLED
        if (relative.isAbsolute()) {
145
            throw new IOException("Absolute resource paths are not allowed: " + reference);
146
        }
147
        Path file = directory.resolve(relative).toRealPath();
148 3 1. load : negated conditional → KILLED
2. load : negated conditional → KILLED
3. load : negated conditional → KILLED
        if (!file.startsWith(directory) || !Files.isRegularFile(file) || !Files.isReadable(file)) {
149
            throw new IOException("Resource must be a readable file inside templatepath: " + reference);
150
        }
151
        Asset asset = files.get(file);
152 1 1. load : negated conditional → KILLED
        if (asset == null) {
153
            Path filename = file.getFileName();
154 1 1. load : negated conditional → KILLED
            if (filename == null) {
155
                throw new IOException("Resource filename is missing: " + reference);
156
            }
157
            String contentType = URLConnection.guessContentTypeFromName(filename.toString());
158 1 1. load : negated conditional → KILLED
            if (contentType == null) {
159
                contentType = "application/octet-stream";
160
            }
161
            asset = new Asset(file, filename.toString(), Files.readAllBytes(file), contentType);
162
            files.put(file, asset);
163
        }
164
        references.put(reference, asset);
165 1 1. load : replaced return value with null for de/aikiit/mailversendala/template/MailResources::load → KILLED
        return asset;
166
    }
167
168
    private record Asset(Path path, String filename, byte[] bytes, String contentType) {
169
        ByteArrayDataSource dataSource() {
170
            ByteArrayDataSource source = new ByteArrayDataSource(bytes, contentType);
171 1 1. dataSource : removed call to jakarta/mail/util/ByteArrayDataSource::setName → SURVIVED
            source.setName(filename);
172 1 1. dataSource : replaced return value with null for de/aikiit/mailversendala/template/MailResources$Asset::dataSource → KILLED
            return source;
173
        }
174
    }
175
}

Mutations

57

1.1
Location : <init>
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[test-template:rejectsUnsafeInlineReferences(java.lang.String)]/[test-template-invocation:#12]
negated conditional → KILLED

62

1.1
Location : <init>
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[test-template:rejectsUnsafeOrMissingAttachments(java.lang.String)]/[test-template-invocation:#2]
negated conditional → KILLED

77

1.1
Location : validate
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:rejectsTraversalToExistingFilesOutsideTheTemplateDirectory(java.nio.file.Path)]
negated conditional → KILLED

82

1.1
Location : validate
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:acceptsNestedImagesWithSpacesEntitiesAndUnquotedAttributes()]
negated conditional → KILLED

96

1.1
Location : applyTo
Killed by : none
removed call to de/aikiit/mailversendala/template/MailResources::validate → SURVIVED
Covering tests

102

1.1
Location : applyTo
Killed by : de.aikiit.mailversendala.SendOutGreenMailTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.SendOutGreenMailTest]/[method:sendsValidatedSnapshotsEvenIfOriginalFilesAreDeleted(java.nio.file.Path)]
negated conditional → KILLED

108

1.1
Location : applyTo
Killed by : de.aikiit.mailversendala.SendOutGreenMailTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.SendOutGreenMailTest]/[method:deliversExternalVelocityTemplatesAsUtf8Alternatives(java.nio.file.Path)]
negated conditional → KILLED

121

1.1
Location : parse
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[test-template:rejectsUnsafeInlineReferences(java.lang.String)]/[test-template-invocation:#12]
replaced return value with null for de/aikiit/mailversendala/template/MailResources::parse → KILLED

126

1.1
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[test-template:rejectsUnsafeOrMissingAttachments(java.lang.String)]/[test-template-invocation:#2]
negated conditional → KILLED

127

1.1
Location : load
Killed by : de.aikiit.mailversendala.SendOutGreenMailTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.SendOutGreenMailTest]/[method:demoModeValidatesResourcesWithoutSending(java.nio.file.Path)]
replaced return value with null for de/aikiit/mailversendala/template/MailResources::load → KILLED

132

1.1
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:rejectsTraversalToExistingFilesOutsideTheTemplateDirectory(java.nio.file.Path)]
negated conditional → KILLED

2.2
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:rejectsTraversalToExistingFilesOutsideTheTemplateDirectory(java.nio.file.Path)]
negated conditional → KILLED

3.3
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:rejectsTraversalToExistingFilesOutsideTheTemplateDirectory(java.nio.file.Path)]
negated conditional → KILLED

133

1.1
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:rejectsTraversalToExistingFilesOutsideTheTemplateDirectory(java.nio.file.Path)]
negated conditional → KILLED

2.2
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:rejectsTraversalToExistingFilesOutsideTheTemplateDirectory(java.nio.file.Path)]
negated conditional → KILLED

3.3
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:rejectsTraversalToExistingFilesOutsideTheTemplateDirectory(java.nio.file.Path)]
negated conditional → KILLED

137

1.1
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:rejectsTraversalToExistingFilesOutsideTheTemplateDirectory(java.nio.file.Path)]
negated conditional → KILLED

144

1.1
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:rejectsTraversalToExistingFilesOutsideTheTemplateDirectory(java.nio.file.Path)]
negated conditional → KILLED

148

1.1
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:rejectsSymlinksEscapingTheTemplateDirectory(java.nio.file.Path)]
negated conditional → KILLED

2.2
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:acceptsNestedImagesWithSpacesEntitiesAndUnquotedAttributes()]
negated conditional → KILLED

3.3
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:acceptsNestedImagesWithSpacesEntitiesAndUnquotedAttributes()]
negated conditional → KILLED

152

1.1
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:acceptsNestedImagesWithSpacesEntitiesAndUnquotedAttributes()]
negated conditional → KILLED

154

1.1
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:acceptsNestedImagesWithSpacesEntitiesAndUnquotedAttributes()]
negated conditional → KILLED

158

1.1
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:acceptsNestedImagesWithSpacesEntitiesAndUnquotedAttributes()]
negated conditional → KILLED

165

1.1
Location : load
Killed by : de.aikiit.mailversendala.template.MailResourcesTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.template.MailResourcesTest]/[method:acceptsNestedImagesWithSpacesEntitiesAndUnquotedAttributes()]
replaced return value with null for de/aikiit/mailversendala/template/MailResources::load → KILLED

171

1.1
Location : dataSource
Killed by : none
removed call to jakarta/mail/util/ByteArrayDataSource::setName → SURVIVED
Covering tests

172

1.1
Location : dataSource
Killed by : de.aikiit.mailversendala.SendOutGreenMailTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.SendOutGreenMailTest]/[method:demoModeValidatesResourcesWithoutSending(java.nio.file.Path)]
replaced return value with null for de/aikiit/mailversendala/template/MailResources$Asset::dataSource → KILLED

Active mutators

Tests examined


Report generated by PIT 1.30.2 support