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.web.bind.annotation.RequestMethod.GET;
9   import static org.springframework.web.bind.annotation.RequestMethod.POST;
10  import static org.tailormap.api.util.HttpProxyUtil.addForwardedForRequestHeaders;
11  import static org.tailormap.api.util.HttpProxyUtil.passthroughRequestHeaders;
12  import static org.tailormap.api.util.HttpProxyUtil.passthroughResponseHeaders;
13  import static org.tailormap.api.util.HttpProxyUtil.setHttpBasicAuthenticationHeader;
14  
15  import io.micrometer.core.annotation.Timed;
16  import jakarta.servlet.http.HttpServletRequest;
17  import java.io.InputStream;
18  import java.lang.invoke.MethodHandles;
19  import java.net.URI;
20  import java.net.http.HttpClient;
21  import java.net.http.HttpRequest;
22  import java.net.http.HttpResponse;
23  import java.nio.charset.StandardCharsets;
24  import java.util.AbstractMap;
25  import java.util.Arrays;
26  import java.util.List;
27  import java.util.Locale;
28  import java.util.Map;
29  import java.util.Set;
30  import java.util.stream.Collectors;
31  import javax.annotation.Nullable;
32  import org.slf4j.Logger;
33  import org.slf4j.LoggerFactory;
34  import org.springframework.core.io.InputStreamResource;
35  import org.springframework.http.HttpHeaders;
36  import org.springframework.http.HttpStatus;
37  import org.springframework.http.ResponseEntity;
38  import org.springframework.util.LinkedMultiValueMap;
39  import org.springframework.util.MultiValueMap;
40  import org.springframework.validation.annotation.Validated;
41  import org.springframework.web.bind.annotation.ModelAttribute;
42  import org.springframework.web.bind.annotation.PathVariable;
43  import org.springframework.web.bind.annotation.RequestMapping;
44  import org.springframework.web.server.ResponseStatusException;
45  import org.springframework.web.util.UriComponentsBuilder;
46  import org.springframework.web.util.UriUtils;
47  import org.tailormap.api.annotation.AppRestController;
48  import org.tailormap.api.persistence.Application;
49  import org.tailormap.api.persistence.GeoService;
50  import org.tailormap.api.persistence.helper.GeoServiceHelper;
51  import org.tailormap.api.persistence.json.GeoServiceLayer;
52  import org.tailormap.api.persistence.json.GeoServiceProtocol;
53  import org.tailormap.api.persistence.json.ServiceAuthentication;
54  import org.tailormap.api.security.AuthorizationService;
55  
56  /**
57   * Proxy controller for OGC WMS and WMTS services. Does not attempt to hide the original service URL. Mostly useful for
58   * access to HTTP Basic secured services without sending the credentials to the client. The access control is handled by
59   * Spring Security and the authorizations configured on the service.
60   *
61   * <p>Only supports GET requests. Does not support CORS, only meant for tailormap-viewer from the same origin.
62   *
63   * <p>Implementation note: uses the Java 11 HttpClient. Spring cloud gateway can proxy with many more features but can
64   * not be used in a non-reactive application.
65   */
66  @AppRestController
67  @Validated
68  // Can't use ${tailormap-api.base-path} because linkTo() won't work
69  @RequestMapping(path = "/api/{viewerKind}/{viewerName}/layer/{appLayerId}/proxy/{protocol}")
70  public class GeoServiceProxyController {
71    private static final Logger logger =
72        LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
73    private final AuthorizationService authorizationService;
74  
75    public GeoServiceProxyController(AuthorizationService authorizationService) {
76      this.authorizationService = authorizationService;
77    }
78  
79    @RequestMapping(method = {GET, POST})
80    @Timed(value = "proxy", description = "Proxy OGC service calls")
81    public ResponseEntity<?> proxy(
82        @ModelAttribute Application application,
83        @ModelAttribute GeoService service,
84        @ModelAttribute GeoServiceLayer layer,
85        @PathVariable("protocol") GeoServiceProtocol protocol,
86        HttpServletRequest request) {
87  
88      if (service == null || layer == null) {
89        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
90      }
91  
92      if (GeoServiceProtocol.XYZ.equals(protocol)) {
93        throw new ResponseStatusException(HttpStatus.NOT_IMPLEMENTED, "XYZ proxying not implemented");
94      }
95  
96      if (!(service.getProtocol().equals(protocol) || GeoServiceProtocol.PROXIEDLEGEND.equals(protocol))) {
97        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid proxy protocol: " + protocol);
98      }
99  
100     if (!service.getSettings().getUseProxy()) {
101       throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Proxy not enabled for requested service");
102     }
103 
104     if (authorizationService.mustDenyAccessForSecuredProxy(application, service)) {
105       logger.warn(
106           "App {} (\"{}\") is using layer \"{}\" from proxied secured service URL {} (username \"{}\"), but app is publicly accessible. Denying proxy, even if user is authenticated.",
107           application.getId(),
108           application.getName(),
109           layer.getName(),
110           service.getUrl(),
111           service.getAuthentication().getUsername());
112       throw new ResponseStatusException(HttpStatus.FORBIDDEN);
113     }
114 
115     switch (protocol) {
116       case WMS:
117       case WMTS:
118         return doProxy(buildWMSUrl(service, request), service, request);
119       case PROXIEDLEGEND:
120         URI legendURI = buildLegendURI(service, layer, request);
121         if (null == legendURI) {
122           logger.warn("No legend URL found for layer {}", layer.getName());
123           return null;
124         }
125         return doProxy(legendURI, service, request);
126       default:
127         throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported proxy protocol: " + protocol);
128     }
129   }
130 
131   private @Nullable URI buildLegendURI(GeoService service, GeoServiceLayer layer, HttpServletRequest request) {
132     URI legendURI = GeoServiceHelper.getLayerLegendUrlFromStyles(service, layer);
133     if (null != legendURI && null != legendURI.getQuery() && null != request.getQueryString()) {
134       // assume this is a getLegendGraphic request
135       UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(legendURI);
136       switch (service.getSettings().getServerType()) {
137         case GEOSERVER:
138           uriComponentsBuilder.queryParam(
139               "LEGEND_OPTIONS", "fontAntiAliasing:true;labelMargin:0;forceLabels:on");
140           break;
141         case MAPSERVER:
142         case AUTO:
143         default:
144           // no special options
145       }
146       if (null != request.getParameterMap().get("SCALE")) {
147         legendURI = uriComponentsBuilder
148             .queryParam("SCALE", request.getParameterMap().get("SCALE")[0])
149             .build(true)
150             .toUri();
151       }
152     }
153     return legendURI;
154   }
155 
156   private URI buildWMSUrl(GeoService service, HttpServletRequest request) {
157     final UriComponentsBuilder originalServiceUrl = UriComponentsBuilder.fromUriString(service.getUrl());
158     // request.getParameterMap() includes parameters from an application/x-www-form-urlencoded POST
159     // body
160     final MultiValueMap<String, String> requestParams = request.getParameterMap().entrySet().stream()
161         .map(entry -> new AbstractMap.SimpleEntry<>(
162             entry.getKey(),
163             Arrays.stream(entry.getValue())
164                 .map(value -> UriUtils.encode(value, StandardCharsets.UTF_8))
165                 .collect(Collectors.toList())))
166         .collect(Collectors.toMap(
167             Map.Entry::getKey, Map.Entry::getValue, (x, y) -> y, LinkedMultiValueMap::new));
168     final MultiValueMap<String, String> params =
169         buildOgcProxyRequestParams(originalServiceUrl.build(true).getQueryParams(), requestParams);
170     originalServiceUrl.replaceQueryParams(params);
171     return originalServiceUrl.build(true).toUri();
172   }
173 
174   public static MultiValueMap<String, String> buildOgcProxyRequestParams(
175       MultiValueMap<String, String> originalServiceParams, MultiValueMap<String, String> requestParams) {
176     // Start with all the parameters from the request
177     final MultiValueMap<String, String> params = new LinkedMultiValueMap<>(requestParams);
178 
179     // Add original service URL parameters if they are not required OGC params (case-insensitive)
180     // and not already set by request
181     final List<String> ogcParams = List.of(new String[] {"SERVICE", "REQUEST", "VERSION"});
182     for (Map.Entry<String, List<String>> serviceParam : originalServiceParams.entrySet()) {
183       if (!params.containsKey(serviceParam.getKey())
184           && !ogcParams.contains(serviceParam.getKey().toUpperCase(Locale.ROOT))) {
185         params.put(serviceParam.getKey(), serviceParam.getValue());
186       }
187     }
188     return params;
189   }
190 
191   private static ResponseEntity<?> doProxy(URI uri, GeoService service, HttpServletRequest request) {
192     final HttpClient.Builder builder = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NORMAL);
193     final HttpClient httpClient = builder.build();
194 
195     HttpRequest.Builder requestBuilder = HttpRequest.newBuilder().uri(uri);
196 
197     addForwardedForRequestHeaders(requestBuilder, request);
198 
199     passthroughRequestHeaders(
200         requestBuilder,
201         request,
202         Set.of(
203             "Accept",
204             "If-Modified-Since",
205             "If-Unmodified-Since",
206             "If-Match",
207             "If-None-Match",
208             "If-Range",
209             "Range",
210             "Referer",
211             "User-Agent"));
212 
213     if (service.getAuthentication() != null
214         && service.getAuthentication().getMethod() == ServiceAuthentication.MethodEnum.PASSWORD) {
215       setHttpBasicAuthenticationHeader(
216           requestBuilder,
217           service.getAuthentication().getUsername(),
218           service.getAuthentication().getPassword());
219     }
220 
221     try {
222       // TODO: close JPA connection before proxying
223       HttpResponse<InputStream> response =
224           httpClient.send(requestBuilder.build(), HttpResponse.BodyHandlers.ofInputStream());
225 
226       // If the server does not accept our credentials it might 'hide' the layer or even send a 401
227       // Unauthorized status. We do not send the WWW-Authenticate header back, so the client will
228       // get the error but not an authorization popup.
229       // It would be nice if proxy (auth) errors were logged and available in the admin interface.
230       // Currently, a layer will just stop working if the geo service credentials are changed
231       // without updating them in the geo service registry.
232       InputStreamResource body = new InputStreamResource(response.body());
233       HttpHeaders headers = passthroughResponseHeaders(
234           response.headers(),
235           Set.of(
236               "Content-Type",
237               "Content-Length",
238               "Content-Range",
239               "Content-Disposition",
240               "Cache-Control",
241               "Expires",
242               "Last-Modified",
243               "ETag",
244               "Pragma"));
245       return ResponseEntity.status(response.statusCode()).headers(headers).body(body);
246     } catch (Exception e) {
247       return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body("Bad Gateway");
248     }
249   }
250 }