Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions backend/models/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,10 @@ class Assignment(BaseModel):
reason: str | None = None # human-readable explanation shown to the trainee
principle: str | None = None # the Cialdini principle being remediated
retest_of: str | None = None # the remediation assignment this re-tests
# Translatable form of `reason` for system assignments: the client renders
# remediation.<reason_key> with these params; `reason` stays as the fallback.
reason_key: str | None = None
reason_params: dict[str, Any] | None = None

created_at: str = Field(default_factory=lambda: datetime.now(UTC).isoformat())

Expand Down
4 changes: 4 additions & 0 deletions backend/routes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from routes.campaigns import router as campaigns_router
from routes.challenges import router as challenges_router
from routes.debrief import router as debrief_router
from routes.demo import router as demo_router
from routes.freetext import router as freetext_router
from routes.glossary import router as glossary_router
from routes.imports import router as imports_router
Expand All @@ -17,6 +18,7 @@
from routes.organizations import router as organizations_router
from routes.personas import router as personas_router
from routes.quizzes import router as quizzes_router
from routes.readiness import router as readiness_router
from routes.report_inbox import router as report_inbox_router
from routes.reports import router as reports_router
from routes.risk_profile import router as risk_profile_router
Expand Down Expand Up @@ -47,6 +49,7 @@
"webhooks_router",
"scenario_builder_router",
"debrief_router",
"demo_router",
# v3 platform services
"personas_router",
"risk_profile_router",
Expand All @@ -56,5 +59,6 @@
"live_router",
"audit_router",
"attack_surface_router",
"readiness_router",
"report_inbox_router",
]
28 changes: 28 additions & 0 deletions backend/routes/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from fastapi import APIRouter, Depends

from models.schemas import User
from services import audit, demo
from services.auth import require_admin

router = APIRouter(prefix="/demo", tags=["demo"])


@router.get("")
async def demo_status(user: User = Depends(require_admin)):
return await demo.status()


@router.post("")
async def load_demo(user: User = Depends(require_admin)):
"""Load (or reload) the fictional demo organization. Admin only."""
result = await demo.seed(user.id, user.organization_id or f"org-{user.id}")
await audit.record(user.id, "demo.load", None, {"people": result["people"]})
return result


@router.delete("")
async def clear_demo(user: User = Depends(require_admin)):
"""Remove all demo records; real data is never touched."""
result = await demo.clear()
await audit.record(user.id, "demo.clear", None, result)
return result
48 changes: 42 additions & 6 deletions backend/routes/live.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,27 @@ async def review_queue(current_user: User = Depends(require_trainer)):
scope = _scope(current_user)
query = {"direction": "outbound", "status": "draft_pending"}
query.update(scope)
return await db.live_messages.find(query, {"_id": 0}).sort("at", 1).to_list(500)
drafts = await db.live_messages.find(query, {"_id": 0}).sort("at", 1).to_list(500)
# Give the reviewer the message being answered and which campaign it is.
names: dict[str, str] = {}
for d in drafts:
cid = d["campaign_id"]
if cid not in names:
c = await db.live_campaigns.find_one({"id": cid}, {"_id": 0, "name": 1})
names[cid] = (c or {}).get("name", "")
d["campaign_name"] = names[cid]
last_in = await db.live_messages.find_one(
{
"campaign_id": cid,
"email": d["email"],
"direction": "inbound",
"at": {"$lte": d["at"]},
},
{"_id": 0, "body_redacted": 1},
sort=[("at", -1)],
)
d["in_reply_to"] = (last_in or {}).get("body_redacted", "")
return drafts


class ReviewDecision(BaseModel):
Expand All @@ -587,6 +607,8 @@ async def approve_draft(
if not campaign or campaign.get("killed"):
raise HTTPException(status_code=409, detail="Campaign is not active")
body = data.body if data.body is not None else msg["body_redacted"]
if not (body or "").strip():
raise HTTPException(status_code=400, detail="Write a reply before sending")
sent = await conversation.send_approved_reply(campaign, msg, body, current_user.id)
await audit.record(
current_user.id, "live.review.approve", message_id, {"edited": bool(data.body)}
Expand Down Expand Up @@ -646,6 +668,9 @@ async def set_kill_switch(data: KillSwitchRequest, current_user: User = Depends(
# ==================== GOPHISH CONFIG (admin) ====================


_SECRETS = ("gophish_api_key", "smtp_password", "imap_password", "report_imap_password")


class LiveConfig(BaseModel):
model_config = {"extra": "forbid"}
gophish_base_url: str = Field(min_length=1, max_length=300)
Expand All @@ -666,6 +691,10 @@ class LiveConfig(BaseModel):
imap_ssl: bool = True
imap_user: str = ""
imap_password: str = ""
# Report mailbox on the same IMAP server: staff forward suspicious mail here
# and reporters of our simulations are credited automatically.
report_imap_user: str = Field(default="", max_length=200)
report_imap_password: str = ""


@router.get("/config")
Expand All @@ -674,18 +703,19 @@ async def get_config(current_user: User = Depends(require_admin)):
if not config:
return None
# Never return stored secrets
for secret in ("gophish_api_key", "smtp_password", "imap_password"):
for secret in _SECRETS:
if config.get(secret):
config[secret] = "***"
return config


@router.post("/poll")
async def poll_inbox(current_user: User = Depends(require_admin)):
"""Fetch and route inbound replies now. The poller also runs on a timer."""
from services.live.inbound import poll_once
"""Fetch and route inbound replies and forwarded reports now. The poller
also runs on a timer."""
from services.live.inbound import poll_once, poll_reports_once

return await poll_once()
return {"replies": await poll_once(), "reports": await poll_reports_once()}


@router.put("/config")
Expand All @@ -694,9 +724,15 @@ async def set_config(data: LiveConfig, current_user: User = Depends(require_admi
# field (e.g. an older client without the IMAP-SSL toggle) does not reset it
# to the model default.
doc = {"id": "live_config", **data.model_dump(exclude_unset=True)}
report_box = (doc.get("report_imap_user") or "").strip().lower()
if report_box and report_box == (doc.get("imap_user") or "").strip().lower():
# Replies would then be counted as reports.
raise HTTPException(
status_code=400, detail="Report mailbox must differ from the reply mailbox"
)
# A resubmitted mask ("***") means "keep the stored secret", not overwrite it.
existing = await db.live_config.find_one({"id": "live_config"}, {"_id": 0})
for secret in ("gophish_api_key", "smtp_password", "imap_password"):
for secret in _SECRETS:
if doc.get(secret) in ("", "***") and existing:
doc[secret] = existing.get(secret, "")
await db.live_config.update_one({"id": "live_config"}, {"$set": doc}, upsert=True)
Expand Down
21 changes: 21 additions & 0 deletions backend/routes/readiness.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from fastapi import APIRouter, Depends

from models.schemas import User
from services import readiness
from services.auth import require_trainer

router = APIRouter(prefix="/readiness", tags=["readiness"])


@router.get("")
async def get_readiness(user: User = Depends(require_trainer)):
"""Cohort-level readiness overview: index, report-rate trend, remediation loop,
weakest principles and attack-surface posture. Admins see every organization;
trainers only their own."""
scope = {} if user.role == "admin" else {"organization_id": user.organization_id}
return await readiness.overview(
user_scope=scope,
campaign_scope=scope,
# Same workspace the Attack Surface Map uses for this user.
org_id=user.organization_id or f"org-{user.id}",
)
18 changes: 17 additions & 1 deletion backend/routes/report_inbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,22 @@ async def report_leaderboard(user: User = Depends(require_trainer)):
return await report_inbox.leaderboard(_scope(user))


@router.get("/mailbox")
async def report_mailbox(user: User = Depends(require_trainer)):
"""The address staff forward suspicious mail to, if a report mailbox is set up."""
config = await db.live_config.find_one({"id": "live_config"}, {"_id": 0}) or {}
address = (config.get("report_imap_user") or "").strip().lower()
return {"address": address or None, "configured": bool(address and config.get("imap_host"))}


@router.post("/poll")
async def poll_report_mailbox(user: User = Depends(require_trainer)):
"""Fetch forwarded reports now instead of waiting for the next poller tick."""
from services.live.inbound import poll_reports_once

return await poll_reports_once()


class ReportIn(BaseModel):
reporter_email: str = Field(min_length=3, max_length=320)
subject: str = Field(default="", max_length=400)
Expand All @@ -52,7 +68,7 @@ class ReportIn(BaseModel):

@router.post("/ingest", status_code=201)
async def ingest(body: ReportIn, user: User = Depends(require_trainer)):
"""Record a reported message (the integration point the mail poller also uses)."""
"""Record a reported message by hand (the report mailbox poller feeds the same path)."""
org_id = None if user.role == "admin" else user.organization_id
report = await report_inbox.ingest_report(
org_id, body.reporter_email, body.subject, body.from_address, body.body
Expand Down
69 changes: 65 additions & 4 deletions backend/routes/triage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
the server grades, computing d' with a false-alarm penalty.
"""

from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
import uuid
from typing import Literal

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field, model_validator

from models.schemas import User
from services import triage
from services.auth import get_current_user
from services import audit, triage
from services.auth import get_current_user, require_trainer
from services.database import db

router = APIRouter(prefix="/triage", tags=["triage"])
Expand Down Expand Up @@ -43,3 +46,61 @@ async def submit(
set_id: str, data: TriageSubmission, current_user: User = Depends(get_current_user)
):
return await triage.grade(set_id, current_user.id, data.marks, data.duration_seconds)


# ---- authoring: trainers add their own sets (e.g. a unit-specific content pack)


class TriageItemIn(BaseModel):
model_config = {"extra": "forbid"}
channel: Literal["email_inbox", "whatsapp", "sms"] = "email_inbox"
# For chat channels `from` is the contact as shown in the chat header and
# `subject` is the one-line preview in the chat list.
from_: str = Field(alias="from", min_length=1, max_length=200)
subject: str = Field(min_length=1, max_length=200)
body: str = Field(min_length=1, max_length=5000)
is_pretext: bool
principle: str | None = Field(default=None, max_length=40)
explanation: str | None = Field(default=None, max_length=2000)

@model_validator(mode="after")
def _pretext_is_explained(self):
if self.is_pretext and not (self.principle and self.explanation):
raise ValueError("a pretext needs a principle and an explanation for the debrief")
return self


class TriageSetIn(BaseModel):
model_config = {"extra": "forbid"}
id: str | None = Field(default=None, min_length=3, max_length=80, pattern=r"^[a-z0-9-]+$")
title: str = Field(min_length=1, max_length=120)
description: str = Field(default="", max_length=1000)
language: Literal["en", "id"] = "en"
difficulty: Literal["easy", "medium", "hard"] = "medium"
items: list[TriageItemIn] = Field(min_length=4, max_length=40)

@model_validator(mode="after")
def _has_both_kinds(self):
# d' needs at least one pretext and one legitimate message to be defined.
kinds = {i.is_pretext for i in self.items}
if kinds != {True, False}:
raise ValueError("a set needs both pretexts and legitimate messages")
return self


@router.post("", status_code=201)
async def create_set(data: TriageSetIn, current_user: User = Depends(require_trainer)):
set_id = data.id or f"triage-{uuid.uuid4().hex[:12]}"
if await db.triage_sets.find_one({"id": set_id}, {"_id": 1}):
raise HTTPException(status_code=409, detail="A triage set with this id already exists")
doc = {
**data.model_dump(exclude={"items", "id"}),
"id": set_id,
"created_by": current_user.id,
"items": [
{"id": str(uuid.uuid4()), **item.model_dump(by_alias=True)} for item in data.items
],
}
await db.triage_sets.insert_one(doc)
await audit.record(current_user.id, "triage.set.create", set_id, {"items": len(data.items)})
return {"id": set_id, "items": len(data.items)}
4 changes: 4 additions & 0 deletions backend/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
campaigns_router,
challenges_router,
debrief_router,
demo_router,
freetext_router,
glossary_router,
imports_router,
Expand All @@ -32,6 +33,7 @@
organizations_router,
personas_router,
quizzes_router,
readiness_router,
report_inbox_router,
reports_router,
risk_profile_router,
Expand Down Expand Up @@ -487,6 +489,8 @@ async def health_check():
api_router.include_router(audit_router)
api_router.include_router(attack_surface_router)
api_router.include_router(report_inbox_router)
api_router.include_router(readiness_router)
api_router.include_router(demo_router)

app.include_router(api_router)

Expand Down
Loading
Loading