-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHandlers.java
More file actions
186 lines (174 loc) · 7.29 KB
/
Copy pathHandlers.java
File metadata and controls
186 lines (174 loc) · 7.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package com.retailsvc.http;
import static com.retailsvc.http.spec.HttpMethod.GET;
import static com.retailsvc.http.spec.HttpMethod.HEAD;
import static java.net.HttpURLConnection.HTTP_BAD_METHOD;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAVAILABLE;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.retailsvc.http.internal.HealthRenderer;
import com.retailsvc.http.internal.ProblemDetail;
import com.retailsvc.http.internal.ProblemDetailRenderer;
import com.retailsvc.http.internal.ResourceSource;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Handlers {
private static final Logger LOG = LoggerFactory.getLogger(Handlers.class);
private static final String ALLOW = "Allow";
private static final String GET_HEAD = "GET, HEAD";
private Handlers() {}
/**
* Response decorator that adds two browser-hardening headers to every response:
*
* <ul>
* <li>{@code X-Content-Type-Options: nosniff} — prevents MIME sniffing.
* <li>{@code Cross-Origin-Resource-Policy: same-origin} — blocks cross-origin reads of the
* response body, mitigating Spectre-class side-channel attacks.
* </ul>
*
* <p>Existing headers with the same names are preserved, so a handler that sets either header
* keeps its value. Wire it in with {@code
* OpenApiServer.builder().responseDecorator(Handlers.securityHeadersDecorator())}.
*/
public static ResponseDecorator securityHeadersDecorator() {
return (request, response) -> {
Response decorated = response;
if (!response.headers().containsKey("X-Content-Type-Options")) {
decorated = decorated.withHeader("X-Content-Type-Options", "nosniff");
}
if (!response.headers().containsKey("Cross-Origin-Resource-Policy")) {
decorated = decorated.withHeader("Cross-Origin-Resource-Policy", "same-origin");
}
return decorated;
};
}
public static ExceptionHandler defaultExceptionHandler() {
return t ->
switch (t) {
case ValidationException ve ->
Response.bytes(
HTTP_BAD_REQUEST,
ProblemDetailRenderer.renderJson(ProblemDetail.forValidation(ve.error())),
"application/problem+json");
case BadRequestException bre -> {
if (bre.getCause() != null && LOG.isDebugEnabled()) {
LOG.debug("BadRequestException cause", bre.getCause());
}
yield Response.bytes(
bre.status(),
ProblemDetailRenderer.renderJson(ProblemDetail.forBadRequest(bre)),
"application/problem+json");
}
case NotFoundException nfe -> {
if (nfe.getCause() != null && LOG.isDebugEnabled()) {
LOG.debug("NotFoundException cause", nfe.getCause());
}
yield Response.notFound();
}
case MethodNotAllowedException mna ->
Response.status(HTTP_BAD_METHOD)
.withHeader(
ALLOW,
mna.allowed().stream().map(Enum::name).collect(Collectors.joining(", ")));
default -> {
LOG.error("Unhandled exception in handler", t);
yield Response.status(HTTP_INTERNAL_ERROR);
}
};
}
/** Returns 204 No Content on GET/HEAD; 405 with {@code Allow: GET, HEAD} otherwise. */
public static RequestHandler aliveHandler() {
return req ->
switch (req.method()) {
case GET, HEAD -> Response.empty();
default -> Response.status(HTTP_BAD_METHOD).withHeader(ALLOW, GET_HEAD);
};
}
/**
* Health endpoint handler. Accepts GET and HEAD; returns 200 with {@code application/json} body
* when the supplied probe reports up (all dependencies up, or no dependencies), and 503 with the
* same body shape otherwise. A probe that throws a {@link RuntimeException} or returns {@code
* null} is mapped to a {@code Down} response with an empty dependency list (and 503); the failure
* is never propagated to the default exception handler.
*
* <p>The wire shape is
*
* <pre>{@code
* {"outcome":"Up","dependencies":[{"id":"jdbc","status":"Up"}]}
* }</pre>
*
* <p>The body is rendered by a built-in writer; no JSON library on the classpath is required.
*
* @param probe supplier of the current {@link HealthOutcome}
*/
public static RequestHandler healthHandler(Supplier<HealthOutcome> probe) {
Objects.requireNonNull(probe, "probe");
return req -> {
if (req.method() != GET && req.method() != HEAD) {
return Response.status(HTTP_BAD_METHOD).withHeader(ALLOW, GET_HEAD);
}
boolean up;
List<Dependency> dependencies;
try {
HealthOutcome outcome = Objects.requireNonNull(probe.get(), "Health probe returned null");
up = outcome.up();
dependencies = outcome.dependencies();
} catch (RuntimeException e) {
LOG.warn("Health probe failed", e);
up = false;
dependencies = List.of();
}
byte[] body = HealthRenderer.renderJson(up, dependencies).getBytes(UTF_8);
int status = up ? HTTP_OK : HTTP_UNAVAILABLE;
return Response.bytes(status, body, "application/json");
};
}
/**
* Serves a classpath resource as a streaming response. Content-Type is inferred from the file
* extension. Existence and length are resolved at construction; a missing resource fails
* immediately with {@link IllegalArgumentException}. The resource is opened and closed per
* request — the handler owns the stream lifecycle.
*
* @param classpathResource absolute classpath path, e.g. {@code /schemas/v1/openapi.yaml}
*/
public static RequestHandler resourceHandler(String classpathResource) {
return resourceHandler(ResourceSource.ofClasspath(classpathResource));
}
/**
* Serves a filesystem file as a streaming response. Content-Type is inferred from the file
* extension. Existence and length are resolved at construction; a missing file fails immediately
* with {@link IllegalArgumentException}. The file is opened and closed per request.
*/
public static RequestHandler resourceHandler(Path file) {
return resourceHandler(ResourceSource.ofFile(file));
}
private static RequestHandler resourceHandler(ResourceSource source) {
long length = source.length();
String contentType = source.contentType();
return req ->
switch (req.method()) {
case GET ->
Response.stream(
HTTP_OK,
length,
contentType,
out -> {
try (InputStream in = source.open()) {
in.transferTo(out);
}
});
case HEAD ->
Response.status(HTTP_OK)
.withContentType(contentType)
.withHeader("Content-Length", String.valueOf(length));
default -> Response.status(HTTP_BAD_METHOD).withHeader(ALLOW, GET_HEAD);
};
}
}