001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.rest.server; 018 019import static java.util.Collections.*; 020import static org.apache.juneau.commons.utils.CollectionUtils.*; 021import static org.apache.juneau.commons.utils.Shorts.*; 022 023import java.io.*; 024import java.net.*; 025import java.util.*; 026import java.util.logging.*; 027 028import org.apache.juneau.commons.collections.*; 029import org.apache.juneau.commons.inject.*; 030import org.apache.juneau.commons.lang.*; 031import org.apache.juneau.commons.logging.*; 032import org.apache.juneau.http.*; 033import org.apache.juneau.http.response.*; 034import org.apache.juneau.marshall.*; 035import org.apache.juneau.rest.server.auth.*; 036import org.apache.juneau.rest.server.logging.*; 037import org.apache.juneau.rest.server.util.*; 038 039import jakarta.servlet.http.*; 040 041/** 042 * Represents a single HTTP request. 043 * 044 * <h2 class='section'>Notes:</h2><ul> 045 * <li class='warn'>This class is not thread safe. 046 * </ul> 047 * 048 */ 049@SuppressWarnings({ 050 "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants 051 "resource", // the per-call BasicBeanStore is owned by this RestSession (closed via finish/close paths); fluent add/addBean calls return the same store we already own. 052 "unchecked" // Type erasure requires cast for pathVars 053}) 054public class RestSession extends ContextSession { 055 056 /** Logger for the finish-path diagnostic-failure containment token (see {@link #finish()}). */ 057 private static final RichLogger LOG = RichLogger.getLogger(RestSession.class); 058 059 /** 060 * Builder class. 061 */ 062 @SuppressWarnings({ 063 "rawtypes" // Raw types required: annotation type parameter is unknown at static analysis time. 064 }) 065 public static class Builder extends ContextSession.Builder { 066 067 private HttpServletRequest req; 068 private HttpServletResponse res; 069 private Object resource; 070 private final RestContext ctx; 071 private String pathInfoUndecoded; 072 private UrlPath urlPath; 073 074 /** 075 * Constructor. 076 * 077 * @param ctx The context creating this session. 078 * <br>Cannot be <jk>null</jk>. 079 */ 080 protected Builder(RestContext ctx) { 081 super(reqnn("ctx", ctx)); 082 this.ctx = ctx; 083 } 084 085 @Override /* Overridden from Session.Builder */ 086 public RestSession build() { 087 return new RestSession(this); 088 } 089 090 /** 091 * Returns the undecoded request servlet path info. 092 * 093 * @return The undecoded request servlet path info, or <jk>null</jk> if there is no extra path information. 094 */ 095 public String getPathInfoUndecoded() { 096 if (pathInfoUndecoded == null) 097 pathInfoUndecoded = RestUtils.getPathInfoUndecoded(req); 098 return pathInfoUndecoded; 099 } 100 101 /** 102 * Returns the request path info as a {@link UrlPath} bean. 103 * 104 * @return The request path info as a {@link UrlPath} bean. 105 */ 106 public UrlPath getUrlPath() { 107 if (urlPath == null) 108 urlPath = UrlPath.of(getPathInfoUndecoded()); 109 return urlPath; 110 } 111 112 /** 113 * Adds resolved <c><ja>@Resource</ja>(path)</c> variable values to this call. 114 * 115 * @param value The variables to add to this call. 116 * <br>Can be <jk>null</jk> (ignored). 117 * @return This object. 118 */ 119 public Builder pathVars(Map<String,String> value) { 120 if (nn(value) && ! value.isEmpty()) { 121 var m = (Map<String,String>)req.getAttribute(REST_PATHVARS_ATTR); 122 if (m == null) { 123 m = new TreeMap<>(); 124 req.setAttribute(REST_PATHVARS_ATTR, m); 125 } 126 m.putAll(value); 127 } 128 return this; 129 } 130 131 /** 132 * Returns the HTTP servlet request object on this call. 133 * 134 * @return The HTTP servlet request object on this call. 135 */ 136 public HttpServletRequest req() { 137 urlPath = null; 138 pathInfoUndecoded = null; 139 return req; 140 } 141 142 /** 143 * Specifies the HTTP servlet request object on this call. 144 * 145 * @param value The value for this setting. 146 * <br>Cannot be <jk>null</jk>. 147 * @return This object. 148 */ 149 public Builder req(HttpServletRequest value) { 150 req = reqnn("value", value); 151 return this; 152 } 153 154 /** 155 * Returns the HTTP servlet response object on this call. 156 * 157 * @return The HTTP servlet response object on this call. 158 */ 159 public HttpServletResponse res() { 160 return res; 161 } 162 163 /** 164 * Specifies the HTTP servlet response object on this call. 165 * 166 * @param value The value for this setting. 167 * <br>Cannot be <jk>null</jk>. 168 * @return This object. 169 */ 170 public Builder res(HttpServletResponse value) { 171 res = reqnn("value", value); 172 return this; 173 } 174 175 /** 176 * Specifies the servlet implementation bean. 177 * 178 * @param value The value for this setting. 179 * <br>Can be <jk>null</jk> (no outer bean will be used for instantiating inner classes). 180 * @return This object. 181 */ 182 public Builder resource(Object value) { 183 resource = value; 184 return this; 185 } 186 } 187 188 /** 189 * Request attribute name for passing path variables from parent to child. 190 */ 191 private static final String REST_PATHVARS_ATTR = "juneau.pathVars"; 192 193 /** 194 * Public-internal servlet-request attribute key under which the active {@link RestSession} publishes itself. 195 * 196 * <p> 197 * The session-handle seam that lets code in other packages resolve the call's cached correlation id without a live 198 * public/custom-key attribute read: the debug formatter's {@code statusLine} (in the {@code logging} package) and 199 * {@code RequestIdFilter} (in the {@code filter} package) both read the session via {@link #fromRequest} and call 200 * {@link #getRequestId()}. Not part of the public REST contract — the attribute name is an internal detail. 201 */ 202 public static final String REQUEST_SESSION_ATTR = "juneau.internal.RestSession"; 203 204 /** 205 * Creates a builder of this object. 206 * 207 * @param ctx The context creating this builder. 208 * <br>Cannot be <jk>null</jk>. 209 * @return A new builder. 210 */ 211 public static Builder create(RestContext ctx) { 212 return new Builder(reqnn("ctx", ctx)); 213 } 214 215 /** 216 * Returns the {@link RestSession} published on the given servlet request via the {@link #REQUEST_SESSION_ATTR} 217 * session-handle seam, or <jk>null</jk> if none is present. 218 * 219 * @param req The servlet request. Can be <jk>null</jk> (returns <jk>null</jk>). 220 * @return The active session, or <jk>null</jk>. 221 */ 222 public static RestSession fromRequest(HttpServletRequest req) { 223 return (nn(req) && req.getAttribute(REQUEST_SESSION_ATTR) instanceof RestSession s) ? s : null; 224 } 225 226 private final long startTime = System.currentTimeMillis(); 227 private final WritableBeanStore beanStore; 228 private HttpServletRequest req; 229 private HttpServletResponse res; 230 private Map<String,String[]> queryParams; 231 private final Object resource; 232 private final RestContext context; 233 private RestOpSession opSession; 234 private String method; 235 private String pathInfoUndecoded; 236 private UrlPath urlPath; 237 private UrlPathMatch urlPathMatch; 238 239 /** 240 * Tracks whether an HTTP status was explicitly assigned via {@link #status(int)} / 241 * {@link #status(HttpStatusLine)} on this call. The {@code NotFound} sentinel in {@link #run()} keys off this 242 * flag instead of {@code getStatus() == 0}, so a genuine 404 stays a 404 under a real container whose response 243 * defaults to the servlet-spec {@code 200} (not the mock's coincidental {@code 0}). A raw 244 * {@code HttpServletResponse.setStatus(...)} (e.g. from a {@code @RestStartCall} hook) bypasses this flag, but 245 * {@link RestContext#handleNotFound(RestSession)} independently normalizes any non-error status to a 404, so an 246 * unmatched path can no longer surface as an HTTP 500 under a real container. A 4xx (or higher) status left by a 247 * start-call hook is preserved: the sentinel does not overwrite it, and {@code handleNotFound} keeps a client-error 248 * status rather than converting it to a 500. 249 */ 250 private boolean statusExplicitlySet; 251 252 /** The correlation id resolved for this call at build time (mint-or-honor). Never {@code null}. */ 253 private final String requestId; 254 255 /** 256 * The single open {@code requestId} {@link LogContext} scope for this call, opened after id resolution and closed 257 * exactly once in {@link #finish()} (after emission) — on the request thread, so a pooled request thread never 258 * carries the scope into the next request. 259 */ 260 private final LogContext.Scope requestIdScope; 261 262 /** 263 * Opaque holder for the debug-resolution snapshot ({@code RestDebugSnapshot}) published at the async-dispatch 264 * handoff and read back on the response-completion thread. Typed as {@link Object} because the snapshot type is a 265 * package-private detail of the {@code logging} package that this class must not expose. Immutable once stashed; 266 * published before the completion callback is registered. 267 */ 268 private Object debugSnapshot; 269 270 /** 271 * Constructor. 272 * 273 * @param builder The builder for this object. 274 * <br>Cannot be <jk>null</jk>. 275 */ 276 public RestSession(Builder builder) { 277 super(builder); 278 context = builder.ctx; 279 resource = builder.resource; 280 beanStore = new BasicBeanStore(context.getBeanStore()).addBean(RestContext.class, context); 281 282 pathInfoUndecoded = builder.pathInfoUndecoded; 283 req = beanStore.add(HttpServletRequest.class, builder.req); 284 res = beanStore.add(HttpServletResponse.class, builder.res); 285 urlPath = beanStore.add(UrlPath.class, builder.urlPath); 286 287 // Always-on request-id correlation resolver. Runs at every session build so it covers 404 / early-error paths 288 // that never reach a @RestStartCall hook, and gives the debug formatter a synchronous, session-cached id to 289 // render. Resolve the id first, then open exactly one LogContext scope (closed in finish()). 290 var settings = context.getRequestIdSettings(); 291 requestId = resolveRequestId(settings, req); 292 req.setAttribute(REQUEST_SESSION_ATTR, this); 293 req.setAttribute(settings.getAttributeKey(), requestId); 294 res.setHeader(RequestIdConstants.HEADER, requestId); 295 requestIdScope = RichLogger.context().with("requestId", requestId); 296 } 297 298 /** 299 * Mints or honors the correlation id for this call. 300 * 301 * <p> 302 * Honors (in order): a non-empty id already stashed under the settings attribute key (idempotent re-entry or a 303 * parent filter); else a sanitized, length-capped, non-truncated, validator-accepted incoming {@code X-Request-Id} 304 * header (sanitize-and-accept); else a freshly minted id from the settings supplier. 305 * 306 * @param settings The resolved request-id settings. Must not be <jk>null</jk>. 307 * @param req The servlet request. Must not be <jk>null</jk>. 308 * @return The resolved id. Never <jk>null</jk> (unless a custom supplier returns <jk>null</jk>). 309 */ 310 private static String resolveRequestId(RequestIdSettings settings, HttpServletRequest req) { 311 var existing = req.getAttribute(settings.getAttributeKey()); 312 if (existing instanceof String s && ! s.isEmpty()) 313 return s; 314 var incoming = req.getHeader(RequestIdConstants.HEADER); 315 if (nn(incoming)) { 316 var sanitized = DebugTextSanitizer.sanitize(incoming, RequestIdConstants.MAX_LEN); 317 if (nn(sanitized) && ! sanitized.isEmpty() && ! sanitized.endsWith(DebugTextSanitizer.TRUNCATED_MARKER) && settings.getValidator().test(sanitized)) 318 return sanitized; 319 } 320 return settings.getIdSupplier().get(); 321 } 322 323 /** 324 * Installs bounded body-caching wrappers on this call's request/response for debug capture. 325 * 326 * <p> 327 * Called by the two-phase debug pipeline when the resolved logger is loggable at 328 * {@link java.util.logging.Level#FINEST FINEST}. Idempotent — the wrappers no-op if already installed. 329 * 330 * <p> 331 * The capture cap is snapshotted from {@link RestContext#getRestDebugFormatter()}<c>.bodyCap()</c> at install 332 * time, so a formatter override actually raises, lowers, or (via {@code bodyCap(0)}) disables the number of 333 * bytes retained — not just the wrapper's own 8 KB default. 334 * 335 * @return This object. 336 * @throws IOException Occurs if the request/response streams could not be wrapped. 337 */ 338 public RestSession installCapture() throws IOException { 339 var cap = resolveBodyCap(); 340 req = CachingHttpServletRequest.wrap(req, cap); 341 res = CachingHttpServletResponse.wrap(res, cap); 342 return this; 343 } 344 345 /** 346 * Resolves the body capture cap in effect for this call, per {@link RestDebugFormatter#bodyCap()}. 347 * 348 * <p> 349 * Mirrors the formatter-resolution fallback used by {@link RestDebugPipeline} (a bean-store lookup can return 350 * <jk>null</jk> despite the {@link RestContext#getRestDebugFormatter()} javadoc contract) so the cap enforced at 351 * capture time always matches the cap the eventual render will report against. 352 * 353 * @return The body capture cap, in bytes. 354 */ 355 private int resolveBodyCap() { 356 var formatter = context.getRestDebugFormatter(); 357 return formatter != null ? formatter.bodyCap() : new BasicRestDebugFormatter().bodyCap(); 358 } 359 360 /** 361 * Identifies that an exception occurred during this call. 362 * 363 * @param value The thrown exception. 364 * <br>Can be <jk>null</jk> (will clear the exception attribute and remove the exception from the bean store). 365 * @return This object. 366 */ 367 public RestSession exception(Throwable value) { 368 req.setAttribute("Exception", value); 369 beanStore.addBean(Throwable.class, value); 370 return this; 371 } 372 373 /** 374 * If the specified failure is a client disconnect (see {@link ClientAborts#isClientAbort(Throwable)}), logs a single 375 * FINE line without a stack trace. 376 * 377 * @param e The failure. 378 * @return <jk>true</jk> if it was a client abort (and so should not be recorded as an exception). 379 */ 380 boolean logClientAbort(Throwable e) { 381 return logClientAbort(e, false); 382 } 383 384 /** 385 * Same as {@link #logClientAbort(Throwable)} but matches only container client-abort types 386 * (see {@link ClientAborts#isContainerClientAbort(Throwable)}). 387 * 388 * @param e The failure. 389 * @return <jk>true</jk> if it was a container-reported client abort. 390 */ 391 boolean logContainerClientAbort(Throwable e) { 392 return logClientAbort(e, true); 393 } 394 395 private boolean logClientAbort(Throwable e, boolean strict) { 396 if (! (strict ? ClientAborts.isContainerClientAbort(e) : ClientAborts.isClientAbort(e))) 397 return false; 398 LOG.fine(() -> "Client disconnected before the response completed: " + req.getMethod() + " " + req.getRequestURI()); 399 return true; 400 } 401 402 /** 403 * Called at the end of a call to finish any remaining tasks such as flushing buffers and logging the response. 404 * 405 * <p> 406 * When the request has been handed off to a real {@code AsyncContext}, the response body/headers are written later 407 * on the response-completion thread. In that case this method neither flushes nor emits nor writes formatter-visible 408 * finish-time attributes — the completion hook owns all of that after the async body exists. The synchronous and 409 * synchronous-fallback (e.g. MockRestClient) paths are unchanged: they set finish-time attributes, flush, and emit 410 * here. 411 * 412 * @return This object. 413 */ 414 public RestSession finish() { 415 // Emit-before-close: the requestId LogContext scope stays open through synchronous emission (so the emitted 416 // record carries the structured id), then always closes in the finally — on the request thread, even on the 417 // async path (where the snapshot was already captured during run()) — so a pooled thread never leaks the scope. 418 try { 419 var asyncOwned = org.apache.juneau.rest.server.processor.AsyncResponseProcessor.isAsyncDispatchOwned(req); 420 try { 421 if (! asyncOwned) 422 setFinishTimeAttributes(); 423 if (nn(opSession)) 424 opSession.finish(); 425 else if (! asyncOwned) { 426 // Skip flush when AsyncContext has been started — see AsyncResponseProcessor. 427 res.flushBuffer(); 428 } 429 } catch (Exception e) { 430 if (! logClientAbort(e)) 431 exception(e); 432 } 433 // Skip synchronous emission on the async path — the completion hook emits after the body/headers are written. 434 if (asyncOwned) 435 return this; 436 // Contain diagnostic formatting/emission: a formatter (or a scrubber that escaped the fail-closed guard) throwing 437 // a RuntimeException/Error during a completed request must not escape and fail the request thread. Log only a 438 // fixed token — never e.getMessage(), the body, the stack, or a second formatter pass — so a scrubber throwing 439 // new RuntimeException(body) cannot re-leak the secret the placeholder just refused. 440 try { 441 RestDebugPipeline.emit(this); 442 } catch (Throwable t) { // NOSONAR - deliberate containment of any diagnostic failure at request completion. 443 LOG.log(Level.WARNING, "debug formatter failed"); 444 } 445 return this; 446 } finally { 447 closeRequestIdScope(); 448 } 449 } 450 451 /** 452 * Closes this call's {@code requestId} {@link LogContext} scope, if open. 453 * 454 * <p> 455 * Idempotent: safe to call more than once (and from a build path that never reaches {@link #finish()}, such as a 456 * throwaway error session). Must run on the request thread that opened the scope so a pooled thread does not carry 457 * the scope into the next request. 458 */ 459 public void closeRequestIdScope() { 460 if (nn(requestIdScope)) 461 requestIdScope.close(); 462 } 463 464 /** 465 * Records the finish-time request attributes consumed by the debug formatter (currently {@code ExecTime}). 466 * 467 * <p> 468 * On the synchronous path this is called from {@link #finish()}. On the asynchronous path it is called by the 469 * completion hook immediately before rendering — never by {@link #finish()} after the async handoff — so the record 470 * always reflects the true request duration and the completion thread never races the request thread over 471 * formatter-visible response state. Idempotent: recomputing the value on repeat calls is harmless. 472 */ 473 public void setFinishTimeAttributes() { 474 req.setAttribute("ExecTime", System.currentTimeMillis() - startTime); 475 } 476 477 /** 478 * Stashes the opaque debug-resolution snapshot on the request thread at the async-dispatch handoff. 479 * 480 * <p> 481 * Internal plumbing for the two-thread async debug pipeline; not part of the public REST contract. The value is a 482 * package-private {@code RestDebugSnapshot} passed as {@link Object} so this class does not expose the type. 483 * 484 * @param value The snapshot, or <jk>null</jk> when access logging is off. 485 */ 486 public void stashDebugSnapshot(Object value) { debugSnapshot = value; } 487 488 /** 489 * Returns the opaque debug-resolution snapshot stashed at the async-dispatch handoff. 490 * 491 * <p> 492 * Internal plumbing for the two-thread async debug pipeline; not part of the public REST contract. 493 * 494 * @return The stashed snapshot, or <jk>null</jk> if none was stashed (synchronous path or access logging off). 495 */ 496 public Object getDebugSnapshot() { return debugSnapshot; } 497 498 /** 499 * Returns the correlation id resolved for this call (mint-or-honor), cached at build time. 500 * 501 * <p> 502 * This is the synchronous, session-cached value the debug formatter and {@code RequestIdFilter} read through the 503 * {@link #fromRequest(HttpServletRequest) session-handle seam} — never a live public/custom-key attribute 504 * read. 505 * 506 * @return The resolved request id. Never <jk>null</jk> (unless a custom id supplier returned <jk>null</jk>). 507 */ 508 public String getRequestId() { return requestId; } 509 510 /** 511 * Returns the bean store of this call. 512 * 513 * @return The bean store of this call. 514 */ 515 public WritableBeanStore getBeanStore() { return beanStore; } 516 517 /** 518 * Returns the context that created this call. 519 * 520 * @return The context that created this call. 521 */ 522 @Override 523 public RestContext getContext() { return context; } 524 525 /** 526 * Returns the exception that occurred during this call. 527 * 528 * @return The exception that occurred during this call, or <jk>null</jk> if no exception occurred. 529 */ 530 public Throwable getException() { return (Throwable)req.getAttribute("Exception"); } 531 532 private static final AsciiSet VALID_METHOD_CHARS = AsciiSet.create().ranges("A-Z", "a-z" ,"0-9").chars("_-").build(); 533 534 /** 535 * Returns the HTTP method name. 536 * 537 * <p> 538 * The request-line method, unless it is overridden by a {@code method} query parameter admitted by 539 * {@code allowedMethodParams}, or by one of the {@link MethodSafety#overrideHeaders() override headers} admitted by 540 * {@code allowedMethodHeaders} (the query parameter wins, then the headers in that order). 541 * 542 * <p> 543 * Override claims on an enabled channel (an allow-list that admits at least one method) must agree: more than one 544 * distinct claim, whether on one channel or across channels, is refused. 545 * 546 * @return The HTTP method name, always uppercased. 547 * @throws MethodNotAllowed If the method parameter contains invalid/malformed characters. 548 * @throws BadRequest If the request carries conflicting method overrides. 549 */ 550 @SuppressWarnings({ 551 "java:S3776" // Cognitive complexity acceptable for REST method resolution/mapping 552 }) 553 public String getMethod() throws MethodNotAllowed, BadRequest { 554 if (method == null) { 555 556 Set<String> s1 = context.getAllowedMethodParams(); 557 Set<String> s2 = context.getAllowedMethodHeaders(); 558 559 var paramClaims = s1.isEmpty() ? List.<String>of() : MethodSafety.queryClaims(req.getQueryString()); 560 var headerClaims = new LinkedHashMap<String,List<String>>(); 561 if (! s2.isEmpty()) { 562 for (var h : MethodSafety.overrideHeaders()) { 563 var e = req.getHeaders(h); 564 if (nn(e) && e.hasMoreElements()) 565 headerClaims.put(h, java.util.Collections.list(e)); 566 } 567 } 568 569 // Claims on an enabled channel must agree, whether or not the allow-list admits them. 570 var distinct = new HashSet<String>(); 571 if (isEnabled(s1)) 572 addClaims(distinct, paramClaims); 573 if (isEnabled(s2)) 574 headerClaims.values().forEach(v -> addClaims(distinct, v)); 575 if (distinct.size() > 1) 576 throw new BadRequest("Conflicting HTTP method overrides."); 577 578 if (! paramClaims.isEmpty()) { 579 var x = paramClaims.get(0); 580 if (s1.contains("*") || s1.contains(x)) 581 method = x; 582 if (method != null && ! VALID_METHOD_CHARS.containsOnly(method)) { 583 throw new MethodNotAllowed(); 584 } 585 } 586 587 if (method == null) { 588 for (var e : headerClaims.entrySet()) { 589 var x = e.getValue().get(0); 590 if (s2.contains("*") || s2.contains(x)) { 591 method = x; 592 break; 593 } 594 } 595 if (method != null && ! VALID_METHOD_CHARS.containsOnly(method)) { 596 throw new MethodNotAllowed(); 597 } 598 } 599 600 if (method == null) 601 method = req.getMethod(); 602 603 method = ucr(method); 604 } 605 606 return method; 607 } 608 609 /** An allow-list is enabled when it admits at least one method: non-empty, and not just the {@code NONE} placeholder. */ 610 private static boolean isEnabled(Set<String> allowed) { 611 return allowed.stream().anyMatch(x -> ! "NONE".equalsIgnoreCase(x)); 612 } 613 614 /** Adds the claims, trimmed and upper-cased as {@link MethodSafety} judges them, skipping blanks. */ 615 private static void addClaims(Set<String> into, List<String> claims) { 616 for (var c : claims) 617 if (inb(c)) 618 into.add(c.trim().toUpperCase(Locale.ROOT)); 619 } 620 621 /** 622 * Returns the operation session of this REST session. 623 * 624 * <p> 625 * The operation session is created once the Java method to be invoked has been determined. 626 * 627 * @return The operation session of this REST session. 628 * @throws InternalServerError If operation session has not been created yet. 629 */ 630 public RestOpSession getOpSession() throws InternalServerError { 631 if (opSession == null) 632 throw new InternalServerError("Op Session not created."); 633 return opSession; 634 } 635 636 /** 637 * Returns the {@link RestOpSession} created during {@link #run()} if one has been built, or {@code null} otherwise. 638 * 639 * <p> 640 * Unlike {@link #getOpSession()}, this method does not throw — it lets callers in lifecycle code paths 641 * (such as mixin endCall dual-firing in {@link RestContext#execute(Object, jakarta.servlet.http.HttpServletRequest, 642 * jakarta.servlet.http.HttpServletResponse)}) inspect whether an operation was ever resolved without risking 643 * a spurious 500 when 404/405/412 paths bypass operation creation entirely. 644 * 645 * @return The operation session, or {@code null} if one was never created (e.g. early routing failure). 646 * @since 10.0.0 647 */ 648 public RestOpSession getOpSessionOrNull() { return opSession; } 649 650 /** 651 * Shortcut for calling <c>getRequest().getPathInfo()</c>. 652 * 653 * @return The request servlet path info. 654 */ 655 public String getPathInfo() { return req.getPathInfo(); } 656 657 /** 658 * Same as {@link #getPathInfo()} but doesn't decode encoded characters. 659 * 660 * @return The undecoded request servlet path info, or <jk>null</jk> if there is no extra path information. 661 */ 662 public String getPathInfoUndecoded() { 663 if (pathInfoUndecoded == null) 664 pathInfoUndecoded = RestUtils.getPathInfoUndecoded(req); 665 return pathInfoUndecoded; 666 } 667 668 /** 669 * Returns resolved <c><ja>@Resource</ja>(path)</c> variable values on this call. 670 * 671 * @return Resolved <c><ja>@Resource</ja>(path)</c> variable values on this call. 672 */ 673 public Map<String,String> getPathVars() { 674 var m = (Map<String,String>)req.getAttribute(REST_PATHVARS_ATTR); 675 return m == null ? emptyMap() : m; 676 } 677 678 /** 679 * Returns the query parameters on the request. 680 * 681 * <p> 682 * Unlike {@link HttpServletRequest#getParameterMap()}, this doesn't parse the content if it's a POST. 683 * 684 * @return The query parameters on the request. 685 */ 686 public Map<String,String[]> getQueryParams() { 687 if (queryParams == null) { 688 if (eqic(req.getMethod(), "POST")) { 689 var listMap = RestUtils.parseQuery(req.getQueryString()); 690 queryParams = map(); 691 for (var e : listMap.entrySet()) { 692 if (e.getValue() == null) 693 queryParams.put(e.getKey(), null); 694 else 695 queryParams.put(e.getKey(), array(e.getValue(), String.class)); 696 } 697 } else 698 queryParams = req.getParameterMap(); 699 } 700 return queryParams; 701 } 702 703 /** 704 * Returns the HTTP servlet request of this REST call. 705 * 706 * @return the HTTP servlet request of this REST call. 707 */ 708 public HttpServletRequest getRequest() { return req; } 709 710 /** 711 * Returns the REST object. 712 * 713 * @return The rest object, or <jk>null</jk> if no resource bean was specified. 714 */ 715 public Object getResource() { return resource; } 716 717 /** 718 * Returns the HTTP servlet response of this REST call. 719 * 720 * @return the HTTP servlet response of this REST call. 721 */ 722 public HttpServletResponse getResponse() { return res; } 723 724 /** 725 * Shortcut for calling <c>getRequest().getServletPath()</c>. 726 * 727 * @return The request servlet path. 728 */ 729 public String getServletPath() { return req.getServletPath(); } 730 731 /** 732 * Shortcut for calling <c>getRequest().getStatus()</c>. 733 * 734 * @return The response status code. 735 */ 736 public int getStatus() { return res.getStatus(); } 737 738 /** 739 * Returns the request path info as a {@link UrlPath} bean. 740 * 741 * @return The request path info as a {@link UrlPath} bean. 742 */ 743 public UrlPath getUrlPath() { 744 if (urlPath == null) 745 urlPath = UrlPath.of(getPathInfoUndecoded()); 746 return urlPath; 747 } 748 749 /** 750 * Returns the URL path pattern match on this call. 751 * 752 * @return The URL path pattern match on this call, or <jk>null</jk> if not set. 753 */ 754 public UrlPathMatch getUrlPathMatch() { return urlPathMatch; } 755 756 /** 757 * Rejects an unsafe-method request that a browser marks as cross-site, unless the resource allows it. 758 * 759 * <p> 760 * A request is refused when <c>Sec-Fetch-Site</c> is <c>cross-site</c>, or when an <c>Origin</c> header is 761 * present (without <c>Sec-Fetch-Site</c>) and neither matches the <c>Host</c> header nor is listed in {@link Rest#allowedOrigins()}. Requests with neither header pass. 762 */ 763 private void checkCrossSite() { 764 if (context.isAllowCrossSite()) 765 return; 766 var m = req.getMethod(); 767 if ("GET".equalsIgnoreCase(m) || "HEAD".equalsIgnoreCase(m) || "OPTIONS".equalsIgnoreCase(m) || "TRACE".equalsIgnoreCase(m)) 768 return; 769 var site = req.getHeader("Sec-Fetch-Site"); 770 var origin = req.getHeader("Origin"); 771 var cross = "cross-site".equalsIgnoreCase(site); 772 // A browser-supplied Sec-Fetch-Site is authoritative; Origin is only compared to Host when it is absent. 773 if (! cross && site == null && origin != null) { 774 var host = req.getHeader("Host"); 775 cross = host == null || ! originMatchesHost(origin, host); 776 if (cross) 777 cross = ! isTrustedOrigin(origin); 778 } 779 if (cross) 780 throw new Forbidden("Cross-site request refused."); 781 } 782 783 private boolean isTrustedOrigin(String origin) { 784 var trusted = context.getAllowedOrigins(); 785 if (trusted.isEmpty()) 786 return false; 787 var o = origin.endsWith("/") ? origin.substring(0, origin.length() - 1) : origin; 788 if (trusted.contains(o)) 789 return true; 790 var fwd = req.getHeader("X-Forwarded-Host"); 791 if (fwd == null) 792 return false; 793 for (var t : trusted) { 794 try { 795 var u = URI.create(t); 796 if (u.getAuthority() != null && u.getAuthority().equalsIgnoreCase(fwd.trim())) 797 return originMatchesHost(origin, fwd.trim()); 798 } catch (IllegalArgumentException e) { 799 // Ignore malformed entry. 800 } 801 } 802 return false; 803 } 804 805 static boolean originMatchesHost(String origin, String host) { 806 try { 807 var u = URI.create(origin); 808 var h = u.getHost(); 809 if (h == null || u.getScheme() == null) 810 return false; 811 var port = u.getPort(); 812 var defaultPort = "https".equalsIgnoreCase(u.getScheme()) ? 443 : 80; 813 var authority = port < 0 || port == defaultPort ? h : h + ":" + port; 814 var hostNorm = host.endsWith(":" + defaultPort) ? host.substring(0, host.length() - (":" + defaultPort).length()) : host; 815 return authority.equalsIgnoreCase(hostNorm); 816 } catch (IllegalArgumentException e) { 817 return false; 818 } 819 } 820 821 /** 822 * Runs this session. 823 * 824 * <p> 825 * Does the following: 826 * <ol> 827 * <li>Finds the Java method to invoke, refuses a safe request overridden to a method that is not a read (see 828 * {@link RestOp#read()}), and creates a {@link RestOpSession} for it. 829 * <li>Invokes {@link RestPreCall} methods by calling {@link RestContext#preCall(RestOpSession)}. 830 * <li>Invokes Java method by calling {@link RestOpSession#run()}. 831 * <li>Invokes {@link RestPostCall} methods by calling {@link RestContext#postCall(RestOpSession)}. 832 * <li>If the Java method produced output, finds the response processor for it and runs it by calling {@link RestContext#processResponse(RestOpSession)}. 833 * <li>If no Java method matched, generates a 404/405/412 by calling {@link RestContext#handleNotFound(RestSession)}. 834 * </ol> 835 * 836 * @throws Exception Any exception can be thrown. 837 */ 838 public void run() throws Exception { 839 try { 840 checkCrossSite(); 841 var op = context.getRestOperations().findOperation(this); 842 checkOverride(op); 843 opSession = op.createSession(this).build(); 844 // For mixin endpoints, fire the mixin's @RestStartCall hooks now that the operation is resolved. 845 // The host's @RestStartCall hooks already fired in RestContext#execute() before s.run(). 846 // Order: host first, mixin second. 847 var opRestContext = opSession.getContext().getContext(); 848 if (opRestContext.isMixinContext()) 849 opRestContext.startCall(this); 850 if (! authenticateOrChallenge(opRestContext)) 851 return; 852 context.preCall(opSession); 853 opSession.run(); 854 context.postCall(opSession); 855 if (opSession.getResponse().hasContent()) { 856 // Now serialize the output if there was any. 857 // Some subclasses may write to the OutputStream or Writer directly. 858 context.processResponse(opSession); 859 } 860 } catch (NotFound e) { 861 // A status of 400 or above can only have been left by a start-call hook; keep it so handleNotFound can honor it. 862 // (A 405/412 from findOperation is thrown as its own exception and bypasses this catch, so those always win.) 863 if (! statusExplicitlySet && res.getStatus() < 400) 864 status(404); 865 exception(e); 866 context.handleNotFound(this); 867 } 868 } 869 870 /** 871 * Refuses a safe request (<c>GET</c>, <c>HEAD</c>, <c>OPTIONS</c>, <c>TRACE</c>) whose method was overridden to one 872 * that is neither safe nor the method of an operation declared {@link RestOp#read() read=true}. 873 * 874 * <p> 875 * Checked here rather than in {@link RestOperations#findOperation(RestSession)}, because a resource can replace 876 * its operations bean, and before the operation session is created, so nothing runs for a request that cannot 877 * succeed. It sees only the request line, the dispatched method and the operation, so every override channel is 878 * covered. 879 * 880 * @param op The operation that matched. 881 * @throws MethodNotAllowed If the override is refused. 882 * @throws BadRequest If the request carries conflicting method overrides. 883 */ 884 private void checkOverride(RestOpContext op) throws MethodNotAllowed, BadRequest { 885 var line = ucr(req.getMethod()); 886 var m = getMethod(); 887 if (MethodSafety.isSafe(line) && neq(m, line) && ! MethodSafety.isSafe(m) && ! op.isRead()) { 888 // The message doesn't echo the claimed method. 889 var e = new MethodNotAllowed("Method override not allowed on a safe request method."); 890 e.setHeader("Allow", context.getRestOperations().allowedMethods(this)); 891 throw e; 892 } 893 } 894 895 /** 896 * Runs the resource-level authentication fold ({@link RestAuthenticator}) and, on failure, writes the 401 challenge. 897 * 898 * <p> 899 * Runs before preCall so {@link RestPreCall @RestPreCall} hooks, guards (roleGuard), and {@code @Auth} arg resolution 900 * all see the resolved principal/roles. 901 * 902 * @param opRestContext The operation's REST context. 903 * @return <jk>true</jk> if the request should proceed, or <jk>false</jk> if a 401 challenge was sent and processing 904 * should stop. 905 * @throws IOException If writing the challenge response fails. 906 */ 907 private boolean authenticateOrChallenge(RestContext opRestContext) throws IOException { 908 try { 909 opRestContext.authenticate(opSession); 910 return true; 911 } catch (AuthenticationException e) { 912 AuthFilter.sendChallenge(res, e); 913 return false; 914 } 915 } 916 917 /** 918 * Sets the HTTP status on this call. 919 * 920 * @param value The status code. 921 * @return This object. 922 */ 923 public RestSession status(int value) { 924 statusExplicitlySet = true; 925 res.setStatus(value); 926 return this; 927 } 928 929 /** 930 * Sets the HTTP status on this call. 931 * 932 * @param value The status code. 933 * <br>Can be <jk>null</jk> (ignored). 934 * @return This object. 935 */ 936 public RestSession status(HttpStatusLine value) { 937 if (nn(value)) { 938 statusExplicitlySet = true; 939 res.setStatus(value.getStatusCode()); 940 } 941 return this; 942 } 943 944 /** 945 * Sets the URL path pattern match on this call. 946 * 947 * @param value The match pattern. 948 * <br>Can be <jk>null</jk> (stored as an explicit <jk>null</jk> binding, distinct from no binding at all). 949 * @return This object. 950 */ 951 public RestSession urlPathMatch(UrlPathMatch value) { 952 urlPathMatch = beanStore.add(UrlPathMatch.class, value); 953 return this; 954 } 955 956 @Override /* Overridden from ContextSession */ 957 protected FluentMap<String,Object> properties() { 958 return super.properties() 959 .a("context", context) 960 .a("resource", resource); 961 } 962}