This commit is contained in:
Getlles
2026-11-25 01:43:37 +03:00
parent 8c7b051c2a
commit 3cd4603888
28 changed files with 1122 additions and 228 deletions
+2 -1
View File
@@ -69,10 +69,11 @@ EOF
chmod 600 "$CERT_DIR/${name}.key"
}
issue_cert "edge-lb" "DNS:localhost,DNS:nginx,IP:127.0.0.1"
issue_cert "edge-lb" "DNS:localhost,DNS:nginx,IP:127.0.0.1,DNS:edge-lb"
issue_cert "api-1" "DNS:api-1,DNS:messenger-api"
issue_cert "api-2" "DNS:api-2,DNS:messenger-api"
issue_cert "worker" "DNS:worker,DNS:messenger-worker"
issue_cert "unprivileged-client" "DNS:unprivileged-client"
issue_cert "postgres" "DNS:postgres"
issue_cert "redis" "DNS:redis"
issue_cert "s3" "DNS:s3"
+3
View File
@@ -30,6 +30,9 @@ def init_bucket():
except Exception:
s3_client.create_bucket(Bucket=S3_BUCKET)
print("Bucket successfully created.")
api_key = os.getenv("S3_API_ACCESS_KEY_ID", "messenger_api_s3")
worker_key = os.getenv("S3_WORKER_ACCESS_KEY_ID", "messenger_worker_s3")
print(f"Configured S3 identities: api={api_key} (prefix=api/), worker={worker_key} (prefix=worker/)")
if __name__ == "__main__":
+14 -4
View File
@@ -60,27 +60,37 @@ bao_exec kv put secret/messenger/worker/s3 \
bao_exec write auth/approle/role/messenger-api \
token_policies="messenger-api" \
token_ttl="1h" \
token_max_ttl="4h" >/dev/null
token_max_ttl="4h" \
secret_id_ttl="24h" \
secret_id_num_uses=10 >/dev/null
bao_exec write auth/approle/role/messenger-worker \
token_policies="messenger-worker" \
token_ttl="1h" \
token_max_ttl="4h" >/dev/null
token_max_ttl="4h" \
secret_id_ttl="24h" \
secret_id_num_uses=10 >/dev/null
API_ROLE_ID=$(bao_exec read -field=role_id auth/approle/role/messenger-api/role-id)
API_SECRET_ID=$(bao_exec write -f -field=secret_id auth/approle/role/messenger-api/secret-id)
API_SECRET_JSON=$(bao_exec write -format=json -f auth/approle/role/messenger-api/secret-id)
API_SECRET_ID=$(echo "$API_SECRET_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['secret_id'])")
API_SECRET_ACCESSOR=$(echo "$API_SECRET_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['secret_id_accessor'])")
WORKER_ROLE_ID=$(bao_exec read -field=role_id auth/approle/role/messenger-worker/role-id)
WORKER_SECRET_ID=$(bao_exec write -f -field=secret_id auth/approle/role/messenger-worker/secret-id)
WORKER_SECRET_JSON=$(bao_exec write -format=json -f auth/approle/role/messenger-worker/secret-id)
WORKER_SECRET_ID=$(echo "$WORKER_SECRET_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['secret_id'])")
WORKER_SECRET_ACCESSOR=$(echo "$WORKER_SECRET_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['secret_id_accessor'])")
cat > ./infra/certs/api-approle.env <<EOF
BAO_ROLE_ID=${API_ROLE_ID}
BAO_SECRET_ID=${API_SECRET_ID}
BAO_SECRET_ID_ACCESSOR=${API_SECRET_ACCESSOR}
EOF
cat > ./infra/certs/worker-approle.env <<EOF
BAO_ROLE_ID=${WORKER_ROLE_ID}
BAO_SECRET_ID=${WORKER_SECRET_ID}
BAO_SECRET_ID_ACCESSOR=${WORKER_SECRET_ACCESSOR}
EOF
chmod 600 ./infra/certs/api-approle.env ./infra/certs/worker-approle.env
+90
View File
@@ -0,0 +1,90 @@
import argparse
import concurrent.futures
import json
import os
import ssl
import statistics
import time
import urllib.error
import urllib.request
from pathlib import Path
def _single_login_attempt(url: str, ssl_ctx: ssl.SSLContext, username: str, password: str, timeout: float) -> tuple[int, float]:
body = json.dumps({"username": username, "password": password}).encode("utf-8")
req = urllib.request.Request(
url,
data=body,
headers={"Content-Type": "application/json"},
method="POST",
)
t0 = time.perf_counter()
try:
with urllib.request.urlopen(req, context=ssl_ctx, timeout=timeout) as resp:
status = resp.status
except urllib.error.HTTPError as exc:
status = exc.code
except (urllib.error.URLError, ssl.SSLError, OSError):
status = 0
elapsed_ms = (time.perf_counter() - t0) * 1000.0
return status, elapsed_ms
def main() -> None:
parser = argparse.ArgumentParser(description="Measure login endpoint latency, throughput, and 429 rate-limit behavior.")
parser.add_argument("--url", default=os.getenv("LOGIN_URL", "https://localhost:8443/api/v1/auth/sessions"))
parser.add_argument("--ca-file", default=os.getenv("CA_FILE", "./infra/certs/ca.crt"))
parser.add_argument("--username", default=os.getenv("TEST_LOGIN_USER", "nonexistent_user"))
parser.add_argument("--password", default=os.getenv("TEST_LOGIN_PASSWORD", "WrongPassword123!"))
parser.add_argument("--requests", type=int, default=45)
parser.add_argument("--concurrency", type=int, default=8)
parser.add_argument("--timeout", type=float, default=10.0)
parser.add_argument("--out", default="evidence/login-dos.txt")
args = parser.parse_args()
ca_path = Path(args.ca_file)
ctx = ssl.create_default_context(cafile=str(ca_path)) if ca_path.exists() else ssl.create_default_context()
results: list[tuple[int, float]] = []
wall_start = time.perf_counter()
with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, args.concurrency)) as pool:
futures = [
pool.submit(_single_login_attempt, args.url, ctx, args.username, args.password, args.timeout)
for _ in range(args.requests)
]
for fut in concurrent.futures.as_completed(futures):
results.append(fut.result())
wall_elapsed_s = max(time.perf_counter() - wall_start, 1e-6)
statuses = [s for s, _ in results]
latencies = [ms for _, ms in results]
non_429_latencies = [ms for s, ms in results if s != 429]
limited_429_latencies = [ms for s, ms in results if s == 429]
def _pct(vals: list[float], p: float) -> float:
if not vals:
return 0.0
ordered = sorted(vals)
idx = min(len(ordered) - 1, max(0, int(round((p / 100.0) * (len(ordered) - 1)))))
return round(ordered[idx], 2)
lines = [
f"url={args.url}",
f"total_requests={len(results)} concurrency={args.concurrency} wall_time_s={wall_elapsed_s:.3f}",
f"effective_throughput_rps={len(results) / wall_elapsed_s:.2f}",
f"status_401={statuses.count(401)} status_429={statuses.count(429)} status_200={statuses.count(200)} other_or_err={sum(1 for s in statuses if s not in (200, 401, 429))}",
f"all_latencies_ms: p50={round(statistics.median(latencies), 2) if latencies else 0.0} p95={_pct(latencies, 95)} max={round(max(latencies), 2) if latencies else 0.0}",
f"non_429_argon2_path_ms: count={len(non_429_latencies)} p50={round(statistics.median(non_429_latencies), 2) if non_429_latencies else 0.0} p95={_pct(non_429_latencies, 95)} max={round(max(non_429_latencies), 2) if non_429_latencies else 0.0}",
f"rate_limited_429_ms: count={len(limited_429_latencies)} p50={round(statistics.median(limited_429_latencies), 2) if limited_429_latencies else 0.0} p95={_pct(limited_429_latencies, 95)} max={round(max(limited_429_latencies), 2) if limited_429_latencies else 0.0}",
]
report = "\n".join(lines)
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(report + "\n", encoding="utf-8")
print(report)
if __name__ == "__main__":
main()
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
set -euo pipefail
export MSYS_NO_PATHCONV=1
OPERATOR_STATE_DIR="${OPERATOR_STATE_DIR:-./.bao-operator}"
ROLE_NAME="${1:-messenger-worker}"
case "$ROLE_NAME" in
messenger-api) ENV_FILE="./infra/certs/api-approle.env" ;;
messenger-worker) ENV_FILE="./infra/certs/worker-approle.env" ;;
*) echo "Unsupported role: $ROLE_NAME" >&2; exit 1 ;;
esac
if [ ! -f "$OPERATOR_STATE_DIR/init.json" ]; then
echo "Missing $OPERATOR_STATE_DIR/init.json" >&2
exit 1
fi
ROOT_TOKEN=$(python3 -c "import json; d=json.load(open('$OPERATOR_STATE_DIR/init.json', encoding='utf-8')); print(d['root_token'])")
bao_exec() {
MSYS_NO_PATHCONV=1 docker compose exec -T \
-e BAO_ADDR=https://127.0.0.1:8200 \
-e BAO_CACERT=/openbao/certs/ca.crt \
-e BAO_CLIENT_CERT=/openbao/certs/openbao.crt \
-e BAO_CLIENT_KEY=/openbao/certs/openbao.key \
-e BAO_TOKEN="$ROOT_TOKEN" \
openbao bao "$@"
}
if [ -f "$ENV_FILE" ]; then
OLD_ACCESSOR=$(grep -E '^BAO_SECRET_ID_ACCESSOR=' "$ENV_FILE" | cut -d= -f2- || true)
if [ -n "${OLD_ACCESSOR:-}" ]; then
echo "Destroying old SecretID accessor for ${ROLE_NAME}: ${OLD_ACCESSOR}"
bao_exec write "auth/approle/role/${ROLE_NAME}/secret-id-accessor/destroy" \
secret_id_accessor="$OLD_ACCESSOR" >/dev/null
else
echo "No old SecretID accessor found in ${ENV_FILE}; skipping destroy."
fi
fi
NEW_SECRET_JSON=$(bao_exec write -format=json -f "auth/approle/role/${ROLE_NAME}/secret-id")
NEW_SECRET_ID=$(echo "$NEW_SECRET_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['secret_id'])")
NEW_SECRET_ACCESSOR=$(echo "$NEW_SECRET_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['secret_id_accessor'])")
ROLE_ID=$(bao_exec read -field=role_id "auth/approle/role/${ROLE_NAME}/role-id")
cat > "$ENV_FILE" <<EOF
BAO_ROLE_ID=${ROLE_ID}
BAO_SECRET_ID=${NEW_SECRET_ID}
BAO_SECRET_ID_ACCESSOR=${NEW_SECRET_ACCESSOR}
EOF
chmod 600 "$ENV_FILE"
echo "Issued fresh SecretID for ${ROLE_NAME} (accessor=${NEW_SECRET_ACCESSOR})."
echo "RoleID=${ROLE_ID}"
echo "Old SecretID (if any) has been destroyed by accessor."
MSYS_NO_PATHCONV=1 docker compose --env-file .env up -d --force-recreate api-1 api-2 worker
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env bash
set -euo pipefail
export MSYS_NO_PATHCONV=1
CERT_DIR="${CERT_DIR:-./infra/certs}"
OPERATOR_STATE_DIR="${OPERATOR_STATE_DIR:-./.bao-operator}"
TARGET_CERT="${1:-edge-lb}"
if [ ! -f "$OPERATOR_STATE_DIR/init.json" ]; then
echo "Missing $OPERATOR_STATE_DIR/init.json" >&2
exit 1
fi
ROOT_TOKEN=$(python3 -c "import json; d=json.load(open('$OPERATOR_STATE_DIR/init.json', encoding='utf-8')); print(d['root_token'])")
bao_exec() {
MSYS_NO_PATHCONV=1 docker compose exec -T \
-e BAO_ADDR=https://127.0.0.1:8200 \
-e BAO_CACERT=/openbao/certs/ca.crt \
-e BAO_CLIENT_CERT=/openbao/certs/openbao.crt \
-e BAO_CLIENT_KEY=/openbao/certs/openbao.key \
-e BAO_TOKEN="$ROOT_TOKEN" \
openbao bao "$@"
}
NEW_HMAC=$(python3 -c "import secrets; print(secrets.token_hex(32))")
CURRENT_DSN=$(bao_exec kv get -field=dsn secret/messenger/api/db)
bao_exec kv put secret/messenger/api/db dsn="$CURRENT_DSN" hmac_key="$NEW_HMAC" >/dev/null
echo "Rotated secret/messenger/api/db hmac_key in OpenBao"
SAN="DNS:localhost,DNS:nginx,IP:127.0.0.1,DNS:edge-lb"
case "$TARGET_CERT" in
edge-lb) SAN="DNS:localhost,DNS:nginx,IP:127.0.0.1,DNS:edge-lb" ;;
api-1) SAN="DNS:api-1,DNS:messenger-api" ;;
api-2) SAN="DNS:api-2,DNS:messenger-api" ;;
worker) SAN="DNS:worker,DNS:messenger-worker" ;;
*) echo "Unsupported target cert: $TARGET_CERT" >&2; exit 1 ;;
esac
openssl genrsa -out "$CERT_DIR/${TARGET_CERT}.key.new" 2048
cat > "$CERT_DIR/${TARGET_CERT}.ext" <<EOF
subjectAltName=${SAN}
extendedKeyUsage=serverAuth,clientAuth
EOF
MSYS_NO_PATHCONV=1 openssl req -new -key "$CERT_DIR/${TARGET_CERT}.key.new" \
-subj "/CN=${TARGET_CERT}" \
-out "$CERT_DIR/${TARGET_CERT}.csr"
openssl x509 -req -in "$CERT_DIR/${TARGET_CERT}.csr" \
-CA "$CERT_DIR/ca.crt" -CAkey "$CERT_DIR/ca.key" -CAcreateserial \
-out "$CERT_DIR/${TARGET_CERT}.crt.new" -days 365 -sha256 \
-extfile "$CERT_DIR/${TARGET_CERT}.ext"
rm -f "$CERT_DIR/${TARGET_CERT}.csr" "$CERT_DIR/${TARGET_CERT}.ext"
chmod 600 "$CERT_DIR/${TARGET_CERT}.key.new"
mv "$CERT_DIR/${TARGET_CERT}.key.new" "$CERT_DIR/${TARGET_CERT}.key"
mv "$CERT_DIR/${TARGET_CERT}.crt.new" "$CERT_DIR/${TARGET_CERT}.crt"
if [ "$TARGET_CERT" = "edge-lb" ]; then
docker compose exec -T nginx nginx -s reload
else
docker compose restart "$TARGET_CERT"
fi
echo "Rotated leaf certificate for '$TARGET_CERT' without image rebuild"
MSYS_NO_PATHCONV=1 docker compose --env-file .env up -d --force-recreate api-1 api-2
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
set -euo pipefail
mkdir -p evidence
OUT_FILE="evidence/deps-trivy.txt"
IMAGE_NAME="${1:-mtusi2026lab7-api-1}"
HOST_PWD="$(pwd -W 2>/dev/null || pwd)"
{
echo "=== Dependency & Image Scan ($(date -u '+%Y-%m-%dT%H:%M:%SZ')) ==="
echo "Target image: ${IMAGE_NAME}"
echo ""
if command -v trivy >/dev/null 2>&1; then
echo "--- Trivy FS (requirements.txt) ---"
trivy fs --scanners vuln --severity HIGH,CRITICAL --format table requirements.txt || true
echo ""
echo "--- Trivy Image (${IMAGE_NAME}) ---"
trivy image --scanners vuln --severity HIGH,CRITICAL --format table "${IMAGE_NAME}" || true
elif command -v docker >/dev/null 2>&1; then
echo "--- Trivy via Docker FS (requirements.txt) ---"
MSYS_NO_PATHCONV=1 docker run --rm \
-v "${HOST_PWD}:/work" \
-v trivy-cache:/root/.cache \
aquasec/trivy:latest fs --scanners vuln --severity HIGH,CRITICAL --format table /work/requirements.txt || true
echo ""
echo "--- Trivy via Docker Image (${IMAGE_NAME}) ---"
MSYS_NO_PATHCONV=1 docker run --rm \
-v //./pipe/docker_engine://./pipe/docker_engine \
-v trivy-cache:/root/.cache \
aquasec/trivy:latest image --scanners vuln --severity HIGH,CRITICAL --format table "${IMAGE_NAME}" || true
else
echo "Neither trivy nor docker CLI found; listing pinned dependencies from requirements.txt:"
cat requirements.txt
fi
} > "${OUT_FILE}"
echo "Saved scan output to ${OUT_FILE}"
head -n 40 "${OUT_FILE}"
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env bash
set -euo pipefail
mkdir -p evidence
OUT_FILE="evidence/sealed-openbao.txt"
INIT_FILE="${1:-./.bao-operator/init.json}"
if [ ! -f "${INIT_FILE}" ]; then
echo "ERROR: init file not found at ${INIT_FILE}" >&2
exit 1
fi
ROOT_TOKEN="$(python3 -c 'import json, sys; d=json.load(open(sys.argv[1])); print(d.get("root_token") or d.get("RootToken") or "")' "${INIT_FILE}")"
UNSEAL_KEY="$(python3 -c 'import json, sys; d=json.load(open(sys.argv[1])); keys=d.get("unseal_keys_b64") or d.get("keys_base64") or []; print(keys[0] if keys else "")' "${INIT_FILE}")"
if [ -z "${ROOT_TOKEN}" ] || [ -z "${UNSEAL_KEY}" ]; then
echo "ERROR: could not extract root_token or unseal key from ${INIT_FILE}" >&2
exit 1
fi
cleanup() {
docker compose --env-file .env exec -T -e UNSEAL_KEY="${UNSEAL_KEY}" openbao sh -c '
export BAO_ADDR=https://127.0.0.1:8200 BAO_CACERT=/openbao/certs/ca.crt
bao operator unseal "$UNSEAL_KEY" >/dev/null 2>&1 || true
' >/dev/null 2>&1 || true
}
trap cleanup EXIT
{
echo "=== OpenBao Sealed Behavior Check ($(date -u '+%Y-%m-%dT%H:%M:%SZ')) ==="
echo ""
echo "--- 1. Seal OpenBao ---"
docker compose --env-file .env exec -T -e BAO_TOKEN="${ROOT_TOKEN}" openbao sh -c '
export BAO_ADDR=https://127.0.0.1:8200 BAO_CACERT=/openbao/certs/ca.crt
bao operator seal
bao status | grep -E "Initialized|Sealed" || true
'
echo ""
echo "--- 2. Attempt secret read while sealed (expected failure/sealed) ---"
docker compose --env-file .env exec -T -e BAO_TOKEN="${ROOT_TOKEN}" openbao sh -c '
export BAO_ADDR=https://127.0.0.1:8200 BAO_CACERT=/openbao/certs/ca.crt
bao kv get secret/messenger/api/db 2>&1 || true
'
echo ""
echo "--- 3. Ingress readiness check while OpenBao is sealed ---"
curl -sS -w "\nHTTP_CODE:%{http_code}\n" --ssl-no-revoke --cacert ./infra/certs/ca.crt https://localhost:8443/health/ready || true
echo ""
echo "--- 4. Unseal OpenBao ---"
docker compose --env-file .env exec -T -e UNSEAL_KEY="${UNSEAL_KEY}" openbao sh -c '
export BAO_ADDR=https://127.0.0.1:8200 BAO_CACERT=/openbao/certs/ca.crt
bao operator unseal "$UNSEAL_KEY" | grep -E "Initialized|Sealed|Progress" || true
'
echo ""
echo "--- 5. Verify secret read & ingress readiness after unseal ---"
docker compose --env-file .env exec -T -e BAO_TOKEN="${ROOT_TOKEN}" openbao sh -c '
export BAO_ADDR=https://127.0.0.1:8200 BAO_CACERT=/openbao/certs/ca.crt
bao kv get secret/messenger/api/db >/dev/null && echo "BAO_KV_GET_AFTER_UNSEAL=OK"
'
curl -sS -w "\nHTTP_CODE:%{http_code}\n" --ssl-no-revoke --cacert ./infra/certs/ca.crt https://localhost:8443/health/ready || true
} > "${OUT_FILE}"
cat "${OUT_FILE}"