Skip to content

Commit d43ef52

Browse files
Include request and response schemas in devproxy api show --output json (#2096)
* Include request and response schemas in devproxy api show --output json Each endpoint in the JSON output now includes OpenAPI-style query parameters, a request body JSON schema, and responses keyed by status code. Also removes the stale /swagger reference from the help text. Closes #2066 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Address review: rename query to parameters, tighten schemas - Rename structured query field to OpenAPI 'parameters' (with in: query) so it doesn't collide with the 'query' hint added in #2092 - Disallow additional properties in the POST /proxy request schema - Document 400 for invalid query values on /proxy/logs Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Require positive validFor in jwtToken schema Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Document 204 for POST /proxy/mockRequest in API schemas Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Mark rootCertificate format query parameter as optional Upstream made format optional (default crt) and added pem as an alias. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent ef9974f commit d43ef52

5 files changed

Lines changed: 438 additions & 6 deletions

File tree

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using DevProxy.ApiControllers;
6+
using DevProxy.Commands;
7+
using DevProxy.Jwt;
8+
using Microsoft.AspNetCore.Mvc;
9+
using Microsoft.AspNetCore.Mvc.Routing;
10+
using System.ComponentModel.DataAnnotations;
11+
using System.Reflection;
12+
using System.Text.Json;
13+
14+
using Xunit;
15+
16+
namespace DevProxy.Tests;
17+
18+
public class ApiEndpointSchemasTests
19+
{
20+
public static TheoryData<string, string, string> ControllerEndpoints()
21+
{
22+
var data = new TheoryData<string, string, string>();
23+
var controllerRoute = "/" + nameof(ProxyController).Replace("Controller", "", StringComparison.Ordinal).ToLowerInvariant();
24+
foreach (var action in typeof(ProxyController).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
25+
{
26+
foreach (var attribute in action.GetCustomAttributes<HttpMethodAttribute>())
27+
{
28+
var path = string.IsNullOrEmpty(attribute.Template) ? controllerRoute : $"{controllerRoute}/{attribute.Template}";
29+
foreach (var method in attribute.HttpMethods)
30+
{
31+
data.Add(method, path, action.Name);
32+
}
33+
}
34+
}
35+
return data;
36+
}
37+
38+
[Theory]
39+
[MemberData(nameof(ControllerEndpoints))]
40+
public void Get_EveryControllerEndpoint_HasSchema(string method, string path, string actionName)
41+
{
42+
_ = actionName;
43+
var schema = ApiEndpointSchemas.Get(method, path);
44+
45+
Assert.NotNull(schema);
46+
Assert.NotEmpty(schema.Responses);
47+
}
48+
49+
[Theory]
50+
[MemberData(nameof(ControllerEndpoints))]
51+
public void Get_QueryParameters_MatchControllerAction(string method, string path, string actionName)
52+
{
53+
var action = GetAction(actionName);
54+
var expected = action.GetParameters()
55+
.Where(p => p.GetCustomAttribute<FromQueryAttribute>() is not null)
56+
.ToDictionary(p => p.Name!, p => p.GetCustomAttribute<RequiredAttribute>() is not null);
57+
58+
var query = ApiEndpointSchemas.Get(method, path)!.Parameters ?? [];
59+
var actual = query.ToDictionary(p => p!["name"]!.GetValue<string>(), p => p!["required"]!.GetValue<bool>());
60+
61+
Assert.Equal(expected.OrderBy(kv => kv.Key), actual.OrderBy(kv => kv.Key));
62+
}
63+
64+
[Theory]
65+
[MemberData(nameof(ControllerEndpoints))]
66+
public void Get_RequestBody_PresentOnlyForFromBodyActions(string method, string path, string actionName)
67+
{
68+
var action = GetAction(actionName);
69+
var hasBody = action.GetParameters().Any(p => p.GetCustomAttribute<FromBodyAttribute>() is not null);
70+
71+
Assert.Equal(hasBody, ApiEndpointSchemas.Get(method, path)!.RequestBody is not null);
72+
}
73+
74+
[Fact]
75+
public void Get_JwtTokenRequestBody_ListsAllJwtOptionsProperties()
76+
{
77+
var properties = GetRequestBodyProperties("POST", "/proxy/jwtToken");
78+
79+
Assert.Equal(CamelCasePropertyNames<JwtOptions>(), properties);
80+
}
81+
82+
[Fact]
83+
public void Get_ProxyStatusResponse_ListsAllProxyInfoProperties()
84+
{
85+
var schema = ApiEndpointSchemas.Get("GET", "/proxy")!;
86+
var properties = schema.Responses["200"]!["content"]![ApiEndpointSchemas.JsonContentType]!["schema"]!["properties"]!
87+
.AsObject().Select(p => p.Key).Order(StringComparer.Ordinal);
88+
89+
Assert.Equal(CamelCasePropertyNames<ProxyInfo>(), properties);
90+
}
91+
92+
[Fact]
93+
public void Get_LogsJsonResponse_ListsAllLogEntryProperties()
94+
{
95+
var logEntryType = typeof(ProxyController).GetNestedType("LogEntryDto", BindingFlags.NonPublic)!;
96+
var expected = logEntryType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
97+
.Select(p => p.Name).Order(StringComparer.Ordinal);
98+
99+
var schema = ApiEndpointSchemas.Get("GET", "/proxy/logs")!;
100+
var properties = schema.Responses["200"]!["content"]![ApiEndpointSchemas.JsonContentType]!["schema"]!["items"]!["properties"]!
101+
.AsObject().Select(p => p.Key).Order(StringComparer.Ordinal);
102+
103+
Assert.Equal(expected, properties);
104+
}
105+
106+
[Fact]
107+
public void Get_UpdateProxyRequestBody_OnlyAllowsWritableProperties()
108+
{
109+
Assert.Equal(["recording"], GetRequestBodyProperties("POST", "/proxy"));
110+
var schema = ApiEndpointSchemas.Get("POST", "/proxy")!.RequestBody!["content"]![ApiEndpointSchemas.JsonContentType]!["schema"]!;
111+
Assert.False(schema["additionalProperties"]!.GetValue<bool>());
112+
}
113+
114+
[Theory]
115+
[InlineData("POST", "/proxy/stopProxy", "202")]
116+
[InlineData("POST", "/proxy/mockRequest", "204")]
117+
[InlineData("GET", "/proxy/rootCertificate", "400")]
118+
[InlineData("GET", "/proxy/logs", "400")]
119+
public void Get_DocumentsNonDefaultStatusCodes(string method, string path, string statusCode)
120+
{
121+
Assert.True(ApiEndpointSchemas.Get(method, path)!.Responses.ContainsKey(statusCode));
122+
}
123+
124+
[Fact]
125+
public void Get_UnknownEndpoint_ReturnsNull()
126+
{
127+
Assert.Null(ApiEndpointSchemas.Get("DELETE", "/proxy"));
128+
}
129+
130+
private static MethodInfo GetAction(string name) =>
131+
typeof(ProxyController).GetMethod(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)!;
132+
133+
private static IEnumerable<string> GetRequestBodyProperties(string method, string path) =>
134+
ApiEndpointSchemas.Get(method, path)!.RequestBody!["content"]![ApiEndpointSchemas.JsonContentType]!["schema"]!["properties"]!
135+
.AsObject().Select(p => p.Key).Order(StringComparer.Ordinal);
136+
137+
private static IEnumerable<string> CamelCasePropertyNames<T>() =>
138+
typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
139+
.Select(p => JsonNamingPolicy.CamelCase.ConvertName(p.Name))
140+
.Order(StringComparer.Ordinal);
141+
}

‎DevProxy/Commands/ApiCommand.cs‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -140,11 +140,18 @@ private void PrintApiInfo(OutputFormat outputFormat)
140140
{
141141
baseUrl,
142142
authentication = new { scheme = "Bearer", header = "Authorization", tokenFilePattern },
143-
endpoints = endpoints.Select(e => new
143+
endpoints = endpoints.Select(e =>
144144
{
145-
method = e.Method,
146-
path = e.Path,
147-
description = e.Description
145+
var schema = ApiEndpointSchemas.Get(e.Method, e.Path);
146+
return new
147+
{
148+
method = e.Method,
149+
path = e.Path,
150+
description = e.Description,
151+
parameters = schema?.Parameters,
152+
requestBody = schema?.RequestBody,
153+
responses = schema?.Responses
154+
};
148155
})
149156
}, ProxyUtils.JsonSerializerOptions);
150157
_logger.LogStructuredOutput(json);

0 commit comments

Comments
 (0)