Files
qrtx dc46ac213d feat(storage): add RustFS attachments and presigned uploads
Add two API replicas, safe object reconciliation, upload validation, regression tests and documented load experiments.
2026-11-12 10:16:39 +03:00

99 lines
2.8 KiB
JavaScript

import { createHash, createHmac } from 'node:crypto';
const hash = (value) => createHash('sha256').update(value).digest('hex');
const hmac = (key, value) => createHmac('sha256', key).update(value).digest();
const encode = (value) =>
encodeURIComponent(value).replace(
/[!'()*]/g,
(character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
);
/** Sign RustFS native JSON admin requests; credentials and response bodies are never logged. */
export function signAdminRequest({
endpoint,
credentials,
region = 'us-east-1',
method,
operation,
query = {},
body,
now = new Date(),
}) {
const url = new URL(`/rustfs/admin/v3/${operation}`, endpoint);
const canonicalQuery = Object.entries(query)
.map(([key, value]) => [encode(key), encode(String(value))])
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([key, value]) => `${key}=${value}`)
.join('&');
url.search = canonicalQuery;
const payload = body === undefined ? '' : JSON.stringify(body);
const date = now.toISOString().replace(/[:-]|\.\d{3}/g, '');
const headers = {
'content-type': 'application/json',
host: url.host,
'x-amz-content-sha256': hash(payload),
'x-amz-date': date,
};
const names = Object.keys(headers).sort();
const canonicalHeaders = names
.map((name) => `${name}:${headers[name]}\n`)
.join('');
const canonical = [
method,
url.pathname,
canonicalQuery,
canonicalHeaders,
names.join(';'),
hash(payload),
].join('\n');
const scope = `${date.slice(0, 8)}/${region}/s3/aws4_request`;
const stringToSign = ['AWS4-HMAC-SHA256', date, scope, hash(canonical)].join(
'\n',
);
const signingKey = hmac(
hmac(
hmac(
hmac(`AWS4${credentials.secretAccessKey}`, date.slice(0, 8)),
region,
),
's3',
),
'aws4_request',
);
const signature = createHmac('sha256', signingKey)
.update(stringToSign)
.digest('hex');
headers.authorization = `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${signature}`;
return {
url,
method,
headers,
body: body === undefined ? undefined : payload,
};
}
export async function adminRequest(config, method, operation, query, body) {
const request = signAdminRequest({
...config,
method,
operation,
query,
body,
});
const response = await fetch(request.url, {
...request,
signal: AbortSignal.timeout(30000),
});
const text = await response.text();
if (!response.ok) {
const code =
text.match(/<Code>([A-Za-z0-9_]+)<\/Code>/)?.[1] ?? 'AdminRequestFailed';
const error = new Error(
`RustFS admin ${operation}: HTTP ${response.status} ${code}`,
);
error.status = response.status;
throw error;
}
return text ? JSON.parse(text) : null;
}