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
124 changes: 117 additions & 7 deletions backend/routes/live.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@
"""

import io
import re
import uuid
from datetime import UTC, datetime, timedelta
from typing import Any
from typing import Any, Literal

import segno
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from pydantic import BaseModel, Field
from pydantic import BaseModel, ConfigDict, Field

from models.schemas import (
CIALDINI_PRINCIPLES,
LIVE_OBJECTIVES,
CampaignSchedule,
CampaignTemplate,
LiveCampaign,
Expand All @@ -31,7 +35,7 @@
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
from services.live.preflight import check_content, has_errors, run_preflight

router = APIRouter(prefix="/live", tags=["live-campaigns"])
audit_router = APIRouter(prefix="/audit", tags=["audit"])
Expand Down Expand Up @@ -120,11 +124,51 @@ async def verify_domain(domain_id: str, current_user: User = Depends(require_tra
return {"domain": doc["domain"], "verified": ok}


def _on_domain(domain: str) -> dict:
"""Mongo regex matching addresses on `domain` or any of its subdomains."""
return {"$regex": rf"[@.]{re.escape(domain)}$", "$options": "i"}


async def _domain_in_use(doc: dict) -> str | None:
"""Name of an active campaign or schedule that still relies on this domain."""
on_domain = _on_domain(doc["domain"])
campaign = await db.live_campaigns.find_one(
{
"organization_id": doc.get("organization_id"),
"status": {"$in": list(ACTIVE_STATUSES)},
"$or": [{"sender_email": on_domain}, {"recipients": on_domain}],
},
{"_id": 0, "name": 1},
)
if campaign:
return f"campaign '{campaign['name']}'"
schedule = await db.campaign_schedules.find_one(
{
"organization_id": doc.get("organization_id"),
"active": True,
"$or": [{"template.sender_email": on_domain}, {"template.recipients": on_domain}],
},
{"_id": 0, "name": 1},
)
if schedule:
return f"recurring schedule '{schedule['name']}'"
return None


@router.delete("/domains/{domain_id}")
async def delete_domain(domain_id: str, current_user: User = Depends(require_admin)):
doc = await db.verified_domains.find_one_and_delete({"id": domain_id}, {"_id": 0})
async def delete_domain(domain_id: str, current_user: User = Depends(require_trainer)):
"""Remove a domain. Blocked while an active campaign or schedule still uses it,
so a running campaign never loses the verification it was approved under."""
doc = await db.verified_domains.find_one({"id": domain_id, **_scope(current_user)}, {"_id": 0})
if not doc:
raise HTTPException(status_code=404, detail="Domain not found")
user_of = await _domain_in_use(doc)
if user_of:
raise HTTPException(
status_code=409,
detail=f"{doc['domain']} is still used by {user_of}. Close, kill or pause it first.",
)
await db.verified_domains.delete_one({"id": domain_id})
await audit.record(current_user.id, "live.domain.delete", doc["domain"])
return {"message": "Domain removed"}

Expand Down Expand Up @@ -176,10 +220,76 @@ def _public(doc: dict) -> dict:
return {**doc, "recipient_count": len(doc.get("recipients", []))}


class LiveTemplateCreate(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1, max_length=120)
category: str = Field(default="Custom", min_length=1, max_length=60)
objective: str
principles: list[str] = Field(min_length=1)
sender_name: str = Field(min_length=1, max_length=80)
subject: str = Field(min_length=1, max_length=200)
body_html: str = Field(min_length=1, max_length=20000)
language: Literal["en", "id"] = "en"


def _template_scope(user: User) -> dict:
"""Built-in templates for everyone; custom ones only within their organization."""
if user.role == "admin":
return {}
return {"$or": [{"builtin": {"$ne": False}}, {"organization_id": user.organization_id}]}


@router.get("/templates")
async def list_templates(current_user: User = Depends(require_trainer)):
"""Built-in phishing templates to start a campaign from."""
return await db.live_templates.find({}, {"_id": 0}).sort("name", 1).to_list(100)
"""Phishing templates to start a campaign from: built-in plus the organization's own."""
return (
await db.live_templates.find(_template_scope(current_user), {"_id": 0})
.sort([("builtin", -1), ("language", 1), ("name", 1)])
.to_list(500)
)


@router.post("/templates", status_code=201)
async def create_template(body: LiveTemplateCreate, current_user: User = Depends(require_trainer)):
"""Save a custom template. It must pass the same content guardrails (G7, G9, G10)
as a campaign, so a template can never be one that pre-flight would block."""
if body.objective not in LIVE_OBJECTIVES:
raise HTTPException(422, f"Unknown objective '{body.objective}'")
unknown = set(body.principles) - set(CIALDINI_PRINCIPLES)
if unknown:
raise HTTPException(422, f"Unknown principles: {sorted(unknown)}")
errors = [f["message"] for f in check_content(body.model_dump()) if f["level"] == "error"]
if errors:
raise HTTPException(422, "; ".join(errors))
if await db.live_templates.find_one(
{"name": body.name, "builtin": False, "organization_id": current_user.organization_id}
):
raise HTTPException(409, "A template with this name already exists")
doc = {
**body.model_dump(),
"id": f"tmpl-c-{uuid.uuid4().hex[:12]}",
"builtin": False,
"organization_id": current_user.organization_id,
"created_by": current_user.id,
"created_at": datetime.now(UTC).isoformat(),
}
await db.live_templates.insert_one(dict(doc))
await audit.record(current_user.id, "live.template.create", doc["id"], {"name": body.name})
return doc


@router.delete("/templates/{template_id}")
async def delete_template(template_id: str, current_user: User = Depends(require_trainer)):
doc = await db.live_templates.find_one(
{"id": template_id, **_template_scope(current_user)}, {"_id": 0}
)
if not doc:
raise HTTPException(404, "Template not found")
if doc.get("builtin", True):
raise HTTPException(400, "Built-in templates cannot be deleted")
await db.live_templates.delete_one({"id": template_id})
await audit.record(current_user.id, "live.template.delete", template_id, {"name": doc["name"]})
return {"message": "Template deleted"}


@router.get("/qr")
Expand Down
50 changes: 47 additions & 3 deletions backend/services/live/launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,10 +346,54 @@ def _naive_utc(dt: datetime) -> datetime:
"body_html": "<p>As part of our security upgrade, all laptops must run the new "
'endpoint agent by end of week. Download and install: <a href="{{.URL}}">get the agent</a>.</p>',
},
# Bahasa Indonesia
{
"id": "tmpl-id-password-expiry",
"name": "Helpdesk TI — kata sandi kedaluwarsa",
"category": "Klik / Kredensial",
"language": "id",
"objective": "click_link",
"principles": ["authority", "scarcity"],
"sender_name": "Helpdesk TI",
"subject": "Kata sandi akun Anda kedaluwarsa hari ini",
"body_html": "<p>Yth. Bapak/Ibu,</p><p>Kata sandi akun kantor Anda akan kedaluwarsa "
"hari ini pukul 17.00. Agar akses email dan aplikasi internal tidak terhenti, "
'perbarui kata sandi melalui tautan berikut: <a href="{{.URL}}">perbarui kata sandi</a>.'
"</p><p>Terima kasih,<br>Helpdesk TI</p>",
},
{
"id": "tmpl-id-shared-document",
"name": "Dokumen bersama — laporan triwulan",
"category": "Klik / Kredensial",
"language": "id",
"objective": "click_link",
"principles": ["liking", "social_proof"],
"sender_name": "Berbagi Dokumen",
"subject": "Dokumen dibagikan kepada Anda: Laporan Triwulan III (final)",
"body_html": "<p>Halo,</p><p>Rekan Anda dari bagian Keuangan membagikan dokumen "
"<b>Laporan Triwulan III (final)</b>. Tujuh rekan lain sudah memberi komentar dan "
'menunggu masukan Anda: <a href="{{.URL}}">buka dokumen</a>.</p>',
},
{
"id": "tmpl-id-director-payment",
"name": "Direktur — pembayaran vendor mendesak",
"category": "Business Email Compromise",
"language": "id",
"objective": "agree_to_approve_payment",
"principles": ["authority", "scarcity"],
"sender_name": "Kantor Direktur",
"subject": "Bisa bantu sebentar? Mendesak",
"body_html": "<p>Saya sedang rapat dan tidak bisa menerima telepon. Ada pembayaran "
"vendor yang harus diproses hari ini sebelum pukul 15.00. Mohon konfirmasi lewat "
'portal berikut: <a href="{{.URL}}">{{.URL}}</a>. Tolong dirahasiakan dulu sampai '
"saya kabari.</p>",
},
]


async def seed_templates() -> None:
if await db.live_templates.count_documents({}):
return
await db.live_templates.insert_many([dict(t) for t in LIVE_TEMPLATES])
"""Upsert the built-in templates by id, so templates added in a later release
reach instances that were seeded earlier. Custom templates are never touched."""
for template in LIVE_TEMPLATES:
doc = {"language": "en", **template, "builtin": True}
await db.live_templates.update_one({"id": doc["id"]}, {"$set": doc}, upsert=True)
129 changes: 129 additions & 0 deletions backend/tests/test_live.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,135 @@ async def test_live_templates_seeded_and_listed(api):
async def test_templates_require_trainer(api):
_, h = await make_user("user")
assert (await api.get("/api/live/templates", headers=h)).status_code == 403
assert (await api.post("/api/live/templates", json={}, headers=h)).status_code == 403


def test_builtin_templates_pass_content_guardrails():
from services.live.launch import LIVE_TEMPLATES
from services.live.preflight import check_content

assert len({t["id"] for t in LIVE_TEMPLATES}) == len(LIVE_TEMPLATES)
assert any(t.get("language") == "id" for t in LIVE_TEMPLATES)
for t in LIVE_TEMPLATES:
assert check_content(t) == [], t["id"]


async def test_seed_templates_adds_new_builtins_and_keeps_custom(api):
from services.live.launch import LIVE_TEMPLATES, seed_templates

# An instance seeded by an older release: one built-in plus a custom template.
await db.live_templates.insert_one({**LIVE_TEMPLATES[0], "name": "old copy"})
await db.live_templates.insert_one({"id": "tmpl-c-1", "name": "mine", "builtin": False})
await seed_templates()
await seed_templates() # idempotent
ids = {d["id"] for d in await db.live_templates.find({}, {"id": 1}).to_list(100)}
assert {t["id"] for t in LIVE_TEMPLATES} | {"tmpl-c-1"} == ids
refreshed = await db.live_templates.find_one({"id": LIVE_TEMPLATES[0]["id"]})
assert refreshed["name"] == LIVE_TEMPLATES[0]["name"] and refreshed["builtin"] is True
assert (await db.live_templates.find_one({"id": "tmpl-c-1"}))["name"] == "mine"


def _template(**over):
base = {
"name": "Nota dinas — protap baru",
"category": "Internal",
"objective": "click_link",
"principles": ["authority"],
"sender_name": "Sekretariat",
"subject": "Protap baru wajib dibaca",
"body_html": '<p>Baca protap terbaru: <a href="{{.URL}}">buka</a></p>',
"language": "id",
}
base.update(over)
return base


async def test_custom_templates_are_org_scoped(api):
from services.live.launch import seed_templates

await seed_templates()
_, a = await make_user("trainer", organization_id="org-a")
_, b = await make_user("trainer", organization_id="org-b")

r = await api.post("/api/live/templates", json=_template(), headers=a)
assert r.status_code == 201, r.text
tid = r.json()["id"]
assert r.json()["builtin"] is False and r.json()["organization_id"] == "org-a"

names_a = {t["name"] for t in (await api.get("/api/live/templates", headers=a)).json()}
names_b = {t["name"] for t in (await api.get("/api/live/templates", headers=b)).json()}
assert "Nota dinas — protap baru" in names_a
assert "Nota dinas — protap baru" not in names_b
assert "IT Helpdesk — verify your mailbox" in names_b # built-ins stay visible

assert (await api.post("/api/live/templates", json=_template(), headers=a)).status_code == 409
assert (await api.post("/api/live/templates", json=_template(), headers=b)).status_code == 201

assert (await api.delete(f"/api/live/templates/{tid}", headers=b)).status_code == 404
builtin = "tmpl-helpdesk-otp"
assert (await api.delete(f"/api/live/templates/{builtin}", headers=a)).status_code == 400
assert (await api.delete(f"/api/live/templates/{tid}", headers=a)).status_code == 200
assert not await db.live_templates.find_one({"id": tid})
assert await db.audit_log.find_one({"action": "live.template.delete", "target": tid})


@pytest.mark.parametrize(
"over",
[
{"subject": "Info kenaikan gaji triwulan ini"}, # G9
{"body_html": "<p>Cek tagihan BPJS: {{.URL}}</p>"}, # G10
{"body_html": "<p>Tidak ada tautan</p>"}, # click_link without {{.URL}}
{"objective": "steal_everything"}, # G7
{"principles": ["fear"]}, # G7
{"language": "fr"},
],
)
async def test_custom_template_must_pass_content_guardrails(api, over):
_, h = await make_user("trainer")
r = await api.post("/api/live/templates", json=_template(**over), headers=h)
assert r.status_code == 422, r.text
assert not await db.live_templates.find_one({"builtin": False})


# ---------- delete domain ----------


async def test_delete_domain_scoped_and_blocked_while_in_use(api):
_, a = await make_user("trainer", organization_id="org-a")
_, b = await make_user("trainer", organization_id="org-b")
dom = await _add_sandbox_domain(api, a)

assert (await api.delete(f"/api/live/domains/{dom['id']}", headers=b)).status_code == 404

r = await api.post("/api/live/campaigns", json=_campaign(), headers=a)
cid = r.json()["id"]
await api.post(f"/api/live/campaigns/{cid}/submit", headers=a)
r = await api.delete(f"/api/live/domains/{dom['id']}", headers=a)
assert r.status_code == 409 and "Q4 helpdesk drill" in r.json()["detail"]

await db.live_campaigns.update_one({"id": cid}, {"$set": {"status": "closed"}})
assert (await api.delete(f"/api/live/domains/{dom['id']}", headers=a)).status_code == 200
assert not await db.verified_domains.find_one({"id": dom["id"]})
assert await db.audit_log.find_one({"action": "live.domain.delete", "target": "acme.test"})


async def test_delete_domain_blocked_by_active_schedule(api):
_, h = await make_user("trainer", organization_id="org-a")
dom = await _add_sandbox_domain(api, h, "sub.acme.test")
template = {k: v for k, v in _campaign().items() if k not in ("starts_at", "ends_at")}
template["recipients"] = ["carol@sub.acme.test"]
template["sender_email"] = "it@sub.acme.test"
r = await api.post(
"/api/live/schedules",
json={"name": "Monthly drill", "interval_days": 30, "template": template},
headers=h,
)
assert r.status_code == 201, r.text
r = await api.delete(f"/api/live/domains/{dom['id']}", headers=h)
assert r.status_code == 409 and "Monthly drill" in r.json()["detail"]

await db.campaign_schedules.update_many({}, {"$set": {"active": False}})
assert (await api.delete(f"/api/live/domains/{dom['id']}", headers=h)).status_code == 200


# ---------- delete campaign ----------
Expand Down
5 changes: 4 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ directly (409).
|--------|------|------|---------|
| GET/POST | `/domains` | T | List / add a recipient domain (G1) |
| POST | `/domains/{id}/verify` | T | Re-check DNS TXT |
| DELETE | `/domains/{id}` | A | Remove |
| DELETE | `/domains/{id}` | T | Remove (own organization; 409 while an active campaign or schedule still uses it) |
| GET | `/templates` | T | Built-in templates (EN/ID) plus the organization's custom ones |
| POST | `/templates` | T | Save a custom template (must pass G7/G9/G10 content checks) |
| DELETE | `/templates/{id}` | T | Delete a custom template (built-ins cannot be deleted) |
| GET/POST | `/exclusions` | T | Exclusion list (G11) |
| DELETE | `/exclusions/{email}` | T | |
| GET/POST | `/campaigns` | T | List / create (runs pre-flight) |
Expand Down
16 changes: 14 additions & 2 deletions frontend/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,10 @@
"pending": "pending DNS",
"sandbox_ok": "Sandbox domain verified",
"verified_toast": "Verified",
"txt_missing": "TXT record not found"
"txt_missing": "TXT record not found",
"delete": "Remove domain",
"confirm_delete": "Confirm?",
"deleted": "{{domain}} removed"
},
"exclusions": {
"title": "Exclusion list",
Expand Down Expand Up @@ -604,7 +607,16 @@
"draft_ok": "Campaign drafted",
"create_failed": "Create failed",
"create_schedule": "Create schedule",
"create_draft": "Create draft"
"create_draft": "Create draft",
"language": "Campaign language (AI replies use it)",
"tpl_group_custom": "Your organization",
"tpl_group_id": "Built-in · Bahasa Indonesia",
"tpl_group_en": "Built-in · English",
"tpl_save": "Save current content as a template",
"tpl_need_content": "Fill in the subject and body first",
"tpl_saved": "Template saved",
"tpl_delete": "Delete this template",
"tpl_deleted": "Template deleted"
}
},
"status": {
Expand Down
Loading
Loading