2022-01-17 07:08:17 +00:00
|
|
|
const urrl = require('url');
|
2022-01-03 04:12:22 +00:00
|
|
|
import { readFileSync } from 'fs';
|
|
|
|
|
import * as tls from 'tls';
|
2022-09-19 14:57:37 +00:00
|
|
|
import {
|
|
|
|
|
QueryError,
|
|
|
|
|
QueryResult,
|
|
|
|
|
QueryService,
|
|
|
|
|
cleanSensitiveData,
|
2024-10-28 17:56:26 +00:00
|
|
|
redactHeaders,
|
2022-09-19 14:57:37 +00:00
|
|
|
User,
|
|
|
|
|
App,
|
2022-10-14 07:55:32 +00:00
|
|
|
OAuthUnauthorizedClientError,
|
2023-07-21 10:08:56 +00:00
|
|
|
getRefreshedToken,
|
|
|
|
|
checkIfContentTypeIsURLenc,
|
2023-11-17 07:06:10 +00:00
|
|
|
checkIfContentTypeIsMultipartFormData,
|
2024-11-21 15:45:18 +00:00
|
|
|
checkIfContentTypeIsJson,
|
2023-07-21 10:08:56 +00:00
|
|
|
isEmpty,
|
|
|
|
|
validateAndSetRequestOptionsBasedOnAuthType,
|
|
|
|
|
sanitizeHeaders,
|
2024-07-01 10:02:24 +00:00
|
|
|
sanitizeCookies,
|
|
|
|
|
cookiesToString,
|
2023-07-21 10:08:56 +00:00
|
|
|
sanitizeSearchParams,
|
|
|
|
|
getAuthUrl,
|
2022-09-19 14:57:37 +00:00
|
|
|
} from '@tooljet-plugins/common';
|
2023-11-17 05:17:35 +00:00
|
|
|
const FormData = require('form-data');
|
2022-04-27 09:51:30 +00:00
|
|
|
const JSON5 = require('json5');
|
2023-07-21 10:08:56 +00:00
|
|
|
import got, { HTTPError, OptionsOfTextResponseBody } from 'got';
|
2022-10-19 14:34:57 +00:00
|
|
|
import { SourceOptions } from './types';
|
2022-01-17 07:08:17 +00:00
|
|
|
|
2023-11-17 05:17:35 +00:00
|
|
|
function isFileObject(value) {
|
|
|
|
|
const keys = Object.keys(value);
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
typeof value === 'object' &&
|
|
|
|
|
keys.length > 0 &&
|
|
|
|
|
keys.includes('name') && // example.zip
|
|
|
|
|
keys.includes('type') && // application/zip
|
|
|
|
|
keys.includes('content') && // raw'ish bytes (contains new lines - \n)
|
|
|
|
|
keys.includes('dataURL') && // data url representation
|
|
|
|
|
keys.includes('base64Data') && // data in base64
|
|
|
|
|
keys.includes('filePath')
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2021-12-28 10:39:38 +00:00
|
|
|
interface RestAPIResult extends QueryResult {
|
2024-10-28 17:56:26 +00:00
|
|
|
metadata?: Array<object> | object;
|
2021-12-28 10:39:38 +00:00
|
|
|
}
|
|
|
|
|
|
2021-07-17 14:22:37 +00:00
|
|
|
export default class RestapiQueryService implements QueryService {
|
2021-07-25 10:21:24 +00:00
|
|
|
/* Body params of the source will be overridden by body params of the query */
|
2024-11-21 15:45:18 +00:00
|
|
|
body(sourceOptions: any, queryOptions: any, hasDataSource: boolean): any {
|
2022-04-27 09:51:30 +00:00
|
|
|
const bodyToggle = queryOptions['body_toggle'];
|
|
|
|
|
if (bodyToggle) {
|
2024-11-21 15:45:18 +00:00
|
|
|
// Use the generalized raw body if provided; otherwise, fall back to the legacy raw JSON body
|
|
|
|
|
const rawBody = queryOptions['raw_body'];
|
|
|
|
|
if (!rawBody) {
|
|
|
|
|
// For backward compatibility, check if JSON body was previously used
|
|
|
|
|
// FIXME: Remove the code inside this if condition and return undefined once data migration is complete
|
|
|
|
|
const jsonBody = queryOptions['json_body'];
|
|
|
|
|
if (!jsonBody) return undefined;
|
|
|
|
|
if (typeof jsonBody === 'string') return { key: 'json_body', value: JSON5.parse(jsonBody) };
|
|
|
|
|
else return { key: 'json_body', value: jsonBody };
|
|
|
|
|
} else {
|
|
|
|
|
return { key: 'raw_body', value: rawBody };
|
|
|
|
|
}
|
2022-04-27 09:51:30 +00:00
|
|
|
} else {
|
|
|
|
|
const _body = (queryOptions.body || []).filter((o) => {
|
|
|
|
|
return o.some((e) => !isEmpty(e));
|
|
|
|
|
});
|
2021-07-25 10:21:24 +00:00
|
|
|
|
2022-04-27 09:51:30 +00:00
|
|
|
if (!hasDataSource) return Object.fromEntries(_body);
|
2021-08-30 17:45:31 +00:00
|
|
|
|
2022-04-27 09:51:30 +00:00
|
|
|
const bodyParams = _body.concat(sourceOptions.body || []);
|
|
|
|
|
return Object.fromEntries(bodyParams);
|
|
|
|
|
}
|
2021-07-25 10:21:24 +00:00
|
|
|
}
|
|
|
|
|
|
2022-03-31 10:30:09 +00:00
|
|
|
isJson(str: string) {
|
|
|
|
|
try {
|
|
|
|
|
JSON.parse(str);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2022-09-19 14:57:37 +00:00
|
|
|
async run(
|
|
|
|
|
sourceOptions: any,
|
|
|
|
|
queryOptions: any,
|
|
|
|
|
dataSourceId: string,
|
|
|
|
|
dataSourceUpdatedAt: string,
|
|
|
|
|
context?: { user?: User; app?: App }
|
|
|
|
|
): Promise<RestAPIResult> {
|
2021-07-25 10:21:24 +00:00
|
|
|
/* REST API queries can be adhoc or associated with a REST API datasource */
|
|
|
|
|
const hasDataSource = dataSourceId !== undefined;
|
2024-10-28 17:56:26 +00:00
|
|
|
const headers = sanitizeHeaders(sourceOptions, queryOptions, hasDataSource);
|
|
|
|
|
const headerEntries = Object.entries(headers);
|
|
|
|
|
const isUrlEncoded = checkIfContentTypeIsURLenc(headerEntries);
|
|
|
|
|
const isMultipartFormData = checkIfContentTypeIsMultipartFormData(headerEntries);
|
2024-11-21 15:45:18 +00:00
|
|
|
const isJson = checkIfContentTypeIsJson(headerEntries);
|
2021-07-25 10:21:24 +00:00
|
|
|
|
2022-10-11 08:16:40 +00:00
|
|
|
/* Prefixing the base url of datasource if datasource exists */
|
2022-12-09 14:53:42 +00:00
|
|
|
const url = hasDataSource ? `${sourceOptions.url || ''}${queryOptions.url || ''}` : queryOptions.url;
|
2021-07-25 10:21:24 +00:00
|
|
|
|
2021-07-17 14:22:37 +00:00
|
|
|
const method = queryOptions['method'];
|
2024-07-09 07:40:22 +00:00
|
|
|
const retryOnNetworkError = queryOptions['retry_network_errors'] === true;
|
2024-11-21 15:45:18 +00:00
|
|
|
const _body = method !== 'get' ? this.body(sourceOptions, queryOptions, hasDataSource) : undefined;
|
2021-09-29 18:41:32 +00:00
|
|
|
const paramsFromUrl = urrl.parse(url, true).query;
|
2023-12-28 09:46:50 +00:00
|
|
|
const searchParams = new URLSearchParams();
|
|
|
|
|
|
2024-10-28 17:56:26 +00:00
|
|
|
for (const param of sourceOptions.url_parameters || []) {
|
|
|
|
|
const [key, value] = param;
|
|
|
|
|
if (key && value) {
|
|
|
|
|
searchParams.append(key, value);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-12-28 09:46:50 +00:00
|
|
|
// Append parameters individually to preserve duplicates
|
|
|
|
|
for (const [key, value] of Object.entries(paramsFromUrl)) {
|
|
|
|
|
if (Array.isArray(value)) {
|
|
|
|
|
value.forEach((val) => searchParams.append(key, val));
|
|
|
|
|
} else {
|
|
|
|
|
searchParams.append(key, String(value));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
for (const [key, value] of sanitizeSearchParams(sourceOptions, queryOptions, hasDataSource)) {
|
|
|
|
|
searchParams.append(key, String(value));
|
|
|
|
|
}
|
2022-04-22 07:31:08 +00:00
|
|
|
|
2023-07-21 10:08:56 +00:00
|
|
|
const _requestOptions: OptionsOfTextResponseBody = {
|
2022-04-22 07:31:08 +00:00
|
|
|
method,
|
2023-07-26 08:28:29 +00:00
|
|
|
...this.fetchHttpsCertsForCustomCA(sourceOptions),
|
2024-10-28 17:56:26 +00:00
|
|
|
headers,
|
2023-12-28 09:46:50 +00:00
|
|
|
searchParams,
|
2024-07-09 07:40:22 +00:00
|
|
|
...(retryOnNetworkError ? {} : { retry: 0 }),
|
2022-04-22 07:31:08 +00:00
|
|
|
};
|
|
|
|
|
|
2024-07-01 10:02:24 +00:00
|
|
|
const sanitizedCookies = sanitizeCookies(sourceOptions, queryOptions, hasDataSource);
|
|
|
|
|
const cookieString = cookiesToString(sanitizedCookies);
|
|
|
|
|
if (cookieString) {
|
|
|
|
|
_requestOptions.headers['Cookie'] = cookieString;
|
|
|
|
|
}
|
|
|
|
|
|
2023-11-17 07:06:10 +00:00
|
|
|
const hasFiles = (json) => {
|
2024-10-28 17:56:26 +00:00
|
|
|
if (isEmpty(json)) return false;
|
|
|
|
|
|
2023-11-17 07:06:10 +00:00
|
|
|
return Object.values(json || {}).some((item) => {
|
|
|
|
|
return isFileObject(item);
|
|
|
|
|
});
|
|
|
|
|
};
|
2023-11-17 05:17:35 +00:00
|
|
|
|
|
|
|
|
if (isUrlEncoded) {
|
2024-11-21 15:45:18 +00:00
|
|
|
_requestOptions.form = _body;
|
|
|
|
|
} else if (isMultipartFormData && hasFiles(_body)) {
|
2023-11-17 05:17:35 +00:00
|
|
|
const form = new FormData();
|
2024-11-21 15:45:18 +00:00
|
|
|
for (const key in _body) {
|
|
|
|
|
const value = _body[key];
|
2023-11-17 05:17:35 +00:00
|
|
|
if (isFileObject(value)) {
|
|
|
|
|
const fileBuffer = Buffer.from(value?.base64Data || '', 'base64');
|
|
|
|
|
form.append(key, fileBuffer, {
|
|
|
|
|
filename: value?.name || '',
|
|
|
|
|
contentType: value?.type || '',
|
|
|
|
|
knownLength: fileBuffer.length,
|
|
|
|
|
});
|
|
|
|
|
} else if (value !== undefined && value !== null) {
|
|
|
|
|
form.append(key, value);
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-11-17 07:06:10 +00:00
|
|
|
_requestOptions.body = form;
|
2024-10-28 17:56:26 +00:00
|
|
|
_requestOptions.headers = { ..._requestOptions.headers, ...form.getHeaders() };
|
2024-11-21 15:45:18 +00:00
|
|
|
} else if (_body && _body.key === 'json_body') {
|
|
|
|
|
// For backward compatibility
|
|
|
|
|
// FIXME: Remove this if condition once data migration is complete
|
|
|
|
|
_requestOptions.json = _body.value;
|
|
|
|
|
} else if (_body) {
|
|
|
|
|
if (isJson) {
|
|
|
|
|
_requestOptions.json = JSON5.parse(_body.value);
|
|
|
|
|
} else {
|
|
|
|
|
_requestOptions.body = _body.value;
|
|
|
|
|
}
|
2023-11-17 05:17:35 +00:00
|
|
|
}
|
|
|
|
|
|
2024-10-28 17:56:26 +00:00
|
|
|
const authValidatedRequestOptions = await validateAndSetRequestOptionsBasedOnAuthType(
|
2023-07-21 10:08:56 +00:00
|
|
|
sourceOptions,
|
|
|
|
|
context,
|
|
|
|
|
_requestOptions
|
|
|
|
|
);
|
|
|
|
|
const { status, data } = authValidatedRequestOptions;
|
|
|
|
|
if (status === 'needs_oauth') return authValidatedRequestOptions;
|
|
|
|
|
|
|
|
|
|
const requestOptions = data as OptionsOfTextResponseBody;
|
|
|
|
|
|
|
|
|
|
let result = {};
|
|
|
|
|
let requestObject = {};
|
|
|
|
|
let responseObject = {};
|
2022-04-22 07:31:08 +00:00
|
|
|
|
2021-07-17 14:22:37 +00:00
|
|
|
try {
|
2022-04-22 07:31:08 +00:00
|
|
|
const response = await got(url, requestOptions);
|
2023-05-10 05:53:35 +00:00
|
|
|
result = this.getResponse(response);
|
2024-10-28 17:56:26 +00:00
|
|
|
|
2021-12-28 10:39:38 +00:00
|
|
|
requestObject = {
|
2024-10-28 17:56:26 +00:00
|
|
|
url: response.requestUrl,
|
2021-12-28 10:39:38 +00:00
|
|
|
method: response.request.options.method,
|
2024-10-28 17:56:26 +00:00
|
|
|
headers: redactHeaders(response.request.options.headers),
|
2021-12-28 10:39:38 +00:00
|
|
|
params: urrl.parse(response.request.requestUrl, true).query,
|
|
|
|
|
};
|
2022-03-08 06:39:53 +00:00
|
|
|
|
2021-12-28 10:39:38 +00:00
|
|
|
responseObject = {
|
|
|
|
|
statusCode: response.statusCode,
|
2024-10-28 17:56:26 +00:00
|
|
|
headers: redactHeaders(response.headers),
|
2021-12-28 10:39:38 +00:00
|
|
|
};
|
2021-07-17 14:22:37 +00:00
|
|
|
} catch (error) {
|
2022-10-14 07:55:32 +00:00
|
|
|
console.error(
|
2022-11-22 13:01:05 +00:00
|
|
|
`Error while calling REST API end point. status code: ${error?.response?.statusCode} message: ${error?.response?.body}`
|
2022-10-14 07:55:32 +00:00
|
|
|
);
|
2021-07-17 14:22:37 +00:00
|
|
|
|
2021-09-21 13:48:28 +00:00
|
|
|
if (error instanceof HTTPError) {
|
2024-07-16 08:25:40 +00:00
|
|
|
const requestUrl = error?.request?.options?.url?.origin + error?.request?.options?.url?.pathname;
|
|
|
|
|
const requestHeaders = cleanSensitiveData(error?.request?.options?.headers, ['authorization']);
|
2021-07-17 14:22:37 +00:00
|
|
|
result = {
|
2021-12-28 10:39:38 +00:00
|
|
|
requestObject: {
|
2024-07-16 08:25:40 +00:00
|
|
|
requestUrl,
|
|
|
|
|
requestHeaders,
|
2021-12-28 10:39:38 +00:00
|
|
|
requestParams: urrl.parse(error.request.requestUrl, true).query,
|
|
|
|
|
},
|
|
|
|
|
responseObject: {
|
|
|
|
|
statusCode: error.response.statusCode,
|
|
|
|
|
responseBody: error.response.body,
|
|
|
|
|
},
|
2022-03-10 06:59:48 +00:00
|
|
|
responseHeaders: error.response.headers,
|
2021-09-21 13:48:28 +00:00
|
|
|
};
|
2021-07-17 14:22:37 +00:00
|
|
|
}
|
2022-10-14 07:55:32 +00:00
|
|
|
|
2023-07-21 10:08:56 +00:00
|
|
|
if (sourceOptions['auth_type'] === 'oauth2' && error?.response?.statusCode == 401) {
|
2022-10-14 07:55:32 +00:00
|
|
|
throw new OAuthUnauthorizedClientError('Unauthorized status from API server', error.message, result);
|
|
|
|
|
}
|
2021-07-17 14:22:37 +00:00
|
|
|
throw new QueryError('Query could not be completed', error.message, result);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
status: 'ok',
|
2021-09-21 13:48:28 +00:00
|
|
|
data: result,
|
2024-10-28 17:56:26 +00:00
|
|
|
metadata: {
|
|
|
|
|
request: requestObject,
|
|
|
|
|
response: responseObject,
|
|
|
|
|
},
|
2021-09-21 13:48:28 +00:00
|
|
|
};
|
2021-07-17 14:22:37 +00:00
|
|
|
}
|
2021-07-25 17:20:19 +00:00
|
|
|
|
2023-07-26 08:28:29 +00:00
|
|
|
fetchHttpsCertsForCustomCA(sourceOptions: any) {
|
|
|
|
|
let httpsParams: any = {};
|
|
|
|
|
switch (sourceOptions.ssl_certificate) {
|
|
|
|
|
case 'ca_certificate':
|
|
|
|
|
httpsParams = {
|
|
|
|
|
https: {
|
|
|
|
|
certificateAuthority: [sourceOptions.ca_cert],
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
break;
|
|
|
|
|
case 'client_certificate':
|
|
|
|
|
httpsParams = {
|
|
|
|
|
https: {
|
|
|
|
|
certificateAuthority: [sourceOptions.ca_cert],
|
|
|
|
|
key: [sourceOptions.client_key],
|
|
|
|
|
certificate: [sourceOptions.client_cert],
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
break;
|
|
|
|
|
default:
|
|
|
|
|
break;
|
|
|
|
|
}
|
2022-01-03 04:12:22 +00:00
|
|
|
|
2023-07-26 08:28:29 +00:00
|
|
|
if (process.env.NODE_EXTRA_CA_CERTS) {
|
|
|
|
|
'https' in httpsParams
|
|
|
|
|
? (httpsParams.https.certificateAuthority = httpsParams.https?.certificateAuthority.concat([
|
|
|
|
|
...tls.rootCertificates,
|
|
|
|
|
readFileSync(process.env.NODE_EXTRA_CA_CERTS),
|
|
|
|
|
]))
|
|
|
|
|
: (httpsParams = {
|
|
|
|
|
https: {
|
|
|
|
|
certificateAuthority: [...tls.rootCertificates, readFileSync(process.env.NODE_EXTRA_CA_CERTS)].join('\n'),
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return httpsParams;
|
2022-01-03 04:12:22 +00:00
|
|
|
}
|
2022-03-25 07:18:29 +00:00
|
|
|
|
2023-05-10 05:53:35 +00:00
|
|
|
private getResponse(response) {
|
|
|
|
|
try {
|
|
|
|
|
if (this.isJson(response.body)) {
|
|
|
|
|
return JSON.parse(response.body);
|
|
|
|
|
}
|
|
|
|
|
if (response.rawBody && response.headers?.['content-type']?.startsWith('image/')) {
|
|
|
|
|
return Buffer.from(response.rawBody, 'binary').toString('base64');
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error while parsing response', error);
|
|
|
|
|
}
|
|
|
|
|
return response.body;
|
|
|
|
|
}
|
|
|
|
|
|
2023-07-21 10:08:56 +00:00
|
|
|
authUrl(sourceOptions: SourceOptions): string {
|
|
|
|
|
return getAuthUrl(sourceOptions);
|
|
|
|
|
}
|
2022-10-14 07:55:32 +00:00
|
|
|
|
2023-07-21 10:08:56 +00:00
|
|
|
async refreshToken(sourceOptions: any, error: any, userId: string, isAppPublic: boolean) {
|
|
|
|
|
return getRefreshedToken(sourceOptions, error, userId, isAppPublic);
|
2022-03-25 07:18:29 +00:00
|
|
|
}
|
2021-07-17 14:22:37 +00:00
|
|
|
}
|