# MHI Gateway Security Proposal

## 1. Security Objectives

MHI Gateway must protect tenant data, provider secrets, wallet balances, delivery history and customer communications. The platform should be designed for multi-tenant isolation, least-privilege access, secure processing of sensitive data and strong operational resilience.

## 2. Core Security Principles

- Never log passwords, API keys, SMPP credentials, private signing keys or wallet secrets.
- Treat all tenant data as sensitive and require strict isolation.
- Enforce authorization at the service layer, not only in controllers.
- Encrypt secrets at rest and use secure transport for all integrations.
- Validate all inbound provider callbacks before processing them.
- Preserve integrity through immutable audit logs and tamper-evident records.

## 3. Authentication and Access Control

### 3.1 Public API authentication

The Public API must use authenticated credentials bound to a specific application and tenant.

Recommended controls:
- Bearer tokens for user-facing integrations
- Signed API keys for server-to-server integrations
- Mutual TLS where required for high-trust partners
- Per-credential scopes for sending, wallet queries, webhook management and reporting
- Short-lived access tokens with refresh rotation where applicable

### 3.2 Internal Admin UI authentication

The Internal Admin UI should use a separate authentication path from the Public API.

Recommended controls:
- Session-based authentication with secure cookie settings
- MFA for privileged roles such as Platform Admin, Tenant Admin and Finance
- Role-based access control enforced server-side
- Administrative actions should be isolated from public API traffic and use stronger session controls

## 4. Hashing vs Encryption

These are different controls and must be used for different purposes.

### Hashing
Use hashing for non-reversible verification.
- Passwords and password reset tokens
- One-way verification of webhook signatures or integrity fingerprints
- Deterministic token or reference comparison where reversibility is not required

### Encryption
Use encryption for reversible protection of sensitive data.
- Provider credentials and SMPP secrets
- Phone numbers and other PII
- Message content and attachments where retention requires confidentiality
- Database fields that store secrets or regulated customer data

### Cryptographic guidance
- Use strong modern algorithms such as AES-256-GCM for symmetric encryption
- Use Argon2id, bcrypt or scrypt for password hashing
- Never use plaintext storage for secrets, even temporarily
- Store decryption keys separately from the data and rotate them on a schedule

## 5. Development vs Production Secret Management

### Development environment
- .env files are acceptable for local development only
- Local secrets must never be committed to source control
- .env files should be excluded from version control and scanned for leakage
- Development credentials must be isolated from production systems

### Production environment
- Secrets must be managed by a dedicated secrets manager such as Vault, AWS Secrets Manager, Azure Key Vault or a similar platform
- Application configuration should load secrets at runtime from the secret manager
- Production secrets should be rotated regularly and support emergency rotation
- Access to production secrets must be limited to approved service identities

## 6. PII Protection

PII must be protected at collection, storage, processing and deletion.

### Required controls
- Encrypt phone numbers at rest and in transit
- Mask phone numbers in logs, admin screens and support workflows unless an explicit need exists
- Hash sensitive identifiers such as phone numbers for lookup or deduplication where reversibility is not required
- Apply retention rules to message content and attachments so data is deleted when no longer needed
- Restrict access to message bodies and PII to roles that require it

### Message retention
- Message bodies should be retained only for the minimum period required by policy or legal requirements
- Short-lived message content should be stored in encrypted form and purged automatically
- Retention schedules must be auditable and configurable per tenant where required

## 7. Immutable Audit Logs

Security-relevant events must be captured in immutable audit logs.

Requirements:
- Append-only storage with no in-place updates or deletes for audit records
- Timestamped events including actor, tenant, action, target, source IP and outcome
- Tamper-evident hashing or log chaining for integrity verification
- Separate storage from operational logs where possible
- Retention aligned with regulatory and internal policy requirements

Examples of audit events:
- authentication success or failure
- role changes
- wallet reservation, capture and reversal
- provider connection changes
- webhook verification failures
- secret rotation and access to secrets

## 8. API Security and Abuse Protection

The Public API and Internal Admin API must resist abuse and misuse.

### Rate limiting and abuse detection
- Enforce per-credential and per-tenant rate limits for read and write operations
- Apply burst protection and distributed throttling for public traffic
- Detect abnormal patterns such as repeated failures, suspicious IP ranges and high-volume retries
- Return structured rate-limit responses with retry guidance

### Replay-attack protection
- Require request timestamps for signed requests
- Use nonce values for replay-resistant signatures where supported
- Use idempotency keys for state-changing operations such as message submission and webhook registration
- Reject stale requests outside an approved validity window

### Request correlation and tracing
- Generate request IDs and correlation IDs for every incoming request
- Propagate them through logs, queue messages and downstream provider calls
- Use them to troubleshoot incidents and investigate abuse events

## 9. Queue Security

Queue workers and queued jobs must be protected as part of the trust boundary.

Required controls:
- Encrypt sensitive job payloads before enqueueing where needed
- Do not place secrets directly in queue payloads
- Use scoped credentials for workers and service identities
- Restrict queue access to authorized services only
- Serialize request and tenant context with each job
- Reject and quarantine malformed or suspicious jobs

## 10. SMPP Security

SMPP integrations require transport and session protections.

Required controls:
- Use persistent binds with heartbeat management
- Enable enquire_link health checks to detect dead sessions
- Implement reconnection logic with backoff and retry limits
- Redact credentials in logs, metrics and exception traces
- Validate bind credentials before activation
- Isolate provider-specific SMPP sessions from general application traffic

## 11. Role-Based Access Control

The platform should support the following roles:

- Platform Admin: full platform control, including tenant administration and critical configuration
- Tenant Admin: controls a single tenant’s applications, credentials and users
- Finance: accesses billing, wallet, reconciliation and financial audit data
- Messaging: manages message templates, channel routing and operational delivery workflows
- Support: reviews message state, customer issues and debugging data within scope
- Auditor: read-only access to security, compliance and immutable audit events
- Read Only: read-only access to non-sensitive operational data

### RBAC principles
- Default deny for all access paths
- Least-privilege role assignment
- Separation of duties between billing, provider management and message operations
- Privileged actions must require additional verification or approval where appropriate

## 12. Secure Billing Transactions

Billing and financial state changes must be atomic and auditable.

Required controls:
- Use immutable ledger entries for wallet movements
- Reserve funds before dispatch, capture funds on delivery or finalization and release funds on cancellation or failure
- Prevent double debit or double credit through transactional workflows and idempotent billing operations
- Keep billing state separate from message status state
- Record every financial transition in immutable audit logs
- Require authorization at the service layer for all wallet and balance mutations

## 13. Database and Storage Protection

### Encrypted database columns
Encrypt or tokenize sensitive columns such as:
- phone_number
- message_body where applicable
- provider_secret
- signing_secret
- smtp_password
- smpp_password
- webhook_secret
- payment_reference or tokenized billing identifiers

### Storage recommendations
- Use database-level encryption or application-level field encryption where appropriate
- Keep encryption keys separate from data stores
- Apply column-level encryption only where sensitive data is stored directly

## 14. Backup, Recovery and Encryption

Backups must be protected as carefully as production data.

Required controls:
- Encrypt backups at rest and in transit
- Store encryption keys separately from the backup repository
- Separate backup copies across at least two locations where possible
- Test restore procedures regularly
- Restrict backup access to authorized operators and service identities

## 15. Monitoring, Metrics and Alerts

Security monitoring should be continuous and actionable.

### Metrics
- authentication attempts and failures
- rate-limit events
- wallet reserve and capture failures
- webhook verification failures
- provider connection errors and reconnect counts
- queue backlog and dead-letter rates
- suspicious burst traffic or repeated retries
- encryption and secret-rotation health

### Alerts
- repeated authentication failures
- sudden spikes in message volume or spend
- failed billing transactions
- provider connection instability
- elevated queue age or dead-letter growth
- missing or failed backups
- unusual access from new IP ranges or geographies

## 16. HTTP Security Headers

All public and admin responses should include appropriate security headers.

Recommended headers:
- Strict-Transport-Security
- X-Content-Type-Options
- X-Frame-Options or Content-Security-Policy
- Referrer-Policy
- Permissions-Policy
- Cache-Control: no-store for sensitive responses

## 17. Production Hardening Checklist

Before production deployment, verify:

- tenant boundaries are enforced in all services
- wallet debit operations cannot exceed the available balance
- provider credentials are encrypted and inaccessible to unauthorized users
- webhook verification rejects unsigned traffic
- audit logs capture significant state changes
- secrets are managed outside source control and rotated on schedule
- queue workers use scoped credentials and do not expose secrets in payloads
- SMPP sessions reconnect safely and redact credentials in logs
- HTTP security headers are present on all relevant responses
- backups are encrypted and tested for restore
- monitoring and alerting cover high-risk security events

## 18. Standards Alignment

The platform should align with the following security frameworks and guidance:

- OWASP Top 10 for web application security
- OWASP API Security Top 10
- OWASP ASVS for secure application design and verification
- Relevant PCI, GDPR and regional privacy requirements where applicable

## 19. Disaster Recovery Goals

The platform should define recovery objectives for continuity and business resilience.

Recommended targets:
- RPO: 15 minutes for critical transactional data where feasible
- RTO: 1 hour for core messaging and billing services during a major incident
- RTO for full platform recovery: 4 hours or less depending on hosting and backup topology

## 20. Security Events Model

Critical security incidents should be captured in a dedicated security_events model.

Suggested fields:
- id
- tenant_id
- severity
- event_type
- title
- description
- source_ip
- actor_id
- detected_at
- status
- remediation_status
- correlation_id
- related_resource_type
- related_resource_id

Security events should be immutable, reviewable and linked to audit evidence where possible.
