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.console.bus; 018 019import java.io.*; 020 021import jakarta.servlet.http.HttpServletRequest; 022 023import org.apache.juneau.http.*; 024import org.apache.juneau.marshall.collections.*; 025import org.apache.juneau.marshall.json.*; 026import org.apache.juneau.rest.server.*; 027 028/** 029 * Exposes the bus's session POST and SSE stream on a REST resource. 030 * 031 * <ul> 032 * <li><b>{@code POST <servlet>/juneau-bus/session}</b> — opens a session and returns its grant. This is the 033 * protocol's only state-changing request, so every guard the application has applies to it. 034 * <li><b>{@code GET <servlet>/juneau-bus/stream/{sessionId}}</b> — a held-open {@code text/event-stream} of bus 035 * frames, each as {@code event: bus}. Gated by the capability in the path; an unknown or expired id, or another 036 * principal, is a {@code 404}. 037 * </ul> 038 * 039 * <p> 040 * When {@link BusPolicy#boundary()} is set, both endpoints run its {@code check}: the full write check on the POST, 041 * and on the GET whatever the boundary applies to a read (a {@code LoopbackBoundary}'s Host check, a 042 * {@code CsrfBoundary}'s allowed hosts). The method judged is the one the request claims, so a GET carrying a 043 * {@code method} parameter or an override header that claims a write gets the write check. 044 * 045 * <h2 class='section'>Example:</h2> 046 * <p class='bjava'> 047 * <ja>@Rest</ja>(path=<js>"/ops/jobs"</js>) 048 * <jk>public class</jk> JobsRest <jk>extends</jk> BasicRestServlet <jk>implements</jk> AsyncJobsMixin, BusEventsMixin { 049 * <jk>static final</jk> ServerBus <jsf>BUS</jsf> = ServerBus.<jsm>create</jsm>(BusPolicy.<jsm>create</jsm>() 050 * .downstream(<js>"ops.jobs"</js>, <jk>true</jk>).build()); 051 * <ja>@Override</ja> <jk>public</jk> ServerBus serverBus() { <jk>return</jk> <jsf>BUS</jsf>; } 052 * ... 053 * } 054 * </p> 055 * 056 * <h2 class='section'>Example:</h2> 057 * <p class='bjava'> 058 * <jc>// An application with its own CSRF guard puts it in front of the session POST. 059 * // Re-declaring @RestPost here is optional and registers the route once.</jc> 060 * <ja>@Override</ja> <ja>@RestPost</ja>(path=<jsf>SESSION_PATH</jsf>) 061 * <jk>public</jk> JsonMap openBusSession(RestRequest <jv>req</jv>, RestResponse <jv>res</jv>) { 062 * requireCsrfToken(<jv>req</jv>); 063 * <jk>return</jk> BusEventsMixin.<jk>super</jk>.openBusSession(<jv>req</jv>, <jv>res</jv>); 064 * } 065 * </p> 066 * 067 * @since 10.0.0 068 */ 069public interface BusEventsMixin { 070 071 /** The servlet-relative prefix of both endpoints. */ 072 String BUS_PREFIX = "/juneau-bus"; 073 074 /** The session POST path. */ 075 String SESSION_PATH = BUS_PREFIX + "/session"; 076 077 /** The SSE stream path. */ 078 String STREAM_PATH = BUS_PREFIX + "/stream/{sessionId}"; 079 080 /** 081 * The bus this resource serves. 082 * 083 * @return The bus. Typically one per application, shared with the code that publishes. 084 */ 085 ServerBus serverBus(); 086 087 /** 088 * [POST /juneau-bus/session] — opens a bus session. 089 * 090 * <p> 091 * Body (at most 64 KB; a larger body is a 400): {@code {"v":1, "bridge":"ops", "transport":"sse"|"websocket", "downstream":[...], "upstream":[...]}}. 092 * Returns the grant ({@code sessionId}, {@code heartbeatMs}, {@code graceMs}, {@code downstream} with each topic's 093 * {@code retain}, {@code upstream} and {@code paths}). A refusal sets its status (400, 403, 429 with 094 * {@code Retry-After}, or 501) and returns {@code {"code":..., "message":..., "denied":[...]}}. 095 * 096 * @param req The REST request. 097 * @param res The REST response. 098 * @return The grant, or the refusal body. 099 */ 100 @SuppressWarnings({ 101 "resource" // False positive: serverBus() returns the shared AutoCloseable bus, which this method borrows but does not own. 102 }) 103 @RestPost(path=SESSION_PATH, summary="Open a message-bus session", swagger=@OpSwagger(ignore=true)) 104 default JsonMap openBusSession(RestRequest req, RestResponse res) { 105 var bus = serverBus(); 106 var hreq = req.getHttpServletRequest(); 107 var boundary = bus.policy().boundary(); 108 if (boundary != null) { 109 var r = boundary.check(hreq); 110 if (! r.isAllowed()) { 111 res.setStatus(r.status()); 112 return JsonMap.of("code", "bus:refused", "message", r.message()); 113 } 114 } 115 else if (bus.policy().sameOriginCheck() && ! sameOrigin(hreq)) { 116 res.setStatus(403); 117 return JsonMap.of("code", "bus:refused", "message", "Cross-origin request refused."); 118 } 119 try { 120 var session = bus.openSession(hreq, sessionBody(req)); 121 return bus.grant(session, servletBase(req) + BUS_PREFIX, req.getContextPath()); 122 } catch (BusRefusal e) { 123 res.setStatus(e.status()); 124 e.retryAfterSeconds().ifPresent(x -> res.setHeader("Retry-After", String.valueOf(x))); 125 return e.toJson(); 126 } 127 } 128 129 /** 130 * The default check applied when the policy has no boundary: a request with an {@code Origin} header passes only 131 * when that origin's authority equals the request's {@code Host}. A request with no {@code Origin} passes. 132 * 133 * @param req The servlet request. 134 * @return <jk>true</jk> if the request is allowed. 135 */ 136 private static boolean sameOrigin(HttpServletRequest req) { 137 var origin = req.getHeader("Origin"); 138 if (origin == null) 139 return true; 140 var host = req.getHeader("Host"); 141 var i = origin.indexOf("://"); 142 return host != null && i > 0 && origin.substring(i + 3).equalsIgnoreCase(host); 143 } 144 145 /** 146 * [GET /juneau-bus/stream/{sessionId}] — streams the session's frames as Server-Sent Events. 147 * 148 * <p> 149 * Sends the resync, then live frames, until the client goes away or the bus closes the connection (bus closed, 150 * session expired, replaced by another connection, or too slow). Each frame is one {@code event: bus} with the 151 * frame as {@code data} and its {@code seq}, when it has one, as {@code id}. 152 * 153 * <p> 154 * The stream URL contains the session capability, so an application must not log request URIs for 155 * {@code /juneau-bus/stream/*}. Juneau's own debug pipeline logs the request path of every completed call when the 156 * resolved logger is loggable at {@code INFO} or finer, and {@code RestSession} logs it at {@code FINE} when a 157 * client disconnects; keep those loggers coarser than {@code INFO} for resources that serve the bus. 158 * 159 * @param id The session's capability id. 160 * @param req The REST request. 161 * @param res The REST response. 162 * @throws IOException If the stream could not be written. 163 */ 164 @SuppressWarnings({ 165 "resource" // False positive: serverBus() returns the shared AutoCloseable bus (not owned here) and the fluent sse.sendEvent/flush calls return the same 'sse' already managed by the try-with-resources. 166 }) 167 @RestGet(path=STREAM_PATH, summary="Message-bus SSE stream", swagger=@OpSwagger(ignore=true)) 168 default void streamBus(@Path("sessionId") String id, RestRequest req, RestResponse res) throws IOException { 169 var bus = serverBus(); 170 var hreq = req.getHttpServletRequest(); 171 var boundary = bus.policy().boundary(); 172 if (boundary != null) { 173 var r = boundary.check(hreq); 174 if (! r.isAllowed()) { 175 res.setStatus(r.status()); 176 return; 177 } 178 } 179 else if (bus.policy().sameOriginCheck() && ! sameOrigin(hreq)) { 180 res.setStatus(403); 181 return; 182 } 183 var session = bus.session(id, hreq.getUserPrincipal()).orElse(null); 184 if (session == null) { 185 res.setStatus(404); 186 return; 187 } 188 var wait = bus.policy().heartbeat(); 189 var sink = new SseFrameSink(bus.subscribeSse(session), bus.policy().maxQueuedFrames()); 190 try (var sse = res.sse()) { 191 var writer = res.getNegotiatedWriter(); 192 bus.connect(session, sink); 193 BusStream.pump(sink, e -> sse.sendEvent(e).flush(), writer::checkError, wait); 194 } catch (InterruptedException e) { 195 Thread.currentThread().interrupt(); 196 } finally { 197 bus.disconnect(session, sink); 198 sink.release(); 199 } 200 } 201 202 /** Parses the POST body; anything but a JSON object, or a body over 64 KB, is a 400. */ 203 private static JsonMap sessionBody(RestRequest req) throws BusRefusal { 204 String text; 205 try { 206 text = BusStream.readCapped(req.getInputStream()); 207 } catch (IOException e) { 208 throw BusRefusal.badRequest("the session request could not be read"); 209 } 210 try { 211 return text.isBlank() ? null : JsonMap.ofString(text, JsonParser.DEFAULT); 212 } catch (RuntimeException e) { 213 throw BusRefusal.badRequest("the session request must be a JSON object"); 214 } 215 } 216 217 /** The root-relative servlet path (context plus servlet) without a trailing slash. */ 218 private static String servletBase(RestRequest req) { 219 return BusStream.trimBase(req.getUriContext().getRootRelativeServletPath()); 220 } 221}