View Javadoc
1   /*
2    * Copyright (C) 2022 B3Partners B.V.
3    *
4    * SPDX-License-Identifier: MIT
5    */
6   package org.tailormap.api.controller;
7   
8   import static org.springframework.http.HttpHeaders.ACCEPT;
9   import static org.springframework.http.HttpHeaders.CACHE_CONTROL;
10  import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION;
11  import static org.springframework.http.HttpHeaders.CONTENT_LENGTH;
12  import static org.springframework.http.HttpHeaders.CONTENT_RANGE;
13  import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
14  import static org.springframework.http.HttpHeaders.ETAG;
15  import static org.springframework.http.HttpHeaders.EXPIRES;
16  import static org.springframework.http.HttpHeaders.IF_MATCH;
17  import static org.springframework.http.HttpHeaders.IF_MODIFIED_SINCE;
18  import static org.springframework.http.HttpHeaders.IF_NONE_MATCH;
19  import static org.springframework.http.HttpHeaders.IF_RANGE;
20  import static org.springframework.http.HttpHeaders.IF_UNMODIFIED_SINCE;
21  import static org.springframework.http.HttpHeaders.LAST_MODIFIED;
22  import static org.springframework.http.HttpHeaders.PRAGMA;
23  import static org.springframework.http.HttpHeaders.RANGE;
24  import static org.springframework.http.HttpHeaders.REFERER;
25  import static org.springframework.http.HttpHeaders.USER_AGENT;
26  import static org.springframework.web.bind.annotation.RequestMethod.GET;
27  import static org.springframework.web.bind.annotation.RequestMethod.POST;
28  import static org.tailormap.api.persistence.helper.GeoServiceHelper.getWmsRequest;
29  import static org.tailormap.api.util.HttpProxyUtil.addForwardedForRequestHeaders;
30  import static org.tailormap.api.util.HttpProxyUtil.configureProxyRequestBuilderForUri;
31  import static org.tailormap.api.util.HttpProxyUtil.passthroughRequestHeaders;
32  import static org.tailormap.api.util.HttpProxyUtil.passthroughResponseHeaders;
33  import static org.tailormap.api.util.HttpProxyUtil.setHttpBasicAuthenticationHeader;
34  
35  import io.micrometer.core.annotation.Timed;
36  import jakarta.servlet.http.HttpServletRequest;
37  import java.io.IOException;
38  import java.io.InputStream;
39  import java.lang.invoke.MethodHandles;
40  import java.net.URI;
41  import java.net.URISyntaxException;
42  import java.net.http.HttpClient;
43  import java.net.http.HttpRequest;
44  import java.net.http.HttpResponse;
45  import java.net.http.HttpTimeoutException;
46  import java.nio.charset.StandardCharsets;
47  import java.time.Duration;
48  import java.util.AbstractMap;
49  import java.util.Arrays;
50  import java.util.List;
51  import java.util.Locale;
52  import java.util.Map;
53  import java.util.Objects;
54  import java.util.Set;
55  import java.util.regex.Pattern;
56  import java.util.stream.Collectors;
57  import org.apache.commons.lang3.StringUtils;
58  import org.apache.hc.core5.http.HeaderElement;
59  import org.apache.hc.core5.http.message.BasicHeaderValueParser;
60  import org.apache.hc.core5.http.message.ParserCursor;
61  import org.geotools.filter.text.cql2.CQLException;
62  import org.jspecify.annotations.Nullable;
63  import org.slf4j.Logger;
64  import org.slf4j.LoggerFactory;
65  import org.springframework.beans.factory.annotation.Value;
66  import org.springframework.core.io.InputStreamResource;
67  import org.springframework.http.HttpHeaders;
68  import org.springframework.http.HttpStatus;
69  import org.springframework.http.MediaType;
70  import org.springframework.http.ResponseEntity;
71  import org.springframework.security.authentication.AnonymousAuthenticationToken;
72  import org.springframework.security.core.Authentication;
73  import org.springframework.security.core.context.SecurityContextHolder;
74  import org.springframework.transaction.PlatformTransactionManager;
75  import org.springframework.transaction.support.TransactionTemplate;
76  import org.springframework.util.LinkedMultiValueMap;
77  import org.springframework.util.MultiValueMap;
78  import org.springframework.validation.annotation.Validated;
79  import org.springframework.web.bind.annotation.ModelAttribute;
80  import org.springframework.web.bind.annotation.PathVariable;
81  import org.springframework.web.bind.annotation.RequestMapping;
82  import org.springframework.web.context.request.ServletWebRequest;
83  import org.springframework.web.server.ResponseStatusException;
84  import org.springframework.web.util.UriComponentsBuilder;
85  import org.springframework.web.util.UriUtils;
86  import org.tailormap.api.annotation.AppRestController;
87  import org.tailormap.api.geotools.FilterUtil;
88  import org.tailormap.api.persistence.Application;
89  import org.tailormap.api.persistence.GeoService;
90  import org.tailormap.api.persistence.TMFeatureType;
91  import org.tailormap.api.persistence.helper.GeoServiceHelper;
92  import org.tailormap.api.persistence.json.AppLayerSettings;
93  import org.tailormap.api.persistence.json.AppTreeLayerNode;
94  import org.tailormap.api.persistence.json.GeoServiceLayer;
95  import org.tailormap.api.persistence.json.GeoServiceLayerSettings;
96  import org.tailormap.api.persistence.json.GeoServiceProtocol;
97  import org.tailormap.api.persistence.json.ServiceAuthentication;
98  import org.tailormap.api.repository.FeatureSourceRepository;
99  import org.tailormap.api.security.AuthorisationService;
100 import org.tailormap.api.viewer.model.Service.ServerTypeEnum;
101 
102 /**
103  * Proxy controller for OGC WMS, WMTS, and 3D Tiles services. Does not attempt to hide the original service URL. Mostly
104  * useful for access to HTTP Basic secured services without sending the credentials to the client. The access control is
105  * handled by Spring Security and the authorizations configured on the service.
106  *
107  * <p>Only supports GET requests. Does not support CORS, only meant for tailormap-viewer from the same origin.
108  *
109  * <p>Implementation note: uses the Java 11 HttpClient. Spring cloud gateway can proxy with many more features but
110  * cannot be used in a non-reactive application.
111  */
112 @AppRestController
113 @Validated
114 // Can't use ${tailormap-api.base-path} because linkTo() won't work
115 @RequestMapping(path = "/api/{viewerKind}/{viewerName}/layer/{appLayerId}/proxy")
116 public class GeoServiceProxyController {
117   private static final Logger logger =
118       LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
119   private final AuthorisationService authorisationService;
120   private final FeatureSourceRepository featureSourceRepository;
121   private final TransactionTemplate transactionTemplate;
122   private final HttpClient httpClient;
123   private final Duration requestTimeout;
124 
125   private static final String CROSS_ORIGIN_RESOURCE_POLICY = "Cross-Origin-Resource-Policy";
126   private static final String CONTENT_SECURITY_POLICY = "Content-Security-Policy";
127 
128   private static final Set<String> REMOVED_CACHE_CONTROL_DIRECTIVES = Set.of("public", "private", "s-maxage");
129 
130   public static final String TILES3D_DESCRIPTION_PATH = "tiles3dDescription";
131 
132   @Value("${tailormap-api.proxy.passthrough.layerpatterns:}")
133   private Set<String> proxyLayerPassthroughPatterns = Set.of();
134 
135   @Value("${tailormap-api.proxy.passthrough.hostnames:}")
136   private Set<String> proxyPassthroughHostNames = Set.of();
137 
138   /** Parameters (case-insensitive) which name the layer(s) to request from a WMS or WMTS. */
139   private static final List<String> LAYER_PARAMS = List.of("LAYERS", "QUERY_LAYERS", "LAYER");
140 
141   /**
142    * Parameters (case-insensitive) which are not allowed. An SLD (or a GeoServer style in another format) can name any
143    * layer of a WMS, and an OGC filter can use functions which query other layers (such as GeoServer's querySingle()).
144    * These would bypass the layer name checks, and the proxied service checks the access rights of the credentials of
145    * the service, not those of the Tailormap user. The viewer doesn't use these parameters.
146    */
147   private static final List<String> FORBIDDEN_PARAMS =
148       List.of("SLD", "SLD_BODY", "SLD_URL", "STYLE_BODY", "STYLE_URL", "FILTER");
149 
150   /** Allowed WMS operations (lowercase) and the layer parameters each requires. */
151   private static final Map<String, Set<String>> WMS_REQUEST_LAYER_PARAMS = Map.of(
152       "getcapabilities", Set.of(),
153       "getmap", Set.of("LAYERS"),
154       "getfeatureinfo", Set.of("LAYERS", "QUERY_LAYERS"),
155       "getlegendgraphic", Set.of("LAYER"));
156 
157   /** Allowed WMTS (KVP) operations (lowercase) and the layer parameters each requires. */
158   private static final Map<String, Set<String>> WMTS_REQUEST_LAYER_PARAMS = Map.of(
159       "getcapabilities", Set.of(),
160       "gettile", Set.of("LAYER"),
161       "getfeatureinfo", Set.of("LAYER"));
162 
163   /** Parameters a request to the legend proxy may not set, so the legend is always for the app layer. */
164   private static final List<String> LEGEND_FORBIDDEN_PARAMS =
165       List.of("LAYER", "LAYERS", "QUERY_LAYERS", "SLD", "SLD_BODY", "SLD_URL");
166 
167   /**
168    * Parameters (uppercase) from a request to the legend proxy which are copied to the legend URL: the parameters the
169    * viewer adds to enhance the legend image. Other parameters are ignored, so a request can't change parameters of
170    * the legend URL such as MapServer's MAP parameter to access other layers with the credentials of the service.
171    */
172   private static final Set<String> LEGEND_ALLOWED_PARAMS =
173       Set.of("STYLE", "SCALE", "LANGUAGE", "LEGEND_OPTIONS", "MAP_RESOLUTION");
174 
175   public GeoServiceProxyController(
176       AuthorisationService authorisationService,
177       FeatureSourceRepository featureSourceRepository,
178       PlatformTransactionManager transactionManager,
179       @Value("${tailormap-api.proxy.connect-timeout:10s}") Duration connectTimeout,
180       @Value("${tailormap-api.proxy.request-timeout:60s}") Duration requestTimeout) {
181     this.authorisationService = authorisationService;
182     this.featureSourceRepository = featureSourceRepository;
183     this.transactionTemplate = new TransactionTemplate(transactionManager);
184     this.transactionTemplate.setReadOnly(true);
185     this.requestTimeout = requestTimeout;
186 
187     final HttpClient.Builder builder = HttpClient.newBuilder()
188         .followRedirects(HttpClient.Redirect.NORMAL)
189         .connectTimeout(connectTimeout);
190     this.httpClient = builder.build();
191   }
192 
193   @RequestMapping(
194       method = {GET, POST},
195       path = "/tiles3d/**")
196   public ResponseEntity<?> proxy3dtiles(
197       @ModelAttribute Application application,
198       @ModelAttribute AppTreeLayerNode appTreeLayerNode,
199       @ModelAttribute GeoService service,
200       @ModelAttribute GeoServiceLayer layer,
201       HttpServletRequest request) {
202 
203     checkRequestValidity(application, appTreeLayerNode, service, layer, GeoServiceProtocol.TILES3D, request);
204 
205     final URI uri;
206     try {
207       uri = build3DTilesUrl(service, request);
208     } catch (IllegalArgumentException e) {
209       throw invalidServiceUrl(service, layer, e);
210     }
211     return doProxy(uri, service, request);
212   }
213 
214   @RequestMapping(
215       method = {GET, POST},
216       path = "/{protocol}")
217   @Timed(value = "proxy", description = "Proxy OGC service calls")
218   public ResponseEntity<?> proxy(
219       @ModelAttribute Application application,
220       @ModelAttribute AppTreeLayerNode appTreeLayerNode,
221       @ModelAttribute GeoService service,
222       @ModelAttribute GeoServiceLayer layer,
223       @PathVariable("protocol") GeoServiceProtocol protocol,
224       HttpServletRequest request) {
225 
226     checkRequestValidity(application, appTreeLayerNode, service, layer, protocol, request);
227 
228     return switch (protocol) {
229       case WMS, WMTS -> {
230         final URI uri;
231         try {
232           uri = buildWMSUrl(service, request);
233         } catch (IllegalArgumentException e) {
234           throw invalidServiceUrl(service, layer, e);
235         }
236         yield doProxy(uri, service, request);
237       }
238       case LEGEND -> {
239         final URI legendURI;
240         try {
241           legendURI = buildLegendURI(service, layer, request);
242         } catch (IllegalArgumentException e) {
243           throw invalidServiceUrl(service, layer, e);
244         }
245         if (legendURI == null) {
246           logger.debug("No legend URL found for layer {} of service {}", layer.getName(), service.getId());
247           throw new ResponseStatusException(
248               HttpStatus.NOT_FOUND, "No legend URL for layer \"%s\"".formatted(layer.getName()));
249         }
250         yield doProxy(legendURI, service, request);
251       }
252       case TILES3D ->
253         throw new ResponseStatusException(
254             HttpStatus.BAD_REQUEST, "Incorrect 3D Tiles proxy request: No path to capabilities or content");
255       default ->
256         throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported proxy protocol: " + protocol);
257     };
258   }
259 
260   private void checkRequestValidity(
261       Application application,
262       AppTreeLayerNode appTreeLayerNode,
263       GeoService service,
264       GeoServiceLayer layer,
265       GeoServiceProtocol protocol,
266       HttpServletRequest request) {
267     if (service == null || layer == null) {
268       throw new ResponseStatusException(HttpStatus.NOT_FOUND);
269     }
270 
271     if (GeoServiceProtocol.XYZ.equals(protocol)) {
272       throw new ResponseStatusException(HttpStatus.NOT_IMPLEMENTED, "XYZ proxying not implemented");
273     }
274 
275     if (!(service.getProtocol().equals(protocol) || GeoServiceProtocol.LEGEND.equals(protocol))) {
276       throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid proxy protocol: " + protocol);
277     }
278 
279     if (!service.getSettings().getUseProxy()) {
280       throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Proxy not enabled for requested service");
281     }
282 
283     if (GeoServiceProtocol.WMS.equals(protocol) || GeoServiceProtocol.WMTS.equals(protocol)) {
284       checkOgcRequestParams(service, layer, protocol, request.getParameterMap());
285     } else if (GeoServiceProtocol.LEGEND.equals(protocol)) {
286       checkLegendRequestParams(request.getParameterMap());
287     }
288 
289     if (authorisationService.mustDenyAccessForSecuredProxy(service)) {
290       logger.debug(
291           "Denying proxy for layer \"{}\" in app #{} (\"{}\") from secured service #{} (URL {}): user is not authenticated",
292           layer.getName(),
293           application.getId(),
294           application.getName(),
295           service.getId(),
296           service.getUrl());
297       throw new ResponseStatusException(HttpStatus.FORBIDDEN);
298     }
299 
300     if (GeoServiceProtocol.WMS.equals(protocol) || GeoServiceProtocol.WMTS.equals(protocol)) {
301       findFeatureTypeAndCheckRequestParams(
302           application, appTreeLayerNode, service, layer, request.getParameterMap());
303     }
304   }
305 
306   /**
307    * Looks up the feature type of the app layer for {@link #checkFeatureTypeRequestParams(TMFeatureType,
308    * AppLayerSettings, Map)}, only for requests that need it so not for every map image or tile. The lookup uses a
309    * short transaction, which is finished before proxying so no database connection is held while waiting for the
310    * proxied service (HTM-2418).
311    */
312   private void findFeatureTypeAndCheckRequestParams(
313       Application application,
314       AppTreeLayerNode appTreeLayerNode,
315       GeoService service,
316       GeoServiceLayer layer,
317       Map<String, String[]> params) {
318     if (!"getfeatureinfo".equalsIgnoreCase(getSingleParam(params, "REQUEST")) && !hasParam(params, "CQL_FILTER")) {
319       return;
320     }
321     final AppLayerSettings appLayerSettings = application.getAppLayerSettings(appTreeLayerNode);
322     transactionTemplate.executeWithoutResult(status -> checkFeatureTypeRequestParams(
323         service.findFeatureTypeForLayer(layer, featureSourceRepository), appLayerSettings, params));
324   }
325 
326   /**
327    * Checks the parameters of a WMS or WMTS request for an app layer with a feature type. Access to the attributes of
328    * the features is restricted by Tailormap (attributes can be hidden in the feature type or app layer settings), so
329    * for such a layer the viewer gets features through the Tailormap API and not with a GetFeatureInfo request to the
330    * proxied service, which would return all attributes. A GetFeatureInfo request is denied, whether or not attributes
331    * are hidden, so a response never needs to be filtered.
332    *
333    * <p>A CQL_FILTER (which is already checked to be a valid ECQL filter by {@link #checkOgcRequestParams}) may only
334    * use attributes available in the viewer, otherwise a filter could be used to find out the values of hidden
335    * attributes by whether features are drawn. Without a feature type Tailormap does not restrict attribute access,
336    * the viewer uses GetFeatureInfo which returns all attributes.
337    */
338   static void checkFeatureTypeRequestParams(
339       @Nullable TMFeatureType featureType, AppLayerSettings appLayerSettings, Map<String, String[]> params) {
340     if (featureType == null) {
341       return;
342     }
343     if ("getfeatureinfo".equalsIgnoreCase(getSingleParam(params, "REQUEST"))) {
344       throw new ResponseStatusException(
345           HttpStatus.BAD_REQUEST, "GetFeatureInfo not allowed for proxied layer with a feature type");
346     }
347     String filter = getSingleParam(params, "CQL_FILTER");
348     if (filter != null) {
349       try {
350         FilterUtil.parseFilter(filter, featureType, appLayerSettings);
351       } catch (CQLException e) {
352         throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "CQL_FILTER parameter is invalid");
353       }
354     }
355   }
356 
357   /**
358    * Checks the parameters of a WMS or WMTS request so that only the app layer (or a layer allowed by the passthrough
359    * configuration) can be requested from the proxied service. Only the operations needed by the viewer are allowed,
360    * and the parameters which name the layer(s) to request are required for operations which return layer content.
361    */
362   void checkOgcRequestParams(
363       GeoService service, GeoServiceLayer layer, GeoServiceProtocol protocol, Map<String, String[]> params) {
364     String serviceParam = getSingleParam(params, "SERVICE");
365     if (serviceParam != null && !protocol.getValue().equalsIgnoreCase(serviceParam)) {
366       throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid SERVICE parameter for proxy protocol");
367     }
368 
369     String requestParam = getSingleParam(params, "REQUEST");
370     Map<String, Set<String>> allowedRequests =
371         GeoServiceProtocol.WMS.equals(protocol) ? WMS_REQUEST_LAYER_PARAMS : WMTS_REQUEST_LAYER_PARAMS;
372     Set<String> requiredLayerParams =
373         requestParam == null ? null : allowedRequests.get(requestParam.toLowerCase(Locale.ROOT));
374     if (requiredLayerParams == null) {
375       throw new ResponseStatusException(
376           HttpStatus.BAD_REQUEST, "Missing or unsupported REQUEST parameter for proxy protocol");
377     }
378 
379     for (String requiredParam : requiredLayerParams) {
380       if (getSingleParam(params, requiredParam) == null) {
381         throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing " + requiredParam + " parameter");
382       }
383     }
384 
385     // Check all parameters naming layers, also when they are not required for the requested operation
386     for (String layerParam : LAYER_PARAMS) {
387       String value = getSingleParam(params, layerParam);
388       if (value == null) {
389         continue;
390       }
391       if (value.indexOf(',') >= 0) {
392         throw new ResponseStatusException(
393             HttpStatus.BAD_REQUEST, "Multiple layers in " + layerParam + " parameter not supported");
394       }
395       checkLayerName(service, layer, protocol, value);
396     }
397 
398     for (String forbiddenParam : FORBIDDEN_PARAMS) {
399       if (hasParam(params, forbiddenParam)) {
400         throw new ResponseStatusException(
401             HttpStatus.BAD_REQUEST, forbiddenParam + " parameter not allowed for proxied services");
402       }
403     }
404 
405     // The viewer only sends a CQL_FILTER to GeoServer. Other servers may support CQL_FILTER with other functions,
406     // so don't allow it for them.
407     if (hasParam(params, "CQL_FILTER")) {
408       if (service.getResolvedServerType() != ServerTypeEnum.GEOSERVER) {
409         throw new ResponseStatusException(
410             HttpStatus.BAD_REQUEST, "CQL_FILTER parameter only allowed for GeoServer");
411       }
412       try {
413         // Throws CQLException on invalid filter. GeoTools does not have the functions querySingle() and
414         // queryCollection() GeoServer has, so this will throw if those are used. More specific checks or
415         // allowlist for functions not needed.
416         // We don't want to allow these functions as they may allow access to other feature types that the
417         // service account Tailormap uses has access to, but the Tailormap user may not.
418         String filter = getSingleParam(params, "CQL_FILTER");
419         FilterUtil.parseFilter(filter);
420       } catch (CQLException e) {
421         throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "CQL_FILTER parameter is invalid");
422       }
423     }
424   }
425 
426   /**
427    * The legend proxy uses the legend URL from the capabilities for the app layer. The request may add parameters to
428    * enhance the legend image, but may not change which layer the legend is for.
429    */
430   static void checkLegendRequestParams(Map<String, String[]> params) {
431     for (String param : LEGEND_FORBIDDEN_PARAMS) {
432       if (hasParam(params, param)) {
433         throw new ResponseStatusException(
434             HttpStatus.BAD_REQUEST, param + " parameter not allowed for proxied legend");
435       }
436     }
437   }
438 
439   private void checkLayerName(
440       GeoService service, GeoServiceLayer layer, GeoServiceProtocol protocol, String layerNameParamValue) {
441     if (layer.getName().equals(layerNameParamValue)) {
442       return;
443     }
444 
445     // On hi-DPI screens the viewer requests the configured substitute layer instead of the WMTS layer. WMS layers
446     // don't have a substitute layer, so only allow it for WMTS.
447     if (GeoServiceProtocol.WMTS.equals(protocol)) {
448       GeoServiceLayerSettings layerSettings = service.getLayerSettings(layer.getName());
449       if (layerSettings != null && layerNameParamValue.equals(layerSettings.getHiDpiSubstituteLayer())) {
450         return;
451       }
452     }
453 
454     // check if layer matches any passthrough pattern, if not throw bad request
455     if (proxyLayerPassthroughPatterns.stream().noneMatch(pattern -> {
456       return Pattern.compile(pattern.formatted(Pattern.quote(layer.getName())))
457           .matcher(layerNameParamValue)
458           .matches();
459     })) {
460       throw new ResponseStatusException(
461           HttpStatus.BAD_REQUEST, "Requested layer name does not match expected layer");
462     }
463 
464     if (!proxyPassthroughHostNames.isEmpty()) {
465       // check if host matches any passthrough hostname, if not throw bad request
466       try {
467         String geoServiceHostName = new URI(service.getUrl()).getHost();
468         if (proxyPassthroughHostNames.stream()
469             .noneMatch(hostname -> hostname.equalsIgnoreCase(geoServiceHostName))) {
470           throw new ResponseStatusException(
471               HttpStatus.BAD_REQUEST,
472               "Requested service hostname does not match allowed hostnames for layer passthrough");
473         }
474       } catch (URISyntaxException e) {
475         logger.error(
476             "Invalid service URL \"{}\" for layer id {}: {}",
477             service.getUrl(),
478             layer.getId(),
479             e.getMessage());
480         throw new ResponseStatusException(
481             HttpStatus.INTERNAL_SERVER_ERROR, "Invalid service URL in configuration");
482       }
483     }
484   }
485 
486   private static boolean hasParam(Map<String, String[]> params, String name) {
487     return params.keySet().stream().anyMatch(name::equalsIgnoreCase);
488   }
489 
490   /**
491    * Returns the value of a parameter (case-insensitive name), or null if not present. Multiple parameters with the
492    * same name (in any case) or multiple values are rejected, because the proxied service may use another one than the
493    * value checked here.
494    */
495   private static @Nullable String getSingleParam(Map<String, String[]> params, String name) {
496     List<String> values = params.entrySet().stream()
497         .filter(entry -> name.equalsIgnoreCase(entry.getKey()))
498         .flatMap(entry -> Arrays.stream(entry.getValue()))
499         .toList();
500     if (values.size() > 1) {
501       throw new ResponseStatusException(
502           HttpStatus.BAD_REQUEST,
503           LAYER_PARAMS.contains(name)
504               ? "Multiple layers in " + name + " parameter not supported"
505               : "Multiple " + name + " parameters not supported");
506     }
507     return values.isEmpty() ? null : values.getFirst();
508   }
509 
510   /**
511    * Log and create an exception for a (legend) URL from the service configuration or capabilities that cannot be
512    * parsed or built, for instance because it contains unencoded characters. Without this a bare server error without
513    * a message would be returned.
514    */
515   private static ResponseStatusException invalidServiceUrl(
516       GeoService service, GeoServiceLayer layer, IllegalArgumentException e) {
517     logger.error(
518         "Invalid URL for proxying layer \"{}\" of service {}: {}",
519         layer.getName(),
520         service.getId(),
521         e.getMessage());
522     return new ResponseStatusException(
523         HttpStatus.INTERNAL_SERVER_ERROR,
524         "Invalid URL for proxying layer \"%s\" of service %s: %s"
525             .formatted(layer.getName(), service.getId(), e.getMessage()),
526         e);
527   }
528 
529   private @Nullable URI buildLegendURI(GeoService service, GeoServiceLayer layer, HttpServletRequest request) {
530     URI legendURI = GeoServiceHelper.getLayerLegendUrlFromStyles(service, layer);
531     if (legendURI == null) {
532       return null;
533     }
534 
535     // If the original service legend URL is not a GetLegendGraphic request, do not add any parameters from the
536     // incoming request and proxy the request as is
537     String wmsRequest = getWmsRequest(legendURI);
538     if (!"getlegendgraphic".equalsIgnoreCase(wmsRequest)) {
539       return legendURI;
540     }
541 
542     return addLegendRequestParams(legendURI, request.getParameterMap());
543   }
544 
545   /**
546    * Adds the allowed parameters ({@link #LEGEND_ALLOWED_PARAMS}) from the incoming request to a GetLegendGraphic URL,
547    * for the style and scale of the legend and vendor-specific parameters to enhance the legend image. Other
548    * parameters are ignored. Parameters which would change the layer of the legend are rejected earlier by
549    * {@link #checkLegendRequestParams(Map)}.
550    */
551   static URI addLegendRequestParams(URI legendURI, @Nullable Map<String, String[]> requestParams) {
552     UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(legendURI);
553     MultiValueMap<String, String> legendParams =
554         new LinkedMultiValueMap<>(uriComponentsBuilder.build(true).getQueryParams());
555     if (requestParams != null) {
556       requestParams.forEach((key, values) -> {
557         if (values.length == 0 || !LEGEND_ALLOWED_PARAMS.contains(key.toUpperCase(Locale.ROOT))) {
558           return;
559         }
560         // Replace the parameter case-insensitively, so it is not sent twice with different values
561         String encodedKey = UriUtils.encode(key, StandardCharsets.UTF_8);
562         legendParams.keySet().removeIf(encodedKey::equalsIgnoreCase);
563         legendParams.add(encodedKey, UriUtils.encode(values[values.length - 1], StandardCharsets.UTF_8));
564       });
565     }
566     uriComponentsBuilder.replaceQueryParams(legendParams);
567     return uriComponentsBuilder.build(true).toUri();
568   }
569 
570   private URI buildWMSUrl(GeoService service, HttpServletRequest request) {
571     final UriComponentsBuilder originalServiceUrl = UriComponentsBuilder.fromUriString(service.getUrl());
572     // request.getParameterMap() includes parameters from an application/x-www-form-urlencoded POST
573     // body
574     final MultiValueMap<String, String> requestParams = request.getParameterMap().entrySet().stream()
575         .map(entry -> new AbstractMap.SimpleEntry<>(
576             UriUtils.encode(entry.getKey(), StandardCharsets.UTF_8),
577             Arrays.stream(entry.getValue())
578                 .map(value -> UriUtils.encode(value, StandardCharsets.UTF_8))
579                 .collect(Collectors.toList())))
580         .collect(Collectors.toMap(
581             Map.Entry::getKey, Map.Entry::getValue, (x, y) -> y, LinkedMultiValueMap::new));
582     final MultiValueMap<String, String> params =
583         buildOgcProxyRequestParams(originalServiceUrl.build(true).getQueryParams(), requestParams);
584     originalServiceUrl.replaceQueryParams(params);
585     return originalServiceUrl.build(true).toUri();
586   }
587 
588   public static MultiValueMap<String, String> buildOgcProxyRequestParams(
589       MultiValueMap<String, String> originalServiceParams, MultiValueMap<String, String> requestParams) {
590     // Start with all the parameters from the request
591     final MultiValueMap<String, String> params = new LinkedMultiValueMap<>(requestParams);
592 
593     // Never use the MapServer or QGIS Server MAP parameter from the request, also when the service URL has none
594     // because the server gets it from an environment variable (MS_MAPFILE or QGIS_PROJECT_FILE)
595     params.keySet().removeIf("MAP"::equalsIgnoreCase);
596 
597     // Add original service URL parameters if they are not required OGC params and not already set by the request
598     // (case-insensitive)
599     final List<String> ogcParams = List.of("SERVICE", "REQUEST", "VERSION");
600     for (Map.Entry<String, List<String>> serviceParam : originalServiceParams.entrySet()) {
601       String key = serviceParam.getKey();
602       if (!ogcParams.contains(key.toUpperCase(Locale.ROOT))
603           && params.keySet().stream().noneMatch(key::equalsIgnoreCase)) {
604         params.put(key, serviceParam.getValue());
605       }
606     }
607     return params;
608   }
609 
610   private URI build3DTilesUrl(GeoService service, HttpServletRequest request) {
611     // The URL in the GeoService refers to the location of the JSON file describing the tileset,
612     // e.g. example.com/buildings/3dtiles. The paths to the subtrees and tiles of the tilesets do
613     // not include the '/3dtiles' (or '/tileset.json') part of the path. Their paths are e.g.
614     // example.com/buildings/subtrees/... or example.com/buildings/t/...
615     final UriComponentsBuilder originalServiceUrl = UriComponentsBuilder.fromUriString(service.getUrl());
616     String baseUrl = originalServiceUrl.build(true).toUriString();
617     String[] parts = request.getRequestURI().split("/proxy/tiles3d/", 2);
618     if (parts.length < 2) {
619       throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid 3D tiles proxy path");
620     }
621     String pathToContent = parts[1];
622 
623     // Prevent path traversal
624     if (pathToContent.contains("..") || pathToContent.contains("\\")) {
625       throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid 3D tiles content path");
626     }
627 
628     // Return service URL when the request is for the JSON file describing the tileset
629     if (Objects.equals(pathToContent, TILES3D_DESCRIPTION_PATH)) {
630       return UriComponentsBuilder.fromUriString(baseUrl).build(true).toUri();
631     }
632 
633     // Remove the part of the service URL referring to the JSON file describing the tileset
634     int lastSlashIndex = baseUrl.lastIndexOf('/');
635     if (lastSlashIndex != -1) {
636       baseUrl = baseUrl.substring(0, lastSlashIndex + 1);
637     }
638 
639     // Return final URL with specific path to the tile or subtree
640     String finalUrl = baseUrl + pathToContent;
641     return UriComponentsBuilder.fromUriString(finalUrl).build(true).toUri();
642   }
643 
644   private ResponseEntity<?> doProxy(URI uri, GeoService service, HttpServletRequest request) {
645     HttpRequest.Builder requestBuilder = HttpRequest.newBuilder().timeout(requestTimeout);
646 
647     try {
648       configureProxyRequestBuilderForUri(requestBuilder, uri, request);
649     } catch (IllegalArgumentException e) {
650       // For instance an unsupported URI scheme in the service URL
651       logger.error("Invalid URL for proxying service {}: {}", service.getId(), e.getMessage());
652       throw new ResponseStatusException(
653           HttpStatus.INTERNAL_SERVER_ERROR,
654           "Invalid URL for proxying service %s: %s".formatted(service.getId(), e.getMessage()),
655           e);
656     }
657 
658     addForwardedForRequestHeaders(requestBuilder, request);
659 
660     try {
661       passthroughRequestHeaders(
662           requestBuilder,
663           request,
664           Set.of(
665               ACCEPT,
666               IF_MODIFIED_SINCE,
667               IF_UNMODIFIED_SINCE,
668               IF_MATCH,
669               IF_NONE_MATCH,
670               IF_RANGE,
671               RANGE,
672               REFERER,
673               USER_AGENT));
674     } catch (IllegalArgumentException e) {
675       // HttpRequest.Builder.header() rejects header values with illegal characters
676       throw new ResponseStatusException(
677           HttpStatus.BAD_REQUEST, "Invalid request header for proxying: " + e.getMessage(), e);
678     }
679 
680     if (service.getAuthentication() != null
681         && service.getAuthentication().getMethod() == ServiceAuthentication.MethodEnum.PASSWORD) {
682       setHttpBasicAuthenticationHeader(
683           requestBuilder,
684           service.getAuthentication().getUsername(),
685           service.getAuthentication().getPassword());
686     }
687 
688     final HttpResponse<InputStream> response;
689     try {
690       // TODO: close JPA connection before proxying
691       response = this.httpClient.send(requestBuilder.build(), HttpResponse.BodyHandlers.ofInputStream());
692     } catch (HttpTimeoutException e) {
693       // Also handles HttpConnectTimeoutException
694       throw upstreamError(HttpStatus.GATEWAY_TIMEOUT, "Timeout proxying request to", uri, service, e);
695     } catch (IOException | RuntimeException e) {
696       throw upstreamError(HttpStatus.BAD_GATEWAY, "Error proxying request to", uri, service, e);
697     } catch (InterruptedException e) {
698       Thread.currentThread().interrupt();
699       throw upstreamError(
700           HttpStatus.SERVICE_UNAVAILABLE, "Interrupted while proxying request to", uri, service, e);
701     }
702 
703     if (response.statusCode() == HttpStatus.UNAUTHORIZED.value()) {
704       // The proxied service does not accept the configured credentials (or none are configured). Do not pass the
705       // 401
706       // on to the client: that would look like the user is not logged in to Tailormap, while the user can do
707       // nothing
708       // about it. A server might also 'hide' the layer instead of sending a 401, which can't be detected here.
709       // It would be nice if these errors were available in the admin interface.
710       closeQuietly(response.body());
711       boolean hasCredentials = service.getAuthentication() != null
712           && service.getAuthentication().getMethod() == ServiceAuthentication.MethodEnum.PASSWORD;
713       String reason = hasCredentials
714           ? "Proxied service %s did not accept the configured credentials"
715           : "Proxied service %s requires authentication but no credentials are configured";
716       logger.warn("{} (HTTP 401 from {})", reason.formatted(service.getId()), withoutUserInfoAndQuery(uri));
717       throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, reason.formatted(service.getId()));
718     }
719 
720     if (response.statusCode() == HttpStatus.OK.value()
721         && GET.name().equals(request.getMethod())
722         && isNotModified(request, response.headers())) {
723       // Spring would turn the 200 response into a 304 Not Modified response itself when the passed through ETag
724       // or
725       // Last-Modified header matches the conditional request headers (when the proxied service ignores them), but
726       // without closing the response body. That would keep the connection to the proxied service open, so handle
727       // this here.
728       closeQuietly(response.body());
729       HttpHeaders headers =
730           passthroughResponseHeaders(response.headers(), Set.of(CACHE_CONTROL, EXPIRES, LAST_MODIFIED, ETAG));
731       addSecurityResponseHeaders(headers);
732       return ResponseEntity.status(HttpStatus.NOT_MODIFIED)
733           .headers(headers)
734           .build();
735     }
736 
737     InputStreamResource body = new InputStreamResource(response.body());
738     HttpHeaders headers = passthroughResponseHeaders(
739         response.headers(),
740         Set.of(
741             CONTENT_TYPE,
742             CONTENT_LENGTH,
743             CONTENT_RANGE,
744             CONTENT_DISPOSITION,
745             CACHE_CONTROL,
746             EXPIRES,
747             LAST_MODIFIED,
748             ETAG,
749             PRAGMA));
750     if (headers.getContentType() == null) {
751       headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
752     }
753     addSecurityResponseHeaders(headers);
754     return ResponseEntity.status(response.statusCode()).headers(headers).body(body);
755   }
756 
757   /**
758    * Add headers to limit what can be done with a proxied response, which is served from the Tailormap origin, with
759    * the credentials of the service and for the session of the user.
760    *
761    * <ul>
762    *   <li>{@code Cross-Origin-Resource-Policy: same-origin}: other sites can't load proxied URLs with {@code <img>}
763    *       or {@code <script>} tags using the cookies of the user.
764    *   <li>{@code Content-Security-Policy: sandbox}: HTML or SVG from the proxied service opened directly via the
765    *       proxy URL can't run scripts in the Tailormap origin.
766    *   <li>{@code Cache-Control: private} for logged-in users, see {@link #privateCacheControl(List)}.
767    * </ul>
768    */
769   private static void addSecurityResponseHeaders(HttpHeaders headers) {
770     headers.set(CROSS_ORIGIN_RESOURCE_POLICY, "same-origin");
771     headers.set(CONTENT_SECURITY_POLICY, "sandbox");
772 
773     Authentication auth = SecurityContextHolder.getContext().getAuthentication();
774     if (auth != null && !(auth instanceof AnonymousAuthenticationToken)) {
775       headers.set(CACHE_CONTROL, privateCacheControl(headers.getOrEmpty(CACHE_CONTROL)));
776     }
777   }
778 
779   /**
780    * Rewrite the {@code Cache-Control} of the proxied service to {@code private} so a shared cache (reverse proxy,
781    * CDN) in front of Tailormap does not serve a response for a logged-in user to others. The service may send
782    * {@code public} for a layer that is only visible for logged-in users in Tailormap, or a service with credentials.
783    * Only done for logged-in users: a response for an anonymous user is one any anonymous user can get. Without a
784    * {@code Cache-Control} header a shared cache may cache a response heuristically, so then {@code private} is added
785    * as well.
786    *
787    * @param cacheControl the Cache-Control header values of the proxied service
788    * @return the Cache-Control header value with {@code private} instead of {@code public}, {@code s-maxage} removed
789    *     and other directives such as {@code max-age} kept
790    */
791   static String privateCacheControl(List<String> cacheControl) {
792     StringBuilder result = new StringBuilder("private");
793     for (String value : cacheControl) {
794       HeaderElement[] headerElements =
795           BasicHeaderValueParser.INSTANCE.parseElements(value, new ParserCursor(0, value.length()));
796       for (HeaderElement directive : headerElements) {
797         String name = directive.getName().trim();
798         if (name.isEmpty() || REMOVED_CACHE_CONTROL_DIRECTIVES.contains(name.toLowerCase(Locale.ROOT))) {
799           continue;
800         }
801         result.append(", ").append(name);
802         if (directive.getValue() != null) {
803           result.append('=').append(formatCacheControlArgument(directive.getValue()));
804         }
805       }
806     }
807     return result.toString();
808   }
809 
810   /**
811    * Format a Cache-Control directive argument. Delta-seconds (max-age, stale-while-revalidate, ...) use the token
812    * form, other arguments such as the field names of no-cache use the quoted-string form which RFC 9111 requires for
813    * those.
814    */
815   private static String formatCacheControlArgument(String argument) {
816     if (StringUtils.isNumeric(argument)) {
817       return argument;
818     }
819     return '"' + argument.replace("\\", "\\\\").replace("\"", "\\\"") + '"';
820   }
821 
822   private static boolean isNotModified(HttpServletRequest request, java.net.http.HttpHeaders upstreamHeaders) {
823     HttpHeaders headers = passthroughResponseHeaders(upstreamHeaders, Set.of(ETAG, LAST_MODIFIED));
824     // getLastModified() returns -1 when the header is missing or invalid
825     long lastModified = headers.getLastModified();
826     if (headers.getETag() == null && lastModified < 0) {
827       return false;
828     }
829     return new ServletWebRequest(request).checkNotModified(headers.getETag(), lastModified);
830   }
831 
832   private static void closeQuietly(InputStream in) {
833     try {
834       in.close();
835     } catch (IOException e) {
836       logger.debug("Error closing proxied response body", e);
837     }
838   }
839 
840   /**
841    * Log a failed request to the proxied service and create an exception to report it to the client. Only the scheme,
842    * host, port and path of the URI are logged and reported, because the user info and query may contain credentials.
843    * The request may also have a Basic authentication header, which is never logged.
844    */
845   private static ResponseStatusException upstreamError(
846       HttpStatus status, String what, URI uri, GeoService service, Exception e) {
847     String safeUri = withoutUserInfoAndQuery(uri);
848     String reason = describeException(e);
849     logger.warn("{} service {} at {}: {}", what, service.getId(), safeUri, reason);
850     return new ResponseStatusException(status, "%s service at %s: %s".formatted(what, safeUri, reason), e);
851   }
852 
853   /**
854    * Describe an exception from the HTTP client. Some exceptions such as {@link java.net.ConnectException} have no
855    * message but have a cause with a message, such as "Connection refused".
856    */
857   private static String describeException(Exception e) {
858     if (e.getMessage() != null && !e.getMessage().isBlank()) {
859       return e.getMessage();
860     }
861     for (Throwable t = e.getCause(); t != null; t = t.getCause()) {
862       if (t.getMessage() != null && !t.getMessage().isBlank()) {
863         return "%s: %s".formatted(e.getClass().getSimpleName(), t.getMessage());
864       }
865     }
866     return e.getClass().getSimpleName();
867   }
868 
869   static String withoutUserInfoAndQuery(URI uri) {
870     try {
871       return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), null, null).toString();
872     } catch (URISyntaxException e) {
873       return "(invalid URI)";
874     }
875   }
876 }