forked from mtusi2026/mtusi2026lab7
fix(security): scope row locks and add explicit expiry recovery
This commit is contained in:
@@ -11,6 +11,7 @@ from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
||||
@@ -278,11 +279,15 @@ def generate():
|
||||
).not_valid_after_utc
|
||||
< datetime.now(UTC) + timedelta(minutes=5)
|
||||
)
|
||||
wrong_issuer = (
|
||||
directory / "cert.pem"
|
||||
).exists() and x509.load_pem_x509_certificate(
|
||||
(directory / "cert.pem").read_bytes()
|
||||
).issuer != cert.subject
|
||||
wrong_issuer = False
|
||||
if (directory / "cert.pem").exists():
|
||||
existing = x509.load_pem_x509_certificate(
|
||||
(directory / "cert.pem").read_bytes()
|
||||
)
|
||||
try:
|
||||
existing.verify_directly_issued_by(cert)
|
||||
except (ValueError, InvalidSignature):
|
||||
wrong_issuer = True
|
||||
# Only this explicit operator command has the offline CA. Agents
|
||||
# cannot refresh a bootstrap credential by themselves after expiry.
|
||||
if (
|
||||
|
||||
+5
-4
@@ -161,7 +161,7 @@ def reload_bao():
|
||||
raise TimeoutError("Verified Bao restart/unseal unavailable: " + str(last))
|
||||
|
||||
|
||||
def recover_bao():
|
||||
def recover_bao(*, all_roles=True):
|
||||
# Explicit operator recovery after the server leaf itself has expired.
|
||||
key, root = ca()
|
||||
leaf_key, leaf = sign_leaf(
|
||||
@@ -184,9 +184,10 @@ def recover_bao():
|
||||
operator = Operator()
|
||||
try:
|
||||
operator.unseal()
|
||||
for role in ROLES:
|
||||
if role != "migrate":
|
||||
repair(operator, role)
|
||||
if all_roles:
|
||||
for role in ROLES:
|
||||
if role != "migrate":
|
||||
repair(operator, role)
|
||||
finally:
|
||||
operator.close()
|
||||
|
||||
|
||||
@@ -111,6 +111,10 @@ def postgres(raw):
|
||||
],
|
||||
},
|
||||
}
|
||||
if "compose.test.yaml" in os.getenv("COMPOSE_FILE", ""):
|
||||
for role in ["api", "relay"]:
|
||||
grants[role]["SELECT"].append("pipeline_faults")
|
||||
grants[role]["UPDATE"].append("pipeline_faults")
|
||||
# SQL literals use psycopg's own adapter; names are fixed local roles.
|
||||
for role, permissions in grants.items():
|
||||
name = "svc_" + role
|
||||
@@ -152,6 +156,15 @@ def postgres(raw):
|
||||
+ name
|
||||
+ ";"
|
||||
)
|
||||
# PostgreSQL row locks also need UPDATE privilege on at least one
|
||||
# column. Grant a key column, not attachment processing state.
|
||||
for table in {
|
||||
"api": ["attachments", "upload_reservations"],
|
||||
"reconciler": ["upload_reservations"],
|
||||
}.get(role, []):
|
||||
statements.append(
|
||||
"GRANT UPDATE(id) ON " + table + " TO " + name + ";"
|
||||
)
|
||||
# Only append-only technical event/outbox IDs use sequences.
|
||||
sequences = {
|
||||
"api": ["outbox_id_seq"],
|
||||
|
||||
+20
-1
@@ -7,7 +7,7 @@ import subprocess
|
||||
import time
|
||||
|
||||
from scripts.bao_operator import Operator
|
||||
from scripts.bootstrap_security import OPERATOR, generate
|
||||
from scripts.bootstrap_security import OPERATOR, ROLES, generate
|
||||
from scripts.credentials import repair
|
||||
from scripts.prepare_dependencies import main as dependencies
|
||||
from scripts.prepare_dependencies import postgres
|
||||
@@ -17,6 +17,11 @@ from scripts.stand import ROOT, command, compose, ready
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--build", action="store_true")
|
||||
parser.add_argument(
|
||||
"--recover-expired",
|
||||
action="store_true",
|
||||
help="Explicit offline-CA recovery of expired service identities",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
generate()
|
||||
os.environ.setdefault("VCS_REF", command(["git", "rev-parse", "HEAD"]))
|
||||
@@ -28,6 +33,10 @@ def main():
|
||||
compose(
|
||||
"up", "-d", "--no-deps", "openbao", "postgres", "cache", "broker", "s3"
|
||||
)
|
||||
if args.recover_expired:
|
||||
from scripts.pki import recover_bao
|
||||
|
||||
recover_bao(all_roles=False)
|
||||
operator = Operator()
|
||||
try:
|
||||
for attempt in range(90):
|
||||
@@ -43,6 +52,10 @@ def main():
|
||||
operator.init()
|
||||
operator.unseal()
|
||||
operator.configure()
|
||||
if args.recover_expired:
|
||||
for role in ROLES:
|
||||
if role not in {"openbao", "lb", "migrate"}:
|
||||
repair(operator, role)
|
||||
# The maintenance identity is intentionally stopped between migrations.
|
||||
# Its expired leaf is repaired explicitly by the operator before reuse.
|
||||
repair(operator, "migrate")
|
||||
@@ -84,6 +97,12 @@ def main():
|
||||
compose("wait", "telemetry-init")
|
||||
backends = ["otel", "prometheus", "loki", "tempo", "grafana", "lb"]
|
||||
compose("up", "-d", "--no-deps", *backends)
|
||||
if args.recover_expired:
|
||||
operator = Operator()
|
||||
try:
|
||||
repair(operator, "lb")
|
||||
finally:
|
||||
operator.close()
|
||||
gates = [
|
||||
r + "-tls"
|
||||
for r in [
|
||||
|
||||
+32
-11
@@ -652,18 +652,39 @@ print(json.dumps({{'job_id':k,'hashes':{{r['name']:r['sha256'] for r in hashes}}
|
||||
a, j = upload()
|
||||
confirm(a, j)
|
||||
key = f"objects/{a['id']}/v1/original"
|
||||
security = inside(f"""from minio.error import S3Error
|
||||
from urllib.error import HTTPError
|
||||
try: urllib.request.urlopen('http://s3:9000/'+BUCKET+'/' + {key!r},timeout=3)
|
||||
except HTTPError as e: anonymous=e.code
|
||||
else: raise AssertionError('Anonymous access allowed')
|
||||
code = f"""import io,json,urllib3
|
||||
from uuid import uuid4
|
||||
from minio import Minio
|
||||
from minio.credentials import StaticProvider
|
||||
from minio.error import S3Error
|
||||
from src.security_probe import context,values,exchange,denied
|
||||
request=b'GET /messenger/{key} HTTP/1.1\\r\\nHost: s3\\r\\nConnection: close\\r\\n\\r\\n'
|
||||
anonymous=denied(lambda:exchange('s3',9443,None,request))
|
||||
v=values('worker');pool=urllib3.PoolManager(ssl_context=context('worker'),retries=False,timeout=urllib3.Timeout(connect=2,read=4))
|
||||
client=Minio('s3:9443',credentials=StaticProvider(v['S3_ACCESS_KEY'],v['S3_SECRET_KEY']),secure=True,http_client=pool,region='us-east-1')
|
||||
denials={{}}
|
||||
for name,fn in [('create_bucket',lambda:store.client.make_bucket('forbidden-'+uuid4().hex)),('write_outside_prefix',lambda:store.client.put_object(BUCKET,'outside-'+uuid4().hex,io.BytesIO(b'x'),1)),('list_other_bucket',lambda:list(store.client.list_objects('forbidden-'+uuid4().hex)))]:
|
||||
try: fn()
|
||||
except S3Error as e: denials[name]=e.code
|
||||
else: raise AssertionError('IAM allowed forbidden action')
|
||||
print(json.dumps({{'anonymous':anonymous,'iam':denials}}))""")
|
||||
assert security["anonymous"] == 403 and set(
|
||||
try:
|
||||
for name,fn in [('create_bucket',lambda:client.make_bucket('forbidden-'+uuid4().hex)),('write_outside_prefix',lambda:client.put_object('messenger','outside-'+uuid4().hex,io.BytesIO(b'x'),1)),('list_other_bucket',lambda:list(client.list_objects('forbidden-'+uuid4().hex)))]:
|
||||
try: fn()
|
||||
except S3Error as error: denials[name]=error.code
|
||||
else: raise AssertionError('Worker was allowed a forbidden S3 operation')
|
||||
print(json.dumps({{'anonymous_tls_denied':anonymous,'iam':denials}}))
|
||||
finally:pool.clear()
|
||||
"""
|
||||
compile(code, "scoped-s3-negative-probe", "exec")
|
||||
security = json.loads(
|
||||
compose(
|
||||
"--profile",
|
||||
"operator",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"operator-probe",
|
||||
"-c",
|
||||
code,
|
||||
)
|
||||
)
|
||||
assert security["anonymous_tls_denied"] and set(
|
||||
security["iam"].values()
|
||||
) == {"AccessDenied"}
|
||||
selected = None
|
||||
|
||||
Reference in New Issue
Block a user