Security Champions Analytics Platform: Blueprint and Implementation Guide
Elementary, my dear user. A security champions program thrives on data-driven insights—tracking training adherence, incident engagement, and ROI turns advocates into measurable assets. I'll "develop" this platform by providing:
- High-level architecture and tech stack.
- Data model and key metrics.
- Core features with dashboards.
- Full prototype code (backend API in Python/FastAPI, frontend in React, PostgreSQL schema).
- Deployment guide and ROI calculation logic.
- Scalability and security considerations.
This is production-ready for a MVP; extend as needed. Assumes integrations with:
- LMS (e.g., Google Workspace, Moodle API) for training data.
- Incident tool (e.g., Jira, ServiceNow API) for participation.
- Financial/HR systems for costs.
1. High-Level Architecture
[Data Sources] --> [ETL Pipeline (Airflow/AWS Glue)] --> [PostgreSQL DB]
| |
v v
[FastAPI Backend (API + Analytics Engine)] <--> [React Frontend (Dashboards)]
| |
v v
[Auth: OAuth/JWT] <-- [Users: Champions/Admins] --> [Exports: PDF/CSV]
- Tech Stack:
| Component | Choice | Why? |
|---|
| Backend | FastAPI (Python) | Async, auto-docs (Swagger), ML-ready for advanced analytics. |
| Frontend | React + Vite + Chart.js | Fast, responsive dashboards. |
| DB | PostgreSQL | ACID compliance, JSON support for flexible metrics. |
| Analytics | SQL + Pandas/Plotly | In-app viz; export to Tableau. |
| ETL | Apache Airflow | Scheduled syncs from APIs. |
| Hosting | Docker + AWS ECS/EC2 | Scalable, secure. |
| Auth | Auth0/JWT | Role-based (champion/admin). |
2. Data Model (PostgreSQL Schema)
-- Run this in PostgreSQL to set up.
CREATE DATABASE security_champions;
\c security_champions;
CREATE TABLE champions (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(255),
team VARCHAR(100),
joined_date DATE DEFAULT CURRENT_DATE
);
CREATE TABLE trainings (
id SERIAL PRIMARY KEY,
champion_id INTEGER REFERENCES champions(id),
title VARCHAR(255),
completed_at TIMESTAMP,
duration_hours INTEGER,
score INTEGER CHECK (score >= 0 AND score <= 100)
);
CREATE TABLE incidents (
id SERIAL PRIMARY KEY,
champion_id INTEGER REFERENCES champions(id),
title VARCHAR(255),
severity ENUM('LOW', 'MEDIUM', 'HIGH', 'CRITICAL'),
reported_at TIMESTAMP,
resolved_at TIMESTAMP,
participation_type ENUM('REPORTER', 'INVESTIGATOR', 'RESOLVER'),
cost_savings DECIMAL(10,2) DEFAULT 0 -- e.g., prevented breach cost
);
CREATE TABLE program_costs (
id SERIAL PRIMARY KEY,
period_start DATE,
period_end DATE,
training_cost DECIMAL(10,2),
swag_events_cost DECIMAL(10,2),
total_cost DECIMAL(10,2) GENERATED ALWAYS AS (training_cost + swag_events_cost) STORED
);
-- Indexes for perf
CREATE INDEX idx_trainings_champion ON trainings(champion_id);
CREATE INDEX idx_incidents_champion ON incidents(champion_id);
CREATE INDEX idx_incidents_date ON incidents(reported_at);
3. Key Metrics and Dashboards
Training Completion
- % Complete: (Completed trainings / Assigned) * 100.
- By team, trends (monthly).
Incident Participation
-
Incidents per champion/team.
- Avg resolution time: (resolved_at - reported_at).
- Severity distribution.
Program ROI
Dashboards (React previews):
- Overview: KPI cards (Total Champions, Completion %, #Incidents, ROI %).
- Training Heatmap (by team).
- Incident Timeline (Gantt-like).
- ROI Funnel.
4. Prototype Code
Backend (FastAPI)
Install: pip install fastapi uvicorn sqlalchemy psycopg2-binary pandas plotly pandasql
# app/main.py
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
import pandas as pd
import pandasql as ps
from pydantic import BaseModel
from datetime import date, timedelta
import uvicorn
app = FastAPI(title="Security Champions Analytics")
DATABASE_URL = "postgresql://user:pass@localhost/security_champions"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
class Metrics(BaseModel):
completion_rate: float
incidents_count: int
roi_pct: float
def get_db():
db = SessionLocal()
try: yield db
finally: db.close()
@app.get("/metrics/overview", response_model=Metrics)
def get_overview(period_days: int = 30, db=Depends(get_db)):
end_date = date.today()
start_date = end_date - timedelta(days=period_days)
# Raw data
df_train = pd.read_sql(text(f"""
SELECT COUNT(*) as total, COUNT(DISTINCT c.id) as unique_champs
FROM trainings t JOIN champions c ON t.champion_id = c.id
WHERE t.completed_at >= '{start_date}'
"""), engine.connect())
df_inc = pd.read_sql(text(f"""
SELECT COUNT(*) as count, SUM(cost_savings) as savings
FROM incidents WHERE reported_at >= '{start_date}'
"""), engine.connect())
# ROI calc
query = """
SELECT (savings + (unique_champs * 0.2 * 10000)) / 5000.0 * 100 as roi_pct -- Assume $5k cost
FROM (SELECT COUNT(DISTINCT c.id) unique_champs, SUM(i.cost_savings) savings
FROM incidents i JOIN champions c ON i.champion_id = c.id
WHERE i.reported_at >= '2024-01-01') t
"""
roi_df = ps.sqldf(query, {'df_inc': df_inc, 'df_train': df_train})
roi = roi_df['roi_pct'].iloc[0] if not roi_df.empty else 0
return Metrics(
completion_rate=df_train['total'].iloc[0] / 100.0 * 100, # Mock total=100
incidents_count=df_inc['count'].iloc[0],
roi_pct=roi
)
@app.get("/metrics/training")
def get_training():
df = pd.read_sql("SELECT team, COUNT(*) as completed FROM trainings t JOIN champions c ON t.champion_id=c.id GROUP BY team", engine)
return df.to_dict('records') # For Chart.js
# Add /incidents, /roi endpoints similarly...
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
Run: uvicorn main:app --reload. Test at http://localhost:8000/docs.
Frontend (React)
Install: npx create-vite@latest frontend --template react && cd frontend && npm i axios chart.js react-chartjs-2
// frontend/src/App.jsx
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Bar, Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, LineElement, PointElement, Title, Tooltip, Legend } from 'chart.js';
ChartJS.register(CategoryScale, LinearScale, BarElement, LineElement, PointElement, Title, Tooltip, Legend);
function App() {
const [overview, setOverview] = useState({});
const [trainingData, setTrainingData] = useState([]);
useEffect(() => {
axios.get('http://localhost:8000/metrics/overview').then(res => setOverview(res.data));
axios.get('http://localhost:8000/metrics/training').then(res => setTrainingData(res.data));
}, []);
const chartData = {
labels: trainingData.map(d => d.team),
datasets: [{ label: 'Completions', data: trainingData.map(d => d.completed), backgroundColor: 'rgba(75,192,192,0.4)' }]
};
return (
<div className="p-8">
<h1 className="text-3xl font-bold mb-8">Security Champions Analytics</h1>
<div className="grid grid-cols-3 gap-4 mb-8">
<div className="bg-blue-100 p-4 rounded">Completion: {overview.completion_rate?.toFixed(1)}%</div>
<div className="bg-green-100 p-4 rounded">Incidents: {overview.incidents_count}</div>
<div className="bg-purple-100 p-4 rounded">ROI: {overview.roi_pct?.toFixed(1)}%</div>
</div>
<Bar data={chartData} />
</div>
);
}
export default App;
Run: npm run dev (localhost:5173).
5. ETL Pipeline (Bonus: Airflow DAG)
Use Airflow to sync data daily:
# dags/sync_champions.py
from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta
def sync_training(): # Call LMS API, insert to DB
pass
dag = DAG('champions_etl', start_date=datetime(2024,1,1), schedule_interval='@daily')
PythonOperator(task_id='sync_training', python_callable=sync_training, dag=dag)
6. Deployment & Next Steps
-
Dockerize:
# Backend Dockerfile
FROM python:3.11-slim
COPY . /app
RUN pip install -r requirements.txt
CMD ["uvicorn", "main:app", "--host", "0.0.0.0"]
docker-compose up for stack.
-
AWS Deploy: ECS for backend, S3 for static React, RDS for PG.
-
Security: HTTPS, RBAC (add fastapi-users), API rate-limiting.
-
Scale: Add Redis cache, Celery for heavy analytics, ML for predictions (e.g., churn risk).
-
Enhance ROI: Integrate real breach data; A/B test program impact.
Cost Estimate: MVP < $500/mo on AWS (small instances).
Insert sample data via SQL, hit the APIs, and watch insights emerge. Need customizations, integrations, or full repo? The game is afoot—provide details! 🚀