Search in sources :

Example 1 with LinkedAccount

use of bio.terra.externalcreds.models.LinkedAccount 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 LinkedAccount

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

the class AuthorizationCodeExchangeTest method runTest.

private void runTest(LinkedAccount expectedLinkedAccount, GA4GHPassport expectedPassport, List<GA4GHVisa> expectedVisas) throws URISyntaxException {
    var state = new OAuth2State.Builder().provider(expectedLinkedAccount.getProviderName()).random(OAuth2State.generateRandomState(new SecureRandom())).build();
    String encodedState = state.encode(objectMapper);
    setupMocks(expectedLinkedAccount, expectedPassport, authorizationCode, redirectUri, scopes, encodedState);
    linkedAccountService.upsertOAuth2State(expectedLinkedAccount.getUserId(), state);
    var linkedAccountWithPassportAndVisas = providerService.createLink(expectedLinkedAccount.getProviderName(), expectedLinkedAccount.getUserId(), authorizationCode, redirectUri, scopes, encodedState);
    assertPresent(linkedAccountWithPassportAndVisas);
    assertEquals(expectedLinkedAccount, linkedAccountWithPassportAndVisas.get().getLinkedAccount().withExpires(passportExpiresTime).withId(Optional.empty()));
    var stablePassport = linkedAccountWithPassportAndVisas.get().getPassport().map(p -> p.withId(Optional.empty()).withLinkedAccountId(Optional.empty()));
    assertEquals(Optional.ofNullable(expectedPassport), stablePassport);
    var stableVisas = linkedAccountWithPassportAndVisas.get().getVisas().stream().map(visa -> visa.withLastValidated(Optional.empty()).withId(Optional.empty()).withPassportId(Optional.empty())).collect(Collectors.toList());
    assertEquals(expectedVisas, stableVisas);
    // state should have been removed from the db
    assertThrows(BadRequestException.class, () -> linkedAccountService.validateAndDeleteOAuth2State(expectedLinkedAccount.getUserId(), state));
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) GA4GHVisa(bio.terra.externalcreds.models.GA4GHVisa) LinkedAccount(bio.terra.externalcreds.models.LinkedAccount) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) JOSEException(com.nimbusds.jose.JOSEException) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) SecureRandom(java.security.SecureRandom) AfterAll(org.junit.jupiter.api.AfterAll) OAuth2State(bio.terra.externalcreds.models.OAuth2State) BaseTest(bio.terra.externalcreds.BaseTest) BeforeAll(org.junit.jupiter.api.BeforeAll) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) Map(java.util.Map) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) URI(java.net.URI) TokenType(org.springframework.security.oauth2.core.OAuth2AccessToken.TokenType) JwtSigningTestUtils(bio.terra.externalcreds.JwtSigningTestUtils) MockBean(org.springframework.boot.test.mock.mockito.MockBean) TestUtils(bio.terra.externalcreds.TestUtils) Assertions.assertInstanceOf(org.junit.jupiter.api.Assertions.assertInstanceOf) Timestamp(java.sql.Timestamp) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Set(java.util.Set) Mockito.when(org.mockito.Mockito.when) UUID(java.util.UUID) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) Collectors(java.util.stream.Collectors) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) ExternalCredsConfig(bio.terra.externalcreds.config.ExternalCredsConfig) Test(org.junit.jupiter.api.Test) List(java.util.List) BadRequestException(bio.terra.common.exception.BadRequestException) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) GA4GHPassport(bio.terra.externalcreds.models.GA4GHPassport) Optional(java.util.Optional) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) TokenTypeEnum(bio.terra.externalcreds.models.TokenTypeEnum) Collections(java.util.Collections) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) SecureRandom(java.security.SecureRandom) OAuth2State(bio.terra.externalcreds.models.OAuth2State)

Example 3 with LinkedAccount

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

the class ProviderService method refreshExpiringPassports.

/**
 * Get a new passport for each linked accounts with visas or passports expiring within
 * externalCredsConfig.getVisaAndPassportRefreshInterval time from now
 *
 * @return the number of linked accounts with expiring visas or passports
 */
public int refreshExpiringPassports() {
    var refreshInterval = externalCredsConfig.getVisaAndPassportRefreshDuration();
    var expirationCutoff = new Timestamp(Instant.now().plus(refreshInterval).toEpochMilli());
    var expiringLinkedAccounts = linkedAccountService.getExpiringLinkedAccounts(expirationCutoff);
    for (LinkedAccount linkedAccount : expiringLinkedAccounts) {
        try {
            authAndRefreshPassport(linkedAccount);
        } catch (Exception e) {
            log.info("Failed to refresh passport, will try again at the next interval.", e);
        }
    }
    return expiringLinkedAccounts.size();
}
Also used : Timestamp(java.sql.Timestamp) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) NotFoundException(bio.terra.common.exception.NotFoundException) ExternalCredsException(bio.terra.externalcreds.ExternalCredsException) BadRequestException(bio.terra.common.exception.BadRequestException) LinkedAccount(bio.terra.externalcreds.models.LinkedAccount)

Aggregations

BadRequestException (bio.terra.common.exception.BadRequestException)3 LinkedAccount (bio.terra.externalcreds.models.LinkedAccount)3 Timestamp (java.sql.Timestamp)3 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)3 NotFoundException (bio.terra.common.exception.NotFoundException)2 ExternalCredsException (bio.terra.externalcreds.ExternalCredsException)2 ExternalCredsConfig (bio.terra.externalcreds.config.ExternalCredsConfig)2 OAuth2State (bio.terra.externalcreds.models.OAuth2State)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 SecureRandom (java.security.SecureRandom)2 Collections (java.util.Collections)2 Map (java.util.Map)2 Optional (java.util.Optional)2 Set (java.util.Set)2 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)2 BaseTest (bio.terra.externalcreds.BaseTest)1 JwtSigningTestUtils (bio.terra.externalcreds.JwtSigningTestUtils)1 TestUtils (bio.terra.externalcreds.TestUtils)1 AuditLogEvent (bio.terra.externalcreds.auditLogging.AuditLogEvent)1 AuditLogEventType (bio.terra.externalcreds.auditLogging.AuditLogEventType)1