Abstract
Automated Program Repair (APR) is increasingly used for vulnerability patching, yet many existing methods focus primarily on syntactic similarity between vulnerable and fixed code, with limited guarantees of semantic correctness and limited alignment with security frameworks. This work presents a prototype-based deep metric learning method for vulnerability repair that integrates normative constraints from OWASP and NIST SSDF. The method combines embeddings of vulnerable code and CWE descriptions, refines category prototypes to improve separation among CWE types, and validates repairs against statement-level control requirements derived from the normative mapping. Experiments on 959 vulnerable–fixed pairs across Python, Java, C, and C++ covering 15 CWE categories achieved a Match Ratio of 88.95%, 0.81 compliance, and 0.84 consistency.
1. Introduction
Cybersecurity has become an essential pillar for safeguarding organizational information technology assets, spanning multiple fronts: the human factor, defensive operations, offensive operations, and regulatory and legal compliance. Within the defensive and compliance domains, the Secure Software Development Life Cycle (SSDLC) plays a central role in the early detection of flaws, from requirements engineering and design to continuous integration and deployment (CI/CD) [1]. This approach drives sustained improvements in software quality, which is particularly important given that, according to the European Union Agency for Cybersecurity (ENISA) [2], poor development practices maintain persistent exposure to vulnerabilities, with notable impact on production systems in sectors such as transport, healthcare, education, and government.
APR has emerged in recent years as a relevant research line within Natural Language Processing, positioning itself as a complementary alternative to traditional static and dynamic analysis. Its momentum largely stems from the use of Large Language Models (LLMs), which can identify risk patterns and propose automated code corrections. In this context, encoder-based models are commonly used to localize potentially vulnerable regions in code; encoder–decoder architectures are used to model and generate concrete modifications on specific fragments; and decoder-only models, supported by retrieval and prompt engineering with reasoning chains, can produce complete repairs or targeted patches for the vulnerable portion [3].
However, much of the state-of-the-art [4,5,6] in APR assumes that the problem is limited to transforming a vulnerable region and contrasting it with its secure counterpart, which requires abundant and consistent vulnerable–fixed pairs and tends to prioritize textual similarity over semantic stability and verifiability. This formulation often yields heterogeneous repairs within the same Common Weakness Enumeration (CWE) category, weak discrimination among closely related weaknesses, and no explicit integration of normative criteria to audit satisfied controls and avoided anti-patterns. This work proposes a category- and compliance-driven alternative, where repair is conditioned on CWE-refined prototypes and anchored to a statement-level normative ground truth aligned with control inventories from the Open Worldwide Application Security Project (OWASP) and the National Institute of Standards and Technology (NIST), enabling joint evaluation of semantic correctness and auditable compliance.
2. Methods and Materials
In Figure 1, the workflow of the proposed methodology is presented.
Figure 1.
Proposed system workflow.
2.1. Sample Collection
The National Vulnerability Database (NVD) [7] was consulted to identify the 15 most prevalent CWE types in 2024. Vulnerable–fixed code pairs were collected from CVEfixes v1.0.8 for Python [8,9], Software Vulnerability Datasets and Vulnerability Fix Dataset for Java [10,11], and Juliet Test Suite v1.3 from the Software Assurance Reference Dataset (SARD) for C/C++ [12]. The Java sources do not specify a single language version, and the Python source corresponds to a multi-project dataset release rather than to a fixed interpreter version. Each sample is aligned with its CWE and linked to technical metadata from the CWE taxonomy [13]. Secure fragments are validated through Static Application Security Testing (SAST) using Semgrep [14] and OWASP Dependency-Check [15]. Normative controls are mapped per fix using the Secure Software Development Framework (SSDF) from NIST SP 800-218 [16] and OWASP controls [17]. Each sample i contains the vulnerable code snippet and the fixed code snippet used as the ground-truth reference, the CWE identifier , the CWE weakness description , the required control set specifying controls that must be present in a valid fix, and the forbidden control set specifying anti-patterns and insecure practices that must be absent, enforcing . The dataset includes 959 samples: 437 in Python (45.6%), 312 in Java (32.5%), and 210 in C/C++ (21.9%), covering the 15 most prevalent CWE categories, including CWE-79, CWE-89, CWE-78, CWE-22, CWE-287, CWE-798, CWE-434, CWE-352, CWE-862, and CWE-200.
2.2. Data Architecture Stage
Preprocessing transforms the raw source-code snippets into normalized forms via , which excludes comments and redundant whitespace to retain only semantically relevant information. Next, each normalized s is segmented into syntactic statements , where each is a syntactically valid unit and the concatenation reconstructs the original snippet. For embedding generation, a shared CodeBERT encoder is used, where denotes the set of finite sequences of tokens produced by the CodeBERT tokenizer. For sample i, the vulnerable-code embedding is defined as and the CWE-description embedding as , where uses the CLS token representation to capture global information through multi-head attention. The final representation is obtained by concatenating both embeddings, .
Representative prototypes are constructed for each vulnerability category in the dataset. Let K denote the number of categories, and for a particular category c, let be the index set of samples whose label equals c, and let be its cardinality. The initial prototype for category c, denoted , is defined as the centroid of the category embeddings and is computed as the arithmetic mean of the vectors for all , as given in Equation (1).
Here, the centroid lies in and constitutes the -optimal representative for category c, as it minimizes the within-category sum of squared Euclidean distances over all candidate prototype vectors p. Prototype quality at initialization is summarized by the separation ratio , where is the mean Euclidean distance between initial prototypes from distinct categories and is the mean Euclidean distance from each embedding to its assigned initial prototype , averaged across categories. Values indicate that inter-category separation dominates within-category dispersion.
Prototype refinement is performed by minimizing a combined objective that increases inter-category separation while reducing within-category dispersion, initialized from the centroid-based prototypes . Here, N is the number of training samples and the prototype set is treated as a trainable parameterization in , initialized with and then updated through gradient-based optimization. Since a desirable configuration satisfies , refinement minimizes a loss that jointly promotes separation and compactness.
Therefore, the total loss is defined in Equation (2) as a weighted sum of Additive Margin Softmax (AMS) [18] and Proxy Neighborhood Components Analysis (ProxyNCA) [19], with weights and set to . In Equation (3), AMS enforces angular separation on the unit hypersphere using , additive margin radians, and scale factor . In Equation (4), ProxyNCA promotes within-category compactness by contrasting squared Euclidean distances with temperature over all K prototypes. Minimizing Equation (2) updates both the shared encoder and the prototype set from to the refined prototypes used in subsequent assignment and ranking stages.
After refinement, the refined prototype set is ranked using the score in Equation (5), which prioritizes assignment accuracy while still rewarding coverage. Let denote the nearest-category assignment induced by the refined prototypes for validation sample i. For each category c, let be the set of validation samples assigned to the prototype . Coverage is defined as , and assignment accuracy is defined as .
To construct the normative ground truth for a sample i with category label , a statement-level diff is computed between the vulnerable snippet and its secure counterpart ; this ground-truth statement set is later queried by the repair policy conditioned on the winning refined prototype , selected from the top-k ranked prototypes by maximizing the prototype score . Let denote the set of syntactic statements extracted from snippet s. Additions are defined as , removals as , and modifications as , where u is a vulnerable-side statement and v is its secure-side counterpart. The final normative statement set merges fully new secure statements with the secure-side revisions of modified statements, as defined in Equation (6).
In Equation (6), is the set of normative statements that constitute the ground-truth repair actions for the sample, namely, statements that must appear in the repaired code either as insertions from or as secure-side replacements selected from . Each normative statement is associated with a binary control vector over the OWASP and NIST control inventories introduced earlier: for an OWASP index , marks control a as required for , and for a NIST index , marks the forbidden pattern associated with control r as disallowed when realizing .
2.3. Vulnerability Fixing Stage
Repair quality is assessed using three complementary metrics capturing semantic correctness, normative compliance, and intra-category consistency. Let denote the number of evaluated samples. For each sample , the system outputs a repaired snippet , which is evaluated against the dataset secure reference . Match ratio is defined in Equation (7) and measures the fraction of repairs that are semantically equivalent to the secure reference, where semantic equivalence requires identical outputs for any admissible input in the input domain Inputs.
Compliance is defined in Equation (8) and measures adherence to the per-sample normative control sets provided by the dataset, namely the required set and the forbidden set . For each evaluated repair , denotes the subset of required controls satisfied by the repair, and denotes the subset of forbidden controls whose associated insecure patterns are absent in the repair, using the same control-mapping procedure applied during dataset construction.
Consistency is defined in Equations (9) and (10) and measures whether repairs associated with the same selected prototype exhibit coherent patch patterns. Let be the category indices of the selected top-k prototypes in ranked order, and for each let be the index set of evaluated samples whose winning category equals . For each sample i, denotes the patch extracted from the pair , and denotes the reference patch pattern for category computed as the most frequent patch among samples in . In Equation (9), Bilingual Evaluation Understudy (BLEU) measures lexical similarity via n-gram overlap, and Abstract Syntax Tree (AST) similarity measures structural similarity by comparing the abstract syntax trees of the generated fix and the ground-truth fix. The system is considered successful when the thresholds in Equation (11) are simultaneously satisfied.
Finally, the system is considered successful when all three criteria are met simultaneously: , , and .
3. Results and Discussion
Across programming languages in the dataset, the system meets the Match Ratio threshold in all languages. Python achieves the highest Match Ratio (96.6%), followed by C (94.6%), C++ (83.1%), and Java (81.5%). Compliance exceeds the 0.85 threshold for Python and C (both at 0.92) but falls below it for Java (0.71) and C++ (0.69). Global consistency surpasses the 0.70 threshold across all languages, ranging from 0.73 in C++ to 0.95 in Python.
As shown in Table 1, all languages exhibit strong performance on CWE-798 (Hard-coded Credentials), CWE-78 (OS Command Injection), and CWE-89 (SQL Injection), where the required mitigations generally involve localized code modifications, such as removing embedded credentials in CWE-798 or applying input sanitization at parameter-entry points in CWE-78 and CWE-89. By contrast, CWE-862 (Missing Authorization) is more challenging in C++, as authorization checks may be dispersed across header files, framework-level mechanisms, and preprocessor directives, which obscures control mapping and lowers Compliance.
Table 1.
Performance metrics by programming language.
Differences across languages track structural complexity and validation clarity. Python attains the highest scores (Match Ratio (%) = 96.6, Compliance = 0.92, Consistencyglobal = 0.95), aided by explicit syntax and standard-library conventions that simplify rule-based validation. C matches Python in Compliance (0.92) but shows lower Consistencyglobal (0.90), reflecting multiple implementation patterns that satisfy the same controls. Java and C++ obtain lower Compliance (0.71 and 0.69), consistent with framework-dependent authorization and library-specific APIs that complicate normative-control mapping.
Only Python meets all three thresholds simultaneously (Match Ratio (%) , Compliance , Consistencyglobal ). Java and C++ exceed the thresholds for Match Ratio (%) and Consistencyglobal, but fall short on Compliance, suggesting that repair patterns are captured adequately while control mapping requires more language- and framework-aware handling.
The comparative analysis in Table 2 evaluates the proposed method against three state-of-the-art approaches in terms of programming language support, algorithmic paradigm, empirical performance, and integration of normative compliance. The comparison reveals three main gaps in the literature and the corresponding mechanisms incorporated in the proposed approach. Huang et al. [4] report 64.71% BLEU under sequence-to-sequence fine-tuning (NMT + CodeT5 + UniXcoder + PLBART); however, the absence of an explicit category-separation objective may allow heterogeneous repairs across closely related CWE categories. By contrast, prototype refinement with AMS and ProxyNCA promotes inter-category separation and intra-category compactness, yielding more stable category-conditioned repair under the selected refined prototype. VulD-Transformer [5] achieves 80.44% accuracy using Transformer encoders and FastText embeddings, yet its single-view representation and the lack of metric-learning refinement limit inter-category discriminability. In contrast, the dual-context representation is refined through the same prototype-based metric-learning objective, improving category resolution under nearest-prototype assignment. Finally, de Fitero-Dominguez et al. [6] report 26% perfect predictions with quantized LLMs (Code Llama + Mistral (QLoRA)), suggesting performance degradation when repair is not guided by structured refinement and verification signals. In contrast, the proposed repairs are constrained by a statement-level normative ground truth aligned with and , enabling auditable compliance under the dataset control mapping.
Table 2.
Comparison with related works in vulnerability detection and repair.
4. Conclusions
This work presented a prototype-based deep metric learning approach for automated vulnerability repair that integrates compliance constraints from OWASP and NIST SSDF. The method combines embeddings of vulnerable code and CWE descriptions, refines category prototypes, and validates repairs against statement-level control requirements. Evaluation on 959 samples across Python, Java, C, and C++ covering 15 CWE categories achieved a Match Ratio of 88.95%, together with 0.81 compliance and 0.84 consistency. Python satisfied all success thresholds simultaneously, while Java and C++ showed reduced compliance due to framework-dependent authorization patterns. Comparative analysis indicated that existing approaches lack normative integration and explicit category separation. The proposed framework addresses these limitations through dual-context embeddings, metric-learning refinement, and enforcement of required and forbidden control sets, enabling compliance verification. Future work will integrate LangChain for orchestration and historical repair memory, and implement the Model Context Protocol for CI/CD pipeline integration. Additional directions include extending control mapping for framework-dependent patterns and evaluating scalability on industrial codebases.
Author Contributions
Conceptualization, A.H.-S., G.S.-P., A.W. and M.P.-C.; methodology, A.H.-S., G.S.-P., A.W. and M.P.-C.; software, A.H.-S.; validation, A.H.-S., L.K.T.-M., H.P.-M., J.O.M., A.W. and M.P.-C.; formal analysis, A.H.-S., H.P.-M., A.W. and M.P.-C.; investigation, A.H.-S., A.W. and M.P.-C.; resources, G.S.-P., H.P.-M., A.W. and M.P.-C.; data curation, A.H.-S. and J.O.M.; writing—original draft preparation, A.H.-S.; writing—review and editing, G.S.-P., L.K.T.-M., H.P.-M., J.O.M., A.W. and M.P.-C.; visualization, A.H.-S., A.W. and M.P.-C.; supervision, G.S.-P., H.P.-M., A.W. and M.P.-C.; project administration, G.S.-P.; funding acquisition, H.P.-M. All authors have read and agreed to the published version of the manuscript.
Funding
This research received no external funding.
Institutional Review Board Statement
Not applicable.
Informed Consent Statement
Not applicable.
Data Availability Statement
All supporting data are included within the manuscript, and additional inquiries are welcome.
Conflicts of Interest
The authors declare no conflicts of interest.
References
- Zhang, J.; Bu, H.; Wen, H.; Liu, Y.; Fei, H.; Xi, R.; Li, L.; Yang, Y.; Zhu, H.; Meng, D. When LLMs Meet Cybersecurity: A Systematic Literature Review. Cybersecurity 2025, 8, 55. [Google Scholar] [CrossRef] [Scilit]
- European Union Agency for Cybersecurity (ENISA). ENISA Threat Landscape 2025; Technical report; ENISA: Athens, Greece, 2025. [Google Scholar]
- Taghavi Far, S.M.; Feyzi, F. Large Language Models for Software Vulnerability Detection: A Guide for Researchers on Models, Methods, Techniques, Datasets, and Metrics. Int. J. Inf. Secur. 2025, 24, 78. [Google Scholar] [CrossRef] [Scilit]
- Huang, K.; Meng, X.; Zhang, J.; Liu, Y.; Wang, W.; Li, S.; Zhang, Y. An Empirical Study on Fine-Tuning Large Language Models of Code for Automated Program Repair. In Proceedings of the 2023 38th IEEE/ACM International Conference on Automated Software Engineering (ASE); IEEE: Piscataway, NJ, USA, 2023; pp. 1162–1174. [Google Scholar]
- Zhang, X.; Zhang, F.; Zhao, B.; Zhou, B.; Xiao, B. VulD-Transformer: Source Code Vulnerability Detection via Transformer. In Proceedings of the 14th Asia-Pacific Symposium on Internetware, Hangzhou, China, 4–6 August 2023; pp. 185–193. [Google Scholar]
- de Fitero-Dominguez, D.; Garcia-Lopez, E.; Garcia-Cabot, A.; Martinez-Herraiz, J.J. Enhanced Automated Code Vulnerability Repair Using Large Language Models. Eng. Appl. Artif. Intell. 2024, 138, 109291. [Google Scholar] [CrossRef] [Scilit]
- National Institute of Standards and Technology. National Vulnerability Database (NVD). Available online: https://nvd.nist.gov/ (accessed on 5 September 2025).
- Bhandari, G.; Naseer, A.; Moonen, L. CVEfixes: Automated Collection of Vulnerabilities and Their Fixes from Open-Source Software. In Proceedings of the 17th International Conference on Predictive Models and Data Analytics in Software Engineering; ACM: New York, NY, USA, 2021; pp. 30–39. [Google Scholar]
- Girish17019. CVEfixes: Vulnerable and Fixed Code Dataset. Available online: https://www.kaggle.com/datasets/girish17019/cvefixes-vulnerable-and-fixed-code (accessed on 5 September 2025).
- Vulnerability Dataset Project. Software Vulnerability Datasets. Available online: https://github.com/vulnerability-dataset/software-vulnerability-datasets (accessed on 5 September 2025).
- JISC ECSE AI/ML. Vulnerability Fix Dataset. Available online: https://www.kaggle.com/datasets/jiscecseaiml/vulnerability-fix-dataset (accessed on 5 September 2025).
- National Institute of Standards and Technology. Software Assurance Reference Dataset (SARD). Available online: https://samate.nist.gov/SARD/ (accessed on 5 September 2025).
- MITRE Corporation. Common Weakness Enumeration (CWE). Available online: https://cwe.mitre.org/ (accessed on 5 September 2025).
- Semgrep, Inc. Semgrep Community Edition. Available online: https://semgrep.dev/products/community-edition/ (accessed on 5 September 2025).
- OWASP Foundation. OWASP Dependency-Check. Available online: https://owasp.org/www-project-dependency-check/ (accessed on 5 September 2025).
- National Institute of Standards and Technology. Secure Software Development Framework (SSDF) Version 1.1: Recommendations for Mitigating the Risk of Software Vulnerabilities; Technical Report NIST SP 800-218; NIST: Gaithersburg, MD, USA, 2022. [Google Scholar]
- OWASP Foundation. OWASP Security Controls. Available online: https://owasp.org/www-community/controls/ (accessed on 5 September 2025).
- Alirezazadeh, P.; Dornaika, F.; Moujahid, A. Cosine Additive Angular Margin Loss for Breast Cancer Classification in Histopathological Images with Small AI Systems. ACM Trans. Intell. Syst. Technol. 2025. [Google Scholar] [CrossRef] [Scilit]
- Elghandour, M. PCA-NCA Based VIT Features for Classification of White Blood Cell Images. J. Supercomput. 2025, 81, 1278. [Google Scholar] [CrossRef] [Scilit]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content. |
© 2026 by the authors. Licensee MDPI, Basel, Switzerland. This article is an open access article distributed under the terms and conditions of the Creative Commons Attribution (CC BY) license.
