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 static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.time.*;
022import java.util.*;
023import java.util.function.*;
024import java.util.regex.*;
025
026import org.apache.juneau.rest.server.filter.*;
027
028import jakarta.servlet.http.*;
029
030/**
031 * What a {@link ServerBus} will carry, in which direction, to whom.  Everything not allowed here is denied.
032 *
033 * <p>
034 * Downstream entries are topic patterns: a custom topic ({@code ns.name}), a keyed custom topic or key pattern
035 * ({@code ns.name:key}, {@code ns.name:*}), a job topic or pattern ({@code job:<id>}, {@code job:*}), or a card command
036 * topic ({@code cmd:<cardId>}).  Upstream entries are exact custom topics, each with its {@link UpstreamHandler}.
037 *
038 * <h2 class='section'>Example:</h2>
039 * <p class='bjava'>
040 *   BusPolicy <jv>p</jv> = BusPolicy.<jsm>create</jsm>()
041 *     .downstream(<js>"ops.jobs"</js>, <jk>true</jk>)                       <jc>// retained state</jc>
042 *     .downstream(<js>"ops.alert:*"</js>, <jk>false</jk>)                  <jc>// events, any key</jc>
043 *     .upstream(<js>"ops.cancel-all"</js>, (<jv>session</jv>, <jv>topic</jv>, <jv>payload</jv>) -&gt; <jv>jobs</jv>.cancelAll())
044 *     .authorizer((<jv>req</jv>, <jv>topic</jv>) -&gt; <jv>req</jv>.isUserInRole(<js>"ops"</js>))  <jc>// per-user, both directions; denied until set (or anyCaller())</jc>
045 *     .boundary(<jv>boundary</jv>)                                           <jc>// LoopbackBoundary or CsrfBoundary</jc>
046 *     .build();
047 *
048 *   <jc>// In a page test: every topic the page's bridges request is granted (E-55 otherwise).</jc>
049 *   <jv>p</jv>.check(PageCapture.<jsm>of</jsm>(<jv>html</jv>).contract());
050 * </p>
051 *
052 * @since 10.0.0
053 */
054public final class BusPolicy {
055
056   static final String CUSTOM = "[a-z][a-z0-9-]{0,31}\\.[a-z][a-z0-9-]{0,31}";
057   static final String KEY = "[A-Za-z0-9_.-]{1,128}";
058   static final String CARD_ID = "[A-Za-z][A-Za-z0-9_-]{0,63}";
059
060   /** Valid downstream topic patterns. */
061   static final Pattern DOWNSTREAM_PATTERN = Pattern.compile(
062      "^(" + CUSTOM + "(:(" + KEY + "|\\*))?|job:(" + KEY + "|\\*)|cmd:" + CARD_ID + ")$");
063
064   /** Valid upstream topics: exact custom topics only. */
065   static final Pattern UPSTREAM_TOPIC = Pattern.compile("^" + CUSTOM + "(:" + KEY + ")?$");
066
067   /** The C1 id pattern, used for bridge ids. */
068   static final Pattern BRIDGE_ID = Pattern.compile("^" + CARD_ID + "$");
069
070   private final Map<String,Boolean> downstream;
071   private final Map<String,UpstreamHandler> upstream;
072   private final BiPredicate<HttpServletRequest,String> authorizer;
073   private final RequestBoundary boundary;
074   private final List<String> allowedOrigins;
075   private final boolean sameOriginCheck;
076   private final Duration sessionGrace;
077   private final Duration maxSessionAge;
078   private final Duration heartbeat;
079   private final int maxSessions;
080   private final int maxQueuedFrames;
081   private final int maxFrameBytes;
082   private final int maxUpstreamPerSecond;
083   private final Function<HttpServletRequest,Map<String,Object>> sessionAttributes;
084
085   private BusPolicy(Builder b) {
086      downstream = Collections.unmodifiableMap(new LinkedHashMap<>(b.downstream));
087      upstream = Collections.unmodifiableMap(new LinkedHashMap<>(b.upstream));
088      authorizer = b.authorizer;
089      boundary = b.boundary;
090      allowedOrigins = b.allowedOrigins;
091      sameOriginCheck = b.sameOriginCheck;
092      sessionGrace = b.sessionGrace;
093      maxSessionAge = b.maxSessionAge;
094      heartbeat = b.heartbeat;
095      maxSessions = b.maxSessions;
096      maxQueuedFrames = b.maxQueuedFrames;
097      maxFrameBytes = b.maxFrameBytes;
098      maxUpstreamPerSecond = b.maxUpstreamPerSecond;
099      sessionAttributes = b.sessionAttributes;
100   }
101
102   /**
103    * Creates a new builder.  An unmodified builder builds a policy that grants nothing.
104    *
105    * @return A new builder.
106    */
107   public static Builder create() {
108      return new Builder();
109   }
110
111   /**
112    * Returns whether a topic (or a requested pattern) may flow downstream, and if so whether it is retained.
113    *
114    * <p>
115    * A policy entry covers a topic when it is equal to it, or when the entry is {@code family:*} and the topic is
116    * {@code family:<anything>}.
117    *
118    * @param topic A concrete topic or a requested pattern.  Can be <jk>null</jk>.
119    * @return The retain flag, or empty when the topic is denied.
120    */
121   public Optional<Boolean> downstreamRetain(String topic) {
122      if (topic == null || ! DOWNSTREAM_PATTERN.matcher(topic).matches())
123         return Optional.empty();
124      var exact = downstream.get(topic);
125      if (exact != null)
126         return Optional.of(exact);
127      var i = topic.indexOf(':');
128      if (i > 0) {
129         var wild = downstream.get(topic.substring(0, i) + ":*");
130         if (wild != null)
131            return Optional.of(wild);
132      }
133      return Optional.empty();
134   }
135
136   /**
137    * Returns whether a topic may flow upstream (exact match only).
138    *
139    * @param topic The topic.  Can be <jk>null</jk>.
140    * @return <jk>true</jk> if the policy has a handler for it.
141    */
142   public boolean allowsUpstream(String topic) {
143      return topic != null && upstream.containsKey(topic);
144   }
145
146   UpstreamHandler upstreamHandler(String topic) {
147      return upstream.get(topic);
148   }
149
150   /**
151    * Checks that this policy grants every topic that a page contract's {@code bridges} request (E-55).
152    *
153    * <p>
154    * Adopter page tests call this next to {@code PageContractAssert.hasNoWiringErrors()}.  The request-dependent
155    * {@link #authorizer()} is not consulted: it can only narrow a grant at session time.
156    *
157    * @param contract The page contract (for example {@code PageCapture.of(html).contract()}).
158    * @throws IllegalStateException Listing every denied topic, one {@code E-55} line each.
159    */
160   @SuppressWarnings({
161      "java:S3776" // Walking the bridge contract is inherently nested.
162   })
163   public void check(Map<String,?> contract) {
164      var problems = new ArrayList<String>();
165      if (contract != null && contract.get("bridges") instanceof Collection<?> bridges) {
166         for (var raw : bridges) {
167            if (! (raw instanceof Map<?,?> bridge))
168               continue;
169            var id = String.valueOf(bridge.get("id"));
170            for (var t : strings(bridge.get("downstream")))
171               if (downstreamRetain(t).isEmpty())
172                  problems.add(e55("downstream", t, id));
173            for (var t : strings(bridge.get("upstream")))
174               if (! allowsUpstream(t))
175                  problems.add(e55("upstream", t, id));
176         }
177      }
178      if (! problems.isEmpty())
179         throw new IllegalStateException(String.join("\n", problems));
180   }
181
182   private static String e55(String direction, String topic, String bridge) {
183      return "E-55: " + f("BusPolicy denies %s topic '%s' that bridge '%s' requests", direction, topic, bridge);
184   }
185
186   private static List<String> strings(Object o) {
187      return o instanceof Collection<?> c ? c.stream().map(String::valueOf).toList() : List.of();
188   }
189
190   /** @return The per-request, per-topic authorizer applied at session open.  Defaults to deny-all until {@link Builder#authorizer(BiPredicate)} or {@link Builder#anyCaller()} is called. */
191   public BiPredicate<HttpServletRequest,String> authorizer() { return authorizer; }
192
193   /** @return The request boundary, or <jk>null</jk> when the application has its own guard. */
194   public RequestBoundary boundary() { return boundary; }
195
196   /**
197    * Whether the session POST and SSE stream refuse a request whose {@code Origin} does not match its {@code Host}
198    * when no {@link #boundary()} is set.  Default <jk>true</jk>.
199    *
200    * @return <jk>true</jk> if the default same-origin check applies.
201    */
202   public boolean sameOriginCheck() { return sameOriginCheck; }
203
204   /** @return The exact origins allowed on a WebSocket handshake when no {@link #boundary()} is set. */
205   public List<String> allowedOrigins() { return allowedOrigins; }
206
207   /** @return How long a session survives after its last connection closes.  Default 60 s. */
208   public Duration sessionGrace() { return sessionGrace; }
209
210   /** @return The absolute session lifetime.  Default 12 h. */
211   public Duration maxSessionAge() { return maxSessionAge; }
212
213   /** @return The idle interval after which a {@code ping} frame is sent.  Default 15 s. */
214   public Duration heartbeat() { return heartbeat; }
215
216   /** @return The maximum number of live sessions.  Default 256. */
217   public int maxSessions() { return maxSessions; }
218
219   /** @return The per-connection outbound queue bound.  Default 1024. */
220   public int maxQueuedFrames() { return maxQueuedFrames; }
221
222   /** @return The maximum encoded frame size in UTF-8 bytes, both directions.  Default 65536. */
223   public int maxFrameBytes() { return maxFrameBytes; }
224
225   /** @return The per-session upstream frame rate limit.  Default 20. */
226   public int maxUpstreamPerSecond() { return maxUpstreamPerSecond; }
227
228   /** @return The function that captures session attributes at session open.  Defaults to an empty map. */
229   public Function<HttpServletRequest,Map<String,Object>> sessionAttributes() { return sessionAttributes; }
230
231   /**
232    * Builder for {@link BusPolicy}.
233    *
234    * <h2 class='section'>Example:</h2>
235    * <p class='bjava'>
236    *   BusPolicy <jv>p</jv> = BusPolicy.<jsm>create</jsm>()
237    *     .downstream(<js>"ops.jobs"</js>, <jk>true</jk>)
238    *     .sessionAttributes(<jv>req</jv> -&gt; Map.<jsm>of</jsm>(<js>"region"</js>, <jv>req</jv>.getHeader(<js>"X-Region"</js>)))
239    *     .maxSessions(64)
240    *     .build();
241    * </p>
242    */
243   public static final class Builder {
244
245      final Map<String,Boolean> downstream = new LinkedHashMap<>();
246      final Map<String,UpstreamHandler> upstream = new LinkedHashMap<>();
247      BiPredicate<HttpServletRequest,String> authorizer = (req, topic) -> false;
248      RequestBoundary boundary;
249      List<String> allowedOrigins = List.of();
250      boolean sameOriginCheck = true;
251      Duration sessionGrace = Duration.ofSeconds(60);
252      Duration maxSessionAge = Duration.ofHours(12);
253      Duration heartbeat = Duration.ofSeconds(15);
254      int maxSessions = 256;
255      int maxQueuedFrames = 1024;
256      int maxFrameBytes = 65536;
257      int maxUpstreamPerSecond = 20;
258      Function<HttpServletRequest,Map<String,Object>> sessionAttributes = req -> Map.of();
259
260      Builder() {}
261
262      /**
263       * Allows a topic pattern downstream (server → page).
264       *
265       * @param topicPattern {@code ns.name}, {@code ns.name:key}, {@code ns.name:*}, {@code job:<id>}, {@code job:*} or {@code cmd:<cardId>}.
266       * @param retain Whether values are retained and resent on every (re)connect.
267       * @return This object.
268       * @throws IllegalArgumentException E-57 on an invalid or repeated pattern.
269       */
270      public Builder downstream(String topicPattern, boolean retain) {
271         if (topicPattern == null || ! DOWNSTREAM_PATTERN.matcher(topicPattern).matches())
272            throw e57("BusPolicy: '%s' is not a valid topic pattern", topicPattern);
273         if (downstream.putIfAbsent(topicPattern, retain) != null)
274            throw e57("BusPolicy: '%s' is declared twice", topicPattern);
275         return this;
276      }
277
278      /**
279       * Allows an exact custom topic upstream (page → server, WebSocket only) and names its handler.
280       *
281       * @param topic The topic ({@code ns.name} or {@code ns.name:key}).
282       * @param handler The handler.  Must not be <jk>null</jk>.
283       * @return This object.
284       * @throws IllegalArgumentException E-57 on an invalid or repeated topic, or a <jk>null</jk> handler.
285       */
286      public Builder upstream(String topic, UpstreamHandler handler) {
287         if (topic == null || ! UPSTREAM_TOPIC.matcher(topic).matches())
288            throw e57("BusPolicy: '%s' is not a valid topic pattern", topic);
289         if (handler == null)
290            throw e57("BusPolicy: upstream topic '%s' has no handler", topic);
291         if (upstream.putIfAbsent(topic, handler) != null)
292            throw e57("BusPolicy: '%s' is declared twice", topic);
293         return this;
294      }
295
296      /**
297       * Sets a per-request, per-topic authorizer, consulted for every requested topic at session open.
298       *
299       * @param value The authorizer.  Must not be <jk>null</jk>.
300       * @return This object.
301       */
302      public Builder authorizer(BiPredicate<HttpServletRequest,String> value) {
303         authorizer = Objects.requireNonNull(value, "authorizer");
304         return this;
305      }
306
307      /**
308       * Grants every declared topic to any caller that can reach the bus endpoints.
309       *
310       * <p>
311       * Without this or {@link #authorizer(BiPredicate)}, no topic is granted.  Use it only when the endpoints are
312       * already protected by the application (a filter, a boundary, or a private network).
313       *
314       * @return This object.
315       */
316      public Builder anyCaller() {
317         authorizer = (req, topic) -> true;
318         return this;
319      }
320
321      /**
322       * Sets the request boundary.  The session POST and SSE stream apply its {@code check}.
323       *
324       * <p>
325       * The WebSocket handshake cannot run {@code check}, so it applies the boundary's own handshake rules: a
326       * {@link LoopbackBoundary}'s exact {@code origin()} and {@code authority()}, or a {@link CsrfBoundary}'s
327       * {@code Origin} match against the handshake's own {@code Host} and scheme.  {@code BusWebSockets.register}
328       * refuses any other boundary type.
329       *
330       * @param value The boundary.  Can be <jk>null</jk>.
331       * @return This object.
332       */
333      public Builder boundary(RequestBoundary value) {
334         boundary = value;
335         return this;
336      }
337
338      /**
339       * Turns off the default same-origin check applied when no boundary is set.
340       *
341       * <p>
342       * With no {@link #boundary(RequestBoundary)}, the session POST and SSE stream refuse a request that carries an
343       * {@code Origin} header whose authority differs from its {@code Host} header; a request with no {@code Origin}
344       * passes.  Call this only when the application guards the endpoints itself, for example when they are served
345       * to pages on another origin behind its own CORS and authentication rules.
346       *
347       * @return This object.
348       */
349      public Builder noSameOriginCheck() {
350         sameOriginCheck = false;
351         return this;
352      }
353
354      /**
355       * Sets the exact origins a WebSocket handshake may carry when no boundary is set.  Ignored when a boundary is set.
356       *
357       * @param values Origins such as {@code https://console.example.org}.  None may be blank.
358       * @return This object.
359       */
360      public Builder allowedOrigins(String...values) {
361         for (var v : Objects.requireNonNull(values, "allowedOrigins"))
362            if (ib(v))
363               throw new IllegalArgumentException("BusPolicy: allowedOrigins entries must not be blank");
364         allowedOrigins = List.of(values);
365         return this;
366      }
367
368      /** @param value Grace after the last connection closes.  Default 60 s. @return This object. */
369      public Builder sessionGrace(Duration value) { sessionGrace = positive("sessionGrace", value); return this; }
370
371      /** @param value Absolute session lifetime.  Default 12 h. @return This object. */
372      public Builder maxSessionAge(Duration value) { maxSessionAge = positive("maxSessionAge", value); return this; }
373
374      /** @param value Idle interval before a {@code ping} frame.  Default 15 s. @return This object. */
375      public Builder heartbeat(Duration value) { heartbeat = positive("heartbeat", value); return this; }
376
377      /** @param value Maximum live sessions.  Default 256. @return This object. */
378      public Builder maxSessions(int value) { maxSessions = positive("maxSessions", value); return this; }
379
380      /** @param value Per-connection outbound queue bound.  Default 1024. @return This object. */
381      public Builder maxQueuedFrames(int value) { maxQueuedFrames = positive("maxQueuedFrames", value); return this; }
382
383      /** @param value Maximum encoded frame size, UTF-8 bytes.  Default 65536. @return This object. */
384      public Builder maxFrameBytes(int value) { maxFrameBytes = positive("maxFrameBytes", value); return this; }
385
386      /** @param value Per-session upstream frames per second.  Default 20. @return This object. */
387      public Builder maxUpstreamPerSecond(int value) { maxUpstreamPerSecond = positive("maxUpstreamPerSecond", value); return this; }
388
389      /**
390       * Sets the function that captures attributes onto each {@link BusSession} at session open.
391       *
392       * @param value The function.  Must not be <jk>null</jk>; it may return <jk>null</jk> for "none".
393       * @return This object.
394       */
395      public Builder sessionAttributes(Function<HttpServletRequest,Map<String,Object>> value) {
396         sessionAttributes = Objects.requireNonNull(value, "sessionAttributes");
397         return this;
398      }
399
400      /**
401       * Builds the policy.
402       *
403       * @return A new immutable policy.
404       */
405      public BusPolicy build() {
406         return new BusPolicy(this);
407      }
408
409      private static Duration positive(String name, Duration v) {
410         if (v == null || v.isZero() || v.isNegative())
411            throw new IllegalArgumentException(f("BusPolicy: %s must be positive", name));
412         return v;
413      }
414
415      private static int positive(String name, int v) {
416         if (v <= 0)
417            throw new IllegalArgumentException(f("BusPolicy: %s must be positive", name));
418         return v;
419      }
420
421      private static IllegalArgumentException e57(String format, Object...args) {
422         return new IllegalArgumentException("E-57: " + f(format, args));
423      }
424   }
425}