Security & Compliance Framework
Grio AI Education Platform
Last Updated: March 2026 Audience: Developers, DevOps Engineers, School Administrators, Ministry Officials Scope: INTERNAL security practices and EXTERNAL government compliance readiness
1. Security Architecture Overview
Grio implements a defense-in-depth approach across multiple security layers:
┌─────────────────────────────────────────────────────┐
│ Cloudflare (DDoS) │
├─────────────────────────────────────────────────────┤
│ Traefik Load Balancer (TLS) │
├─────────────────────────────────────────────────────┤
│ UFW Firewall (Network Isolation) │
├─────────────────────────────────────────────────────┤
│ K3s Cluster (Container Runtime) │
│ ┌─────────────┬──────────────┬──────────────┐ │
│ │ Django API │ Web Frontend│ AI Service │ │
│ │ (Auth) │ (HTTPS) │ (Sandboxed) │ │
│ └─────────────┴──────────────┴──────────────┘ │
├─────────────────────────────────────────────────────┤
│ PostgreSQL with RLS (Row-Level Security) │
│ Encrypted Backups to Secure Storage │
└─────────────────────────────────────────────────────┘Security Layers: - Network: Cloudflare DDoS protection, UFW firewall, VPN-only admin access - Application: HTTPS/TLS 1.2+, JWT authentication, input validation, rate limiting - Data: Encryption in transit and at rest, RLS for tenant isolation, audit logging - Access: RBAC with 5 roles, session management, password policies, MFA-ready
2. Authentication & Access Control
Authentication Mechanism
All user authentication uses JWT (JSON Web Tokens) with OAuth 2.0 support:
- Tokens issued by Django backend at login/signup
- Access tokens (15-minute TTL) + refresh tokens (30-day TTL)
- Secure, HTTP-only cookie storage (browser-based clients)
- Mobile clients use token-in-header with TLS pinning
- Multi-factor authentication (MFA) roadmap for Phase 2
Role-Based Access Control (RBAC)
┌──────────────────────────────────────────────────┐
│ SUPER_ADMIN │
│ - Platform configuration & monitoring │
│ - User role assignment │
│ - All school data visibility (audit only) │
│ - Government data export │
└──────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────┐
│ SCHOOL_ADMIN (Tenant Scoped) │
│ - School-level user management │
│ - Enrollment & student records │
│ - Teacher & class management │
│ - School analytics & usage reports │
│ - Cannot access other schools' data │
└──────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────┐
│ TEACHER (School Scoped) │
│ - Class management & assignments │
│ - Student progress tracking │
│ - Content creation & curriculum alignment │
│ - AI tutor configuration & monitoring │
│ - Cannot edit other teachers' classes │
└──────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────┐
│ STUDENT (Individual Scoped) │
│ - Access assigned classes only │
│ - Submit assignments & view feedback │
│ - Learning analytics (own progress) │
│ - Cannot view other students' data │
└──────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────┐
│ INDEPENDENT_LEARNER (Subscription) │
│ - Access curated content by topic │
│ - Progress tracking within subscription │
│ - Limited AI tutor interactions (quota-based) │
│ - Cannot access school resources │
└──────────────────────────────────────────────────┘Session Management
- Session timeout: 30 minutes of inactivity (configurable by role)
- Simultaneous session limit: 1 per user (mobile + web, configurable)
- Token revocation on logout, password change, admin suspension
- All session events logged to audit trail
3. Multi-Tenancy & Data Isolation
Row-Level Security (RLS) in PostgreSQL
Every query is filtered by tenant context:
-- Example: Teachers can only see their school's students
POLICY teacher_see_own_school_students ON students
USING (school_id = current_setting('app.school_id')::uuid)
-- Example: Students can only see themselves
POLICY student_see_self ON student_progress
USING (student_id = current_setting('app.user_id')::uuid)Tenant Types & Boundaries
School Tenants: - Separate namespace per school (school_id) - School admins cannot access other schools (enforced at DB and application layer) - Student data belongs exclusively to enrolling school - Teachers see only their assigned classes within their school
Independent Learners: - Individual tenant per subscription (user_id) - No school associations or data sharing - Complete data isolation from all school tenants
Admin Access Scoping
- Super Admin can query school data only for audit purposes
- Explicit audit logging when Super Admin accesses any sensitive school data
- No bulk export of all student PII without government authorization
- Data access requests from Ministry logged and traceable
4. Data Protection
Encryption in Transit
- HTTPS Everywhere: TLS 1.2+ enforced on all endpoints
- Certificate provider: Let’s Encrypt (automated renewal via cert-manager)
- Load balancer (Traefik) terminates all TLS connections
- API endpoints reject plaintext HTTP with 301 redirect to HTTPS
- Secure headers enabled: HSTS, X-Frame-Options, X-Content-Type-Options
Encryption at Rest
- PostgreSQL database: disk-level encryption (LUKS on Hetzner)
- Backup storage: encrypted archives with separate encryption key
- File storage (if used): S3-compatible with server-side encryption
- Secrets never stored in code or git history (environment variables only)
Sensitive Data Handling
Student PII Protected: - Student names, email, phone numbers, parent contact info - Academic records (grades, test scores, attendance) - AI interaction transcripts logged separately with access restrictions
Minimal Data Collection: - Only collect data necessary for learning & school operations - No tracking for advertising or third-party resale - Student data not used to train AI models without explicit consent
Data Retention Policies
- Active student records: retained while enrolled + 2 years after graduation
- Inactive accounts: flagged after 12 months, deleted after 24 months
- Audit logs: retained for 7 years (compliance requirement)
- Backup copies: maintained per retention schedule
Right to Erasure
Students and parents can request complete data deletion: 1. Request submitted via secure form or school admin 2. Verification of identity and authorization 3. Data anonymized/deleted within 30 days 4. Audit log entry created (for compliance verification) 5. Confirmation email sent to requester
5. Network Security
Firewall Configuration
UFW (Uncomplicated Firewall) Rules:
- Port 80 (HTTP): ALLOW → redirects to 443
- Port 443 (HTTPS): ALLOW → Traefik load balancer
- Port 22 (SSH): ALLOW from VPN only (restrict to specific IPs)
- Port 5432 (DB): DENY from internet, ALLOW from K3s cluster only
- All other ports: DENY (default-deny policy)VPN for Administrative Access
- All ops/admin access through WireGuard VPN
- Database access only from VPN-authenticated clients
- SSH access only from VPN IPs
- Admin dashboard requires VPN + 2FA (Phase 2)
Load Balancer Architecture
- Traefik as single entry point (reverse proxy)
- Terminates all TLS connections
- Routes traffic to backend services in K3s
- No direct database exposure to internet
- Automatic HTTPS redirect
DDoS Mitigation
- Cloudflare free tier: rate limiting, bot protection, IP reputation filtering
- Platform-level rate limiting: 100 requests/minute per IP (API endpoints)
- Geographic blocking: restrict access to expected countries if needed
6. Application Security
Input Validation & Sanitization
- All user inputs validated server-side (never trust client-side)
- Whitelist validation for structured fields (email, phone, numeric IDs)
- HTML escaping for text content (prevents stored XSS)
- File upload validation: type + magic byte verification
SQL Injection Prevention
- Django ORM for all database queries (parameterized queries)
- Raw SQL only when necessary, with explicit parameterization
- Regular dependency scanning for vulnerable libraries
- Quarterly security audits of custom SQL
XSS & CSRF Protection
- Django CSRF middleware enabled (token validation on state-changing requests)
- Content Security Policy (CSP) header set on all responses
- Template auto-escaping in Django enabled by default
- No inline JavaScript in templates
Rate Limiting
- API endpoints: 100 requests/minute per authenticated user
- Login attempts: 5 failures per 15 minutes (temporary lockout)
- Email sending: 10 emails/hour per account
- AI service requests: quota-based per role (configurable)
Secure Headers
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' (reviewed)7. AI-Specific Security
Prompt Injection Prevention
- AI service runs in isolated container with minimal permissions
- Curriculum boundaries enforced at service level (topic-locking)
- User prompts sanitized before sending to AI model
- No access to system prompts or model internals from user code
- All AI interactions logged with exact prompt/response text
Output Filtering & Age-Appropriateness
- AI responses filtered for:
- Age-inappropriate content (curriculum-specific)
- Out-of-curriculum responses (return “Ask your teacher” if off-topic)
- Potentially harmful content (self-harm, hate speech)
- Student PII reflection (prevent model echoing back personal data)
PII Protection in AI Responses
- AI service cannot access student database directly
- Teacher-provided context (student names, grades) never sent to AI
- If PII mentioned in conversation, AI instructed to use placeholders (e.g., “Your name” instead of “John”)
- Output scanning removes any detected PII before returning to frontend
Topic-Locking as Security Boundary
- Each subject/topic has defined curriculum scope
- AI tutor constrained to provide help only within topic scope
- Off-topic questions logged and escalated to teacher/admin if suspicious
- Prevents AI from being used for unintended purposes
Audit Trail for AI Interactions
- Every AI request logged: user_id, class_id, topic, timestamp, input, output
- Response time & token usage tracked (performance & abuse detection)
- Logs retained per data retention policy (7 years for compliance)
- Searchable by Ministry for oversight/investigation
8. Infrastructure Security
Container Image Scanning
- All base images scanned for vulnerabilities (Trivy scanner)
- Production images built from minimal, hardened base (Alpine Linux)
- Regular image rebuilds to patch OS/library vulnerabilities
- Private registry used (no public image pulls during runtime)
K3s Cluster Hardening
- RBAC enabled: service accounts with minimal permissions
- Network policies defined: pod-to-pod communication restricted by label
- Pod security policies (PSPs) enforced for privileged operations
- API server authorization via webhook (deny by default)
- Etcd encryption enabled for secrets at rest
Secret Management
- All secrets passed via environment variables (not in git)
- Secret rotation: database passwords rotated quarterly
- External secret store ready (HashiCorp Vault integration in Phase 2)
- No secrets in Docker images, config files, or logs
Minimal Attack Surface
- Only necessary services running in cluster
- No SSH access to nodes (kubectl port-forward for debugging)
- Container processes run as non-root user
- No privileged containers in production
9. Government Compliance Readiness
Data Sovereignty
- All data stored in-country (planned: migration from Hetzner to local servers)
- No international data transfers without explicit authorization
- Comply with Uganda Data Protection Act (if applicable)
- Data backups maintained within country jurisdiction
Comprehensive Audit Logs
Logs capture: - Who: user_id, role, authentication method - What: action taken, resource accessed, data modified - When: precise timestamp, timezone included - Where: IP address, user agent, session_id - Why: audit reason (for Ministry-initiated access)
Example log entry:
{
"timestamp": "2026-03-24T14:32:00Z",
"user_id": "admin-001",
"role": "SUPER_ADMIN",
"action": "export_student_data",
"school_id": "school-123",
"record_count": 500,
"authorization": "ministry-request-2026-03-24",
"ip_address": "192.168.1.100",
"status": "success"
}Ministry Data Export
- Secure API endpoint for Ministry to request student/school data
- Request verification: authorized Ministry official only
- Data provided in standardized format (CSV/JSON)
- Export logged and tracked in audit trail
- Ability to filter by: school, subject, date range, student cohort
Audit Trail for Sensitive Operations
All these events trigger audit logs: - User creation, role assignment, suspension - Student data access by admin/teacher - School configuration changes - AI service access & output review - Failed login/authentication attempts - Data export/deletion requests
Compliance Verification
- Regular internal audits: monthly for security, quarterly for compliance
- Documented procedures for data breach investigation
- Incident response plan: detection → containment → notification (within 72 hours)
- Annual compliance statement prepared for government
10. Monitoring & Incident Response
Security Event Logging
All security events logged to centralized log store: - Authentication attempts (success/failure) - Authorization failures (permission denied) - Suspicious patterns (rate limit breaches, multiple failed logins) - Administrative actions (role changes, data access) - AI service anomalies (excessive requests, filter triggers)
Anomaly Detection (Phase 2)
- Failed login spike: alert if 10+ failed attempts per account in 1 hour
- Unusual data access: alert if teacher accesses 100+ unrelated student records
- AI output filter triggers: escalate to review if 5+ filters triggered per session
- Geographic anomaly: alert if login from unexpected country
Incident Response Procedure
- Detection: Alert triggered by monitoring or staff report
- Investigation: Examine logs, isolate affected systems, assess scope
- Containment: Revoke compromised credentials, reset affected accounts
- Remediation: Apply patches, update firewall rules, change secrets
- Notification: Inform affected users, parents, school admin (within 72 hours)
- Documentation: Post-incident review, update procedures
Breach Notification Process
Upon confirmed data breach: - Immediate notification to Ministry (if required by law) - Notification to affected school admins within 24 hours - Parents/students notified within 72 hours with details: - Type of data exposed - Steps taken to secure systems - Protective measures users should take - Contact information for questions
11. Compliance Checklist
| Requirement | Status | Implementation | Notes |
|---|---|---|---|
| Data Protection | |||
| Encryption in transit (TLS 1.2+) | ✅ Implemented | HTTPS, Let’s Encrypt | All endpoints secured |
| Encryption at rest | ✅ Implemented | LUKS disk encryption | Hetzner native |
| Data minimization | ✅ Implemented | Collected only required fields | PII restricted |
| Data retention policies | ✅ Implemented | 2yr active + 7yr audit logs | Automated purge scheduled |
| Right to erasure | ✅ Implemented | Secure deletion API | 30-day SLA |
| Access Control | |||
| RBAC with 5+ roles | ✅ Implemented | JWT + Django permissions | Scoped to tenant |
| Session management | ✅ Implemented | 30-min timeout, token refresh | Logout revocation |
| MFA for admin | 📋 Planned | Phase 2 Q2 2026 | TOTP-based |
| Audit logging | ✅ Implemented | Comprehensive event log | 7-year retention |
| Admin access scoping | ✅ Implemented | Explicit audit trail | Super Admin restricted |
| Network Security | |||
| Firewall (UFW) | ✅ Implemented | Default-deny, port whitelist | Reviewed quarterly |
| VPN for admin | ✅ Implemented | WireGuard VPN required | SSH/DB access restricted |
| Load balancer (Traefik) | ✅ Implemented | TLS termination, routing | Single entry point |
| DDoS protection | ✅ Implemented | Cloudflare free tier | Rate limiting configured |
| Application Security | |||
| Input validation | ✅ Implemented | Server-side whitelist validation | All endpoints protected |
| SQL injection prevention | ✅ Implemented | Django ORM parameterization | Code review audits |
| XSS protection | ✅ Implemented | CSP headers, template escaping | No inline scripts |
| CSRF protection | ✅ Implemented | Django CSRF middleware | Token validation |
| Rate limiting | ✅ Implemented | 100 req/min per IP | Configurable per endpoint |
| AI Security | |||
| Prompt injection prevention | ✅ Implemented | Input sanitization, isolation | Containerized AI service |
| Output filtering | ✅ Implemented | Age-appropriate filter | Curriculum-bounded |
| PII protection in outputs | ✅ Implemented | Response scanning | Placeholder substitution |
| Topic-locking | ✅ Implemented | Curriculum scope enforcement | Off-topic logging |
| AI audit trail | ✅ Implemented | Complete interaction logging | 7-year retention |
| Infrastructure | |||
| Container scanning | ✅ Implemented | Trivy vulnerability scanning | Every build |
| K3s hardening | ✅ Implemented | RBAC, network policies, PSPs | Quarterly review |
| Secret management | ✅ Implemented | Environment variables only | Rotation quarterly |
| Data sovereignty | ✅ Designed | In-country storage planned | Migration Phase 2 |
| Compliance | |||
| Comprehensive audit logs | ✅ Implemented | Who/what/when/where/why | Ministry-exportable |
| Ministry data export | ✅ Planned | Secure API endpoint | Phase 2 Q1 2026 |
| Incident response plan | ✅ Documented | 72-hour notification SLA | Legal review pending |
| Annual compliance statement | 📋 Planned | Phase 1 completion | Quarterly thereafter |
12. Security Roadmap
Phase 1: Foundation (NOW - Q2 2026)
- ✅ Basic authentication (JWT, OAuth-ready)
- ✅ HTTPS everywhere (TLS 1.2+, Let’s Encrypt)
- ✅ Firewall & network isolation (UFW, VPN admin access)
- ✅ RBAC (5 roles, tenant-scoped)
- ✅ Encryption at rest (database, backups)
- ✅ Row-Level Security (PostgreSQL RLS)
- ✅ AI topic-locking & output filtering
- ✅ Audit logging framework
- Acceptance Criteria: Zero high-severity vulnerabilities, all data encrypted, 100% TLS coverage
Phase 2: Enhanced Hardening (Q2-Q4 2026)
- 📋 Multi-factor authentication (TOTP, hardware key support)
- 📋 Automated security scanning (CI/CD pipeline)
- 📋 Enhanced monitoring & anomaly detection
- 📋 Ministry data export API (secure, audited)
- 📋 In-country data migration (Hetzner → local servers)
- 📋 External secret management (HashiCorp Vault)
- 📋 Security incident response runbook (internal team training)
- Acceptance Criteria: MFA enforced for admin, 100% secrets rotated, Ministry export operational
Phase 3: Government Certification (Q1-Q2 2027)
- 🔄 SOC2 Type II audit preparation
- 🔄 Government certification readiness assessment
- 🔄 Penetration testing by accredited firm
- 🔄 Advanced threat detection (SIEM integration)
- 🔄 Incident response plan: Ministry-approved
- 🔄 Annual compliance statement published
- Acceptance Criteria: Government sign-off on compliance, SOC2 Type II ready, zero open compliance gaps
Key Contacts & Escalation
- Security Lead: [DevOps/Security Team]
- Compliance Officer: [To be assigned]
- Ministry Liaison: [To be assigned]
- Incident Hotline: [TBD - 24/7 contact]
- Email: security@grio-ai.example.com
Document Control
| Version | Date | Author | Change |
|---|---|---|---|
| 1.0 | Mar 24, 2026 | DevOps Team | Initial comprehensive framework |
This document is intended for internal use and government compliance readiness. It should be reviewed and updated quarterly.