Search in sources :

Example 1 with Gw2AccountVerificationEntity

use of com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity in project oauth2-server by gw2auth.

the class ApplicationControllerTest method getApplicationSummary.

@Test
public void getApplicationSummary() throws Exception {
    final long accountId = this.accountRepository.save(new AccountEntity(null, Instant.now())).id();
    final int accounts = 102;
    final int apiTokens = 3;
    final int verifiedGw2Accounts = 5;
    final int clientRegistrations = 12;
    // this must be less than clientRegistrations! (only to keep the testcase simple)
    final int clientAuthorizations = 10;
    for (int i = 0; i < accounts; i++) {
        this.accountRepository.save(new AccountEntity(null, Instant.now()));
    }
    for (int i = 0; i < apiTokens; i++) {
        this.testHelper.createApiToken(accountId, UUID.randomUUID(), Set.of(), "Name");
    }
    for (int i = 0; i < verifiedGw2Accounts; i++) {
        this.gw2AccountVerificationRepository.save(new Gw2AccountVerificationEntity(UUID.randomUUID(), accountId));
    }
    final Queue<ClientRegistrationEntity> clientRegistrationEntities = new LinkedList<>();
    for (int i = 0; i < clientRegistrations; i++) {
        clientRegistrationEntities.add(this.clientRegistrationRepository.save(new ClientRegistrationEntity(null, accountId, Instant.now(), "Name", UUID.randomUUID(), "", Set.of(), Set.of("http://127.0.0.1/"))));
    }
    for (int i = 0; i < clientAuthorizations; i++) {
        this.clientConsentRepository.save(new ClientConsentEntity(accountId, clientRegistrationEntities.poll().id(), UUID.randomUUID(), Set.of("dummy")));
    }
    // add one client authorization without scopes (that should not be counted)
    this.clientConsentRepository.save(new ClientConsentEntity(accountId, clientRegistrationEntities.poll().id(), UUID.randomUUID(), Set.of()));
    this.mockMvc.perform(get("/api/application/summary")).andExpect(status().isOk()).andExpect(// we create one dummy account who owns everything else
    jsonPath("$.accounts").value(Integer.toString(accounts + 1))).andExpect(jsonPath("$.apiTokens").value(Integer.toString(apiTokens))).andExpect(jsonPath("$.verifiedGw2Accounts").value(Integer.toString(verifiedGw2Accounts))).andExpect(jsonPath("$.clientRegistrations").value(Integer.toString(clientRegistrations))).andExpect(jsonPath("$.clientAuthorizations").value(Integer.toString(clientAuthorizations)));
}
Also used : ClientRegistrationEntity(com.gw2auth.oauth2.server.repository.client.registration.ClientRegistrationEntity) Gw2AccountVerificationEntity(com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity) AccountEntity(com.gw2auth.oauth2.server.repository.account.AccountEntity) LinkedList(java.util.LinkedList) ClientConsentEntity(com.gw2auth.oauth2.server.repository.client.consent.ClientConsentEntity) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 2 with Gw2AccountVerificationEntity

use of com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity in project oauth2-server by gw2auth.

the class ApiTokenControllerTest method updateApiTokenThatHasBeenVerifiedByAnotherAccount.

@WithGw2AuthLogin
public void updateApiTokenThatHasBeenVerifiedByAnotherAccount(MockHttpSession session) throws Exception {
    final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
    final long otherUserAccountId = this.accountRepository.save(new AccountEntity(null, Instant.now())).id();
    final UUID gw2AccountId = UUID.randomUUID();
    // save key for the same gw2 account id on both accounts
    this.testHelper.createApiToken(accountId, gw2AccountId, Set.of(), "Name A");
    this.testHelper.createApiToken(otherUserAccountId, gw2AccountId, Set.of(), "Name B");
    // save verification for the other account
    this.gw2AccountVerificationRepository.save(new Gw2AccountVerificationEntity(gw2AccountId, otherUserAccountId));
    this.mockMvc.perform(patch("/api/token/{gw2AccountId}", gw2AccountId).session(session).with(csrf()).queryParam("displayName", "Hello World")).andExpect(status().isNotAcceptable());
    // api token should be deleted now
    assertTrue(this.apiTokenRepository.findAllByAccountIdAndGw2AccountIds(accountId, Set.of(gw2AccountId)).isEmpty());
}
Also used : Gw2AccountVerificationEntity(com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity) AccountEntity(com.gw2auth.oauth2.server.repository.account.AccountEntity)

Example 3 with Gw2AccountVerificationEntity

use of com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity in project oauth2-server by gw2auth.

the class OAuth2ServerTest method consentSubmitWithGw2AuthVerifiedScope.

@WithGw2AuthLogin
public void consentSubmitWithGw2AuthVerifiedScope(MockHttpSession session) throws Exception {
    final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
    final ClientRegistrationCreation clientRegistrationCreation = createClientRegistration();
    final ClientRegistration clientRegistration = clientRegistrationCreation.clientRegistration();
    // perform authorization request (which should redirect to the consent page)
    MvcResult result = performAuthorizeWithClient(session, clientRegistration, List.of(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE)).andReturn();
    // submit the consent
    final String tokenA = TestHelper.randomRootToken();
    final String tokenB = TestHelper.randomRootToken();
    final String tokenC = TestHelper.randomRootToken();
    result = performSubmitConsent(session, clientRegistration, URI.create(Objects.requireNonNull(result.getResponse().getRedirectedUrl())), tokenA, tokenB, tokenC).andReturn();
    // verify the consent has been saved
    final ClientConsentEntity clientConsentEntity = this.clientConsentRepository.findByAccountIdAndClientRegistrationId(accountId, clientRegistration.id()).orElse(null);
    assertNotNull(clientConsentEntity);
    assertEquals(Set.of(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE), clientConsentEntity.authorizedScopes());
    // verify the authorization has been saved
    final List<ClientAuthorizationEntity> authorizations = this.clientAuthorizationRepository.findAllByAccountIdAndClientRegistrationId(accountId, clientConsentEntity.clientRegistrationId());
    assertEquals(1, authorizations.size());
    final ClientAuthorizationEntity clientAuthorization = authorizations.get(0);
    assertEquals(Set.of(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE), clientAuthorization.authorizedScopes());
    List<ClientAuthorizationTokenEntity> clientAuthorizationTokenEntities = this.clientAuthorizationTokenRepository.findAllByAccountIdAndClientAuthorizationId(accountId, clientAuthorization.id());
    assertEquals(2, clientAuthorizationTokenEntities.size());
    // save account verification for one account
    this.gw2AccountVerificationRepository.save(new Gw2AccountVerificationEntity(this.gw2AccountId1st, accountId));
    // set testing clock to token customizer
    Clock testingClock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
    this.oAuth2TokenCustomizerService.setClock(testingClock);
    // retrieve the initial access and refresh token
    final String[] dummySubtokenA = new String[] { TestHelper.createSubtokenJWT(this.gw2AccountId1st, Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant(), Duration.ofMinutes(30L)) };
    final String[] dummySubtokenB = new String[] { TestHelper.createSubtokenJWT(this.gw2AccountId2nd, Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant(), Duration.ofMinutes(30L)) };
    result = performRetrieveTokenByCode(clientRegistrationCreation, URI.create(Objects.requireNonNull(result.getResponse().getRedirectedUrl())), Map.of(tokenA, dummySubtokenA[0], tokenB, dummySubtokenB[0]), Set.of(Gw2ApiPermission.ACCOUNT)).andExpectAll(expectValidTokenResponse(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE)).andReturn();
    // verify the authorized tokens have been updated
    Set<String> savedSubtokens = this.apiSubTokenRepository.findAllByAccountIdGw2AccountIdsAndGw2ApiPermissionsBitSet(accountId, Set.of(this.gw2AccountId1st, this.gw2AccountId2nd), Gw2ApiPermission.toBitSet(Set.of(Gw2ApiPermission.ACCOUNT))).stream().map(ApiSubTokenEntity::gw2ApiSubtoken).collect(Collectors.toSet());
    assertEquals(2, savedSubtokens.size());
    assertTrue(savedSubtokens.contains(dummySubtokenA[0]));
    assertTrue(savedSubtokens.contains(dummySubtokenB[0]));
    // verify the validity status has been saved
    final List<ApiTokenEntity> apiTokenEntities = this.apiTokenRepository.findAllByAccountIdAndGw2AccountIds(accountId, Set.of(this.gw2AccountId1st, this.gw2AccountId2nd));
    assertEquals(2, apiTokenEntities.size());
    assertTrue(apiTokenEntities.get(0).isValid());
    assertInstantEquals(testingClock.instant(), apiTokenEntities.get(0).lastValidCheckTime());
    assertTrue(apiTokenEntities.get(1).isValid());
    assertInstantEquals(testingClock.instant(), apiTokenEntities.get(1).lastValidCheckTime());
    // verify the access token
    JsonNode tokenResponse = assertTokenResponse(result, () -> Map.of(this.gw2AccountId1st, new com.nimbusds.jose.shaded.json.JSONObject(Map.of("name", "First", "token", dummySubtokenA[0], "verified", true)), this.gw2AccountId2nd, new com.nimbusds.jose.shaded.json.JSONObject(Map.of("name", "Second", "token", dummySubtokenB[0], "verified", false))));
    // remove the verification for the first account and save one for the second
    this.gw2AccountVerificationRepository.deleteById(this.gw2AccountId1st);
    this.gw2AccountVerificationRepository.save(new Gw2AccountVerificationEntity(this.gw2AccountId2nd, accountId));
    // retrieve a new access token using the refresh token
    final String refreshToken = tokenResponse.get("refresh_token").textValue();
    result = performRetrieveTokensByRefreshToken(clientRegistrationCreation, refreshToken).andExpectAll(expectValidTokenResponse(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE)).andReturn();
    tokenResponse = assertTokenResponse(result, () -> Map.of(this.gw2AccountId1st, new com.nimbusds.jose.shaded.json.JSONObject(Map.of("name", "First", "token", dummySubtokenA[0], "verified", false)), this.gw2AccountId2nd, new com.nimbusds.jose.shaded.json.JSONObject(Map.of("name", "Second", "token", dummySubtokenB[0], "verified", true))));
}
Also used : ApiTokenEntity(com.gw2auth.oauth2.server.repository.apitoken.ApiTokenEntity) JsonNode(com.fasterxml.jackson.databind.JsonNode) MvcResult(org.springframework.test.web.servlet.MvcResult) Clock(java.time.Clock) Gw2AccountVerificationEntity(com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity) ClientRegistrationCreation(com.gw2auth.oauth2.server.service.client.registration.ClientRegistrationCreation) ClientAuthorizationEntity(com.gw2auth.oauth2.server.repository.client.authorization.ClientAuthorizationEntity) ClientRegistration(com.gw2auth.oauth2.server.service.client.registration.ClientRegistration) JSONObject(org.json.JSONObject) ClientAuthorizationTokenEntity(com.gw2auth.oauth2.server.repository.client.authorization.ClientAuthorizationTokenEntity) ClientConsentEntity(com.gw2auth.oauth2.server.repository.client.consent.ClientConsentEntity)

Example 4 with Gw2AccountVerificationEntity

use of com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity in project oauth2-server by gw2auth.

the class VerificationControllerTest method startAndSubmitApiTokenNameChallengeLaterFulfilled.

@WithGw2AuthLogin
public void startAndSubmitApiTokenNameChallengeLaterFulfilled(MockHttpSession session) throws Exception {
    final UUID gw2AccountId = UUID.randomUUID();
    // insert an api token for another account but for the same gw2 account id
    final long otherUserAccountId = this.accountRepository.save(new AccountEntity(null, Instant.now())).id();
    this.testHelper.createApiToken(otherUserAccountId, gw2AccountId, Set.of(), "Name");
    final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
    // prepare the testing clock
    Clock testingClock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
    this.verificationService.setClock(testingClock);
    final String gw2ApiToken = TestHelper.randomRootToken();
    final String gw2ApiSubtoken = TestHelper.createSubtokenJWT(UUID.randomUUID(), Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant(), Duration.ofMinutes(90L));
    // prepare the gw2 api
    this.gw2RestServer.reset();
    preparedGw2RestServerForCreateSubtoken(gw2ApiToken, gw2ApiSubtoken, Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant().plus(Duration.ofMinutes(90L)));
    preparedGw2RestServerForAccountRequest(gw2AccountId, gw2ApiSubtoken);
    prepareGw2RestServerForTokenInfoRequest(gw2ApiSubtoken, "Not the name that was requested", Set.of(Gw2ApiPermission.ACCOUNT));
    // start the challenge
    final VerificationChallengeStart challengeStart = this.verificationService.startChallenge(accountId, 1L);
    // submit the challenge
    this.mockMvc.perform(post("/api/verification/pending").session(session).with(csrf()).queryParam("token", gw2ApiToken)).andExpect(status().isOk()).andExpect(jsonPath("$.isSuccess").value("false")).andExpect(jsonPath("$.pending").isMap());
    // started challenge should be removed
    assertTrue(this.gw2AccountVerificationChallengeRepository.findByAccountIdAndGw2AccountId(accountId, "").isEmpty());
    // pending challenge should be inserted
    assertTrue(this.gw2AccountVerificationChallengeRepository.findByAccountIdAndGw2AccountId(accountId, gw2AccountId.toString()).isPresent());
    // let 15 minutes pass
    testingClock = Clock.offset(testingClock, Duration.ofMinutes(15L));
    this.verificationService.setClock(testingClock);
    // prepare the api again and now set the name to the requested one
    this.gw2RestServer.reset();
    prepareGw2RestServerForTokenInfoRequest(gw2ApiSubtoken, challengeStart.message().get("apiTokenName").toString(), Set.of(Gw2ApiPermission.ACCOUNT));
    // simulate scheduled check
    this.verificationService.tryVerifyAllPending();
    // pending challenge should be removed
    assertTrue(this.gw2AccountVerificationChallengeRepository.findByAccountIdAndGw2AccountId(accountId, gw2AccountId.toString()).isEmpty());
    // account should now be verified
    final Gw2AccountVerificationEntity accountVerification = this.gw2AccountVerificationRepository.findById(gw2AccountId).orElse(null);
    assertNotNull(accountVerification);
    assertEquals(accountId, accountVerification.accountId());
    // the other users api token should be removed
    assertTrue(this.apiTokenRepository.findByAccountIdAndGw2AccountId(otherUserAccountId, gw2AccountId).isEmpty());
}
Also used : VerificationChallengeStart(com.gw2auth.oauth2.server.service.verification.VerificationChallengeStart) UUID(java.util.UUID) Clock(java.time.Clock) Gw2AccountVerificationEntity(com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity) AccountEntity(com.gw2auth.oauth2.server.repository.account.AccountEntity)

Example 5 with Gw2AccountVerificationEntity

use of com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity in project oauth2-server by gw2auth.

the class VerificationControllerTest method startAndSubmitApiTokenNameChallengeDirectlyFulfilled.

@WithGw2AuthLogin
public void startAndSubmitApiTokenNameChallengeDirectlyFulfilled(MockHttpSession session) throws Exception {
    final UUID gw2AccountId = UUID.randomUUID();
    // insert an api token for another account but for the same gw2 account id
    final long otherUserAccountId = this.accountRepository.save(new AccountEntity(null, Instant.now())).id();
    this.testHelper.createApiToken(otherUserAccountId, gw2AccountId, Set.of(), "Name");
    final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
    // prepare the testing clock
    Clock testingClock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
    this.verificationService.setClock(testingClock);
    final String gw2ApiToken = TestHelper.randomRootToken();
    final String gw2ApiSubtoken = TestHelper.createSubtokenJWT(UUID.randomUUID(), Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant(), Duration.ofMinutes(90L));
    // start the challenge
    final VerificationChallengeStart challengeStart = this.verificationService.startChallenge(accountId, 1L);
    // prepare the gw2 api
    this.gw2RestServer.reset();
    preparedGw2RestServerForCreateSubtoken(gw2ApiToken, gw2ApiSubtoken, Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant().plus(Duration.ofMinutes(90L)));
    preparedGw2RestServerForAccountRequest(gw2AccountId, gw2ApiSubtoken);
    prepareGw2RestServerForTokenInfoRequest(gw2ApiSubtoken, challengeStart.message().get("apiTokenName").toString(), Set.of(Gw2ApiPermission.ACCOUNT));
    // submit the challenge
    this.mockMvc.perform(post("/api/verification/pending").session(session).with(csrf()).queryParam("token", gw2ApiToken)).andExpect(status().isOk()).andExpect(jsonPath("$.isSuccess").value("true"));
    // started challenge should be removed
    assertTrue(this.gw2AccountVerificationChallengeRepository.findByAccountIdAndGw2AccountId(accountId, "").isEmpty());
    // pending challenge should not be present (either removed or never inserted)
    assertTrue(this.gw2AccountVerificationChallengeRepository.findByAccountIdAndGw2AccountId(accountId, gw2AccountId.toString()).isEmpty());
    // account should now be verified
    final Gw2AccountVerificationEntity accountVerification = this.gw2AccountVerificationRepository.findById(gw2AccountId).orElse(null);
    assertNotNull(accountVerification);
    assertEquals(accountId, accountVerification.accountId());
    // the other users api token should be removed
    assertTrue(this.apiTokenRepository.findByAccountIdAndGw2AccountId(otherUserAccountId, gw2AccountId).isEmpty());
}
Also used : VerificationChallengeStart(com.gw2auth.oauth2.server.service.verification.VerificationChallengeStart) UUID(java.util.UUID) Clock(java.time.Clock) Gw2AccountVerificationEntity(com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity) AccountEntity(com.gw2auth.oauth2.server.repository.account.AccountEntity)

Aggregations

Gw2AccountVerificationEntity (com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity)8 AccountEntity (com.gw2auth.oauth2.server.repository.account.AccountEntity)5 Clock (java.time.Clock)5 UUID (java.util.UUID)4 ClientConsentEntity (com.gw2auth.oauth2.server.repository.client.consent.ClientConsentEntity)3 VerificationChallengeStart (com.gw2auth.oauth2.server.service.verification.VerificationChallengeStart)3 ClientRegistrationEntity (com.gw2auth.oauth2.server.repository.client.registration.ClientRegistrationEntity)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 AccountFederationEntity (com.gw2auth.oauth2.server.repository.account.AccountFederationEntity)1 ApiTokenEntity (com.gw2auth.oauth2.server.repository.apitoken.ApiTokenEntity)1 ClientAuthorizationEntity (com.gw2auth.oauth2.server.repository.client.authorization.ClientAuthorizationEntity)1 ClientAuthorizationTokenEntity (com.gw2auth.oauth2.server.repository.client.authorization.ClientAuthorizationTokenEntity)1 Gw2AccountVerificationChallengeEntity (com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationChallengeEntity)1 ClientRegistration (com.gw2auth.oauth2.server.service.client.registration.ClientRegistration)1 ClientRegistrationCreation (com.gw2auth.oauth2.server.service.client.registration.ClientRegistrationCreation)1 Gw2SubToken (com.gw2auth.oauth2.server.service.gw2.Gw2SubToken)1 Duration (java.time.Duration)1 Instant (java.time.Instant)1 LinkedList (java.util.LinkedList)1 JSONObject (org.json.JSONObject)1