Beispiel #1
0
        public async Task BodyParser_Parse_ContentEncoding_GZip_And_DecompressGzipAndDeflate_Is_True_Should_Decompress(string compression)
        {
            // Arrange
            var bytes              = Encoding.ASCII.GetBytes("0");
            var compressed         = CompressionUtils.Compress(compression, bytes);
            var bodyParserSettings = new BodyParserSettings
            {
                Stream                   = new MemoryStream(compressed),
                ContentType              = "text/plain",
                DeserializeJson          = false,
                ContentEncoding          = compression.ToUpperInvariant(),
                DecompressGZipAndDeflate = true
            };

            // Act
            var result = await BodyParser.Parse(bodyParserSettings);

            // Assert
            result.DetectedBodyType.Should().Be(BodyType.String);
            result.DetectedBodyTypeFromContentType.Should().Be(BodyType.String);
            result.BodyAsBytes.Should().BeEquivalentTo(new byte[] { 48 });
            result.BodyAsJson.Should().BeNull();
            result.BodyAsString.Should().Be("0");
            result.DetectedCompression.Should().Be(compression);
        }
        public async Task RequestMessageBodyMatcher_GetMatchingScore_Funcs_Matching(object body, RequestMessageBodyMatcher matcher, bool shouldMatch)
        {
            // assign
            BodyData bodyData;

            if (body is byte[] b)
            {
                bodyData = await BodyParser.Parse(new MemoryStream(b), null);
            }
            else if (body is string s)
            {
                bodyData = await BodyParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(s)), null);
            }
            else
            {
                throw new Exception();
            }

            var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", bodyData);

            // act
            var result = new RequestMatchResult();
            var score  = matcher.GetMatchingScore(requestMessage, result);

            // assert
            Check.That(score).IsEqualTo(shouldMatch ? 1d : 0d);
        }
Beispiel #3
0
        public static async Task <ResponseMessage> CreateAsync(HttpResponseMessage httpResponseMessage, Uri requiredUri, Uri originalUri, bool deserializeJson, bool decompressGzipAndDeflate)
        {
            var responseMessage = new ResponseMessage {
                StatusCode = (int)httpResponseMessage.StatusCode
            };

            // Set both content and response headers, replacing URLs in values
            var headers = (httpResponseMessage.Content?.Headers.Union(httpResponseMessage.Headers) ?? Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >()).ToArray();

            if (httpResponseMessage.Content != null)
            {
                var stream = await httpResponseMessage.Content.ReadAsStreamAsync();

                IEnumerable <string> contentTypeHeader = null;
                if (headers.Any(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)))
                {
                    contentTypeHeader = headers.First(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)).Value;
                }

                IEnumerable <string> contentEncodingHeader = null;
                if (headers.Any(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentEncoding, StringComparison.OrdinalIgnoreCase)))
                {
                    contentEncodingHeader = headers.First(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentEncoding, StringComparison.OrdinalIgnoreCase)).Value;
                }

                var bodyParserSettings = new BodyParserSettings
                {
                    Stream                   = stream,
                    ContentType              = contentTypeHeader?.FirstOrDefault(),
                    DeserializeJson          = deserializeJson,
                    ContentEncoding          = contentEncodingHeader?.FirstOrDefault(),
                    DecompressGZipAndDeflate = decompressGzipAndDeflate
                };
                responseMessage.BodyData = await BodyParser.Parse(bodyParserSettings);
            }

            foreach (var header in headers)
            {
                // If Location header contains absolute redirect URL, and base URL is one that we proxy to,
                // we need to replace it to original one.
                if (string.Equals(header.Key, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase) &&
                    Uri.TryCreate(header.Value.First(), UriKind.Absolute, out Uri absoluteLocationUri) &&
                    string.Equals(absoluteLocationUri.Host, requiredUri.Host, StringComparison.OrdinalIgnoreCase))
                {
                    var replacedLocationUri = new Uri(originalUri, absoluteLocationUri.PathAndQuery);
                    responseMessage.AddHeader(header.Key, replacedLocationUri.ToString());
                }
                else
                {
                    responseMessage.AddHeader(header.Key, header.Value.ToArray());
                }
            }

            return(responseMessage);
        }
        /// <inheritdoc cref="IOwinRequestMapper.MapAsync"/>
        public async Task <RequestMessage> MapAsync(IRequest request, IWireMockMiddlewareOptions options)
        {
            (UrlDetails urldetails, string clientIP) = ParseRequest(request);

            string method = request.Method;

            Dictionary <string, string[]> headers = null;
            IEnumerable <string>          contentEncodingHeader = null;

            if (request.Headers.Any())
            {
                headers = new Dictionary <string, string[]>();
                foreach (var header in request.Headers)
                {
                    headers.Add(header.Key, header.Value);

                    if (string.Equals(header.Key, HttpKnownHeaderNames.ContentEncoding, StringComparison.OrdinalIgnoreCase))
                    {
                        contentEncodingHeader = header.Value;
                    }
                }
            }

            IDictionary <string, string> cookies = null;

            if (request.Cookies.Any())
            {
                cookies = new Dictionary <string, string>();
                foreach (var cookie in request.Cookies)
                {
                    cookies.Add(cookie.Key, cookie.Value);
                }
            }

            BodyData body = null;

            if (request.Body != null && BodyParser.ShouldParseBody(method, options.AllowBodyForAllHttpMethods == true))
            {
                var bodyParserSettings = new BodyParserSettings
                {
                    Stream                   = request.Body,
                    ContentType              = request.ContentType,
                    DeserializeJson          = !options.DisableJsonBodyParsing.GetValueOrDefault(false),
                    ContentEncoding          = contentEncodingHeader?.FirstOrDefault(),
                    DecompressGZipAndDeflate = !options.DisableRequestBodyDecompressing.GetValueOrDefault(false)
                };

                body = await BodyParser.Parse(bodyParserSettings);
            }

            return(new RequestMessage(urldetails, method, clientIP, body, headers, cookies)
            {
                DateTime = DateTime.UtcNow
            });
        }
Beispiel #5
0
        public async Task BodyParser_Parse_DetectedBodyType(byte[] content, BodyType detectedBodyType)
        {
            // arrange
            var memoryStream = new MemoryStream(content);

            // act
            var body = await BodyParser.Parse(memoryStream, null);

            // assert
            Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
        }
Beispiel #6
0
        public async Task BodyParser_Parse_ApplicationXml()
        {
            // Assign
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes("<xml>hello</xml>"));

            // Act
            var body = await BodyParser.Parse(memoryStream, "application/xml; charset=UTF-8");

            // Assert
            Check.That(body.BodyAsBytes).IsNull();
            Check.That(body.BodyAsJson).IsNull();
            Check.That(body.BodyAsString).Equals("<xml>hello</xml>");
        }
Beispiel #7
0
        [Fact] // http://jsonapi.org/
        public async Task BodyParser_Parse_ApplicationJsonApi()
        {
            // Assign
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes("{ \"x\": 1 }"));

            // Act
            var body = await BodyParser.Parse(memoryStream, "application/vnd.api+json");

            // Assert
            Check.That(body.BodyAsBytes).IsNull();
            Check.That(body.BodyAsJson).IsNotNull();
            Check.That(body.BodyAsString).Equals("{ \"x\": 1 }");
        }
        public async Task BodyParser_Parse_ContentTypeString(string contentType, string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType)
        {
            // Arrange
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString));

            // Act
            var body = await BodyParser.Parse(memoryStream, contentType);

            // Assert
            Check.That(body.BodyAsBytes).IsNotNull();
            Check.That(body.BodyAsJson).IsNull();
            Check.That(body.BodyAsString).Equals(bodyAsString);
            Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
            Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType);
        }
Beispiel #9
0
        public async Task BodyParser_Parse_DetectedBodyTypeNoJsonParsing(byte[] content, BodyType detectedBodyType)
        {
            // arrange
            var bodyParserSettings = new BodyParserSettings
            {
                Stream          = new MemoryStream(content),
                ContentType     = null,
                DeserializeJson = false
            };

            // act
            var body = await BodyParser.Parse(bodyParserSettings);

            // assert
            Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
        }
        public async Task BodyParser_Parse_WithUTF16EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString()
        {
            // Arrange
            string contentType = "multipart/form-data";
            string body        = char.ConvertFromUtf32(0x1D161); //U+1D161 = MUSICAL SYMBOL SIXTEENTH NOTE

            var memoryStream = new MemoryStream(Encoding.UTF32.GetBytes(body));

            // Act
            var result = await BodyParser.Parse(memoryStream, contentType);

            // Assert
            Check.That(result.DetectedBodyType).IsEqualTo(BodyType.Bytes);
            Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart);
            Check.That(result.BodyAsBytes).IsNotNull();
            Check.That(result.BodyAsJson).IsNull();
            Check.That(result.BodyAsString).IsNull();
        }
Beispiel #11
0
        public async Task BodyParser_Parse_ContentTypeJson(string contentType, string bodyAsJson, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType)
        {
            // Arrange
            var bodyParserSettings = new BodyParserSettings
            {
                Stream          = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsJson)),
                ContentType     = contentType,
                DeserializeJson = true
            };

            // Act
            var body = await BodyParser.Parse(bodyParserSettings);

            // Assert
            Check.That(body.BodyAsBytes).IsNotNull();
            Check.That(body.BodyAsJson).IsNotNull();
            Check.That(body.BodyAsString).Equals(bodyAsJson);
            Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
            Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType);
        }
Beispiel #12
0
        public async Task BodyParser_Parse_WithUTF8EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString()
        {
            // Arrange
            string contentType = "multipart/form-data";
            string body        = @"

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name=""text""

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name=""file1""; filename=""a.txt""
Content-Type: text/plain

Content of a txt

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name=""file2""; filename=""a.html""
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--";

            var bodyParserSettings = new BodyParserSettings
            {
                Stream          = new MemoryStream(Encoding.UTF8.GetBytes(body)),
                ContentType     = contentType,
                DeserializeJson = true
            };

            // Act
            var result = await BodyParser.Parse(bodyParserSettings);

            // Assert
            Check.That(result.DetectedBodyType).IsEqualTo(BodyType.String);
            Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart);
            Check.That(result.BodyAsBytes).IsNotNull();
            Check.That(result.BodyAsJson).IsNull();
            Check.That(result.BodyAsString).IsNotNull();
        }
Beispiel #13
0
        static async Task MainAsync(CancellationToken cancellationToken)
        {
            var function = new Function();

            function.PrepareFunctionContext();

            System.Diagnostics.Debug.WriteLine("C# AfterBurn running.");

            var httpFormatter = new HttpFormatter();
            var stdin         = Console.OpenStandardInput();

            using (TextReader reader = new StreamReader(stdin))
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    HeaderParser parser = new HeaderParser();
                    var          header = parser.Parse(reader);

                    foreach (string v in header.HttpHeaders)
                    {
                        System.Diagnostics.Debug.WriteLine(v + "=" + header.HttpHeaders[v]);
                    }

                    System.Diagnostics.Debug.WriteLine("Content-Length: " + header.ContentLength);

                    BodyParser bodyParser = new BodyParser();
                    string     body       = String.Empty;
                    if (header.ContentLength > 0)
                    {
                        body = bodyParser.Parse(reader, header.ContentLength);

                        System.Diagnostics.Debug.WriteLine(body);
                    }

                    await function.Invoke(body, cancellationToken);

                    var httpAdded = httpFormatter.Format("");
                    Console.WriteLine(httpAdded);
                }
            }
        }
Beispiel #14
0
        /// <inheritdoc cref="IOwinRequestMapper.MapAsync"/>
        public async Task <RequestMessage> MapAsync(IRequest request)
        {
            (UrlDetails urldetails, string clientIP) = ParseRequest(request);

            string method = request.Method;

            Dictionary <string, string[]> headers = null;

            if (request.Headers.Any())
            {
                headers = new Dictionary <string, string[]>();
                foreach (var header in request.Headers)
                {
                    headers.Add(header.Key, header.Value);
                }
            }

            IDictionary <string, string> cookies = null;

            if (request.Cookies.Any())
            {
                cookies = new Dictionary <string, string>();
                foreach (var cookie in request.Cookies)
                {
                    cookies.Add(cookie.Key, cookie.Value);
                }
            }

            BodyData body = null;

            if (request.Body != null && BodyParser.ShouldParseBody(method))
            {
                body = await BodyParser.Parse(request.Body, request.ContentType);
            }

            return(new RequestMessage(urldetails, method, clientIP, body, headers, cookies)
            {
                DateTime = DateTime.UtcNow
            });
        }
        /// <inheritdoc cref="IOwinRequestMapper.MapAsync"/>
        public async Task <RequestMessage> MapAsync(IRequest request, IWireMockMiddlewareOptions options)
        {
            (UrlDetails urldetails, string clientIP) = ParseRequest(request);

            string method = request.Method;

            Dictionary <string, string[]> headers = null;

            if (request.Headers.Any())
            {
                headers = new Dictionary <string, string[]>();
                foreach (var header in request.Headers)
                {
                    headers.Add(header.Key, header.Value);
                }
            }

            IDictionary <string, string> cookies = null;

            if (request.Cookies.Any())
            {
                cookies = new Dictionary <string, string>();
                foreach (var cookie in request.Cookies)
                {
                    cookies.Add(cookie.Key, cookie.Value);
                }
            }

            BodyData body = null;

            if (request.Body != null && BodyParser.ShouldParseBody(method, options.AllowBodyForAllHttpMethods == true))
            {
                body = await BodyParser.Parse(request.Body, request.ContentType, !options.DisableJsonBodyParsing.GetValueOrDefault(false));
            }

            return(new RequestMessage(urldetails, method, clientIP, body, headers, cookies)
            {
                DateTime = DateTime.UtcNow
            });
        }
        static void Main(string[] args)
        {
            var function = new Function.Handler();

            System.Diagnostics.Debug.WriteLine("C# AfterBurn running.");

            var httpFormatter = new HttpFormatter();
            var stdin         = Console.OpenStandardInput();

            using (TextReader reader = new StreamReader(stdin)) {
                while (true)
                {
                    HeaderParser parser = new HeaderParser();
                    var          header = parser.Parse(reader);

                    foreach (string v in header.HttpHeaders)
                    {
                        System.Diagnostics.Debug.WriteLine(v + "=" + header.HttpHeaders[v]);
                    }

                    System.Diagnostics.Debug.WriteLine("Content-Length: " + header.ContentLength);

                    BodyParser bodyParser = new BodyParser();
                    char[]     body       = new char[0] {
                    };
                    if (header.ContentLength > 0)
                    {
                        body = bodyParser.Parse(reader, header.ContentLength);

                        System.Diagnostics.Debug.WriteLine(body);
                    }

                    var httpAdded = httpFormatter.Format(function.Invoke(body));
                    Console.WriteLine(httpAdded);
                }
            }
        }
Beispiel #17
0
        public static async Task <ResponseMessage> SendAsync([NotNull] HttpClient client, [NotNull] RequestMessage requestMessage, string url)
        {
            Check.NotNull(client, nameof(client));
            Check.NotNull(requestMessage, nameof(requestMessage));

            var originalUri = new Uri(requestMessage.Url);
            var requiredUri = new Uri(url);

            var httpRequestMessage = new HttpRequestMessage(new HttpMethod(requestMessage.Method), url);

            WireMockList <string> contentTypeHeader = null;
            bool contentTypeHeaderPresent           = requestMessage.Headers.Any(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase));

            if (contentTypeHeaderPresent)
            {
                contentTypeHeader = requestMessage.Headers[HttpKnownHeaderNames.ContentType];
            }

            // Set Body if present
            if (requestMessage.BodyAsBytes != null)
            {
                httpRequestMessage.Content = new ByteArrayContent(requestMessage.BodyAsBytes);
            }
            else if (requestMessage.BodyAsJson != null)
            {
                httpRequestMessage.Content = new StringContent(JsonConvert.SerializeObject(requestMessage.BodyAsJson), requestMessage.BodyEncoding);
            }
            else if (requestMessage.Body != null)
            {
                httpRequestMessage.Content = new StringContent(requestMessage.Body, requestMessage.BodyEncoding);
            }

            // Overwrite the host header
            httpRequestMessage.Headers.Host = requiredUri.Authority;

            // Set headers if present
            if (requestMessage.Headers != null)
            {
                foreach (var header in requestMessage.Headers.Where(header => !string.Equals(header.Key, "HOST", StringComparison.OrdinalIgnoreCase)))
                {
                    // Try to add to request headers. If failed - try to add to content headers
                    if (!httpRequestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value))
                    {
                        httpRequestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value);
                    }
                }
            }

            // Call the URL
            var httpResponseMessage = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead);

            // Create transform response
            var responseMessage = new ResponseMessage {
                StatusCode = (int)httpResponseMessage.StatusCode
            };

            // Set both content and response headers, replacing URLs in values
            var headers = (httpResponseMessage.Content?.Headers.Union(httpResponseMessage.Headers) ?? Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >()).ToArray();

            if (httpResponseMessage.Content != null)
            {
                var stream = await httpResponseMessage.Content.ReadAsStreamAsync();

                var body = await BodyParser.Parse(stream, contentTypeHeader?.FirstOrDefault());

                responseMessage.Body        = body.BodyAsString;
                responseMessage.BodyAsJson  = body.BodyAsJson;
                responseMessage.BodyAsBytes = body.BodyAsBytes;
            }

            foreach (var header in headers)
            {
                // If Location header contains absolute redirect URL, and base URL is one that we proxy to,
                // we need to replace it to original one.
                if (string.Equals(header.Key, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase) &&
                    Uri.TryCreate(header.Value.First(), UriKind.Absolute, out Uri absoluteLocationUri) &&
                    string.Equals(absoluteLocationUri.Host, requiredUri.Host, StringComparison.OrdinalIgnoreCase))
                {
                    var replacedLocationUri = new Uri(originalUri, absoluteLocationUri.PathAndQuery);
                    responseMessage.AddHeader(header.Key, replacedLocationUri.ToString());
                }
                else
                {
                    responseMessage.AddHeader(header.Key, header.Value.ToArray());
                }
            }

            return(responseMessage);
        }
 public static Template Compile(string template, params ArgumentDescription[] args)
 {
     return(new Template(BodyParser.Parse(template, args)));
 }