1   /*
2    * Copyright 2019 LINE Corporation
3    *
4    * LINE Corporation licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package com.linecorp.centraldogma.server;
17  
18  import javax.annotation.Nullable;
19  
20  import org.slf4j.Logger;
21  import org.slf4j.LoggerFactory;
22  
23  import com.linecorp.armeria.common.HttpRequest;
24  import com.linecorp.armeria.common.HttpResponse;
25  import com.linecorp.armeria.common.HttpStatus;
26  import com.linecorp.armeria.server.HttpService;
27  import com.linecorp.armeria.server.ServiceRequestContext;
28  import com.linecorp.armeria.server.auth.AuthFailureHandler;
29  import com.linecorp.centraldogma.common.AuthorizationException;
30  import com.linecorp.centraldogma.common.ShuttingDownException;
31  import com.linecorp.centraldogma.server.internal.api.HttpApiUtil;
32  
33  final class CentralDogmaAuthFailureHandler implements AuthFailureHandler {
34  
35      private static final Logger logger = LoggerFactory.getLogger(CentralDogmaAuthFailureHandler.class);
36  
37      private static final AuthorizationException AUTHORIZATION_EXCEPTION = new AuthorizationException("", false);
38  
39      @Override
40      public HttpResponse authFailed(HttpService delegate,
41                                     ServiceRequestContext ctx, HttpRequest req,
42                                     @Nullable Throwable cause) throws Exception {
43          if (cause != null) {
44              if (!(cause instanceof ShuttingDownException)) {
45                  logger.warn("Unexpected exception during authorization:", cause);
46              }
47              return HttpApiUtil.newResponse(ctx, HttpStatus.INTERNAL_SERVER_ERROR, cause);
48          }
49  
50          return HttpApiUtil.newResponse(ctx, HttpStatus.UNAUTHORIZED, AUTHORIZATION_EXCEPTION);
51      }
52  }