public async Task AuthorizedRequestWhenCertIsNotSet()
        {
            var next = Mock.Of <RequestDelegate>();

            var listener = new Mock <IWebSocketListener>();

            listener.Setup(wsl => wsl.SubProtocol).Returns("abc");
            listener.Setup(
                wsl => wsl.ProcessWebSocketRequestAsync(
                    It.IsAny <WebSocket>(),
                    It.IsAny <Option <EndPoint> >(),
                    It.IsAny <EndPoint>(),
                    It.IsAny <string>()))
            .Returns(Task.CompletedTask);

            var registry = new WebSocketListenerRegistry();

            registry.TryRegister(listener.Object);

            HttpContext httpContext   = this.ContextWithRequestedSubprotocols("abc");
            var         authenticator = new Mock <IAuthenticator>();

            authenticator.Setup(p => p.AuthenticateAsync(It.IsAny <IClientCredentials>())).ReturnsAsync(false);

            IHttpProxiedCertificateExtractor certExtractor = new HttpProxiedCertificateExtractor(authenticator.Object, Mock.Of <IClientCredentialsFactory>(), "hub", "edge", "proxy");

            var middleware = new WebSocketHandlingMiddleware(next, registry, Task.FromResult(certExtractor));
            await middleware.Invoke(httpContext);

            authenticator.Verify(auth => auth.AuthenticateAsync(It.IsAny <IClientCredentials>()), Times.Never);
            listener.VerifyAll();
        }
Example #2
0
        public async Task AuthenticateRequestTestX509ApiProxyForward_InvalidCertificate_ShoudThrow()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId       = "device_2";
            string apiProxyId     = "iotedgeApiProxy";
            var    httpContext    = new DefaultHttpContext();

            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var    certContentBytes  = Encoding.UTF8.GetBytes("Invalid cert");
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString  = $"{certContentBase64}";

            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            string sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{deviceId}/modules/{apiProxyId}");

            httpContext.Request.Headers.Add(HeaderNames.Authorization, new StringValues(sasToken));
            var authenticator = new Mock <IAuthenticator>();

            var identityFactory = new ClientCredentialsFactory(new IdentityProvider(iothubHostName));

            var httpRequestAuthenticator = new HttpProxiedCertificateExtractor(authenticator.Object, identityFactory, iothubHostName, deviceId, apiProxyId);
            await Assert.ThrowsAsync <AuthenticationException>(() => httpRequestAuthenticator.GetClientCertificate(httpContext));

            authenticator.VerifyAll();
        }
Example #3
0
        public async Task AuthenticateRequestTestX509ApiProxyForward_NoSasToken_ShouldThrow()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId       = "device_2";
            string apiProxyId     = "iotedgeApiProxy";
            var    httpContext    = new DefaultHttpContext();

            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var    certContentBytes  = CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString  = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";

            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            var authenticator = new Mock <IAuthenticator>();

            var identityFactory = new ClientCredentialsFactory(new IdentityProvider(iothubHostName));

            var httpRequestAuthenticator = new HttpProxiedCertificateExtractor(authenticator.Object, identityFactory, iothubHostName, deviceId, apiProxyId);
            var ex = await Assert.ThrowsAsync <AuthenticationException>(() => httpRequestAuthenticator.GetClientCertificate(httpContext));

            Assert.Equal($"Unable to authorize proxy iotedgeApiProxy to forward device certificate - Authorization header missing", ex.Message);
            authenticator.VerifyAll();
        }
Example #4
0
        public async Task AuthenticateRequestTestX509ApiProxyForward_ProxyAuthSuccess_ShouldReturnCertificate()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId       = "device_2";
            string apiProxyId     = "iotedgeApiProxy";
            var    httpContext    = new DefaultHttpContext();

            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var    certContentBytes  = CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString  = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";

            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            string sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{deviceId}/modules/{apiProxyId}");

            httpContext.Request.Headers.Add(HeaderNames.Authorization, new StringValues(sasToken));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            var authenticator = new Mock <IAuthenticator>();

            authenticator.Setup(a => a.AuthenticateAsync(It.Is <IClientCredentials>(c => c.Identity.Id == "device_2/iotedgeApiProxy"))).ReturnsAsync(true);

            var identityFactory = new ClientCredentialsFactory(new IdentityProvider(iothubHostName));

            var httpRequestAuthenticator = new HttpProxiedCertificateExtractor(authenticator.Object, identityFactory, iothubHostName, deviceId, apiProxyId);
            var cert = await httpRequestAuthenticator.GetClientCertificate(httpContext);

            Assert.True(cert.HasValue);
            authenticator.VerifyAll();
        }
Example #5
0
        public async Task AuthenticateRequestTest_NoForwardedCertificate_ShoultReturnNone()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId       = "device_2";
            string apiProxyId     = "iotedgeApiProxy";
            var    httpContext    = new DefaultHttpContext();

            httpContext.Connection.RemoteIpAddress = new IPAddress(0);

            var authenticator   = new Mock <IAuthenticator>();
            var identityFactory = new ClientCredentialsFactory(new IdentityProvider(iothubHostName));

            var httpRequestAuthenticator = new HttpProxiedCertificateExtractor(authenticator.Object, identityFactory, iothubHostName, deviceId, apiProxyId);
            var cert = await httpRequestAuthenticator.GetClientCertificate(httpContext);

            Assert.Equal(Option.None <X509Certificate2>(), cert);
            authenticator.VerifyAll();
        }
Example #6
0
        protected override void Load(ContainerBuilder builder)
        {
            // IValidator
            builder.Register(c => new MethodRequestValidator())
            .As <IValidator <MethodRequest> >()
            .SingleInstance();

            // IWebSocketListenerRegistry
            builder.Register(c => new WebSocketListenerRegistry())
            .As <IWebSocketListenerRegistry>()
            .SingleInstance();

            // IHttpProxiedCertificateExtractor
            builder.Register(
                async c =>
            {
                var authenticator = await c.Resolve <Task <IAuthenticator> >();
                var credFactory   = c.Resolve <IClientCredentialsFactory>();
                IHttpProxiedCertificateExtractor httpProxiedCertificateExtractor = new HttpProxiedCertificateExtractor(authenticator, credFactory, this.iothubHostName, this.edgeDeviceId, this.proxyModuleId);
                return(httpProxiedCertificateExtractor);
            })
            .As <Task <IHttpProxiedCertificateExtractor> >()
            .SingleInstance();

            // IHttpAuthenticator
            builder.Register(
                async c =>
            {
                var authenticator = await c.Resolve <Task <IAuthenticator> >();
                var credFactory   = c.Resolve <IClientCredentialsFactory>();
                var httpProxiedCertificateExtractor         = await c.Resolve <Task <IHttpProxiedCertificateExtractor> >();
                IHttpRequestAuthenticator httpAuthenticator = new HttpRequestAuthenticator(authenticator, credFactory, this.iothubHostName, httpProxiedCertificateExtractor);
                return(httpAuthenticator);
            })
            .As <Task <IHttpRequestAuthenticator> >()
            .SingleInstance();

            base.Load(builder);
        }