Skip to content

Commit 78203e9

Browse files
committed
Exclude non-relative OpenAPI paths from selection and cover base-path reconciliation
Extend the Python parser to exclude absolute or authority-changing operation paths (for example "https://another-host/admin") before the selection predicate is consulted, so selection and request construction share one canonical target. The .NET OpenAPI reader already rejects such non-relative path keys during parsing, so a regression test locks that in rather than adding an unreachable check. Add the missing test coverage for the base-path reconciliation branch, which rejects a same-authority request whose canonical path escapes the configured server base path, in both the .NET and Python request builders.
1 parent 06241a2 commit 78203e9

6 files changed

Lines changed: 140 additions & 7 deletions

File tree

‎dotnet/src/Functions/Functions.OpenApi/OpenApi/OpenApiDocumentParser.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,9 @@ internal static List<RestApiOperation> CreateRestApiOperations(OpenApiDocument d
200200
// Exclude operations whose path contains an encoded or literal dot-segment before the
201201
// selection predicate is consulted. Such a path is canonicalized into a different
202202
// effective endpoint at request time, so offering it to an include/exclude predicate
203-
// would let an encoded dot-segment bypass the operation-selection filter.
203+
// would let an encoded dot-segment bypass the operation-selection filter. Absolute or
204+
// authority-changing path keys are already rejected by the OpenAPI reader, so a
205+
// dot-segment check is sufficient here.
204206
if (RestApiOperation.ContainsDotSegment(path))
205207
{
206208
logger.LogWarning("Operation '{OperationId}' at path '{Path}' contains a dot-segment and will be skipped during operation selection.", operationItem.OperationId, path);

‎dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV20Tests.cs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,42 @@ public async Task ItShouldNotOfferEncodedDotSegmentOperationsToSelectionPredicat
505505
Assert.DoesNotContain(restApiSpec.Operations, o => o.Path == "/resources/%2e%2e/admin");
506506
}
507507

508+
[Fact]
509+
public async Task ItShouldRejectDocumentWithNonRelativeOperationPathAsync()
510+
{
511+
// Arrange - an absolute / authority-changing operation path key would resolve to a request off
512+
// the configured server. The OpenAPI reader rejects such a non-relative path key so it can
513+
// never reach operation selection or request construction.
514+
var document =
515+
"""
516+
{
517+
"swagger": "2.0",
518+
"info": {
519+
"title": "Test API",
520+
"version": "1.0.0"
521+
},
522+
"paths": {
523+
"https://evil.com/admin": {
524+
"get": {
525+
"operationId": "GetAdmin",
526+
"summary": "Get admin",
527+
"responses": {
528+
"200": {
529+
"description": "Successful response"
530+
}
531+
}
532+
}
533+
}
534+
}
535+
}
536+
""";
537+
538+
await using var stream = new MemoryStream(Encoding.UTF8.GetBytes(document));
539+
540+
// Act & Assert - a non-relative operation path key is rejected during parsing.
541+
await Assert.ThrowsAsync<KernelException>(() => this._sut.ParseAsync(stream));
542+
}
543+
508544
[Fact]
509545
public async Task ItCanParsePathItemPathParametersAsync()
510546
{

‎dotnet/src/Functions/Functions.UnitTests/OpenApi/RestApiOperationTests.cs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1585,6 +1585,30 @@ public void ItShouldRejectOperationPathThatChangesRequestAuthority(string path)
15851585
Assert.Contains("does not match the configured server", ex.Message);
15861586
}
15871587

1588+
[Fact]
1589+
public void ItShouldRejectSameAuthorityBasePathEscape()
1590+
{
1591+
// Arrange — an absolute path on the same authority but outside the configured base path must
1592+
// be rejected, so a request cannot be moved to a different route even when the scheme, host,
1593+
// and port all match the configured server.
1594+
var sut = new RestApiOperation(
1595+
id: "fake_id",
1596+
servers: [new RestApiServer("https://example.com/api")],
1597+
path: "https://example.com/other/admin",
1598+
method: HttpMethod.Get,
1599+
description: "fake_description",
1600+
parameters: [],
1601+
responses: new Dictionary<string, RestApiExpectedResponse>(),
1602+
securityRequirements: []
1603+
);
1604+
1605+
var arguments = new Dictionary<string, object?>();
1606+
1607+
// Act & Assert — the resolved request path must remain within the configured server base path.
1608+
var ex = Assert.Throws<KernelException>(() => sut.BuildOperationUrl(arguments));
1609+
Assert.Contains("outside the configured server base path", ex.Message);
1610+
}
1611+
15881612
[Fact]
15891613
public void ItShouldBuildUrlForOperationPathOnTheConfiguredServer()
15901614
{

‎python/semantic_kernel/connectors/openapi_plugin/models/rest_api_operation.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,22 @@ def _contains_dot_segment(path: str) -> bool:
363363
return True
364364
return False
365365

366+
@staticmethod
367+
def _is_non_relative_path(path: str) -> bool:
368+
"""Return True if the path is non-relative (absolute or authority-changing).
369+
370+
A conformant OpenAPI operation path is relative to the server URL. An absolute URI, a
371+
protocol-relative reference ("//host"), or a backslash-authority reference changes the request
372+
target once combined with the server URL, so such a path is excluded during operation selection
373+
to keep selection and request construction on one canonical target.
374+
"""
375+
if not path:
376+
return False
377+
if path.startswith(("//", "\\\\", "/\\", "\\/")):
378+
return True
379+
parsed = urlparse(path)
380+
return bool(parsed.scheme or parsed.netloc)
381+
366382
def build_query_string(self, arguments: dict[str, Any]) -> str:
367383
"""Build the query string for the operation."""
368384
segments = []

‎python/semantic_kernel/connectors/openapi_plugin/openapi_parser.py‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -265,13 +265,15 @@ def create_rest_api_operations(
265265
summary = details.get("summary", None)
266266
description = details.get("description", None)
267267

268-
# Exclude operations whose path contains an encoded or literal dot-segment before the
269-
# selection predicate is consulted. Such a path is canonicalized into a different
270-
# effective endpoint at request time, so offering it to an include/exclude predicate
271-
# would let an encoded dot-segment bypass the operation-selection filter.
272-
if RestApiOperation._contains_dot_segment(path):
268+
# Exclude operations whose path would resolve to a different effective request target
269+
# than the one offered to the selection predicate: a dot-segment (encoded or literal)
270+
# or a non-relative (absolute / authority-changing) path. Excluding them here keeps
271+
# operation selection and request construction on one canonical target so such a path
272+
# cannot bypass an include/exclude operation-selection filter.
273+
if RestApiOperation._contains_dot_segment(path) or RestApiOperation._is_non_relative_path(path):
273274
logger.warning(
274-
f"Skipping operation {operationId} at path '{path}' because it contains a dot-segment."
275+
f"Skipping operation {operationId} at path '{path}' because it does not resolve to a "
276+
f"relative path on the configured server."
275277
)
276278
continue
277279

‎python/tests/unit/connectors/openapi_plugin/test_sk_openapi.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -552,6 +552,16 @@ def test_build_operation_url_allows_same_server_path():
552552
assert operation.build_operation_url({}) == "https://example.com/api/resources/item"
553553

554554

555+
def test_build_operation_url_rejects_same_authority_base_path_escape():
556+
# An absolute path on the same authority but outside the configured base path must be rejected,
557+
# so a request cannot be moved to a different route even when scheme, host, and port all match.
558+
operation = RestApiOperation(
559+
id="test", method="GET", servers=["https://example.com/api"], path="https://example.com/other/admin", params=[]
560+
)
561+
with pytest.raises(FunctionExecutionException, match="outside the configured server base path"):
562+
operation.build_operation_url({})
563+
564+
555565
def test_build_query_string_with_required_parameter():
556566
parameters = [
557567
RestApiParameter(name="query", type="string", location=RestApiParameterLocation.QUERY, is_required=True)
@@ -970,6 +980,49 @@ def predicate_callback(context):
970980
assert "getAdmin" not in operations
971981

972982

983+
def test_non_relative_path_operations_excluded_from_selection():
984+
# An operation whose path is an absolute / authority-changing URI resolves to a request off the
985+
# configured server, so it must be excluded before the selection predicate is consulted rather
986+
# than offered to a path-based filter and only rejected later at request construction.
987+
parsed_document = {
988+
"servers": [{"url": "https://example.com"}],
989+
"paths": {
990+
"/items": {
991+
"get": {
992+
"operationId": "getItems",
993+
"summary": "Get items",
994+
"responses": {"200": {"description": "OK"}},
995+
}
996+
},
997+
"https://evil.com/admin": {
998+
"get": {
999+
"operationId": "getAdmin",
1000+
"summary": "Get admin",
1001+
"responses": {"200": {"description": "OK"}},
1002+
}
1003+
},
1004+
},
1005+
}
1006+
1007+
observed_paths: list[str] = []
1008+
1009+
def predicate_callback(context):
1010+
observed_paths.append(context.path)
1011+
return True
1012+
1013+
parser = OpenApiParser()
1014+
exec_settings = OpenAPIFunctionExecutionParameters(operation_selection_predicate=predicate_callback)
1015+
operations = parser.create_rest_api_operations(parsed_document, execution_settings=exec_settings)
1016+
1017+
# The regular operation is offered to the predicate and imported.
1018+
assert "/items" in observed_paths
1019+
assert "getItems" in operations
1020+
1021+
# The absolute operation path is excluded before the predicate is consulted.
1022+
assert "https://evil.com/admin" not in observed_paths
1023+
assert "getAdmin" not in operations
1024+
1025+
9731026
@patch("aiohttp.ClientSession.request")
9741027
async def test_run_operation_with_invalid_request(mock_request, openapi_runner):
9751028
runner, operations = openapi_runner

0 commit comments

Comments
 (0)