Search in sources :

Example 6 with UserConfiguration

use of org.apache.jackrabbit.oak.spi.security.user.UserConfiguration in project jackrabbit-oak by apache.

the class RepositoryUpgrade method copy.

/**
     * Copies the full content from the source to the target repository.
     * <p>
     * The source repository <strong>must not be modified</strong> while
     * the copy operation is running to avoid an inconsistent copy.
     * <p>
     * Note that both the source and the target repository must be closed
     * during the copy operation as this method requires exclusive access
     * to the repositories.
     *
     * @param initializer optional extra repository initializer to use
     * @throws RepositoryException if the copy operation fails
     */
public void copy(RepositoryInitializer initializer) throws RepositoryException {
    if (checkLongNames) {
        assertNoLongNames();
    }
    RepositoryConfig config = source.getRepositoryConfig();
    logger.info("Copying repository content from {} to Oak", config.getHomeDir());
    try {
        NodeBuilder targetBuilder = target.getRoot().builder();
        if (VersionHistoryUtil.getVersionStorage(targetBuilder).exists() && !versionCopyConfiguration.skipOrphanedVersionsCopy()) {
            logger.warn("The version storage on destination already exists. Orphaned version histories will be skipped.");
            versionCopyConfiguration.setCopyOrphanedVersions(null);
        }
        final Root upgradeRoot = new UpgradeRoot(targetBuilder);
        String workspaceName = source.getRepositoryConfig().getDefaultWorkspaceName();
        SecurityProviderImpl security = new SecurityProviderImpl(mapSecurityConfig(config.getSecurityConfig()));
        if (skipInitialization) {
            logger.info("Skipping the repository initialization");
        } else {
            // init target repository first
            logger.info("Initializing initial repository content from {}", config.getHomeDir());
            new InitialContent().initialize(targetBuilder);
            if (initializer != null) {
                initializer.initialize(targetBuilder);
            }
            logger.debug("InitialContent completed from {}", config.getHomeDir());
            for (SecurityConfiguration sc : security.getConfigurations()) {
                RepositoryInitializer ri = sc.getRepositoryInitializer();
                ri.initialize(targetBuilder);
                logger.debug("Repository initializer '" + ri.getClass().getName() + "' completed", config.getHomeDir());
            }
            for (SecurityConfiguration sc : security.getConfigurations()) {
                WorkspaceInitializer wi = sc.getWorkspaceInitializer();
                wi.initialize(targetBuilder, workspaceName);
                logger.debug("Workspace initializer '" + wi.getClass().getName() + "' completed", config.getHomeDir());
            }
        }
        HashBiMap<String, String> uriToPrefix = HashBiMap.create();
        logger.info("Copying registered namespaces");
        copyNamespaces(targetBuilder, uriToPrefix);
        logger.debug("Namespace registration completed.");
        if (skipInitialization) {
            logger.info("Skipping registering node types and privileges");
        } else {
            logger.info("Copying registered node types");
            NodeTypeManager ntMgr = new ReadWriteNodeTypeManager() {

                @Override
                protected Tree getTypes() {
                    return upgradeRoot.getTree(NODE_TYPES_PATH);
                }

                @Nonnull
                @Override
                protected Root getWriteRoot() {
                    return upgradeRoot;
                }
            };
            copyNodeTypes(ntMgr, new ValueFactoryImpl(upgradeRoot, NamePathMapper.DEFAULT));
            logger.debug("Node type registration completed.");
            // migrate privileges
            logger.info("Copying registered privileges");
            PrivilegeConfiguration privilegeConfiguration = security.getConfiguration(PrivilegeConfiguration.class);
            copyCustomPrivileges(privilegeConfiguration.getPrivilegeManager(upgradeRoot, NamePathMapper.DEFAULT));
            logger.debug("Privilege registration completed.");
            // Triggers compilation of type information, which we need for
            // the type predicates used by the bulk  copy operations below.
            new TypeEditorProvider(false).getRootEditor(targetBuilder.getBaseState(), targetBuilder.getNodeState(), targetBuilder, null);
        }
        final NodeState reportingSourceRoot = ReportingNodeState.wrap(JackrabbitNodeState.createRootNodeState(source, workspaceName, targetBuilder.getNodeState(), uriToPrefix, copyBinariesByReference, skipOnError), new LoggingReporter(logger, "Migrating", LOG_NODE_COPY, -1));
        final NodeState sourceRoot;
        if (filterLongNames) {
            sourceRoot = NameFilteringNodeState.wrap(reportingSourceRoot);
        } else {
            sourceRoot = reportingSourceRoot;
        }
        final Stopwatch watch = Stopwatch.createStarted();
        logger.info("Copying workspace content");
        copyWorkspace(sourceRoot, targetBuilder, workspaceName);
        // on TarMK this does call triggers the actual copy
        targetBuilder.getNodeState();
        logger.info("Upgrading workspace content completed in {}s ({})", watch.elapsed(TimeUnit.SECONDS), watch);
        if (!versionCopyConfiguration.skipOrphanedVersionsCopy()) {
            logger.info("Copying version storage");
            watch.reset().start();
            copyVersionStorage(targetBuilder, getVersionStorage(sourceRoot), getVersionStorage(targetBuilder), versionCopyConfiguration);
            // on TarMK this does call triggers the actual copy
            targetBuilder.getNodeState();
            logger.info("Version storage copied in {}s ({})", watch.elapsed(TimeUnit.SECONDS), watch);
        } else {
            logger.info("Skipping the version storage as the copyOrphanedVersions is set to false");
        }
        watch.reset().start();
        logger.info("Applying default commit hooks");
        // TODO: default hooks?
        List<CommitHook> hooks = newArrayList();
        UserConfiguration userConf = security.getConfiguration(UserConfiguration.class);
        String groupsPath = userConf.getParameters().getConfigValue(UserConstants.PARAM_GROUP_PATH, UserConstants.DEFAULT_GROUP_PATH);
        String usersPath = userConf.getParameters().getConfigValue(UserConstants.PARAM_USER_PATH, UserConstants.DEFAULT_USER_PATH);
        // hooks specific to the upgrade, need to run first
        hooks.add(new EditorHook(new CompositeEditorProvider(new RestrictionEditorProvider(), new GroupEditorProvider(groupsPath), // copy referenced version histories
        new VersionableEditor.Provider(sourceRoot, workspaceName, versionCopyConfiguration), new SameNameSiblingsEditor.Provider(), AuthorizableFolderEditor.provider(groupsPath, usersPath))));
        // this editor works on the VersionableEditor output, so it can't be
        // a part of the same EditorHook
        hooks.add(new EditorHook(new VersionablePropertiesEditor.Provider()));
        // security-related hooks
        for (SecurityConfiguration sc : security.getConfigurations()) {
            hooks.addAll(sc.getCommitHooks(workspaceName));
        }
        if (customCommitHooks != null) {
            hooks.addAll(customCommitHooks);
        }
        // type validation, reference and indexing hooks
        hooks.add(new EditorHook(new CompositeEditorProvider(createTypeEditorProvider(), createIndexEditorProvider())));
        target.merge(targetBuilder, new LoggingCompositeHook(hooks, source, overrideEarlyShutdown()), CommitInfo.EMPTY);
        logger.info("Processing commit hooks completed in {}s ({})", watch.elapsed(TimeUnit.SECONDS), watch);
        logger.debug("Repository upgrade completed.");
    } catch (Exception e) {
        throw new RepositoryException("Failed to copy content", e);
    }
}
Also used : NodeTypeManager(javax.jcr.nodetype.NodeTypeManager) ReadWriteNodeTypeManager(org.apache.jackrabbit.oak.plugins.nodetype.write.ReadWriteNodeTypeManager) NameFilteringNodeState(org.apache.jackrabbit.oak.upgrade.nodestate.NameFilteringNodeState) ReportingNodeState(org.apache.jackrabbit.oak.upgrade.nodestate.report.ReportingNodeState) NodeState(org.apache.jackrabbit.oak.spi.state.NodeState) ValueFactoryImpl(org.apache.jackrabbit.oak.plugins.value.jcr.ValueFactoryImpl) Stopwatch(com.google.common.base.Stopwatch) LoggingReporter(org.apache.jackrabbit.oak.upgrade.nodestate.report.LoggingReporter) NodeBuilder(org.apache.jackrabbit.oak.spi.state.NodeBuilder) EditorHook(org.apache.jackrabbit.oak.spi.commit.EditorHook) VersionableEditor(org.apache.jackrabbit.oak.upgrade.version.VersionableEditor) SecurityProviderImpl(org.apache.jackrabbit.oak.security.SecurityProviderImpl) PrivilegeConfiguration(org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConfiguration) UserConfiguration(org.apache.jackrabbit.oak.spi.security.user.UserConfiguration) RepositoryConfig(org.apache.jackrabbit.core.config.RepositoryConfig) ReadWriteNodeTypeManager(org.apache.jackrabbit.oak.plugins.nodetype.write.ReadWriteNodeTypeManager) CompositeEditorProvider(org.apache.jackrabbit.oak.spi.commit.CompositeEditorProvider) RestrictionEditorProvider(org.apache.jackrabbit.oak.upgrade.security.RestrictionEditorProvider) Root(org.apache.jackrabbit.oak.api.Root) CommitHook(org.apache.jackrabbit.oak.spi.commit.CommitHook) RepositoryException(javax.jcr.RepositoryException) FileSystemException(org.apache.jackrabbit.core.fs.FileSystemException) IOException(java.io.IOException) CommitFailedException(org.apache.jackrabbit.oak.api.CommitFailedException) RepositoryException(javax.jcr.RepositoryException) NamespaceException(javax.jcr.NamespaceException) PropertyIndexEditorProvider(org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexEditorProvider) EditorProvider(org.apache.jackrabbit.oak.spi.commit.EditorProvider) IndexEditorProvider(org.apache.jackrabbit.oak.plugins.index.IndexEditorProvider) CompositeEditorProvider(org.apache.jackrabbit.oak.spi.commit.CompositeEditorProvider) RestrictionEditorProvider(org.apache.jackrabbit.oak.upgrade.security.RestrictionEditorProvider) GroupEditorProvider(org.apache.jackrabbit.oak.upgrade.security.GroupEditorProvider) ReferenceEditorProvider(org.apache.jackrabbit.oak.plugins.index.reference.ReferenceEditorProvider) TypeEditorProvider(org.apache.jackrabbit.oak.plugins.nodetype.TypeEditorProvider) CompositeIndexEditorProvider(org.apache.jackrabbit.oak.plugins.index.CompositeIndexEditorProvider) InitialContent(org.apache.jackrabbit.oak.InitialContent) WorkspaceInitializer(org.apache.jackrabbit.oak.spi.lifecycle.WorkspaceInitializer) TypeEditorProvider(org.apache.jackrabbit.oak.plugins.nodetype.TypeEditorProvider) GroupEditorProvider(org.apache.jackrabbit.oak.upgrade.security.GroupEditorProvider) SecurityConfiguration(org.apache.jackrabbit.oak.spi.security.SecurityConfiguration) RepositoryInitializer(org.apache.jackrabbit.oak.spi.lifecycle.RepositoryInitializer)

Example 7 with UserConfiguration

use of org.apache.jackrabbit.oak.spi.security.user.UserConfiguration in project jackrabbit-oak by apache.

the class UserInitializerTest method testAnonymousConfiguration.

/**
     * @since OAK 1.0 The anonymous user is optional.
     */
@Test
public void testAnonymousConfiguration() throws Exception {
    Map<String, Object> userParams = new HashMap();
    userParams.put(UserConstants.PARAM_ANONYMOUS_ID, "");
    ConfigurationParameters params = ConfigurationParameters.of(UserConfiguration.NAME, ConfigurationParameters.of(userParams));
    SecurityProvider sp = new SecurityProviderImpl(params);
    final ContentRepository repo = new Oak().with(new InitialContent()).with(new PropertyIndexEditorProvider()).with(new PropertyIndexProvider()).with(new TypeEditorProvider()).with(sp).createContentRepository();
    ContentSession cs = Subject.doAs(SystemSubject.INSTANCE, new PrivilegedExceptionAction<ContentSession>() {

        @Override
        public ContentSession run() throws Exception {
            return repo.login(null, null);
        }
    });
    try {
        Root root = cs.getLatestRoot();
        UserConfiguration uc = sp.getConfiguration(UserConfiguration.class);
        UserManager umgr = uc.getUserManager(root, NamePathMapper.DEFAULT);
        Authorizable anonymous = umgr.getAuthorizable(UserConstants.DEFAULT_ANONYMOUS_ID);
        assertNull(anonymous);
    } finally {
        cs.close();
    }
    // login as admin should fail
    ContentSession anonymousSession = null;
    try {
        anonymousSession = repo.login(new GuestCredentials(), null);
        fail();
    } catch (LoginException e) {
    //success
    } finally {
        if (anonymousSession != null) {
            anonymousSession.close();
        }
    }
}
Also used : Root(org.apache.jackrabbit.oak.api.Root) HashMap(java.util.HashMap) PropertyIndexEditorProvider(org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexEditorProvider) ConfigurationParameters(org.apache.jackrabbit.oak.spi.security.ConfigurationParameters) LoginException(javax.security.auth.login.LoginException) InitialContent(org.apache.jackrabbit.oak.InitialContent) PropertyIndexProvider(org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexProvider) TypeEditorProvider(org.apache.jackrabbit.oak.plugins.nodetype.TypeEditorProvider) UserManager(org.apache.jackrabbit.api.security.user.UserManager) SecurityProvider(org.apache.jackrabbit.oak.spi.security.SecurityProvider) ContentRepository(org.apache.jackrabbit.oak.api.ContentRepository) Oak(org.apache.jackrabbit.oak.Oak) ContentSession(org.apache.jackrabbit.oak.api.ContentSession) Authorizable(org.apache.jackrabbit.api.security.user.Authorizable) LoginException(javax.security.auth.login.LoginException) SecurityProviderImpl(org.apache.jackrabbit.oak.security.SecurityProviderImpl) GuestCredentials(javax.jcr.GuestCredentials) UserConfiguration(org.apache.jackrabbit.oak.spi.security.user.UserConfiguration) AbstractSecurityTest(org.apache.jackrabbit.oak.AbstractSecurityTest) Test(org.junit.Test)

Example 8 with UserConfiguration

use of org.apache.jackrabbit.oak.spi.security.user.UserConfiguration in project jackrabbit-oak by apache.

the class AbstractLoginModule method getUserManager.

/**
     * Retrieves the {@link UserManager} that should be used to handle
     * this authentication. If no user manager has been configure this
     * method returns {@code null}.
     *
     * @return A instance of {@code UserManager} or {@code null}.
     */
@CheckForNull
protected UserManager getUserManager() {
    UserManager userManager = null;
    SecurityProvider sp = getSecurityProvider();
    Root r = getRoot();
    if (r != null && sp != null) {
        UserConfiguration uc = securityProvider.getConfiguration(UserConfiguration.class);
        userManager = uc.getUserManager(r, NamePathMapper.DEFAULT);
    }
    if (userManager == null && callbackHandler != null) {
        try {
            UserManagerCallback userCallBack = new UserManagerCallback();
            callbackHandler.handle(new Callback[] { userCallBack });
            userManager = userCallBack.getUserManager();
        } catch (IOException | UnsupportedCallbackException e) {
            log.debug(e.getMessage());
        }
    }
    return userManager;
}
Also used : UserManagerCallback(org.apache.jackrabbit.oak.spi.security.authentication.callback.UserManagerCallback) Root(org.apache.jackrabbit.oak.api.Root) UserManager(org.apache.jackrabbit.api.security.user.UserManager) SecurityProvider(org.apache.jackrabbit.oak.spi.security.SecurityProvider) IOException(java.io.IOException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) UserConfiguration(org.apache.jackrabbit.oak.spi.security.user.UserConfiguration) CheckForNull(javax.annotation.CheckForNull)

Example 9 with UserConfiguration

use of org.apache.jackrabbit.oak.spi.security.user.UserConfiguration in project jackrabbit-oak by apache.

the class UserInitializer method initialize.

//-----------------------------------------------< WorkspaceInitializer >---
@Override
public void initialize(NodeBuilder builder, String workspaceName) {
    // squeeze node state before it is passed to store (OAK-2411)
    NodeState base = squeeze(builder.getNodeState());
    MemoryNodeStore store = new MemoryNodeStore(base);
    Root root = RootFactory.createSystemRoot(store, EmptyHook.INSTANCE, workspaceName, securityProvider, null, new CompositeQueryIndexProvider(new PropertyIndexProvider(), new NodeTypeIndexProvider()));
    UserConfiguration userConfiguration = securityProvider.getConfiguration(UserConfiguration.class);
    UserManager userManager = userConfiguration.getUserManager(root, NamePathMapper.DEFAULT);
    String errorMsg = "Failed to initialize user content.";
    try {
        Tree rootTree = root.getTree(PathUtils.ROOT_PATH);
        checkState(rootTree.exists());
        Tree index = TreeUtil.getOrAddChild(rootTree, IndexConstants.INDEX_DEFINITIONS_NAME, JcrConstants.NT_UNSTRUCTURED);
        if (!index.hasChild("authorizableId")) {
            Tree authorizableId = IndexUtils.createIndexDefinition(index, "authorizableId", true, new String[] { REP_AUTHORIZABLE_ID }, new String[] { NT_REP_AUTHORIZABLE });
            authorizableId.setProperty("info", "Oak index used by the user management " + "to enforce uniqueness of rep:authorizableId property values.");
        }
        if (!index.hasChild("principalName")) {
            Tree principalName = IndexUtils.createIndexDefinition(index, "principalName", true, new String[] { REP_PRINCIPAL_NAME }, new String[] { NT_REP_AUTHORIZABLE });
            principalName.setProperty("info", "Oak index used by the user management " + "to enforce uniqueness of rep:principalName property values, " + "and to quickly search a principal by name if it was constructed manually.");
        }
        if (!index.hasChild("repMembers")) {
            Tree members = IndexUtils.createIndexDefinition(index, "repMembers", false, new String[] { REP_MEMBERS }, new String[] { NT_REP_MEMBER_REFERENCES });
            members.setProperty("info", "Oak index used by the user management to lookup group membership.");
        }
        ConfigurationParameters params = userConfiguration.getParameters();
        String adminId = params.getConfigValue(PARAM_ADMIN_ID, DEFAULT_ADMIN_ID);
        if (userManager.getAuthorizable(adminId) == null) {
            boolean omitPw = params.getConfigValue(PARAM_OMIT_ADMIN_PW, false);
            userManager.createUser(adminId, (omitPw) ? null : adminId);
        }
        String anonymousId = Strings.emptyToNull(params.getConfigValue(PARAM_ANONYMOUS_ID, DEFAULT_ANONYMOUS_ID, String.class));
        if (anonymousId != null && userManager.getAuthorizable(anonymousId) == null) {
            userManager.createUser(anonymousId, null);
        }
        if (root.hasPendingChanges()) {
            root.commit();
        }
    } catch (RepositoryException | CommitFailedException e) {
        log.error(errorMsg, e);
        throw new RuntimeException(e);
    }
    NodeState target = store.getRoot();
    target.compareAgainstBaseState(base, new ApplyDiff(builder));
}
Also used : ApplyDiff(org.apache.jackrabbit.oak.spi.state.ApplyDiff) NodeState(org.apache.jackrabbit.oak.spi.state.NodeState) NodeTypeIndexProvider(org.apache.jackrabbit.oak.plugins.index.nodetype.NodeTypeIndexProvider) Root(org.apache.jackrabbit.oak.api.Root) CompositeQueryIndexProvider(org.apache.jackrabbit.oak.spi.query.CompositeQueryIndexProvider) RepositoryException(javax.jcr.RepositoryException) ConfigurationParameters(org.apache.jackrabbit.oak.spi.security.ConfigurationParameters) PropertyIndexProvider(org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexProvider) MemoryNodeStore(org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore) UserManager(org.apache.jackrabbit.api.security.user.UserManager) Tree(org.apache.jackrabbit.oak.api.Tree) CommitFailedException(org.apache.jackrabbit.oak.api.CommitFailedException) UserConfiguration(org.apache.jackrabbit.oak.spi.security.user.UserConfiguration)

Example 10 with UserConfiguration

use of org.apache.jackrabbit.oak.spi.security.user.UserConfiguration in project jackrabbit-oak by apache.

the class SecurityProviderImplTest method testUnBindUserConfiguration.

@Test
public void testUnBindUserConfiguration() {
    UserConfiguration uc = Mockito.mock(UserConfiguration.class);
    securityProvider.bindUserConfiguration(uc);
    securityProvider.unbindUserConfiguration(uc);
    assertNull(securityProvider.getConfiguration(UserConfiguration.class));
    for (SecurityConfiguration sc : securityProvider.getConfigurations()) {
        if (sc instanceof UserConfiguration) {
            fail();
        }
    }
}
Also used : SecurityConfiguration(org.apache.jackrabbit.oak.spi.security.SecurityConfiguration) UserConfiguration(org.apache.jackrabbit.oak.spi.security.user.UserConfiguration) Test(org.junit.Test)

Aggregations

UserConfiguration (org.apache.jackrabbit.oak.spi.security.user.UserConfiguration)15 Root (org.apache.jackrabbit.oak.api.Root)7 Test (org.junit.Test)7 UserManager (org.apache.jackrabbit.api.security.user.UserManager)4 AbstractSecurityTest (org.apache.jackrabbit.oak.AbstractSecurityTest)4 SecurityProvider (org.apache.jackrabbit.oak.spi.security.SecurityProvider)4 InitialContent (org.apache.jackrabbit.oak.InitialContent)3 PropertyIndexEditorProvider (org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexEditorProvider)3 PropertyIndexProvider (org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexProvider)3 TypeEditorProvider (org.apache.jackrabbit.oak.plugins.nodetype.TypeEditorProvider)3 SecurityProviderImpl (org.apache.jackrabbit.oak.security.SecurityProviderImpl)3 SecurityConfiguration (org.apache.jackrabbit.oak.spi.security.SecurityConfiguration)3 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 CheckForNull (javax.annotation.CheckForNull)2 Nonnull (javax.annotation.Nonnull)2 GuestCredentials (javax.jcr.GuestCredentials)2 RepositoryException (javax.jcr.RepositoryException)2 SimpleCredentials (javax.jcr.SimpleCredentials)2 LoginException (javax.security.auth.login.LoginException)2