feat(web): SMTP victim-domain + stored-mail panels on attacker detail

Adds GET /attackers/{uuid}/smtp-targets (viewer) and GET /attackers/{uuid}/mail
(admin) endpoints, plus two new sections on the attacker detail page:
VICTIM DOMAINS rollup (aggregate-only, federation-gossip-safe) and STORED MAIL
with a drawer that decodes headers, lists attachments, and downloads the raw
.eml via the existing artifact endpoint (?service=smtp).
This commit is contained in:
2026-04-22 22:33:53 -04:00
parent d43303251d
commit 8cbb7834ef
9 changed files with 618 additions and 1 deletions

View File

@@ -187,6 +187,11 @@ class BaseRepository(ABC):
"""Return SmtpTarget rows for an attacker, ordered by most-recent first.""" """Return SmtpTarget rows for an attacker, ordered by most-recent first."""
pass pass
@abstractmethod
async def get_attacker_stored_mail(self, uuid: str) -> list[Any]:
"""Return `message_stored` log rows for an attacker, newest first."""
pass
@abstractmethod @abstractmethod
async def smtp_target_seen(self, domain: str) -> dict[str, Any]: async def smtp_target_seen(self, domain: str) -> dict[str, Any]:
""" """

View File

@@ -898,6 +898,30 @@ class SQLModelRepository(BaseRepository):
) )
return [r.model_dump(mode="json") for r in rows.scalars().all()] return [r.model_dump(mode="json") for r in rows.scalars().all()]
async def get_attacker_stored_mail(self, uuid: str) -> list[dict[str, Any]]:
"""Return `message_stored` logs for an attacker, newest first.
Mirrors :meth:`get_attacker_artifacts` — the SMTP template emits one
`message_stored` row per accepted DATA body, with headers + sha256 +
attachment manifest already decoded into ``fields`` by the ingester.
Capped at 200 rows to match the artifact/transcript query shape.
"""
async with self._session() as session:
ip_res = await session.execute(
select(Attacker.ip).where(Attacker.uuid == uuid)
)
ip = ip_res.scalar_one_or_none()
if not ip:
return []
rows = await session.execute(
select(Log)
.where(Log.attacker_ip == ip)
.where(Log.event_type == "message_stored")
.order_by(desc(Log.timestamp))
.limit(200)
)
return [r.model_dump(mode="json") for r in rows.scalars().all()]
async def get_session_log(self, sid: str) -> Optional[dict[str, Any]]: async def get_session_log(self, sid: str) -> Optional[dict[str, Any]]:
"""Look up the `session_recorded` Log row that owns a given sid. """Look up the `session_recorded` Log row that owns a given sid.

View File

@@ -16,6 +16,8 @@ from .attackers.api_get_attacker_detail import router as attacker_detail_router
from .attackers.api_get_attacker_commands import router as attacker_commands_router from .attackers.api_get_attacker_commands import router as attacker_commands_router
from .attackers.api_get_attacker_artifacts import router as attacker_artifacts_router from .attackers.api_get_attacker_artifacts import router as attacker_artifacts_router
from .attackers.api_get_attacker_transcripts import router as attacker_transcripts_router from .attackers.api_get_attacker_transcripts import router as attacker_transcripts_router
from .attackers.api_get_attacker_smtp_targets import router as attacker_smtp_targets_router
from .attackers.api_get_attacker_mail import router as attacker_mail_router
from .transcripts import transcripts_router from .transcripts import transcripts_router
from .config.api_get_config import router as config_get_router from .config.api_get_config import router as config_get_router
from .config.api_update_config import router as config_update_router from .config.api_update_config import router as config_update_router
@@ -68,6 +70,8 @@ api_router.include_router(attacker_detail_router)
api_router.include_router(attacker_commands_router) api_router.include_router(attacker_commands_router)
api_router.include_router(attacker_artifacts_router) api_router.include_router(attacker_artifacts_router)
api_router.include_router(attacker_transcripts_router) api_router.include_router(attacker_transcripts_router)
api_router.include_router(attacker_smtp_targets_router)
api_router.include_router(attacker_mail_router)
# Observability # Observability
api_router.include_router(stats_router) api_router.include_router(stats_router)

View File

@@ -0,0 +1,37 @@
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from decnet.telemetry import traced as _traced
from decnet.web.dependencies import require_admin, repo
router = APIRouter()
@router.get(
"/attackers/{uuid}/mail",
tags=["Attacker Profiles"],
responses={
401: {"description": "Could not validate credentials"},
403: {"description": "Admin access required"},
404: {"description": "Attacker not found"},
},
)
@_traced("api.get_attacker_mail")
async def get_attacker_mail(
uuid: str,
admin: dict = Depends(require_admin),
) -> dict[str, Any]:
"""List stored messages this attacker relayed via the SMTP honeypots.
Each entry is a ``message_stored`` log row — headers + attachment
manifest live in ``fields``; the raw .eml bytes are fetched via
``/artifacts/{decky}/{stored_as}?service=smtp`` (also admin-gated).
Admin-only because message bodies are attacker-controlled content
and may include phishing kits / malware droppers.
"""
attacker = await repo.get_attacker_by_uuid(uuid)
if not attacker:
raise HTTPException(status_code=404, detail="Attacker not found")
rows = await repo.get_attacker_stored_mail(uuid)
return {"total": len(rows), "data": rows}

View File

@@ -0,0 +1,36 @@
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from decnet.telemetry import traced as _traced
from decnet.web.dependencies import require_viewer, repo
router = APIRouter()
@router.get(
"/attackers/{uuid}/smtp-targets",
tags=["Attacker Profiles"],
responses={
401: {"description": "Could not validate credentials"},
403: {"description": "Insufficient permissions"},
404: {"description": "Attacker not found"},
},
)
@_traced("api.get_attacker_smtp_targets")
async def get_attacker_smtp_targets(
uuid: str,
user: dict = Depends(require_viewer),
) -> dict[str, Any]:
"""List victim domains this attacker targeted via the SMTP honeypots.
Rows are ordered by most-recent activity. Each row is one
(attacker, domain) pair with a running count + first/last seen — no
local-parts (user names) are ever stored, so this is safe to show
to any viewer role.
"""
attacker = await repo.get_attacker_by_uuid(uuid)
if not attacker:
raise HTTPException(status_code=404, detail="Attacker not found")
rows = await repo.list_smtp_targets(uuid)
return {"total": len(rows), "data": rows}

View File

@@ -1,8 +1,9 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom'; import { useParams, useNavigate } from 'react-router-dom';
import { Activity, ArrowLeft, ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Crosshair, Fingerprint, Shield, Clock, Wifi, Lock, FileKey, Radio, Timer, Paperclip, Terminal, Package, FileText } from 'lucide-react'; import { Activity, ArrowLeft, ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Crosshair, Fingerprint, Shield, Clock, Wifi, Lock, FileKey, Radio, Timer, Paperclip, Terminal, Package, FileText, Mail, AtSign } from 'lucide-react';
import api from '../utils/api'; import api from '../utils/api';
import ArtifactDrawer from './ArtifactDrawer'; import ArtifactDrawer from './ArtifactDrawer';
import MailDrawer from './MailDrawer';
import SessionDrawer from './SessionDrawer'; import SessionDrawer from './SessionDrawer';
import EmptyState from './EmptyState/EmptyState'; import EmptyState from './EmptyState/EmptyState';
import './Dashboard.css'; import './Dashboard.css';
@@ -710,6 +711,8 @@ const AttackerDetail: React.FC = () => {
fingerprints: true, fingerprints: true,
artifacts: true, artifacts: true,
sessions: true, sessions: true,
smtpTargets: true,
mail: true,
}); });
// Captured file-drop artifacts (ssh inotify farm) for this attacker. // Captured file-drop artifacts (ssh inotify farm) for this attacker.
@@ -733,6 +736,28 @@ const AttackerDetail: React.FC = () => {
}; };
const [sessions, setSessions] = useState<SessionLog[]>([]); const [sessions, setSessions] = useState<SessionLog[]>([]);
const [session, setSession] = useState<{ decky: string; sid: string; fields: Record<string, any> } | null>(null); const [session, setSession] = useState<{ decky: string; sid: string; fields: Record<string, any> } | null>(null);
// SMTP victim-domain rollup (viewer-safe: domains only, no local parts).
type SmtpTargetRow = {
domain: string;
count: number;
first_seen: string;
last_seen: string;
};
const [smtpTargets, setSmtpTargets] = useState<SmtpTargetRow[]>([]);
// Stored SMTP messages (admin-gated: full attacker-controlled bodies).
type MailLog = {
id: number;
timestamp: string;
decky: string;
service: string;
fields: string;
};
const [mail, setMail] = useState<MailLog[]>([]);
const [mailForbidden, setMailForbidden] = useState(false);
const [mailItem, setMailItem] = useState<{ decky: string; storedAs: string; fields: Record<string, any> } | null>(null);
const toggle = (key: string) => setOpenSections((prev) => ({ ...prev, [key]: !prev[key] })); const toggle = (key: string) => setOpenSections((prev) => ({ ...prev, [key]: !prev[key] }));
// Commands pagination state // Commands pagination state
@@ -799,6 +824,34 @@ const AttackerDetail: React.FC = () => {
fetchArtifacts(); fetchArtifacts();
}, [id]); }, [id]);
useEffect(() => {
if (!id) return;
const fetchSmtpTargets = async () => {
try {
const res = await api.get(`/attackers/${id}/smtp-targets`);
setSmtpTargets(res.data.data ?? []);
} catch {
setSmtpTargets([]);
}
};
fetchSmtpTargets();
}, [id]);
useEffect(() => {
if (!id) return;
const fetchMail = async () => {
try {
const res = await api.get(`/attackers/${id}/mail`);
setMail(res.data.data ?? []);
setMailForbidden(false);
} catch (err: any) {
setMail([]);
setMailForbidden(err?.response?.status === 403);
}
};
fetchMail();
}, [id]);
useEffect(() => { useEffect(() => {
if (!id) return; if (!id) return;
const fetchSessions = async () => { const fetchSessions = async () => {
@@ -1200,6 +1253,141 @@ const AttackerDetail: React.FC = () => {
/> />
)} )}
{/* SMTP Victim Domains (viewer-safe rollup) */}
<Section
title={<>SMTP VICTIM DOMAINS ({smtpTargets.length})</>}
open={openSections.smtpTargets}
onToggle={() => toggle('smtpTargets')}
>
{smtpTargets.length > 0 ? (
<div className="logs-table-container">
<table className="logs-table">
<thead>
<tr>
<th>DOMAIN</th>
<th>COUNT</th>
<th>FIRST SEEN</th>
<th>LAST SEEN</th>
</tr>
</thead>
<tbody>
{smtpTargets.map((row) => (
<tr key={row.domain}>
<td className="matrix-text" style={{ fontFamily: 'monospace', wordBreak: 'break-all' }}>
{row.domain}
</td>
<td className="matrix-text" style={{ fontFamily: 'monospace' }}>
{row.count}
</td>
<td className="dim" style={{ fontSize: '0.75rem', whiteSpace: 'nowrap' }}>
{new Date(row.first_seen).toLocaleString()}
</td>
<td className="dim" style={{ fontSize: '0.75rem', whiteSpace: 'nowrap' }}>
{new Date(row.last_seen).toLocaleString()}
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<EmptyState
icon={AtSign}
title="NO SMTP VICTIMS OBSERVED"
size="compact"
/>
)}
</Section>
{/* Stored Mail (admin only — bodies are attacker-controlled) */}
<Section
title={<>STORED MAIL ({mail.length})</>}
open={openSections.mail}
onToggle={() => toggle('mail')}
>
{mailForbidden ? (
<EmptyState
icon={Mail}
title="ADMIN ROLE REQUIRED"
size="compact"
/>
) : mail.length > 0 ? (
<div className="logs-table-container">
<table className="logs-table">
<thead>
<tr>
<th>TIMESTAMP</th>
<th>DECKY</th>
<th>SUBJECT</th>
<th>FROM</th>
<th>SIZE</th>
<th></th>
</tr>
</thead>
<tbody>
{mail.map((row) => {
let fields: Record<string, any> = {};
try { fields = JSON.parse(row.fields || '{}'); } catch {}
const storedAs = fields.stored_as ? String(fields.stored_as) : null;
return (
<tr key={row.id}>
<td className="dim" style={{ fontSize: '0.75rem', whiteSpace: 'nowrap' }}>
{new Date(row.timestamp).toLocaleString()}
</td>
<td className="violet-accent">{row.decky}</td>
<td className="matrix-text" style={{ fontFamily: 'monospace', wordBreak: 'break-all' }}>
{fields.subject || '—'}
</td>
<td className="matrix-text" style={{ fontFamily: 'monospace', wordBreak: 'break-all' }}>
{fields.from_addr || fields.mail_from || '—'}
</td>
<td className="matrix-text" style={{ fontFamily: 'monospace' }}>
{fields.size ? `${fields.size} B` : '—'}
</td>
<td>
{storedAs && (
<button
onClick={() => setMailItem({ decky: row.decky, storedAs, fields })}
title="Inspect stored message"
style={{
display: 'flex', alignItems: 'center', gap: '6px',
fontSize: '0.7rem',
backgroundColor: 'rgba(255, 170, 0, 0.1)',
padding: '2px 8px',
borderRadius: '4px',
border: '1px solid rgba(255, 170, 0, 0.5)',
color: '#ffaa00',
cursor: 'pointer',
}}
>
<Mail size={11} /> OPEN
</button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
) : (
<EmptyState
icon={Mail}
title="NO MAIL STORED"
size="compact"
/>
)}
</Section>
{mailItem && (
<MailDrawer
decky={mailItem.decky}
storedAs={mailItem.storedAs}
fields={mailItem.fields}
onClose={() => setMailItem(null)}
/>
)}
{/* Recorded PTY Sessions (SSH / Telnet) */} {/* Recorded PTY Sessions (SSH / Telnet) */}
<Section <Section
title={<>SESSION TRANSCRIPTS ({sessions.length})</>} title={<>SESSION TRANSCRIPTS ({sessions.length})</>}

View File

@@ -0,0 +1,216 @@
import React, { useEffect, useRef, useState } from 'react';
import { X, Download, AlertTriangle, Paperclip } from 'lucide-react';
import api from '../utils/api';
import { useEscapeKey } from '../hooks/useEscapeKey';
import { useFocusTrap } from '../hooks/useFocusTrap';
interface MailDrawerProps {
decky: string;
storedAs: string;
fields: Record<string, any>;
onClose: () => void;
}
interface AttachmentManifest {
filename?: string | null;
content_type?: string | null;
size?: number | null;
sha256?: string | null;
}
function parseAttachments(fields: Record<string, any>): AttachmentManifest[] {
const raw = fields.attachments_json;
if (typeof raw !== 'string' || !raw) return [];
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch (err) {
console.error('mail: failed to parse attachments_json', err);
return [];
}
}
const Row: React.FC<{ label: string; value: React.ReactNode }> = ({ label, value }) => (
<div style={{ display: 'flex', gap: '12px', padding: '6px 0', borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
<div style={{ minWidth: '140px', color: 'var(--dim-color)', fontSize: '0.75rem', textTransform: 'uppercase' }}>{label}</div>
<div style={{ flex: 1, fontSize: '0.85rem', wordBreak: 'break-all' }}>{value ?? <span style={{ opacity: 0.4 }}></span>}</div>
</div>
);
const MailDrawer: React.FC<MailDrawerProps> = ({ decky, storedAs, fields, onClose }) => {
const panelRef = useRef<HTMLDivElement | null>(null);
useEscapeKey(onClose, true);
useFocusTrap(panelRef, true);
useEffect(() => {
const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => { document.body.style.overflow = prev; };
}, []);
const [downloading, setDownloading] = useState(false);
const [error, setError] = useState<string | null>(null);
const attachments = parseAttachments(fields);
const handleDownload = async () => {
setDownloading(true);
setError(null);
try {
const res = await api.get(
`/artifacts/${encodeURIComponent(decky)}/${encodeURIComponent(storedAs)}?service=smtp`,
{ responseType: 'blob' },
);
const blobUrl = URL.createObjectURL(res.data);
const a = document.createElement('a');
a.href = blobUrl;
a.download = storedAs;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(blobUrl);
} catch (err: any) {
const status = err?.response?.status;
setError(
status === 403 ? 'Admin role required to download mail.' :
status === 404 ? 'Message not found on disk (may have been purged).' :
status === 400 ? 'Server rejected the request (invalid parameters).' :
'Download failed — see console.'
);
console.error('mail download failed', err);
} finally {
setDownloading(false);
}
};
const recipients = Array.isArray(fields.rcpts)
? fields.rcpts.join(', ')
: (typeof fields.rcpts === 'string' ? fields.rcpts : null);
return (
<div
onClick={onClose}
style={{
position: 'fixed', inset: 0,
backgroundColor: 'rgba(0,0,0,0.6)',
display: 'flex', justifyContent: 'flex-end',
zIndex: 1000,
}}
>
<div
ref={panelRef}
role="dialog"
aria-modal="true"
onClick={(e) => e.stopPropagation()}
style={{
width: 'min(620px, 100%)', height: '100%',
backgroundColor: 'var(--bg-color, #0d1117)',
borderLeft: '1px solid var(--border-color, #30363d)',
padding: '24px', overflowY: 'auto',
color: 'var(--text-color)',
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
<div>
<div style={{ fontSize: '0.7rem', color: 'var(--dim-color)', letterSpacing: '0.1em' }}>
STORED MESSAGE · {decky}
</div>
<div style={{ fontSize: '1rem', fontWeight: 'bold', marginTop: '4px', wordBreak: 'break-all' }}>
{fields.subject || storedAs}
</div>
</div>
<button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--text-color)', cursor: 'pointer' }}>
<X size={20} />
</button>
</div>
<div style={{
display: 'flex', alignItems: 'center', gap: '8px',
padding: '8px 12px', marginBottom: '16px',
border: '1px solid rgba(255, 170, 0, 0.3)',
backgroundColor: 'rgba(255, 170, 0, 0.05)',
fontSize: '0.75rem', color: '#ffaa00',
}}>
<AlertTriangle size={14} />
Attacker-controlled content. Phishing kits / malware likely.
</div>
<button
onClick={handleDownload}
disabled={downloading}
style={{
display: 'flex', alignItems: 'center', gap: '8px',
padding: '8px 14px', marginBottom: '20px',
border: '1px solid var(--text-color)',
background: 'transparent', color: 'var(--text-color)',
cursor: downloading ? 'wait' : 'pointer',
opacity: downloading ? 0.5 : 1,
}}
>
<Download size={14} /> {downloading ? 'DOWNLOADING…' : 'DOWNLOAD .EML'}
</button>
{error && (
<div style={{ color: '#ff5555', fontSize: '0.8rem', marginBottom: '16px' }}>{error}</div>
)}
<section style={{ marginBottom: '24px' }}>
<h3 style={{ fontSize: '0.8rem', letterSpacing: '0.1em', color: 'var(--dim-color)', marginBottom: '8px' }}>
HEADERS
</h3>
<Row label="Subject" value={fields.subject} />
<Row label="From" value={fields.from_addr ?? fields.from} />
<Row label="To" value={recipients} />
<Row label="Date" value={fields.date} />
<Row label="Message-ID" value={fields.message_id} />
<Row label="Mail from" value={fields.mail_from} />
</section>
<section style={{ marginBottom: '24px' }}>
<h3 style={{ fontSize: '0.8rem', letterSpacing: '0.1em', color: 'var(--dim-color)', marginBottom: '8px' }}>
BODY
</h3>
<Row label="Size" value={fields.size ? `${fields.size} bytes` : null} />
<Row label="SHA-256" value={fields.sha256} />
<Row label="Truncated" value={fields.truncated ? 'yes (10 MB cap)' : 'no'} />
<Row label="Stored as" value={storedAs} />
</section>
{attachments.length > 0 && (
<section>
<h3 style={{ fontSize: '0.8rem', letterSpacing: '0.1em', color: 'var(--dim-color)', marginBottom: '8px' }}>
ATTACHMENTS ({attachments.length})
</h3>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
{attachments.map((att, idx) => (
<div
key={idx}
style={{
padding: '8px 12px',
border: '1px solid rgba(255,255,255,0.08)',
background: 'rgba(255,255,255,0.02)',
fontSize: '0.8rem',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
<Paperclip size={12} />
<span style={{ fontFamily: 'monospace', wordBreak: 'break-all' }}>
{att.filename || '(unnamed)'}
</span>
</div>
<div style={{ fontSize: '0.7rem', color: 'var(--dim-color)', fontFamily: 'monospace' }}>
{att.content_type ?? '?'} · {att.size != null ? `${att.size} B` : '? B'}
</div>
{att.sha256 && (
<div style={{ fontSize: '0.7rem', color: 'var(--dim-color)', fontFamily: 'monospace', wordBreak: 'break-all' }}>
{att.sha256}
</div>
)}
</div>
))}
</div>
</section>
)}
</div>
</div>
);
};
export default MailDrawer;

View File

@@ -393,6 +393,111 @@ class TestGetAttackerTranscripts:
assert exc_info.value.status_code == 404 assert exc_info.value.status_code == 404
# ─── GET /attackers/{uuid}/smtp-targets ──────────────────────────────────────
class TestGetAttackerSmtpTargets:
@pytest.mark.asyncio
async def test_returns_smtp_targets(self):
from decnet.web.router.attackers.api_get_attacker_smtp_targets import (
get_attacker_smtp_targets,
)
sample = _sample_attacker()
rows = [
{
"id": 1, "attacker_uuid": "att-uuid-1",
"domain": "corp1.com", "count": 5,
"first_seen": "2026-04-18T02:22:56+00:00",
"last_seen": "2026-04-19T10:15:03+00:00",
},
]
with patch("decnet.web.router.attackers.api_get_attacker_smtp_targets.repo") as mock_repo:
mock_repo.get_attacker_by_uuid = AsyncMock(return_value=sample)
mock_repo.list_smtp_targets = AsyncMock(return_value=rows)
result = await get_attacker_smtp_targets(
uuid="att-uuid-1",
user={"uuid": "test-user", "role": "viewer"},
)
assert result["total"] == 1
assert result["data"][0]["domain"] == "corp1.com"
mock_repo.list_smtp_targets.assert_awaited_once_with("att-uuid-1")
@pytest.mark.asyncio
async def test_404_on_unknown_uuid(self):
from decnet.web.router.attackers.api_get_attacker_smtp_targets import (
get_attacker_smtp_targets,
)
with patch("decnet.web.router.attackers.api_get_attacker_smtp_targets.repo") as mock_repo:
mock_repo.get_attacker_by_uuid = AsyncMock(return_value=None)
with pytest.raises(HTTPException) as exc_info:
await get_attacker_smtp_targets(
uuid="nonexistent",
user={"uuid": "test-user", "role": "viewer"},
)
assert exc_info.value.status_code == 404
# ─── GET /attackers/{uuid}/mail ──────────────────────────────────────────────
class TestGetAttackerMail:
@pytest.mark.asyncio
async def test_returns_stored_mail(self):
from decnet.web.router.attackers.api_get_attacker_mail import get_attacker_mail
sample = _sample_attacker()
rows = [
{
"id": 1,
"timestamp": "2026-04-18T02:22:56+00:00",
"decky": "decky-01", "service": "smtp",
"event_type": "message_stored",
"attacker_ip": "1.2.3.4",
"raw_line": "", "msg": "",
"fields": json.dumps({
"stored_as": "2026-04-18T02:22:56Z_abc123def456_ABC123.eml",
"sha256": "deadbeef" * 8,
"size": "1024",
"subject": "URGENT invoice",
"from_hdr": "spam@evil.com",
"rcpt_to": "<a@corp.com>",
"attachment_count": "1",
}),
},
]
with patch("decnet.web.router.attackers.api_get_attacker_mail.repo") as mock_repo:
mock_repo.get_attacker_by_uuid = AsyncMock(return_value=sample)
mock_repo.get_attacker_stored_mail = AsyncMock(return_value=rows)
result = await get_attacker_mail(
uuid="att-uuid-1",
admin={"uuid": "test-admin", "role": "admin"},
)
assert result["total"] == 1
assert result["data"][0]["event_type"] == "message_stored"
mock_repo.get_attacker_stored_mail.assert_awaited_once_with("att-uuid-1")
@pytest.mark.asyncio
async def test_404_on_unknown_uuid(self):
from decnet.web.router.attackers.api_get_attacker_mail import get_attacker_mail
with patch("decnet.web.router.attackers.api_get_attacker_mail.repo") as mock_repo:
mock_repo.get_attacker_by_uuid = AsyncMock(return_value=None)
with pytest.raises(HTTPException) as exc_info:
await get_attacker_mail(
uuid="nonexistent",
admin={"uuid": "test-admin", "role": "admin"},
)
assert exc_info.value.status_code == 404
# ─── Auth enforcement ──────────────────────────────────────────────────────── # ─── Auth enforcement ────────────────────────────────────────────────────────
class TestAttackersAuth: class TestAttackersAuth:

View File

@@ -33,6 +33,7 @@ class DummyRepo(BaseRepository):
async def get_session_profile(self, sid): await super().get_session_profile(sid) async def get_session_profile(self, sid): await super().get_session_profile(sid)
async def increment_smtp_target(self, u, d): await super().increment_smtp_target(u, d) async def increment_smtp_target(self, u, d): await super().increment_smtp_target(u, d)
async def list_smtp_targets(self, u): await super().list_smtp_targets(u) async def list_smtp_targets(self, u): await super().list_smtp_targets(u)
async def get_attacker_stored_mail(self, u): await super().get_attacker_stored_mail(u)
async def smtp_target_seen(self, d): await super().smtp_target_seen(d) async def smtp_target_seen(self, d): await super().smtp_target_seen(d)
async def get_attacker_by_uuid(self, u): await super().get_attacker_by_uuid(u) async def get_attacker_by_uuid(self, u): await super().get_attacker_by_uuid(u)
async def get_attackers(self, **kw): await super().get_attackers(**kw) async def get_attackers(self, **kw): await super().get_attackers(**kw)
@@ -77,6 +78,7 @@ async def test_base_repo_coverage():
await dr.get_session_profile("sid") await dr.get_session_profile("sid")
await dr.increment_smtp_target("uuid", "corp.com") await dr.increment_smtp_target("uuid", "corp.com")
await dr.list_smtp_targets("uuid") await dr.list_smtp_targets("uuid")
await dr.get_attacker_stored_mail("uuid")
await dr.smtp_target_seen("corp.com") await dr.smtp_target_seen("corp.com")
await dr.get_attacker_by_uuid("a") await dr.get_attacker_by_uuid("a")
await dr.get_attackers() await dr.get_attackers()