All files / frontend/helpers requests.js

98.71% Statements 154/156
93.63% Branches 147/157
95% Functions 19/20
98.65% Lines 147/149

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377                                                                                                            10x     10x     10x           10x 17x 2x 1x                 16x   16x   9x 3x   6x 6x 5x   5x 5x 5x         11x         10x 28x 26x           28x 1x   28x 20x   20x 20x   15x       20x 20x 2x     28x         36x 31x 30x 30x         4x 26x       11x 15x       3x     36x           10x 10x 1x 1x 1x 4x   9x 1x   8x     2x 1x   1x     10x 26x 1x   26x   26x 1x   1x 1x       25x         33x 32x 27x 26x 14x   26x 26x 2x     4x 3x 2x   1x         4x 4x 4x     4x   25x               2x 1x   1x           11x         10x         7x         3x         10x 10x 8x 8x         2x         12x 6x 6x 6x       3x 3x 3x 3x 3x               67x 67x   67x     67x 67x   67x 1x 1x       66x 1x 1x 1x 1x 65x 6x     6x 6x 59x 3x   56x       66x 66x     28x 28x     38x       5x 5x 5x 5x   33x 10x 9x     10x 10x   10x 10x 10x 10x   10x 10x 4x   6x   10x         10x 10x       23x        
/*
  Copyright (C) 2021 owner Roman Piontik R.Piontik@mail.ru
 
  Copyright (C) 2022 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
  http://www.apache.org/licenses/LICENSE-2.0
 
  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project
 
  https://dochub.info
 
  The use of this product or its derivatives for any purpose cannot be a secret.
 
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 
  Maintainers:
      R.Piontik <r.piontik@mail.ru>
 
  Contributors:
      R.Piontik <r.piontik@mail.ru> - 2023
      R.Piontik <r.piontik@mail.ru> - 2022
      R.Piontik <r.piontik@mail.ru> - 2021
      Rostislav Kabalin <kabalin2009@yandex.ru> - 2022
*/
 
import axios from 'axios';
import YAML from 'yaml';
import crc16 from '@global/helpers/crc16';
import gitlab from '@front/helpers/gitlab';
import uriTool from '@front/helpers/uri';
import { Buffer } from 'buffer';
import xml from '@global/helpers/xmlparser';
import { v4 as uuidv4 } from 'uuid';
import { HttpHeaders } from '@global/helpers/httpHeaders.mjs';
import { BITBUCKET_URI_PREFIX, GITLAB_URI_PREFIX } from '@global/constants.mjs';
 
import env, { Plugins } from './env';
import { responseCacheInterceptor, requestCacheInterceptor } from './cache';
import userStore from '@front/store/userStore.js';
 
import { unenvelopeDocument } from '@global/helpers/api/unenvelope.js';
import {extreactOrgCtxFromWindow, isUriHostEqualBackendHost} from '@front/helpers/orgCtxTools.js';
 
// CRC16 URL задействованных файлов
const tracers = {};
 
function escapeRegExp(value) {
    return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
 
const fileStorageRequestPattern = new RegExp(
    `^${escapeRegExp(env.backendFileStorageURL)}[0-9a-f]{32}/`
);
 
// Add a request interceptor
 
const responseErrorInterceptor = async(error) => {
	if (error.response?.status === 304) {
		if (error.config.lastCachedResult) {
			return {
				...error.response,
				data: error.config.lastCachedResult.data
			};
		}
	}
 
	// Бэк не принял запрос пользователя: не больше одного обновления на токен и один повтор.
	// 401 на повтор — отказ по правам. authToken — токен, с которым ушёл запрос (ставит интерцептор запроса)
	const config = error.config;
	// Фоновый запрос (background) на 401 токен не обновляет, не повторяется и на вход не уводит
	if (error.response?.status === 401 && config && !config.background
		&& env.backendURL && isUriHostEqualBackendHost(config.url)) {
		if (config.authRetried) {
			await userStore.handleUnauthorized(config.authToken ?? null, {retried: true});
		} else {
			const accessToken = await userStore.handleUnauthorized(config.authToken ?? null);
			if (accessToken) {
				config.authRetried = true;
				// Токен и идентификатор запроса проставит интерцептор запроса заново
				delete config.headers.Authorization;
				delete config.headers[HttpHeaders.REQUEST_ID];
				return axios(config);
			}
		}
	}
 
	return Promise.reject(error);
};
 
 
// Интерцептор для GitLab авторизации
axios.interceptors.request.use(async(params) => {
	if(!env.isPlugin()) {
		params.headers = {
			[HttpHeaders.REQUEST_ID]: uuidv4(),
			...params.headers
		};
	}
 
	if (env.cache) {
		await requestCacheInterceptor(params);
	}
	if (env.backendURL && isUriHostEqualBackendHost(params.url)) {
		const accessToken = await userStore.getAccessToken({background: params.background === true});
		// Ключ конфига axios, на сервер не уходит: по нему 401 связывается с токеном запроса
		params.authToken = accessToken || null;
		if (accessToken) {
			// На верхнем уровне: при повторе запроса заголовки уже «сплющены», и common не перебьёт старый токен
			params.headers.Authorization = 'Bearer ' + accessToken;
		}
		// Контекст организации — после токена: после старта без токена userStore с первым токеном
		// загружает права и ставит контекст в адрес страницы, а запрос ждёт этого
		const orgCtx = !env.isPlugin() && extreactOrgCtxFromWindow();
		if (orgCtx) {
			params.headers[HttpHeaders.X_SFA_ORGCTX] = orgCtx;
		}
	}
	return gitlab.axiosInterceptor(params);
}, (error) => Promise.reject(error));
 
// Здесь разбираемся, что к нам вернулось из запроса и преобразуем к формату внутренних данных
function parseResponseData(response) {
	if (typeof response.data === 'string') {
		if (!response.config.raw) {
			const url = (response.config.url || '').toString().split('?')[0].toLowerCase();
			if (
				(url.endsWith('.json/raw'))
				|| (url.endsWith('.json'))
				|| (response?.headers || {})['content-type'] === 'application/json'
				)
				response.data = JSON.parse(response.data);
			else if (
				(url.endsWith('.yaml/raw'))
				|| (url.endsWith('.yaml'))
				|| (response?.headers || {})['content-type'] === 'application/x-yaml')
				response.data = YAML.parse(response.data);
			else if (
				(url.endsWith('.xml/raw'))
				|| (url.endsWith('.xml'))
				|| (response?.headers || {})['content-type'] === 'application/xml')
				response.data = xml.parse(response.data);
		}
	}
	return response;
}
 
// Приводит содержимое файла из транспортного пакета к запрошенному responseType,
// так же как это делает axios в обычном режиме
function decodeEnvelopedContent(content, responseType) {
	let bytes = null;
	if (content.encoding === 'base64') {
		const binary = atob(content.data);
		bytes = new Uint8Array(binary.length);
		for (let i = 0; i < binary.length; i++) {
			bytes[i] = binary.charCodeAt(i);
		}
	} else if (responseType === 'arraybuffer' || responseType === 'blob') {
		bytes = new TextEncoder().encode(content.data);
	} else {
		return content.data;
	}
 
	if (responseType === 'blob') {
		return new Blob([bytes], content.contentType ? { type: content.contentType } : undefined);
	}
	return bytes.buffer;
}
 
axios.interceptors.response.use(async(response) => {
	if (response.config.responseHook) {
		response.config.responseHook(response);
	}
	parseResponseData(response);
 
	if (env.cache) {
		const reRequest = await responseCacheInterceptor(response);
 
		Eif (reRequest) {
			return axios(reRequest);
		}
	}
 
	return response;
}, responseErrorInterceptor);
 
 
function injectPAPIMiddleware() {
	if (window.$PAPI && !window.$PAPI.middleware) {
		window.$PAPI.middleware = function(response, params) {
			if (!response) return response;
      if (params.responseHook) {
        response = params.responseHook(response);
      }
			let type = response.contentType;
			switch (type) {
				case 'yaml': response.data = YAML.parse(response.data); break;
				case 'json':
					// IDE может вернуть JSON строкой или уже разобранным объектом.
					if (typeof response.data === 'string') response.data = JSON.parse(response.data);
					break;
				case 'xml': !params?.raw && (response.data = xml.parse(response.data)); break;
				case 'jpg':
					type = 'jpeg';
				// eslint-disable-next-line no-fallthrough
				case 'jpeg':
				case 'png':
				case 'svg':
					if (type === 'svg') type = 'svg+xml';
					response.data = Buffer.from(response.data, 'base64');
					response.headers = Object.assign(response.headers || {}, {
						'content-type': `image/${type}`
					});
					break;
			}
			return response;
		};
	}
}
 
export default {
	axios,
	getSourceRoot() {
		if (env.isPlugin(Plugins.idea)) {
			return 'plugin:/idea/source/';
		} else {
			return window.origin + '/';
		}
	},
 
	// Возвращает "чистый" URL пригодный для индексирования
	getIndexURL(url) {
		return url.toString().split('?')[0].split('#')[0];
	},
 
	// Возвращает CRC ссылки
	crcOfURL(url) {
		return crc16(this.getIndexURL(url));
	},
 
	// Фиксируются все обращения для построения карты задействованных ресурсов
	trace(url) {
		env.isPlugin() && (tracers[this.crcOfURL(url)] = Date.now());
	},
 
	// Возвращает время последнего обращения к ресурсу
	isUsedURL(url) {
		return tracers[this.crcOfURL(url)];
	},
 
	// Транслирует ссылки на backend в прямые URL
	translateBackendURL(url) {
		const finalURl = url && url.toString();
		if (finalURl && finalURl.startsWith('backend://')) {
			try {
				return (new URL(finalURl.slice(10), env.backendFileStorageURL));
			} catch (e) {
				throw new Error(e);
			}
		} else {
			return url;
		}
	},
 
	encodeRelPath(path) {
		if (!env.isBackendMode) return path;
		const struct = path.split('?');
		struct[0] = struct[0].replace(/\.\./g, '%E2%86%90');
		return struct.join('?');
	},
 
	expandResourceURI(URI) {
		const url = new URL(URI);
    const objectPath = `${url.hostname}${url.pathname}`;
		const subPath = this.encodeRelPath(url.hash.slice(1));
		const result = uriTool.makeURL(uriTool.makeURIByBaseURI(subPath, uriTool.getBaseURIOfPath(objectPath))).url;
		return result.toString();
	},
 
	// axios_params - параметры передаваемые в axios
	// 		responseHook - содержит функцию обработки ответа перед работой interceptors
	//		raw - если true возвращает ответ без обработки
	//		background - фоновый запрос (опрос и т. п.): токен не обновляет, на 401 не повторяется и на вход не уводит
	request(uri, baseURI, axios_params) {
		const params = Object.assign({}, axios_params);
		params.url = uri;
		// Если ссылка ведет на backend конвертируем ее
		let strURI = (uri || '').toString();
 
		// Если URI является ссылкой на ресурс в Data Lake интерпретируем ее
		strURI.startsWith('res://') && (strURI = this.expandResourceURI(strURI));
		baseURI && baseURI.toString().startsWith('res://') && (baseURI = this.expandResourceURI(baseURI));
 
		if (strURI.startsWith('source:')) {
			return new Promise((success) => {
				success({
					data: JSON.parse(decodeURIComponent((new URL(uri)).pathname))
				});
			});
		} else if (strURI.startsWith('backend://')) {
			const structURI = strURI.split('/');
			const origin = `${structURI[0]}//${structURI[2]}/`;
			const path = this.encodeRelPath(strURI.slice(origin.length));
			params.url = new URL(path, this.translateBackendURL(origin));
		} else if ((baseURI || '').toString().startsWith('backend://')) {
			let path = uri.toString();
			// Абсолютный путь к файлу репозитория (bitbucket:/gitlab:) URL разобрал бы как схему, и запрос не ушёл
			// бы на backend. Передаём его в storage как относительный - абсолютные пути разбирает контроллер storage
			(path.startsWith(BITBUCKET_URI_PREFIX) || path.startsWith(GITLAB_URI_PREFIX)) && (path = `./${path}`);
			params.url = new URL(this.encodeRelPath(path), this.translateBackendURL(baseURI));
		} else if (baseURI) {
			params.url = uriTool.makeURL(uriTool.makeURIByBaseURI(strURI, baseURI)).url;
		} else {
			params.url = uriTool.makeURL(strURI).url;
		}
 
 
		let paramsUrl = params.url.toString();
		if (env.isPlugin(Plugins.idea) &&
			(strURI?.startsWith('bitbucket:') || baseURI?.startsWith('bitbucket:'))
		) {
			injectPAPIMiddleware();
			return window.$PAPI.downloadBitBucket(paramsUrl);
		}
 
		if (
			env.isPlugin(Plugins.idea) && paramsUrl.startsWith('plugin:') ||
			env.isPlugin(Plugins.vscode) && paramsUrl.startsWith('https://file+.vscode-resource.vscode-cdn.net') && !params.responseHook
		) {
			injectPAPIMiddleware();
			this.trace(params.url);
			params.raw = !!axios_params?.raw;
			return window.$PAPI.request(params);
		} else {
            if (env.isEnvelopedRequests && fileStorageRequestPattern.test(paramsUrl)) {
                if (!params.url.searchParams.has('envelope')) {
                    params.url.searchParams.set('envelope', 'true');
                }
                // responseHook должен работать с содержимым файла, а не с транспортным пакетом
                const responseHook = params.responseHook;
                params.responseHook = undefined;
                // Транспортный пакет всегда JSON, запрошенный тип применяется к содержимому файла
                const responseType = params.responseType;
                params.responseType = 'json';
                return axios(params).then((result) => {
                    const content = unenvelopeDocument(result.data);
                    // content-type пакета заменяем на content-type файла
                    const headers = Object.assign({}, result.headers);
                    if (content.contentType) {
                        headers['content-type'] = content.contentType;
                    } else {
                        delete headers['content-type'];
                    }
                    let response = {
                        ...result,
                        headers,
                        data: decodeEnvelopedContent(content, responseType)
                    };
                    responseHook && (response = responseHook(response) || response);
                    return parseResponseData(response);
                });
            }
 
			return axios(params);
		}
	}
};