Skip to content

[kotlin-spring] Escape generated values by source context - #25766

Open
Picazsoo wants to merge 5 commits into
OpenAPITools:masterfrom
Picazsoo:bugfix/kotlin-spring-values-escaping
Open

Picazsoo wants to merge 5 commits into
OpenAPITools:masterfrom
Picazsoo:bugfix/kotlin-spring-values-escaping

Conversation

@Picazsoo

@Picazsoo Picazsoo commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The kotlin-spring generator now escapes values from the OpenAPI document correctly for the place each one lands in the generated code. Before this change, templates mostly used fields that were already HTML/Javadoc-escaped and wrapped them in hand-written "..." or """...""". When a value contained ", \, $, */, line breaks or control characters, the generated Kotlin could fail to compile. It could also end up with the wrong string value (double-escaped, or $ read as string interpolation), or contain a broken KDoc.

Changes

New escaper: SourceStringEscaper (org.openapitools.codegen.templating). It takes raw, unescaped input and returns one of:

  • a Kotlin string literal or its content: escapes \, " and $, writes control characters as \uXXXX
  • text that is safe inside /* */ doc comments: HTML entities, /* and */ broken up, continuation lines prefixed with *

Templates use it through three new lambdas: kotlinStringLiteral, kotlinStringContent and kotlinDocText.

Raw values available to templates, so each value is escaped once, for its target context:

  • operations: unescapedPath, unescapedSummary
  • responses: unescapedMessage
  • body parameters: unescapedDescription
  • enums: valueRaw
  • security scopes: descriptionRaw
  • properties and parameters: rawDefaultValue, rawDefaultValueText, hasDefaultValue
  • generator metadata: appNameRaw, appVersionRaw, infoEmailRaw, infoNameRaw, infoUrlRaw, licenseInfoRaw, licenseUrlRaw, termsOfServiceRaw, contextPathRaw

These are additions only. Existing fields and other generators' output are unchanged.

kotlin-spring templates now use these values for:

  • annotations (@Operation, @ApiResponse, @Parameter, @Schema, @RequestMapping, security requirements, swagger1 Authorization)
  • path and base-path constants
  • @JsonProperty names
  • enum values
  • discriminator / type-info annotations
  • the SpringDocConfiguration metadata
  • KDoc

KotlinSpringServerCodegen:

  • String and URI defaults and discriminator default values are written as escaped Kotlin literals.
  • Spring's form binding does not apply OpenAPI defaults to form parameters. The generator now logs a warning and the KDoc says "OpenAPI schema default to …" instead of claiming a default is applied.

Samples: the kotlin-spring samples are regenerated. Most of the diff replaces description = """...""" with standard Kotlin string literals. KDoc entities are normalized as well.

Testing

  • New tests in KotlinSpringServerCodegenTest use the new 3_0/spring/escaping-regressions.yaml and 3_0/spring/kotlin-escaping-regressions.yaml fixtures. They cover paths, context paths, OAuth names and scopes, SpringDoc metadata, URI and decimal defaults, discriminators, enum values, form-parameter defaults and KDoc, across the controller, interface-only, delegate, service, swagger1 and declarative-http-interface variants.
  • New SourceStringEscaperTest.
  • KotlinSpringServerCodegenTest, SourceStringEscaperTest, DefaultCodegenTest and DefaultGeneratorTest all pass (555 tests).

PR checklist

  • Read the contribution guidelines.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in WSL)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

Summary by cubic

Updates the Kotlin Spring generator to escape generated values per target context, fixing compiled code when quotes, backslashes, dollar signs, or doc-comment delimiters appear in OpenAPI values.

Values now stay unescaped in the code model and are encoded where rendered via SourceStringEscaper (kotlinStringLiteral, kotlinStringContent, kotlinDocText lambdas), covering annotations, path constants, enum values, JSON property names, and KDoc. String/URI defaults and discriminator values are written as Kotlin literals, and KDoc/@Operation output no longer uses triple-quoted strings. Multi-line property examples keep their line breaks and control characters instead of being stripped.

Bug Fixes

  • Keeps date/date-time parameter defaults unset so format: date defaults don't render as timezone-shifted date-times that Spring cannot bind.
  • Documents that Spring form binding does not apply OpenAPI defaults to form parameters.
  • Adds regression fixtures covering Java and Kotlin escaping cases, and a SourceStringEscaperTest.

Written for commit e557ee0. Summary will update on new commits.

View guided diff

Port the Kotlin Spring part of the values-escaping work onto current master.

- Add SourceStringEscaper with Kotlin string-literal/content and doc-comment
  encoders, exposed to kotlin-spring templates as the kotlinStringLiteral,
  kotlinStringContent and kotlinDocText lambdas.
- Carry unescaped values alongside escaped ones (operation path/summary,
  response message, body description, enum valueRaw, scope descriptionRaw,
  raw default values, and *Raw app/contact/license/context-path metadata) so
  templates encode each value once for its target context.
- Rewrite kotlin-spring templates to use them for annotations, constants,
  enum values, JSON property names and KDoc.
- Escape string/URI defaults and discriminator values as Kotlin literals.
- Warn and document that OpenAPI defaults on form parameters are not applied
  by Spring binding.
- Regenerate kotlin-spring samples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Picazsoo Picazsoo changed the title fix(kotlin-spring): escape generated values by source context [kotlin-spring] Escape generated values by source context Nov 21, 2026
@Picazsoo
Picazsoo marked this pull request as ready for review November 21, 2026 23:09

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 89 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java:5908">
P2: Date form parameters can receive an invalid generated default in their `@Parameter` schema because this path copies the materialized `Date` text before setting `isDate` and never applies the date normalization used by `fromParameter`. Normalize the raw default after date classification, or share the existing date-default handling.</violation>

<violation number="2" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java:7299">
P3: `valueRaw` is populated from the transformed enum value, so callers that sanitize `values` still expose sanitized text as the raw template value. Set `ENUM_VALUE_RAW` from `rawValues.get(i)` while keeping the generated `value` based on `values.get(i)`.</violation>
</file>

<file name="modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java">

<violation number="1" location="modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java:4755">
P2: These assertions use raw Java Unicode escapes, so Java rewrites `\u002a` to `*` before the test runs and the expected KDoc/path text no longer matches generated output. Escape the backslash as `\\u002a` in all three assertions (lines 4755, 4756, and 4762).</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic


codegenParameter.hasDefaultValue = codegenProperty != null && codegenProperty.hasDefaultValue;
codegenParameter.rawDefaultValue = codegenProperty == null ? null : codegenProperty.rawDefaultValue;
codegenParameter.rawDefaultValueText = codegenProperty == null ? null : codegenProperty.rawDefaultValueText;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Date form parameters can receive an invalid generated default in their @Parameter schema because this path copies the materialized Date text before setting isDate and never applies the date normalization used by fromParameter. Normalize the raw default after date classification, or share the existing date-default handling.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java, line 5908:

<comment>Date form parameters can receive an invalid generated default in their `@Parameter` schema because this path copies the materialized `Date` text before setting `isDate` and never applies the date normalization used by `fromParameter`. Normalize the raw default after date classification, or share the existing date-default handling.</comment>

<file context>
@@ -5892,11 +5903,38 @@ public CodegenParameter fromParameter(Parameter parameter, Set<String> imports)
-
+        codegenParameter.hasDefaultValue = codegenProperty != null && codegenProperty.hasDefaultValue;
+        codegenParameter.rawDefaultValue = codegenProperty == null ? null : codegenProperty.rawDefaultValue;
+        codegenParameter.rawDefaultValueText = codegenProperty == null ? null : codegenProperty.rawDefaultValueText;
+        // swagger-parser materializes date defaults as Date, losing the lexical
+        // OpenAPI value. Preserve the same date form emitted for parameter binding.
</file context>

Map.of(SERVICE_INTERFACE, true));
String serviceSource = Files.readString(files.get("EscapedApiService.kt").toPath());

Assert.assertTrue(serviceSource.contains("External docs &amp;amp; &lt;literal&gt; *&#47; &#92;u002a/"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: These assertions use raw Java Unicode escapes, so Java rewrites \u002a to * before the test runs and the expected KDoc/path text no longer matches generated output. Escape the backslash as \\u002a in all three assertions (lines 4755, 4756, and 4762).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java, line 4755:

<comment>These assertions use raw Java Unicode escapes, so Java rewrites `\u002a` to `*` before the test runs and the expected KDoc/path text no longer matches generated output. Escape the backslash as `\\u002a` in all three assertions (lines 4755, 4756, and 4762).</comment>

<file context>
@@ -4721,6 +4721,109 @@ public void springBootEscapesQuotedMediaTypes() throws IOException {
+                Map.of(SERVICE_INTERFACE, true));
+        String serviceSource = Files.readString(files.get("EscapedApiService.kt").toPath());
+
+        Assert.assertTrue(serviceSource.contains("External docs &amp;amp; &lt;literal&gt; *&#47; &#92;u002a/"));
+        Assert.assertFalse(serviceSource.contains("Operation docs *&#47; &#92;u002a/\n     * @see"));
+
</file context>

enumVar.enumVar(finalEnumName, toEnumValue(String.valueOf(value), dataType), isDataTypeString(dataType));
String rawEnumValue = String.valueOf(value);
enumVar.enumVar(finalEnumName, toEnumValue(rawEnumValue, dataType), isDataTypeString(dataType));
enumVar.setEnumValueRaw(rawEnumValue);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: valueRaw is populated from the transformed enum value, so callers that sanitize values still expose sanitized text as the raw template value. Set ENUM_VALUE_RAW from rawValues.get(i) while keeping the generated value based on values.get(i).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java, line 7299:

<comment>`valueRaw` is populated from the transformed enum value, so callers that sanitize `values` still expose sanitized text as the raw template value. Set `ENUM_VALUE_RAW` from `rawValues.get(i)` while keeping the generated `value` based on `values.get(i)`.</comment>

<file context>
@@ -7256,7 +7294,9 @@ protected List<EnumVarMap> buildEnumVars(List<Object> values, String dataType, L
-            enumVar.enumVar(finalEnumName, toEnumValue(String.valueOf(value), dataType), isDataTypeString(dataType));
+            String rawEnumValue = String.valueOf(value);
+            enumVar.enumVar(finalEnumName, toEnumValue(rawEnumValue, dataType), isDataTypeString(dataType));
+            enumVar.setEnumValueRaw(rawEnumValue);
             enumVar.setEnumRawValue(rawValues.get(i));
             // TODO: add isNumeric
</file context>

Picazsoo and others added 4 commits November 22, 2026 00:22
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
swagger-parser materializes `format: date` defaults as java.util.Date at
local midnight, so the raw default snapshot rendered a timezone-shifted
date-time (e.g. "2024-03-04T23:00:00.000+00:00" for "2024-03-05") into
@RequestParam/@parameter defaults and KDoc. Spring could not bind that to
LocalDate. Keep the generator's previous behavior of not emitting date and
date-time parameter defaults, including for form parameters.

Also include unescapedPath and unescapedSummary in CodegenOperation's
equals/hashCode/toString alongside unescapedNotes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Render @Schema/@ApiModelProperty example values through the Kotlin string
literal escaper instead of stripping line breaks, so multi-line examples
keep their value and control characters are escaped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 11 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java:1213">
P2: This leaves date/date-time defaults enabled for cookie parameters: clearing `hasDefaultValue` selects the template's fallback branch, which still emits the non-null `defaultValue`. Clear `parameter.defaultValue` as well so temporal parameter defaults are consistently omitted.</violation>
</file>

<file name="modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java">

<violation number="1" location="modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java:4835">
P2: This form regression check does not prove that `day` and `at` were generated. Add positive assertions for their `@RequestParam` declarations before checking that their defaults are absent.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

*/
private static void clearTemporalDefault(CodegenParameter parameter) {
if (parameter.isDate || parameter.isDateTime) {
parameter.hasDefaultValue = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This leaves date/date-time defaults enabled for cookie parameters: clearing hasDefaultValue selects the template's fallback branch, which still emits the non-null defaultValue. Clear parameter.defaultValue as well so temporal parameter defaults are consistently omitted.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java, line 1213:

<comment>This leaves date/date-time defaults enabled for cookie parameters: clearing `hasDefaultValue` selects the template's fallback branch, which still emits the non-null `defaultValue`. Clear `parameter.defaultValue` as well so temporal parameter defaults are consistently omitted.</comment>

<file context>
@@ -1196,6 +1197,25 @@ public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set
+     */
+    private static void clearTemporalDefault(CodegenParameter parameter) {
+        if (parameter.isDate || parameter.isDateTime) {
+            parameter.hasDefaultValue = false;
+            parameter.rawDefaultValue = null;
+            parameter.rawDefaultValueText = null;
</file context>
Suggested change
parameter.hasDefaultValue = false;
parameter.hasDefaultValue = false;
parameter.defaultValue = null;

"@RequestParam(value = \"at\", required = false)",
"@RequestParam(value = \"label\", required = false, defaultValue = \"plain\")");
assertFileNotContains(controller, "2024-03-0");
assertFileNotContains(formController, "2024-03-0");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This form regression check does not prove that day and at were generated. Add positive assertions for their @RequestParam declarations before checking that their defaults are absent.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java, line 4835:

<comment>This form regression check does not prove that `day` and `at` were generated. Add positive assertions for their `@RequestParam` declarations before checking that their defaults are absent.</comment>

<file context>
@@ -4817,6 +4817,45 @@ public void kotlinSourceLiteralsEscapePathsContextPathsAndOAuthAnnotations() thr
+                "@RequestParam(value = \"at\", required = false)",
+                "@RequestParam(value = \"label\", required = false, defaultValue = \"plain\")");
+        assertFileNotContains(controller, "2024-03-0");
+        assertFileNotContains(formController, "2024-03-0");
+        assertFileNotContains(service, "2024-03-0");
+        assertFileNotContains(formService, "2024-03-0");
</file context>
Suggested change
assertFileNotContains(formController, "2024-03-0");
assertFileContains(formController,
"@RequestParam(value = \"day\", required = false)",
"@RequestParam(value = \"at\", required = false)");
assertFileNotContains(formController, "2024-03-0");

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant