Skip to content
25 changes: 23 additions & 2 deletions src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,18 +122,26 @@ internal static partial class OpenApiV2Deserializer
{s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))}
};

private static void MakeServers(IList<OpenApiServer> servers, ParsingContext context, Uri defaultUrl)
private static void MakeServers(IList<OpenApiServer> servers, ParsingContext context, RootNode rootNode)
{
var host = context.GetFromTempStorage<string>("host");
var basePath = context.GetFromTempStorage<string>("basePath");
var schemes = context.GetFromTempStorage<List<string>>("schemes");
Uri defaultUrl = rootNode.Context.BaseUrl;

// If nothing is provided, don't create a server
if (host == null && basePath == null && schemes == null)
{
return;
}

//Validate host
if (host != null && !IsHostValid(host))
{
rootNode.Diagnostic.Errors.Add(new OpenApiError(rootNode.Context.GetLocation(), "Invalid host"));
return;
}

// Fill in missing information based on the defaultUrl
if (defaultUrl != null)
{
Expand Down Expand Up @@ -226,7 +234,7 @@ public static OpenApiDocument LoadOpenApi(RootNode rootNode)
openApidoc.Servers = new List<OpenApiServer>();
}

MakeServers(openApidoc.Servers, openApiNode.Context, rootNode.Context.BaseUrl);
MakeServers(openApidoc.Servers, openApiNode.Context, rootNode);

FixRequestBodyReferences(openApidoc);
return openApidoc;
Expand All @@ -243,6 +251,19 @@ private static void FixRequestBodyReferences(OpenApiDocument doc)
walker.Walk(doc);
}
}

private static bool IsHostValid(string host)
{
//Check if the host contains ://
if (host.Contains(Uri.SchemeDelimiter))
{
return false;
}

//Check if the host (excluding port number) is a valid dns/ip address.
var hostPart = host.Split(':').First();
return Uri.CheckHostName(hostPart) != UriHostNameType.Unknown;
}
}

internal class RequestBodyReferenceFixer : OpenApiVisitorBase
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using System;
using FluentAssertions;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Expand Down Expand Up @@ -257,5 +260,35 @@ public void LocalHostWithCustomHost()
Assert.Equal(1, doc.Servers.Count);
Assert.Equal("https://localhost:23232", server.Url);
}

[Fact]
public void InvalidHostShouldYieldError()
{
var input = @"
swagger: 2.0
info:
title: test
version: 1.0.0
host: http://test.microsoft.com
paths: {}
";
var reader = new OpenApiStringReader(new OpenApiReaderSettings()
{
BaseUrl = new Uri("https://bing.com")
});

var doc = reader.Read(input, out var diagnostic);
doc.Servers.Count.Should().Be(0);
diagnostic.ShouldBeEquivalentTo(
new OpenApiDiagnostic
{
Errors =
{
new OpenApiError("#/", "Invalid host")
},
SpecificationVersion = OpenApiSpecVersion.OpenApi2_0
});
}

}
}