-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenApiServer.java
More file actions
484 lines (439 loc) · 18.2 KB
/
Copy pathOpenApiServer.java
File metadata and controls
484 lines (439 loc) · 18.2 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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package com.retailsvc.http;
import static java.lang.Thread.ofVirtual;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.Executors.newThreadPerTaskExecutor;
import com.retailsvc.http.internal.DispatchHandler;
import com.retailsvc.http.internal.ExceptionFilter;
import com.retailsvc.http.internal.ExtraRouteAdapter;
import com.retailsvc.http.internal.FormTypeMapper;
import com.retailsvc.http.internal.NotFoundHandler;
import com.retailsvc.http.internal.PemSslContext;
import com.retailsvc.http.internal.RequestPreparationFilter;
import com.retailsvc.http.internal.ResponseRenderer;
import com.retailsvc.http.internal.Router;
import com.retailsvc.http.internal.SecurityFilter;
import com.retailsvc.http.internal.TextTypeMapper;
import com.retailsvc.http.internal.TlsHttpsConfigurator;
import com.retailsvc.http.internal.gson.GsonJsonMapper;
import com.retailsvc.http.spec.Operation;
import com.retailsvc.http.spec.Spec;
import com.retailsvc.http.spec.security.SecurityRequirement;
import com.retailsvc.http.spec.security.SecurityScheme;
import com.retailsvc.http.validate.DefaultValidator;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsServer;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import javax.net.ssl.SSLContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Set up an {@link HttpServer} exposing endpoints declared in an OpenAPI 3.1.x specification.
*
* @author thced
*/
public class OpenApiServer implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(OpenApiServer.class);
private static final int DEFAULT_PORT = 8080;
private static final int DEFAULT_HTTPS_PORT = 8443;
private static final String JSON = "application/json";
private static final String GSON_CLASS = "com.google.gson.Gson";
private final HttpServer httpServer;
private final int shutdownTimeoutSeconds;
/** Internal grouping of handler-related configuration to keep the constructor signature small. */
record HandlerConfig(
Map<String, RequestHandler> handlers,
List<RequestInterceptor> interceptors,
List<ResponseDecorator> decorators,
ExceptionHandler exceptionHandler,
Map<String, RequestHandler> extras,
Map<String, SchemeValidator> securityValidators,
boolean externalAuth,
List<AfterResponseHook> afterHooks) {}
OpenApiServer(
Spec spec,
Map<String, TypeMapper> bodyMappers,
HandlerConfig handlerConfig,
int port,
InetAddress bindAddress,
int shutdownTimeoutSeconds,
SSLContext sslContext)
throws IOException {
requireNonNull(spec, "Spec must not be null");
requireNonNull(bodyMappers, "bodyMappers must not be null");
requireNonNull(handlerConfig.handlers(), "handlers must not be null");
ExceptionHandler exceptionHandler = handlerConfig.exceptionHandler();
long t0 = System.currentTimeMillis();
Router router = new Router(spec.operations());
Map<String, Operation> operationsById =
spec.operations().stream()
.collect(Collectors.toUnmodifiableMap(Operation::operationId, op -> op));
DefaultValidator validator = new DefaultValidator(spec::resolveSchema);
InetSocketAddress socketAddress =
(bindAddress == null)
? new InetSocketAddress(port)
: new InetSocketAddress(bindAddress, port);
if (sslContext != null) {
HttpsServer https = HttpsServer.create(socketAddress, 0);
https.setHttpsConfigurator(new TlsHttpsConfigurator(sslContext));
this.httpServer = https;
} else {
this.httpServer = HttpServer.create(socketAddress, 0);
}
httpServer.setExecutor(newThreadPerTaskExecutor(ofVirtual().name("http-", 0).factory()));
ResponseRenderer renderer = new ResponseRenderer(bodyMappers);
String basePath = Optional.ofNullable(spec.basePath()).orElse("/");
HttpContext ctx = httpServer.createContext(basePath);
ctx.getFilters()
.add(
new RequestPreparationFilter(
spec,
router,
validator,
bodyMappers,
exceptionHandler,
renderer,
handlerConfig.afterHooks()));
ctx.getFilters()
.add(
new SecurityFilter(
operationsById,
spec.securitySchemes(),
spec.security(),
handlerConfig.securityValidators(),
handlerConfig.externalAuth()));
ctx.setHandler(
new DispatchHandler(
handlerConfig.handlers(),
handlerConfig.interceptors(),
handlerConfig.decorators(),
renderer));
for (Map.Entry<String, RequestHandler> e : handlerConfig.extras().entrySet()) {
HttpContext extraCtx = httpServer.createContext(e.getKey());
extraCtx.getFilters().add(new ExceptionFilter(exceptionHandler, renderer));
extraCtx.setHandler(new ExtraRouteAdapter(e.getKey(), e.getValue(), renderer));
}
if (!"/".equals(basePath)) {
httpServer.createContext("/", new NotFoundHandler());
}
httpServer.start();
this.shutdownTimeoutSeconds = shutdownTimeoutSeconds;
String host = httpServer.getAddress().getHostString();
String displayHost = host.contains(":") ? "[" + host + "]" : host;
LOG.info(
"Server started ({}:{}) in {}ms",
displayHost,
httpServer.getAddress().getPort(),
System.currentTimeMillis() - t0);
}
public int listenPort() {
return httpServer.getAddress().getPort();
}
/**
* Returns the local address the server is bound to. For a wildcard-bound server this is the
* wildcard address; for a loopback-bound server this is the loopback address.
*/
public InetAddress bindAddress() {
return httpServer.getAddress().getAddress();
}
/**
* Stops the server, waiting up to {@code delaySeconds} for active exchanges to finish before
* closing them. {@code 0} stops immediately.
*
* @param delaySeconds maximum seconds to wait for in-flight exchanges; must be non-negative
*/
public void stop(int delaySeconds) {
if (delaySeconds < 0) {
throw new IllegalArgumentException("delaySeconds must be non-negative, got " + delaySeconds);
}
if (httpServer != null) {
httpServer.stop(delaySeconds);
}
}
@Override
public void close() {
stop(shutdownTimeoutSeconds);
}
public static Builder builder() {
return new Builder();
}
/** Fluent builder for {@link OpenApiServer}. */
public static final class Builder {
private Spec spec;
private final LinkedHashMap<String, TypeMapper> bodyMappers = new LinkedHashMap<>();
private Map<String, RequestHandler> handlers;
private final List<ResponseDecorator> decorators = new ArrayList<>();
private final List<RequestInterceptor> interceptors = new ArrayList<>();
private final List<AfterResponseHook> afterHooks = new ArrayList<>();
private ExceptionHandler exceptionHandler;
private Integer port;
private Path httpsCertChain;
private Path httpsPrivateKey;
private InetAddress bindAddress;
private int shutdownTimeoutSeconds = 0;
private final LinkedHashMap<String, RequestHandler> extras = new LinkedHashMap<>();
private final Map<String, SchemeValidator> securityValidators = new LinkedHashMap<>();
private boolean externalAuth = false;
private Builder() {}
public Builder spec(Spec spec) {
this.spec = spec;
return this;
}
public Builder bodyMapper(String mediaType, TypeMapper mapper) {
requireNonNull(mediaType, "mediaType must not be null");
requireNonNull(mapper, "mapper must not be null");
bodyMappers.put(mediaType.toLowerCase(Locale.ROOT), mapper);
return this;
}
public Builder jsonMapper(TypeMapper mapper) {
return bodyMapper(JSON, mapper);
}
public Builder handlers(Map<String, RequestHandler> handlers) {
this.handlers = handlers;
return this;
}
/**
* Registers a {@link ResponseDecorator} that transforms the {@link Response} returned by the
* handler before it is rendered. Decorators compose in registration order; decorator-supplied
* headers override handler-supplied ones on conflict.
*/
public Builder responseDecorator(ResponseDecorator decorator) {
decorators.add(requireNonNull(decorator, "decorator must not be null"));
return this;
}
/**
* Registers a {@link RequestInterceptor} that wraps the handler invocation. Interceptors run in
* registration order; the first registered is the outermost.
*/
public Builder interceptor(RequestInterceptor interceptor) {
interceptors.add(requireNonNull(interceptor, "interceptor must not be null"));
return this;
}
/**
* Registers an {@link AfterResponseHook} invoked after each response is sent. Hooks run on the
* request thread inside the library's request scope, in registration order, with all exceptions
* swallowed. Hooks fire only when a {@link Request} was successfully built — pre-request
* failures (404, 405, 400 validation) do not fire hooks.
*/
public Builder afterResponseHook(AfterResponseHook hook) {
afterHooks.add(requireNonNull(hook, "hook must not be null"));
return this;
}
/**
* Registers a {@link SchemeValidator} for the OpenAPI security scheme named {@code schemeName}.
* The library extracts a {@link Credential} per request and hands it to this callback; return a
* non-empty {@link Optional} carrying the principal on success, or {@link Optional#empty()} to
* deny. Library renders 401/403 on denial.
*/
public Builder securityValidator(String schemeName, SchemeValidator validator) {
requireNonNull(schemeName, "schemeName must not be null");
requireNonNull(validator, "validator must not be null");
securityValidators.put(schemeName, validator);
return this;
}
/**
* Opts out of in-process security enforcement. Use when an external sidecar (OPA/Envoy etc.)
* authenticates requests upstream. The library still parses {@code securitySchemes} into the
* {@link Spec}, but {@code SecurityFilter} short-circuits and the boot-time
* validator-registration check is skipped.
*/
public Builder useExternalAuthentication() {
this.externalAuth = true;
return this;
}
public Builder exceptionHandler(ExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
/**
* Sets the TCP port to listen on. Defaults to {@value #DEFAULT_PORT} for HTTP and {@value
* #DEFAULT_HTTPS_PORT} when {@link #https(Path, Path)} is set. Use {@code 0} to bind on an
* ephemeral port (read it back via {@link OpenApiServer#listenPort()}).
*/
public Builder port(int port) {
this.port = port;
return this;
}
/**
* Restricts the server to a specific local interface. {@code null} (the default) binds to the
* wildcard address (all interfaces). Use {@link InetAddress#getLoopbackAddress()} to listen on
* loopback only.
*/
public Builder bindAddress(InetAddress bindAddress) {
this.bindAddress = bindAddress;
return this;
}
/**
* Enables HTTPS using the given PEM-encoded certificate chain and PKCS#8 private key. Both
* files must exist when {@link #build()} runs; failures surface as {@link
* IllegalStateException} with the offending path. The certificate file is a PEM concatenation
* of the server certificate followed by any intermediates (matches certbot's {@code
* fullchain.pem}). The private key is an unencrypted PKCS#8 PEM (matches certbot's {@code
* privkey.pem}); RSA and EC keys are both accepted.
*
* <p>When set, the default port changes from {@value #DEFAULT_PORT} to {@value
* #DEFAULT_HTTPS_PORT}; {@link #port(int)} still overrides.
*/
public Builder https(Path certificateChainPem, Path privateKeyPem) {
this.httpsCertChain =
requireNonNull(certificateChainPem, "certificateChainPem must not be null");
this.httpsPrivateKey = requireNonNull(privateKeyPem, "privateKeyPem must not be null");
return this;
}
/**
* Sets the default drain timeout used by {@link OpenApiServer#close()}. {@code 0} (the default)
* stops immediately; positive values wait up to that many seconds for in-flight exchanges to
* finish.
*/
public Builder shutdownTimeoutSeconds(int shutdownTimeoutSeconds) {
if (shutdownTimeoutSeconds < 0) {
throw new IllegalArgumentException(
"shutdownTimeoutSeconds must be non-negative, got " + shutdownTimeoutSeconds);
}
this.shutdownTimeoutSeconds = shutdownTimeoutSeconds;
return this;
}
/**
* Registers an extra HTTP route at {@code path} that bypasses OpenAPI validation and routing.
* Use for side concerns like {@code /alive}, {@code /health}, or serving the spec itself —
* anything that isn't an OpenAPI {@code operationId}. For OpenAPI-described operations use
* {@link #handlers(Map)}.
*/
public Builder extraRoute(String path, RequestHandler handler) {
requireNonNull(path, "path must not be null");
requireNonNull(handler, "handler must not be null");
if (extras.containsKey(path)) {
throw new IllegalStateException("duplicate extra route path: " + path);
}
extras.put(path, handler);
return this;
}
public OpenApiServer build() throws IOException {
requireNonNull(spec, "Spec must not be null");
requireNonNull(handlers, "handlers must not be null");
String basePath = Optional.ofNullable(spec.basePath()).orElse("/");
for (String path : extras.keySet()) {
if (path.equals(basePath)) {
throw new IllegalStateException(
"extra handler path " + path + " conflicts with spec basePath " + basePath);
}
}
if (!externalAuth) {
validateSecurityWiring(spec, securityValidators);
}
validateHandlerWiring(spec, handlers);
Map<String, TypeMapper> resolved = resolveBodyMappers(bodyMappers);
ExceptionHandler effectiveExceptionHandler =
exceptionHandler != null ? exceptionHandler : Handlers.defaultExceptionHandler();
HandlerConfig handlerConfig =
new HandlerConfig(
handlers,
interceptors,
decorators,
effectiveExceptionHandler,
extras,
Map.copyOf(securityValidators),
externalAuth,
List.copyOf(afterHooks));
int resolvedPort = resolvePort();
SSLContext sslContext =
httpsCertChain != null ? PemSslContext.load(httpsCertChain, httpsPrivateKey) : null;
return new OpenApiServer(
spec,
resolved,
handlerConfig,
resolvedPort,
bindAddress,
shutdownTimeoutSeconds,
sslContext);
}
private int resolvePort() {
if (port != null) {
return port;
}
return httpsCertChain != null ? DEFAULT_HTTPS_PORT : DEFAULT_PORT;
}
private static void validateHandlerWiring(Spec spec, Map<String, RequestHandler> handlers) {
Set<String> specOps = new TreeSet<>();
for (Operation op : spec.operations()) {
specOps.add(op.operationId());
}
Set<String> missing = new TreeSet<>(specOps);
missing.removeAll(handlers.keySet());
if (!missing.isEmpty()) {
throw new IllegalStateException(
"no handler registered for spec operationId(s): " + missing);
}
Set<String> unknown = new TreeSet<>(handlers.keySet());
unknown.removeAll(specOps);
if (!unknown.isEmpty()) {
throw new IllegalStateException(
"handler registered for unknown operationId(s) not in spec: " + unknown);
}
}
private static void validateSecurityWiring(Spec spec, Map<String, SchemeValidator> validators) {
Set<String> referenced = new LinkedHashSet<>();
for (Operation op : spec.operations()) {
for (SecurityRequirement req : op.security().orElse(spec.security())) {
referenced.addAll(req.schemes().keySet());
}
}
for (String name : referenced) {
SecurityScheme scheme = spec.securitySchemes().get(name);
if (scheme == null) {
throw new IllegalStateException(
"security requirement references unknown scheme '" + name + "'");
}
if (scheme instanceof SecurityScheme.Unsupported(String type)) {
throw new IllegalStateException(
"scheme '" + name + "' uses unsupported type '" + type + "'");
}
if (!validators.containsKey(name)) {
throw new IllegalStateException(
"no SchemeValidator registered for security scheme '" + name + "'");
}
}
}
private static Map<String, TypeMapper> resolveBodyMappers(
Map<String, TypeMapper> userSupplied) {
LinkedHashMap<String, TypeMapper> out = new LinkedHashMap<>();
out.put("application/x-www-form-urlencoded", new FormTypeMapper());
out.put("text/plain", new TextTypeMapper());
out.put("text/html", new TextTypeMapper());
out.putAll(userSupplied);
if (!out.containsKey(JSON)) {
TypeMapper fallback = tryLoadGsonMapper();
if (fallback != null) {
out.put(JSON, fallback);
}
}
if (!out.containsKey(JSON)) {
throw new IllegalStateException(
"No TypeMapper registered for application/json and Gson not found on classpath; "
+ "register one via Builder.bodyMapper(\"application/json\", ...)");
}
return out;
}
private static TypeMapper tryLoadGsonMapper() {
try {
Class.forName(GSON_CLASS, false, OpenApiServer.class.getClassLoader());
} catch (ClassNotFoundException _) {
return null;
}
return new GsonJsonMapper();
}
}
}