forked from mtusi2026/mtusi2026lab7
Implement lab7 security and compromised worker recovery evidence
This commit is contained in:
@@ -0,0 +1,239 @@
|
||||
import argparse
|
||||
import ipaddress
|
||||
import json
|
||||
import secrets
|
||||
import os
|
||||
import subprocess
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from cryptography.hazmat.primitives.serialization import pkcs12
|
||||
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PRIVATE = ROOT / "secrets"
|
||||
ROLES = (
|
||||
"lb",
|
||||
"api",
|
||||
"worker",
|
||||
"dispatcher",
|
||||
"gateway",
|
||||
"db",
|
||||
"minio",
|
||||
"openbao",
|
||||
"collector",
|
||||
"prometheus",
|
||||
"grafana",
|
||||
"operator",
|
||||
"intruder",
|
||||
)
|
||||
|
||||
|
||||
def write(path, value):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(value.encode() if isinstance(value, str) else value)
|
||||
|
||||
|
||||
def key_bytes(key):
|
||||
return key.private_bytes(
|
||||
serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()
|
||||
)
|
||||
|
||||
|
||||
def authority():
|
||||
path = PRIVATE / "operator/ca.key"
|
||||
if path.exists():
|
||||
return serialization.load_pem_private_key(
|
||||
path.read_bytes(), None
|
||||
), x509.load_pem_x509_certificate((PRIVATE / "public/ca.crt").read_bytes())
|
||||
key = rsa.generate_private_key(public_exponent=65537, key_size=3072)
|
||||
now = datetime.now(timezone.utc)
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Messenger lab7 local CA")])
|
||||
cert = (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(name)
|
||||
.issuer_name(name)
|
||||
.public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now - timedelta(minutes=5))
|
||||
.not_valid_after(now + timedelta(days=365))
|
||||
.add_extension(x509.BasicConstraints(ca=True, path_length=0), True)
|
||||
.add_extension(
|
||||
x509.KeyUsage(False, False, False, False, False, True, True, False, False), True
|
||||
)
|
||||
.sign(key, hashes.SHA256())
|
||||
)
|
||||
write(path, key_bytes(key))
|
||||
write(PRIVATE / "public/ca.crt", cert.public_bytes(serialization.Encoding.PEM))
|
||||
return key, cert
|
||||
|
||||
|
||||
def leaf(role, ca_key, ca_cert, minutes=480):
|
||||
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
now = datetime.now(timezone.utc)
|
||||
names = [
|
||||
x509.DNSName(role),
|
||||
x509.DNSName("localhost"),
|
||||
x509.IPAddress(ipaddress.ip_address("127.0.0.1")),
|
||||
x509.UniformResourceIdentifier("spiffe://messenger/" + role),
|
||||
]
|
||||
if role == "gateway":
|
||||
names += [
|
||||
x509.DNSName(n)
|
||||
for n in ("broker", "redis", "otel-collector", "prometheus", "loki", "tempo", "grafana")
|
||||
]
|
||||
cert = (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, role)]))
|
||||
.issuer_name(ca_cert.subject)
|
||||
.public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now - timedelta(minutes=1))
|
||||
.not_valid_after(now + timedelta(minutes=minutes))
|
||||
.add_extension(x509.BasicConstraints(ca=False, path_length=None), True)
|
||||
.add_extension(x509.SubjectAlternativeName(names), False)
|
||||
.add_extension(
|
||||
x509.ExtendedKeyUsage(
|
||||
[ExtendedKeyUsageOID.CLIENT_AUTH]
|
||||
if role
|
||||
in (
|
||||
"worker",
|
||||
"dispatcher",
|
||||
"collector",
|
||||
"prometheus",
|
||||
"grafana",
|
||||
"operator",
|
||||
"intruder",
|
||||
)
|
||||
else [ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH]
|
||||
),
|
||||
False,
|
||||
)
|
||||
.sign(ca_key, hashes.SHA256())
|
||||
)
|
||||
folder = PRIVATE / role
|
||||
write(folder / "service.crt", cert.public_bytes(serialization.Encoding.PEM))
|
||||
write(folder / "service.key", key_bytes(key))
|
||||
write(
|
||||
folder / "service.pk8",
|
||||
key.private_bytes(
|
||||
serialization.Encoding.DER,
|
||||
serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption(),
|
||||
),
|
||||
)
|
||||
write(
|
||||
folder / "service.p12",
|
||||
pkcs12.serialize_key_and_certificates(
|
||||
role.encode(), key, cert, [ca_cert], serialization.NoEncryption()
|
||||
),
|
||||
)
|
||||
write(
|
||||
folder / "trust.p12",
|
||||
pkcs12.serialize_java_truststore(
|
||||
[pkcs12.PKCS12Certificate(ca_cert, b"local-ca")], serialization.NoEncryption()
|
||||
),
|
||||
)
|
||||
return cert
|
||||
|
||||
|
||||
def crl(ca_key, ca_cert, serials):
|
||||
now = datetime.now(timezone.utc)
|
||||
builder = (
|
||||
x509.CertificateRevocationListBuilder()
|
||||
.issuer_name(ca_cert.subject)
|
||||
.last_update(now)
|
||||
.next_update(now + timedelta(days=7))
|
||||
)
|
||||
for serial in serials:
|
||||
builder = builder.add_revoked_certificate(
|
||||
x509.RevokedCertificateBuilder().serial_number(serial).revocation_date(now).build()
|
||||
)
|
||||
write(
|
||||
PRIVATE / "public/ca.crl",
|
||||
builder.sign(ca_key, hashes.SHA256()).public_bytes(serialization.Encoding.PEM),
|
||||
)
|
||||
|
||||
|
||||
def credentials():
|
||||
path = PRIVATE / "operator/credentials.json"
|
||||
if path.exists():
|
||||
return
|
||||
roles = {}
|
||||
for role in ("api", "worker", "dispatcher"):
|
||||
roles[role] = dict(
|
||||
postgres_db="messenger",
|
||||
postgres_user=role,
|
||||
postgres_password=secrets.token_hex(24),
|
||||
s3_access_key_id=role,
|
||||
s3_secret_access_key=secrets.token_hex(24),
|
||||
broker_user=role,
|
||||
broker_password=secrets.token_hex(24),
|
||||
cache_password=secrets.token_hex(24),
|
||||
)
|
||||
data = dict(
|
||||
roles=roles,
|
||||
postgres_password=secrets.token_hex(24),
|
||||
minio_root_user="operator",
|
||||
minio_root_password=secrets.token_hex(24),
|
||||
grafana_password=secrets.token_hex(24),
|
||||
)
|
||||
write(path, json.dumps(data))
|
||||
for name in ("postgres_password", "minio_root_user", "minio_root_password", "grafana_password"):
|
||||
write(PRIVATE / "operator" / name, data[name])
|
||||
|
||||
|
||||
def main():
|
||||
PRIVATE.mkdir(parents=True, exist_ok=True)
|
||||
if os.name == "nt":
|
||||
account = os.environ["USERDOMAIN"] + "\\" + os.environ["USERNAME"]
|
||||
subprocess.run(
|
||||
[
|
||||
"icacls",
|
||||
str(PRIVATE),
|
||||
"/inheritance:r",
|
||||
"/grant:r",
|
||||
account + ":(OI)(CI)F",
|
||||
"*S-1-5-18:(OI)(CI)F",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
else:
|
||||
PRIVATE.chmod(0o700)
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--rotate", choices=ROLES)
|
||||
args = parser.parse_args()
|
||||
key, cert = authority()
|
||||
for role in ([args.rotate] if args.rotate else ROLES):
|
||||
if args.rotate or not (PRIVATE / role / "service.crt").exists():
|
||||
leaf(role, key, cert)
|
||||
if not (PRIVATE / "foreign/service.crt").exists():
|
||||
foreign_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
now = datetime.now(timezone.utc)
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Untrusted test CA")])
|
||||
foreign_ca = (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(name)
|
||||
.issuer_name(name)
|
||||
.public_key(foreign_key.public_key())
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now - timedelta(minutes=1))
|
||||
.not_valid_after(now + timedelta(days=1))
|
||||
.add_extension(x509.BasicConstraints(ca=True, path_length=0), True)
|
||||
.sign(foreign_key, hashes.SHA256())
|
||||
)
|
||||
leaf("foreign", foreign_key, foreign_ca)
|
||||
if not (PRIVATE / "public/ca.crl").exists():
|
||||
crl(key, cert, [])
|
||||
credentials()
|
||||
if not (ROOT / ".env").exists():
|
||||
write(ROOT / ".env", "COMPOSE_PROJECT_NAME=messenger-lab7\nSESSION_TTL_SECONDS=3600\n")
|
||||
print("Local PKI and operator credentials prepared; private values omitted.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,64 @@
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def private_values():
|
||||
result = []
|
||||
|
||||
def collect(value):
|
||||
if isinstance(value, dict):
|
||||
for item in value.values():
|
||||
collect(item)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
collect(item)
|
||||
elif isinstance(value, str) and len(value) >= 20:
|
||||
result.append(value)
|
||||
|
||||
for path in (ROOT / "secrets/operator").glob("*.json"):
|
||||
collect(json.loads(path.read_text()))
|
||||
for path in (ROOT / "secrets/operator").glob("*.txt"):
|
||||
value = path.read_text().strip()
|
||||
if len(value) >= 20:
|
||||
result.append(value)
|
||||
return result
|
||||
|
||||
|
||||
def run(name, command):
|
||||
started = datetime.now(timezone.utc).isoformat()
|
||||
before = time.monotonic()
|
||||
output = subprocess.run(command, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
text = output.stdout.decode("utf-8", errors="replace").replace("\r\n", "\n")
|
||||
if any(value in text for value in private_values()):
|
||||
raise RuntimeError("Private value detected in command output; evidence withheld")
|
||||
report = (
|
||||
"Command: "
|
||||
+ json.dumps(command, ensure_ascii=False)
|
||||
+ "\nUTC: "
|
||||
+ started
|
||||
+ "\nExit code: "
|
||||
+ str(output.returncode)
|
||||
+ "\nElapsed seconds: "
|
||||
+ str(round(time.monotonic() - before, 3))
|
||||
+ "\n\n"
|
||||
+ text
|
||||
)
|
||||
(ROOT / "evidence" / (name + ".txt")).write_text(report, encoding="utf-8", newline="\n")
|
||||
print(text, end="", flush=True)
|
||||
if output.returncode:
|
||||
raise SystemExit(output.returncode)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("name")
|
||||
parser.add_argument("command", nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args()
|
||||
run(args.name, args.command)
|
||||
@@ -0,0 +1,56 @@
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from capture import ROOT, private_values
|
||||
|
||||
|
||||
def main():
|
||||
names = subprocess.check_output(["git", "ls-files", "--cached", "-z"], cwd=ROOT)
|
||||
files = [name.decode() for name in names.split(b"\0") if name]
|
||||
secrets = private_values()
|
||||
sources = []
|
||||
for name in files:
|
||||
path = Path(name)
|
||||
assert "secrets" not in path.parts, "Private directory staged"
|
||||
assert path.name != ".env", "Environment secrets staged"
|
||||
assert path.suffix not in {
|
||||
".key",
|
||||
".p12",
|
||||
".pfx",
|
||||
".jks",
|
||||
".pem",
|
||||
}, "Private material staged"
|
||||
content = subprocess.check_output(["git", "show", ":" + name], cwd=ROOT)
|
||||
text = content.decode("utf-8", errors="replace")
|
||||
assert not re.search(
|
||||
r"^-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----", text, re.MULTILINE
|
||||
), "Private key staged"
|
||||
assert not any(value in text for value in secrets), "Known secret staged"
|
||||
if path.parts[0] != "evidence":
|
||||
sources.append(dict(path=name, sha256=hashlib.sha256(content).hexdigest()))
|
||||
for path in (ROOT / "evidence").glob("*.txt"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
if text.startswith("Command:"):
|
||||
assert "\nExit code: 0\n" in text, "Failed evidence: " + path.name
|
||||
for target in re.findall(r"\]\(([^)]+)\)", (ROOT / "REPORT.md").read_text()):
|
||||
if "://" not in target and target != "evidence/source-manifest.json":
|
||||
assert (ROOT / target).exists(), "Missing report evidence: " + target
|
||||
output = dict(
|
||||
utc=datetime.now(timezone.utc).isoformat(),
|
||||
upstream_base="20afc2c",
|
||||
branch="solution/bvt2301-ivanov",
|
||||
method="SHA-256 of staged source bytes; source list excludes evidence to avoid recursive hashes. Compare files after checkout with LF endings.",
|
||||
no_known_secrets_or_private_keys_staged=True,
|
||||
captured_commands_successful=True,
|
||||
source_files=sources,
|
||||
)
|
||||
(ROOT / "evidence/source-manifest.json").write_text(json.dumps(output, indent=2) + "\n")
|
||||
print("PASS staged source integrity, secret exclusion and captured command exit codes")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,220 @@
|
||||
import json
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from bootstrap import PRIVATE, ROOT, write
|
||||
|
||||
|
||||
def compose(*args, stdin=None):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
cwd=ROOT,
|
||||
input=stdin.encode() if stdin is not None else None,
|
||||
capture_output=True,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError("Compose operation failed: " + " ".join(args[:3]))
|
||||
return result.stdout.decode()
|
||||
|
||||
|
||||
def bao(path, data=None, token=None, method=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
body = None if data is None else json.dumps(data).encode()
|
||||
req = urllib.request.Request("https://127.0.0.1:18200/v1/" + path, body, headers, method=method)
|
||||
context = ssl.create_default_context(cafile=str(PRIVATE / "public/ca.crt"))
|
||||
with urllib.request.urlopen(req, context=context, timeout=10) as response:
|
||||
raw = response.read()
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def prepare():
|
||||
data = json.loads((PRIVATE / "operator/credentials.json").read_text())
|
||||
if "broker_operator_password" not in data:
|
||||
data["broker_operator_password"] = secrets.token_hex(24)
|
||||
write(PRIVATE / "operator/credentials.json", json.dumps(data))
|
||||
for source, target in [("service.crt", "public.crt"), ("service.key", "private.key")]:
|
||||
write(PRIVATE / "minio" / target, (PRIVATE / "minio" / source).read_bytes())
|
||||
commands = dict(
|
||||
worker="+ping +hello +client|setinfo +client|setname +xgroup +xreadgroup +xautoclaim +xack +xdel +xrange +hget +hdel +eval",
|
||||
dispatcher="+ping +hello +client|setinfo +client|setname +eval +xadd +xrange +hget +hset",
|
||||
api="+ping",
|
||||
)
|
||||
acl = "user default off resetpass ~* &* +@all\n"
|
||||
acl += f"user operator on >{data['broker_operator_password']} ~* +@all\n"
|
||||
for role, values in data["roles"].items():
|
||||
acl += f"user {values['broker_user']} on >{values['broker_password']} ~attachment-jobs ~job-publications {commands[role]}\n"
|
||||
write(PRIVATE / "operator/broker.acl", acl)
|
||||
write(
|
||||
PRIVATE / "operator/redis.acl",
|
||||
f"user default off resetpass ~* &* +@all\nuser api on >{data['roles']['api']['cache_password']} ~sessions::* +ping +hello +client|setinfo +client|setname +get +set +del +unlink +pexpire +pttl\n",
|
||||
)
|
||||
print("Local runtime files prepared.")
|
||||
|
||||
|
||||
def initialize_bao():
|
||||
path = PRIVATE / "operator/bao-init.json"
|
||||
if not path.exists():
|
||||
write(path, json.dumps(bao("sys/init", {"secret_shares": 1, "secret_threshold": 1})))
|
||||
init = json.loads(path.read_text())
|
||||
bao("sys/unseal", {"key": init["keys"][0]})
|
||||
token = init["root_token"]
|
||||
for endpoint, body in [
|
||||
("sys/mounts/secret", dict(type="kv", options={"version": "2"})),
|
||||
("sys/auth/cert", dict(type="cert")),
|
||||
]:
|
||||
try:
|
||||
bao(endpoint, body, token)
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code != 400:
|
||||
raise
|
||||
bao("auth/cert/crls/lab7", {"crl": (PRIVATE / "public/ca.crl").read_text()}, token)
|
||||
roles = json.loads((PRIVATE / "operator/credentials.json").read_text())["roles"]
|
||||
ca = (PRIVATE / "public/ca.crt").read_text()
|
||||
for role, values in roles.items():
|
||||
policy = f'path "secret/data/{role}" {{ capabilities = ["read"] }}\npath "auth/token/revoke-self" {{ capabilities = ["update"] }}\n'
|
||||
write(ROOT / "infra/security/policies" / (role + ".hcl"), policy)
|
||||
bao("sys/policies/acl/" + role, {"policy": policy}, token)
|
||||
bao(
|
||||
"auth/cert/certs/" + role,
|
||||
dict(
|
||||
certificate=ca,
|
||||
allowed_common_names=[role],
|
||||
allowed_uri_sans=["spiffe://messenger/" + role],
|
||||
token_policies=[role],
|
||||
token_no_default_policy=True,
|
||||
token_ttl=60,
|
||||
token_max_ttl=60,
|
||||
),
|
||||
token,
|
||||
)
|
||||
bao("secret/data/" + role, {"data": values}, token)
|
||||
print("Persistent OpenBao initialized/unsealed; scoped cert authentication configured.")
|
||||
|
||||
|
||||
def initialize_db():
|
||||
data = json.loads((PRIVATE / "operator/credentials.json").read_text())
|
||||
roles = data["roles"]
|
||||
if "pipeline_operator_password" not in data:
|
||||
data["pipeline_operator_password"] = __import__("secrets").token_hex(24)
|
||||
write(PRIVATE / "operator/credentials.json", json.dumps(data))
|
||||
write(
|
||||
PRIVATE / "operator/pipeline.json",
|
||||
json.dumps(
|
||||
dict(
|
||||
postgres_db="messenger",
|
||||
postgres_user="pipeline_operator",
|
||||
postgres_password=data["pipeline_operator_password"],
|
||||
)
|
||||
),
|
||||
)
|
||||
diagnostics = dict(
|
||||
postgres_db="messenger",
|
||||
postgres_user="pipeline_operator",
|
||||
postgres_password=data["pipeline_operator_password"],
|
||||
s3_access_key_id=data["minio_root_user"],
|
||||
s3_secret_access_key=data["minio_root_password"],
|
||||
)
|
||||
write(PRIVATE / "operator/diagnostics.json", json.dumps(diagnostics))
|
||||
migration = (ROOT / "src/main/resources/db/migration/V1__init.sql").read_text()
|
||||
existing = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"db",
|
||||
"psql",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-Atc",
|
||||
"SELECT to_regclass('public.users')",
|
||||
)
|
||||
sql = "BEGIN;\n"
|
||||
if not existing.strip():
|
||||
sql += migration
|
||||
for role, values in roles.items():
|
||||
sql += f"\nDO $$ BEGIN IF NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='{role}') THEN CREATE ROLE {role} LOGIN; END IF; END $$;\nALTER ROLE {role} WITH PASSWORD '{values['postgres_password']}';\nGRANT CONNECT ON DATABASE messenger TO {role}; GRANT USAGE ON SCHEMA public TO {role};\n"
|
||||
sql += "REVOKE ALL ON DATABASE messenger FROM PUBLIC; REVOKE CREATE ON SCHEMA public FROM PUBLIC;\n"
|
||||
sql += "REVOKE ALL ON ALL TABLES IN SCHEMA public FROM api,worker,dispatcher;\n"
|
||||
sql += "GRANT SELECT,INSERT ON users,chats,chat_members,messages,sessions,attachments,message_attachments,processing_jobs,processing_outbox,login_budget TO api; GRANT UPDATE(password_hash) ON users TO api; GRANT UPDATE(title) ON chats TO api; GRANT UPDATE(status) ON attachments TO api; GRANT UPDATE ON sessions,login_budget TO api; GRANT SELECT,INSERT,UPDATE,DELETE ON idempotency_keys TO api; GRANT SELECT ON attachment_variants TO api;\n"
|
||||
sql += "GRANT SELECT(id,object_key,staging_key,content_type,checksum,size_bytes,pipeline_version,status,updated_at,error_code,created_at) ON attachments TO worker; GRANT UPDATE(object_key,staging_key,status,updated_at,error_code) ON attachments TO worker; GRANT SELECT ON processing_jobs TO worker; GRANT UPDATE(status,attempt,lease_token,lease_until,next_at,next_publish_at,error_code,completed_at) ON processing_jobs TO worker; GRANT SELECT,INSERT ON attachment_variants TO worker; GRANT INSERT ON pipeline_events TO worker;\n"
|
||||
sql += "GRANT SELECT(id,object_key,staging_key,pipeline_version,status,updated_at,error_code) ON attachments TO dispatcher; GRANT UPDATE(staging_key,status,updated_at,error_code) ON attachments TO dispatcher; GRANT SELECT ON processing_jobs,processing_outbox,attachment_variants TO dispatcher; GRANT UPDATE(status,lease_until,next_at,next_publish_at,error_code,completed_at) ON processing_jobs TO dispatcher; GRANT UPDATE(published_at,publish_count) ON processing_outbox TO dispatcher; GRANT INSERT ON pipeline_events TO dispatcher;\n"
|
||||
sql += "GRANT USAGE ON SEQUENCE pipeline_events_seq_seq TO worker,dispatcher;\n"
|
||||
password = data["pipeline_operator_password"]
|
||||
sql += f"DO $$ BEGIN IF NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='pipeline_operator') THEN CREATE ROLE pipeline_operator LOGIN; END IF; END $$; ALTER ROLE pipeline_operator PASSWORD '{password}';\n"
|
||||
sql += "GRANT CONNECT ON DATABASE messenger TO pipeline_operator; GRANT USAGE ON SCHEMA public TO pipeline_operator; GRANT SELECT,INSERT,UPDATE ON attachments,processing_jobs,processing_outbox,pipeline_events TO pipeline_operator; GRANT SELECT ON attachment_variants TO pipeline_operator; GRANT USAGE ON SEQUENCE pipeline_events_seq_seq TO pipeline_operator;\n"
|
||||
sql += "COMMIT;\n"
|
||||
compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"db",
|
||||
"psql",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
stdin=sql,
|
||||
)
|
||||
print("Schema and restricted database roles ready.")
|
||||
|
||||
|
||||
def initialize_s3():
|
||||
data = json.loads((PRIVATE / "operator/credentials.json").read_text())
|
||||
script = (
|
||||
"set -eu\nmc alias set local https://minio:9000 "
|
||||
+ data["minio_root_user"]
|
||||
+ " "
|
||||
+ data["minio_root_password"]
|
||||
+ " >/dev/null\nmc mb --ignore-existing local/messenger-attachments >/dev/null\nmc anonymous set none local/messenger-attachments >/dev/null\n"
|
||||
)
|
||||
for role, values in data["roles"].items():
|
||||
statements = [
|
||||
dict(
|
||||
Effect="Allow",
|
||||
Action=(
|
||||
["s3:GetBucketLocation"]
|
||||
if role == "worker"
|
||||
else ["s3:GetBucketLocation", "s3:ListBucket"]
|
||||
),
|
||||
Resource=["arn:aws:s3:::messenger-attachments"],
|
||||
)
|
||||
]
|
||||
rights = {
|
||||
"api": [
|
||||
("staging/*", ["s3:PutObject", "s3:GetObject", "s3:DeleteObject"]),
|
||||
("results/*", ["s3:GetObject"]),
|
||||
],
|
||||
"worker": [
|
||||
("staging/*", ["s3:GetObject", "s3:DeleteObject"]),
|
||||
("results/*", ["s3:PutObject", "s3:GetObject"]),
|
||||
],
|
||||
"dispatcher": [("staging/*", ["s3:DeleteObject"]), ("results/*", ["s3:DeleteObject"])],
|
||||
}[role]
|
||||
for prefix, actions in rights:
|
||||
statements.append(
|
||||
dict(
|
||||
Effect="Allow",
|
||||
Action=actions,
|
||||
Resource=["arn:aws:s3:::messenger-attachments/" + prefix],
|
||||
)
|
||||
)
|
||||
policy = json.dumps(dict(Version="2012-10-17", Statement=statements))
|
||||
write(ROOT / f"infra/security/policies/{role}-s3.json", policy)
|
||||
script += f"mc admin user add local {values['s3_access_key_id']} {values['s3_secret_access_key']} >/dev/null\nmc admin policy create local {role} /policies/{role}-s3.json >/dev/null\nmc admin policy attach local {role} --user {values['s3_access_key_id']} >/dev/null\n"
|
||||
compose("run", "--rm", "--no-deps", "-T", "s3-admin", stdin=script)
|
||||
print("Private S3 bucket and separate prefix policies ready.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
{"prepare": prepare, "bao": initialize_bao, "db": initialize_db, "s3": initialize_s3}[
|
||||
sys.argv[1]
|
||||
]()
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
"%~dp0..\.venv\Scripts\python.exe" "%~dp0stack_operator.py" restart
|
||||
exit /b %errorlevel%
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 scripts/stack_operator.py restart
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
RAW = ROOT / "build/scans"
|
||||
SCANNER = (
|
||||
"aquasec/trivy:0.69.3@sha256:bcc376de8d77cfe086a917230e818dc9f8528e3c852f7b1aff648949b6258d1c"
|
||||
)
|
||||
|
||||
|
||||
def scan(name, mode, target, mount=None, extra=()):
|
||||
command = [
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--security-opt",
|
||||
"no-new-privileges:true",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"-v",
|
||||
"messenger-lab7-trivy-cache:/root/.cache/trivy",
|
||||
"-v",
|
||||
str(RAW) + ":/reports",
|
||||
]
|
||||
if mount:
|
||||
command += ["-v", mount]
|
||||
command += [
|
||||
SCANNER,
|
||||
mode,
|
||||
"--timeout",
|
||||
"15m",
|
||||
"--scanners",
|
||||
"vuln",
|
||||
"--no-progress",
|
||||
"--skip-version-check",
|
||||
"--format",
|
||||
"json",
|
||||
"--output",
|
||||
"/reports/" + name + ".json",
|
||||
*extra,
|
||||
target,
|
||||
]
|
||||
result = subprocess.run(command, capture_output=True)
|
||||
if result.returncode:
|
||||
raise RuntimeError(
|
||||
"Scanner failed for " + name + ": " + result.stderr.decode(errors="replace")[-1000:]
|
||||
)
|
||||
return command
|
||||
|
||||
|
||||
def summary(path, command):
|
||||
raw = path.read_bytes()
|
||||
document = json.loads(raw)
|
||||
rows = []
|
||||
packages = set()
|
||||
for result in document.get("Results", []):
|
||||
for package in result.get("Packages", []):
|
||||
packages.add((package["Name"], package.get("Version", "not recorded")))
|
||||
for value in result.get("Vulnerabilities", []):
|
||||
rows.append(
|
||||
{
|
||||
k: value.get(k)
|
||||
for k in (
|
||||
"VulnerabilityID",
|
||||
"PkgName",
|
||||
"InstalledVersion",
|
||||
"FixedVersion",
|
||||
"Severity",
|
||||
"Status",
|
||||
"PrimaryURL",
|
||||
)
|
||||
}
|
||||
)
|
||||
return dict(
|
||||
command=command,
|
||||
exit_code=0,
|
||||
artifact=document.get("ArtifactName"),
|
||||
scanner=document.get("Metadata", {}).get("RepoDigests", []),
|
||||
raw_sha256=hashlib.sha256(raw).hexdigest(),
|
||||
findings=len(rows),
|
||||
severity=dict(Counter(r["Severity"] for r in rows)),
|
||||
resolved_package_records=len(packages),
|
||||
vulnerabilities=rows,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
RAW.mkdir(parents=True, exist_ok=True)
|
||||
compose = yaml.safe_load((ROOT / "docker-compose.yml").read_text())
|
||||
jars = list((ROOT / "build/libs").glob("messenger-lab7-*.jar"))
|
||||
if len(jars) != 1:
|
||||
raise RuntimeError("Build exactly one current messenger-lab7 bootJar first")
|
||||
jobs = [
|
||||
(
|
||||
"worker-resolved-scan",
|
||||
"fs",
|
||||
"/scan",
|
||||
str(ROOT / "worker/requirements-resolved.txt") + ":/scan/requirements.txt:ro",
|
||||
(),
|
||||
),
|
||||
("java-scan", "rootfs", "/scan", str(jars[0]) + ":/scan/app.jar:ro", ()),
|
||||
(
|
||||
"image-jre-scan",
|
||||
"image",
|
||||
(ROOT / "Dockerfile").read_text().split("FROM ")[-1].split()[0],
|
||||
None,
|
||||
("--image-src", "remote", "--pkg-types", "os"),
|
||||
),
|
||||
(
|
||||
"image-worker-updated-scan",
|
||||
"image",
|
||||
(ROOT / "worker/Dockerfile").read_text().splitlines()[0].split()[1],
|
||||
None,
|
||||
("--image-src", "remote", "--pkg-types", "os"),
|
||||
),
|
||||
(
|
||||
"image-nginx-scan",
|
||||
"image",
|
||||
compose["services"]["gateway"]["image"],
|
||||
None,
|
||||
("--image-src", "remote"),
|
||||
),
|
||||
(
|
||||
"image-bao-scan",
|
||||
"image",
|
||||
compose["services"]["openbao"]["image"],
|
||||
None,
|
||||
("--image-src", "remote"),
|
||||
),
|
||||
]
|
||||
previous = ROOT / "evidence/scan-summary.json"
|
||||
old = json.loads(previous.read_text()).get("reports", {}) if previous.exists() else {}
|
||||
results = {
|
||||
name: value
|
||||
for name, value in old.items()
|
||||
if "before" in name or name == "image-worker-base-scan"
|
||||
}
|
||||
for name, mode, target, mount, extra in jobs:
|
||||
command = scan(name, mode, target, mount, extra)
|
||||
results[name] = summary(RAW / (name + ".json"), command)
|
||||
print(name + ": " + str(results[name]["severity"]), flush=True)
|
||||
for path in (ROOT / "evidence").glob("*-scan*.json"):
|
||||
if path.name == "scan-summary.json":
|
||||
continue
|
||||
if "before" in path.stem or path.stem == "image-worker-base-scan":
|
||||
results[path.stem] = summary(
|
||||
path, "Initial recorded Trivy 0.69.3 baseline; see SCAN_TRIAGE.md"
|
||||
)
|
||||
output = dict(
|
||||
scanner=SCANNER,
|
||||
scope="Runtime Java JAR, all resolved worker packages including pip, four production base images. OS packages are unchanged by application Dockerfiles; no socket or secrets mount. Native libraries bundled inside wheels and all other infrastructure images are not a complete SBOM coverage claim.",
|
||||
reports=results,
|
||||
)
|
||||
(ROOT / "evidence/scan-summary.json").write_text(
|
||||
json.dumps(output, indent=2) + "\n", encoding="utf-8"
|
||||
)
|
||||
for name in ("worker-resolved-scan", "java-scan"):
|
||||
if results[name]["findings"]:
|
||||
raise RuntimeError("Runtime application dependency findings require triage: " + name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,108 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from bootstrap import PRIVATE, ROOT, write
|
||||
from provision import bao, compose
|
||||
|
||||
|
||||
def snapshot():
|
||||
ids = compose("ps", "-a", "-q").splitlines()
|
||||
result = {}
|
||||
for item in json.loads(subprocess.check_output(["docker", "inspect", *ids])):
|
||||
name = item["Config"]["Labels"]["com.docker.compose.service"]
|
||||
if (
|
||||
"com.docker.compose.oneoff" in item["Config"]["Labels"]
|
||||
and item["Config"]["Labels"]["com.docker.compose.oneoff"] == "True"
|
||||
):
|
||||
continue
|
||||
result[item["Name"].lstrip("/")] = dict(
|
||||
service=name,
|
||||
started_at=item["State"]["StartedAt"],
|
||||
image=item["Image"],
|
||||
status=item["State"]["Status"],
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def unseal():
|
||||
init = json.loads((PRIVATE / "operator/bao-init.json").read_text())
|
||||
for _ in range(20):
|
||||
try:
|
||||
bao("sys/unseal", {"key": init["keys"][0]})
|
||||
return
|
||||
except Exception:
|
||||
time.sleep(1)
|
||||
raise RuntimeError("Operator unseal failed")
|
||||
|
||||
|
||||
def restart():
|
||||
before = snapshot()
|
||||
compose("restart", "openbao")
|
||||
unseal()
|
||||
compose("restart", "gateway")
|
||||
roles = (
|
||||
"db",
|
||||
"redis",
|
||||
"broker",
|
||||
"minio",
|
||||
"otel-collector",
|
||||
"prometheus",
|
||||
"loki",
|
||||
"tempo",
|
||||
"grafana",
|
||||
"api-agent",
|
||||
"worker-agent",
|
||||
"dispatcher-agent",
|
||||
"api",
|
||||
"worker",
|
||||
"dispatcher",
|
||||
"lb",
|
||||
)
|
||||
compose("restart", "--timeout", "5", *roles)
|
||||
after = snapshot()
|
||||
changed = {
|
||||
name: row["started_at"] != before[name]["started_at"]
|
||||
for name, row in after.items()
|
||||
if name in before
|
||||
}
|
||||
if not changed or not all(changed.values()):
|
||||
raise RuntimeError("Not all intended containers restarted")
|
||||
write(
|
||||
ROOT / "evidence/restart-containers.json",
|
||||
json.dumps(
|
||||
dict(before=before, after=after, all_start_times_changed=True, volumes_preserved=True),
|
||||
indent=2,
|
||||
)
|
||||
+ "\n",
|
||||
)
|
||||
|
||||
|
||||
def stop_one():
|
||||
target = os.environ["TARGET_INSTANCE_ID"]
|
||||
selected = []
|
||||
for identifier in compose("ps", "-q", "api").splitlines():
|
||||
alias = (
|
||||
subprocess.check_output(["docker", "exec", identifier, "cat", "/tmp/instance-id"])
|
||||
.decode()
|
||||
.strip()
|
||||
)
|
||||
if alias == target:
|
||||
selected.append(identifier)
|
||||
if len(selected) != 1:
|
||||
raise RuntimeError("Instance alias did not resolve to exactly one running replica")
|
||||
before = snapshot()
|
||||
subprocess.run(["docker", "stop", "--time", "1", selected[0]], capture_output=True, check=True)
|
||||
history = ROOT / "evidence/failover-containers.json"
|
||||
events = json.loads(history.read_text()) if history.exists() else []
|
||||
events.append(
|
||||
dict(alias=target, stopped_container=selected[0], before=before, after=snapshot())
|
||||
)
|
||||
write(history, json.dumps(events, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
{"restart": restart, "stop-one": stop_one, "unseal": unseal}[sys.argv[1]]()
|
||||
@@ -0,0 +1,22 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Split-Path $PSScriptRoot -Parent)
|
||||
$Python = Join-Path (Get-Location) '.venv\Scripts\python.exe'
|
||||
|
||||
function Invoke-Step {
|
||||
param([string]$Program, [string[]]$Arguments)
|
||||
& $Program @Arguments
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Step failed: $Program $($Arguments[0])"
|
||||
}
|
||||
}
|
||||
|
||||
Invoke-Step $Python @('scripts/bootstrap.py')
|
||||
Invoke-Step $Python @('scripts/provision.py', 'prepare')
|
||||
Invoke-Step 'docker' @('compose', 'build')
|
||||
Invoke-Step 'docker' @('compose', 'run', '--rm', '--no-deps', '-T', 'bao-permissions')
|
||||
Invoke-Step 'docker' @('compose', 'run', '--rm', '--no-deps', '-T', 's3-permissions')
|
||||
Invoke-Step 'docker' @('compose', 'up', '-d', '--wait', '--wait-timeout', '120', 'gateway', 'db', 'minio', 'openbao')
|
||||
Invoke-Step $Python @('scripts/provision.py', 'bao')
|
||||
Invoke-Step $Python @('scripts/provision.py', 'db')
|
||||
Invoke-Step $Python @('scripts/provision.py', 's3')
|
||||
Invoke-Step 'docker' @('compose', 'up', '-d', '--wait', '--wait-timeout', '180')
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
PYTHON="${PYTHON:-.venv/bin/python}"
|
||||
"$PYTHON" scripts/bootstrap.py
|
||||
"$PYTHON" scripts/provision.py prepare
|
||||
docker compose build
|
||||
docker compose run --rm --no-deps -T bao-permissions
|
||||
docker compose run --rm --no-deps -T s3-permissions
|
||||
docker compose up -d --wait --wait-timeout 120 gateway db minio openbao
|
||||
"$PYTHON" scripts/provision.py bao
|
||||
"$PYTHON" scripts/provision.py db
|
||||
"$PYTHON" scripts/provision.py s3
|
||||
docker compose up -d --wait --wait-timeout 180
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
"%~dp0..\.venv\Scripts\python.exe" "%~dp0stack_operator.py" stop-one
|
||||
exit /b %errorlevel%
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 scripts/stack_operator.py stop-one
|
||||
@@ -0,0 +1,88 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.request
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VERSION = "1.28.0"
|
||||
SHA256 = "32342e7c1b4600f80df3471da46aee8012d3e1445d5ea1be1fb71289b07cc735"
|
||||
|
||||
|
||||
def formatter():
|
||||
jar = Path(tempfile.gettempdir()) / f"google-java-format-{VERSION}-all-deps.jar"
|
||||
if not jar.exists():
|
||||
url = (
|
||||
"https://repo.maven.apache.org/maven2/com/google/googlejavaformat/"
|
||||
f"google-java-format/{VERSION}/{jar.name}"
|
||||
)
|
||||
with urllib.request.urlopen(url, timeout=60) as response:
|
||||
jar.write_bytes(response.read())
|
||||
if hashlib.sha256(jar.read_bytes()).hexdigest() != SHA256:
|
||||
raise RuntimeError("Java formatter checksum mismatch")
|
||||
return jar
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--apply", action="store_true")
|
||||
args = parser.parse_args()
|
||||
java_home = os.environ.get("JAVA_HOME")
|
||||
java = str(Path(java_home) / "bin" / "java") if java_home else "java"
|
||||
files = sorted(str(p.relative_to(ROOT)) for p in (ROOT / "src").rglob("*.java"))
|
||||
mode = ["--replace"] if args.apply else ["--dry-run", "--set-exit-if-changed"]
|
||||
subprocess.run([java, "-jar", str(formatter()), "--aosp", *mode, *files], cwd=ROOT, check=True)
|
||||
python = ["worker/pipeline"]
|
||||
python += sorted(
|
||||
str(p.relative_to(ROOT))
|
||||
for p in (ROOT / "scripts").glob("*.py")
|
||||
if p.name not in {"check_contract.py", "validate_openapi.py"}
|
||||
)
|
||||
python += sorted(str(p.relative_to(ROOT)) for p in (ROOT / "student-tests").glob("*.py"))
|
||||
subprocess.run(
|
||||
[sys.executable, "-m", "black", *([] if args.apply else ["--check"]), *python],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
)
|
||||
check_controllers()
|
||||
print("PASS Java AOSP / Python Black style")
|
||||
|
||||
|
||||
def check_controllers():
|
||||
directory = ROOT / "src/main/java/ru/mtusi/messenger/controller"
|
||||
operations = 0
|
||||
for path in directory.glob("*Controller.java"):
|
||||
source = path.read_text(encoding="utf-8")
|
||||
fields = re.findall(r"private final (\w+Service) (\w+);", source)
|
||||
if "@RequiredArgsConstructor" not in source or len(fields) != 1:
|
||||
raise AssertionError(f"Controller DI contract: {path.name}")
|
||||
bodies = re.findall(r"@Override\s+public [^{}]+\{([^{}]*)\}", source)
|
||||
if not bodies:
|
||||
raise AssertionError(f"Controller has no operations: {path.name}")
|
||||
service = fields[0][1]
|
||||
for body in bodies:
|
||||
if body.count(";") != 1 or len(re.findall(rf"\b{service}\.\w+\(", body)) != 1:
|
||||
raise AssertionError(f"Controller must call one service: {path.name}")
|
||||
if not re.fullmatch(rf"\s*(?:return )?{service}\.\w+\([^;]*\);\s*", body):
|
||||
raise AssertionError(f"Controller contains extra logic: {path.name}")
|
||||
operations += len(bodies)
|
||||
for path in directory.glob("*Api.java"):
|
||||
source = path.read_text(encoding="utf-8")
|
||||
if source.count("/**") != source.count("@Operation(") + 1:
|
||||
raise AssertionError(f"Missing API documentation: {path.name}")
|
||||
for path in (ROOT / "src/main/java").rglob("*.java"):
|
||||
source = path.read_text(encoding="utf-8")
|
||||
if "@Autowired" in source:
|
||||
raise AssertionError(f"Use constructor injection: {path.name}")
|
||||
if re.search(r"^import .*\*;", source, re.MULTILINE):
|
||||
raise AssertionError(f"Use explicit imports: {path.name}")
|
||||
print(f"PASS {operations} controller operations: one service call, constructor DI, API Javadoc")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,58 @@
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from capture import run
|
||||
from provision import compose, prepare, initialize_db
|
||||
|
||||
|
||||
def permission(statement):
|
||||
compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"db",
|
||||
"psql",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
stdin=statement,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--faults-only", action="store_true")
|
||||
args = parser.parse_args()
|
||||
prepare()
|
||||
initialize_db()
|
||||
compose("restart", "broker")
|
||||
os.environ["PYTHONPATH"] = "tests"
|
||||
os.environ["BASE_URL"] = "https://127.0.0.1:8443"
|
||||
os.environ["CA_FILE"] = str(Path("secrets/public/ca.crt").resolve())
|
||||
for name in (
|
||||
"pipeline_core",
|
||||
"pipeline_filename",
|
||||
"pipeline_history_capacity",
|
||||
"pipeline_boundaries",
|
||||
"pipeline_upload_crash",
|
||||
):
|
||||
if not args.faults_only:
|
||||
run(name, [sys.executable, "student-tests/" + name + ".py"])
|
||||
os.environ["COMPOSE_FILE"] = os.pathsep.join(("docker-compose.yml", "compose.test.yaml"))
|
||||
permission("GRANT SELECT,UPDATE ON pipeline_faults TO worker,dispatcher;")
|
||||
try:
|
||||
compose("up", "-d", "--wait", "--wait-timeout", "180", "api", "worker", "dispatcher")
|
||||
for name in ("pipeline_faults", "pipeline_ack_guard", "pipeline_retention", "observe"):
|
||||
run(name, [sys.executable, "student-tests/" + name + ".py"])
|
||||
finally:
|
||||
os.environ.pop("COMPOSE_FILE", None)
|
||||
compose("up", "-d", "--wait", "--wait-timeout", "180", "api", "worker", "dispatcher")
|
||||
permission("REVOKE ALL ON pipeline_faults FROM worker,dispatcher;")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,27 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from capture import run
|
||||
|
||||
|
||||
def main():
|
||||
os.environ["PYTHONPATH"] = "tests"
|
||||
os.environ["BASE_URL"] = "https://127.0.0.1:8443"
|
||||
os.environ["CA_FILE"] = str(Path("secrets/public/ca.crt").resolve())
|
||||
for name in ("security_auth", "security_baseline"):
|
||||
run(name.replace("_", "-"), [sys.executable, "student-tests/" + name + ".py"])
|
||||
run(
|
||||
"bao-policy",
|
||||
["docker", "compose", "run", "--rm", "--no-deps", "-T", "audit", "/checks/bao_policy.py"],
|
||||
)
|
||||
run("security-lifecycle", [sys.executable, "student-tests/security_lifecycle.py"])
|
||||
run(
|
||||
"tls-matrix",
|
||||
["docker", "compose", "run", "--rm", "--no-deps", "-T", "audit", "/checks/tls_matrix.py"],
|
||||
)
|
||||
run("security-inventory", [sys.executable, "student-tests/security_inventory.py"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user