add level 3
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
"""Obtain scoped service configuration using a certificate identity in OpenBao."""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
|
||||
def main():
|
||||
role = os.environ['BAO_SERVICE_ROLE']
|
||||
if role not in {'api', 'worker'}:
|
||||
raise ValueError('unsupported service identity')
|
||||
base = os.environ.get('BAO_ADDR', 'https://openbao:8200').rstrip('/')
|
||||
context = ssl.create_default_context(cafile=os.environ['BAO_CACERT'])
|
||||
context.load_cert_chain(os.environ['BAO_CLIENT_CERT'])
|
||||
login = urllib.request.Request(base + '/v1/auth/cert/login',
|
||||
data=json.dumps({'name': role}).encode(),
|
||||
headers={'Content-Type': 'application/json'}, method='POST')
|
||||
with urllib.request.urlopen(login, context=context, timeout=5) as response:
|
||||
token = json.load(response)['auth']['client_token']
|
||||
request = urllib.request.Request(base + '/v1/lab/data/' + role,
|
||||
headers={'X-Vault-Token': token})
|
||||
with urllib.request.urlopen(request, context=context, timeout=5) as response:
|
||||
values = json.load(response)['data']['data']
|
||||
allowed = {'DATABASE_URL', 'CURSOR_SECRET', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY', 'BROKER_URL'}
|
||||
if set(values) != allowed or not all(isinstance(v, str) and v for v in values.values()):
|
||||
raise ValueError('invalid service configuration from OpenBao')
|
||||
for key, value in values.items():
|
||||
os.environ.pop(key + '_FILE', None)
|
||||
os.environ[key] = value
|
||||
if len(sys.argv) < 2:
|
||||
raise SystemExit('missing command')
|
||||
os.execv(sys.argv[1], sys.argv[1:])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+10
-3
@@ -1,6 +1,7 @@
|
||||
"""Small durable RabbitMQ adapter; broker messages contain no attachment bytes."""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
|
||||
import pika
|
||||
@@ -16,13 +17,19 @@ DLQ = "attachment.process.v1.dlq"
|
||||
def broker_url() -> str:
|
||||
path = os.environ.get("BROKER_URL_FILE")
|
||||
value = Path(path).read_text(encoding="utf-8").strip() if path else os.environ.get("BROKER_URL", "")
|
||||
if not value.startswith(("amqp://", "amqps://")):
|
||||
raise ValueError("BROKER_URL или BROKER_URL_FILE должен содержать AMQP URL")
|
||||
if not value.startswith("amqps://"):
|
||||
raise ValueError("BROKER_URL или BROKER_URL_FILE должен содержать AMQPS URL")
|
||||
return value
|
||||
|
||||
|
||||
def _connection() -> pika.BlockingConnection:
|
||||
connection = pika.BlockingConnection(pika.URLParameters(broker_url()))
|
||||
url = broker_url()
|
||||
parameters = pika.URLParameters(url)
|
||||
ca_file = os.environ.get("BROKER_CA_FILE")
|
||||
if not ca_file:
|
||||
raise ValueError("BROKER_CA_FILE is required for verified broker TLS")
|
||||
parameters.ssl_options = pika.SSLOptions(ssl.create_default_context(cafile=ca_file), parameters.host)
|
||||
connection = pika.BlockingConnection(parameters)
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, durable=True)
|
||||
channel.queue_declare(queue=DLQ, durable=True)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Bounded per-process login attempt limit, using a monotonic clock."""
|
||||
import math
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
|
||||
class LoginLimiter:
|
||||
def __init__(self, attempts: int = 60, window_seconds: int = 60, clock=time.monotonic):
|
||||
if attempts < 1 or window_seconds < 1:
|
||||
raise ValueError("login limit must be positive")
|
||||
self.attempts = attempts
|
||||
self.window_seconds = window_seconds
|
||||
self.clock = clock
|
||||
self.timestamps = deque()
|
||||
|
||||
def retry_after(self) -> int:
|
||||
now = self.clock()
|
||||
while self.timestamps and self.timestamps[0] <= now - self.window_seconds:
|
||||
self.timestamps.popleft()
|
||||
if len(self.timestamps) >= self.attempts:
|
||||
return max(1, math.ceil(self.timestamps[0] + self.window_seconds - now))
|
||||
self.timestamps.append(now)
|
||||
return 0
|
||||
+20
-2
@@ -1,6 +1,7 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -21,6 +22,7 @@ from .attachments import router as attachment_router
|
||||
from .storage.s3 import S3Settings, S3Store
|
||||
from .storage.postgres import PostgresStore
|
||||
from . import telemetry as tel
|
||||
from .login_limit import LoginLimiter
|
||||
|
||||
tel.setup("messenger-api")
|
||||
|
||||
@@ -48,6 +50,7 @@ async def lifespan(application: FastAPI):
|
||||
await store.connect()
|
||||
application.state.store = store
|
||||
application.state.settings = settings
|
||||
application.state.login_limiter = LoginLimiter()
|
||||
application.state.s3 = S3Store(S3Settings.load())
|
||||
concurrency = int(os.environ.get("UPLOAD_CONCURRENCY", "1"))
|
||||
if not 1 <= concurrency <= 8:
|
||||
@@ -75,7 +78,7 @@ async def lifespan(application: FastAPI):
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger",
|
||||
version="1.6.0",
|
||||
version="1.7.0",
|
||||
redoc_url=None,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
@@ -90,7 +93,22 @@ async def add_request_id(request: Request, call_next) -> Response:
|
||||
status_code = 500
|
||||
with tel.tracer.start_as_current_span("HTTP request", context=tel.extract(dict(request.headers)), kind=tel.SpanKind.SERVER, record_exception=False, set_status_on_exception=False) as span:
|
||||
try:
|
||||
response = await call_next(request)
|
||||
upload = request.method == "POST" and re.fullmatch(r"/api/v1/chats/[^/]+/attachments", request.url.path)
|
||||
if request.method in {"POST", "PUT", "PATCH"} and not upload:
|
||||
# Buffer only bounded non-upload bodies; upload has its own streaming limit.
|
||||
chunks = []
|
||||
size = 0
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > 65536:
|
||||
response = error_response(request, 413, "payload_too_large", "Тело запроса слишком велико")
|
||||
break
|
||||
chunks.append(chunk)
|
||||
else:
|
||||
request._body = b"".join(chunks)
|
||||
response = await call_next(request)
|
||||
else:
|
||||
response = await call_next(request)
|
||||
status_code = response.status_code
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
response.headers["X-Instance-Id"] = request.app.state.settings.instance_id
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Create limited application roles after migrations using operator DB credentials."""
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import re
|
||||
import ssl
|
||||
import asyncpg
|
||||
|
||||
|
||||
async def main():
|
||||
secret = lambda name: Path('/run/secrets/' + name).read_text().strip()
|
||||
connection = await asyncpg.connect(secret('database_url'),
|
||||
ssl=ssl.create_default_context(cafile='/run/secrets/ca_cert'))
|
||||
try:
|
||||
for role in ('api', 'worker', 'outbox', 'reconcile'):
|
||||
user = 'messenger_' + role
|
||||
password = secret('database_' + role + '_password')
|
||||
if not re.fullmatch(r'[0-9a-f]{64}', password):
|
||||
raise ValueError('invalid generated password')
|
||||
exists = await connection.fetchval('SELECT 1 FROM pg_roles WHERE rolname=$1', user)
|
||||
if not exists:
|
||||
await connection.execute(f'CREATE ROLE {user} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION PASSWORD \'{password}\'')
|
||||
await connection.execute(f'GRANT USAGE ON SCHEMA public TO {user}')
|
||||
await connection.execute('REVOKE CREATE ON SCHEMA public FROM PUBLIC')
|
||||
await connection.execute('GRANT SELECT, INSERT ON users, chats, chat_members, messages TO messenger_api')
|
||||
await connection.execute('GRANT SELECT, INSERT, DELETE ON sessions TO messenger_api')
|
||||
await connection.execute('GRANT SELECT, INSERT, UPDATE, DELETE ON idempotency_records TO messenger_api')
|
||||
await connection.execute('GRANT SELECT, INSERT, UPDATE ON attachments, attachment_jobs TO messenger_api')
|
||||
await connection.execute('GRANT SELECT ON attachment_variants TO messenger_api')
|
||||
await connection.execute('GRANT INSERT ON attachment_outbox, attachment_slo TO messenger_api')
|
||||
await connection.execute('GRANT SELECT, UPDATE ON attachments, attachment_jobs, attachment_slo TO messenger_worker')
|
||||
await connection.execute('GRANT SELECT, INSERT, UPDATE ON attachment_variants TO messenger_worker')
|
||||
await connection.execute('GRANT SELECT, UPDATE ON attachments, attachment_jobs, attachment_slo TO messenger_outbox')
|
||||
await connection.execute('GRANT SELECT, INSERT, UPDATE ON attachment_outbox TO messenger_outbox')
|
||||
await connection.execute('GRANT SELECT ON attachments, attachment_variants TO messenger_reconcile')
|
||||
print('Database API and worker roles configured.')
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -100,6 +100,9 @@ async def create_session(
|
||||
authorization: str | None = Header(default=None),
|
||||
store: PostgresStore = Depends(get_store),
|
||||
) -> dict:
|
||||
retry_after = request.app.state.login_limiter.retry_after()
|
||||
if retry_after:
|
||||
raise ApiError(429, "rate_limited", "Слишком много попыток входа", {"Retry-After": str(retry_after)})
|
||||
if await request.body():
|
||||
raise ApiError(400, "invalid_request", "Тело запроса не требуется")
|
||||
username, password = parse_basic(authorization)
|
||||
|
||||
@@ -2,6 +2,8 @@ from datetime import datetime, timedelta, timezone
|
||||
from contextlib import asynccontextmanager
|
||||
from hashlib import sha256
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
from secrets import token_urlsafe
|
||||
from uuid import UUID, uuid4
|
||||
@@ -16,7 +18,7 @@ from .. import telemetry as tel
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MIGRATIONS = ROOT / "migrations"
|
||||
PASSWORD_HASHER = PasswordHasher()
|
||||
PASSWORD_HASHER = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
DB_ERRORS = (asyncpg.PostgresError, asyncpg.InterfaceError, OSError, TimeoutError)
|
||||
|
||||
|
||||
@@ -27,8 +29,12 @@ class PostgresStore:
|
||||
|
||||
async def connect(self) -> None:
|
||||
try:
|
||||
ca_file = os.environ.get("DATABASE_CA_FILE")
|
||||
if not ca_file:
|
||||
raise ValueError("DATABASE_CA_FILE is required for verified PostgreSQL TLS")
|
||||
tls = ssl.create_default_context(cafile=ca_file)
|
||||
self._pool = await asyncpg.create_pool(
|
||||
self._database_url, min_size=1, max_size=10, command_timeout=5
|
||||
self._database_url, min_size=1, max_size=10, command_timeout=5, ssl=tls
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
+4
-1
@@ -36,7 +36,10 @@ class S3Settings:
|
||||
max_pixels = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||
if not 1 <= max_bytes <= 10485760 or not 1 <= max_pixels <= 40000000:
|
||||
raise ValueError("Image limits exceed contract")
|
||||
return cls(os.environ.get("S3_ENDPOINT", "http://s3:8333"),
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "https://s3:8333")
|
||||
if not endpoint.startswith("https://") or not os.environ.get("AWS_CA_BUNDLE"):
|
||||
raise ValueError("S3 requires HTTPS and AWS_CA_BUNDLE")
|
||||
return cls(endpoint,
|
||||
os.environ.get("S3_REGION", "us-east-1"),
|
||||
os.environ.get("S3_BUCKET", "messenger-attachments"),
|
||||
secret("S3_ACCESS_KEY_ID"), secret("S3_SECRET_ACCESS_KEY"),
|
||||
|
||||
Reference in New Issue
Block a user