public void PostRequestToUsersEndpointReturnsResponseBody() { var request = new Request("/users", "POST", "bob"); var userRepository = new UserRepository(); var userService = new UserService(userRepository); var requestRouter = new RequestRouter(request, userService); var expected = "Bob has been added"; var actual = requestRouter.Route().Body; Assert.Equal(expected, actual); }
public void RequestWithoutResourceReturnsError(string path, string method, string body) { var request = new Request(path, method, body); var userRepository = new UserRepository(); var userService = new UserService(userRepository); var requestRouter = new RequestRouter(request, userService); var expected = "uri resource empty"; var actual = requestRouter.Route().Body; Assert.Contains(expected, actual); }
public void IncorrectPathReturns404(string path, string method, string body) { var userRepository = new UserRepository(); var userService = new UserService(userRepository); var request = new Request(path, method, body); var requestRouter = new RequestRouter(request, userService); var expected = "invalid path"; var actual = requestRouter.Route(); Assert.Equal(expected, actual.Body); Assert.Equal(404, actual.StatusCode); }
public void AddRequestRouting_WithRequestBaseClassAdded_AddsToRoutingTable() { // Arrange var router = new RequestRouter(); router.AddRequestRouting <Request, ISender>(address); // Act router.AddRequestRouting <SubRequest, ISender>(address); // Assert Assert.That(router.RoutingTable.ContainsKey(typeof(SubRequest)), Is.True); }
public void AddRequestRouting_WithSameAddressAsExistingRouting_DoesNothing() { // Arrange var router = new RequestRouter(); router.AddRequestRouting <Request, ISender>(address); // Act TestDelegate addTopicRouting = () => router.AddRequestRouting <Request, ISender>(address); // Assert Assert.That(addTopicRouting, Throws.Nothing); }
public void AddRequestRouting_WithDifferentAddressToExistingRouting_ThrowsRoutingAlreadyRegisteredException() { // Arrange var router = new RequestRouter(); router.AddRequestRouting <Request, ISender>(address); // Act TestDelegate addRouting = () => router.AddRequestRouting <Request, ISender>(address2); // Assert Assert.That(addRouting, Throws.TypeOf <RoutingAlreadyRegisteredException <SenderRouting> >()); }
public void RoutingFor_WithSubClassRoutingAdded_ReturnsFalse() { // Arrange var router = new RequestRouter(); router.AddRequestRouting <SubRequest, ISender>(address); // Act var hasRouting = router.RoutingFor <Request>(out var routing); // Assert Assert.That(hasRouting, Is.False); }
public void RoutingFor_WithRoutingAdded_ReturnsRoutingWithSameSenderType() { // Arrange var router = new RequestRouter(); router.AddRequestRouting <Request, ISender>(address); // Act var hasRouting = router.RoutingFor <Request>(out var routing); // Assert Assert.That(routing.SenderType, Is.EqualTo(typeof(ISender))); }
public static bool Authenticate(HttpContext httpContext, ServerStore serverStore, string database, string remoteTask) { var feature = httpContext.Features.Get <IHttpAuthenticationFeature>() as RavenServer.AuthenticateConnection; if (feature == null) // we are not using HTTPS { return(true); } switch (feature.Status) { case RavenServer.AuthenticationStatus.Operator: case RavenServer.AuthenticationStatus.ClusterAdmin: // we can trust this certificate return(true); case RavenServer.AuthenticationStatus.Allowed: // check that the certificate is allowed for this database. if (feature.CanAccess(database, requireAdmin: false)) { return(true); } RequestRouter.UnlikelyFailAuthorization(httpContext, database, feature, AuthorizationStatus.RestrictedAccess); return(false); case RavenServer.AuthenticationStatus.UnfamiliarIssuer: RequestRouter.UnlikelyFailAuthorization(httpContext, database, feature, AuthorizationStatus.RestrictedAccess); return(false); case RavenServer.AuthenticationStatus.UnfamiliarCertificate: using (serverStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context)) using (context.OpenReadTransaction()) { if (serverStore.Cluster.TryReadPullReplicationDefinition(database, remoteTask, context, out var pullReplication)) { var cert = httpContext.Connection.ClientCertificate; if (pullReplication.CanAccess(cert?.Thumbprint)) { return(true); } } RequestRouter.UnlikelyFailAuthorization(httpContext, database, feature, AuthorizationStatus.RestrictedAccess); return(false); } default: throw new ArgumentException($"This is a bug, we should deal with '{feature?.Status}' authentication status at RequestRoute.TryAuthorize function."); } }
public void GetRequestToUsersEndpointReturnsListOfUsers() { var request = new Request("/users", "GET", ""); var userRepository = new UserRepository(); var userService = new UserService(userRepository); userService.AddUserToList("peter"); var requestRouter = new RequestRouter(request, userService); var expected = "Martyna, Peter"; var actual = requestRouter.Route().Body; Assert.Equal(expected, actual); }
public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory) { app.UseWebSockets(new WebSocketOptions { // TODO: KeepAlive causes "Unexpect reserved bit set" (we are sending our own hearbeats, so we do not need this) //KeepAliveInterval = Debugger.IsAttached ? // TimeSpan.FromHours(24) : TimeSpan.FromSeconds(30), KeepAliveInterval = TimeSpan.FromHours(24), ReceiveBufferSize = 4096, }); _router = app.ApplicationServices.GetService <RequestRouter>(); _server = app.ApplicationServices.GetService <RavenServer>(); app.Run(RequestHandler); }
public async Task ExecutesHandler() { var exitHandler = Substitute.For <IExitHandler>(); var collection = new HandlerCollection { exitHandler }; IRequestRouter mediator = new RequestRouter(collection, new Serializer()); var notification = new Notification("exit", null); await mediator.RouteNotification(notification); await exitHandler.Received(1).Handle(); }
public Builder(string name) { this.name = name; TopicRouter = new TopicRouter(); MonitorCache = new MonitorCache(); RequestRouter = new RequestRouter(); PackageFactory = new PackageFactory(); TopicDispatcher = new TopicDispatcher(); RequestDispatcher = new RequestDispatcher(); SubscriptionsCache = new SubscriptionsCache(); SerializerCache = new SerializerCache(); SenderCache = new SenderCache(RequestRouter, MonitorCache); ReceiverCache = new ReceiverCache(MonitorCache); PublisherCache = new PublisherCache(MonitorCache); SubscriberCache = new SubscriberCache(TopicRouter, MonitorCache, SubscriptionsCache); }
// ... public PingModule(IProvider <IPAddress> addressProvider) { _cancelTokenSource = new CancellationTokenSource(); _requestProducer = new PingRequestProducerWorkStage(1, addressProvider, NextRequestFor, _cancelTokenSource.Token); _disconnectedPinger = new PingWorkStage(2, 10 * 2, _cancelTokenSource.Token); _slowAddressesPinger = new PingWorkStage(2, 10 * 2, _cancelTokenSource.Token); _normalPinger = new PingWorkStage(3, 10 * 2, _cancelTokenSource.Token); _requestRouter = new RequestRouter(RoutePingRequest); _replyProcessor = new PingReplyProcessingWorkStage(2, 10 * 2, _cancelTokenSource.Token); // connect the pipeline _requestProducer.ConnectTo(_requestRouter); _disconnectedPinger.ConnectTo(_replyProcessor); _slowAddressesPinger.ConnectTo(_replyProcessor); _normalPinger.ConnectTo(_replyProcessor); _replyProcessor.ConnectTo(this); }
private static void CheckVersionAndWrapException(HttpContext context, ref Exception e) { if (RequestRouter.TryGetClientVersion(context, out var version) == false) { return; } if (version.Major == '3') { e = new ClientVersionMismatchException( $"RavenDB does not support interaction between Client API major version 3 and Server version {RavenVersionAttribute.Instance.MajorVersion} when major version does not match. Client: {version}. " + $"Server: {RavenVersionAttribute.Instance.AssemblyVersion}", e); } else if (HasInvalidCommandTypeException(e)) { RequestRouter.CheckClientVersionAndWrapException(version, ref e); }
public async Task ExecutesHandler() { var cancelRequestHandler = Substitute.For <ICancelRequestHandler>(); var collection = new HandlerCollection { cancelRequestHandler }; IRequestRouter mediator = new RequestRouter(collection); var @params = new CancelParams() { Id = Guid.NewGuid() }; var notification = new Notification("$/cancelRequest", JObject.Parse(JsonConvert.SerializeObject(@params))); await mediator.RouteNotification(notification); await cancelRequestHandler.Received(1).Handle(Arg.Any <CancelParams>()); }
public async Task ExecutesHandler() { var codeActionHandler = Substitute.For <ICodeActionHandler>(); var collection = new HandlerCollection { codeActionHandler }; IRequestRouter mediator = new RequestRouter(collection, new Serializer()); var id = Guid.NewGuid().ToString(); var @params = new CodeActionParams() { TextDocument = "TextDocument", Range = "Range", Context = "Context" }; var request = new Request(id, "textDocument/codeAction", JObject.Parse(JsonConvert.SerializeObject(@params))); var response = await mediator.RouteRequest(request); await codeActionHandler.Received(1).Handle(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>()); }
public async Task ExecutesHandler() { var executeCommandHandler = Substitute.For <IExecuteCommandHandler>(); var collection = new HandlerCollection { executeCommandHandler }; IRequestRouter mediator = new RequestRouter(collection, new Serializer()); var id = Guid.NewGuid().ToString(); var @params = new ExecuteCommandParams() { Command = "123" }; var request = new Request(id, "workspace/executeCommand", JObject.Parse(JsonConvert.SerializeObject(@params))); var response = await mediator.RouteRequest(request); await executeCommandHandler.Received(1).Handle(Arg.Any <ExecuteCommandParams>(), Arg.Any <CancellationToken>()); }
private void ApplyBackwardCompatibility(DatabaseSmugglerOptionsServerSide options) { if (options == null) { return; } if (((options.OperateOnTypes & DatabaseItemType.DatabaseRecord) != 0) && (options.OperateOnDatabaseRecordTypes == DatabaseRecordItemType.None)) { options.OperateOnDatabaseRecordTypes = DatabaseSmugglerOptions.DefaultOperateOnDatabaseRecordTypes; } if (RequestRouter.TryGetClientVersion(HttpContext, out var version) == false) { return; } if (version.Major != RavenVersionAttribute.Instance.MajorVersion) { return; } #pragma warning disable 618 if (version.Minor < 2 && options.OperateOnTypes.HasFlag(DatabaseItemType.Counters)) #pragma warning restore 618 { options.OperateOnTypes |= DatabaseItemType.CounterGroups; } // only all 4.0 and 4.1 less or equal to 41006 if (version.Revision < 50 || version.Revision > 41006) { return; } if (options.OperateOnTypes.HasFlag(DatabaseItemType.Documents)) { options.OperateOnTypes |= DatabaseItemType.Attachments; } }
public void SetUp() { const string verb = "POST"; const string applicationPath = "/"; var uri = new Uri("http://example.com/resources/1"); HttpContextBase.Request.HttpMethod.Returns(verb); HttpContextBase.Request.ApplicationPath.Returns(applicationPath); HttpContextBase.Request.Url.Returns(uri); var inputStream = Substitute.For <Stream>(); inputStream.CanRead.Returns(false); HttpContextBase.Request.InputStream.Returns(inputStream); RequestRouter.When(x => x.FindRequestHandler(verb, applicationPath, uri)).Do(_ => { throw new Exception(); }); _piccoloContext = new PiccoloContext(HttpContextBase); Engine.ProcessRequest(_piccoloContext); }
public System.Data.DataSet Read(string targetCategory, string viewName, NBK.Common.Foundations.Utilities.FilterCriteria[] filterCriteria, NBK.Common.Foundations.Utilities.SortCriteria[] sortCriteria, int startIndex, int numberOfRecords, ref int totalNumberOfRecords) { try { Header = SoapHeaderHelper <WebServiceHeader> .GetInputHeader("Header"); const string location = "NBK.EAI.Services.Web.NBKCentral.Read"; using (LogEnterExit lee = new LogEnterExit(location)) { string _instanceName = ""; if (string.IsNullOrEmpty(viewName)) { _instanceName = "READ_" + targetCategory + "_VW_" + "Default"; } else { _instanceName = "READ_" + targetCategory + "_VW_" + viewName; } //Do data validation before delegating to Request Router CheckArgument(targetCategory != null && targetCategory != "", "Target Category cannot be null or empty"); //Delegate the call to the Request Router class DataSet result = RequestRouter.Read(GetCallContext(), targetCategory, viewName, filterCriteria, sortCriteria, startIndex, numberOfRecords, ref totalNumberOfRecords); return(result); } } catch (Exception ex) { BaseException.Publish(ex); //LogCallContext(); throw ExceptionUtils.GetSOAPException(ex); } }
public void Configuration(IAppBuilder app) { var cachePath = RoleEnvironment.IsAvailable ? RoleEnvironment.GetLocalResource("fileCache").RootPath : Path.Combine(Path.GetTempPath(), "XML2JSON.Web.OWIN"); Directory.CreateDirectory(cachePath); var cache = new FileCache(cachePath); cache.MaxCacheSize = RoleEnvironment.IsAvailable ? RoleEnvironment.GetLocalResource("fileCache").MaximumSizeInMegabytes * 1024 : 2048 * 1024; //2GB //when the max size is reached, purge everything more than 24 hours old and hope for the best! cache.MaxCacheSizeReached += (s, e) => cache.Flush(DateTime.UtcNow.Subtract(TimeSpan.FromDays(1))); var router = new RequestRouter { Cache = cache }; app.Run(router.HandleRequest); }
public void Configuration(IAppBuilder app) { var cachePath = RoleEnvironment.IsAvailable ? RoleEnvironment.GetLocalResource("fileCache").RootPath : Path.Combine(Path.GetTempPath(), "PokerOdds.Web.OWIN"); Directory.CreateDirectory(cachePath); _cache = new FileBackedMemoryCache("cache", cachePath); _cache.MaxCacheSize = RoleEnvironment.IsAvailable ? RoleEnvironment.GetLocalResource("fileCache").MaximumSizeInMegabytes * 1024L * 1024L : 2048L * 1024L * 1024L; //2GB _cache.MaxCacheSizeReached += MaxCacheSizeReached; PrimeCache(); var router = new RequestRouter { Cache = _cache }; app.Run(router.HandleRequest); }
public async Task ApplyCommand() { using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context)) { if (ServerStore.IsLeader() == false) { throw new NoLeaderException("Not a leader, cannot accept commands."); } HttpContext.Response.Headers["Reached-Leader"] = "true"; var commandJson = await context.ReadForMemoryAsync(RequestBodyStream(), "external/rachis/command"); CommandBase command; try { command = CommandBase.CreateFrom(commandJson); } catch (InvalidOperationException e) { RequestRouter.AssertClientVersion(HttpContext, e); throw; } switch (command) { case AddDatabaseCommand addDatabase: if (addDatabase.Record.Topology.Count == 0) { ServerStore.AssignNodesToDatabase(ServerStore.GetClusterTopology(), addDatabase.Record); } break; case AddOrUpdateCompareExchangeBatchCommand batchCmpExchange: batchCmpExchange.ContextToWriteResult = context; break; case CompareExchangeCommandBase cmpExchange: cmpExchange.ContextToWriteResult = context; break; } var isClusterAdmin = IsClusterAdmin(); command.VerifyCanExecuteCommand(ServerStore, context, isClusterAdmin); var(etag, result) = await ServerStore.Engine.PutAsync(command); HttpContext.Response.StatusCode = (int)HttpStatusCode.OK; var ms = context.CheckoutMemoryStream(); try { using (var writer = new BlittableJsonTextWriter(context, ms)) { context.Write(writer, new DynamicJsonValue { [nameof(ServerStore.PutRaftCommandResult.RaftCommandIndex)] = etag, [nameof(ServerStore.PutRaftCommandResult.Data)] = result }); writer.Flush(); } // now that we know that we properly serialized it ms.Position = 0; await ms.CopyToAsync(ResponseBodyStream()); } finally { context.ReturnMemoryStream(ms); } } }
public void SetUp() { _routeHandlerLookupResult = RequestRouter.FindRequestHandler("get", string.Empty, new Uri("http://test.com/specificity/static", UriKind.Absolute)); }
public void SetUp() { _routeHandlerLookupResult = RequestRouter.FindRequestHandler("get", string.Empty, new Uri("http://test.com/level-1/level-2", UriKind.Absolute)); }
public static async ValueTask <bool> AuthenticateAsync(HttpContext httpContext, ServerStore serverStore, string database, string remoteTask) { var feature = httpContext.Features.Get <IHttpAuthenticationFeature>() as RavenServer.AuthenticateConnection; if (feature == null) // we are not using HTTPS { return(true); } switch (feature.Status) { case RavenServer.AuthenticationStatus.Operator: case RavenServer.AuthenticationStatus.ClusterAdmin: // we can trust this certificate return(true); case RavenServer.AuthenticationStatus.Allowed: // check that the certificate is allowed for this database. if (feature.CanAccess(database, requireAdmin: false)) { return(true); } await RequestRouter.UnlikelyFailAuthorizationAsync(httpContext, database, feature, AuthorizationStatus.RestrictedAccess); return(false); case RavenServer.AuthenticationStatus.UnfamiliarIssuer: await RequestRouter.UnlikelyFailAuthorizationAsync(httpContext, database, feature, AuthorizationStatus.RestrictedAccess); return(false); case RavenServer.AuthenticationStatus.UnfamiliarCertificate: using (serverStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context)) using (context.OpenReadTransaction()) { if (serverStore.Cluster.TryReadPullReplicationDefinition(database, remoteTask, context, out var pullReplication)) { var cert = httpContext.Connection.ClientCertificate; #pragma warning disable CS0618 // Type or member is obsolete if (pullReplication.Certificates != null && pullReplication.Certificates.Count > 0) { if (pullReplication.Certificates.ContainsKey(cert.Thumbprint)) { return(true); } } #pragma warning restore CS0618 // Type or member is obsolete else { if (serverStore.Cluster.IsReplicationCertificate(context, database, remoteTask, cert, out _)) { return(true); } if (serverStore.Cluster.IsReplicationCertificateByPublicKeyPinningHash(context, database, remoteTask, cert, serverStore.Configuration.Security, out _)) { return(true); } } } await RequestRouter.UnlikelyFailAuthorizationAsync(httpContext, database, feature, AuthorizationStatus.RestrictedAccess); return(false); } default: throw new ArgumentException($"This is a bug, we should deal with '{feature?.Status}' authentication status at RequestRoute.TryAuthorize function."); } }
public PiccoloHttpHandler(Assembly assembly, bool applyCustomConfiguration) { _configuration = Bootstrapper.ApplyConfiguration(assembly, applyCustomConfiguration); _requestRouter = new RequestRouter(_configuration.RequestHandlers); _requestHandlerInvoker = new RequestHandlerInvoker(_configuration.JsonDeserialiser, _configuration.ParameterBinders); }
public void Initialize() { var sp = Stopwatch.StartNew(); var clusterCert = InitializeClusterCertificate(out var httpsCert); try { ServerStore.Initialize(); } catch (Exception e) { if (Logger.IsOperationsEnabled) { Logger.Operations("Could not open the server store", e); } throw; } if (Logger.IsInfoEnabled) { Logger.Info(string.Format("Server store started took {0:#,#;;0} ms", sp.ElapsedMilliseconds)); } sp.Restart(); ListenToPipes().IgnoreUnobservedExceptions(); Router = new RequestRouter(RouteScanner.Scan(), this); try { void ConfigureKestrel(KestrelServerOptions options) { options.Limits.MaxRequestLineSize = (int)Configuration.Http.MaxRequestLineSize.GetValue(SizeUnit.Bytes); options.Limits.MaxRequestBodySize = null; // no limit! options.Limits.MinResponseDataRate = null; // no limit! options.Limits.MinRequestBodyDataRate = null; // no limit! if (Configuration.Http.MinDataRatePerSecond.HasValue && Configuration.Http.MinDataRateGracePeriod.HasValue) { options.Limits.MinResponseDataRate = new MinDataRate(Configuration.Http.MinDataRatePerSecond.Value.GetValue(SizeUnit.Bytes), Configuration.Http.MinDataRateGracePeriod.Value.AsTimeSpan); options.Limits.MinRequestBodyDataRate = new MinDataRate(Configuration.Http.MinDataRatePerSecond.Value.GetValue(SizeUnit.Bytes), Configuration.Http.MinDataRateGracePeriod.Value.AsTimeSpan); } if (Configuration.Http.MaxRequestBufferSize.HasValue) { options.Limits.MaxRequestBufferSize = Configuration.Http.MaxRequestBufferSize.Value.GetValue(SizeUnit.Bytes); } var actualCert = httpsCert ?? clusterCert; if (actualCert != null) { var adapterOptions = new HttpsConnectionAdapterOptions { ServerCertificate = actualCert.Certificate, CheckCertificateRevocation = true, ClientCertificateMode = ClientCertificateMode.AllowCertificate, SslProtocols = SslProtocols.Tls12, ClientCertificateValidation = (cert, chain, errors) => // Here we are explicitly ignoring trust chain issues for client certificates // this is because we don't actually require trust, we just use the certificate // as a way to authenticate. The admin is going to tell us which specific certs // we can trust anyway, so we can ignore such errors. errors == SslPolicyErrors.RemoteCertificateChainErrors || errors == SslPolicyErrors.None }; var uri = new Uri(Configuration.Core.ServerUrl); var host = uri.DnsSafeHost; var ipAddresses = GetListenIpAddresses(host); var loggerFactory = options.ApplicationServices.GetRequiredService <ILoggerFactory>(); var adapter = new AuthenticatingAdapter(this, new HttpsConnectionAdapter(adapterOptions, loggerFactory)); foreach (var address in ipAddresses) { options.Listen(address, uri.Port, listenOptions => { listenOptions.ConnectionAdapters.Add(adapter); }); } } } _webHost = new WebHostBuilder() .CaptureStartupErrors(captureStartupErrors: true) .UseKestrel(ConfigureKestrel) .UseUrls(Configuration.Core.ServerUrl) .UseStartup <RavenServerStartup>() .UseShutdownTimeout(TimeSpan.FromSeconds(1)) .ConfigureServices(services => { if (Configuration.Http.UseResponseCompression) { services.Configure <ResponseCompressionOptions>(options => { options.EnableForHttps = Configuration.Http.AllowResponseCompressionOverHttps; options.Providers.Add(typeof(GzipCompressionProvider)); options.Providers.Add(typeof(DeflateCompressionProvider)); }); services.Configure <GzipCompressionProviderOptions>(options => { options.Level = Configuration.Http.GzipResponseCompressionLevel; }); services.Configure <DeflateCompressionProviderOptions>(options => { options.Level = Configuration.Http.DeflateResponseCompressionLevel; }); services.AddResponseCompression(); } services.AddSingleton(Router); services.AddSingleton(this); services.Configure <FormOptions>(options => { options.MultipartBodyLengthLimit = long.MaxValue; }); }) // ReSharper disable once AccessToDisposedClosure .Build(); ClusterCertificateHolder = ClusterCertificateHolder ?? httpsCert ?? new CertificateHolder(); } catch (Exception e) { if (Logger.IsInfoEnabled) { Logger.Info("Could not configure server", e); } throw; } if (Logger.IsInfoEnabled) { Logger.Info(string.Format("Configuring HTTP server took {0:#,#;;0} ms", sp.ElapsedMilliseconds)); } try { _webHost.Start(); var serverAddressesFeature = _webHost.ServerFeatures.Get <IServerAddressesFeature>(); WebUrl = GetWebUrl(serverAddressesFeature.Addresses.First()).TrimEnd('/'); if (Logger.IsInfoEnabled) { Logger.Info($"Initialized Server... {WebUrl}"); } ServerStore.TriggerDatabases(); _tcpListenerStatus = StartTcpListener(); StartSnmp(); } catch (Exception e) { if (Logger.IsOperationsEnabled) { Logger.Operations("Could not start server", e); } throw; } }
public void it_should_not_continue_processing_request() { RequestRouter.DidNotReceive().FindRequestHandler(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <Uri>()); }