forked from mtusi2026/mtusi2026lab4
feat(storage): add RustFS attachments and presigned uploads
Add two API replicas, safe object reconciliation, upload validation, regression tests and documented load experiments.
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
S3Client,
|
||||
CreateBucketCommand,
|
||||
HeadBucketCommand,
|
||||
} from '@aws-sdk/client-s3';
|
||||
import { adminRequest } from './admin.mjs';
|
||||
import { bootstrapSettings, storagePolicies } from './policies.mjs';
|
||||
|
||||
const settings = bootstrapSettings();
|
||||
const client = new S3Client({
|
||||
endpoint: settings.endpoint,
|
||||
region: settings.region,
|
||||
forcePathStyle: true,
|
||||
maxAttempts: 1,
|
||||
credentials: settings.credentials,
|
||||
});
|
||||
const Bucket = settings.bucket;
|
||||
try {
|
||||
try {
|
||||
await client.send(new HeadBucketCommand({ Bucket }), {
|
||||
abortSignal: AbortSignal.timeout(30000),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.$metadata?.httpStatusCode !== 404) throw error;
|
||||
try {
|
||||
await client.send(new CreateBucketCommand({ Bucket }), {
|
||||
abortSignal: AbortSignal.timeout(30000),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.name !== 'BucketAlreadyOwnedByYou') throw error;
|
||||
}
|
||||
}
|
||||
const policies = storagePolicies(Bucket);
|
||||
for (const role of ['api', 'reconciler']) {
|
||||
const identity = settings[role];
|
||||
const policyName = `${Bucket}-${role}`;
|
||||
await adminRequest(
|
||||
settings,
|
||||
'PUT',
|
||||
'add-canned-policy',
|
||||
{ name: policyName },
|
||||
policies[role],
|
||||
);
|
||||
await adminRequest(
|
||||
settings,
|
||||
'PUT',
|
||||
'add-user',
|
||||
{ accessKey: identity.accessKeyId },
|
||||
{ secretKey: identity.secretAccessKey, status: 'enabled' },
|
||||
);
|
||||
// Replace the direct binding instead of accumulating old policies across bootstraps.
|
||||
await adminRequest(settings, 'PUT', 'set-user-or-group-policy', {
|
||||
policyName,
|
||||
userOrGroup: identity.accessKeyId,
|
||||
isGroup: false,
|
||||
});
|
||||
console.log(`Restricted S3 identity provisioned: ${role}`);
|
||||
}
|
||||
console.log('Private attachments bucket and restricted identities are ready');
|
||||
} finally {
|
||||
client.destroy();
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
export function storagePolicies(bucket) {
|
||||
const bucketArn = `arn:aws:s3:::${bucket}`;
|
||||
const objectsArn = `${bucketArn}/originals/*`;
|
||||
const base = [
|
||||
{
|
||||
Effect: 'Allow',
|
||||
Action: ['s3:GetBucketLocation'],
|
||||
Resource: [bucketArn],
|
||||
},
|
||||
];
|
||||
return {
|
||||
api: {
|
||||
Version: '2012-10-17',
|
||||
Statement: [
|
||||
...base,
|
||||
{
|
||||
Effect: 'Allow',
|
||||
Action: ['s3:GetObject', 's3:PutObject', 's3:DeleteObject'],
|
||||
Resource: [objectsArn, `${bucketArn}/staging/*`],
|
||||
},
|
||||
],
|
||||
},
|
||||
reconciler: {
|
||||
Version: '2012-10-17',
|
||||
Statement: [
|
||||
...base,
|
||||
{
|
||||
Effect: 'Allow',
|
||||
Action: ['s3:ListBucket'],
|
||||
Resource: [bucketArn],
|
||||
Condition: {
|
||||
StringLike: { 's3:prefix': ['originals/*', 'staging/*'] },
|
||||
},
|
||||
},
|
||||
{
|
||||
Effect: 'Allow',
|
||||
Action: ['s3:GetObject', 's3:DeleteObject'],
|
||||
Resource: [objectsArn, `${bucketArn}/staging/*`],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function bootstrapSettings(env = process.env) {
|
||||
const settings = {
|
||||
endpoint: env.S3_ENDPOINT ?? 'http://s3:9000',
|
||||
region: env.S3_REGION ?? 'us-east-1',
|
||||
bucket: env.S3_BUCKET ?? 'messenger-attachments',
|
||||
credentials: {
|
||||
accessKeyId: env.S3_ACCESS_KEY_ID,
|
||||
secretAccessKey: env.S3_SECRET_ACCESS_KEY,
|
||||
},
|
||||
api: {
|
||||
accessKeyId: env.S3_API_ACCESS_KEY_ID ?? 'LABAPI',
|
||||
secretAccessKey:
|
||||
env.S3_API_SECRET_ACCESS_KEY ?? 'local_api_storage_password',
|
||||
},
|
||||
reconciler: {
|
||||
accessKeyId: env.S3_RECONCILER_ACCESS_KEY_ID ?? 'LABRECONCILER',
|
||||
secretAccessKey:
|
||||
env.S3_RECONCILER_SECRET_ACCESS_KEY ??
|
||||
'local_reconciler_storage_password',
|
||||
},
|
||||
};
|
||||
const identities = [settings.credentials, settings.api, settings.reconciler];
|
||||
for (const identity of identities) {
|
||||
if (
|
||||
!identity.accessKeyId ||
|
||||
!identity.secretAccessKey ||
|
||||
identity.secretAccessKey.length < 8
|
||||
) {
|
||||
throw new Error(
|
||||
'All S3 identities require an access key and a secret of at least 8 characters',
|
||||
);
|
||||
}
|
||||
}
|
||||
if (
|
||||
new Set(identities.map((identity) => identity.accessKeyId)).size !== 3 ||
|
||||
new Set(identities.map((identity) => identity.secretAccessKey)).size !== 3
|
||||
) {
|
||||
throw new Error(
|
||||
'Root, API and reconciler identities must have distinct access and secret keys',
|
||||
);
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
Reference in New Issue
Block a user