public void ShouldSkipAuthOnWrongAuthScheme()
        {
            var builder = new AppBuilderFactory().Create();

            var context = new OwinContext();
            OwinRequest request = (OwinRequest)context.Request;
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Basic " });

            var response = context.Response;

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) => 
                    {
                        response.StatusCode = 200;
                        return Task.FromResult<object>(null);
                    }), 
                builder, 
                new HawkAuthenticationOptions
                {
                    Credentials = GetCredential
                }
            );

            middleware.Invoke(context);

            Assert.IsNotNull(response);
            Assert.AreEqual(200, response.StatusCode);
        }
        public void ShouldFailOnInvalidAuthFormat()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

            var request = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " +
                ""});

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) =>
                {
                    response.StatusCode = 401;
                    return Task.FromResult<object>(null);
                }),
               builder,
               new HawkAuthenticationOptions
               {
                   Credentials = GetCredential
               }
            );

            middleware.Invoke(request, response);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Invalid header format", logger.Messages[0]);
        }
        public void ShouldFailOnMissingAuthAttribute()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));
            var context = new OwinContext();
            var request = (OwinRequest)context.Request;
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " + 
                "ts = \"1353788437\", mac = \"/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=\", ext = \"hello\""});

            var response = (OwinResponse)context.Response;
            response.StatusCode = 401;

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) => 
                    {
                        response.StatusCode = 401;
                        return Task.FromResult<object>(null);
                    }),
                builder,
                new HawkAuthenticationOptions
                {
                    Credentials = GetCredential
                }
            );

            middleware.Invoke(context);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Missing attributes", logger.Messages[0]);
        }
 public void InitializeMethodIsCalledWithProperties()
 {
     var serverFactory = new InitializePatternTwo();
     var adapter = new ServerFactoryAdapter(serverFactory);
     IAppBuilder builder = new AppBuilderFactory().Create();
     adapter.Initialize(builder);
     builder.Properties["called"].ShouldBe(serverFactory);
 }
 public void CreateMethodCalledWithAppAndProperties()
 {
     var serverFactory = new CreatePatternOne();
     var adapter = new ServerFactoryAdapter(serverFactory);
     IAppBuilder builder = new AppBuilderFactory().Create();
     IDisposable disposable = adapter.Create(builder);
     builder.Properties["called"].ShouldBe(serverFactory);
     builder.Properties["app"].ShouldNotBe(null);
     builder.Properties["properties"].ShouldBeSameAs(builder.Properties);
     disposable.ShouldBe(serverFactory);
 }
        public void ShouldFailOnCredentialsFuncException()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

            var ts = Hawk.ConvertToUnixTimestamp(DateTime.Now).ToString();

            var context = new OwinContext();
            var request = (OwinRequest)context.Request;
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetHeader("Host", new string[] { "localhost" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " +
                "id = \"456\", ts = \"" + ts + "\", nonce=\"k3j4h2\", mac = \"qrP6b5tiS2CO330rpjUEym/USBM=\", ext = \"hello\""});

            var response = (OwinResponse)context.Response;

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) =>
                {
                    response.StatusCode = 401;
                    return Task.FromResult<object>(null);
                }),
               builder,
               new HawkAuthenticationOptions
               {
                   Credentials = (id) => { throw new Exception("Invalid"); }
               }
            );

            middleware.Invoke(context);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Unknown user", logger.Messages[0]);
        }
        public void ShouldReturnChallengeOnEmptyAuthHeaderWithStatusUnauthorized()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

            var ts = Math.Floor(Hawk.ConvertToUnixTimestamp(DateTime.Now) / 1000).ToString();

            var request = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetHeader("Host", new string[] { "localhost" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                            new AppFuncTransition((env) =>
                            {
                                response.StatusCode = 401;
                                return Task.FromResult<object>(null);
                            }),
                           builder,
                           new HawkAuthenticationOptions
                           {
                               Credentials = (id) =>
                               {
                                   return Task.FromResult(new HawkCredential
                                   {
                                       Id = "123",
                                       Algorithm = "hmac-sha-0",
                                       Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                                       User = "******"
                                   });
                               }
                           }
                        );

            middleware.Invoke(request, response);

            Assert.AreEqual(401, response.StatusCode);
            Assert.IsNotNull(((IDictionary<string, string[]>)response.Environment["owin.ResponseHeaders"])["WWW-Authenticate"]);
        }
        public void ShouldParseValidAuthHeaderWithSha256()
        {
            var credential = new HawkCredential
            {
                Id = "123",
                Algorithm = "hmacsha256",
                Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                User = "******"
            };

            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

            var ts = Math.Floor(Hawk.ConvertToUnixTimestamp(DateTime.Now) / 1000);
            var mac = Hawk.CalculateMac("example.com", "get", new Uri("http://example.com:8080/resource/4?filter=a"), "hello", ts.ToString(), "j4h3g2", credential, "header");

            var request = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetHeader("Host", new string[] { "example.com" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " +
                string.Format("id = \"456\", ts = \"{0}\", nonce=\"j4h3g2\", mac = \"{1}\", ext = \"hello\"",
                ts, mac)});

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                            new AppFuncTransition((env) =>
                            {
                                response.StatusCode = 200;
                                return Task.FromResult<object>(null);
                            }),
                           builder,
                           new HawkAuthenticationOptions
                           {
                               Credentials = (id) => Task.FromResult(credential)
                           }
                        );

            middleware.Invoke(request, response);

            Assert.AreEqual(200, response.StatusCode);
            Assert.IsTrue(logger.Messages.Count == 0);
        }
        public void ShouldFailOnUnknownCredentialsAlgorithm()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

            var ts = Math.Floor(Hawk.ConvertToUnixTimestamp(DateTime.Now) / 1000).ToString();

            var request = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetHeader("Host", new string[] { "localhost" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " +
                "id = \"456\", ts = \"" + ts + "\", nonce=\"k3j4h2\", mac = \"qrP6b5tiS2CO330rpjUEym/USBM=\", ext = \"hello\""});

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                            new AppFuncTransition((env) =>
                            {
                                response.StatusCode = 401;
                                return Task.FromResult<object>(null);
                            }),
                           builder,
                           new HawkAuthenticationOptions
                           {
                               Credentials = (id) =>
                               {
                                   return Task.FromResult(new HawkCredential
                                   {
                                       Id = "123",
                                       Algorithm = "hmac-sha-0",
                                       Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                                       User = "******"
                                   });
                               }
                           }
                        );

            middleware.Invoke(request, response);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Unknown algorithm", logger.Messages[0]);
        }
        public void ShouldParseValidAuthHeaderAndPayloadWithSha256()
        {
            var credential = new HawkCredential
            {
                Id = "123",
                Algorithm = "sha256",
                Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                User = "******"
            };

            var body = "hello world";
            var bodyBytes = Encoding.UTF8.GetBytes(body);
            var ms = new MemoryStream();
            ms.Write(bodyBytes, 0, bodyBytes.Length);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

            var hash = Hawk.CalculatePayloadHash(body, "text/plain", credential);
            var ts = Hawk.ConvertToUnixTimestamp(DateTime.Now);
            var mac = Hawk.CalculateMac("example.com", "post", new Uri("http://example.com:8080/resource/4?filter=a"), "hello", ts.ToString(), "j4h3g2", credential, "header", hash);

            var context = new OwinContext();
            var request = (OwinRequest)context.Request;
            
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "post";
            request.Body = ms;
            request.SetHeader("Host", new string[] { "example.com" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.ContentType = "text/plain";
            request.SetHeader("Authorization", new string[] { "Hawk " + 
                string.Format("id = \"456\", ts = \"{0}\", nonce=\"j4h3g2\", mac = \"{1}\", ext = \"hello\", hash=\"{2}\"",
                ts, mac, hash)});

            var response = (OwinResponse)context.Response;

            var middleware = new HawkAuthenticationMiddleware(
                            new AppFuncTransition((env) =>
                            {
                                response.StatusCode = 200;
                                return Task.FromResult<object>(null);
                            }),
                           builder,
                           new HawkAuthenticationOptions
                           {
                               Credentials = (id) => Task.FromResult(credential)
                           }
                        );

            middleware.Invoke(context);

            Assert.AreEqual(200, response.StatusCode);
            Assert.IsTrue(logger.Messages.Count == 0);
        }
        public void ShouldFailOnUnknownBadMac()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

            var ts = Hawk.ConvertToUnixTimestamp(DateTime.Now).ToString();

            var context = new OwinContext();
            var request = (OwinRequest)context.Request;
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetHeader("Host", new string[] { "localhost" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " + 
                "id = \"456\", ts = \"" + ts + "\", nonce=\"k3j4h2\", mac = \"/qwS4UjfVWMcU4jlr7T/wuKe3dKijvTvSos=\", ext = \"hello\""});

            var response = (OwinResponse)context.Response;

            var middleware = new HawkAuthenticationMiddleware(
                            new AppFuncTransition((env) =>
                            {
                                response.StatusCode = 401;
                                return Task.FromResult<object>(null);
                            }),
                           builder,
                           new HawkAuthenticationOptions
                           {
                               Credentials = (id) =>
                               {
                                   return Task.FromResult(new HawkCredential
                                   {
                                       Id = "123",
                                       Algorithm = "sha256",
                                       Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                                       User = "******"
                                   });
                               }
                           }
                        );

            middleware.Invoke(context);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Bad mac", logger.Messages[0]);
        }