Search in sources :

Example 11 with UserId

use of com.bakdata.conquery.models.identifiable.ids.specific.UserId in project conquery by bakdata.

the class IntrospectionDelegatingRealm method extractId.

private static UserId extractId(TokenIntrospectionSuccessResponse successResponse) {
    String identifier = successResponse.getUsername();
    if (StringUtils.isBlank(identifier)) {
        identifier = successResponse.getStringParameter("preferred_username");
    }
    if (StringUtils.isBlank(identifier)) {
        identifier = successResponse.getStringParameter("email");
    }
    if (StringUtils.isBlank(identifier)) {
        throw new IllegalStateException("Unable to retrieve a user identifier from validated token. Dismissing the token.");
    }
    UserId userId = new UserId(identifier);
    log.trace("Extracted UserId {}", userId);
    return userId;
}
Also used : UserId(com.bakdata.conquery.models.identifiable.ids.specific.UserId)

Example 12 with UserId

use of com.bakdata.conquery.models.identifiable.ids.specific.UserId in project conquery by bakdata.

the class JwtPkceVerifyingRealm method doGetAuthenticationInfo.

@Override
public ConqueryAuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    Optional<JwtPkceVerifyingRealmFactory.IdpConfiguration> idpConfigurationOpt = idpConfigurationSupplier.get();
    if (idpConfigurationOpt.isEmpty()) {
        log.warn("Unable to start authentication, because idp configuration is not available.");
        return null;
    }
    JwtPkceVerifyingRealmFactory.IdpConfiguration idpConfiguration = idpConfigurationOpt.get();
    log.trace("Creating token verifier");
    TokenVerifier<AccessToken> verifier = TokenVerifier.create(((BearerToken) token).getToken(), AccessToken.class).withChecks(new TokenVerifier.RealmUrlCheck(idpConfiguration.getIssuer()), TokenVerifier.SUBJECT_EXISTS_CHECK, activeVerifier).withChecks(tokenChecks).publicKey(idpConfiguration.getPublicKey()).audience(allowedAudience);
    String subject;
    log.trace("Verifying token");
    AccessToken accessToken = null;
    try {
        verifier.verify();
        accessToken = verifier.getToken();
    } catch (VerificationException e) {
        log.trace("Verification failed", e);
        throw new IncorrectCredentialsException(e);
    }
    subject = accessToken.getSubject();
    if (subject == null) {
        // Should not happen, as sub is mandatory in an access_token
        throw new UnsupportedTokenException("Unable to extract a subject from the provided token.");
    }
    log.trace("Authentication successfull for subject {}", subject);
    UserId userId = new UserId(subject);
    User user = storage.getUser(userId);
    if (user != null) {
        log.trace("Successfully authenticated user {}", userId);
        return new ConqueryAuthenticationInfo(user, token, this, true);
    }
    // Try alternative ids
    List<UserId> alternativeIds = new ArrayList<>();
    for (String alternativeIdClaim : alternativeIdClaims) {
        Object altId = accessToken.getOtherClaims().get(alternativeIdClaim);
        if (!(altId instanceof String)) {
            log.trace("Found no value for alternative id claim {}", alternativeIdClaim);
            continue;
        }
        userId = new UserId((String) altId);
        user = storage.getUser(userId);
        if (user != null) {
            log.trace("Successfully mapped subject {} using user id {}", subject, userId);
            return new ConqueryAuthenticationInfo(user, token, this, true);
        }
    }
    throw new UnknownAccountException("The user id was unknown: " + subject);
}
Also used : User(com.bakdata.conquery.models.auth.entities.User) ArrayList(java.util.ArrayList) UnsupportedTokenException(org.apache.shiro.authc.pam.UnsupportedTokenException) JwtPkceVerifyingRealmFactory(com.bakdata.conquery.models.config.auth.JwtPkceVerifyingRealmFactory) AccessToken(org.keycloak.representations.AccessToken) UserId(com.bakdata.conquery.models.identifiable.ids.specific.UserId) ConqueryAuthenticationInfo(com.bakdata.conquery.models.auth.ConqueryAuthenticationInfo) VerificationException(org.keycloak.common.VerificationException)

Example 13 with UserId

use of com.bakdata.conquery.models.identifiable.ids.specific.UserId in project conquery by bakdata.

the class AuthorizationController method flatCopyUser.

/**
 * Creates a copy of an existing user. The copied user has the same effective permissions as the original user
 * at the time of copying, but these are flatted. This means that the original user might hold certain permissions
 * through inheritance from roles or groups, the copy will hold the permissions directly.
 * @param originUser The user to make a flat copy of
 * @param namePrefix The prefix for the id of the new copied user
 * @return A flat copy of the referenced user
 */
public static User flatCopyUser(@NonNull User originUser, String namePrefix, @NonNull MetaStorage storage) {
    final UserId originUserId = originUser.getId();
    if (Strings.isNullOrEmpty(namePrefix)) {
        throw new IllegalArgumentException("There must be a prefix");
    }
    // Find a new user id that is not used yet
    String name = null;
    do {
        name = namePrefix + UUID.randomUUID() + originUserId.getName();
    } while (storage.getUser(new UserId(name)) != null);
    // Retrieve original user and its effective permissions
    // Copy inherited permissions
    Set<ConqueryPermission> copiedPermission = new HashSet<>();
    copiedPermission.addAll(originUser.getEffectivePermissions());
    // Give read permission to all executions the original user owned
    copiedPermission.addAll(storage.getAllExecutions().stream().filter(originUser::isOwner).map(exc -> exc.createPermission(Ability.READ.asSet())).collect(Collectors.toSet()));
    // Give read permission to all form configs the original user owned
    copiedPermission.addAll(storage.getAllFormConfigs().stream().filter(originUser::isOwner).map(conf -> conf.createPermission(Ability.READ.asSet())).collect(Collectors.toSet()));
    // Create copied user
    User copy = new User(name, originUser.getLabel(), storage);
    storage.addUser(copy);
    copy.updatePermissions(copiedPermission);
    return copy;
}
Also used : ConqueryPermission(com.bakdata.conquery.models.auth.permissions.ConqueryPermission) ProtoUser(com.bakdata.conquery.apiv1.auth.ProtoUser) User(com.bakdata.conquery.models.auth.entities.User) UserId(com.bakdata.conquery.models.identifiable.ids.specific.UserId) HashSet(java.util.HashSet)

Example 14 with UserId

use of com.bakdata.conquery.models.identifiable.ids.specific.UserId in project conquery by bakdata.

the class ApiTokenRealm method doGetAuthenticationInfo.

@Override
public ConqueryAuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (!(token instanceof ApiToken)) {
        return null;
    }
    final ApiToken apiToken = ((ApiToken) token);
    ApiTokenHash tokenHash = apiToken.hashToken();
    // Clear the token
    apiToken.clear();
    ApiTokenData tokenData = tokenStorage.get(tokenHash);
    if (tokenData == null) {
        log.trace("Unknown token, cannot map token hash to token data. Aborting authentication");
        throw new IncorrectCredentialsException();
    }
    if (LocalDate.now().isAfter(tokenData.getExpirationDate())) {
        log.info("Supplied token expired on: {}", tokenData.getExpirationDate());
        throw new ExpiredCredentialsException("Supplied token is expired");
    }
    final ApiTokenData.MetaData metaData = new ApiTokenData.MetaData(LocalDate.now());
    tokenStorage.updateMetaData(tokenData.getId(), metaData);
    final UserId userId = tokenData.getUserId();
    final User user = storage.getUser(userId);
    if (user == null) {
        throw new UnknownAccountException("The UserId does not map to a user: " + userId);
    }
    return new ConqueryAuthenticationInfo(new TokenScopedUser(user, tokenData), token, this, false);
}
Also used : IncorrectCredentialsException(org.apache.shiro.authc.IncorrectCredentialsException) User(com.bakdata.conquery.models.auth.entities.User) UserId(com.bakdata.conquery.models.identifiable.ids.specific.UserId) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) ConqueryAuthenticationInfo(com.bakdata.conquery.models.auth.ConqueryAuthenticationInfo) ExpiredCredentialsException(org.apache.shiro.authc.ExpiredCredentialsException)

Example 15 with UserId

use of com.bakdata.conquery.models.identifiable.ids.specific.UserId in project conquery by bakdata.

the class SerializingStoreDumpTest method testCorruptValueDump.

/**
 * Tests if entries with corrupted values are dumped.
 */
@Test
public void testCorruptValueDump() throws IOException {
    // Set dump directory to this tests temp-dir
    config.setUnreadableDataDumpDirectory(tmpDir);
    {
        // Open a store and insert a valid key-value pair (UserId & User)
        SerializingStore<UserId, User> store = createSerializedStore(config, env, Validators.newValidator(), USER_STORE_ID);
        store.add(user.getId(), user);
    }
    {
        // Open that store again, with a different config to insert a corrupt entry
        // (UserId & ManagedQuery)
        SerializingStore<UserId, QueryDescription> store = createSerializedStore(config, env, Validators.newValidator(), new StoreInfo<>(USER_STORE_ID.getName(), UserId.class, QueryDescription.class));
        store.add(new UserId("testU2"), cQuery);
    }
    {
        // Reopen the store with the initial value and try to iterate over all entries
        // (this triggers the dump or removal of invalid entries)
        SerializingStore<UserId, User> store = createSerializedStore(config, env, Validators.newValidator(), USER_STORE_ID);
        IterationStatistic expectedResult = new IterationStatistic();
        expectedResult.setTotalProcessed(2);
        expectedResult.setFailedKeys(0);
        expectedResult.setFailedValues(1);
        // Iterate (do nothing with the entries themselves)
        IterationStatistic result = store.forEach((k, v, s) -> {
        });
        assertThat(result).isEqualTo(expectedResult);
    }
    // Test if the correct number of dumpfiles was generated
    Condition<File> dumpFileCond = new Condition<>(f -> f.getName().endsWith(SerializingStore.DUMP_FILE_EXTENTION), "dump file");
    assertThat(tmpDir.listFiles()).areExactly(1, dumpFileCond);
    // Test if the dump is correct
    File dumpFile = getDumpFile(dumpFileCond);
    assertThat((QueryDescription) Jackson.MAPPER.readerFor(QueryDescription.class).readValue(dumpFile)).isEqualTo(cQuery);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) ManagedQuery(com.bakdata.conquery.models.query.ManagedQuery) Validators(io.dropwizard.jersey.validation.Validators) Environments(jetbrains.exodus.env.Environments) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) UserId(com.bakdata.conquery.models.identifiable.ids.specific.UserId) StoreMappings(com.bakdata.conquery.io.storage.StoreMappings) Environment(jetbrains.exodus.env.Environment) Files(com.google.common.io.Files) QueryDescription(com.bakdata.conquery.apiv1.query.QueryDescription) IterationStatistic(com.bakdata.conquery.io.storage.xodus.stores.SerializingStore.IterationStatistic) Validator(javax.validation.Validator) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) User(com.bakdata.conquery.models.auth.entities.User) File(java.io.File) Dataset(com.bakdata.conquery.models.datasets.Dataset) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) ConceptQuery(com.bakdata.conquery.apiv1.query.ConceptQuery) Slf4j(lombok.extern.slf4j.Slf4j) AfterEach(org.junit.jupiter.api.AfterEach) Condition(org.assertj.core.api.Condition) CQReusedQuery(com.bakdata.conquery.apiv1.query.concept.specific.CQReusedQuery) Jackson(com.bakdata.conquery.io.jackson.Jackson) XodusStoreFactory(com.bakdata.conquery.models.config.XodusStoreFactory) MetaStorage(com.bakdata.conquery.io.storage.MetaStorage) NonPersistentStoreFactory(com.bakdata.conquery.util.NonPersistentStoreFactory) Condition(org.assertj.core.api.Condition) UserId(com.bakdata.conquery.models.identifiable.ids.specific.UserId) IterationStatistic(com.bakdata.conquery.io.storage.xodus.stores.SerializingStore.IterationStatistic) QueryDescription(com.bakdata.conquery.apiv1.query.QueryDescription) File(java.io.File) Test(org.junit.jupiter.api.Test)

Aggregations

UserId (com.bakdata.conquery.models.identifiable.ids.specific.UserId)19 User (com.bakdata.conquery.models.auth.entities.User)10 Test (org.junit.jupiter.api.Test)10 MetaStorage (com.bakdata.conquery.io.storage.MetaStorage)4 ConqueryAuthenticationInfo (com.bakdata.conquery.models.auth.ConqueryAuthenticationInfo)4 Date (java.util.Date)4 ConceptQuery (com.bakdata.conquery.apiv1.query.ConceptQuery)3 QueryDescription (com.bakdata.conquery.apiv1.query.QueryDescription)3 CQReusedQuery (com.bakdata.conquery.apiv1.query.concept.specific.CQReusedQuery)3 Jackson (com.bakdata.conquery.io.jackson.Jackson)3 StoreMappings (com.bakdata.conquery.io.storage.StoreMappings)3 IterationStatistic (com.bakdata.conquery.io.storage.xodus.stores.SerializingStore.IterationStatistic)3 XodusStoreFactory (com.bakdata.conquery.models.config.XodusStoreFactory)3 Dataset (com.bakdata.conquery.models.datasets.Dataset)3 ManagedQuery (com.bakdata.conquery.models.query.ManagedQuery)3 NonPersistentStoreFactory (com.bakdata.conquery.util.NonPersistentStoreFactory)3 Files (com.google.common.io.Files)3 Validators (io.dropwizard.jersey.validation.Validators)3 File (java.io.File)3 IOException (java.io.IOException)3