from __future__ import annotations import json from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any import numpy as np import pandas as pd from src.domain import ( ACCOUNT_IDS, DEFAULT_SEED, MAINTENANCE_TICKET, ChangeType, Family, Split, TEST_START_ISO, ) from src.schemas import LabEvent UTC = timezone.utc START = datetime(2026, 4, 1, tzinfo=UTC) TEST_START = datetime.fromisoformat(TEST_START_ISO.replace("Z", "+00:00")) DAYS = 14 REGION = "us-east-1" ACTORS: dict[str, dict[str, str]] = { "alice": {"type": "IAMUser", "account": "prod", "name": "alice"}, "bob": {"type": "IAMUser", "account": "staging", "name": "bob"}, "carol": {"type": "IAMUser", "account": "sandbox", "name": "carol"}, "dave": {"type": "IAMUser", "account": "prod", "name": "dave"}, "root": {"type": "Root", "account": "prod", "name": "root"}, "terraform-staging": {"type": "AssumedRole", "account": "staging", "name": "terraform-staging"}, "terraform-prod": {"type": "AssumedRole", "account": "prod", "name": "terraform-prod"}, "ci-github": {"type": "AssumedRole", "account": "staging", "name": "ci-github"}, "lambda-rotator": {"type": "AssumedRole", "account": "prod", "name": "lambda-rotator"}, } READ_EVENTS = ( ("iam.amazonaws.com", "ListUsers", True), ("iam.amazonaws.com", "GetRole", True), ("s3.amazonaws.com", "GetBucketAcl", True), ("ec2.amazonaws.com", "DescribeInstances", True), ("cloudtrail.amazonaws.com", "DescribeTrails", True), ("sts.amazonaws.com", "GetCallerIdentity", True), ("guardduty.amazonaws.com", "GetDetector", True), ) def iso(ts: datetime) -> str: return ts.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") def split_for(ts: datetime) -> str: return Split.TEST.value if ts >= TEST_START else Split.DEVELOPMENT.value def account_id(key: str) -> str: return ACCOUNT_IDS[key] def lab_events() -> list[LabEvent]: return [ LabEvent( event_id="EVT-MAINT-DEV-01", account_alias="acct_staging", actor_alias="role_terraform-staging", start=iso(START + timedelta(days=4, hours=2, minutes=15)), end=iso(START + timedelta(days=4, hours=2, minutes=16)), family=Family.BENIGN_MAINTENANCE.value, split=Split.DEVELOPMENT.value, change_type=ChangeType.IAM_PRIVILEGE_GRANT.value, note="Sunday staging window. Terraform attaches a job role policy with ticket CHG-4411.", ), LabEvent( event_id="EVT-SG-SAFE-DEV-01", account_alias="acct_staging", actor_alias="role_terraform-staging", start=iso(START + timedelta(days=4, hours=2, minutes=40)), end=iso(START + timedelta(days=4, hours=2, minutes=41)), family=Family.BENIGN_RESTRICTED_SG.value, split=Split.DEVELOPMENT.value, change_type=ChangeType.SECURITY_GROUP_INGRESS.value, note="Maintenance SG ingress from 10.0.0.0/8, not 0.0.0.0/0.", ), LabEvent( event_id="EVT-IAM-DEV-01", account_alias="acct_prod", actor_alias="usr_alice", start=iso(START + timedelta(days=2, hours=3, minutes=12)), end=iso(START + timedelta(days=2, hours=3, minutes=13)), family=Family.REVIEW_IAM.value, split=Split.DEVELOPMENT.value, change_type=ChangeType.IAM_PRIVILEGE_GRANT.value, note="Off-hours AttachUserPolicy AdministratorAccess on prod.", ), LabEvent( event_id="EVT-S3-DEV-01", account_alias="acct_prod", actor_alias="usr_bob", start=iso(START + timedelta(days=3, hours=14, minutes=22)), end=iso(START + timedelta(days=3, hours=14, minutes=23)), family=Family.REVIEW_EXPOSURE.value, split=Split.DEVELOPMENT.value, change_type=ChangeType.S3_PUBLIC_EXPOSURE.value, note="DeletePublicAccessBlock on a prod bucket. That is a request, not proven current exposure.", ), LabEvent( event_id="EVT-SG-OPEN-DEV-01", account_alias="acct_prod", actor_alias="usr_alice", start=iso(START + timedelta(days=2, hours=18)), end=iso(START + timedelta(days=2, hours=18, minutes=1)), family=Family.REVIEW_EXPOSURE.value, split=Split.DEVELOPMENT.value, change_type=ChangeType.SECURITY_GROUP_INGRESS.value, note="AuthorizeSecurityGroupIngress 0.0.0.0/0 on prod.", ), LabEvent( event_id="EVT-TRAIL-DEV-01", account_alias="acct_prod", actor_alias="usr_carol", start=iso(START + timedelta(days=5, hours=1, minutes=5)), end=iso(START + timedelta(days=5, hours=1, minutes=6)), family=Family.REVIEW_LOGGING.value, split=Split.DEVELOPMENT.value, change_type=ChangeType.TRAIL_LOGGING_CHANGE.value, note="Contractor StopLogging on the prod trail.", ), LabEvent( event_id="EVT-ROOT-DEV-01", account_alias="acct_prod", actor_alias="root_lab", start=iso(START + timedelta(days=6, hours=9)), end=iso(START + timedelta(days=6, hours=9, minutes=1)), family=Family.REVIEW_ROOT.value, split=Split.DEVELOPMENT.value, change_type=ChangeType.ROOT_ACTIVITY.value, note="Root console login.", ), LabEvent( event_id="EVT-TRUST-DEV-01", account_alias="acct_prod", actor_alias="usr_dave", start=iso(START + timedelta(days=7, hours=16, minutes=10)), end=iso(START + timedelta(days=7, hours=16, minutes=11)), family=Family.REVIEW_TRUST.value, split=Split.DEVELOPMENT.value, change_type=ChangeType.ROLE_TRUST_CHANGE.value, note="UpdateAssumeRolePolicy with Principal *.", ), LabEvent( event_id="EVT-KEY-DEV-01", account_alias="acct_staging", actor_alias="usr_bob", start=iso(START + timedelta(days=6, hours=11, minutes=20)), end=iso(START + timedelta(days=6, hours=11, minutes=21)), family=Family.REVIEW_IAM.value, split=Split.DEVELOPMENT.value, change_type=ChangeType.IAM_CREDENTIAL_CREATE.value, note="CreateAccessKey for a staging user during business hours.", ), LabEvent( event_id="EVT-INSUFF-DEV-01", account_alias="acct_prod", actor_alias="usr_bob", start=iso(START + timedelta(days=1, hours=11)), end=iso(START + timedelta(days=1, hours=11, minutes=1)), family=Family.INSUFFICIENT.value, split=Split.DEVELOPMENT.value, change_type=ChangeType.S3_PUBLIC_EXPOSURE.value, note="PutBucketPolicy without requestParameters. Before/after unknown.", ), LabEvent( event_id="EVT-MAINT-01", account_alias="acct_staging", actor_alias="role_terraform-staging", start=iso(START + timedelta(days=11, hours=2, minutes=20)), end=iso(START + timedelta(days=11, hours=2, minutes=21)), family=Family.BENIGN_MAINTENANCE.value, split=Split.TEST.value, change_type=ChangeType.IAM_PRIVILEGE_GRANT.value, note="Held-out Sunday staging terraform AttachRolePolicy with CHG-4411.", ), LabEvent( event_id="EVT-SG-SAFE-01", account_alias="acct_staging", actor_alias="role_terraform-staging", start=iso(START + timedelta(days=11, hours=3, minutes=5)), end=iso(START + timedelta(days=11, hours=3, minutes=6)), family=Family.BENIGN_RESTRICTED_SG.value, split=Split.TEST.value, change_type=ChangeType.SECURITY_GROUP_INGRESS.value, note="Held-out restricted SG during the approved window.", ), LabEvent( event_id="EVT-IAM-01", account_alias="acct_prod", actor_alias="usr_alice", start=iso(START + timedelta(days=10, hours=2, minutes=48)), end=iso(START + timedelta(days=10, hours=2, minutes=49)), family=Family.REVIEW_IAM.value, split=Split.TEST.value, change_type=ChangeType.IAM_PRIVILEGE_GRANT.value, note="Held-out off-hours AdministratorAccess attach on prod.", ), LabEvent( event_id="EVT-S3-01", account_alias="acct_prod", actor_alias="usr_bob", start=iso(START + timedelta(days=10, hours=15, minutes=30)), end=iso(START + timedelta(days=10, hours=15, minutes=31)), family=Family.REVIEW_EXPOSURE.value, split=Split.TEST.value, change_type=ChangeType.S3_PUBLIC_EXPOSURE.value, note="Held-out DeletePublicAccessBlock.", ), LabEvent( event_id="EVT-SG-OPEN-01", account_alias="acct_prod", actor_alias="usr_bob", start=iso(START + timedelta(days=10, hours=18, minutes=20)), end=iso(START + timedelta(days=10, hours=18, minutes=21)), family=Family.REVIEW_EXPOSURE.value, split=Split.TEST.value, change_type=ChangeType.SECURITY_GROUP_INGRESS.value, note="Held-out 0.0.0.0/0 security group ingress.", ), LabEvent( event_id="EVT-TRAIL-01", account_alias="acct_prod", actor_alias="usr_carol", start=iso(START + timedelta(days=12, hours=0, minutes=40)), end=iso(START + timedelta(days=12, hours=0, minutes=41)), family=Family.REVIEW_LOGGING.value, split=Split.TEST.value, change_type=ChangeType.TRAIL_LOGGING_CHANGE.value, note="Held-out StopLogging.", ), LabEvent( event_id="EVT-ROOT-01", account_alias="acct_prod", actor_alias="root_lab", start=iso(START + timedelta(days=12, hours=10, minutes=15)), end=iso(START + timedelta(days=12, hours=10, minutes=16)), family=Family.REVIEW_ROOT.value, split=Split.TEST.value, change_type=ChangeType.ROOT_ACTIVITY.value, note="Held-out root CreateAccessKey.", ), LabEvent( event_id="EVT-TRUST-01", account_alias="acct_prod", actor_alias="usr_dave", start=iso(START + timedelta(days=13, hours=11, minutes=20)), end=iso(START + timedelta(days=13, hours=11, minutes=21)), family=Family.REVIEW_TRUST.value, split=Split.TEST.value, change_type=ChangeType.ROLE_TRUST_CHANGE.value, note="Held-out wildcard trust policy.", ), LabEvent( event_id="EVT-GD-01", account_alias="acct_prod", actor_alias="usr_alice", start=iso(START + timedelta(days=13, hours=1, minutes=10)), end=iso(START + timedelta(days=13, hours=1, minutes=11)), family=Family.REVIEW_LOGGING.value, split=Split.TEST.value, change_type=ChangeType.DETECTOR_DISABLE.value, note="Held-out GuardDuty UpdateDetector Enable=false.", ), LabEvent( event_id="EVT-KEY-01", account_alias="acct_staging", actor_alias="usr_bob", start=iso(START + timedelta(days=11, hours=11, minutes=40)), end=iso(START + timedelta(days=11, hours=11, minutes=41)), family=Family.REVIEW_IAM.value, split=Split.TEST.value, change_type=ChangeType.IAM_CREDENTIAL_CREATE.value, note="Held-out CreateAccessKey. Medium severity; should drop at a high T.", ), LabEvent( event_id="EVT-INSUFF-01", account_alias="acct_prod", actor_alias="usr_bob", start=iso(START + timedelta(days=9, hours=13)), end=iso(START + timedelta(days=9, hours=13, minutes=1)), family=Family.INSUFFICIENT.value, split=Split.TEST.value, change_type=ChangeType.S3_PUBLIC_EXPOSURE.value, note="Held-out PutBucketAcl without requestParameters.", ), ] def _identity(actor_key: str) -> dict[str, Any]: spec = ACTORS[actor_key] acct = account_id(spec["account"]) name = spec["name"] if spec["type"] == "Root": return { "type": "Root", "principalId": f"{acct}", "arn": f"arn:aws:iam::{acct}:root", "accountId": acct, } if spec["type"] == "AssumedRole": return { "type": "AssumedRole", "principalId": f"{acct}:{name}", "arn": f"arn:aws:sts::{acct}:assumed-role/{name}/session", "accountId": acct, "sessionContext": { "sessionIssuer": { "type": "Role", "userName": name, "arn": f"arn:aws:iam::{acct}:role/{name}", "accountId": acct, } }, } return { "type": "IAMUser", "principalId": f"AIDAI{name.upper()[:8]}LAB", "arn": f"arn:aws:iam::{acct}:user/{name}", "accountId": acct, "userName": name, } def _event( event_id: str, ts: datetime, actor_key: str, source: str, name: str, request: dict[str, Any] | None, *, read_only: bool = False, user_agent: str = "aws-cli/2.15.0", ip: str = "203.0.113.10", lab_event_id: str = "", lab_family: str = "", ticket: str = "", incomplete: bool = False, error_code: str | None = None, ) -> dict[str, Any]: spec = ACTORS[actor_key] acct = account_id(spec["account"]) payload: dict[str, Any] = { "eventVersion": "1.09", "userIdentity": _identity(actor_key), "eventTime": iso(ts), "eventSource": source, "eventName": name, "awsRegion": REGION, "sourceIPAddress": ip, "userAgent": user_agent, "requestParameters": None if incomplete else (request or {}), "responseElements": None if read_only or incomplete else {"_lab": True}, "requestID": f"req-{event_id.lower()}", "eventID": event_id, "readOnly": read_only, "eventType": "AwsApiCall", "managementEvent": True, "recipientAccountId": acct, "errorCode": error_code, "lab_event_id": lab_event_id, "lab_family": lab_family, "change_ticket": ticket, "split": split_for(ts), "incomplete": incomplete, } return payload def _authored() -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] specs = [ ( "EVT-MAINT-DEV-01", START + timedelta(days=4, hours=2, minutes=15), "terraform-staging", "iam.amazonaws.com", "AttachRolePolicy", {"roleName": "job-runner", "policyArn": "arn:aws:iam::aws:policy/ReadOnlyAccess"}, {"lab_family": Family.BENIGN_MAINTENANCE.value, "ticket": MAINTENANCE_TICKET, "ua": "terraform/1.9.0", "ip": "198.51.100.20"}, ), ( "EVT-SG-SAFE-DEV-01", START + timedelta(days=4, hours=2, minutes=40), "terraform-staging", "ec2.amazonaws.com", "AuthorizeSecurityGroupIngress", {"groupId": "sg-staging-web", "cidrIp": "10.0.0.0/8", "fromPort": 443, "toPort": 443}, {"lab_family": Family.BENIGN_RESTRICTED_SG.value, "ticket": MAINTENANCE_TICKET, "ua": "terraform/1.9.0", "ip": "198.51.100.20"}, ), ( "EVT-IAM-DEV-01", START + timedelta(days=2, hours=3, minutes=12), "alice", "iam.amazonaws.com", "AttachUserPolicy", {"userName": "carol", "policyArn": "arn:aws:iam::aws:policy/AdministratorAccess"}, {"lab_family": Family.REVIEW_IAM.value, "ua": "console.amazonaws.com", "ip": "203.0.113.10"}, ), ( "EVT-S3-DEV-01", START + timedelta(days=3, hours=14, minutes=22), "bob", "s3.amazonaws.com", "DeletePublicAccessBlock", {"bucketName": "prod-invoice-export"}, {"lab_family": Family.REVIEW_EXPOSURE.value, "ua": "aws-cli/2.15.0", "ip": "192.0.2.55"}, ), ( "EVT-SG-OPEN-DEV-01", START + timedelta(days=2, hours=18), "alice", "ec2.amazonaws.com", "AuthorizeSecurityGroupIngress", {"groupId": "sg-prod-web", "cidrIp": "0.0.0.0/0", "fromPort": 22, "toPort": 22}, {"lab_family": Family.REVIEW_EXPOSURE.value, "ua": "console.amazonaws.com"}, ), ( "EVT-TRAIL-DEV-01", START + timedelta(days=5, hours=1, minutes=5), "carol", "cloudtrail.amazonaws.com", "StopLogging", {"name": "org-management"}, {"lab_family": Family.REVIEW_LOGGING.value, "ip": "192.0.2.55"}, ), ( "EVT-ROOT-DEV-01", START + timedelta(days=6, hours=9), "root", "signin.amazonaws.com", "ConsoleLogin", {}, {"lab_family": Family.REVIEW_ROOT.value, "ua": "signin.amazonaws.com"}, ), ( "EVT-TRUST-DEV-01", START + timedelta(days=7, hours=16, minutes=10), "dave", "iam.amazonaws.com", "UpdateAssumeRolePolicy", {"roleName": "ci-deploy", "policyDocument": '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"sts:AssumeRole"}]}'}, {"lab_family": Family.REVIEW_TRUST.value}, ), ( "EVT-KEY-DEV-01", START + timedelta(days=6, hours=11, minutes=20), "bob", "iam.amazonaws.com", "CreateAccessKey", {"userName": "deploy-bot"}, {"lab_family": Family.REVIEW_IAM.value}, ), ( "EVT-INSUFF-DEV-01", START + timedelta(days=1, hours=11), "bob", "s3.amazonaws.com", "PutBucketPolicy", None, {"lab_family": Family.INSUFFICIENT.value, "incomplete": True}, ), ( "EVT-MAINT-01", START + timedelta(days=11, hours=2, minutes=20), "terraform-staging", "iam.amazonaws.com", "AttachRolePolicy", {"roleName": "job-runner", "policyArn": "arn:aws:iam::aws:policy/ReadOnlyAccess"}, {"lab_family": Family.BENIGN_MAINTENANCE.value, "ticket": MAINTENANCE_TICKET, "ua": "terraform/1.9.0", "ip": "198.51.100.20"}, ), ( "EVT-SG-SAFE-01", START + timedelta(days=11, hours=3, minutes=5), "terraform-staging", "ec2.amazonaws.com", "AuthorizeSecurityGroupIngress", {"groupId": "sg-staging-web", "cidrIp": "10.0.0.0/8", "fromPort": 443, "toPort": 443}, {"lab_family": Family.BENIGN_RESTRICTED_SG.value, "ticket": MAINTENANCE_TICKET, "ua": "terraform/1.9.0", "ip": "198.51.100.20"}, ), ( "EVT-IAM-01", START + timedelta(days=10, hours=2, minutes=48), "alice", "iam.amazonaws.com", "AttachRolePolicy", {"roleName": "break-glass", "policyArn": "arn:aws:iam::aws:policy/AdministratorAccess"}, {"lab_family": Family.REVIEW_IAM.value, "ua": "console.amazonaws.com"}, ), ( "EVT-S3-01", START + timedelta(days=10, hours=15, minutes=30), "bob", "s3.amazonaws.com", "DeletePublicAccessBlock", {"bucketName": "prod-invoice-export"}, {"lab_family": Family.REVIEW_EXPOSURE.value, "ip": "192.0.2.55"}, ), ( "EVT-SG-OPEN-01", START + timedelta(days=10, hours=18, minutes=20), "bob", "ec2.amazonaws.com", "AuthorizeSecurityGroupIngress", {"groupId": "sg-prod-web", "cidrIp": "0.0.0.0/0", "fromPort": 22, "toPort": 22}, {"lab_family": Family.REVIEW_EXPOSURE.value}, ), ( "EVT-TRAIL-01", START + timedelta(days=12, hours=0, minutes=40), "carol", "cloudtrail.amazonaws.com", "StopLogging", {"name": "org-management"}, {"lab_family": Family.REVIEW_LOGGING.value, "ip": "192.0.2.55"}, ), ( "EVT-ROOT-01", START + timedelta(days=12, hours=10, minutes=15), "root", "iam.amazonaws.com", "CreateAccessKey", {"userName": "root"}, {"lab_family": Family.REVIEW_ROOT.value, "ua": "console.amazonaws.com"}, ), ( "EVT-TRUST-01", START + timedelta(days=13, hours=11, minutes=20), "dave", "iam.amazonaws.com", "UpdateAssumeRolePolicy", {"roleName": "ci-deploy", "policyDocument": '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"sts:AssumeRole"}]}'}, {"lab_family": Family.REVIEW_TRUST.value}, ), ( "EVT-GD-01", START + timedelta(days=13, hours=1, minutes=10), "alice", "guardduty.amazonaws.com", "UpdateDetector", {"detectorId": "det-prod-01", "enable": False}, {"lab_family": Family.REVIEW_LOGGING.value, "ua": "console.amazonaws.com"}, ), ( "EVT-KEY-01", START + timedelta(days=11, hours=11, minutes=40), "bob", "iam.amazonaws.com", "CreateAccessKey", {"userName": "deploy-bot"}, {"lab_family": Family.REVIEW_IAM.value}, ), ( "EVT-INSUFF-01", START + timedelta(days=9, hours=13), "bob", "s3.amazonaws.com", "PutBucketAcl", None, {"lab_family": Family.INSUFFICIENT.value, "incomplete": True}, ), ] for event_id, ts, actor, source, name, request, extra in specs: rows.append( _event( event_id, ts, actor, source, name, request, lab_event_id=event_id, lab_family=str(extra.get("lab_family") or ""), ticket=str(extra.get("ticket") or ""), incomplete=bool(extra.get("incomplete")), user_agent=str(extra.get("ua") or "aws-cli/2.15.0"), ip=str(extra.get("ip") or "203.0.113.10"), ) ) # Before-state companions (not gold review rows). rows.append( _event( "EVT-S3-BEFORE-DEV", START + timedelta(days=3, hours=10), "dave", "s3.amazonaws.com", "PutPublicAccessBlock", { "bucketName": "prod-invoice-export", "PublicAccessBlockConfiguration": { "BlockPublicAcls": True, "IgnorePublicAcls": True, "BlockPublicPolicy": True, "RestrictPublicBuckets": True, }, }, read_only=False, ) ) rows.append( _event( "EVT-S3-BEFORE-01", START + timedelta(days=10, hours=9), "dave", "s3.amazonaws.com", "PutPublicAccessBlock", { "bucketName": "prod-invoice-export", "PublicAccessBlockConfiguration": { "BlockPublicAcls": True, "IgnorePublicAcls": True, "BlockPublicPolicy": True, "RestrictPublicBuckets": True, }, }, ) ) rows.append( _event( "EVT-TRAIL-BEFORE-DEV", START + timedelta(days=1, hours=8), "dave", "cloudtrail.amazonaws.com", "StartLogging", {"name": "org-management"}, ) ) rows.append( _event( "EVT-TRAIL-BEFORE-01", START + timedelta(days=9, hours=8), "dave", "cloudtrail.amazonaws.com", "StartLogging", {"name": "org-management"}, ) ) return rows def _background(seed: int) -> list[dict[str, Any]]: rng = np.random.default_rng(seed) rows: list[dict[str, Any]] = [] humans = ("alice", "bob", "carol", "dave") services = ("terraform-prod", "terraform-staging", "ci-github", "lambda-rotator") seq = 0 for day in range(DAYS): for _ in range(18): seq += 1 actor = str(rng.choice(humans + services)) source, name, read_only = READ_EVENTS[int(rng.integers(0, len(READ_EVENTS)))] hour = int(rng.integers(8, 18)) minute = int(rng.integers(0, 60)) ts = START + timedelta(days=day, hours=hour, minutes=minute, seconds=int(rng.integers(0, 50))) request = {"marker": "lab-read"} if name == "GetBucketAcl": request = {"bucketName": "prod-invoice-export"} if name == "GetRole": request = {"roleName": "job-runner"} rows.append( _event( f"bg-{seq:04d}", ts, actor, source, name, request, read_only=read_only, user_agent="aws-cli/2.15.0" if actor in humans else "terraform/1.9.0", ip="198.51.100.20" if actor not in humans else "203.0.113.10", ) ) for _ in range(3): seq += 1 ts = START + timedelta(days=day, hours=int(rng.integers(9, 16)), minutes=int(rng.integers(0, 60))) rows.append( _event( f"tag-{seq:04d}", ts, str(rng.choice(("terraform-prod", "terraform-staging", "ci-github"))), "ec2.amazonaws.com", "CreateTags", {"resourcesSet": {"items": [{"resourceId": "i-labweb01"}]}, "tagSet": {"items": [{"key": "env", "value": "lab"}]}}, user_agent="terraform/1.9.0", ip="198.51.100.20", ) ) return rows def build_lab(seed: int = DEFAULT_SEED) -> dict[str, Any]: events = _authored() + _background(seed) frame = pd.DataFrame(events) gold = pd.DataFrame([item.model_dump() for item in lab_events()]) return { "events": frame, "gold": gold, "n_events": int(len(frame)), "n_accounts": 3, "seed": seed, } def filter_lab(pack: dict[str, Any], scenario: str) -> dict[str, Any]: events: pd.DataFrame = pack["events"].copy() gold: pd.DataFrame = pack["gold"].copy() if scenario == "maintenance": keep = gold["family"].isin({Family.BENIGN_MAINTENANCE.value, Family.BENIGN_RESTRICTED_SG.value, Family.BACKGROUND.value}) gold = gold.loc[gold["family"].isin({Family.BENIGN_MAINTENANCE.value, Family.BENIGN_RESTRICTED_SG.value})].copy() ids = set(gold["event_id"]) events = events.loc[events["eventID"].isin(ids) | events["eventName"].isin([item[1] for item in READ_EVENTS])].copy() _ = keep elif scenario == "exposure": gold = gold.loc[gold["family"].eq(Family.REVIEW_EXPOSURE.value)].copy() ids = set(gold["event_id"]) | {"EVT-S3-BEFORE-DEV", "EVT-S3-BEFORE-01"} events = events.loc[events["eventID"].isin(ids) | events["eventName"].isin(["GetBucketAcl", "DescribeInstances"])].copy() elif scenario == "iam": gold = gold.loc[gold["family"].isin({Family.REVIEW_IAM.value, Family.REVIEW_ROOT.value, Family.REVIEW_TRUST.value})].copy() ids = set(gold["event_id"]) events = events.loc[events["eventID"].isin(ids) | events["eventName"].eq("ListUsers")].copy() elif scenario == "logging": gold = gold.loc[gold["family"].eq(Family.REVIEW_LOGGING.value)].copy() ids = set(gold["event_id"]) | {"EVT-TRAIL-BEFORE-DEV", "EVT-TRAIL-BEFORE-01"} events = events.loc[events["eventID"].isin(ids) | events["eventName"].eq("DescribeTrails")].copy() elif scenario == "broken": broken = events.head(40).copy() broken["eventTime"] = "not-a-timestamp" return {"events": broken, "gold": gold.iloc[0:0], "n_events": len(broken), "n_accounts": 0, "seed": pack.get("seed")} return {"events": events.reset_index(drop=True), "gold": gold.reset_index(drop=True), "n_events": int(len(events)), "n_accounts": 3, "seed": pack.get("seed")} def cloudtrail_document(events: pd.DataFrame) -> dict[str, Any]: records = [] for row in events.to_dict(orient="records"): item = dict(row) records.append(item) return {"Records": records} def write_examples(folder: Path, seed: int = DEFAULT_SEED) -> dict[str, Any]: folder.mkdir(parents=True, exist_ok=True) pack = build_lab(seed) events: pd.DataFrame = pack["events"] gold = [item.model_dump() for item in lab_events()] document = cloudtrail_document(events) (folder / "events.json").write_text(json.dumps(document, indent=2, default=str), encoding="utf-8") preview_ids = {item["event_id"] for item in gold} preview = events.loc[events["eventID"].isin(preview_ids) | events["eventName"].isin(["GetBucketAcl", "ListUsers", "StartLogging", "PutPublicAccessBlock"])] (folder / "events_preview.json").write_text(json.dumps(cloudtrail_document(preview.head(80)), indent=2, default=str), encoding="utf-8") with (folder / "events.jsonl").open("w", encoding="utf-8") as handle: for row in events.head(80).to_dict(orient="records"): handle.write(json.dumps(row, default=str) + "\n") flat = pd.DataFrame( { "event_id": events["eventID"], "timestamp": events["eventTime"], "event_name": events["eventName"], "event_source": events["eventSource"], "account_id": events["recipientAccountId"], "split": events["split"], "lab_event_id": events["lab_event_id"], } ) flat.head(400).to_csv(folder / "events_preview.csv", index=False) (folder / "gold_events.json").write_text(json.dumps(gold, indent=2), encoding="utf-8") sample = cloudtrail_document(events.loc[events["eventID"].astype(str).str.startswith("EVT-")].head(12)) (folder / "cloudtrail_sample.json").write_text(json.dumps(sample, indent=2, default=str), encoding="utf-8") schema = { "schema_id": "ariacloudtrail.change_event.v1", "required_after_parse": ["timestamp", "event_name"], "cloudtrail_fields": ["eventTime", "eventName", "eventSource", "userIdentity", "recipientAccountId"], "timezone": "UTC", "null_meaning": "missing field, not a safe default", "change_types": [item.value for item in ChangeType if item != ChangeType.NONE], } (folder / "schema.json").write_text(json.dumps(schema, indent=2), encoding="utf-8") splits = { "development": "2026-04-01T00:00:00Z/2026-04-10T00:00:00Z", "test": "2026-04-10T00:00:00Z/2026-04-15T00:00:00Z", "group": "account and period; one authored event stays in one split", "service_principals": "AssumedRole actors are modeled separately from IAM users", "history": "before/after and burst counts use only earlier events", } (folder / "splits.json").write_text(json.dumps(splits, indent=2), encoding="utf-8") (folder / "protocol.md").write_text( "\n".join( [ "# AriaCloudTrail laboratory protocol", "", "Synthetic AWS CloudTrail management events, seed 16, three lab accounts.", "Account IDs 111111111111 / 222222222222 / 333333333333 are aliases for prod/staging/sandbox.", "No live cloud credentials, no configuration changes, no network calls to AWS.", "", "Gold `needs_review_*` ranges are authored sensitive changes. Sunday 02:00-06:00 UTC on staging with ticket CHG-4411 is approved maintenance.", "Before/after is only claimed when both events exist in the export. A single Put/Delete does not prove current exposure.", "", "Split is by period (test starts 2026-04-10) and account. Rows of one authored event stay together.", ] ), encoding="utf-8", ) (folder / "ruleset.json").write_text( json.dumps( { "maintenance": { "account": "acct_staging", "actor": "role_terraform-staging", "ticket": MAINTENANCE_TICKET, "window": "Sunday 02:00-06:00 UTC", "allowed": ["iam_privilege_grant", "security_group_ingress"], "forbidden": ["AdministratorAccess", "0.0.0.0/0", "root"], }, "event_map_count": 28, }, indent=2, ), encoding="utf-8", ) return {"n_events": int(len(events)), "n_accounts": 3, "n_gold": len(gold), "seed": seed}