Search in sources :

Example 6 with AMQPConnection

use of org.apache.qpid.server.transport.AMQPConnection in project qpid-broker-j by apache.

the class ConnectionAndUserPredicateTest method testEvaluateRemoteContainerIdAndUsername.

public void testEvaluateRemoteContainerIdAndUsername() {
    AMQPConnection connection = mock(AMQPConnection.class);
    when(connection.getRemoteAddressString()).thenReturn("foo:1234");
    when(connection.getRemoteContainerName()).thenReturn("TestClientId");
    _subject.getPrincipals().add(new ConnectionPrincipal(connection));
    _predicate.setRemoteContainerIdPattern(".*Client.*");
    _predicate.setUsernamePattern("testUser.*");
    Subject.doAs(_subject, new PrivilegedAction<Void>() {

        @Override
        public Void run() {
            assertTrue("predicate unexpectedly did not match", _predicate.evaluate(mock(ILoggingEvent.class)));
            return null;
        }
    });
    _predicate.setRemoteContainerIdPattern(".*noMatchingClient.*");
    Subject.doAs(_subject, new PrivilegedAction<Void>() {

        @Override
        public Void run() {
            assertFalse("predicate unexpectedly matched", _predicate.evaluate(mock(ILoggingEvent.class)));
            return null;
        }
    });
    _predicate.setRemoteContainerIdPattern(".*Client.*");
    _predicate.setUsernamePattern("noMatchingUsername.*");
    Subject.doAs(_subject, new PrivilegedAction<Void>() {

        @Override
        public Void run() {
            assertFalse("predicate unexpectedly matched", _predicate.evaluate(mock(ILoggingEvent.class)));
            return null;
        }
    });
}
Also used : AMQPConnection(org.apache.qpid.server.transport.AMQPConnection) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) ConnectionPrincipal(org.apache.qpid.server.connection.ConnectionPrincipal) ManagementConnectionPrincipal(org.apache.qpid.server.security.auth.ManagementConnectionPrincipal)

Example 7 with AMQPConnection

use of org.apache.qpid.server.transport.AMQPConnection in project qpid-broker-j by apache.

the class AMQPConnection_1_0Impl method receiveOpenInternal.

private void receiveOpenInternal(final NamedAddressSpace addressSpace) {
    if (!addressSpace.isActive()) {
        final Error err = new Error();
        err.setCondition(AmqpError.NOT_FOUND);
        populateConnectionRedirect(addressSpace, err);
        closeConnection(err);
    } else {
        if (AuthenticatedPrincipal.getOptionalAuthenticatedPrincipalFromSubject(getSubject()) == null) {
            closeConnection(AmqpError.NOT_ALLOWED, "Connection has not been authenticated");
        } else {
            try {
                boolean registerSucceeded = addressSpace.registerConnection(this, (existingConnections, newConnection) -> {
                    boolean proceedWithRegistration = true;
                    if (newConnection instanceof AMQPConnection_1_0Impl && !newConnection.isClosing()) {
                        List<ListenableFuture<Void>> rescheduleFutures = new ArrayList<>();
                        for (AMQPConnection<?> existingConnection : StreamSupport.stream(existingConnections.spliterator(), false).filter(con -> con instanceof AMQPConnection_1_0).filter(con -> !con.isClosing()).filter(con -> con.getRemoteContainerName().equals(newConnection.getRemoteContainerName())).collect(Collectors.toList())) {
                            SoleConnectionEnforcementPolicy soleConnectionEnforcementPolicy = null;
                            if (((AMQPConnection_1_0Impl) existingConnection)._soleConnectionEnforcementPolicy != null) {
                                soleConnectionEnforcementPolicy = ((AMQPConnection_1_0Impl) existingConnection)._soleConnectionEnforcementPolicy;
                            } else if (((AMQPConnection_1_0Impl) newConnection)._soleConnectionEnforcementPolicy != null) {
                                soleConnectionEnforcementPolicy = ((AMQPConnection_1_0Impl) newConnection)._soleConnectionEnforcementPolicy;
                            }
                            if (SoleConnectionEnforcementPolicy.REFUSE_CONNECTION.equals(soleConnectionEnforcementPolicy)) {
                                _properties.put(Symbol.valueOf("amqp:connection-establishment-failed"), true);
                                Error error = new Error(AmqpError.INVALID_FIELD, String.format("Connection closed due to sole-connection-enforcement-policy '%s'", soleConnectionEnforcementPolicy.toString()));
                                error.setInfo(Collections.singletonMap(Symbol.valueOf("invalid-field"), Symbol.valueOf("container-id")));
                                newConnection.doOnIOThreadAsync(() -> ((AMQPConnection_1_0Impl) newConnection).closeConnection(error));
                                proceedWithRegistration = false;
                                break;
                            } else if (SoleConnectionEnforcementPolicy.CLOSE_EXISTING.equals(soleConnectionEnforcementPolicy)) {
                                final Error error = new Error(AmqpError.RESOURCE_LOCKED, String.format("Connection closed due to sole-connection-enforcement-policy '%s'", soleConnectionEnforcementPolicy.toString()));
                                error.setInfo(Collections.singletonMap(Symbol.valueOf("sole-connection-enforcement"), true));
                                rescheduleFutures.add(existingConnection.doOnIOThreadAsync(() -> ((AMQPConnection_1_0Impl) existingConnection).closeConnection(error)));
                                proceedWithRegistration = false;
                            }
                        }
                        if (!rescheduleFutures.isEmpty()) {
                            doAfter(allAsList(rescheduleFutures), () -> newConnection.doOnIOThreadAsync(() -> receiveOpenInternal(addressSpace)));
                        }
                    }
                    return proceedWithRegistration;
                });
                if (registerSucceeded) {
                    setAddressSpace(addressSpace);
                    if (!addressSpace.authoriseCreateConnection(this)) {
                        closeConnection(AmqpError.NOT_ALLOWED, "Connection refused");
                    } else {
                        switch(_connectionState) {
                            case AWAIT_OPEN:
                                sendOpen(_channelMax, _maxFrameSize);
                                _connectionState = ConnectionState.OPENED;
                                break;
                            case CLOSE_SENT:
                            case CLOSED:
                                // already sent our close - probably due to an error
                                break;
                            default:
                                throw new ConnectionScopedRuntimeException(String.format("Unexpected state %s during connection open.", _connectionState));
                        }
                    }
                }
            } catch (VirtualHostUnavailableException | AccessControlException e) {
                closeConnection(AmqpError.NOT_ALLOWED, e.getMessage());
            }
        }
    }
}
Also used : AccessControlContext(java.security.AccessControlContext) Arrays(java.util.Arrays) SoleConnectionDetectionPolicy(org.apache.qpid.server.protocol.v1_0.type.extensions.soleconn.SoleConnectionDetectionPolicy) PeekingIterator(com.google.common.collect.PeekingIterator) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) ExternalAuthenticationManagerImpl(org.apache.qpid.server.security.auth.manager.ExternalAuthenticationManagerImpl) Map(java.util.Map) Disposition(org.apache.qpid.server.protocol.v1_0.type.transport.Disposition) ProtocolHandler(org.apache.qpid.server.protocol.v1_0.codec.ProtocolHandler) ConnectionError(org.apache.qpid.server.protocol.v1_0.type.transport.ConnectionError) End(org.apache.qpid.server.protocol.v1_0.type.transport.End) Futures.allAsList(com.google.common.util.concurrent.Futures.allAsList) Set(java.util.Set) DescribedTypeConstructorRegistry(org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry) AMQPConnection(org.apache.qpid.server.transport.AMQPConnection) SaslCode(org.apache.qpid.server.protocol.v1_0.type.security.SaslCode) VirtualHostUnavailableException(org.apache.qpid.server.virtualhost.VirtualHostUnavailableException) Binary(org.apache.qpid.server.protocol.v1_0.type.Binary) Transport(org.apache.qpid.server.model.Transport) SASLFrame(org.apache.qpid.server.protocol.v1_0.framing.SASLFrame) OversizeFrameException(org.apache.qpid.server.protocol.v1_0.framing.OversizeFrameException) AggregateTicker(org.apache.qpid.server.transport.AggregateTicker) ByteBufferSender(org.apache.qpid.server.transport.ByteBufferSender) ConnectionScopedRuntimeException(org.apache.qpid.server.util.ConnectionScopedRuntimeException) AccessController(java.security.AccessController) ValueWriter(org.apache.qpid.server.protocol.v1_0.codec.ValueWriter) ProtocolEngine(org.apache.qpid.server.transport.ProtocolEngine) FrameBody(org.apache.qpid.server.protocol.v1_0.type.FrameBody) FrameWriter(org.apache.qpid.server.protocol.v1_0.codec.FrameWriter) SOLE_CONNECTION_ENFORCEMENT_POLICY(org.apache.qpid.server.protocol.v1_0.type.extensions.soleconn.SoleConnectionConnectionProperties.SOLE_CONNECTION_ENFORCEMENT_POLICY) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Close(org.apache.qpid.server.protocol.v1_0.type.transport.Close) ChannelFrameBody(org.apache.qpid.server.protocol.v1_0.type.transport.ChannelFrameBody) SoleConnectionEnforcementPolicy(org.apache.qpid.server.protocol.v1_0.type.extensions.soleconn.SoleConnectionEnforcementPolicy) AmqpError(org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError) StreamSupport(java.util.stream.StreamSupport) Flow(org.apache.qpid.server.protocol.v1_0.type.transport.Flow) ConnectionPropertyEnricher(org.apache.qpid.server.plugin.ConnectionPropertyEnricher) SaslFrameBody(org.apache.qpid.server.protocol.v1_0.type.SaslFrameBody) SoleConnectionConnectionProperties(org.apache.qpid.server.protocol.v1_0.type.extensions.soleconn.SoleConnectionConnectionProperties) Connection(org.apache.qpid.server.model.Connection) ServerNetworkConnection(org.apache.qpid.server.transport.ServerNetworkConnection) UnsignedShort(org.apache.qpid.server.protocol.v1_0.type.UnsignedShort) AMQFrame(org.apache.qpid.server.protocol.v1_0.framing.AMQFrame) SaslChallenge(org.apache.qpid.server.protocol.v1_0.type.security.SaslChallenge) QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer) TransportFrame(org.apache.qpid.server.protocol.v1_0.framing.TransportFrame) AMQPDescribedTypeRegistry(org.apache.qpid.server.protocol.v1_0.type.codec.AMQPDescribedTypeRegistry) SocketAddress(java.net.SocketAddress) Open(org.apache.qpid.server.protocol.v1_0.type.transport.Open) LoggerFactory(org.slf4j.LoggerFactory) ByteBuffer(java.nio.ByteBuffer) ConnectionMessages(org.apache.qpid.server.logging.messages.ConnectionMessages) ErrorCondition(org.apache.qpid.server.protocol.v1_0.type.ErrorCondition) Transfer(org.apache.qpid.server.protocol.v1_0.type.transport.Transfer) AmqpPort(org.apache.qpid.server.model.port.AmqpPort) ValueHandler(org.apache.qpid.server.protocol.v1_0.codec.ValueHandler) SectionDecoderRegistry(org.apache.qpid.server.protocol.v1_0.codec.SectionDecoderRegistry) Symbol(org.apache.qpid.server.protocol.v1_0.type.Symbol) StoreException(org.apache.qpid.server.store.StoreException) LocalTransaction(org.apache.qpid.server.txn.LocalTransaction) Detach(org.apache.qpid.server.protocol.v1_0.type.transport.Detach) Collection(java.util.Collection) AnonymousAuthenticationManager(org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SaslOutcome(org.apache.qpid.server.protocol.v1_0.type.security.SaslOutcome) UUID(java.util.UUID) PrivilegedAction(java.security.PrivilegedAction) Collectors(java.util.stream.Collectors) Functions(org.apache.qpid.server.transport.util.Functions) Sets(com.google.common.collect.Sets) Attach(org.apache.qpid.server.protocol.v1_0.type.transport.Attach) List(java.util.List) Principal(java.security.Principal) NamedAddressSpace(org.apache.qpid.server.model.NamedAddressSpace) AccessControlException(java.security.AccessControlException) FrameHandler(org.apache.qpid.server.protocol.v1_0.framing.FrameHandler) Queue(java.util.Queue) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) AuthenticationProvider(org.apache.qpid.server.model.AuthenticationProvider) Begin(org.apache.qpid.server.protocol.v1_0.type.transport.Begin) UnsignedInteger(org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) SaslMechanisms(org.apache.qpid.server.protocol.v1_0.type.security.SaslMechanisms) Iterators(com.google.common.collect.Iterators) Error(org.apache.qpid.server.protocol.v1_0.type.transport.Error) SaslNegotiator(org.apache.qpid.server.security.auth.sasl.SaslNegotiator) SaslInit(org.apache.qpid.server.protocol.v1_0.type.security.SaslInit) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) AbstractAMQPConnection(org.apache.qpid.server.transport.AbstractAMQPConnection) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) SaslResponse(org.apache.qpid.server.protocol.v1_0.type.security.SaslResponse) NoSuchElementException(java.util.NoSuchElementException) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) ServerTransaction(org.apache.qpid.server.txn.ServerTransaction) Logger(org.slf4j.Logger) Action(org.apache.qpid.server.util.Action) Iterator(java.util.Iterator) Broker(org.apache.qpid.server.model.Broker) Protocol(org.apache.qpid.server.model.Protocol) SubjectCreator(org.apache.qpid.server.security.SubjectCreator) ConnectionClosingTicker(org.apache.qpid.server.protocol.ConnectionClosingTicker) AMQPSession(org.apache.qpid.server.session.AMQPSession) Collections(java.util.Collections) ArrayList(java.util.ArrayList) ConnectionError(org.apache.qpid.server.protocol.v1_0.type.transport.ConnectionError) AmqpError(org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError) Error(org.apache.qpid.server.protocol.v1_0.type.transport.Error) AccessControlException(java.security.AccessControlException) VirtualHostUnavailableException(org.apache.qpid.server.virtualhost.VirtualHostUnavailableException) SoleConnectionEnforcementPolicy(org.apache.qpid.server.protocol.v1_0.type.extensions.soleconn.SoleConnectionEnforcementPolicy) ConnectionScopedRuntimeException(org.apache.qpid.server.util.ConnectionScopedRuntimeException) ListenableFuture(com.google.common.util.concurrent.ListenableFuture)

Example 8 with AMQPConnection

use of org.apache.qpid.server.transport.AMQPConnection in project qpid-broker-j by apache.

the class ServerConnectionDelegate method isSessionNameUnique.

private boolean isSessionNameUnique(final byte[] name, final ServerConnection conn) {
    final Principal authorizedPrincipal = conn.getAuthorizedPrincipal();
    final String userId = authorizedPrincipal == null ? "" : authorizedPrincipal.getName();
    final Iterator<? extends org.apache.qpid.server.model.Connection<?>> connections = conn.getAddressSpace().getConnections().iterator();
    while (connections.hasNext()) {
        final AMQPConnection<?> amqConnectionModel = (AMQPConnection<?>) connections.next();
        final String userName = amqConnectionModel.getAuthorizedPrincipal() == null ? "" : amqConnectionModel.getAuthorizedPrincipal().getName();
        if (userId.equals(userName) && amqConnectionModel.hasSessionWithName(name)) {
            return false;
        }
    }
    return true;
}
Also used : AMQPConnection(org.apache.qpid.server.transport.AMQPConnection) Principal(java.security.Principal)

Example 9 with AMQPConnection

use of org.apache.qpid.server.transport.AMQPConnection in project qpid-broker-j by apache.

the class ChannelLogSubject method updateSessionDetails.

public void updateSessionDetails() {
    /**
     * LOG FORMAT used by the AMQPConnectorActor follows
     * ChannelLogSubject.CHANNEL_FORMAT : con:{0}({1}@{2}/{3})/ch:{4}.
     *
     * Uses a MessageFormat call to insert the required values according to
     * these indices:
     *
     * 0 - Connection ID
     * 1 - User ID
     * 2 - IP
     * 3 - Virtualhost
     * 4 - Channel ID
     */
    AMQPConnection connection = _sessionModel.getAMQPConnection();
    setLogStringWithFormat(CHANNEL_FORMAT, connection == null ? -1L : connection.getConnectionId(), (connection == null || connection.getAuthorizedPrincipal() == null) ? "?" : connection.getAuthorizedPrincipal().getName(), (connection == null || connection.getRemoteAddressString() == null) ? "?" : connection.getRemoteAddressString(), (connection == null || connection.getAddressSpaceName() == null) ? "?" : connection.getAddressSpaceName(), _sessionModel.getChannelId());
}
Also used : AMQPConnection(org.apache.qpid.server.transport.AMQPConnection)

Example 10 with AMQPConnection

use of org.apache.qpid.server.transport.AMQPConnection in project qpid-broker-j by apache.

the class VirtualHostTest method testDeleteVirtualHost_ClosesConnections.

public void testDeleteVirtualHost_ClosesConnections() {
    String virtualHostName = getName();
    QueueManagingVirtualHost<?> virtualHost = createVirtualHost(virtualHostName);
    assertEquals("Unexpected state", State.ACTIVE, virtualHost.getState());
    AbstractAMQPConnection connection = createMockProtocolConnection(virtualHost);
    assertEquals("Unexpected number of connections before connection registered", 0, virtualHost.getConnectionCount());
    AMQPConnection modelConnection = mock(AMQPConnection.class);
    when(modelConnection.closeAsync()).thenReturn(Futures.immediateFuture(null));
    virtualHost.registerConnection(modelConnection, new NoopConnectionEstablishmentPolicy());
    assertEquals("Unexpected number of connections after connection registered", 1, virtualHost.getConnectionCount());
    virtualHost.delete();
    assertEquals("Unexpected state", State.DELETED, virtualHost.getState());
    assertEquals("Unexpected number of connections after virtualhost deleted", 0, virtualHost.getConnectionCount());
    verify(modelConnection).closeAsync();
}
Also used : AbstractAMQPConnection(org.apache.qpid.server.transport.AbstractAMQPConnection) AMQPConnection(org.apache.qpid.server.transport.AMQPConnection) AbstractAMQPConnection(org.apache.qpid.server.transport.AbstractAMQPConnection) NoopConnectionEstablishmentPolicy(org.apache.qpid.server.virtualhost.NoopConnectionEstablishmentPolicy) Matchers.anyString(org.mockito.Matchers.anyString)

Aggregations

AMQPConnection (org.apache.qpid.server.transport.AMQPConnection)12 Principal (java.security.Principal)4 ConnectionPrincipal (org.apache.qpid.server.connection.ConnectionPrincipal)4 InetSocketAddress (java.net.InetSocketAddress)3 Subject (javax.security.auth.Subject)3 AbstractAMQPConnection (org.apache.qpid.server.transport.AbstractAMQPConnection)3 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)2 InetAddress (java.net.InetAddress)2 QpidByteBuffer (org.apache.qpid.server.bytebuffer.QpidByteBuffer)2 AuthenticatedPrincipal (org.apache.qpid.server.security.auth.AuthenticatedPrincipal)2 ManagementConnectionPrincipal (org.apache.qpid.server.security.auth.ManagementConnectionPrincipal)2 Iterators (com.google.common.collect.Iterators)1 PeekingIterator (com.google.common.collect.PeekingIterator)1 Sets (com.google.common.collect.Sets)1 Futures.allAsList (com.google.common.util.concurrent.Futures.allAsList)1 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)1 SocketAddress (java.net.SocketAddress)1 ByteBuffer (java.nio.ByteBuffer)1 AccessControlContext (java.security.AccessControlContext)1 AccessControlException (java.security.AccessControlException)1