forked from cartsnitch/cartsnitch
Compare commits
47 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c715c0e47a | |||
| c968088a3f | |||
| bb50ddc85d | |||
| bd2e8feff6 | |||
| 2b32bfdfe1 | |||
| 1e8223caeb | |||
| e1d77d7789 | |||
| 16200c5500 | |||
| 1803d09095 | |||
| 8592701382 | |||
| 17447fb5e1 | |||
| e29bad9a39 | |||
| 349b519a00 | |||
| b274fdff8e | |||
| a64dc7ab5e | |||
| 7fc524b593 | |||
| 0fb99e6c16 | |||
| a53daddb9a | |||
| 4e139dc4b6 | |||
| 3351d74058 | |||
| 6481cf03e4 | |||
| 37c75c3887 | |||
| 8a0b2c03a1 | |||
| aa893d9cc1 | |||
| 91c062130c | |||
| 0aef2455fd | |||
| 6602b8c105 | |||
| dbbc8d2e7b | |||
| 1267caf43c | |||
| 015401861a | |||
| 9891e1aefb | |||
| 69ad161e36 | |||
| 485f890df3 | |||
| bf3ed0ede3 | |||
| 3f41eb7346 | |||
| 6cbd1ef298 | |||
| 94214f762e | |||
| 562c6ef6f6 | |||
| ccc8189d88 | |||
| 86594e4a8e | |||
| c2f1a83c1d | |||
| 6f8e5a9577 | |||
| bbfa816e57 | |||
| 5904eb03a2 | |||
| 87b6433ff7 | |||
| d7c9938f7e | |||
| 02434060ee |
+123
-8
@@ -13,6 +13,7 @@ concurrency:
|
|||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
packages: write
|
packages: write
|
||||||
|
security-events: write
|
||||||
|
|
||||||
env:
|
env:
|
||||||
REGISTRY: ghcr.io
|
REGISTRY: ghcr.io
|
||||||
@@ -151,17 +152,44 @@ jobs:
|
|||||||
type=raw,value=${{ steps.calver.outputs.version }},enable=${{ github.ref == 'refs/heads/main' }}
|
type=raw,value=${{ steps.calver.outputs.version }},enable=${{ github.ref == 'refs/heads/main' }}
|
||||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||||
|
|
||||||
- name: Build and push Docker image
|
- name: Build Docker image
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
push: ${{ github.event_name == 'push' }}
|
load: true
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
target: prod
|
target: prod
|
||||||
cache-from: type=gha
|
cache-from: type=gha
|
||||||
cache-to: type=gha,mode=max
|
cache-to: type=gha,mode=max
|
||||||
|
|
||||||
|
- name: Scan frontend image for vulnerabilities
|
||||||
|
uses: anchore/scan-action@v5
|
||||||
|
id: scan
|
||||||
|
with:
|
||||||
|
image: "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:sha-${{ github.sha }}"
|
||||||
|
fail-build: true
|
||||||
|
severity-cutoff: high
|
||||||
|
only-fixed: "true"
|
||||||
|
output-format: sarif
|
||||||
|
|
||||||
|
- name: Upload frontend scan results to GitHub Security
|
||||||
|
uses: github/codeql-action/upload-sarif@v3
|
||||||
|
if: always()
|
||||||
|
with:
|
||||||
|
sarif_file: ${{ steps.scan.outputs.sarif }}
|
||||||
|
|
||||||
|
- name: Push Docker image
|
||||||
|
if: github.event_name == 'push'
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
target: prod
|
||||||
|
cache-from: type=gha
|
||||||
|
|
||||||
- name: Create git tag
|
- name: Create git tag
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
run: |
|
run: |
|
||||||
@@ -221,14 +249,43 @@ jobs:
|
|||||||
type=raw,value=${{ steps.calver.outputs.version }},enable=${{ github.ref == 'refs/heads/main' }}
|
type=raw,value=${{ steps.calver.outputs.version }},enable=${{ github.ref == 'refs/heads/main' }}
|
||||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||||
|
|
||||||
- name: Build and push auth Docker image
|
- name: Build Docker image
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: ./auth
|
context: ./auth
|
||||||
file: ./auth/Dockerfile
|
file: ./auth/Dockerfile
|
||||||
push: ${{ github.event_name == 'push' }}
|
load: true
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
|
||||||
|
- name: Scan auth image for vulnerabilities
|
||||||
|
uses: anchore/scan-action@v5
|
||||||
|
id: scan
|
||||||
|
with:
|
||||||
|
image: "${{ env.REGISTRY }}/${{ env.AUTH_IMAGE_NAME }}:sha-${{ github.sha }}"
|
||||||
|
fail-build: true
|
||||||
|
severity-cutoff: high
|
||||||
|
only-fixed: "true"
|
||||||
|
output-format: sarif
|
||||||
|
|
||||||
|
- name: Upload auth scan results to GitHub Security
|
||||||
|
uses: github/codeql-action/upload-sarif@v3
|
||||||
|
if: always()
|
||||||
|
with:
|
||||||
|
sarif_file: ${{ steps.scan.outputs.sarif }}
|
||||||
|
|
||||||
|
- name: Push Docker image
|
||||||
|
if: github.event_name == 'push'
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: ./auth
|
||||||
|
file: ./auth/Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
cache-from: type=gha
|
||||||
|
|
||||||
build-and-push-receiptwitness:
|
build-and-push-receiptwitness:
|
||||||
runs-on: runners-cartsnitch
|
runs-on: runners-cartsnitch
|
||||||
@@ -278,14 +335,43 @@ jobs:
|
|||||||
type=raw,value=${{ steps.calver.outputs.version }},enable=${{ github.ref == 'refs/heads/main' }}
|
type=raw,value=${{ steps.calver.outputs.version }},enable=${{ github.ref == 'refs/heads/main' }}
|
||||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||||
|
|
||||||
- name: Build and push receiptwitness image
|
- name: Build Docker image
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: ./receiptwitness/Dockerfile
|
file: ./receiptwitness/Dockerfile
|
||||||
push: ${{ github.event_name == 'push' }}
|
load: true
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
|
||||||
|
- name: Scan receiptwitness image for vulnerabilities
|
||||||
|
uses: anchore/scan-action@v5
|
||||||
|
id: scan
|
||||||
|
with:
|
||||||
|
image: "${{ env.REGISTRY }}/${{ env.RECEIPTWITNESS_IMAGE_NAME }}:sha-${{ github.sha }}"
|
||||||
|
fail-build: true
|
||||||
|
severity-cutoff: high
|
||||||
|
only-fixed: "true"
|
||||||
|
output-format: sarif
|
||||||
|
|
||||||
|
- name: Upload receiptwitness scan results to GitHub Security
|
||||||
|
uses: github/codeql-action/upload-sarif@v3
|
||||||
|
if: always()
|
||||||
|
with:
|
||||||
|
sarif_file: ${{ steps.scan.outputs.sarif }}
|
||||||
|
|
||||||
|
- name: Push Docker image
|
||||||
|
if: github.event_name == 'push'
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./receiptwitness/Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
cache-from: type=gha
|
||||||
|
|
||||||
build-and-push-api:
|
build-and-push-api:
|
||||||
runs-on: runners-cartsnitch
|
runs-on: runners-cartsnitch
|
||||||
@@ -335,14 +421,43 @@ jobs:
|
|||||||
type=raw,value=${{ steps.calver.outputs.version }},enable=${{ github.ref == 'refs/heads/main' }}
|
type=raw,value=${{ steps.calver.outputs.version }},enable=${{ github.ref == 'refs/heads/main' }}
|
||||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||||
|
|
||||||
- name: Build and push API Docker image
|
- name: Build Docker image
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: ./api
|
context: ./api
|
||||||
file: ./api/Dockerfile
|
file: ./api/Dockerfile
|
||||||
push: ${{ github.event_name == 'push' }}
|
load: true
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
|
||||||
|
- name: Scan api image for vulnerabilities
|
||||||
|
uses: anchore/scan-action@v5
|
||||||
|
id: scan
|
||||||
|
with:
|
||||||
|
image: "${{ env.REGISTRY }}/${{ env.API_IMAGE_NAME }}:sha-${{ github.sha }}"
|
||||||
|
fail-build: true
|
||||||
|
severity-cutoff: high
|
||||||
|
only-fixed: "true"
|
||||||
|
output-format: sarif
|
||||||
|
|
||||||
|
- name: Upload api scan results to GitHub Security
|
||||||
|
uses: github/codeql-action/upload-sarif@v3
|
||||||
|
if: always()
|
||||||
|
with:
|
||||||
|
sarif_file: ${{ steps.scan.outputs.sarif }}
|
||||||
|
|
||||||
|
- name: Push Docker image
|
||||||
|
if: github.event_name == 'push'
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: ./api
|
||||||
|
file: ./api/Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
cache-from: type=gha
|
||||||
|
|
||||||
deploy-dev:
|
deploy-dev:
|
||||||
runs-on: runners-cartsnitch
|
runs-on: runners-cartsnitch
|
||||||
|
|||||||
+4
-1
@@ -1,6 +1,6 @@
|
|||||||
# Stage 1: Build
|
# Stage 1: Build
|
||||||
FROM node:20-alpine AS build
|
FROM node:20-alpine AS build
|
||||||
|
RUN apk update && apk upgrade --no-cache
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
@@ -11,6 +11,9 @@ RUN npm run build
|
|||||||
|
|
||||||
# Stage 2: Production — uses nginxinc/nginx-unprivileged which runs as non-root (UID 101)
|
# Stage 2: Production — uses nginxinc/nginx-unprivileged which runs as non-root (UID 101)
|
||||||
FROM nginxinc/nginx-unprivileged:stable-alpine AS prod
|
FROM nginxinc/nginx-unprivileged:stable-alpine AS prod
|
||||||
|
USER root
|
||||||
|
RUN apk update && apk upgrade --no-cache
|
||||||
|
USER 101
|
||||||
|
|
||||||
COPY --from=build /app/dist /usr/share/nginx/html
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
FROM python:3.12-slim AS build
|
FROM python:3.12-slim AS build
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends \
|
||||||
libpq-dev \
|
libpq-dev \
|
||||||
build-essential \
|
build-essential \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
@@ -12,7 +12,7 @@ RUN pip install --no-cache-dir --prefix=/install .
|
|||||||
|
|
||||||
FROM python:3.12-slim AS prod
|
FROM python:3.12-slim AS prod
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends libpq5 && rm -rf /var/lib/apt/lists/*
|
RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends libpq5 && rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
RUN adduser --system --group --uid 1000 app
|
RUN adduser --system --group --uid 1000 app
|
||||||
|
|||||||
@@ -32,9 +32,6 @@ class Settings(BaseSettings):
|
|||||||
|
|
||||||
rate_limit_requests: int = 60
|
rate_limit_requests: int = 60
|
||||||
rate_limit_window_seconds: int = 60
|
rate_limit_window_seconds: int = 60
|
||||||
rate_limit_auth_requests: int = 5
|
|
||||||
rate_limit_auth_window_seconds: int = 60
|
|
||||||
rate_limit_redis_enabled: bool = True
|
|
||||||
rate_limit_enabled: bool = True
|
rate_limit_enabled: bool = True
|
||||||
|
|
||||||
_PLACEHOLDER_VALUES = {"change-me-in-production"}
|
_PLACEHOLDER_VALUES = {"change-me-in-production"}
|
||||||
@@ -75,9 +72,7 @@ class Settings(BaseSettings):
|
|||||||
def normalize_database_url(self):
|
def normalize_database_url(self):
|
||||||
"""Normalize postgresql:// → postgresql+asyncpg:// for the asyncpg driver."""
|
"""Normalize postgresql:// → postgresql+asyncpg:// for the asyncpg driver."""
|
||||||
if self.database_url.startswith("postgresql://"):
|
if self.database_url.startswith("postgresql://"):
|
||||||
self.database_url = self.database_url.replace(
|
self.database_url = self.database_url.replace("postgresql://", "postgresql+asyncpg://", 1)
|
||||||
"postgresql://", "postgresql+asyncpg://", 1
|
|
||||||
)
|
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,31 +5,18 @@ Per-IP limiting on public endpoints, per-token limiting on authenticated endpoin
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
import logging
|
|
||||||
import time
|
import time
|
||||||
import uuid
|
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
from typing import Protocol
|
|
||||||
|
|
||||||
from fastapi import FastAPI, Request, status
|
from fastapi import FastAPI, Request, status
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from redis.asyncio import Redis, RedisError
|
|
||||||
from starlette.middleware.base import BaseHTTPMiddleware
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
|
||||||
from cartsnitch_api.config import settings
|
from cartsnitch_api.config import settings
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
class _SlidingWindowCounter:
|
||||||
class RateLimitBackend(Protocol):
|
|
||||||
"""Protocol for rate limit backends."""
|
|
||||||
|
|
||||||
async def is_allowed(self, key: str) -> tuple[bool, int, int]:
|
|
||||||
"""Check if request is allowed. Returns (allowed, remaining, retry_after)."""
|
|
||||||
|
|
||||||
|
|
||||||
class InMemorySlidingWindow:
|
|
||||||
"""Thread-safe in-memory sliding window rate limiter."""
|
"""Thread-safe in-memory sliding window rate limiter."""
|
||||||
|
|
||||||
def __init__(self, max_requests: int, window_seconds: int) -> None:
|
def __init__(self, max_requests: int, window_seconds: int) -> None:
|
||||||
@@ -38,12 +25,13 @@ class InMemorySlidingWindow:
|
|||||||
self._hits: dict[str, list[float]] = defaultdict(list)
|
self._hits: dict[str, list[float]] = defaultdict(list)
|
||||||
self._lock = Lock()
|
self._lock = Lock()
|
||||||
|
|
||||||
async def is_allowed(self, key: str) -> tuple[bool, int, int]:
|
def is_allowed(self, key: str) -> tuple[bool, int, int]:
|
||||||
"""Check if request is allowed. Returns (allowed, remaining, retry_after)."""
|
"""Check if request is allowed. Returns (allowed, remaining, retry_after)."""
|
||||||
now = time.monotonic()
|
now = time.monotonic()
|
||||||
cutoff = now - self.window_seconds
|
cutoff = now - self.window_seconds
|
||||||
|
|
||||||
with self._lock:
|
with self._lock:
|
||||||
|
# Prune expired entries
|
||||||
self._hits[key] = [t for t in self._hits[key] if t > cutoff]
|
self._hits[key] = [t for t in self._hits[key] if t > cutoff]
|
||||||
|
|
||||||
current_count = len(self._hits[key])
|
current_count = len(self._hits[key])
|
||||||
@@ -56,84 +44,15 @@ class InMemorySlidingWindow:
|
|||||||
return True, remaining, 0
|
return True, remaining, 0
|
||||||
|
|
||||||
|
|
||||||
class RedisSlidingWindow:
|
# Module-level counters — one for public (per-IP), one for auth (per-token)
|
||||||
"""Redis-backed sliding window rate limiter using sorted sets."""
|
_public_limiter = _SlidingWindowCounter(
|
||||||
|
max_requests=settings.rate_limit_requests,
|
||||||
def __init__(self, redis: Redis, max_requests: int, window_seconds: int) -> None:
|
window_seconds=settings.rate_limit_window_seconds,
|
||||||
self.redis = redis
|
)
|
||||||
self.max_requests = max_requests
|
_auth_limiter = _SlidingWindowCounter(
|
||||||
self.window_seconds = window_seconds
|
max_requests=settings.rate_limit_requests * 5, # 300/min for authenticated users
|
||||||
|
window_seconds=settings.rate_limit_window_seconds,
|
||||||
async def is_allowed(self, key: str) -> tuple[bool, int, int]:
|
)
|
||||||
"""Check if request is allowed. Returns (allowed, remaining, retry_after)."""
|
|
||||||
try:
|
|
||||||
now = time.monotonic()
|
|
||||||
cutoff = now - self.window_seconds
|
|
||||||
now_ms = int(now * 1000)
|
|
||||||
cutoff_ms = int(cutoff * 1000)
|
|
||||||
|
|
||||||
pipe = self.redis.pipeline()
|
|
||||||
pipe.zremrangebyscore(key, 0, cutoff_ms)
|
|
||||||
pipe.zcard(key)
|
|
||||||
results = await pipe.execute()
|
|
||||||
|
|
||||||
current_count = results[1]
|
|
||||||
|
|
||||||
if current_count >= self.max_requests:
|
|
||||||
oldest = await self.redis.zrange(key, 0, 0, withscores=True)
|
|
||||||
if oldest:
|
|
||||||
retry_after = int((oldest[0][1] - cutoff) / 1000) + 1
|
|
||||||
else:
|
|
||||||
retry_after = self.window_seconds
|
|
||||||
return False, 0, retry_after
|
|
||||||
|
|
||||||
member = f"{now_ms}:{uuid.uuid4().hex[:8]}"
|
|
||||||
pipe = self.redis.pipeline()
|
|
||||||
pipe.zadd(key, {member: now_ms})
|
|
||||||
pipe.expire(key, self.window_seconds)
|
|
||||||
await pipe.execute()
|
|
||||||
|
|
||||||
remaining = self.max_requests - current_count - 1
|
|
||||||
return True, remaining, 0
|
|
||||||
|
|
||||||
except RedisError as e:
|
|
||||||
logger.warning("Redis rate limit error, falling back to in-memory: %s", e)
|
|
||||||
in_memory = InMemorySlidingWindow(self.max_requests, self.window_seconds)
|
|
||||||
return await in_memory.is_allowed(key)
|
|
||||||
|
|
||||||
|
|
||||||
_redis_client: Redis | None = None
|
|
||||||
_use_redis = False
|
|
||||||
|
|
||||||
if settings.rate_limit_redis_enabled:
|
|
||||||
try:
|
|
||||||
_redis_client = Redis.from_url(settings.redis_url)
|
|
||||||
_use_redis = True
|
|
||||||
logger.info("Rate limiting will use Redis at %s", settings.redis_url)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("Failed to connect to Redis for rate limiting, using in-memory: %s", e)
|
|
||||||
_use_redis = False
|
|
||||||
|
|
||||||
if _use_redis and _redis_client:
|
|
||||||
_public_limiter = RedisSlidingWindow(
|
|
||||||
_redis_client, settings.rate_limit_requests, settings.rate_limit_window_seconds
|
|
||||||
)
|
|
||||||
_auth_limiter = RedisSlidingWindow(
|
|
||||||
_redis_client, settings.rate_limit_requests * 5, settings.rate_limit_window_seconds
|
|
||||||
)
|
|
||||||
_auth_strict_limiter = RedisSlidingWindow(
|
|
||||||
_redis_client, settings.rate_limit_auth_requests, settings.rate_limit_auth_window_seconds
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
_public_limiter = InMemorySlidingWindow(
|
|
||||||
settings.rate_limit_requests, settings.rate_limit_window_seconds
|
|
||||||
)
|
|
||||||
_auth_limiter = InMemorySlidingWindow(
|
|
||||||
settings.rate_limit_requests * 5, settings.rate_limit_window_seconds
|
|
||||||
)
|
|
||||||
_auth_strict_limiter = InMemorySlidingWindow(
|
|
||||||
settings.rate_limit_auth_requests, settings.rate_limit_auth_window_seconds
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _get_client_ip(request: Request) -> str:
|
def _get_client_ip(request: Request) -> str:
|
||||||
@@ -144,30 +63,30 @@ def _get_client_ip(request: Request) -> str:
|
|||||||
return request.client.host if request.client else "unknown"
|
return request.client.host if request.client else "unknown"
|
||||||
|
|
||||||
|
|
||||||
def _get_rate_limit_key(request: Request) -> tuple[str, RateLimitBackend]:
|
def _get_rate_limit_key(request: Request) -> tuple[str, _SlidingWindowCounter]:
|
||||||
"""Determine rate limit key and which limiter to use."""
|
"""Determine rate limit key and which limiter to use."""
|
||||||
if request.url.path.startswith("/public"):
|
if request.url.path.startswith("/public"):
|
||||||
return f"ip:{_get_client_ip(request)}", _public_limiter
|
return f"ip:{_get_client_ip(request)}", _public_limiter
|
||||||
|
|
||||||
if request.url.path.startswith("/auth/") and request.method == "POST":
|
# For authenticated endpoints, use Bearer token as key if present
|
||||||
return f"ip:{_get_client_ip(request)}", _auth_strict_limiter
|
|
||||||
|
|
||||||
auth_header = request.headers.get("authorization", "")
|
auth_header = request.headers.get("authorization", "")
|
||||||
if auth_header.startswith("Bearer "):
|
if auth_header.startswith("Bearer "):
|
||||||
token = auth_header[7:]
|
token = auth_header[7:]
|
||||||
token_hash = hashlib.sha256(token.encode()).hexdigest()
|
token_hash = hashlib.sha256(token.encode()).hexdigest()
|
||||||
return f"token:{token_hash}", _auth_limiter
|
return f"token:{token_hash}", _auth_limiter
|
||||||
|
|
||||||
|
# Fallback to IP for unauthenticated non-public endpoints
|
||||||
return f"ip:{_get_client_ip(request)}", _public_limiter
|
return f"ip:{_get_client_ip(request)}", _public_limiter
|
||||||
|
|
||||||
|
|
||||||
class RateLimitMiddleware(BaseHTTPMiddleware):
|
class RateLimitMiddleware(BaseHTTPMiddleware):
|
||||||
async def dispatch(self, request: Request, call_next):
|
async def dispatch(self, request: Request, call_next):
|
||||||
|
# Skip rate limiting when disabled (e.g. in tests) or for health checks
|
||||||
if not settings.rate_limit_enabled or request.url.path == "/health":
|
if not settings.rate_limit_enabled or request.url.path == "/health":
|
||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
key, limiter = _get_rate_limit_key(request)
|
key, limiter = _get_rate_limit_key(request)
|
||||||
allowed, remaining, retry_after = await limiter.is_allowed(key)
|
allowed, remaining, retry_after = limiter.is_allowed(key)
|
||||||
|
|
||||||
if not allowed:
|
if not allowed:
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
|
|||||||
@@ -1,184 +1,49 @@
|
|||||||
"""Tests for rate limiting middleware."""
|
"""Tests for rate limiting middleware."""
|
||||||
|
|
||||||
import time
|
from unittest.mock import MagicMock
|
||||||
from unittest.mock import AsyncMock, MagicMock, patch
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from cartsnitch_api.config import settings
|
from cartsnitch_api.middleware.rate_limit import _SlidingWindowCounter, _get_rate_limit_key
|
||||||
from cartsnitch_api.middleware.rate_limit import (
|
|
||||||
InMemorySlidingWindow,
|
|
||||||
RedisSlidingWindow,
|
|
||||||
_get_client_ip,
|
|
||||||
_get_rate_limit_key,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestInMemorySlidingWindow:
|
class TestSlidingWindowCounter:
|
||||||
def test_allows_within_limit(self):
|
def test_allows_within_limit(self):
|
||||||
limiter = InMemorySlidingWindow(max_requests=5, window_seconds=60)
|
counter = _SlidingWindowCounter(max_requests=5, window_seconds=60)
|
||||||
for i in range(5):
|
for i in range(5):
|
||||||
allowed, remaining, retry = limiter.is_allowed("test-key")
|
allowed, remaining, retry = counter.is_allowed("test-key")
|
||||||
assert allowed is True
|
assert allowed is True
|
||||||
assert remaining == 4 - i
|
assert remaining == 4 - i
|
||||||
|
|
||||||
def test_blocks_over_limit(self):
|
def test_blocks_over_limit(self):
|
||||||
limiter = InMemorySlidingWindow(max_requests=3, window_seconds=60)
|
counter = _SlidingWindowCounter(max_requests=3, window_seconds=60)
|
||||||
for _ in range(3):
|
for _ in range(3):
|
||||||
limiter.is_allowed("test-key")
|
counter.is_allowed("test-key")
|
||||||
|
|
||||||
allowed, remaining, retry = limiter.is_allowed("test-key")
|
allowed, remaining, retry = counter.is_allowed("test-key")
|
||||||
assert allowed is False
|
assert allowed is False
|
||||||
assert remaining == 0
|
assert remaining == 0
|
||||||
assert retry > 0
|
assert retry > 0
|
||||||
|
|
||||||
def test_separate_keys(self):
|
def test_separate_keys(self):
|
||||||
limiter = InMemorySlidingWindow(max_requests=2, window_seconds=60)
|
counter = _SlidingWindowCounter(max_requests=2, window_seconds=60)
|
||||||
limiter.is_allowed("key-a")
|
# Fill key-a
|
||||||
limiter.is_allowed("key-a")
|
counter.is_allowed("key-a")
|
||||||
allowed_a, _, _ = limiter.is_allowed("key-a")
|
counter.is_allowed("key-a")
|
||||||
|
allowed_a, _, _ = counter.is_allowed("key-a")
|
||||||
assert allowed_a is False
|
assert allowed_a is False
|
||||||
|
|
||||||
allowed_b, remaining, _ = limiter.is_allowed("key-b")
|
# key-b should still be allowed
|
||||||
|
allowed_b, remaining, _ = counter.is_allowed("key-b")
|
||||||
assert allowed_b is True
|
assert allowed_b is True
|
||||||
assert remaining == 1
|
assert remaining == 1
|
||||||
|
|
||||||
def test_resets_after_window_expires(self):
|
|
||||||
limiter = InMemorySlidingWindow(max_requests=2, window_seconds=1)
|
|
||||||
for _ in range(2):
|
|
||||||
limiter.is_allowed("test-key")
|
|
||||||
allowed, remaining, _ = limiter.is_allowed("test-key")
|
|
||||||
assert allowed is False
|
|
||||||
|
|
||||||
time.sleep(1.1)
|
|
||||||
allowed, remaining, _ = limiter.is_allowed("test-key")
|
|
||||||
assert allowed is True
|
|
||||||
assert remaining == 1
|
|
||||||
|
|
||||||
|
|
||||||
class TestGetClientIp:
|
|
||||||
def test_x_forwarded_for_single(self):
|
|
||||||
req = MagicMock()
|
|
||||||
req.headers = {"x-forwarded-for": "192.168.1.1"}
|
|
||||||
req.client = None
|
|
||||||
assert _get_client_ip(req) == "192.168.1.1"
|
|
||||||
|
|
||||||
def test_x_forwarded_for_multiple(self):
|
|
||||||
req = MagicMock()
|
|
||||||
req.headers = {"x-forwarded-for": "192.168.1.1, 10.0.0.1, 172.16.0.1"}
|
|
||||||
req.client = None
|
|
||||||
assert _get_client_ip(req) == "192.168.1.1"
|
|
||||||
|
|
||||||
def test_x_forwarded_for_with_port(self):
|
|
||||||
req = MagicMock()
|
|
||||||
req.headers = {"x-forwarded-for": "192.168.1.1:8080"}
|
|
||||||
req.client = None
|
|
||||||
assert _get_client_ip(req) == "192.168.1.1"
|
|
||||||
|
|
||||||
def test_no_forwarded_header(self):
|
|
||||||
req = MagicMock()
|
|
||||||
req.headers = {}
|
|
||||||
req.client.host = "127.0.0.1"
|
|
||||||
assert _get_client_ip(req) == "127.0.0.1"
|
|
||||||
|
|
||||||
def test_no_client(self):
|
|
||||||
req = MagicMock()
|
|
||||||
req.headers = {}
|
|
||||||
req.client = None
|
|
||||||
assert _get_client_ip(req) == "unknown"
|
|
||||||
|
|
||||||
|
|
||||||
class TestGetRateLimitKey:
|
|
||||||
def _make_request(
|
|
||||||
self,
|
|
||||||
path: str = "/purchases",
|
|
||||||
method: str = "GET",
|
|
||||||
auth_header: str = "",
|
|
||||||
headers: dict | None = None,
|
|
||||||
) -> MagicMock:
|
|
||||||
req = MagicMock()
|
|
||||||
req.url.path = path
|
|
||||||
req.method = method
|
|
||||||
req.headers = dict(headers) if headers else {}
|
|
||||||
if auth_header:
|
|
||||||
req.headers["authorization"] = auth_header
|
|
||||||
return req
|
|
||||||
|
|
||||||
def test_public_path_uses_public_limiter(self):
|
|
||||||
req = self._make_request("/public/inflation")
|
|
||||||
key, limiter = _get_rate_limit_key(req)
|
|
||||||
assert key.startswith("ip:")
|
|
||||||
assert limiter.max_requests == settings.rate_limit_requests
|
|
||||||
|
|
||||||
def test_auth_post_path_uses_strict_limiter(self):
|
|
||||||
req = self._make_request("/auth/login", method="POST")
|
|
||||||
key, limiter = _get_rate_limit_key(req)
|
|
||||||
assert key.startswith("ip:")
|
|
||||||
assert limiter.max_requests == settings.rate_limit_auth_requests
|
|
||||||
assert limiter.window_seconds == settings.rate_limit_auth_window_seconds
|
|
||||||
|
|
||||||
def test_auth_get_path_uses_auth_limiter(self):
|
|
||||||
req = self._make_request("/auth/me", method="GET")
|
|
||||||
key, limiter = _get_rate_limit_key(req)
|
|
||||||
assert key.startswith("ip:")
|
|
||||||
assert limiter.max_requests == settings.rate_limit_requests * 5
|
|
||||||
|
|
||||||
def test_authenticated_token_uses_auth_limiter(self):
|
|
||||||
req = self._make_request("/purchases", auth_header="Bearer token123")
|
|
||||||
key, limiter = _get_rate_limit_key(req)
|
|
||||||
assert key.startswith("token:")
|
|
||||||
assert limiter.max_requests == settings.rate_limit_requests * 5
|
|
||||||
|
|
||||||
def test_distinct_tokens_produce_distinct_keys(self):
|
|
||||||
req1 = self._make_request("/purchases", auth_header="Bearer token_alpha_12345")
|
|
||||||
req2 = self._make_request("/purchases", auth_header="Bearer token_beta_67890")
|
|
||||||
key1, _ = _get_rate_limit_key(req1)
|
|
||||||
key2, _ = _get_rate_limit_key(req2)
|
|
||||||
assert key1 != key2
|
|
||||||
|
|
||||||
def test_same_token_produces_same_key(self):
|
|
||||||
req1 = self._make_request("/purchases", auth_header="Bearer same_token_value_abc")
|
|
||||||
req2 = self._make_request("/purchases", auth_header="Bearer same_token_value_abc")
|
|
||||||
key1, _ = _get_rate_limit_key(req1)
|
|
||||||
key2, _ = _get_rate_limit_key(req2)
|
|
||||||
assert key1 == key2
|
|
||||||
|
|
||||||
def test_key_does_not_contain_raw_token_suffix(self):
|
|
||||||
raw_token = "my_secret_jwt_token_xyz"
|
|
||||||
req = self._make_request("/purchases", auth_header=f"Bearer {raw_token}")
|
|
||||||
key, _ = _get_rate_limit_key(req)
|
|
||||||
assert raw_token[-16:] not in key
|
|
||||||
assert raw_token not in key
|
|
||||||
|
|
||||||
|
|
||||||
class TestRedisSlidingWindowFallback:
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_fallback_on_redis_connection_error(self):
|
|
||||||
mock_redis = AsyncMock()
|
|
||||||
mock_redis.pipeline.return_value = AsyncMock()
|
|
||||||
pipe_mock = AsyncMock()
|
|
||||||
pipe_mock.execute.side_effect = Exception("Connection refused")
|
|
||||||
mock_redis.pipeline.return_value = pipe_mock
|
|
||||||
|
|
||||||
limiter = RedisSlidingWindow(mock_redis, max_requests=5, window_seconds=60)
|
|
||||||
allowed, remaining, retry = await limiter.is_allowed("test-key")
|
|
||||||
assert allowed is True
|
|
||||||
assert remaining == 4
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_fallback_on_redis_error_during_pipeline(self):
|
|
||||||
mock_redis = AsyncMock()
|
|
||||||
pipe_mock = AsyncMock()
|
|
||||||
pipe_mock.execute.side_effect = Exception("Redis error")
|
|
||||||
mock_redis.pipeline.return_value = pipe_mock
|
|
||||||
|
|
||||||
limiter = RedisSlidingWindow(mock_redis, max_requests=3, window_seconds=60)
|
|
||||||
allowed, remaining, retry = await limiter.is_allowed("test-key")
|
|
||||||
assert allowed is True
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_rate_limit_returns_429(client):
|
async def test_rate_limit_returns_429(client):
|
||||||
|
"""Public endpoint should return 429 after limit exceeded."""
|
||||||
|
# The default limit is 60/min — we won't hit it in normal tests,
|
||||||
|
# but we verify the middleware adds rate limit headers.
|
||||||
resp = await client.get("/public/inflation")
|
resp = await client.get("/public/inflation")
|
||||||
assert "x-ratelimit-limit" in resp.headers
|
assert "x-ratelimit-limit" in resp.headers
|
||||||
assert "x-ratelimit-remaining" in resp.headers
|
assert "x-ratelimit-remaining" in resp.headers
|
||||||
@@ -186,6 +51,36 @@ async def test_rate_limit_returns_429(client):
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_health_skips_rate_limit(client):
|
async def test_health_skips_rate_limit(client):
|
||||||
|
"""Health endpoint should not have rate limit headers."""
|
||||||
resp = await client.get("/health")
|
resp = await client.get("/health")
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
assert "x-ratelimit-limit" not in resp.headers
|
assert "x-ratelimit-limit" not in resp.headers
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetRateLimitKey:
|
||||||
|
def _make_request(self, auth_header: str = "") -> MagicMock:
|
||||||
|
req = MagicMock()
|
||||||
|
req.url.path = "/purchases"
|
||||||
|
req.headers = {"authorization": auth_header} if auth_header else {}
|
||||||
|
return req
|
||||||
|
|
||||||
|
def test_distinct_tokens_produce_distinct_keys(self):
|
||||||
|
req1 = self._make_request("Bearer token_alpha_12345")
|
||||||
|
req2 = self._make_request("Bearer token_beta_67890")
|
||||||
|
key1, _ = _get_rate_limit_key(req1)
|
||||||
|
key2, _ = _get_rate_limit_key(req2)
|
||||||
|
assert key1 != key2
|
||||||
|
|
||||||
|
def test_same_token_produces_same_key(self):
|
||||||
|
req1 = self._make_request("Bearer same_token_value_abc")
|
||||||
|
req2 = self._make_request("Bearer same_token_value_abc")
|
||||||
|
key1, _ = _get_rate_limit_key(req1)
|
||||||
|
key2, _ = _get_rate_limit_key(req2)
|
||||||
|
assert key1 == key2
|
||||||
|
|
||||||
|
def test_key_does_not_contain_raw_token_suffix(self):
|
||||||
|
raw_token = "my_secret_jwt_token_xyz"
|
||||||
|
req = self._make_request(f"Bearer {raw_token}")
|
||||||
|
key, _ = _get_rate_limit_key(req)
|
||||||
|
assert raw_token[-16:] not in key
|
||||||
|
assert raw_token not in key
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
FROM node:22-alpine AS builder
|
FROM node:22-alpine AS builder
|
||||||
|
RUN apk update && apk upgrade --no-cache
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json package-lock.json* ./
|
COPY package.json package-lock.json* ./
|
||||||
RUN npm ci
|
RUN npm ci
|
||||||
@@ -7,6 +8,7 @@ COPY src/ src/
|
|||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
FROM node:22-alpine
|
FROM node:22-alpine
|
||||||
|
RUN apk update && apk upgrade --no-cache
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
COPY package.json package-lock.json* ./
|
COPY package.json package-lock.json* ./
|
||||||
|
|||||||
Generated
+3
-3
@@ -941,9 +941,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/defu": {
|
"node_modules/defu": {
|
||||||
"version": "6.1.4",
|
"version": "6.1.7",
|
||||||
"resolved": "https://registry.npmjs.org/defu/-/defu-6.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz",
|
||||||
"integrity": "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==",
|
"integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/delegates": {
|
"node_modules/delegates": {
|
||||||
|
|||||||
+12
-6
@@ -4,17 +4,23 @@ import pg from "pg";
|
|||||||
|
|
||||||
const { Pool } = pg;
|
const { Pool } = pg;
|
||||||
|
|
||||||
const pool = new Pool({
|
|
||||||
connectionString:
|
|
||||||
process.env.DATABASE_URL ??
|
|
||||||
"postgresql://cartsnitch:cartsnitch@localhost:5432/cartsnitch",
|
|
||||||
});
|
|
||||||
|
|
||||||
const secret = process.env.BETTER_AUTH_SECRET;
|
const secret = process.env.BETTER_AUTH_SECRET;
|
||||||
if (!secret) {
|
if (!secret) {
|
||||||
throw new Error("BETTER_AUTH_SECRET environment variable is required");
|
throw new Error("BETTER_AUTH_SECRET environment variable is required");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const databaseUrl = process.env.DATABASE_URL;
|
||||||
|
if (!databaseUrl) {
|
||||||
|
console.warn(
|
||||||
|
"WARNING: DATABASE_URL is not set — using default localhost connection. " +
|
||||||
|
"Set DATABASE_URL for production deployments."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const pool = new Pool({
|
||||||
|
connectionString: databaseUrl ?? "postgresql://cartsnitch:cartsnitch@localhost:5432/cartsnitch",
|
||||||
|
});
|
||||||
|
|
||||||
export const auth = betterAuth({
|
export const auth = betterAuth({
|
||||||
database: pool,
|
database: pool,
|
||||||
basePath: "/auth",
|
basePath: "/auth",
|
||||||
|
|||||||
+17
-3
@@ -1,6 +1,6 @@
|
|||||||
import { createServer } from "node:http";
|
import { createServer } from "node:http";
|
||||||
import { toNodeHandler } from "better-auth/node";
|
import { toNodeHandler } from "better-auth/node";
|
||||||
import { auth } from "./auth.js";
|
import { auth, pool } from "./auth.js";
|
||||||
|
|
||||||
const port = parseInt(process.env.PORT ?? "3001", 10);
|
const port = parseInt(process.env.PORT ?? "3001", 10);
|
||||||
|
|
||||||
@@ -9,8 +9,22 @@ const handler = toNodeHandler(auth);
|
|||||||
const server = createServer(async (req, res) => {
|
const server = createServer(async (req, res) => {
|
||||||
// Health check
|
// Health check
|
||||||
if (req.url === "/health" && req.method === "GET") {
|
if (req.url === "/health" && req.method === "GET") {
|
||||||
res.writeHead(200, { "Content-Type": "application/json" });
|
try {
|
||||||
res.end(JSON.stringify({ status: "ok" }));
|
const client = await pool.connect();
|
||||||
|
try {
|
||||||
|
await Promise.race([
|
||||||
|
client.query("SELECT 1"),
|
||||||
|
new Promise((_, reject) => setTimeout(() => reject(new Error("DB timeout")), 2000)),
|
||||||
|
]);
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
|
res.writeHead(200, { "Content-Type": "application/json" });
|
||||||
|
res.end(JSON.stringify({ status: "ok", db: "connected" }));
|
||||||
|
} catch {
|
||||||
|
res.writeHead(503, { "Content-Type": "application/json" });
|
||||||
|
res.end(JSON.stringify({ status: "error", db: "unreachable" }));
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
Submodule
+1
Submodule cartsnitch added at a53daddb9a
Generated
+3
-3
@@ -9805,9 +9805,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "6.4.1",
|
"version": "6.4.2",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.2.tgz",
|
||||||
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
|
"integrity": "sha512-2N/55r4JDJ4gdrCvGgINMy+HH3iRpNIz8K6SFwVsA+JbQScLiC+clmAxBgwiSPgcG9U15QmvqCGWzMbqda5zGQ==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ WORKDIR /app
|
|||||||
|
|
||||||
# build-essential and libpq-dev are needed to compile any C-extension wheels
|
# build-essential and libpq-dev are needed to compile any C-extension wheels
|
||||||
# (e.g. psycopg2 fallback). No git needed — common/ is copied from the repo root.
|
# (e.g. psycopg2 fallback). No git needed — common/ is copied from the repo root.
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends \
|
||||||
libpq-dev \
|
libpq-dev \
|
||||||
build-essential \
|
build-essential \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
@@ -25,7 +25,7 @@ FROM python:3.12-slim AS prod
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Install Playwright system dependencies for Chromium
|
# Install Playwright system dependencies for Chromium
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends \
|
||||||
libnss3 \
|
libnss3 \
|
||||||
libatk1.0-0 \
|
libatk1.0-0 \
|
||||||
libatk-bridge2.0-0 \
|
libatk-bridge2.0-0 \
|
||||||
|
|||||||
Reference in New Issue
Block a user