Skip to content

Commit

Permalink
Fix/set proxy in axios default to false to prevent double proxying (#153
Browse files Browse the repository at this point in the history
)

* chore: bump axios

* fix: set proxy in axios default config to false to prevent double proxying

* chore: update test

* chore: version bumps

* fix: update tests
  • Loading branch information
jkoenig134 authored Jun 3, 2024
1 parent 370f4b9 commit e5c2091
Show file tree
Hide file tree
Showing 8 changed files with 59 additions and 71 deletions.
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/runtime/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nmshd/runtime",
"version": "4.10.5",
"version": "4.10.6",
"description": "The enmeshed client runtime.",
"homepage": "https://enmeshed.eu",
"repository": {
Expand Down Expand Up @@ -59,7 +59,7 @@
"@nmshd/consumption": "3.11.0",
"@nmshd/content": "2.10.1",
"@nmshd/crypto": "2.0.6",
"@nmshd/transport": "2.7.4",
"@nmshd/transport": "2.7.5",
"ajv": "^8.13.0",
"ajv-errors": "^3.0.0",
"ajv-formats": "^3.0.1",
Expand Down
4 changes: 2 additions & 2 deletions packages/transport/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nmshd/transport",
"version": "2.7.4",
"version": "2.7.5",
"description": "The transport library handles backbone communication and content encryption.",
"homepage": "https://enmeshed.eu",
"repository": {
Expand Down Expand Up @@ -62,7 +62,7 @@
"@js-soft/logging-abstractions": "^1.0.1",
"@js-soft/simple-logger": "1.0.4",
"@js-soft/ts-utils": "^2.3.3",
"axios": "^1.7.1",
"axios": "^1.7.2",
"fast-json-patch": "^3.1.1",
"form-data": "^4.0.0",
"https-proxy-agent": "^7.0.4",
Expand Down
4 changes: 2 additions & 2 deletions packages/transport/src/core/backbone/AuthClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import qs from "qs";
import { CoreDate } from "../types";
import { ClientResult } from "./ClientResult";
import { PlatformParameters } from "./PlatformParameters";
import { RESTClient } from "./RESTClient";
import { RequestError } from "./RequestError";
import { RESTClient } from "./RESTClient";

export interface IAuthenticationRequest {
grantType: string;
Expand All @@ -25,7 +25,7 @@ export class AuthClient extends RESTClient {

let response;
try {
response = await this.createAxios().post<string, AxiosResponse<any>>(
response = await this.axiosInstance.post<string, AxiosResponse<any>>(
path,
qs.stringify({
client_id: params.clientId, // eslint-disable-line @typescript-eslint/naming-convention
Expand Down
59 changes: 27 additions & 32 deletions packages/transport/src/core/backbone/RESTClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export interface IRESTClientConfig {
export class RESTClient {
protected _logger: ILogger;
protected _logDirective = RESTClientLogDirective.LogAll;
protected axiosInstance: AxiosInstance;

public logRequest(): boolean {
return this._logDirective === RESTClientLogDirective.LogRequest || this._logDirective === RESTClientLogDirective.LogAll;
Expand All @@ -65,7 +66,7 @@ export class RESTClient {

public constructor(
protected readonly config: IRESTClientConfig,
protected requestConfig: AxiosRequestConfig = {}
requestConfig: AxiosRequestConfig = {}
) {
const defaults: AxiosRequestConfig = {
baseURL: config.baseUrl,
Expand All @@ -75,22 +76,22 @@ export class RESTClient {
maxContentLength: Infinity,
maxBodyLength: Infinity,
validateStatus: (status) => status < 300 || status === 400 || status === 404 || status === 500,
paramsSerializer: { dots: true, indexes: null }
paramsSerializer: { dots: true, indexes: null },
headers: this.config.platformAdditionalHeaders,
proxy: false
};

if (this.config.platformAdditionalHeaders) {
defaults.headers = _.defaultsDeep({}, defaults.headers, this.config.platformAdditionalHeaders);
}
const resultingRequestConfig = _.defaultsDeep(defaults, requestConfig);

if (typeof window === "undefined" && process.env.https_proxy) {
const httpsProxy = process.env.https_proxy;
defaults.httpsAgent = new HttpsProxyAgent(httpsProxy, this.config.httpsAgentOptions);
if (typeof window === "undefined" && (process.env.https_proxy ?? process.env.HTTPS_PROXY)) {
const httpsProxy = (process.env.https_proxy ?? process.env.HTTPS_PROXY)!;
resultingRequestConfig.httpsAgent = new HttpsProxyAgent(httpsProxy, this.config.httpsAgentOptions);
} else {
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const httpsAgent = require("https")?.Agent;

if (httpsAgent) defaults.httpsAgent = new httpsAgent(this.config.httpsAgentOptions);
if (httpsAgent) resultingRequestConfig.httpsAgent = new httpsAgent(this.config.httpsAgentOptions);
} catch (e) {
// ignore
}
Expand All @@ -100,23 +101,17 @@ export class RESTClient {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const agent = require("http")?.Agent;

if (agent) defaults.httpAgent = new agent(this.config.httpAgentOptions);
if (agent) resultingRequestConfig.httpAgent = new agent(this.config.httpAgentOptions);
} catch (e) {
// ignore
}

this.requestConfig = _.defaultsDeep(this.requestConfig, defaults);

this._logger = TransportLoggerFactory.getLogger(RESTClient);
}

protected createAxios(): AxiosInstance {
const axiosInstance = axios.create(this.requestConfig);

this.axiosInstance = axios.create(resultingRequestConfig);
if (this.config.debug) {
this.addAxiosLoggingInterceptors(axiosInstance);
this.addAxiosLoggingInterceptors(this.axiosInstance);
}
return axiosInstance;
}

private addAxiosLoggingInterceptors(axiosInstance: AxiosInstance) {
Expand Down Expand Up @@ -295,7 +290,7 @@ export class RESTClient {

public async get<T>(path: string, params: any = {}, config?: AxiosRequestConfig): Promise<ClientResult<T>> {
const id = await this.generateRequestId();
const conf = _.defaultsDeep({ params: params }, config, this.requestConfig);
const conf = _.defaultsDeep({ params: params }, config);
if (this.logRequest()) {
const anyThis = this as any;
if (anyThis._username) {
Expand All @@ -306,7 +301,7 @@ export class RESTClient {
}

try {
const response = await this.createAxios().get<PlatformResponse<T>>(path, conf);
const response = await this.axiosInstance.get<PlatformResponse<T>>(path, conf);
return this.getResult("GET", path, response, id);
} catch (e: any) {
const err = RequestError.fromAxiosError("GET", path, e, id);
Expand All @@ -317,10 +312,10 @@ export class RESTClient {

public async getPaged<T>(path: string, params: any = {}, config?: AxiosRequestConfig, progessCallback?: PaginatorPercentageCallback): Promise<ClientResult<Paginator<T>>> {
const id = await this.generateRequestId();
const conf = _.defaultsDeep({ params: params }, config, this.requestConfig);
const conf = _.defaultsDeep({ params: params }, config);

try {
const response = await this.createAxios().get<PlatformResponse<T[]>>(path, conf);
const response = await this.axiosInstance.get<PlatformResponse<T[]>>(path, conf);
return this.getPaginator(path, response, id, params, progessCallback);
} catch (e: any) {
const err = RequestError.fromAxiosError("GET", path, e, id);
Expand All @@ -331,7 +326,7 @@ export class RESTClient {

public async post<T>(path: string, data: any, params: any = {}, config?: AxiosRequestConfig): Promise<ClientResult<T>> {
const id = await this.generateRequestId();
const conf = _.defaultsDeep({ params: params }, config, this.requestConfig);
const conf = _.defaultsDeep({ params: params }, config);

if (this.logRequest()) {
const anyThis = this as any;
Expand All @@ -343,7 +338,7 @@ export class RESTClient {
}

try {
const response = await this.createAxios().post<PlatformResponse<T>>(path, data, conf);
const response = await this.axiosInstance.post<PlatformResponse<T>>(path, data, conf);
return this.getResult("POST", path, response, id);
} catch (e: any) {
const err = RequestError.fromAxiosError("POST", path, e, id);
Expand Down Expand Up @@ -377,7 +372,7 @@ export class RESTClient {
}
}

const conf = _.defaultsDeep({}, config, this.requestConfig);
const conf = _.defaultsDeep({}, config);
let sendData = formData;
if (typeof formData.getHeaders !== "undefined") {
const h = formData.getHeaders();
Expand All @@ -397,7 +392,7 @@ export class RESTClient {
}

try {
const response = await this.createAxios().post<PlatformResponse<T>>(path, sendData, conf);
const response = await this.axiosInstance.post<PlatformResponse<T>>(path, sendData, conf);
return this.getResult("POST-Upload", path, response, id);
} catch (e: any) {
const err = RequestError.fromAxiosError("POST-Upload", path, e, id);
Expand All @@ -408,7 +403,7 @@ export class RESTClient {

public async put<T>(path: string, data: any, config?: AxiosRequestConfig): Promise<ClientResult<T>> {
const id = await this.generateRequestId();
const conf = _.defaultsDeep({}, config, this.requestConfig);
const conf = _.defaultsDeep({}, config);
if (this.logRequest()) {
const anyThis = this as any;
if (anyThis._username) {
Expand All @@ -419,7 +414,7 @@ export class RESTClient {
}

try {
const response = await this.createAxios().put<PlatformResponse<T>>(path, data, conf);
const response = await this.axiosInstance.put<PlatformResponse<T>>(path, data, conf);
return this.getResult("PUT", path, response, id);
} catch (e: any) {
const err = RequestError.fromAxiosError("PUT", path, e, id);
Expand All @@ -430,7 +425,7 @@ export class RESTClient {

public async delete<T>(path: string, config?: AxiosRequestConfig): Promise<ClientResult<T>> {
const id = await this.generateRequestId();
const conf = _.defaultsDeep({}, config, this.requestConfig);
const conf = _.defaultsDeep({}, config);
if (this.logRequest()) {
const anyThis = this as any;
if (anyThis._username) {
Expand All @@ -441,7 +436,7 @@ export class RESTClient {
}

try {
const response = await this.createAxios().delete<PlatformResponse<T>>(path, conf);
const response = await this.axiosInstance.delete<PlatformResponse<T>>(path, conf);
return this.getResult("DELETE", path, response, id);
} catch (e: any) {
const err = RequestError.fromAxiosError("DELETE", path, e, id);
Expand All @@ -452,7 +447,7 @@ export class RESTClient {

public async download(path: string, config?: AxiosRequestConfig): Promise<ClientResult<Buffer | ArrayBuffer>> {
const id = await this.generateRequestId();
const conf = _.defaultsDeep({}, config, this.requestConfig);
const conf = _.defaultsDeep({}, config);
conf.responseType = "arraybuffer";
if (this.logRequest()) {
const anyThis = this as any;
Expand All @@ -464,7 +459,7 @@ export class RESTClient {
}

try {
const response = await this.createAxios().get<Buffer | ArrayBuffer>(path, conf);
const response = await this.axiosInstance.get<Buffer | ArrayBuffer>(path, conf);
const platformParameters = this.extractPlatformParameters(response);

this._logResponse(response, platformParameters, id, "GET-Download", path);
Expand Down
8 changes: 4 additions & 4 deletions packages/transport/test/core/backbone/Authentication.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,17 @@ describe("AuthenticationTest", function () {
};

if (config.baseUrl) {
const authenticatorAsAny = controller.parent.authenticator as any;
oldBaseUrl = authenticatorAsAny.authClient.requestConfig.baseURL;
authenticatorAsAny.authClient.requestConfig.baseURL = config.baseUrl;
const authenticator = controller.parent.authenticator;
oldBaseUrl = authenticator["authClient"]["axiosInstance"].defaults.baseURL!;
authenticator["authClient"]["axiosInstance"].defaults.baseURL = config.baseUrl;
}
}

function stopWrongAuth(controller: TransportController) {
const anyC = controller as any;
anyC.parent.activeDevice.getCredentials = oldGetCredentials;
if (oldBaseUrl) {
(controller.parent.authenticator as any).authClient.requestConfig.baseURL = oldBaseUrl;
controller.parent.authenticator["authClient"]["axiosInstance"].defaults.baseURL = oldBaseUrl;
oldBaseUrl = "";
}
anyC.client._logger = oldLogger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ describe("AccountController", function () {

let transport: Transport;

let account: AccountController;
let account: AccountController | undefined;

beforeAll(async function () {
connection = await TestUtil.createDatabaseConnection();
Expand All @@ -20,13 +20,13 @@ describe("AccountController", function () {
});

afterAll(async function () {
await account.close();
await account?.close();

await connection.close();
});

// eslint-disable-next-line jest/expect-expect
test("should init a second time", async function () {
await account.init();
await account!.init();
});
});
31 changes: 12 additions & 19 deletions packages/transport/test/testHelpers/RequestInterceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ export class RequestInterceptor {
return this._client;
}

private oldCreateAxios: any;

public constructor(client: RESTClient) {
this._client = client;
this._measuringRequests = true;
Expand All @@ -32,23 +30,18 @@ export class RequestInterceptor {

private injectToClient(client: RESTClient) {
const that = this;
const anyC = client as any;
this.oldCreateAxios = anyC.createAxios;
function newCreateAxios() {
const axiosInstance = that.oldCreateAxios.apply(anyC);
axiosInstance.interceptors.request.use((req: AxiosRequestConfig) => {
if (!that._measuringRequests) return req;
that._requests.push(req);
return req;
});
axiosInstance.interceptors.response.use((res: AxiosResponse) => {
if (!that._measuringRequests) return res;
that._responses.push(res);
return res;
});
return axiosInstance;
}
anyC.createAxios = newCreateAxios;

const axiosInstance = client["axiosInstance"];
axiosInstance.interceptors.request.use((req) => {
if (!that._measuringRequests) return req;
that._requests.push(req);
return req;
});
axiosInstance.interceptors.response.use((res) => {
if (!that._measuringRequests) return res;
that._responses.push(res);
return res;
});
}

public start(): this {
Expand Down

0 comments on commit e5c2091

Please sign in to comment.