55using System . Collections . Generic ;
66using System . Globalization ;
77using System . Linq ;
8+ using Microsoft . OpenApi . Exceptions ;
89using Microsoft . OpenApi . Extensions ;
910using Microsoft . OpenApi . Interfaces ;
1011using Microsoft . OpenApi . Models ;
@@ -122,18 +123,26 @@ internal static partial class OpenApiV2Deserializer
122123 { s => s . StartsWith ( "x-" ) , ( o , p , n ) => o . AddExtension ( p , LoadExtension ( p , n ) ) }
123124 } ;
124125
125- private static void MakeServers ( IList < OpenApiServer > servers , ParsingContext context , Uri defaultUrl )
126+ private static void MakeServers ( IList < OpenApiServer > servers , ParsingContext context , RootNode rootNode )
126127 {
127128 var host = context . GetFromTempStorage < string > ( "host" ) ;
128129 var basePath = context . GetFromTempStorage < string > ( "basePath" ) ;
129130 var schemes = context . GetFromTempStorage < List < string > > ( "schemes" ) ;
131+ Uri defaultUrl = rootNode . Context . BaseUrl ;
130132
131133 // If nothing is provided, don't create a server
132134 if ( host == null && basePath == null && schemes == null )
133135 {
134136 return ;
135137 }
136138
139+ //Validate host
140+ if ( host != null && ! IsHostValid ( host ) )
141+ {
142+ rootNode . Diagnostic . Errors . Add ( new OpenApiError ( new OpenApiException ( "Invalid host" ) ) ) ;
143+ return ;
144+ }
145+
137146 // Fill in missing information based on the defaultUrl
138147 if ( defaultUrl != null )
139148 {
@@ -226,7 +235,7 @@ public static OpenApiDocument LoadOpenApi(RootNode rootNode)
226235 openApidoc . Servers = new List < OpenApiServer > ( ) ;
227236 }
228237
229- MakeServers ( openApidoc . Servers , openApiNode . Context , rootNode . Context . BaseUrl ) ;
238+ MakeServers ( openApidoc . Servers , openApiNode . Context , rootNode ) ;
230239
231240 FixRequestBodyReferences ( openApidoc ) ;
232241 return openApidoc ;
@@ -243,6 +252,26 @@ private static void FixRequestBodyReferences(OpenApiDocument doc)
243252 walker . Walk ( doc ) ;
244253 }
245254 }
255+
256+ private static bool IsHostValid ( string host )
257+ {
258+ try
259+ {
260+ //Check if the host contains ://
261+ if ( host . Contains ( Uri . SchemeDelimiter ) )
262+ {
263+ return false ;
264+ }
265+
266+ //Check if the host (excluding port number) is a valid dns/ip address.
267+ var hostPart = host . Split ( ':' ) . First ( ) ;
268+ return Uri . CheckHostName ( hostPart ) != UriHostNameType . Unknown ;
269+ }
270+ catch ( Exception )
271+ {
272+ return false ;
273+ }
274+ }
246275 }
247276
248277 internal class RequestBodyReferenceFixer : OpenApiVisitorBase
0 commit comments