# Helpdesk Module — Security Review

## Overview

This document captures the security posture of the Helpdesk module as of the Phase 9 completion. It serves as both a review artefact and a checklist for future audits.

---

## 1. Authentication & Authorization

### 1.1 Authentication
- All API endpoints require authentication via Django session or token auth.
- Unauthenticated requests return HTTP 401.
- The `X-Tenant` header is required on every request; missing header returns 400.

### 1.2 Authorization (IAM)
- 38 granular permissions registered in the platform IAM registry (33 core + 5 AI).
- Three default role templates: Agent, Supervisor, Portal User.
- Views enforce permissions via `HasPermission` / custom permission checks.
- Permission codenames follow `<module>.<action>_<model>` convention.

### 1.3 Tenant Isolation
- All models extend `TenantScopedModel` (tenant + org_node FKs).
- Service layer enforces tenant scoping on all write operations.
- Cross-tenant access attempts return 403 or 404 (information hiding).
- Selectors/querysets are filtered by request tenant context.

### 1.4 Object-Level Permissions
- Portal users can only view their own tickets (enforced at service/selector layer).
- Internal notes are hidden from non-agent users (filtered in views).
- Cross-team note visibility is controlled by `helpdesk.cross_team_notes` setting.

---

## 2. Data Protection

### 2.1 Input Validation
- All API input is validated through DRF serializers.
- Ticket subject length capped at 512 characters.
- JSON fields (`custom_fields`, `conditions`, `actions`) validated for structure.
- File uploads gated by `helpdesk.max_attachment_bytes` setting.

### 2.2 SQL Injection
- All queries use Django ORM parameterized queries.
- No raw SQL in the helpdesk module.
- Category/tag name lookups use Django's built-in escaping.

### 2.3 XSS Prevention
- Ticket descriptions and reply bodies are stored as plain text.
- `html_body` field on TicketReply is explicitly marked as sanitized.
- Frontend renders content via React (auto-escaping) with `dangerouslySetInnerHTML` used sparingly.

### 2.4 CSRF
- DRF's `SessionAuthentication` enforces CSRF checks for browser-based sessions.
- API clients using token auth are not CSRF-vulnerable.

### 2.5 Soft Delete
- Ticket, TicketReply, Queue, Category, Tag, Automation, AgentTeam, AgentTeamMember, and SLATimer all use `SoftDeleteModel`.
- Hard deletion requires Django admin access.
- Soft-deleted rows excluded from default manager querysets.

---

## 3. Infrastructure

### 3.1 Secrets Management
- No secrets or API keys stored in helpdesk models.
- Email/SMS provider config stored in platform settings (not in module code).
- Connector configs (`ConnectorConfig`) store integration credentials via encrypted settings backend.

### 3.2 Rate Limiting
- No built-in rate limiting — delegates to platform-level middleware.
- Recommended: add `django-ratelimit` or API gateway rate limiting on ticket creation endpoint.

### 3.3 Logging
- Structured logging via `structlog` on all service methods.
- No PII logged in production (ticket subjects/logged only in debug).
- AI action logs capture before/after snapshots for auditability.

---

## 4. AI-Specific Security

### 4.1 AI Permissions
- Five dedicated AI permissions isolate AI operations from standard helpdesk permissions.
- AI action execution requires explicit `helpdesk.aiaction.execute` perm.

### 4.2 AI Audit Trail
- `AIActionLog` is append-only — rows are never updated or deleted.
- Every AI action logs: ticket, suggestion, action type, before/after payloads, executor, provider, metadata.
- Audit logs are tenant-scoped and permission-gated via `helpdesk.aiaudit.view`.

### 4.3 AI Suggestion Approval
- AI suggestions are created in PENDING status.
- Human approval is required (via `AISuggestionService.decide_suggestion`) before application.
- Rejected suggestions are preserved for audit (soft-deleted).

---

## 5. Recommendations

| Area | Recommendation | Priority |
|------|---------------|----------|
| Rate limiting | Add rate limit on `/tickets/` POST (creation) | Medium |
| Attachment scanning | Integrate antivirus/malware scan on uploaded attachments | Medium |
| Content filtering | Add profanity/spam filter on ticket descriptions | Low |
| API key rotation | For ConnectorConfig credentials, implement key rotation support | Low |
| CSAT token expiry | CSAT survey links should expire after configurable time | Low |
| BCC archiving | Outbound email replies should be BCC'd to archive address | Low |

---

## Review History

| Date | Reviewer | Notes |
|------|----------|-------|
| 2026-06-11 | Automated review (Phase 9) | Initial comprehensive review completed. All Phase 1–8 issues addressed. AI permissions and audit trail added. |

