diff --git a/backend/routes/live.py b/backend/routes/live.py index bd9b0c5..9515658 100644 --- a/backend/routes/live.py +++ b/backend/routes/live.py @@ -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, @@ -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"]) @@ -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"} @@ -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") diff --git a/backend/services/live/launch.py b/backend/services/live/launch.py index c67c6ad..5c7a2b3 100644 --- a/backend/services/live/launch.py +++ b/backend/services/live/launch.py @@ -346,10 +346,54 @@ def _naive_utc(dt: datetime) -> datetime: "body_html": "
As part of our security upgrade, all laptops must run the new " 'endpoint agent by end of week. Download and install: get the agent.
', }, + # 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": "Yth. Bapak/Ibu,
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: perbarui kata sandi.' + "
Terima kasih,
Helpdesk TI
Halo,
Rekan Anda dari bagian Keuangan membagikan dokumen " + "Laporan Triwulan III (final). Tujuh rekan lain sudah memberi komentar dan " + 'menunggu masukan Anda: buka dokumen.
', + }, + { + "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": "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: {{.URL}}. Tolong dirahasiakan dulu sampai ' + "saya kabari.
", + }, ] 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) diff --git a/backend/tests/test_live.py b/backend/tests/test_live.py index 9834d6a..9ebda69 100644 --- a/backend/tests/test_live.py +++ b/backend/tests/test_live.py @@ -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": 'Baca protap terbaru: buka
', + "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": "Cek tagihan BPJS: {{.URL}}
"}, # G10 + {"body_html": "Tidak ada tautan
"}, # 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 ---------- diff --git a/docs/api.md b/docs/api.md index dffa44e..ae52f82 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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) | diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index ffd95ca..9e106db 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -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", @@ -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": { diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json index 188e884..3485f54 100644 --- a/frontend/src/i18n/locales/id.json +++ b/frontend/src/i18n/locales/id.json @@ -543,7 +543,10 @@ "pending": "menunggu DNS", "sandbox_ok": "Domain sandbox terverifikasi", "verified_toast": "Terverifikasi", - "txt_missing": "Record TXT tidak ditemukan" + "txt_missing": "Record TXT tidak ditemukan", + "delete": "Hapus domain", + "confirm_delete": "Yakin?", + "deleted": "{{domain}} dihapus" }, "exclusions": { "title": "Daftar kecuali", @@ -604,7 +607,16 @@ "draft_ok": "Draf kampanye dibuat", "create_failed": "Gagal membuat", "create_schedule": "Buat jadwal", - "create_draft": "Buat draf" + "create_draft": "Buat draf", + "language": "Bahasa campaign (dipakai untuk balasan AI)", + "tpl_group_custom": "Milik organisasi", + "tpl_group_id": "Bawaan · Bahasa Indonesia", + "tpl_group_en": "Bawaan · English", + "tpl_save": "Simpan isi saat ini sebagai template", + "tpl_need_content": "Isi subjek dan isi email terlebih dahulu", + "tpl_saved": "Template disimpan", + "tpl_delete": "Hapus template ini", + "tpl_deleted": "Template dihapus" } }, "status": { diff --git a/frontend/src/pages/LiveCampaignsPage.js b/frontend/src/pages/LiveCampaignsPage.js index de77d32..5e63b09 100644 --- a/frontend/src/pages/LiveCampaignsPage.js +++ b/frontend/src/pages/LiveCampaignsPage.js @@ -109,6 +109,17 @@ function DomainsCard() { toast[res.data.verified ? 'success' : 'error'](res.data.verified ? t('live.domains.verified_toast') : t('live.domains.txt_missing')); load(); }; + // Two-step delete: the first click arms the button, the second removes the domain. + const [armed, setArmed] = useState(null); + const remove = async (d) => { + if (armed !== d.id) { setArmed(d.id); return; } + setArmed(null); + try { + await api.delete(`/live/domains/${d.id}`); + toast.success(t('live.domains.deleted', { domain: d.domain })); + load(); + } catch (e) { toast.error(e.response?.data?.detail || t('live.failed')); } + }; return (