-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_audit_report.py
More file actions
870 lines (778 loc) · 34.5 KB
/
generate_audit_report.py
File metadata and controls
870 lines (778 loc) · 34.5 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
"""
generate_audit_report.py — produces a professional audit report .docx
from the three CSV reports generated by generate_report.py.
Reads:
reports/01_summary.csv — signal pass/fail per framework
reports/02_control_coverage.csv — control-level status
reports/03_findings_detail.csv — individual findings
Writes:
reports/audit_report.docx — Word document, ready to share or print to PDF
Requires:
- Node.js (any version >= 16)
- docx npm package (npm install -g docx)
Usage:
python generate_audit_report.py
python generate_audit_report.py --reports-dir reports --output reports/audit_report.docx
python generate_audit_report.py --client "Acme Corp" --auditor "Ree Hiri" --region eu-west-1
Adding to GitHub Actions (after generate_report.py):
- name: Generate audit report
run: python generate_audit_report.py --reports-dir reports --client "${{ vars.CLIENT_NAME }}"
Concept — why Python calls Node:
The docx library is a JavaScript/Node package. It is the best available tool
for producing well-formed .docx files programmatically. This script:
1. Reads your CSVs in Python (familiar, already part of the project)
2. Builds a JSON data structure
3. Writes a temporary Node script that uses docx to render the Word file
4. Runs Node to execute that script
5. Cleans up the temp file
The result is a single Python entry point you can call from anywhere.
"""
import argparse
import csv
import json
import os
import subprocess
import sys
import tempfile
from datetime import datetime, timezone
from pathlib import Path
# ── CSV readers ────────────────────────────────────────────────────────────
def read_csv(path: Path) -> list[dict]:
if not path.exists():
print(f" [WARN] {path} not found — skipping")
return []
with open(path, newline="", encoding="utf-8") as f:
return list(csv.DictReader(f))
# ── Data builders ──────────────────────────────────────────────────────────
def build_meta(summary_rows, args) -> dict:
"""Pull account ID from the CSV; use CLI args for everything else."""
account = "N/A"
for row in summary_rows:
a = row.get("aws_account", "")
if a and a not in ("N/A", "unknown", ""):
account = a
break
run_date = datetime.now(timezone.utc).strftime("%B %d, %Y")
# Mask real account numbers — safe for portfolio demos and client deliverables
masked_account = "XXXXXXXXXXXX" if account and account != "N/A" else "N/A"
return {
"client": args.client,
"auditor": args.auditor,
"reportDate": run_date,
"period": args.period,
"account": masked_account,
"region": args.region,
"classification": args.classification,
"reportVersion": "1.0",
}
def build_framework_summary(summary_rows) -> list[dict]:
"""
Count signal-level pass/fail per framework.
Returns list of {id, label, pass, total, pct, status} dicts.
"""
fw_order = ["PCI-DSS", "SOC 2", "ISO 27001", "ISO 42001"]
fw_labels = {
"PCI-DSS": "PCI-DSS v4.0",
"SOC 2": "SOC 2 Type II",
"ISO 27001": "ISO 27001:2022",
"ISO 42001": "ISO 42001:2023",
}
counts = {fw: {"pass": 0, "total": 0} for fw in fw_order}
for row in summary_rows:
status = row.get("status", "")
for fw in fw_order:
if row.get(fw, "").strip():
counts[fw]["total"] += 1
if status == "PASS":
counts[fw]["pass"] += 1
result = []
for fw in fw_order:
c = counts[fw]
total = c["total"] or 1
pct = round(c["pass"] / total * 100)
if pct >= 80:
posture = "Satisfactory"
elif pct >= 60:
posture = "Needs Improvement"
else:
posture = "At Risk"
result.append({
"id": fw,
"label": fw_labels[fw],
"pass": c["pass"],
"total": c["total"],
"pct": pct,
"posture": posture,
})
return result
def build_controls(coverage_rows) -> list[dict]:
result = []
for row in coverage_rows:
sources = [s.strip() for s in row.get("evidence_ids", "").split(";") if s.strip()]
try:
n = int(row.get("evidence_count", 1))
except ValueError:
n = 1
status = row.get("overall_status", "UNKNOWN").upper()
# First description only, truncated
raw_desc = row.get("signal_descriptions", "")
desc = raw_desc.split("|")[0].strip()[:80]
result.append({
"fw": row.get("framework", ""),
"id": row.get("control_id", ""),
"status": status if status in ("PASS", "FAIL") else "FAIL",
"signals": n,
"passing": int(row.get("passing_signals", 0)),
"failing": int(row.get("failing_signals", 0)),
"sources": sources,
"desc": desc,
})
return result
def build_findings(findings_rows) -> list[dict]:
sev_order = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3}
findings = []
for row in findings_rows:
sev = row.get("severity", "MEDIUM").upper()
findings.append({
"sev": sev,
"type": row.get("finding_type", ""),
"resource": row.get("resource", ""),
"detail": row.get("detail", ""),
"rem": row.get("remediation", ""),
"src": row.get("evidence_id", "").replace("aws_", "").replace("_", " "),
"date": row.get("collected_at", "")[:10],
})
findings.sort(key=lambda f: sev_order.get(f["sev"], 99))
return findings
def build_signals(summary_rows) -> list[dict]:
src_labels = {
"aws_cloudtrail_logs": "CloudTrail",
"aws_config_rules": "Config",
"aws_iam_posture": "IAM",
"aws_securityhub_findings": "Security Hub",
}
result = []
for row in summary_rows:
status = row.get("status", "ERROR").upper()
result.append({
"signal": row.get("signal", ""),
"desc": row.get("description", ""),
"status": status,
"src": src_labels.get(row.get("evidence_id", ""), row.get("evidence_id", "")),
"account": row.get("aws_account", ""),
"date": row.get("collected_at", "")[:10],
})
return result
# ── Node.js script template ────────────────────────────────────────────────
# This is the JavaScript that actually builds the Word document.
# DATA_PLACEHOLDER is replaced with the JSON blob before execution.
NODE_SCRIPT = r"""
'use strict';
const fs = require('fs');
const path = require('path');
const {
Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell,
Header, Footer, AlignmentType, HeadingLevel, BorderStyle, WidthType,
ShadingType, VerticalAlign, PageNumber, PageBreak, LevelFormat,
TableOfContents, TabStopType, TabStopPosition,
} = require('docx');
// ── Injected data ──────────────────────────────────────────────────────────
const DATA = DATA_PLACEHOLDER;
const { meta, frameworks, controls, findings, signals, outputPath } = DATA;
// ── Design constants ───────────────────────────────────────────────────────
const CONTENT_WIDTH = 9360; // 6.5 inches in DXA (US Letter minus 1" margins each side)
const PAGE_W = 12240;
const PAGE_H = 15840;
const MARGIN = 1440; // 1 inch
// Brand colours (hex without #)
const C_DARK = "1A1918";
const C_MID = "5F5E5A";
const C_LIGHT = "888780";
const C_BORDER = "D3D1C7";
const C_PASS = "1D9E75";
const C_FAIL = "D85A30";
const C_WARN = "BA7517";
const C_ACCENT = "185FA5";
const C_BG_HEAD= "1A1918"; // dark header row background
const C_BG_ALT = "F8F7F4"; // alternating row tint
// ── Helpers ────────────────────────────────────────────────────────────────
function cell(text, opts = {}) {
const {
bold = false, color = C_DARK, bg = "FFFFFF", width = null,
align = AlignmentType.LEFT, shade = false,
} = opts;
const border = { style: BorderStyle.SINGLE, size: 1, color: C_BORDER };
return new TableCell({
width: width ? { size: width, type: WidthType.DXA } : undefined,
borders: { top: border, bottom: border, left: border, right: border },
shading: { fill: bg, type: ShadingType.CLEAR },
margins: { top: 80, bottom: 80, left: 120, right: 120 },
verticalAlign: VerticalAlign.CENTER,
children: [new Paragraph({
alignment: align,
children: [new TextRun({ text: String(text), bold, color, font: "Arial", size: 20 })],
})],
});
}
function headerCell(text, width = null) {
const border = { style: BorderStyle.SINGLE, size: 1, color: C_BORDER };
return new TableCell({
width: width ? { size: width, type: WidthType.DXA } : undefined,
borders: { top: border, bottom: border, left: border, right: border },
shading: { fill: C_BG_HEAD, type: ShadingType.CLEAR },
margins: { top: 100, bottom: 100, left: 120, right: 120 },
verticalAlign: VerticalAlign.CENTER,
children: [new Paragraph({
children: [new TextRun({ text, bold: true, color: "FFFFFF", font: "Arial", size: 20 })],
})],
});
}
function statusColor(s) {
if (s === "PASS") return C_PASS;
if (s === "FAIL") return C_FAIL;
if (s === "HIGH") return C_FAIL;
if (s === "CRITICAL") return C_FAIL;
if (s === "MEDIUM") return C_WARN;
return C_WARN;
}
function h1(text) {
return new Paragraph({
heading: HeadingLevel.HEADING_1,
pageBreakBefore: true,
children: [new TextRun({ text, font: "Arial", size: 32, bold: true, color: C_DARK })],
});
}
function h2(text) {
return new Paragraph({
heading: HeadingLevel.HEADING_2,
children: [new TextRun({ text, font: "Arial", size: 26, bold: true, color: C_DARK })],
});
}
function h3(text) {
return new Paragraph({
heading: HeadingLevel.HEADING_3,
children: [new TextRun({ text, font: "Arial", size: 22, bold: true, color: C_MID })],
});
}
function para(text, opts = {}) {
const { color = C_DARK, bold = false, size = 22, spacing = 160 } = opts;
return new Paragraph({
spacing: { after: spacing },
children: [new TextRun({ text, font: "Arial", size, color, bold })],
});
}
function spacer(after = 200) {
return new Paragraph({ spacing: { after }, children: [new TextRun("")] });
}
function bullet(text, bold_prefix = "") {
return new Paragraph({
numbering: { reference: "bullets", level: 0 },
spacing: { after: 80 },
children: bold_prefix
? [new TextRun({ text: bold_prefix, bold: true, font: "Arial", size: 22, color: C_DARK }),
new TextRun({ text, font: "Arial", size: 22, color: C_DARK })]
: [new TextRun({ text, font: "Arial", size: 22, color: C_DARK })],
});
}
function ruled_line() {
return new Paragraph({
border: { bottom: { style: BorderStyle.SINGLE, size: 4, color: C_BORDER, space: 1 } },
spacing: { after: 200 },
children: [new TextRun("")],
});
}
// ── Cover page ─────────────────────────────────────────────────────────────
function coverPage() {
return [
spacer(2880),
new Paragraph({
alignment: AlignmentType.LEFT,
spacing: { after: 120 },
children: [new TextRun({
text: "COMPLIANCE AUDIT REPORT",
font: "Arial", size: 52, bold: true, color: C_DARK,
})],
}),
new Paragraph({
alignment: AlignmentType.LEFT,
spacing: { after: 480 },
children: [new TextRun({
text: "Continuous Compliance Monitoring",
font: "Arial", size: 30, color: C_MID,
})],
}),
ruled_line(),
new Paragraph({
alignment: AlignmentType.LEFT,
spacing: { after: 120 },
tabStops: [{ type: TabStopType.RIGHT, position: TabStopPosition.MAX }],
children: [
new TextRun({ text: "Prepared for", font: "Arial", size: 22, color: C_LIGHT }),
new TextRun({ text: "\t" + meta.reportDate, font: "Arial", size: 22, color: C_LIGHT }),
],
}),
new Paragraph({
alignment: AlignmentType.LEFT,
spacing: { after: 80 },
tabStops: [{ type: TabStopType.RIGHT, position: TabStopPosition.MAX }],
children: [
new TextRun({ text: meta.client, font: "Arial", size: 28, bold: true, color: C_DARK }),
new TextRun({ text: "\tVersion " + meta.reportVersion, font: "Arial", size: 22, color: C_LIGHT }),
],
}),
spacer(240),
new Paragraph({
alignment: AlignmentType.LEFT,
spacing: { after: 80 },
children: [new TextRun({ text: "Auditor: " + meta.auditor, font: "Arial", size: 22, color: C_MID })],
}),
new Paragraph({
alignment: AlignmentType.LEFT,
spacing: { after: 80 },
children: [new TextRun({ text: "AWS Account: " + meta.account + " | Region: " + meta.region, font: "Arial", size: 22, color: C_MID })],
}),
new Paragraph({
alignment: AlignmentType.LEFT,
spacing: { after: 80 },
children: [new TextRun({ text: "Assessment period: " + meta.period, font: "Arial", size: 22, color: C_MID })],
}),
spacer(400),
new Paragraph({
alignment: AlignmentType.LEFT,
children: [new TextRun({ text: meta.classification, font: "Arial", size: 20, bold: true, color: C_FAIL })],
}),
];
}
// ── Executive summary ──────────────────────────────────────────────────────
function execSummary() {
const totalControls = controls.length;
const failControls = controls.filter(c => c.status === "FAIL").length;
const passControls = totalControls - failControls;
const totalFindings = findings.length;
const highFindings = findings.filter(f => f.sev === "HIGH" || f.sev === "CRITICAL").length;
const overallPct = frameworks.length
? Math.round(frameworks.reduce((s, f) => s + f.pct, 0) / frameworks.length)
: 0;
const overallLabel = overallPct >= 80 ? "satisfactory" : overallPct >= 60 ? "requiring improvement" : "at risk";
const summaryText =
`This report presents the results of an automated compliance assessment conducted against ` +
`${meta.client}'s AWS environment (account ${meta.account}, region ${meta.region}) ` +
`during the period ${meta.period}. Evidence was collected automatically using ` +
`boto3 collectors attached to CloudTrail, AWS Config, IAM, and Security Hub, ` +
`with results committed to a git repository to provide a continuous, tamper-evident audit trail.` +
`\n\n` +
`The overall compliance posture is ${overallLabel}, with an average pass rate of ${overallPct}% ` +
`across all four frameworks assessed. Of ${totalControls} framework controls evaluated, ` +
`${passControls} are passing and ${failControls} require remediation. ` +
`A total of ${totalFindings} individual findings were identified, ` +
`of which ${highFindings} are rated HIGH or CRITICAL severity and require priority attention.`;
const rows = [
{ label: "Assessment date", value: meta.reportDate },
{ label: "AWS account", value: meta.account },
{ label: "Region", value: meta.region },
{ label: "Frameworks assessed", value: frameworks.map(f => f.label).join(", ") },
{ label: "Controls evaluated", value: String(totalControls) },
{ label: "Controls passing", value: String(passControls) },
{ label: "Controls failing", value: String(failControls) },
{ label: "Total findings", value: String(totalFindings) },
{ label: "HIGH / CRITICAL findings",value: String(highFindings) },
{ label: "Overall posture", value: overallPct + "% (" + overallLabel + ")" },
];
const summaryTable = new Table({
width: { size: CONTENT_WIDTH, type: WidthType.DXA },
columnWidths: [3000, 6360],
rows: rows.map((r, i) => new TableRow({
children: [
cell(r.label, { bold: true, bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: 3000 }),
cell(r.value, { bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: 6360 }),
],
})),
});
const items = [
h1("1. Executive Summary"),
para(summaryText, { spacing: 200 }),
spacer(160),
h2("Assessment at a glance"),
summaryTable,
spacer(240),
h2("Framework posture"),
];
// Framework posture table
const fwTable = new Table({
width: { size: CONTENT_WIDTH, type: WidthType.DXA },
columnWidths: [3000, 1800, 1800, 1400, 1360],
rows: [
new TableRow({
tableHeader: true,
children: [
headerCell("Framework", 3000),
headerCell("Pass rate", 1800),
headerCell("Signals", 1800),
headerCell("Controls", 1400),
headerCell("Posture", 1360),
],
}),
...frameworks.map((fw, i) => new TableRow({
children: [
cell(fw.label, { bold: true, bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: 3000 }),
cell(fw.pct + "%", { color: statusColor(fw.pct >= 80 ? "PASS" : fw.pct >= 60 ? "MEDIUM" : "FAIL"), bold: true, bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: 1800 }),
cell(fw.pass + " / " + fw.total, { bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: 1800 }),
cell(String(controls.filter(c => c.fw === fw.id).length), { bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: 1400 }),
cell(fw.posture, { color: statusColor(fw.pct >= 80 ? "PASS" : fw.pct >= 60 ? "MEDIUM" : "FAIL"), bold: true, bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: 1360 }),
],
})),
],
});
items.push(fwTable);
return items;
}
// ── Scope and methodology ──────────────────────────────────────────────────
function scopeSection() {
return [
h1("2. Scope and Methodology"),
h2("Assessment scope"),
para(
"This assessment covers the AWS environment identified above. Evidence was collected from " +
"four AWS services, each mapped to a dedicated collector. All evidence is stored as " +
"timestamped JSON artifacts committed to a git repository, providing an immutable " +
"audit trail that can be inspected at any point in time."
),
spacer(80),
h2("Evidence sources"),
...[
["CloudTrail", "aws_cloudtrail_logs", "Trail configuration, log validation status, write event activity over 90-day lookback"],
["AWS Config", "aws_config_rules", "Rule compliance status, non-compliant resource details, high-value rule failure tracking"],
["IAM", "aws_iam_posture", "Password policy, root account posture, per-user MFA status, access key age analysis"],
["Security Hub","aws_securityhub_findings", "Hub enablement, enabled standards, active findings by severity (CRITICAL/HIGH sample)"],
].map(([name, eid, desc]) => bullet(`${desc}`, `${name} (${eid}): `)),
spacer(160),
h2("Frameworks assessed"),
...[
["PCI-DSS v4.0", "Payment Card Industry Data Security Standard — requirements for organisations that handle cardholder data"],
["SOC 2 Type II", "AICPA Trust Services Criteria — Security, Availability, and Confidentiality principles"],
["ISO 27001:2022", "International standard for information security management systems"],
["ISO 42001:2023", "International standard for AI management systems — governance of AI systems and models"],
].map(([name, desc]) => bullet(`${desc}`, `${name}: `)),
spacer(160),
h2("Evidence collection approach"),
para(
"Evidence is collected automatically on a weekly schedule via GitHub Actions, using " +
"short-lived OIDC credentials to assume a read-only AWS IAM role. No long-lived " +
"access keys are stored anywhere. Each collector saves its output in a standard " +
"envelope format — evidence_id, collected_at, aws_account, aws_region, status, data — " +
"and commits both a latest.json (for quick status checks) and a timestamped snapshot " +
"(for audit trail purposes) to the repository."
),
para(
"A single evidence artifact can satisfy controls across multiple frameworks simultaneously. " +
"For example, an IAM credential report satisfies MFA controls in PCI-DSS 8.4.2, " +
"SOC 2 CC6.1, ISO 27001 A.5.17, and ISO 42001 6.4.1 in a single collection run. " +
"This overlap is made explicit in the controls.yaml mapping file, which is the " +
"machine-readable risk register underlying this report."
),
];
}
// ── Per-framework findings ─────────────────────────────────────────────────
function frameworkSections() {
const items = [h1("3. Findings by Framework")];
frameworks.forEach((fw, fi) => {
const fwControls = controls.filter(c => c.fw === fw.id);
const failing = fwControls.filter(c => c.status === "FAIL");
const passing = fwControls.filter(c => c.status === "PASS");
items.push(h2(`3.${fi + 1} ${fw.label}`));
items.push(para(
`Pass rate: ${fw.pct}% (${fw.pass} of ${fw.total} signals passing). ` +
`${passing.length} controls have satisfactory evidence coverage; ` +
`${failing.length} controls have identified gaps requiring remediation.`
));
if (fwControls.length === 0) {
items.push(para("No controls mapped for this framework.", { color: C_LIGHT }));
return;
}
const colWidths = [1300, 4460, 1200, 1200, 1200];
const controlTable = new Table({
width: { size: CONTENT_WIDTH, type: WidthType.DXA },
columnWidths: colWidths,
rows: [
new TableRow({
tableHeader: true,
children: [
headerCell("Control ID", colWidths[0]),
headerCell("Description", colWidths[1]),
headerCell("Status", colWidths[2]),
headerCell("Signals", colWidths[3]),
headerCell("Evidence", colWidths[4]),
],
}),
...fwControls.map((c, i) => new TableRow({
children: [
cell(c.id, { bold: true, bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[0] }),
cell(c.desc, { bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[1] }),
cell(c.status, { bold: true, color: statusColor(c.status), bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[2] }),
cell(c.passing + "/" + c.signals, { bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[3] }),
cell(c.sources.map(s => s.replace("aws_","").replace(/_/g," ")).join(", "), { bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[4] }),
],
})),
],
});
items.push(controlTable);
items.push(spacer(240));
});
return items;
}
// ── Detailed findings ──────────────────────────────────────────────────────
function findingsSection() {
const items = [
h1("4. Detailed Findings"),
para(
`The following ${findings.length} findings were identified during this assessment period. ` +
`Each finding maps to one or more framework controls. Findings are ordered by severity ` +
`(CRITICAL first, then HIGH, then MEDIUM).`
),
];
if (findings.length === 0) {
items.push(para("No findings identified. All controls passing.", { color: C_PASS, bold: true }));
return items;
}
const colWidths = [1100, 2200, 2200, 1800, 2060];
const findingsTable = new Table({
width: { size: CONTENT_WIDTH, type: WidthType.DXA },
columnWidths: colWidths,
rows: [
new TableRow({
tableHeader: true,
children: [
headerCell("Severity", colWidths[0]),
headerCell("Finding", colWidths[1]),
headerCell("Resource", colWidths[2]),
headerCell("Detail", colWidths[3]),
headerCell("Remediation", colWidths[4]),
],
}),
...findings.map((f, i) => new TableRow({
children: [
cell(f.sev, { bold: true, color: statusColor(f.sev), bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[0] }),
cell(f.type, { bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[1] }),
cell(f.resource, { bold: true, bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[2] }),
cell(f.detail, { bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[3] }),
cell(f.rem, { bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[4] }),
],
})),
],
});
items.push(findingsTable);
return items;
}
// ── Signal inventory appendix ──────────────────────────────────────────────
function appendix() {
const colWidths = [2800, 3560, 1200, 1800];
const rows = [
new TableRow({
tableHeader: true,
children: [
headerCell("Signal", colWidths[0]),
headerCell("Description", colWidths[1]),
headerCell("Status", colWidths[2]),
headerCell("Source", colWidths[3]),
],
}),
...signals.map((s, i) => new TableRow({
children: [
cell(s.signal, { bold: true, bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[0] }),
cell(s.desc, { bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[1] }),
cell(s.status, { bold: true, color: statusColor(s.status), bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[2] }),
cell(s.src, { bg: i % 2 === 0 ? C_BG_ALT : "FFFFFF", width: colWidths[3] }),
],
})),
];
return [
h1("Appendix A — Signal Inventory"),
para(
"The following table lists every compliance signal evaluated in this assessment, " +
"its status, and the evidence source that produced it."
),
new Table({
width: { size: CONTENT_WIDTH, type: WidthType.DXA },
columnWidths: colWidths,
rows,
}),
];
}
// ── Assemble document ──────────────────────────────────────────────────────
const headerPara = new Paragraph({
tabStops: [{ type: TabStopType.RIGHT, position: TabStopPosition.MAX }],
children: [
new TextRun({ text: meta.client + " — Compliance Audit Report", font: "Arial", size: 18, color: C_LIGHT }),
new TextRun({ text: "\t" + meta.classification, font: "Arial", size: 18, color: C_FAIL, bold: true }),
],
});
const footerPara = new Paragraph({
tabStops: [{ type: TabStopType.RIGHT, position: TabStopPosition.MAX }],
children: [
new TextRun({ text: meta.reportDate, font: "Arial", size: 18, color: C_LIGHT }),
new TextRun({ text: "\tPage ", font: "Arial", size: 18, color: C_LIGHT }),
new TextRun({ children: [PageNumber.CURRENT], font: "Arial", size: 18, color: C_LIGHT }),
new TextRun({ text: " of ", font: "Arial", size: 18, color: C_LIGHT }),
new TextRun({ children: [PageNumber.TOTAL_PAGES], font: "Arial", size: 18, color: C_LIGHT }),
],
});
const doc = new Document({
creator: meta.auditor,
title: "Compliance Audit Report — " + meta.client,
description: "Automated compliance assessment across PCI-DSS, SOC 2, ISO 27001, ISO 42001",
styles: {
default: {
document: { run: { font: "Arial", size: 22, color: C_DARK } },
},
paragraphStyles: [
{
id: "Heading1", name: "Heading 1", basedOn: "Normal", next: "Normal", quickFormat: true,
run: { size: 32, bold: true, font: "Arial", color: C_DARK },
paragraph: { spacing: { before: 360, after: 240 }, outlineLevel: 0 },
},
{
id: "Heading2", name: "Heading 2", basedOn: "Normal", next: "Normal", quickFormat: true,
run: { size: 26, bold: true, font: "Arial", color: C_DARK },
paragraph: { spacing: { before: 280, after: 160 }, outlineLevel: 1 },
},
{
id: "Heading3", name: "Heading 3", basedOn: "Normal", next: "Normal", quickFormat: true,
run: { size: 22, bold: true, font: "Arial", color: C_MID },
paragraph: { spacing: { before: 200, after: 120 }, outlineLevel: 2 },
},
],
},
numbering: {
config: [{
reference: "bullets",
levels: [{
level: 0, format: LevelFormat.BULLET, text: "\u2022",
alignment: AlignmentType.LEFT,
style: { paragraph: { indent: { left: 720, hanging: 360 } } },
}],
}],
},
sections: [{
properties: {
page: {
size: { width: PAGE_W, height: PAGE_H },
margin: { top: MARGIN, right: MARGIN, bottom: MARGIN, left: MARGIN },
},
},
headers: { default: new Header({ children: [headerPara] }) },
footers: { default: new Footer({ children: [footerPara] }) },
children: [
...coverPage(),
new Paragraph({ children: [new PageBreak()] }),
new TableOfContents("Table of Contents", { hyperlink: true, headingStyleRange: "1-2" }),
...execSummary(),
...scopeSection(),
...frameworkSections(),
...findingsSection(),
...appendix(),
],
}],
});
Packer.toBuffer(doc).then(buffer => {
fs.writeFileSync(outputPath, buffer);
console.log("OK:" + outputPath);
}).catch(err => {
console.error("ERROR:" + err.message);
process.exit(1);
});
"""
# ── Main ───────────────────────────────────────────────────────────────────
def generate(args):
reports_dir = Path(args.reports_dir)
output_path = Path(args.output) if args.output else reports_dir / "audit_report.docx"
print(f"\n{'='*56}")
print(f" Compliance Audit Report Generator")
print(f" reports : {reports_dir}")
print(f" output : {output_path}")
print(f"{'='*56}\n")
# Read CSVs
summary_rows = read_csv(reports_dir / "01_summary.csv")
coverage_rows = read_csv(reports_dir / "02_control_coverage.csv")
findings_rows = read_csv(reports_dir / "03_findings_detail.csv")
if not summary_rows and not coverage_rows:
print("[ERROR] No CSV data found. Run generate_report.py first.")
sys.exit(1)
# Build data
meta = build_meta(summary_rows, args)
frameworks = build_framework_summary(summary_rows)
controls = build_controls(coverage_rows)
findings = build_findings(findings_rows)
signals = build_signals(summary_rows)
output_path.parent.mkdir(parents=True, exist_ok=True)
data = {
"meta": meta,
"frameworks": frameworks,
"controls": controls,
"findings": findings,
"signals": signals,
"outputPath": str(output_path.resolve()),
}
# Write temp Node script with data injected
node_source = NODE_SCRIPT.replace(
"DATA_PLACEHOLDER",
json.dumps(data, indent=2, ensure_ascii=False)
)
with tempfile.NamedTemporaryFile(
mode="w", suffix=".js", delete=False, encoding="utf-8"
) as tmp:
tmp.write(node_source)
tmp_path = tmp.name
try:
print(" Running Node.js docx builder...")
result = subprocess.run(
["node", tmp_path],
capture_output=True, text=True
)
if result.returncode != 0:
print(f"[ERROR] Node.js failed:\n{result.stderr}")
sys.exit(1)
output = result.stdout.strip()
if output.startswith("ERROR:"):
print(f"[ERROR] docx builder: {output}")
sys.exit(1)
size_kb = round(output_path.stat().st_size / 1024)
print(f" Signals : {len(signals)}")
print(f" Controls : {len(controls)} ({sum(1 for c in controls if c['status']=='FAIL')} failing)")
print(f" Findings : {len(findings)}")
print(f" File size : {size_kb} KB")
print(f"\n Report written to: {output_path}")
print(f"{'='*56}\n")
finally:
os.unlink(tmp_path)
def main():
parser = argparse.ArgumentParser(
description="Generate a professional compliance audit report (.docx) from CSV reports",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python generate_audit_report.py
python generate_audit_report.py --client "Acme Corp" --auditor "J. Smith"
python generate_audit_report.py --reports-dir reports --output reports/audit_report.docx
GitHub Actions usage (after generate_report.py):
- name: Generate audit report
run: |
npm install -g docx
python generate_audit_report.py \\
--reports-dir reports \\
--client "${{ vars.CLIENT_NAME || 'Internal Assessment' }}"
"""
)
parser.add_argument("--reports-dir", default="reports", help="Directory with CSV reports (default: reports)")
parser.add_argument("--output", default=None, help="Output .docx path (default: <reports-dir>/audit_report.docx)")
parser.add_argument("--client", default="[Company Name]", help="Client or organisation name for the cover page")
parser.add_argument("--auditor", default="[Sharifa S.]", help="Auditor name for the cover page")
parser.add_argument("--period", default=None, help="Assessment period string (default: auto-generated from current date)")
parser.add_argument("--region", default="us-east-1", help="AWS region (default: us-east-1)")
parser.add_argument("--classification", default="CONFIDENTIAL", help="Document classification label (default: CONFIDENTIAL)")
args = parser.parse_args()
if args.period is None:
# Default: "Week ending <date>"
args.period = "Week ending " + datetime.now(timezone.utc).strftime("%B %d, %Y")
generate(args)
if __name__ == "__main__":
main()