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 | 2x 2x 2x 2x 30x 30x 30x 30x 30x 30x 27x 9x 9x 9x 6x 9x 9x 21x 21x 21x 5x 3x 3x 2x 2x 1x 16x 3x 13x 8x 8x 2x 5x 1x 18x 1x 18x 29x | /*
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
*/
import request, { requestRaw } from '../helpers/request.mjs';
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import { envelopeDocument } from '@global/helpers/api/envelope.js';
import { HttpError } from '@back/helpers/httpError.mjs';
import { decodePath, parseAbsoluteRepositoryPath, resolveConnectedRepositoryPath } from '@back/helpers/repositoryPath.ts';
const LOG_TAG = 'controller-storage';
const logger = getLoggerWithTag(LOG_TAG);
const _baseUrlV1 = '/seaf-core/api/core/storage';
const _baseUrlV2 = '/core/storage';
async function requestToStorage(req, res, reqBaseUrl) {
const hash = req.params.hash || '$unknown$';
let url = req.originalUrl.slice(`${reqBaseUrl}/${hash}/`.length).replace(/%E2%86%90/g, '..');
let uri = url.split('?')[0];
const baseURL = req.storage?.md5Map[hash];
try {
// Путь в URL закодирован: разбираем раскодированный, иначе абсолютный путь с %-кодированием ушёл бы
// в request как относительный и был бы прочитан без проверки репозитория
// TODO: ERA-2973 устаревшая форма '@bitbucket:...' оставлена на 1-1.5 мес для обратной совместимости.
// Её принимает parseAbsoluteRepositoryPath; без неё такой путь станет относительным, и чтение вернёт ошибку вместо файла
const repositoryPath = parseAbsoluteRepositoryPath(decodePath(uri));
if (repositoryPath) {
const repositorySources = Array.isArray(req.storage?.repositorySources) ? req.storage.repositorySources : [];
uri = resolveConnectedRepositoryPath(repositoryPath, repositorySources);
if (!uri) {
throw new HttpError(`Репозиторий файла ${repositoryPath} не используется в манифесте!`, 400);
}
}
} catch (e) {
const statusCode = typeof (e?.status) === 'number' ? e.status : 500;
return res.status(statusCode).json({
message: e.message,
error: e
});
}
const envelope = req.query?.envelope;
logger.trace(() => `Request to storage ${req.originalUrl}`);
if (req.query?.inlineContent && !uri && baseURL) { //в запросе есть флаг, что контент вложенный и не передан uri, используем только baseURL
if (envelope) {
try {
// Отдаем файл как есть, разбор выполняет клиент (как при проксировании)
// {data, contentType, encoding?} - поля без undefined, envelope их не поддерживает
res.status(200).json(envelopeDocument(await requestRaw(baseURL, null)));
} catch (e) {
// статус источника пробрасываем как при проксировании: по 404 клиент понимает, что файла нет
res.status(e?.response?.status || 500).json({
message: e.message,
error: e
});
}
} else {
request(baseURL, null, res)
.catch((e) => res.status(500).json({
message: e.message,
error: e
}));
}
} else if (!baseURL || !uri) { // иначе если нет одно из путей, то не сможем обработать запрос, возвращаем ошибку
res.status(403).json({
error: 'Access denied'
});
} else {
if (envelope) {
try {
// Отдаем файл как есть, разбор выполняет клиент (как при проксировании)
// {data, contentType, encoding?} - поля без undefined, envelope их не поддерживает
res.status(200).json(envelopeDocument(await requestRaw(uri, baseURL)));
} catch (e) {
res.status(e?.response?.status || 500).json({
message: e.message,
error: e
});
}
} else {
request(uri, baseURL, res)
.catch((e) => res.status(500).json({
message: e.message,
error: e
}));
}
}
}
export default (app) => {
// Проксирует запрос к хранилищу
// V1 оставлена до совместимости см manifestNeedChecker.mjs
app.get(_baseUrlV1 + '/:hash/*', async function(req, res) {
await requestToStorage(req, res, _baseUrlV1);
});
app.get(_baseUrlV2 + '/:hash/*', async function(req, res) {
await requestToStorage(req, res, _baseUrlV2);
});
};
|