feat: enable amqps and separate producer and consumer permissions

This commit is contained in:
2026-11-30 16:36:14 +03:00
parent 7162d4c518
commit cd336d8472
7 changed files with 82 additions and 17 deletions
+20 -12
View File
@@ -238,23 +238,28 @@ services:
rabbitmq: rabbitmq:
image: rabbitmq:4.0.5-alpine@sha256:e045b5166b9188a38eee5c99411709aa1f0ffa2ac75664053e64cb69411f7c32 image: rabbitmq:4.0.5-alpine@sha256:e045b5166b9188a38eee5c99411709aa1f0ffa2ac75664053e64cb69411f7c32
hostname: rabbitmq hostname: rabbitmq
security_opt: [no-new-privileges:true]
environment:
RABBITMQ_NODENAME: rabbit@localhost
ERL_EPMD_ADDRESS: 127.0.0.1
volumes: volumes:
- rabbitmqdata:/var/lib/rabbitmq - rabbitmqdata:/var/lib/rabbitmq
- { type: volume, source: secrets, target: /etc/rabbitmq/conf.d, read_only: true, volume: { subpath: rabbitmq } } - ./infra/rabbitmq/10-messenger.conf:/etc/rabbitmq/conf.d/10-messenger.conf:ro
deploy: - ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro
resources: - {type: volume, source: pki, target: /run/tls, read_only: true, volume: {subpath: rabbitmq}}
limits: { cpus: "0.5", memory: 512M }
healthcheck: healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"] test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"]
interval: 10s interval: 5s
timeout: 10s timeout: 8s
retries: 12
start_period: 20s start_period: 20s
stop_grace_period: 30s retries: 12
depends_on: depends_on:
secrets-init: bootstrap: {condition: service_completed_successfully}
condition: service_completed_successfully stop_grace_period: 30s
restart: unless-stopped restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.5", memory: 512M}
relay: relay:
build: build:
@@ -263,8 +268,10 @@ services:
image: mtusi-messenger-lab7-api:dev image: mtusi-messenger-lab7-api:dev
command: ["node", "dist/relay.js"] command: ["node", "dist/relay.js"]
environment: environment:
NODE_EXTRA_CA_CERTS: /run/tls/ca.crt
DATABASE_URL_FILE: /run/tls/database_url DATABASE_URL_FILE: /run/tls/database_url
BROKER_URL_FILE: /run/secrets/broker_url BROKER_URL_FILE: /run/tls/broker_url
AMQP_TOPOLOGY_PREPROVISIONED: "true"
JOB_STALE_SECONDS: ${JOB_STALE_SECONDS:-300} JOB_STALE_SECONDS: ${JOB_STALE_SECONDS:-300}
RELAY_FAULT: ${RELAY_FAULT:-} RELAY_FAULT: ${RELAY_FAULT:-}
<<: *otel <<: *otel
@@ -293,7 +300,8 @@ services:
command: ["node", "dist/worker.js"] command: ["node", "dist/worker.js"]
environment: environment:
DATABASE_URL_FILE: /run/tls/database_url DATABASE_URL_FILE: /run/tls/database_url
BROKER_URL_FILE: /run/secrets/broker_url BROKER_URL_FILE: /run/tls/broker_url
AMQP_TOPOLOGY_PREPROVISIONED: "true"
NODE_EXTRA_CA_CERTS: /run/tls/ca.crt NODE_EXTRA_CA_CERTS: /run/tls/ca.crt
S3_ENDPOINT: https://s3:9000 S3_ENDPOINT: https://s3:9000
S3_REGION: ${S3_REGION:-us-east-1} S3_REGION: ${S3_REGION:-us-east-1}
+38 -2
View File
@@ -1,5 +1,8 @@
"""Generate local stand identities and credentials, once per secrets volume.""" """Generate local stand identities and credentials, once per secrets volume."""
import base64
import hashlib
import json
import os import os
import secrets import secrets
import shutil import shutil
@@ -66,12 +69,39 @@ def db_url(role, password, limit):
f"&application_name={role}&options=-c%20statement_timeout%3D5000") f"&application_name={role}&options=-c%20statement_timeout%3D5000")
def broker_definitions(relay_password, worker_password):
def user(name, password):
salt = secrets.token_bytes(4)
digest = hashlib.sha256(salt + password.encode()).digest()
return {"name": name, "password_hash": base64.b64encode(salt + digest).decode(),
"hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []}
return {
"users": [user("relay", relay_password), user("worker", worker_password)],
"vhosts": [{"name": "/messenger"}],
"permissions": [
{"user": "relay", "vhost": "/messenger", "configure": "^$", "write": "^amq\\.default$",
"read": "^$"},
{"user": "worker", "vhost": "/messenger", "configure": "^$", "write": "^$",
"read": "^attachment\\.jobs$"},
],
"queues": [
{"name": "attachment.jobs.dlq", "vhost": "/messenger", "durable": True,
"auto_delete": False, "arguments": {"x-queue-type": "quorum"}},
{"name": "attachment.jobs", "vhost": "/messenger", "durable": True,
"auto_delete": False, "arguments": {"x-queue-type": "quorum", "x-delivery-limit": 20,
"x-dead-letter-exchange": "",
"x-dead-letter-routing-key": "attachment.jobs.dlq"}},
],
}
def main(): def main():
if (ROOT / "initialized").is_file(): if (ROOT / "initialized").is_file():
print("Local identities already initialized") print("Local identities already initialized")
return return
os.umask(0o077) os.umask(0o077)
names = ("operator", "lb", "checks", "postgres", "migrate", "s3", "s3-init", *ROLES) names = ("operator", "lb", "checks", "postgres", "migrate", "s3", "s3-init", "rabbitmq", *ROLES)
directories = {name: ROOT / name for name in names} directories = {name: ROOT / name for name in names}
for directory in directories.values(): for directory in directories.values():
directory.mkdir(exist_ok=True) directory.mkdir(exist_ok=True)
@@ -122,8 +152,14 @@ def main():
write(directories[role] / "s3_access_key_id", f"messenger-{role}") write(directories[role] / "s3_access_key_id", f"messenger-{role}")
write(directories[role] / "s3_secret_access_key", password) write(directories[role] / "s3_secret_access_key", password)
write(directories["s3-init"] / f"{role}_password", password) write(directories["s3-init"] / f"{role}_password", password)
leaf(directories["rabbitmq"], "rabbitmq", server_ca)
relay_password, worker_password = secrets.token_hex(24), secrets.token_hex(24)
write(directories["rabbitmq"] / "definitions.json",
json.dumps(broker_definitions(relay_password, worker_password)))
for role, password in (("relay", relay_password), ("worker", worker_password)):
write(directories[role] / "broker_url", f"amqps://{role}:{password}@rabbitmq:5671/%2Fmessenger")
shutil.copyfile(api / "api.crt", checks / "api.crt") shutil.copyfile(api / "api.crt", checks / "api.crt")
owners = {"lb": 1000, "postgres": 70, "migrate": 1000, **dict.fromkeys(ROLES, 1000)} owners = {"lb": 1000, "rabbitmq": 100, "postgres": 70, "migrate": 1000, **dict.fromkeys(ROLES, 1000)}
for name, uid in owners.items(): for name, uid in owners.items():
own(directories[name], uid) own(directories[name], uid)
(ROOT / "initialized").touch() (ROOT / "initialized").touch()
+12
View File
@@ -0,0 +1,12 @@
listeners.tcp = none
listeners.ssl.default = 5671
ssl_options.certfile = /run/tls/rabbitmq.crt
ssl_options.keyfile = /run/tls/rabbitmq.key
ssl_options.verify = verify_none
ssl_options.fail_if_no_peer_cert = false
ssl_options.versions.1 = tlsv1.3
ssl_options.versions.2 = tlsv1.2
definitions.import_backend = local_filesystem
definitions.local.path = /run/tls/definitions.json
distribution.listener.interface = 127.0.0.1
log.console = true
+1
View File
@@ -0,0 +1 @@
[].
+5 -1
View File
@@ -39,7 +39,11 @@ export async function connectWithRetry(
let delay = 500; let delay = 500;
while (!stopping()) { while (!stopping()) {
try { try {
const connection = await amqp.connect(brokerUrl(), { timeout: 5000 }); const url = new URL(brokerUrl());
const connection = await amqp.connect(url.href, {
timeout: 5000,
...(url.protocol === 'amqps:' ? { servername: url.hostname, rejectUnauthorized: true } : {}),
});
logger.log('connected to broker'); logger.log('connected to broker');
return connection; return connection;
} catch (error) { } catch (error) {
+3 -1
View File
@@ -165,7 +165,9 @@ async function run(): Promise<void> {
channel.on('close', () => { channel.on('close', () => {
closed = true; closed = true;
}); });
await assertTopology(channel); if (process.env.AMQP_TOPOLOGY_PREPROVISIONED !== 'true') {
await assertTopology(channel);
}
while (!stopping && !closed) { while (!stopping && !closed) {
let published = 0; let published = 0;
try { try {
+3 -1
View File
@@ -158,7 +158,9 @@ async function run(): Promise<void> {
}); });
try { try {
const channel = await connection.createChannel(); const channel = await connection.createChannel();
await assertTopology(channel); if (process.env.AMQP_TOPOLOGY_PREPROVISIONED !== 'true') {
await assertTopology(channel);
}
await channel.prefetch(CONCURRENCY); await channel.prefetch(CONCURRENCY);
const { consumerTag } = await channel.consume( const { consumerTag } = await channel.consume(
JOB_QUEUE, JOB_QUEUE,