Skip to content

Commit 3efaba1

Browse files
fix(typescript-fetch): encode basic auth credentials as UTF-8 (#25951)
* fix(typescript-fetch): encode basic auth credentials as UTF-8 * fix(typescript-fetch): support indexed access checks in auth encoder * chore(samples): regenerate typescript-fetch clients * fix(typescript-fetch): add UTF-8 fallback without TextEncoder * chore(samples): regenerate typescript-fetch auth fallback
1 parent df448aa commit 3efaba1

32 files changed

Lines changed: 638 additions & 4 deletions

File tree

‎modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ export class {{classname}} extends runtime.BaseAPI {
293293
{{#isBasic}}
294294
{{#isBasicBasic}}
295295
if (this.configuration && (this.configuration.username !== undefined || this.configuration.password !== undefined)) {
296-
headerParameters["Authorization"] = "Basic " + btoa((this.configuration.username || "") + ":" + (this.configuration.password || ""));
296+
headerParameters["Authorization"] = "Basic " + runtime.encodeBasicAuth(this.configuration.username || "", this.configuration.password || "");
297297
}
298298
{{/isBasicBasic}}
299299
{{#isBasicBearer}}

‎modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,28 @@ export function jsonStringifyForHeader(value: unknown): string | undefined {
1313
{{/hasJsonContentModelHeader}}
1414
export const BASE_PATH: string = "{{{basePath}}}".replace(/\/+$/, "");
1515

16+
function encodeUtf8Binary(value: string): string {
17+
if (typeof TextEncoder !== "undefined") {
18+
const bytes = new TextEncoder().encode(value);
19+
let binary = "";
20+
for (let i = 0; i < bytes.length; i++) {
21+
binary += String.fromCharCode(bytes[i]!);
22+
}
23+
return binary;
24+
}
25+
26+
// Replace unpaired surrogates as TextEncoder does before percent-encoding.
27+
const normalizedValue = value.replace(
28+
/[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g,
29+
chars => chars.length === 1 ? "\ufffd" : chars
30+
);
31+
return unescape(encodeURIComponent(normalizedValue));
32+
}
33+
34+
export function encodeBasicAuth(username: string, password: string): string {
35+
return btoa(encodeUtf8Binary(username + ":" + password));
36+
}
37+
1638
export interface ConfigurationParameters {
1739
basePath?: string; // override base path
1840
fetchApi?: FetchAPI; // override for fetch implementation

‎modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientCodegenTest.java‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,40 @@ public void testJsonContentHeaderRuntime(boolean withoutRuntimeChecks) throws IO
194194
}
195195
}
196196

197+
@Test
198+
public void testBasicAuthUsesUtf8Base64Encoding() throws IOException, InterruptedException {
199+
try {
200+
if (new ProcessBuilder("node", "-e", "if (typeof btoa === 'undefined' || typeof TextEncoder === 'undefined') process.exit(1)").start().waitFor() != 0
201+
|| new ProcessBuilder("tsc", "--version").start().waitFor() != 0) {
202+
throw new SkipException("Node.js with btoa and TextEncoder, and TypeScript compiler are required");
203+
}
204+
} catch (IOException ignored) {
205+
throw new SkipException("Node.js with btoa and TextEncoder, and TypeScript compiler are required");
206+
}
207+
File output = Files.createTempDirectory("typescript-fetch-basic-auth-runtime").toFile();
208+
try {
209+
CodegenConfigurator configurator = new CodegenConfigurator()
210+
.setGeneratorName("typescript-fetch")
211+
.setInputSpec("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml")
212+
.setOutputDir(output.getAbsolutePath());
213+
new DefaultGenerator().opts(configurator.toClientOptInput()).generate();
214+
TestUtils.assertFileContains(output.toPath().resolve("apis/FakeApi.ts"),
215+
"headerParameters[\"Authorization\"] = \"Basic \" + runtime.encodeBasicAuth(this.configuration.username || \"\", this.configuration.password || \"\");");
216+
Process compile = new ProcessBuilder("tsc", "--target", "ES2018", "--module", "commonjs",
217+
"--lib", "ES2018,DOM", "--strict", "--noUncheckedIndexedAccess", "--outDir", "compiled", "runtime.ts")
218+
.directory(output).redirectErrorStream(true).start();
219+
String compileOutput = new String(compile.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
220+
Assert.assertEquals(compile.waitFor(), 0, compileOutput);
221+
Process test = new ProcessBuilder("node", Paths.get("src/test/resources/3_0/typescript-fetch/basic-auth-runtime.cjs")
222+
.toAbsolutePath().toString(), output.toPath().resolve("compiled").toString())
223+
.redirectErrorStream(true).start();
224+
String testOutput = new String(test.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
225+
Assert.assertEquals(test.waitFor(), 0, testOutput);
226+
} finally {
227+
org.apache.commons.io.FileUtils.deleteDirectory(output);
228+
}
229+
}
230+
197231
@Test
198232
public void testJsonContentHeadersWithoutRuntimeChecks() throws IOException {
199233
File output = Files.createTempDirectory("typescript-fetch-json-header").toFile();
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const assert = require('assert');
2+
const path = require('path');
3+
const { encodeBasicAuth } = require(path.join(process.argv[2], 'runtime.js'));
4+
5+
const cases = [
6+
['ascii', 'password', 'YXNjaWk6cGFzc3dvcmQ='],
7+
['\u00c5\u00c4\u00d6-test', 'password\u00c5\u00c4\u00d6', 'w4XDhMOWLXRlc3Q6cGFzc3dvcmTDhcOEw5Y='],
8+
['\u0142', '\u20ac', 'xYI64oKs'],
9+
['\ud83d\ude00', 'x', '8J+YgDp4'],
10+
['\ud800', 'x', '77+9Ong='],
11+
['x', '\udc00', 'eDrvv70=']
12+
];
13+
14+
function assertEncodings(encoder) {
15+
for (const [username, password, expected] of cases) {
16+
assert.strictEqual(encodeBasicAuth(username, password), expected, encoder);
17+
}
18+
}
19+
20+
assertEncodings('TextEncoder');
21+
const textEncoder = Object.getOwnPropertyDescriptor(globalThis, 'TextEncoder');
22+
Object.defineProperty(globalThis, 'TextEncoder', { ...textEncoder, value: undefined });
23+
try {
24+
assertEncodings('UTF-8 fallback');
25+
} finally {
26+
Object.defineProperty(globalThis, 'TextEncoder', textEncoder);
27+
}
28+
console.log('Basic auth runtime checks passed');

‎samples/client/others/typescript-fetch/additional-properties-in-multipart-issue/runtime.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,28 @@
1414

1515
export const BASE_PATH: string = "http://localhost:8080".replace(/\/+$/, "");
1616

17+
function encodeUtf8Binary(value: string): string {
18+
if (typeof TextEncoder !== "undefined") {
19+
const bytes = new TextEncoder().encode(value);
20+
let binary = "";
21+
for (let i = 0; i < bytes.length; i++) {
22+
binary += String.fromCharCode(bytes[i]!);
23+
}
24+
return binary;
25+
}
26+
27+
// Replace unpaired surrogates as TextEncoder does before percent-encoding.
28+
const normalizedValue = value.replace(
29+
/[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g,
30+
chars => chars.length === 1 ? "\ufffd" : chars
31+
);
32+
return unescape(encodeURIComponent(normalizedValue));
33+
}
34+
35+
export function encodeBasicAuth(username: string, password: string): string {
36+
return btoa(encodeUtf8Binary(username + ":" + password));
37+
}
38+
1739
export interface ConfigurationParameters {
1840
basePath?: string; // override base path
1941
fetchApi?: FetchAPI; // override for fetch implementation

‎samples/client/others/typescript-fetch/infinite-recursion-issue/runtime.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,28 @@
1414

1515
export const BASE_PATH: string = "http://localhost:8080".replace(/\/+$/, "");
1616

17+
function encodeUtf8Binary(value: string): string {
18+
if (typeof TextEncoder !== "undefined") {
19+
const bytes = new TextEncoder().encode(value);
20+
let binary = "";
21+
for (let i = 0; i < bytes.length; i++) {
22+
binary += String.fromCharCode(bytes[i]!);
23+
}
24+
return binary;
25+
}
26+
27+
// Replace unpaired surrogates as TextEncoder does before percent-encoding.
28+
const normalizedValue = value.replace(
29+
/[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g,
30+
chars => chars.length === 1 ? "\ufffd" : chars
31+
);
32+
return unescape(encodeURIComponent(normalizedValue));
33+
}
34+
35+
export function encodeBasicAuth(username: string, password: string): string {
36+
return btoa(encodeUtf8Binary(username + ":" + password));
37+
}
38+
1739
export interface ConfigurationParameters {
1840
basePath?: string; // override base path
1941
fetchApi?: FetchAPI; // override for fetch implementation

‎samples/client/others/typescript-fetch/multipart-file-array/runtime.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,28 @@
1414

1515
export const BASE_PATH: string = "http://localhost".replace(/\/+$/, "");
1616

17+
function encodeUtf8Binary(value: string): string {
18+
if (typeof TextEncoder !== "undefined") {
19+
const bytes = new TextEncoder().encode(value);
20+
let binary = "";
21+
for (let i = 0; i < bytes.length; i++) {
22+
binary += String.fromCharCode(bytes[i]!);
23+
}
24+
return binary;
25+
}
26+
27+
// Replace unpaired surrogates as TextEncoder does before percent-encoding.
28+
const normalizedValue = value.replace(
29+
/[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g,
30+
chars => chars.length === 1 ? "\ufffd" : chars
31+
);
32+
return unescape(encodeURIComponent(normalizedValue));
33+
}
34+
35+
export function encodeBasicAuth(username: string, password: string): string {
36+
return btoa(encodeUtf8Binary(username + ":" + password));
37+
}
38+
1739
export interface ConfigurationParameters {
1840
basePath?: string; // override base path
1941
fetchApi?: FetchAPI; // override for fetch implementation

‎samples/client/others/typescript-fetch/self-import-issue/runtime.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,28 @@
1414

1515
export const BASE_PATH: string = "http://localhost".replace(/\/+$/, "");
1616

17+
function encodeUtf8Binary(value: string): string {
18+
if (typeof TextEncoder !== "undefined") {
19+
const bytes = new TextEncoder().encode(value);
20+
let binary = "";
21+
for (let i = 0; i < bytes.length; i++) {
22+
binary += String.fromCharCode(bytes[i]!);
23+
}
24+
return binary;
25+
}
26+
27+
// Replace unpaired surrogates as TextEncoder does before percent-encoding.
28+
const normalizedValue = value.replace(
29+
/[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g,
30+
chars => chars.length === 1 ? "\ufffd" : chars
31+
);
32+
return unescape(encodeURIComponent(normalizedValue));
33+
}
34+
35+
export function encodeBasicAuth(username: string, password: string): string {
36+
return btoa(encodeUtf8Binary(username + ":" + password));
37+
}
38+
1739
export interface ConfigurationParameters {
1840
basePath?: string; // override base path
1941
fetchApi?: FetchAPI; // override for fetch implementation

‎samples/client/petstore/typescript-fetch/builds/allOf-nullable/runtime.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,28 @@
1414

1515
export const BASE_PATH: string = "http://api.example.xyz/v1".replace(/\/+$/, "");
1616

17+
function encodeUtf8Binary(value: string): string {
18+
if (typeof TextEncoder !== "undefined") {
19+
const bytes = new TextEncoder().encode(value);
20+
let binary = "";
21+
for (let i = 0; i < bytes.length; i++) {
22+
binary += String.fromCharCode(bytes[i]!);
23+
}
24+
return binary;
25+
}
26+
27+
// Replace unpaired surrogates as TextEncoder does before percent-encoding.
28+
const normalizedValue = value.replace(
29+
/[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g,
30+
chars => chars.length === 1 ? "\ufffd" : chars
31+
);
32+
return unescape(encodeURIComponent(normalizedValue));
33+
}
34+
35+
export function encodeBasicAuth(username: string, password: string): string {
36+
return btoa(encodeUtf8Binary(username + ":" + password));
37+
}
38+
1739
export interface ConfigurationParameters {
1840
basePath?: string; // override base path
1941
fetchApi?: FetchAPI; // override for fetch implementation

‎samples/client/petstore/typescript-fetch/builds/allOf-readonly/runtime.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,28 @@
1414

1515
export const BASE_PATH: string = "http://api.example.xyz/v1".replace(/\/+$/, "");
1616

17+
function encodeUtf8Binary(value: string): string {
18+
if (typeof TextEncoder !== "undefined") {
19+
const bytes = new TextEncoder().encode(value);
20+
let binary = "";
21+
for (let i = 0; i < bytes.length; i++) {
22+
binary += String.fromCharCode(bytes[i]!);
23+
}
24+
return binary;
25+
}
26+
27+
// Replace unpaired surrogates as TextEncoder does before percent-encoding.
28+
const normalizedValue = value.replace(
29+
/[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g,
30+
chars => chars.length === 1 ? "\ufffd" : chars
31+
);
32+
return unescape(encodeURIComponent(normalizedValue));
33+
}
34+
35+
export function encodeBasicAuth(username: string, password: string): string {
36+
return btoa(encodeUtf8Binary(username + ":" + password));
37+
}
38+
1739
export interface ConfigurationParameters {
1840
basePath?: string; // override base path
1941
fetchApi?: FetchAPI; // override for fetch implementation

0 commit comments

Comments
 (0)