Ejemplo n.º 1
0
        public void ContainerHostPlainPrincipalTest()
        {
            string       name          = MethodInfo.GetCurrentMethod().Name;
            ListenerLink link          = null;
            var          linkProcessor = new TestLinkProcessor();

            linkProcessor.OnLinkAttached += a => link = a;
            this.host.RegisterLinkProcessor(linkProcessor);

            var connection = new Connection(Address);
            var session    = new Session(connection);
            var sender     = new SenderLink(session, name, name);

            sender.Send(new Message("msg1"), SendTimeout);
            connection.Close();

            Assert.IsTrue(link != null, "link is null");
            var listenerConnection = (ListenerConnection)link.Session.Connection;

            Assert.IsTrue(listenerConnection.Principal != null, "principal is null");
            Assert.IsTrue(listenerConnection.Principal.Identity.AuthenticationType == "PLAIN", "wrong auth type");
        }
Ejemplo n.º 2
0
        public async Task IsAuthorized_ReturnsTrue_WhenConnectionAuthorized()
        {
            ListenerLink   link              = null;
            var            authorized        = false;
            ILinkProcessor fakeLinkProcessor = Substitute.For <ILinkProcessor>();

            fakeLinkProcessor
            .When(instance => instance.Process(Arg.Any <AttachContext>()))
            .Do(c =>
            {
                AttachContext attachContext = c.ArgAt <AttachContext>(0);
                link = attachContext.Link;
                attachContext.Complete(new Error(ErrorCode.IllegalState)
                {
                    Description = "Test"
                });
            });

            ContainerHost host = TestAmqpHost.Open();

            try
            {
                host.RegisterLinkProcessor(fakeLinkProcessor);
                Connection connection = await host.ConnectAndAttachAsync();

                var securityContext = new SecurityContext();
                securityContext.Authorize(link.Session.Connection);
                authorized = securityContext.IsAuthorized(link.Session.Connection);

                await connection.CloseAsync();
            }
            finally
            {
                host.Close();
            }

            authorized.ShouldBeTrue();
        }
Ejemplo n.º 3
0
                static void OnMessage(ListenerLink link, Message message, DeliveryState deliveryState, object state)
                {
                    var    thisPtr        = (Publisher)state;
                    string errorCondition = null;

                    if (message.ApplicationProperties != null &&
                        (errorCondition = (string)message.ApplicationProperties["errorcondition"]) != null)
                    {
                        link.DisposeMessage(
                            message,
                            new Rejected()
                        {
                            Error = new Error()
                            {
                                Condition = errorCondition, Description = "message was rejected"
                            }
                        },
                            true);
                    }
                    else
                    {
                        var txnState = deliveryState as TransactionalState;
                        if (txnState != null)
                        {
                            Transaction txn = thisPtr.queue.broker.txnManager.GetTransaction(txnState.TxnId);
                            txn.AddOperation(message, onDischarge, thisPtr);
                            txnState.Outcome = new Accepted();
                        }
                        else
                        {
                            thisPtr.queue.Enqueue((BrokerMessage)message);
                            deliveryState = new Accepted();
                        }

                        thisPtr.link.DisposeMessage(message, deliveryState, true);
                    }
                }
Ejemplo n.º 4
0
        public void ContainerHostSaslAnonymousTest()
        {
            string       name          = "ContainerHostSaslAnonymousTest";
            ListenerLink link          = null;
            var          linkProcessor = new TestLinkProcessor();

            linkProcessor.OnLinkAttached += a => link = a;
            this.host.RegisterLinkProcessor(this.linkProcessor = linkProcessor);

            var factory = new ConnectionFactory();

            factory.SASL.Profile = SaslProfile.Anonymous;
            var connection = factory.CreateAsync(new Address(Address.Host, Address.Port, null, null, "/", Address.Scheme)).Result;
            var session    = new Session(connection);
            var sender     = new SenderLink(session, name, name);

            sender.Send(new Message("msg1"), SendTimeout);
            connection.Close();

            Assert.IsTrue(link != null, "link is null");
            var listenerConnection = (ListenerConnection)link.Session.Connection;

            Assert.IsTrue(listenerConnection.Principal == null, "principal should be null");
        }
Ejemplo n.º 5
0
        public async Task WebSocketSslMutalAuthTest()
        {
            string testName      = "WebSocketSslMutalAuthTest";
            string listenAddress = "wss://localhost:18081/" + testName + "/";
            Uri    uri           = new Uri(listenAddress);

            X509Certificate2 cert = ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");

            string output;
            int    code = Exec("netsh.exe", string.Format("http show sslcert hostnameport={0}:{1}", uri.Host, uri.Port), out output);

            if (code != 0)
            {
                string args = string.Format("http add sslcert hostnameport={0}:{1} certhash={2} certstorename=MY appid={{{3}}} clientcertnegotiation=enable",
                                            uri.Host, uri.Port, cert.Thumbprint, Guid.NewGuid());
                code = Exec("netsh.exe", args, out output);
                Assert.AreEqual(0, code, "failed to add ssl cert: " + output);
            }

            X509Certificate serviceCert  = null;
            X509Certificate clientCert   = null;
            ListenerLink    listenerLink = null;

            var linkProcessor = new TestLinkProcessor()
            {
                OnLinkAttached = c => listenerLink = c
            };
            var host = new ContainerHost(new List <Uri>()
            {
                uri
            }, null, uri.UserInfo);

            host.Listeners[0].SASL.EnableExternalMechanism            = true;
            host.Listeners[0].SSL.ClientCertificateRequired           = true;
            host.Listeners[0].SSL.CheckCertificateRevocation          = true;
            host.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => { clientCert = b; return(true); };
            host.RegisterLinkProcessor(linkProcessor);
            host.Open();

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { serviceCert = b; return(true); };
                var wssFactory = new WebSocketTransportFactory();
                wssFactory.Options = o =>
                {
                    o.ClientCertificates.Add(ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, uri.Host));
                };

                ConnectionFactory connectionFactory = new ConnectionFactory(new TransportProvider[] { wssFactory });
                connectionFactory.SASL.Profile = SaslProfile.External;
                Connection connection = await connectionFactory.CreateAsync(new Address(listenAddress));

                Session    session = new Session(connection);
                SenderLink sender  = new SenderLink(session, "sender-" + testName, "q1");
                await sender.SendAsync(new Message("test") { Properties = new Properties()
                                                             {
                                                                 MessageId = testName
                                                             } });

                await connection.CloseAsync();

                Assert.IsTrue(serviceCert != null, "service cert not received");
                Assert.IsTrue(clientCert != null, "client cert not received");
                Assert.IsTrue(listenerLink != null, "link not attached");

                IPrincipal principal = ((ListenerConnection)listenerLink.Session.Connection).Principal;
                Assert.IsTrue(principal != null, "connection pricipal is null");
                Assert.IsTrue(principal.Identity is X509Identity, "identify should be established by client cert");
            }
            finally
            {
                host.Close();
            }
        }
 public ClientToServerLinkEndpoint(ListenerLink link)
     : base(link)
 {
 }
Ejemplo n.º 7
0
 void RemoveCoordinator(ListenerLink link)
 {
     lock (this.coordinators)
     {
         this.coordinators.Remove(link);
     }
 }
Ejemplo n.º 8
0
                static void OnMessage(ListenerLink link, Message message, DeliveryState deliveryState, object state)
                {
                    var thisPtr = (Publisher)state;
                    string errorCondition = null;
                    if (message.ApplicationProperties != null &&
                        (errorCondition = (string)message.ApplicationProperties["errorcondition"]) != null)
                    {
                        link.DisposeMessage(
                            message,
                            new Rejected() { Error = new Error() { Condition = errorCondition, Description = "message was rejected" } },
                            true);
                    }
                    else
                    {
                        var txnState = deliveryState as TransactionalState;
                        if (txnState != null)
                        {
                            Transaction txn = thisPtr.queue.broker.txnManager.GetTransaction(txnState.TxnId);
                            txn.AddOperation(message, onDischarge, thisPtr);
                            txnState.Outcome = new Accepted();
                        }
                        else
                        {
                            thisPtr.queue.Enqueue((BrokerMessage)message);
                            deliveryState = new Accepted();
                        }

                        thisPtr.link.DisposeMessage(message, deliveryState, true);
                    }
                }
Ejemplo n.º 9
0
                public Consumer(TestQueue queue, ListenerLink link, int id)
                {
                    this.queue = queue;
                    this.link = link;
                    this.id = id;

                    link.Closed += this.OnLinkClosed;
                    link.InitializeSender(onCredit, onDispose, this);
                }
Ejemplo n.º 10
0
                public Publisher(TestQueue queue, ListenerLink link, int id)
                {
                    this.queue = queue;
                    this.link = link;
                    this.id = id;

                    link.Closed += this.OnLinkClosed;
                    link.InitializeReceiver(200, onMessage, this);
                }
Ejemplo n.º 11
0
 public void CreatePublisher(ListenerLink link)
 {
     int id = Interlocked.Increment(ref this.currentId);
     Publisher publisher = new Publisher(this, link, id);
     lock (this.publishers)
     {
         this.publishers.Add(id, publisher);
     }
 }
Ejemplo n.º 12
0
 public void CreateConsumer(ListenerLink link)
 {
     int id = Interlocked.Increment(ref this.currentId);
     Consumer consumer = new Consumer(this, link, id);
     lock (this.consumers)
     {
         this.consumers.Add(id, consumer);
     }
 }
Ejemplo n.º 13
0
 public ServerLinkEndpoint(ListenerLink link)
 {
     this.Link = link;
 }
Ejemplo n.º 14
0
        public async Task Should_not_recreate_consumer_when_resource_deleted()
        {
            var host1 = CreateOpenedContainerHost();
            var host2 = CreateContainerHost();
            var host3 = CreateContainerHost();

            ListenerLink listenerLink1 = null;

            host1.CreateTestLinkProcessor().SetHandler(context =>
            {
                listenerLink1 = context.Link;
                return(false);
            });

            await using var connection = await CreateConnection(new[] { host1.Endpoint, host2.Endpoint, host3.Endpoint });

            var consumer = await connection.CreateConsumerAsync("a1", RoutingType.Anycast);

            var receiveTask = consumer.ReceiveAsync(CancellationToken);

            try
            {
                await listenerLink1.CloseAsync(Timeout, new Error(ErrorCode.ResourceDeleted) { Description = "Queue was deleted: a1" });
            }
            catch (Exception)
            {
                // ignored
            }

            await Assert.ThrowsAsync <ConsumerClosedException>(async() => await receiveTask);

            await DisposeHostAndWaitUntilConnectionNotified(host1, connection);

            var waitUntilConnectionRecoveredTask = WaitUntilConnectionRecovered(connection);

            host2.CreateTestLinkProcessor().SetHandler(context =>
            {
                context.Complete(new Error(ErrorCode.NotFound)
                {
                    Description = "Queue: 'a1' does not exist"
                });
                return(true);
            });
            host2.Open();

            // wait until the connection recovered
            await waitUntilConnectionRecoveredTask;

            // make sure that the consumer remains closed
            await Assert.ThrowsAsync <ConsumerClosedException>(async() => await consumer.ReceiveAsync(CancellationToken));

            // perform again auto-recovery cycle, to make sure that
            // no further attempts to recover the consumer will be made
            await DisposeHostAndWaitUntilConnectionNotified(host2, connection);

            waitUntilConnectionRecoveredTask = WaitUntilConnectionRecovered(connection);

            ListenerLink listenerLink3 = null;

            host3.CreateTestLinkProcessor().SetHandler(context =>
            {
                listenerLink3 = context.Link;
                return(false);
            });
            host3.Open();

            // wait until the connection recovered
            await waitUntilConnectionRecoveredTask;

            // make sure that no listener link was created on the final host
            Assert.Null(listenerLink3);
        }
Ejemplo n.º 15
0
            public void AddCoordinator(ListenerLink link)
            {
                lock (this.coordinators)
                {
                    this.coordinators.Add(link);
                }

                link.Closed += (o, e) => this.RemoveCoordinator((ListenerLink)o);
                link.InitializeReceiver(100, OnMessage, this);
            }
 public ServerToClientLinkEndpoint(ListenerLink link)
     : base(link)
 {
 }
Ejemplo n.º 17
0
            static void OnMessage(ListenerLink link, Message message, DeliveryState deliveryState, object state)
            {
                var thisPtr = (TxnManager)state;
                object body;
                try
                {
                    body = Message.Decode(((BrokerMessage)message).Buffer).Body;
                }
                catch (Exception exception)
                {
                    Trace.WriteLine(TraceLevel.Error, exception.Message);
                    link.DisposeMessage(
                        message,
                        new Rejected() { Error = new Error() { Condition = ErrorCode.DecodeError, Description = "Cannot decode txn message" } },
                        true);

                    return;
                }

                if (body is Declare)
                {
                    int txnId = thisPtr.CreateTransaction();
                    var outcome = new Declared() { TxnId = BitConverter.GetBytes(txnId) };
                    link.DisposeMessage(message, outcome, true);
                }
                else if (body is Discharge)
                {
                    Discharge discharge = (Discharge)body;
                    int txnId = BitConverter.ToInt32(discharge.TxnId, 0);
                    Transaction txn;
                    if (thisPtr.transactions.TryGetValue(txnId, out txn))
                    {
                        lock (thisPtr.transactions)
                        {
                            thisPtr.transactions.Remove(txnId);
                        }

                        txn.Discharge(discharge.Fail);
                        link.DisposeMessage(message, new Accepted(), true);
                    }
                    else
                    {
                        link.DisposeMessage(
                            message,
                            new Rejected() { Error = new Error() { Condition = ErrorCode.NotFound, Description = "Transaction not found" } },
                            true);
                    }
                }
                else
                {
                    link.DisposeMessage(
                        message,
                        new Rejected() { Error = new Error() { Condition = ErrorCode.NotImplemented, Description = "Unsupported message body" } },
                        true);
                }
            }
Ejemplo n.º 18
0
            static void OnMessage(ListenerLink link, Message message, DeliveryState deliveryState, object state)
            {
                var    thisPtr = (TxnManager)state;
                object body;

                try
                {
                    body = Message.Decode(((BrokerMessage)message).Buffer).Body;
                }
                catch (Exception exception)
                {
                    Trace.WriteLine(TraceLevel.Error, exception.Message);
                    link.DisposeMessage(
                        message,
                        new Rejected()
                    {
                        Error = new Error()
                        {
                            Condition = ErrorCode.DecodeError, Description = "Cannot decode txn message"
                        }
                    },
                        true);

                    return;
                }

                if (body is Declare)
                {
                    int txnId   = thisPtr.CreateTransaction();
                    var outcome = new Declared()
                    {
                        TxnId = BitConverter.GetBytes(txnId)
                    };
                    link.DisposeMessage(message, outcome, true);
                }
                else if (body is Discharge)
                {
                    Discharge   discharge = (Discharge)body;
                    int         txnId     = BitConverter.ToInt32(discharge.TxnId, 0);
                    Transaction txn;
                    if (thisPtr.transactions.TryGetValue(txnId, out txn))
                    {
                        lock (thisPtr.transactions)
                        {
                            thisPtr.transactions.Remove(txnId);
                        }

                        txn.Discharge(discharge.Fail);
                        link.DisposeMessage(message, new Accepted(), true);
                    }
                    else
                    {
                        link.DisposeMessage(
                            message,
                            new Rejected()
                        {
                            Error = new Error()
                            {
                                Condition = ErrorCode.NotFound, Description = "Transaction not found"
                            }
                        },
                            true);
                    }
                }
                else
                {
                    link.DisposeMessage(
                        message,
                        new Rejected()
                    {
                        Error = new Error()
                        {
                            Condition = ErrorCode.NotImplemented, Description = "Unsupported message body"
                        }
                    },
                        true);
                }
            }
Ejemplo n.º 19
0
 public override void OnLinkClosed(ListenerLink link, Error error)
 => CancelFlowTask();