Implement Lab 7 security and infrastructure
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$Root = Split-Path -Parent $PSScriptRoot
|
||||
$Tls = Join-Path $Root "secrets/tls"
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $Tls | Out-Null
|
||||
|
||||
$OpenSSL = Get-Command openssl -ErrorAction SilentlyContinue
|
||||
if (-not $OpenSSL) {
|
||||
throw "OpenSSL not found in PATH"
|
||||
}
|
||||
|
||||
function Run-OpenSSL([string[]]$OpenSslArgs) {
|
||||
& openssl @OpenSslArgs
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "OpenSSL failed: $OpenSslArgs"
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Test-Path "$Tls/ca.key")) {
|
||||
Run-OpenSSL @(
|
||||
"req", "-x509", "-newkey", "rsa:3072",
|
||||
"-sha256", "-days", "3650", "-nodes",
|
||||
"-keyout", "$Tls/ca.key",
|
||||
"-out", "$Tls/ca.crt",
|
||||
"-subj", "/CN=Lab7 Server Root CA",
|
||||
"-addext", "basicConstraints=critical,CA:TRUE",
|
||||
"-addext", "keyUsage=critical,keyCertSign,cRLSign"
|
||||
)
|
||||
}
|
||||
|
||||
if (-not (Test-Path "$Tls/lb-ca.key")) {
|
||||
Run-OpenSSL @(
|
||||
"req", "-x509", "-newkey", "rsa:3072",
|
||||
"-sha256", "-days", "3650", "-nodes",
|
||||
"-keyout", "$Tls/lb-ca.key",
|
||||
"-out", "$Tls/lb-ca.crt",
|
||||
"-subj", "/CN=Lab7 Ingress Client CA",
|
||||
"-addext", "basicConstraints=critical,CA:TRUE",
|
||||
"-addext", "keyUsage=critical,keyCertSign,cRLSign"
|
||||
)
|
||||
}
|
||||
|
||||
function New-ServerCert([string]$Name, [string]$San) {
|
||||
$key = "$Tls/$Name.key"
|
||||
$csr = "$Tls/$Name.csr"
|
||||
$crt = "$Tls/$Name.crt"
|
||||
$ext = "$Tls/$Name.ext"
|
||||
|
||||
if (Test-Path $crt) {
|
||||
return
|
||||
}
|
||||
|
||||
Set-Content -Encoding ascii $ext "basicConstraints=critical,CA:FALSE`nsubjectAltName=$San`nextendedKeyUsage=serverAuth`nkeyUsage=digitalSignature,keyEncipherment"
|
||||
|
||||
Run-OpenSSL @(
|
||||
"req", "-new", "-newkey", "rsa:2048", "-nodes",
|
||||
"-keyout", $key,
|
||||
"-out", $csr,
|
||||
"-subj", "/CN=$Name"
|
||||
)
|
||||
|
||||
Run-OpenSSL @(
|
||||
"x509", "-req", "-in", $csr,
|
||||
"-CA", "$Tls/ca.crt",
|
||||
"-CAkey", "$Tls/ca.key",
|
||||
"-CAcreateserial",
|
||||
"-out", $crt,
|
||||
"-days", "825",
|
||||
"-sha256",
|
||||
"-extfile", $ext
|
||||
)
|
||||
|
||||
Remove-Item $csr, $ext -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
New-ServerCert "nginx" "DNS:localhost,IP:127.0.0.1"
|
||||
New-ServerCert "api" "DNS:api,DNS:localhost,IP:127.0.0.1"
|
||||
New-ServerCert "openbao" "DNS:openbao,DNS:localhost,IP:127.0.0.1"
|
||||
New-ServerCert "tls-proxy" "DNS:tls-proxy,DNS:localhost,IP:127.0.0.1"
|
||||
|
||||
if (-not (Test-Path "$Tls/lb-client.crt")) {
|
||||
Set-Content -Encoding ascii "$Tls/lb-client.ext" "basicConstraints=critical,CA:FALSE`nsubjectAltName=URI:spiffe://lab7/ingress/nginx`nextendedKeyUsage=clientAuth`nkeyUsage=digitalSignature,keyEncipherment"
|
||||
|
||||
Run-OpenSSL @(
|
||||
"req", "-new", "-newkey", "rsa:2048", "-nodes",
|
||||
"-keyout", "$Tls/lb-client.key",
|
||||
"-out", "$Tls/lb-client.csr",
|
||||
"-subj", "/CN=lab7-nginx/OU=ingress"
|
||||
)
|
||||
|
||||
Run-OpenSSL @(
|
||||
"x509", "-req", "-in", "$Tls/lb-client.csr",
|
||||
"-CA", "$Tls/lb-ca.crt",
|
||||
"-CAkey", "$Tls/lb-ca.key",
|
||||
"-CAcreateserial",
|
||||
"-out", "$Tls/lb-client.crt",
|
||||
"-days", "365",
|
||||
"-sha256",
|
||||
"-extfile", "$Tls/lb-client.ext"
|
||||
)
|
||||
|
||||
Remove-Item "$Tls/lb-client.csr", "$Tls/lb-client.ext" -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
Write-Host "Certificates created under secrets/tls."
|
||||
Write-Host "Private keys must never be committed to Git."
|
||||
@@ -0,0 +1,114 @@
|
||||
$ErrorActionPreference = "Stop"
|
||||
$Root = Split-Path -Parent $PSScriptRoot
|
||||
$Tls = Join-Path $Root "secrets/tls"
|
||||
$BaoDir = Join-Path $Root "secrets/bao"
|
||||
$EnvFile = Join-Path $Root ".env"
|
||||
if (-not (Test-Path $EnvFile)) { throw "Create .env from .env.example first." }
|
||||
$vars = @{}
|
||||
Get-Content $EnvFile | ForEach-Object {
|
||||
$line = $_.Trim()
|
||||
if ($line -and -not $line.StartsWith("#") -and $line.Contains("=")) {
|
||||
$pair = $line.Split("=",2)
|
||||
$vars[$pair[0].Trim()] = $pair[1].Trim().Trim('"').Trim("'")
|
||||
}
|
||||
}
|
||||
if (-not $vars.POSTGRES_USER -or -not $vars.POSTGRES_PASSWORD -or -not $vars.POSTGRES_DB -or
|
||||
-not $vars.API_DB_USER -or -not $vars.API_DB_PASSWORD -or
|
||||
-not $vars.WORKER_DB_USER -or -not $vars.WORKER_DB_PASSWORD -or
|
||||
-not $vars.OUTBOX_DB_USER -or -not $vars.OUTBOX_DB_PASSWORD -or
|
||||
-not $vars.PUBLISHER_RABBITMQ_USER -or -not $vars.PUBLISHER_RABBITMQ_PASSWORD -or
|
||||
-not $vars.WORKER_RABBITMQ_USER -or -not $vars.WORKER_RABBITMQ_PASSWORD -or
|
||||
-not $vars.REDIS_ADMIN_PASSWORD -or -not $vars.API_REDIS_PASSWORD -or -not $vars.WORKER_REDIS_PASSWORD) {
|
||||
throw ".env must define admin, API, Worker and Outbox database/broker credentials."
|
||||
}
|
||||
Import-Certificate -FilePath "$Tls/ca.crt" -CertStoreLocation Cert:\CurrentUser\Root | Out-Null
|
||||
$rootSecure = Read-Host "OpenBao operator root token (input is hidden by PowerShell secure prompt)" -AsSecureString
|
||||
$ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($rootSecure)
|
||||
try { $rootToken = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) }
|
||||
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) }
|
||||
$base = "https://localhost:18200/v1"
|
||||
$headers = @{ "X-Vault-Token" = $rootToken }
|
||||
function BaoPut($path,$body) {
|
||||
Invoke-RestMethod -Method Put -Uri "$base/$path" -Headers $headers -ContentType "application/json" -Body ($body | ConvertTo-Json -Depth 12) | Out-Null
|
||||
}
|
||||
function BaoPost($path,$body) {
|
||||
Invoke-RestMethod -Method Post -Uri "$base/$path" -Headers $headers -ContentType "application/json" -Body ($body | ConvertTo-Json -Depth 12)
|
||||
}
|
||||
# KV v2 mount and AppRole auth.
|
||||
try { BaoPost "sys/mounts/secret" @{type="kv"; options=@{version="2"}} } catch {}
|
||||
try { BaoPost "sys/auth/approle" @{type="approle"} } catch {}
|
||||
$apiPolicy = [System.IO.File]::ReadAllText("$Root/infra/openbao/api-policy.hcl")
|
||||
$workerPolicy = [System.IO.File]::ReadAllText("$Root/infra/openbao/worker-policy.hcl")
|
||||
$outboxPolicy = [System.IO.File]::ReadAllText("$Root/infra/openbao/outbox-policy.hcl")
|
||||
BaoPut "sys/policies/acl/api-policy" @{policy=$apiPolicy}
|
||||
BaoPut "sys/policies/acl/worker-policy" @{policy=$workerPolicy}
|
||||
BaoPut "sys/policies/acl/outbox-policy" @{policy=$outboxPolicy}
|
||||
|
||||
$apiDb = "postgresql+psycopg://$($vars.API_DB_USER):$($vars.API_DB_PASSWORD)@tls-proxy:15432/$($vars.POSTGRES_DB)?sslmode=verify-full&sslrootcert=/run/tls/ca.crt"
|
||||
$workerDb = "postgresql+psycopg://$($vars.WORKER_DB_USER):$($vars.WORKER_DB_PASSWORD)@tls-proxy:15432/$($vars.POSTGRES_DB)?sslmode=verify-full&sslrootcert=/run/tls/ca.crt"
|
||||
$outboxDb = "postgresql+psycopg://$($vars.OUTBOX_DB_USER):$($vars.OUTBOX_DB_PASSWORD)@tls-proxy:15432/$($vars.POSTGRES_DB)?sslmode=verify-full&sslrootcert=/run/tls/ca.crt"
|
||||
$workerBroker = "amqps://$($vars.WORKER_RABBITMQ_USER):$($vars.WORKER_RABBITMQ_PASSWORD)@tls-proxy:15672/"
|
||||
$publisherBroker = "amqps://$($vars.PUBLISHER_RABBITMQ_USER):$($vars.PUBLISHER_RABBITMQ_PASSWORD)@tls-proxy:15672/"
|
||||
$apiCache = "rediss://messenger-api:$($vars.API_REDIS_PASSWORD)@tls-proxy:16379/0?ssl_cert_reqs=required&ssl_ca_certs=/run/tls/ca.crt&ssl_check_hostname=true"
|
||||
$workerCache = "rediss://messenger-worker:$($vars.WORKER_REDIS_PASSWORD)@tls-proxy:16379/0?ssl_cert_reqs=required&ssl_ca_certs=/run/tls/ca.crt&ssl_check_hostname=true"
|
||||
$s3Endpoint = $vars.S3_ENDPOINT
|
||||
$apiSecrets = @{
|
||||
DATABASE_URL=$apiDb; CACHE_URL=$apiCache; S3_ENDPOINT=$s3Endpoint
|
||||
S3_ACCESS_KEY=$vars.S3_ACCESS_KEY_ID; S3_SECRET_KEY=$vars.S3_SECRET_ACCESS_KEY; S3_PUBLIC_ENDPOINT_URL=$vars.S3_PUBLIC_ENDPOINT_URL
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=$vars.OTEL_EXPORTER_OTLP_ENDPOINT
|
||||
}
|
||||
$workerSecrets = $apiSecrets.Clone()
|
||||
$workerSecrets.DATABASE_URL = $workerDb
|
||||
$workerSecrets.CACHE_URL = $workerCache
|
||||
$workerSecrets.RABBITMQ_URL = $workerBroker
|
||||
$outboxSecrets = @{
|
||||
DATABASE_URL=$outboxDb
|
||||
RABBITMQ_URL=$publisherBroker
|
||||
}
|
||||
BaoPost "secret/data/messenger/api" @{data=$apiSecrets} | Out-Null
|
||||
BaoPost "secret/data/messenger/worker" @{data=$workerSecrets} | Out-Null
|
||||
BaoPost "secret/data/messenger/outbox" @{data=$outboxSecrets} | Out-Null
|
||||
|
||||
foreach ($role in @(
|
||||
@{name="api"; policy="api-policy"},
|
||||
@{name="worker"; policy="worker-policy"},
|
||||
@{name="outbox"; policy="outbox-policy"}
|
||||
)) {
|
||||
BaoPost "auth/approle/role/$($role.name)" @{
|
||||
token_policies=@($role.policy); token_ttl="15m"; token_max_ttl="1h"
|
||||
secret_id_ttl="24h"; secret_id_num_uses=0
|
||||
} | Out-Null
|
||||
$roleId = (Invoke-RestMethod -Method Get -Uri "$base/auth/approle/role/$($role.name)/role-id" -Headers $headers).data.role_id
|
||||
$secretId = (BaoPost "auth/approle/role/$($role.name)/secret-id" @{}).data.secret_id
|
||||
$dir = Join-Path $BaoDir $role.name
|
||||
New-Item -ItemType Directory -Force -Path $dir | Out-Null
|
||||
Set-Content -NoNewline -Encoding ascii (Join-Path $dir "role_id") $roleId
|
||||
Set-Content -NoNewline -Encoding ascii (Join-Path $dir "secret_id") $secretId
|
||||
}
|
||||
# Restrict the Outbox DB role to its table after migrations have created it.
|
||||
& docker compose exec -T postgres psql -U $vars.POSTGRES_USER -d $vars.POSTGRES_DB -c "GRANT SELECT, UPDATE ON TABLE outbox_events TO $($vars.OUTBOX_DB_USER)" | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw "Could not grant Outbox table permissions; run migrations before OpenBao bootstrap." }
|
||||
|
||||
# Distinct Redis ACL identities for API and Worker; the default admin password stays in the Redis container/operator .env only.
|
||||
& docker compose exec -T redis redis-cli -a $vars.REDIS_ADMIN_PASSWORD ACL SETUSER messenger-api on ">$($vars.API_REDIS_PASSWORD)" "~*" "+@read" "+@write" "+@connection" "+@transaction" "+@scripting" *> $null
|
||||
if ($LASTEXITCODE -ne 0) { throw "Could not create Redis API ACL user." }
|
||||
& docker compose exec -T redis redis-cli -a $vars.REDIS_ADMIN_PASSWORD ACL SETUSER messenger-worker on ">$($vars.WORKER_REDIS_PASSWORD)" "~*" "+@read" "+@write" "+@connection" "+@transaction" "+@scripting" *> $null
|
||||
if ($LASTEXITCODE -ne 0) { throw "Could not create Redis Worker ACL user." }
|
||||
|
||||
& docker compose exec -T redis redis-cli -a $vars.REDIS_ADMIN_PASSWORD --no-auth-warning ACL SAVE *> $null
|
||||
if ($LASTEXITCODE -ne 0) { throw "Could not save Redis ACL file." }
|
||||
|
||||
function Set-RabbitUser([string]$User,[string]$Password,[string]$Configure,[string]$Write,[string]$Read) {
|
||||
& docker compose exec -T rabbitmq rabbitmqctl add_user $User $Password *> $null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
& docker compose exec -T rabbitmq rabbitmqctl change_password $User $Password *> $null
|
||||
if ($LASTEXITCODE -ne 0) { throw "Could not create/update RabbitMQ service user." }
|
||||
}
|
||||
& docker compose exec -T rabbitmq rabbitmqctl set_permissions -p / $User $Configure $Write $Read *> $null
|
||||
if ($LASTEXITCODE -ne 0) { throw "Could not set RabbitMQ permissions." }
|
||||
}
|
||||
Set-RabbitUser $vars.PUBLISHER_RABBITMQ_USER $vars.PUBLISHER_RABBITMQ_PASSWORD '^(attachments|attachment\.process\.v1)$' '^attachments$' '^$'
|
||||
Set-RabbitUser $vars.WORKER_RABBITMQ_USER $vars.WORKER_RABBITMQ_PASSWORD '^(attachments|attachments\.retry|attachments\.dead|attachment\.process\.v1|attachment\.process\.v1\.retry|attachment\.process\.v1\.dead)$' '^(attachments\.retry|attachments\.dead)$' '^attachment\.process\.v1$'
|
||||
|
||||
$rootToken = $null; $headers = $null
|
||||
Write-Host "OpenBao policies, AppRoles and scoped RabbitMQ identities configured. Credentials are stored under ignored secrets/bao/."
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Verify the configured Argon2id cost parameters."""
|
||||
from app.services.user_service import password_hasher
|
||||
|
||||
sample = password_hasher.hash("Lab7-test-password-only")
|
||||
assert sample.startswith("$argon2id$v=19$m=19456,t=2,p=1$"), sample
|
||||
assert password_hasher.verify("Lab7-test-password-only", sample)
|
||||
print("PASS: Argon2id m=19456 KiB, t=2, p=1; salt is embedded in PHC hash")
|
||||
@@ -9,7 +9,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def main():
|
||||
lab = json.loads((ROOT/'lab.json').read_text())['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
|
||||
spec = json.loads((ROOT / 'contracts/openapi.json').read_text(encoding='utf-8'))
|
||||
assert spec['openapi']=='3.1.0'
|
||||
assert spec['info']['version']=='1.%d.0'%lab
|
||||
operation_ids = set()
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Internal mTLS negative/positive probes; run inside the API container."""
|
||||
import argparse
|
||||
import http.client
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
|
||||
def probe(mode: str) -> int:
|
||||
context = ssl.create_default_context(cafile="/run/tls/ca.crt")
|
||||
headers = {"Host": "api", "X-Lab7-Client-Identity": "spiffe://lab7/ingress/nginx"}
|
||||
if mode == "positive":
|
||||
context.load_cert_chain("/run/tls/lb-client.crt", "/run/tls/lb-client.key")
|
||||
elif mode == "wrong-identity":
|
||||
context.load_cert_chain("/run/tls/lb-client.crt", "/run/tls/lb-client.key")
|
||||
headers["X-Lab7-Client-Identity"] = "spiffe://lab7/worker"
|
||||
elif mode == "foreign-ca":
|
||||
context.load_cert_chain("/tmp/foreign-client.crt", "/tmp/foreign-client.key")
|
||||
elif mode != "no-cert":
|
||||
raise ValueError(mode)
|
||||
|
||||
try:
|
||||
raw = socket.create_connection(("127.0.0.1", 8443), timeout=4)
|
||||
tls = context.wrap_socket(raw, server_hostname="api")
|
||||
request = "GET /health/live HTTP/1.1\r\n"
|
||||
request += "".join(f"{k}: {v}\r\n" for k, v in headers.items())
|
||||
request += "Connection: close\r\n\r\n"
|
||||
tls.sendall(request.encode())
|
||||
response = tls.recv(4096).decode("latin1", errors="replace")
|
||||
tls.close()
|
||||
status = int(response.split(" ", 2)[1])
|
||||
except (ssl.SSLError, OSError) as exc:
|
||||
if mode in {"no-cert", "foreign-ca"}:
|
||||
print(f"PASS: {mode} rejected during TLS handshake ({type(exc).__name__})")
|
||||
return 0
|
||||
raise
|
||||
|
||||
if mode == "positive" and status == 200:
|
||||
print("PASS: allowed ingress identity accepted")
|
||||
return 0
|
||||
if mode == "wrong-identity" and status == 403:
|
||||
print("PASS: non-ingress identity rejected by API authorization")
|
||||
return 0
|
||||
if mode in {"no-cert", "foreign-ca"}:
|
||||
raise AssertionError(f"{mode} unexpectedly reached HTTP status {status}")
|
||||
raise AssertionError(f"{mode} expected its security outcome, got HTTP {status}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("mode", choices=["no-cert", "foreign-ca", "wrong-identity", "positive"])
|
||||
args = parser.parse_args()
|
||||
sys.exit(probe(args.mode))
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Safely replay a failed attachment processing job.
|
||||
|
||||
Usage:
|
||||
python scripts/replay_failed_job.py ATTACHMENT_UUID
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import sys
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
# Add project root to Python import path.
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.models import Attachment, OutboxEvent, ProcessingJob
|
||||
from app.db.session import SessionLocal
|
||||
|
||||
|
||||
logger = logging.getLogger("replay_failed_job")
|
||||
|
||||
EVENT_TYPE = "attachment.process.v1"
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def replay_failed_job(attachment_id: uuid.UUID) -> None:
|
||||
db = SessionLocal()
|
||||
|
||||
try:
|
||||
# Lock the attachment first to serialize concurrent replay requests.
|
||||
attachment = db.scalar(
|
||||
select(Attachment)
|
||||
.where(Attachment.id == attachment_id)
|
||||
.with_for_update()
|
||||
)
|
||||
|
||||
if attachment is None:
|
||||
raise ValueError(f"Attachment not found: {attachment_id}")
|
||||
|
||||
job = db.scalar(
|
||||
select(ProcessingJob)
|
||||
.where(
|
||||
ProcessingJob.attachment_id == attachment_id,
|
||||
ProcessingJob.pipeline_version == attachment.pipeline_version,
|
||||
)
|
||||
.with_for_update()
|
||||
)
|
||||
|
||||
if job is None:
|
||||
raise ValueError(
|
||||
f"Processing job not found for attachment: {attachment_id}"
|
||||
)
|
||||
|
||||
# Only terminally failed jobs may be replayed.
|
||||
if job.status != "failed":
|
||||
raise ValueError(
|
||||
f"Job cannot be replayed: current job status is '{job.status}'"
|
||||
)
|
||||
|
||||
if attachment.status != "failed":
|
||||
raise ValueError(
|
||||
"Attachment and job states are inconsistent: "
|
||||
f"attachment status is '{attachment.status}'"
|
||||
)
|
||||
|
||||
# The worker needs the original staged file.
|
||||
if not attachment.staging_key:
|
||||
raise ValueError(
|
||||
"Cannot replay: staging_key is empty. "
|
||||
"The original file is not available for processing."
|
||||
)
|
||||
|
||||
now = utc_now()
|
||||
|
||||
# Reset the existing job. Keep its ID and pipeline version.
|
||||
job.attempt = 0
|
||||
job.status = "queued"
|
||||
job.available_at = now
|
||||
job.lease_until = None
|
||||
job.worker_id = None
|
||||
job.last_error_code = None
|
||||
|
||||
# Return attachment metadata to the queued state.
|
||||
attachment.status = "queued"
|
||||
attachment.error_code = None
|
||||
|
||||
# Create a new durable outbox event in the same transaction.
|
||||
event = OutboxEvent(
|
||||
event_type=EVENT_TYPE,
|
||||
aggregate_id=attachment.id,
|
||||
payload={
|
||||
"schema_version": 1,
|
||||
"job_id": str(job.id),
|
||||
"type": EVENT_TYPE,
|
||||
"attachment_id": str(attachment.id),
|
||||
"pipeline_version": job.pipeline_version,
|
||||
"attempt": 1,
|
||||
"created_at": now.isoformat(),
|
||||
},
|
||||
status="pending",
|
||||
)
|
||||
|
||||
db.add(event)
|
||||
db.commit()
|
||||
|
||||
print("Replay request successfully committed.")
|
||||
print(f"Attachment ID: {attachment.id}")
|
||||
print(f"Job ID: {job.id}")
|
||||
print(f"Job status: {job.status}")
|
||||
print(f"Attempt: {job.attempt}")
|
||||
print(f"Outbox event: {event.id}")
|
||||
print("Outbox status: pending")
|
||||
print()
|
||||
print("The existing outbox-publisher will publish the event.")
|
||||
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Replay a terminally failed attachment processing job."
|
||||
)
|
||||
parser.add_argument(
|
||||
"attachment_id",
|
||||
help="UUID of the attachment to replay",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
attachment_id = uuid.UUID(args.attachment_id)
|
||||
replay_failed_job(attachment_id)
|
||||
return 0
|
||||
|
||||
except ValueError as exc:
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
except Exception:
|
||||
logger.exception("Could not replay failed processing job")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
# Restart persistent services without deleting their volumes.
|
||||
docker compose restart postgres redis seaweedfs
|
||||
|
||||
# Restart RabbitMQ first, then refresh stunnel DNS resolution.
|
||||
docker compose restart rabbitmq
|
||||
docker compose restart tls-proxy
|
||||
|
||||
# Restart application services after their dependencies.
|
||||
docker compose restart api worker outbox-publisher
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test must provide the API instance id}"
|
||||
found=""
|
||||
for container in $(docker compose ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container")
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
found="$container"
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ -z "$found" ]; then
|
||||
echo "No API container matched TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
docker stop "$found" >/dev/null
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Exercise Nginx login rate limiting; run against the HTTPS ingress."""
|
||||
import argparse
|
||||
import base64
|
||||
import ssl
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="https://localhost:8443")
|
||||
p.add_argument("--ca-file", default="secrets/tls/ca.crt")
|
||||
args = p.parse_args()
|
||||
context = ssl.create_default_context(cafile=args.ca_file)
|
||||
auth = base64.b64encode(b"not-a-user:deliberately-wrong-password").decode()
|
||||
statuses = []
|
||||
retry_after = None
|
||||
for _ in range(12):
|
||||
request = urllib.request.Request(
|
||||
args.base_url.rstrip("/") + "/api/v1/auth/sessions",
|
||||
data=b"{}",
|
||||
headers={"Authorization": "Basic " + auth, "Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, context=context, timeout=5) as response:
|
||||
statuses.append(response.status)
|
||||
except urllib.error.HTTPError as exc:
|
||||
statuses.append(exc.code)
|
||||
if exc.code == 429:
|
||||
retry_after = exc.headers.get("Retry-After")
|
||||
time.sleep(0.05)
|
||||
assert 429 in statuses, f"rate limiter did not return 429; statuses={statuses}"
|
||||
assert retry_after, "429 response lacks Retry-After"
|
||||
print("PASS: login rate limit returned 429 with Retry-After")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,21 @@
|
||||
$ErrorActionPreference = "Stop"
|
||||
$Root = Split-Path -Parent $PSScriptRoot
|
||||
$Tls = Join-Path $Root "secrets/tls"
|
||||
if (-not (Get-Command openssl -ErrorAction SilentlyContinue)) { throw "OpenSSL is required." }
|
||||
function Run-OpenSSL([string[]]$Args) {
|
||||
& openssl @Args
|
||||
if ($LASTEXITCODE -ne 0) { throw "OpenSSL failed: $Args" }
|
||||
}
|
||||
$foreign="$Tls/foreign"
|
||||
New-Item -ItemType Directory -Force -Path $foreign | Out-Null
|
||||
Run-OpenSSL @("req","-x509","-newkey","rsa:2048","-nodes","-keyout","$foreign/ca.key","-out","$foreign/ca.crt","-days","30","-subj","/CN=Foreign Test CA")
|
||||
Run-OpenSSL @("req","-newkey","rsa:2048","-nodes","-keyout","$foreign/client.key","-out","$foreign/client.csr","-subj","/CN=foreign-client")
|
||||
Run-OpenSSL @("x509","-req","-in","$foreign/client.csr","-CA","$foreign/ca.crt","-CAkey","$foreign/ca.key","-CAcreateserial","-out","$foreign/client.crt","-days","30")
|
||||
$container = (docker compose ps -q api | Select-Object -First 1)
|
||||
if (-not $container) { throw "API container is not running." }
|
||||
docker cp "$foreign/client.crt" "${container}:/tmp/foreign-client.crt"
|
||||
docker cp "$foreign/client.key" "${container}:/tmp/foreign-client.key"
|
||||
docker compose exec api python scripts/mtls_probe.py no-cert
|
||||
docker compose exec api python scripts/mtls_probe.py foreign-ca
|
||||
docker compose exec api python scripts/mtls_probe.py wrong-identity
|
||||
docker compose exec api python scripts/mtls_probe.py positive
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Check that AppRole tokens are scoped to their own KV v2 path."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import requests
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE = "https://localhost:18200/v1"
|
||||
CA = ROOT / "secrets" / "tls" / "ca.crt"
|
||||
|
||||
|
||||
def token_for(role: str) -> str:
|
||||
role_dir = ROOT / "secrets" / "bao" / role
|
||||
response = requests.post(
|
||||
BASE + "/auth/approle/login",
|
||||
json={
|
||||
"role_id": (role_dir / "role_id").read_text().strip(),
|
||||
"secret_id": (role_dir / "secret_id").read_text().strip(),
|
||||
},
|
||||
verify=str(CA),
|
||||
timeout=5,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()["auth"]["client_token"]
|
||||
|
||||
|
||||
def check_role(role: str, allowed: str, denied: str) -> None:
|
||||
token = token_for(role)
|
||||
headers = {"X-Vault-Token": token}
|
||||
own = requests.get(BASE + f"/secret/data/messenger/{allowed}", headers=headers, verify=str(CA), timeout=5)
|
||||
assert own.status_code == 200, f"{role} cannot read its own path"
|
||||
other = requests.get(BASE + f"/secret/data/messenger/{denied}", headers=headers, verify=str(CA), timeout=5)
|
||||
assert other.status_code == 403, f"{role} unexpectedly read {denied}"
|
||||
write = requests.post(
|
||||
BASE + f"/secret/data/messenger/{allowed}",
|
||||
headers=headers,
|
||||
json={"data": {"forbidden_write": "must-not-be-written"}},
|
||||
verify=str(CA),
|
||||
timeout=5,
|
||||
)
|
||||
assert write.status_code == 403, f"{role} unexpectedly wrote its own path"
|
||||
print(f"PASS: {role} reads {allowed}; denied {denied} and write")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
check_role("api", "api", "worker")
|
||||
check_role("worker", "worker", "api")
|
||||
check_role("outbox", "outbox", "api")
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify that an expired session is rejected through HTTPS."""
|
||||
|
||||
import hashlib
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, Failure, arguments, run
|
||||
|
||||
|
||||
def database_query(sql):
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker", "compose", "exec", "-T",
|
||||
"-e", "SQL=" + sql,
|
||||
"postgres",
|
||||
"sh", "-lc",
|
||||
'psql -X -A -t -v ON_ERROR_STOP=1 '
|
||||
'-U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "$SQL"',
|
||||
],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
raise Failure("PostgreSQL operation failed")
|
||||
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Expired session security test")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
|
||||
actor = client.user("expiry")
|
||||
token = actor["token"]
|
||||
token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
try:
|
||||
updated = database_query(
|
||||
"UPDATE sessions "
|
||||
"SET expires_at = NOW() - INTERVAL '1 second' "
|
||||
f"WHERE token_hash = '{token_hash}' "
|
||||
"RETURNING id;"
|
||||
)
|
||||
|
||||
if not updated:
|
||||
raise Failure("Test session was not found in PostgreSQL")
|
||||
|
||||
client.call(
|
||||
"GET",
|
||||
"/api/v1/users/me",
|
||||
401,
|
||||
actor=actor,
|
||||
)
|
||||
|
||||
print("PASS: expired session rejected with HTTP 401")
|
||||
|
||||
finally:
|
||||
database_query(
|
||||
f"DELETE FROM sessions WHERE token_hash = '{token_hash}';"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user