fix(iam): restrict revocation to lab users and allow s3 ListBucket #16

Open
Bryan.bano wants to merge 3 commits from bugfix/15-scope-lab-containment into develop
5 changed files with 241 additions and 9 deletions
Showing only changes of commit a12d7b754e - Show all commits

View File

@ -51,6 +51,16 @@ No se crean usuarios ni claves automáticamente. SSO y perfiles de roles no est
soportados como actor de esta suite. El preflight consulta con el operador quién es
el dueño de la clave antes de invocar el perfil del actor; no registra claves.
La revocación automática se limita al prefijo reservado `tesis-ir-temp-`: la
política de ejecución solo permite administrar esos usuarios y el handler rechaza
los nombres que no cumplen el formato de la simulación. Los administradores de
`authorized_admin_users` también quedan excluidos mediante `PROTECTED_IAM_USERS`,
incluso si un nombre coincide con el prefijo. No uses identidades operativas como
actores desechables. Un evento fuera de alcance devuelve `outside_lab_scope` o
`protected_user` sin llamadas a IAM, escritura de evidencia ni notificaciones.
Una falla al leer el historial de revocaciones aborta la escritura para no
sobrescribir evidencia existente; solo un objeto ausente inicia un historial nuevo.
```bash
ansible-playbook ansible/playbooks/simulations/run_all.yml \
--tags privilege_escalation -e simulation_confirm=true \

View File

@ -0,0 +1,110 @@
# EPN TIC: configuration-first AWS evidence and report
Objective: complete Component C using newly collected AWS evidence and the existing Rubric Driven TIC template. Region: us-east-2; credential context: the user-authorized default profile. Baseline: c5a8440.
Branch: bugfix/15-scope-lab-containment; Issue: Forgejo #15 (milestone: Evaluacion cuantitativa del TIC, label: type::bug). Delivery: local work-unit commits only; no push or PR is authorized. Test runners: repository Python 3.12 unittest, Terraform validation, Ansible checks and isolated AWS-hosted experiments. Route: inline implementation, bounded read-only mapping and independent high-risk verification. No historical measurements may be reused.
## Specs
- **S1 — Institutional scope.** "este proyecto es de EPN como proyecto de tic, no es de istpet asi que no deberia de estar mencionado , corrigelo". Replace incorrect institutional attribution in project documentation; preserve unrelated repository policy. Verify with a scoped text search.
- **S2 — Exact subject.** "DISEÑO E IMPLEMENTACIÓN DE UN SISTEMA DE DETECCIÓN Y RESPUESTA ANTE INCIDENTES DE SEGURIDAD EN ENTORNOS CLOUD (AWS) Componente C — Automatización de Respuesta a Incidentes (Playbooks Serverless)". Use this project/component identity in the report.
- **S3 — Perspective.** "me gustaria que se enfoque en la importancia de la conffiguracion antes que el desarrollo". Explain configuration, reproducibility, integration, operation and validation; describe custom code only where technically necessary.
- **S4 — Actual infrastructure.** "tienes que levantar la infraestructura en aws real con terraform y ansible"; "no importa generar costos"; "las capturas deben realizarse en aws real con posibles costos y accciones de contencion". Use the authorized account/profile and selected region, inspect a fresh Terraform plan and preserve existing unrelated resources. All measured services and experimental runners must be AWS-hosted. Never target the deployment operator or unrelated principals for containment.
- **S5 — New measurements.** "no uses los resultados existentes"; "los resultados tienes que tomarlos de aws real"; "el objetivo es medir pruebas de rendimiento, tiempos de respuesta que podrian ir en anexos o en el informe". Save raw observations, UTC timestamps, execution context and failures; calculate summaries from those observations only. Clearly distinguish HTTP latency, Lambda duration, detection and independently observed containment. Do not invent unobservable stage timings or notification delivery.
- **S6 — Template and outputs.** "el objetivo es que uses rubric driven para darme el documento con la plantilla correspondiente '/home/bryan/Downloads/Trabajo Integracion Curricular.DOCX.pdf'". Use the existing subject's tic_docx.py, not the generic APA generator; produce DOCX/PDF using the kit's guarded PDF conversion. The 29-page PDF is a structural reference, not authoritative metadata or results. Track criteria in a task created with the kit utility; no institutional rubric has been supplied, so use the user's explicit scope as task criteria without inventing scores.
- **S7 — Preliminaries and style.** "de una forma generica llena igualmente la dedicatoria, agradecimientos y demas". Use Spanish academic prose, varied sentence lengths, precise vocabulary and direct paragraph openings. Do not use the phrases "Es importante destacar", "En conclusión", "En última instancia", "Un tapiz de", "Desentrañar", "Cabe recalcar", "A medida que avanzamos", "El paisaje de" or "En resumen". Do not fabricate personal data, approvals, signatures, human validation or claims of detector evasion. Disclose actual AI assistance consistently with the subject's instructions.
- **S8 — Execution location.** "no tiene queu ser nada en mi pc". Do not substitute local-service benchmarks for AWS evidence; local Terraform/Ansible orchestration and document generation remain necessary tooling.
- **S9 — Region selection.** "decide tu donde desplegarla". Selected us-east-2 because the local profile, private tfvars and previous state metadata agree; identity verified through AWS MCP before resource inspection.
## Tasks
- **T1 [S4,S8,S9] — Safety and deployment baseline** — inline (one existing deployment); status: correction implemented, independent recheck pending; commit: none. Verify identity, resource inventory, private settings, fresh plan and operator recovery. Risk: items 2 and 5 (IAM containment and deployment). Independent verification is required before applying changes.
- **T2 [S4,S8] — Terraform and Ansible deployment** — inline; status: pending; commit: none. Apply a reviewed non-destructive plan, configure the portal through SSM, verify health/telemetry and a second idempotence pass. Delegate long-running checks only.
- **T3 [S4,S5,S8] — AWS-hosted experiment and evidence** — inline; status: pending; commit: none. Prepare isolated disposable stimuli and a separate recovery path; collect raw HTTP and incident observations, screenshots and limitations. Start with a bounded pilot; do not claim the proposed main campaign has run.
- **T4 [S1,S2,S3,S6,S7] — EPN TIC task and report** — inline (depends on T3); status: task prepared, report pending; commit: none. Correct institutional docs; create the private Rubric Driven task and generator; retain unconfirmed personal fields visibly pending rather than inventing them.
- **T5 [S1-S9] — Report verification and handoff** — inline structural checks plus independent operational verification where applicable; status: pending; commit: none. Verify provenance, template, DOCX/PDF rendering and criterion coverage; report every missing proof and retained chargeable resource.
## Log
### L1 — Original authorized request
> listo, no hay problema, quiero que uses el proyecto de rubric driven, ya cree una materia nueva de Proyecto de integracion curricular, aqui ya tiene la plantilla y los pasos, pero en este proyecto tienes todo lo que se ha hecho, aqui esta documentacion , el proyecto y todo lo necesario entonces el objetivo es que uses rubric driven para darme el documento con la plantilla correspondiente '/home/bryan/Downloads/Trabajo Integracion Curricular.DOCX.pdf' , esta incompleto como puedes ver, voy a necesitar que este proyecto levantes los servicios, tomes capturas, pruebas de rendimiento y demas para que completes el documento que esta igual de plantilla en rubric driven, entonces analiza el proyecto, levanta los servicios, prueba, toma las capturas, pruebas de rendimiento y de una forma generica llena igualmente la dedicatoria, agradecimientos y demas , para la redaccion quiero que hagas lo siguiente: Actúa como un escritor académico humano experto. Tu objetivo es parafrasear el siguiente texto manteniendo intactas mis ideas originales, pero alterando completamente la estructura lingüística para que el resultado sea orgánico y no sea detectado por herramientas de análisis algorítmico.
>
> Aplica de forma estricta las siguientes reglas:
>
> Alta variación de ráfaga (Burstiness): Intercala oraciones muy cortas y contundentes (de 5 a 10 palabras) con oraciones compuestas más largas y analíticas. Rompe el ritmo constante y monótono.
>
> Evita muletillas de IA: Está estrictamente prohibido usar frases predecibles como: "Es importante destacar", "En conclusión", "En última instancia", "Un tapiz de", "Desentrañar", "Cabe recalcar", "A medida que avanzamos", "El paisaje de" o "En resumen".
>
> Perplejidad natural: Usa un vocabulario académico preciso, pero no reemplaces palabras con sinónimos arcaicos o rimbombantes que suenen forzados. Escribe de manera directa y al grano.
>
> Apertura de párrafos asimétrica: No inicies los párrafos con conectores mecánicos (Por lo tanto, Sin embargo, Además). Inicia las oraciones directamente con el sujeto, un sustantivo o la acción principal.
>
> Aquí tienes mi texto original para parafrasear:
### L2 — Scope clarification, 2026-11-17
> no tengo ninguna tarea creada, el objetivo es generar el documento que complete y complemente con informacion nueva y actual de lo que tengo realmente en este proyecto , el tema es este: DISEÑO E IMPLEMENTACIÓN DE UN SISTEMA DE DETECCIÓN Y RESPUESTA ANTE INCIDENTES DE SEGURIDAD EN ENTORNOS CLOUD (AWS) Componente C — Automatización de Respuesta a Incidentes (Playbooks Serverless) entonces me gustaria que se enfoque en la importancia de la conffiguracion antes que el desarrollo , enfocado en este punto de vista mas que nada , no uses los resultados existentes, tienes que levantar la infraestructura en aws real con terraform y ansible, este proyecto es de EPN como proyecto de tic, no es de istpet asi que no deberia de estar mencionado , corrigelo, los resultados tienes que tomarlos de aws real, no importa generar costos, el objetivo es medir pruebas de rendimiento, tiempos de respuesta que podrian ir en anexos o en el informe que tiene rubric driven de 29 paginas entonces no tiene queu ser nada en mi pc , las capturas deben realizarse en aws real con posibles costos y accciones de contencion
### L3 — Region discretion, 2026-11-17
> decide tu donde desplegarla
### L4 — Verified initial state, 2026-11-17
- Read-only mapping completed by tic_evidence_map; parent spot-checked detector guards and private configuration without exposing addresses or credentials.
- AWS MCP verified the exact account/IAM identity shown by the user. No project-tagged VPC or active/stopped EC2 was found in us-east-2. Remaining global-name inventory is pending.
- Current local Terraform state has zero resource blocks. Its backup contains 115 previous blocks from us-east-2; it is NOT being restored or treated as proof that those resources exist.
- The controller's current public egress does NOT match the configured SSH CIDR or detector-authorized CIDRs. Correct the private configuration before enabling detection subscriptions; keep administrator-name protection and restrictive network scope.
- Existing revocation permissions are account-wide and have no universal protected-admin check. Do not use deployment/recovery identities as victims or share attacker/control egress.
- Terraform 1.15.9, repository Python 3.12.16, Ansible 2.19.9 and Session Manager plugin are available. Rubric Driven verification passed for its environment, DOCX/Pillow and guarded PDF converter.
- RDD is explicitly off globally; do not start native review or enable it. Functional checks and independent high-risk verification still apply.
- No public Git operation is authorized. HEAD equals the cached forgejo/develop baseline; branch/issue linkage must be resolved before repository commits. Do not invent an issue or claim a remote ref is freshly fetched.
- Initial authored-change forecast: approximately 150-350 tracked documentation/planning lines, with private generated report/evidence outside Git. Delivery strategy: ask-on-risk; reassess before any source changes beyond this forecast.
- Next: finish scoped inventory, prepare a private current-egress deployment configuration, run fresh validation/plan, and obtain independent safety verification before apply.
### L5 — Region, preparation and independent verification, 2026-11-17
- Selected us-east-2 definitively: local profile, private tfvars and historical state metadata agree. AWS MCP verified the account/user from the user's screenshot; scoped reads found no project VPC, active/stopped EC2, Lambda, S3 bucket or IAM role. No resource mutation has been performed through AWS MCP.
- Updated only ignored private terraform.tfvars: current control /32, HTTP restricted to that /32, detector CIDR list appended without dropping prior entries, existing authorized administrators retained, SSM selected, evidence force_destroy disabled, Flow Logs and S3 Data Events enabled, AWS Config left off. Existing private notification fields were preserved; removed input names: none.
- Terraform init and validate passed. Fresh plan: 124 creates, 0 changes, 0 destroys. Its validity is limited to these current bytes; never apply it after a safety correction without regenerating and re-verifying.
- Named high-risk verification (items 2 and 5) ran against a fresh scratch archive of c5a8440 with dummy AWS credentials: 20 unit tests passed, both Ansible syntax checks passed, ansible-lint passed across 20 files. Parent spot check of test_simulation_guards.py passed (1 test).
- Independent verifier confirmed detector_config -> detector Lambda -> subscriptions ordering. No targeted bootstrap is needed to fix a config-availability race.
- ACTIVATION BLOCKER: main.tf:1542-1549 grants IAM revocation on Resource="*"; the handler has no protected-user/laboratory boundary. CloudTrail management subscriptions and the revocation event source would enable account-wide automatic containment before experiments. Operator CIDR allowlisting alone does not protect unrelated identities. Full apply was NOT run. Required correction: constrain containment to disposable laboratory principals and preserve the operator/recovery identities, then regenerate the plan and perform the one bounded blocker recheck.
- The source correction and requested institutional-document changes require an issue-linked working branch under repository GitFlow. No Issue or remote Git action has been authorized; ask one focused question for permission to create the Forgejo Issue rather than inventing an identifier or publishing silently.
- Created the private kit task with tareas.py: materias/trabajo-de-integracion-curricular/TIC1_Componente_C_Configuracion_Y_Evidencia_AWS/. TAREA.md records user-supplied criteria (no invented institutional rubric/scores), pending metadata and the safety blocker. The reference PDF was copied into enunciado/. Four preparation-check logs are retained under evidencia/preparacion/. The initial generic generator remains a scaffold and MUST NOT be used for the final TIC.
- Rubric Driven's public Git tree remains clean; materias/ is ignored. No report DOCX/PDF or performance result has been generated.
- Verifier scratch /tmp/tic-preapply-verify-fsHrIB and /tmp/.ansible-0aaa were removed after retaining their four logs in the private task. Parent run directory /tmp/tic-epn-aws-LiavWj remains mode 0700 with private plan, logs and pre-change tfvars backup; pointer /tmp/tic-epn-aws-active-path is mode 0600. These contain sensitive material and are not report annexes or repository content. Retain until safe continuation/rollback, then remove.
- No Terraform apply, Ansible remote run, load generation, containment trial or teardown has occurred. Next step requires the GitFlow/publishing decision, not approval of costs or region again.
### L6 — Forgejo authorization and security correction, 2026-11-17
> si, lo autorizo, hazlo
- Created Issue #15: https://git.bryan-bano.com/Bryan.bano/localstack-tesis/issues/15 . Verified creation response, milestone 3 and type::bug; no duplicate write or occurrence comment. Authenticated only the exact repository-owner credential for the authorized host; no credential values were exposed.
- Fetched forgejo/develop and created bugfix/15-scope-lab-containment from c5a8440. No remote branch, PR or merge is authorized.
- Correction scope: retain the simulation suite's existing reserved namespace tesis-ir-temp-, reject other usernames before side effects, propagate protected administrator names to the handler, and narrow the existing IAM user resource ARN to the same namespace. Preserve IAM actions, incident selection, audit/notification behavior for valid disposable users and all simulation confirmations.
- Named risk: items 2 and 5. Observe focused RED before code; run focused and full tests after correction, Terraform normalization/validation and a regenerated plan, then the existing verifier's one bounded recheck of the containment blocker. RDD remains explicitly off.
- Static-policy baseline command proposed for analysis only (no upload): uvx iam-policy-autopilot@latest generate-policies <absolute repository>/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py --region us-east-2 --account <authorized account> --service-hints iam s3 sns ses --tf-dir <absolute repository>/terraform-tesis-ir-secure-portal --pretty . Verify installed command flags before execution; keep generated outputs outside the workspace. This does not authorize broad generated policies.
### L6 — Forgejo authorization, 2026-11-17
> si, lo autorizo, hazlo
- Created and verified https://git.bryan-bano.com/Bryan.bano/localstack-tesis/issues/15, label type::bug, milestone Evaluacion cuantitativa del TIC. Used only the host-scoped credential matching the repository owner's exact name; no secret was displayed. Fetched forgejo/develop and created bugfix/15-scope-lab-containment from c5a8440. Push/PR/merge remain unauthorized.
### L7 — Bounded containment correction, 2026-11-17
- Reused the existing reserved simulation namespace tesis-ir-temp-. The role's three IAM actions now target only that current-account user namespace. The handler requires the same full-name pattern as simulation preflight and checks PROTECTED_IAM_USERS, populated from authorized_admin_users, before any AWS call or audit/notification write.
- Added tests/test_revoke_credentials.py, exercising the public handler. RED: 3 tests with 8 failing unauthorized-target subcases before the fix. GREEN: 3 focused tests passed; valid disposable containment still deactivates a key, applies EmergencyDenyAll, writes audit and publishes SNS.
- After Terraform formatting, the full suite passed: 23 tests. Terraform fmt/validate passed. Regenerated plan deployment-corrected.tfplan: 124 creates, 0 changes, 0 destroys. Differential checks against c5a8440 confirmed identical outputs, stdout/stderr and mocked AWS side effects for valid disposable PRIVILEGE_ESCALATION and CREDENTIAL_LEAK inputs.
- Static IAM Policy Autopilot 0.4.0 ran successfully without AWS credentials/uploads and confirmed the existing three IAM actions. It cannot infer authorized experiment scope; its broader generated output is not being attached. Scratch /tmp/tic-iam-static-pb42mP remains pending removal after retaining a nonsensitive execution summary.
- Source normalization is complete. Next: record the security work-unit commit, run the existing independent verifier's single bounded blocker recheck and validate effective scope with the read-only AWS IAM simulator. No apply yet.
### L8 — Required commit gate and audit preservation, 2026-11-17
- The first commit attempt was refused because the configured reviewer executable was absent; no commit was created. Read-only mapping confirmed that the same required hook supports a one-invocation GGA_PROVIDER=codex override. No hook, global provider preference or RDD switch was changed or bypassed.
- The existing guard then identified a pre-existing silent catch in load_revoke_log that could overwrite audit history after S3/JSON read failures. Added public-handler regression coverage: RED showed AccessDenied and JSONDecodeError were swallowed. The correction catches only S3 NoSuchKey, propagates other failures and closes the streaming body. Focused GREEN: all 5 tests passed. Final full suite: 25 tests passed; Terraform fmt/validate passed; regenerated plan still has 124 creates, 0 changes and 0 destroys.
- AWS IAM SimulateCustomPolicy was called read-only with the existing three generated IAM actions and the exact corrected namespace. Resource-specific results confirmed all three actions allowed for a disposable principal and implicitly denied for the deployment administrator and an unrelated production-named principal (9 resource/action decisions). The first result reader expected 9 top-level rows; AWS returns 3 action rows with nested resource decisions, so the reader was corrected before interpreting the evidence. No IAM resources were changed.

View File

@ -1546,7 +1546,7 @@ resource "aws_iam_role_policy" "playbook_revoke_credentials" {
"iam:UpdateAccessKey",
"iam:PutUserPolicy"
]
Resource = "*"
Resource = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:user/tesis-ir-temp-*"
},
{
Sid = "WriteRevokeAudit"
@ -1590,11 +1590,12 @@ resource "aws_lambda_function" "playbook_revoke_credentials" {
environment {
variables = {
SNS_ALERTS_ARN = aws_sns_topic.alerts.arn
EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket
RESPONSE_PREFIX = "responses/revoke-credentials"
ALERT_EMAIL = var.alert_email
SES_SENDER_EMAIL = var.ses_sender_email
SNS_ALERTS_ARN = aws_sns_topic.alerts.arn
EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket
RESPONSE_PREFIX = "responses/revoke-credentials"
ALERT_EMAIL = var.alert_email
SES_SENDER_EMAIL = var.ses_sender_email
PROTECTED_IAM_USERS = join(",", var.authorized_admin_users)
}
}

View File

@ -7,6 +7,7 @@ registra evidencia en S3 y notifica via HTML Card (SES) y SNS (Telegram).
import html
import json
import os
import re
import uuid
from datetime import datetime
from zoneinfo import ZoneInfo
@ -23,6 +24,11 @@ SNS_ARN = os.environ["SNS_ALERTS_ARN"]
RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/revoke-credentials")
ALERT_EMAIL = os.environ.get("ALERT_EMAIL", "")
SES_SENDER_EMAIL = os.environ.get("SES_SENDER_EMAIL") or ALERT_EMAIL
PROTECTED_IAM_USERS = {
username.strip()
for username in os.environ.get("PROTECTED_IAM_USERS", "").split(",")
if username.strip()
}
EC_TZ = ZoneInfo("America/Guayaquil")
DENY_ALL_POLICY = json.dumps({
@ -175,9 +181,10 @@ def send_ses_email(subject: str, html_body: str, plain_body: str) -> None:
def load_revoke_log() -> list:
try:
obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=f"{RESPONSE_PREFIX}/revoked-credentials.json")
return json.loads(obj["Body"].read())
except Exception:
except s3.exceptions.NoSuchKey:
return []
with obj["Body"] as body:
return json.loads(body.read())
def save_revoke_log(revoke_log: list) -> None:
@ -189,7 +196,7 @@ def save_revoke_log(revoke_log: list) -> None:
)
def lambda_handler(event, context):
def lambda_handler(event: dict, context: object | None) -> dict:
results = []
for record in event.get("Records", []):
@ -216,6 +223,13 @@ def lambda_handler(event, context):
results.append({"status": "skipped", "reason": f"invalid_affected_resource:{affected_resource}"})
continue
if username in PROTECTED_IAM_USERS:
results.append({"status": "skipped", "reason": "protected_user"})
continue
if not re.fullmatch(r"tesis-ir-temp-[a-z0-9-]+", username):
results.append({"status": "skipped", "reason": "outside_lab_scope"})
continue
actions_taken = []
keys_revoked = []
enforcement = {}

View File

@ -0,0 +1,97 @@
"""Credential containment is restricted to disposable laboratory identities."""
import importlib.util
import io
import json
import os
from pathlib import Path
import unittest
from unittest.mock import Mock, patch
from botocore.exceptions import ClientError
class RevokeCredentialsScopeTest(unittest.TestCase):
def setUp(self):
self.clients = {name: Mock() for name in ("s3", "sns", "iam", "ses")}
env = {
"EVIDENCE_BUCKET": "test-evidence",
"SNS_ALERTS_ARN": "test-alerts",
"ALERT_EMAIL": "",
"PROTECTED_IAM_USERS": "admin-tesis,tesis-ir-temp-recovery",
}
path = Path(__file__).resolve().parents[1] / (
"terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py"
)
with patch.dict(os.environ, env), patch("boto3.client", side_effect=self.clients.get):
spec = importlib.util.spec_from_file_location("revoke_scope", path)
self.handler = importlib.util.module_from_spec(spec)
spec.loader.exec_module(self.handler)
self.clients["s3"].get_object.return_value = {"Body": io.BytesIO(b"[]")}
self.clients["s3"].exceptions.NoSuchKey = type("NoSuchKey", (ClientError,), {})
self.clients["iam"].list_access_keys.return_value = {
"AccessKeyMetadata": [{"AccessKeyId": "demo-key-id", "Status": "Active"}]
}
def invoke(self, username, incident_type="CREDENTIAL_LEAK"):
return self.handler.lambda_handler({"Records": [{"body": json.dumps({
"incident_type": incident_type,
"affectedResource": "iam:user/" + username,
"sourceIPAddress": "198.51.100.20",
"incident_id": "scope-regression",
})}]}, None)
def assert_no_side_effects(self):
for client in self.clients.values():
self.assertEqual(client.mock_calls, [])
def test_rejects_non_lab_users_without_side_effects(self):
for incident in ("CREDENTIAL_LEAK", "PRIVILEGE_ESCALATION"):
for username in ("production-user", "tesis-ir-temp-", "tesis-ir-temp-user/path"):
with self.subTest(incident=incident, username=username):
result = self.invoke(username, incident)
self.assertEqual(result["results"], [{
"status": "skipped", "reason": "outside_lab_scope",
}])
self.assert_no_side_effects()
def test_rejects_protected_users_without_side_effects(self):
for username in ("admin-tesis", "tesis-ir-temp-recovery"):
with self.subTest(username=username):
result = self.invoke(username)
self.assertEqual(result["results"], [{
"status": "skipped", "reason": "protected_user",
}])
self.assert_no_side_effects()
def test_missing_audit_object_starts_new_history(self):
self.clients["s3"].get_object.side_effect = self.clients["s3"].exceptions.NoSuchKey(
{"Error": {"Code": "NoSuchKey"}}, "GetObject"
)
result = self.invoke("tesis-ir-temp-regression")
self.assertEqual(result["results"][0]["action"], "CONTAINED")
self.assertEqual(self.clients["s3"].put_object.call_count, 2)
def test_audit_read_failures_do_not_overwrite_history(self):
failures = (
ClientError({"Error": {"Code": "AccessDenied"}}, "GetObject"),
json.JSONDecodeError("corrupt history", "{", 0),
)
for failure in failures:
with self.subTest(failure=type(failure).__name__):
self.clients["s3"].get_object.side_effect = failure
with self.assertRaises(type(failure)):
self.invoke("tesis-ir-temp-regression")
self.clients["s3"].put_object.assert_not_called()
self.clients["sns"].publish.assert_not_called()
def test_disposable_user_preserves_containment_and_audit(self):
result = self.invoke("tesis-ir-temp-actor")
self.assertEqual(result["results"][0]["action"], "CONTAINED")
iam = self.clients["iam"]
iam.update_access_key.assert_called_once_with(
UserName="tesis-ir-temp-actor", AccessKeyId="demo-key-id", Status="Inactive",
)
self.assertEqual(iam.put_user_policy.call_args.kwargs["PolicyName"], "EmergencyDenyAll")
self.assertEqual(self.clients["s3"].put_object.call_count, 2)
self.clients["sns"].publish.assert_called_once()