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.state.Constants;
7
import com.renomad.minum.state.Context;
8
import com.renomad.minum.utils.*;
9
10
import javax.net.ssl.SSLException;
11
import java.io.ByteArrayOutputStream;
12
import java.io.IOException;
13
import java.io.OutputStream;
14
import java.net.SocketException;
15
import java.net.SocketTimeoutException;
16
import java.nio.charset.StandardCharsets;
17
import java.nio.file.Path;
18
import java.time.ZoneId;
19
import java.time.ZonedDateTime;
20
import java.time.format.DateTimeFormatter;
21
import java.util.*;
22
import java.util.concurrent.ConcurrentHashMap;
23
import java.util.concurrent.locks.ReentrantLock;
24
import java.util.function.Function;
25
import java.util.zip.GZIPOutputStream;
26
27
import static com.renomad.minum.utils.FileUtils.checkForBadFilePatterns;
28
import static com.renomad.minum.web.StatusLine.StatusCode.*;
29
import static com.renomad.minum.web.WebEngine.HTTP_CRLF;
30
31
/**
32
 * This class is responsible for the HTTP handling after socket connection.
33
 * <p>
34
 *     The public methods are for registering endpoints - code that will be
35
 *     run for a given combination of HTTP method and path.  See documentation
36
 *     for the methods in this class.
37
 * </p>
38
 */
39
public final class WebFramework {
40
41
    private final Constants constants;
42
    private final IInputStreamUtils inputStreamUtils;
43
    private final IBodyProcessor bodyProcessor;
44
    /**
45
     * This is a variable storing a pseudo-random (non-secure) number
46
     * that is shown to users when a serious error occurs, which
47
     * will also be put in the logs, to make finding it easier.
48
     */
49
    private final Random randomErrorCorrelationId;
50
    private final RequestLine validRequestLine;
51
    private final ITheBrig theBrig;
52
    private final IFileUtils fileUtils;
53
54
    /**
55
     * This contains the directory path to the static files, as
56
     * specified in the configuration file.  See {@link Constants#staticFilesDirectory}
57
     */
58
    private final Path staticFilesDirectoryPathBase;
59
60
    public Map<String,String> getSuffixToMimeMappings() {
61 1 1. getSuffixToMimeMappings : replaced return value with Collections.emptyMap for com/renomad/minum/web/WebFramework::getSuffixToMimeMappings → KILLED
        return new HashMap<>(fileSuffixToMime);
62
    }
63
64
    /**
65
     * This is used as a key when registering endpoints
66
     */
67
    record MethodPath(RequestLine.Method method, String path) { }
68
69
    /**
70
     * The list of paths that our system is registered to handle.
71
     */
72
    private final Map<MethodPath, ThrowingFunction<IRequest, IResponse>> registeredDynamicPaths;
73
74
    /**
75
     * These are registrations for cases where the function depends on parts of the path conditionally.
76
     * Like if the client sends us GET /.well-known/acme-challenge/HGr8U1IeTW4kY_Z6UIyaakzOkyQgPr_7ArlLgtZE8SX
77
     * and we want to match ".well-known/acme-challenge"
78
     */
79
    private final Map<RequestLine.Method, List<Function<String, ThrowingFunction<IRequest, IResponse>>>> registeredPathFunctions;
80
81
    /**
82
     * A special path function that checks if the path starts with the defined one.
83
     * It's here to retain the duplication check on {@link #registerPartialPath(RequestLine.Method, String, ThrowingFunction)},
84
     */
85
    private record PartialPathFunction(String pathName, ThrowingFunction<IRequest, IResponse> handler) implements Function<String, ThrowingFunction<IRequest, IResponse>> {
86
        @Override
87
        public ThrowingFunction<IRequest, IResponse> apply(String path) {
88 1 1. apply : negated conditional → KILLED
            return path.startsWith(pathName) ? handler : null;
89
        }
90
    }
91
92
    /**
93
     * A function that will be run instead of the ordinary business code. Has
94
     * provisions for running the business code as well.  See {@link #registerPreHandler(ThrowingFunction)}
95
     */
96
    private ThrowingFunction<PreHandlerInputs, IResponse> preHandler;
97
98
    /**
99
     * A function run after the ordinary business code
100
     */
101
    private ThrowingFunction<LastMinuteHandlerInputs, IResponse> lastMinuteHandler;
102
103
    private final IFileReader fileReader;
104
105
    /**
106
     * A map between a key of file suffixes and a value of mime type,
107
     * used for determining a proper mime for response on a file in
108
     * the static files directory
109
     */
110
    private final Map<String, String> fileSuffixToMime;
111
112
    /**
113
     * This is a map of path to a boolean valuable for whether the
114
     * file benefits from compression.
115
     */
116
    private final Map<String, Boolean> fileIsCompressible;
117
118
    // This is just used for testing.  If it's null, we use the real time.
119
    private final ZonedDateTime overrideForDateTime;
120
    private final FullSystem fs;
121
    private final ILogger logger;
122
123
    /**
124
     * For static files (See {@link Constants#staticFilesDirectory}), This is
125
     * the cutoff for the maximum quantity of bytes where we will
126
     * use {@link FileReader#readFile(String)} and caching for the data.
127
     * Past this point, we will use {@link #createOkResponseForLargeStaticFiles}
128
     * and not use caching.
129
     */
130
    static final int MAX_CACHED_BYTES = 100_000;
131
132
    void httpProcessing(ISocketWrapper sw) {
133
        try (sw) {
134
            final var is = sw.getInputStream();
135
136
            // By default, browsers expect the server to run in keep-alive mode.
137
            // We'll break out later if we find that the browser doesn't do keep-alive
138
            while (true) {
139
                dumpIfAttacker(sw, fs);
140
                // we'll store the status line and headers in this
141
                StringBuilder headerStringBuilder = new StringBuilder(600); // 600 is just a magic arbitrary number I picked, because our response headers
142
                // are not usually too large - even if the user added a bunch, there is a good
143
                // chance it would be far under 600.  If that turns out to be wrong, adjust/redesign
144
145
                // set some basic variables we'll need access to throughout
146
                long startMillis = System.currentTimeMillis();
147
                RequestLine requestLine;
148
                IRequest request;
149
                Headers headers;
150
                IResponse response;
151
                boolean isKeepAlive;
152
                IResponse adjustedResponse;
153
                boolean isHeadRequest = false;
154
155
                final String rawStartLine = inputStreamUtils.readLine(is);
156
157
                try {
158 2 1. httpProcessing : negated conditional → KILLED
2. httpProcessing : negated conditional → KILLED
                    if (rawStartLine == null || rawStartLine.isEmpty()) {
159
                        // here, the client connected, sent nothing, and closed.
160
                        // nothing to do but return.
161
                        logger.logTrace(() -> "rawStartLine was empty.  Returning.");
162
                        break;
163
                    }
164
                    requestLine = getProcessedRequestLine(sw, rawStartLine);
165
166
                    // check if the user is seeming to attack us.
167 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::checkIfSuspiciousPath → KILLED
                    checkIfSuspiciousPath(sw, requestLine);
168
169
                    // React to what the user requested, generate a result
170
                    headers = getHeaders(sw);
171
                    request = new Request(headers, requestLine, sw.getRemoteAddr(), sw, bodyProcessor, false);
172
                    response = processRequest(request, sw, requestLine, headers);
173
174
                    // check that the response is non-null.  If it is null, that suggests
175
                    // the developer made a mistake.
176 1 1. httpProcessing : negated conditional → KILLED
                    if (response == null) {
177
                        throw new WebServerException("The returned value for the endpoint \"%s\" was null.".formatted(request.getRequestLine().getPathDetails().getIsolatedPath()));
178
                    }
179
180
                    isKeepAlive = determineIfKeepAlive(request, logger, request.hasAccessedBody());
181
182
                    // calculate proper headers for the response
183 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::addDefaultHeaders → TIMED_OUT
                    addDefaultHeaders(response, headerStringBuilder);
184 1 1. httpProcessing : removed call to com/renomad/minum/web/Headers::appendHeadersToBuilder → KILLED
                    response.getExtraHeaders().appendHeadersToBuilder(headerStringBuilder);
185 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::addKeepAliveTimeout → KILLED
                    addKeepAliveTimeout(isKeepAlive, headerStringBuilder);
186
187
                    // if the response is text (i.e. probably good compressibility) and large enough
188
                    // to be worth compressing, we'll compress it.
189 3 1. httpProcessing : negated conditional → TIMED_OUT
2. httpProcessing : changed conditional boundary → TIMED_OUT
3. httpProcessing : negated conditional → KILLED
                    if (response.isBodyText() && response.getBodyLength() > 500) {
190
                        List<String> acceptEncoding = headers.valueByKey("accept-encoding");
191
                        adjustedResponse = compressBodyIfRequested(response, acceptEncoding, headerStringBuilder, logger, request.getRequestLine().getRawValue());
192
                    } else {
193
                        adjustedResponse = response;
194
                    }
195
196 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::applyContentLength → KILLED
                    applyContentLength(headerStringBuilder, adjustedResponse.getBodyLength());
197 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::confirmBodyHasContentType → KILLED
                    confirmBodyHasContentType(request, response);
198
199
                    // if the user sent a HEAD request, we send everything back except the body.
200
                    // even though we skip the body, this requires full processing to get the
201
                    // numbers right, like content-length.
202 1 1. httpProcessing : negated conditional → TIMED_OUT
                    if (request.getRequestLine().getMethod().equals(RequestLine.Method.HEAD)) {
203
                        logger.logDebug(() -> "client " + request.getRemoteRequester() +
204
                                " is requesting HEAD for " + request.getRequestLine().getPathDetails().getIsolatedPath() +
205
                                ".  Excluding body from response");
206
                        isHeadRequest = true;
207
                    }
208
209
                } catch (BadRequestException ex) {
210
                    // this catch block needs to be down below the scope where
211
                    // the request variable is needed.
212 1 1. httpProcessing : removed call to java/lang/StringBuilder::setLength → KILLED
                    headerStringBuilder.setLength(0); // clear the contents
213
                    adjustedResponse = handleBadRequestException(ex);
214 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::addDefaultHeaders → TIMED_OUT
                    addDefaultHeaders(adjustedResponse, headerStringBuilder);
215
                    isKeepAlive = false;
216
                    headerStringBuilder.append("Content-Length: ").append(adjustedResponse.getBodyLength()).append(HTTP_CRLF);
217
                }
218
219
                // send the headers
220 1 1. httpProcessing : removed call to com/renomad/minum/web/ISocketWrapper::send → TIMED_OUT
                sw.send(headerStringBuilder.append(HTTP_CRLF).toString().getBytes(StandardCharsets.US_ASCII));
221
222 1 1. httpProcessing : negated conditional → TIMED_OUT
                if (!isHeadRequest) {
223
                    // send the body
224 1 1. httpProcessing : removed call to com/renomad/minum/web/IResponse::sendBody → KILLED
                    adjustedResponse.sendBody(sw);
225
                }
226
227
                // ship it out
228 1 1. httpProcessing : removed call to com/renomad/minum/web/ISocketWrapper::flush → TIMED_OUT
                sw.flush();
229
230
                // print how long this processing took
231
                long endMillis = System.currentTimeMillis();
232
                logger.logTrace(() -> String.format("full processing (including communication time) of %s %s took %d millis", sw, rawStartLine, endMillis - startMillis));
233
234 1 1. httpProcessing : negated conditional → TIMED_OUT
                if (!isKeepAlive) {
235
                    logger.logTrace(() -> "We will not keep-alive this connection - exiting loop and closing socket");
236
                    break;
237
                }
238
239
            }
240
        } catch (ForbiddenUseException ex) {
241 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::handleForbiddenUse → TIMED_OUT
            handleForbiddenUse(sw, ex, logger, theBrig, constants.vulnSeekingJailDuration);
242
        } catch (Exception ex) {
243 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::finalExceptionHandler → TIMED_OUT
            finalExceptionHandler(sw, ex, logger, theBrig, constants.vulnSeekingJailDuration, constants.suspiciousErrors);
244
        }
245
    }
246
247
248
    /**
249
     * Last-chance handler for any exceptions originating in WebFramework.httpProcessing
250
     */
251
    static void finalExceptionHandler(ISocketWrapper sw, Throwable ex, ILogger logger, ITheBrig theBrig,
252
                                      long vulnSeekingJailDuration, Set<String> suspiciousErrors) {
253
        // This first section catches a lot when clients make eager connections in anticipation of
254
        // parallel requests, but then let them time out.
255 2 1. finalExceptionHandler : negated conditional → KILLED
2. finalExceptionHandler : negated conditional → KILLED
        if (ex instanceof SocketException || ex instanceof SocketTimeoutException) {
256 1 1. finalExceptionHandler : negated conditional → SURVIVED
            if (ex.getMessage().equals("Read timed out")) {
257
                logger.logTrace(() -> "Read timed out - remote address: " + sw.getRemoteAddrWithPort());
258
            } else {
259
                logger.logDebug(() -> ex.getMessage() + " - remote address: " + sw.getRemoteAddrWithPort());
260
            }
261 2 1. finalExceptionHandler : negated conditional → KILLED
2. finalExceptionHandler : negated conditional → KILLED
        } else if (suspiciousErrors.contains(ex.getMessage()) && theBrig != null) {
262
            logger.logDebug(() -> sw.getRemoteAddr() + " is looking for vulnerabilities, for this: " + ex.getMessage());
263
            theBrig.sendToJail(sw.getRemoteAddr() + "_vuln_seeking", vulnSeekingJailDuration);
264 1 1. finalExceptionHandler : negated conditional → TIMED_OUT
        } else if (ex instanceof SSLException) {
265
            // at this point we just want to catch some of the common garbage exceptions that bubble up
266
            // as a result of clients force-closing their SSl connections
267
            logger.logTrace(() -> ex.getMessage() + "for remote address: " + sw.getRemoteAddrWithPort());
268
        } else {
269
            logger.logWarn(() -> "Exception caught in WebFramework.finalExceptionHandler: " + StacktraceUtils.stackTraceToString(ex));
270
        }
271
    }
272
273
    static void handleForbiddenUse(ISocketWrapper sw, ForbiddenUseException ex, ILogger logger, ITheBrig theBrig, long vulnSeekingJailDuration) {
274
        logger.logDebug(() -> sw.getRemoteAddr() + " is looking for vulnerabilities, for this: " + ex.getMessage());
275 1 1. handleForbiddenUse : negated conditional → KILLED
        if (theBrig != null) {
276
            theBrig.sendToJail(sw.getRemoteAddr() + "_vuln_seeking", vulnSeekingJailDuration);
277
        } else {
278
            logger.logDebug(() -> "theBrig is null at handleForbiddenUse, will not store address in database");
279
        }
280
    }
281
282
    /**
283
     * if an error happens in parsing a request, and it's not considered an attack (which
284
     * would instead use ForbiddenUseException), this is the
285
     * last-chance handling of that error where we return a 400 Bad Request response and a
286
     * random code to the client, so a developer can find the detailed
287
     * information in the logs, which have that same value.
288
     */
289
    IResponse handleBadRequestException(BadRequestException ex) {
290
        int randomNumber = randomErrorCorrelationId.nextInt();
291
        logger.logDebug(() -> "Bad data in request. Code: " + randomNumber + " Error: " + ex.getMessage() + (ex.getCause() == null ? "" : " Cause: " + ex.getCause().getMessage()));
292 1 1. handleBadRequestException : replaced return value with null for com/renomad/minum/web/WebFramework::handleBadRequestException → TIMED_OUT
        return Response.buildResponse(CODE_400_BAD_REQUEST, new Headers(List.of("Content-Type: text/plain;charset=UTF-8")), "Bad request from user (HTTP 400) error: " + randomNumber);
293
    }
294
295
    /**
296
     * Logic for how to process an incoming request.  For example, did the developer
297
     * write a function to handle this? Is it a request for a static file, like an image
298
     * or script?  Did the user provide a "pre" or "post" handler?
299
     */
300
    IResponse processRequest(
301
            IRequest clientRequest,
302
            ISocketWrapper sw,
303
            RequestLine requestLine,
304
            Headers requestHeaders) throws Exception {
305
        IResponse response;
306
        ThrowingFunction<IRequest, IResponse> endpoint = findEndpointForThisStartline(requestLine, requestHeaders);
307 1 1. processRequest : negated conditional → KILLED
        if (endpoint == null) {
308
            response = Response.buildLeanResponse(CODE_404_NOT_FOUND);
309
        } else {
310
            long millisAtStart = System.currentTimeMillis();
311
            try {
312 1 1. processRequest : negated conditional → TIMED_OUT
                if (preHandler != null) {
313
                    response = preHandler.apply(new PreHandlerInputs(clientRequest, endpoint, sw));
314
                } else {
315
                    response = endpoint.apply(clientRequest);
316
                }
317
            } catch (Exception ex) {
318
                // if an error happens while running an endpoint's code, this is the
319
                // last-chance handling of that error where we return a 500 and a
320
                // random code to the client, so a developer can find the detailed
321
                // information in the logs, which have that same value.
322
                int randomNumber = randomErrorCorrelationId.nextInt();
323
                logger.logAsyncError(() -> "error while running endpoint " + endpoint + ". Code: " + randomNumber + ". Error: " + StacktraceUtils.stackTraceToString(ex));
324
                response = Response.buildResponse(CODE_500_INTERNAL_SERVER_ERROR, new Headers(List.of("Content-Type: text/plain;charset=UTF-8")), "Server error: " + randomNumber);
325
            }
326
            long millisAtEnd = System.currentTimeMillis();
327
            logger.logTrace(() -> String.format("handler processing of %s %s took %d millis", sw, requestLine, millisAtEnd - millisAtStart));
328
        }
329
330 1 1. processRequest : negated conditional → KILLED
        if (lastMinuteHandler != null) {
331
            response = lastMinuteHandler.apply(new LastMinuteHandlerInputs(clientRequest, response));
332
        }
333
334 1 1. processRequest : replaced return value with null for com/renomad/minum/web/WebFramework::processRequest → KILLED
        return response;
335
    }
336
337
    private Headers getHeaders(ISocketWrapper sw) throws IOException {
338
    /*
339
       next we will read the headers (e.g. Content-Type: foo/bar) one-by-one.
340
341
       the headers tell us vital information about the
342
       body.  If, for example, we're getting a POST and receiving a
343
       www form url encoded, there will be a header of "content-length"
344
       that will mention how many bytes to read.  On the other hand, if
345
       we're receiving a multipart, there will be no content-length, but
346
       the content-type will include the boundary string.
347
    */
348
        List<String> allHeaders = Headers.getAllHeaders(sw.getInputStream(), inputStreamUtils);
349
        Headers hi = new Headers(allHeaders);
350
        logger.logTrace(() -> "The headers are: " + hi.getHeaderStrings());
351 1 1. getHeaders : replaced return value with null for com/renomad/minum/web/WebFramework::getHeaders → KILLED
        return hi;
352
    }
353
354
    /**
355
     * determine if we are in a keep-alive connection.
356
     * <p>
357
     *     This checks the headers and request-line for characteristics
358
     *     which require keep-alive on or off.
359
     * </p>
360
     * <p>
361
     *     It also checks whether there are lingering unread bytes from
362
     *     a request.  If there are, it will set keep-alive to false, so
363
     *     that the following request will encounter a clean starting point.
364
     *     Lingering bytes could occur if the responsible handler does not
365
     *     read the body bytes sent to it.
366
     * </p>
367
     * <p>
368
     *     The algorithm is:
369
     *     <ul>
370
     *         <li>If the HTTP version is 1.0, then we keep-alive if there is a header telling us to</li>
371
     *         <li>If the HTTP version is 1.1, then we *stop* keep-alive if there is a header telling us to</li>
372
     *         <li>If we are keep-alive, but there are lingering body bytes that have not been read by
373
     *         the handler, set keep-alive to false</li>
374
     *     </ul>
375
     * </p>
376
     */
377
    static boolean determineIfKeepAlive(IRequest request, ILogger logger, boolean hasAccessedBody) {
378
        boolean isKeepAlive = false;
379 1 1. determineIfKeepAlive : negated conditional → KILLED
        if (request.getRequestLine().getVersion() == HttpVersion.ONE_DOT_ZERO) {
380
            isKeepAlive = request.getHeaders().hasKeepAlive();
381 1 1. determineIfKeepAlive : negated conditional → KILLED
        } else if (request.getRequestLine().getVersion() == HttpVersion.ONE_DOT_ONE) {
382 1 1. determineIfKeepAlive : negated conditional → KILLED
            isKeepAlive = ! request.getHeaders().hasConnectionClose();
383
        }
384
385 4 1. determineIfKeepAlive : changed conditional boundary → TIMED_OUT
2. determineIfKeepAlive : negated conditional → KILLED
3. determineIfKeepAlive : negated conditional → KILLED
4. determineIfKeepAlive : negated conditional → KILLED
        if (isKeepAlive && request.getHeaders().contentLength() >= 0 && !hasAccessedBody) {
386
            // if there was a body and the user has not read it by this point, we will log the
387
            // discrepancy and close the socket.
388
            logger.logDebug(() -> ("A body sized %d bytes was included in the request, but the endpoint (%s) did not access the body. " +
389
                    "Closing socket after request is finished").formatted(request.getHeaders().contentLength(), request.getRequestLine().getPathDetails().getIsolatedPath()));
390
            isKeepAlive = false;
391
        }
392
393
        boolean finalIsKeepAlive = isKeepAlive;
394
395
        logger.logTrace(() -> "Is this a keep-alive connection? %s".formatted(finalIsKeepAlive));
396 2 1. determineIfKeepAlive : replaced boolean return with false for com/renomad/minum/web/WebFramework::determineIfKeepAlive → TIMED_OUT
2. determineIfKeepAlive : replaced boolean return with true for com/renomad/minum/web/WebFramework::determineIfKeepAlive → KILLED
        return finalIsKeepAlive;
397
    }
398
399
    RequestLine getProcessedRequestLine(ISocketWrapper sw, String rawStartLine) {
400
        logger.logTrace(() -> sw + ": raw request line received: " + rawStartLine);
401
402
        RequestLine extractedRequestLine = validRequestLine.extractRequestLine(rawStartLine);
403
        logger.logTrace(() -> sw + ": RequestLine has been derived: " + extractedRequestLine);
404 1 1. getProcessedRequestLine : replaced return value with null for com/renomad/minum/web/WebFramework::getProcessedRequestLine → KILLED
        return extractedRequestLine;
405
    }
406
407
    void checkIfSuspiciousPath(ISocketWrapper sw, RequestLine requestLine) {
408 1 1. checkIfSuspiciousPath : negated conditional → KILLED
        if (constants.suspiciousPaths.contains(requestLine.getPathDetails().getIsolatedPath())) {
409
            String msg = sw.getRemoteAddr() + " is looking for a vulnerability, for this: " + requestLine.getPathDetails().getIsolatedPath();
410
            throw new ForbiddenUseException(msg);
411
        }
412
    }
413
414
    /**
415
     * Drops the connection immediately if the client is recognized
416
     * as someone we consider an attacker, by dint of having been
417
     * added to a blacklist in {@link com.renomad.minum.security.TheBrig}
418
     * with a suffix of "_vuln_seeking"
419
     */
420
    boolean dumpIfAttacker(ISocketWrapper sw, FullSystem fs) {
421 1 1. dumpIfAttacker : negated conditional → KILLED
        if (fs == null) {
422 1 1. dumpIfAttacker : replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return false;
423 1 1. dumpIfAttacker : negated conditional → KILLED
        } else if (fs.getTheBrig() == null) {
424 1 1. dumpIfAttacker : replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return false;
425
        } else {
426 1 1. dumpIfAttacker : removed call to com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            dumpIfAttacker(sw, fs.getTheBrig());
427 1 1. dumpIfAttacker : replaced boolean return with false for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return true;
428
        }
429
    }
430
431
    /**
432
     * For documentation, see {@link #dumpIfAttacker(ISocketWrapper, FullSystem)}
433
     */
434
    void dumpIfAttacker(ISocketWrapper sw, ITheBrig theBrig) {
435
        String remoteClient = sw.getRemoteAddr();
436 1 1. dumpIfAttacker : negated conditional → KILLED
        if (theBrig.isInJail(remoteClient + "_vuln_seeking")) {
437
            // if this client is a vulnerability seeker, throw an exception,
438
            // causing them to get dumped unceremoniously
439
            String message = "closing the socket on " + remoteClient + " due to being found in the brig";
440
            logger.logDebug(() -> message);
441
            throw new ForbiddenUseException(message);
442
        }
443
    }
444
445
    /**
446
     * Prepare some of the basic server response headers, like the status code, the
447
     * date-time stamp, the server name.
448
     */
449
    private void addDefaultHeaders(IResponse response, StringBuilder headerStringBuilder) {
450
        String date = Objects.requireNonNullElseGet(overrideForDateTime,
451 1 1. lambda$addDefaultHeaders$20 : replaced return value with null for com/renomad/minum/web/WebFramework::lambda$addDefaultHeaders$20 → KILLED
                () -> ZonedDateTime.now(ZoneId.of("UTC"))).format(DateTimeFormatter.RFC_1123_DATE_TIME);
452
453
        // add the status line
454
        headerStringBuilder.append("HTTP/1.1 ").append(response.getStatusCode().code).append(" ").append(response.getStatusCode().shortDescription).append(HTTP_CRLF);
455
456
        // add a date-timestamp
457
        headerStringBuilder.append("Date: ").append(date).append(HTTP_CRLF);
458
459
        // add the server name
460
        headerStringBuilder.append("Server: minum").append(HTTP_CRLF);
461
    }
462
463
    /**
464
     * If a response body exists, it needs to have a content-type specified,
465
     * or throw an exception. Otherwise, the user could totally miss they did
466
     * not set a content-type, because the browser will inspect the data and
467
     * do sort-of-the-right-thing a lot of the time, but we want to enforce correctness.
468
     */
469
    static void confirmBodyHasContentType(IRequest request, IResponse response) {
470
        // check the correctness of the content-type header versus the data length (if any data, that is)
471 1 1. confirmBodyHasContentType : negated conditional → KILLED
        boolean hasContentType = response.getExtraHeaders().valueByKey("content-type") != null;
472
473
        // if there *is* data, we had better be returning a content type
474 3 1. confirmBodyHasContentType : negated conditional → KILLED
2. confirmBodyHasContentType : changed conditional boundary → KILLED
3. confirmBodyHasContentType : negated conditional → KILLED
        if (response.getBodyLength() > 0 && !hasContentType) {
475
            throw new WebServerException("a Content-Type header must be specified in the Response object if it returns data. Response details: " + response + " Request: " + request);
476
        }
477
    }
478
479
    /**
480
     * If this is a keep-alive communication, add a header specifying the
481
     * socket timeout for the browser.
482
     */
483
    private void addKeepAliveTimeout(boolean isKeepAlive, StringBuilder stringBuilder) {
484
        // if we're a keep-alive connection, reply with a keep-alive header
485 1 1. addKeepAliveTimeout : negated conditional → TIMED_OUT
        if (isKeepAlive) {
486
            stringBuilder.append("Keep-Alive: timeout=").append(constants.keepAliveTimeoutSeconds).append(HTTP_CRLF);
487
        }
488
    }
489
490
    /**
491
     * The rules regarding the content-length header are byzantine.  Even in the cases
492
     * where you aren't returning anything, servers can use this header to determine when the
493
     * response is finished.
494
     * See <a href="https://www.rfc-editor.org/rfc/rfc9110.html#name-content-length">Content-Length in the HTTP spec</a>
495
     */
496
    private static void applyContentLength(StringBuilder stringBuilder, long bodyLength) {
497
        stringBuilder.append("Content-Length: ").append(bodyLength).append(HTTP_CRLF);
498
    }
499
500
    /**
501
     * This method will examine the content-encoding headers, and if "gzip" is
502
     * requested by the client, we will replace the body bytes with compressed
503
     * bytes, using the GZIP compression algorithm.
504
     *
505
     * @param acceptEncoding headers sent by the client about what compression
506
     *                       algorithms will be understood.
507
     * @param stringBuilder  the string we are gradually building up to send back to
508
     *                       the client for the status line and headers. We'll use it
509
     *                       here if we need to append a content-encoding - that is,
510
     *                       if we successfully compress data as gzip.
511
     * @param endpointPath the endpoint whose data we are compressing, e.g. "foo?bar=baz",
512
     *                     used for logging.
513
     */
514
    static IResponse compressBodyIfRequested(IResponse response, List<String> acceptEncoding, StringBuilder stringBuilder, ILogger logger, String endpointPath) {
515 1 1. compressBodyIfRequested : negated conditional → KILLED
        String allContentEncodingHeaders = acceptEncoding != null ? String.join(";", acceptEncoding) : "";
516 1 1. compressBodyIfRequested : negated conditional → KILLED
        if (allContentEncodingHeaders.contains("gzip")) {
517
            stringBuilder.append("Content-Encoding: gzip").append(HTTP_CRLF);
518
            stringBuilder.append("Vary: accept-encoding").append(HTTP_CRLF);
519
            var out = new ByteArrayOutputStream();
520 1 1. compressBodyIfRequested : removed call to com/renomad/minum/web/WebFramework::compressBody → SURVIVED
            compressBody(out, response.getBody());
521
            logger.logTrace(() -> "Compressing results of %s.  Compression ratio: %d%%. Original size: %d bytes. Compressed size: %d bytes".formatted(endpointPath,
522 2 1. lambda$compressBodyIfRequested$21 : Replaced double multiplication with division → SURVIVED
2. lambda$compressBodyIfRequested$21 : Replaced double division with multiplication → SURVIVED
                    Math.round(((double) out.size() / (double) response.getBodyLength()) * 100), response.getBodyLength(), out.size()));
523 1 1. compressBodyIfRequested : replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED
            return Response.buildResponse(
524
                    response.getStatusCode(),
525
                    response.getExtraHeaders(),
526
                    out.toByteArray()
527
            );
528
        }
529 1 1. compressBodyIfRequested : replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED
        return response;
530
    }
531
532
    /**
533
     * Compress the data in this body using gzip.
534
     * <br>
535
     * This operates by getting the body field from this instance of {@link Response} and
536
     * creating a new Response with the compressed data.
537
     * @param out this is provided as a parameter for better control during testing
538
     */
539
    static void compressBody(OutputStream out, byte[] body) {
540
        try (var gos = new GZIPOutputStream(out)) {
541 1 1. compressBody : removed call to java/util/zip/GZIPOutputStream::write → KILLED
            gos.write(body);
542 1 1. compressBody : removed call to java/util/zip/GZIPOutputStream::finish → TIMED_OUT
            gos.finish();
543
        } catch (IOException e) {
544
            throw new WebServerException("Error in Response.compressBody", e);
545
        }
546
    }
547
548
    /**
549
     * Looks through the mappings of {@link MethodPath} and path to registered endpoints
550
     * or the static cache and returns the appropriate one (If we
551
     * do not find anything, return null)
552
     */
553
    ThrowingFunction<IRequest, IResponse> findEndpointForThisStartline(RequestLine sl, Headers requestHeaders) {
554
        ThrowingFunction<IRequest, IResponse> handler;
555
        logger.logTrace(() -> "Seeking a handler for " + sl);
556
557
        // first we check if there's a simple direct match
558
        String requestedPath = sl.getPathDetails().getIsolatedPath().toLowerCase(Locale.ROOT);
559
560
        // if the user is asking for a HEAD request, they want to run a GET command
561
        // but don't want the body.  We'll simply exclude sending the body, later on, when returning the data
562 1 1. findEndpointForThisStartline : negated conditional → KILLED
        RequestLine.Method method = sl.getMethod() == RequestLine.Method.HEAD ? RequestLine.Method.GET : sl.getMethod();
563
564
        MethodPath key = new MethodPath(method, requestedPath);
565
        handler = registeredDynamicPaths.get(key);
566
567 1 1. findEndpointForThisStartline : negated conditional → KILLED
        if (handler == null) {
568
            logger.logTrace(() -> "No direct handler found.  looking for a partial match for " + requestedPath);
569
            handler = findHandlerByPathFunction(sl);
570
        }
571
572 1 1. findEndpointForThisStartline : negated conditional → KILLED
        if (handler == null) {
573
            logger.logTrace(() -> "No partial match found, checking files on disk for " + requestedPath );
574
            handler = findHandlerByFilesOnDisk(sl, requestHeaders);
575
        }
576
577
        // we'll return this, and it could be a null.
578 1 1. findEndpointForThisStartline : replaced return value with null for com/renomad/minum/web/WebFramework::findEndpointForThisStartline → TIMED_OUT
        return handler;
579
    }
580
581
    /**
582
     * last ditch effort - look on disk.  This response will either
583
     * be the file to return, or null if we didn't find anything.
584
     * The request method has to be GET or HEAD.
585
     */
586
    private ThrowingFunction<IRequest, IResponse> findHandlerByFilesOnDisk(RequestLine sl, Headers requestHeaders) {
587 2 1. findHandlerByFilesOnDisk : negated conditional → TIMED_OUT
2. findHandlerByFilesOnDisk : negated conditional → KILLED
        if (sl.getMethod() == RequestLine.Method.GET || sl.getMethod() == RequestLine.Method.HEAD) {
588
            String requestedPath = sl.getPathDetails().getIsolatedPath();
589
            IResponse response = readStaticFile(requestedPath, requestHeaders);
590 2 1. lambda$findHandlerByFilesOnDisk$25 : replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByFilesOnDisk$25 → TIMED_OUT
2. findHandlerByFilesOnDisk : replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByFilesOnDisk → KILLED
            return request -> response;
591
        } else {
592
            return null;
593
        }
594
    }
595
596
597
    /**
598
     * Get a file from a path and create a response for it with a mime type.
599
     * <p>
600
     *     Parent directories are made unavailable by searching the path for
601
     *     bad characters. see {@link FileUtils#checkForBadFilePatterns}
602
     * </p>
603
     *
604
     * @return a response with the file contents and caching headers and mime if valid.
605
     *  if the path has invalid characters, we'll return a "bad request" response.
606
     */
607
    IResponse readStaticFile(String path, Headers requestHeaders) {
608
        String mimeType = getMimeString(path);
609
        Path staticFilePath;
610
        try {
611
            staticFilePath = staticFilesDirectoryPathBase.resolve(path);
612
        } catch (Exception e) {
613
            throw new BadRequestException("Error creating a valid path from: " + path);
614
        }
615
616
        // move value to a variable - used in several places, may as well
617
        String staticFilePathString = staticFilePath.toString();
618
619 1 1. readStaticFile : negated conditional → KILLED
        if (constants.useCacheForStaticFiles) {
620
            ReentrantLock cacheLock = fileReader.getCacheLock();
621 1 1. readStaticFile : removed call to java/util/concurrent/locks/ReentrantLock::lock → KILLED
            cacheLock.lock();
622
            try {
623
                byte[] fileContents = fileReader.getLruCache().get(staticFilePathString);
624 1 1. readStaticFile : negated conditional → KILLED
                if (fileContents != null) {
625
                    logger.logTrace(() -> "%d bytes of data found in cache for request of %s".formatted(fileContents.length, staticFilePath));
626 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                    return createOkResponseForStaticFiles(fileContents, mimeType, staticFilePathString);
627
                }
628
            } finally {
629 1 1. readStaticFile : removed call to java/util/concurrent/locks/ReentrantLock::unlock → KILLED
                cacheLock.unlock();
630
            }
631
        }
632
633
        try {
634 1 1. readStaticFile : removed call to com/renomad/minum/utils/FileUtils::checkForBadFilePatterns → KILLED
            checkForBadFilePatterns(path);
635
        } catch (Exception ex) {
636
            logger.logDebug(() -> String.format("Bad path requested at readStaticFile: %s.  Exception: %s", path, ex.getMessage()));
637 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
            return Response.buildLeanResponse(CODE_400_BAD_REQUEST);
638
        }
639
640
        try {
641 1 1. readStaticFile : removed call to com/renomad/minum/utils/IFileUtils::checkFileIsWithinDirectory → KILLED
            fileUtils.checkFileIsWithinDirectory(path, constants.staticFilesDirectory);
642
        } catch (Exception ex) {
643
            logger.logDebug(() -> String.format("Unable to find %s in allowed directories", path));
644 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
            return Response.buildLeanResponse(CODE_404_NOT_FOUND);
645
        }
646
647
        try {
648 1 1. readStaticFile : negated conditional → KILLED
            if (!fileUtils.isRegularFile(staticFilePath)) {
649
                logger.logDebug(() -> String.format("No readable regular file found at %s", path));
650 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return Response.buildLeanResponse(CODE_404_NOT_FOUND);
651
            }
652
653
            long size = fileUtils.size(staticFilePath);
654 1 1. readStaticFile : negated conditional → KILLED
            if (size == 0) {
655
                logger.logTrace(() -> "Requested file, %s, was empty.  Returning 200 OK, content-length 0, with mime of %s".formatted(staticFilePath, mimeType));
656 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → SURVIVED
                return Response.buildLeanResponse(CODE_200_OK, Map.of("Content-Type", mimeType));
657 2 1. readStaticFile : changed conditional boundary → KILLED
2. readStaticFile : negated conditional → KILLED
            } else if (size < (long) MAX_CACHED_BYTES) {
658
                logger.logTrace(() -> "Size of static file, %s was %d bytes.  Since less than max allowed (%d), caching allowed.".formatted(staticFilePath, size, MAX_CACHED_BYTES));
659
                var fileContents = fileReader.readFile(staticFilePathString);
660 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return createOkResponseForStaticFiles(fileContents, mimeType, staticFilePathString);
661
            } else {
662
                logger.logTrace(() -> "Size of static file, %s was %d bytes.  Since greater than max allowed (%d), no caching allowed.".formatted(staticFilePath, size, MAX_CACHED_BYTES));
663 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return createOkResponseForLargeStaticFiles(mimeType, staticFilePath, requestHeaders);
664
            }
665
666
        } catch (IOException e) {
667
            logger.logAsyncError(() -> String.format("Error while reading file: %s. %s", path, StacktraceUtils.stackTraceToString(e)));
668 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → SURVIVED
            return Response.buildLeanResponse(CODE_400_BAD_REQUEST);
669
        }
670
    }
671
672
    private String getMimeString(String path) {
673
        String mimeType = null;
674
        // if the provided path has a dot in it, use that
675
        // to obtain a suffix for determining file type
676
        int suffixBeginIndex = path.lastIndexOf('.');
677 2 1. getMimeString : changed conditional boundary → TIMED_OUT
2. getMimeString : negated conditional → KILLED
        if (suffixBeginIndex > 0) {
678 1 1. getMimeString : Replaced integer addition with subtraction → KILLED
            String suffix = path.substring(suffixBeginIndex+1);
679
            mimeType = fileSuffixToMime.get(suffix);
680
        }
681
682
        // if we don't find any registered mime types for this
683
        // suffix, or if it doesn't have a suffix, set the mime type
684
        // to application/octet-stream
685 1 1. getMimeString : negated conditional → KILLED
        if (mimeType == null) {
686
            mimeType = "application/octet-stream";
687
        }
688 1 1. getMimeString : replaced return value with "" for com/renomad/minum/web/WebFramework::getMimeString → KILLED
        return mimeType;
689
    }
690
691
    /**
692
     * A method used for handling smaller files in the static files directory
693
     * (less than {@link #MAX_CACHED_BYTES})
694
     * All static responses will get a cache time of STATIC_FILE_CACHE_TIME seconds
695
     */
696
    private IResponse createOkResponseForStaticFiles(byte[] fileContents, String mimeType, String path) {
697
        var headers = new Headers(List.of(
698
                "Cache-Control: max-age=" + constants.staticFileCacheTime,
699
                "Content-Type: " + mimeType));
700
        // if the map does not have this key, then we haven't analyzed this file yet.
701 1 1. createOkResponseForStaticFiles : negated conditional → KILLED
        if (!fileIsCompressible.containsKey(path)) {
702
            ByteArrayOutputStream out = new ByteArrayOutputStream();
703 1 1. createOkResponseForStaticFiles : removed call to com/renomad/minum/web/WebFramework::compressBody → KILLED
            compressBody(out, fileContents);
704
705
            // we only want to compress it if we get a decent compression.
706
            // 30% smaller seems fine.
707 2 1. createOkResponseForStaticFiles : Replaced double division with multiplication → KILLED
2. createOkResponseForStaticFiles : Replaced double multiplication with division → KILLED
            long compressionRatio = Math.round(((double) out.size() / (double) fileContents.length) * 100);
708 2 1. createOkResponseForStaticFiles : changed conditional boundary → SURVIVED
2. createOkResponseForStaticFiles : negated conditional → TIMED_OUT
            boolean isWorthCompressing = compressionRatio < 70;
709
            logger.logTrace(() -> "static file %s worth compressing? %s.  Compression ratio: %d%%.  Original size: %d bytes. Compressed size: %d bytes".formatted(
710
                    path, isWorthCompressing, compressionRatio, fileContents.length, out.size()));
711
            fileIsCompressible.put(path, isWorthCompressing);
712
        }
713
        logger.logTrace(() -> "Creating OK response for file %s, mime: %s, length: %s, fileIsCompressible: %s".formatted(
714
                path, mimeType, fileContents.length, fileIsCompressible.get(path)));
715 1 1. createOkResponseForStaticFiles : replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForStaticFiles → KILLED
        return new Response(CODE_200_OK, headers, fileContents,
716 1 1. lambda$createOkResponseForStaticFiles$36 : removed call to com/renomad/minum/web/ISocketWrapper::send → KILLED
                socketWrapper -> socketWrapper.send(fileContents), fileContents.length, fileIsCompressible.get(path));
717
    }
718
719
    /**
720
     * A method used for handling larger files in the static files directory
721
     * (greater-than or equal to {@link #MAX_CACHED_BYTES})
722
     * All static responses will get a cache time of STATIC_FILE_CACHE_TIME seconds
723
     */
724
    private IResponse createOkResponseForLargeStaticFiles(String mimeType, Path filePath, Headers requestHeaders) {
725
        var headers = new Headers(List.of(
726
                "Cache-Control: max-age=" + constants.staticFileCacheTime,
727
                "Content-Type: " + mimeType,
728
                "Accept-Ranges: bytes"
729
                ));
730
731 1 1. createOkResponseForLargeStaticFiles : replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForLargeStaticFiles → KILLED
        return Response.buildLargeFileResponse(
732
                headers,
733
                filePath.toString(),
734
                requestHeaders,
735
                fileUtils
736
                );
737
    }
738
739
740
    /**
741
     * These are the default starting values for mappings
742
     * between file suffixes and appropriate mime types
743
     */
744
    private void addDefaultValuesForMimeMap() {
745
        fileSuffixToMime.put("css", "text/css");
746
        fileSuffixToMime.put("js", "application/javascript");
747
        fileSuffixToMime.put("webp", "image/webp");
748
        fileSuffixToMime.put("jpg", "image/jpeg");
749
        fileSuffixToMime.put("jpeg", "image/jpeg");
750
        fileSuffixToMime.put("htm", "text/html");
751
        fileSuffixToMime.put("html", "text/html");
752
        fileSuffixToMime.put("txt", "text/plain");
753
    }
754
755
    /**
756
     * let's see if we can match the registered paths against a path function
757
     */
758
    ThrowingFunction<IRequest, IResponse> findHandlerByPathFunction(RequestLine sl) {
759
        var functionList = registeredPathFunctions.get(sl.getMethod());
760 1 1. findHandlerByPathFunction : negated conditional → KILLED
        if (functionList == null) {
761
            return null;
762
        }
763
        String requestedPath = sl.getPathDetails().getIsolatedPath();
764 1 1. findHandlerByPathFunction : replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByPathFunction → KILLED
        return functionList.stream()
765 1 1. lambda$findHandlerByPathFunction$37 : replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByPathFunction$37 → KILLED
                .map(function -> function.apply(requestedPath))
766
                .filter(Objects::nonNull)
767
                .findFirst()
768
                .orElse(null);
769
    }
770
771
    /**
772
     * This constructor is used for the real production system
773
     */
774
    WebFramework(Context context) {
775
        this(context, null, null, null);
776
    }
777
778
    /**
779
     * This constructor is mainly used for testing
780
     */
781
    WebFramework(Context context, ZonedDateTime overrideForDateTime) {
782
        this(context, overrideForDateTime, null, null);
783
    }
784
785
    /**
786
     * A constructor with slots available for testing
787
     * @param overrideForDateTime for those test cases where we need to control the time. Providing null
788
     *                            for this parameter will cause code to use ZonedDateTime.now() instead,
789
     *                            which is the expected behavior during ordinary system use.
790
     * @param fileReader when we want to provide an instance for better control during testing. Providing
791
     *                   null here will cause a FileReader to be instantiated in the constructor.
792
     * @param fileUtils when we want to provide an instance for better control during testing. Providing
793
     *                  null here will cause a FileUtils to be instantiated in the constructor.
794
     */
795
    WebFramework(Context context, ZonedDateTime overrideForDateTime, IFileReader fileReader, IFileUtils fileUtils) {
796
        this.fs = context.getFullSystem();
797 1 1. <init> : negated conditional → KILLED
        this.theBrig = this.fs != null ? this.fs.getTheBrig() : null;
798
        this.logger = context.getLogger();
799
        this.constants = context.getConstants();
800
        this.overrideForDateTime = overrideForDateTime;
801
        this.registeredDynamicPaths = new HashMap<>();
802
        this.registeredPathFunctions = new EnumMap<>(RequestLine.Method.class);
803
        this.inputStreamUtils = new InputStreamUtils(constants.maxReadLineSizeBytes);
804
        this.bodyProcessor = new BodyProcessor(context);
805
        this.staticFilesDirectoryPathBase = Path.of(constants.staticFilesDirectory);
806
807 1 1. <init> : negated conditional → KILLED
        if (fileUtils != null) {
808
            this.fileUtils = fileUtils;
809
        } else {
810
            this.fileUtils = new FileUtils(logger, constants);
811
        }
812
813
        // This random value is purely to help provide correlation between
814
        // error messages in the UI and error logs.  There are no security concerns.
815
        this.randomErrorCorrelationId = new Random();
816
        this.validRequestLine =  new RequestLine(
817
                RequestLine.Method.NONE,
818
                PathDetails.empty,
819
                HttpVersion.NONE,
820
                "", logger);
821
822
        // this allows us to inject a IFileReader for deeper testing
823 1 1. <init> : negated conditional → KILLED
        if (fileReader != null) {
824
            this.fileReader = fileReader;
825
        } else {
826
            this.fileReader = new FileReader(
827
                    LRUCache.getLruCache(constants.maxElementsLruCacheStaticFiles),
828
                    constants.useCacheForStaticFiles,
829
                    logger);
830
        }
831
        this.fileSuffixToMime = new HashMap<>();
832
        this.fileIsCompressible = new ConcurrentHashMap<>();
833 1 1. <init> : removed call to com/renomad/minum/web/WebFramework::addDefaultValuesForMimeMap → TIMED_OUT
        addDefaultValuesForMimeMap();
834 1 1. <init> : removed call to com/renomad/minum/web/WebFramework::readExtraMimeMappings → KILLED
        readExtraMimeMappings(constants.extraMimeMappings);
835
    }
836
837
    void readExtraMimeMappings(List<String> input) {
838 2 1. readExtraMimeMappings : negated conditional → KILLED
2. readExtraMimeMappings : negated conditional → KILLED
        if (input == null || input.isEmpty()) return;
839 2 1. readExtraMimeMappings : Replaced integer modulus with multiplication → KILLED
2. readExtraMimeMappings : negated conditional → KILLED
        if (input.size() % 2 != 0) {
840
            throw new WebServerException("input must be even (key + value = 2 items). Your input: " + input);
841
        }
842
843 2 1. readExtraMimeMappings : negated conditional → TIMED_OUT
2. readExtraMimeMappings : changed conditional boundary → KILLED
        for (int i = 0; i < input.size(); i += 2) {
844
            String fileSuffix = input.get(i);
845 1 1. readExtraMimeMappings : Replaced integer addition with subtraction → KILLED
            String mime = input.get(i+1);
846
            logger.logTrace(() -> "Adding mime mapping: " + fileSuffix + " -> " + mime);
847
            fileSuffixToMime.put(fileSuffix, mime);
848
        }
849
    }
850
851
    /**
852
     * Add a new handler in the web application for a combination
853
     * of a {@link RequestLine.Method}, a path, and then provide
854
     * the code to handle a request.
855
     * <br>
856
     * Note that the path text expected is *after* the first forward slash,
857
     * so for example with {@code http://foo.com/mypath}, provide "mypath" as the path.
858
     * @throws WebServerException if duplicate paths are registered, or if the path is prefixed with a slash
859
     */
860
    public void registerPath(RequestLine.Method method, String pathName, ThrowingFunction<IRequest, IResponse> webHandler) {
861 2 1. registerPath : negated conditional → KILLED
2. registerPath : negated conditional → KILLED
        if (pathName.startsWith("\\") || pathName.startsWith("/")) {
862
            throw new WebServerException(
863
                    String.format("Path should not be prefixed with a slash.  Corrected version: registerPath(%s, \"%s\", ... )", method.name(), pathName.substring(1)));
864
        }
865
866
        var result = registeredDynamicPaths.put(new MethodPath(method, pathName), webHandler);
867 1 1. registerPath : negated conditional → KILLED
        if (result != null) {
868
            throw new WebServerException("Duplicate endpoint registered: " + new MethodPath(method, pathName));
869
        }
870
871 1 1. registerPath : removed call to com/renomad/minum/web/WebFramework::checkForDuplicatePartialPath → KILLED
        checkForDuplicatePartialPath(method, pathName);
872
    }
873
874
    /**
875
     * check if the user had already registered a "partial path" with this pathName, which
876
     * means it would be duplicate endpoints, and throw an exception if so.
877
     */
878
    private void checkForDuplicatePartialPath(RequestLine.Method method, String pathName) {
879
        List<Function<String, ThrowingFunction<IRequest, IResponse>>> existingPathFunctions = registeredPathFunctions.get(method);
880 1 1. checkForDuplicatePartialPath : negated conditional → KILLED
        if (existingPathFunctions != null) {
881
            if (existingPathFunctions.stream()
882
                    .filter(PartialPathFunction.class::isInstance)
883
                    .map(PartialPathFunction.class::cast)
884 1 1. lambda$checkForDuplicatePartialPath$39 : replaced return value with "" for com/renomad/minum/web/WebFramework::lambda$checkForDuplicatePartialPath$39 → KILLED
                    .map(function -> function.pathName)
885 1 1. checkForDuplicatePartialPath : negated conditional → KILLED
                    .anyMatch(pathName::equals)
886
            ) {
887
                throw new WebServerException("Duplicate partial-path endpoint registered: " + new MethodPath(method, pathName));
888
            }
889
        }
890
    }
891
892
    /**
893
     * Allows adding complex path function handling.
894
     * <p>
895
     *     <em>Note:</em> This is advanced functionality to provide extra flexibility
896
     *     to the developer.  It is intended for use in those situations where the
897
     *     minimalist approach is insufficient.  <em>Think hard whether this is truly
898
     *     necessary or if the base assumptions should be reconsidered before going this route</em>
899
     * </p>
900
     * <h4>
901
     *     Example use cases:
902
     * </h4>
903
     * <pre>{@code
904
     *
905
     * // an example helper method by the developer
906
     * private void registerPatternPath(RequestLine.Method method, Pattern pattern, BiFunction<IRequest, Matcher, IResponse> function) {
907
     *     webFramework.registerPath(method, path -> {
908
     *         Matcher matcher = pattern.matcher(path);
909
     *         if (matcher.matches()) {
910
     *             return request -> function.apply(request, matcher);
911
     *         }
912
     *         return null;
913
     *     });
914
     * }
915
     *
916
     * // a regular expression to look for paths like "/projects/123" and to
917
     * // collect the "123" part.
918
     * Pattern idMatcher = Pattern.compile("projects/(\\d+)");
919
     *
920
     * // a regular endpoint, no advanced usage
921
     * webFramework.registerPath(RequestLine.Method.GET, "projects", request -> {
922
     *     return Response.htmlOk("Do GET /projects");
923
     * });
924
     *
925
     * // registering a GET handler for the advanced use case
926
     * registerPatternPath(RequestLine.Method.GET, idMatcher, (request, matcher) -> {
927
     *     int id = Integer.parseInt(matcher.group(1));
928
     *     return Response.htmlOk("Do GET /projects/" + id);
929
     * });
930
     *
931
     * }</pre>
932
     */
933
    public void registerPath(RequestLine.Method method, Function<String, ThrowingFunction<IRequest, IResponse>> pathFunction) {
934 1 1. lambda$registerPath$40 : replaced return value with Collections.emptyList for com/renomad/minum/web/WebFramework::lambda$registerPath$40 → TIMED_OUT
        registeredPathFunctions.computeIfAbsent(method, k -> new ArrayList<>()).add(pathFunction);
935
    }
936
937
    /**
938
     * Similar to {@link WebFramework#registerPath(RequestLine.Method, String, ThrowingFunction)} except that the paths
939
     * registered here may be partially matched.
940
     * <p>
941
     *     For example, if you register {@code .well-known/acme-challenge} then it
942
     *     can match a client request for {@code .well-known/acme-challenge/HGr8U1IeTW4kY_Z6UIyaakzOkyQgPr_7ArlLgtZE8SX}
943
     * </p>
944
     * <p>
945
     *     Be careful here, be thoughtful - partial paths will match a lot, and may
946
     *     overlap with other URL's for your app, such as endpoints and static files.
947
     * </p>
948
     * @throws WebServerException if duplicate paths are registered, or if the path is prefixed with a slash
949
     */
950
    public void registerPartialPath(RequestLine.Method method, String pathName, ThrowingFunction<IRequest, IResponse> webHandler) {
951 2 1. registerPartialPath : negated conditional → KILLED
2. registerPartialPath : negated conditional → KILLED
        if (pathName.startsWith("\\") || pathName.startsWith("/")) {
952
            throw new WebServerException(
953
                    String.format("Path should not be prefixed with a slash.  Corrected version: registerPartialPath(%s, \"%s\", ... )", method.name(), pathName.substring(1)));
954
        }
955
956
        // if the user had previously registered a normal path with this value, it would
957
        // conflict and so we will throw an exception.
958 1 1. registerPartialPath : negated conditional → KILLED
        if (registeredDynamicPaths.containsKey(new MethodPath(method, pathName))) {
959
            throw new WebServerException("Duplicate endpoint registered: " + new MethodPath(method, pathName));
960
        }
961
962 1 1. registerPartialPath : removed call to com/renomad/minum/web/WebFramework::checkForDuplicatePartialPath → KILLED
        checkForDuplicatePartialPath(method, pathName);
963 1 1. registerPartialPath : removed call to com/renomad/minum/web/WebFramework::registerPath → KILLED
        registerPath(method, new PartialPathFunction(pathName, webHandler));
964
    }
965
966
    /**
967
     * Sets a handler to process all requests across the board.
968
     * <br>
969
     * <p>
970
     *     This is an <b>unusual</b> method.  Setting a handler here allows the user to run code of his
971
     * choosing before the regular business code is run.  Note that by defining this value, the ordinary
972
     * call to endpoint.apply(request) will not be run.
973
     * </p>
974
     * <p>Here is an example</p>
975
     * <pre>{@code
976
     *
977
     *      webFramework.registerPreHandler(preHandlerInputs -> preHandlerCode(preHandlerInputs, auth, context));
978
     *
979
     *      ...
980
     *
981
     *      private IResponse preHandlerCode(PreHandlerInputs preHandlerInputs, AuthUtils auth, Context context) throws Exception {
982
     *          int secureServerPort = context.getConstants().secureServerPort;
983
     *          Request request = preHandlerInputs.clientRequest();
984
     *          ThrowingFunction<IRequest, IResponse> endpoint = preHandlerInputs.endpoint();
985
     *          ISocketWrapper sw = preHandlerInputs.sw();
986
     *
987
     *          // log all requests
988
     *          logger.logTrace(() -> String.format("Request: %s by %s",
989
     *              request.requestLine().getRawValue(),
990
     *              request.remoteRequester())
991
     *          );
992
     *
993
     *          // redirect to https if they are on the plain-text connection and the path is "login"
994
     *
995
     *          // get the path from the request line
996
     *          String path = request.getRequestLine().getPathDetails().getIsolatedPath();
997
     *
998
     *          // redirect to https on the configured secure port if they are on the plain-text connection and the path contains "login"
999
     *          if (path.contains("login") &&
1000
     *              sw.getServerType().equals(HttpServerType.PLAIN_TEXT_HTTP)) {
1001
     *              return Response.redirectTo("https://%s:%d/%s".formatted(sw.getHostName(), secureServerPort, path));
1002
     *          }
1003
     *
1004
     *          // adjust behavior if non-authenticated and path includes "secure/"
1005
     *          if (path.contains("secure/")) {
1006
     *              AuthResult authResult = auth.processAuth(request);
1007
     *              if (authResult.isAuthenticated()) {
1008
     *                  return endpoint.apply(request);
1009
     *              } else {
1010
     *                  return Response.buildLeanResponse(CODE_403_FORBIDDEN);
1011
     *              }
1012
     *          }
1013
     *
1014
     *          // if the path does not include /secure, just move the request along unchanged.
1015
     *          return endpoint.apply(request);
1016
     *      }
1017
     * }</pre>
1018
     */
1019
        public void registerPreHandler(ThrowingFunction<PreHandlerInputs, IResponse> preHandler) {
1020
        this.preHandler = preHandler;
1021
    }
1022
1023
    /**
1024
     * Sets a handler to be executed after running the ordinary handler, just
1025
     * before sending the response.
1026
     * <p>
1027
     *     This is an <b>unusual</b> method, so please be aware of its proper use. Its
1028
     *     purpose is to allow the user to inject code to run after ordinary code, across
1029
     *     all requests.
1030
     * </p>
1031
     * <p>
1032
     *     For example, if the system would have returned a 404 NOT FOUND response,
1033
     *     code can handle that situation in a switch case and adjust the response according
1034
     *     to your programming.
1035
     * </p>
1036
     * <p>Here is an example</p>
1037
     * <pre>{@code
1038
     *
1039
     *
1040
     *      webFramework.registerLastMinuteHandler(TheRegister::lastMinuteHandlerCode);
1041
     *
1042
     * ...
1043
     *
1044
     *     private static IResponse lastMinuteHandlerCode(LastMinuteHandlerInputs inputs) {
1045
     *         switch (inputs.response().statusCode()) {
1046
     *             case CODE_404_NOT_FOUND -> {
1047
     *                 return Response.buildResponse(
1048
     *                         CODE_404_NOT_FOUND,
1049
     *                         Map.of("Content-Type", "text/html; charset=UTF-8"),
1050
     *                         "<p>No document was found</p>"));
1051
     *             }
1052
     *             case CODE_500_INTERNAL_SERVER_ERROR -> {
1053
     *                 return Response.buildResponse(
1054
     *                         CODE_500_INTERNAL_SERVER_ERROR,
1055
     *                         Map.of("Content-Type", "text/html; charset=UTF-8"),
1056
     *                         "<p>Server error occurred.</p>" ));
1057
     *             }
1058
     *             default -> {
1059
     *                 return inputs.response();
1060
     *             }
1061
     *         }
1062
     *     }
1063
     * }
1064
     * </pre>
1065
     * @param lastMinuteHandler a function that will take a request and return a response, exactly like
1066
     *                   we use in the other registration methods for this class.
1067
     */
1068
    public void registerLastMinuteHandler(ThrowingFunction<LastMinuteHandlerInputs, IResponse> lastMinuteHandler) {
1069
        this.lastMinuteHandler = lastMinuteHandler;
1070
    }
1071
1072
    /**
1073
     * This allows users to add extra mappings
1074
     * between file suffixes and mime types, in case
1075
     * a user needs one that was not provided.
1076
     * <p>
1077
     *     This is made available through the
1078
     *     web framework.
1079
     * </p>
1080
     * <p>
1081
     *     Example:
1082
     * </p>
1083
     * <pre>
1084
     * {@code webFramework.addMimeForSuffix().put("foo","text/foo")}
1085
     * </pre>
1086
     */
1087
    public void addMimeForSuffix(String suffix, String mimeType) {
1088
        fileSuffixToMime.put(suffix, mimeType);
1089
    }
1090
}

Mutations

61

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

88

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

158

1.1
Location : httpProcessing
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

2.2
Location : httpProcessing
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

167

1.1
Location : httpProcessing
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/WebFramework::checkIfSuspiciousPath → KILLED

176

1.1
Location : httpProcessing
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

183

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/WebFramework::addDefaultHeaders → TIMED_OUT

184

1.1
Location : httpProcessing
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response(com.renomad.minum.FunctionalTests)
removed call to com/renomad/minum/web/Headers::appendHeadersToBuilder → KILLED

185

1.1
Location : httpProcessing
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/WebFramework::addKeepAliveTimeout → KILLED

189

1.1
Location : httpProcessing
Killed by : none
negated conditional → TIMED_OUT

2.2
Location : httpProcessing
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_PostHandler_IgnoreBody(com.renomad.minum.FunctionalTests)
negated conditional → KILLED

3.3
Location : httpProcessing
Killed by : none
changed conditional boundary → TIMED_OUT

196

1.1
Location : httpProcessing
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
removed call to com/renomad/minum/web/WebFramework::applyContentLength → KILLED

197

1.1
Location : httpProcessing
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
removed call to com/renomad/minum/web/WebFramework::confirmBodyHasContentType → KILLED

202

1.1
Location : httpProcessing
Killed by : none
negated conditional → TIMED_OUT

212

1.1
Location : httpProcessing
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_BadRequest2(com.renomad.minum.FunctionalTests)
removed call to java/lang/StringBuilder::setLength → KILLED

214

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/WebFramework::addDefaultHeaders → TIMED_OUT

220

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/ISocketWrapper::send → TIMED_OUT

222

1.1
Location : httpProcessing
Killed by : none
negated conditional → TIMED_OUT

224

1.1
Location : httpProcessing
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
removed call to com/renomad/minum/web/IResponse::sendBody → KILLED

228

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/ISocketWrapper::flush → TIMED_OUT

234

1.1
Location : httpProcessing
Killed by : none
negated conditional → TIMED_OUT

241

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/WebFramework::handleForbiddenUse → TIMED_OUT

243

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/WebFramework::finalExceptionHandler → TIMED_OUT

255

1.1
Location : finalExceptionHandler
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

2.2
Location : finalExceptionHandler
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

256

1.1
Location : finalExceptionHandler
Killed by : none
negated conditional → SURVIVED
Covering tests

261

1.1
Location : finalExceptionHandler
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

2.2
Location : finalExceptionHandler
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

264

1.1
Location : finalExceptionHandler
Killed by : none
negated conditional → TIMED_OUT

275

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

292

1.1
Location : handleBadRequestException
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::handleBadRequestException → TIMED_OUT

307

1.1
Location : processRequest
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

312

1.1
Location : processRequest
Killed by : none
negated conditional → TIMED_OUT

330

1.1
Location : processRequest
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

334

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

351

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

379

1.1
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

381

1.1
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

382

1.1
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

385

1.1
Location : determineIfKeepAlive
Killed by : none
changed conditional boundary → TIMED_OUT

2.2
Location : determineIfKeepAlive
Killed by : com.renomad.minum.FunctionalTests.testEndToEnd_Functional(com.renomad.minum.FunctionalTests)
negated conditional → KILLED

3.3
Location : determineIfKeepAlive
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_Response_MultiCookies(com.renomad.minum.FunctionalTests)
negated conditional → KILLED

4.4
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

396

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

2.2
Location : determineIfKeepAlive
Killed by : none
replaced boolean return with false for com/renomad/minum/web/WebFramework::determineIfKeepAlive → TIMED_OUT

404

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

408

1.1
Location : checkIfSuspiciousPath
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

421

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response_Range(com.renomad.minum.FunctionalTests)
negated conditional → KILLED

422

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

423

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

424

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

426

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
removed call to com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED

427

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

436

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

451

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

471

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

474

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

2.2
Location : confirmBodyHasContentType
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
changed conditional boundary → KILLED

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

485

1.1
Location : addKeepAliveTimeout
Killed by : none
negated conditional → TIMED_OUT

515

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

516

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

520

1.1
Location : compressBodyIfRequested
Killed by : none
removed call to com/renomad/minum/web/WebFramework::compressBody → SURVIVED
Covering tests

522

1.1
Location : lambda$compressBodyIfRequested$21
Killed by : none
Replaced double multiplication with division → SURVIVED
Covering tests

2.2
Location : lambda$compressBodyIfRequested$21
Killed by : none
Replaced double division with multiplication → SURVIVED Covering tests

523

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

529

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

541

1.1
Location : compressBody
Killed by : com.renomad.minum.web.CachingAndCompressionTests
removed call to java/util/zip/GZIPOutputStream::write → KILLED

542

1.1
Location : compressBody
Killed by : none
removed call to java/util/zip/GZIPOutputStream::finish → TIMED_OUT

562

1.1
Location : findEndpointForThisStartline
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response_Range(com.renomad.minum.FunctionalTests)
negated conditional → KILLED

567

1.1
Location : findEndpointForThisStartline
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

572

1.1
Location : findEndpointForThisStartline
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

578

1.1
Location : findEndpointForThisStartline
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::findEndpointForThisStartline → TIMED_OUT

587

1.1
Location : findHandlerByFilesOnDisk
Killed by : com.renomad.minum.FunctionalTests.testEndToEnd_Functional(com.renomad.minum.FunctionalTests)
negated conditional → KILLED

2.2
Location : findHandlerByFilesOnDisk
Killed by : none
negated conditional → TIMED_OUT

590

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

2.2
Location : lambda$findHandlerByFilesOnDisk$25
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByFilesOnDisk$25 → TIMED_OUT

619

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

621

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
removed call to java/util/concurrent/locks/ReentrantLock::lock → KILLED

624

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

626

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

629

1.1
Location : readStaticFile
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response(com.renomad.minum.FunctionalTests)
removed call to java/util/concurrent/locks/ReentrantLock::unlock → KILLED

634

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

637

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

641

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

644

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

648

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

650

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

654

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

656

1.1
Location : readStaticFile
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → SURVIVED
Covering tests

657

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.CachingAndCompressionTests
changed conditional boundary → KILLED

2.2
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

660

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

663

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

668

1.1
Location : readStaticFile
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → SURVIVED
Covering tests

677

1.1
Location : getMimeString
Killed by : none
changed conditional boundary → TIMED_OUT

2.2
Location : getMimeString
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

678

1.1
Location : getMimeString
Killed by : com.renomad.minum.web.WebFrameworkTests
Replaced integer addition with subtraction → KILLED

685

1.1
Location : getMimeString
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

688

1.1
Location : getMimeString
Killed by : com.renomad.minum.web.WebFrameworkTests
replaced return value with "" for com/renomad/minum/web/WebFramework::getMimeString → KILLED

701

1.1
Location : createOkResponseForStaticFiles
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

703

1.1
Location : createOkResponseForStaticFiles
Killed by : com.renomad.minum.web.CachingAndCompressionTests
removed call to com/renomad/minum/web/WebFramework::compressBody → KILLED

707

1.1
Location : createOkResponseForStaticFiles
Killed by : com.renomad.minum.web.CachingAndCompressionTests
Replaced double division with multiplication → KILLED

2.2
Location : createOkResponseForStaticFiles
Killed by : com.renomad.minum.web.WebFrameworkTests
Replaced double multiplication with division → KILLED

708

1.1
Location : createOkResponseForStaticFiles
Killed by : none
negated conditional → TIMED_OUT

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

715

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

716

1.1
Location : lambda$createOkResponseForStaticFiles$36
Killed by : com.renomad.minum.FunctionalTests.testEndToEnd_Functional(com.renomad.minum.FunctionalTests)
removed call to com/renomad/minum/web/ISocketWrapper::send → KILLED

731

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

760

1.1
Location : findHandlerByPathFunction
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response(com.renomad.minum.FunctionalTests)
negated conditional → KILLED

764

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

765

1.1
Location : lambda$findHandlerByPathFunction$37
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response(com.renomad.minum.FunctionalTests)
replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByPathFunction$37 → KILLED

797

1.1
Location : <init>
Killed by : com.renomad.minum.web.WebEngineTests
negated conditional → KILLED

807

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

823

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

833

1.1
Location : <init>
Killed by : none
removed call to com/renomad/minum/web/WebFramework::addDefaultValuesForMimeMap → TIMED_OUT

834

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

838

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

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

839

1.1
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebEngineTests
Replaced integer modulus with multiplication → KILLED

2.2
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebEngineTests
negated conditional → KILLED

843

1.1
Location : readExtraMimeMappings
Killed by : none
negated conditional → TIMED_OUT

2.2
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebEngineTests
changed conditional boundary → KILLED

845

1.1
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebEngineTests
Replaced integer addition with subtraction → KILLED

861

1.1
Location : registerPath
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

2.2
Location : registerPath
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

867

1.1
Location : registerPath
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

871

1.1
Location : registerPath
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/WebFramework::checkForDuplicatePartialPath → KILLED

880

1.1
Location : checkForDuplicatePartialPath
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

884

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

885

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

934

1.1
Location : lambda$registerPath$40
Killed by : none
replaced return value with Collections.emptyList for com/renomad/minum/web/WebFramework::lambda$registerPath$40 → TIMED_OUT

951

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

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

958

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

962

1.1
Location : registerPartialPath
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/WebFramework::checkForDuplicatePartialPath → KILLED

963

1.1
Location : registerPartialPath
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/WebFramework::registerPath → KILLED

Active mutators

Tests examined


Report generated by PIT 1.17.0