1
2
3
4
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
104
105
106
107
108
109
110
111
112 @AppRestController
113 @Validated
114
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
139 private static final List<String> LAYER_PARAMS = List.of("LAYERS", "QUERY_LAYERS", "LAYER");
140
141
142
143
144
145
146
147 private static final List<String> FORBIDDEN_PARAMS =
148 List.of("SLD", "SLD_BODY", "SLD_URL", "STYLE_BODY", "STYLE_URL", "FILTER");
149
150
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
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
164 private static final List<String> LEGEND_FORBIDDEN_PARAMS =
165 List.of("LAYER", "LAYERS", "QUERY_LAYERS", "SLD", "SLD_BODY", "SLD_URL");
166
167
168
169
170
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
308
309
310
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
328
329
330
331
332
333
334
335
336
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
359
360
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
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
406
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
414
415
416
417
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
428
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
446
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
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
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
492
493
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
512
513
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
536
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
547
548
549
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
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
573
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
591 final MultiValueMap<String, String> params = new LinkedMultiValueMap<>(requestParams);
592
593
594
595 params.keySet().removeIf("MAP"::equalsIgnoreCase);
596
597
598
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
612
613
614
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
624 if (pathToContent.contains("..") || pathToContent.contains("\\")) {
625 throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid 3D tiles content path");
626 }
627
628
629 if (Objects.equals(pathToContent, TILES3D_DESCRIPTION_PATH)) {
630 return UriComponentsBuilder.fromUriString(baseUrl).build(true).toUri();
631 }
632
633
634 int lastSlashIndex = baseUrl.lastIndexOf('/');
635 if (lastSlashIndex != -1) {
636 baseUrl = baseUrl.substring(0, lastSlashIndex + 1);
637 }
638
639
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
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
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
691 response = this.httpClient.send(requestBuilder.build(), HttpResponse.BodyHandlers.ofInputStream());
692 } catch (HttpTimeoutException e) {
693
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
705
706
707
708
709
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
724
725
726
727
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
759
760
761
762
763
764
765
766
767
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
781
782
783
784
785
786
787
788
789
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
812
813
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
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
842
843
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
855
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 }