Ejemplo n.º 1
0
        public void Given_Parameter_When_Instantiated_Then_It_Should_Return_Result(string scheme, string hostname, int port, string key, string value, string payload)
        {
            var context = new Mock <FunctionContext>();

            var ports    = new[] { 80, 443 };
            var baseHost = $"{hostname}{(ports.Contains(port) ? string.Empty : $":{port}")}";
            var uri      = Uri.TryCreate($"{scheme}://{baseHost}?{key}={value}", UriKind.Absolute, out var tried) ? tried : null;

            var headers = new Dictionary <string, string>()
            {
                { key, value }
            };

            var bytes = Encoding.UTF8.GetBytes(payload);
            var body  = new MemoryStream(bytes);

            var req = (HttpRequestData) new FakeHttpRequestData(context.Object, uri, headers, body);

            var result = new HttpRequestObject(req);

            result.Scheme.Should().Be(scheme);
            result.Host.Value.Should().Be(baseHost);
            result.Headers.Should().ContainKey(key);
            result.Query.Should().ContainKey(key);
            ((string)result.Query[key]).Should().Be(value);
            (new StreamReader(result.Body)).ReadToEnd().Should().Be(payload);

            body.Dispose();
        }
Ejemplo n.º 2
0
        /// <inheritdoc/>
        public async Task <HttpResponseData> RenderOpenApiDocument(HttpRequestData req, string version, string extension, FunctionContext ctx)
        {
            var log = ctx.GetLogger(nameof(OpenApiTriggerFunction));

            log.LogInformation($"{version}.{extension} was requested.");

            var fi       = new FileInfo(ctx.FunctionDefinition.PathToAssembly);
            var request  = new HttpRequestObject(req);
            var result   = default(string);
            var response = default(HttpResponseData);

            try
            {
                var auth = await this._context
                           .SetApplicationAssemblyAsync(fi.Directory.FullName, appendBin : false)
                           .AuthorizeAsync(request)
                           .ConfigureAwait(false);

                if (!auth.IsNullOrDefault())
                {
                    response = req.CreateResponse(auth.StatusCode);
                    response.Headers.Add("Content-Type", auth.ContentType);
                    await response.WriteStringAsync(auth.Payload).ConfigureAwait(false);

                    return(response);
                }

                result = await this._context
                         .Document
                         .InitialiseDocument()
                         .AddMetadata(this._context.OpenApiConfigurationOptions.Info)
                         .AddServer(request, this._context.HttpSettings.RoutePrefix, this._context.OpenApiConfigurationOptions)
                         .AddNamingStrategy(this._context.NamingStrategy)
                         .AddVisitors(this._context.GetVisitorCollection())
                         .Build(this._context.ApplicationAssembly, this._context.GetOpenApiVersionType(version))
                         .ApplyDocumentFilters(this._context.GetDocumentFilterCollection())
                         .RenderAsync(this._context.GetOpenApiSpecVersion(version), this._context.GetOpenApiFormat(extension))
                         .ConfigureAwait(false);

                response = req.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Content-Type", this._context.GetOpenApiFormat(extension).GetContentType());
                await response.WriteStringAsync(result).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);

                result = ex.Message;
                if (this._context.IsDevelopment)
                {
                    result += "\r\n\r\n";
                    result += ex.StackTrace;
                }
                response = req.CreateResponse(HttpStatusCode.InternalServerError);
                response.Headers.Add("Content-Type", ContentTypeText);
                await response.WriteStringAsync(result).ConfigureAwait(false);
            }

            return(response);
        }
Ejemplo n.º 3
0
        /// <inheritdoc/>
        public async Task <HttpResponseData> RenderSwaggerUI(HttpRequestData req, FunctionContext ctx)
        {
            var log = ctx.GetLogger(nameof(OpenApiTriggerFunction));

            log.LogInformation("SwaggerUI page was requested.");

            var fi       = new FileInfo(ctx.FunctionDefinition.PathToAssembly);
            var request  = new HttpRequestObject(req);
            var result   = default(string);
            var response = default(HttpResponseData);

            try
            {
                var auth = await this._context
                           .SetApplicationAssemblyAsync(fi.Directory.FullName, appendBin : false)
                           .AuthorizeAsync(request)
                           .ConfigureAwait(false);

                if (!auth.IsNullOrDefault())
                {
                    response = req.CreateResponse(auth.StatusCode);
                    response.Headers.Add("Content-Type", auth.ContentType);
                    await response.WriteStringAsync(auth.Payload).ConfigureAwait(false);

                    return(response);
                }

                result = await this._context
                         .SwaggerUI
                         .AddMetadata(this._context.OpenApiConfigurationOptions.Info)
                         .AddServer(request, this._context.HttpSettings.RoutePrefix, this._context.OpenApiConfigurationOptions)
                         .BuildAsync(this._context.PackageAssembly, this._context.OpenApiCustomUIOptions)
                         .RenderAsync("swagger.json", this._context.GetDocumentAuthLevel(), this._context.GetSwaggerAuthKey())
                         .ConfigureAwait(false);

                response = req.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Content-Type", ContentTypeHtml);
                await response.WriteStringAsync(result).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);

                result = ex.Message;
                if (this._context.IsDevelopment)
                {
                    result += "\r\n\r\n";
                    result += ex.StackTrace;
                }
                response = req.CreateResponse(HttpStatusCode.InternalServerError);
                response.Headers.Add("Content-Type", ContentTypeText);
                await response.WriteStringAsync(result).ConfigureAwait(false);
            }

            return(response);
        }
Ejemplo n.º 4
0
        private ActionResult RequestHandler(string requestURI, string contentType = "", string referer = "", string userName = "", string password = "")
        {
            HttpRequestObject requestObject = new HttpRequestObject();

            requestObject.requestURI  = requestURI;
            requestObject.contentType = contentType;
            requestObject.referer     = referer;
            requestObject.userName    = userName;
            requestObject.password    = password;

            HttpResponseObject responseObject = SendHttpRequest.WmsRequest(requestObject);

            return(new FileStreamResult(responseObject.responseStream, responseObject.contentType));
        }
Ejemplo n.º 5
0
        public void CheckHttpRequests()
        {
            if (m_CmdManager.m_ScriptEngine.World == null)
            {
                return;
            }

            IHttpRequestModule iHttpReq =
                m_CmdManager.m_ScriptEngine.World.RequestModuleInterface <IHttpRequestModule>();

            HttpRequestObject httpInfo = null;

            if (iHttpReq != null)
            {
                httpInfo = (HttpRequestObject)iHttpReq.GetNextCompletedRequest();
            }

            while (httpInfo != null)
            {
                //m_log.Debug("[AsyncLSL]:" + httpInfo.response_body + httpInfo.status);

                // Deliver data to prim's remote_data handler
                //
                // TODO: Returning null for metadata, since the lsl function
                // only returns the byte for HTTP_BODY_TRUNCATED, which is not
                // implemented here yet anyway.  Should be fixed if/when maxsize
                // is supported

                object[] resobj = new object[]
                {
                    httpInfo.ReqID.ToString(),
                         httpInfo.Status,
                    new object[0],
                         httpInfo.ResponseBody
                };

                foreach (IScriptEngine e in m_CmdManager.ScriptEngines)
                {
                    if (e.PostObjectEvent(httpInfo.LocalID,
                                          new EventParams("http_response",
                                                          resobj, new DetectParams[0])))
                    {
                        break;
                    }
                }
                httpInfo = (HttpRequestObject)iHttpReq.GetNextCompletedRequest();
            }
        }
Ejemplo n.º 6
0
        public void Test1()
        {
            HttpRequestObject ex1 = new HttpRequestObject(
                "GET / HTTP/1.1 \r\n" +
                "Host: 127.0.0.1:12345 \r\n" +
                "Connection: keep-alive \r\n" +
                "Cache-Control: max-age=0 \r\n" +
                "Upgrade-Insecure-Requests: 1 \r\n" +
                "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36 \r\n" +
                "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 \r\n" +
                "Sec-Fetch-Site: none \r\n" +
                "Sec-Fetch-Mode: navigate \r\n" +
                "Sec-Fetch-User: ?1 \r\n" +
                "Sec-Fetch-Dest: document \r\n" +
                "Accept-Encoding: gzip, deflate, br \r\n" +
                "Accept-Language: ja,en-US;q=0.9,en;q=0.8\r\n"
                );

            Assert.Equals(ex1.RqType, RequestType.Get);
            Assert.Equals(ex1.Path, "/");
            Assert.Equals(ex1.HttpVersion, "1.1");

            Assert.True(ex1.Header.ContainsKey("Host"));
            Assert.True(ex1.Header.ContainsKey("User-Agent"));
            Assert.True(ex1.Header.ContainsKey("Accept"));
            Assert.True(ex1.Header.ContainsKey("Sec-Fetch-User"));
            Assert.True(ex1.Header.ContainsKey("Accept-Encoding"));
            Assert.True(ex1.Header.ContainsKey("Accept-Language"));

            Assert.Equals(ex1.Header["Host"], "127.0.0.1:12345");
            Assert.Equals(ex1.Header["Connection"], "keep-alive");
            Assert.Equals(ex1.Header["Cache-Control"], "max-age=0");
            Assert.Equals(ex1.Header["User-Agent"], "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36");
            Assert.Equals(ex1.Header["Accept"], "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            Assert.Equals(ex1.Header["Sec-Fetch-User"], "?1");
            // Assert.Equals(ex1.Header["Host"], "127.0.0.1:12345");
            // Assert.Equals(ex1.Header["Host"], "127.0.0.1:12345");
            // Assert.Equals(ex1.Header["Host"], "127.0.0.1:12345");
            // Assert.Equals(ex1.Header["Host"], "127.0.0.1:12345");

            // Assert.False(ex1.Validate());
        }
Ejemplo n.º 7
0
        public void Given_Parameter_When_Instantiated_Then_It_Should_Return_Result(string scheme, string hostname, int port, string key, string value, string payload)
        {
            var req = new Mock <HttpRequest>();

            req.SetupGet(p => p.Scheme).Returns(scheme);

            var ports      = new[] { 80, 443 };
            var baseHost   = $"{hostname}{(ports.Contains(port) ? string.Empty : $":{port}")}";
            var hoststring = new HostString(baseHost);

            req.SetupGet(p => p.Host).Returns(hoststring);

            var dict = new Dictionary <string, StringValues>()
            {
                { key, new StringValues(value) }
            };
            var header = new HeaderDictionary(dict);

            req.SetupGet(p => p.Headers).Returns(header);

            var query = new QueryCollection(dict);

            req.SetupGet(p => p.Query).Returns(query);

            var bytes = Encoding.UTF8.GetBytes(payload);
            var body  = new MemoryStream(bytes);

            req.SetupGet(p => p.Body).Returns(body);

            var result = new HttpRequestObject(req.Object);

            result.Scheme.Should().Be(scheme);
            result.Host.Value.Should().Be(baseHost);
            result.Headers.Should().ContainKey(key);
            result.Query.Should().ContainKey(key);
            ((string)result.Query[key]).Should().Be(value);
            (new StreamReader(result.Body)).ReadToEnd().Should().Be(payload);

            body.Dispose();
        }