WebFramework.java

1
package com.renomad.minum.web;
2
3
import com.renomad.minum.logging.ILogger;
4
import com.renomad.minum.security.ForbiddenUseException;
5
import com.renomad.minum.security.ITheBrig;
6
import com.renomad.minum.security.UnderInvestigation;
7
import com.renomad.minum.state.Constants;
8
import com.renomad.minum.state.Context;
9
import com.renomad.minum.utils.*;
10
11
import java.io.IOException;
12
import java.net.SocketException;
13
import java.net.SocketTimeoutException;
14
import java.nio.file.Files;
15
import java.nio.file.Path;
16
import java.time.ZoneId;
17
import java.time.ZonedDateTime;
18
import java.time.format.DateTimeFormatter;
19
import java.util.*;
20
import java.util.regex.Matcher;
21
import java.util.regex.Pattern;
22
import java.util.stream.Collectors;
23
24
import static com.renomad.minum.utils.FileUtils.*;
25
import static com.renomad.minum.utils.Invariants.mustBeTrue;
26
import static com.renomad.minum.web.StatusLine.StatusCode.*;
27
import static com.renomad.minum.web.WebEngine.HTTP_CRLF;
28
29
/**
30
 * This class is responsible for the HTTP handling after socket connection.
31
 * <p>
32
 *     The public methods are for registering endpoints - code that will be
33
 *     run for a given combination of HTTP method and path.  See documentation
34
 *     for the methods in this class.
35
 * </p>
36
 */
37
public final class WebFramework {
38
39
    private final Constants constants;
40
    private final UnderInvestigation underInvestigation;
41
    private final IInputStreamUtils inputStreamUtils;
42
    private final IBodyProcessor bodyProcessor;
43
    /**
44
     * This is a variable storing a pseudo-random (non-secure) number
45
     * that is shown to users when a serious error occurs, which
46
     * will also be put in the logs, to make finding it easier.
47
     */
48
    private final Random randomErrorCorrelationId;
49
    private final RequestLine emptyRequestLine;
50
51
    public Map<String,String> getSuffixToMimeMappings() {
52 1 1. getSuffixToMimeMappings : replaced return value with Collections.emptyMap for com/renomad/minum/web/WebFramework::getSuffixToMimeMappings → KILLED
        return new HashMap<>(fileSuffixToMime);
53
    }
54
55
    /**
56
     * This is used as a key when registering endpoints
57
     */
58
    record MethodPath(RequestLine.Method method, String path) { }
59
60
    /**
61
     * The list of paths that our system is registered to handle.
62
     */
63
    private final Map<MethodPath, ThrowingFunction<IRequest, IResponse>> registeredDynamicPaths;
64
65
    /**
66
     * These are registrations for paths that partially match, for example,
67
     * if the client sends us GET /.well-known/acme-challenge/HGr8U1IeTW4kY_Z6UIyaakzOkyQgPr_7ArlLgtZE8SX
68
     * and we want to match ".well-known/acme-challenge"
69
     */
70
    private final Map<MethodPath, ThrowingFunction<IRequest, IResponse>> registeredPartialPaths;
71
72
    /**
73
     * A function that will be run instead of the ordinary business code. Has
74
     * provisions for running the business code as well.  See {@link #registerPreHandler(ThrowingFunction)}
75
     */
76
    private ThrowingFunction<PreHandlerInputs, IResponse> preHandler;
77
78
    /**
79
     * A function run after the ordinary business code
80
     */
81
    private ThrowingFunction<LastMinuteHandlerInputs, IResponse> lastMinuteHandler;
82
83
    private final IFileReader fileReader;
84
    private final Map<String, String> fileSuffixToMime;
85
86
    // This is just used for testing.  If it's null, we use the real time.
87
    private final ZonedDateTime overrideForDateTime;
88
    private final FullSystem fs;
89
    private final ILogger logger;
90
91
    /**
92
     * This is the minimum number of bytes in a text response to apply gzip.
93
     */
94
    private static final int MINIMUM_NUMBER_OF_BYTES_TO_COMPRESS = 2048;
95
96
    /**
97
     * This is the brains of how the server responds to web clients.  Whatever
98
     * code lives here will be inserted into a slot within the server code.
99
     */
100
    ThrowingRunnable makePrimaryHttpHandler(ISocketWrapper sw, ITheBrig theBrig) {
101
102 1 1. makePrimaryHttpHandler : replaced return value with null for com/renomad/minum/web/WebFramework::makePrimaryHttpHandler → KILLED
        return () -> {
103
            Thread.currentThread().setName("SocketWrapper thread for " + sw.getRemoteAddr());
104
            try (sw) {
105
                dumpIfAttacker(sw, fs);
106
                final var is = sw.getInputStream();
107
108
                // By default, browsers expect the server to run in keep-alive mode.
109
                // We'll break out later if we find that the browser doesn't do keep-alive
110
                while (true) {
111
                    final String rawStartLine = inputStreamUtils.readLine(is);
112
                    long startMillis = System.currentTimeMillis();
113 1 1. lambda$makePrimaryHttpHandler$5 : negated conditional → KILLED
                    if (rawStartLine.isEmpty()) {
114
                        // here, the client connected, sent nothing, and closed.
115
                        // nothing to do but return.
116
                        logger.logTrace(() -> "rawStartLine was empty.  Returning.");
117
                        break;
118
                    }
119
                    final RequestLine sl = getProcessedRequestLine(sw, rawStartLine);
120
121 1 1. lambda$makePrimaryHttpHandler$5 : negated conditional → KILLED
                    if (sl.equals(emptyRequestLine)) {
122
                        // here, the client sent something we cannot parse.
123
                        // nothing to do but return.
124
                        logger.logTrace(() -> "RequestLine was unparseable.  Returning.");
125
                        break;
126
                    }
127
                    // check if the user is seeming to attack us.
128 1 1. lambda$makePrimaryHttpHandler$5 : removed call to com/renomad/minum/web/WebFramework::checkIfSuspiciousPath → KILLED
                    checkIfSuspiciousPath(sw, sl);
129
130
                    // React to what the user requested, generate a result
131
                    Headers hi = getHeaders(sw);
132
                    boolean isKeepAlive = determineIfKeepAlive(sl, hi, logger);
133 1 1. lambda$makePrimaryHttpHandler$5 : negated conditional → KILLED
                    if (isThereIsABody(hi)) {
134
                        logger.logTrace(() -> "There is a body. Content-type is " + hi.contentType());
135
                    }
136
                    ProcessingResult result = processRequest(sw, sl, hi);
137
                    IRequest request = result.clientRequest();
138
                    Response response = (Response)result.resultingResponse();
139
140
                    // check that the response is non-null.  If it is null, that suggests
141
                    // the developer made a mistake.
142 1 1. lambda$makePrimaryHttpHandler$5 : negated conditional → KILLED
                    if (response == null) {
143
                        throw new WebServerException("The returned value for the endpoint \"%s\" was null.".formatted(request.getRequestLine().getPathDetails().getIsolatedPath()));
144
                    }
145
146
                    // calculate proper headers for the response
147
                    StringBuilder headerStringBuilder = addDefaultHeaders(response);
148 1 1. lambda$makePrimaryHttpHandler$5 : removed call to com/renomad/minum/web/WebFramework::addOptionalExtraHeaders → KILLED
                    addOptionalExtraHeaders(response, headerStringBuilder);
149 1 1. lambda$makePrimaryHttpHandler$5 : removed call to com/renomad/minum/web/WebFramework::addKeepAliveTimeout → KILLED
                    addKeepAliveTimeout(isKeepAlive, headerStringBuilder);
150
151
                    // inspect the response being sent, see whether we can compress the data.
152
                    Response adjustedResponse = potentiallyCompress(request.getHeaders(), response, headerStringBuilder);
153 1 1. lambda$makePrimaryHttpHandler$5 : removed call to com/renomad/minum/web/WebFramework::applyContentLength → KILLED
                    applyContentLength(headerStringBuilder, adjustedResponse.getBodyLength());
154 1 1. lambda$makePrimaryHttpHandler$5 : removed call to com/renomad/minum/web/WebFramework::confirmBodyHasContentType → KILLED
                    confirmBodyHasContentType(request, response);
155
156
                    // send the headers
157 1 1. lambda$makePrimaryHttpHandler$5 : removed call to com/renomad/minum/web/ISocketWrapper::send → KILLED
                    sw.send(headerStringBuilder.append(HTTP_CRLF).toString());
158
159
                    // if the user sent a HEAD request, we send everything back except the body.
160
                    // even though we skip the body, this requires full processing to get the
161
                    // numbers right, like content-length.
162 1 1. lambda$makePrimaryHttpHandler$5 : negated conditional → TIMED_OUT
                    if (request.getRequestLine().getMethod().equals(RequestLine.Method.HEAD)) {
163
                        logger.logDebug(() -> "client " + request.getRemoteRequester() +
164
                                " is requesting HEAD for "+ request.getRequestLine().getPathDetails().getIsolatedPath() +
165
                                ".  Excluding body from response");
166
                    } else {
167
                        // send the body
168 1 1. lambda$makePrimaryHttpHandler$5 : removed call to com/renomad/minum/web/Response::sendBody → TIMED_OUT
                        adjustedResponse.sendBody(sw);
169
                    }
170
                    // print how long this processing took
171
                    long endMillis = System.currentTimeMillis();
172
                    logger.logTrace(() -> String.format("full processing (including communication time) of %s %s took %d millis", sw, sl, endMillis - startMillis));
173 1 1. lambda$makePrimaryHttpHandler$5 : negated conditional → KILLED
                    if (!isKeepAlive) break;
174
                }
175
            } catch (SocketException | SocketTimeoutException ex) {
176 1 1. lambda$makePrimaryHttpHandler$5 : removed call to com/renomad/minum/web/WebFramework::handleReadTimedOut → SURVIVED
                handleReadTimedOut(sw, ex, logger);
177
            } catch (ForbiddenUseException ex) {
178 1 1. lambda$makePrimaryHttpHandler$5 : removed call to com/renomad/minum/web/WebFramework::handleForbiddenUse → KILLED
                handleForbiddenUse(sw, ex, logger, theBrig, constants.vulnSeekingJailDuration);
179
            } catch (IOException ex) {
180 1 1. lambda$makePrimaryHttpHandler$5 : removed call to com/renomad/minum/web/WebFramework::handleIOException → SURVIVED
                handleIOException(sw, ex, logger, theBrig, underInvestigation, constants.vulnSeekingJailDuration);
181
            }
182
        };
183
    }
184
185
186
    static void handleIOException(ISocketWrapper sw, IOException ex, ILogger logger, ITheBrig theBrig, UnderInvestigation underInvestigation, int vulnSeekingJailDuration ) {
187
        logger.logDebug(() -> ex.getMessage() + " (at Server.start)");
188
        String suspiciousClues = underInvestigation.isClientLookingForVulnerabilities(ex.getMessage());
189
190 2 1. handleIOException : negated conditional → KILLED
2. handleIOException : negated conditional → KILLED
        if (!suspiciousClues.isEmpty() && theBrig != null) {
191
            logger.logDebug(() -> sw.getRemoteAddr() + " is looking for vulnerabilities, for this: " + suspiciousClues);
192
            theBrig.sendToJail(sw.getRemoteAddr() + "_vuln_seeking", vulnSeekingJailDuration);
193
        }
194
    }
195
196
    static void handleForbiddenUse(ISocketWrapper sw, ForbiddenUseException ex, ILogger logger, ITheBrig theBrig, int vulnSeekingJailDuration) {
197
        logger.logDebug(() -> sw.getRemoteAddr() + " is looking for vulnerabilities, for this: " + ex.getMessage());
198 1 1. handleForbiddenUse : negated conditional → KILLED
        if (theBrig != null) {
199
            theBrig.sendToJail(sw.getRemoteAddr() + "_vuln_seeking", vulnSeekingJailDuration);
200
        } else {
201
            logger.logDebug(() -> "theBrig is null at handleForbiddenUse, will not store address in database");
202
        }
203
    }
204
205
    static void handleReadTimedOut(ISocketWrapper sw, IOException ex, ILogger logger) {
206
        /*
207
        if we close the application on the server side, there's a good
208
        likelihood a SocketException will come bubbling through here.
209
        NOTE:
210
          it seems that Socket closed is what we get when the client closes the connection in non-SSL, and conversely,
211
          if we are operating in secure (i.e. SSL/TLS) mode, we get "an established connection..."
212
        */
213 1 1. handleReadTimedOut : negated conditional → KILLED
        if (ex.getMessage().equals("Read timed out")) {
214
            logger.logTrace(() -> "Read timed out - remote address: " + sw.getRemoteAddrWithPort());
215
        } else {
216
            logger.logDebug(() -> ex.getMessage() + " - remote address: " + sw.getRemoteAddrWithPort());
217
        }
218
    }
219
220
    /**
221
     * Logic for how to process an incoming request.  For example, did the developer
222
     * write a function to handle this? Is it a request for a static file, like an image
223
     * or script?  Did the user provide a "pre" or "post" handler?
224
     */
225
    ProcessingResult processRequest(
226
            ISocketWrapper sw,
227
            RequestLine requestLine,
228
            Headers requestHeaders) throws Exception {
229
        IRequest clientRequest = new Request(requestHeaders, requestLine, sw.getRemoteAddr(), sw, bodyProcessor);
230
        IResponse response;
231
        ThrowingFunction<IRequest, IResponse> endpoint = findEndpointForThisStartline(requestLine, requestHeaders);
232 1 1. processRequest : negated conditional → KILLED
        if (endpoint == null) {
233
            response = Response.buildLeanResponse(CODE_404_NOT_FOUND);
234
        } else {
235
            long millisAtStart = System.currentTimeMillis();
236
            try {
237 1 1. processRequest : negated conditional → KILLED
                if (preHandler != null) {
238
                    response = preHandler.apply(new PreHandlerInputs(clientRequest, endpoint, sw));
239
                } else {
240
                    response = endpoint.apply(clientRequest);
241
                }
242
            } catch (Exception ex) {
243
                // if an error happens while running an endpoint's code, this is the
244
                // last-chance handling of that error where we return a 500 and a
245
                // random code to the client, so a developer can find the detailed
246
                // information in the logs, which have that same value.
247
                int randomNumber = randomErrorCorrelationId.nextInt();
248
                logger.logAsyncError(() -> "error while running endpoint " + endpoint + ". Code: " + randomNumber + ". Error: " + StacktraceUtils.stackTraceToString(ex));
249
                response = Response.buildResponse(CODE_500_INTERNAL_SERVER_ERROR, Map.of("Content-Type", "text/plain;charset=UTF-8"), "Server error: " + randomNumber);
250
            }
251
            long millisAtEnd = System.currentTimeMillis();
252
            logger.logTrace(() -> String.format("handler processing of %s %s took %d millis", sw, requestLine, millisAtEnd - millisAtStart));
253
        }
254
255
        // if the user has chosen to customize the response based on status code, that will
256
        // be applied now, and it will override the previous response.
257 1 1. processRequest : negated conditional → KILLED
        if (lastMinuteHandler != null) {
258
            response = lastMinuteHandler.apply(new LastMinuteHandlerInputs(clientRequest, response));
259
        }
260
261 1 1. processRequest : replaced return value with null for com/renomad/minum/web/WebFramework::processRequest → KILLED
        return new ProcessingResult(clientRequest, response);
262
    }
263
264
    record ProcessingResult(IRequest clientRequest, IResponse resultingResponse) { }
265
266
    private Headers getHeaders(ISocketWrapper sw) {
267
    /*
268
       next we will read the headers (e.g. Content-Type: foo/bar) one-by-one.
269
270
       the headers tell us vital information about the
271
       body.  If, for example, we're getting a POST and receiving a
272
       www form url encoded, there will be a header of "content-length"
273
       that will mention how many bytes to read.  On the other hand, if
274
       we're receiving a multipart, there will be no content-length, but
275
       the content-type will include the boundary string.
276
    */
277
        List<String> allHeaders = Headers.getAllHeaders(sw.getInputStream(), inputStreamUtils);
278
        Headers hi = new Headers(allHeaders);
279
        logger.logTrace(() -> "The headers are: " + hi.getHeaderStrings());
280 1 1. getHeaders : replaced return value with null for com/renomad/minum/web/WebFramework::getHeaders → KILLED
        return hi;
281
    }
282
283
    /**
284
     * determine if we are in a keep-alive connection
285
     */
286
    static boolean determineIfKeepAlive(RequestLine sl, Headers hi, ILogger logger) {
287
        boolean isKeepAlive = false;
288 1 1. determineIfKeepAlive : negated conditional → KILLED
        if (sl.getVersion() == HttpVersion.ONE_DOT_ZERO) {
289
            isKeepAlive = hi.hasKeepAlive();
290 1 1. determineIfKeepAlive : negated conditional → KILLED
        } else if (sl.getVersion() == HttpVersion.ONE_DOT_ONE) {
291 1 1. determineIfKeepAlive : negated conditional → KILLED
            isKeepAlive = ! hi.hasConnectionClose();
292
        }
293
        boolean finalIsKeepAlive = isKeepAlive;
294
        logger.logTrace(() -> "Is this a keep-alive connection? " + finalIsKeepAlive);
295 2 1. determineIfKeepAlive : replaced boolean return with false for com/renomad/minum/web/WebFramework::determineIfKeepAlive → KILLED
2. determineIfKeepAlive : replaced boolean return with true for com/renomad/minum/web/WebFramework::determineIfKeepAlive → KILLED
        return isKeepAlive;
296
    }
297
298
    RequestLine getProcessedRequestLine(ISocketWrapper sw, String rawStartLine) {
299
        logger.logTrace(() -> sw + ": raw request line received: " + rawStartLine);
300
        RequestLine rl = new RequestLine(
301
                RequestLine.Method.NONE,
302
                PathDetails.empty,
303
                HttpVersion.NONE,
304
                "", logger);
305
        RequestLine extractedRequestLine = rl.extractRequestLine(rawStartLine);
306
        logger.logTrace(() -> sw + ": RequestLine has been derived: " + extractedRequestLine);
307 1 1. getProcessedRequestLine : replaced return value with null for com/renomad/minum/web/WebFramework::getProcessedRequestLine → KILLED
        return extractedRequestLine;
308
    }
309
310
    void checkIfSuspiciousPath(ISocketWrapper sw, RequestLine requestLine) {
311
        String suspiciousClues = underInvestigation.isLookingForSuspiciousPaths(
312
                requestLine.getPathDetails().getIsolatedPath());
313 1 1. checkIfSuspiciousPath : negated conditional → KILLED
        if (!suspiciousClues.isEmpty()) {
314
            String msg = sw.getRemoteAddr() + " is looking for a vulnerability, for this: " + suspiciousClues;
315
            throw new ForbiddenUseException(msg);
316
        }
317
    }
318
319
    /**
320
     * This code confirms our objects are valid before calling
321
     * to {@link #dumpIfAttacker(ISocketWrapper, ITheBrig)}.
322
     * @return true if successfully called to subsequent method, false otherwise.
323
     */
324
    boolean dumpIfAttacker(ISocketWrapper sw, FullSystem fs) {
325 1 1. dumpIfAttacker : negated conditional → KILLED
        if (fs == null) {
326 1 1. dumpIfAttacker : replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return false;
327 1 1. dumpIfAttacker : negated conditional → KILLED
        } else if (fs.getTheBrig() == null) {
328 1 1. dumpIfAttacker : replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return false;
329
        } else {
330 1 1. dumpIfAttacker : removed call to com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            dumpIfAttacker(sw, fs.getTheBrig());
331 1 1. dumpIfAttacker : replaced boolean return with false for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return true;
332
        }
333
    }
334
335
    void dumpIfAttacker(ISocketWrapper sw, ITheBrig theBrig) {
336
        String remoteClient = sw.getRemoteAddr();
337 1 1. dumpIfAttacker : negated conditional → KILLED
        if (theBrig.isInJail(remoteClient + "_vuln_seeking")) {
338
            // if this client is a vulnerability seeker, throw an exception,
339
            // causing them to get dumped unceremoniously
340
            String message = "closing the socket on " + remoteClient + " due to being found in the brig";
341
            logger.logDebug(() -> message);
342
            throw new ForbiddenUseException(message);
343
        }
344
    }
345
346
    /**
347
     * Determine whether the headers in this HTTP message indicate that
348
     * a body is available to read
349
     */
350
    static boolean isThereIsABody(Headers hi) {
351
        // if the client sent us a content-type header at all...
352 1 1. isThereIsABody : negated conditional → KILLED
        if (!hi.contentType().isBlank()) {
353
            // if the content-length is greater than 0, we've got a body
354 3 1. isThereIsABody : negated conditional → TIMED_OUT
2. isThereIsABody : replaced boolean return with false for com/renomad/minum/web/WebFramework::isThereIsABody → KILLED
3. isThereIsABody : changed conditional boundary → KILLED
            if (hi.contentLength() > 0) return true;
355
356
            // if the transfer-encoding header is set to chunked, we have a body
357
            List<String> transferEncodingHeaders = hi.valueByKey("transfer-encoding");
358 5 1. isThereIsABody : negated conditional → KILLED
2. lambda$isThereIsABody$19 : replaced boolean return with false for com/renomad/minum/web/WebFramework::lambda$isThereIsABody$19 → KILLED
3. lambda$isThereIsABody$19 : replaced boolean return with true for com/renomad/minum/web/WebFramework::lambda$isThereIsABody$19 → KILLED
4. isThereIsABody : replaced boolean return with true for com/renomad/minum/web/WebFramework::isThereIsABody → KILLED
5. isThereIsABody : negated conditional → KILLED
            return transferEncodingHeaders != null && transferEncodingHeaders.stream().anyMatch(x -> x.equalsIgnoreCase("chunked"));
359
        }
360
        // otherwise, no body we recognize
361 1 1. isThereIsABody : replaced boolean return with true for com/renomad/minum/web/WebFramework::isThereIsABody → SURVIVED
        return false;
362
    }
363
364
    /**
365
     * Prepare some of the basic server response headers, like the status code, the
366
     * date-time stamp, the server name.
367
     */
368
    private StringBuilder addDefaultHeaders(IResponse response) {
369
370 1 1. lambda$addDefaultHeaders$20 : replaced return value with null for com/renomad/minum/web/WebFramework::lambda$addDefaultHeaders$20 → KILLED
        String date = Objects.requireNonNullElseGet(overrideForDateTime, () -> ZonedDateTime.now(ZoneId.of("UTC"))).format(DateTimeFormatter.RFC_1123_DATE_TIME);
371
372
        // we'll store the status line and headers in this
373
        StringBuilder headerStringBuilder = new StringBuilder();
374
375
376
        // add the status line
377
        headerStringBuilder.append("HTTP/1.1 ").append(response.getStatusCode().code).append(" ").append(response.getStatusCode().shortDescription).append(HTTP_CRLF);
378
379
        // add a date-timestamp
380
        headerStringBuilder.append("Date: ").append(date).append(HTTP_CRLF);
381
382
        // add the server name
383
        headerStringBuilder.append("Server: minum").append(HTTP_CRLF);
384
385 1 1. addDefaultHeaders : replaced return value with null for com/renomad/minum/web/WebFramework::addDefaultHeaders → KILLED
        return headerStringBuilder;
386
    }
387
388
    /**
389
     * Add extra headers specified by the business logic (set by the developer)
390
     */
391
    private static void addOptionalExtraHeaders(IResponse response, StringBuilder stringBuilder) {
392
        stringBuilder.append(
393
                response.getExtraHeaders().entrySet().stream()
394 1 1. lambda$addOptionalExtraHeaders$21 : replaced return value with "" for com/renomad/minum/web/WebFramework::lambda$addOptionalExtraHeaders$21 → KILLED
                .map(x -> x.getKey() + ": " + x.getValue() + HTTP_CRLF)
395
                .collect(Collectors.joining()));
396
    }
397
398
    /**
399
     * If a response body exists, it needs to have a content-type specified, or throw an exception.
400
     */
401
    static void confirmBodyHasContentType(IRequest request, Response response) {
402
        // check the correctness of the content-type header versus the data length (if any data, that is)
403 2 1. lambda$confirmBodyHasContentType$22 : replaced boolean return with true for com/renomad/minum/web/WebFramework::lambda$confirmBodyHasContentType$22 → KILLED
2. lambda$confirmBodyHasContentType$22 : replaced boolean return with false for com/renomad/minum/web/WebFramework::lambda$confirmBodyHasContentType$22 → KILLED
        boolean hasContentType = response.getExtraHeaders().entrySet().stream().anyMatch(x -> x.getKey().toLowerCase(Locale.ROOT).equals("content-type"));
404
405
        // if there *is* data, we had better be returning a content type
406 2 1. confirmBodyHasContentType : changed conditional boundary → KILLED
2. confirmBodyHasContentType : negated conditional → KILLED
        if (response.getBodyLength() > 0) {
407
            mustBeTrue(hasContentType, "a Content-Type header must be specified in the Response object if it returns data. Response details: " + response + " Request: " + request);
408
        }
409
    }
410
411
    /**
412
     * If this is a keep-alive communication, add a header specifying the
413
     * socket timeout for the browser.
414
     */
415
    private void addKeepAliveTimeout(boolean isKeepAlive, StringBuilder stringBuilder) {
416
        // if we're a keep-alive connection, reply with a keep-alive header
417 1 1. addKeepAliveTimeout : negated conditional → KILLED
        if (isKeepAlive) {
418
            stringBuilder.append("Keep-Alive: timeout=").append(constants.keepAliveTimeoutSeconds).append(HTTP_CRLF);
419
        }
420
    }
421
422
    /**
423
     * The rules regarding the content-length header are byzantine.  Even in the cases
424
     * where you aren't returning anything, servers can use this header to determine when the
425
     * response is finished.
426
     * See <a href="https://www.rfc-editor.org/rfc/rfc9110.html#name-content-length">Content-Length in the HTTP spec</a>
427
     */
428
    private static void applyContentLength(StringBuilder stringBuilder, long bodyLength) {
429
        stringBuilder.append("Content-Length: ").append(bodyLength).append(HTTP_CRLF);
430
    }
431
432
    /**
433
     * This method will examine the request headers and response content-type, and
434
     * compress the outgoing data if necessary.  Uses {@link #compressibleMimesPattern}
435
     */
436
    static Response potentiallyCompress(Headers requestHeaders, Response response, StringBuilder headerStringBuilder) throws IOException {
437
        // we may make modifications to the response body at this point, specifically
438
        // we may compress the data, if the client requested it.
439
        // see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-encoding
440
        List<String> acceptEncoding = requestHeaders.valueByKey("accept-encoding");
441
442
        // regardless of whether the client requests compression in their Accept-Encoding header,
443
        // if the data we're sending back is not of an appropriate type, we won't bother
444
        // compressing it.  Basically, we're going to compress plain text.
445 2 1. lambda$potentiallyCompress$23 : replaced boolean return with false for com/renomad/minum/web/WebFramework::lambda$potentiallyCompress$23 → KILLED
2. lambda$potentiallyCompress$23 : replaced boolean return with true for com/renomad/minum/web/WebFramework::lambda$potentiallyCompress$23 → KILLED
        Map.Entry<String, String> contentTypeHeader = SearchUtils.findExactlyOne(response.getExtraHeaders().entrySet().stream(), x -> x.getKey().equalsIgnoreCase("content-type"));
446
447 1 1. potentiallyCompress : negated conditional → KILLED
        if (contentTypeHeader != null) {
448
            String contentType = contentTypeHeader.getValue().toLowerCase(Locale.ROOT);
449
            boolean hasCompressibleMimeType = determineCompressible(contentType);
450 1 1. potentiallyCompress : negated conditional → KILLED
            if (hasCompressibleMimeType) {
451 1 1. potentiallyCompress : replaced return value with null for com/renomad/minum/web/WebFramework::potentiallyCompress → KILLED
                return compressBodyIfRequested(response, acceptEncoding, headerStringBuilder, MINIMUM_NUMBER_OF_BYTES_TO_COMPRESS);
452
            }
453
        }
454 1 1. potentiallyCompress : replaced return value with null for com/renomad/minum/web/WebFramework::potentiallyCompress → KILLED
        return response;
455
    }
456
457
458
    /**
459
     * A regular expression for finding mimes that we can compress
460
     */
461
    final static Pattern compressibleMimesPattern = Pattern.compile("^text/|(?:json|\\+?xml)$");
462
463
    /**
464
     * Run a regular expression against the Content-Type header, and return
465
     * true if the mime is text-based and thus would benefit from compression.
466
     * Uses {@link #compressibleMimesPattern}
467
     */
468
    static boolean determineCompressible(String contentType) {
469 2 1. determineCompressible : replaced boolean return with false for com/renomad/minum/web/WebFramework::determineCompressible → KILLED
2. determineCompressible : replaced boolean return with true for com/renomad/minum/web/WebFramework::determineCompressible → KILLED
        return compressibleMimesPattern.matcher(contentType).find();
470
    }
471
472
    /**
473
     * This method will examine the content-encoding headers, and if "gzip" is
474
     * requested by the client, we will replace the body bytes with compressed
475
     * bytes, using the GZIP compression algorithm, as long as the response body
476
     * is greater than minNumberBytes bytes.
477
     *
478
     * @param acceptEncoding headers sent by the client about what compression
479
     *                       algorithms will be understood.
480
     * @param stringBuilder  the string we are gradually building up to send back to
481
     *                       the client for the status line and headers. We'll use it
482
     *                       here if we need to append a content-encoding - that is,
483
     *                       if we successfully compress data as gzip.
484
     * @param minNumberBytes number of bytes must be larger than this to compress.
485
     */
486
    static Response compressBodyIfRequested(Response response, List<String> acceptEncoding, StringBuilder stringBuilder, int minNumberBytes) throws IOException {
487 1 1. compressBodyIfRequested : negated conditional → KILLED
        String allContentEncodingHeaders = acceptEncoding != null ? String.join(";", acceptEncoding) : "";
488 4 1. compressBodyIfRequested : negated conditional → KILLED
2. compressBodyIfRequested : negated conditional → KILLED
3. compressBodyIfRequested : changed conditional boundary → KILLED
4. compressBodyIfRequested : negated conditional → KILLED
        if (response.getBodyLength() >= minNumberBytes && acceptEncoding != null && allContentEncodingHeaders.contains("gzip")) {
489
            stringBuilder.append("Content-Encoding: gzip" + HTTP_CRLF);
490
            stringBuilder.append("Vary: accept-encoding" + HTTP_CRLF);
491 1 1. compressBodyIfRequested : replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED
            return response.compressBody();
492
        }
493 1 1. compressBodyIfRequested : replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED
        return response;
494
    }
495
496
    /**
497
     * Looks through the mappings of {@link MethodPath} and path to registered endpoints
498
     * or the static cache and returns the appropriate one (If we
499
     * do not find anything, return null)
500
     */
501
    ThrowingFunction<IRequest, IResponse> findEndpointForThisStartline(RequestLine sl, Headers requestHeaders) {
502
        ThrowingFunction<IRequest, IResponse> handler;
503
        logger.logTrace(() -> "Seeking a handler for " + sl);
504
505
        // first we check if there's a simple direct match
506
        String requestedPath = sl.getPathDetails().getIsolatedPath().toLowerCase(Locale.ROOT);
507
508
        // if the user is asking for a HEAD request, they want to run a GET command
509
        // but don't want the body.  We'll simply exclude sending the body, later on, when returning the data
510 1 1. findEndpointForThisStartline : negated conditional → KILLED
        RequestLine.Method method = sl.getMethod() == RequestLine.Method.HEAD ? RequestLine.Method.GET : sl.getMethod();
511
512
        MethodPath key = new MethodPath(method, requestedPath);
513
        handler = registeredDynamicPaths.get(key);
514
515 1 1. findEndpointForThisStartline : negated conditional → KILLED
        if (handler == null) {
516
            logger.logTrace(() -> "No direct handler found.  looking for a partial match for " + requestedPath);
517
            handler = findHandlerByPartialMatch(sl);
518
        }
519
520 1 1. findEndpointForThisStartline : negated conditional → KILLED
        if (handler == null) {
521
            logger.logTrace(() -> "No partial match found, checking files on disk for " + requestedPath );
522
            handler = findHandlerByFilesOnDisk(sl, requestHeaders);
523
        }
524
525
        // we'll return this, and it could be a null.
526 1 1. findEndpointForThisStartline : replaced return value with null for com/renomad/minum/web/WebFramework::findEndpointForThisStartline → KILLED
        return handler;
527
    }
528
529
    /**
530
     * last ditch effort - look on disk.  This response will either
531
     * be the file to return, or null if we didn't find anything.
532
     */
533
    private ThrowingFunction<IRequest, IResponse> findHandlerByFilesOnDisk(RequestLine sl, Headers requestHeaders) {
534 2 1. findHandlerByFilesOnDisk : negated conditional → KILLED
2. findHandlerByFilesOnDisk : negated conditional → KILLED
        if (sl.getMethod() != RequestLine.Method.GET && sl.getMethod() != RequestLine.Method.HEAD) {
535
            return null;
536
        }
537
        String requestedPath = sl.getPathDetails().getIsolatedPath();
538
        IResponse response = readStaticFile(requestedPath, requestHeaders);
539 2 1. lambda$findHandlerByFilesOnDisk$27 : replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByFilesOnDisk$27 → KILLED
2. findHandlerByFilesOnDisk : replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByFilesOnDisk → KILLED
        return request -> response;
540
    }
541
542
543
    /**
544
     * Get a file from a path and create a response for it with a mime type.
545
     * <p>
546
     *     Parent directories are made unavailable by searching the path for
547
     *     bad characters.  See {@link FileUtils#badFilePathPatterns}
548
     * </p>
549
     *
550
     * @return a response with the file contents and caching headers and mime if valid.
551
     *  if the path has invalid characters, we'll return a "bad request" response.
552
     */
553
    IResponse readStaticFile(String path, Headers requestHeaders) {
554
        try {
555 1 1. readStaticFile : removed call to com/renomad/minum/utils/FileUtils::checkForBadFilePatterns → KILLED
            checkForBadFilePatterns(path);
556
        } catch (Exception ex) {
557
            logger.logDebug(() -> String.format("Bad path requested at readStaticFile: %s.  Exception: %s", path, ex.getMessage()));
558 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
            return Response.buildLeanResponse(CODE_400_BAD_REQUEST);
559
        }
560
        String mimeType = null;
561
562
        try {
563 1 1. readStaticFile : removed call to com/renomad/minum/utils/FileUtils::checkFileIsWithinDirectory → KILLED
            checkFileIsWithinDirectory(path, constants.staticFilesDirectory);
564
        } catch (Exception ex) {
565
            logger.logDebug(() -> String.format("Unable to find %s in allowed directories", path));
566 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
            return Response.buildLeanResponse(CODE_404_NOT_FOUND);
567
        }
568
569
        try {
570
            Path staticFilePath = Path.of(constants.staticFilesDirectory).resolve(path);
571 1 1. readStaticFile : negated conditional → KILLED
            if (!Files.isRegularFile(staticFilePath)) {
572
                logger.logDebug(() -> String.format("No readable regular file found at %s", path));
573 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return Response.buildLeanResponse(CODE_404_NOT_FOUND);
574
            }
575
576
            // if the provided path has a dot in it, use that
577
            // to obtain a suffix for determining file type
578
            int suffixBeginIndex = path.lastIndexOf('.');
579 2 1. readStaticFile : changed conditional boundary → SURVIVED
2. readStaticFile : negated conditional → KILLED
            if (suffixBeginIndex > 0) {
580 1 1. readStaticFile : Replaced integer addition with subtraction → KILLED
                String suffix = path.substring(suffixBeginIndex+1);
581
                mimeType = fileSuffixToMime.get(suffix);
582
            }
583
584
            // if we don't find any registered mime types for this
585
            // suffix, or if it doesn't have a suffix, set the mime type
586
            // to application/octet-stream
587 1 1. readStaticFile : negated conditional → KILLED
            if (mimeType == null) {
588
                mimeType = "application/octet-stream";
589
            }
590
591 2 1. readStaticFile : negated conditional → KILLED
2. readStaticFile : changed conditional boundary → KILLED
            if (Files.size(staticFilePath) < 100_000) {
592
                var fileContents = fileReader.readFile(staticFilePath.toString());
593 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return createOkResponseForStaticFiles(fileContents, mimeType);
594
            } else {
595 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return createOkResponseForLargeStaticFiles(mimeType, staticFilePath, requestHeaders);
596
            }
597
598
        } catch (IOException e) {
599
            logger.logAsyncError(() -> String.format("Error while reading file: %s. %s", path, StacktraceUtils.stackTraceToString(e)));
600 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
            return Response.buildLeanResponse(CODE_400_BAD_REQUEST);
601
        }
602
    }
603
604
    /**
605
     * All static responses will get a cache time of STATIC_FILE_CACHE_TIME seconds
606
     */
607
    private IResponse createOkResponseForStaticFiles(byte[] fileContents, String mimeType) {
608
        var headers = Map.of(
609
                "cache-control", "max-age=" + constants.staticFileCacheTime,
610
                "content-type", mimeType);
611
612 1 1. createOkResponseForStaticFiles : replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForStaticFiles → KILLED
        return Response.buildResponse(
613
                CODE_200_OK,
614
                headers,
615
                fileContents);
616
    }
617
618
    /**
619
     * All static responses will get a cache time of STATIC_FILE_CACHE_TIME seconds
620
     */
621
    private IResponse createOkResponseForLargeStaticFiles(String mimeType, Path filePath, Headers requestHeaders) throws IOException {
622
        var headers = Map.of(
623
                "cache-control", "max-age=" + constants.staticFileCacheTime,
624
                "content-type", mimeType,
625
                "Accept-Ranges", "bytes"
626
                );
627
628 1 1. createOkResponseForLargeStaticFiles : replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForLargeStaticFiles → KILLED
        return Response.buildLargeFileResponse(
629
                headers,
630
                filePath.toString(),
631
                requestHeaders
632
                );
633
    }
634
635
636
    /**
637
     * These are the default starting values for mappings
638
     * between file suffixes and appropriate mime types
639
     */
640
    private void addDefaultValuesForMimeMap() {
641
        fileSuffixToMime.put("css", "text/css");
642
        fileSuffixToMime.put("js", "application/javascript");
643
        fileSuffixToMime.put("webp", "image/webp");
644
        fileSuffixToMime.put("jpg", "image/jpeg");
645
        fileSuffixToMime.put("jpeg", "image/jpeg");
646
        fileSuffixToMime.put("htm", "text/html");
647
        fileSuffixToMime.put("html", "text/html");
648
    }
649
650
651
    /**
652
     * let's see if we can match the registered paths against a **portion** of the startline
653
     */
654
    ThrowingFunction<IRequest, IResponse> findHandlerByPartialMatch(RequestLine sl) {
655
        String requestedPath = sl.getPathDetails().getIsolatedPath();
656
        var methodPathFunctionEntry = registeredPartialPaths.entrySet().stream()
657 2 1. lambda$findHandlerByPartialMatch$32 : replaced boolean return with true for com/renomad/minum/web/WebFramework::lambda$findHandlerByPartialMatch$32 → KILLED
2. lambda$findHandlerByPartialMatch$32 : negated conditional → KILLED
                .filter(x -> requestedPath.startsWith(x.getKey().path()) &&
658 1 1. lambda$findHandlerByPartialMatch$32 : negated conditional → KILLED
                        x.getKey().method().equals(sl.getMethod()))
659
                .findFirst().orElse(null);
660 1 1. findHandlerByPartialMatch : negated conditional → KILLED
        if (methodPathFunctionEntry != null) {
661 1 1. findHandlerByPartialMatch : replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByPartialMatch → KILLED
            return methodPathFunctionEntry.getValue();
662
        } else {
663
            return null;
664
        }
665
    }
666
667
    /**
668
     * This constructor is used for the real production system
669
     */
670
    WebFramework(Context context) {
671
        this(context, null, null);
672
    }
673
674
    WebFramework(Context context, ZonedDateTime overrideForDateTime) {
675
        this(context, overrideForDateTime, null);
676
    }
677
678
    /**
679
     * This provides the ZonedDateTime as a parameter so we
680
     * can set the current date (for testing purposes)
681
     * @param overrideForDateTime for those test cases where we need to control the time
682
     */
683
    WebFramework(Context context, ZonedDateTime overrideForDateTime, IFileReader fileReader) {
684
        this.fs = context.getFullSystem();
685
        this.logger = context.getLogger();
686
        this.constants = context.getConstants();
687
        this.overrideForDateTime = overrideForDateTime;
688
        this.registeredDynamicPaths = new HashMap<>();
689
        this.registeredPartialPaths = new HashMap<>();
690
        this.underInvestigation = new UnderInvestigation(constants);
691
        this.inputStreamUtils = new InputStreamUtils(constants.maxReadLineSizeBytes);
692
        this.bodyProcessor = new BodyProcessor(context);
693
694
        // This random value is purely to help provide correlation between
695
        // error messages in the UI and error logs.  There are no security concerns.
696
        this.randomErrorCorrelationId = new Random();
697
        this.emptyRequestLine = RequestLine.EMPTY;
698
699
        // this allows us to inject a IFileReader for deeper testing
700 1 1. <init> : negated conditional → KILLED
        if (fileReader != null) {
701
            this.fileReader = fileReader;
702
        } else {
703
            this.fileReader = new FileReader(
704
                    LRUCache.getLruCache(constants.maxElementsLruCacheStaticFiles),
705
                    constants.useCacheForStaticFiles,
706
                    logger);
707
        }
708
        this.fileSuffixToMime = new HashMap<>();
709 1 1. <init> : removed call to com/renomad/minum/web/WebFramework::addDefaultValuesForMimeMap → KILLED
        addDefaultValuesForMimeMap();
710 1 1. <init> : removed call to com/renomad/minum/web/WebFramework::readExtraMimeMappings → KILLED
        readExtraMimeMappings(constants.extraMimeMappings);
711
    }
712
713
    void readExtraMimeMappings(List<String> input) {
714 2 1. readExtraMimeMappings : negated conditional → KILLED
2. readExtraMimeMappings : negated conditional → KILLED
        if (input == null || input.isEmpty()) return;
715
        mustBeTrue(input.size() % 2 == 0, "input must be even (key + value = 2 items). Your input: " + input);
716
717 2 1. readExtraMimeMappings : negated conditional → KILLED
2. readExtraMimeMappings : changed conditional boundary → KILLED
        for (int i = 0; i < input.size(); i += 2) {
718
            String fileSuffix = input.get(i);
719 1 1. readExtraMimeMappings : Replaced integer addition with subtraction → KILLED
            String mime = input.get(i+1);
720
            logger.logTrace(() -> "Adding mime mapping: " + fileSuffix + " -> " + mime);
721
            fileSuffixToMime.put(fileSuffix, mime);
722
        }
723
    }
724
725
    /**
726
     * Add a new handler in the web application for a combination
727
     * of a {@link RequestLine.Method}, a path, and then provide
728
     * the code to handle a request.
729
     * <br>
730
     * Note that the path text expected is *after* the first forward slash,
731
     * so for example with {@code http://foo.com/mypath}, provide "mypath" as the path.
732
     */
733
    public void registerPath(RequestLine.Method method, String pathName, ThrowingFunction<IRequest, IResponse> webHandler) {
734
        registeredDynamicPaths.put(new MethodPath(method, pathName), webHandler);
735
    }
736
737
    /**
738
     * Similar to {@link WebFramework#registerPath(RequestLine.Method, String, ThrowingFunction)} except that the paths
739
     * registered here may be partially matched.
740
     * <p>
741
     *     For example, if you register {@code .well-known/acme-challenge} then it
742
     *     can match a client request for {@code .well-known/acme-challenge/HGr8U1IeTW4kY_Z6UIyaakzOkyQgPr_7ArlLgtZE8SX}
743
     * </p>
744
     * <p>
745
     *     Be careful here, be thoughtful - partial paths will match a lot, and may
746
     *     overlap with other URL's for your app, such as endpoints and static files.
747
     * </p>
748
     */
749
    public void registerPartialPath(RequestLine.Method method, String pathName, ThrowingFunction<IRequest, IResponse> webHandler) {
750
        registeredPartialPaths.put(new MethodPath(method, pathName), webHandler);
751
    }
752
753
    /**
754
     * Sets a handler to process all requests across the board.
755
     * <br>
756
     * <p>
757
     *     This is an <b>unusual</b> method.  Setting a handler here allows the user to run code of his
758
     * choosing before the regular business code is run.  Note that by defining this value, the ordinary
759
     * call to endpoint.apply(request) will not be run.
760
     * </p>
761
     * <p>Here is an example</p>
762
     * <pre>{@code
763
     *
764
     *      webFramework.registerPreHandler(preHandlerInputs -> preHandlerCode(preHandlerInputs, auth, context));
765
     *
766
     *      ...
767
     *
768
     *      private IResponse preHandlerCode(PreHandlerInputs preHandlerInputs, AuthUtils auth, Context context) throws Exception {
769
     *          int secureServerPort = context.getConstants().secureServerPort;
770
     *          Request request = preHandlerInputs.clientRequest();
771
     *          ThrowingFunction<IRequest, IResponse> endpoint = preHandlerInputs.endpoint();
772
     *          ISocketWrapper sw = preHandlerInputs.sw();
773
     *
774
     *          // log all requests
775
     *          logger.logTrace(() -> String.format("Request: %s by %s",
776
     *              request.requestLine().getRawValue(),
777
     *              request.remoteRequester())
778
     *          );
779
     *
780
     *          // redirect to https if they are on the plain-text connection and the path is "login"
781
     *
782
     *          // get the path from the request line
783
     *          String path = request.getRequestLine().getPathDetails().getIsolatedPath();
784
     *
785
     *          // redirect to https on the configured secure port if they are on the plain-text connection and the path contains "login"
786
     *          if (path.contains("login") &&
787
     *              sw.getServerType().equals(HttpServerType.PLAIN_TEXT_HTTP)) {
788
     *              return Response.redirectTo("https://%s:%d/%s".formatted(sw.getHostName(), secureServerPort, path));
789
     *          }
790
     *
791
     *          // adjust behavior if non-authenticated and path includes "secure/"
792
     *          if (path.contains("secure/")) {
793
     *              AuthResult authResult = auth.processAuth(request);
794
     *              if (authResult.isAuthenticated()) {
795
     *                  return endpoint.apply(request);
796
     *              } else {
797
     *                  return Response.buildLeanResponse(CODE_403_FORBIDDEN);
798
     *              }
799
     *          }
800
     *
801
     *          // if the path does not include /secure, just move the request along unchanged.
802
     *          return endpoint.apply(request);
803
     *      }
804
     * }</pre>
805
     */
806
        public void registerPreHandler(ThrowingFunction<PreHandlerInputs, IResponse> preHandler) {
807
        this.preHandler = preHandler;
808
    }
809
810
    /**
811
     * Sets a handler to be executed after running the ordinary handler, just
812
     * before sending the response.
813
     * <p>
814
     *     This is an <b>unusual</b> method, so please be aware of its proper use. Its
815
     *     purpose is to allow the user to inject code to run after ordinary code, across
816
     *     all requests.
817
     * </p>
818
     * <p>
819
     *     For example, if the system would have returned a 404 NOT FOUND response,
820
     *     code can handle that situation in a switch case and adjust the response according
821
     *     to your programming.
822
     * </p>
823
     * <p>Here is an example</p>
824
     * <pre>{@code
825
     *
826
     *
827
     *      webFramework.registerLastMinuteHandler(TheRegister::lastMinuteHandlerCode);
828
     *
829
     * ...
830
     *
831
     *     private static IResponse lastMinuteHandlerCode(LastMinuteHandlerInputs inputs) {
832
     *         switch (inputs.response().statusCode()) {
833
     *             case CODE_404_NOT_FOUND -> {
834
     *                 return Response.buildResponse(
835
     *                         CODE_404_NOT_FOUND,
836
     *                         Map.of("Content-Type", "text/html; charset=UTF-8"),
837
     *                         "<p>No document was found</p>"));
838
     *             }
839
     *             case CODE_500_INTERNAL_SERVER_ERROR -> {
840
     *                 return Response.buildResponse(
841
     *                         CODE_500_INTERNAL_SERVER_ERROR,
842
     *                         Map.of("Content-Type", "text/html; charset=UTF-8"),
843
     *                         "<p>Server error occurred.</p>" ));
844
     *             }
845
     *             default -> {
846
     *                 return inputs.response();
847
     *             }
848
     *         }
849
     *     }
850
     * }
851
     * </pre>
852
     * @param lastMinuteHandler a function that will take a request and return a response, exactly like
853
     *                   we use in the other registration methods for this class.
854
     */
855
    public void registerLastMinuteHandler(ThrowingFunction<LastMinuteHandlerInputs, IResponse> lastMinuteHandler) {
856
        this.lastMinuteHandler = lastMinuteHandler;
857
    }
858
859
    /**
860
     * This allows users to add extra mappings
861
     * between file suffixes and mime types, in case
862
     * a user needs one that was not provided.
863
     * <p>
864
     *     This is made available through the
865
     *     web framework.
866
     * </p>
867
     * <p>
868
     *     Example:
869
     * </p>
870
     * <pre>
871
     * {@code webFramework.addMimeForSuffix().put("foo","text/foo")}
872
     * </pre>
873
     */
874
    public void addMimeForSuffix(String suffix, String mimeType) {
875
        fileSuffixToMime.put(suffix, mimeType);
876
    }
877
}

Mutations

52

1.1
Location : getSuffixToMimeMappings
Killed by : com.renomad.minum.web.WebFrameworkTests.test_ExtraMimeMappings(com.renomad.minum.web.WebFrameworkTests)
replaced return value with Collections.emptyMap for com/renomad/minum/web/WebFramework::getSuffixToMimeMappings → KILLED

102

1.1
Location : makePrimaryHttpHandler
Killed by : com.renomad.minum.web.WebFrameworkTests.test_makePrimaryHttpHandler_throwingIOException(com.renomad.minum.web.WebFrameworkTests)
replaced return value with null for com/renomad/minum/web/WebFramework::makePrimaryHttpHandler → KILLED

113

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

121

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

128

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/WebFramework::checkIfSuspiciousPath → KILLED

133

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.FunctionalTests
negated conditional → KILLED

142

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

148

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/WebFramework::addOptionalExtraHeaders → KILLED

149

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/WebFramework::addKeepAliveTimeout → KILLED

153

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/WebFramework::applyContentLength → KILLED

154

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/WebFramework::confirmBodyHasContentType → KILLED

157

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/ISocketWrapper::send → KILLED

162

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : none
negated conditional → TIMED_OUT

168

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : none
removed call to com/renomad/minum/web/Response::sendBody → TIMED_OUT

173

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

176

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : none
removed call to com/renomad/minum/web/WebFramework::handleReadTimedOut → SURVIVED
Covering tests

178

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : com.renomad.minum.FunctionalTests
removed call to com/renomad/minum/web/WebFramework::handleForbiddenUse → KILLED

180

1.1
Location : lambda$makePrimaryHttpHandler$5
Killed by : none
removed call to com/renomad/minum/web/WebFramework::handleIOException → SURVIVED
Covering tests

190

1.1
Location : handleIOException
Killed by : com.renomad.minum.web.WebFrameworkTests.testHandleIoException(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

2.2
Location : handleIOException
Killed by : com.renomad.minum.web.WebFrameworkTests.testHandleIoException(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

198

1.1
Location : handleForbiddenUse
Killed by : com.renomad.minum.web.WebFrameworkTests.test_HandleForbiddenUse(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

213

1.1
Location : handleReadTimedOut
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

232

1.1
Location : processRequest
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

237

1.1
Location : processRequest
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

257

1.1
Location : processRequest
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

261

1.1
Location : processRequest
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::processRequest → KILLED

280

1.1
Location : getHeaders
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::getHeaders → KILLED

288

1.1
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

290

1.1
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

291

1.1
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

295

1.1
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with false for com/renomad/minum/web/WebFramework::determineIfKeepAlive → KILLED

2.2
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with true for com/renomad/minum/web/WebFramework::determineIfKeepAlive → KILLED

307

1.1
Location : getProcessedRequestLine
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::getProcessedRequestLine → KILLED

313

1.1
Location : checkIfSuspiciousPath
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

325

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.web.WebFrameworkTests.test_makePrimaryHttpHandler_throwingIOException(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

326

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED

327

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

328

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED

330

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.FunctionalTests
removed call to com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED

331

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.FunctionalTests
replaced boolean return with false for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED

337

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

352

1.1
Location : isThereIsABody
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

354

1.1
Location : isThereIsABody
Killed by : com.renomad.minum.FunctionalTests
replaced boolean return with false for com/renomad/minum/web/WebFramework::isThereIsABody → KILLED

2.2
Location : isThereIsABody
Killed by : com.renomad.minum.web.WebTests
changed conditional boundary → KILLED

3.3
Location : isThereIsABody
Killed by : none
negated conditional → TIMED_OUT

358

1.1
Location : isThereIsABody
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

2.2
Location : lambda$isThereIsABody$19
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with false for com/renomad/minum/web/WebFramework::lambda$isThereIsABody$19 → KILLED

3.3
Location : lambda$isThereIsABody$19
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with true for com/renomad/minum/web/WebFramework::lambda$isThereIsABody$19 → KILLED

4.4
Location : isThereIsABody
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with true for com/renomad/minum/web/WebFramework::isThereIsABody → KILLED

5.5
Location : isThereIsABody
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

361

1.1
Location : isThereIsABody
Killed by : none
replaced boolean return with true for com/renomad/minum/web/WebFramework::isThereIsABody → SURVIVED
Covering tests

370

1.1
Location : lambda$addDefaultHeaders$20
Killed by : com.renomad.minum.FunctionalTests
replaced return value with null for com/renomad/minum/web/WebFramework::lambda$addDefaultHeaders$20 → KILLED

385

1.1
Location : addDefaultHeaders
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::addDefaultHeaders → KILLED

394

1.1
Location : lambda$addOptionalExtraHeaders$21
Killed by : com.renomad.minum.web.WebTests
replaced return value with "" for com/renomad/minum/web/WebFramework::lambda$addOptionalExtraHeaders$21 → KILLED

403

1.1
Location : lambda$confirmBodyHasContentType$22
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with true for com/renomad/minum/web/WebFramework::lambda$confirmBodyHasContentType$22 → KILLED

2.2
Location : lambda$confirmBodyHasContentType$22
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with false for com/renomad/minum/web/WebFramework::lambda$confirmBodyHasContentType$22 → KILLED

406

1.1
Location : confirmBodyHasContentType
Killed by : com.renomad.minum.web.WebTests
changed conditional boundary → KILLED

2.2
Location : confirmBodyHasContentType
Killed by : com.renomad.minum.web.BodyProcessorTests
negated conditional → KILLED

417

1.1
Location : addKeepAliveTimeout
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

445

1.1
Location : lambda$potentiallyCompress$23
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with false for com/renomad/minum/web/WebFramework::lambda$potentiallyCompress$23 → KILLED

2.2
Location : lambda$potentiallyCompress$23
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with true for com/renomad/minum/web/WebFramework::lambda$potentiallyCompress$23 → KILLED

447

1.1
Location : potentiallyCompress
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

450

1.1
Location : potentiallyCompress
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

451

1.1
Location : potentiallyCompress
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::potentiallyCompress → KILLED

454

1.1
Location : potentiallyCompress
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::potentiallyCompress → KILLED

469

1.1
Location : determineCompressible
Killed by : com.renomad.minum.web.WebFrameworkTests.test_CompressMoreMimeTypes(com.renomad.minum.web.WebFrameworkTests)
replaced boolean return with false for com/renomad/minum/web/WebFramework::determineCompressible → KILLED

2.2
Location : determineCompressible
Killed by : com.renomad.minum.web.WebFrameworkTests.test_CompressMoreMimeTypes(com.renomad.minum.web.WebFrameworkTests)
replaced boolean return with true for com/renomad/minum/web/WebFramework::determineCompressible → KILLED

487

1.1
Location : compressBodyIfRequested
Killed by : com.renomad.minum.web.WebFrameworkTests.test_compressIfRequested(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

488

1.1
Location : compressBodyIfRequested
Killed by : com.renomad.minum.web.WebFrameworkTests.test_compressIfRequested(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

2.2
Location : compressBodyIfRequested
Killed by : com.renomad.minum.web.WebFrameworkTests.test_compressIfRequested(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

3.3
Location : compressBodyIfRequested
Killed by : com.renomad.minum.web.WebTests
changed conditional boundary → KILLED

4.4
Location : compressBodyIfRequested
Killed by : com.renomad.minum.web.WebFrameworkTests.test_compressIfRequested(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

491

1.1
Location : compressBodyIfRequested
Killed by : com.renomad.minum.web.WebFrameworkTests.test_compressIfRequested(com.renomad.minum.web.WebFrameworkTests)
replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED

493

1.1
Location : compressBodyIfRequested
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED

510

1.1
Location : findEndpointForThisStartline
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

515

1.1
Location : findEndpointForThisStartline
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

520

1.1
Location : findEndpointForThisStartline
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

526

1.1
Location : findEndpointForThisStartline
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::findEndpointForThisStartline → KILLED

534

1.1
Location : findHandlerByFilesOnDisk
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

2.2
Location : findHandlerByFilesOnDisk
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

539

1.1
Location : lambda$findHandlerByFilesOnDisk$27
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByFilesOnDisk$27 → KILLED

2.2
Location : findHandlerByFilesOnDisk
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByFilesOnDisk → KILLED

555

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests.test_readStaticFile_Edge_OutsideDirectory(com.renomad.minum.web.WebFrameworkTests)
removed call to com/renomad/minum/utils/FileUtils::checkForBadFilePatterns → KILLED

558

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests.test_readStaticFile_Edge_OutsideDirectory(com.renomad.minum.web.WebFrameworkTests)
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

563

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/utils/FileUtils::checkFileIsWithinDirectory → KILLED

566

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests.test_readStaticFile_Edge_Directory(com.renomad.minum.web.WebFrameworkTests)
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

571

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests.test_readStaticFile_Edge_CurrentDirectory(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

573

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests.test_readStaticFile_Edge_CurrentDirectory(com.renomad.minum.web.WebFrameworkTests)
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

579

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests.test_readStaticFile_CSS(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

2.2
Location : readStaticFile
Killed by : none
changed conditional boundary → SURVIVED
Covering tests

580

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests.test_readStaticFile_CSS(com.renomad.minum.web.WebFrameworkTests)
Replaced integer addition with subtraction → KILLED

587

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests.test_Edge_ApplicationOctetStream(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

591

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests.test_readStaticFile_IOException(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

2.2
Location : readStaticFile
Killed by : com.renomad.minum.FunctionalTests
changed conditional boundary → KILLED

593

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests.test_Edge_ApplicationOctetStream(com.renomad.minum.web.WebFrameworkTests)
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

595

1.1
Location : readStaticFile
Killed by : com.renomad.minum.FunctionalTests
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

600

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests.test_readStaticFile_IOException(com.renomad.minum.web.WebFrameworkTests)
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

612

1.1
Location : createOkResponseForStaticFiles
Killed by : com.renomad.minum.web.WebFrameworkTests.test_Edge_ApplicationOctetStream(com.renomad.minum.web.WebFrameworkTests)
replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForStaticFiles → KILLED

628

1.1
Location : createOkResponseForLargeStaticFiles
Killed by : com.renomad.minum.FunctionalTests
replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForLargeStaticFiles → KILLED

657

1.1
Location : lambda$findHandlerByPartialMatch$32
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with true for com/renomad/minum/web/WebFramework::lambda$findHandlerByPartialMatch$32 → KILLED

2.2
Location : lambda$findHandlerByPartialMatch$32
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

658

1.1
Location : lambda$findHandlerByPartialMatch$32
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

660

1.1
Location : findHandlerByPartialMatch
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

661

1.1
Location : findHandlerByPartialMatch
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByPartialMatch → KILLED

700

1.1
Location : <init>
Killed by : com.renomad.minum.web.WebFrameworkTests.test_readStaticFile_IOException(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

709

1.1
Location : <init>
Killed by : com.renomad.minum.web.WebFrameworkTests.test_readStaticFile_CSS(com.renomad.minum.web.WebFrameworkTests)
removed call to com/renomad/minum/web/WebFramework::addDefaultValuesForMimeMap → KILLED

710

1.1
Location : <init>
Killed by : com.renomad.minum.FunctionalTests
removed call to com/renomad/minum/web/WebFramework::readExtraMimeMappings → KILLED

714

1.1
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebFrameworkTests.test_ExtraMimeMappings_BadSyntax(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

2.2
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebFrameworkTests.test_ExtraMimeMappings_Null(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

717

1.1
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebFrameworkTests.test_ExtraMimeMappings(com.renomad.minum.web.WebFrameworkTests)
negated conditional → KILLED

2.2
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebFrameworkTests.test_ExtraMimeMappings_NoValues(com.renomad.minum.web.WebFrameworkTests)
changed conditional boundary → KILLED

719

1.1
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebFrameworkTests.test_ExtraMimeMappings_NoValues(com.renomad.minum.web.WebFrameworkTests)
Replaced integer addition with subtraction → KILLED

Active mutators

Tests examined


Report generated by PIT 1.17.0