Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix dangerous destructuration in typescript-nestjs services #20157

Merged
merged 5 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions bin/configs/typescript-nestjs-reserved-param-names.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
generatorName: typescript-nestjs
outputDir: samples/client/petstore/typescript-nestjs/builds/reservedParamNames
inputSpec: modules/openapi-generator/src/test/resources/3_0/typescript-nestjs/reserved-param-names.yaml
templateDir: modules/openapi-generator/src/main/resources/typescript-nestjs
additionalProperties:
"useSingleRequestParameter" : true
2 changes: 2 additions & 0 deletions docs/generators/typescript-nestjs.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>float</li>
<li>for</li>
<li>formParams</li>
<li>from</li>
<li>function</li>
<li>goto</li>
<li>headerParams</li>
<li>headers</li>
<li>if</li>
<li>implements</li>
<li>import</li>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
package org.openapitools.codegen.languages;

import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import lombok.Getter;
import lombok.Setter;
import org.openapitools.codegen.*;
Expand Down Expand Up @@ -88,6 +90,8 @@ public TypeScriptNestjsClientCodegen() {
apiPackage = "api";
modelPackage = "model";

reservedWords.addAll(Arrays.asList("from", "headers"));

this.cliOptions.add(new CliOption(NPM_REPOSITORY,
"Use this property to set an url your private npmRepo in the package.json"));
this.cliOptions.add(CliOption.newBoolean(WITH_INTERFACES,
Expand Down Expand Up @@ -265,6 +269,34 @@ private boolean isLanguageGenericType(String type) {
return false;
}

@Override
public List<CodegenParameter> fromRequestBodyToFormParameters(RequestBody body, Set<String> imports) {
Copy link
Member

Choose a reason for hiding this comment

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

please separate this change of parameters into a separate PR. also, is there an easier way than to extends CodegenParameter?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was inpired by the typescript-fetch generator. If you know a better way to do it I can make the changes

Copy link
Member

Choose a reason for hiding this comment

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

ah i see. the risk is just that whenever new properties are added to the CodegenParameter, we will probably forget to add them here. can this be automated/avoided somehow?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I see uses of param.vendorExtensions in others generators:

Do you think it would be a better approach as it doesn't require to extend CodegenParameter ?

Copy link
Member

Choose a reason for hiding this comment

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

oh that sounds compelling, yes please try if that works!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done ! It works as well 😃

Copy link
Member

Choose a reason for hiding this comment

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

thanks!
are you motivated to also do that for the typescript-fetch generator in a separate PR?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You mean using vendorExtensions instead of extending CodegenParameter ? Or keeping original names in requestParameters interfaces ? Or both maybe ? 😃

List<CodegenParameter> superParams = super.fromRequestBodyToFormParameters(body, imports);
List<CodegenParameter> extendedParams = new ArrayList<CodegenParameter>();
for (CodegenParameter cp : superParams) {
extendedParams.add(new ExtendedCodegenParameter(cp));
}
return extendedParams;
}

@Override
public ExtendedCodegenParameter fromParameter(Parameter parameter, Set<String> imports) {
CodegenParameter cp = super.fromParameter(parameter, imports);
return new ExtendedCodegenParameter(cp);
}

@Override
public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set<String> imports) {
CodegenParameter cp = super.fromFormProperty(name, propertySchema, imports);
return new ExtendedCodegenParameter(cp);
}

@Override
public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) {
CodegenParameter cp = super.fromRequestBody(body, imports, bodyParameterName);
return new ExtendedCodegenParameter(cp);
}

@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
Expand Down Expand Up @@ -327,6 +359,12 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap operations, L

// Overwrite path to TypeScript template string, after applying everything we just did.
op.path = pathBuffer.toString();

for (CodegenParameter cpParam : op.allParams) {
ExtendedCodegenParameter param = (ExtendedCodegenParameter) cpParam;

param.hasSanitizedName = !param.baseName.equals(param.paramName);
}
}

operations.put("hasSomeFormParams", hasSomeFormParams);
Expand Down Expand Up @@ -482,6 +520,126 @@ public String removeModelPrefixSuffix(String name) {
return result;
}

public class ExtendedCodegenParameter extends CodegenParameter {
public boolean hasSanitizedName = false;

public ExtendedCodegenParameter(CodegenParameter cp) {
super();

this.isFormParam = cp.isFormParam;
this.isQueryParam = cp.isQueryParam;
this.isPathParam = cp.isPathParam;
this.isHeaderParam = cp.isHeaderParam;
this.isCookieParam = cp.isCookieParam;
this.isBodyParam = cp.isBodyParam;
this.isContainer = cp.isContainer;
this.isCollectionFormatMulti = cp.isCollectionFormatMulti;
this.isPrimitiveType = cp.isPrimitiveType;
this.isModel = cp.isModel;
this.isExplode = cp.isExplode;
this.baseName = cp.baseName;
this.paramName = cp.paramName;
this.dataType = cp.dataType;
this.datatypeWithEnum = cp.datatypeWithEnum;
this.dataFormat = cp.dataFormat;
this.contentType = cp.contentType;
this.collectionFormat = cp.collectionFormat;
this.description = cp.description;
this.unescapedDescription = cp.unescapedDescription;
this.baseType = cp.baseType;
this.defaultValue = cp.defaultValue;
this.enumName = cp.enumName;
this.style = cp.style;
this.nameInLowerCase = cp.nameInLowerCase;
this.example = cp.example;
this.jsonSchema = cp.jsonSchema;
this.isString = cp.isString;
this.isNumeric = cp.isNumeric;
this.isInteger = cp.isInteger;
this.isLong = cp.isLong;
this.isNumber = cp.isNumber;
this.isFloat = cp.isFloat;
this.isDouble = cp.isDouble;
this.isDecimal = cp.isDecimal;
this.isByteArray = cp.isByteArray;
this.isBinary = cp.isBinary;
this.isBoolean = cp.isBoolean;
this.isDate = cp.isDate;
this.isDateTime = cp.isDateTime;
this.isUuid = cp.isUuid;
this.isUri = cp.isUri;
this.isEmail = cp.isEmail;
this.isFreeFormObject = cp.isFreeFormObject;
this.isAnyType = cp.isAnyType;
this.isArray = cp.isArray;
this.isMap = cp.isMap;
this.isFile = cp.isFile;
this.isEnum = cp.isEnum;
this.isEnumRef = cp.isEnumRef;
this._enum = cp._enum;
this.allowableValues = cp.allowableValues;
this.items = cp.items;
this.additionalProperties = cp.additionalProperties;
this.vars = cp.vars;
this.requiredVars = cp.requiredVars;
this.mostInnerItems = cp.mostInnerItems;
this.vendorExtensions = cp.vendorExtensions;
this.hasValidation = cp.hasValidation;
this.isNullable = cp.isNullable;
this.required = cp.required;
this.maximum = cp.maximum;
this.exclusiveMaximum = cp.exclusiveMaximum;
this.minimum = cp.minimum;
this.exclusiveMinimum = cp.exclusiveMinimum;
this.maxLength = cp.maxLength;
this.minLength = cp.minLength;
this.pattern = cp.pattern;
this.maxItems = cp.maxItems;
this.minItems = cp.minItems;
this.uniqueItems = cp.uniqueItems;
this.multipleOf = cp.multipleOf;
this.setHasVars(cp.getHasVars());
this.setHasRequired(cp.getHasRequired());
this.setMaxProperties(cp.getMaxProperties());
this.setMinProperties(cp.getMinProperties());
}

@Override
public ExtendedCodegenParameter copy() {
CodegenParameter superCopy = super.copy();
ExtendedCodegenParameter output = new ExtendedCodegenParameter(superCopy);
output.hasSanitizedName = this.hasSanitizedName;
return output;
}

@Override
public boolean equals(Object o) {
if (o == null)
return false;

if (this.getClass() != o.getClass())
return false;

boolean result = super.equals(o);
ExtendedCodegenParameter that = (ExtendedCodegenParameter) o;
return result && hasSanitizedName == that.hasSanitizedName;
}

@Override
public int hashCode() {
int superHash = super.hashCode();
return Objects.hash(superHash, hasSanitizedName);
}

@Override
public String toString() {
String superString = super.toString();
final StringBuilder sb = new StringBuilder(superString);
sb.append(", hasSanitizedName=").append(hasSanitizedName);
return sb.toString();
}
}

/**
* Validates that the given string value only contains '-', '.' and alpha numeric characters.
* Throws an IllegalArgumentException, if the string contains any other characters.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export interface {{classname}}{{operationIdCamelCase}}Request {
* @type {{=<% %>=}}{<%&dataType%>}<%={{ }}=%>
* @memberof {{classname}}{{operationIdCamelCase}}
*/
readonly {{paramName}}{{^required}}?{{/required}}: {{{dataType}}}
readonly {{#hasSanitizedName}}'{{{baseName}}}'{{/hasSanitizedName}}{{^hasSanitizedName}}{{{paramName}}}{{/hasSanitizedName}}{{^required}}?{{/required}}: {{{dataType}}}
{{^-last}}

{{/-last}}
Expand Down Expand Up @@ -106,7 +106,7 @@ export class {{classname}} {
{{#useSingleRequestParameter}}
const {
{{#allParams}}
{{paramName}},
{{#hasSanitizedName}}'{{{baseName}}}': {{/hasSanitizedName}}{{paramName}},
Copy link
Member

Choose a reason for hiding this comment

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

this is not an object, but destructuring the request parameters, please revert this change

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I know, it's to keep the request parameter with the original names while renaming the params in this method to avoid conflicts with existing properties.
In the end it looks like this :

const {
    notReserved,
    'from': _from,
    'headers': _headers,
} = requestParameters;

Copy link
Member

Choose a reason for hiding this comment

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

ah i see, i didnt know this is possible

{{/allParams}}
} = requestParameters;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ export interface {{classname}}{{#allParents}}{{#-first}} extends {{/-first}}{{{.
* {{{.}}}
*/
{{/description}}
{{#isReadOnly}}readonly {{/isReadOnly}}{{{name}}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}} | null{{/isNullable}};
{{#isReadOnly}}readonly {{/isReadOnly}}{{#hasSanitizedName}}'{{{baseName}}}'{{/hasSanitizedName}}{{^hasSanitizedName}}{{{name}}}{{/hasSanitizedName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}} | null{{/isNullable}};
{{/vars}}
}{{>modelGenericEnums}}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ export interface {{classname}} { {{>modelGenericAdditionalProperties}}
* {{{.}}}
*/
{{/description}}
{{name}}{{^required}}?{{/required}}: {{#discriminatorValue}}'{{.}}'{{/discriminatorValue}}{{^discriminatorValue}}{{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{/discriminatorValue}}{{#isNullable}} | null{{/isNullable}};
{{#hasSanitizedName}}'{{{baseName}}}'{{/hasSanitizedName}}{{^hasSanitizedName}}{{{name}}}{{/hasSanitizedName}}{{^required}}?{{/required}}: {{#discriminatorValue}}'{{.}}'{{/discriminatorValue}}{{^discriminatorValue}}{{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{/discriminatorValue}}{{#isNullable}} | null{{/isNullable}};
{{/allVars}}
}
{{>modelGenericEnums}}
{{/parent}}
{{^parent}}
{{>modelGeneric}}
{{/parent}}
{{/discriminator}}
{{/discriminator}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
openapi: 3.0.0
info:
description: Test reserved param names
version: 1.0.0
title: Reserved param names
paths:
/test:
post:
security:
- bearerAuth: []
summary: Test reserved param names
description: ''
operationId: testReservedParamNames
parameters:
- name: notReserved
in: query
description: Should not be treated as a reserved param name
required: true
schema:
type: string
- name: from
in: query
description: Might conflict with rxjs import
required: true
schema:
type: string
- name: headers
in: header
description: Might conflict with headers const
required: true
schema:
type: string
responses:
'200':
description: successful operation
'405':
description: Invalid input
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
wwwroot/*.js
node_modules
typings
dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator

# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.

# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs

# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux

# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux

# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.gitignore
README.md
api.module.ts
api/api.ts
api/default.service.ts
configuration.ts
git_push.sh
index.ts
model/models.ts
variables.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
7.11.0-SNAPSHOT
Loading
Loading