View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.syncope.sra;
20  
21  import io.netty.channel.unix.Errors.NativeIoException;
22  import java.net.ConnectException;
23  import java.net.URI;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.Optional;
27  import java.util.concurrent.ConcurrentHashMap;
28  import org.apache.commons.lang3.StringUtils;
29  import org.apache.syncope.common.lib.to.SRARouteTO;
30  import org.apache.syncope.common.rest.api.RESTHeaders;
31  import org.slf4j.Logger;
32  import org.slf4j.LoggerFactory;
33  import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
34  import org.springframework.cloud.gateway.support.NotFoundException;
35  import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
36  import org.springframework.context.ApplicationListener;
37  import org.springframework.core.annotation.Order;
38  import org.springframework.http.HttpHeaders;
39  import org.springframework.http.HttpStatus;
40  import org.springframework.http.InvalidMediaTypeException;
41  import org.springframework.http.MediaType;
42  import org.springframework.http.server.reactive.ServerHttpRequest;
43  import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
44  import org.springframework.web.server.ServerWebExchange;
45  import org.springframework.web.server.WebExceptionHandler;
46  import reactor.core.publisher.Mono;
47  
48  @Order(-2)
49  public class SyncopeSRAWebExceptionHandler implements WebExceptionHandler, ApplicationListener<RefreshRoutesEvent> {
50  
51      private static final Logger LOG = LoggerFactory.getLogger(SyncopeSRAWebExceptionHandler.class);
52  
53      private static final Map<String, Optional<URI>> CACHE = new ConcurrentHashMap<>();
54  
55      private final RouteProvider routeProvider;
56  
57      private final SRAProperties props;
58  
59      public SyncopeSRAWebExceptionHandler(final RouteProvider routeProvider, final SRAProperties props) {
60          this.routeProvider = routeProvider;
61          this.props = props;
62      }
63  
64      @Override
65      public void onApplicationEvent(final RefreshRoutesEvent event) {
66          CACHE.clear();
67      }
68  
69      private URI getError(final ServerWebExchange exchange) {
70          URI error = props.getGlobal().getError();
71          String routeId = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_PREDICATE_ROUTE_ATTR);
72          if (StringUtils.isNotBlank(routeId)) {
73              Optional<URI> routeError = Optional.ofNullable(CACHE.get(routeId)).orElseGet(() -> {
74                  Optional<SRARouteTO> route = routeProvider.getRouteTOs().stream().
75                          filter(r -> routeId.equals(r.getKey())).findFirst();
76                  URI uri = route.map(SRARouteTO::getError).orElse(null);
77  
78                  CACHE.put(routeId, Optional.ofNullable(uri));
79                  return CACHE.get(routeId);
80              });
81              if (routeError.isPresent()) {
82                  error = routeError.get();
83              }
84          }
85  
86          return error;
87      }
88  
89      private boolean acceptsTextHtml(final ServerHttpRequest request) {
90          try {
91              List<MediaType> acceptedMediaTypes = request.getHeaders().getAccept();
92              acceptedMediaTypes.remove(MediaType.ALL);
93              MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
94              return acceptedMediaTypes.stream().anyMatch(MediaType.TEXT_HTML::isCompatibleWith);
95          } catch (InvalidMediaTypeException e) {
96              LOG.debug("Unexpected exception", e);
97              return false;
98          }
99      }
100 
101     private Mono<Void> doHandle(final ServerWebExchange exchange, final Throwable throwable, final HttpStatus status) {
102         try {
103             if (acceptsTextHtml(exchange.getRequest())) {
104                 exchange.getResponse().setStatusCode(HttpStatus.SEE_OTHER);
105 
106                 URI error = getError(exchange);
107                 exchange.getResponse().getHeaders().add(HttpHeaders.LOCATION, error.toASCIIString());
108             } else {
109                 exchange.getResponse().setStatusCode(status);
110 
111                 exchange.getResponse().getHeaders().add(
112                         RESTHeaders.ERROR_CODE, HttpStatus.NOT_FOUND.toString());
113                 exchange.getResponse().getHeaders().add(
114                         RESTHeaders.ERROR_INFO, throwable.getMessage().replace("\n", " "));
115             }
116         } catch (UnsupportedOperationException e) {
117             LOG.debug("Could not perform, ignoring", e);
118         }
119 
120         return exchange.getResponse().setComplete();
121     }
122 
123     @Override
124     public Mono<Void> handle(final ServerWebExchange exchange, final Throwable throwable) {
125         if (throwable instanceof ConnectException
126                 || throwable instanceof NativeIoException
127                 || throwable instanceof NotFoundException) {
128 
129             LOG.error("ConnectException thrown", throwable);
130 
131             return doHandle(exchange, throwable, HttpStatus.NOT_FOUND);
132         } else if (throwable instanceof OAuth2AuthorizationException) {
133             LOG.error("OAuth2AuthorizationException thrown", throwable);
134 
135             return doHandle(exchange, throwable, HttpStatus.INTERNAL_SERVER_ERROR);
136         }
137 
138         return Mono.error(throwable);
139     }
140 }