Search in sources :

Example 11 with SecurityContext

use of org.apache.ignite.internal.processors.security.SecurityContext in project ignite by apache.

the class AuthenticationProcessorSelfTest method testProceedUsersOnJoinNode.

/**
 * @throws Exception If failed.
 */
@Test
public void testProceedUsersOnJoinNode() throws Exception {
    try (AutoCloseable ignored = withSecurityContextOnAllNodes(secCtxDflt)) {
        grid(0).context().security().createUser("test0", "test".toCharArray());
        grid(0).context().security().createUser("test1", "test".toCharArray());
        int nodeIdx = NODES_COUNT;
        startGrid(nodeIdx);
        SecurityContext secCtx0 = authenticate(grid(nodeIdx), "test0", "test");
        SecurityContext secCtx1 = authenticate(grid(nodeIdx), "test1", "test");
        assertNotNull(secCtx0);
        assertEquals("test0", secCtx0.subject().login());
        assertNotNull(secCtx1);
        assertEquals("test1", secCtx1.subject().login());
    }
}
Also used : SecurityContext(org.apache.ignite.internal.processors.security.SecurityContext) OperationSecurityContext(org.apache.ignite.internal.processors.security.OperationSecurityContext) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 12 with SecurityContext

use of org.apache.ignite.internal.processors.security.SecurityContext in project ignite by apache.

the class Authentication1kUsersNodeRestartTest method test1kUsersNodeRestartServer.

/**
 * @throws Exception If failed.
 */
@Test
public void test1kUsersNodeRestartServer() throws Exception {
    startGrid(0);
    grid(0).cluster().active(true);
    IgniteSecurity sec = grid(0).context().security();
    SecurityContext secCtxDflt = authenticate(grid(0), User.DFAULT_USER_NAME, "ignite");
    withSecurityContextOnAllNodes(secCtxDflt);
    IntStream.range(0, USERS_COUNT).parallel().forEach(i -> {
        try (AutoCloseable ignored = withSecurityContextOnAllNodes(secCtxDflt)) {
            sec.createUser("test" + i, "init".toCharArray());
        } catch (Exception e) {
            throw new IgniteException(e);
        }
    });
    IntStream.range(0, USERS_COUNT).parallel().forEach(i -> {
        try (AutoCloseable ignored = withSecurityContextOnAllNodes(secCtxDflt)) {
            sec.alterUser("test" + i, ("passwd_" + i).toCharArray());
        } catch (Exception e) {
            throw new IgniteException(e);
        }
    });
    stopGrid(0);
    startGrid(0);
    authenticate(grid(0), "ignite", "ignite");
}
Also used : IgniteSecurity(org.apache.ignite.internal.processors.security.IgniteSecurity) IgniteException(org.apache.ignite.IgniteException) SecurityContext(org.apache.ignite.internal.processors.security.SecurityContext) IgniteException(org.apache.ignite.IgniteException) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 13 with SecurityContext

use of org.apache.ignite.internal.processors.security.SecurityContext in project ignite by apache.

the class GridCachePartitionExchangeManager method onDiscoveryEvent.

/**
 * @param evt Event.
 * @param cache Discovery data cache.
 */
private void onDiscoveryEvent(DiscoveryEvent evt, DiscoCache cache) {
    ClusterNode loc = cctx.localNode();
    assert evt.type() == EVT_NODE_JOINED || evt.type() == EVT_NODE_LEFT || evt.type() == EVT_NODE_FAILED || evt.type() == EVT_DISCOVERY_CUSTOM_EVT;
    final ClusterNode n = evt.eventNode();
    GridDhtPartitionExchangeId exchId = null;
    GridDhtPartitionsExchangeFuture exchFut = null;
    if (evt.type() != EVT_DISCOVERY_CUSTOM_EVT) {
        assert evt.type() != EVT_NODE_JOINED || n.isLocal() || n.order() > loc.order() : "Node joined with smaller-than-local " + "order [newOrder=" + n.order() + ", locOrder=" + loc.order() + ", evt=" + evt + ']';
        exchId = exchangeId(n.id(), affinityTopologyVersion(evt), evt);
        ExchangeActions exchActs = null;
        boolean locJoin = evt.type() == EVT_NODE_JOINED && evt.eventNode().isLocal();
        if (locJoin) {
            LocalJoinCachesContext locJoinCtx = cctx.cache().localJoinCachesContext();
            if (locJoinCtx != null) {
                exchActs = new ExchangeActions();
                exchActs.localJoinContext(locJoinCtx);
            }
        }
        if (!n.isClient() && !n.isDaemon())
            exchActs = cctx.kernalContext().state().autoAdjustExchangeActions(exchActs);
        exchFut = exchangeFuture(exchId, evt, cache, exchActs, null);
    } else {
        DiscoveryCustomMessage customMsg = ((DiscoveryCustomEvent) evt).customMessage();
        if (customMsg instanceof ChangeGlobalStateMessage) {
            ChangeGlobalStateMessage stateChangeMsg = (ChangeGlobalStateMessage) customMsg;
            ExchangeActions exchActions = stateChangeMsg.exchangeActions();
            if (exchActions != null) {
                exchId = exchangeId(n.id(), affinityTopologyVersion(evt), evt);
                exchFut = exchangeFuture(exchId, evt, cache, exchActions, null);
                boolean baselineChanging;
                if (stateChangeMsg.forceChangeBaselineTopology())
                    baselineChanging = true;
                else {
                    DiscoveryDataClusterState state = cctx.kernalContext().state().clusterState();
                    assert state.transition() : state;
                    baselineChanging = exchActions.changedBaseline() || // Or it is the first activation.
                    state.state() != ClusterState.INACTIVE && !state.previouslyActive() && state.previousBaselineTopology() == null;
                }
                exchFut.listen(f -> onClusterStateChangeFinish(f, exchActions, baselineChanging));
            }
        } else if (customMsg instanceof DynamicCacheChangeBatch) {
            DynamicCacheChangeBatch batch = (DynamicCacheChangeBatch) customMsg;
            ExchangeActions exchActions = batch.exchangeActions();
            if (exchActions != null) {
                exchId = exchangeId(n.id(), affinityTopologyVersion(evt), evt);
                exchFut = exchangeFuture(exchId, evt, cache, exchActions, null);
            }
        } else if (customMsg instanceof CacheAffinityChangeMessage) {
            CacheAffinityChangeMessage msg = (CacheAffinityChangeMessage) customMsg;
            if (msg.exchangeId() == null) {
                if (msg.exchangeNeeded()) {
                    exchId = exchangeId(n.id(), affinityTopologyVersion(evt), evt);
                    exchFut = exchangeFuture(exchId, evt, cache, null, msg);
                }
            } else if (msg.exchangeId().topologyVersion().topologyVersion() >= cctx.discovery().localJoinEvent().topologyVersion())
                exchangeFuture(msg.exchangeId(), null, null, null, null).onAffinityChangeMessage(evt.eventNode(), msg);
        } else if (customMsg instanceof DynamicCacheChangeFailureMessage) {
            DynamicCacheChangeFailureMessage msg = (DynamicCacheChangeFailureMessage) customMsg;
            if (msg.exchangeId().topologyVersion().topologyVersion() >= affinityTopologyVersion(cctx.discovery().localJoinEvent()).topologyVersion())
                exchangeFuture(msg.exchangeId(), null, null, null, null).onDynamicCacheChangeFail(evt.eventNode(), msg);
        } else if (customMsg instanceof SnapshotDiscoveryMessage && ((SnapshotDiscoveryMessage) customMsg).needExchange()) {
            exchId = exchangeId(n.id(), affinityTopologyVersion(evt), evt);
            exchFut = exchangeFuture(exchId, evt, null, null, null);
        } else if (customMsg instanceof WalStateAbstractMessage && ((WalStateAbstractMessage) customMsg).needExchange()) {
            exchId = exchangeId(n.id(), affinityTopologyVersion(evt), evt);
            exchFut = exchangeFuture(exchId, evt, null, null, null);
        } else {
            // Process event as custom discovery task if needed.
            CachePartitionExchangeWorkerTask task = cctx.cache().exchangeTaskForCustomDiscoveryMessage(customMsg);
            if (task != null)
                exchWorker.addCustomTask(task);
        }
    }
    if (exchId != null) {
        if (log.isDebugEnabled())
            log.debug("Discovery event (will start exchange): " + exchId);
        // Event callback - without this callback future will never complete.
        exchFut.onEvent(exchId, evt, cache);
        Span span = cctx.kernalContext().tracing().create(EXCHANGE_FUTURE, evt.span());
        if (exchId != null) {
            GridDhtPartitionExchangeId exchIdf = exchId;
            span.addTag(SpanTags.tag(SpanTags.EVENT_NODE, SpanTags.ID), () -> evt.eventNode().id().toString());
            span.addTag(SpanTags.tag(SpanTags.EVENT_NODE, SpanTags.CONSISTENT_ID), () -> evt.eventNode().consistentId().toString());
            span.addTag(SpanTags.tag(SpanTags.EVENT, SpanTags.TYPE), () -> String.valueOf(evt.type()));
            span.addTag(SpanTags.tag(SpanTags.EXCHANGE, SpanTags.ID), () -> String.valueOf(exchIdf.toString()));
            span.addTag(SpanTags.tag(SpanTags.INITIAL, SpanTags.TOPOLOGY_VERSION, SpanTags.MAJOR), () -> String.valueOf(exchIdf.topologyVersion().topologyVersion()));
            span.addTag(SpanTags.tag(SpanTags.INITIAL, SpanTags.TOPOLOGY_VERSION, SpanTags.MINOR), () -> String.valueOf(exchIdf.topologyVersion().minorTopologyVersion()));
        }
        span.addTag(SpanTags.NODE_ID, () -> cctx.localNodeId().toString());
        span.addLog(() -> "Created");
        exchFut.span(span);
        // Start exchange process.
        addFuture(exchFut);
    } else {
        if (log.isDebugEnabled())
            log.debug("Do not start exchange for discovery event: " + evt);
    }
    notifyNodeFail(evt);
    // Notify indexing engine about node leave so that we can re-map coordinator accordingly.
    if (evt.type() == EVT_NODE_LEFT || evt.type() == EVT_NODE_FAILED) {
        SecurityContext secCtx = remoteSecurityContext(cctx.kernalContext());
        exchWorker.addCustomTask(new SchemaNodeLeaveExchangeWorkerTask(secCtx, evt.eventNode()));
        exchWorker.addCustomTask(new WalStateNodeLeaveExchangeTask(secCtx, evt.eventNode()));
    }
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) GridDhtPartitionsExchangeFuture(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture) ChangeGlobalStateMessage(org.apache.ignite.internal.processors.cluster.ChangeGlobalStateMessage) DiscoveryDataClusterState(org.apache.ignite.internal.processors.cluster.DiscoveryDataClusterState) GridDhtPartitionExchangeId(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionExchangeId) DiscoveryCustomMessage(org.apache.ignite.internal.managers.discovery.DiscoveryCustomMessage) DiscoveryCustomEvent(org.apache.ignite.internal.events.DiscoveryCustomEvent) Span(org.apache.ignite.internal.processors.tracing.Span) SnapshotDiscoveryMessage(org.apache.ignite.internal.processors.cache.persistence.snapshot.SnapshotDiscoveryMessage) SecurityContext(org.apache.ignite.internal.processors.security.SecurityContext) SecurityUtils.remoteSecurityContext(org.apache.ignite.internal.processors.security.SecurityUtils.remoteSecurityContext) SecurityUtils.withRemoteSecurityContext(org.apache.ignite.internal.processors.security.SecurityUtils.withRemoteSecurityContext) OperationSecurityContext(org.apache.ignite.internal.processors.security.OperationSecurityContext) SchemaNodeLeaveExchangeWorkerTask(org.apache.ignite.internal.processors.query.schema.SchemaNodeLeaveExchangeWorkerTask)

Example 14 with SecurityContext

use of org.apache.ignite.internal.processors.security.SecurityContext in project ignite by apache.

the class ValidationOnNodeJoinUtils method validateNode.

/**
 * Checks a joining node to configuration consistency.
 *
 * @param node Node.
 * @param discoData Disco data.
 * @param marsh Marsh.
 * @param ctx Context.
 * @param cacheDescProvider Cache descriptor provider.
 */
@Nullable
static IgniteNodeValidationResult validateNode(ClusterNode node, DiscoveryDataBag.JoiningNodeDiscoveryData discoData, Marshaller marsh, GridKernalContext ctx, Function<String, DynamicCacheDescriptor> cacheDescProvider) {
    if (discoData.hasJoiningNodeData() && discoData.joiningNodeData() instanceof CacheJoinNodeDiscoveryData) {
        CacheJoinNodeDiscoveryData nodeData = (CacheJoinNodeDiscoveryData) discoData.joiningNodeData();
        boolean isGridActive = ctx.state().clusterState().active();
        StringBuilder errorMsg = new StringBuilder();
        if (!node.isClient()) {
            validateRmtRegions(node, ctx).forEach(error -> {
                if (errorMsg.length() > 0)
                    errorMsg.append("\n");
                errorMsg.append(error);
            });
        }
        SecurityContext secCtx = null;
        if (ctx.security().enabled()) {
            try {
                secCtx = nodeSecurityContext(marsh, U.resolveClassLoader(ctx.config()), node);
            } catch (SecurityException se) {
                errorMsg.append(se.getMessage());
            }
        }
        for (CacheJoinNodeDiscoveryData.CacheInfo cacheInfo : nodeData.caches().values()) {
            if (secCtx != null && cacheInfo.cacheType() == CacheType.USER) {
                try (OperationSecurityContext s = ctx.security().withContext(secCtx)) {
                    GridCacheProcessor.authorizeCacheCreate(ctx.security(), cacheInfo.cacheData().config());
                } catch (SecurityException ex) {
                    if (errorMsg.length() > 0)
                        errorMsg.append("\n");
                    errorMsg.append(ex.getMessage());
                }
            }
            DynamicCacheDescriptor locDesc = cacheDescProvider.apply(cacheInfo.cacheData().config().getName());
            if (locDesc == null)
                continue;
            String joinedSchema = cacheInfo.cacheData().config().getSqlSchema();
            Collection<QueryEntity> joinedQryEntities = cacheInfo.cacheData().queryEntities();
            String locSchema = locDesc.cacheConfiguration().getSqlSchema();
            // QuerySchema is empty and schema name is null (when indexing enabled dynamically).
            if (!F.eq(joinedSchema, locSchema) && (locSchema != null || !locDesc.schema().isEmpty()) && (joinedSchema != null || !F.isEmpty(joinedQryEntities))) {
                errorMsg.append(String.format(SQL_SCHEMA_CONFLICTS_MESSAGE, locDesc.cacheName(), joinedSchema, locSchema));
            }
            QuerySchemaPatch schemaPatch = locDesc.makeSchemaPatch(joinedQryEntities);
            if (schemaPatch.hasConflicts() || (isGridActive && !schemaPatch.isEmpty())) {
                if (errorMsg.length() > 0)
                    errorMsg.append("\n");
                if (schemaPatch.hasConflicts()) {
                    errorMsg.append(String.format(MERGE_OF_CONFIG_CONFLICTS_MESSAGE, locDesc.cacheName(), schemaPatch.getConflictsMessage()));
                } else
                    errorMsg.append(String.format(MERGE_OF_CONFIG_REQUIRED_MESSAGE, locDesc.cacheName()));
            }
            // This check must be done on join, otherwise group encryption key will be
            // written to metastore regardless of validation check and could trigger WAL write failures.
            boolean locEnc = locDesc.cacheConfiguration().isEncryptionEnabled();
            boolean rmtEnc = cacheInfo.cacheData().config().isEncryptionEnabled();
            if (locEnc != rmtEnc) {
                if (errorMsg.length() > 0)
                    errorMsg.append("\n");
                // Message will be printed on remote node, so need to swap local and remote.
                errorMsg.append(String.format(ENCRYPT_MISMATCH_MESSAGE, locDesc.cacheName(), rmtEnc, locEnc));
            }
        }
        if (errorMsg.length() > 0) {
            String msg = errorMsg.toString();
            return new IgniteNodeValidationResult(node.id(), msg);
        }
    }
    return null;
}
Also used : IgniteNodeValidationResult(org.apache.ignite.spi.IgniteNodeValidationResult) SecurityException(org.apache.ignite.plugin.security.SecurityException) QueryEntity(org.apache.ignite.cache.QueryEntity) QuerySchemaPatch(org.apache.ignite.internal.processors.query.QuerySchemaPatch) OperationSecurityContext(org.apache.ignite.internal.processors.security.OperationSecurityContext) SecurityUtils.nodeSecurityContext(org.apache.ignite.internal.processors.security.SecurityUtils.nodeSecurityContext) SecurityContext(org.apache.ignite.internal.processors.security.SecurityContext) OperationSecurityContext(org.apache.ignite.internal.processors.security.OperationSecurityContext) Nullable(org.jetbrains.annotations.Nullable)

Example 15 with SecurityContext

use of org.apache.ignite.internal.processors.security.SecurityContext in project ignite by apache.

the class TestSecurityProcessor method authenticate.

/**
 * {@inheritDoc}
 */
@Override
public SecurityContext authenticate(AuthenticationContext ctx) throws IgniteCheckedException {
    if (ctx.credentials() == null || ctx.credentials().getLogin() == null)
        return null;
    SecurityPermissionSet perms = PERMS.get(ctx.credentials());
    if (perms == null) {
        perms = new SecurityBasicPermissionSet();
        ((SecurityBasicPermissionSet) perms).setDefaultAllowAll(true);
    }
    SecurityContext res = new TestSecurityContext(new TestSecuritySubject().setType(ctx.subjectType()).setId(ctx.subjectId()).setAddr(ctx.address()).setLogin(ctx.credentials().getLogin()).setPerms(perms).setCerts(ctx.certificates()).sandboxPermissions(SANDBOX_PERMS.get(ctx.credentials())));
    SECURITY_CONTEXTS.put(res.subject().id(), res);
    return res;
}
Also used : SecurityPermissionSet(org.apache.ignite.plugin.security.SecurityPermissionSet) SecurityContext(org.apache.ignite.internal.processors.security.SecurityContext) SecurityBasicPermissionSet(org.apache.ignite.plugin.security.SecurityBasicPermissionSet)

Aggregations

SecurityContext (org.apache.ignite.internal.processors.security.SecurityContext)32 OperationSecurityContext (org.apache.ignite.internal.processors.security.OperationSecurityContext)15 Test (org.junit.Test)15 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)14 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)10 IgniteException (org.apache.ignite.IgniteException)6 SecurityCredentials (org.apache.ignite.plugin.security.SecurityCredentials)4 IgniteClientDisconnectedException (org.apache.ignite.IgniteClientDisconnectedException)3 IgniteInterruptedException (org.apache.ignite.IgniteInterruptedException)3 ClusterNode (org.apache.ignite.cluster.ClusterNode)3 IgniteClientDisconnectedCheckedException (org.apache.ignite.internal.IgniteClientDisconnectedCheckedException)3 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)3 IgniteSpiException (org.apache.ignite.spi.IgniteSpiException)3 InetSocketAddress (java.net.InetSocketAddress)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)2 DiscoveryEvent (org.apache.ignite.events.DiscoveryEvent)2 GridComponent (org.apache.ignite.internal.GridComponent)2 IgniteKernal (org.apache.ignite.internal.IgniteKernal)2