Search in sources :

Example 6 with HttpResponseException

use of com.google.api.client.http.HttpResponseException in project workbench by all-of-us.

the class AuthInterceptor method preHandle.

/**
 * Returns true iff the request is auth'd and should proceed. Publishes authenticated user info
 * using Spring's SecurityContext.
 * @param handler The Swagger-generated ApiController. It contains our handler as a private
 *     delegate.
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // OPTIONS methods requests don't need authorization.
    if (request.getMethod().equals(HttpMethods.OPTIONS)) {
        return true;
    }
    HandlerMethod method = (HandlerMethod) handler;
    boolean isAuthRequired = false;
    ApiOperation apiOp = AnnotationUtils.findAnnotation(method.getMethod(), ApiOperation.class);
    if (apiOp != null) {
        for (Authorization auth : apiOp.authorizations()) {
            if (auth.value().equals(authName)) {
                isAuthRequired = true;
                break;
            }
        }
    }
    if (!isAuthRequired) {
        return true;
    }
    String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
        log.warning("No bearer token found in request");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
    String token = authorizationHeader.substring("Bearer".length()).trim();
    Userinfoplus userInfo;
    try {
        userInfo = userInfoService.getUserInfo(token);
    } catch (HttpResponseException e) {
        log.log(Level.WARNING, "{0} response getting user info for bearer token {1}: {2}", new Object[] { e.getStatusCode(), token, e.getStatusMessage() });
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
    // TODO: check Google group membership to ensure user is in registered user group
    String userEmail = userInfo.getEmail();
    WorkbenchConfig workbenchConfig = workbenchConfigProvider.get();
    if (workbenchConfig.auth.serviceAccountApiUsers.contains(userEmail)) {
        // Whitelisted service accounts are able to make API calls, too.
        // TODO: stop treating service accounts as normal users, have a separate table for them,
        // administrators.
        User user = userDao.findUserByEmail(userEmail);
        if (user == null) {
            user = userService.createServiceAccountUser(userEmail);
        }
        SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(user, userInfo, token, UserType.SERVICE_ACCOUNT));
        log.log(Level.INFO, "{0} service account in use", userInfo.getEmail());
        return true;
    }
    String gsuiteDomainSuffix = "@" + workbenchConfig.googleDirectoryService.gSuiteDomain;
    if (!userEmail.endsWith(gsuiteDomainSuffix)) {
        try {
            // If the email isn't in our GSuite domain, try FireCloud; we could be dealing with a
            // pet service account. In both AofU and FireCloud, the pet SA is treated as if it were
            // the user it was created for.
            userEmail = fireCloudService.getMe().getUserInfo().getUserEmail();
        } catch (ApiException e) {
            log.log(Level.INFO, "FireCloud lookup for {0} failed, can't access the workbench: {1}", new Object[] { userInfo.getEmail(), e.getMessage() });
            response.sendError(e.getCode());
            return false;
        }
        if (!userEmail.endsWith(gsuiteDomainSuffix)) {
            log.log(Level.INFO, "User {0} isn't in domain {1}, can't access the workbench", new Object[] { userEmail, gsuiteDomainSuffix });
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }
    }
    User user = userDao.findUserByEmail(userEmail);
    if (user == null) {
        // TODO(danrodney): start populating contact email in Google account, use it here.
        user = userService.createUser(userInfo.getGivenName(), userInfo.getFamilyName(), userInfo.getEmail(), null);
    } else {
        if (user.getDisabled()) {
            throw new ForbiddenException(ExceptionUtils.errorResponse(ErrorCode.USER_DISABLED, "This user account has been disabled."));
        }
    }
    SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(user, userInfo, token, UserType.RESEARCHER));
    // TODO: setup this in the context, get rid of log statement
    log.log(Level.INFO, "{0} logged in", userInfo.getEmail());
    if (!hasRequiredAuthority(method, user)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }
    return true;
}
Also used : Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) WorkbenchConfig(org.pmiops.workbench.config.WorkbenchConfig) ForbiddenException(org.pmiops.workbench.exceptions.ForbiddenException) User(org.pmiops.workbench.db.model.User) HttpResponseException(com.google.api.client.http.HttpResponseException) UserAuthentication(org.pmiops.workbench.auth.UserAuthentication) HandlerMethod(org.springframework.web.method.HandlerMethod) Authorization(io.swagger.annotations.Authorization) ApiOperation(io.swagger.annotations.ApiOperation) ApiException(org.pmiops.workbench.firecloud.ApiException)

Example 7 with HttpResponseException

use of com.google.api.client.http.HttpResponseException in project jib by google.

the class BlobCheckerTest method testHandleHttpResponseException_notBlobUnknown.

@Test
public void testHandleHttpResponseException_notBlobUnknown() throws IOException, RegistryErrorException {
    HttpResponseException mockHttpResponseException = Mockito.mock(HttpResponseException.class);
    Mockito.when(mockHttpResponseException.getStatusCode()).thenReturn(HttpStatusCodes.STATUS_CODE_NOT_FOUND);
    ErrorResponseTemplate emptyErrorResponseTemplate = new ErrorResponseTemplate();
    Mockito.when(mockHttpResponseException.getContent()).thenReturn(Blobs.writeToString(JsonTemplateMapper.toBlob(emptyErrorResponseTemplate)));
    try {
        testBlobChecker.handleHttpResponseException(mockHttpResponseException);
        Assert.fail("Non-BLOB_UNKNOWN errors should not be handled");
    } catch (HttpResponseException ex) {
        Assert.assertEquals(mockHttpResponseException, ex);
    }
}
Also used : HttpResponseException(com.google.api.client.http.HttpResponseException) ErrorResponseTemplate(com.google.cloud.tools.jib.registry.json.ErrorResponseTemplate) Test(org.junit.Test)

Example 8 with HttpResponseException

use of com.google.api.client.http.HttpResponseException in project jib by google.

the class BlobCheckerTest method testHandleHttpResponseException.

@Test
public void testHandleHttpResponseException() throws IOException, RegistryErrorException {
    HttpResponseException mockHttpResponseException = Mockito.mock(HttpResponseException.class);
    Mockito.when(mockHttpResponseException.getStatusCode()).thenReturn(HttpStatusCodes.STATUS_CODE_NOT_FOUND);
    ErrorResponseTemplate emptyErrorResponseTemplate = new ErrorResponseTemplate().addError(new ErrorEntryTemplate(ErrorCodes.BLOB_UNKNOWN.name(), "some message"));
    Mockito.when(mockHttpResponseException.getContent()).thenReturn(Blobs.writeToString(JsonTemplateMapper.toBlob(emptyErrorResponseTemplate)));
    BlobDescriptor blobDescriptor = testBlobChecker.handleHttpResponseException(mockHttpResponseException);
    Assert.assertNull(blobDescriptor);
}
Also used : BlobDescriptor(com.google.cloud.tools.jib.blob.BlobDescriptor) HttpResponseException(com.google.api.client.http.HttpResponseException) ErrorResponseTemplate(com.google.cloud.tools.jib.registry.json.ErrorResponseTemplate) ErrorEntryTemplate(com.google.cloud.tools.jib.registry.json.ErrorEntryTemplate) Test(org.junit.Test)

Example 9 with HttpResponseException

use of com.google.api.client.http.HttpResponseException in project jib by google.

the class RegistryClient method callRegistryEndpoint.

/**
 * Calls the registry endpoint with an override URL.
 *
 * @param url the endpoint URL to call, or {@code null} to use default from {@code
 *     registryEndpointProvider}
 * @param registryEndpointProvider the {@link RegistryEndpointProvider} to the endpoint
 */
@Nullable
private <T> T callRegistryEndpoint(@Nullable URL url, RegistryEndpointProvider<T> registryEndpointProvider) throws IOException, RegistryException {
    if (url == null) {
        url = registryEndpointProvider.getApiRoute(getApiRouteBase());
    }
    try (Connection connection = new Connection(url)) {
        Request request = Request.builder().setAuthorization(authorization).setUserAgent(getUserAgent()).setAccept(registryEndpointProvider.getAccept()).setBody(registryEndpointProvider.getContent()).build();
        Response response = connection.send(registryEndpointProvider.getHttpMethod(), request);
        return registryEndpointProvider.handleResponse(response);
    } catch (HttpResponseException ex) {
        // First, see if the endpoint provider handles an exception as an expected response.
        try {
            return registryEndpointProvider.handleHttpResponseException(ex);
        } catch (HttpResponseException httpResponseException) {
            if (httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_BAD_REQUEST || httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND || httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_METHOD_NOT_ALLOWED) {
                // The name or reference was invalid.
                ErrorResponseTemplate errorResponse = JsonTemplateMapper.readJson(httpResponseException.getContent(), ErrorResponseTemplate.class);
                RegistryErrorExceptionBuilder registryErrorExceptionBuilder = new RegistryErrorExceptionBuilder(registryEndpointProvider.getActionDescription(), httpResponseException);
                for (ErrorEntryTemplate errorEntry : errorResponse.getErrors()) {
                    registryErrorExceptionBuilder.addReason(errorEntry);
                }
                throw registryErrorExceptionBuilder.build();
            } else if (httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED || httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_FORBIDDEN) {
                throw new RegistryUnauthorizedException(registryEndpointProperties.getServerUrl(), registryEndpointProperties.getImageName(), httpResponseException);
            } else if (httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_TEMPORARY_REDIRECT) {
                return callRegistryEndpoint(new URL(httpResponseException.getHeaders().getLocation()), registryEndpointProvider);
            } else {
                // Unknown
                throw httpResponseException;
            }
        }
    } catch (NoHttpResponseException ex) {
        throw new RegistryNoResponseException(ex);
    } catch (SSLPeerUnverifiedException ex) {
        // Fall-back to HTTP
        GenericUrl httpUrl = new GenericUrl(url);
        httpUrl.setScheme("http");
        return callRegistryEndpoint(httpUrl.toURL(), registryEndpointProvider);
    }
}
Also used : NoHttpResponseException(org.apache.http.NoHttpResponseException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) Connection(com.google.cloud.tools.jib.http.Connection) Request(com.google.cloud.tools.jib.http.Request) NoHttpResponseException(org.apache.http.NoHttpResponseException) HttpResponseException(com.google.api.client.http.HttpResponseException) GenericUrl(com.google.api.client.http.GenericUrl) ErrorResponseTemplate(com.google.cloud.tools.jib.registry.json.ErrorResponseTemplate) URL(java.net.URL) Response(com.google.cloud.tools.jib.http.Response) ErrorEntryTemplate(com.google.cloud.tools.jib.registry.json.ErrorEntryTemplate) Nullable(javax.annotation.Nullable)

Example 10 with HttpResponseException

use of com.google.api.client.http.HttpResponseException in project jib by google.

the class ManifestPusherIntegrationTest method testPush_missingBlobs.

@Test
public void testPush_missingBlobs() throws IOException, RegistryException {
    RegistryClient registryClient = new RegistryClient(null, "gcr.io", "distroless/java");
    ManifestTemplate manifestTemplate = registryClient.pullManifest("latest");
    registryClient = new RegistryClient(null, "localhost:5000", "busybox");
    try {
        registryClient.pushManifest((V22ManifestTemplate) manifestTemplate, "latest");
        Assert.fail("Pushing manifest without its BLOBs should fail");
    } catch (RegistryErrorException ex) {
        HttpResponseException httpResponseException = (HttpResponseException) ex.getCause();
        Assert.assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, httpResponseException.getStatusCode());
    }
}
Also used : HttpResponseException(com.google.api.client.http.HttpResponseException) V22ManifestTemplate(com.google.cloud.tools.jib.image.json.V22ManifestTemplate) ManifestTemplate(com.google.cloud.tools.jib.image.json.ManifestTemplate) Test(org.junit.Test)

Aggregations

HttpResponseException (com.google.api.client.http.HttpResponseException)38 GenericUrl (com.google.api.client.http.GenericUrl)15 IOException (java.io.IOException)15 HttpResponse (com.google.api.client.http.HttpResponse)13 Test (org.junit.Test)13 HttpRequest (com.google.api.client.http.HttpRequest)10 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)6 HttpHeaders (com.google.api.client.http.HttpHeaders)4 LowLevelHttpResponse (com.google.api.client.http.LowLevelHttpResponse)4 ErrorResponseTemplate (com.google.cloud.tools.jib.registry.json.ErrorResponseTemplate)4 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)3 ErrorEntryTemplate (com.google.cloud.tools.jib.registry.json.ErrorEntryTemplate)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 PServiceCall (net.morimekta.providence.PServiceCall)3 Request (net.morimekta.test.providence.client.Request)3 TestService (net.morimekta.test.providence.client.TestService)3 AccountManager (android.accounts.AccountManager)2 ByteArrayContent (com.google.api.client.http.ByteArrayContent)2 HttpTransport (com.google.api.client.http.HttpTransport)2 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)2