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
            dumpIfAttacker(sw, fs);
135
            final var is = sw.getInputStream();
136
137
            // By default, browsers expect the server to run in keep-alive mode.
138
            // We'll break out later if we find that the browser doesn't do keep-alive
139
            while (true) {
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 → TIMED_OUT
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);
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 → KILLED
                    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 : negated conditional → TIMED_OUT
3. httpProcessing : changed conditional boundary → 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 → SURVIVED
                    headerStringBuilder.setLength(0); // clear the contents
213
                    adjustedResponse = handleBadRequestException(ex);
214 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::addDefaultHeaders → KILLED
                    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 → KILLED
                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 → TIMED_OUT
                    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 → KILLED
                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 → KILLED
            handleForbiddenUse(sw, ex, logger, theBrig, constants.vulnSeekingJailDuration);
242
        } catch (Exception ex) {
243 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::finalExceptionHandler → KILLED
            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
                                      int 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 → KILLED
            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 → KILLED
        } 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, int 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 → KILLED
        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 → KILLED
                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 → TIMED_OUT
        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 → TIMED_OUT
        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 → TIMED_OUT
        } 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 : negated conditional → TIMED_OUT
2. determineIfKeepAlive : negated conditional → KILLED
3. determineIfKeepAlive : negated conditional → KILLED
4. determineIfKeepAlive : changed conditional boundary → 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 true for com/renomad/minum/web/WebFramework::determineIfKeepAlive → TIMED_OUT
2. determineIfKeepAlive : replaced boolean return with false for com/renomad/minum/web/WebFramework::determineIfKeepAlive → TIMED_OUT
        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 → TIMED_OUT
        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
     */
419
    boolean dumpIfAttacker(ISocketWrapper sw, FullSystem fs) {
420 1 1. dumpIfAttacker : negated conditional → KILLED
        if (fs == null) {
421 1 1. dumpIfAttacker : replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return false;
422 1 1. dumpIfAttacker : negated conditional → KILLED
        } else if (fs.getTheBrig() == null) {
423 1 1. dumpIfAttacker : replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return false;
424
        } else {
425 1 1. dumpIfAttacker : removed call to com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            dumpIfAttacker(sw, fs.getTheBrig());
426 1 1. dumpIfAttacker : replaced boolean return with false for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return true;
427
        }
428
    }
429
430
    void dumpIfAttacker(ISocketWrapper sw, ITheBrig theBrig) {
431
        String remoteClient = sw.getRemoteAddr();
432 1 1. dumpIfAttacker : negated conditional → KILLED
        if (theBrig.isInJail(remoteClient + "_vuln_seeking")) {
433
            // if this client is a vulnerability seeker, throw an exception,
434
            // causing them to get dumped unceremoniously
435
            String message = "closing the socket on " + remoteClient + " due to being found in the brig";
436
            logger.logDebug(() -> message);
437
            throw new ForbiddenUseException(message);
438
        }
439
    }
440
441
    /**
442
     * Prepare some of the basic server response headers, like the status code, the
443
     * date-time stamp, the server name.
444
     */
445
    private void addDefaultHeaders(IResponse response, StringBuilder headerStringBuilder) {
446
        String date = Objects.requireNonNullElseGet(overrideForDateTime,
447 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);
448
449
        // add the status line
450
        headerStringBuilder.append("HTTP/1.1 ").append(response.getStatusCode().code).append(" ").append(response.getStatusCode().shortDescription).append(HTTP_CRLF);
451
452
        // add a date-timestamp
453
        headerStringBuilder.append("Date: ").append(date).append(HTTP_CRLF);
454
455
        // add the server name
456
        headerStringBuilder.append("Server: minum").append(HTTP_CRLF);
457
    }
458
459
    /**
460
     * If a response body exists, it needs to have a content-type specified,
461
     * or throw an exception. Otherwise, the user could totally miss they did
462
     * not set a content-type, because the browser will inspect the data and
463
     * do sort-of-the-right-thing a lot of the time, but we want to enforce correctness.
464
     */
465
    static void confirmBodyHasContentType(IRequest request, IResponse response) {
466
        // check the correctness of the content-type header versus the data length (if any data, that is)
467 1 1. confirmBodyHasContentType : negated conditional → KILLED
        boolean hasContentType = response.getExtraHeaders().valueByKey("content-type") != null;
468
469
        // if there *is* data, we had better be returning a content type
470 3 1. confirmBodyHasContentType : negated conditional → KILLED
2. confirmBodyHasContentType : changed conditional boundary → KILLED
3. confirmBodyHasContentType : negated conditional → KILLED
        if (response.getBodyLength() > 0 && !hasContentType) {
471
            throw new WebServerException("a Content-Type header must be specified in the Response object if it returns data. Response details: " + response + " Request: " + request);
472
        }
473
    }
474
475
    /**
476
     * If this is a keep-alive communication, add a header specifying the
477
     * socket timeout for the browser.
478
     */
479
    private void addKeepAliveTimeout(boolean isKeepAlive, StringBuilder stringBuilder) {
480
        // if we're a keep-alive connection, reply with a keep-alive header
481 1 1. addKeepAliveTimeout : negated conditional → KILLED
        if (isKeepAlive) {
482
            stringBuilder.append("Keep-Alive: timeout=").append(constants.keepAliveTimeoutSeconds).append(HTTP_CRLF);
483
        }
484
    }
485
486
    /**
487
     * The rules regarding the content-length header are byzantine.  Even in the cases
488
     * where you aren't returning anything, servers can use this header to determine when the
489
     * response is finished.
490
     * See <a href="https://www.rfc-editor.org/rfc/rfc9110.html#name-content-length">Content-Length in the HTTP spec</a>
491
     */
492
    private static void applyContentLength(StringBuilder stringBuilder, long bodyLength) {
493
        stringBuilder.append("Content-Length: ").append(bodyLength).append(HTTP_CRLF);
494
    }
495
496
    /**
497
     * This method will examine the content-encoding headers, and if "gzip" is
498
     * requested by the client, we will replace the body bytes with compressed
499
     * bytes, using the GZIP compression algorithm.
500
     *
501
     * @param acceptEncoding headers sent by the client about what compression
502
     *                       algorithms will be understood.
503
     * @param stringBuilder  the string we are gradually building up to send back to
504
     *                       the client for the status line and headers. We'll use it
505
     *                       here if we need to append a content-encoding - that is,
506
     *                       if we successfully compress data as gzip.
507
     * @param endpointPath the endpoint whose data we are compressing, e.g. "foo?bar=baz",
508
     *                     used for logging.
509
     */
510
    static IResponse compressBodyIfRequested(IResponse response, List<String> acceptEncoding, StringBuilder stringBuilder, ILogger logger, String endpointPath) {
511 1 1. compressBodyIfRequested : negated conditional → KILLED
        String allContentEncodingHeaders = acceptEncoding != null ? String.join(";", acceptEncoding) : "";
512 1 1. compressBodyIfRequested : negated conditional → KILLED
        if (allContentEncodingHeaders.contains("gzip")) {
513
            stringBuilder.append("Content-Encoding: gzip").append(HTTP_CRLF);
514
            stringBuilder.append("Vary: accept-encoding").append(HTTP_CRLF);
515
            var out = new ByteArrayOutputStream();
516 1 1. compressBodyIfRequested : removed call to com/renomad/minum/web/WebFramework::compressBody → SURVIVED
            compressBody(out, response.getBody());
517
            logger.logTrace(() -> "Compressing results of %s.  Compression ratio: %d%%. Original size: %d bytes. Compressed size: %d bytes".formatted(endpointPath,
518 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()));
519 1 1. compressBodyIfRequested : replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED
            return Response.buildResponse(
520
                    response.getStatusCode(),
521
                    response.getExtraHeaders(),
522
                    out.toByteArray()
523
            );
524
        }
525 1 1. compressBodyIfRequested : replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED
        return response;
526
    }
527
528
    /**
529
     * Compress the data in this body using gzip.
530
     * <br>
531
     * This operates by getting the body field from this instance of {@link Response} and
532
     * creating a new Response with the compressed data.
533
     * @param out this is provided as a parameter for better control during testing
534
     */
535
    static void compressBody(OutputStream out, byte[] body) {
536
        try (var gos = new GZIPOutputStream(out)) {
537 1 1. compressBody : removed call to java/util/zip/GZIPOutputStream::write → KILLED
            gos.write(body);
538 1 1. compressBody : removed call to java/util/zip/GZIPOutputStream::finish → KILLED
            gos.finish();
539
        } catch (IOException e) {
540
            throw new WebServerException("Error in Response.compressBody", e);
541
        }
542
    }
543
544
    /**
545
     * Looks through the mappings of {@link MethodPath} and path to registered endpoints
546
     * or the static cache and returns the appropriate one (If we
547
     * do not find anything, return null)
548
     */
549
    ThrowingFunction<IRequest, IResponse> findEndpointForThisStartline(RequestLine sl, Headers requestHeaders) {
550
        ThrowingFunction<IRequest, IResponse> handler;
551
        logger.logTrace(() -> "Seeking a handler for " + sl);
552
553
        // first we check if there's a simple direct match
554
        String requestedPath = sl.getPathDetails().getIsolatedPath().toLowerCase(Locale.ROOT);
555
556
        // if the user is asking for a HEAD request, they want to run a GET command
557
        // but don't want the body.  We'll simply exclude sending the body, later on, when returning the data
558 1 1. findEndpointForThisStartline : negated conditional → TIMED_OUT
        RequestLine.Method method = sl.getMethod() == RequestLine.Method.HEAD ? RequestLine.Method.GET : sl.getMethod();
559
560
        MethodPath key = new MethodPath(method, requestedPath);
561
        handler = registeredDynamicPaths.get(key);
562
563 1 1. findEndpointForThisStartline : negated conditional → KILLED
        if (handler == null) {
564
            logger.logTrace(() -> "No direct handler found.  looking for a partial match for " + requestedPath);
565
            handler = findHandlerByPathFunction(sl);
566
        }
567
568 1 1. findEndpointForThisStartline : negated conditional → KILLED
        if (handler == null) {
569
            logger.logTrace(() -> "No partial match found, checking files on disk for " + requestedPath );
570
            handler = findHandlerByFilesOnDisk(sl, requestHeaders);
571
        }
572
573
        // we'll return this, and it could be a null.
574 1 1. findEndpointForThisStartline : replaced return value with null for com/renomad/minum/web/WebFramework::findEndpointForThisStartline → KILLED
        return handler;
575
    }
576
577
    /**
578
     * last ditch effort - look on disk.  This response will either
579
     * be the file to return, or null if we didn't find anything.
580
     * The request method has to be GET or HEAD.
581
     */
582
    private ThrowingFunction<IRequest, IResponse> findHandlerByFilesOnDisk(RequestLine sl, Headers requestHeaders) {
583 2 1. findHandlerByFilesOnDisk : negated conditional → KILLED
2. findHandlerByFilesOnDisk : negated conditional → KILLED
        if (sl.getMethod() == RequestLine.Method.GET || sl.getMethod() == RequestLine.Method.HEAD) {
584
            String requestedPath = sl.getPathDetails().getIsolatedPath();
585
            IResponse response = readStaticFile(requestedPath, requestHeaders);
586 2 1. findHandlerByFilesOnDisk : replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByFilesOnDisk → KILLED
2. lambda$findHandlerByFilesOnDisk$25 : replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByFilesOnDisk$25 → KILLED
            return request -> response;
587
        } else {
588
            return null;
589
        }
590
    }
591
592
593
    /**
594
     * Get a file from a path and create a response for it with a mime type.
595
     * <p>
596
     *     Parent directories are made unavailable by searching the path for
597
     *     bad characters. see {@link FileUtils#checkForBadFilePatterns}
598
     * </p>
599
     *
600
     * @return a response with the file contents and caching headers and mime if valid.
601
     *  if the path has invalid characters, we'll return a "bad request" response.
602
     */
603
    IResponse readStaticFile(String path, Headers requestHeaders) {
604
        String mimeType = getMimeString(path);
605
        Path staticFilePath;
606
        try {
607
            staticFilePath = staticFilesDirectoryPathBase.resolve(path);
608
        } catch (Exception e) {
609
            throw new BadRequestException("Error creating a valid path from: " + path);
610
        }
611
612
        // move value to a variable - used in several places, may as well
613
        String staticFilePathString = staticFilePath.toString();
614
615 1 1. readStaticFile : negated conditional → KILLED
        if (constants.useCacheForStaticFiles) {
616
            ReentrantLock cacheLock = fileReader.getCacheLock();
617 1 1. readStaticFile : removed call to java/util/concurrent/locks/ReentrantLock::lock → KILLED
            cacheLock.lock();
618
            try {
619
                byte[] fileContents = fileReader.getLruCache().get(staticFilePathString);
620 1 1. readStaticFile : negated conditional → KILLED
                if (fileContents != null) {
621
                    logger.logTrace(() -> "%d bytes of data found in cache for request of %s".formatted(fileContents.length, staticFilePath));
622 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                    return createOkResponseForStaticFiles(fileContents, mimeType, staticFilePathString);
623
                }
624
            } finally {
625 1 1. readStaticFile : removed call to java/util/concurrent/locks/ReentrantLock::unlock → KILLED
                cacheLock.unlock();
626
            }
627
        }
628
629
        try {
630 1 1. readStaticFile : removed call to com/renomad/minum/utils/FileUtils::checkForBadFilePatterns → KILLED
            checkForBadFilePatterns(path);
631
        } catch (Exception ex) {
632
            logger.logDebug(() -> String.format("Bad path requested at readStaticFile: %s.  Exception: %s", path, ex.getMessage()));
633 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
            return Response.buildLeanResponse(CODE_400_BAD_REQUEST);
634
        }
635
636
        try {
637 1 1. readStaticFile : removed call to com/renomad/minum/utils/IFileUtils::checkFileIsWithinDirectory → KILLED
            fileUtils.checkFileIsWithinDirectory(path, constants.staticFilesDirectory);
638
        } catch (Exception ex) {
639
            logger.logDebug(() -> String.format("Unable to find %s in allowed directories", path));
640 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
            return Response.buildLeanResponse(CODE_404_NOT_FOUND);
641
        }
642
643
        try {
644 1 1. readStaticFile : negated conditional → KILLED
            if (!fileUtils.isRegularFile(staticFilePath)) {
645
                logger.logDebug(() -> String.format("No readable regular file found at %s", path));
646 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return Response.buildLeanResponse(CODE_404_NOT_FOUND);
647
            }
648
649
            long size = fileUtils.size(staticFilePath);
650 1 1. readStaticFile : negated conditional → KILLED
            if (size == 0) {
651
                logger.logTrace(() -> "Requested file, %s, was empty.  Returning 200 OK, content-length 0, with mime of %s".formatted(staticFilePath, mimeType));
652 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));
653 2 1. readStaticFile : negated conditional → TIMED_OUT
2. readStaticFile : changed conditional boundary → KILLED
            } else if (size < MAX_CACHED_BYTES) {
654
                logger.logTrace(() -> "Size of static file, %s was %d bytes.  Since less than max allowed (%d), caching allowed.".formatted(staticFilePath, size, MAX_CACHED_BYTES));
655
                var fileContents = fileReader.readFile(staticFilePathString);
656 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return createOkResponseForStaticFiles(fileContents, mimeType, staticFilePathString);
657
            } else {
658
                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));
659 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return createOkResponseForLargeStaticFiles(mimeType, staticFilePath, requestHeaders);
660
            }
661
662
        } catch (IOException e) {
663
            logger.logAsyncError(() -> String.format("Error while reading file: %s. %s", path, StacktraceUtils.stackTraceToString(e)));
664 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → SURVIVED
            return Response.buildLeanResponse(CODE_400_BAD_REQUEST);
665
        }
666
    }
667
668
    private String getMimeString(String path) {
669
        String mimeType = null;
670
        // if the provided path has a dot in it, use that
671
        // to obtain a suffix for determining file type
672
        int suffixBeginIndex = path.lastIndexOf('.');
673 2 1. getMimeString : changed conditional boundary → KILLED
2. getMimeString : negated conditional → KILLED
        if (suffixBeginIndex > 0) {
674 1 1. getMimeString : Replaced integer addition with subtraction → KILLED
            String suffix = path.substring(suffixBeginIndex+1);
675
            mimeType = fileSuffixToMime.get(suffix);
676
        }
677
678
        // if we don't find any registered mime types for this
679
        // suffix, or if it doesn't have a suffix, set the mime type
680
        // to application/octet-stream
681 1 1. getMimeString : negated conditional → KILLED
        if (mimeType == null) {
682
            mimeType = "application/octet-stream";
683
        }
684 1 1. getMimeString : replaced return value with "" for com/renomad/minum/web/WebFramework::getMimeString → KILLED
        return mimeType;
685
    }
686
687
    /**
688
     * A method used for handling smaller files in the static files directory
689
     * (less than {@link #MAX_CACHED_BYTES})
690
     * All static responses will get a cache time of STATIC_FILE_CACHE_TIME seconds
691
     */
692
    private IResponse createOkResponseForStaticFiles(byte[] fileContents, String mimeType, String path) {
693
        var headers = new Headers(List.of(
694
                "Cache-Control: max-age=" + constants.staticFileCacheTime,
695
                "Content-Type: " + mimeType));
696
        // if the map does not have this key, then we haven't analyzed this file yet.
697 1 1. createOkResponseForStaticFiles : negated conditional → KILLED
        if (!fileIsCompressible.containsKey(path)) {
698
            ByteArrayOutputStream out = new ByteArrayOutputStream();
699 1 1. createOkResponseForStaticFiles : removed call to com/renomad/minum/web/WebFramework::compressBody → KILLED
            compressBody(out, fileContents);
700
701
            // we only want to compress it if we get a decent compression.
702
            // 30% smaller seems fine.
703 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);
704 2 1. createOkResponseForStaticFiles : changed conditional boundary → SURVIVED
2. createOkResponseForStaticFiles : negated conditional → KILLED
            boolean isWorthCompressing = compressionRatio < 70;
705
            logger.logTrace(() -> "static file %s worth compressing? %s.  Compression ratio: %d%%.  Original size: %d bytes. Compressed size: %d bytes".formatted(
706
                    path, isWorthCompressing, compressionRatio, fileContents.length, out.size()));
707
            fileIsCompressible.put(path, isWorthCompressing);
708
        }
709
        logger.logTrace(() -> "Creating OK response for file %s, mime: %s, length: %s, fileIsCompressible: %s".formatted(
710
                path, mimeType, fileContents.length, fileIsCompressible.get(path)));
711 1 1. createOkResponseForStaticFiles : replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForStaticFiles → KILLED
        return new Response(CODE_200_OK, headers, fileContents,
712 1 1. lambda$createOkResponseForStaticFiles$36 : removed call to com/renomad/minum/web/ISocketWrapper::send → KILLED
                socketWrapper -> socketWrapper.send(fileContents), fileContents.length, fileIsCompressible.get(path));
713
    }
714
715
    /**
716
     * A method used for handling larger files in the static files directory
717
     * (greater-than or equal to {@link #MAX_CACHED_BYTES})
718
     * All static responses will get a cache time of STATIC_FILE_CACHE_TIME seconds
719
     */
720
    private IResponse createOkResponseForLargeStaticFiles(String mimeType, Path filePath, Headers requestHeaders) {
721
        var headers = new Headers(List.of(
722
                "Cache-Control: max-age=" + constants.staticFileCacheTime,
723
                "Content-Type: " + mimeType,
724
                "Accept-Ranges: bytes"
725
                ));
726
727 1 1. createOkResponseForLargeStaticFiles : replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForLargeStaticFiles → KILLED
        return Response.buildLargeFileResponse(
728
                headers,
729
                filePath.toString(),
730
                requestHeaders,
731
                fileUtils
732
                );
733
    }
734
735
736
    /**
737
     * These are the default starting values for mappings
738
     * between file suffixes and appropriate mime types
739
     */
740
    private void addDefaultValuesForMimeMap() {
741
        fileSuffixToMime.put("css", "text/css");
742
        fileSuffixToMime.put("js", "application/javascript");
743
        fileSuffixToMime.put("webp", "image/webp");
744
        fileSuffixToMime.put("jpg", "image/jpeg");
745
        fileSuffixToMime.put("jpeg", "image/jpeg");
746
        fileSuffixToMime.put("htm", "text/html");
747
        fileSuffixToMime.put("html", "text/html");
748
        fileSuffixToMime.put("txt", "text/plain");
749
    }
750
751
    /**
752
     * let's see if we can match the registered paths against a path function
753
     */
754
    ThrowingFunction<IRequest, IResponse> findHandlerByPathFunction(RequestLine sl) {
755
        var functionList = registeredPathFunctions.get(sl.getMethod());
756 1 1. findHandlerByPathFunction : negated conditional → KILLED
        if (functionList == null) {
757
            return null;
758
        }
759
        String requestedPath = sl.getPathDetails().getIsolatedPath();
760 1 1. findHandlerByPathFunction : replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByPathFunction → KILLED
        return functionList.stream()
761 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))
762
                .filter(Objects::nonNull)
763
                .findFirst()
764
                .orElse(null);
765
    }
766
767
    /**
768
     * This constructor is used for the real production system
769
     */
770
    WebFramework(Context context) {
771
        this(context, null, null, null);
772
    }
773
774
    /**
775
     * This constructor is mainly used for testing
776
     */
777
    WebFramework(Context context, ZonedDateTime overrideForDateTime) {
778
        this(context, overrideForDateTime, null, null);
779
    }
780
781
    /**
782
     * A constructor with slots available for testing
783
     * @param overrideForDateTime for those test cases where we need to control the time. Providing null
784
     *                            for this parameter will cause code to use ZonedDateTime.now() instead,
785
     *                            which is the expected behavior during ordinary system use.
786
     * @param fileReader when we want to provide an instance for better control during testing. Providing
787
     *                   null here will cause a FileReader to be instantiated in the constructor.
788
     * @param fileUtils when we want to provide an instance for better control during testing. Providing
789
     *                  null here will cause a FileUtils to be instantiated in the constructor.
790
     */
791
    WebFramework(Context context, ZonedDateTime overrideForDateTime, IFileReader fileReader, IFileUtils fileUtils) {
792
        this.fs = context.getFullSystem();
793 1 1. <init> : negated conditional → KILLED
        this.theBrig = this.fs != null ? this.fs.getTheBrig() : null;
794
        this.logger = context.getLogger();
795
        this.constants = context.getConstants();
796
        this.overrideForDateTime = overrideForDateTime;
797
        this.registeredDynamicPaths = new HashMap<>();
798
        this.registeredPathFunctions = new EnumMap<>(RequestLine.Method.class);
799
        this.inputStreamUtils = new InputStreamUtils(constants.maxReadLineSizeBytes);
800
        this.bodyProcessor = new BodyProcessor(context);
801
        this.staticFilesDirectoryPathBase = Path.of(constants.staticFilesDirectory);
802
803 1 1. <init> : negated conditional → KILLED
        if (fileUtils != null) {
804
            this.fileUtils = fileUtils;
805
        } else {
806
            this.fileUtils = new FileUtils(logger, constants);
807
        }
808
809
        // This random value is purely to help provide correlation between
810
        // error messages in the UI and error logs.  There are no security concerns.
811
        this.randomErrorCorrelationId = new Random();
812
        this.validRequestLine =  new RequestLine(
813
                RequestLine.Method.NONE,
814
                PathDetails.empty,
815
                HttpVersion.NONE,
816
                "", logger);
817
818
        // this allows us to inject a IFileReader for deeper testing
819 1 1. <init> : negated conditional → TIMED_OUT
        if (fileReader != null) {
820
            this.fileReader = fileReader;
821
        } else {
822
            this.fileReader = new FileReader(
823
                    LRUCache.getLruCache(constants.maxElementsLruCacheStaticFiles),
824
                    constants.useCacheForStaticFiles,
825
                    logger);
826
        }
827
        this.fileSuffixToMime = new HashMap<>();
828
        this.fileIsCompressible = new ConcurrentHashMap<>();
829 1 1. <init> : removed call to com/renomad/minum/web/WebFramework::addDefaultValuesForMimeMap → TIMED_OUT
        addDefaultValuesForMimeMap();
830 1 1. <init> : removed call to com/renomad/minum/web/WebFramework::readExtraMimeMappings → TIMED_OUT
        readExtraMimeMappings(constants.extraMimeMappings);
831
    }
832
833
    void readExtraMimeMappings(List<String> input) {
834 2 1. readExtraMimeMappings : negated conditional → TIMED_OUT
2. readExtraMimeMappings : negated conditional → KILLED
        if (input == null || input.isEmpty()) return;
835 2 1. readExtraMimeMappings : Replaced integer modulus with multiplication → KILLED
2. readExtraMimeMappings : negated conditional → KILLED
        if (input.size() % 2 != 0) {
836
            throw new WebServerException("input must be even (key + value = 2 items). Your input: " + input);
837
        }
838
839 2 1. readExtraMimeMappings : negated conditional → TIMED_OUT
2. readExtraMimeMappings : changed conditional boundary → KILLED
        for (int i = 0; i < input.size(); i += 2) {
840
            String fileSuffix = input.get(i);
841 1 1. readExtraMimeMappings : Replaced integer addition with subtraction → KILLED
            String mime = input.get(i+1);
842
            logger.logTrace(() -> "Adding mime mapping: " + fileSuffix + " -> " + mime);
843
            fileSuffixToMime.put(fileSuffix, mime);
844
        }
845
    }
846
847
    /**
848
     * Add a new handler in the web application for a combination
849
     * of a {@link RequestLine.Method}, a path, and then provide
850
     * the code to handle a request.
851
     * <br>
852
     * Note that the path text expected is *after* the first forward slash,
853
     * so for example with {@code http://foo.com/mypath}, provide "mypath" as the path.
854
     * @throws WebServerException if duplicate paths are registered, or if the path is prefixed with a slash
855
     */
856
    public void registerPath(RequestLine.Method method, String pathName, ThrowingFunction<IRequest, IResponse> webHandler) {
857 2 1. registerPath : negated conditional → KILLED
2. registerPath : negated conditional → KILLED
        if (pathName.startsWith("\\") || pathName.startsWith("/")) {
858
            throw new WebServerException(
859
                    String.format("Path should not be prefixed with a slash.  Corrected version: registerPath(%s, \"%s\", ... )", method.name(), pathName.substring(1)));
860
        }
861
862
        var result = registeredDynamicPaths.put(new MethodPath(method, pathName), webHandler);
863 1 1. registerPath : negated conditional → KILLED
        if (result != null) {
864
            throw new WebServerException("Duplicate endpoint registered: " + new MethodPath(method, pathName));
865
        }
866
867 1 1. registerPath : removed call to com/renomad/minum/web/WebFramework::checkForDuplicatePartialPath → KILLED
        checkForDuplicatePartialPath(method, pathName);
868
    }
869
870
    /**
871
     * check if the user had already registered a "partial path" with this pathName, which
872
     * means it would be duplicate endpoints, and throw an exception if so.
873
     */
874
    private void checkForDuplicatePartialPath(RequestLine.Method method, String pathName) {
875
        List<Function<String, ThrowingFunction<IRequest, IResponse>>> existingPathFunctions = registeredPathFunctions.get(method);
876 1 1. checkForDuplicatePartialPath : negated conditional → KILLED
        if (existingPathFunctions != null) {
877
            if (existingPathFunctions.stream()
878
                    .filter(PartialPathFunction.class::isInstance)
879
                    .map(PartialPathFunction.class::cast)
880 1 1. lambda$checkForDuplicatePartialPath$39 : replaced return value with "" for com/renomad/minum/web/WebFramework::lambda$checkForDuplicatePartialPath$39 → KILLED
                    .map(function -> function.pathName)
881 1 1. checkForDuplicatePartialPath : negated conditional → KILLED
                    .anyMatch(pathName::equals)
882
            ) {
883
                throw new WebServerException("Duplicate partial-path endpoint registered: " + new MethodPath(method, pathName));
884
            }
885
        }
886
    }
887
888
    /**
889
     * Allows adding complex path function handling.
890
     * <p>
891
     *     <em>Note:</em> This is advanced functionality to provide extra flexibility
892
     *     to the developer.  It is intended for use in those situations where the
893
     *     minimalist approach is insufficient.  <em>Think hard whether this is truly
894
     *     necessary or if the base assumptions should be reconsidered before going this route</em>
895
     * </p>
896
     * <h4>
897
     *     Example use cases:
898
     * </h4>
899
     * <pre>{@code
900
     *
901
     * // an example helper method by the developer
902
     * private void registerPatternPath(RequestLine.Method method, Pattern pattern, BiFunction<IRequest, Matcher, IResponse> function) {
903
     *     webFramework.registerPath(method, path -> {
904
     *         Matcher matcher = pattern.matcher(path);
905
     *         if (matcher.matches()) {
906
     *             return request -> function.apply(request, matcher);
907
     *         }
908
     *         return null;
909
     *     });
910
     * }
911
     *
912
     * // a regular expression to look for paths like "/projects/123" and to
913
     * // collect the "123" part.
914
     * Pattern idMatcher = Pattern.compile("projects/(\\d+)");
915
     *
916
     * // a regular endpoint, no advanced usage
917
     * webFramework.registerPath(RequestLine.Method.GET, "projects", request -> {
918
     *     return Response.htmlOk("Do GET /projects");
919
     * });
920
     *
921
     * // registering a GET handler for the advanced use case
922
     * registerPatternPath(RequestLine.Method.GET, idMatcher, (request, matcher) -> {
923
     *     int id = Integer.parseInt(matcher.group(1));
924
     *     return Response.htmlOk("Do GET /projects/" + id);
925
     * });
926
     *
927
     * }</pre>
928
     */
929
    public void registerPath(RequestLine.Method method, Function<String, ThrowingFunction<IRequest, IResponse>> pathFunction) {
930 1 1. lambda$registerPath$40 : replaced return value with Collections.emptyList for com/renomad/minum/web/WebFramework::lambda$registerPath$40 → KILLED
        registeredPathFunctions.computeIfAbsent(method, k -> new ArrayList<>()).add(pathFunction);
931
    }
932
933
    /**
934
     * Similar to {@link WebFramework#registerPath(RequestLine.Method, String, ThrowingFunction)} except that the paths
935
     * registered here may be partially matched.
936
     * <p>
937
     *     For example, if you register {@code .well-known/acme-challenge} then it
938
     *     can match a client request for {@code .well-known/acme-challenge/HGr8U1IeTW4kY_Z6UIyaakzOkyQgPr_7ArlLgtZE8SX}
939
     * </p>
940
     * <p>
941
     *     Be careful here, be thoughtful - partial paths will match a lot, and may
942
     *     overlap with other URL's for your app, such as endpoints and static files.
943
     * </p>
944
     * @throws WebServerException if duplicate paths are registered, or if the path is prefixed with a slash
945
     */
946
    public void registerPartialPath(RequestLine.Method method, String pathName, ThrowingFunction<IRequest, IResponse> webHandler) {
947 2 1. registerPartialPath : negated conditional → KILLED
2. registerPartialPath : negated conditional → KILLED
        if (pathName.startsWith("\\") || pathName.startsWith("/")) {
948
            throw new WebServerException(
949
                    String.format("Path should not be prefixed with a slash.  Corrected version: registerPartialPath(%s, \"%s\", ... )", method.name(), pathName.substring(1)));
950
        }
951
952
        // if the user had previously registered a normal path with this value, it would
953
        // conflict and so we will throw an exception.
954 1 1. registerPartialPath : negated conditional → KILLED
        if (registeredDynamicPaths.containsKey(new MethodPath(method, pathName))) {
955
            throw new WebServerException("Duplicate endpoint registered: " + new MethodPath(method, pathName));
956
        }
957
958 1 1. registerPartialPath : removed call to com/renomad/minum/web/WebFramework::checkForDuplicatePartialPath → KILLED
        checkForDuplicatePartialPath(method, pathName);
959 1 1. registerPartialPath : removed call to com/renomad/minum/web/WebFramework::registerPath → KILLED
        registerPath(method, new PartialPathFunction(pathName, webHandler));
960
    }
961
962
    /**
963
     * Sets a handler to process all requests across the board.
964
     * <br>
965
     * <p>
966
     *     This is an <b>unusual</b> method.  Setting a handler here allows the user to run code of his
967
     * choosing before the regular business code is run.  Note that by defining this value, the ordinary
968
     * call to endpoint.apply(request) will not be run.
969
     * </p>
970
     * <p>Here is an example</p>
971
     * <pre>{@code
972
     *
973
     *      webFramework.registerPreHandler(preHandlerInputs -> preHandlerCode(preHandlerInputs, auth, context));
974
     *
975
     *      ...
976
     *
977
     *      private IResponse preHandlerCode(PreHandlerInputs preHandlerInputs, AuthUtils auth, Context context) throws Exception {
978
     *          int secureServerPort = context.getConstants().secureServerPort;
979
     *          Request request = preHandlerInputs.clientRequest();
980
     *          ThrowingFunction<IRequest, IResponse> endpoint = preHandlerInputs.endpoint();
981
     *          ISocketWrapper sw = preHandlerInputs.sw();
982
     *
983
     *          // log all requests
984
     *          logger.logTrace(() -> String.format("Request: %s by %s",
985
     *              request.requestLine().getRawValue(),
986
     *              request.remoteRequester())
987
     *          );
988
     *
989
     *          // redirect to https if they are on the plain-text connection and the path is "login"
990
     *
991
     *          // get the path from the request line
992
     *          String path = request.getRequestLine().getPathDetails().getIsolatedPath();
993
     *
994
     *          // redirect to https on the configured secure port if they are on the plain-text connection and the path contains "login"
995
     *          if (path.contains("login") &&
996
     *              sw.getServerType().equals(HttpServerType.PLAIN_TEXT_HTTP)) {
997
     *              return Response.redirectTo("https://%s:%d/%s".formatted(sw.getHostName(), secureServerPort, path));
998
     *          }
999
     *
1000
     *          // adjust behavior if non-authenticated and path includes "secure/"
1001
     *          if (path.contains("secure/")) {
1002
     *              AuthResult authResult = auth.processAuth(request);
1003
     *              if (authResult.isAuthenticated()) {
1004
     *                  return endpoint.apply(request);
1005
     *              } else {
1006
     *                  return Response.buildLeanResponse(CODE_403_FORBIDDEN);
1007
     *              }
1008
     *          }
1009
     *
1010
     *          // if the path does not include /secure, just move the request along unchanged.
1011
     *          return endpoint.apply(request);
1012
     *      }
1013
     * }</pre>
1014
     */
1015
        public void registerPreHandler(ThrowingFunction<PreHandlerInputs, IResponse> preHandler) {
1016
        this.preHandler = preHandler;
1017
    }
1018
1019
    /**
1020
     * Sets a handler to be executed after running the ordinary handler, just
1021
     * before sending the response.
1022
     * <p>
1023
     *     This is an <b>unusual</b> method, so please be aware of its proper use. Its
1024
     *     purpose is to allow the user to inject code to run after ordinary code, across
1025
     *     all requests.
1026
     * </p>
1027
     * <p>
1028
     *     For example, if the system would have returned a 404 NOT FOUND response,
1029
     *     code can handle that situation in a switch case and adjust the response according
1030
     *     to your programming.
1031
     * </p>
1032
     * <p>Here is an example</p>
1033
     * <pre>{@code
1034
     *
1035
     *
1036
     *      webFramework.registerLastMinuteHandler(TheRegister::lastMinuteHandlerCode);
1037
     *
1038
     * ...
1039
     *
1040
     *     private static IResponse lastMinuteHandlerCode(LastMinuteHandlerInputs inputs) {
1041
     *         switch (inputs.response().statusCode()) {
1042
     *             case CODE_404_NOT_FOUND -> {
1043
     *                 return Response.buildResponse(
1044
     *                         CODE_404_NOT_FOUND,
1045
     *                         Map.of("Content-Type", "text/html; charset=UTF-8"),
1046
     *                         "<p>No document was found</p>"));
1047
     *             }
1048
     *             case CODE_500_INTERNAL_SERVER_ERROR -> {
1049
     *                 return Response.buildResponse(
1050
     *                         CODE_500_INTERNAL_SERVER_ERROR,
1051
     *                         Map.of("Content-Type", "text/html; charset=UTF-8"),
1052
     *                         "<p>Server error occurred.</p>" ));
1053
     *             }
1054
     *             default -> {
1055
     *                 return inputs.response();
1056
     *             }
1057
     *         }
1058
     *     }
1059
     * }
1060
     * </pre>
1061
     * @param lastMinuteHandler a function that will take a request and return a response, exactly like
1062
     *                   we use in the other registration methods for this class.
1063
     */
1064
    public void registerLastMinuteHandler(ThrowingFunction<LastMinuteHandlerInputs, IResponse> lastMinuteHandler) {
1065
        this.lastMinuteHandler = lastMinuteHandler;
1066
    }
1067
1068
    /**
1069
     * This allows users to add extra mappings
1070
     * between file suffixes and mime types, in case
1071
     * a user needs one that was not provided.
1072
     * <p>
1073
     *     This is made available through the
1074
     *     web framework.
1075
     * </p>
1076
     * <p>
1077
     *     Example:
1078
     * </p>
1079
     * <pre>
1080
     * {@code webFramework.addMimeForSuffix().put("foo","text/foo")}
1081
     * </pre>
1082
     */
1083
    public void addMimeForSuffix(String suffix, String mimeType) {
1084
        fileSuffixToMime.put(suffix, mimeType);
1085
    }
1086
}

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 : none
negated conditional → TIMED_OUT

167

1.1
Location : httpProcessing
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response(com.renomad.minum.FunctionalTests)
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 : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
removed call to com/renomad/minum/web/WebFramework::addDefaultHeaders → KILLED

184

1.1
Location : httpProcessing
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_Response_MultiCookies(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.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
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 : none
negated conditional → TIMED_OUT

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

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 : none
removed call to java/lang/StringBuilder::setLength → SURVIVED
Covering tests

214

1.1
Location : httpProcessing
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_BadRequest2(com.renomad.minum.FunctionalTests)
removed call to com/renomad/minum/web/WebFramework::addDefaultHeaders → KILLED

220

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

222

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

224

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

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 : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

241

1.1
Location : httpProcessing
Killed by : com.renomad.minum.FunctionalTests.testEndToEnd_Functional(com.renomad.minum.FunctionalTests)
removed call to com/renomad/minum/web/WebFramework::handleForbiddenUse → KILLED

243

1.1
Location : httpProcessing
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_IOExceptionThrown_WebFramework(com.renomad.minum.FunctionalTests)
removed call to com/renomad/minum/web/WebFramework::finalExceptionHandler → KILLED

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 : com.renomad.minum.web.WebTests
negated conditional → KILLED

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 : com.renomad.minum.web.WebTests
negated conditional → KILLED

275

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

292

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

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 : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

330

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

334

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

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 : none
negated conditional → TIMED_OUT

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 : com.renomad.minum.FunctionalTests.test_EdgeCase_PostHandler_IgnoreBody(com.renomad.minum.FunctionalTests)
negated conditional → KILLED

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

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

4.4
Location : determineIfKeepAlive
Killed by : none
negated conditional → TIMED_OUT

396

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

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 : none
replaced return value with null for com/renomad/minum/web/WebFramework::getProcessedRequestLine → TIMED_OUT

408

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

420

1.1
Location : dumpIfAttacker
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.web.WebTests
replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED

422

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

423

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

425

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

426

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

432

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

447

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

467

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

470

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

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

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

481

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

511

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

512

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

516

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

518

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

519

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

525

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

537

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

538

1.1
Location : compressBody
Killed by : com.renomad.minum.FunctionalTests.testEndToEnd_Functional(com.renomad.minum.FunctionalTests)
removed call to java/util/zip/GZIPOutputStream::finish → KILLED

558

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

563

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

568

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

574

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

583

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

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

586

1.1
Location : findHandlerByFilesOnDisk
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response_Range(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 : com.renomad.minum.FunctionalTests.test_PathFunction_Response_Range(com.renomad.minum.FunctionalTests)
replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByFilesOnDisk$25 → KILLED

615

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

617

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

620

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

622

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

625

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

630

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

633

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

637

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

640

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

644

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

646

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

650

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

652

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

653

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

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

656

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

659

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

664

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

673

1.1
Location : getMimeString
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response_Range(com.renomad.minum.FunctionalTests)
changed conditional boundary → KILLED

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

674

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

681

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

684

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

697

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

699

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

703

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.CachingAndCompressionTests
Replaced double multiplication with division → KILLED

704

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

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

711

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

712

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

727

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

756

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

760

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

761

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

793

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

803

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

819

1.1
Location : <init>
Killed by : none
negated conditional → TIMED_OUT

829

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

830

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

834

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

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

835

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

839

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

841

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

857

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

863

1.1
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.WebTests
removed call to com/renomad/minum/web/WebFramework::checkForDuplicatePartialPath → KILLED

876

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

880

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

881

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

930

1.1
Location : lambda$registerPath$40
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_Response_MultiCookies(com.renomad.minum.FunctionalTests)
replaced return value with Collections.emptyList for com/renomad/minum/web/WebFramework::lambda$registerPath$40 → KILLED

947

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

954

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

958

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

959

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