Skip to content

Commit b5ba170

Browse files
authored
[rust-axum] Honor additionalProperties: false on object models (#25256)
* fix(rust-axum): reject unknown fields in closed object models Signed-off-by: lucarlig <luca.carlig@ibm.com> * fix(rust-axum): handle boolean schemas and tighten regressions Signed-off-by: lucarlig <luca.carlig@ibm.com> * fix(rust-axum): apply model extension review feedback Signed-off-by: lucarlig <luca.carlig@ibm.com> --------- Signed-off-by: lucarlig <luca.carlig@ibm.com>
1 parent bf51cab commit b5ba170

7 files changed

Lines changed: 237 additions & 0 deletions

File tree

‎modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustAxumServerCodegen.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1420,6 +1420,20 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert
14201420
}
14211421
}
14221422

1423+
@Override
1424+
public CodegenModel fromModel(String name, Schema schema) {
1425+
final CodegenModel model = super.fromModel(name, schema);
1426+
// Only explicit false closes an object; an omitted keyword must retain its current behavior.
1427+
final Object additionalProperties = schema.getAdditionalProperties();
1428+
final boolean denyUnknownFields = Boolean.FALSE.equals(additionalProperties)
1429+
|| (additionalProperties instanceof Schema
1430+
&& Boolean.FALSE.equals(((Schema) additionalProperties).getBooleanSchemaValue()));
1431+
if (denyUnknownFields) {
1432+
model.vendorExtensions.put("x-rust-deny-unknown-fields", true);
1433+
}
1434+
return model;
1435+
}
1436+
14231437
@Override
14241438
public ModelsMap postProcessModels(ModelsMap modelsMap) {
14251439
for (ModelMap mo : modelsMap.getModels()) {

‎modules/openapi-generator/src/main/resources/rust-axum/models.mustache‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -990,6 +990,9 @@ impl From<{{{dataType}}}> for {{{classname}}} {
990990
{{^oneOf.size}}
991991
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)]
992992
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
993+
{{#vendorExtensions.x-rust-deny-unknown-fields}}
994+
#[serde(deny_unknown_fields)]
995+
{{/vendorExtensions.x-rust-deny-unknown-fields}}
993996
pub struct {{{classname}}} {
994997
{{#vars}}
995998
{{#description}}

‎modules/openapi-generator/src/test/java/org/openapitools/codegen/rust/RustAxumServerCodegenTest.java‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import org.openapitools.codegen.config.CodegenConfigurator;
77
import org.openapitools.codegen.languages.RustAxumServerCodegen;
88
import org.testng.Assert;
9+
import org.testng.annotations.DataProvider;
910
import org.testng.annotations.Test;
1011

1112
import java.io.File;
@@ -18,6 +19,36 @@
1819
import static org.openapitools.codegen.TestUtils.linearize;
1920

2021
public class RustAxumServerCodegenTest {
22+
@DataProvider(name = "additionalPropertiesSpecs")
23+
public Object[][] additionalPropertiesSpecs() {
24+
return new Object[][] {
25+
{"src/test/resources/3_0/rust-axum/additional-properties.yaml"},
26+
{"src/test/resources/3_1/rust-axum/additional-properties.yaml"}
27+
};
28+
}
29+
30+
@Test(dataProvider = "additionalPropertiesSpecs")
31+
public void testAdditionalPropertiesFalse(String inputSpec) throws IOException {
32+
Path target = Files.createTempDirectory("test");
33+
final CodegenConfigurator configurator = new CodegenConfigurator()
34+
.setGeneratorName("rust-axum")
35+
.setInputSpec(inputSpec)
36+
.setSkipOverwrite(false)
37+
.setOutputDir(target.toAbsolutePath().toString().replace("\\", "/"));
38+
List<File> files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate();
39+
files.forEach(File::deleteOnExit);
40+
41+
Path modelsPath = Path.of(target.toString(), "/src/models.rs");
42+
TestUtils.assertFileExists(modelsPath);
43+
for (String model : List.of("ClosedObject", "ClosedNested", "ClosedOptional")) {
44+
TestUtils.assertFileContains(modelsPath, "#[serde(deny_unknown_fields)]\npub struct " + model + " {");
45+
}
46+
for (String model : List.of("OpenObject", "UnspecifiedObject", "TypedAdditionalProperties")) {
47+
TestUtils.assertFileContains(modelsPath, "pub struct " + model + " {");
48+
TestUtils.assertFileNotContains(modelsPath, "#[serde(deny_unknown_fields)]\npub struct " + model + " {");
49+
}
50+
}
51+
2152
@Test
2253
public void testObjectStructFieldIsPublic() throws IOException {
2354
Path target = Files.createTempDirectory("test");
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
openapi: 3.0.3
2+
info:
3+
title: Additional properties test
4+
version: 1.0.0
5+
paths:
6+
/objects:
7+
get:
8+
operationId: getObject
9+
responses:
10+
'200':
11+
description: A closed object with an open configuration field
12+
content:
13+
application/json:
14+
schema:
15+
$ref: '#/components/schemas/ClosedObject'
16+
components:
17+
schemas:
18+
ClosedObject:
19+
type: object
20+
additionalProperties: false
21+
required:
22+
- name
23+
- nested
24+
- config
25+
properties:
26+
name:
27+
type: string
28+
nested:
29+
$ref: '#/components/schemas/ClosedNested'
30+
config:
31+
type: object
32+
additionalProperties: true
33+
ClosedNested:
34+
type: object
35+
additionalProperties: false
36+
required:
37+
- value
38+
properties:
39+
value:
40+
type: string
41+
ClosedOptional:
42+
type: object
43+
additionalProperties: false
44+
properties:
45+
value:
46+
type: string
47+
OpenObject:
48+
type: object
49+
additionalProperties: true
50+
required:
51+
- name
52+
properties:
53+
name:
54+
type: string
55+
UnspecifiedObject:
56+
type: object
57+
required:
58+
- name
59+
properties:
60+
name:
61+
type: string
62+
TypedAdditionalProperties:
63+
type: object
64+
additionalProperties:
65+
type: string
66+
required:
67+
- name
68+
properties:
69+
name:
70+
type: string
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
openapi: 3.1.0
2+
info:
3+
title: Additional properties test
4+
version: 1.0.0
5+
paths:
6+
/objects:
7+
get:
8+
operationId: getObject
9+
responses:
10+
'200':
11+
description: A closed object with an open configuration field
12+
content:
13+
application/json:
14+
schema:
15+
$ref: '#/components/schemas/ClosedObject'
16+
components:
17+
schemas:
18+
ClosedObject:
19+
type: object
20+
additionalProperties: false
21+
required:
22+
- name
23+
- nested
24+
- config
25+
properties:
26+
name:
27+
type: string
28+
nested:
29+
$ref: '#/components/schemas/ClosedNested'
30+
config:
31+
type: object
32+
additionalProperties: true
33+
ClosedNested:
34+
type: object
35+
additionalProperties: false
36+
required:
37+
- value
38+
properties:
39+
value:
40+
type: string
41+
ClosedOptional:
42+
type: object
43+
additionalProperties: false
44+
properties:
45+
value:
46+
type: string
47+
OpenObject:
48+
type: object
49+
additionalProperties: true
50+
required:
51+
- name
52+
properties:
53+
name:
54+
type: string
55+
UnspecifiedObject:
56+
type: object
57+
required:
58+
- name
59+
properties:
60+
name:
61+
type: string
62+
TypedAdditionalProperties:
63+
type: object
64+
additionalProperties:
65+
type: string
66+
required:
67+
- name
68+
properties:
69+
name:
70+
type: string

‎samples/server/petstore/rust-axum/output/rust-axum-oneof/src/models.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ pub fn check_xss_map<T>(
9494

9595
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)]
9696
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
97+
#[serde(deny_unknown_fields)]
9798
pub struct Goodbye {
9899
/// Note: inline enums are not fully supported by openapi-generator
99100
#[serde(default = "Goodbye::_name_for_op")]
@@ -399,6 +400,7 @@ impl std::convert::TryFrom<HeaderValue> for header::IntoHeaderValue<GoodbyeD> {
399400

400401
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)]
401402
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
403+
#[serde(deny_unknown_fields)]
402404
pub struct Greeting {
403405
#[serde(rename = "d")]
404406
#[validate(nested)]
@@ -702,6 +704,7 @@ impl std::convert::TryFrom<HeaderValue> for header::IntoHeaderValue<GreetingD> {
702704

703705
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)]
704706
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
707+
#[serde(deny_unknown_fields)]
705708
pub struct Hello {
706709
/// Note: inline enums are not fully supported by openapi-generator
707710
#[serde(default = "Hello::_name_for_op")]
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
use rust_axum_oneof::models::{Hello, Message, YoMessage};
2+
use serde_json::json;
3+
4+
#[test]
5+
fn closed_object_rejects_unknown_fields() {
6+
let mut input = json!({"op": "Hello", "d": {"welcome_message": "known"}});
7+
assert!(serde_json::from_value::<Hello>(input.clone()).is_ok());
8+
9+
input["unexpected"] = json!(true);
10+
let error = serde_json::from_value::<Hello>(input).unwrap_err();
11+
assert!(error.to_string().contains("unknown field `unexpected`"));
12+
}
13+
14+
#[test]
15+
fn tagged_closed_variants_reject_unknown_fields() {
16+
for mut input in [
17+
json!({"op": "Hello", "d": {"welcome_message": "known"}}),
18+
json!({"op": "Greeting", "d": {"greet_message": "known"}}),
19+
json!({"op": "Goodbye", "d": {"goodbye_message": "known"}}),
20+
] {
21+
assert!(serde_json::from_value::<Message>(input.clone()).is_ok());
22+
input["unexpected"] = json!(true);
23+
assert!(serde_json::from_value::<Message>(input).is_err());
24+
}
25+
}
26+
27+
#[test]
28+
fn closed_object_keeps_its_declared_nested_object_open() {
29+
let input = json!({
30+
"op": "Hello",
31+
"d": {
32+
"welcome_message": "known",
33+
"custom": {"enabled": true, "items": [1, "two", null]}
34+
}
35+
});
36+
let model: Hello = serde_json::from_value(input.clone()).unwrap();
37+
assert_eq!(model.d.welcome_message, "known");
38+
assert!(serde_json::from_value::<Message>(input).is_ok());
39+
}
40+
41+
#[test]
42+
fn object_without_explicit_false_keeps_accepting_unknown_fields() {
43+
let input = json!({"op": "yo", "d": {"nickname": "known"}, "unexpected": true});
44+
let model: YoMessage = serde_json::from_value(input).unwrap();
45+
assert_eq!(model.d.nickname, "known");
46+
}

0 commit comments

Comments
 (0)