Catalyst / admin/Strike 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / Strike

public

Web-Based UK Cyber Compliance Tool with Reporting

Code Issues Pull requests Pipelines Packages Security Insights Wiki Settings
Strike / strikexi-v2 / backend / app / pdf_report.py 12017 B · main
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"""
PDF reporting engine for StrikeXi.

Renders a professional CAF maturity report (HTML/CSS -> PDF via WeasyPrint).
Charts are inline SVG (donut for overall, bars for per-objective) so they
embed cleanly in the PDF without an external rendering service.
"""
import math
import os
from datetime import date

from jinja2 import Template
from weasyprint import HTML
from sqlalchemy.orm import Session

from . import models, risk as risk_engine

REPORTS_DIR = "/app/reports"

OBJ_TITLES = {
    "A": "Managing security risk",
    "B": "Protecting against cyber attack",
    "C": "Detecting cyber security events",
    "D": "Minimising the impact of incidents",
}


def _band(score: float) -> str:
    if score >= 80:
        return "Strong"
    if score >= 60:
        return "Established"
    if score >= 40:
        return "Developing"
    return "Initial"


def _donut_svg(score: float) -> str:
    r, cx, cy = 52, 70, 70
    circ = 2 * math.pi * r
    pct = max(0.0, min(100.0, score)) / 100.0
    dash = circ * pct
    colour = "#2ecc71" if score >= 60 else ("#f39c12" if score >= 40 else "#e74c3c")
    return f"""
    <svg width="140" height="140" viewBox="0 0 140 140">
      <circle cx="{cx}" cy="{cy}" r="{r}" fill="none" stroke="#e8edf3" stroke-width="14"/>
      <circle cx="{cx}" cy="{cy}" r="{r}" fill="none" stroke="{colour}" stroke-width="14"
              stroke-dasharray="{dash:.2f} {circ:.2f}" stroke-linecap="round"
              transform="rotate(-90 {cx} {cy})"/>
      <text x="{cx}" y="{cy+2}" text-anchor="middle" font-size="26"
            font-family="DejaVu Sans" font-weight="bold" fill="#1f2d3d">{score:.0f}</text>
      <text x="{cx}" y="{cy+20}" text-anchor="middle" font-size="11"
            font-family="DejaVu Sans" fill="#7b8a9a">/ 100</text>
    </svg>"""


def _bars_svg(objective_scores: dict) -> str:
    bars = ""
    x = 40
    width = 70
    gap = 55
    base_y = 180
    max_h = 140
    for oid in ["A", "B", "C", "D"]:
        score = objective_scores.get(oid, 0.0)
        h = (score / 100.0) * max_h
        y = base_y - h
        colour = "#2ecc71" if score >= 60 else ("#f39c12" if score >= 40 else "#e74c3c")
        bars += f"""
          <rect x="{x}" y="{y:.1f}" width="{width}" height="{h:.1f}" rx="4" fill="{colour}"/>
          <text x="{x + width/2}" y="{y-6:.1f}" text-anchor="middle" font-size="12"
                font-family="DejaVu Sans" font-weight="bold" fill="#1f2d3d">{score:.0f}</text>
          <text x="{x + width/2}" y="{base_y+18}" text-anchor="middle" font-size="13"
                font-family="DejaVu Sans" fill="#1f2d3d">Obj {oid}</text>
        """
        x += width + gap
    return f"""
    <svg width="520" height="210" viewBox="0 0 520 210">
      <line x1="30" y1="180" x2="500" y2="180" stroke="#cdd6e0" stroke-width="1"/>
      {bars}
    </svg>"""


_TEMPLATE = Template(r"""
<!DOCTYPE html>
<html><head><meta charset="utf-8"><style>
  @page { size: A4; margin: 1.6cm 1.5cm; @bottom-center {
      content: "StrikeXi CAF Maturity Report  —  Confidential  —  Page " counter(page) " of " counter(pages);
      font-size: 9px; color: #8a97a6; } }
  body { font-family: "DejaVu Sans", sans-serif; color: #2c3e50; font-size: 12px; }
  .cover { text-align:center; margin-top: 60px; }
  .brand { font-size: 34px; font-weight: bold; color: #16324f; letter-spacing: 1px; }
  .brand span { color: #2e86de; }
  .subtitle { font-size: 16px; color: #5b6b7b; margin-top: 6px; }
  .meta { margin-top: 50px; font-size: 14px; }
  .meta b { color:#16324f; }
  h2 { color:#16324f; border-bottom: 2px solid #2e86de; padding-bottom: 4px; margin-top: 28px; }
  .scorecard { display:flex; align-items:center; gap:24px; margin: 16px 0; }
  .band { display:inline-block; padding:4px 12px; border-radius:14px; color:#fff; font-weight:bold; }
  table { width:100%; border-collapse: collapse; margin-top:10px; }
  th, td { text-align:left; padding:8px 10px; border-bottom:1px solid #e3e9ef; font-size:11.5px; }
  th { background:#16324f; color:#fff; }
  .step { border-left:4px solid #2e86de; background:#f6f9fc; padding:10px 14px; margin:10px 0; }
  .step .num { font-weight:bold; color:#2e86de; }
  .pill { font-size:10px; padding:2px 8px; border-radius:10px; background:#eef3f8; color:#16324f; }
  .page-break { page-break-before: always; }
</style></head><body>

  <div class="cover">
    <div class="brand">Strike<span>Xi</span></div>
    <div class="subtitle">NCSC Cyber Assessment Framework — Maturity Report</div>
    <div class="meta">
      <p><b>Organisation Assessed:</b> {{ org }}</p>
      <p><b>Date of Assessment:</b> {{ adate }}</p>
      <p><b>Report Generated:</b> {{ generated }}</p>
    </div>
  </div>

  <div class="page-break"></div>
  <h2>Overall Maturity</h2>
  <div class="scorecard">
    {{ donut|safe }}
    <div>
      <p style="font-size:18px;"><b>Overall score: {{ overall }}/100</b></p>
      <p>Maturity band: <span class="band" style="background:{{ band_colour }}">{{ band }}</span></p>
      <p style="max-width:340px; color:#5b6b7b;">This score is the weighted mean of the four CAF
      objectives, derived from weighted answers across the assessed principles.</p>
    </div>
  </div>

  <h2>Per-Objective Scores</h2>
  {{ bars|safe }}
  <table>
    <tr><th>Objective</th><th>Title</th><th>Score</th><th>Band</th></tr>
    {% for oid, score in objective_rows %}
    <tr><td><b>{{ oid }}</b></td><td>{{ obj_titles[oid] }}</td><td>{{ '%.0f'|format(score) }}/100</td>
        <td>{{ band_of(score) }}</td></tr>
    {% endfor %}
  </table>

  <h2>Risk Assessment Summary</h2>
  <p style="color:#5b6b7b;">This risk assessment is derived from the responses given in this
  assessment. Lower maturity indicates higher residual cyber risk.</p>
  <div class="scorecard">
    <div style="text-align:center;">
      <div class="band" style="background:{{ risk.overall_colour }};font-size:18px;padding:8px 20px;">{{ risk.overall_risk }} RISK</div>
      <div style="font-size:11px;color:#7b8a9a;margin-top:6px;">Overall residual risk</div>
    </div>
    <div style="max-width:380px;color:#41536b;">{{ risk.narrative }}</div>
  </div>
  <table>
    <tr><th>Risk band</th><th>Critical</th><th>High</th><th>Medium</th><th>Low</th></tr>
    <tr><td><b>Principles</b></td>
        <td>{{ risk.counts.Critical }}</td><td>{{ risk.counts.High }}</td>
        <td>{{ risk.counts.Medium }}</td><td>{{ risk.counts.Low }}</td></tr>
  </table>
  <table>
    <tr><th>Objective</th><th>Title</th><th>Score</th><th>Risk level</th></tr>
    {% for o in risk.objective_risks %}
    <tr><td><b>{{ o.objective_id }}</b></td><td>{{ o.title }}</td>
        <td>{{ '%.0f'|format(o.score) }}/100</td>
        <td><span class="pill" style="background:{{ o.colour }};color:#fff;">{{ o.risk_level }}</span></td></tr>
    {% endfor %}
  </table>
  <h3 style="color:#16324f;margin-top:18px;">Key Risk Areas</h3>
  <p style="color:#5b6b7b;">The principles carrying the highest residual risk, in priority order.</p>
  <table>
    <tr><th>#</th><th>Objective</th><th>Principle</th><th>Score</th><th>Risk level</th></tr>
    {% for k in risk.key_risks %}
    <tr><td>{{ loop.index }}</td><td>{{ k.objective_id }}</td>
        <td><b>{{ k.principle_id }}</b> — {{ k.principle_title }}</td>
        <td>{{ '%.0f'|format(k.score) }}/100</td>
        <td><span class="pill" style="background:{{ k.colour }};color:#fff;">{{ k.risk_level }}</span></td></tr>
    {% endfor %}
  </table>

  <div class="page-break"></div>
  <h2>Assessment Summary &amp; Breakdown</h2>
  <p style="color:#5b6b7b;">Score for every assessed CAF principle, grouped by objective.
  Principles below the maturity threshold (70/100) trigger a remediation in the roadmap.</p>
  <table>
    <tr><th>Objective</th><th>Principle</th><th>Score</th><th>Status</th></tr>
    {% for oid, pid, pname, pscore in principle_rows %}
    <tr><td>{{ oid }}</td><td><b>{{ pid }}</b> — {{ pname }}</td><td>{{ '%.0f'|format(pscore) }}/100</td>
        <td>{% if pscore < 70 %}<span class="pill" style="background:#fdecea;color:#c0392b;">Needs improvement</span>
            {% else %}<span class="pill" style="background:#eafaf1;color:#1e8449;">On track</span>{% endif %}</td></tr>
    {% endfor %}
  </table>

  <div class="page-break"></div>
  <h2>Actionable Maturity Roadmap</h2>
  <p style="color:#5b6b7b;">The following corrective actions were triggered by principles scoring
  below the maturity threshold. They are ordered by priority to form a step-by-step roadmap.</p>
  {% if roadmap %}
    {% for item in roadmap %}
    <div class="step">
      <p><span class="num">Step {{ loop.index }}.</span> <b>{{ item.title }}</b></p>
      <p style="margin:4px 0 6px;">
         <span class="pill">Objective {{ item.objective_id }}</span>
         <span class="pill">Principle {{ item.principle_id }} — {{ item.principle_title }}</span>
         <span class="pill">Current score: {{ '%.0f'|format(item.principle_score) }}/100</span>
         <span class="pill">Effort: {{ item.effort }}</span>
         <span class="pill">Priority: {{ item.priority }}</span></p>
      <p style="margin:4px 0 0;"><b>Mitigation:</b> {{ item.detail }}</p>
    </div>
    {% endfor %}
  {% else %}
    <p><b>No remediation actions triggered.</b> All assessed principles met the maturity threshold.</p>
  {% endif %}

</body></html>
""")


def generate_report(db: Session, assessment: models.Assessment) -> str:
    obj_scores = {
        s.objective_id: float(s.score)
        for s in db.query(models.AssessmentObjectiveScore)
        .filter(models.AssessmentObjectiveScore.assessment_id == assessment.id).all()
    }

    principles = {p.id: p for p in db.query(models.CafPrinciple).all()}
    sugg = {s.id: s for s in db.query(models.RemediationSuggestion).all()}

    actions = (
        db.query(models.RemediationAction)
        .filter(models.RemediationAction.assessment_id == assessment.id).all()
    )
    roadmap = []
    for a in actions:
        s = sugg.get(a.remediation_id)
        if not s:
            continue
        pr = principles.get(a.principle_id)
        roadmap.append({
            "title": s.title, "detail": s.detail, "effort": s.effort,
            "priority": s.priority, "principle_id": a.principle_id,
            "principle_title": pr.title if pr else "",
            "objective_id": pr.objective_id if pr else "",
            "principle_score": float(a.principle_score),
        })
    roadmap.sort(key=lambda x: (x["priority"], x["principle_score"]))

    # FULL per-principle breakdown (every assessed principle), grouped by objective
    pscores = (
        db.query(models.AssessmentPrincipleScore)
        .filter(models.AssessmentPrincipleScore.assessment_id == assessment.id).all()
    )
    principle_rows = []
    for ps in pscores:
        pr = principles.get(ps.principle_id)
        principle_rows.append((
            pr.objective_id if pr else "",
            ps.principle_id,
            pr.title if pr else "",
            float(ps.score),
        ))
    principle_rows.sort(key=lambda x: (x[0], x[1]))

    risk_summary = risk_engine.build_risk_summary(db, assessment)

    overall = float(assessment.overall_score or 0.0)
    band = _band(overall)
    band_colour = "#27ae60" if overall >= 60 else ("#f39c12" if overall >= 40 else "#e74c3c")

    html = _TEMPLATE.render(
        org=assessment.organisation_name,
        adate=assessment.assessment_date.strftime("%d %B %Y"),
        generated=date.today().strftime("%d %B %Y"),
        donut=_donut_svg(overall),
        bars=_bars_svg(obj_scores),
        overall=f"{overall:.0f}",
        band=band, band_colour=band_colour,
        obj_titles=OBJ_TITLES,
        objective_rows=sorted(obj_scores.items()),
        principle_rows=principle_rows,
        roadmap=roadmap,
        risk=risk_summary,
        band_of=_band,
    )

    os.makedirs(REPORTS_DIR, exist_ok=True)
    out_path = os.path.join(REPORTS_DIR, f"StrikeXi_Report_{assessment.id}.pdf")
    HTML(string=html).write_pdf(out_path)
    return out_path