public async Task JwtAuthenticationOption_GetSwaggerDocs_ContainsJwtSecurityScheme() { // Arrange string key = $"secret-{Guid.NewGuid()}"; string issuer = $"issuer-{Guid.NewGuid()}"; string audience = $"audience-{Guid.NewGuid()}"; string jwtToken = CreateToken(key, issuer, audience); var jwtHeader = AuthenticationHeaderValue.Parse("Bearer " + jwtToken); var options = new WebApiProjectOptions().WithJwtAuthentication(key, issuer, audience); using (var project = await WebApiProject.StartNewAsync(options, _outputWriter)) { // Act using (HttpResponseMessage response = await project.Swagger.GetSwaggerDocsAsync()) { // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var reader = new OpenApiStreamReader(); using (Stream json = await response.Content.ReadAsStreamAsync()) { OpenApiDocument document = reader.Read(json, out OpenApiDiagnostic diagnostic); Assert.NotNull(document.Components); (string schemeName, OpenApiSecurityScheme componentScheme) = Assert.Single(document.Components.SecuritySchemes); Assert.Equal(SecuritySchemeType.Http, componentScheme.Type); OpenApiSecurityRequirement requirement = Assert.Single(document.SecurityRequirements); Assert.NotNull(requirement); (OpenApiSecurityScheme requirementScheme, IList <string> scopes) = Assert.Single(requirement); Assert.Equal("jwt", requirementScheme.Reference.Id); } } } }
internal async Task LoadAsync(OpenApiReference reference, OpenApiDocument document) { _workspace.AddDocument(reference.ExternalResource, document); document.Workspace = _workspace; // Collect remote references by walking document var referenceCollector = new OpenApiRemoteReferenceCollector(document); var collectorWalker = new OpenApiWalker(referenceCollector); collectorWalker.Walk(document); var reader = new OpenApiStreamReader(_readerSettings); // Walk references foreach (var item in referenceCollector.References) { // If not already in workspace, load it and process references if (!_workspace.Contains(item.ExternalResource)) { var input = await _loader.LoadAsync(new Uri(item.ExternalResource, UriKind.RelativeOrAbsolute)); var result = await reader.ReadAsync(input); // TODO merge _diagnositics await LoadAsync(item, result.OpenApiDocument); } } }
internal byte[] ConvertOpenApiDocument(string inputFileContent, OpenApiSpecVersion apiSpecVersion, OpenApiFormat apiFormat) { using (Stream stream = this.CreateStream(inputFileContent)) { var document = new OpenApiStreamReader().Read(stream, out var context); this.codeGeneratorProgress?.Progress(50, 100); var outputStream = new MemoryStream(); document.Serialize(outputStream, apiSpecVersion, apiFormat); this.codeGeneratorProgress?.Progress(100, 100); var encoding = Encoding.GetEncoding(Encoding.UTF8.WindowsCodePage); //Get the preamble (byte-order mark) for our encoding byte[] preamble = encoding.GetPreamble(); int preambleLength = preamble.Length; outputStream.Position = 0; //Convert the writer contents to a byte array byte[] body = encoding.GetBytes(new StreamReader(outputStream).ReadToEnd()); //Prepend the preamble to body (store result in resized preamble array) Array.Resize(ref preamble, preambleLength + body.Length); Array.Copy(body, 0, preamble, preambleLength, body.Length); //Return the combined byte array return(preamble); } }
//ObjectName //DependsOn: List<ObjectName> static void Main(string[] args) { Console.WriteLine("Hello World!"); var httpClient = new HttpClient { BaseAddress = new Uri("https://raw.githubusercontent.com/") }; var stream = httpClient.GetStreamAsync("heroiclabs/nakama/master/apigrpc/apigrpc.swagger.json").Result; var openApiDocument = new OpenApiStreamReader().Read(stream, out var diagnostic); var path = openApiDocument.Paths; var schemas = openApiDocument.Components.Schemas; HashSet <string> set = new HashSet <string>(); List <ObjectProperty> ob = new List <ObjectProperty>(); BuildObjects(ref ob, schemas); if (objectsToGen.Count > 0) { } }
private async Task PublishServiceApiAsync(HttpContext context, string serviceId) { var reader = new OpenApiStreamReader(); var document = reader.Read(context.Request.Body, out var diagnostic); if (diagnostic.Errors.Count > 0) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Error reading OpenApi document. " + string.Join(Environment.NewLine, diagnostic.Errors.Select(e => e.Message))); } if (ValidateModel(document)) { await _serviceRepository.StoreApiAsync(new Models.ServiceApiDescription { ApiDocument = document, ServiceId = serviceId }); context.Response.StatusCode = (int)HttpStatusCode.OK; } else { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Invalid OpenApi document."); } }
public async Task LoadDocumentIntoWorkspace() { // Create a reader that will resolve all references var reader = new OpenApiStreamReader(new OpenApiReaderSettings() { ReferenceResolution = ReferenceResolutionSetting.ResolveAllReferences, CustomExternalLoader = new MockLoader() }); // Todo: this should be ReadAsync var stream = new MemoryStream(); var doc = @"openapi: 3.0.0 info: title: foo version: 1.0.0 paths: {}"; var wr = new StreamWriter(stream); wr.Write(doc); wr.Flush(); stream.Position = 0; var result = await reader.ReadAsync(stream); Assert.NotNull(result.OpenApiDocument.Workspace); }
public GraphTests(ITestOutputHelper output) { _output = output; System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; _httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }); _httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip")); _httpClient.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("OpenApi.Net.Tests", "1.0")); var response = _httpClient.GetAsync(graphOpenApiUrl) .GetAwaiter().GetResult(); if (!response.IsSuccessStatusCode) { _output.WriteLine($"Couldn't load graph openapi"); return; } var stream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); ; var reader = new OpenApiStreamReader(); _graphOpenApi = reader.Read(stream, out var diagnostic); if (diagnostic.Errors.Count > 0) { _output.WriteLine($"Errors parsing"); _output.WriteLine(String.Join("\n", diagnostic.Errors)); // Assert.True(false); // Uncomment to identify descriptions with errors. } }
private static (OpenApiDocument, OpenApiDiagnostic) ReadSpecification(Stream stream) { var reader = new OpenApiStreamReader(); var apiDocument = reader.Read(stream, out OpenApiDiagnostic diags); return(apiDocument, diags); }
public async Task SwaggerEndpoint_ReturnsCorrectPriceExample_ForDifferentCultures(string culture) { var testSite = new TestSite(typeof(Basic.Startup)); var client = testSite.BuildClient(); var swaggerResponse = await client.GetAsync($"/swagger/v1/swagger.json?culture={culture}"); swaggerResponse.EnsureSuccessStatusCode(); var contentStream = await swaggerResponse.Content.ReadAsStreamAsync(); var currentCulture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; try { var openApiDocument = new OpenApiStreamReader().Read(contentStream, out OpenApiDiagnostic diagnostic); var example = openApiDocument.Components.Schemas["Product"].Example as OpenApiObject; var price = (example["price"] as OpenApiDouble); Assert.NotNull(price); Assert.Equal(14.37, price.Value); } finally { CultureInfo.CurrentCulture = currentCulture; } }
public void ParseOAuth2ImplicitSecuritySchemeShouldSucceed() { using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "oauth2ImplicitSecurityScheme.yaml"))) { var document = OpenApiStreamReader.LoadYamlDocument(stream); var context = new ParsingContext(); var diagnostic = new OpenApiDiagnostic(); var node = new MapNode(context, diagnostic, (YamlMappingNode)document.RootNode); // Act var securityScheme = OpenApiV2Deserializer.LoadSecurityScheme(node); // Assert securityScheme.ShouldBeEquivalentTo( new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { Implicit = new OpenApiOAuthFlow { AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), Scopes = { ["write:pets"] = "modify pets in your account", ["read:pets"] = "read your pets" } } } }); } }
public async Task OAuthAuthorizeOperationFilter_ShouldNotIncludeSecurityDefinitionResponses_OnNonAuthorizedOperations() { // Arrange using (var client = _testServer.CreateClient()) // Act using (HttpResponseMessage response = await client.GetAsync("swagger/v1/swagger.json")) { // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var reader = new OpenApiStreamReader(); using (var responseStream = await response.Content.ReadAsStreamAsync()) { OpenApiDocument swagger = reader.Read(responseStream, out OpenApiDiagnostic diagnostic); _outputWriter.WriteLine(diagnostic.Errors.Count == 0 ? String.Empty : String.Join(", ", diagnostic.Errors.Select(e => e.Message + ": " + e.Pointer))); Assert.True( swagger.Paths.TryGetValue("/oauth/none", out OpenApiPathItem oauthPath), "Cannot find OAuth none authorized path in Open API spec file"); Assert.True( oauthPath.Operations.TryGetValue(OperationType.Get, out OpenApiOperation oauthOperation), "Cannot find OAuth GET operation in Open API spec file"); OpenApiResponses oauthResponses = oauthOperation.Responses; Assert.DoesNotContain(oauthResponses, r => r.Key == "401"); Assert.DoesNotContain(oauthResponses, r => r.Key == "403"); } } }
private async Task <JObject> GetOpenApiSpecificationFromBlobStorageAsync() { var openApiDocument = new OpenApiDocument(); _logger.LogInformation("Retrieving OpenAPI Specification from blob storage."); try { var cloudBlockBlob = _cloudBlobContainer.GetBlockBlobReference(_appSettings.BlobName); var ms = new MemoryStream(); await cloudBlockBlob.DownloadToStreamAsync(ms); ms.Seek(0, SeekOrigin.Begin); // Only using OpenApiDocument to allow validation and conversion of yaml into json. openApiDocument = new OpenApiStreamReader().Read(ms, out var diagnostic); if (diagnostic.Errors.Any()) { _logger.LogWarning("Diagnostic error reading open api document.", args: diagnostic.Errors); } } catch (Exception e) { _logger.LogCritical(e, e.Message); } finally { _logger.LogInformation("Finished retrieving OpenAPI Specification."); } return(JObject.Parse(openApiDocument.Serialize(OpenApiSpecVersion.OpenApi3_0, OpenApiFormat.Json))); }
public void LoadResponseReference() { // Arrange OpenApiDocument document; var diagnostic = new OpenApiDiagnostic(); using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml"))) { document = new OpenApiStreamReader().Read(stream, out diagnostic); } var reference = new OpenApiReference { Type = ReferenceType.Response, Id = "NotFound" }; // Act var referencedObject = document.ResolveReference(reference); // Assert referencedObject.ShouldBeEquivalentTo( new OpenApiResponse { Description = "Entity not found.", Reference = new OpenApiReference { Type = ReferenceType.Response, Id = "NotFound" } } ); }
private static void WriteRows(StreamWriter csvFile, string file) { var fileInfo = new FileInfo(file); using var stream = fileInfo.OpenRead(); var openApiDocument = new OpenApiStreamReader().Read(stream, out var diagnostic); var apiInfo = openApiDocument.Paths .Select(path => new { ProductName = fileInfo.Directory.Name, SpecFile = fileInfo.Name, Path = path.Key, Operation = path.Value.Operations.First().Key.ToString().ToUpper() }) .Distinct(); foreach (var api in apiInfo) { csvFile.Write($"{api.ProductName},"); csvFile.Write($"{api.SpecFile},"); csvFile.Write($"{api.Path},"); csvFile.Write($"{api.Operation},"); csvFile.Write($"{openApiDocument.Info.Title},"); csvFile.Write($"\"{openApiDocument.Info.Description}\","); csvFile.Write($"{openApiDocument.Info.Version},"); csvFile.WriteLine(); } }
internal static void ValidateOpenApiDocument(string input) { if (input == null) { throw new ArgumentNullException("input"); } var stream = GetStream(input); OpenApiDocument document; document = new OpenApiStreamReader(new OpenApiReaderSettings { RuleSet = ValidationRuleSet.GetDefaultRuleSet() } ).Read(stream, out var context); if (context.Errors.Count != 0) { foreach (var error in context.Errors) { Console.WriteLine(error.ToString()); } } var statsVisitor = new StatsVisitor(); var walker = new OpenApiWalker(statsVisitor); walker.Walk(document); Console.WriteLine(statsVisitor.GetStatisticsReport()); }
public void LoadSecuritySchemeReference() { // Arrange OpenApiDocument document; var diagnostic = new OpenApiDiagnostic(); using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml"))) { document = new OpenApiStreamReader().Read(stream, out diagnostic); } var reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "api_key_sample" }; // Act var referencedObject = document.ResolveReference(reference); // Assert referencedObject.ShouldBeEquivalentTo( new OpenApiSecurityScheme { Type = SecuritySchemeType.ApiKey, Name = "api_key", In = ParameterLocation.Header, Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "api_key_sample" } } ); }
public void ParseAdvancedCallbackWithReferenceShouldSucceed() { using (var stream = File.OpenRead(Path.Combine(SampleFolderPath, "advancedCallbackWithReference.yaml"))) { // Act var openApiDoc = new OpenApiStreamReader().Read(stream, out var context); // Assert var path = openApiDoc.Paths.First().Value; var subscribeOperation = path.Operations[OperationType.Post]; var callback = subscribeOperation.Callbacks["simpleHook"]; context.ShouldBeEquivalentTo(new OpenApiDiagnostic()); callback.ShouldBeEquivalentTo( new OpenApiCallback { Reference = new OpenApiReference { Type = ReferenceType.Callback, Id = "simpleHook", }, PathItems = { [RuntimeExpression.Build("$request.body#/url")] = new OpenApiPathItem { Operations = { [OperationType.Post] = new OpenApiOperation { RequestBody = new OpenApiRequestBody { Content = { ["application/json"] = new OpenApiMediaType { Schema = new OpenApiSchema { Type = "object" } } } }, Responses = new OpenApiResponses { ["200"] = new OpenApiResponse { Description = "Success" } } } } } } }); } }
private static OpenApiDocument GetOpenApiDocument(string url) { HttpClient httpClient = CreateHttpClient(); var response = httpClient.GetAsync(url) .GetAwaiter().GetResult(); if (!response.IsSuccessStatusCode) { throw new Exception("Failed to retrieve OpenApi document"); } var stream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult();; var newrules = ValidationRuleSet.GetDefaultRuleSet().Rules .Where(r => r.GetType() != typeof(ValidationRule <OpenApiSchema>)).ToList(); var reader = new OpenApiStreamReader(new OpenApiReaderSettings() { RuleSet = new ValidationRuleSet(newrules) }); var openApiDoc = reader.Read(stream, out var diagnostic); if (diagnostic.Errors.Count > 0) { throw new Exception("OpenApi document has errors : " + String.Join("\n", diagnostic.Errors)); } return(openApiDoc); }
public async Task SharedAccessKeyAuthenticationOption_GetsSwaggerDocs_ContainsSharedAccessKeySecurityScheme() { // Arrange const string headerName = "x-shared-access-key"; const string secretKey = "MySecretKey"; string secretValue = Guid.NewGuid().ToString("N"); var authenticatedArguments = new WebApiProjectOptions() .WithSharedAccessAuthentication(headerName, secretKey, secretValue); using (var project = await WebApiProject.StartNewAsync(_configuration, authenticatedArguments, _outputWriter)) // Act using (HttpResponseMessage response = await project.Swagger.GetSwaggerDocsAsync()) { // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var reader = new OpenApiStreamReader(); using (Stream json = await response.Content.ReadAsStreamAsync()) { OpenApiDocument document = reader.Read(json, out OpenApiDiagnostic diagnostic); Assert.NotNull(document.Components); (string schemeName, OpenApiSecurityScheme componentScheme) = Assert.Single(document.Components.SecuritySchemes); Assert.Equal("shared-access-key", schemeName); Assert.Equal(ParameterLocation.Header, componentScheme.In); Assert.Equal(headerName, componentScheme.Name); OpenApiSecurityRequirement requirement = Assert.Single(document.SecurityRequirements); Assert.NotNull(requirement); (OpenApiSecurityScheme requirementScheme, IList <string> scopes) = Assert.Single(requirement); Assert.Equal(headerName, requirementScheme.Name); } } }
private string ConvertToOpenAPI(string text) { Stream stream = CreateStream(text); var document = new OpenApiStreamReader(new OpenApiReaderSettings { ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences, RuleSet = ValidationRuleSet.GetDefaultRuleSet() } ).Read(stream, out var context); if (context.Errors.Any()) { var errorReport = new StringBuilder(); foreach (var error in context.Errors) { errorReport.AppendLine(error.ToString()); } throw new ConversionException(errorReport.ToString()); } return(WriteContents(document)); }
public async Task EnsureThatICouldParse(string url) { var response = await _httpClient.GetAsync(url); if (!response.IsSuccessStatusCode) { _output.WriteLine($"Couldn't load {url}"); return; } await response.Content.LoadIntoBufferAsync(); var stream = await response.Content.ReadAsStreamAsync(); var stopwatch = new Stopwatch(); stopwatch.Start(); var reader = new OpenApiStreamReader(); var openApiDocument = reader.Read(stream, out var diagnostic); if (diagnostic.Errors.Count > 0) { _output.WriteLine($"Errors parsing {url}"); _output.WriteLine(String.Join("\n", diagnostic.Errors)); // Assert.True(false); // Uncomment to identify descriptions with errors. } Assert.NotNull(openApiDocument); stopwatch.Stop(); _output.WriteLine($"Parsing {url} took {stopwatch.ElapsedMilliseconds} ms."); }
internal static async void ValidateOpenApiDocument(string openapi, LogLevel loglevel) { if (string.IsNullOrEmpty(openapi)) { throw new ArgumentNullException(nameof(openapi)); } var logger = ConfigureLoggerInstance(loglevel); var stream = await GetStream(openapi, logger); OpenApiDocument document; logger.LogTrace("Parsing the OpenApi file"); document = new OpenApiStreamReader(new OpenApiReaderSettings { RuleSet = ValidationRuleSet.GetDefaultRuleSet() } ).Read(stream, out var context); if (context.Errors.Count != 0) { foreach (var error in context.Errors) { Console.WriteLine(error.ToString()); } } var statsVisitor = new StatsVisitor(); var walker = new OpenApiWalker(statsVisitor); walker.Walk(document); logger.LogTrace("Finished walking through the OpenApi document. Generating a statistics report.."); Console.WriteLine(statsVisitor.GetStatisticsReport()); }
public void ParseSelfReferencingSchemaShouldNotStackOverflow() { using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "selfReferencingSchema.yaml"))) { // Act var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); // Assert var components = openApiDoc.Components; diagnostic.ShouldBeEquivalentTo( new OpenApiDiagnostic() { SpecificationVersion = OpenApiSpecVersion.OpenApi3_0 }); var schemaExtension = new OpenApiSchema() { AllOf = { new OpenApiSchema() { Title = "schemaExtension", Type = "object", Properties = { ["description"] = new OpenApiSchema() { Type = "string", Nullable = true }, ["targetTypes"] = new OpenApiSchema() { Type = "array", Items = new OpenApiSchema() { Type = "string" } }, ["status"] = new OpenApiSchema() { Type = "string" }, ["owner"] = new OpenApiSchema() { Type = "string" }, ["child"] = null } } }, Reference = new OpenApiReference() { Type = ReferenceType.Schema, Id = "microsoft.graph.schemaExtension" } }; schemaExtension.AllOf[0].Properties["child"] = schemaExtension; components.Schemas["microsoft.graph.schemaExtension"].ShouldBeEquivalentTo(components.Schemas["microsoft.graph.schemaExtension"].AllOf[0].Properties["child"]); } }
private static IOpenApiAny MapExample(string exampleAsJson) { var stringAsStream = new MemoryStream(Encoding.UTF8.GetBytes(exampleAsJson)); var reader = new OpenApiStreamReader(); return(reader.ReadFragment <IOpenApiAny>(stringAsStream, OpenApiSpecVersion.OpenApi3_0, out _)); }
public static void AddOpenApiFile(this ApiTestRunnerOptions options, string documentName, string filePath) { using (var fileStream = File.OpenRead(filePath)) { var openApiDocument = new OpenApiStreamReader().Read(fileStream, out OpenApiDiagnostic diagnostic); options.OpenApiDocs.Add(documentName, openApiDocument); } }
private static OpenApiDocument FromStream(Stream stream) { using (stream) { var sr = new OpenApiStreamReader(_settings); return(sr.Read(stream, out var diagnostic)); } }
private async Task <OpenApiDocument> ReadDocumentAsync() { var reader = new OpenApiStreamReader(); await using var stream = File.OpenRead(_options.InputFile); return(reader.Read(stream, out _)); }
private async Task AssertValidSwaggerAsync(HttpResponseMessage swaggerResponse) { var contentStream = await swaggerResponse.Content.ReadAsStreamAsync(); var openApiDocument = new OpenApiStreamReader().Read(contentStream, out OpenApiDiagnostic diagnostic); Assert.Equal(Enumerable.Empty <OpenApiError>(), diagnostic.Errors); }
public static OpenApiDocument Read(this OpenApiStreamReader reader, Stream input) { if (reader is null) { throw new ArgumentNullException(nameof(reader)); } return(reader.Read(input, out OpenApiDiagnostic _)); }
public OpenApiDocument LoadOpenApiDocument(string filePath) { using (var streamReader = File.OpenText(Path.Combine(GetCurrentAssemblyFolder(), filePath))) { var openApiDocument = new OpenApiStreamReader().Read(streamReader.BaseStream, out var context); Assert.False(context.Errors?.Count > 0); return(openApiDocument); } }