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:
2026-11-12 10:16:39 +03:00
parent ec540a1a72
commit dc46ac213d
118 changed files with 44628 additions and 38 deletions
+56
View File
@@ -0,0 +1,56 @@
events {}
http {
# Capabilities are query strings; never write signed URLs to access logs.
server {
listen 9000;
access_log off;
error_log /dev/null;
client_max_body_size 10m;
client_body_timeout 15s;
location ~ "^/messenger-attachments/staging/[0-9a-f-]{36}/[0-9a-f-]{36}$" {
add_header Access-Control-Allow-Origin '*' always;
add_header Access-Control-Allow-Methods 'PUT, OPTIONS' always;
add_header Access-Control-Allow-Headers 'Content-Type, Content-Length, If-None-Match, x-amz-checksum-sha256' always;
add_header Access-Control-Expose-Headers 'ETag, x-amz-checksum-sha256' always;
if ($request_method = OPTIONS) { return 204; }
if ($request_method != PUT) { return 405; }
proxy_pass http://s3:9000;
proxy_request_buffering off;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header Connection '';
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Headers;
proxy_hide_header Access-Control-Allow-Methods;
proxy_connect_timeout 2s;
proxy_read_timeout 30s;
}
location / { return 403; }
}
upstream api {
least_conn;
zone api 64k;
include /etc/nginx/ready-upstreams.conf;
}
server {
listen 80;
client_max_body_size 11m;
location / {
proxy_pass http://api;
proxy_request_buffering off;
proxy_http_version 1.1;
# Preserve early 4xx responses while the client is still sending a body.
# The default Connection: close can make Node close before Nginx reads 413.
proxy_set_header Connection '';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 2s;
proxy_read_timeout 30s;
}
}
}
+98
View File
@@ -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;
}
+62
View File
@@ -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();
}
+87
View File
@@ -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;
}
+71
View File
@@ -0,0 +1,71 @@
#!/bin/sh
set -eu
upstreams=/etc/nginx/ready-upstreams.conf
printf 'server 127.0.0.1:9 down;\n' > "$upstreams"
check_ready() {
state=/tmp/nginx-readiness.state
probes=/tmp/nginx-readiness-probes
mkdir -p "$probes"
: > "$state"
sleep 2
while :; do
next="${upstreams}.next"
previous="${upstreams}.previous"
: > "${state}.next"
printf 'server 127.0.0.1:9 down;\n' > "$next"
addresses=$(getent ahostsv4 api | awk '{print $1}' | sort -u)
for address in $addresses; do
(
if wget -q -T 1 -t 1 -O /dev/null "http://${address}:8080/health/ready"; then
printf '1\n'
else
printf '0\n'
fi > "$probes/$address"
) &
done
wait
for address in $addresses; do
record=$(awk -v address="$address" '$1 == address {print $2, $3, $4}' "$state")
set -- ${record:-0 0 0}
ready=$1
successes=$2
failures=$3
if [ "$(cat "$probes/$address")" = 1 ]; then
failures=0
if [ "$successes" -lt 2 ]; then successes=$((successes + 1)); fi
if [ "$successes" -ge 2 ]; then ready=1; fi
else
successes=0
if [ "$failures" -lt 2 ]; then failures=$((failures + 1)); fi
if [ "$failures" -ge 2 ]; then ready=0; fi
fi
printf '%s %s %s %s\n' "$address" "$ready" "$successes" "$failures" >> "${state}.next"
if [ "$ready" -eq 1 ]; then
printf 'server %s:8080 max_fails=2 fail_timeout=2s;\n' "$address" >> "$next"
fi
done
mv "${state}.next" "$state"
if cmp -s "$next" "$upstreams"; then
rm -f "$next"
else
cp "$upstreams" "$previous"
mv "$next" "$upstreams"
if nginx -t -q && nginx -s reload; then
rm -f "$previous"
else
mv "$previous" "$upstreams"
printf 'Could not reload Nginx readiness upstreams\n' >&2
fi
fi
sleep 2
done
}
check_ready &
exec nginx -g 'daemon off;'