[+] add project
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-12-05 22:05:31 +03:00
parent 20afc2c790
commit 1d146756d7
63 changed files with 3501 additions and 149 deletions
+111
View File
@@ -0,0 +1,111 @@
#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
PKI_DIR="$ROOT/secrets/pki"
umask 077
if [ -e "$PKI_DIR" ] && [ -n "$(find "$PKI_DIR" -mindepth 1 -maxdepth 1 -print -quit)" ]; then
printf '%s\n' "Refusing to overwrite existing PKI in $PKI_DIR" >&2
exit 1
fi
mkdir -p "$PKI_DIR"
chmod 700 "$ROOT/secrets" "$PKI_DIR"
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out "$PKI_DIR/ca.key"
openssl req -x509 -new -key "$PKI_DIR/ca.key" -sha256 -days 3650 \
-subj "/CN=MTUSI Lab 7 Local CA" \
-addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
-addext "keyUsage=critical,keyCertSign,cRLSign" \
-out "$PKI_DIR/ca.crt"
issue_cert() {
name=$1
common_name=$2
dns_names=$3
ip_names=$4
uri_name=$5
usage=$6
key="$PKI_DIR/$name.key"
csr="$PKI_DIR/$name.csr"
cert="$PKI_DIR/$name.crt"
ext="$PKI_DIR/$name.ext"
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$key"
openssl req -new -key "$key" -subj "/CN=$common_name" -out "$csr"
{
printf '%s\n' '[v3_req]' 'basicConstraints=critical,CA:FALSE'
printf '%s\n' 'keyUsage=critical,digitalSignature,keyEncipherment'
printf 'extendedKeyUsage=%s\n' "$usage"
printf '%s\n' 'subjectAltName=@alt_names' '[alt_names]'
index=1
old_ifs=$IFS
IFS=,
for dns in $dns_names; do
[ -n "$dns" ] || continue
printf 'DNS.%s=%s\n' "$index" "$dns"
index=$((index + 1))
done
IFS=$old_ifs
index=1
IFS=,
for ip in $ip_names; do
[ -n "$ip" ] || continue
printf 'IP.%s=%s\n' "$index" "$ip"
index=$((index + 1))
done
IFS=$old_ifs
if [ -n "$uri_name" ]; then
printf 'URI.1=%s\n' "$uri_name"
fi
} > "$ext"
openssl x509 -req -in "$csr" -CA "$PKI_DIR/ca.crt" -CAkey "$PKI_DIR/ca.key" \
-CAcreateserial -out "$cert" -days 397 -sha256 -extfile "$ext" -extensions v3_req
rm -f "$csr" "$ext"
chmod 600 "$key"
chmod 644 "$cert"
}
issue_cert ingress localhost localhost,ingress 127.0.0.1 "" serverAuth
issue_cert lb-client load-balancer "" "" spiffe://lab7/role/load-balancer clientAuth
issue_cert api-server api api "" spiffe://lab7/role/api serverAuth,clientAuth
issue_cert api-client api-service "" "" spiffe://lab7/role/api clientAuth
issue_cert worker-client worker-service "" "" spiffe://lab7/role/worker clientAuth
issue_cert postgres-server postgres postgres "" "" serverAuth
issue_cert s3-server s3 s3 "" "" serverAuth
issue_cert rabbit-server rabbitmq rabbitmq "" "" serverAuth
issue_cert openbao-server openbao openbao "" "" serverAuth
issue_cert collector-server otel-collector otel-collector "" "" serverAuth
issue_cert prometheus-server prometheus prometheus "" "" serverAuth
issue_cert loki-server loki loki "" "" serverAuth
issue_cert tempo-server tempo tempo "" "" serverAuth
issue_cert grafana-server grafana grafana "" "" serverAuth
prepare_runtime_cert() {
service=$1
certificate=$2
mkdir -p "$ROOT/secrets/runtime-pki/$service"
cp "$PKI_DIR/ca.crt" "$ROOT/secrets/runtime-pki/$service/ca.crt"
cp "$PKI_DIR/$certificate.crt" "$ROOT/secrets/runtime-pki/$service/server.crt"
cp "$PKI_DIR/$certificate.key" "$ROOT/secrets/runtime-pki/$service/server.key"
}
prepare_runtime_cert ingress ingress
for service in api postgres s3 rabbit openbao collector prometheus loki tempo grafana; do
prepare_runtime_cert "$service" "$service-server"
done
cp "$PKI_DIR/lb-client.crt" "$ROOT/secrets/runtime-pki/ingress/client.crt"
cp "$PKI_DIR/lb-client.key" "$ROOT/secrets/runtime-pki/ingress/client.key"
cp "$PKI_DIR/api-client.crt" "$ROOT/secrets/runtime-pki/api/client.crt"
cp "$PKI_DIR/api-client.key" "$ROOT/secrets/runtime-pki/api/client.key"
mkdir -p "$ROOT/secrets/runtime-pki/worker"
cp "$PKI_DIR/ca.crt" "$ROOT/secrets/runtime-pki/worker/ca.crt"
cp "$PKI_DIR/worker-client.crt" "$ROOT/secrets/runtime-pki/worker/client.crt"
cp "$PKI_DIR/worker-client.key" "$ROOT/secrets/runtime-pki/worker/client.key"
rm -f "$PKI_DIR/ca.srl"
"$ROOT/scripts/bootstrap-untrusted-client.sh"
printf 'Created local CA and service certificates in %s\n' "$PKI_DIR"
printf 'Prepared service-specific runtime certificates in %s\n' "$ROOT/secrets/runtime-pki"
printf 'Keep all private keys out of Git and do not reuse this CA outside the local lab.\n'
+66
View File
@@ -0,0 +1,66 @@
#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
SECRETS_DIR="$ROOT/secrets"
ENV_FILE="$ROOT/.env"
umask 077
mkdir -p "$SECRETS_DIR"
chmod 700 "$SECRETS_DIR"
if [ -e "$ENV_FILE" ]; then
printf '%s\n' "Refusing to overwrite existing local secrets: $ENV_FILE" >&2
exit 1
fi
random_secret() {
openssl rand -hex 32
}
POSTGRES_PASSWORD=$(random_secret)
POSTGRES_API_PASSWORD=$(random_secret)
POSTGRES_WORKER_PASSWORD=$(random_secret)
MINIO_ROOT_PASSWORD=$(random_secret)
S3_API_ACCESS_KEY=$(openssl rand -hex 16)
S3_API_SECRET_KEY=$(random_secret)
S3_WORKER_ACCESS_KEY=$(openssl rand -hex 16)
S3_WORKER_SECRET_KEY=$(random_secret)
RABBITMQ_DEFAULT_PASSWORD=$(random_secret)
RABBITMQ_API_PASSWORD=$(random_secret)
RABBITMQ_WORKER_PASSWORD=$(random_secret)
GRAFANA_ADMIN_PASSWORD=$(random_secret)
cat > "$ENV_FILE" <<EOF
POSTGRES_DB=messenger
POSTGRES_USER=postgres
POSTGRES_PASSWORD=$POSTGRES_PASSWORD
POSTGRES_API_PASSWORD=$POSTGRES_API_PASSWORD
POSTGRES_WORKER_PASSWORD=$POSTGRES_WORKER_PASSWORD
MINIO_ROOT_USER=lab7operator
MINIO_ROOT_PASSWORD=$MINIO_ROOT_PASSWORD
S3_API_ACCESS_KEY=$S3_API_ACCESS_KEY
S3_API_SECRET_KEY=$S3_API_SECRET_KEY
S3_WORKER_ACCESS_KEY=$S3_WORKER_ACCESS_KEY
S3_WORKER_SECRET_KEY=$S3_WORKER_SECRET_KEY
RABBITMQ_DEFAULT_USER=lab7operator
RABBITMQ_DEFAULT_PASS=$RABBITMQ_DEFAULT_PASSWORD
RABBITMQ_API_PASSWORD=$RABBITMQ_API_PASSWORD
RABBITMQ_WORKER_PASSWORD=$RABBITMQ_WORKER_PASSWORD
GRAFANA_ADMIN_USER=operator
GRAFANA_ADMIN_PASSWORD=$GRAFANA_ADMIN_PASSWORD
EOF
chmod 600 "$ENV_FILE"
for pair in \
"api_db_password:$POSTGRES_API_PASSWORD" \
"worker_db_password:$POSTGRES_WORKER_PASSWORD"
do
name=${pair%%:*}
value=${pair#*:}
printf '%s' "$value" > "$SECRETS_DIR/$name"
chmod 600 "$SECRETS_DIR/$name"
done
printf 'Created non-overwriting local runtime secrets: %s\n' "$ENV_FILE"
printf 'Do not print or commit .env; only the one-shot provisioners receive its credentials.\n'
+44
View File
@@ -0,0 +1,44 @@
#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
PKI_DIR="$ROOT/secrets/pki"
RUNTIME_PKI="$ROOT/secrets/runtime-pki"
if [ ! -f "$PKI_DIR/ca.crt" ]; then
"$ROOT/scripts/bootstrap-local-pki.sh"
elif [ ! -f "$RUNTIME_PKI/ingress/server.crt" ]; then
for certificate in ingress api-server api-client worker-client postgres-server \
s3-server rabbit-server openbao-server collector-server prometheus-server \
loki-server tempo-server grafana-server; do
if [ ! -f "$PKI_DIR/$certificate.crt" ] || [ ! -f "$PKI_DIR/$certificate.key" ]; then
printf 'Existing local PKI is incomplete: %s\n' "$PKI_DIR/$certificate" >&2
exit 1
fi
done
mkdir -p "$RUNTIME_PKI"
for service in ingress api postgres s3 rabbit openbao collector prometheus loki tempo grafana; do
certificate="$service-server"
[ "$service" != ingress ] || certificate=ingress
mkdir -p "$RUNTIME_PKI/$service"
cp "$PKI_DIR/ca.crt" "$RUNTIME_PKI/$service/ca.crt"
cp "$PKI_DIR/$certificate.crt" "$RUNTIME_PKI/$service/server.crt"
cp "$PKI_DIR/$certificate.key" "$RUNTIME_PKI/$service/server.key"
done
cp "$PKI_DIR/lb-client.crt" "$RUNTIME_PKI/ingress/client.crt"
cp "$PKI_DIR/lb-client.key" "$RUNTIME_PKI/ingress/client.key"
cp "$PKI_DIR/api-client.crt" "$RUNTIME_PKI/api/client.crt"
cp "$PKI_DIR/api-client.key" "$RUNTIME_PKI/api/client.key"
mkdir -p "$RUNTIME_PKI/worker"
cp "$PKI_DIR/ca.crt" "$RUNTIME_PKI/worker/ca.crt"
cp "$PKI_DIR/worker-client.crt" "$RUNTIME_PKI/worker/client.crt"
cp "$PKI_DIR/worker-client.key" "$RUNTIME_PKI/worker/client.key"
chmod 600 "$RUNTIME_PKI"/*/*.key
fi
if [ ! -f "$ROOT/.env" ]; then
"$ROOT/scripts/bootstrap-local-secrets.sh"
fi
"$ROOT/scripts/bootstrap-untrusted-client.sh"
printf 'Local PKI and stack secrets are ready. Next run: make up\n'
+44
View File
@@ -0,0 +1,44 @@
#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
PKI_DIR="$ROOT/secrets/pki"
umask 077
if [ -f "$PKI_DIR/foreign-client.crt" ] && [ -f "$PKI_DIR/foreign-client.key" ] \
&& [ -f "$PKI_DIR/foreign-ca.crt" ]; then
exit 0
fi
if [ -e "$PKI_DIR/foreign-client.crt" ] || [ -e "$PKI_DIR/foreign-client.key" ] \
|| [ -e "$PKI_DIR/foreign-ca.crt" ]; then
printf '%s\n' "Incomplete foreign test identity in $PKI_DIR; inspect it before repair." >&2
exit 1
fi
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$PKI_DIR/foreign-ca.key"
openssl req -x509 -new -key "$PKI_DIR/foreign-ca.key" -sha256 -days 365 \
-subj "/CN=MTUSI Lab 7 Untrusted Test CA" \
-addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
-addext "keyUsage=critical,keyCertSign,cRLSign" \
-out "$PKI_DIR/foreign-ca.crt"
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 \
-out "$PKI_DIR/foreign-client.key"
openssl req -new -key "$PKI_DIR/foreign-client.key" \
-subj "/CN=untrusted-load-balancer" -out "$PKI_DIR/foreign-client.csr"
cat > "$PKI_DIR/foreign-client.ext" <<'EOF'
[v3_req]
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=clientAuth
subjectAltName=URI:spiffe://lab7/role/load-balancer
EOF
openssl x509 -req -in "$PKI_DIR/foreign-client.csr" \
-CA "$PKI_DIR/foreign-ca.crt" -CAkey "$PKI_DIR/foreign-ca.key" \
-CAcreateserial -out "$PKI_DIR/foreign-client.crt" -days 90 -sha256 \
-extfile "$PKI_DIR/foreign-client.ext" -extensions v3_req
rm -f "$PKI_DIR/foreign-ca.key" "$PKI_DIR/foreign-ca.srl" \
"$PKI_DIR/foreign-client.csr" "$PKI_DIR/foreign-client.ext"
chmod 600 "$PKI_DIR/foreign-client.key"
chmod 644 "$PKI_DIR/foreign-client.crt" "$PKI_DIR/foreign-ca.crt"
printf '%s\n' "Created local untrusted client identity for negative mTLS testing."
+8 -2
View File
@@ -40,7 +40,13 @@ def main():
assert 'X-Instance-Id' in response['headers']
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
python_files = (
list((ROOT/'tests').glob('*.py'))
+ list((ROOT/'scripts').glob('*.py'))
+ list((ROOT/'app').glob('*.py'))
+ list((ROOT/'infra/openbao').glob('*.py'))
)
for file in python_files:
ast.parse(file.read_text(),filename=str(file))
for file in ROOT.rglob('*.json'):
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
@@ -48,7 +54,7 @@ def main():
json.loads(file.read_text())
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
assert (ROOT/required).is_file(), 'missing '+required
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
print('PASS: offline structure, local refs, JSON and Python syntax; runtime requires Compose.')
if __name__=='__main__':
main()
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Initialize and provision the local persistent OpenBao instance."""
import json
import os
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
OPERATOR_FILE = ROOT / "secrets" / "openbao-operator.json"
def main() -> int:
if not (ROOT / ".env").is_file():
raise RuntimeError("local secrets are missing; run make bootstrap first")
if not OPERATOR_FILE.exists():
result = subprocess.run(
[
"docker", "compose", "exec", "-T", "openbao", "bao", "operator",
"init", "-key-shares=1", "-key-threshold=1", "-format=json",
],
cwd=ROOT,
capture_output=True,
text=True,
check=False,
)
if result.returncode:
raise RuntimeError(
"OpenBao initialization failed. If the persistent volume was already initialized, "
"restore the operator recovery material instead of reinitializing it."
)
material = json.loads(result.stdout)
if not material.get("root_token") or not material.get("unseal_keys_b64"):
raise RuntimeError("OpenBao initialization returned incomplete operator material")
OPERATOR_FILE.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
fd = os.open(OPERATOR_FILE, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as output:
json.dump(material, output)
output.write("\n")
else:
material = json.loads(OPERATOR_FILE.read_text(encoding="utf-8"))
if not material.get("root_token") or not material.get("unseal_keys_b64"):
raise RuntimeError("local OpenBao operator file is incomplete")
result = subprocess.run(
["docker", "compose", "run", "--rm", "--no-deps", "openbao-provisioner"],
cwd=ROOT,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
if result.returncode:
raise RuntimeError(
"OpenBao provisioning failed. Inspect service readiness and local operator state; "
"secret values and tokens were not printed."
)
print("OpenBao is unsealed; scoped API/worker AppRoles and secrets are provisioned.")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except (OSError, ValueError, RuntimeError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
raise SystemExit(1)
+33
View File
@@ -0,0 +1,33 @@
#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
set -a
. "$ROOT/.env"
set +a
attempt=0
ready=0
while [ "$attempt" -lt 60 ]; do
if docker compose exec -T postgres \
pg_isready -U "$POSTGRES_USER" -d "$POSTGRES_DB" >/dev/null 2>&1; then
ready=1
break
fi
attempt=$((attempt + 1))
sleep 2
done
[ "$ready" -eq 1 ] || {
printf '%s\n' "PostgreSQL did not become ready" >&2
exit 1
}
{
printf '%s\n' "\\set api_password '$POSTGRES_API_PASSWORD'"
printf '%s\n' "\\set worker_password '$POSTGRES_WORKER_PASSWORD'"
cat "$ROOT/infra/postgres/roles.sql"
} | docker compose exec -T -e "PGPASSWORD=$POSTGRES_PASSWORD" postgres \
psql --host=/var/run/postgresql --username "$POSTGRES_USER" \
--dbname "$POSTGRES_DB" --set=ON_ERROR_STOP=1
printf '%s\n' "PostgreSQL API/worker roles provisioned with separate credentials."
+44
View File
@@ -0,0 +1,44 @@
#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
set -a
. "$ROOT/.env"
set +a
attempt=0
ready=0
while [ "$attempt" -lt 60 ]; do
if docker compose exec -T rabbitmq rabbitmq-diagnostics -q ping >/dev/null 2>&1; then
ready=1
break
fi
attempt=$((attempt + 1))
sleep 2
done
[ "$ready" -eq 1 ] || {
printf '%s\n' "RabbitMQ did not become ready" >&2
exit 1
}
compose() {
docker compose exec -T rabbitmq rabbitmqctl "$@"
}
ensure_user() {
username=$1
password=$2
if compose list_users | awk 'NR > 1 { print $1 }' | grep -Fxq "$username"; then
compose change_password "$username" "$password" >/dev/null
else
compose add_user "$username" "$password" >/dev/null
fi
}
ensure_user messenger_api "$RABBITMQ_API_PASSWORD"
compose set_permissions -p messenger messenger_api '^attachment\.jobs$' '^amq\.default$' '^$' >/dev/null
ensure_user messenger_worker "$RABBITMQ_WORKER_PASSWORD"
compose set_permissions -p messenger messenger_worker '^attachment\.jobs$' '^amq\.default$' '^attachment\.jobs$' >/dev/null
printf '%s\n' "RabbitMQ API/worker credentials provisioned with vhost-scoped permissions."
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"
if [ ! -f .env ] || [ ! -f secrets/pki/ca.crt ]; then
scripts/bootstrap-local-stack.sh
fi
docker compose up -d certs-init postgres s3 rabbitmq openbao
scripts/provision-db.sh
docker compose run --rm --no-deps s3-provisioner
scripts/provision-rabbitmq.sh
python3 scripts/initialize-openbao.py
docker compose up -d --build
printf '%s\n' "Stack started. Public endpoint: https://localhost:8443"
printf '%s\n' "Use CA_FILE=secrets/pki/ca.crt make test and make test-security."
+1 -1
View File
@@ -20,4 +20,4 @@ for path in (root/'contracts').glob('*.schema.json'):
Draft202012Validator.check_schema(schema)
for example in schema.get('examples',[]):
Draft202012Validator(schema).validate(example)
print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.')
print('PASS: full OpenAPI 3.1 and JSON Schema validation.')