5
5
using System . Collections . Generic ;
6
6
using System . Globalization ;
7
7
using System . Linq ;
8
+ using Microsoft . OpenApi . Exceptions ;
8
9
using Microsoft . OpenApi . Extensions ;
9
10
using Microsoft . OpenApi . Interfaces ;
10
11
using Microsoft . OpenApi . Models ;
@@ -122,18 +123,26 @@ internal static partial class OpenApiV2Deserializer
122
123
{ s => s . StartsWith ( "x-" ) , ( o , p , n ) => o . AddExtension ( p , LoadExtension ( p , n ) ) }
123
124
} ;
124
125
125
- private static void MakeServers ( IList < OpenApiServer > servers , ParsingContext context , Uri defaultUrl )
126
+ private static void MakeServers ( IList < OpenApiServer > servers , ParsingContext context , RootNode rootNode )
126
127
{
127
128
var host = context . GetFromTempStorage < string > ( "host" ) ;
128
129
var basePath = context . GetFromTempStorage < string > ( "basePath" ) ;
129
130
var schemes = context . GetFromTempStorage < List < string > > ( "schemes" ) ;
131
+ Uri defaultUrl = rootNode . Context . BaseUrl ;
130
132
131
133
// If nothing is provided, don't create a server
132
134
if ( host == null && basePath == null && schemes == null )
133
135
{
134
136
return ;
135
137
}
136
138
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
+
137
146
// Fill in missing information based on the defaultUrl
138
147
if ( defaultUrl != null )
139
148
{
@@ -226,7 +235,7 @@ public static OpenApiDocument LoadOpenApi(RootNode rootNode)
226
235
openApidoc . Servers = new List < OpenApiServer > ( ) ;
227
236
}
228
237
229
- MakeServers ( openApidoc . Servers , openApiNode . Context , rootNode . Context . BaseUrl ) ;
238
+ MakeServers ( openApidoc . Servers , openApiNode . Context , rootNode ) ;
230
239
231
240
FixRequestBodyReferences ( openApidoc ) ;
232
241
return openApidoc ;
@@ -243,6 +252,26 @@ private static void FixRequestBodyReferences(OpenApiDocument doc)
243
252
walker . Walk ( doc ) ;
244
253
}
245
254
}
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
+ }
246
275
}
247
276
248
277
internal class RequestBodyReferenceFixer : OpenApiVisitorBase
0 commit comments