Search in sources :

Example 1 with ExternalCredsException

use of bio.terra.externalcreds.ExternalCredsException in project terra-external-credentials-manager by DataBiosphere.

the class ProviderService method getRefreshedPassportsAndVisas.

private LinkedAccountWithPassportAndVisas getRefreshedPassportsAndVisas(LinkedAccount linkedAccount) {
    var clientRegistration = providerClientCache.getProviderClient(linkedAccount.getProviderName()).orElseThrow(() -> new ExternalCredsException(String.format("Unable to find configs for the provider: %s", linkedAccount.getProviderName())));
    var accessTokenResponse = oAuth2Service.authorizeWithRefreshToken(clientRegistration, new OAuth2RefreshToken(linkedAccount.getRefreshToken(), null));
    // save the linked account with the new refresh token and extracted passport
    var linkedAccountWithRefreshToken = Optional.ofNullable(accessTokenResponse.getRefreshToken()).map(refreshToken -> linkedAccountService.upsertLinkedAccount(linkedAccount.withRefreshToken(refreshToken.getTokenValue()))).orElse(linkedAccount);
    // update the passport and visas
    var userInfo = oAuth2Service.getUserInfo(clientRegistration, accessTokenResponse.getAccessToken());
    return jwtUtils.enrichAccountWithPassportAndVisas(linkedAccountWithRefreshToken, userInfo);
}
Also used : AuditLogEvent(bio.terra.externalcreds.auditLogging.AuditLogEvent) VisaVerificationDetails(bio.terra.externalcreds.models.VisaVerificationDetails) LinkedAccount(bio.terra.externalcreds.models.LinkedAccount) AuditLogger(bio.terra.externalcreds.auditLogging.AuditLogger) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) WebClient(org.springframework.web.reactive.function.client.WebClient) NotFoundException(bio.terra.common.exception.NotFoundException) ArrayList(java.util.ArrayList) SecureRandom(java.security.SecureRandom) ExternalCredsException(bio.terra.externalcreds.ExternalCredsException) OAuth2State(bio.terra.externalcreds.models.OAuth2State) Service(org.springframework.stereotype.Service) Duration(java.time.Duration) Map(java.util.Map) ProviderProperties(bio.terra.externalcreds.config.ProviderProperties) AuditLogEventType(bio.terra.externalcreds.auditLogging.AuditLogEventType) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Set(java.util.Set) Mono(reactor.core.publisher.Mono) CannotDecodeOAuth2State(bio.terra.externalcreds.models.CannotDecodeOAuth2State) Instant(java.time.Instant) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) ExternalCredsConfig(bio.terra.externalcreds.config.ExternalCredsConfig) Objects(java.util.Objects) HttpStatus(org.springframework.http.HttpStatus) LinkedAccountWithPassportAndVisas(bio.terra.externalcreds.models.LinkedAccountWithPassportAndVisas) Slf4j(lombok.extern.slf4j.Slf4j) ChronoUnit(java.time.temporal.ChronoUnit) Stream(java.util.stream.Stream) BadRequestException(bio.terra.common.exception.BadRequestException) Optional(java.util.Optional) VisibleForTesting(com.google.common.annotations.VisibleForTesting) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Collections(java.util.Collections) ExternalCredsException(bio.terra.externalcreds.ExternalCredsException) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken)

Example 2 with ExternalCredsException

use of bio.terra.externalcreds.ExternalCredsException in project terra-external-credentials-manager by DataBiosphere.

the class ProviderService method authAndRefreshPassport.

@VisibleForTesting
void authAndRefreshPassport(LinkedAccount linkedAccount) {
    if (linkedAccount.getExpires().before(Timestamp.from(Instant.now()))) {
        invalidateLinkedAccount(linkedAccount);
    } else {
        try {
            var linkedAccountWithRefreshedPassport = getRefreshedPassportsAndVisas(linkedAccount);
            linkedAccountService.upsertLinkedAccountWithPassportAndVisas(linkedAccountWithRefreshedPassport);
            auditLogger.logEvent(new AuditLogEvent.Builder().auditLogEventType(AuditLogEventType.LinkRefreshed).providerName(linkedAccount.getProviderName()).userId(linkedAccount.getUserId()).build());
        } catch (IllegalArgumentException iae) {
            throw new ExternalCredsException(String.format("Could not contact issuer for provider %s", linkedAccount.getProviderName()), iae);
        } catch (OAuth2AuthorizationException oauthEx) {
            // if it looks like the refresh token will never work, delete the passport
            if (unrecoverableOAuth2ErrorCodes.contains(getRootOAuth2ErrorCode(oauthEx))) {
                log.info(String.format("Caught unrecoverable oauth2 error code refreshing passport for user id [%s].", linkedAccount.getUserId()), oauthEx);
                if (linkedAccount.getId().isEmpty()) {
                    throw new ExternalCredsException("linked account id missing");
                }
                invalidateLinkedAccount(linkedAccount);
            } else {
                // log and try again later
                throw new ExternalCredsException("Failed to refresh passport: ", oauthEx);
            }
        }
    }
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) AuditLogEvent(bio.terra.externalcreds.auditLogging.AuditLogEvent) ExternalCredsException(bio.terra.externalcreds.ExternalCredsException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 3 with ExternalCredsException

use of bio.terra.externalcreds.ExternalCredsException in project terra-external-credentials-manager by DataBiosphere.

the class EventPublisher method publishAuthorizationChangeEvent.

public void publishAuthorizationChangeEvent(AuthorizationChangeEvent event) {
    authorizationChangeEventPublisher.ifPresent(publisher -> {
        try {
            var message = PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(objectMapper.writeValueAsString(event))).build();
            var apiFuture = publisher.publish(message);
            ApiFutures.addCallback(apiFuture, new ApiFutureCallback<>() {

                @Override
                public void onFailure(Throwable throwable) {
                    log.error("failure publishing authorization change event", throwable);
                }

                @Override
                public void onSuccess(String messageId) {
                }
            }, MoreExecutors.directExecutor());
        } catch (JsonProcessingException e) {
            throw new ExternalCredsException("json exception writing authorization change event:" + event, e);
        }
    });
}
Also used : ExternalCredsException(bio.terra.externalcreds.ExternalCredsException) ByteString(com.google.protobuf.ByteString) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 4 with ExternalCredsException

use of bio.terra.externalcreds.ExternalCredsException in project terra-external-credentials-manager by DataBiosphere.

the class OidcApiController method getUserIdFromSam.

private String getUserIdFromSam() {
    try {
        var header = request.getHeader("authorization");
        if (header == null)
            throw new UnauthorizedException("User is not authorized");
        var accessToken = BearerTokenParser.parse(header);
        return samService.samUsersApi(accessToken).getUserStatusInfo().getUserSubjectId();
    } catch (ApiException e) {
        throw new ExternalCredsException(e, e.getCode() == HttpStatus.NOT_FOUND.value() ? HttpStatus.FORBIDDEN : HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : ExternalCredsException(bio.terra.externalcreds.ExternalCredsException) UnauthorizedException(bio.terra.common.exception.UnauthorizedException) ApiException(org.broadinstitute.dsde.workbench.client.sam.ApiException)

Example 5 with ExternalCredsException

use of bio.terra.externalcreds.ExternalCredsException in project terra-external-credentials-manager by DataBiosphere.

the class EventPublisher method shutdownPublisher.

@PreDestroy
void shutdownPublisher() {
    authorizationChangeEventPublisher.ifPresent(publisher -> {
        try {
            publisher.shutdown();
            publisher.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ExternalCredsException("publisher shutdown interrupted", e);
        }
    });
}
Also used : ExternalCredsException(bio.terra.externalcreds.ExternalCredsException) PreDestroy(javax.annotation.PreDestroy)

Aggregations

ExternalCredsException (bio.terra.externalcreds.ExternalCredsException)7 AuditLogEvent (bio.terra.externalcreds.auditLogging.AuditLogEvent)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)2 BadRequestException (bio.terra.common.exception.BadRequestException)1 NotFoundException (bio.terra.common.exception.NotFoundException)1 UnauthorizedException (bio.terra.common.exception.UnauthorizedException)1 BaseTest (bio.terra.externalcreds.BaseTest)1 AuditLogEventType (bio.terra.externalcreds.auditLogging.AuditLogEventType)1 AuditLogger (bio.terra.externalcreds.auditLogging.AuditLogger)1 ExternalCredsConfig (bio.terra.externalcreds.config.ExternalCredsConfig)1 ProviderProperties (bio.terra.externalcreds.config.ProviderProperties)1 CannotDecodeOAuth2State (bio.terra.externalcreds.models.CannotDecodeOAuth2State)1 LinkedAccount (bio.terra.externalcreds.models.LinkedAccount)1 LinkedAccountWithPassportAndVisas (bio.terra.externalcreds.models.LinkedAccountWithPassportAndVisas)1 OAuth2State (bio.terra.externalcreds.models.OAuth2State)1 VisaVerificationDetails (bio.terra.externalcreds.models.VisaVerificationDetails)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ByteString (com.google.protobuf.ByteString)1