Search in sources :

Example 16 with AuthenticatedPrincipal

use of org.apache.qpid.server.security.auth.AuthenticatedPrincipal in project qpid-broker-j by apache.

the class OAuth2InteractiveAuthenticatorTest method createMockOAuth2AuthenticationProvider.

private OAuth2AuthenticationProvider<?> createMockOAuth2AuthenticationProvider(final HttpPort mockPort) throws URISyntaxException {
    OAuth2AuthenticationProvider authenticationProvider = mock(OAuth2AuthenticationProvider.class);
    Broker mockBroker = mock(Broker.class);
    SubjectCreator mockSubjectCreator = mock(SubjectCreator.class);
    when(_mockPort.getSubjectCreator(anyBoolean(), anyString())).thenReturn(mockSubjectCreator);
    SubjectAuthenticationResult mockSuccessfulSubjectAuthenticationResult = mock(SubjectAuthenticationResult.class);
    SubjectAuthenticationResult mockUnauthorizedSubjectAuthenticationResult = mock(SubjectAuthenticationResult.class);
    final Subject successfulSubject = new Subject(true, Collections.singleton(new AuthenticatedPrincipal(new UsernamePrincipal(TEST_AUTHORIZED_USER, null))), Collections.emptySet(), Collections.emptySet());
    final Subject unauthorizedSubject = new Subject(true, Collections.singleton(new AuthenticatedPrincipal(new UsernamePrincipal(TEST_UNAUTHORIZED_USER, null))), Collections.emptySet(), Collections.emptySet());
    AuthenticationResult mockSuccessfulAuthenticationResult = mock(AuthenticationResult.class);
    AuthenticationResult mockUnauthorizedAuthenticationResult = mock(AuthenticationResult.class);
    AuthenticationResult failedAuthenticationResult = new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new Exception("authentication failed"));
    SubjectAuthenticationResult failedSubjectAuthenticationResult = new SubjectAuthenticationResult(failedAuthenticationResult);
    doAnswer(new Answer() {

        @Override
        public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
            final Subject subject = Subject.getSubject(AccessController.getContext());
            if (!subject.getPrincipals().iterator().next().getName().equals(TEST_AUTHORIZED_USER)) {
                throw new AccessControlException("access denied");
            }
            return null;
        }
    }).when(mockBroker).authorise(eq(Operation.PERFORM_ACTION("manage")));
    when(authenticationProvider.getAuthorizationEndpointURI(any())).thenReturn(new URI(TEST_AUTHORIZATION_ENDPOINT));
    when(authenticationProvider.getClientId()).thenReturn(TEST_CLIENT_ID);
    when(authenticationProvider.getScope()).thenReturn(TEST_OAUTH2_SCOPE);
    when(authenticationProvider.getParent()).thenReturn(mockBroker);
    when(authenticationProvider.authenticateViaAuthorizationCode(matches(TEST_VALID_AUTHORIZATION_CODE), matches(TEST_REQUEST_HOST), any())).thenReturn(mockSuccessfulAuthenticationResult);
    when(authenticationProvider.authenticateViaAuthorizationCode(matches(TEST_INVALID_AUTHORIZATION_CODE), matches(TEST_REQUEST_HOST), any())).thenReturn(failedAuthenticationResult);
    when(authenticationProvider.authenticateViaAuthorizationCode(matches(TEST_UNAUTHORIZED_AUTHORIZATION_CODE), matches(TEST_REQUEST_HOST), any())).thenReturn(mockUnauthorizedAuthenticationResult);
    when(mockSuccessfulSubjectAuthenticationResult.getSubject()).thenReturn(successfulSubject);
    when(mockUnauthorizedSubjectAuthenticationResult.getSubject()).thenReturn(unauthorizedSubject);
    when(mockSubjectCreator.createResultWithGroups(mockSuccessfulAuthenticationResult)).thenReturn(mockSuccessfulSubjectAuthenticationResult);
    when(mockSubjectCreator.createResultWithGroups(mockUnauthorizedAuthenticationResult)).thenReturn(mockUnauthorizedSubjectAuthenticationResult);
    when(mockSubjectCreator.createResultWithGroups(failedAuthenticationResult)).thenReturn(failedSubjectAuthenticationResult);
    return authenticationProvider;
}
Also used : Broker(org.apache.qpid.server.model.Broker) AccessControlException(java.security.AccessControlException) URI(java.net.URI) HttpURI(org.eclipse.jetty.http.HttpURI) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) Subject(javax.security.auth.Subject) URISyntaxException(java.net.URISyntaxException) AccessControlException(java.security.AccessControlException) IOException(java.io.IOException) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) OAuth2AuthenticationProvider(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider) SubjectCreator(org.apache.qpid.server.security.SubjectCreator)

Example 17 with AuthenticatedPrincipal

use of org.apache.qpid.server.security.auth.AuthenticatedPrincipal in project qpid-broker-j by apache.

the class AbstractConfiguredObject method initializeAttributes.

private void initializeAttributes() {
    final AuthenticatedPrincipal currentUser = AuthenticatedPrincipal.getCurrentUser();
    if (currentUser != null) {
        String currentUserName = currentUser.getName();
        _attributes.put(LAST_UPDATED_BY, currentUserName);
        _attributes.put(CREATED_BY, currentUserName);
    }
    final Date currentTime = new Date();
    _attributes.put(LAST_UPDATED_TIME, currentTime);
    _attributes.put(CREATED_TIME, currentTime);
    ConfiguredObject<?> proxyForInitialization = null;
    for (ConfiguredObjectAttribute<?, ?> attr : _attributeTypes.values()) {
        if (!attr.isDerived()) {
            ConfiguredSettableAttribute autoAttr = (ConfiguredSettableAttribute) attr;
            final boolean isPresent = _attributes.containsKey(attr.getName());
            final boolean hasDefault = !"".equals(autoAttr.defaultValue());
            if (!isPresent && hasDefault) {
                switch(autoAttr.getInitialization()) {
                    case copy:
                        _attributes.put(autoAttr.getName(), autoAttr.defaultValue());
                        break;
                    case materialize:
                        if (proxyForInitialization == null) {
                            proxyForInitialization = createProxyForInitialization(_attributes);
                        }
                        _attributes.put(autoAttr.getName(), autoAttr.convert(autoAttr.defaultValue(), proxyForInitialization));
                        break;
                }
            }
        }
    }
}
Also used : Date(java.util.Date) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal)

Example 18 with AuthenticatedPrincipal

use of org.apache.qpid.server.security.auth.AuthenticatedPrincipal in project qpid-broker-j by apache.

the class AMQPConnection_0_8Test method setUp.

@Before
public void setUp() throws Exception {
    EventLogger value = new EventLogger();
    SystemConfig systemConfig = mock(SystemConfig.class);
    when(systemConfig.getEventLogger()).thenReturn(mock(EventLogger.class));
    _taskExecutor = new TaskExecutorImpl();
    _taskExecutor.start();
    Model model = BrokerModel.getInstance();
    _broker = mock(Broker.class);
    when(_broker.getParent()).thenReturn(systemConfig);
    when(_broker.getModel()).thenReturn(model);
    when(_broker.getCategoryClass()).thenReturn(Broker.class);
    when(_broker.getTaskExecutor()).thenReturn(_taskExecutor);
    when(_broker.getChildExecutor()).thenReturn(_taskExecutor);
    when(_broker.getEventLogger()).thenReturn(value);
    when(_broker.getContextValue(eq(Long.class), eq(Broker.CHANNEL_FLOW_CONTROL_ENFORCEMENT_TIMEOUT))).thenReturn(0l);
    _virtualHostNode = mock(VirtualHostNode.class);
    when(_virtualHostNode.getParent()).thenReturn(_broker);
    when(_virtualHostNode.getModel()).thenReturn(model);
    when(_virtualHostNode.getCategoryClass()).thenReturn(VirtualHostNode.class);
    when(_virtualHostNode.getTaskExecutor()).thenReturn(_taskExecutor);
    when(_virtualHostNode.getChildExecutor()).thenReturn(_taskExecutor);
    _virtualHost = mock(QueueManagingVirtualHost.class);
    VirtualHostPrincipal virtualHostPrincipal = new VirtualHostPrincipal(_virtualHost);
    when(_virtualHost.getParent()).thenReturn(_virtualHostNode);
    when(_virtualHost.getModel()).thenReturn(model);
    when(_virtualHost.getCategoryClass()).thenReturn(VirtualHost.class);
    when(_virtualHost.getState()).thenReturn(State.ACTIVE);
    when(_virtualHost.isActive()).thenReturn(true);
    when(_virtualHost.getTaskExecutor()).thenReturn(_taskExecutor);
    when(_virtualHost.getPrincipal()).thenReturn(virtualHostPrincipal);
    when(_virtualHost.getContextValue(Integer.class, Broker.MESSAGE_COMPRESSION_THRESHOLD_SIZE)).thenReturn(1024);
    when(_virtualHost.getContextValue(Long.class, Connection.MAX_UNCOMMITTED_IN_MEMORY_SIZE)).thenReturn(1024l);
    when(_virtualHost.getContextValue(Boolean.class, Broker.BROKER_MSG_AUTH)).thenReturn(false);
    when(_virtualHost.authoriseCreateConnection(any(AMQPConnection.class))).thenReturn(true);
    when(_virtualHost.getEventLogger()).thenReturn(value);
    SubjectCreator subjectCreator = mock(SubjectCreator.class);
    SaslNegotiator saslNegotiator = mock(SaslNegotiator.class);
    when(subjectCreator.createSaslNegotiator(eq(SASL_MECH.toString()), any(SaslSettings.class))).thenReturn(saslNegotiator);
    when(subjectCreator.authenticate(saslNegotiator, SASL_RESPONSE)).thenReturn(new SubjectAuthenticationResult(new AuthenticationResult(new AuthenticatedPrincipal(new UsernamePrincipal("username", null))), new Subject()));
    AuthenticationProvider authenticationProvider = mock(AuthenticationProvider.class);
    when(authenticationProvider.getAvailableMechanisms(anyBoolean())).thenReturn(Collections.singletonList(SASL_MECH.toString()));
    _port = mock(AmqpPort.class);
    when(_port.getParent()).thenReturn(_broker);
    when(_port.getCategoryClass()).thenReturn(Port.class);
    when(_port.getChildExecutor()).thenReturn(_taskExecutor);
    when(_port.getModel()).thenReturn(model);
    when(_port.getAuthenticationProvider()).thenReturn(authenticationProvider);
    when(_port.getAddressSpace(VIRTUAL_HOST_NAME)).thenReturn(_virtualHost);
    when(_port.getContextValue(Long.class, Port.CONNECTION_MAXIMUM_AUTHENTICATION_DELAY)).thenReturn(2500l);
    when(_port.getContextValue(Integer.class, Connection.MAX_MESSAGE_SIZE)).thenReturn(Connection.DEFAULT_MAX_MESSAGE_SIZE);
    when(_port.getSubjectCreator(eq(false), anyString())).thenReturn(subjectCreator);
    _sender = mock(ByteBufferSender.class);
    _network = mock(ServerNetworkConnection.class);
    when(_network.getSender()).thenReturn(_sender);
    when(_network.getLocalAddress()).thenReturn(new InetSocketAddress("localhost", 12345));
    when(_network.getSelectedHost()).thenReturn("localhost");
    _transport = Transport.TCP;
    _protocol = Protocol.AMQP_0_8;
    _ticker = new AggregateTicker();
}
Also used : ByteBufferSender(org.apache.qpid.server.transport.ByteBufferSender) ServerNetworkConnection(org.apache.qpid.server.transport.ServerNetworkConnection) SystemConfig(org.apache.qpid.server.model.SystemConfig) TaskExecutorImpl(org.apache.qpid.server.configuration.updater.TaskExecutorImpl) Broker(org.apache.qpid.server.model.Broker) QueueManagingVirtualHost(org.apache.qpid.server.virtualhost.QueueManagingVirtualHost) EventLogger(org.apache.qpid.server.logging.EventLogger) InetSocketAddress(java.net.InetSocketAddress) AuthenticationProvider(org.apache.qpid.server.model.AuthenticationProvider) AggregateTicker(org.apache.qpid.server.transport.AggregateTicker) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) Subject(javax.security.auth.Subject) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) SaslSettings(org.apache.qpid.server.security.auth.sasl.SaslSettings) UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) AMQPConnection(org.apache.qpid.server.transport.AMQPConnection) BrokerModel(org.apache.qpid.server.model.BrokerModel) Model(org.apache.qpid.server.model.Model) VirtualHostPrincipal(org.apache.qpid.server.virtualhost.VirtualHostPrincipal) SaslNegotiator(org.apache.qpid.server.security.auth.sasl.SaslNegotiator) AmqpPort(org.apache.qpid.server.model.port.AmqpPort) SubjectCreator(org.apache.qpid.server.security.SubjectCreator) VirtualHostNode(org.apache.qpid.server.model.VirtualHostNode) Before(org.junit.Before)

Example 19 with AuthenticatedPrincipal

use of org.apache.qpid.server.security.auth.AuthenticatedPrincipal 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();
        populateConnectionRedirect(addressSpace, err);
        closeConnection(err);
        return;
    }
    final Principal authenticatedPrincipal = getAuthorizedPrincipal();
    if (authenticatedPrincipal == null) {
        closeConnection(AmqpError.NOT_ALLOWED, "Connection has not been authenticated");
        return;
    }
    try {
        addressSpace.registerConnection(this);
        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());
    } catch (SoleConnectionEnforcementPolicyException e) {
        handleSoleConnectionEnforcement(addressSpace, e);
    } catch (ConnectionLimitException e) {
        LOGGER.debug("User connection limit exceeded", e);
        closeConnection(AmqpError.RESOURCE_LIMIT_EXCEEDED, e.getMessage());
    }
}
Also used : ConnectionLimitException(org.apache.qpid.server.security.limit.ConnectionLimitException) VirtualHostUnavailableException(org.apache.qpid.server.virtualhost.VirtualHostUnavailableException) SoleConnectionEnforcementPolicyException(org.apache.qpid.server.protocol.v1_0.type.extensions.soleconn.SoleConnectionEnforcementPolicyException) ConnectionScopedRuntimeException(org.apache.qpid.server.util.ConnectionScopedRuntimeException) 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) Principal(java.security.Principal) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal)

Example 20 with AuthenticatedPrincipal

use of org.apache.qpid.server.security.auth.AuthenticatedPrincipal in project qpid-broker-j by apache.

the class AMQPConnection_1_0Impl method processProtocolHeader.

private void processProtocolHeader(final QpidByteBuffer msg) {
    if (msg.remaining() >= 8) {
        byte[] header = new byte[8];
        msg.get(header);
        final AuthenticationProvider<?> authenticationProvider = getPort().getAuthenticationProvider();
        if (Arrays.equals(header, SASL_HEADER)) {
            if (_saslComplete) {
                throw new ConnectionScopedRuntimeException("SASL Layer header received after SASL already established");
            }
            try (QpidByteBuffer protocolHeader = QpidByteBuffer.wrap(SASL_HEADER)) {
                getSender().send(protocolHeader);
            }
            SaslMechanisms mechanisms = new SaslMechanisms();
            ArrayList<Symbol> mechanismsList = new ArrayList<>();
            for (String name : authenticationProvider.getAvailableMechanisms(getTransport().isSecure())) {
                mechanismsList.add(Symbol.valueOf(name));
            }
            mechanisms.setSaslServerMechanisms(mechanismsList.toArray(new Symbol[mechanismsList.size()]));
            send(new SASLFrame(mechanisms));
            _connectionState = ConnectionState.AWAIT_SASL_INIT;
            _frameHandler = getFrameHandler(true);
        } else if (Arrays.equals(header, AMQP_HEADER)) {
            if (!_saslComplete) {
                final List<String> mechanisms = authenticationProvider.getAvailableMechanisms(getTransport().isSecure());
                if (mechanisms.contains(ExternalAuthenticationManagerImpl.MECHANISM_NAME) && getNetwork().getPeerPrincipal() != null) {
                    setUserPrincipal(new AuthenticatedPrincipal(getNetwork().getPeerPrincipal()));
                } else if (mechanisms.contains(AnonymousAuthenticationManager.MECHANISM_NAME)) {
                    setUserPrincipal(new AuthenticatedPrincipal(((AnonymousAuthenticationManager) authenticationProvider).getAnonymousPrincipal()));
                } else {
                    LOGGER.warn("{} : attempt to initiate AMQP connection without correctly authenticating", getLogSubject());
                    _connectionState = ConnectionState.CLOSED;
                    getNetwork().close();
                }
            }
            try (QpidByteBuffer protocolHeader = QpidByteBuffer.wrap(AMQP_HEADER)) {
                getSender().send(protocolHeader);
            }
            _connectionState = ConnectionState.AWAIT_OPEN;
            _frameHandler = getFrameHandler(false);
        } else {
            LOGGER.warn("{} : unknown AMQP header {}", getLogSubject(), Functions.str(header));
            _connectionState = ConnectionState.CLOSED;
            getNetwork().close();
        }
    }
}
Also used : Symbol(org.apache.qpid.server.protocol.v1_0.type.Symbol) SASLFrame(org.apache.qpid.server.protocol.v1_0.framing.SASLFrame) ArrayList(java.util.ArrayList) SaslMechanisms(org.apache.qpid.server.protocol.v1_0.type.security.SaslMechanisms) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) AnonymousAuthenticationManager(org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager) ConnectionScopedRuntimeException(org.apache.qpid.server.util.ConnectionScopedRuntimeException) QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer) Futures.allAsList(com.google.common.util.concurrent.Futures.allAsList) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

AuthenticatedPrincipal (org.apache.qpid.server.security.auth.AuthenticatedPrincipal)27 Subject (javax.security.auth.Subject)12 UsernamePrincipal (org.apache.qpid.server.security.auth.UsernamePrincipal)11 Principal (java.security.Principal)7 ConfiguredObject (org.apache.qpid.server.model.ConfiguredObject)7 Before (org.junit.Before)6 Test (org.junit.Test)6 Date (java.util.Date)5 EventLogger (org.apache.qpid.server.logging.EventLogger)5 SubjectCreator (org.apache.qpid.server.security.SubjectCreator)5 ArrayList (java.util.ArrayList)4 AmqpPort (org.apache.qpid.server.model.port.AmqpPort)4 AMQPConnection (org.apache.qpid.server.transport.AMQPConnection)4 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 Broker (org.apache.qpid.server.model.Broker)3 GenericPrincipal (org.apache.qpid.server.model.preferences.GenericPrincipal)3 TransportFrame (org.apache.qpid.server.protocol.v1_0.framing.TransportFrame)3 SubjectAuthenticationResult (org.apache.qpid.server.security.auth.SubjectAuthenticationResult)3 URISyntaxException (java.net.URISyntaxException)2