diff --git a/backend/models/schemas.py b/backend/models/schemas.py index 842c2f7..2432430 100644 --- a/backend/models/schemas.py +++ b/backend/models/schemas.py @@ -582,6 +582,7 @@ class OrgNode(BaseModel): # Identity name: str + email: str | None = None # planning address; used to target a campaign at this person role: str # job title department: str hierarchy_level: int = 0 # 0 = individual contributor, higher = more authority @@ -731,6 +732,7 @@ class LiveCampaignCreate(BaseModel): ends_at: datetime max_turns: int = Field(default=4, ge=0, le=6) language: str = "en" + use_qr: bool = False # quishing: the lure is a QR code encoding the tracked URL brand_override_reason: str | None = Field(default=None, max_length=1000) @@ -747,3 +749,41 @@ class LiveCampaign(LiveCampaignCreate): # Opaque token in the Reply-To address, used to match inbound replies (P3). reply_token: str = Field(default_factory=lambda: secrets.token_urlsafe(12)) created_at: str = Field(default_factory=lambda: datetime.now(UTC).isoformat()) + + +class CampaignTemplate(BaseModel): + """The content of a campaign, without the per-run time window. Used as the + body that a schedule materialises into a fresh campaign each cycle.""" + + model_config = ConfigDict(extra="forbid") + name: str = Field(min_length=1, max_length=120) + objective: str + principles: list[str] = Field(min_length=1) + sender_name: str = Field(min_length=1, max_length=80) + sender_email: str = Field(min_length=3, max_length=254) + subject: str = Field(min_length=1, max_length=200) + body_html: str = Field(min_length=1, max_length=20000) + recipients: list[str] = Field(min_length=1, max_length=5000) + max_turns: int = Field(default=4, ge=0, le=6) + language: str = "en" + use_qr: bool = False + + +class CampaignSchedule(BaseModel): + """A recurring campaign. Each cycle it materialises a fresh campaign in + `pending_approval` — never auto-sent, so the two-person approval guardrail + (G2) still holds; the schedule only automates the drafting cadence.""" + + model_config = ConfigDict(extra="ignore") + id: str = Field(default_factory=lambda: str(uuid.uuid4())) + organization_id: str | None = None + name: str = Field(min_length=1, max_length=120) + interval_days: int = Field(ge=1, le=365) + window_days: int = Field(default=5, ge=1, le=30) # active window of each run + next_run: str # ISO timestamp of the next materialisation + active: bool = True + template: dict # a CampaignTemplate + created_by: str + last_run_at: str | None = None + last_campaign_id: str | None = None + created_at: str = Field(default_factory=lambda: datetime.now(UTC).isoformat()) diff --git a/backend/requirements.txt b/backend/requirements.txt index 44e3278..0808db4 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -25,3 +25,4 @@ PyYAML==6.0.3 httpx==0.28.1 aiosmtplib==5.1.3 dnspython==2.9.0 # TXT lookups for live-campaign domain verification +segno==1.6.6 # pure-Python QR codes for "quishing" campaigns (no Pillow) diff --git a/backend/routes/attack_surface.py b/backend/routes/attack_surface.py index 95aea2e..6a69212 100644 --- a/backend/routes/attack_surface.py +++ b/backend/routes/attack_surface.py @@ -38,11 +38,19 @@ async def get_analysis(user: User = Depends(require_trainer)): return await attack_surface.analyze(_org(user)) +@router.get("/targets") +async def get_targets(user: User = Depends(require_trainer)): + """Emailable people on the map, ranked most-susceptible first — to seed a + campaign aimed at the human weak points.""" + return {"targets": await attack_surface.targets(_org(user))} + + # ---------------------------------------------------------------- nodes class NodeIn(BaseModel): name: str + email: str | None = None role: str = "" department: str = "" hierarchy_level: int = 0 diff --git a/backend/routes/live.py b/backend/routes/live.py index 73d4b8a..25824a9 100644 --- a/backend/routes/live.py +++ b/backend/routes/live.py @@ -5,12 +5,22 @@ `killed` reachable from any non-final state. See docs/design/live-campaigns.md. """ +import io +from datetime import UTC, datetime, timedelta from typing import Any -from fastapi import APIRouter, Depends, HTTPException, Query +import segno +from fastapi import APIRouter, Depends, HTTPException, Query, Response from pydantic import BaseModel, Field -from models.schemas import LiveCampaign, LiveCampaignCreate, User, VerifiedDomain +from models.schemas import ( + CampaignSchedule, + CampaignTemplate, + LiveCampaign, + LiveCampaignCreate, + User, + VerifiedDomain, +) from services import audit from services.ai_gateway import AIGateway from services.auth import require_admin, require_trainer @@ -18,6 +28,7 @@ from services.live import conversation from services.live import domains as domain_svc from services.live import launch as launch_svc +from services.live import scheduler as sched_svc from services.live.domains import email_domain from services.live.gophish import GophishClient, GophishError from services.live.preflight import has_errors, run_preflight @@ -171,6 +182,20 @@ async def list_templates(current_user: User = Depends(require_trainer)): return await db.live_templates.find({}, {"_id": 0}).sort("name", 1).to_list(100) +@router.get("/qr") +async def qr_image(data: str = Query(..., min_length=1, max_length=2000)): + """Render a QR code PNG for `data`. Public (no auth) so a recipient's mail + client can load it into a "quishing" email; `data` is the GoPhish-tracked + URL, so a scan is attributed to that recipient exactly like a click.""" + buf = io.BytesIO() + segno.make(data, error="m").save(buf, kind="png", scale=5, border=2) + return Response( + content=buf.getvalue(), + media_type="image/png", + headers={"Cache-Control": "no-store"}, + ) + + @router.get("/campaigns") async def list_campaigns(current_user: User = Depends(require_trainer)): # List view omits the heavy fields (body, full recipient list) and keeps a count. @@ -411,6 +436,91 @@ async def live_analytics(current_user: User = Depends(require_trainer)): } +# ==================== RECURRING SCHEDULES ==================== + + +class ScheduleCreate(BaseModel): + name: str = Field(min_length=1, max_length=120) + interval_days: int = Field(ge=1, le=365) + window_days: int = Field(default=5, ge=1, le=30) + start_in_days: int = Field(default=0, ge=0, le=365) + template: CampaignTemplate + + +class ScheduleUpdate(BaseModel): + active: bool | None = None + interval_days: int | None = Field(default=None, ge=1, le=365) + window_days: int | None = Field(default=None, ge=1, le=30) + + +@router.get("/schedules") +async def list_schedules(current_user: User = Depends(require_trainer)): + return ( + await db.campaign_schedules.find(_scope(current_user), {"_id": 0}) + .sort("created_at", -1) + .to_list(200) + ) + + +@router.post("/schedules", status_code=201) +async def create_schedule(body: ScheduleCreate, current_user: User = Depends(require_trainer)): + next_run = (datetime.now(UTC) + timedelta(days=body.start_in_days)).isoformat() + schedule = CampaignSchedule( + organization_id=current_user.organization_id, + name=body.name, + interval_days=body.interval_days, + window_days=body.window_days, + next_run=next_run, + template=body.template.model_dump(), + created_by=current_user.id, + ) + await db.campaign_schedules.insert_one(schedule.model_dump()) + await audit.record(current_user.id, "live.schedule.create", schedule.id, {"name": body.name}) + return schedule.model_dump() + + +@router.patch("/schedules/{schedule_id}") +async def update_schedule( + schedule_id: str, body: ScheduleUpdate, current_user: User = Depends(require_trainer) +): + updates = {k: v for k, v in body.model_dump(exclude_unset=True).items() if v is not None} + if not updates: + raise HTTPException(422, "No fields to update") + res = await db.campaign_schedules.update_one( + {"id": schedule_id, **_scope(current_user)}, {"$set": updates} + ) + if not res.matched_count: + raise HTTPException(404, "Schedule not found") + return {"updated": schedule_id, **updates} + + +@router.delete("/schedules/{schedule_id}") +async def delete_schedule(schedule_id: str, current_user: User = Depends(require_trainer)): + res = await db.campaign_schedules.delete_one({"id": schedule_id, **_scope(current_user)}) + if not res.deleted_count: + raise HTTPException(404, "Schedule not found") + await audit.record(current_user.id, "live.schedule.delete", schedule_id) + return {"deleted": schedule_id} + + +@router.post("/schedules/{schedule_id}/run-now") +async def run_schedule_now(schedule_id: str, current_user: User = Depends(require_trainer)): + """Materialise one campaign from the schedule immediately (still pending_approval).""" + schedule = await db.campaign_schedules.find_one( + {"id": schedule_id, **_scope(current_user)}, {"_id": 0} + ) + if not schedule: + raise HTTPException(404, "Schedule not found") + cid = await sched_svc.materialize(schedule) + if not cid: + raise HTTPException(422, "Schedule template is invalid — edit the schedule") + await db.campaign_schedules.update_one( + {"id": schedule_id}, + {"$set": {"last_run_at": datetime.now(UTC).isoformat(), "last_campaign_id": cid}}, + ) + return {"created_campaign": cid} + + # ==================== CONVERSATION & REVIEW QUEUE (P3) ==================== @@ -542,6 +652,9 @@ class LiveConfig(BaseModel): gophish_api_key: str = Field(min_length=1, max_length=200) verify_tls: bool = False phish_url: str = Field(min_length=1, max_length=300) + # Public URL of THIS backend, used to serve QR images into "quishing" emails. + # Optional unless a campaign uses QR. e.g. http://localhost:9442 + public_base_url: str = "" smtp_host: str = Field(min_length=1, max_length=200) smtp_username: str = "" smtp_password: str = "" diff --git a/backend/server.py b/backend/server.py index 8621257..d9e9874 100644 --- a/backend/server.py +++ b/backend/server.py @@ -368,6 +368,8 @@ async def lifespan(app: FastAPI): await db.phish_reports.create_index("id", unique=True) await db.phish_reports.create_index([("organization_id", 1), ("created_at", -1)]) await db.phish_reports.create_index([("organization_id", 1), ("verdict", 1)]) + await db.campaign_schedules.create_index("id", unique=True) + await db.campaign_schedules.create_index([("active", 1), ("next_run", 1)]) # G14: live campaign telemetry expires after 180 days await db.live_events.create_index("at", expireAfterSeconds=180 * 24 * 3600) await db.live_events.create_index([("campaign_id", 1), ("type", 1)]) @@ -398,8 +400,10 @@ async def lifespan(app: FastAPI): import asyncio from services.live.inbound import run_poller + from services.live.scheduler import run_scheduler poller_task = asyncio.create_task(run_poller()) + scheduler_task = asyncio.create_task(run_scheduler()) yield @@ -408,6 +412,8 @@ async def lifespan(app: FastAPI): if poller_task: poller_task.cancel() + if scheduler_task: + scheduler_task.cancel() client.close() diff --git a/backend/services/attack_surface.py b/backend/services/attack_surface.py index 40115eb..5a4b4fb 100644 --- a/backend/services/attack_surface.py +++ b/backend/services/attack_surface.py @@ -166,6 +166,32 @@ async def build_graph(org_id: str, *, refresh: bool = True) -> dict: return {"nodes": nodes, "edges": edges} +async def targets(org_id: str) -> list[dict]: + """People on the map who have a reachable email, ranked most-susceptible first + — the recipient list for a campaign aimed at the human weak points.""" + graph = await build_graph(org_id) + out: list[dict] = [] + for n in graph["nodes"]: + if n.get("is_asset"): + continue + email = n.get("email") + if not email and n.get("user_id"): + user = await db.users.find_one({"id": n["user_id"]}, {"_id": 0, "email": 1}) + email = (user or {}).get("email") + if email: + out.append( + { + "name": n["name"], + "role": n.get("role"), + "email": email, + "susceptibility": n.get("susceptibility"), + "band": n.get("band"), + } + ) + out.sort(key=lambda x: x["susceptibility"] or 0, reverse=True) + return out + + # ============================ pathfinding ================================== INTERNET = "__internet__" # virtual source: an attacker outside the org @@ -401,6 +427,7 @@ async def seed_demo_org(org_id: str) -> dict: node = OrgNode( org_id=org_id, name=name, + email=None if is_asset else f"{key}@acme.test", # sandbox planning address role=role, department=dept, hierarchy_level=level, diff --git a/backend/services/live/launch.py b/backend/services/live/launch.py index f41606d..c67c6ad 100644 --- a/backend/services/live/launch.py +++ b/backend/services/live/launch.py @@ -38,6 +38,30 @@ def _obj_name(campaign_id: str) -> str: return f"pretexta-{campaign_id}" +# The {{.URL}} token stays literal so GoPhish substitutes the per-recipient +# tracked link into the QR image's src — a scan is then attributed exactly like +# a click. GoPhish URL-encodes the substituted value for a query parameter. +_QR_BLOCK = ( + '
' + 'Scan to continue' + '

Scan the QR code with your phone\'s ' + "camera to continue.

" +) + + +def _body_with_qr(campaign: dict, config: dict) -> str: + """For a quishing campaign, append a QR image that encodes the tracked URL.""" + body = campaign["body_html"] + if not campaign.get("use_qr"): + return body + base = (config.get("public_base_url") or "").rstrip("/") + if not base: + logger.warning(f"Campaign {campaign['id']} uses QR but public_base_url is unset; skipping") + return body + return body + _QR_BLOCK.format(base=base) + + def _reply_to_address(config: dict, campaign: dict) -> str | None: """Reply-To that routes replies back to this campaign via plus-addressing.""" local = config.get("reply_local") @@ -74,7 +98,7 @@ async def launch_campaign(campaign: dict, actor_id: str) -> dict: config["gophish_base_url"], config["gophish_api_key"], config.get("verify_tls", False) ) as gp: await gp.create_group(name, targets) - await gp.create_template(name, campaign["subject"], campaign["body_html"]) + await gp.create_template(name, campaign["subject"], _body_with_qr(campaign, config)) await gp.create_page(name, TEACHABLE_MOMENT_HTML, redirect_url="") headers = [ {"key": "From", "value": f"{campaign['sender_name']} <{campaign['sender_email']}>"} diff --git a/backend/services/live/scheduler.py b/backend/services/live/scheduler.py new file mode 100644 index 0000000..ad8fba2 --- /dev/null +++ b/backend/services/live/scheduler.py @@ -0,0 +1,79 @@ +""" +Recurring live campaigns (LIVE OPS). A schedule materialises a fresh campaign on +a cadence so an organization can run a baseline and periodic retests without +re-building the campaign each time. + +Guardrail note (G2): a scheduled run is created in `pending_approval`, never sent +automatically. A second admin still has to approve and launch each instance, so +two-person approval and the kill switch continue to apply. The schedule only +automates the drafting cadence, not the send ("supervised auto-send" stays a +separate, deferred step). +""" + +import asyncio +import logging +from datetime import UTC, datetime, timedelta + +from models.schemas import CampaignTemplate, LiveCampaign +from services.database import db +from services.live.preflight import run_preflight + +logger = logging.getLogger(__name__) + +SCHEDULER_INTERVAL_SECONDS = 300 # how often the loop checks for due schedules + + +async def materialize(schedule: dict, now: datetime | None = None) -> str | None: + """Create one campaign instance from a schedule's template (pending_approval).""" + now = now or datetime.now(UTC) + try: + template = CampaignTemplate(**schedule["template"]) + except Exception as exc: # a bad template must not wedge the whole loop + logger.warning(f"Schedule {schedule['id']} has an invalid template: {exc}") + return None + + window = int(schedule.get("window_days", 5)) + campaign = LiveCampaign( + **template.model_dump(), + starts_at=now, + ends_at=now + timedelta(days=window), + organization_id=schedule.get("organization_id"), + created_by=schedule["created_by"], + status="pending_approval", + ) + doc = campaign.model_dump() + doc["preflight"] = await run_preflight(doc) + doc["scheduled_from"] = schedule["id"] + await db.live_campaigns.insert_one(dict(doc)) + logger.info(f"Schedule {schedule['id']} created campaign {campaign.id}") + return campaign.id + + +async def run_due(now: datetime | None = None) -> list[str]: + """Materialise every active schedule whose next_run has passed, and advance it.""" + now = now or datetime.now(UTC) + created: list[str] = [] + cursor = db.campaign_schedules.find( + {"active": True, "next_run": {"$lte": now.isoformat()}}, {"_id": 0} + ) + async for schedule in cursor: + cid = await materialize(schedule, now) + updates = { + "next_run": (now + timedelta(days=int(schedule["interval_days"]))).isoformat(), + "last_run_at": now.isoformat(), + } + if cid: + updates["last_campaign_id"] = cid + created.append(cid) + await db.campaign_schedules.update_one({"id": schedule["id"]}, {"$set": updates}) + return created + + +async def run_scheduler(interval_seconds: int = SCHEDULER_INTERVAL_SECONDS) -> None: + """Background loop. Always running; a no-op until a schedule is due.""" + while True: + try: + await run_due() + except Exception as exc: # never let the loop die + logger.warning(f"scheduler tick failed: {exc}") + await asyncio.sleep(interval_seconds) diff --git a/backend/tests/test_attack_surface.py b/backend/tests/test_attack_surface.py index 976805c..f1742a0 100644 --- a/backend/tests/test_attack_surface.py +++ b/backend/tests/test_attack_surface.py @@ -153,3 +153,41 @@ async def test_asset_requires_valid_kind(api): json={"name": "X", "is_asset": True, "asset_kind": "bogus"}, ) assert r.status_code == 422 + + +# ---------- launch targets ---------- + + +async def test_targets_from_demo_ranked_by_susceptibility(api): + await attack_surface.seed_demo_org("org-t") + rows = await attack_surface.targets("org-t") + # 7 people, all with sandbox emails; no assets. + assert len(rows) == 7 + assert all(r["email"].endswith("@acme.test") for r in rows) + # Most susceptible first (New Joiner, susceptibility 82). + assert rows[0]["name"] == "New Joiner" + assert rows[0]["susceptibility"] >= rows[-1]["susceptibility"] + + +async def test_targets_resolves_email_via_user_id(api): + user, _ = await make_user("user", organization_id="acme") + await db.users.update_one({"id": user.id}, {"$set": {"email": "real@acme.test"}}) + await db.org_nodes.insert_one( + { + "id": "n1", + "org_id": "acme", + "name": "Linked", + "user_id": user.id, + "role": "Staff", + "department": "Ops", + "is_asset": False, + "susceptibility": 60, + } + ) + rows = await attack_surface.targets("acme") + assert any(r["email"] == "real@acme.test" for r in rows) + + +async def test_targets_endpoint_requires_staff(api): + _, h = await make_user("user") + assert (await api.get("/api/attack-surface/targets", headers=h)).status_code == 403 diff --git a/backend/tests/test_live_qr.py b/backend/tests/test_live_qr.py new file mode 100644 index 0000000..811dce5 --- /dev/null +++ b/backend/tests/test_live_qr.py @@ -0,0 +1,60 @@ +"""Quishing: the QR image endpoint and QR injection into the launch body.""" + +from services.live.launch import _body_with_qr +from tests.conftest import make_user + + +async def test_qr_endpoint_returns_png(api): + # Public endpoint (a mail client loads it), so no auth header. + r = await api.get("/api/live/qr", params={"data": "http://phish.test/track?rid=abc"}) + assert r.status_code == 200 + assert r.headers["content-type"] == "image/png" + assert r.content[:8] == b"\x89PNG\r\n\x1a\n" # PNG magic + + +async def test_qr_endpoint_rejects_empty(api): + assert (await api.get("/api/live/qr", params={"data": ""})).status_code == 422 + + +def test_body_with_qr_injects_tracked_url(): + body = _body_with_qr( + {"id": "c1", "body_html": "

hi {{.URL}}

", "use_qr": True}, + {"public_base_url": "http://host:9442/"}, + ) + # The literal GoPhish token is preserved so it is substituted per recipient. + assert "http://host:9442/api/live/qr?data={{.URL}}" in body + assert "

hi {{.URL}}

" in body # original body kept + + +def test_body_with_qr_noop_without_flag_or_base(): + assert _body_with_qr({"id": "c", "body_html": "x", "use_qr": False}, {}) == "x" + assert ( + _body_with_qr({"id": "c", "body_html": "x", "use_qr": True}, {"public_base_url": ""}) == "x" + ) + + +async def test_create_campaign_accepts_use_qr(api): + from datetime import UTC, datetime, timedelta + + _, h = await make_user("trainer") + await api.post("/api/live/domains", json={"domain": "acme.test"}, headers=h) + now = datetime.now(UTC) + payload = { + "name": "QR drill", + "objective": "click_link", + "principles": ["authority"], + "sender_name": "IT", + "sender_email": "it@acme.test", + "subject": "Scan to verify", + "body_html": "

Scan: {{.URL}}

", + "recipients": ["a@acme.test"], + "starts_at": (now + timedelta(hours=1)).isoformat(), + "ends_at": (now + timedelta(days=2)).isoformat(), + "use_qr": True, + } + r = await api.post("/api/live/campaigns", json=payload, headers=h) + assert r.status_code == 200 + from services.database import db + + camp = await db.live_campaigns.find_one({"id": r.json()["id"]}) + assert camp["use_qr"] is True diff --git a/backend/tests/test_live_scheduler.py b/backend/tests/test_live_scheduler.py new file mode 100644 index 0000000..187c63a --- /dev/null +++ b/backend/tests/test_live_scheduler.py @@ -0,0 +1,117 @@ +"""Recurring campaign schedules: materialisation, the due loop, and the API.""" + +from datetime import UTC, datetime, timedelta + +from services.database import db +from services.live import scheduler +from tests.conftest import make_user + +TEMPLATE = { + "name": "Monthly helpdesk drill", + "objective": "click_link", + "principles": ["authority"], + "sender_name": "IT Helpdesk", + "sender_email": "helpdesk@acme.test", + "subject": "Password reset required", + "body_html": "

Reset: {{.URL}}

", + "recipients": ["alice@acme.test", "bob@acme.test"], + "max_turns": 0, + "language": "en", +} + + +async def _schedule(**over): + doc = { + "id": over.get("id", "sch-1"), + "organization_id": None, + "name": "sched", + "interval_days": 30, + "window_days": 5, + "next_run": datetime.now(UTC).isoformat(), + "active": True, + "template": TEMPLATE, + "created_by": "sys", + } + doc.update(over) + await db.campaign_schedules.insert_one(doc) + return doc + + +# ---------- materialisation ---------- + + +async def test_materialize_creates_pending_approval_campaign(api): + s = await _schedule() + cid = await scheduler.materialize(s) + camp = await db.live_campaigns.find_one({"id": cid}, {"_id": 0}) + assert camp["status"] == "pending_approval" # never auto-sent (G2) + assert camp["objective"] == "click_link" + assert camp["scheduled_from"] == "sch-1" + assert camp["recipients"] == ["alice@acme.test", "bob@acme.test"] + + +async def test_materialize_bad_template_returns_none(api): + s = await _schedule(id="bad", template={"name": "x"}) # missing required fields + assert await scheduler.materialize(s) is None + + +# ---------- the due loop ---------- + + +async def test_run_due_materialises_and_advances(api): + await _schedule(next_run=(datetime.now(UTC) - timedelta(minutes=1)).isoformat()) + created = await scheduler.run_due() + assert len(created) == 1 + s = await db.campaign_schedules.find_one({"id": "sch-1"}, {"_id": 0}) + # next_run advanced ~interval_days into the future + assert datetime.fromisoformat(s["next_run"]) > datetime.now(UTC) + timedelta(days=29) + assert s["last_campaign_id"] == created[0] + + +async def test_run_due_skips_future_and_inactive(api): + await _schedule(id="future", next_run=(datetime.now(UTC) + timedelta(days=10)).isoformat()) + await _schedule( + id="off", active=False, next_run=(datetime.now(UTC) - timedelta(days=1)).isoformat() + ) + created = await scheduler.run_due() + assert created == [] + + +# ---------- API ---------- + + +async def test_schedule_crud(api): + _, h = await make_user("trainer", organization_id="acme") + body = { + "name": "Monthly", + "interval_days": 30, + "window_days": 5, + "start_in_days": 0, + "template": TEMPLATE, + } + created = (await api.post("/api/live/schedules", json=body, headers=h)).json() + sid = created["id"] + assert created["active"] is True and created["interval_days"] == 30 + + listed = (await api.get("/api/live/schedules", headers=h)).json() + assert len(listed) == 1 + + # run-now materialises a pending_approval campaign + run = await api.post(f"/api/live/schedules/{sid}/run-now", headers=h) + assert run.status_code == 200 + cid = run.json()["created_campaign"] + assert (await db.live_campaigns.find_one({"id": cid}))["status"] == "pending_approval" + + # pause it + await api.patch(f"/api/live/schedules/{sid}", json={"active": False}, headers=h) + assert (await db.campaign_schedules.find_one({"id": sid}))["active"] is False + + # delete + assert (await api.delete(f"/api/live/schedules/{sid}", headers=h)).status_code == 200 + assert await db.campaign_schedules.count_documents({"id": sid}) == 0 + + +async def test_schedules_require_staff(api): + _, h = await make_user("user") + assert (await api.get("/api/live/schedules", headers=h)).status_code == 403 + assert (await api.post("/api/live/schedules", json={}, headers=h)).status_code == 403 diff --git a/docs/api.md b/docs/api.md index add5cc0..31c8da6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -103,6 +103,11 @@ Audit — `/api/audit` (admin): `GET /` (entries), `GET /verify` (chain integrit `PATCH /{id}` (triage). `DELETE /api/live/campaigns/{id}` removes a finished campaign. - `GET /api/live/analytics` — historical behaviour across launched campaigns: report-rate trend, per-campaign comparison, and repeat offenders. +- `/api/live/schedules` — recurring campaigns (staff): CRUD + `POST /{id}/run-now`. + Each cycle materialises a campaign in `pending_approval` (never auto-sent, G2). +- `GET /api/live/qr?data=` — public PNG QR code for "quishing" campaigns. +- `GET /api/attack-surface/targets` — emailable people on the map, ranked + most-susceptible first, to seed a campaign aimed at the human weak points. ## Health diff --git a/docs/roadmap.md b/docs/roadmap.md index 332c56b..3170e94 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -118,10 +118,18 @@ node click for the same staff who already see risk profiles (guardrail G13). more than once — the ones the remediation loop should be hardening). - **AI Challenge demoted** — still server-scored and assignable, but removed from the headline nav; it now serves as a targeted practice / remediation exercise. +- **Recurring schedules** (`services/live/scheduler.py`) — a schedule materialises + a campaign on a cadence (baseline → periodic retest), each run in + `pending_approval` so two-person approval still holds (G2). +- **Quishing** — a campaign can deliver its lure as a QR code encoding the tracked + URL (`/live/qr`, `use_qr`); a scan is attributed exactly like a click. +- **Launch from the Attack Surface Map** — `GET /attack-surface/targets` + a + one-click flow that pre-fills a campaign with the most-susceptible, emailable + people. The map finds the human risk; one click targets it; results feed back. ## Deferred (real product, later) TLS/public deployment and multi-worker rate limiting; management reporting and -export; recurring/scheduled campaigns; supervised auto-send; prompt-quality -evaluation for the AI personas; IMAP auto-ingest for the report mailbox and an -end-user "Report Phish" button. +export; supervised auto-send (scheduled runs still require manual approval); +prompt-quality evaluation for the AI personas; IMAP auto-ingest for the report +mailbox and an end-user "Report Phish" button. diff --git a/docs/user-guide.md b/docs/user-guide.md index 2d13995..6e9ed31 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -178,6 +178,18 @@ sent; if a recipient types a secret (OTP, password) it is redacted before storag and the thread ends with a teachable-moment email. This layer is powerful but stays manual by design (G8) — it is not the headline. +**More controls on the Live Campaigns page:** + +- **Jadwalkan berulang** — turn the create form into a recurring schedule; each + cycle materialises a campaign in *pending_approval* (never auto-sent, G2). Manage + schedules in the "Kampanye terjadwal" card (run-now / pause / delete). +- **Quishing (kode QR)** — tick this to deliver the lure as a QR code that encodes + the tracked link; a scan is attributed like a click. Set the app's **Public base + URL** in Settings first so mail clients can load the QR image. +- **Daftar kecuali** — the allowlist of people who must never be phished. +- **Luncurkan ke titik rawan** — from the Attack Surface Map, one click pre-fills a + campaign with the most-susceptible, emailable people. + --- ## 5b. Human Attack Surface Map (admin / trainer) diff --git a/frontend/src/pages/AttackSurfaceMapPage.js b/frontend/src/pages/AttackSurfaceMapPage.js index 8a84241..001d0c3 100644 --- a/frontend/src/pages/AttackSurfaceMapPage.js +++ b/frontend/src/pages/AttackSurfaceMapPage.js @@ -1,7 +1,8 @@ import React, { useMemo, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; import { Share2, ShieldAlert, Crosshair, Target, RefreshCw, Trash2, Database, - Banknote, KeyRound, Server, Loader2, TriangleAlert, Lock, + Banknote, KeyRound, Server, Loader2, TriangleAlert, Lock, Radio, } from 'lucide-react'; import PageHeader from '../components/PageHeader'; import SectionCard from '../components/SectionCard'; @@ -193,9 +194,28 @@ export default function AttackSurfaceMapPage() { const [selectedPath, setSelectedPath] = useState(null); const [selectedNode, setSelectedNode] = useState(null); const [busy, setBusy] = useState(false); + const navigate = useNavigate(); const refresh = () => { refetchGraph(); refetchAnalysis(); }; + // Hand the emailable, most-susceptible people to a new campaign. + const launchToWeakPoints = async () => { + setBusy(true); + try { + const { data } = await api.get('/attack-surface/targets'); + const emails = (data.targets || []).map((t) => t.email); + if (emails.length === 0) { + toast.error('Tidak ada node dengan email. Tautkan node ke user atau isi emailnya.'); + return; + } + try { sessionStorage.setItem('pretexta_prefill_recipients', emails.join('\n')); } catch { /* noop */ } + toast.success(`${emails.length} target disiapkan untuk kampanye`); + navigate('/live'); + } catch (e) { + toast.error(e.response?.data?.detail || 'Gagal'); + } finally { setBusy(false); } + }; + const act = async (fn, msg) => { setBusy(true); try { await fn(); toast.success(msg); setSelectedPath(null); refresh(); } @@ -218,6 +238,12 @@ export default function AttackSurfaceMapPage() { className="text-[10px] uppercase tracking-widest"> Segarkan + {!empty && ( + + )} {!empty && ( + + + + + ))} + + + ); +}); + const BLANK = { name: '', objective: 'click_link', principles: ['authority'], sender_name: 'IT Helpdesk', sender_email: 'helpdesk@acme.test', subject: '', body_html: '

Hello,

Please confirm here: {{.URL}}

', - recipients: '', starts_at: '', ends_at: '', max_turns: 0, + recipients: '', starts_at: '', ends_at: '', max_turns: 0, use_qr: false, }; -function CreateForm({ onClose, onCreated }) { - const [f, setF] = useState(BLANK); +function CreateForm({ onClose, onCreated, onScheduled, initial }) { + const [f, setF] = useState({ ...BLANK, ...(initial || {}) }); const [templates, setTemplates] = useState([]); const [aiMode, setAiMode] = useState(false); // click campaign by default + const [recurring, setRecurring] = useState(false); + const [sched, setSched] = useState({ interval_days: 30, window_days: 5 }); const set = (k, v) => setF((p) => ({ ...p, [k]: v })); const togglePrinciple = (p) => set('principles', f.principles.includes(p) ? f.principles.filter((x) => x !== p) : [...f.principles, p]); @@ -225,15 +281,34 @@ function CreateForm({ onClose, onCreated }) { }; const submit = async () => { - const payload = { - ...f, - max_turns: Number(f.max_turns), - recipients: f.recipients.split(/[\s,;]+/).map((x) => x.trim()).filter(Boolean), - starts_at: new Date(f.starts_at).toISOString(), - ends_at: new Date(f.ends_at).toISOString(), - }; + const recipients = f.recipients.split(/[\s,;]+/).map((x) => x.trim()).filter(Boolean); try { - const res = await api.post('/live/campaigns', payload); + if (recurring) { + // Build the schedule template — only the content fields (no time window). + const template = { + name: f.name, objective: f.objective, principles: f.principles, + sender_name: f.sender_name, sender_email: f.sender_email, + subject: f.subject, body_html: f.body_html, recipients, + max_turns: Number(f.max_turns), language: f.language || 'en', + use_qr: !!f.use_qr, + }; + await api.post('/live/schedules', { + name: f.name || 'Jadwal kampanye', + interval_days: Number(sched.interval_days), + window_days: Number(sched.window_days), + start_in_days: 0, + template, + }); + toast.success('Jadwal dibuat — tiap siklus membuat kampanye untuk disetujui'); + onScheduled?.(); + onClose?.(); + return; + } + const res = await api.post('/live/campaigns', { + ...f, max_turns: Number(f.max_turns), recipients, + starts_at: new Date(f.starts_at).toISOString(), + ends_at: new Date(f.ends_at).toISOString(), + }); toast.success('Campaign drafted'); onCreated(res.data.id); } catch (e) { @@ -287,8 +362,36 @@ function CreateForm({ onClose, onCreated }) {
set('sender_name', e.target.value)} />
set('sender_email', e.target.value)} />
-
set('starts_at', e.target.value)} />
-
set('ends_at', e.target.value)} />
+ {!recurring && <> +
set('starts_at', e.target.value)} />
+
set('ends_at', e.target.value)} />
+ } +
+ + {/* Quishing: deliver the lure as a QR code encoding the tracked URL. */} + + + {/* Recurring schedule: each cycle materialises a campaign for approval (G2). */} +
+ + {recurring && ( +
+
setSched((p) => ({ ...p, interval_days: e.target.value }))} />
+
setSched((p) => ({ ...p, window_days: e.target.value }))} />
+
+ )}
{/* Advanced AI settings only when the AI mode is chosen. */} @@ -329,7 +432,11 @@ function CreateForm({ onClose, onCreated }) {