repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/report-configuration.go
pkg/report/report-configuration.go
package report type ChaptersToShowHide string const ( RiskRulesCheckedByThreagile ChaptersToShowHide = "RiskRulesCheckedByThreagile" AssetRegister ChaptersToShowHide = "AssetRegister" ) type ReportConfiguation struct { HideChapter map[ChaptersToShowHide]bool }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/adocReport.go
pkg/report/adocReport.go
package report import ( "fmt" "image" "io" "log" "os" "path/filepath" "regexp" "sort" "strconv" "strings" "time" "github.com/threagile/threagile/pkg/types" "golang.org/x/text/cases" "golang.org/x/text/language" ) type adocReport struct { targetDirectory string model *types.Model mainFile *os.File imagesDir string riskRules types.RiskRules iconsType string tocDepth int hideEmptyChapter bool } func copyFile(source string, destination string) error { /* #nosec source is not tainted (see caller restricting it to files we created ourself or are legitimate to be copied) */ src, err := os.Open(source) if err != nil { return err } defer func() { _ = src.Close() }() /* #nosec destination is not tainted (see caller restricting it to the desired report output folder) */ dst, err := os.Create(destination) if err != nil { return err } defer func() { _ = dst.Close() }() _, err = io.Copy(dst, src) if err != nil { return err } return nil } func fixBasicHtml(inputWithHtml string) string { result := strings.ReplaceAll(inputWithHtml, "<b>", "*") result = strings.ReplaceAll(result, "</b>", "*") result = strings.ReplaceAll(result, "<i>", "_") result = strings.ReplaceAll(result, "</i>", "_") result = strings.ReplaceAll(result, "<u>", "[.underline]#") result = strings.ReplaceAll(result, "</u>", "#") result = strings.ReplaceAll(result, "<br>", "\n") result = strings.ReplaceAll(result, "</br>", "\n") linkAndName := regexp.MustCompile(`<a href=\"(.*)\".*>(.*)</a>`) result = linkAndName.ReplaceAllString(result, "${1}[${2}]") return result } func NewAdocReport(targetDirectory string, riskRules types.RiskRules, hideEmptyChapter bool) adocReport { adoc := adocReport{ targetDirectory: filepath.Join(targetDirectory, "adocReport"), iconsType: "font", tocDepth: 2, imagesDir: filepath.Join(targetDirectory, "adocReport", "images"), riskRules: riskRules, hideEmptyChapter: hideEmptyChapter, } return adoc } func writeLine(file *os.File, line string) { _, err := file.WriteString(line + "\n") if err != nil { log.Fatal("Could not write »" + line + "« into: " + file.Name() + ": " + err.Error()) } } func (adoc adocReport) writeDefaultTheme(logoImagePath string) error { err := os.MkdirAll(filepath.Join(adoc.targetDirectory, "theme"), 0750) if err != nil { return err } err = os.MkdirAll(adoc.imagesDir, 0750) if err != nil { return err } theme, err := os.Create(filepath.Join(adoc.targetDirectory, "theme", "pdf-theme.yml")) defer func() { _ = theme.Close() }() if err != nil { return err } adocLogoPath := "" if logoImagePath != "" { if _, err := os.Stat(logoImagePath); err == nil { suffix := filepath.Ext(logoImagePath) adocLogoPath = "logo" + suffix logoDestPath := filepath.Join(adoc.targetDirectory, "theme", adocLogoPath) err = copyFile(logoImagePath, logoDestPath) if err != nil { log.Fatal("Could not copy file: »" + logoImagePath + "« to »" + logoDestPath + "«: " + err.Error()) } } else { log.Println("logo image path does not exist: " + logoImagePath) } } writeLine(theme, `extends: default page: layout: portrait margin: [3cm, 2.5cm, 2.7cm, 2.5cm] title-page: authors: content: "{author}, {author-homepage}[]" `) if adocLogoPath != "" { writeLine(theme, ` logo: image: image:`+adocLogoPath+`[]`) } writeLine(theme, `header: height: 2cm line-height: 1 recto: center: content: "{document-title} -- `+adoc.model.Title+` -- {section-or-chapter-title}" verso: center: content: "{document-title} -- `+adoc.model.Title+` -- {section-or-chapter-title}" footer: height: 2cm line-height: 1.2 recto: center: content: -- confidential -- left: content: "Version: {DOC_VERSION}" right: content: "Page {page-number} of {page-count}" verso: center: content: -- confidential -- left: content: "Version: {DOC_VERSION}" right: content: Page {page-number} of {page-count} role: LowRisk: font-color: `+rgbHexColorLowRisk()+` MediumRisk: font-color: `+rgbHexColorMediumRisk()+` ElevatedRisk: font-color: `+rgbHexColorElevatedRisk()+` HighRisk: font-color: `+rgbHexColorHighRisk()+` CriticalRisk: font-color: `+rgbHexColorCriticalRisk()+` OutOfScope: font-color: #7f7f7f GreyText: font-color: #505050 LightGreyText: font-color: #646464 ModelFailure: font-color: #945200 RiskStatusFalsePositive: font-color: `+rgbHexColorRiskStatusFalsePositive()+` RiskStatusMitigated: font-color: `+rgbHexColorRiskStatusMitigated()+` RiskStatusInProgress: font-color: `+rgbHexColorRiskStatusInProgress()+` RiskStatusAccepted: font-color: `+rgbHexColorRiskStatusAccepted()+` RiskStatusInDiscussion: font-color: `+rgbHexColorRiskStatusInDiscussion()+` RiskStatusUnchecked: font-color: `+RgbHexColorRiskStatusUnchecked()+` Twilight: font-color: `+rgbHexColorTwilight()+` SmallGrey: font-size: 0.5em font-color: #505050 Silver: font-color: #C0C0C0 `) return nil } func (adoc adocReport) writeMainLine(line string) { writeLine(adoc.mainFile, line) } func (adoc adocReport) WriteReport(model *types.Model, dataFlowDiagramFilenamePNG string, dataAssetDiagramFilenamePNG string, modelFilename string, skipRiskRules []string, buildTimestamp string, threagileVersion string, modelHash string, introTextRAA string, customRiskRules types.RiskRules, logoImagePath string, hideChapters map[ChaptersToShowHide]bool) error { adoc.model = model err := adoc.initReport() if err != nil { return err } err = adoc.writeDefaultTheme(logoImagePath) if err != nil { return err } // err = adoc.createDefaultTheme() FIXME adoc.writeTitleAndPreamble() err = adoc.writeManagementSummery() if err != nil { return err } err = adoc.writeImpactInitialRisks() if err != nil { return fmt.Errorf("error creating impact initial risks: %w", err) } err = adoc.writeRiskMitigationStatus() if err != nil { return fmt.Errorf("error creating risk mitigation status: %w", err) } if val := hideChapters[AssetRegister]; !val { err = adoc.writeAssetRegister() if err != nil { return fmt.Errorf("error creating asset register status: %w", err) } } err = adoc.writeImpactRemainingRisks() if err != nil { return fmt.Errorf("error creating impact remaining risks: %w", err) } err = adoc.writeTargetDescription(filepath.Dir(modelFilename)) if err != nil { return fmt.Errorf("error creating target description: %w", err) } err = adoc.writeDataFlowDiagram(dataFlowDiagramFilenamePNG) if err != nil { return fmt.Errorf("error creating data flow diagram section: %w", err) } err = adoc.writeSecurityRequirements() if err != nil { return fmt.Errorf("error creating security requirements: %w", err) } err = adoc.writeAbuseCases() if err != nil { return fmt.Errorf("error creating abuse cases: %w", err) } err = adoc.writeTagListing() if err != nil { return fmt.Errorf("error creating tag listing: %w", err) } err = adoc.writeSTRIDE() if err != nil { return fmt.Errorf("error creating STRIDE: %w", err) } err = adoc.writeAssignmentByFunction() if err != nil { return fmt.Errorf("error creating assignment by function: %w", err) } err = adoc.writeRAA(introTextRAA) if err != nil { return fmt.Errorf("error creating RAA: %w", err) } err = adoc.writeDataRiskMapping(dataAssetDiagramFilenamePNG) if err != nil { return fmt.Errorf("error creating data risk mapping: %w", err) } err = adoc.writeOutOfScopeAssets() if err != nil { return fmt.Errorf("error creating Out of Scope Assets: %w", err) } err = adoc.writeModelFailures() if err != nil { return fmt.Errorf("error creating model failures: %w", err) } err = adoc.writeQuestions() if err != nil { return fmt.Errorf("error creating questions: %w", err) } err = adoc.writeRiskCategories() if err != nil { return fmt.Errorf("error creating risk categories: %w", err) } err = adoc.writeTechnicalAssets() if err != nil { return fmt.Errorf("error creating technical assets: %w", err) } err = adoc.writeDataAssets() if err != nil { return fmt.Errorf("error creating data assets: %w", err) } err = adoc.writeTrustBoundaries() if err != nil { return fmt.Errorf("error creating trust boundaries: %w", err) } err = adoc.writeSharedRuntimes() if err != nil { return fmt.Errorf("error creating shared runtimes: %w", err) } if val := hideChapters[RiskRulesCheckedByThreagile]; !val { err = adoc.writeRiskRulesChecked(modelFilename, skipRiskRules, buildTimestamp, threagileVersion, modelHash, customRiskRules) if err != nil { return fmt.Errorf("error creating risk rules checked: %w", err) } } err = adoc.writeAppendixRating() if err != nil { return fmt.Errorf("error creating appendix for the rating mappings") } err = adoc.writeDisclaimer() if err != nil { return fmt.Errorf("error creating disclaimer: %w", err) } return nil } func (adoc *adocReport) initReport() error { _ = os.RemoveAll(adoc.targetDirectory) err := os.MkdirAll(adoc.targetDirectory, 0750) if err != nil { return err } adoc.mainFile, err = os.Create(filepath.Join(adoc.targetDirectory, "000_main.adoc")) if err != nil { return err } return nil } func (adoc adocReport) writeTitleAndPreamble() { adoc.writeMainLine("= Threat Model Report: " + adoc.model.Title) adoc.writeMainLine(":title-page:") adoc.writeMainLine(":author: " + adoc.model.Author.Name) if strings.HasPrefix(adoc.model.Author.Homepage, "http") { adoc.writeMainLine(`:author-homepage: ` + adoc.model.Author.Homepage) } else { adoc.writeMainLine(`:author-homepage: https://` + adoc.model.Author.Homepage) } adoc.writeMainLine(":email: " + adoc.model.Author.Contact) adoc.writeMainLine(":toc:") adoc.writeMainLine(":toclevels: " + strconv.Itoa(adoc.tocDepth)) adoc.writeMainLine(":icons: " + adoc.iconsType) reportDate := adoc.model.Date if reportDate.IsZero() { reportDate = types.Date{Time: time.Now()} } adoc.writeMainLine(":revdate: " + reportDate.Format("2 January 2006")) adoc.writeMainLine("") } func (adoc adocReport) writeManagementSummery() error { filename := "010_ManagementSummary.adoc" ms, err := os.Create(filepath.Join(adoc.targetDirectory, filename)) defer func() { _ = ms.Close() }() if err != nil { return err } adoc.writeMainLine("include::" + filename + "[leveloffset=+1]") writeLine(ms, "= Management Summary") writeLine(ms, "") writeLine(ms, "Threagile toolkit was used to model the architecture of \""+adoc.model.Title+"\" and derive risks by analyzing the components and data flows.") writeLine(ms, "The risks identified during this analysis are shown in the following chapters.") writeLine(ms, "Identified risks during threat modeling do not necessarily mean that the "+ "vulnerability associated with this risk actually exists: it is more to be seen as a list"+ " of potential risks and threats, which should be individually reviewed and reduced by removing false positives.") writeLine(ms, "For the remaining risks it should be checked in the design and implementation of \""+adoc.model.Title+"\" whether the mitigation advices have been applied or not.") writeLine(ms, "\n\n") writeLine(ms, "Each risk finding references a chapter of the OWASP ASVS (Application Security Verification Standard) audit checklist.") writeLine(ms, "The OWASP ASVS checklist should be considered as an inspiration by architects and developers to further harden the application in a Defense-in-Depth approach.") writeLine(ms, "Additionally, for each risk finding a link towards a matching OWASP Cheat Sheet or similar with technical details about how to implement a mitigation is given.") writeLine(ms, "\n\n") writeLine(ms, "In total *"+strconv.Itoa(totalRiskCount(adoc.model))+" initial risks* in *"+strconv.Itoa(len(adoc.model.GeneratedRisksByCategory))+" categories* have been identified during the threat modeling process:") writeLine(ms, "\n\n") countCritical := len(filteredBySeverity(adoc.model, types.CriticalSeverity)) countHigh := len(filteredBySeverity(adoc.model, types.HighSeverity)) countElevated := len(filteredBySeverity(adoc.model, types.ElevatedSeverity)) countMedium := len(filteredBySeverity(adoc.model, types.MediumSeverity)) countLow := len(filteredBySeverity(adoc.model, types.LowSeverity)) countStatusUnchecked := len(filteredByRiskStatus(adoc.model, types.Unchecked)) countStatusInDiscussion := len(filteredByRiskStatus(adoc.model, types.InDiscussion)) countStatusAccepted := len(filteredByRiskStatus(adoc.model, types.Accepted)) countStatusInProgress := len(filteredByRiskStatus(adoc.model, types.InProgress)) countStatusMitigated := len(filteredByRiskStatus(adoc.model, types.Mitigated)) countStatusFalsePositive := len(filteredByRiskStatus(adoc.model, types.FalsePositive)) pieCharts := `[cols="a,a",frame=none,grid=none] |=== | [mermaid] .... %%{init: {'pie' : {'textPosition' : 0.5}, 'theme': 'base', 'themeVariables': { 'pie1': '` + rgbHexColorCriticalRisk() + `', 'pie2': '` + rgbHexColorHighRisk() + `', 'pie3': '` + rgbHexColorElevatedRisk() + `', 'pie4': '` + rgbHexColorMediumRisk() + `', 'pie5': '` + rgbHexColorLowRisk() + `'}}}%% pie showData "critical risk" : ` + strconv.Itoa(countCritical) + ` "high risk" : ` + strconv.Itoa(countHigh) + ` "elevated risk" : ` + strconv.Itoa(countElevated) + ` "medium risk" : ` + strconv.Itoa(countMedium) + ` "low risk" : ` + strconv.Itoa(countLow) + ` .... | [mermaid] .... %%{init: {'pie' : {'textPosition' : 0.5}, 'theme': 'base', 'themeVariables': { 'pie1': '` + RgbHexColorRiskStatusUnchecked() + `', 'pie2': '` + rgbHexColorRiskStatusInDiscussion() + `', 'pie3': '` + rgbHexColorRiskStatusAccepted() + `', 'pie4': '` + rgbHexColorRiskStatusInProgress() + `', 'pie5': '` + rgbHexColorRiskStatusMitigated() + `', 'pie5': '` + rgbHexColorRiskStatusFalsePositive() + `'}}}%% pie showData "unchecked" : ` + strconv.Itoa(countStatusUnchecked) + ` "in discussion" : ` + strconv.Itoa(countStatusInDiscussion) + ` "accepted" : ` + strconv.Itoa(countStatusAccepted) + ` "in progress" : ` + strconv.Itoa(countStatusInProgress) + ` "mitigated" : ` + strconv.Itoa(countStatusMitigated) + ` "false positive" : ` + strconv.Itoa(countStatusFalsePositive) + ` .... |=== ` writeLine(ms, pieCharts) // individual management summary comment if len(adoc.model.ManagementSummaryComment) > 0 { writeLine(ms, "\n\n\n"+fixBasicHtml(adoc.model.ManagementSummaryComment)) } return nil } func colorPrefixBySeverity(severity types.RiskSeverity, smallFont bool) (string, string) { start := "" switch severity { case types.CriticalSeverity: start = "[.CriticalRisk" case types.HighSeverity: start = "[.HighRisk" case types.ElevatedSeverity: start = "[.ElevatedRisk" case types.MediumSeverity: start = "[.MediumRisk" case types.LowSeverity: start = "[.LowRisk" default: return "", "" } if smallFont { start += ".small" } return start + "]#", "#" } func colorPrefixByDataBreachProbability(probability types.DataBreachProbability, smallFont bool) (string, string) { switch probability { case types.Probable: return colorPrefixBySeverity(types.HighSeverity, smallFont) case types.Possible: return colorPrefixBySeverity(types.MediumSeverity, smallFont) case types.Improbable: return colorPrefixBySeverity(types.LowSeverity, smallFont) default: return "", "" } } func titleOfSeverity(severity types.RiskSeverity) string { switch severity { case types.CriticalSeverity: return "Critical Risk Severity" case types.HighSeverity: return "High Risk Severity" case types.ElevatedSeverity: return "Elevated Risk Severity" case types.MediumSeverity: return "Medium Risk Severity" case types.LowSeverity: return "Low Risk Severity" default: return "" } } func riskSuffix(remainingRisks int, totalRisks int) string { suffix := "" if remainingRisks > 0 { suffix = strconv.Itoa(remainingRisks) + "/" + strconv.Itoa(totalRisks) + " unmitigated Risk" } else { suffix = strconv.Itoa(totalRisks) + " mitigated Risk" } if totalRisks != 1 { suffix += "s" } return suffix } func (adoc adocReport) addCategories(f *os.File, risksByCategory map[string][]*types.Risk, initialRisks bool, severity types.RiskSeverity, bothInitialAndRemainingRisks bool, describeDescription bool) { describeImpact := true riskCategories := getRiskCategories(adoc.model, reduceToSeverityRisk(risksByCategory, initialRisks, severity)) sort.Sort(types.ByRiskCategoryTitleSort(riskCategories)) for _, riskCategory := range riskCategories { risksStr := risksByCategory[riskCategory.ID] if !initialRisks { risksStr = types.ReduceToOnlyStillAtRisk(risksStr) } if len(risksStr) == 0 { continue } var prefix string colorPrefix, colorSuffix := colorPrefixBySeverity(severity, false) switch severity { case types.CriticalSeverity: prefix = "Critical: " case types.HighSeverity: prefix = "High: " case types.ElevatedSeverity: prefix = "Elevated: " case types.MediumSeverity: prefix = "Medium: " case types.LowSeverity: prefix = "Low: " default: prefix = "" } if len(types.ReduceToOnlyStillAtRisk(risksStr)) == 0 { colorPrefix = "" colorSuffix = "" } fullLine := "<<" + riskCategory.ID + "," + colorPrefix + prefix + "*" + riskCategory.Title + "*: " count := len(risksStr) initialStr := "Initial" if !initialRisks { initialStr = "Remaining" } remainingRisks := types.ReduceToOnlyStillAtRisk(risksStr) suffix := strconv.Itoa(count) + " " + initialStr + " Risk" if count != 1 { suffix += "s" } if bothInitialAndRemainingRisks { suffix = riskSuffix(len(remainingRisks), count) } suffix += " - Exploitation likelihood is _" if initialRisks { suffix += highestExploitationLikelihood(risksStr).Title() + "_ with _" + highestExploitationImpact(risksStr).Title() + "_ impact." } else { suffix += highestExploitationLikelihood(remainingRisks).Title() + "_ with _" + highestExploitationImpact(remainingRisks).Title() + "_ impact." } fullLine += suffix + colorSuffix + ">>::" writeLine(f, fullLine) if describeImpact { writeLine(f, firstParagraph(riskCategory.Impact)) } else if describeDescription { writeLine(f, firstParagraph(riskCategory.Description)) } else { writeLine(f, firstParagraph(riskCategory.Mitigation)) } writeLine(f, "") } } func (adoc adocReport) impactAnalysis(f *os.File, initialRisks bool) int { count := 0 catCount := 0 initialStr := "" if initialRisks { count = totalRiskCount(adoc.model) catCount = len(adoc.model.GeneratedRisksByCategory) initialStr = "initial" } else { count = len(filteredByStillAtRisk(adoc.model)) catCount = len(reduceToOnlyStillAtRisk(adoc.model.GeneratedRisksByCategoryWithCurrentStatus())) initialStr = "remaining" } riskText := "risks" if count == 1 { riskText = "risk" } catText := "categories" if catCount == 1 { catText = "category" } titleCaser := cases.Title(language.English) chapTitle := titleCaser.String("= Impact Analysis of " + strconv.Itoa(count) + " " + initialStr + " " + riskText + " in " + strconv.Itoa(catCount) + " " + catText) writeLine(f, chapTitle) writeLine(f, ":fn-risk-findings: footnote:riskfinding[Risk finding paragraphs are clickable and link to the corresponding chapter.]") writeLine(f, "The most prevalent impacts of the *"+strconv.Itoa(count)+" "+initialStr+" "+riskText+"*"+ " (distributed over *"+strconv.Itoa(catCount)+" risk categories*) are "+ "(taking the severity ratings into account and using the highest for each category)!{fn-risk-findings}") writeLine(f, "") adoc.addCategories(f, adoc.model.GeneratedRisksByCategoryWithCurrentStatus(), initialRisks, types.CriticalSeverity, false, false) adoc.addCategories(f, adoc.model.GeneratedRisksByCategoryWithCurrentStatus(), initialRisks, types.HighSeverity, false, false) adoc.addCategories(f, adoc.model.GeneratedRisksByCategoryWithCurrentStatus(), initialRisks, types.ElevatedSeverity, false, false) adoc.addCategories(f, adoc.model.GeneratedRisksByCategoryWithCurrentStatus(), initialRisks, types.MediumSeverity, false, false) adoc.addCategories(f, adoc.model.GeneratedRisksByCategoryWithCurrentStatus(), initialRisks, types.LowSeverity, false, false) return count } func (adoc adocReport) writeImpactInitialRisks() error { filename := "020_ImpactIntialRisks.adoc" ir, err := os.Create(filepath.Join(adoc.targetDirectory, filename)) defer func() { _ = ir.Close() }() if err != nil { return err } adoc.writeMainLine("<<<") adoc.writeMainLine("include::" + filename + "[leveloffset=+1]") adoc.impactAnalysis(ir, true) return nil } func (adoc adocReport) riskMitigationStatus(f *os.File) { writeLine(f, "= Risk Mitigation") writeLine(f, "The following chart gives a high-level overview of the risk tracking status (including mitigated risks):") risksCritical := filteredBySeverity(adoc.model, types.CriticalSeverity) risksHigh := filteredBySeverity(adoc.model, types.HighSeverity) risksElevated := filteredBySeverity(adoc.model, types.ElevatedSeverity) risksMedium := filteredBySeverity(adoc.model, types.MediumSeverity) risksLow := filteredBySeverity(adoc.model, types.LowSeverity) countStatusUnchecked := len(filteredByRiskStatus(adoc.model, types.Unchecked)) countStatusInDiscussion := len(filteredByRiskStatus(adoc.model, types.InDiscussion)) countStatusAccepted := len(filteredByRiskStatus(adoc.model, types.Accepted)) countStatusInProgress := len(filteredByRiskStatus(adoc.model, types.InProgress)) countStatusMitigated := len(filteredByRiskStatus(adoc.model, types.Mitigated)) countStatusFalsePositive := len(filteredByRiskStatus(adoc.model, types.FalsePositive)) lowTitle := types.LowSeverity.Title() + " (" + strconv.Itoa(len(risksLow)) + ")" medTitle := types.MediumSeverity.Title() + " (" + strconv.Itoa(len(risksMedium)) + ")" elevatedTitle := types.ElevatedSeverity.Title() + " (" + strconv.Itoa(len(risksElevated)) + ")" highTitle := types.HighSeverity.Title() + " (" + strconv.Itoa(len(risksHigh)) + ")" criticalTitle := types.CriticalSeverity.Title() + " (" + strconv.Itoa(len(risksCritical)) + ")" diagram := ` [vegalite] .... { "width": 400, "$schema": "https://vega.github.io/schema/vega-lite/v4.json", "data": { "values": [ {"risk": "` + lowTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksLow, types.Unchecked))) + `, "status": "Unchecked", "color": "` + RgbHexColorRiskStatusUnchecked() + `"}, {"risk": "` + lowTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksLow, types.InDiscussion))) + `, "status": "InDiscussion", "color": "` + rgbHexColorRiskStatusInDiscussion() + `"}, {"risk": "` + lowTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksLow, types.Accepted))) + `, "status": "Accepted", "color": "` + rgbHexColorRiskStatusAccepted() + `"}, {"risk": "` + lowTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksLow, types.InProgress))) + `, "status": "InProgress", "color": "` + rgbHexColorRiskStatusInProgress() + `"}, {"risk": "` + lowTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksLow, types.Mitigated))) + `, "status": "Mitigated", "color": "` + rgbHexColorRiskStatusMitigated() + `"}, {"risk": "` + lowTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksLow, types.FalsePositive))) + `, "status": "FalsePositive", "color": "` + rgbHexColorRiskStatusFalsePositive() + `"}, {"risk": "` + medTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksMedium, types.Unchecked))) + `, "status": "Unchecked", "color": "` + RgbHexColorRiskStatusUnchecked() + `"}, {"risk": "` + medTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksMedium, types.InDiscussion))) + `, "status": "InDiscussion", "color": "` + rgbHexColorRiskStatusInDiscussion() + `"}, {"risk": "` + medTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksMedium, types.Accepted))) + `, "status": "Accepted", "color": "` + rgbHexColorRiskStatusAccepted() + `"}, {"risk": "` + medTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksMedium, types.InProgress))) + `, "status": "InProgress", "color": "` + rgbHexColorRiskStatusInProgress() + `"}, {"risk": "` + medTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksMedium, types.Mitigated))) + `, "status": "Mitigated", "color": "` + rgbHexColorRiskStatusMitigated() + `"}, {"risk": "` + medTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksMedium, types.FalsePositive))) + `, "status": "FalsePositive", "color": "` + rgbHexColorRiskStatusFalsePositive() + `"}, {"risk": "` + elevatedTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksElevated, types.Unchecked))) + `, "status": "Unchecked", "color": "` + RgbHexColorRiskStatusUnchecked() + `"}, {"risk": "` + elevatedTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksElevated, types.InDiscussion))) + `, "status": "InDiscussion", "color": "` + rgbHexColorRiskStatusInDiscussion() + `"}, {"risk": "` + elevatedTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksElevated, types.Accepted))) + `, "status": "Accepted", "color": "` + rgbHexColorRiskStatusAccepted() + `"}, {"risk": "` + elevatedTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksElevated, types.InProgress))) + `, "status": "InProgress", "color": "` + rgbHexColorRiskStatusInProgress() + `"}, {"risk": "` + elevatedTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksElevated, types.Mitigated))) + `, "status": "Mitigated", "color": "` + rgbHexColorRiskStatusMitigated() + `"}, {"risk": "` + elevatedTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksElevated, types.FalsePositive))) + `, "status": "FalsePositive", "color": "` + rgbHexColorRiskStatusFalsePositive() + `"}, {"risk": "` + highTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksHigh, types.Unchecked))) + `, "status": "Unchecked", "color": "` + RgbHexColorRiskStatusUnchecked() + `"}, {"risk": "` + highTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksHigh, types.InDiscussion))) + `, "status": "InDiscussion", "color": "` + rgbHexColorRiskStatusInDiscussion() + `"}, {"risk": "` + highTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksHigh, types.Accepted))) + `, "status": "Accepted", "color": "` + rgbHexColorRiskStatusAccepted() + `"}, {"risk": "` + highTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksHigh, types.InProgress))) + `, "status": "InProgress", "color": "` + rgbHexColorRiskStatusInProgress() + `"}, {"risk": "` + highTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksHigh, types.Mitigated))) + `, "status": "Mitigated", "color": "` + rgbHexColorRiskStatusMitigated() + `"}, {"risk": "` + highTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksHigh, types.FalsePositive))) + `, "status": "FalsePositive", "color": "` + rgbHexColorRiskStatusFalsePositive() + `"}, {"risk": "` + criticalTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksCritical, types.Unchecked))) + `, "status": "Unchecked", "color": "` + RgbHexColorRiskStatusUnchecked() + `"}, {"risk": "` + criticalTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksCritical, types.InDiscussion))) + `, "status": "InDiscussion", "color": "` + rgbHexColorRiskStatusInDiscussion() + `"}, {"risk": "` + criticalTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksCritical, types.Accepted))) + `, "status": "Accepted", "color": "` + rgbHexColorRiskStatusAccepted() + `"}, {"risk": "` + criticalTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksCritical, types.InProgress))) + `, "status": "InProgress", "color": "` + rgbHexColorRiskStatusInProgress() + `"}, {"risk": "` + criticalTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksCritical, types.Mitigated))) + `, "status": "Mitigated", "color": "` + rgbHexColorRiskStatusMitigated() + `"}, {"risk": "` + criticalTitle + `", "value": ` + strconv.Itoa(len(reduceToRiskStatus(risksCritical, types.FalsePositive))) + `, "status": "FalsePositive", "color": "` + rgbHexColorRiskStatusFalsePositive() + `"} ] }, "mark": {"type": "bar", "cornerRadiusTopLeft": 3, "cornerRadiusTopRight": 3}, "encoding": { "x": {"field": "risk", "type": "ordinal", "title": "", "sort": [], "axis": { "labelAngle": 0 }}, "y": {"field": "value", "type": "quantitative", "title": "", "axis": { "orient": "right" }}, "color": { "field": "status", "scale": { "domain": ["Unchecked", "InDiscussion", "Accepted", "InProgress", "Mitigated", "FalsePositive"], "range": ["` + RgbHexColorRiskStatusUnchecked() + `", "` + rgbHexColorRiskStatusInDiscussion() + `", "` + rgbHexColorRiskStatusAccepted() + `", "` + rgbHexColorRiskStatusInProgress() + `", "` + rgbHexColorRiskStatusMitigated() + `", "` + rgbHexColorRiskStatusFalsePositive() + `"] }, "legend" : { "title": "", "labelExpr": "datum.label == \"Unchecked\" ? \"` + strconv.Itoa(countStatusUnchecked) + ` unchecked\" : datum.label == \"InDiscussion\" ? \"` + strconv.Itoa(countStatusInDiscussion) + ` in discussion\" : datum.label == \"Accepted\" ? \"` + strconv.Itoa(countStatusAccepted) + ` accepted\" : datum.label == \"InProgress\" ? \"` + strconv.Itoa(countStatusInProgress) + ` in progress\" : datum.label == \"Mitigated\" ? \"` + strconv.Itoa(countStatusMitigated) + ` mitigated\" : datum.label == \"FalsePositive\" ? \"` + strconv.Itoa(countStatusFalsePositive) + ` false positive\" : \"\"" } } } } .... ` writeLine(f, diagram) writeLine(f, "") stillAtRisk := filteredByStillAtRisk(adoc.model) count := len(stillAtRisk) if count == 0 { writeLine(f, "After removal of risks with status _mitigated_ and _false positive_ "+ "*"+strconv.Itoa(count)+" remain unmitigated*.") } else { writeLine(f, "After removal of risks with status _mitigated_ and _false positive_ "+ "the following *"+strconv.Itoa(count)+" remain unmitigated*:") countCritical := len(types.ReduceToOnlyStillAtRisk(filteredBySeverity(adoc.model, types.CriticalSeverity))) countHigh := len(types.ReduceToOnlyStillAtRisk(filteredBySeverity(adoc.model, types.HighSeverity))) countElevated := len(types.ReduceToOnlyStillAtRisk(filteredBySeverity(adoc.model, types.ElevatedSeverity))) countMedium := len(types.ReduceToOnlyStillAtRisk(filteredBySeverity(adoc.model, types.MediumSeverity))) countLow := len(types.ReduceToOnlyStillAtRisk(filteredBySeverity(adoc.model, types.LowSeverity))) countBusinessSide := len(types.ReduceToOnlyStillAtRisk(filteredByRiskFunction(adoc.model, types.BusinessSide))) countArchitecture := len(types.ReduceToOnlyStillAtRisk(filteredByRiskFunction(adoc.model, types.Architecture))) countDevelopment := len(types.ReduceToOnlyStillAtRisk(filteredByRiskFunction(adoc.model, types.Development))) countOperation := len(types.ReduceToOnlyStillAtRisk(filteredByRiskFunction(adoc.model, types.Operations))) pieCharts := `[cols="a,a",frame=none,grid=none] |=== | [mermaid] .... %%{init: {'pie' : {'textPosition' : 0.5}, 'theme': 'base', 'themeVariables': { 'pie1': '` + rgbHexColorCriticalRisk() + `', 'pie2': '` + rgbHexColorHighRisk() + `', 'pie3': '` + rgbHexColorElevatedRisk() + `', 'pie4': '` + rgbHexColorMediumRisk() + `', 'pie5': '` + rgbHexColorLowRisk() + `'}}}%% pie showData "unmitigated critical risk" : ` + strconv.Itoa(countCritical) + ` "unmitigated high risk" : ` + strconv.Itoa(countHigh) + ` "unmitigated elevated risk" : ` + strconv.Itoa(countElevated) + ` "unmitigated medium risk" : ` + strconv.Itoa(countMedium) + ` "unmitigated low risk" : ` + strconv.Itoa(countLow) + ` .... | [mermaid] .... %%{init: {'pie' : {'textPosition' : 0.5}, 'theme': 'base', 'themeVariables': { 'pie1': '` + rgbHexColorBusiness() + `', 'pie2': '` + rgbHexColorArchitecture() + `', 'pie3': '` + rgbHexColorDevelopment() + `', 'pie4': '` + rgbHexColorOperation() + `'}}}%% pie showData "business side related" : ` + strconv.Itoa(countBusinessSide) + ` "architecture related" : ` + strconv.Itoa(countArchitecture) + ` "development related" : ` + strconv.Itoa(countDevelopment) + ` "operations related" : ` + strconv.Itoa(countOperation) + ` .... |=== ` writeLine(f, pieCharts) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
true
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/risk-item.go
pkg/report/risk-item.go
package report import "github.com/threagile/threagile/pkg/types" type RiskItem struct { Columns []string Status types.RiskStatus Severity types.RiskSeverity }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/excel-style.go
pkg/report/excel-style.go
package report import ( "fmt" "strings" "github.com/threagile/threagile/pkg/types" "github.com/xuri/excelize/v2" ) type ExcelStyles struct { severityCriticalBold int severityCriticalCenter int severityHighBold int severityHighCenter int severityElevatedBold int severityElevatedCenter int severityMediumBold int severityMediumCenter int severityLowBold int severityLowCenter int redCenter int greenCenter int blueCenter int yellowCenter int orangeCenter int grayCenter int blackLeft int blackLeftBold int blackCenter int blackRight int blackSmall int graySmall int blackBold int mitigation int headCenter int headCenterBoldItalic int headCenterBold int } type styleCreator struct { ExcelFile *excelize.File Error error } func (what *styleCreator) Init(excel *excelize.File) *styleCreator { what.ExcelFile = excel return what } func (what *styleCreator) NewStyle(style *excelize.Style) int { if what.Error != nil { return 0 } var styleID int styleID, what.Error = what.ExcelFile.NewStyle(style) return styleID } func (what *ExcelStyles) Init(excel *excelize.File, config reportConfigReader) (*ExcelStyles, error) { if excel == nil { return what, fmt.Errorf("no excel file provided to create styles") } creator := new(styleCreator).Init(excel) colorCriticalRisk := "#000000" if config.GetRiskExcelColorText() { colorCriticalRisk = rgbHexColorCriticalRisk() } what.severityCriticalBold = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorCriticalRisk, Size: 12, Bold: true, }, }) what.severityCriticalCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorCriticalRisk, Size: 12, }, }) colorHighRisk := "#000000" if config.GetRiskExcelColorText() { colorHighRisk = rgbHexColorHighRisk() } what.severityHighBold = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorHighRisk, Size: 12, Bold: true, }, }) what.severityHighCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorHighRisk, Size: 12, }, }) colorElevatedRisk := "#000000" if config.GetRiskExcelColorText() { colorElevatedRisk = rgbHexColorElevatedRisk() } what.severityElevatedBold = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorElevatedRisk, Size: 12, Bold: true, }, }) what.severityElevatedCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorElevatedRisk, Size: 12, }, }) colorMediumRisk := "#000000" if config.GetRiskExcelColorText() { colorMediumRisk = rgbHexColorMediumRisk() } what.severityMediumBold = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorMediumRisk, Size: 12, Bold: true, }, }) what.severityMediumCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorMediumRisk, Size: 12, }, }) colorLowRisk := "#000000" if config.GetRiskExcelColorText() { colorLowRisk = rgbHexColorLowRisk() } what.severityLowBold = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorLowRisk, Size: 12, Bold: true, }, }) what.severityLowCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorLowRisk, Size: 12, }, }) what.redCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorLowRisk, Size: 12, }, }) colorRiskStatusMitigated := "#000000" if config.GetRiskExcelColorText() { colorRiskStatusMitigated = rgbHexColorRiskStatusMitigated() } what.greenCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorRiskStatusMitigated, Size: 12, }, }) colorRiskStatusInProgress := "#000000" if config.GetRiskExcelColorText() { colorRiskStatusInProgress = rgbHexColorRiskStatusInProgress() } what.blueCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorRiskStatusInProgress, Size: 12, }, }) colorRiskStatusAccepted := "#000000" if config.GetRiskExcelColorText() { colorRiskStatusAccepted = rgbHexColorRiskStatusAccepted() } what.yellowCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorRiskStatusAccepted, Size: 12, }, }) colorRiskStatusInDiscussion := "#000000" if config.GetRiskExcelColorText() { colorRiskStatusInDiscussion = rgbHexColorRiskStatusInDiscussion() } what.orangeCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorRiskStatusInDiscussion, Size: 12, }, }) colorRiskStatusFalsePositive := "#000000" if config.GetRiskExcelColorText() { colorRiskStatusFalsePositive = rgbHexColorRiskStatusFalsePositive() } what.grayCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorRiskStatusFalsePositive, Size: 12, }, }) what.blackLeft = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "left", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: "#000000", Size: 12, }, }) what.blackCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: "#000000", Size: 12, }, }) what.blackRight = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "right", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: "#000000", Size: 12, }, }) what.blackSmall = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: "#000000", Size: 10, }, }) colorOutOfScope := "#000000" if config.GetRiskExcelColorText() { colorOutOfScope = rgbHexColorOutOfScope() } what.graySmall = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorOutOfScope, Size: 10, }, }) what.blackBold = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: "#000000", Size: 12, Bold: true, }, }) what.blackLeftBold = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "left", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: "#000000", Size: 12, Bold: true, }, }) what.mitigation = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: colorRiskStatusMitigated, Size: 10, }, }) what.headCenterBoldItalic = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: "#000000", Bold: true, Italic: false, Size: 14, }, Fill: excelize.Fill{ Type: "pattern", Color: []string{"#eeeeee"}, Pattern: 1, }, }) what.headCenterBold = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: "#000000", Size: 14, Bold: true, }, Fill: excelize.Fill{ Type: "pattern", Color: []string{"#eeeeee"}, Pattern: 1, }, }) what.headCenter = creator.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", ShrinkToFit: config.GetRiskExcelShrinkColumnsToFit(), WrapText: config.GetRiskExcelWrapText(), }, Font: &excelize.Font{ Color: "#000000", Size: 14, }, Fill: excelize.Fill{ Type: "pattern", Color: []string{"#eeeeee"}, Pattern: 1, }, }) return what, creator.Error } func (what *ExcelStyles) Get(column string, status types.RiskStatus, severity types.RiskSeverity) int { switch strings.ToUpper(column) { case "A", "B", "C", "D", "E", "F": if !status.IsStillAtRisk() { return what.blackCenter } switch severity { case types.CriticalSeverity: return what.severityCriticalCenter case types.HighSeverity: return what.severityHighCenter case types.ElevatedSeverity: return what.severityElevatedCenter case types.MediumSeverity: return what.severityMediumCenter case types.LowSeverity: return what.severityLowCenter } case "G", "H", "I": if !status.IsStillAtRisk() { return what.blackBold } switch severity { case types.CriticalSeverity: return what.severityCriticalBold case types.HighSeverity: return what.severityHighBold case types.ElevatedSeverity: return what.severityElevatedBold case types.MediumSeverity: return what.severityMediumBold case types.LowSeverity: return what.severityLowBold } case "J": return what.blackRight case "K": return what.blackSmall case "L", "M", "N": return what.mitigation case "O": return what.graySmall case "P": switch status { case types.Unchecked: return what.redCenter case types.Mitigated: return what.greenCenter case types.InProgress: return what.blueCenter case types.Accepted: return what.yellowCenter case types.InDiscussion: return what.orangeCenter case types.FalsePositive: return what.grayCenter default: return what.blackCenter } case "Q": return what.blackSmall case "R", "S": return what.blackCenter case "T": return what.blackLeft } return what.blackRight }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/excel.go
pkg/report/excel.go
package report import ( "fmt" "sort" "strconv" "strings" "unicode/utf8" "github.com/shopspring/decimal" "github.com/threagile/threagile/pkg/types" "github.com/xuri/excelize/v2" ) func WriteRisksExcelToFile(parsedModel *types.Model, filename string, config reportConfigReader) error { columns := new(ExcelColumns).GetColumns() excel := excelize.NewFile() sheetName := parsedModel.Title setDocPropsError := excel.SetDocProps(&excelize.DocProperties{ Category: "Threat Model Risks Summary", ContentStatus: "Final", Creator: parsedModel.Author.Name, Description: sheetName + " via Threagile", Identifier: "xlsx", Keywords: "Threat Model", LastModifiedBy: parsedModel.Author.Name, Revision: "0", Subject: sheetName, Title: sheetName, Language: "en-US", Version: "1.0.0", }) if setDocPropsError != nil { return fmt.Errorf("failed to set doc properties: %w", setDocPropsError) } sheetIndex, newSheetError := excel.NewSheet(sheetName) if newSheetError != nil { return fmt.Errorf("failed to add sheet: %w", newSheetError) } deleteSheetError := excel.DeleteSheet("Sheet1") if deleteSheetError != nil { return fmt.Errorf("failed to delete sheet: %w", deleteSheetError) } orientation := "landscape" size := 9 // A4 setPageLayoutError := excel.SetPageLayout(sheetName, &excelize.PageLayoutOptions{Orientation: &orientation, Size: &size}) if setPageLayoutError != nil { return fmt.Errorf("unable to set page layout: %w", setPageLayoutError) } setHeaderFooterError := excel.SetHeaderFooter(sheetName, &excelize.HeaderFooterOptions{ DifferentFirst: false, DifferentOddEven: false, OddHeader: "&R&P", OddFooter: "&C&F", EvenHeader: "&L&P", EvenFooter: "&L&D&R&T", FirstHeader: `&Threat Model &"-,` + parsedModel.Title + `"Bold&"-,Regular"Risks Summary+000A&D`, }) if setHeaderFooterError != nil { return fmt.Errorf("unable to set header/footer: %w", setHeaderFooterError) } // set header row for columnLetter, column := range columns { setCellValueError := excel.SetCellValue(sheetName, columnLetter+"1", column.Title) if setCellValueError != nil { return fmt.Errorf("unable to set cell value: %w", setCellValueError) } } cellStyles, createCellStylesError := new(ExcelStyles).Init(excel, config) if createCellStylesError != nil { return fmt.Errorf("unable to create cell styles: %w", createCellStylesError) } // get sorted risks riskItems := make([]RiskItem, 0) for _, category := range parsedModel.SortedRiskCategories() { risks := parsedModel.SortedRisksOfCategory(category) for _, risk := range risks { techAsset := parsedModel.TechnicalAssets[risk.MostRelevantTechnicalAssetId] techAssetTitle := "" techAssetRAA := 0. if techAsset != nil { techAssetTitle = techAsset.Title techAssetRAA = techAsset.RAA } commLink := parsedModel.CommunicationLinks[risk.MostRelevantCommunicationLinkId] commLinkTitle := "" if commLink != nil { commLinkTitle = commLink.Title } date := "" riskTracking := parsedModel.GetRiskTrackingWithDefault(risk) if !riskTracking.Date.IsZero() { date = riskTracking.Date.Format("2006-01-02") } riskItems = append(riskItems, RiskItem{ Columns: []string{ risk.Severity.Title(), risk.ExploitationLikelihood.Title(), risk.ExploitationImpact.Title(), category.STRIDE.Title(), category.Function.Title(), "CWE-" + strconv.Itoa(category.CWE), category.Title, techAssetTitle, commLinkTitle, decimal.NewFromFloat(techAssetRAA).StringFixed(0), removeFormattingTags(risk.Title), category.Action, category.Mitigation, category.Check, risk.SyntheticId, riskTracking.Status.Title(), riskTracking.Justification, date, riskTracking.CheckedBy, riskTracking.Ticket, }, Status: riskTracking.Status, Severity: risk.Severity, }) } } // group risks groupedRisk, groupedRiskError := new(RiskGroup).Make(riskItems, columns, config.GetRiskExcelConfigSortByColumns()) if groupedRiskError != nil { return fmt.Errorf("failed to group risks: %w", groupedRiskError) } // write data writeError := groupedRisk.Write(excel, sheetName, cellStyles) if writeError != nil { return fmt.Errorf("failed to write data: %w", writeError) } // set header style setCellStyleError := excel.SetCellStyle(sheetName, "A1", "T1", cellStyles.headCenterBoldItalic) if setCellStyleError != nil { return fmt.Errorf("unable to set cell style: %w", setCellStyleError) } // fix column width cols, colsError := excel.GetCols(sheetName) if colsError == nil { for colIndex, col := range cols { name, columnNumberToNameError := excelize.ColumnNumberToName(colIndex + 1) if columnNumberToNameError != nil { return columnNumberToNameError } var minWidth float64 = 0 width, widthOk := config.GetRiskExcelConfigWidthOfColumns()[columns[name].Title] if widthOk { minWidth = width } else { var largestWidth float64 = 0 for rowIndex, rowCell := range col { cellWidth := float64(utf8.RuneCountInString(rowCell) + 2) // + 2 for margin cellName, coordinateError := excelize.CoordinatesToCellName(colIndex+1, rowIndex+1) if coordinateError == nil { style, styleError := excel.GetCellStyle(sheetName, cellName) if styleError == nil { styleDetails, detailsError := excel.GetStyle(style) if detailsError == nil { if styleDetails.Font != nil && styleDetails.Font.Size > 0 { cellWidth *= styleDetails.Font.Size / 14. } } } } cellWidth += 5 // add some extra width for auto filter if cellWidth > largestWidth { largestWidth = cellWidth } } for columnLetter := range columns { if strings.EqualFold(columnLetter, name) { minWidth = columns[columnLetter].Width } } if largestWidth < 100 { minWidth = largestWidth } if minWidth < 8 { minWidth = 8 } } setColWidthError := excel.SetColWidth(sheetName, name, name, minWidth) if setColWidthError != nil { return setColWidthError } } } // hide some columns for columnLetter, column := range columns { for _, hiddenColumn := range config.GetRiskExcelConfigHideColumns() { if strings.EqualFold(hiddenColumn, column.Title) { hideColumnError := excel.SetColVisible(sheetName, columnLetter, false) if hideColumnError != nil { return fmt.Errorf("unable to hide column: %w", hideColumnError) } } } } // freeze header freezeError := excel.SetPanes(sheetName, &excelize.Panes{ Freeze: true, Split: false, XSplit: 0, YSplit: 1, TopLeftCell: "A2", ActivePane: "bottomLeft", }) if freezeError != nil { return fmt.Errorf("unable to freeze header: %w", freezeError) } excel.SetActiveSheet(sheetIndex) lastColumn, err := excelize.ColumnNumberToName(len(columns)) if err != nil { return fmt.Errorf("failed to get last column name: %w", err) } lastRow := len(riskItems) + 1 filterRange := fmt.Sprintf("A1:%s%d", lastColumn, lastRow) err = excel.AutoFilter(sheetName, filterRange, []excelize.AutoFilterOptions{}) if err != nil { return fmt.Errorf("failed to add autofilter: %w", err) } // save file saveAsError := excel.SaveAs(filename) if saveAsError != nil { return fmt.Errorf("unable to save excel file: %w", saveAsError) } return nil } // TODO: eventually when len(sortedTagsAvailable) == 0 is: write a hint in the Excel that no tags are used func WriteTagsExcelToFile(parsedModel *types.Model, filename string, config reportConfigReader) error { excelRow := 0 excel := excelize.NewFile() sheetName := parsedModel.Title err := excel.SetDocProps(&excelize.DocProperties{ Category: "Tag Matrix", ContentStatus: "Final", Creator: parsedModel.Author.Name, Description: sheetName + " via Threagile", Identifier: "xlsx", Keywords: "Tag Matrix", LastModifiedBy: parsedModel.Author.Name, Revision: "0", Subject: sheetName, Title: sheetName, Language: "en-US", Version: "1.0.0", }) if err != nil { return err } sheetIndex, _ := excel.NewSheet(sheetName) _ = excel.DeleteSheet("Sheet1") orientation := "landscape" size := 9 err = excel.SetPageLayout(sheetName, &excelize.PageLayoutOptions{Orientation: &orientation, Size: &size}) // A4 if err != nil { return err } err = excel.SetHeaderFooter(sheetName, &excelize.HeaderFooterOptions{ DifferentFirst: false, DifferentOddEven: false, OddHeader: "&R&P", OddFooter: "&C&F", EvenHeader: "&L&P", EvenFooter: "&L&D&R&T", FirstHeader: `&Tag Matrix &"-,` + parsedModel.Title + `"Bold&"-,Regular"Summary+000A&D`, }) if err != nil { return err } err = excel.SetCellValue(sheetName, "A1", "Element") // TODO is "Element" the correct generic name when referencing assets, links, trust boundaries etc.? Eventually add separate column "type of element" like "technical asset" or "data asset"? if err != nil { return err } sortedTagsAvailable := parsedModel.TagsActuallyUsed() sort.Strings(sortedTagsAvailable) for i, tag := range sortedTagsAvailable { cellName, coordinatesToCellNameError := excelize.CoordinatesToCellName(i+2, 1) if coordinatesToCellNameError != nil { return fmt.Errorf("failed to get cell coordinates from [%d, %d]: %w", i+2, 1, coordinatesToCellNameError) } err = excel.SetCellValue(sheetName, cellName, tag) if err != nil { return err } } err = excel.SetColWidth(sheetName, "A", "A", 60) if err != nil { return err } lastColumn, _ := excelize.ColumnNumberToName(len(sortedTagsAvailable) + 2) if len(sortedTagsAvailable) > 0 { err = excel.SetColWidth(sheetName, "B", lastColumn, 35) } if err != nil { return err } cellStyles, createCellStylesError := new(ExcelStyles).Init(excel, config) if createCellStylesError != nil { return fmt.Errorf("unable to create cell styles: %w", createCellStylesError) } excelRow++ // as we have a header line if len(sortedTagsAvailable) > 0 { for _, techAsset := range sortedTechnicalAssetsByTitle(parsedModel) { err := writeRow(excel, &excelRow, sheetName, lastColumn, cellStyles.blackLeftBold, cellStyles.blackCenter, sortedTagsAvailable, techAsset.Title, techAsset.Tags) if err != nil { return fmt.Errorf("unable to write row: %w", err) } for _, commLink := range techAsset.CommunicationLinksSorted() { err := writeRow(excel, &excelRow, sheetName, lastColumn, cellStyles.blackLeftBold, cellStyles.blackCenter, sortedTagsAvailable, commLink.Title, commLink.Tags) if err != nil { return fmt.Errorf("unable to write row: %w", err) } } } for _, dataAsset := range sortedDataAssetsByTitle(parsedModel) { err := writeRow(excel, &excelRow, sheetName, lastColumn, cellStyles.blackLeftBold, cellStyles.blackCenter, sortedTagsAvailable, dataAsset.Title, dataAsset.Tags) if err != nil { return fmt.Errorf("unable to write row: %w", err) } } for _, trustBoundary := range sortedTrustBoundariesByTitle(parsedModel) { err := writeRow(excel, &excelRow, sheetName, lastColumn, cellStyles.blackLeftBold, cellStyles.blackCenter, sortedTagsAvailable, trustBoundary.Title, trustBoundary.Tags) if err != nil { return fmt.Errorf("unable to write row: %w", err) } } for _, sharedRuntime := range sortedSharedRuntimesByTitle(parsedModel) { err := writeRow(excel, &excelRow, sheetName, lastColumn, cellStyles.blackLeftBold, cellStyles.blackCenter, sortedTagsAvailable, sharedRuntime.Title, sharedRuntime.Tags) if err != nil { return fmt.Errorf("unable to write row: %w", err) } } } err = excel.SetCellStyle(sheetName, "A1", "A1", cellStyles.headCenterBold) if len(sortedTagsAvailable) > 0 { err = excel.SetCellStyle(sheetName, "B1", lastColumn+"1", cellStyles.headCenter) } if err != nil { return fmt.Errorf("unable to set cell style: %w", err) } excel.SetActiveSheet(sheetIndex) err = excel.SaveAs(filename) if err != nil { return fmt.Errorf("unable to save excel file: %w", err) } return nil } func sortedTrustBoundariesByTitle(parsedModel *types.Model) []*types.TrustBoundary { boundaries := make([]*types.TrustBoundary, 0) for _, boundary := range parsedModel.TrustBoundaries { boundaries = append(boundaries, boundary) } sort.Sort(byTrustBoundaryTitleSort(boundaries)) return boundaries } type byTrustBoundaryTitleSort []*types.TrustBoundary func (what byTrustBoundaryTitleSort) Len() int { return len(what) } func (what byTrustBoundaryTitleSort) Swap(i, j int) { what[i], what[j] = what[j], what[i] } func (what byTrustBoundaryTitleSort) Less(i, j int) bool { return what[i].Title < what[j].Title } func sortedDataAssetsByTitle(parsedModel *types.Model) []*types.DataAsset { assets := make([]*types.DataAsset, 0) for _, asset := range parsedModel.DataAssets { assets = append(assets, asset) } sort.Sort(types.ByDataAssetTitleSort(assets)) return assets } func writeRow(excel *excelize.File, excelRow *int, sheetName string, _ string, styleBlackLeftBold int, styleBlackCenter int, sortedTags []string, assetTitle string, tagsUsed []string) error { *excelRow++ firstCellName, firstCoordinatesToCellNameError := excelize.CoordinatesToCellName(1, *excelRow) if firstCoordinatesToCellNameError != nil { return fmt.Errorf("failed to get cell coordinates from [%d, %d]: %w", 1, *excelRow, firstCoordinatesToCellNameError) } err := excel.SetCellValue(sheetName, firstCellName, assetTitle) if err != nil { return fmt.Errorf("unable to write row: %w", err) } for i, tag := range sortedTags { if contains(tagsUsed, tag) { cellName, coordinatesToCellNameError := excelize.CoordinatesToCellName(i+2, *excelRow) if coordinatesToCellNameError != nil { return fmt.Errorf("failed to get cell coordinates from [%d, %d]: %w", i+2, *excelRow, coordinatesToCellNameError) } err = excel.SetCellValue(sheetName, cellName, "X") if err != nil { return fmt.Errorf("unable to write row: %w", err) } } } err = excel.SetCellStyle(sheetName, firstCellName, firstCellName, styleBlackLeftBold) if err != nil { return fmt.Errorf("unable to write row: %w", err) } secondCellName, secondCoordinatesToCellNameError := excelize.CoordinatesToCellName(2, *excelRow) if secondCoordinatesToCellNameError != nil { return fmt.Errorf("failed to get cell coordinates from [%d, %d]: %w", 2, *excelRow, secondCoordinatesToCellNameError) } lastCellName, lastCoordinatesToCellNameError := excelize.CoordinatesToCellName(len(sortedTags)+2, *excelRow) if lastCoordinatesToCellNameError != nil { return fmt.Errorf("failed to get cell coordinates from [%d, %d]: %w", len(sortedTags)+2, *excelRow, lastCoordinatesToCellNameError) } err = excel.SetCellStyle(sheetName, secondCellName, lastCellName, styleBlackCenter) if err != nil { return fmt.Errorf("unable to write row: %w", err) } return nil } func removeFormattingTags(content string) string { result := strings.ReplaceAll(strings.ReplaceAll(content, "<b>", ""), "</b>", "") result = strings.ReplaceAll(strings.ReplaceAll(result, "<i>", ""), "</i>", "") result = strings.ReplaceAll(strings.ReplaceAll(result, "<u>", ""), "</u>", "") return result }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/report-helper.go
pkg/report/report-helper.go
package report import ( "sort" "github.com/threagile/threagile/pkg/types" ) func filteredByRiskStatus(parsedModel *types.Model, status types.RiskStatus) []*types.Risk { filteredRisks := make([]*types.Risk, 0) for _, risks := range parsedModel.GeneratedRisksByCategoryWithCurrentStatus() { for _, risk := range risks { if risk.RiskStatus == status { filteredRisks = append(filteredRisks, risk) } } } return filteredRisks } func filteredByRiskFunction(parsedModel *types.Model, function types.RiskFunction) []*types.Risk { filteredRisks := make([]*types.Risk, 0) for categoryId, risks := range parsedModel.GeneratedRisksByCategory { category := parsedModel.GetRiskCategory(categoryId) for _, risk := range risks { if category.Function == function { filteredRisks = append(filteredRisks, risk) } } } return filteredRisks } func reduceToRiskStatus(risks []*types.Risk, status types.RiskStatus) []*types.Risk { filteredRisks := make([]*types.Risk, 0) for _, risk := range risks { if risk.RiskStatus == status { filteredRisks = append(filteredRisks, risk) } } return filteredRisks } func reduceToFunctionRisk(parsedModel *types.Model, risksByCategory map[string][]*types.Risk, function types.RiskFunction) map[string][]*types.Risk { result := make(map[string][]*types.Risk) for categoryId, risks := range risksByCategory { for _, risk := range risks { category := parsedModel.GetRiskCategory(categoryId) if category.Function == function { result[categoryId] = append(result[categoryId], risk) } } } return result } func reduceToSTRIDERisk(parsedModel *types.Model, risksByCategory map[string][]*types.Risk, stride types.STRIDE) map[string][]*types.Risk { result := make(map[string][]*types.Risk) for categoryId, risks := range risksByCategory { for _, risk := range risks { category := parsedModel.GetRiskCategory(categoryId) if category != nil && category.STRIDE == stride { result[categoryId] = append(result[categoryId], risk) } } } return result } func countRisks(risksByCategory map[string][]*types.Risk) int { result := 0 for _, risks := range risksByCategory { result += len(risks) } return result } func totalRiskCount(parsedModel *types.Model) int { count := 0 for _, risks := range parsedModel.GeneratedRisksByCategory { count += len(risks) } return count } func sortedTechnicalAssetsByRAAAndTitle(parsedModel *types.Model) []*types.TechnicalAsset { assets := make([]*types.TechnicalAsset, 0) for _, asset := range parsedModel.TechnicalAssets { assets = append(assets, asset) } sort.Sort(types.ByTechnicalAssetRAAAndTitleSort(assets)) return assets } func sortedKeysOfQuestions(parsedModel *types.Model) []string { keys := make([]string, 0) for k := range parsedModel.Questions { keys = append(keys, k) } sort.Strings(keys) return keys } func filteredBySeverity(parsedModel *types.Model, severity types.RiskSeverity) []*types.Risk { filteredRisks := make([]*types.Risk, 0) for _, risks := range parsedModel.GeneratedRisksByCategoryWithCurrentStatus() { for _, risk := range risks { if risk.Severity == severity { filteredRisks = append(filteredRisks, risk) } } } return filteredRisks } func sortedTechnicalAssetsByRiskSeverityAndTitle(parsedModel *types.Model) []*types.TechnicalAsset { assets := make([]*types.TechnicalAsset, 0) for _, asset := range parsedModel.TechnicalAssets { assets = append(assets, asset) } sortByTechnicalAssetRiskSeverityAndTitleStillAtRisk(assets, parsedModel) return assets } func filteredByStillAtRisk(parsedModel *types.Model) []*types.Risk { filteredRisks := make([]*types.Risk, 0) for _, risks := range parsedModel.GeneratedRisksByCategoryWithCurrentStatus() { stillAtRisk := types.ReduceToOnlyStillAtRisk(risks) filteredRisks = append(filteredRisks, stillAtRisk...) } return filteredRisks } func identifiedDataBreachProbabilityStillAtRisk(parsedModel *types.Model, dataAsset *types.DataAsset) types.DataBreachProbability { highestProbability := types.Improbable for _, risk := range filteredByStillAtRisk(parsedModel) { for _, techAsset := range risk.DataBreachTechnicalAssetIDs { if contains(parsedModel.TechnicalAssets[techAsset].DataAssetsProcessed, dataAsset.Id) { if risk.DataBreachProbability > highestProbability { highestProbability = risk.DataBreachProbability break } } } } return highestProbability }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/generate.go
pkg/report/generate.go
package report import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "io" "os" "path/filepath" "github.com/threagile/threagile/pkg/model" "github.com/threagile/threagile/pkg/types" ) type GenerateCommands struct { DataFlowDiagram bool DataAssetDiagram bool RisksJSON bool TechnicalAssetsJSON bool StatsJSON bool RisksExcel bool TagsExcel bool ReportPDF bool ReportADOC bool } func (c *GenerateCommands) Defaults() *GenerateCommands { *c = GenerateCommands{ DataFlowDiagram: true, DataAssetDiagram: true, RisksJSON: true, TechnicalAssetsJSON: true, StatsJSON: true, RisksExcel: true, TagsExcel: true, ReportPDF: true, ReportADOC: true, } return c } type reportConfigReader interface { GetBuildTimestamp() string GetThreagileVersion() string GetAppFolder() string GetOutputFolder() string GetTempFolder() string GetInputFile() string GetDataFlowDiagramFilenamePNG() string GetDataAssetDiagramFilenamePNG() string GetDataFlowDiagramFilenameDOT() string GetDataAssetDiagramFilenameDOT() string GetReportFilename() string GetExcelRisksFilename() string GetExcelTagsFilename() string GetJsonRisksFilename() string GetJsonTechnicalAssetsFilename() string GetJsonStatsFilename() string GetTemplateFilename() string GetReportLogoImagePath() string GetSkipRiskRules() []string GetRiskExcelConfigHideColumns() []string GetRiskExcelConfigSortByColumns() []string GetRiskExcelConfigWidthOfColumns() map[string]float64 GetRiskExcelWrapText() bool GetRiskExcelShrinkColumnsToFit() bool GetRiskExcelColorText() bool GetDiagramDPI() int GetMinGraphvizDPI() int GetMaxGraphvizDPI() int GetKeepDiagramSourceFiles() bool GetAddModelTitle() bool GetAddLegend() bool GetReportConfigurationHideChapters() map[ChaptersToShowHide]bool GetHideEmptyChapters() bool } func Generate(config reportConfigReader, readResult *model.ReadResult, commands *GenerateCommands, riskRules types.RiskRules, progressReporter progressReporter) error { generateDataFlowDiagram := commands.DataFlowDiagram generateDataAssetsDiagram := commands.DataAssetDiagram _ = os.MkdirAll(filepath.Clean(config.GetOutputFolder()), 0750) _ = os.MkdirAll(filepath.Clean(config.GetTempFolder()), 0700) if commands.ReportPDF || commands.ReportADOC { // as the PDF report includes both diagrams if !generateDataFlowDiagram { dataFlowFile := filepath.Join(config.GetOutputFolder(), config.GetDataFlowDiagramFilenamePNG()) if _, err := os.Stat(dataFlowFile); errors.Is(err, os.ErrNotExist) { progressReporter.Warn("Forcibly create the needed Data-Flow Diagram file to enable report generation.") generateDataFlowDiagram = true } } if !generateDataAssetsDiagram { dataAssetFile := filepath.Join(config.GetOutputFolder(), config.GetDataAssetDiagramFilenamePNG()) if _, err := os.Stat(dataAssetFile); errors.Is(err, os.ErrNotExist) { progressReporter.Warn("Forcibly create the needed Data-Asset Diagram file to enable report generation.") generateDataAssetsDiagram = true } } } diagramDPI := config.GetDiagramDPI() if diagramDPI < config.GetMinGraphvizDPI() { diagramDPI = config.GetMinGraphvizDPI() } else if diagramDPI > config.GetMaxGraphvizDPI() { diagramDPI = config.GetMaxGraphvizDPI() } // Data-flow Diagram rendering if generateDataFlowDiagram { gvFile := filepath.Join(config.GetOutputFolder(), config.GetDataFlowDiagramFilenameDOT()) if !config.GetKeepDiagramSourceFiles() { tmpFileGV, err := os.CreateTemp(config.GetTempFolder(), config.GetDataFlowDiagramFilenameDOT()) if err != nil { return err } gvFile = tmpFileGV.Name() defer func() { _ = os.Remove(gvFile) }() } dotFile, err := WriteDataFlowDiagramGraphvizDOT(readResult.ParsedModel, gvFile, diagramDPI, config.GetAddModelTitle(), config.GetAddLegend(), progressReporter) if err != nil { return fmt.Errorf("error while generating data flow diagram: %w", err) } err = GenerateDataFlowDiagramGraphvizImage(dotFile, config.GetOutputFolder(), config.GetTempFolder(), config.GetDataFlowDiagramFilenamePNG(), progressReporter, config.GetKeepDiagramSourceFiles()) if err != nil { progressReporter.Warn(err) } } // Data Asset Diagram rendering if generateDataAssetsDiagram { gvFile := filepath.Join(config.GetOutputFolder(), config.GetDataAssetDiagramFilenameDOT()) if !config.GetKeepDiagramSourceFiles() { tmpFile, err := os.CreateTemp(config.GetTempFolder(), config.GetDataAssetDiagramFilenameDOT()) if err != nil { return err } gvFile = tmpFile.Name() defer func() { _ = os.Remove(gvFile) }() } dotFile, err := WriteDataAssetDiagramGraphvizDOT(readResult.ParsedModel, gvFile, diagramDPI, progressReporter) if err != nil { return fmt.Errorf("error while generating data asset diagram: %w", err) } err = GenerateDataAssetDiagramGraphvizImage(dotFile, config.GetOutputFolder(), config.GetTempFolder(), config.GetDataAssetDiagramFilenamePNG(), progressReporter) if err != nil { progressReporter.Warn(err) } } // risks as risks json if commands.RisksJSON { progressReporter.Info("Writing risks json") err := WriteRisksJSON(readResult.ParsedModel, filepath.Join(config.GetOutputFolder(), config.GetJsonRisksFilename())) if err != nil { return fmt.Errorf("error while writing risks json: %w", err) } } // technical assets json if commands.TechnicalAssetsJSON { progressReporter.Info("Writing technical assets json") err := WriteTechnicalAssetsJSON(readResult.ParsedModel, filepath.Join(config.GetOutputFolder(), config.GetJsonTechnicalAssetsFilename())) if err != nil { return fmt.Errorf("error while writing technical assets json: %w", err) } } // risks as risks json if commands.StatsJSON { progressReporter.Info("Writing stats json") err := WriteStatsJSON(readResult.ParsedModel, filepath.Join(config.GetOutputFolder(), config.GetJsonStatsFilename())) if err != nil { return fmt.Errorf("error while writing stats json: %w", err) } } // risks Excel if commands.RisksExcel { progressReporter.Info("Writing risks excel") err := WriteRisksExcelToFile(readResult.ParsedModel, filepath.Join(config.GetOutputFolder(), config.GetExcelRisksFilename()), config) if err != nil { return err } } // tags Excel if commands.TagsExcel { progressReporter.Info("Writing tags excel") err := WriteTagsExcelToFile(readResult.ParsedModel, filepath.Join(config.GetOutputFolder(), config.GetExcelTagsFilename()), config) if err != nil { return err } } if commands.ReportPDF { // hash the YAML input file f, err := os.Open(config.GetInputFile()) if err != nil { return err } defer func() { _ = f.Close() }() hasher := sha256.New() if _, err := io.Copy(hasher, f); err != nil { return err } modelHash := hex.EncodeToString(hasher.Sum(nil)) // report PDF progressReporter.Info("Writing report pdf") pdfReporter := newPdfReporter(riskRules) err = pdfReporter.WriteReportPDF(filepath.Join(config.GetOutputFolder(), config.GetReportFilename()), filepath.Join(config.GetAppFolder(), config.GetTemplateFilename()), filepath.Join(config.GetOutputFolder(), config.GetDataFlowDiagramFilenamePNG()), filepath.Join(config.GetOutputFolder(), config.GetDataAssetDiagramFilenamePNG()), config.GetInputFile(), config.GetSkipRiskRules(), config.GetBuildTimestamp(), config.GetThreagileVersion(), modelHash, readResult.IntroTextRAA, readResult.CustomRiskRules, config.GetTempFolder(), readResult.ParsedModel, config.GetReportConfigurationHideChapters()) if err != nil { return err } } if commands.ReportADOC { // hash the YAML input file f, err := os.Open(config.GetInputFile()) if err != nil { return err } defer func() { _ = f.Close() }() hasher := sha256.New() if _, err := io.Copy(hasher, f); err != nil { return err } modelHash := hex.EncodeToString(hasher.Sum(nil)) // report ADOC progressReporter.Info("Writing report adoc") adocReporter := NewAdocReport(config.GetOutputFolder(), riskRules, config.GetHideEmptyChapters()) err = adocReporter.WriteReport(readResult.ParsedModel, filepath.Join(config.GetOutputFolder(), config.GetDataFlowDiagramFilenamePNG()), filepath.Join(config.GetOutputFolder(), config.GetDataAssetDiagramFilenamePNG()), config.GetInputFile(), config.GetSkipRiskRules(), config.GetBuildTimestamp(), config.GetThreagileVersion(), modelHash, readResult.IntroTextRAA, readResult.CustomRiskRules, config.GetReportLogoImagePath(), config.GetReportConfigurationHideChapters()) if err != nil { return err } } return nil } type progressReporter interface { Info(a ...any) Warn(a ...any) Error(a ...any) } func contains(a []string, x string) bool { for _, n := range a { if x == n { return true } } return false }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/colors.go
pkg/report/colors.go
package report import ( "encoding/hex" "github.com/jung-kurt/gofpdf" ) const ( Amber = "#AF780E" Green = "#008000" Blue = "#000080" DarkBlue = "#000060" Black = "#000000" Gray = "#444444" LightGray = "#666666" MiddleLightGray = "#999999" MoreLightGray = "#D2D2D2" VeryLightGray = "#E5E5E5" ExtremeLightGray = "#F6F6F6" Pink = "#F987C5" LightPink = "#FFE7EF" Red = "#CC0000" OutOfScopeFancy = "#D5D7FF" CustomDevelopedParts = "#FFFC97" ExtremeLightBlue = "#DDFFFF" LightBlue = "#77FFFF" Brown = "#8C4C17" ) func darkenHexColor(hexString string) string { colorBytes, _ := hex.DecodeString(hexString[1:]) adjusted := make([]byte, len(colorBytes)) for i := range colorBytes { if colorBytes[i] > 0x22 { adjusted[i] = colorBytes[i] - 0x20 } else { adjusted[i] = 0x00 } } return "#" + hex.EncodeToString(adjusted) } func brightenHexColor(hexString string) string { colorBytes, _ := hex.DecodeString(hexString[1:]) adjusted := make([]byte, len(colorBytes)) for i := range colorBytes { if colorBytes[i] < 0xDD { adjusted[i] = colorBytes[i] + 0x20 } else { adjusted[i] = 0xFF } } return "#" + hex.EncodeToString(adjusted) } func colorCriticalRisk(pdf *gofpdf.Fpdf) { pdf.SetTextColor(255, 38, 0) } func rgbHexColorCriticalRisk() string { return "#FF2600" } func colorHighRisk(pdf *gofpdf.Fpdf) { pdf.SetTextColor(160, 40, 30) } func rgbHexColorHighRisk() string { return "#A0281E" } func colorElevatedRisk(pdf *gofpdf.Fpdf) { pdf.SetTextColor(255, 142, 0) } func rgbHexColorElevatedRisk() string { return "#FF8E00" } func colorMediumRisk(pdf *gofpdf.Fpdf) { pdf.SetTextColor(200, 120, 50) } func rgbHexColorMediumRisk() string { return "#C87832" } func colorLowRisk(pdf *gofpdf.Fpdf) { pdf.SetTextColor(35, 70, 95) } func rgbHexColorLowRisk() string { return "#23465F" } func rgbHexColorOutOfScope() string { return "#7F7F7F" } func colorRiskStatusUnchecked(pdf *gofpdf.Fpdf) { pdf.SetTextColor(256, 0, 0) } func RgbHexColorRiskStatusUnchecked() string { return "#FF0000" } func colorRiskStatusMitigated(pdf *gofpdf.Fpdf) { pdf.SetTextColor(0, 143, 0) } func rgbHexColorRiskStatusMitigated() string { return "#008F00" } func colorRiskStatusInProgress(pdf *gofpdf.Fpdf) { pdf.SetTextColor(0, 0, 256) } func rgbHexColorRiskStatusInProgress() string { return "#0000FF" } func colorRiskStatusAccepted(pdf *gofpdf.Fpdf) { pdf.SetTextColor(255, 64, 255) } func rgbHexColorRiskStatusAccepted() string { return "#FF40FF" } func colorRiskStatusInDiscussion(pdf *gofpdf.Fpdf) { pdf.SetTextColor(256, 147, 0) } func rgbHexColorRiskStatusInDiscussion() string { return "#FF9300" } func colorRiskStatusFalsePositive(pdf *gofpdf.Fpdf) { pdf.SetTextColor(102, 102, 102) } func rgbHexColorRiskStatusFalsePositive() string { return "#666666" } func colorTwilight(pdf *gofpdf.Fpdf) { pdf.SetTextColor(58, 82, 200) } func rgbHexColorTwilight() string { return "#3A52C8" } func colorBusiness(pdf *gofpdf.Fpdf) { pdf.SetTextColor(83, 27, 147) } func rgbHexColorBusiness() string { return "#531B93" } func colorArchitecture(pdf *gofpdf.Fpdf) { pdf.SetTextColor(0, 84, 147) } func rgbHexColorArchitecture() string { return "#005493" } func colorDevelopment(pdf *gofpdf.Fpdf) { pdf.SetTextColor(222, 146, 35) } func rgbHexColorDevelopment() string { return "#DE9223" } func colorOperation(pdf *gofpdf.Fpdf) { pdf.SetTextColor(148, 127, 80) } func rgbHexColorOperation() string { return "#947F50" } func colorModelFailure(pdf *gofpdf.Fpdf) { pdf.SetTextColor(148, 82, 0) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/report.go
pkg/report/report.go
package report import ( "fmt" "image" "log" "os" "path/filepath" "regexp" "sort" "strconv" "strings" "time" "unicode/utf8" "github.com/jung-kurt/gofpdf" "github.com/jung-kurt/gofpdf/contrib/gofpdi" "github.com/threagile/threagile/pkg/types" "github.com/wcharczuk/go-chart" "github.com/wcharczuk/go-chart/drawing" ) const fontSizeHeadline, fontSizeHeadlineSmall, fontSizeBody, fontSizeSmall, fontSizeVerySmall = 20, 16, 12, 9, 7 const allowedPdfLandscapePages, embedDiagramLegendPage = true, false type pdfReporter struct { isLandscapePage bool pdf *gofpdf.Fpdf coverTemplateId int contentTemplateId int diagramLegendTemplateId int pageNo int linkCounter int tocLinkIdByAssetId map[string]int homeLink int currentChapterTitleBreadcrumb string riskRules types.RiskRules } func newPdfReporter(types.RiskRules) *pdfReporter { return &pdfReporter{} } func (r *pdfReporter) initReport() { r.pdf = nil r.isLandscapePage = false r.pageNo = 0 r.linkCounter = 0 r.homeLink = 0 r.currentChapterTitleBreadcrumb = "" r.tocLinkIdByAssetId = make(map[string]int) } func (r *pdfReporter) WriteReportPDF(reportFilename string, templateFilename string, dataFlowDiagramFilenamePNG string, dataAssetDiagramFilenamePNG string, modelFilename string, skipRiskRules []string, buildTimestamp string, threagileVersion string, modelHash string, introTextRAA string, customRiskRules types.RiskRules, tempFolder string, model *types.Model, hideChapters map[ChaptersToShowHide]bool) error { defer func() { value := recover() if value != nil { fmt.Printf("error creating PDF report: %v", value) } }() r.initReport() r.createPdfAndInitMetadata(model) r.parseBackgroundTemplate(templateFilename) r.createCover(model) r.createTableOfContents(model) err := r.createManagementSummary(model, tempFolder) if err != nil { return fmt.Errorf("error creating management summary: %w", err) } r.createImpactInitialRisks(model) err = r.createRiskMitigationStatus(model, tempFolder) if err != nil { return fmt.Errorf("error creating risk mitigation status: %w", err) } if val := hideChapters[AssetRegister]; !val { r.createAssetRegister(model) } r.createImpactRemainingRisks(model) err = r.createTargetDescription(model, filepath.Dir(modelFilename)) if err != nil { return fmt.Errorf("error creating target description: %w", err) } r.embedDataFlowDiagram(dataFlowDiagramFilenamePNG, tempFolder) r.createSecurityRequirements(model) r.createAbuseCases(model) r.createTagListing(model) r.createSTRIDE(model) r.createAssignmentByFunction(model) r.createRAA(model, introTextRAA) r.embedDataRiskMapping(dataAssetDiagramFilenamePNG, tempFolder) //createDataRiskQuickWins() r.createOutOfScopeAssets(model) r.createModelFailures(model) r.createQuestions(model) r.createRiskCategories(model) r.createTechnicalAssets(model) r.createDataAssets(model) r.createTrustBoundaries(model) r.createSharedRuntimes(model) if val := hideChapters[RiskRulesCheckedByThreagile]; !val { r.createRiskRulesChecked(model, modelFilename, skipRiskRules, buildTimestamp, threagileVersion, modelHash, customRiskRules) } r.createDisclaimer(model) err = r.writeReportToFile(reportFilename) if err != nil { return fmt.Errorf("error writing report to file: %w", err) } return nil } func (r *pdfReporter) createPdfAndInitMetadata(model *types.Model) { r.pdf = gofpdf.New("P", "mm", "A4", "") r.pdf.SetCreator(model.Author.Homepage, true) r.pdf.SetAuthor(model.Author.Name, true) r.pdf.SetTitle("Threat Model Report: "+model.Title, true) r.pdf.SetSubject("Threat Model Report: "+model.Title, true) // r.pdf.SetPageBox("crop", 0, 0, 100, 010) r.pdf.SetHeaderFunc(func() { if r.isLandscapePage { return } gofpdi.UseImportedTemplate(r.pdf, r.contentTemplateId, 0, 0, 0, 300) r.pdf.SetTopMargin(35) }) r.pdf.SetFooterFunc(func() { r.addBreadcrumb(model) r.pdf.SetFont("Helvetica", "", 10) r.pdf.SetTextColor(127, 127, 127) r.pdf.Text(8.6, 284, "Threat Model Report via Threagile") //: "+parsedModel.Title) r.pdf.Link(8.4, 281, 54.6, 4, r.homeLink) r.pageNo++ text := "Page " + strconv.Itoa(r.pageNo) if r.pageNo < 10 { text = " " + text } else if r.pageNo < 100 { text = " " + text } if r.pageNo > 1 { r.pdf.Text(186, 284, text) } }) r.linkCounter = 1 // link counting starts at 1 via r.pdf.AddLink } func (r *pdfReporter) addBreadcrumb(parsedModel *types.Model) { if len(r.currentChapterTitleBreadcrumb) > 0 { uni := r.pdf.UnicodeTranslatorFromDescriptor("") r.pdf.SetFont("Helvetica", "", 10) r.pdf.SetTextColor(127, 127, 127) r.pdf.Text(46.7, 24.5, uni(r.currentChapterTitleBreadcrumb+" - "+parsedModel.Title)) } } func (r *pdfReporter) parseBackgroundTemplate(templateFilename string) { /* imageBox, err := rice.FindBox("template") checkErr(err) file, err := os.CreateTemp("", "background-*-.r.pdf") checkErr(err) defer os.Remove(file.Title()) backgroundBytes := imageBox.MustBytes("background.r.pdf") err = os.WriteFile(file.Title(), backgroundBytes, 0644) checkErr(err) */ r.coverTemplateId = gofpdi.ImportPage(r.pdf, templateFilename, 1, "/MediaBox") r.contentTemplateId = gofpdi.ImportPage(r.pdf, templateFilename, 2, "/MediaBox") r.diagramLegendTemplateId = gofpdi.ImportPage(r.pdf, templateFilename, 3, "/MediaBox") } func (r *pdfReporter) createCover(parsedModel *types.Model) { uni := r.pdf.UnicodeTranslatorFromDescriptor("") r.pdf.AddPage() gofpdi.UseImportedTemplate(r.pdf, r.coverTemplateId, 0, 0, 0, 300) r.pdf.SetFont("Helvetica", "B", 28) r.pdf.SetTextColor(0, 0, 0) r.pdf.Text(40, 110, "Threat Model Report") r.pdf.Text(40, 125, uni(parsedModel.Title)) r.pdf.SetFont("Helvetica", "", 12) reportDate := parsedModel.Date if reportDate.IsZero() { reportDate = types.Date{Time: time.Now()} } r.pdf.Text(40.7, 145, reportDate.Format("2 January 2006")) r.pdf.Text(40.7, 153, uni(parsedModel.Author.Name)) r.pdf.SetFont("Helvetica", "", 10) r.pdf.SetTextColor(80, 80, 80) r.pdf.Text(8.6, 275, parsedModel.Author.Homepage) r.pdf.SetFont("Helvetica", "", 12) r.pdf.SetTextColor(0, 0, 0) } func (r *pdfReporter) createTableOfContents(parsedModel *types.Model) { uni := r.pdf.UnicodeTranslatorFromDescriptor("") r.pdf.AddPage() r.currentChapterTitleBreadcrumb = "Table of Contents" r.homeLink = r.pdf.AddLink() r.defineLinkTarget("{home}") gofpdi.UseImportedTemplate(r.pdf, r.contentTemplateId, 0, 0, 0, 300) r.pdf.SetFont("Helvetica", "B", fontSizeHeadline) r.pdf.Text(11, 40, "Table of Contents") r.pdf.SetFont("Helvetica", "", fontSizeBody) r.pdf.SetY(46) r.pdf.SetLineWidth(0.25) r.pdf.SetDrawColor(160, 160, 160) r.pdf.SetDashPattern([]float64{0.5, 0.5}, 0) // =============== var y float64 = 50 r.pdf.SetFont("Helvetica", "B", fontSizeBody) r.pdf.Text(11, y, "Results Overview") r.pdf.SetFont("Helvetica", "", fontSizeBody) y += 6 r.pdf.Text(11, y, " "+"Management Summary") r.pdf.Text(175, y, "{management-summary}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) risksStr := "Risks" catStr := "Categories" count, catCount := totalRiskCount(parsedModel), len(parsedModel.GeneratedRisksByCategory) if count == 1 { risksStr = "Risk" } if catCount == 1 { catStr = "category" } y += 6 r.pdf.Text(11, y, " "+"Impact Analysis of "+strconv.Itoa(count)+" Initial "+risksStr+" in "+strconv.Itoa(catCount)+" "+catStr) r.pdf.Text(175, y, "{impact-analysis-initial-risks}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 r.pdf.Text(11, y, " "+"Risk Mitigation") r.pdf.Text(175, y, "{risk-mitigation-status}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 r.pdf.Text(11, y, " "+"Asset Register") r.pdf.Text(175, y, "{asset-register}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 risksStr = "Risks" catStr = "Categories" count, catCount = len(filteredByStillAtRisk(parsedModel)), len(reduceToOnlyStillAtRisk(parsedModel.GeneratedRisksByCategoryWithCurrentStatus())) if count == 1 { risksStr = "Risk" } if catCount == 1 { catStr = "category" } r.pdf.Text(11, y, " "+"Impact Analysis of "+strconv.Itoa(count)+" Remaining "+risksStr+" in "+strconv.Itoa(catCount)+" "+catStr) r.pdf.Text(175, y, "{impact-analysis-remaining-risks}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 r.pdf.Text(11, y, " "+"Application Overview") r.pdf.Text(175, y, "{target-overview}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 r.pdf.Text(11, y, " "+"Data-Flow Diagram") r.pdf.Text(175, y, "{data-flow-diagram}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 r.pdf.Text(11, y, " "+"Security Requirements") r.pdf.Text(175, y, "{security-requirements}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 r.pdf.Text(11, y, " "+"Abuse Cases") r.pdf.Text(175, y, "{abuse-cases}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 r.pdf.Text(11, y, " "+"Tag Listing") r.pdf.Text(175, y, "{tag-listing}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 r.pdf.Text(11, y, " "+"STRIDE Classification of Identified Risks") r.pdf.Text(175, y, "{stride}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 r.pdf.Text(11, y, " "+"Assignment by Function") r.pdf.Text(175, y, "{function-assignment}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 r.pdf.Text(11, y, " "+"RAA Analysis") r.pdf.Text(175, y, "{raa-analysis}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 r.pdf.Text(11, y, " "+"Data Mapping") r.pdf.Text(175, y, "{data-risk-mapping}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) /* y += 6 assets := "assets" count = len(model.SortedTechnicalAssetsByQuickWinsAndTitle()) if count == 1 { assets = "asset" } r.pdf.Text(11, y, " "+"Data Risk Quick Wins: "+strconv.Itoa(count)+" "+assets) r.pdf.Text(175, y, "{data-risk-quick-wins}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) */ y += 6 assets := "Assets" count = len(parsedModel.OutOfScopeTechnicalAssets()) if count == 1 { assets = "Asset" } r.pdf.Text(11, y, " "+"Out-of-Scope Assets: "+strconv.Itoa(count)+" "+assets) r.pdf.Text(175, y, "{out-of-scope-assets}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 modelFailures := flattenRiskSlice(filterByModelFailures(parsedModel, parsedModel.GeneratedRisksByCategory)) risksStr = "Risks" count = len(modelFailures) if count == 1 { risksStr = "Risk" } countStillAtRisk := len(types.ReduceToOnlyStillAtRisk(modelFailures)) if countStillAtRisk > 0 { colorModelFailure(r.pdf) } r.pdf.Text(11, y, " "+"Potential Model Failures: "+strconv.Itoa(countStillAtRisk)+" / "+strconv.Itoa(count)+" "+risksStr) r.pdf.Text(175, y, "{model-failures}") r.pdfColorBlack() r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 questions := "Questions" count = len(parsedModel.Questions) if count == 1 { questions = "Question" } if questionsUnanswered(parsedModel) > 0 { colorModelFailure(r.pdf) } r.pdf.Text(11, y, " "+"Questions: "+strconv.Itoa(questionsUnanswered(parsedModel))+" / "+strconv.Itoa(count)+" "+questions) r.pdf.Text(175, y, "{questions}") r.pdfColorBlack() r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) // =============== if len(parsedModel.GeneratedRisksByCategory) > 0 { y += 6 y += 6 if y > 260 { // 260 instead of 275 for major group headlines to avoid "Schusterjungen" r.pageBreakInLists() y = 40 } r.pdf.SetFont("Helvetica", "B", fontSizeBody) r.pdf.SetTextColor(0, 0, 0) r.pdf.Text(11, y, "Risks by Vulnerability category") r.pdf.SetFont("Helvetica", "", fontSizeBody) y += 6 r.pdf.Text(11, y, " "+"Identified Risks by Vulnerability category") r.pdf.Text(175, y, "{intro-risks-by-vulnerability-category}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) for _, category := range parsedModel.SortedRiskCategories() { newRisksStr := parsedModel.SortedRisksOfCategory(category) switch types.HighestSeverityStillAtRisk(newRisksStr) { case types.CriticalSeverity: colorCriticalRisk(r.pdf) case types.HighSeverity: colorHighRisk(r.pdf) case types.ElevatedSeverity: colorElevatedRisk(r.pdf) case types.MediumSeverity: colorMediumRisk(r.pdf) case types.LowSeverity: colorLowRisk(r.pdf) default: r.pdfColorBlack() } if len(types.ReduceToOnlyStillAtRisk(newRisksStr)) == 0 { r.pdfColorBlack() } y += 6 if y > 275 { r.pageBreakInLists() y = 40 } countStillAtRisk := len(types.ReduceToOnlyStillAtRisk(newRisksStr)) suffix := strconv.Itoa(countStillAtRisk) + " / " + strconv.Itoa(len(newRisksStr)) + " Risk" if len(newRisksStr) != 1 { suffix += "s" } r.pdf.Text(11, y, " "+uni(category.Title)+": "+suffix) r.pdf.Text(175, y, "{"+category.ID+"}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.tocLinkIdByAssetId[category.ID] = r.pdf.AddLink() r.pdf.Link(10, y-5, 172.5, 6.5, r.tocLinkIdByAssetId[category.ID]) } } // =============== if len(parsedModel.TechnicalAssets) > 0 { y += 6 y += 6 if y > 260 { // 260 instead of 275 for major group headlines to avoid "Schusterjungen" r.pageBreakInLists() y = 40 } r.pdf.SetFont("Helvetica", "B", fontSizeBody) r.pdf.SetTextColor(0, 0, 0) r.pdf.Text(11, y, "Risks by Technical Asset") r.pdf.SetFont("Helvetica", "", fontSizeBody) y += 6 r.pdf.Text(11, y, " "+"Identified Risks by Technical Asset") r.pdf.Text(175, y, "{intro-risks-by-technical-asset}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) for _, technicalAsset := range sortedTechnicalAssetsByRiskSeverityAndTitle(parsedModel) { newRisksStr := parsedModel.GeneratedRisks(technicalAsset) y += 6 if y > 275 { r.pageBreakInLists() y = 40 } countStillAtRisk := len(types.ReduceToOnlyStillAtRisk(newRisksStr)) suffix := strconv.Itoa(countStillAtRisk) + " / " + strconv.Itoa(len(newRisksStr)) + " Risk" if len(newRisksStr) != 1 { suffix += "s" } if technicalAsset.OutOfScope { r.pdfColorOutOfScope() suffix = "out-of-scope" } else { switch types.HighestSeverityStillAtRisk(newRisksStr) { case types.CriticalSeverity: colorCriticalRisk(r.pdf) case types.HighSeverity: colorHighRisk(r.pdf) case types.ElevatedSeverity: colorElevatedRisk(r.pdf) case types.MediumSeverity: colorMediumRisk(r.pdf) case types.LowSeverity: colorLowRisk(r.pdf) default: r.pdfColorBlack() } if len(types.ReduceToOnlyStillAtRisk(newRisksStr)) == 0 { r.pdfColorBlack() } } r.pdf.Text(11, y, " "+uni(technicalAsset.Title)+": "+suffix) r.pdf.Text(175, y, "{"+technicalAsset.Id+"}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.tocLinkIdByAssetId[technicalAsset.Id] = r.pdf.AddLink() r.pdf.Link(10, y-5, 172.5, 6.5, r.tocLinkIdByAssetId[technicalAsset.Id]) } } // =============== if len(parsedModel.DataAssets) > 0 { y += 6 y += 6 if y > 260 { // 260 instead of 275 for major group headlines to avoid "Schusterjungen" r.pageBreakInLists() y = 40 } r.pdf.SetFont("Helvetica", "B", fontSizeBody) r.pdfColorBlack() r.pdf.Text(11, y, "Data Breach Probabilities by Data Asset") r.pdf.SetFont("Helvetica", "", fontSizeBody) y += 6 r.pdf.Text(11, y, " "+"Identified Data Breach Probabilities by Data Asset") r.pdf.Text(175, y, "{intro-risks-by-data-asset}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) for _, dataAsset := range sortedDataAssetsByDataBreachProbabilityAndTitle(parsedModel) { y += 6 if y > 275 { r.pageBreakInLists() y = 40 } newRisksStr := parsedModel.IdentifiedDataBreachProbabilityRisks(dataAsset) countStillAtRisk := len(types.ReduceToOnlyStillAtRisk(newRisksStr)) suffix := strconv.Itoa(countStillAtRisk) + " / " + strconv.Itoa(len(newRisksStr)) + " Risk" if len(newRisksStr) != 1 { suffix += "s" } switch identifiedDataBreachProbabilityStillAtRisk(parsedModel, dataAsset) { case types.Probable: colorHighRisk(r.pdf) case types.Possible: colorMediumRisk(r.pdf) case types.Improbable: colorLowRisk(r.pdf) default: r.pdfColorBlack() } if !isDataBreachPotentialStillAtRisk(parsedModel, dataAsset) { r.pdfColorBlack() } r.pdf.Text(11, y, " "+uni(dataAsset.Title)+": "+suffix) r.pdf.Text(175, y, "{data:"+dataAsset.Id+"}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.tocLinkIdByAssetId[dataAsset.Id] = r.pdf.AddLink() r.pdf.Link(10, y-5, 172.5, 6.5, r.tocLinkIdByAssetId[dataAsset.Id]) } } // =============== if len(parsedModel.TrustBoundaries) > 0 { y += 6 y += 6 if y > 260 { // 260 instead of 275 for major group headlines to avoid "Schusterjungen" r.pageBreakInLists() y = 40 } r.pdf.SetFont("Helvetica", "B", fontSizeBody) r.pdfColorBlack() r.pdf.Text(11, y, "Trust Boundaries") r.pdf.SetFont("Helvetica", "", fontSizeBody) for _, key := range sortedKeysOfTrustBoundaries(parsedModel) { trustBoundary := parsedModel.TrustBoundaries[key] y += 6 if y > 275 { r.pageBreakInLists() y = 40 } colorTwilight(r.pdf) if !trustBoundary.Type.IsNetworkBoundary() { r.pdfColorLightGray() } r.pdf.Text(11, y, " "+uni(trustBoundary.Title)) r.pdf.Text(175, y, "{boundary:"+trustBoundary.Id+"}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.tocLinkIdByAssetId[trustBoundary.Id] = r.pdf.AddLink() r.pdf.Link(10, y-5, 172.5, 6.5, r.tocLinkIdByAssetId[trustBoundary.Id]) } r.pdfColorBlack() } // =============== if len(parsedModel.SharedRuntimes) > 0 { y += 6 y += 6 if y > 260 { // 260 instead of 275 for major group headlines to avoid "Schusterjungen" r.pageBreakInLists() y = 40 } r.pdf.SetFont("Helvetica", "B", fontSizeBody) r.pdfColorBlack() r.pdf.Text(11, y, "Shared Runtime") r.pdf.SetFont("Helvetica", "", fontSizeBody) for _, key := range sortedKeysOfSharedRuntime(parsedModel) { sharedRuntime := parsedModel.SharedRuntimes[key] y += 6 if y > 275 { r.pageBreakInLists() y = 40 } r.pdf.Text(11, y, " "+uni(sharedRuntime.Title)) r.pdf.Text(175, y, "{runtime:"+sharedRuntime.Id+"}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.tocLinkIdByAssetId[sharedRuntime.Id] = r.pdf.AddLink() r.pdf.Link(10, y-5, 172.5, 6.5, r.tocLinkIdByAssetId[sharedRuntime.Id]) } } // =============== y += 6 y += 6 if y > 260 { // 260 instead of 275 for major group headlines to avoid "Schusterjungen" r.pageBreakInLists() y = 40 } r.pdfColorBlack() r.pdf.SetFont("Helvetica", "B", fontSizeBody) r.pdf.Text(11, y, "About Threagile") r.pdf.SetFont("Helvetica", "", fontSizeBody) y += 6 if y > 275 { r.pageBreakInLists() y = 40 } r.pdf.Text(11, y, " "+"Risk Rules Checked by Threagile") r.pdf.Text(175, y, "{risk-rules-checked}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) y += 6 if y > 275 { r.pageBreakInLists() y = 40 } r.pdfColorDisclaimer() r.pdf.Text(11, y, " "+"Disclaimer") r.pdf.Text(175, y, "{disclaimer}") r.pdf.Line(15.6, y+1.3, 11+171.5, y+1.3) r.pdf.Link(10, y-5, 172.5, 6.5, r.pdf.AddLink()) r.pdfColorBlack() r.pdf.SetDrawColor(0, 0, 0) r.pdf.SetDashPattern([]float64{}, 0) // Now write all the sections/pages. Before we start writing, we use `RegisterAlias` to // ensure that the alias written in the table of contents will be replaced // by the current page number. --> See the "r.pdf.RegisterAlias()" calls during the PDF creation in this file } // as in Go ranging over map is random order, range over them in sorted (hence reproducible) way: func sortedKeysOfTrustBoundaries(model *types.Model) []string { keys := make([]string, 0) for k := range model.TrustBoundaries { keys = append(keys, k) } sort.Strings(keys) return keys } // as in Go ranging over map is random order, range over them in sorted (hence reproducible) way: func sortedKeysOfSharedRuntime(model *types.Model) []string { keys := make([]string, 0) for k := range model.SharedRuntimes { keys = append(keys, k) } sort.Strings(keys) return keys } func sortByTechnicalAssetRiskSeverityAndTitleStillAtRisk(assets []*types.TechnicalAsset, parsedModel *types.Model) { sort.Slice(assets, func(i, j int) bool { risksLeft := types.ReduceToOnlyStillAtRisk(parsedModel.GeneratedRisks(assets[i])) risksRight := types.ReduceToOnlyStillAtRisk(parsedModel.GeneratedRisks(assets[j])) highestSeverityLeft := types.HighestSeverityStillAtRisk(risksLeft) highestSeverityRight := types.HighestSeverityStillAtRisk(risksRight) var result bool if highestSeverityLeft == highestSeverityRight { if len(risksLeft) == 0 && len(risksRight) > 0 { return false } else if len(risksLeft) > 0 && len(risksRight) == 0 { return true } else { result = assets[i].Title < assets[j].Title } } else { result = highestSeverityLeft > highestSeverityRight } if assets[i].OutOfScope && assets[j].OutOfScope { result = assets[i].Title < assets[j].Title } else if assets[i].OutOfScope { result = false } else if assets[j].OutOfScope { result = true } return result }) } func sortedDataAssetsByDataBreachProbabilityAndTitle(parsedModel *types.Model) []*types.DataAsset { assets := make([]*types.DataAsset, 0) for _, asset := range parsedModel.DataAssets { assets = append(assets, asset) } sortByDataAssetDataBreachProbabilityAndTitleStillAtRisk(parsedModel, assets) return assets } func sortByDataAssetDataBreachProbabilityAndTitleStillAtRisk(parsedModel *types.Model, assets []*types.DataAsset) { sort.Slice(assets, func(i, j int) bool { risksLeft := identifiedDataBreachProbabilityRisksStillAtRisk(parsedModel, assets[i]) risksRight := identifiedDataBreachProbabilityRisksStillAtRisk(parsedModel, assets[j]) highestDataBreachProbabilityLeft := identifiedDataBreachProbabilityStillAtRisk(parsedModel, assets[i]) highestDataBreachProbabilityRight := identifiedDataBreachProbabilityStillAtRisk(parsedModel, assets[j]) if highestDataBreachProbabilityLeft == highestDataBreachProbabilityRight { if len(risksLeft) == 0 && len(risksRight) > 0 { return false } if len(risksLeft) > 0 && len(risksRight) == 0 { return true } return assets[i].Title < assets[j].Title } return highestDataBreachProbabilityLeft > highestDataBreachProbabilityRight }) } func (r *pdfReporter) defineLinkTarget(alias string) { pageNumbStr := strconv.Itoa(r.pdf.PageNo()) if len(pageNumbStr) == 1 { pageNumbStr = " " + pageNumbStr } else if len(pageNumbStr) == 2 { pageNumbStr = " " + pageNumbStr } r.pdf.RegisterAlias(alias, pageNumbStr) r.pdf.SetLink(r.linkCounter, 0, -1) r.linkCounter++ } func (r *pdfReporter) createDisclaimer(parsedModel *types.Model) { r.pdf.AddPage() r.currentChapterTitleBreadcrumb = "Disclaimer" r.defineLinkTarget("{disclaimer}") gofpdi.UseImportedTemplate(r.pdf, r.contentTemplateId, 0, 0, 0, 300) r.pdfColorDisclaimer() r.pdf.SetFont("Helvetica", "B", fontSizeHeadline) r.pdf.Text(11, 40, "Disclaimer") r.pdf.SetFont("Helvetica", "", fontSizeBody) r.pdf.SetY(46) var disclaimer strings.Builder disclaimer.WriteString(parsedModel.Author.Name + " conducted this threat analysis using the open-source Threagile toolkit " + "on the applications and systems that were modeled as of this report's date. " + "Information security threats are continually changing, with new " + "vulnerabilities discovered on a daily basis, and no application can ever be 100% secure no matter how much " + "threat modeling is conducted. It is recommended to execute threat modeling and also penetration testing on a regular basis " + "(for example yearly) to ensure a high ongoing level of security and constantly check for new attack vectors. " + "<br><br>" + "This report cannot and does not protect against personal or business loss as the result of use of the " + "applications or systems described. " + parsedModel.Author.Name + " and the Threagile toolkit offers no warranties, representations or " + "legal certifications concerning the applications or systems it tests. All software includes defects: nothing " + "in this document is intended to represent or warrant that threat modeling was complete and without error, " + "nor does this document represent or warrant that the architecture analyzed is suitable to task, free of other " + "defects than reported, fully compliant with any industry standards, or fully compatible with any operating " + "system, hardware, or other application. Threat modeling tries to analyze the modeled architecture without " + "having access to a real working system and thus cannot and does not test the implementation for defects and vulnerabilities. " + "These kinds of checks would only be possible with a separate code review and penetration test against " + "a working system and not via a threat model." + "<br><br>" + "By using the resulting information you agree that " + parsedModel.Author.Name + " and the Threagile toolkit " + "shall be held harmless in any event." + "<br><br>" + "This report is confidential and intended for internal, confidential use by the client. The recipient " + "is obligated to ensure the highly confidential contents are kept secret. The recipient assumes responsibility " + "for further distribution of this document." + "<br><br>" + "In this particular project, a time box approach was used to define the analysis effort. This means that the " + "author allotted a prearranged amount of time to identify and document threats. Because of this, there " + "is no guarantee that all possible threats and risks are discovered. Furthermore, the analysis " + "applies to a snapshot of the current state of the modeled architecture (based on the architecture information provided " + "by the customer) at the examination time." + "<br><br><br>" + "<b>Report Distribution</b>" + "<br><br>" + "Distribution of this report (in full or in part like diagrams or risk findings) requires that this disclaimer " + "as well as the chapter about the Threagile toolkit and method used is kept intact as part of the " + "distributed report or referenced from the distributed parts.") html := r.pdf.HTMLBasicNew() uni := r.pdf.UnicodeTranslatorFromDescriptor("") html.Write(5, uni(disclaimer.String())) r.pdfColorBlack() } func (r *pdfReporter) createManagementSummary(parsedModel *types.Model, tempFolder string) error { uni := r.pdf.UnicodeTranslatorFromDescriptor("") r.pdf.SetTextColor(0, 0, 0) title := "Management Summary" r.addHeadline(title, false) r.defineLinkTarget("{management-summary}") r.currentChapterTitleBreadcrumb = title countCritical := len(filteredBySeverity(parsedModel, types.CriticalSeverity)) countHigh := len(filteredBySeverity(parsedModel, types.HighSeverity)) countElevated := len(filteredBySeverity(parsedModel, types.ElevatedSeverity)) countMedium := len(filteredBySeverity(parsedModel, types.MediumSeverity)) countLow := len(filteredBySeverity(parsedModel, types.LowSeverity)) countStatusUnchecked := len(filteredByRiskStatus(parsedModel, types.Unchecked)) countStatusInDiscussion := len(filteredByRiskStatus(parsedModel, types.InDiscussion)) countStatusAccepted := len(filteredByRiskStatus(parsedModel, types.Accepted)) countStatusInProgress := len(filteredByRiskStatus(parsedModel, types.InProgress)) countStatusMitigated := len(filteredByRiskStatus(parsedModel, types.Mitigated)) countStatusFalsePositive := len(filteredByRiskStatus(parsedModel, types.FalsePositive)) html := r.pdf.HTMLBasicNew() html.Write(5, "Threagile toolkit was used to model the architecture of \""+uni(parsedModel.Title)+"\" "+ "and derive risks by analyzing the components and data flows. The risks identified during this analysis are shown "+ "in the following chapters. Identified risks during threat modeling do not necessarily mean that the "+ "vulnerability associated with this risk actually exists: it is more to be seen as a list of potential risks and "+ "threats, which should be individually reviewed and reduced by removing false positives. For the remaining risks it should "+ "be checked in the design and implementation of \""+uni(parsedModel.Title)+"\" whether the mitigation advices "+ "have been applied or not."+ "<br><br>"+ "Each risk finding references a chapter of the OWASP ASVS (Application Security Verification Standard) audit checklist. "+ "The OWASP ASVS checklist should be considered as an inspiration by architects and developers to further harden "+ "the application in a Defense-in-Depth approach. Additionally, for each risk finding a "+ "link towards a matching OWASP Cheat Sheet or similar with technical details about how to implement a mitigation is given."+ "<br><br>"+ "In total <b>"+strconv.Itoa(totalRiskCount(parsedModel))+" initial risks</b> in <b>"+strconv.Itoa(len(parsedModel.GeneratedRisksByCategory))+" categories</b> have "+ "been identified during the threat modeling process:<br><br>") // TODO plural singular stuff risk/s category/ies has/have r.pdf.SetFont("Helvetica", "B", fontSizeBody) r.pdf.CellFormat(17, 6, "", "0", 0, "", false, 0, "") r.pdf.CellFormat(10, 6, "", "0", 0, "", false, 0, "") r.pdf.CellFormat(60, 6, "", "0", 0, "", false, 0, "") colorRiskStatusUnchecked(r.pdf) r.pdf.CellFormat(23, 6, "", "0", 0, "", false, 0, "") r.pdf.CellFormat(10, 6, strconv.Itoa(countStatusUnchecked), "0", 0, "R", false, 0, "") r.pdf.CellFormat(60, 6, "unchecked", "0", 0, "", false, 0, "") r.pdf.Ln(-1) colorCriticalRisk(r.pdf) r.pdf.CellFormat(17, 6, "", "0", 0, "", false, 0, "") r.pdf.CellFormat(10, 6, strconv.Itoa(countCritical), "0", 0, "R", false, 0, "") r.pdf.CellFormat(60, 6, "critical risk", "0", 0, "", false, 0, "") colorRiskStatusInDiscussion(r.pdf) r.pdf.CellFormat(23, 6, "", "0", 0, "", false, 0, "") r.pdf.CellFormat(10, 6, strconv.Itoa(countStatusInDiscussion), "0", 0, "R", false, 0, "") r.pdf.CellFormat(60, 6, "in discussion", "0", 0, "", false, 0, "") r.pdf.Ln(-1) colorHighRisk(r.pdf) r.pdf.CellFormat(17, 6, "", "0", 0, "", false, 0, "") r.pdf.CellFormat(10, 6, strconv.Itoa(countHigh), "0", 0, "R", false, 0, "") r.pdf.CellFormat(60, 6, "high risk", "0", 0, "", false, 0, "") colorRiskStatusAccepted(r.pdf) r.pdf.CellFormat(23, 6, "", "0", 0, "", false, 0, "") r.pdf.CellFormat(10, 6, strconv.Itoa(countStatusAccepted), "0", 0, "R", false, 0, "") r.pdf.CellFormat(60, 6, "accepted", "0", 0, "", false, 0, "") r.pdf.Ln(-1) colorElevatedRisk(r.pdf) r.pdf.CellFormat(17, 6, "", "0", 0, "", false, 0, "") r.pdf.CellFormat(10, 6, strconv.Itoa(countElevated), "0", 0, "R", false, 0, "") r.pdf.CellFormat(60, 6, "elevated risk", "0", 0, "", false, 0, "") colorRiskStatusInProgress(r.pdf) r.pdf.CellFormat(23, 6, "", "0", 0, "", false, 0, "") r.pdf.CellFormat(10, 6, strconv.Itoa(countStatusInProgress), "0", 0, "R", false, 0, "") r.pdf.CellFormat(60, 6, "in progress", "0", 0, "", false, 0, "") r.pdf.Ln(-1) colorMediumRisk(r.pdf) r.pdf.CellFormat(17, 6, "", "0", 0, "", false, 0, "") r.pdf.CellFormat(10, 6, strconv.Itoa(countMedium), "0", 0, "R", false, 0, "") r.pdf.CellFormat(60, 6, "medium risk", "0", 0, "", false, 0, "") colorRiskStatusMitigated(r.pdf) r.pdf.CellFormat(23, 6, "", "0", 0, "", false, 0, "") r.pdf.CellFormat(10, 6, strconv.Itoa(countStatusMitigated), "0", 0, "R", false, 0, "") r.pdf.SetFont("Helvetica", "BI", fontSizeBody) r.pdf.CellFormat(60, 6, "mitigated", "0", 0, "", false, 0, "") r.pdf.SetFont("Helvetica", "B", fontSizeBody) r.pdf.Ln(-1)
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
true
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/json.go
pkg/report/json.go
package report import ( "encoding/json" "fmt" "os" "github.com/threagile/threagile/pkg/types" ) func WriteRisksJSON(parsedModel *types.Model, filename string) error { jsonBytes, err := json.Marshal(parsedModel.AllRisks()) if err != nil { return fmt.Errorf("failed to marshal risks to JSON: %w", err) } err = os.WriteFile(filename, jsonBytes, 0600) if err != nil { return fmt.Errorf("failed to write risks to JSON file: %w", err) } return nil } // TODO: also a "data assets" json? func WriteTechnicalAssetsJSON(parsedModel *types.Model, filename string) error { jsonBytes, err := json.Marshal(parsedModel.TechnicalAssets) if err != nil { return fmt.Errorf("failed to marshal technical assets to JSON: %w", err) } err = os.WriteFile(filename, jsonBytes, 0600) if err != nil { return fmt.Errorf("failed to write technical assets to JSON file: %w", err) } return nil } func WriteStatsJSON(parsedModel *types.Model, filename string) error { jsonBytes, err := json.Marshal(overallRiskStatistics(parsedModel)) if err != nil { return fmt.Errorf("failed to marshal stats to JSON: %w", err) } err = os.WriteFile(filename, jsonBytes, 0600) if err != nil { return fmt.Errorf("failed to write stats to JSON file: %w", err) } return nil } func overallRiskStatistics(parsedModel *types.Model) riskStatistics { result := riskStatistics{} result.Risks = make(map[string]map[string]int) result.Risks[types.CriticalSeverity.String()] = make(map[string]int) result.Risks[types.CriticalSeverity.String()][types.Unchecked.String()] = 0 result.Risks[types.CriticalSeverity.String()][types.InDiscussion.String()] = 0 result.Risks[types.CriticalSeverity.String()][types.Accepted.String()] = 0 result.Risks[types.CriticalSeverity.String()][types.InProgress.String()] = 0 result.Risks[types.CriticalSeverity.String()][types.Mitigated.String()] = 0 result.Risks[types.CriticalSeverity.String()][types.FalsePositive.String()] = 0 result.Risks[types.HighSeverity.String()] = make(map[string]int) result.Risks[types.HighSeverity.String()][types.Unchecked.String()] = 0 result.Risks[types.HighSeverity.String()][types.InDiscussion.String()] = 0 result.Risks[types.HighSeverity.String()][types.Accepted.String()] = 0 result.Risks[types.HighSeverity.String()][types.InProgress.String()] = 0 result.Risks[types.HighSeverity.String()][types.Mitigated.String()] = 0 result.Risks[types.HighSeverity.String()][types.FalsePositive.String()] = 0 result.Risks[types.ElevatedSeverity.String()] = make(map[string]int) result.Risks[types.ElevatedSeverity.String()][types.Unchecked.String()] = 0 result.Risks[types.ElevatedSeverity.String()][types.InDiscussion.String()] = 0 result.Risks[types.ElevatedSeverity.String()][types.Accepted.String()] = 0 result.Risks[types.ElevatedSeverity.String()][types.InProgress.String()] = 0 result.Risks[types.ElevatedSeverity.String()][types.Mitigated.String()] = 0 result.Risks[types.ElevatedSeverity.String()][types.FalsePositive.String()] = 0 result.Risks[types.MediumSeverity.String()] = make(map[string]int) result.Risks[types.MediumSeverity.String()][types.Unchecked.String()] = 0 result.Risks[types.MediumSeverity.String()][types.InDiscussion.String()] = 0 result.Risks[types.MediumSeverity.String()][types.Accepted.String()] = 0 result.Risks[types.MediumSeverity.String()][types.InProgress.String()] = 0 result.Risks[types.MediumSeverity.String()][types.Mitigated.String()] = 0 result.Risks[types.MediumSeverity.String()][types.FalsePositive.String()] = 0 result.Risks[types.LowSeverity.String()] = make(map[string]int) result.Risks[types.LowSeverity.String()][types.Unchecked.String()] = 0 result.Risks[types.LowSeverity.String()][types.InDiscussion.String()] = 0 result.Risks[types.LowSeverity.String()][types.Accepted.String()] = 0 result.Risks[types.LowSeverity.String()][types.InProgress.String()] = 0 result.Risks[types.LowSeverity.String()][types.Mitigated.String()] = 0 result.Risks[types.LowSeverity.String()][types.FalsePositive.String()] = 0 for _, risks := range parsedModel.GeneratedRisksByCategory { for _, risk := range risks { result.Risks[risk.Severity.String()][risk.RiskStatus.String()]++ } } return result } type riskStatistics struct { // TODO add also some more like before / after (i.e. with mitigation applied) Risks map[string]map[string]int `yaml:"risks" json:"risks"` }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/risk-group.go
pkg/report/risk-group.go
package report import ( "fmt" "github.com/mpvl/unique" "github.com/xuri/excelize/v2" "sort" ) type RiskGroup struct { Groups map[string]*RiskGroup Items []RiskItem } func (what *RiskGroup) Init(riskItems []RiskItem) *RiskGroup { *what = RiskGroup{ Groups: make(map[string]*RiskGroup), Items: riskItems, } return what } func (what *RiskGroup) SortedGroups() []string { groups := make([]string, 0) for group := range what.Groups { groups = append(groups, group) } sort.Strings(groups) unique.Strings(&groups) return groups } func (what *RiskGroup) Make(riskItems []RiskItem, columns ExcelColumns, groupBy []string) (*RiskGroup, error) { what.Init(riskItems) if len(groupBy) == 0 { return what, nil } groupName, groupBy := groupBy[0], groupBy[1:] column := columns.FindColumnIndexByTitle(groupName) if column < 0 { return what, fmt.Errorf("unable to find column %q", groupName) } values := what.uniqueValues(column) for _, value := range values { subItems := make([]RiskItem, 0) for _, item := range what.Items { if item.Columns[column] == value { subItems = append(subItems, item) } } group, groupError := new(RiskGroup).Make(subItems, columns, groupBy) if groupError != nil { return what, fmt.Errorf("unable to create group: %w", groupError) } what.Groups[value] = group } return what, nil } func (what *RiskGroup) Write(excel *excelize.File, sheetName string, cellStyles *ExcelStyles) error { if len(what.Groups) == 0 { _, writeError := what.writeGroup(excel, sheetName, cellStyles, 0) return writeError } var writeError error excelRow := 0 for _, group := range what.SortedGroups() { excelRow, writeError = what.Groups[group].writeGroup(excel, sheetName, cellStyles, excelRow) if writeError != nil { return writeError } } return writeError } func (what *RiskGroup) writeGroup(excel *excelize.File, sheetName string, cellStyles *ExcelStyles, excelRow int) (int, error) { for _, risk := range what.Items { excelRow++ for columnIndex, column := range risk.Columns { cellName, coordinatesToCellNameError := excelize.CoordinatesToCellName(columnIndex+1, excelRow+1) if coordinatesToCellNameError != nil { return excelRow, fmt.Errorf("failed to get cell coordinates from [%d, %d]: %w", columnIndex+1, excelRow+1, coordinatesToCellNameError) } setCellValueError := excel.SetCellValue(sheetName, cellName, column) if setCellValueError != nil { return excelRow, setCellValueError } columnName, columnNameError := excelize.ColumnNumberToName(columnIndex + 1) if columnNameError != nil { return excelRow, fmt.Errorf("failed to get cell coordinates from column [%d]: %w", columnIndex+1, columnNameError) } setCellStyleError := excel.SetCellStyle(sheetName, cellName, cellName, cellStyles.Get(columnName, risk.Status, risk.Severity)) if setCellStyleError != nil { return excelRow, fmt.Errorf("failed to set cell style: %w", setCellStyleError) } } } return excelRow, nil } func (what *RiskGroup) uniqueValues(column int) []string { values := make([]string, 0) for _, risk := range what.Items { values = append(values, risk.Columns[column]) } sort.Strings(values) unique.Strings(&values) return values }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/risks.go
pkg/risks/risks.go
package risks import ( "embed" "fmt" "github.com/threagile/threagile/pkg/risks/script" "io/fs" "github.com/threagile/threagile/pkg/risks/builtin" "github.com/threagile/threagile/pkg/types" ) func GetBuiltInRiskRules() types.RiskRules { rules := make(types.RiskRules) for _, rule := range []types.RiskRule{ builtin.NewAccidentalSecretLeakRule(), builtin.NewCodeBackdooringRule(), builtin.NewContainerBaseImageBackdooringRule(), builtin.NewContainerPlatformEscapeRule(), builtin.NewCrossSiteRequestForgeryRule(), builtin.NewCrossSiteScriptingRule(), builtin.NewDosRiskyAccessAcrossTrustBoundaryRule(), builtin.NewIncompleteModelRule(), builtin.NewLdapInjectionRule(), builtin.NewMissingAuthenticationRule(), builtin.NewMissingAuthenticationSecondFactorRule(builtin.NewMissingAuthenticationRule()), builtin.NewMissingBuildInfrastructureRule(), builtin.NewMissingCloudHardeningRule(), builtin.NewMissingFileValidationRule(), builtin.NewMissingHardeningRule(), builtin.NewMissingIdentityPropagationRule(), builtin.NewMissingIdentityProviderIsolationRule(), builtin.NewMissingIdentityStoreRule(), builtin.NewMissingNetworkSegmentationRule(), builtin.NewMissingVaultRule(), builtin.NewMissingVaultIsolationRule(), builtin.NewMissingWafRule(), builtin.NewMixedTargetsOnSharedRuntimeRule(), builtin.NewPathTraversalRule(), builtin.NewPushInsteadPullDeploymentRule(), builtin.NewSearchQueryInjectionRule(), builtin.NewServerSideRequestForgeryRule(), builtin.NewServiceRegistryPoisoningRule(), builtin.NewSqlNoSqlInjectionRule(), builtin.NewUncheckedDeploymentRule(), builtin.NewUnencryptedAssetRule(), builtin.NewUnencryptedCommunicationRule(), builtin.NewUnguardedAccessFromInternetRule(), builtin.NewUnguardedDirectDatastoreAccessRule(), builtin.NewUnnecessaryCommunicationLinkRule(), builtin.NewUnnecessaryDataAssetRule(), builtin.NewUnnecessaryDataTransferRule(), builtin.NewUnnecessaryTechnicalAssetRule(), builtin.NewUntrustedDeserializationRule(), builtin.NewWrongCommunicationLinkContentRule(), builtin.NewWrongTrustBoundaryContentRule(), builtin.NewXmlExternalEntityRule(), } { rules[rule.Category().ID] = rule } scriptRules, scriptError := GetScriptRiskRules() if scriptError != nil { fmt.Printf("error loading script risk rules: %v\n", scriptError) return rules } for id, rule := range scriptRules { builtinRule, ok := rules[id] if ok && builtinRule != nil { fmt.Printf("WARNING: script risk rule %q shadows built-in risk rule\n", id) } rules[id] = rule } return rules } //go:embed scripts/*.yaml var ruleScripts embed.FS type RiskRules types.RiskRules func GetScriptRiskRules() (RiskRules, error) { return make(RiskRules).LoadRiskRules() } func (what RiskRules) LoadRiskRules() (RiskRules, error) { fileSystem := ruleScripts walkError := fs.WalkDir(fileSystem, "scripts", func(path string, entry fs.DirEntry, err error) error { if err != nil { return err } newRule := new(script.RiskRule).Init() loadError := newRule.Load(fileSystem, path, entry) if loadError != nil { return loadError } if newRule.Category().ID == "" { return nil } what[newRule.Category().ID] = newRule return nil }) if walkError != nil { return nil, walkError } return what, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/scripts/accidental_secret_leak_test.go
pkg/risks/scripts/accidental_secret_leak_test.go
package scripts import ( _ "embed" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/risks/script" "github.com/threagile/threagile/pkg/types" ) // TODO: fix when there are no technical assets in scope // func TestAccidentalSecretLeakRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { // rule := loadAccidentalSecretLeakRule() // risks, err := rule.GenerateRisks(&types.Model{}) // assert.Nil(t, err) // assert.Empty(t, risks) // } func TestAccidentalSecretLeakRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := loadAccidentalSecretLeakRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestAccidentalSecretLeakRuleGenerateRisksTechAssetNotContainSecretsNotRisksCreated(t *testing.T) { rule := loadAccidentalSecretLeakRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.MayContainSecrets: false, types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } // TODO: fix the test // func TestAccidentalSecretLeakRuleGenerateRisksTechAssetGitContainSecretsRisksCreated(t *testing.T) { // rule := loadAccidentalSecretLeakRule() // risks, err := rule.GenerateRisks(&types.Model{ // TechnicalAssets: map[string]*types.TechnicalAsset{ // "ta1": { // Technologies: types.TechnologyList{ // { // Name: "git repository", // Attributes: map[string]bool{ // types.MayContainSecrets: true, // }, // }, // }, // Tags: []string{"git"}, // }, // }, // }) // assert.Nil(t, err) // assert.Equal(t, len(risks), 1) // assert.Contains(t, risks[0].Title, "Accidental Secret Leak (Git)") // } // TODO: fix the test // func TestAccidentalSecretLeakRuleGenerateRisksTechAssetNotGitContainSecretsRisksCreated(t *testing.T) { // rule := loadAccidentalSecretLeakRule() // risks, err := rule.GenerateRisks(&types.Model{ // TechnicalAssets: map[string]*types.TechnicalAsset{ // "ta1": { // Technologies: types.TechnologyList{ // { // Name: "git repository", // Attributes: map[string]bool{ // types.MayContainSecrets: true, // }, // }, // }, // }, // }, // }) // assert.Nil(t, err) // assert.Equal(t, len(risks), 1) // assert.Equal(t, "<b>Accidental Secret Leak</b> risk at <b></b>", risks[0].Title) // } // TODO: fix the test // func TestAccidentalSecretLeakRuleGenerateRisksTechAssetProcessStrictlyConfidentialDataAssetHighImpactRiskCreated(t *testing.T) { // rule := loadAccidentalSecretLeakRule() // risks, err := rule.GenerateRisks(&types.Model{ // TechnicalAssets: map[string]*types.TechnicalAsset{ // "ta1": { // Technologies: types.TechnologyList{ // { // Name: "git repository", // Attributes: map[string]bool{ // types.MayContainSecrets: true, // }, // }, // }, // DataAssetsProcessed: []string{"confidential-data-asset", "strictly-confidential-data-asset"}, // }, // }, // DataAssets: map[string]*types.DataAsset{ // "confidential-data-asset": { // Confidentiality: types.Confidential, // }, // "strictly-confidential-data-asset": { // Confidentiality: types.StrictlyConfidential, // }, // }, // }) // assert.Nil(t, err) // assert.Equal(t, len(risks), 1) // assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) // } //go:embed accidental-secret-leak.yaml var accidental_secret_leak string func loadAccidentalSecretLeakRule() types.RiskRule { result := new(script.RiskRule).Init() riskRule, _ := result.ParseFromData([]byte(accidental_secret_leak)) return riskRule }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/method.go
pkg/risks/script/method.go
package script type Method struct { Name string Parameters []Variable }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/script.go
pkg/risks/script/script.go
package script import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" "github.com/threagile/threagile/pkg/risks/script/expressions" "github.com/threagile/threagile/pkg/risks/script/statements" "strings" "github.com/threagile/threagile/pkg/types" "gopkg.in/yaml.v3" ) type Script struct { id map[string]any match common.Statement data map[string]any utils map[string]*statements.MethodStatement formatter formatter } type formatter interface { AddLineNumbers(script any) string } func NewScript(f formatter) *Script { s := new(Script) s.formatter = f return s } func (what *Script) NewScope(risk *types.RiskCategory) (*common.Scope, error) { methods := make(map[string]common.Statement) for name, method := range what.utils { methods[name] = method } scope := new(common.Scope) scopeError := scope.Init(risk, methods) if scopeError != nil { return scope, fmt.Errorf("error initializing scope: %w", scopeError) } return scope, nil } func (what *Script) ParseScriptsFromData(text []byte) (map[string]*Script, error) { items := make(map[string]any) parseError := yaml.Unmarshal(text, &items) if parseError != nil { return nil, parseError } return what.ParseScripts(items) } func (what *Script) ParseScripts(items map[string]any) (map[string]*Script, error) { for key, value := range items { switch strings.ToLower(key) { case "individual_risk_categories": riskScripts, ok := value.(map[string]any) if !ok { return nil, fmt.Errorf("unexpected format %T in data definition", value) } scripts := make(map[string]*Script) for scriptID, riskScript := range riskScripts { risk, ok := riskScript.(map[string]any) if !ok { return nil, fmt.Errorf("unexpected format %T in data definition for %q", riskScript, scriptID) } script, scriptError := NewScript(what.formatter).ParseScript(risk) if scriptError != nil { return nil, fmt.Errorf("failed to parse script of data definition for %q: %w", scriptID, scriptError) } scripts[scriptID] = script } return scripts, nil default: return nil, fmt.Errorf("unexpected key %q in data definition", key) } } return nil, fmt.Errorf("no scripts found") } func (what *Script) ParseCategoryFromData(text []byte) (*Script, error) { items := make(map[string]any) parseError := yaml.Unmarshal(text, &items) if parseError != nil { return nil, parseError } return what.ParseCategory(items) } func (what *Script) ParseCategory(script map[string]any) (*Script, error) { for key, value := range script { switch strings.ToLower(key) { case common.Risk: switch castValue := value.(type) { case map[string]any: return what.ParseScript(castValue) default: return what, fmt.Errorf("failed to parse %q: unexpected script type %T\nscript:\n%v", key, value, what.formatter.AddLineNumbers(value)) } } } return what, nil } func (what *Script) ParseScriptFromData(text []byte) (*Script, error) { items := make(map[string]any) parseError := yaml.Unmarshal(text, &items) if parseError != nil { return nil, parseError } return what.ParseScript(items) } func (what *Script) ParseScript(script map[string]any) (*Script, error) { for key, value := range script { switch strings.ToLower(key) { case common.ID: stringItem, ok := value.(map[string]any) if !ok { return nil, fmt.Errorf("ID expression is not a script (map[string]any)") } what.id = stringItem case common.Data: switch castValue := value.(type) { case map[string]any: what.data = castValue default: return what, fmt.Errorf("failed to parse %q: unexpected script type %T\nscript:\n%v", key, value, what.formatter.AddLineNumbers(value)) } case common.Match: item, errorScript, itemError := new(statements.MethodStatement).Parse(value) if itemError != nil { return what, fmt.Errorf("failed to parse %q: %v\nscript:\n%v", key, itemError, what.formatter.AddLineNumbers(errorScript)) } what.match = item case common.Utils: item, errorScript, itemError := what.parseUtils(value) if itemError != nil { return what, fmt.Errorf("failed to parse %q: %v\nscript:\n%v", key, itemError, what.formatter.AddLineNumbers(errorScript)) } what.utils = item } } return what, nil } func (what *Script) GetTechnicalAssetsByRiskID(scope *common.Scope, riskID string) ([]any, error) { value, valueOk := what.getItem(scope.Model, "technical_assets") if !valueOk { return nil, fmt.Errorf("no technical assets in scope") } techAssets, techAssetsOk := value.(map[string]common.Value) if !techAssetsOk { return nil, fmt.Errorf("unexpected format of technical assets %T", techAssets) } matchingTechAssets := make([]any, 0) for techAssetName, techAsset := range techAssets { _ = techAssetName isMatch, _, matchError := what.matchRisk(scope, techAsset) if matchError != nil { return nil, matchError } if !isMatch.BoolValue() { continue } matchingTechAssets = append(matchingTechAssets, techAsset) } return matchingTechAssets, nil } func (what *Script) GenerateRisks(scope *common.Scope) ([]*types.Risk, string, error) { value, valueOk := what.getItem(scope.Model, "technical_assets") if !valueOk { return nil, "", fmt.Errorf("no technical assets in scope") } techAssets, techAssetsOk := value.(map[string]any) if !techAssetsOk { return nil, "", fmt.Errorf("unexpected format of technical assets %T", techAssets) } risks := make([]*types.Risk, 0) for techAssetName, techAsset := range techAssets { techAssetValue := common.SomeValue(techAsset, common.NewEvent(common.NewValueProperty(techAsset), common.NewPath(fmt.Sprintf("technical asset '%v'", techAssetName)))) isMatch, errorMatchLiteral, matchError := what.matchRisk(scope, techAssetValue) if matchError != nil { return nil, errorMatchLiteral, matchError } if !isMatch.BoolValue() { continue } risk, errorRiskLiteral, riskError := what.generateRisk(scope, techAssetName, techAssetValue, isMatch.Event()) if riskError != nil { return nil, errorRiskLiteral, riskError } if risk == nil { continue } riskId, errorGetIDLiteral, errorId := what.getRiskID(scope, techAssetValue, risk) if errorId != nil { return nil, errorGetIDLiteral, errorId } risk.SyntheticId = riskId if len(risk.SyntheticId) == 0 { risk.SyntheticId = risk.CategoryId + "@" + risk.MostRelevantTechnicalAssetId } risks = append(risks, risk) } return risks, "", nil } func (what *Script) matchRisk(outerScope *common.Scope, techAsset common.Value) (*common.BoolValue, string, error) { if what.match == nil { return common.EmptyBoolValue(), "", nil } scope, cloneError := outerScope.Clone() if cloneError != nil { return common.EmptyBoolValue(), "", fmt.Errorf("failed to clone scope: %w", cloneError) } scope.Args = append(scope.Args, techAsset) errorLiteral, runError := what.match.Run(scope) if runError != nil { return common.EmptyBoolValue(), errorLiteral, runError } if scope.GetReturnValue() == nil { return common.EmptyBoolValue(), "", nil } switch boolValue := scope.GetReturnValue().(type) { case *common.BoolValue: return boolValue, "", nil } return common.EmptyBoolValue(), "", nil } func (what *Script) generateRisk(outerScope *common.Scope, techAssetName string, techAsset common.Value, isMatchEvent *common.Event) (*types.Risk, string, error) { if what.data == nil { return nil, "", fmt.Errorf("no data template") } scope, cloneError := outerScope.Clone() if cloneError != nil { return nil, "", fmt.Errorf("failed to clone scope: %w", cloneError) } scope.Args = append(scope.Args, techAsset) parameter, ok := what.data[common.Parameter] if ok { switch castParameter := parameter.(type) { case string: if len(scope.Args) != 1 { return nil, common.ToLiteral(parameter), fmt.Errorf("expected single parameter, got %d", len(scope.Args)) } if scope.Vars == nil { scope.Vars = make(map[string]common.Value) } scope.Vars[castParameter] = scope.Args[0] default: return nil, common.ToLiteral(parameter), fmt.Errorf("unexpected parameter format %T", parameter) } } ratingExplanation := make([]string, 0) riskMap := make(map[string]any) for name, value := range what.data { expression, errorParseLiteral, parseError := new(expressions.ValueExpression).ParseValue(value) if parseError != nil { return nil, common.ToLiteral(errorParseLiteral), fmt.Errorf("failed to parse field value: %w", parseError) } newValue, errorEvalLiteral, evalError := expression.EvalAny(scope) if evalError != nil { return nil, errorEvalLiteral, fmt.Errorf("failed to eval field value: %w", evalError) } riskMap[name] = newValue.PlainValue() title := "" switch name { case "severity": title = "Severity" case "exploitation_likelihood": title = "Exploitation Likelihood" case "exploitation_impact": title = "Exploitation Impact" case "data_breach_probability": title = "Data Breach Probability" default: continue } text := fmt.Sprintf("'%v' is '%v'", title, newValue.PlainValue()) explanation := what.Explain([]*common.Event{newValue.Event()}) if len(explanation) > 0 { ratingExplanation = append(ratingExplanation, text+" because") for n, line := range explanation { if n < len(explanation)-1 { ratingExplanation = append(ratingExplanation, line+", and") } else { ratingExplanation = append(ratingExplanation, line) } } } else { ratingExplanation = append(ratingExplanation, text) } } riskData, marshalError := yaml.Marshal(riskMap) if marshalError != nil { return nil, common.ToLiteral(riskMap), fmt.Errorf("failed to print data: %v", marshalError) } var risk types.Risk unmarshalError := yaml.Unmarshal(riskData, &risk) if unmarshalError != nil { return nil, string(riskData), fmt.Errorf("failed to parse data: %w", unmarshalError) } risk.CategoryId, _ = what.getItemString(scope.Risk, "id") riskExplanation := make([]string, 0) text := fmt.Sprintf("Risk '%v' has been flagged for technical asset '%v'", scope.Category.Title, techAssetName) var explanation []string if isMatchEvent != nil { explanation = what.Explain(isMatchEvent.Events) if len(explanation) > 0 { riskExplanation = append(riskExplanation, text+" because") for n, line := range explanation { if n < len(explanation)-1 { riskExplanation = append(riskExplanation, line+", and") } else { riskExplanation = append(riskExplanation, line) } } } else { riskExplanation = append(riskExplanation, text) } } risk.RiskExplanation = riskExplanation risk.RatingExplanation = ratingExplanation return &risk, "", nil } func (what *Script) Explain(history []*common.Event) []string { text := make([]string, 0) for _, event := range history { text = append(text, event.Indented(0)...) } return text } func (what *Script) getRiskID(outerScope *common.Scope, techAsset common.Value, risk *types.Risk) (string, string, error) { if len(what.id) == 0 { return "", "", fmt.Errorf("no ID expression") } scope, cloneError := outerScope.Clone() if cloneError != nil { return "", "", fmt.Errorf("failed to clone scope: %w", cloneError) } scope.Args = append(scope.Args, techAsset) parameter, parameterOk := what.id[common.Parameter] if parameterOk { switch castParameter := parameter.(type) { case string: if len(scope.Args) != 1 { return "", common.ToLiteral(parameter), fmt.Errorf("expected single parameter, got %d", len(scope.Args)) } if scope.Vars == nil { scope.Vars = make(map[string]common.Value) } scope.Vars[castParameter] = scope.Args[0] default: return "", common.ToLiteral(parameter), fmt.Errorf("unexpected parameter format %T", parameter) } } riskData, marshalError := yaml.Marshal(risk) if marshalError != nil { return "", "", fmt.Errorf("failed to print risk: %v", marshalError) } unmarshalError := yaml.Unmarshal(riskData, &scope.Risk) if unmarshalError != nil { return "", string(riskData), fmt.Errorf("failed to parse data: %w", unmarshalError) } id, idOk := what.id[common.ID] if idOk { expression, errorParseLiteral, parseError := new(expressions.ValueExpression).ParseValue(id) if parseError != nil { return "", common.ToLiteral(errorParseLiteral), fmt.Errorf("failed to parse ID expression: %w", parseError) } value, errorEvalLiteral, evalError := expression.EvalString(scope) if evalError != nil { return "", errorEvalLiteral, evalError } return value.StringValue(), "", nil } return "", "", nil } func (what *Script) getItemString(value any, path ...string) (string, bool) { item, itemOk := what.getItem(value, path...) if !itemOk { return "", false } itemString, itemStringOk := item.(string) if !itemStringOk { return "", false } return itemString, true } func (what *Script) getItem(value any, path ...string) (any, bool) { if len(path) == 0 { return nil, false } object, ok := value.(map[string]any) if !ok { return nil, false } for name, item := range object { if strings.EqualFold(path[0], name) { if len(path[1:]) > 0 { return what.getItem(item) } return item, true } } return nil, false } func (what *Script) parseUtils(script any) (map[string]*statements.MethodStatement, any, error) { statementMap := make(map[string]*statements.MethodStatement) switch castScript := script.(type) { case map[string]any: for key, value := range castScript { methodStatement := new(statements.MethodStatement) _, errorScript, parseError := methodStatement.Parse(value) if parseError != nil { return nil, errorScript, fmt.Errorf("failed to parse method %q: %w", key, parseError) } statementMap[key] = methodStatement } case []any: for n, value := range castScript { newStatementMap, errorScript, parseError := what.parseUtils(value) if parseError != nil { return nil, errorScript, fmt.Errorf("failed to parse method #%d: %w", n+1, parseError) } for name, method := range newStatementMap { _, ok := statementMap[name] if ok { return nil, errorScript, fmt.Errorf("method %q redefined", name) } statementMap[name] = method } } default: return nil, script, fmt.Errorf("unexpected utils format %T", script) } return statementMap, nil, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/variable.go
pkg/risks/script/variable.go
package script import ( "github.com/threagile/threagile/pkg/risks/script/common" ) type Variable struct { Name string Expression common.Expression }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/risk-rule.go
pkg/risks/script/risk-rule.go
package script import ( "fmt" "io/fs" "path/filepath" "strings" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" "gopkg.in/yaml.v3" ) type RiskRule struct { types.RiskRule category types.RiskCategory supportedTags []string script *Script } func (what *RiskRule) Init() *RiskRule { return what } func (what *RiskRule) ParseFromData(text []byte) (*RiskRule, error) { categoryError := yaml.Unmarshal(text, &what.category) if categoryError != nil { return nil, categoryError } var rule struct { Category string `yaml:"category"` SupportedTags []string `yaml:"supported-tags"` Script map[string]any `yaml:"risk"` } ruleError := yaml.Unmarshal(text, &rule) if ruleError != nil { return nil, ruleError } what.supportedTags = rule.SupportedTags script, scriptError := NewScript(new(input.Strings)).ParseScript(rule.Script) if scriptError != nil { return nil, scriptError } what.script = script return what, nil } func (what *RiskRule) Category() *types.RiskCategory { return &what.category } func (what *RiskRule) SupportedTags() []string { return what.supportedTags } func (what *RiskRule) GenerateRisks(parsedModel *types.Model) ([]*types.Risk, error) { if what.script == nil { return nil, fmt.Errorf("no script found in risk rule") } newScope, scopeError := what.script.NewScope(&what.category) if scopeError != nil { return nil, scopeError } modelError := newScope.SetModel(parsedModel) if modelError != nil { return nil, modelError } newRisks, errorLiteral, riskError := what.script.GenerateRisks(newScope) if riskError != nil { msg := make([]string, 0) msg = append(msg, fmt.Sprintf("error generating risks: %v\n", riskError)) if len(errorLiteral) > 0 { msg = append(msg, fmt.Sprintf("in:\n%v\n", new(input.Strings).IndentPrintf(1, errorLiteral))) } return nil, fmt.Errorf("%v", strings.Join(msg, "\n")) } return newRisks, nil } func (what *RiskRule) Load(fileSystem fs.FS, path string, entry fs.DirEntry) error { if entry.IsDir() { return nil } loadError := what.loadRiskRule(fileSystem, path) if loadError != nil { return loadError } return nil } func (what *RiskRule) loadRiskRule(fileSystem fs.FS, filename string) error { scriptFilename := filepath.Clean(filename) ruleData, ruleReadError := fs.ReadFile(fileSystem, scriptFilename) if ruleReadError != nil { return fmt.Errorf("error reading data category: %w", ruleReadError) } _, parseError := what.ParseFromData(ruleData) if parseError != nil { return fmt.Errorf("error parsing scripts from %q: %w", scriptFilename, parseError) } return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/greater-or-equal.go
pkg/risks/script/property/greater-or-equal.go
package property type GreaterOrEqual struct { negated bool } func NewGreaterOrEqual() *GreaterOrEqual { return new(GreaterOrEqual) } func (what *GreaterOrEqual) Path() { } func (what *GreaterOrEqual) Negate() { what.negated = !what.negated } func (what *GreaterOrEqual) Negated() bool { return what.negated } func (what *GreaterOrEqual) Text() []string { if what.negated { return []string{"less than"} } return []string{"greater than or equal to"} }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/item-with-path.go
pkg/risks/script/property/item-with-path.go
package property type ItemWithPath interface { Item Path() }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/less-or-equal.go
pkg/risks/script/property/less-or-equal.go
package property type LessOrEqual struct { negated bool } func NewLessOrEqual() *LessOrEqual { return new(LessOrEqual) } func (what *LessOrEqual) Path() { } func (what *LessOrEqual) Negate() { what.negated = !what.negated } func (what *LessOrEqual) Negated() bool { return what.negated } func (what *LessOrEqual) Text() []string { if what.negated { return []string{"greater than"} } return []string{"less than or equal to"} }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/blank.go
pkg/risks/script/property/blank.go
package property /* this is a property for a value that should not be printed as part of the history, such as structured values */ type Blank struct { } func NewBlank() *Blank { return new(Blank) } func (what *Blank) Negate() { } func (what *Blank) Negated() bool { return false } func (what *Blank) Text() []string { return []string{} }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/texter.go
pkg/risks/script/property/texter.go
package property type Texter interface { Text() []string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/equal.go
pkg/risks/script/property/equal.go
package property type Equal struct { negated bool } func NewEqual() *Equal { return new(Equal) } func (what *Equal) Path() { } func (what *Equal) Negate() { what.negated = !what.negated } func (what *Equal) Negated() bool { return what.negated } func (what *Equal) Text() []string { if what.negated { return []string{"not equal to"} } return []string{"equal to"} }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/greater.go
pkg/risks/script/property/greater.go
package property type Greater struct { negated bool } func NewGreater() *Greater { return new(Greater) } func (what *Greater) Path() { } func (what *Greater) Negate() { what.negated = !what.negated } func (what *Greater) Negated() bool { return what.negated } func (what *Greater) Text() []string { if what.negated { return []string{"less than or equal to"} } return []string{"greater than"} }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/less.go
pkg/risks/script/property/less.go
package property type Less struct { negated bool } func NewLess() *Less { return new(Less) } func (what *Less) Path() { } func (what *Less) Negate() { what.negated = !what.negated } func (what *Less) Negated() bool { return what.negated } func (what *Less) Text() []string { if what.negated { return []string{"greater than or equal to"} } return []string{"less than"} }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/value.go
pkg/risks/script/property/value.go
package property import ( "fmt" ) type Value struct { value any negated bool } func NewValue(value any) *Value { return &Value{value: value} } func (what *Value) Negate() { what.negated = !what.negated } func (what *Value) Negated() bool { return what.negated } func (what *Value) Text() []string { text := make([]string, 0) switch castValue := what.value.(type) { case Texter: if what.negated { text = append(text, "not") } for _, value := range castValue.Text() { text = append(text, fmt.Sprintf(" %v", value)) } case []any: if what.negated { text = append(text, "not") } for _, item := range castValue { text = append(text, fmt.Sprintf(" - %v", item)) } case map[string]any: if what.negated { text = append(text, "not") } for name, item := range castValue { text = append(text, fmt.Sprintf(" %v: %v", name, item)) } default: if what.negated { text = append(text, fmt.Sprintf("not %v", castValue)) } else { text = append(text, fmt.Sprintf("%v", castValue)) } } return text }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/true.go
pkg/risks/script/property/true.go
package property type True struct { negated bool } func NewTrue() *True { return new(True) } func (what *True) Negate() { what.negated = !what.negated } func (what *True) Negated() bool { return what.negated } func (what *True) Text() []string { if what.negated { return []string{"false"} } return []string{"true"} }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/false.go
pkg/risks/script/property/false.go
package property type False struct { negated bool } func NewFalse() *False { return new(False) } func (what *False) Value() any { return what.negated } func (what *False) Negate() { what.negated = !what.negated } func (what *False) Negated() bool { return what.negated } func (what *False) Text() []string { if what.negated { return []string{"true"} } return []string{"false"} }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/item.go
pkg/risks/script/property/item.go
package property type Item interface { Negate() Negated() bool Text() []string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/property/not-equal.go
pkg/risks/script/property/not-equal.go
package property type NotEqual struct { negated bool } func NewNotEqual() *NotEqual { return new(NotEqual) } func (what *NotEqual) Path() { } func (what *NotEqual) Negate() { what.negated = !what.negated } func (what *NotEqual) Negated() bool { return what.negated } func (what *NotEqual) Text() []string { if what.negated { return []string{"equal to"} } return []string{"not equal to"} }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/statements/assign-statement.go
pkg/risks/script/statements/assign-statement.go
package statements import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" "github.com/threagile/threagile/pkg/risks/script/expressions" ) type AssignStatement struct { literal string items map[string]common.Expression } func (what *AssignStatement) Parse(script any) (common.Statement, any, error) { what.literal = common.ToLiteral(script) if what.items == nil { what.items = make(map[string]common.Expression) } switch castScript := script.(type) { case map[string]any: return what.parse(castScript) case []any: for _, statement := range castScript { _, errorScript, itemError := what.Parse(statement) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse assign-statement: %w", itemError) } } default: return nil, script, fmt.Errorf("unexpected assign-statement format %T", script) } return what, nil, nil } func (what *AssignStatement) parse(script map[string]any) (common.Statement, any, error) { for key, value := range script { expression, errorScript, parseError := new(expressions.ExpressionList).ParseAny(value) if parseError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of assign-statement: %w", key, parseError) } what.items[key] = expression } return what, nil, nil } func (what *AssignStatement) Run(scope *common.Scope) (string, error) { if scope.HasReturned { return "", nil } for name, item := range what.items { value, errorLiteral, evalError := item.EvalAny(scope) if evalError != nil { return errorLiteral, fmt.Errorf("failed to eval %q of assign-statement: %w", name, evalError) } scope.Set(name, value) } return "", nil } func (what *AssignStatement) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/statements/if-statement.go
pkg/risks/script/statements/if-statement.go
package statements import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" "github.com/threagile/threagile/pkg/risks/script/expressions" ) type IfStatement struct { literal string expression common.BoolExpression yesPath common.Statement noPath common.Statement } func (what *IfStatement) Parse(script any) (common.Statement, any, error) { what.literal = common.ToLiteral(script) switch castScript := script.(type) { case map[any]any: for key, value := range castScript { statement, errorScript, parseError := what.parse(key, value, script) if parseError != nil { return statement, errorScript, parseError } } case map[string]any: for key, value := range castScript { statement, errorScript, parseError := what.parse(key, value, script) if parseError != nil { return statement, errorScript, parseError } } default: return nil, script, fmt.Errorf("failed to parse if-statement: expected map[string]any, got %T", script) } return what, nil, nil } func (what *IfStatement) parse(key any, value any, script any) (common.Statement, any, error) { switch key { case common.Then: item, errorScript, itemError := new(StatementList).Parse(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of if-statement: %w", key, itemError) } what.yesPath = item case common.Else: item, errorScript, itemError := new(StatementList).Parse(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of if-statement: %w", key, itemError) } what.noPath = item default: if what.expression != nil { return nil, script, fmt.Errorf("if-statement has multiple expressions") } item, errorScript, itemError := new(expressions.ExpressionList).ParseExpression(map[string]any{fmt.Sprintf("%v", key): value}) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse expression of if-statement: %w", itemError) } boolItem, ok := item.(common.BoolExpression) if !ok { return nil, script, fmt.Errorf("expression of if-statement is not a bool expression: %w", itemError) } what.expression = boolItem } return what, nil, nil } func (what *IfStatement) Run(scope *common.Scope) (string, error) { if scope.HasReturned { return "", nil } if what.expression == nil { return "", nil } value, errorLiteral, evalError := what.expression.EvalBool(scope) if evalError != nil { return errorLiteral, evalError } if value.BoolValue() { if what.yesPath != nil { scope.PushCall(common.NewEventFrom(common.NewTrueProperty(), value)) defer scope.PopCall() return what.yesPath.Run(scope) } } else { if what.noPath != nil { scope.PushCall(common.NewEventFrom(common.NewFalseProperty(), value)) defer scope.PopCall() return what.noPath.Run(scope) } } return "", nil } func (what *IfStatement) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/statements/explain-statement.go
pkg/risks/script/statements/explain-statement.go
package statements import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" "github.com/threagile/threagile/pkg/risks/script/expressions" ) type ExplainStatement struct { literal string expression common.StringExpression } func (what *ExplainStatement) Parse(script any) (common.Statement, any, error) { what.literal = common.ToLiteral(script) expression, errorScript, parseError := new(expressions.ExpressionList).ParseAny(script) if parseError != nil { return nil, errorScript, fmt.Errorf("failed to parse explain-statement: %w", parseError) } switch castItem := expression.(type) { case common.StringExpression: what.expression = castItem default: return nil, script, fmt.Errorf("explain-statement has non-string expression of type %T", castItem) } return what, nil, nil } func (what *ExplainStatement) Run(scope *common.Scope) (string, error) { if scope.HasReturned { return "", nil } scope.Explain = what return "", nil } func (what *ExplainStatement) Eval(scope *common.Scope) string { value, _, _ := what.expression.EvalString(scope) return value.StringValue() } func (what *ExplainStatement) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/statements/return-statement.go
pkg/risks/script/statements/return-statement.go
package statements import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" "github.com/threagile/threagile/pkg/risks/script/expressions" ) type ReturnStatement struct { literal string expression common.Expression } func (what *ReturnStatement) Parse(script any) (common.Statement, any, error) { what.literal = common.ToLiteral(script) item, errorScript, itemError := new(expressions.ExpressionList).ParseAny(script) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse expressions of return-statement: %w", itemError) } what.expression = item return what, nil, nil } func (what *ReturnStatement) Run(scope *common.Scope) (string, error) { if scope.HasReturned { return "", nil } if what.expression == nil { return "", nil } value, errorLiteral, evalError := what.expression.EvalAny(scope) if evalError != nil { return errorLiteral, evalError } scope.SetReturnValue(common.AddValueHistory(value, scope.GetHistory())) scope.HasReturned = true return "", nil } func (what *ReturnStatement) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/statements/statement-list.go
pkg/risks/script/statements/statement-list.go
package statements import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type StatementList struct { literal string statements []common.Statement } func (what *StatementList) Parse(script any) (common.Statement, any, error) { what.literal = common.ToLiteral(script) switch castScript := script.(type) { case map[string]any: scriptMap := castScript if len(scriptMap) != 1 { return nil, script, fmt.Errorf("failed to parse statement-list: statements must have single identifier") } for name, body := range scriptMap { return new(Statement).Parse(name, body) } case []any: for _, statement := range castScript { item, errorScript, itemError := what.Parse(statement) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse statement-list: %w", itemError) } what.statements = append(what.statements, item) } if len(what.statements) == 1 { statement := what.statements[0] what.statements = make([]common.Statement, 0) return statement, "", nil } default: return nil, script, fmt.Errorf("unexpected statement-list format %T", script) } return what, nil, nil } func (what *StatementList) Run(scope *common.Scope) (string, error) { if scope.HasReturned { return "", nil } for _, statement := range what.statements { if scope.HasReturned { return "", nil } errorLiteral, statementError := statement.Run(scope) if statementError != nil { return errorLiteral, statementError } } return "", nil } func (what *StatementList) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/statements/defer-statement.go
pkg/risks/script/statements/defer-statement.go
package statements import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type DeferStatement struct { literal string statements []common.Statement } func (what *DeferStatement) Parse(script any) (common.Statement, any, error) { what.literal = common.ToLiteral(script) switch castScript := script.(type) { case map[string]any: scriptMap := castScript if len(scriptMap) != 1 { return nil, script, fmt.Errorf("failed to parse defer-statement: statements must have single identifier") } for name, body := range scriptMap { return new(Statement).Parse(name, body) } case []any: for _, statement := range castScript { item, errorScript, itemError := what.Parse(statement) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse defer-statement: %w", itemError) } what.statements = append(what.statements, item) } default: return nil, script, fmt.Errorf("unexpected defer-statement format %T", script) } return what, nil, nil } func (what *DeferStatement) Run(scope *common.Scope) (string, error) { if scope.HasReturned { return "", nil } for _, statement := range what.statements { scope.Defer(statement) } return "", nil } func (what *DeferStatement) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/statements/loop-statement.go
pkg/risks/script/statements/loop-statement.go
package statements import ( "fmt" "github.com/shopspring/decimal" "github.com/threagile/threagile/pkg/risks/script/common" "github.com/threagile/threagile/pkg/risks/script/expressions" ) type LoopStatement struct { literal string in common.ValueExpression item string index string body common.Statement } func (what *LoopStatement) Parse(script any) (common.Statement, any, error) { what.literal = common.ToLiteral(script) switch script.(type) { case map[string]any: for key, value := range script.(map[string]any) { switch key { case common.In: item, errorExpression, itemError := new(expressions.ValueExpression).ParseValue(value) if itemError != nil { return nil, errorExpression, fmt.Errorf("failed to parse %q of loop-statement: %w", key, itemError) } what.in = item case common.Item: text, ok := value.(string) if !ok { return nil, value, fmt.Errorf("failed to parse %q of loop-statement: expected string, got %T", key, value) } what.item = text case common.Index: text, ok := value.(string) if !ok { return nil, value, fmt.Errorf("failed to parse %q of loop-statement: expected string, got %T", key, value) } what.index = text case common.Do: item, errorScript, itemError := new(StatementList).Parse(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of loop-statement: %w", key, itemError) } what.body = item default: return nil, script, fmt.Errorf("failed to parse loop-statement: unexpected keyword %q", key) } } default: return nil, script, fmt.Errorf("failed to parse loop-statement: expected map[string]any, got %T", script) } return what, nil, nil } func (what *LoopStatement) Run(scope *common.Scope) (string, error) { if scope.HasReturned { return "", nil } oldIterator := scope.PopItem() defer scope.SetItem(oldIterator) value, errorEvalLiteral, evalError := what.in.EvalAny(scope) if evalError != nil { return errorEvalLiteral, evalError } return what.run(scope, value) } func (what *LoopStatement) run(scope *common.Scope, value common.Value) (string, error) { switch castValue := value.Value().(type) { case []any: for index, item := range castValue { if scope.HasReturned { return "", nil } if len(what.index) > 0 { scope.Set(what.index, common.SomeDecimalValue(decimal.NewFromInt(int64(index)), nil)) } itemValue := scope.SetItem(common.SomeValue(item, value.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } errorLiteral, runError := what.body.Run(scope) if runError != nil { return errorLiteral, fmt.Errorf("failed to run loop-statement for item #%d: %w", index+1, runError) } } case []common.Value: for index, item := range castValue { if scope.HasReturned { return "", nil } if len(what.index) > 0 { scope.Set(what.index, common.SomeDecimalValue(decimal.NewFromInt(int64(index)), nil)) } itemValue := scope.SetItem(common.SomeValue(item.Value(), value.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } errorLiteral, runError := what.body.Run(scope) if runError != nil { return errorLiteral, fmt.Errorf("failed to run loop-statement for item #%d: %w", index+1, runError) } } case map[string]any: for name, item := range castValue { if scope.HasReturned { return "", nil } if len(what.index) > 0 { scope.Set(what.index, common.SomeStringValue(name, nil)) } itemValue := scope.SetItem(common.SomeValue(item, value.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } errorLiteral, runError := what.body.Run(scope) if runError != nil { return errorLiteral, fmt.Errorf("failed to run loop-statement for item %q: %w", name, runError) } } case common.Value: return what.run(scope, common.SomeValue(castValue.Value(), value.Event())) default: return what.Literal(), fmt.Errorf("failed to run loop-statement: expected iterable type, got %T", value) } return "", nil } func (what *LoopStatement) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/statements/statement.go
pkg/risks/script/statements/statement.go
package statements import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type Statement struct { } func (what *Statement) Parse(name string, body any) (common.Statement, any, error) { switch name { case common.Assign: statement, errorScript, parseError := new(AssignStatement).Parse(body) if parseError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q-statement: %w", name, parseError) } return statement, errorScript, parseError case common.Defer: statement, errorScript, parseError := new(DeferStatement).Parse(body) if parseError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q-statement: %w", name, parseError) } return statement, errorScript, parseError case common.Explain: statement, errorScript, parseError := new(ExplainStatement).Parse(body) if parseError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q-statement: %w", name, parseError) } return statement, errorScript, parseError case common.If: statement, errorScript, parseError := new(IfStatement).Parse(body) if parseError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q-statement: %w", name, parseError) } return statement, errorScript, parseError case common.Loop: statement, errorScript, parseError := new(LoopStatement).Parse(body) if parseError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q-statement: %w", name, parseError) } return statement, errorScript, parseError case common.Return: statement, errorScript, parseError := new(ReturnStatement).Parse(body) if parseError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q-statement: %w", name, parseError) } return statement, errorScript, parseError default: return nil, body, fmt.Errorf("failed to parse statement: unexpected keyword %q", name) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/statements/method-statement.go
pkg/risks/script/statements/method-statement.go
package statements import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type MethodStatement struct { literal string parameters []string body common.Statement } func (what *MethodStatement) Parse(script any) (common.Statement, any, error) { what.literal = common.ToLiteral(script) switch script.(type) { case map[string]any: for key, value := range script.(map[string]any) { switch key { case common.Parameter, common.Parameters: switch castValue := value.(type) { case []string: what.parameters = append(what.parameters, castValue...) case []any: for _, generic := range castValue { text, ok := generic.(string) if !ok { return nil, generic, fmt.Errorf("failed to parse %q of method-statement: expected string, got %T", key, generic) } what.parameters = append(what.parameters, text) } case string: what.parameters = append(what.parameters, castValue) default: return nil, value, fmt.Errorf("failed to parse %q of method-statement: unexpected parameter type %T", key, value) } case common.Do: item, errorScript, itemError := new(StatementList).Parse(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of method-statement: %w", key, itemError) } what.body = item default: return nil, script, fmt.Errorf("failed to parse method-statement: unexpected statement %q", key) } } default: return nil, script, fmt.Errorf("failed to parse method-statement: expected map[string]any, got %T", script) } return what, nil, nil } func (what *MethodStatement) Run(scope *common.Scope) (string, error) { if scope.HasReturned { return "", nil } defer what.runDeferred(scope) if len(what.parameters) != len(scope.Args) { return what.Literal(), fmt.Errorf("failed to run method-statement: expected %d parameters, got %d", len(what.parameters), len(scope.Args)) } for n, name := range what.parameters { scope.Set(name, scope.Args[n]) } if what.body != nil { errorLiteral, runError := what.body.Run(scope) if runError != nil { return errorLiteral, fmt.Errorf("failed to run method-statement: %w", runError) } } return "", nil } func (what *MethodStatement) runDeferred(scope *common.Scope) { for _, statement := range scope.Deferred { scope.HasReturned = false _, _ = statement.Run(scope) } if scope.Explain != nil { scope.HasReturned = false scope.CallStack = make(common.History, 0) returnValue := scope.GetReturnValue() if returnValue != nil { returnValue = common.SomeValue(returnValue.PlainValue(), returnValue.Event()) scope.SetReturnValue(returnValue) } } } func (what *MethodStatement) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/any-expression.go
pkg/risks/script/expressions/any-expression.go
package expressions import ( "fmt" "github.com/shopspring/decimal" "github.com/threagile/threagile/pkg/risks/script/common" ) type AnyExpression struct { literal string in common.ValueExpression item string index string expression common.BoolExpression } func (what *AnyExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) switch script.(type) { case map[string]any: for key, value := range script.(map[string]any) { switch key { case common.In: item, errorExpression, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorExpression, fmt.Errorf("failed to parse %q of any-expression: %w", key, itemError) } what.in = item case common.Item: text, ok := value.(string) if !ok { return nil, value, fmt.Errorf("failed to parse %q of any-expression: expected string, got %T", key, value) } what.item = text case common.Index: text, ok := value.(string) if !ok { return nil, value, fmt.Errorf("failed to parse %q of any-expression: expected string, got %T", key, value) } what.index = text default: if what.expression != nil { return nil, script, fmt.Errorf("failed to parse any-expression: additional bool expression %q", key) } expression, errorScript, itemError := new(ExpressionList).ParseAny(map[string]any{key: value}) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse any-expression: %w", itemError) } boolExpression, ok := expression.(common.BoolExpression) if !ok { return nil, script, fmt.Errorf("any-expression contains non-bool expression: %w", itemError) } what.expression = boolExpression } } default: return nil, script, fmt.Errorf("failed to parse any-expression: expected map[string]any, got %T", script) } return what, nil, nil } func (what *AnyExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *AnyExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { oldItem := scope.PopItem() defer scope.SetItem(oldItem) inValue, errorEvalLiteral, evalError := what.in.EvalAny(scope) if evalError != nil { return common.EmptyBoolValue(), errorEvalLiteral, evalError } return what.evalBool(scope, inValue) } func (what *AnyExpression) evalBool(scope *common.Scope, inValue common.Value) (*common.BoolValue, string, error) { switch castValue := inValue.Value().(type) { case []any: if what.expression == nil { return common.SomeBoolValue(true, nil), "", nil } values := make([]common.Value, 0) for index, item := range castValue { if len(what.index) > 0 { scope.Set(what.index, common.SomeDecimalValue(decimal.NewFromInt(int64(index)), nil)) } itemValue := scope.SetItem(common.SomeValue(item, inValue.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } value, errorLiteral, expressionError := what.expression.EvalBool(scope) if expressionError != nil { return common.EmptyBoolValue(), errorLiteral, fmt.Errorf("error evaluating expression #%v of any-expression: %w", index+1, expressionError) } if value.BoolValue() { return common.SomeBoolValue(true, value.Event()), "", nil } values = append(values, value) } return common.SomeBoolValue(false, common.NewEvent(common.NewFalseProperty(), inValue.Event().Origin).From(values...)), "", nil case []common.Value: if what.expression == nil { return common.SomeBoolValue(true, nil), "", nil } values := make([]common.Value, 0) for index, item := range castValue { if len(what.index) > 0 { scope.Set(what.index, common.SomeDecimalValue(decimal.NewFromInt(int64(index)), nil)) } itemValue := scope.SetItem(common.SomeValue(item.Value(), inValue.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } value, errorLiteral, expressionError := what.expression.EvalBool(scope) if expressionError != nil { return common.EmptyBoolValue(), errorLiteral, fmt.Errorf("error evaluating expression #%v of any-expression: %w", index+1, expressionError) } if value.BoolValue() { return common.SomeBoolValue(true, value.Event()), "", nil } values = append(values, value) } return common.SomeBoolValue(false, common.NewEvent(common.NewFalseProperty(), inValue.Event().Origin).From(values...)), "", nil case map[string]any: if what.expression == nil { return common.SomeBoolValue(true, nil), "", nil } values := make([]common.Value, 0) for name, item := range castValue { if len(what.index) > 0 { scope.Set(what.index, common.SomeStringValue(name, nil)) } itemValue := scope.SetItem(common.SomeValue(item, inValue.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } value, errorLiteral, expressionError := what.expression.EvalBool(scope) if expressionError != nil { return common.EmptyBoolValue(), errorLiteral, fmt.Errorf("error evaluating expression %q of any-expression: %w", name, expressionError) } if value.BoolValue() { return common.SomeBoolValue(false, value.Event()), "", nil } values = append(values, value) } return common.SomeBoolValue(true, common.NewEvent(common.NewFalseProperty(), inValue.Event().Origin).From(values...)), "", nil case common.Value: return what.evalBool(scope, common.SomeValue(castValue.Value(), inValue.Event())) case nil: return common.SomeBoolValue(false, nil), "", nil default: return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to eval any-expression: expected iterable type, got %T", inValue) } } func (what *AnyExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *AnyExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/array-expression.go
pkg/risks/script/expressions/array-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type ArrayExpression struct { literal string expressions common.ExpressionList } func (what *ArrayExpression) ParseArray(script any) (common.ArrayExpression, any, error) { what.literal = common.ToLiteral(script) switch castScript := script.(type) { case map[string]any: expressions := new(ExpressionList) _, errorScript, itemError := expressions.ParseAny(castScript) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse array-expression: %w", itemError) } what.expressions = expressions default: return nil, script, fmt.Errorf("unexpected array-expression format %T", script) } return what, nil, nil } func (what *ArrayExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseArray(script) } func (what *ArrayExpression) EvalArray(scope *common.Scope) (*common.ArrayValue, string, error) { values := make([]common.Value, 0) for index, expression := range what.expressions.Expressions() { value, errorLiteral, evalError := expression.EvalAny(scope) if evalError != nil { return nil, errorLiteral, fmt.Errorf("%q: error evaluating array-expression #%v: %w", what.literal, index+1, evalError) } values = append(values, value) } return common.SomeArrayValue(values, common.NewEvent(common.NewValueProperty(values), common.NewPath("array value")).From(values...)), "", nil } func (what *ArrayExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalArray(scope) } func (what *ArrayExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/greater-expression.go
pkg/risks/script/expressions/greater-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type GreaterExpression struct { literal string first common.ValueExpression second common.ValueExpression as common.StringExpression } func (what *GreaterExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) switch castScript := script.(type) { case map[string]any: for key, value := range castScript { switch key { case common.First: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.first = item case common.Second: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.second = item case common.As: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.as = item default: return nil, script, fmt.Errorf("failed to parse equal-expression: unexpected keyword %q", key) } } default: return nil, script, fmt.Errorf("failed to parse equal-expression: expected map[string]any, got %T", script) } return what, nil, nil } func (what *GreaterExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *GreaterExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { first, errorItemLiteral, itemError := what.first.EvalAny(scope) if itemError != nil { return common.EmptyBoolValue(), errorItemLiteral, itemError } second, errorInLiteral, evalError := what.second.EvalAny(scope) if evalError != nil { return common.EmptyBoolValue(), errorInLiteral, evalError } as, errorAsLiteral, asError := what.as.EvalString(scope) if asError != nil { return common.EmptyBoolValue(), errorAsLiteral, asError } compareValue, compareError := common.Compare(first, second, as.StringValue()) if compareError != nil { return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to compare equal-expression: %w", compareError) } if common.IsGreater(compareValue.Property) { return common.SomeBoolValue(true, compareValue), "", nil } return common.SomeBoolValue(false, compareValue), "", nil } func (what *GreaterExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *GreaterExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/value-expression.go
pkg/risks/script/expressions/value-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" "regexp" "strconv" "strings" "github.com/shopspring/decimal" ) type ValueExpression struct { literal string value any } func (what *ValueExpression) ParseArray(script any) (common.ArrayExpression, any, error) { what.literal = common.ToLiteral(script) what.value = script return what, nil, nil } func (what *ValueExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) what.value = script return what, nil, nil } func (what *ValueExpression) ParseDecimal(script any) (common.DecimalExpression, any, error) { what.literal = common.ToLiteral(script) what.value = script return what, nil, nil } func (what *ValueExpression) ParseString(script any) (common.StringExpression, any, error) { what.literal = common.ToLiteral(script) what.value = script return what, nil, nil } func (what *ValueExpression) ParseValue(script any) (common.ValueExpression, any, error) { what.literal = common.ToLiteral(script) what.value = script return what, nil, nil } func (what *ValueExpression) ParseAny(script any) (common.Expression, any, error) { what.literal = common.ToLiteral(script) what.value = script return what, nil, nil } func (what *ValueExpression) EvalArray(scope *common.Scope) (*common.ArrayValue, string, error) { return what.evalArray(scope, common.SomeValue(what.value, nil)) } func (what *ValueExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { return what.evalBool(scope, common.SomeValue(what.value, nil)) } func (what *ValueExpression) EvalDecimal(scope *common.Scope) (*common.DecimalValue, string, error) { return what.evalDecimal(scope, common.SomeValue(what.value, nil)) } func (what *ValueExpression) EvalString(scope *common.Scope) (*common.StringValue, string, error) { return what.evalString(scope, common.SomeValue(what.value, nil)) } func (what *ValueExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.evalAny(scope, common.SomeValue(what.value, nil)) } func (what *ValueExpression) evalArray(scope *common.Scope, anyValue common.Value) (*common.ArrayValue, string, error) { switch castValue := anyValue.(type) { case *common.StringValue: value, errorLiteral, evalError := what.evalStringReference(scope, castValue) if evalError != nil { return common.EmptyArrayValue(), errorLiteral, evalError } arrayValue, arrayValueError := common.ToArrayValue(value) return arrayValue, what.Literal(), arrayValueError case *common.ArrayValue: array := make([]common.Value, 0) for _, item := range castValue.ArrayValue() { value, errorLiteral, evalError := what.evalAny(scope, item) if evalError != nil { return nil, errorLiteral, evalError } array = append(array, value) } return common.SomeArrayValue(array, nil), "", nil case nil: return common.EmptyArrayValue(), "", nil default: return nil, what.Literal(), fmt.Errorf("failed to eval value-expression: value type %T is not an array", what.value) } } func (what *ValueExpression) evalBool(scope *common.Scope, anyValue common.Value) (*common.BoolValue, string, error) { switch castValue := anyValue.(type) { case *common.StringValue: return what.stringToBool(scope, castValue) case *common.BoolValue: return castValue, "", nil case nil: return common.SomeBoolValue(false, nil), "", nil default: return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to eval value-expression: value type %T is not a bool", what.value) } } func (what *ValueExpression) evalDecimal(scope *common.Scope, anyValue common.Value) (*common.DecimalValue, string, error) { switch castValue := anyValue.(type) { case *common.StringValue: return what.stringToDecimal(scope, castValue) case *common.DecimalValue: return castValue, "", nil case nil: return common.SomeDecimalValue(decimal.Zero, nil), "", nil default: return common.EmptyDecimalValue(), what.Literal(), fmt.Errorf("failed to eval value-expression: value type %T is not a decimal", what.value) } } func (what *ValueExpression) evalString(scope *common.Scope, anyValue common.Value) (*common.StringValue, string, error) { switch castValue := anyValue.(type) { case *common.StringValue: return what.stringToString(scope, castValue) case nil: return common.SomeStringValue("", nil), "", nil default: return common.EmptyStringValue(), what.Literal(), fmt.Errorf("failed to eval value-expression: value type %T is not a string", what.value) } } func (what *ValueExpression) evalAny(scope *common.Scope, anyValue common.Value) (common.Value, string, error) { switch castValue := anyValue.(type) { case *common.StringValue: return what.evalStringReference(scope, castValue) case *common.BoolValue: return castValue, "", nil case *common.DecimalValue: return castValue, "", nil case *common.ArrayValue: return what.evalArray(scope, castValue) case nil: return common.SomeValue(nil, nil), "", nil default: return nil, what.Literal(), fmt.Errorf("failed to eval value-expression: value type is %T", what.value) } } func (what *ValueExpression) stringToBool(scope *common.Scope, valueString *common.StringValue) (*common.BoolValue, string, error) { value, errorLiteral, evalError := what.evalStringReference(scope, valueString) // resolve references if evalError != nil { return common.EmptyBoolValue(), errorLiteral, evalError } if value == nil { return common.SomeBoolValue(false, valueString.Event()), "", nil } switch castValue := value.Value().(type) { case string: // string literal if len(castValue) == 0 { return common.SomeBoolValue(false, value.Event()), "", nil } boolValue, parseError := strconv.ParseBool(castValue) if parseError != nil { return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to parse value-expression: %w", parseError) } return common.SomeBoolValue(boolValue, value.Event()), "", nil case bool: // bool value return common.SomeBoolValue(castValue, value.Event()), "", nil case nil: // empty value return common.SomeBoolValue(false, value.Event()), "", nil case common.Value: return what.evalBool(scope, castValue) default: return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("expected value-expression to eval to a bool instead of %T", value) } } func (what *ValueExpression) stringToDecimal(scope *common.Scope, valueString *common.StringValue) (*common.DecimalValue, string, error) { value, errorLiteral, evalError := what.evalStringReference(scope, valueString) if evalError != nil { return common.EmptyDecimalValue(), errorLiteral, evalError } switch castValue := value.Value().(type) { case decimal.Decimal: return common.SomeDecimalValue(castValue, value.Event()), "", nil case string: decimalValue, parseError := decimal.NewFromString(castValue) if parseError != nil { return common.EmptyDecimalValue(), what.Literal(), fmt.Errorf("failed to parse value-expression: %w", parseError) } return common.SomeDecimalValue(decimalValue, value.Event()), "", nil case nil: return common.SomeDecimalValue(decimal.Zero, value.Event()), "", nil default: return common.EmptyDecimalValue(), what.Literal(), fmt.Errorf("expected value-expression to eval to a decimal instead of %T", value) } } func (what *ValueExpression) stringToString(scope *common.Scope, valueString *common.StringValue) (*common.StringValue, string, error) { value, errorLiteral, evalError := what.evalStringReference(scope, valueString) if evalError != nil { return common.EmptyStringValue(), errorLiteral, evalError } switch castValue := value.Value().(type) { case string: return common.SomeStringValue(castValue, value.Event()), "", nil case *common.StringValue: return castValue, "", nil case nil: return common.EmptyStringValue(), "", nil default: return common.EmptyStringValue(), what.Literal(), fmt.Errorf("expected value-expression to eval to a string instead of %T", value) } } func (what *ValueExpression) evalStringReference(scope *common.Scope, ref *common.StringValue) (common.Value, string, error) { varRe := `\{[^{}]+}` value := what.resolveStringValues(scope, varRe, ref) if regexp.MustCompile(`^` + varRe + `$`).MatchString(value.StringValue()) { returnValue, ok := scope.Get(value.StringValue()[1 : len(value.StringValue())-1]) if ok { return returnValue, "", nil } return returnValue, "", nil // return common.SomeStringValue(value.StringValue()[1:len(value.StringValue())-1], nil), "", nil } funcRe := `(\w+)\(([^()]+)\)` resolvedValue, errorLiteral, evalError := what.resolveMethodCalls(scope, funcRe, value) if evalError != nil { return common.EmptyStringValue(), errorLiteral, evalError } if regexp.MustCompile(`^` + funcRe + `$`).MatchString(resolvedValue.StringValue()) { genericValue, genericErrorLiteral, genericEvalError := what.resolveMethodCall(scope, funcRe, resolvedValue) return common.SomeValue(genericValue, ref.Event()), genericErrorLiteral, genericEvalError } return common.SomeValue(resolvedValue, ref.Event()), "", nil } func (what *ValueExpression) resolveStringValues(scope *common.Scope, reString string, value *common.StringValue) *common.StringValue { replacements := 0 values := make([]common.Value, 0) text := regexp.MustCompile(reString).ReplaceAllStringFunc(value.StringValue(), func(name string) string { cleanName := name[1 : len(name)-1] item, ok := scope.Get(strings.ToLower(cleanName)) if !ok { return name } switch castItem := item.Value().(type) { case string: replacements++ return castItem case common.Value: values = append(values, castItem) stringValue := castItem.PlainValue() switch castStringValue := stringValue.(type) { case string: replacements++ return castStringValue default: return name } default: return name } }) if replacements > 0 { return what.resolveStringValues(scope, reString, common.SomeStringValue(text, value.Event().From(values...))) } return common.SomeStringValue(text, value.Event()) } func (what *ValueExpression) resolveMethodCalls(scope *common.Scope, reString string, value *common.StringValue) (*common.StringValue, string, error) { replacements := 0 values := make([]common.Value, 0) text := regexp.MustCompile(reString).ReplaceAllStringFunc(value.StringValue(), func(name string) string { returnValue, _, callError := what.resolveMethodCall(scope, reString, common.SomeStringValue(name, value.Event())) if callError != nil { return name } if returnValue != nil { stringValue, valueError := common.ToString(returnValue) if valueError != nil { return name } replacements++ values = append(values, stringValue) return stringValue.StringValue() } return name }) if replacements == 0 { return common.SomeStringValue(text, value.Event().From(values...)), "", nil } return what.resolveMethodCalls(scope, reString, common.SomeStringValue(text, value.Event().From(values...))) } func (what *ValueExpression) resolveMethodCall(scope *common.Scope, reString string, value *common.StringValue) (common.Value, string, error) { re := regexp.MustCompile(reString) match := re.FindStringSubmatch(value.StringValue()) if len(match) != 3 { return common.NilValue(), what.Literal(), fmt.Errorf("method call match failed for %q", value.StringValue()) } name := strings.ToLower(match[1]) args := make([]common.Value, 0) if len(strings.TrimSpace(match[2])) > 0 { // todo: better arg parsing for '{var1}, {var2}' for _, arg := range strings.Split(match[2], ",") { val, errorLiteral, evalError := what.evalStringReference(scope, common.SomeStringValue(strings.TrimSpace(arg), value.Event())) if evalError != nil { return nil, errorLiteral, fmt.Errorf("failed to eval method parameter: %w", evalError) } args = append(args, val) } } method, ok := scope.Methods[name] if ok { newScope, cloneError := scope.Clone() if cloneError != nil { return common.NilValue(), what.Literal(), fmt.Errorf("failed to clone scope: %w", cloneError) } newScope.Args = args errorLiteral, runError := method.Run(newScope) if runError != nil { return common.NilValue(), errorLiteral, fmt.Errorf("failed to run method %q: %w", name, runError) } return newScope.GetReturnValue(), "", nil } if common.IsBuiltIn(name) { callValue, callError := common.CallBuiltIn(name, args...) if callError != nil { return common.NilValue(), what.Literal(), fmt.Errorf("failed to call %q: %w", name, callError) } return callValue, "", nil } return common.NilValue(), what.Literal(), fmt.Errorf("no method %q", match[1]) } func (what *ValueExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/equal-or-less-expression.go
pkg/risks/script/expressions/equal-or-less-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type EqualOrLessExpression struct { literal string first common.ValueExpression second common.ValueExpression as string } func (what *EqualOrLessExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) switch script.(type) { case map[string]any: for key, value := range script.(map[string]any) { switch key { case common.First: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.first = item case common.Second: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.second = item case common.As: item, ok := value.(string) if !ok { return nil, script, fmt.Errorf("failed to parse equal-expression: %q is not a string but %T", key, value) } what.as = item default: return nil, script, fmt.Errorf("failed to parse equal-expression: unexpected keyword %q", key) } } default: return nil, script, fmt.Errorf("failed to parse equal-expression: expected map[string]any, got %T", script) } return what, nil, nil } func (what *EqualOrLessExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *EqualOrLessExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { first, errorItemLiteral, itemError := what.first.EvalAny(scope) if itemError != nil { return common.EmptyBoolValue(), errorItemLiteral, itemError } second, errorInLiteral, evalError := what.second.EvalAny(scope) if evalError != nil { return common.EmptyBoolValue(), errorInLiteral, evalError } compareValue, compareError := common.Compare(first, second, what.as) if compareError != nil { return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to compare equal-expression: %w", compareError) } if common.IsSame(compareValue.Property) { return common.SomeBoolValue(true, compareValue), "", nil } if common.IsLess(compareValue.Property) { return common.SomeBoolValue(true, compareValue), "", nil } return common.SomeBoolValue(false, compareValue), "", nil } func (what *EqualOrLessExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *EqualOrLessExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/or-expression.go
pkg/risks/script/expressions/or-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type OrExpression struct { literal string expressions []common.BoolExpression } func (what *OrExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) item, errorScript, itemError := new(ExpressionList).ParseAny(script) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse or-expression list: %w", itemError) } switch castItem := item.(type) { case common.ExpressionList: for _, expression := range castItem.Expressions() { boolExpression, ok := expression.(common.BoolExpression) if !ok { return nil, script, fmt.Errorf("or-expression contains non-bool expression: %w", itemError) } what.expressions = append(what.expressions, boolExpression) } case common.BoolExpression: what.expressions = append(what.expressions, castItem) default: return nil, script, fmt.Errorf("or-expression has non-bool expression: %w", itemError) } return what, nil, nil } func (what *OrExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *OrExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { values := make([]common.Value, 0) for index, expression := range what.expressions { value, errorLiteral, evalError := expression.EvalBool(scope) if evalError != nil { return common.EmptyBoolValue(), errorLiteral, fmt.Errorf("%q: error evaluating or-expression #%v: %w", what.literal, index+1, evalError) } if value.BoolValue() { return common.SomeBoolValue(true, value.Event()), "", nil } values = append(values, value) } return common.SomeBoolValue(false, common.NewEvent(common.NewFalseProperty(), common.EmptyPath()).From(values...)), "", nil } func (what *OrExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *OrExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/expression-list.go
pkg/risks/script/expressions/expression-list.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type ExpressionList struct { literal string expressions []common.Expression } func (what *ExpressionList) ParseExpression(script map[string]any) (common.Expression, any, error) { for key, value := range script { switch key { case common.All: return new(AllExpression).ParseBool(value) case common.Any: return new(AnyExpression).ParseBool(value) case common.And: return new(AndExpression).ParseBool(value) case common.Contains: return new(ContainsExpression).ParseBool(value) case common.Count: return new(CountExpression).ParseDecimal(value) case common.Equal: return new(EqualExpression).ParseBool(value) case common.EqualOrGreater: return new(EqualOrGreaterExpression).ParseBool(value) case common.EqualOrLess: return new(EqualOrLessExpression).ParseBool(value) case common.False: return new(FalseExpression).ParseBool(value) case common.Greater: return new(GreaterExpression).ParseBool(value) case common.Less: return new(LessExpression).ParseBool(value) case common.NotEqual: return new(NotEqualExpression).ParseBool(value) case common.Or: return new(OrExpression).ParseBool(value) case common.True: return new(TrueExpression).ParseBool(value) default: return nil, script, fmt.Errorf("failed to parse expression: unexpected keyword %q", key) } } return what, nil, nil } func (what *ExpressionList) ParseArray(script any) (common.ExpressionList, any, error) { what.literal = common.ToLiteral(script) switch castScript := script.(type) { case []any: for _, expression := range castScript { item, errorScript, itemError := what.ParseAny(expression) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse expression list: %w", itemError) } what.expressions = append(what.expressions, item) } default: return nil, script, fmt.Errorf("unexpected expression list format %T", script) } return what, nil, nil } func (what *ExpressionList) ParseAny(script any) (common.Expression, any, error) { what.literal = common.ToLiteral(script) switch castScript := script.(type) { case map[any]any: newMap := make(map[string]any) for key, value := range castScript { newMap[fmt.Sprintf("%v", key)] = value } return what.ParseExpression(newMap) case map[string]any: return what.ParseExpression(castScript) case []any: for _, expression := range castScript { item, errorScript, itemError := what.ParseAny(expression) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse expression list: %w", itemError) } what.expressions = append(what.expressions, item) } if len(what.expressions) == 1 { return what.expressions[0], nil, nil } default: return new(ValueExpression).ParseAny(script) } return what, nil, nil } func (what *ExpressionList) EvalAny(scope *common.Scope) (common.Value, string, error) { if what.expressions == nil { return nil, "", nil } switch len(what.expressions) { case 0: return nil, "", nil case 1: return what.expressions[0].EvalAny(scope) default: var values []common.Value for _, expression := range what.expressions { value, errorLiteral, statementError := expression.EvalAny(scope) if statementError != nil { return nil, errorLiteral, statementError } values = append(values, value) } return common.SomeArrayValue(values, common.NewEvent(common.NewValueProperty(values), common.NewPath("array value")).From(values...)), "", nil } } func (what *ExpressionList) Literal() string { return what.literal } func (what *ExpressionList) Expressions() []common.Expression { return what.expressions }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/equal-or-greater-expression.go
pkg/risks/script/expressions/equal-or-greater-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type EqualOrGreaterExpression struct { literal string first common.ValueExpression second common.ValueExpression as string } func (what *EqualOrGreaterExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) switch script.(type) { case map[string]any: for key, value := range script.(map[string]any) { switch key { case common.First: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.first = item case common.Second: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.second = item case common.As: item, ok := value.(string) if !ok { return nil, script, fmt.Errorf("failed to parse equal-expression: %q is not a string but %T", key, value) } what.as = item default: return nil, script, fmt.Errorf("failed to parse equal-expression: unexpected keyword %q", key) } } default: return nil, script, fmt.Errorf("failed to parse equal-expression: expected map[string]any, got %T", script) } return what, nil, nil } func (what *EqualOrGreaterExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *EqualOrGreaterExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { first, errorItemLiteral, itemError := what.first.EvalAny(scope) if itemError != nil { return common.EmptyBoolValue(), errorItemLiteral, itemError } second, errorInLiteral, evalError := what.second.EvalAny(scope) if evalError != nil { return common.EmptyBoolValue(), errorInLiteral, evalError } compareValue, compareError := common.Compare(first, second, what.as) if compareError != nil { return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to compare equal-expression: %w", compareError) } if common.IsSame(compareValue.Property) { return common.SomeBoolValue(true, compareValue), "", nil } if common.IsGreater(compareValue.Property) { return common.SomeBoolValue(true, compareValue), "", nil } return common.SomeBoolValue(false, compareValue), "", nil } func (what *EqualOrGreaterExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *EqualOrGreaterExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/contains-expression.go
pkg/risks/script/expressions/contains-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type ContainsExpression struct { literal string item common.ValueExpression in common.ValueExpression as string } func (what *ContainsExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) switch script.(type) { case map[string]any: for key, value := range script.(map[string]any) { switch key { case common.Item: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of contains-expression: %w", key, itemError) } what.item = item case common.In: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of contains-expression: %w", key, itemError) } what.in = item case common.As: item, ok := value.(string) if !ok { return nil, script, fmt.Errorf("failed to parse contains-expression: %q is not a string but %T", key, value) } what.as = item default: return nil, script, fmt.Errorf("failed to parse contains-expression: unexpected keyword %q", key) } } default: return nil, script, fmt.Errorf("failed to parse contains-expression: expected map[string]any, got %T", script) } return what, nil, nil } func (what *ContainsExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *ContainsExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { item, errorItemLiteral, itemError := what.item.EvalAny(scope) if itemError != nil { return common.EmptyBoolValue(), errorItemLiteral, itemError } inValue, errorInLiteral, evalError := what.in.EvalAny(scope) if evalError != nil { return common.EmptyBoolValue(), errorInLiteral, evalError } return what.evalBool(scope, item, inValue) } func (what *ContainsExpression) evalBool(scope *common.Scope, item common.Value, inValue common.Value) (*common.BoolValue, string, error) { switch castValue := inValue.Value().(type) { case []any: for index, value := range castValue { compareValue, compareError := common.Compare(item, common.SomeValue(value, nil), what.as) if compareError != nil { return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to eval contains-expression: can't compare value to item #%v: %w", index+1, compareError) } if common.IsSame(compareValue.Property) { return common.SomeBoolValue(true, compareValue), "", nil } } return common.SomeBoolValue(false, nil), "", nil case []common.Value: for index, value := range castValue { compareValue, compareError := common.Compare(item, common.SomeValue(value.Value(), value.Event()), what.as) if compareError != nil { return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to eval contains-expression: can't compare value to item #%v: %w", index+1, compareError) } if common.IsSame(compareValue.Property) { return common.SomeBoolValue(true, compareValue), "", nil } } return common.SomeBoolValue(false, nil), "", nil case map[string]any: for name, value := range castValue { compareValue, compareError := common.Compare(item, common.SomeValue(value, nil), what.as) if compareError != nil { return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to eval contains-expression: can't compare value to item %q: %w", name, compareError) } if common.IsSame(compareValue.Property) { return common.SomeBoolValue(true, compareValue), "", nil } } return common.SomeBoolValue(false, nil), "", nil case common.Value: return what.evalBool(scope, item, common.SomeValue(castValue.Value(), inValue.Event())) case nil: return common.SomeBoolValue(false, nil), "", nil default: return common.EmptyBoolValue(), "", fmt.Errorf("failed to eval contains-expression: expected iterable type, got %T", inValue) } } func (what *ContainsExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *ContainsExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/false-expression.go
pkg/risks/script/expressions/false-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type FalseExpression struct { literal string expression common.BoolExpression } func (what *FalseExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) item, errorScript, itemError := new(ExpressionList).ParseAny(script) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse false-expression: %w", itemError) } switch castItem := item.(type) { case common.BoolExpression: what.expression = castItem default: return nil, script, fmt.Errorf("false-expression has non-bool expression: %w", itemError) } return what, nil, nil } func (what *FalseExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *FalseExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { value, errorLiteral, evalError := what.expression.EvalBool(scope) if evalError != nil { return common.EmptyBoolValue(), errorLiteral, fmt.Errorf("%q: error evaluating false-expression: %w", what.literal, evalError) } return common.SomeBoolValue(!value.BoolValue(), value.Event()), "", nil } func (what *FalseExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *FalseExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/less-expression.go
pkg/risks/script/expressions/less-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type LessExpression struct { literal string first common.ValueExpression second common.ValueExpression as string } func (what *LessExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) switch script.(type) { case map[string]any: for key, value := range script.(map[string]any) { switch key { case common.First: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.first = item case common.Second: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.second = item case common.As: item, ok := value.(string) if !ok { return nil, script, fmt.Errorf("failed to parse equal-expression: %q is not a string but %T", key, value) } what.as = item default: return nil, script, fmt.Errorf("failed to parse equal-expression: unexpected keyword %q", key) } } default: return nil, script, fmt.Errorf("failed to parse equal-expression: expected map[string]any, got %T", script) } return what, nil, nil } func (what *LessExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *LessExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { first, errorItemLiteral, itemError := what.first.EvalAny(scope) if itemError != nil { return common.EmptyBoolValue(), errorItemLiteral, itemError } second, errorInLiteral, evalError := what.second.EvalAny(scope) if evalError != nil { return common.EmptyBoolValue(), errorInLiteral, evalError } compareValue, compareError := common.Compare(first, second, what.as) if compareError != nil { return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to compare equal-expression: %w", compareError) } if common.IsLess(compareValue.Property) { return common.SomeBoolValue(true, compareValue), "", nil } return common.SomeBoolValue(false, compareValue), "", nil } func (what *LessExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *LessExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/equal-expression.go
pkg/risks/script/expressions/equal-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type EqualExpression struct { literal string first common.ValueExpression second common.ValueExpression as string } func (what *EqualExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) switch script.(type) { case map[string]any: for key, value := range script.(map[string]any) { switch key { case common.First: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.first = item case common.Second: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.second = item case common.As: item, ok := value.(string) if !ok { return nil, script, fmt.Errorf("failed to parse equal-expression: %q is not a string but %T", key, value) } what.as = item default: return nil, script, fmt.Errorf("failed to parse equal-expression: unexpected keyword %q", key) } } default: return nil, script, fmt.Errorf("failed to parse equal-expression: expected map[string]any, got %T", script) } return what, nil, nil } func (what *EqualExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *EqualExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { first, errorItemLiteral, itemError := what.first.EvalAny(scope) if itemError != nil { return common.EmptyBoolValue(), errorItemLiteral, itemError } second, errorInLiteral, evalError := what.second.EvalAny(scope) if evalError != nil { return common.EmptyBoolValue(), errorInLiteral, evalError } compareValue, compareError := common.Compare(first, second, what.as) if compareError != nil { return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to compare equal-expression: %w", compareError) } if common.IsSame(compareValue.Property) { return common.SomeBoolValue(true, compareValue), "", nil } return common.SomeBoolValue(false, compareValue), "", nil } func (what *EqualExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *EqualExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/not-equal-expression.go
pkg/risks/script/expressions/not-equal-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type NotEqualExpression struct { literal string first common.ValueExpression second common.ValueExpression as string } func (what *NotEqualExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) switch script.(type) { case map[string]any: for key, value := range script.(map[string]any) { switch key { case common.First: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.first = item case common.Second: item, errorScript, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse %q of equal-expression: %w", key, itemError) } what.second = item case common.As: item, ok := value.(string) if !ok { return nil, script, fmt.Errorf("failed to parse equal-expression: %q is not a string but %T", key, value) } what.as = item default: return nil, script, fmt.Errorf("failed to parse equal-expression: unexpected keyword %q", key) } } default: return nil, script, fmt.Errorf("failed to parse equal-expression: expected map[string]any, got %T", script) } return what, nil, nil } func (what *NotEqualExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *NotEqualExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { first, errorItemLiteral, itemError := what.first.EvalAny(scope) if itemError != nil { return common.EmptyBoolValue(), errorItemLiteral, itemError } second, errorInLiteral, evalError := what.second.EvalAny(scope) if evalError != nil { return common.EmptyBoolValue(), errorInLiteral, evalError } compareValue, compareError := common.Compare(first, second, what.as) if compareError != nil { return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to compare not-equal-expression: %w", compareError) } if !common.IsSame(compareValue.Property) { return common.SomeBoolValue(true, compareValue), "", nil } return common.SomeBoolValue(false, compareValue), "", nil } func (what *NotEqualExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *NotEqualExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/and-expression.go
pkg/risks/script/expressions/and-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type AndExpression struct { literal string expressions []common.BoolExpression } func (what *AndExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) item, errorScript, itemError := new(ExpressionList).ParseAny(script) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse and-expression list: %w", itemError) } switch castItem := item.(type) { case common.ExpressionList: for _, expression := range castItem.Expressions() { boolExpression, ok := expression.(common.BoolExpression) if !ok { return nil, script, fmt.Errorf("and-expression contains non-bool expression: %w", itemError) } what.expressions = append(what.expressions, boolExpression) } case common.BoolExpression: what.expressions = append(what.expressions, castItem) default: return nil, script, fmt.Errorf("and-expression has non-bool expression: %w", itemError) } return what, nil, nil } func (what *AndExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *AndExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { values := make([]common.Value, 0) for index, expression := range what.expressions { value, errorLiteral, evalError := expression.EvalBool(scope) if evalError != nil { return common.EmptyBoolValue(), errorLiteral, fmt.Errorf("%q: error evaluating and-expression #%v: %w", what.literal, index+1, evalError) } if !value.BoolValue() { return common.SomeBoolValue(false, value.Event()), "", nil } values = append(values, value) } return common.SomeBoolValue(true, common.NewEvent(common.NewTrueProperty(), common.EmptyPath()).From(values...)), "", nil } func (what *AndExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *AndExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/count-expression.go
pkg/risks/script/expressions/count-expression.go
package expressions import ( "fmt" "github.com/shopspring/decimal" "github.com/threagile/threagile/pkg/risks/script/common" ) type CountExpression struct { literal string in common.ValueExpression item string index string expression common.BoolExpression } func (what *CountExpression) ParseDecimal(script any) (common.DecimalExpression, any, error) { what.literal = common.ToLiteral(script) switch script.(type) { case map[string]any: for key, value := range script.(map[string]any) { switch key { case common.In: item, errorExpression, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorExpression, fmt.Errorf("failed to parse %q of count-expression: %w", key, itemError) } what.in = item case common.Item: text, ok := value.(string) if !ok { return nil, value, fmt.Errorf("failed to parse %q of count-expression: expected string, got %T", key, value) } what.item = text case common.Index: text, ok := value.(string) if !ok { return nil, value, fmt.Errorf("failed to parse %q of count-expression: expected string, got %T", key, value) } what.index = text default: if what.expression != nil { return nil, script, fmt.Errorf("failed to parse count-expression: additional bool expression %q", key) } expression, errorScript, itemError := new(ExpressionList).ParseAny(map[string]any{key: value}) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse count-expression: %w", itemError) } boolExpression, ok := expression.(common.BoolExpression) if !ok { return nil, script, fmt.Errorf("count-expression contains non-bool expression: %w", itemError) } what.expression = boolExpression } } default: return nil, script, fmt.Errorf("failed to parse count-expression: expected map[string]any, got %T", script) } return what, nil, nil } func (what *CountExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseDecimal(script) } func (what *CountExpression) EvalDecimal(scope *common.Scope) (*common.DecimalValue, string, error) { oldItem := scope.PopItem() defer scope.SetItem(oldItem) inValue, errorEvalLiteral, evalError := what.in.EvalAny(scope) if evalError != nil { return common.EmptyDecimalValue(), errorEvalLiteral, evalError } return what.evalDecimal(scope, inValue) } func (what *CountExpression) evalDecimal(scope *common.Scope, inValue common.Value) (*common.DecimalValue, string, error) { switch castValue := inValue.Value().(type) { case []any: if what.expression == nil { return common.SomeDecimalValue(decimal.NewFromInt(int64(len(castValue))), nil), "", nil } var count int64 = 0 values := make([]common.Value, 0) for index, item := range castValue { if len(what.index) > 0 { scope.Set(what.index, common.SomeDecimalValue(decimal.NewFromInt(int64(index)), nil)) } itemValue := scope.SetItem(common.SomeValue(item, inValue.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } value, errorLiteral, expressionError := what.expression.EvalBool(scope) if expressionError != nil { return common.EmptyDecimalValue(), errorLiteral, fmt.Errorf("error evaluating expression #%v of all-expression: %w", index+1, expressionError) } if value.BoolValue() { values = append(values, value) count++ } } return common.SomeDecimalValue(decimal.NewFromInt(count), inValue.Event().From(values...)), "", nil case []common.Value: if what.expression == nil { return common.SomeDecimalValue(decimal.NewFromInt(int64(len(castValue))), nil), "", nil } var count int64 = 0 values := make([]common.Value, 0) for index, item := range castValue { if len(what.index) > 0 { scope.Set(what.index, common.SomeDecimalValue(decimal.NewFromInt(int64(index)), nil)) } itemValue := scope.SetItem(common.SomeValue(item.Value(), inValue.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } value, errorLiteral, expressionError := what.expression.EvalBool(scope) if expressionError != nil { return common.EmptyDecimalValue(), errorLiteral, fmt.Errorf("error evaluating expression #%v of all-expression: %w", index+1, expressionError) } if value.BoolValue() { values = append(values, value) count++ } } return common.SomeDecimalValue(decimal.NewFromInt(count), inValue.Event().From(values...)), "", nil case map[string]any: if what.expression == nil { return common.SomeDecimalValue(decimal.NewFromInt(int64(len(castValue))), nil), "", nil } var count int64 = 0 values := make([]common.Value, 0) for name, item := range castValue { if len(what.index) > 0 { scope.Set(what.index, common.SomeStringValue(name, nil)) } itemValue := scope.SetItem(common.SomeValue(item, inValue.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } value, errorLiteral, expressionError := what.expression.EvalBool(scope) if expressionError != nil { return common.EmptyDecimalValue(), errorLiteral, fmt.Errorf("error evaluating expression %q of all-expression: %w", name, expressionError) } if value.BoolValue() { values = append(values, value) count++ } } return common.SomeDecimalValue(decimal.NewFromInt(count), inValue.Event().From(values...)), "", nil case common.Value: return what.evalDecimal(scope, common.SomeValue(castValue.Value(), inValue.Event())) case nil: return common.EmptyDecimalValue(), "", nil default: return common.EmptyDecimalValue(), what.Literal(), fmt.Errorf("failed to eval all-expression: expected iterable type, got %T", inValue) } } func (what *CountExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalDecimal(scope) } func (what *CountExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/true-expression.go
pkg/risks/script/expressions/true-expression.go
package expressions import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/common" ) type TrueExpression struct { literal string expression common.BoolExpression } func (what *TrueExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) item, errorScript, itemError := new(ExpressionList).ParseAny(script) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse true-expression: %w", itemError) } switch castItem := item.(type) { case common.BoolExpression: what.expression = castItem default: return nil, script, fmt.Errorf("true-expression has non-bool expression: %w", itemError) } return what, nil, nil } func (what *TrueExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *TrueExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { value, errorLiteral, evalError := what.expression.EvalBool(scope) if evalError != nil { return common.EmptyBoolValue(), errorLiteral, fmt.Errorf("%q: error evaluating true-expression: %w", what.literal, evalError) } return value, "", nil } func (what *TrueExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *TrueExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/expressions/all-expression.go
pkg/risks/script/expressions/all-expression.go
package expressions import ( "fmt" "github.com/shopspring/decimal" "github.com/threagile/threagile/pkg/risks/script/common" ) type AllExpression struct { literal string in common.ValueExpression item string index string expression common.BoolExpression } func (what *AllExpression) ParseBool(script any) (common.BoolExpression, any, error) { what.literal = common.ToLiteral(script) switch script.(type) { case map[string]any: for key, value := range script.(map[string]any) { switch key { case common.In: item, errorExpression, itemError := new(ValueExpression).ParseValue(value) if itemError != nil { return nil, errorExpression, fmt.Errorf("failed to parse %q of all-expression: %w", key, itemError) } what.in = item case common.Item: text, ok := value.(string) if !ok { return nil, value, fmt.Errorf("failed to parse %q of all-expression: expected string, got %T", key, value) } what.item = text case common.Index: text, ok := value.(string) if !ok { return nil, value, fmt.Errorf("failed to parse %q of all-expression: expected string, got %T", key, value) } what.index = text default: if what.expression != nil { return nil, script, fmt.Errorf("failed to parse all-expression: additional bool expression %q", key) } expression, errorScript, itemError := new(ExpressionList).ParseAny(map[string]any{key: value}) if itemError != nil { return nil, errorScript, fmt.Errorf("failed to parse all-expression: %w", itemError) } boolExpression, ok := expression.(common.BoolExpression) if !ok { return nil, script, fmt.Errorf("all-expression contains non-bool expression: %w", itemError) } what.expression = boolExpression } } default: return nil, script, fmt.Errorf("failed to parse all-expression: expected map[string]any, got %T", script) } return what, nil, nil } func (what *AllExpression) ParseAny(script any) (common.Expression, any, error) { return what.ParseBool(script) } func (what *AllExpression) EvalBool(scope *common.Scope) (*common.BoolValue, string, error) { oldItem := scope.PopItem() defer scope.SetItem(oldItem) inValue, errorEvalLiteral, evalError := what.in.EvalAny(scope) if evalError != nil { return common.EmptyBoolValue(), errorEvalLiteral, evalError } return what.evalBool(scope, inValue) } func (what *AllExpression) evalBool(scope *common.Scope, inValue common.Value) (*common.BoolValue, string, error) { oldItem := scope.PopItem() defer scope.SetItem(oldItem) switch castValue := inValue.Value().(type) { case []any: if what.expression == nil { return common.SomeBoolValue(true, nil), "", nil } values := make([]common.Value, 0) for index, item := range castValue { if len(what.index) > 0 { scope.Set(what.index, common.SomeDecimalValue(decimal.NewFromInt(int64(index)), nil)) } itemValue := scope.SetItem(common.SomeValue(item, inValue.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } value, errorLiteral, expressionError := what.expression.EvalBool(scope) if expressionError != nil { return common.EmptyBoolValue(), errorLiteral, fmt.Errorf("error evaluating expression #%v of all-expression: %w", index+1, expressionError) } if !value.BoolValue() { return common.SomeBoolValue(false, value.Event()), "", nil } values = append(values, value) } return common.SomeBoolValue(true, common.NewEvent(common.NewTrueProperty(), inValue.Event().Origin).From(values...)), "", nil case []common.Value: if what.expression == nil { return common.SomeBoolValue(true, nil), "", nil } values := make([]common.Value, 0) for index, item := range castValue { if len(what.index) > 0 { scope.Set(what.index, common.SomeDecimalValue(decimal.NewFromInt(int64(index)), nil)) } itemValue := scope.SetItem(common.SomeValue(item.Value(), inValue.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } value, errorLiteral, expressionError := what.expression.EvalBool(scope) if expressionError != nil { return common.EmptyBoolValue(), errorLiteral, fmt.Errorf("error evaluating expression #%v of all-expression: %w", index+1, expressionError) } if !value.BoolValue() { return common.SomeBoolValue(false, value.Event()), "", nil } values = append(values, value) } return common.SomeBoolValue(true, common.NewEvent(common.NewTrueProperty(), inValue.Event().Origin).From(values...)), "", nil case map[string]any: if what.expression == nil { return common.SomeBoolValue(true, nil), "", nil } values := make([]common.Value, 0) for name, item := range castValue { if len(what.index) > 0 { scope.Set(what.index, common.SomeStringValue(name, nil)) } itemValue := scope.SetItem(common.SomeValue(item, inValue.Event())) if len(what.item) > 0 { scope.Set(what.item, itemValue) } value, errorLiteral, expressionError := what.expression.EvalBool(scope) if expressionError != nil { return common.EmptyBoolValue(), errorLiteral, fmt.Errorf("error evaluating expression %q of all-expression: %w", name, expressionError) } if !value.BoolValue() { return common.SomeBoolValue(false, value.Event()), "", nil } values = append(values, value) } return common.SomeBoolValue(true, common.NewEvent(common.NewTrueProperty(), inValue.Event().Origin).From(values...)), "", nil case common.Value: return what.evalBool(scope, common.SomeValue(castValue.Value(), inValue.Event())) case nil: return common.SomeBoolValue(false, nil), "", nil default: return common.EmptyBoolValue(), what.Literal(), fmt.Errorf("failed to eval all-expression: expected iterable type, got %T", inValue) } } func (what *AllExpression) EvalAny(scope *common.Scope) (common.Value, string, error) { return what.EvalBool(scope) } func (what *AllExpression) Literal() string { return what.literal }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/key-words.go
pkg/risks/script/common/key-words.go
package common const ( Risk = "risk" Data = "data" ID = "id" Match = "match" Utils = "utils" Assign = "assign" Loop = "loop" Do = "do" Return = "return" In = "in" Item = "item" Index = "index" Parameter = "parameter" Parameters = "parameters" As = "as" First = "first" Second = "second" If = "if" Then = "then" Else = "else" Defer = "defer" Explain = "explain" All = "all" And = "and" Any = "any" Contains = "contains" Count = "count" Equal = "equal" EqualOrGreater = "equal-or-greater" EqualOrLess = "equal-or-less" False = "false" Greater = "greater" Less = "less" NotEqual = "not-equal" Or = "or" True = "true" )
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/event.go
pkg/risks/script/common/event.go
package common import ( "strings" ) type Event struct { Origin *Path Property *Property Events []*Event } func NewEvent(property *Property, path *Path) *Event { return &Event{ Property: property, Origin: path, } } func NewEventFrom(property *Property, firstValue Value, value ...Value) *Event { var path *Path var events []*Event if firstValue != nil && firstValue.Event() != nil { path = firstValue.Event().Path().Copy() events = firstValue.Event().Events } event := &Event{ Property: property, Origin: path, Events: events, } event.From(value...) return event } func EmptyEvent() *Event { return &Event{ Property: NewBlankProperty(), } } func (what *Event) From(values ...Value) *Event { if what == nil { return what } for _, value := range values { if value.Event() != nil { what.Events = append(what.Events, value.Event()) } } return what } func (what *Event) AddHistory(history []*Event) *Event { if what == nil { return what } what.Events = append(what.Events, history...) return what } func (what *Event) Path() *Path { if what == nil { return nil } return what.Origin } func (what *Event) SetPath(path *Path) *Event { if what == nil { return what } what.Origin = path return what } func (what *Event) AddPathParent(path ...string) *Event { if what == nil { return what } what.Origin.AddPathParent(path...) return what } func (what *Event) AddPathLeaf(path ...string) *Event { if what == nil { return what } what.Origin.AddPathLeaf(path...) return what } func (what *Event) String() string { if what == nil { return "" } return strings.Join(what.Indented(0), "\n") } func (what *Event) Indented(level int) []string { if what == nil { return []string{} } propertyText := what.Property.Text() lines := make([]string, 0) text := what.Origin.String() + " is " if len(propertyText) <= 1 { text += strings.Join(propertyText, " ") if len(what.Events) > 0 { text += " because" } if len(text) > 0 { lines = append(lines, what.indent(level, text)) } } else { for _, line := range propertyText { lines = append(lines, what.indent(level+1, line)) } if len(what.Events) > 0 { lines = append(lines, what.indent(level, " because")) } } for _, event := range what.Events { lines = append(lines, event.Indented(level+1)...) } return lines } func (what *Event) indent(level int, text string) string { if what == nil { return "" } return strings.Repeat(" ", level) + text }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/array-expression.go
pkg/risks/script/common/array-expression.go
package common type ArrayExpression interface { ParseArray(script any) (ArrayExpression, any, error) ParseAny(script any) (Expression, any, error) EvalArray(scope *Scope) (*ArrayValue, string, error) EvalAny(scope *Scope) (Value, string, error) Literal() string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/literal.go
pkg/risks/script/common/literal.go
package common import ( "fmt" "gopkg.in/yaml.v3" ) func ToLiteral(script any) string { switch script.(type) { case []any, map[string]any: data, marshalError := yaml.Marshal(script) if marshalError != nil { return fmt.Sprintf("%v", script) } return string(data) default: return fmt.Sprintf("%v", script) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/string-expression.go
pkg/risks/script/common/string-expression.go
package common type StringExpression interface { ParseString(script any) (StringExpression, any, error) ParseAny(script any) (Expression, any, error) EvalString(scope *Scope) (*StringValue, string, error) EvalAny(scope *Scope) (Value, string, error) Literal() string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/value-expression.go
pkg/risks/script/common/value-expression.go
package common type ValueExpression interface { ParseArray(script any) (ArrayExpression, any, error) ParseBool(script any) (BoolExpression, any, error) ParseDecimal(script any) (DecimalExpression, any, error) ParseString(script any) (StringExpression, any, error) ParseAny(script any) (Expression, any, error) EvalArray(scope *Scope) (*ArrayValue, string, error) EvalBool(scope *Scope) (*BoolValue, string, error) EvalDecimal(scope *Scope) (*DecimalValue, string, error) EvalString(scope *Scope) (*StringValue, string, error) EvalAny(scope *Scope) (Value, string, error) Literal() string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/path.go
pkg/risks/script/common/path.go
package common import ( "fmt" "strings" ) type Path struct { Path []string } func NewPath(path ...string) *Path { return new(Path).SetPath(path...) } func EmptyPath() *Path { return new(Path) } func (what *Path) Copy() *Path { if what == nil { return what } return &Path{ Path: what.Path[:], } } func (what *Path) SetPath(path ...string) *Path { if what == nil { return what } what.Path = path return what } func (what *Path) AddPathParent(path ...string) *Path { if what == nil { return what } what.Path = append(path, what.Path...) return what } func (what *Path) AddPathLeaf(path ...string) *Path { if what == nil { return what } what.Path = append(what.Path, path...) return what } func (what *Path) String() string { if what == nil { return "" } path := make([]string, 0) for _, item := range what.Path { path = append([]string{fmt.Sprintf("%v", item)}, path...) } return strings.Join(path, " of ") }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/bool-value.go
pkg/risks/script/common/bool-value.go
package common import ( "fmt" ) type BoolValue struct { value bool name Path event *Event } func (what BoolValue) Value() any { return what.value } func (what BoolValue) Name() Path { return what.name } func (what BoolValue) SetName(name ...string) { what.name.SetPath(name...) } func (what BoolValue) Event() *Event { return what.event } func (what BoolValue) PlainValue() any { return what.value } func (what BoolValue) Text() []string { return []string{fmt.Sprintf("%v", what.value)} } func (what BoolValue) BoolValue() bool { return what.value } func EmptyBoolValue() *BoolValue { return &BoolValue{} } func SomeBoolValue(value bool, event *Event) *BoolValue { return &BoolValue{ value: value, event: event, } } func ToBoolValue(value Value) (*BoolValue, error) { castValue, ok := value.Value().(bool) var conversionError error if !ok { conversionError = fmt.Errorf("expected value-expression to eval to a bool instead of %T", value.Value) } return &BoolValue{ value: castValue, name: value.Name(), event: value.Event(), }, conversionError }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/string-value.go
pkg/risks/script/common/string-value.go
package common import ( "fmt" ) type StringValue struct { value string name Path event *Event } func (what StringValue) Value() any { return what.value } func (what StringValue) Name() Path { return what.name } func (what StringValue) SetName(name ...string) { what.name.SetPath(name...) } func (what StringValue) Event() *Event { return what.event } func (what StringValue) PlainValue() any { return what.value } func (what StringValue) Text() []string { return []string{what.value} } func (what StringValue) StringValue() string { return what.value } func EmptyStringValue() *StringValue { return &StringValue{} } func SomeStringValue(value string, event *Event) *StringValue { return &StringValue{ value: value, event: event, } } func ToStringValue(value Value) (*StringValue, error) { castValue, ok := value.Value().(string) var conversionError error if !ok { conversionError = fmt.Errorf("expected value-expression to eval to a string instead of %T", value.Value) } return &StringValue{ value: castValue, name: value.Name(), event: value.Event(), }, conversionError }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/cast.go
pkg/risks/script/common/cast.go
package common import ( "fmt" "github.com/shopspring/decimal" "github.com/threagile/threagile/pkg/types" ) const ( authentication = "authentication" authorization = "authorization" confidentiality = "confidentiality" criticality = "criticality" integrity = "integrity" availability = "availability" probability = "probability" encryption = "encryption" quantity = "quantity" impact = "impact" likelihood = "likelihood" size = "size" ) var ( cast = map[string]castFunc{ authentication: toAuthentication, authorization: toAuthorization, confidentiality: toConfidentiality, criticality: toCriticality, integrity: toCriticality, availability: toCriticality, probability: toProbability, encryption: toEncryption, quantity: toQuantity, impact: toImpact, likelihood: toLikelihood, size: toSize, } ) type castFunc func(value Value) (Value, error) func CastValue(value Value, castType string) (Value, error) { if value == nil { return NilValue(), nil } caster, ok := cast[castType] if !ok { return nil, fmt.Errorf("unknown cast type %v", castType) } return caster(value) } func toConfidentiality(value Value) (Value, error) { switch castValue := value.Value().(type) { case string: converted, conversionError := types.Confidentiality(0).Find(castValue) if conversionError != nil { return nil, conversionError } return SomeDecimalValue(decimal.NewFromInt(int64(converted)), value.Event()), nil case int: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), value.Event()), nil case int64: return SomeDecimalValue(decimal.NewFromInt(castValue), value.Event()), nil case Value: return toConfidentiality(castValue) default: return nil, fmt.Errorf("toConfidentiality: unexpected type %T", value) } } func toCriticality(value Value) (Value, error) { switch castValue := value.Value().(type) { case string: converted, conversionError := types.Criticality(0).Find(castValue) if conversionError != nil { return nil, conversionError } return SomeDecimalValue(decimal.NewFromInt(int64(converted)), value.Event()), nil case int: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), value.Event()), nil case int64: return SomeDecimalValue(decimal.NewFromInt(castValue), value.Event()), nil case Value: return toCriticality(castValue) default: return nil, fmt.Errorf("toConfidentiality: unexpected type %T", value) } } func toAuthentication(value Value) (Value, error) { switch castValue := value.Value().(type) { case string: converted, conversionError := types.Authentication(0).Find(castValue) if conversionError != nil { return nil, conversionError } return SomeDecimalValue(decimal.NewFromInt(int64(converted)), value.Event()), nil case int: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), value.Event()), nil case int64: return SomeDecimalValue(decimal.NewFromInt(castValue), value.Event()), nil case Value: return toAuthentication(castValue) default: return nil, fmt.Errorf("toConfidentiality: unexpected type %T", value) } } func toAuthorization(value Value) (Value, error) { switch castValue := value.Value().(type) { case string: converted, conversionError := types.Authorization(0).Find(castValue) if conversionError != nil { return nil, conversionError } return SomeDecimalValue(decimal.NewFromInt(int64(converted)), value.Event()), nil case int: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), value.Event()), nil case int64: return SomeDecimalValue(decimal.NewFromInt(castValue), value.Event()), nil case Value: return toAuthorization(castValue) default: return nil, fmt.Errorf("toConfidentiality: unexpected type %T", value) } } func toProbability(value Value) (Value, error) { switch castValue := value.Value().(type) { case string: converted, conversionError := types.DataBreachProbability(0).Find(castValue) if conversionError != nil { return nil, conversionError } return SomeDecimalValue(decimal.NewFromInt(int64(converted)), value.Event()), nil case int: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), value.Event()), nil case int64: return SomeDecimalValue(decimal.NewFromInt(castValue), value.Event()), nil case Value: return toProbability(castValue) default: return nil, fmt.Errorf("toConfidentiality: unexpected type %T", value) } } func toEncryption(value Value) (Value, error) { switch castValue := value.Value().(type) { case string: converted, conversionError := types.EncryptionStyle(0).Find(castValue) if conversionError != nil { return nil, conversionError } return SomeDecimalValue(decimal.NewFromInt(int64(converted)), value.Event()), nil case int: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), value.Event()), nil case int64: return SomeDecimalValue(decimal.NewFromInt(castValue), value.Event()), nil case Value: return toEncryption(castValue) default: return nil, fmt.Errorf("toConfidentiality: unexpected type %T", value) } } func toQuantity(value Value) (Value, error) { switch castValue := value.Value().(type) { case string: converted, conversionError := types.Quantity(0).Find(castValue) if conversionError != nil { return nil, conversionError } return SomeDecimalValue(decimal.NewFromInt(int64(converted)), value.Event()), nil case int: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), value.Event()), nil case int64: return SomeDecimalValue(decimal.NewFromInt(castValue), value.Event()), nil case Value: return toQuantity(castValue) default: return nil, fmt.Errorf("toConfidentiality: unexpected type %T", value) } } func toImpact(value Value) (Value, error) { switch castValue := value.Value().(type) { case string: converted, conversionError := types.RiskExploitationImpact(0).Find(castValue) if conversionError != nil { return nil, conversionError } return SomeDecimalValue(decimal.NewFromInt(int64(converted)), value.Event()), nil case int: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), value.Event()), nil case int64: return SomeDecimalValue(decimal.NewFromInt(castValue), value.Event()), nil case Value: return toImpact(castValue) default: return nil, fmt.Errorf("toConfidentiality: unexpected type %T", value) } } func toLikelihood(value Value) (Value, error) { switch castValue := value.Value().(type) { case string: converted, conversionError := types.RiskExploitationLikelihood(0).Find(castValue) if conversionError != nil { return nil, conversionError } return SomeDecimalValue(decimal.NewFromInt(int64(converted)), value.Event()), nil case int: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), value.Event()), nil case int64: return SomeDecimalValue(decimal.NewFromInt(castValue), value.Event()), nil case Value: return toLikelihood(castValue) default: return nil, fmt.Errorf("toConfidentiality: unexpected type %T", value) } } func toSize(value Value) (Value, error) { switch castValue := value.Value().(type) { case string: converted, conversionError := types.TechnicalAssetSize(0).Find(castValue) if conversionError != nil { return nil, conversionError } return SomeDecimalValue(decimal.NewFromInt(int64(converted)), value.Event()), nil case int: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), value.Event()), nil case int64: return SomeDecimalValue(decimal.NewFromInt(castValue), value.Event()), nil case Value: return toSize(castValue) default: return nil, fmt.Errorf("toConfidentiality: unexpected type %T", value) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/built-in.go
pkg/risks/script/common/built-in.go
package common import ( "fmt" "github.com/shopspring/decimal" "github.com/threagile/threagile/pkg/types" ) const ( calculateSeverity = "calculate_severity" ) var ( callers = map[string]builtInFunc{ calculateSeverity: calculateSeverityFunc, } ) type builtInFunc func(parameters []Value) (Value, error) func IsBuiltIn(builtInName string) bool { _, ok := callers[builtInName] return ok } func CallBuiltIn(builtInName string, parameters ...Value) (Value, error) { caller, ok := callers[builtInName] if !ok { return nil, fmt.Errorf("unknown built-in %v", builtInName) } return caller(parameters) } func calculateSeverityFunc(parameters []Value) (Value, error) { if len(parameters) != 2 { return nil, fmt.Errorf("failed to calculate severity: expected 2 parameters, got %d", len(parameters)) } likelihoodValue, likelihoodError := toLikelihood(parameters[0]) if likelihoodError != nil { return nil, fmt.Errorf("failed to calculate severity: %w", likelihoodError) } likelihoodDecimal := likelihoodValue.Value().(decimal.Decimal).IntPart() impactValue, impactError := toImpact(parameters[1]) if impactError != nil { return nil, fmt.Errorf("failed to calculate severity: %w", impactError) } impactDecimal := impactValue.Value().(decimal.Decimal).IntPart() return SomeStringValue(types.CalculateSeverity(types.RiskExploitationLikelihood(likelihoodDecimal), types.RiskExploitationImpact(impactDecimal)).String(), nil), nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/explain-statement.go
pkg/risks/script/common/explain-statement.go
package common type ExplainStatement interface { Statement Eval(scope *Scope) string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/expression-list.go
pkg/risks/script/common/expression-list.go
package common type ExpressionList interface { ParseExpression(script map[string]any) (Expression, any, error) ParseArray(script any) (ExpressionList, any, error) ParseAny(script any) (Expression, any, error) EvalAny(scope *Scope) (Value, string, error) Expressions() []Expression Literal() string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/array-value.go
pkg/risks/script/common/array-value.go
package common import ( "fmt" ) type ArrayValue struct { value []Value name Path event *Event } func (what ArrayValue) Value() any { return what.value } func (what ArrayValue) Name() Path { return what.name } func (what ArrayValue) SetName(name ...string) { what.name.SetPath(name...) } func (what ArrayValue) Event() *Event { return what.event } func (what ArrayValue) ArrayValue() []Value { return what.value } func (what ArrayValue) PlainValue() any { values := make([]any, 0) for _, value := range what.value { values = append(values, value.PlainValue()) } return values } func (what ArrayValue) Text() []string { text := make([]string, 0) for _, item := range what.value { itemText := item.Text() switch len(itemText) { case 0: case 1: text = append(text, " - "+itemText[0]) default: text = append(text, " - ") for _, line := range itemText { text = append(text, " "+line) } } } return text } func EmptyArrayValue() *ArrayValue { return &ArrayValue{} } func SomeArrayValue(value []Value, event *Event) *ArrayValue { return &ArrayValue{ value: value, event: event, } } func ToArrayValue(value Value) (*ArrayValue, error) { var arrayValue []Value switch castValue := value.Value().(type) { case []Value: arrayValue = castValue case []any: arrayValue = make([]Value, 0) for _, item := range castValue { arrayValue = append(arrayValue, SomeValue(item, nil)) } default: return nil, fmt.Errorf("expected value-expression to eval to an array instead of %T", value.Value) } return &ArrayValue{ value: arrayValue, name: value.Name(), event: value.Event(), }, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/history.go
pkg/risks/script/common/history.go
package common import ( "strings" ) type History []*Event func NewHistory(item *Event) History { return new(History).New(item) } func (what History) New(item *Event) History { if item != nil { return append(History{item}, what...) } return what } func (what History) String() string { return strings.Join(what.Indented(0), "\n") } func (what History) Indented(level int) []string { lines := make([]string, 0) for _, item := range what { lines = append(lines, item.Indented(level)...) } return lines }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/expression.go
pkg/risks/script/common/expression.go
package common type Expression interface { ParseAny(script any) (Expression, any, error) EvalAny(scope *Scope) (Value, string, error) Literal() string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/value.go
pkg/risks/script/common/value.go
package common type Value interface { PlainValue() any Value() any Name() Path SetName(name ...string) Event() *Event Text() []string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/decimal-expression.go
pkg/risks/script/common/decimal-expression.go
package common type DecimalExpression interface { ParseDecimal(script any) (DecimalExpression, any, error) ParseAny(script any) (Expression, any, error) EvalDecimal(scope *Scope) (*DecimalValue, string, error) EvalAny(scope *Scope) (Value, string, error) Literal() string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/property.go
pkg/risks/script/common/property.go
package common import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/property" ) type Property struct { Property property.Item Path *Path } func NewBlankProperty() *Property { return &Property{ Property: property.NewBlank(), } } func NewEqualProperty(value Value) *Property { var path *Path if value.Event() != nil { path = value.Event().Path().Copy() } return &Property{ Property: property.NewEqual(), Path: path, } } func NewFalseProperty() *Property { return &Property{ Property: property.NewFalse(), } } func NewGreaterProperty(value Value) *Property { var path *Path if value.Event() != nil { path = value.Event().Path().Copy() } return &Property{ Property: property.NewGreater(), Path: path, } } func NewLessProperty(value Value) *Property { var path *Path if value.Event() != nil { path = value.Event().Path().Copy() } return &Property{ Property: property.NewLess(), Path: path, } } func NewNotEqualProperty(value Value) *Property { var path *Path if value.Event() != nil { path = value.Event().Path().Copy() } return &Property{ Property: property.NewNotEqual(), Path: path, } } func NewTrueProperty() *Property { return &Property{ Property: property.NewTrue(), } } func NewValueProperty(value any) *Property { return &Property{ Property: property.NewValue(value), } } func (what *Property) Text() []string { if what == nil { return []string{} } propertyText := what.Property.Text() switch len(propertyText) { case 0: // blank return []string{} case 1: if what.Path != nil { return []string{fmt.Sprintf("%v %v", propertyText[0], what.Path.String())} } return propertyText default: // value property return propertyText } } func (what *Property) SetPath(path *Path) *Property { if what == nil { return what } what.Path = path return what } func (what *Property) AddPathParent(path ...string) *Property { if what == nil { return what } what.Path.AddPathParent(path...) return what } func (what *Property) AddPathLeaf(path ...string) *Property { if what == nil { return what } what.Path.AddPathLeaf(path...) return what }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/decimal-value.go
pkg/risks/script/common/decimal-value.go
package common import ( "fmt" "github.com/shopspring/decimal" ) type DecimalValue struct { value decimal.Decimal name Path event *Event } func (what DecimalValue) Value() any { return what.value } func (what DecimalValue) Name() Path { return what.name } func (what DecimalValue) SetName(name ...string) { what.name.SetPath(name...) } func (what DecimalValue) Event() *Event { return what.event } func (what DecimalValue) PlainValue() any { return what.value } func (what DecimalValue) Text() []string { return []string{what.value.String()} } func (what DecimalValue) DecimalValue() decimal.Decimal { return what.value } func EmptyDecimalValue() *DecimalValue { return &DecimalValue{ value: decimal.Zero, } } func SomeDecimalValue(value decimal.Decimal, event *Event) *DecimalValue { return &DecimalValue{ value: value, event: event, } } func ToDecimalValue(value Value) (*DecimalValue, error) { castValue, ok := value.Value().(decimal.Decimal) var conversionError error if !ok { conversionError = fmt.Errorf("expected value-expression to eval to a decimal instead of %T", value.Value) } return &DecimalValue{ value: castValue, name: value.Name(), event: value.Event(), }, conversionError }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/bool-expression.go
pkg/risks/script/common/bool-expression.go
package common type BoolExpression interface { ParseBool(script any) (BoolExpression, any, error) ParseAny(script any) (Expression, any, error) EvalBool(scope *Scope) (*BoolValue, string, error) EvalAny(scope *Scope) (Value, string, error) Literal() string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/compare.go
pkg/risks/script/common/compare.go
package common import ( "fmt" "github.com/threagile/threagile/pkg/risks/script/property" ) func Compare(first Value, second Value, as string) (*Event, error) { firstValue := first secondValue := second if len(as) > 0 { var castError error firstValue, castError = CastValue(firstValue, as) if castError != nil { return nil, fmt.Errorf("failed to cast value to %q: %w", as, castError) } secondValue, castError = CastValue(secondValue, as) if castError != nil { return nil, fmt.Errorf("failed to cast value to %q: %w", as, castError) } } return compare(firstValue, secondValue) } func compare(firstValue Value, secondValue Value) (*Event, error) { switch first := firstValue.(type) { case *ArrayValue: second, conversionError := ToArrayValue(secondValue) if conversionError != nil { return nil, conversionError } return compareArrays(first, second) case *BoolValue: second, conversionError := ToBoolValue(secondValue) if conversionError != nil { return nil, conversionError } if first.BoolValue() == second.BoolValue() { return NewEventFrom(NewEqualProperty(second), first, second), nil } return NewEventFrom(NewNotEqualProperty(second), first, second), nil case *DecimalValue: second, conversionError := ToDecimalValue(secondValue) if conversionError != nil { return nil, conversionError } value := first.DecimalValue().Cmp(second.DecimalValue()) prop := NewEqualProperty(secondValue) if value < 0 { prop = NewLessProperty(secondValue) } else if value > 0 { prop = NewGreaterProperty(secondValue) } return NewEventFrom(prop, first, second), nil case *StringValue: second, conversionError := ToStringValue(secondValue) if conversionError != nil { return nil, conversionError } if first.StringValue() == second.StringValue() { return NewEventFrom(NewEqualProperty(second), first, second), nil } return NewEventFrom(NewNotEqualProperty(second), first, second), nil case *AnyValue: if firstValue.Value() == nil { return compare(nil, secondValue) } case nil: switch second := secondValue.(type) { case *ArrayValue: if len(second.ArrayValue()) == 0 { return NewEventFrom(NewEqualProperty(second), first, second), nil } return NewEventFrom(NewNotEqualProperty(second), first, second), nil case *BoolValue: if !second.BoolValue() { return NewEventFrom(NewEqualProperty(second), first, second), nil } return NewEventFrom(NewNotEqualProperty(second), first, second), nil case *DecimalValue: if second.DecimalValue().IsZero() { return NewEventFrom(NewEqualProperty(second), first, second), nil } return NewEventFrom(NewNotEqualProperty(second), first, second), nil case *StringValue: if len(second.StringValue()) == 0 { return NewEventFrom(NewEqualProperty(second), first, second), nil } return NewEventFrom(NewNotEqualProperty(second), first, second), nil case *AnyValue: if second.Value() == nil { return NewEvent(NewEqualProperty(nil), nil), nil } case nil: return NewEvent(NewEqualProperty(nil), nil), nil } } return nil, fmt.Errorf("can't compare %T to %T", firstValue, secondValue) } func compareArrays(firstValue *ArrayValue, secondValue *ArrayValue) (*Event, error) { if len(firstValue.ArrayValue()) != len(secondValue.ArrayValue()) { return NewEventFrom(NewNotEqualProperty(firstValue), firstValue, secondValue), nil } for index, first := range firstValue.ArrayValue() { second := secondValue.ArrayValue()[index] event, compareError := compare(first, second) if compareError != nil { return event, compareError } if !IsSame(event.Property) { return NewEventFrom(NewNotEqualProperty(firstValue), firstValue, secondValue), nil } } return NewEventFrom(NewEqualProperty(firstValue), firstValue, secondValue), nil } func IsSame(value *Property) bool { if value == nil { return false } switch value.Property.(type) { case *property.Equal: return true } return false } func IsGreater(value *Property) bool { if value == nil { return false } switch value.Property.(type) { case *property.Greater: return true } return false } func IsLess(value *Property) bool { if value == nil { return false } switch value.Property.(type) { case *property.Less: return true } return false } func ToString(value any) (*StringValue, error) { switch castValue := value.(type) { case string: return SomeStringValue(castValue, nil), nil case *StringValue: return castValue, nil case *AnyValue: aString, valueError := ToString(castValue.Value()) stringValue := SomeStringValue(aString.StringValue(), castValue.Event()) if valueError != nil { return stringValue, valueError } return stringValue, nil default: return EmptyStringValue(), fmt.Errorf("expected string, got %T", value) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/any-value.go
pkg/risks/script/common/any-value.go
package common import ( "fmt" "github.com/shopspring/decimal" ) type AnyValue struct { value any name Path event *Event } func (what AnyValue) Value() any { return what.value } func (what AnyValue) Name() Path { return what.name } func (what AnyValue) SetName(name ...string) { what.name.SetPath(name...) } func (what AnyValue) Event() *Event { return what.event } func (what AnyValue) PlainValue() any { switch castValue := what.value.(type) { case Value: return castValue.PlainValue() } return what.value } func (what AnyValue) Text() []string { switch castValue := what.value.(type) { case []any: text := make([]string, 0) for _, item := range castValue { text = append(text, fmt.Sprintf(" - %v", item)) } return text case map[string]any: text := make([]string, 0) for name, item := range castValue { text = append(text, fmt.Sprintf(" %v: %v", name, item)) } return text } return []string{fmt.Sprintf("%v", what.PlainValue())} } func NilValue() Value { return &AnyValue{} } func SomeValue(anyValue any, event *Event) Value { switch castValue := anyValue.(type) { case string: return SomeStringValue(castValue, event) case bool: return SomeBoolValue(castValue, event) case decimal.Decimal: return SomeDecimalValue(castValue, event) case int: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), event) case int8: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), event) case int16: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), event) case int32: return SomeDecimalValue(decimal.NewFromInt(int64(castValue)), event) case int64: return SomeDecimalValue(decimal.NewFromInt(castValue), event) case float32: return SomeDecimalValue(decimal.NewFromFloat32(castValue), event) case float64: return SomeDecimalValue(decimal.NewFromFloat(castValue), event) case []Value: return SomeArrayValue(castValue, event) case []any: array := make([]Value, 0) for _, item := range castValue { switch castItem := item.(type) { case Value: array = append(array, castItem) default: array = append(array, SomeValue(castItem, nil)) } } return SomeArrayValue(array, event) case Value: return castValue } return &AnyValue{ value: anyValue, event: event, } } func AddValueHistory(anyValue Value, history []*Event) Value { if anyValue == nil { if len(history) == 0 { return nil } return SomeValue(nil, NewEvent(NewValueProperty(nil), EmptyPath()).AddHistory(history)) } event := anyValue.Event() if event == nil { path := anyValue.Name() event = NewEvent(NewValueProperty(anyValue), &path).AddHistory(history) } return SomeValue(anyValue.PlainValue(), event) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/statement.go
pkg/risks/script/common/statement.go
package common type Statement interface { Run(scope *Scope) (string, error) Literal() string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/values.go
pkg/risks/script/common/values.go
package common import "fmt" type Values map[string]Value func (what Values) Copy() (Values, error) { values := make(Values, 0) for name, value := range what { switch castValue := value.(type) { case *AnyValue: values[name] = SomeValue(castValue.Value(), castValue.Event()) case *ArrayValue: values[name] = SomeArrayValue(castValue.ArrayValue(), castValue.Event()) case *BoolValue: values[name] = SomeBoolValue(castValue.BoolValue(), castValue.Event()) case *DecimalValue: values[name] = SomeDecimalValue(castValue.DecimalValue(), castValue.Event()) case *StringValue: values[name] = SomeStringValue(castValue.StringValue(), castValue.Event()) default: return nil, fmt.Errorf("can't copy value of type %T", value) } } return values, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/scope.go
pkg/risks/script/common/scope.go
package common import ( "gopkg.in/yaml.v3" "strings" "github.com/threagile/threagile/pkg/types" ) type Scope struct { Parent *Scope Category *types.RiskCategory Args []Value Vars map[string]Value Model map[string]any Risk map[string]any Methods map[string]Statement Deferred []Statement Explain ExplainStatement CallStack History HasReturned bool item Value returnValue Value } func (what *Scope) Init(risk *types.RiskCategory, methods map[string]Statement) error { if risk != nil { data, marshalError := yaml.Marshal(risk) if marshalError != nil { return marshalError } unmarshalError := yaml.Unmarshal(data, &what.Risk) if unmarshalError != nil { return unmarshalError } } what.Category = risk what.Methods = methods return nil } func (what *Scope) SetModel(model *types.Model) error { if model != nil { data, marshalError := yaml.Marshal(model) if marshalError != nil { return marshalError } unmarshalError := yaml.Unmarshal(data, &what.Model) if unmarshalError != nil { return unmarshalError } } return nil } func (what *Scope) Clone() (*Scope, error) { varsCopy, copyError := Values(what.Vars).Copy() if copyError != nil { return what, copyError } scope := Scope{ Parent: what, Category: what.Category, Args: what.Args, Vars: varsCopy, Model: what.Model, Risk: what.Risk, Methods: what.Methods, CallStack: what.CallStack, } return &scope, nil } func (what *Scope) Defer(statement Statement) { what.Deferred = append(what.Deferred, statement) } func (what *Scope) PushCall(event *Event) History { what.CallStack = what.CallStack.New(event) return what.CallStack } func (what *Scope) PopCall() { if len(what.CallStack) > 0 { what.CallStack = what.CallStack[:len(what.CallStack)-1] } } func (what *Scope) Set(name string, value Value) { if what.Vars == nil { what.Vars = make(map[string]Value) } what.Vars[name] = value } func (what *Scope) Get(name string) (Value, bool) { path := strings.Split(name, ".") if strings.HasPrefix(path[0], "$") { switch strings.ToLower(path[0]) { // value name starts with `$model`: refers to `what.Model` case "$model": value, ok := what.get(path[1:], what.Model, NewPath("threat model", strings.Join(path[1:], "."))) if ok { return value, true } // value name starts with `$risk`: refers to `what.Risk` case "$risk": value, ok := what.get(path[1:], what.Risk, NewPath("risk category", strings.Join(path[1:], "."))) if ok { return value, true } } } // value name starts with a dot: refers to `what.item` if len(path[0]) == 0 { if len(path[1:]) > 0 { if what.item == nil { return nil, false } switch castValue := what.item.Value().(type) { case map[string]any: value, ok := what.get(path[1:], castValue, what.item.Event().Path().Copy().AddPathLeaf(strings.Join(path[1:], "."))) if ok { return value, true } } return nil, false } return what.item, true } // value name starts with something else: refers to `what.Vars` if what.Vars == nil { return nil, false } variable, fieldOk := what.Vars[strings.ToLower(path[0])] if !fieldOk { return nil, false } if len(path) == 1 { return variable, true } value, isMap := variable.Value().(map[string]any) if isMap { return what.get(path[1:], value, variable.Event().Path().Copy().AddPathLeaf(strings.Join(path[1:], "."))) } // value name does not resolve return nil, false } func (what *Scope) GetHistory() []*Event { history := make([]*Event, 0) for _, event := range what.CallStack { newHistory := what.getHistory(event) if newHistory != nil { history = append(history, newHistory...) } } return history } func (what *Scope) getHistory(event *Event) []*Event { history := make([]*Event, 0) if event == nil { return history } if event.Origin != nil && len(event.Origin.Path) > 0 { return append(history, event) } for _, subEvent := range event.Events { newHistory := what.getHistory(subEvent) if newHistory != nil { history = append(history, newHistory...) } } return history } func (what *Scope) GetItem() Value { return what.item } func (what *Scope) SetItem(value Value) Value { what.item = value return value } func (what *Scope) PopItem() Value { var currentItem Value currentItem, what.item = what.item, nil return currentItem } func (what *Scope) SetReturnValue(value Value) { what.returnValue = value } func (what *Scope) GetReturnValue() Value { return what.returnValue } func (what *Scope) get(path []string, item map[string]any, valuePath *Path) (Value, bool) { if len(path) == 0 { return nil, false } if item == nil { return nil, false } field, ok := item[strings.ToLower(path[0])] if !ok { return SomeValue(nil, NewEvent(NewValueProperty(nil), valuePath)), false } if len(path) == 1 { switch castField := field.(type) { case Value: return castField, true default: return SomeValue(castField, NewEvent(NewValueProperty(castField), valuePath)), true } } value, isMap := field.(map[string]any) if isMap { return what.get(path[1:], value, valuePath) } return nil, false }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/script/common/value-list.go
pkg/risks/script/common/value-list.go
package common type ValueList []Value
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/code_backdooring_rule.go
pkg/risks/builtin/code_backdooring_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type CodeBackdooringRule struct{} func NewCodeBackdooringRule() *CodeBackdooringRule { return &CodeBackdooringRule{} } func (*CodeBackdooringRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "code-backdooring", Title: "Code Backdooring", Description: "For each build pipeline component Code Backdooring risks might arise where attackers compromise the build pipeline " + "in order to let backdoored artifacts be shipped into production. Aside from direct code backdooring this includes " + "backdooring of dependencies and even of more lower-level build infrastructure, like backdooring compilers (similar to what the XcodeGhost malware did) or dependencies.", Impact: "If this risk remains unmitigated, attackers might be able to execute code on and completely takeover " + "production environments.", ASVS: "V10 - Malicious Code Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Vulnerable_Dependency_Management_Cheat_Sheet.html", Action: "Build Pipeline Hardening", Mitigation: "Reduce the attack surface of backdooring the build pipeline by not directly exposing the build pipeline " + "components on the public internet and also not exposing it in front of unmanaged (out-of-scope) developer clients." + "Also consider the use of code signing to prevent code modifications.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Operations, STRIDE: types.Tampering, DetectionLogic: "In-scope development relevant technical assets which are either accessed by out-of-scope unmanaged " + "developer clients and/or are directly accessed by any kind of internet-located (non-VPN) component or are themselves directly located " + "on the internet.", RiskAssessment: "The risk rating depends on the confidentiality and integrity rating of the code being handled and deployed " + "as well as the placement/calling of this technical asset on/from the internet.", // TODO also take the CIA rating of the deployment targets (and their data) into account? FalsePositives: "When the build-pipeline and sourcecode-repo is not exposed to the internet and considered fully " + "trusted (which implies that all accessing clients are also considered fully trusted in terms of their patch management " + "and applied hardening, which must be equivalent to a managed developer client environment) this can be considered a false positive " + "after individual review.", ModelFailurePossibleReason: false, CWE: 912, } } func (*CodeBackdooringRule) SupportedTags() []string { return []string{} } func (r *CodeBackdooringRule) GenerateRisks(parsedModel *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range parsedModel.SortedTechnicalAssetIDs() { technicalAsset := parsedModel.TechnicalAssets[id] if !technicalAsset.OutOfScope && technicalAsset.Technologies.GetAttribute(types.IsDevelopmentRelevant) { if technicalAsset.Internet { risks = append(risks, r.createRisk(parsedModel, technicalAsset)) continue } // TODO: ensure that even internet or unmanaged clients coming over a reverse-proxy or load-balancer like component are treated as if it was directly accessed/exposed on the internet or towards unmanaged dev clients for _, callerLink := range parsedModel.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] { caller := parsedModel.TechnicalAssets[callerLink.SourceId] if !callerLink.VPN && caller.Internet { risks = append(risks, r.createRisk(parsedModel, technicalAsset)) break } } } } return risks, nil } func (r *CodeBackdooringRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>Code Backdooring</b> risk at <b>" + technicalAsset.Title + "</b>" impact := types.LowImpact if !technicalAsset.Technologies.GetAttribute(types.CodeInspectionPlatform) { impact = types.MediumImpact if input.HighestProcessedConfidentiality(technicalAsset) >= types.Confidential || input.HighestProcessedIntegrity(technicalAsset) >= types.Critical { impact = types.HighImpact } } // data breach at all deployment targets uniqueDataBreachTechnicalAssetIDs := make(map[string]interface{}) uniqueDataBreachTechnicalAssetIDs[technicalAsset.Id] = true for _, codeDeploymentTargetCommLink := range technicalAsset.CommunicationLinks { if codeDeploymentTargetCommLink.Usage != types.DevOps { continue } for _, dataAssetID := range codeDeploymentTargetCommLink.DataAssetsSent { // it appears to be code when elevated integrity rating of sent data asset if input.DataAssets[dataAssetID].Integrity >= types.Important { // here we've got a deployment target which has its data assets at risk via deployment of backdoored code uniqueDataBreachTechnicalAssetIDs[codeDeploymentTargetCommLink.TargetId] = true break } } } dataBreachTechnicalAssetIDs := make([]string, 0) for key := range uniqueDataBreachTechnicalAssetIDs { dataBreachTechnicalAssetIDs = append(dataBreachTechnicalAssetIDs, key) } // create risk risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: dataBreachTechnicalAssetIDs, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/untrusted_deserialization_rule.go
pkg/risks/builtin/untrusted_deserialization_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type UntrustedDeserializationRule struct{} func NewUntrustedDeserializationRule() *UntrustedDeserializationRule { return &UntrustedDeserializationRule{} } func (*UntrustedDeserializationRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "untrusted-deserialization", Title: "Untrusted Deserialization", Description: "When a technical asset accepts data in a specific serialized form (like Java or .NET serialization), " + "Untrusted Deserialization risks might arise." + "<br><br>See <a href=\"https://christian-schneider.net/JavaDeserializationSecurityFAQ.html\">https://christian-schneider.net/JavaDeserializationSecurityFAQ.html</a> " + "for more details.", Impact: "If this risk is unmitigated, attackers might be able to execute code on target systems by exploiting untrusted deserialization endpoints.", ASVS: "V5 - Validation, Sanitization and Encoding Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html", Action: "Prevention of Deserialization of Untrusted Data", Mitigation: "Try to avoid the deserialization of untrusted data (even of data within the same trust-boundary as long as " + "it is sent across a remote connection) in order to stay safe from Untrusted Deserialization vulnerabilities. " + "Alternatively a strict whitelisting approach of the classes/types/values to deserialize might help as well. " + "When a third-party product is used instead of custom developed software, check if the product applies the proper mitigation and ensure a reasonable patch-level.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.Tampering, DetectionLogic: "In-scope technical assets accepting serialization data formats (including EJB and RMI protocols).", RiskAssessment: "The risk rating depends on the sensitivity of the technical asset itself and of the data assets processed.", FalsePositives: "Fully trusted (i.e. cryptographically signed or similar) data deserialized can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 502, } } func (*UntrustedDeserializationRule) SupportedTags() []string { return []string{} } func (r *UntrustedDeserializationRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if technicalAsset.OutOfScope { continue } hasOne, acrossTrustBoundary := false, false commLinkTitle := "" for _, format := range technicalAsset.DataFormatsAccepted { if format == types.Serialization { hasOne = true } } if technicalAsset.Technologies.GetAttribute(types.EJB) { hasOne = true } // check for any incoming IIOP and JRMP protocols for _, commLink := range input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] { if commLink.Protocol == types.IIOP || commLink.Protocol == types.IiopEncrypted || commLink.Protocol == types.JRMP || commLink.Protocol == types.JrmpEncrypted { hasOne = true if isAcrossTrustBoundaryNetworkOnly(input, commLink) { acrossTrustBoundary = true commLinkTitle = commLink.Title } } } if hasOne { risks = append(risks, r.createRisk(input, technicalAsset, acrossTrustBoundary, commLinkTitle)) } } return risks, nil } func (r *UntrustedDeserializationRule) createRisk(parsedModel *types.Model, technicalAsset *types.TechnicalAsset, acrossTrustBoundary bool, commLinkTitle string) *types.Risk { title := "<b>Untrusted Deserialization</b> risk at <b>" + technicalAsset.Title + "</b>" impact := types.HighImpact likelihood := types.Likely if acrossTrustBoundary { likelihood = types.VeryLikely title += " across a trust boundary (at least via communication link <b>" + commLinkTitle + "</b>)" } if parsedModel.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || parsedModel.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical || parsedModel.HighestProcessedAvailability(technicalAsset) == types.MissionCritical { impact = types.VeryHighImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/push_instead_of_pull_deployment_rule_test.go
pkg/risks/builtin/push_instead_of_pull_deployment_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestPushInsteadPullDeploymentRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewPushInsteadPullDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestPushInsteadPullDeploymentRuleGenerateRisksNoBuildPipelineNoRisksCreated(t *testing.T) { rule := NewPushInsteadPullDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Build Pipeline Technical Asset", OutOfScope: true, Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.BuildPipeline: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestPushInsteadPullDeploymentRuleGenerateRisksNoCommunicationWithBuildPipelineNoRisksCreated(t *testing.T) { rule := NewPushInsteadPullDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Build Pipeline Technical Asset", OutOfScope: true, Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.BuildPipeline: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestPushInsteadPullDeploymentRuleGenerateRisksReadOnlyCommunicationWithBuildPipelineNoRisksCreated(t *testing.T) { rule := NewPushInsteadPullDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Build Pipeline Technical Asset", Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.BuildPipeline: true, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta2", Readonly: true, Usage: types.Business, }, }, }, "ta2": { Id: "ta2", Title: "Target Pipeline Technical Asset", OutOfScope: false, Usage: types.Business, Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestPushInsteadPullDeploymentRuleGenerateRisksTargetOutOfScopeWithBuildPipelineNoRisksCreated(t *testing.T) { rule := NewPushInsteadPullDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Build Pipeline Technical Asset", Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.BuildPipeline: true, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta2", Readonly: false, Usage: types.DevOps, }, }, }, "ta2": { Id: "ta2", Title: "Target Pipeline Technical Asset", OutOfScope: true, Usage: types.Business, Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestPushInsteadPullDeploymentRuleGenerateRisksDevOpsUsageNoRisksCreated(t *testing.T) { rule := NewPushInsteadPullDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Build Pipeline Technical Asset", Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.BuildPipeline: true, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta2", Readonly: false, Usage: types.DevOps, }, }, }, "ta2": { Id: "ta2", Title: "Target Pipeline Technical Asset", Usage: types.DevOps, Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestPushInsteadPullDeploymentRuleGenerateRisksTargetIsDevOpsUsageNoRisksCreated(t *testing.T) { rule := NewPushInsteadPullDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Build Pipeline Technical Asset", Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.BuildPipeline: true, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta2", Readonly: false, Usage: types.DevOps, }, }, }, "ta2": { Id: "ta2", Title: "Target Pipeline Technical Asset", Usage: types.DevOps, Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestPushInsteadPullDeploymentRuleGenerateRisksTargetIsDevelopmentRelatedNoRisksCreated(t *testing.T) { rule := NewPushInsteadPullDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Build Pipeline Technical Asset", Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.BuildPipeline: true, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta2", Readonly: false, Usage: types.DevOps, }, }, }, "ta2": { Id: "ta2", Title: "Target Pipeline Technical Asset", Usage: types.Business, Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type PushInsteadOfPullRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality availability types.Criticality expectedImpact types.RiskExploitationImpact } func TestPushInsteadOfPullRuleGenerateRisksRiskCreated(t *testing.T) { testCases := map[string]PushInsteadOfPullRuleTest{ "low impact": { confidentiality: types.Restricted, integrity: types.Important, availability: types.Important, expectedImpact: types.LowImpact, }, "confidential medium impact": { confidentiality: types.Confidential, integrity: types.Important, availability: types.Important, expectedImpact: types.MediumImpact, }, "critical integrity medium impact": { confidentiality: types.Restricted, integrity: types.Critical, availability: types.Important, expectedImpact: types.MediumImpact, }, "critical availability medium impact": { confidentiality: types.Restricted, integrity: types.Important, availability: types.Critical, expectedImpact: types.MediumImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewPushInsteadPullDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Build Pipeline Technical Asset", Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.BuildPipeline: true, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { Title: "Test Communication Link", TargetId: "ta2", Readonly: false, Usage: types.DevOps, }, }, }, "ta2": { Id: "ta2", Title: "Target Pipeline Technical Asset", Usage: types.Business, Technologies: types.TechnologyList{ { Name: "build pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: false, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) expTitle := "<b>Push instead of Pull Deployment</b> at <b>Target Pipeline Technical Asset</b> via build pipeline asset <b>Build Pipeline Technical Asset</b>" assert.Equal(t, expTitle, risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/container_platform_escape_rule.go
pkg/risks/builtin/container_platform_escape_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type ContainerPlatformEscapeRule struct{} func NewContainerPlatformEscapeRule() *ContainerPlatformEscapeRule { return &ContainerPlatformEscapeRule{} } func (*ContainerPlatformEscapeRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "container-platform-escape", Title: "Container Platform Escape", Description: "Container platforms are especially interesting targets for attackers as they host big parts of a containerized runtime infrastructure. " + "When not configured and operated with security best practices in mind, attackers might exploit a vulnerability inside an container and escape towards " + "the platform as highly privileged users. These scenarios might give attackers capabilities to attack every other container as owning the container platform " + "(via container escape attacks) equals to owning every container.", Impact: "If this risk is unmitigated, attackers which have successfully compromised a container (via other vulnerabilities) " + "might be able to deeply persist in the target system by executing code in many deployed containers " + "and the container platform itself.", ASVS: "V14 - Configuration Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Docker_Security_Cheat_Sheet.html", Action: "Container Infrastructure Hardening", Mitigation: "Apply hardening of all container infrastructures. " + "<p>See for example the <i>CIS-Benchmarks for Docker and Kubernetes</i> " + "as well as the <i>Docker Bench for Security</i> ( <a href=\"https://github.com/docker/docker-bench-security\">https://github.com/docker/docker-bench-security</a> ) " + "or <i>InSpec Checks for Docker and Kubernetes</i> ( <a href=\"https://github.com/dev-sec/cis-kubernetes-benchmark\">https://github.com/dev-sec/cis-docker-benchmark</a> and <a href=\"https://github.com/dev-sec/cis-kubernetes-benchmark\">https://github.com/dev-sec/cis-kubernetes-benchmark</a> ). " + "Use only trusted base images, verify digital signatures and apply image creation best practices. Also consider using Google's <b>Distroless</i> base images or otherwise very small base images. " + "Apply namespace isolation and nod affinity to separate pods from each other in terms of access and nodes the same style as you separate data.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS or CSVS chapter applied?", Function: types.Operations, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "In-scope container platforms.", RiskAssessment: "The risk rating depends on the sensitivity of the technical asset itself and of the data assets processed.", FalsePositives: "Container platforms not running parts of the target architecture can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 1008, } } func (*ContainerPlatformEscapeRule) SupportedTags() []string { return []string{"docker", "kubernetes", "openshift"} } func (r *ContainerPlatformEscapeRule) GenerateRisks(parsedModel *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range parsedModel.SortedTechnicalAssetIDs() { technicalAsset := parsedModel.TechnicalAssets[id] if r.skipAsset(technicalAsset) { continue } if technicalAsset.Technologies.GetAttribute(types.ContainerPlatform) { risks = append(risks, r.createRisk(parsedModel, technicalAsset)) } } return risks, nil } func (asl ContainerPlatformEscapeRule) skipAsset(techAsset *types.TechnicalAsset) bool { return techAsset.OutOfScope } func (r *ContainerPlatformEscapeRule) createRisk(parsedModel *types.Model, technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>Container Platform Escape</b> risk at <b>" + technicalAsset.Title + "</b>" impact := types.MediumImpact if parsedModel.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || parsedModel.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical || parsedModel.HighestProcessedAvailability(technicalAsset) == types.MissionCritical { impact = types.HighImpact } // data breach at all container assets dataBreachTechnicalAssetIDs := make([]string, 0) for id, techAsset := range parsedModel.TechnicalAssets { if techAsset.Machine == types.Container { dataBreachTechnicalAssetIDs = append(dataBreachTechnicalAssetIDs, id) } } // create risk risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: dataBreachTechnicalAssetIDs, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/ldap_injection_rule.go
pkg/risks/builtin/ldap_injection_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type LdapInjectionRule struct{} func NewLdapInjectionRule() *LdapInjectionRule { return &LdapInjectionRule{} } func (*LdapInjectionRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "ldap-injection", Title: "LDAP-Injection", Description: "When an LDAP server is accessed LDAP-Injection risks might arise. " + "The risk rating depends on the sensitivity of the LDAP server itself and of the data assets processed.", Impact: "If this risk remains unmitigated, attackers might be able to modify LDAP queries and access more data from the LDAP server than allowed.", ASVS: "V5 - Validation, Sanitization and Encoding Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html", Action: "LDAP-Injection Prevention", Mitigation: "Try to use libraries that properly encode LDAP meta characters in searches and queries to access " + "the LDAP server in order to stay safe from LDAP-Injection vulnerabilities. " + "When a third-party product is used instead of custom developed software, check if the product applies the proper mitigation and ensure a reasonable patch-level.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Development, STRIDE: types.Tampering, DetectionLogic: "In-scope clients accessing LDAP servers via typical LDAP access protocols.", RiskAssessment: "The risk rating depends on the sensitivity of the LDAP server itself and of the data assets processed.", FalsePositives: "LDAP server queries by search values not consisting of parts controllable by the caller can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 90, } } func (*LdapInjectionRule) SupportedTags() []string { return []string{} } func (r *LdapInjectionRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, technicalAsset := range input.TechnicalAssets { if technicalAsset.OutOfScope { continue } incomingFlows := input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] for _, incomingFlow := range incomingFlows { if r.skipAsset(input, incomingFlow) { continue } if incomingFlow.Protocol == types.LDAP || incomingFlow.Protocol == types.LDAPS { likelihood := types.Likely if incomingFlow.Usage == types.DevOps { likelihood = types.Unlikely } risks = append(risks, r.createRisk(input, technicalAsset, incomingFlow, likelihood)) } } } return risks, nil } func (li *LdapInjectionRule) skipAsset(input *types.Model, incomingFlow *types.CommunicationLink) bool { return input.TechnicalAssets[incomingFlow.SourceId].OutOfScope } func (r *LdapInjectionRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset, incomingFlow *types.CommunicationLink, likelihood types.RiskExploitationLikelihood) *types.Risk { caller := input.TechnicalAssets[incomingFlow.SourceId] title := "<b>LDAP-Injection</b> risk at <b>" + caller.Title + "</b> against LDAP server <b>" + technicalAsset.Title + "</b>" + " via <b>" + incomingFlow.Title + "</b>" impact := types.MediumImpact if input.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || input.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical { impact = types.HighImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: caller.Id, MostRelevantCommunicationLinkId: incomingFlow.Id, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + caller.Id + "@" + technicalAsset.Id + "@" + incomingFlow.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/cross_site_scripting_rule_test.go
pkg/risks/builtin/cross_site_scripting_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestCrossSiteScriptingRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewCrossSiteScriptingRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestCrossSiteScriptingRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewCrossSiteScriptingRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestCrossSiteScriptingRuleGenerateRisksTechAssetNotWebApplicationNotRisksCreated(t *testing.T) { rule := NewCrossSiteScriptingRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.WebApplication: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestCrossSiteScriptingRuleGenerateRisksTechAssetWebApplicationRisksCreated(t *testing.T) { rule := NewCrossSiteScriptingRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Web Application", Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Cross-Site Scripting (XSS)</b> risk at <b>Web Application</b>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) } func TestCrossSiteScriptingRuleGenerateRisksTechAssetProcessStrictlyConfidentialDataAssetHighImpactRiskCreated(t *testing.T) { rule := NewCrossSiteScriptingRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Web Application", Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, DataAssetsProcessed: []string{"strictly-confidential-data-asset"}, }, }, DataAssets: map[string]*types.DataAsset{ "strictly-confidential-data-asset": { Confidentiality: types.StrictlyConfidential, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Cross-Site Scripting (XSS)</b> risk at <b>Web Application</b>", risks[0].Title) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_authentication_second_factor_rule_test.go
pkg/risks/builtin/missing_authentication_second_factor_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingAuthenticationSecondFactorRuleGenerateRisksEmptyModelNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleGenerateRisksTrafficForwardingTechnologyNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "load-balancer", Attributes: map[string]bool{ types.IsTrafficForwarding: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleGenerateRisksUnprotectedCommunicationToleratedNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "monitoring", Attributes: map[string]bool{ types.IsUnprotectedCommunicationsTolerated: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleGenerateRisksCallerFromDatastoreNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "Test Datastore", Type: types.Datastore, MultiTenant: true, // require less code instead of adding processed data }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleGenerateRisksCallerUnprotectedCommunicationToleratedNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "Test Monitoring", Technologies: types.TechnologyList{ { Name: "monitoring", Attributes: map[string]bool{ types.IsUnprotectedCommunicationsTolerated: true, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleUsedAsClientByHumanLessRiskyDataSentTwoFactorAuthenticationEnabledNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "Browser", UsedAsClientByHuman: true, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", Authentication: types.TwoFactor, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleUsedAsClientByHumanCriticalIntegrityDataAccessRiskyDataSentTwoFactorAuthenticationEnabledNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "Browser", UsedAsClientByHuman: true, MultiTenant: true, // require less code instead of adding processed data }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", Authentication: types.TwoFactor, DataAssetsSent: []string{"da1"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Test Data Asset", Integrity: types.Critical, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleUsedAsClientByHumanConfidentialDataSentTwoFactorAuthenticationDisabledRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "Browser", UsedAsClientByHuman: true, MultiTenant: true, // require less code instead of adding processed data }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", Title: "Access confidential data with client certificate", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Test Data Asset", Confidentiality: types.Confidential, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Missing Two-Factor Authentication</b> covering communication link <b>Access confidential data with client certificate</b> from <b>Browser</b> to <b>Test Technical Asset</b>", risks[0].Title) } func TestMissingAuthenticationSecondFactorRuleNotUsedAsClientByHumanAndNotTrafficForwardingCriticalIntegrityDataAccessRiskyDataSentTwoFactorAuthenticationEnabledNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "elb", Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.IsTrafficForwarding: false, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Test Data Asset", Integrity: types.Critical, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleNotTrafficForwardingCriticalIntegrityDataAccessTwoFactorAuthenticationDisabledNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "elb", Technologies: types.TechnologyList{ { Name: "load-balancer", Attributes: map[string]bool{ types.IsTrafficForwarding: true, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Test Data Asset", Integrity: types.Critical, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleCallersCallerDataStoreNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "elb": { Id: "elb", Title: "Load Balancer", Technologies: types.TechnologyList{ { Name: "load-balancer", Attributes: map[string]bool{ types.IsTrafficForwarding: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Datastore", Type: types.Datastore, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "elb", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, }, }, "elb": { { SourceId: "ta2", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Test Data Asset", Integrity: types.Critical, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleCallersCallerUnprotectedCommunicationsToleratedNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "elb": { Id: "elb", Title: "Load Balancer", Technologies: types.TechnologyList{ { Name: "load-balancer", Attributes: map[string]bool{ types.IsTrafficForwarding: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Monitoring", Technologies: types.TechnologyList{ { Name: "monitoring", Attributes: map[string]bool{ types.IsUnprotectedCommunicationsTolerated: true, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "elb", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, }, }, "elb": { { SourceId: "ta2", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Test Data Asset", Integrity: types.Critical, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleCallersCallerNotUsedAsClientByHumanNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "elb": { Id: "elb", Title: "Load Balancer", Technologies: types.TechnologyList{ { Name: "load-balancer", Attributes: map[string]bool{ types.IsTrafficForwarding: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Tool", Technologies: types.TechnologyList{ { Name: "tool", }, }, UsedAsClientByHuman: false, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "elb", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, }, }, "elb": { { SourceId: "ta2", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Test Data Asset", Integrity: types.Critical, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleCallersCallerProcessLessRiskyDataNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "elb": { Id: "elb", Title: "Load Balancer", Technologies: types.TechnologyList{ { Name: "load-balancer", Attributes: map[string]bool{ types.IsTrafficForwarding: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Browser", UsedAsClientByHuman: true, Technologies: types.TechnologyList{ { Name: "browser", }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "elb", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, }, }, "elb": { { SourceId: "ta2", Authentication: types.TwoFactor, DataAssetsSent: []string{"da1"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Test Data Asset", Integrity: types.Important, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleCallersCallerProcessCriticalDataTwoFactorEnabledNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "elb": { Id: "elb", Title: "Load Balancer", Technologies: types.TechnologyList{ { Name: "load-balancer", Attributes: map[string]bool{ types.IsTrafficForwarding: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Browser", UsedAsClientByHuman: true, Technologies: types.TechnologyList{ { Name: "browser", }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "elb", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, }, }, "elb": { { SourceId: "ta2", Authentication: types.TwoFactor, DataAssetsSent: []string{"da1"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Test Data Asset", Integrity: types.Critical, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationSecondFactorRuleCallersCallerProcessConfidentialDataTwoFactorDisabledRisksCreated(t *testing.T) { rule := NewMissingAuthenticationSecondFactorRule(NewMissingAuthenticationRule()) risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "elb": { Id: "elb", Title: "Load Balancer", Technologies: types.TechnologyList{ { Name: "load-balancer", Attributes: map[string]bool{ types.IsTrafficForwarding: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Browser", UsedAsClientByHuman: true, Technologies: types.TechnologyList{ { Name: "browser", }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "elb", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, Title: "Access confidential data with client certificate from load balancer", }, }, "elb": { { SourceId: "ta2", Authentication: types.ClientCertificate, DataAssetsSent: []string{"da1"}, Title: "Access confidential data with client certificate via load balancer by human", }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Test Data Asset", Confidentiality: types.Confidential, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Missing Two-Factor Authentication</b> covering communication link <b>Access confidential data with client certificate from load balancer</b> from <b>Browser</b> forwarded via <b>Load Balancer</b> to <b>Test Technical Asset</b>", risks[0].Title) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_file_validation_rule_test.go
pkg/risks/builtin/missing_file_validation_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingFileValidationRuleGenerateRisksEmptyModelNoRisksCreated(t *testing.T) { rule := NewMissingFileValidationRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingFileValidationRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewMissingFileValidationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingFileValidationRuleGenerateRisksNotCustomlyDevelopedTechnicalAssetNoRisksCreated(t *testing.T) { rule := NewMissingFileValidationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: false, OutOfScope: false, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingFileValidationRuleGenerateRisksNoFileAcceptedAssetNoRisksCreated(t *testing.T) { rule := NewMissingFileValidationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, OutOfScope: false, DataFormatsAccepted: []types.DataFormat{types.CSV, types.Serialization, types.XML}, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingFileValidationRuleGenerateRisksFileDataFormatsAcceptedRisksCreated(t *testing.T) { rule := NewMissingFileValidationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, OutOfScope: false, DataFormatsAccepted: []types.DataFormat{types.File}, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing File Validation</b> risk at <b>Test Technical Asset</b>", risks[0].Title) } func TestMissingFileValidationRuleGenerateRisksProcessStrictlyConfidentialDataRisksCreatedWithMediumImpact(t *testing.T) { rule := NewMissingFileValidationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, OutOfScope: false, DataFormatsAccepted: []types.DataFormat{types.File}, DataAssetsProcessed: []string{"da1"}, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Title: "Test Data Asset", Confidentiality: types.StrictlyConfidential, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing File Validation</b> risk at <b>Test Technical Asset</b>", risks[0].Title) } func TestMissingFileValidationRuleGenerateRisksProcessMissionCriticalIntegrityDataRisksCreatedWithMediumImpact(t *testing.T) { rule := NewMissingFileValidationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, OutOfScope: false, DataFormatsAccepted: []types.DataFormat{types.File}, DataAssetsProcessed: []string{"da1"}, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Title: "Test Data Asset", Integrity: types.MissionCritical, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing File Validation</b> risk at <b>Test Technical Asset</b>", risks[0].Title) } func TestMissingFileValidationRuleGenerateRisksProcessMissionCriticalAvailabilityDataRisksCreatedWithMediumImpact(t *testing.T) { rule := NewMissingFileValidationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, OutOfScope: false, DataFormatsAccepted: []types.DataFormat{types.File}, DataAssetsProcessed: []string{"da1"}, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Title: "Test Data Asset", Availability: types.MissionCritical, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing File Validation</b> risk at <b>Test Technical Asset</b>", risks[0].Title) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/helpers.go
pkg/risks/builtin/helpers.go
package builtin import ( "strings" "github.com/threagile/threagile/pkg/types" ) func isAcrossTrustBoundaryNetworkOnly(parsedModel *types.Model, communicationLink *types.CommunicationLink) bool { isAcrossNetworkTrustBoundary := func( trustBoundaryOfSourceAsset *types.TrustBoundary, trustBoundaryOfTargetAsset *types.TrustBoundary) bool { return trustBoundaryOfSourceAsset.Id != trustBoundaryOfTargetAsset.Id && trustBoundaryOfTargetAsset.Type.IsNetworkBoundary() } trustBoundaryOfSourceAsset, trustBoundaryOfSourceAssetOk := parsedModel.DirectContainingTrustBoundaryMappedByTechnicalAssetId[communicationLink.SourceId] if !isNetworkOnly(parsedModel, trustBoundaryOfSourceAssetOk, trustBoundaryOfSourceAsset) { return false } trustBoundaryOfTargetAsset, trustBoundaryOfTargetAssetOk := parsedModel.DirectContainingTrustBoundaryMappedByTechnicalAssetId[communicationLink.TargetId] if !isNetworkOnly(parsedModel, trustBoundaryOfTargetAssetOk, trustBoundaryOfTargetAsset) { return false } return isAcrossNetworkTrustBoundary(trustBoundaryOfSourceAsset, trustBoundaryOfTargetAsset) } func isNetworkOnly(parsedModel *types.Model, trustBoundaryOk bool, trustBoundary *types.TrustBoundary) bool { if !trustBoundaryOk { return false } if !trustBoundary.Type.IsNetworkBoundary() { // find and use the parent boundary then parentTrustBoundary := parsedModel.FindParentTrustBoundary(trustBoundary) if parentTrustBoundary != nil { return false } } return true } func contains(as []string, b string) bool { for _, a := range as { if b == a { return true } } return false } func containsCaseInsensitiveAny(as []string, bs ...string) bool { for _, a := range as { for _, b := range bs { if strings.TrimSpace(strings.ToLower(b)) == strings.TrimSpace(strings.ToLower(a)) { return true } } } return false } func isSameExecutionEnvironment(parsedModel *types.Model, ta *types.TechnicalAsset, otherAssetId string) bool { trustBoundaryOfMyAsset, trustBoundaryOfMyAssetOk := parsedModel.DirectContainingTrustBoundaryMappedByTechnicalAssetId[ta.Id] trustBoundaryOfOtherAsset, trustBoundaryOfOtherAssetOk := parsedModel.DirectContainingTrustBoundaryMappedByTechnicalAssetId[otherAssetId] if trustBoundaryOfMyAssetOk != trustBoundaryOfOtherAssetOk { return false } if !trustBoundaryOfMyAssetOk { return true } if trustBoundaryOfMyAsset.Type == types.ExecutionEnvironment && trustBoundaryOfOtherAsset.Type == types.ExecutionEnvironment { return trustBoundaryOfMyAsset.Id == trustBoundaryOfOtherAsset.Id } return false } func isSameTrustBoundaryNetworkOnly(parsedModel *types.Model, ta *types.TechnicalAsset, otherAssetId string) bool { useParentBoundary := func(trustBoundaryOfAsset **types.TrustBoundary, parsedModel *types.Model, trustBoundaryOfAssetOk *bool) { if trustBoundaryOfAsset == nil { return } tb := *trustBoundaryOfAsset if tb != nil && !tb.Type.IsNetworkBoundary() { *trustBoundaryOfAsset = parsedModel.FindParentTrustBoundary(tb) *trustBoundaryOfAssetOk = *trustBoundaryOfAsset != nil } } trustBoundaryOfMyAsset, trustBoundaryOfMyAssetOk := parsedModel.DirectContainingTrustBoundaryMappedByTechnicalAssetId[ta.Id] useParentBoundary(&trustBoundaryOfMyAsset, parsedModel, &trustBoundaryOfMyAssetOk) trustBoundaryOfOtherAsset, trustBoundaryOfOtherAssetOk := parsedModel.DirectContainingTrustBoundaryMappedByTechnicalAssetId[otherAssetId] useParentBoundary(&trustBoundaryOfOtherAsset, parsedModel, &trustBoundaryOfOtherAssetOk) if trustBoundaryOfMyAssetOk != trustBoundaryOfOtherAssetOk { return false } if !trustBoundaryOfMyAssetOk { return true } return trustBoundaryOfMyAsset.Id == trustBoundaryOfOtherAsset.Id }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/wrong_communication_link_content_rule.go
pkg/risks/builtin/wrong_communication_link_content_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type WrongCommunicationLinkContentRule struct{} func NewWrongCommunicationLinkContentRule() *WrongCommunicationLinkContentRule { return &WrongCommunicationLinkContentRule{} } func (*WrongCommunicationLinkContentRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "wrong-communication-link-content", Title: "Wrong Communication Link Content", Description: "When a communication link is defined as readonly, but does not receive any data asset, " + "or when it is defined as not readonly, but does not send any data asset, it is likely to be a model failure.", Impact: "If this potential model error is not fixed, some risks might not be visible.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Threat_Modeling_Cheat_Sheet.html", Action: "Model Consistency", Mitigation: "Try to model the correct readonly flag and/or data sent/received of communication links. " + "Also try to use communication link types matching the target technology/machine types.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.InformationDisclosure, DetectionLogic: "Communication links with inconsistent data assets being sent/received not matching their readonly flag or otherwise inconsistent protocols not matching the target technology type.", RiskAssessment: types.LowSeverity.String(), FalsePositives: "Usually no false positives as this looks like an incomplete model.", ModelFailurePossibleReason: true, CWE: 1008, } } func (*WrongCommunicationLinkContentRule) SupportedTags() []string { return []string{} } func (r *WrongCommunicationLinkContentRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, techAsset := range input.TechnicalAssets { for _, commLink := range techAsset.CommunicationLinks { // check readonly consistency if commLink.Readonly { if len(commLink.DataAssetsReceived) == 0 && len(commLink.DataAssetsSent) > 0 { risks = append(risks, r.createRisk(techAsset, commLink, "(data assets sent/received not matching the communication link's readonly flag)")) } } else { if len(commLink.DataAssetsSent) == 0 && len(commLink.DataAssetsReceived) > 0 { risks = append(risks, r.createRisk(techAsset, commLink, "(data assets sent/received not matching the communication link's readonly flag)")) } } // check for protocol inconsistencies targetAsset := input.TechnicalAssets[commLink.TargetId] if commLink.Protocol == types.InterProcessCommunication && targetAsset.Type != types.Process { risks = append(risks, r.createRisk(techAsset, commLink, "(protocol type \""+types.InterProcessCommunication.String()+"\" does not match target technology type \""+targetAsset.Technologies.String()+"\": expected \""+types.Process.String()+"\")")) } if commLink.Protocol == types.InProcessLibraryCall && !targetAsset.Technologies.GetAttribute(types.Library) { risks = append(risks, r.createRisk(techAsset, commLink, "(protocol type \""+types.InProcessLibraryCall.String()+"\" does not match target technology type \""+targetAsset.Technologies.String()+"\": expected \""+types.Library+"\")")) } if commLink.Protocol == types.LocalFileAccess && !targetAsset.Technologies.GetAttribute(types.LocalFileSystem) { risks = append(risks, r.createRisk(techAsset, commLink, "(protocol type \""+types.LocalFileAccess.String()+"\" does not match target technology type \""+targetAsset.Technologies.String()+"\": expected \""+types.LocalFileSystem+"\")")) } if commLink.Protocol == types.ContainerSpawning && targetAsset.Machine != types.Container { risks = append(risks, r.createRisk(techAsset, commLink, "(protocol type \""+types.ContainerSpawning.String()+"\" does not match target machine type \""+targetAsset.Machine.String()+"\": expected \""+types.Container.String()+"\")")) } } } return risks, nil } func (r *WrongCommunicationLinkContentRule) createRisk(technicalAsset *types.TechnicalAsset, commLink *types.CommunicationLink, reason string) *types.Risk { title := "<b>Wrong Communication Link Content</b> " + reason + " at <b>" + technicalAsset.Title + "</b> " + "regarding communication link <b>" + commLink.Title + "</b>" risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, types.LowImpact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: types.LowImpact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, MostRelevantCommunicationLinkId: commLink.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id + "@" + commLink.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_identity_store_rule_test.go
pkg/risks/builtin/missing_identity_store_rule_test.go
package builtin import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingIdentityStoreRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewMissingIdentityStoreRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingIdentityStoreRuleGenerateRisksThereIsIdenityStoreWithinScopeNoRisksCreated(t *testing.T) { rule := NewMissingIdentityStoreRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{ types.IsIdentityStore: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingIdentityStoreRuleGenerateRisksNoEndUserIdentityPropagationNoRisksCreated(t *testing.T) { rule := NewMissingIdentityStoreRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, }, "ta2": { Title: "Test Sparring Technical Asset", OutOfScope: false, CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta1", Authorization: types.NoneAuthorization, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type MissingIdentityStoreRuleTest struct { targetConfidentiality types.Confidentiality targetIntegrity types.Criticality targetAvailability types.Criticality dataProcessedConfidentiality types.Confidentiality dataProcessedIntegrity types.Criticality dataProcessedAvailability types.Criticality sourceConfidentiality types.Confidentiality sourceIntegrity types.Criticality sourceAvailability types.Criticality expectedImpact types.RiskExploitationImpact expectedMostRelevantAssetTitle string } func TestMissingIdentityStoreRule(t *testing.T) { testCases := map[string]MissingIdentityStoreRuleTest{ "low impact": { targetConfidentiality: types.Restricted, targetAvailability: types.Important, targetIntegrity: types.Important, dataProcessedConfidentiality: types.Restricted, dataProcessedIntegrity: types.Important, dataProcessedAvailability: types.Important, sourceConfidentiality: types.Restricted, sourceIntegrity: types.Important, sourceAvailability: types.Important, expectedImpact: types.LowImpact, expectedMostRelevantAssetTitle: "Test Technical Asset", }, "source asset more relevant": { targetConfidentiality: types.Restricted, targetAvailability: types.Important, targetIntegrity: types.Important, dataProcessedConfidentiality: types.Restricted, dataProcessedIntegrity: types.Important, dataProcessedAvailability: types.Important, sourceConfidentiality: types.Confidential, sourceIntegrity: types.Important, sourceAvailability: types.Important, expectedImpact: types.LowImpact, expectedMostRelevantAssetTitle: "Test Sparring Technical Asset", }, "medium impact confidential target asset": { targetConfidentiality: types.Confidential, targetAvailability: types.Important, targetIntegrity: types.Important, dataProcessedConfidentiality: types.Restricted, dataProcessedIntegrity: types.Important, dataProcessedAvailability: types.Important, sourceConfidentiality: types.Restricted, sourceIntegrity: types.Important, sourceAvailability: types.Important, expectedImpact: types.MediumImpact, expectedMostRelevantAssetTitle: "Test Technical Asset", }, "medium impact critical integrity target asset": { targetConfidentiality: types.Restricted, targetAvailability: types.Critical, targetIntegrity: types.Important, dataProcessedConfidentiality: types.Restricted, dataProcessedIntegrity: types.Important, dataProcessedAvailability: types.Important, sourceConfidentiality: types.Restricted, sourceIntegrity: types.Important, sourceAvailability: types.Important, expectedImpact: types.MediumImpact, expectedMostRelevantAssetTitle: "Test Technical Asset", }, "medium impact critical availability target asset": { targetConfidentiality: types.Restricted, targetAvailability: types.Important, targetIntegrity: types.Critical, dataProcessedConfidentiality: types.Restricted, dataProcessedIntegrity: types.Important, dataProcessedAvailability: types.Important, sourceConfidentiality: types.Restricted, sourceIntegrity: types.Important, sourceAvailability: types.Important, expectedImpact: types.MediumImpact, expectedMostRelevantAssetTitle: "Test Technical Asset", }, "medium impact process confidential data asset": { targetConfidentiality: types.Restricted, targetAvailability: types.Important, targetIntegrity: types.Important, dataProcessedConfidentiality: types.Confidential, dataProcessedIntegrity: types.Important, dataProcessedAvailability: types.Important, sourceConfidentiality: types.Restricted, sourceIntegrity: types.Important, sourceAvailability: types.Important, expectedImpact: types.MediumImpact, expectedMostRelevantAssetTitle: "Test Technical Asset", }, "medium impact process critical integrity data asset": { targetConfidentiality: types.Restricted, targetAvailability: types.Important, targetIntegrity: types.Important, dataProcessedConfidentiality: types.Restricted, dataProcessedIntegrity: types.Critical, dataProcessedAvailability: types.Important, sourceConfidentiality: types.Restricted, sourceIntegrity: types.Important, sourceAvailability: types.Important, expectedImpact: types.MediumImpact, expectedMostRelevantAssetTitle: "Test Technical Asset", }, "medium impact process critical availability data asset": { targetConfidentiality: types.Restricted, targetAvailability: types.Important, targetIntegrity: types.Important, dataProcessedConfidentiality: types.Restricted, dataProcessedIntegrity: types.Important, dataProcessedAvailability: types.Critical, sourceConfidentiality: types.Restricted, sourceIntegrity: types.Important, sourceAvailability: types.Important, expectedImpact: types.MediumImpact, expectedMostRelevantAssetTitle: "Test Technical Asset", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingIdentityStoreRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Availability: testCase.targetAvailability, Confidentiality: testCase.targetConfidentiality, Integrity: testCase.targetIntegrity, DataAssetsProcessed: []string{"da1"}, }, "ta2": { Title: "Test Sparring Technical Asset", OutOfScope: false, Availability: testCase.sourceAvailability, Confidentiality: testCase.sourceConfidentiality, Integrity: testCase.sourceIntegrity, CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta1", Authorization: types.EndUserIdentityPropagation, }, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Title: "Test Data Asset", Availability: testCase.dataProcessedAvailability, Confidentiality: testCase.dataProcessedConfidentiality, Integrity: testCase.dataProcessedIntegrity, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Identity Store</b> in the threat model (referencing asset <b>%s</b> as an example)", testCase.expectedMostRelevantAssetTitle) assert.Equal(t, expTitle, risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/untrusted_deserialization_rule_test.go
pkg/risks/builtin/untrusted_deserialization_rule_test.go
package builtin import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestUntrustedDeserializationRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewUntrustedDeserializationRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestUntrustedDeserializationRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewUntrustedDeserializationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUntrustedDeserializationRuleGenerateRisksNoSerializationRisksCreated(t *testing.T) { rule := NewUntrustedDeserializationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUntrustedDeserializationRuleGenerateRiskAcceptSerializationRisksCreated(t *testing.T) { rule := NewUntrustedDeserializationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", DataFormatsAccepted: []types.DataFormat{types.Serialization}, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.Likely, risks[0].ExploitationLikelihood) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Untrusted Deserialization</b> risk at <b>Test Technical Asset</b>", risks[0].Title) } func TestUntrustedDeserializationRuleGenerateRiskEJBRisksCreated(t *testing.T) { rule := NewUntrustedDeserializationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Attributes: map[string]bool{ types.EJB: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.Likely, risks[0].ExploitationLikelihood) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Untrusted Deserialization</b> risk at <b>Test Technical Asset</b>", risks[0].Title) } type UntrustedDeserialisationRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality availability types.Criticality protocol types.Protocol isAcrossTrustBoundary bool expectedImpact types.RiskExploitationImpact expectedLikelihood types.RiskExploitationLikelihood expectedSuffixTitle string } func TestUntrustedDeserializationRuleGenerateRisks(t *testing.T) { testCases := map[string]UntrustedDeserialisationRuleTest{ "IIOP": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, protocol: types.IIOP, isAcrossTrustBoundary: false, expectedImpact: types.HighImpact, expectedLikelihood: types.Likely, }, "IiopEncrypted": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, protocol: types.IiopEncrypted, isAcrossTrustBoundary: false, expectedImpact: types.HighImpact, expectedLikelihood: types.Likely, }, "JRMP": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, protocol: types.JRMP, isAcrossTrustBoundary: false, expectedImpact: types.HighImpact, expectedLikelihood: types.Likely, }, "JrmpEncrypted": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, protocol: types.JrmpEncrypted, isAcrossTrustBoundary: false, expectedImpact: types.HighImpact, expectedLikelihood: types.Likely, }, "strictly confidential": { confidentiality: types.StrictlyConfidential, integrity: types.Critical, availability: types.Critical, protocol: types.IIOP, isAcrossTrustBoundary: false, expectedImpact: types.VeryHighImpact, expectedLikelihood: types.Likely, }, "mission critical integrity": { confidentiality: types.Confidential, integrity: types.MissionCritical, availability: types.Critical, protocol: types.IIOP, isAcrossTrustBoundary: false, expectedImpact: types.VeryHighImpact, expectedLikelihood: types.Likely, }, "mission critical availability": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.MissionCritical, protocol: types.IIOP, isAcrossTrustBoundary: false, expectedImpact: types.VeryHighImpact, expectedLikelihood: types.Likely, }, "across trust boundary": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, protocol: types.IIOP, isAcrossTrustBoundary: true, expectedImpact: types.HighImpact, expectedLikelihood: types.VeryLikely, expectedSuffixTitle: " across a trust boundary (at least via communication link <b>Test Communication Link</b>)", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewUntrustedDeserializationRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "First Trust Boundary", TechnicalAssetsInside: []string{"source", "target"}, Type: types.NetworkCloudProvider, } tb2 := &types.TrustBoundary{ Id: "tb2", Title: "Second Trust Boundary", Type: types.NetworkCloudProvider, } if testCase.isAcrossTrustBoundary { tb1.TechnicalAssetsInside = []string{"source"} tb2.TechnicalAssetsInside = []string{"target"} } directContainingTrustBoundaryMappedByTechnicalAssetId := map[string]*types.TrustBoundary{ "source": tb1, "target": tb1, } if testCase.isAcrossTrustBoundary { directContainingTrustBoundaryMappedByTechnicalAssetId["target"] = tb2 } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", CommunicationLinks: []*types.CommunicationLink{ { Title: "Test Communication Link", SourceId: "source", TargetId: "target", Protocol: testCase.protocol, }, }, }, "target": { Id: "target", Title: "Target Technical Asset", Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, "tb2": tb2, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: directContainingTrustBoundaryMappedByTechnicalAssetId, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "target": { { SourceId: "source", TargetId: "target", Protocol: testCase.protocol, Title: "Test Communication Link", }, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, testCase.expectedLikelihood, risks[0].ExploitationLikelihood) expectedMessage := fmt.Sprintf("<b>Untrusted Deserialization</b> risk at <b>Target Technical Asset</b>%s", testCase.expectedSuffixTitle) assert.Equal(t, risks[0].Title, expectedMessage) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_authentication_rule.go
pkg/risks/builtin/missing_authentication_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type MissingAuthenticationRule struct{} func NewMissingAuthenticationRule() *MissingAuthenticationRule { return &MissingAuthenticationRule{} } func (*MissingAuthenticationRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-authentication", Title: "Missing Authentication", Description: "Technical assets (especially multi-tenant systems) should authenticate incoming requests when the asset processes sensitive data. ", Impact: "If this risk is unmitigated, attackers might be able to access or modify sensitive data in an unauthenticated way.", ASVS: "V2 - Authentication Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html", Action: "Authentication of Incoming Requests", Mitigation: "Apply an authentication method to the technical asset. To protect highly sensitive data consider " + "the use of two-factor authentication for human users.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "In-scope technical assets (except " + types.LoadBalancer + ", " + types.ReverseProxy + ", " + types.ServiceRegistry + ", " + types.WAF + ", " + types.IDS + ", and " + types.IPS + " and in-process calls) should authenticate incoming requests when the asset processes " + "sensitive data. This is especially the case for all multi-tenant assets (there even non-sensitive ones).", RiskAssessment: "The risk rating (medium or high) " + "depends on the sensitivity of the data sent across the communication link. Monitoring callers are exempted from this risk.", FalsePositives: "Technical assets which do not process requests regarding functionality or data linked to end-users (customers) " + "can be considered as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 306, } } func (*MissingAuthenticationRule) SupportedTags() []string { return []string{} } func (r *MissingAuthenticationRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if technicalAsset.OutOfScope || technicalAsset.Technologies.GetAttribute(types.NoAuthenticationRequired) { continue } if input.HighestProcessedConfidentiality(technicalAsset) < types.Confidential && input.HighestProcessedIntegrity(technicalAsset) < types.Critical && input.HighestProcessedAvailability(technicalAsset) < types.Critical && !technicalAsset.MultiTenant { continue } // check each incoming data flow commLinks := input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] for _, commLink := range commLinks { caller := input.TechnicalAssets[commLink.SourceId] if caller.Technologies.GetAttribute(types.IsUnprotectedCommunicationsTolerated) || caller.Type == types.Datastore { continue } impact := r.calculateImpact(commLink, input) if commLink.Authentication == types.NoneAuthentication && !commLink.Protocol.IsProcessLocal() { risks = append(risks, r.createRisk(input, technicalAsset, commLink, commLink, "", impact, types.Likely, false, r.Category())) } } } return risks, nil } func (r *MissingAuthenticationRule) calculateImpact(commLink *types.CommunicationLink, input *types.Model) types.RiskExploitationImpact { if input.HighestCommunicationLinkConfidentiality(commLink) == types.StrictlyConfidential || input.HighestCommunicationLinkIntegrity(commLink) == types.MissionCritical { return types.HighImpact } if input.HighestCommunicationLinkConfidentiality(commLink) <= types.Internal && input.HighestCommunicationLinkIntegrity(commLink) == types.Operational { return types.LowImpact } return types.MediumImpact } func (r *MissingAuthenticationRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset, incomingAccess, incomingAccessOrigin *types.CommunicationLink, hopBetween string, impact types.RiskExploitationImpact, likelihood types.RiskExploitationLikelihood, twoFactor bool, category *types.RiskCategory) *types.Risk { factorString := "" if twoFactor { factorString = "Two-Factor " } if len(hopBetween) > 0 { hopBetween = "forwarded via <b>" + hopBetween + "</b> " } risk := &types.Risk{ CategoryId: category.ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: "<b>Missing " + factorString + "Authentication</b> covering communication link <b>" + incomingAccess.Title + "</b> " + "from <b>" + input.TechnicalAssets[incomingAccessOrigin.SourceId].Title + "</b> " + hopBetween + "to <b>" + technicalAsset.Title + "</b>", MostRelevantTechnicalAssetId: technicalAsset.Id, MostRelevantCommunicationLinkId: incomingAccess.Id, DataBreachProbability: types.Possible, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + incomingAccess.Id + "@" + input.TechnicalAssets[incomingAccess.SourceId].Id + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/container_baseimage_backdooring_rule.go
pkg/risks/builtin/container_baseimage_backdooring_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type ContainerBaseImageBackdooringRule struct{} func NewContainerBaseImageBackdooringRule() *ContainerBaseImageBackdooringRule { return &ContainerBaseImageBackdooringRule{} } func (*ContainerBaseImageBackdooringRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "container-baseimage-backdooring", Title: "Container Base Image Backdooring", Description: "When a technical asset is built using container technologies, Base Image Backdooring risks might arise where " + "base images and other layers used contain vulnerable components or backdoors." + "<br><br>See for example: <a href=\"https://techcrunch.com/2018/06/15/tainted-crypto-mining-containers-pulled-from-docker-hub/\">https://techcrunch.com/2018/06/15/tainted-crypto-mining-containers-pulled-from-docker-hub/</a>", Impact: "If this risk is unmitigated, attackers might be able to deeply persist in the target system by executing code in deployed containers.", ASVS: "V10 - Malicious Code Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Docker_Security_Cheat_Sheet.html", Action: "Container Infrastructure Hardening", Mitigation: "Apply hardening of all container infrastructures (see for example the <i>CIS-Benchmarks for Docker and Kubernetes</i> and the <i>Docker Bench for Security</i>). " + "Use only trusted base images of the original vendors, verify digital signatures and apply image creation best practices. " + "Also consider using Google's <i>Distroless</i> base images or otherwise very small base images. " + "Regularly execute container image scans with tools checking the layers for vulnerable components.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS/CSVS applied?", Function: types.Operations, STRIDE: types.Tampering, DetectionLogic: "In-scope technical assets running as containers.", RiskAssessment: "The risk rating depends on the sensitivity of the technical asset itself and of the data assets.", FalsePositives: "Fully trusted (i.e. reviewed and cryptographically signed or similar) base images of containers can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 912, } } func (*ContainerBaseImageBackdooringRule) SupportedTags() []string { return []string{} } func (r *ContainerBaseImageBackdooringRule) GenerateRisks(parsedModel *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range parsedModel.SortedTechnicalAssetIDs() { technicalAsset := parsedModel.TechnicalAssets[id] if !technicalAsset.OutOfScope && technicalAsset.Machine == types.Container { risks = append(risks, r.createRisk(parsedModel, technicalAsset)) } } return risks, nil } func (r *ContainerBaseImageBackdooringRule) createRisk(parsedModel *types.Model, technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>Container Base Image Backdooring</b> risk at <b>" + technicalAsset.Title + "</b>" impact := types.MediumImpact if parsedModel.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || parsedModel.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical || parsedModel.HighestProcessedAvailability(technicalAsset) == types.MissionCritical { impact = types.HighImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/accidental_secret_leak_rule_test.go
pkg/risks/builtin/accidental_secret_leak_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestAccidentalSecretLeakRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewAccidentalSecretLeakRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestAccidentalSecretLeakRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewAccidentalSecretLeakRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestAccidentalSecretLeakRuleGenerateRisksTechAssetNotContainSecretsNotRisksCreated(t *testing.T) { rule := NewAccidentalSecretLeakRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.MayContainSecrets: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestAccidentalSecretLeakRuleGenerateRisksTechAssetGitContainSecretsRisksCreated(t *testing.T) { rule := NewAccidentalSecretLeakRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Technologies: types.TechnologyList{ { Name: "git repository", Attributes: map[string]bool{ types.MayContainSecrets: true, }, }, }, Tags: []string{"git"}, }, }, }) assert.Nil(t, err) assert.Equal(t, len(risks), 1) assert.Contains(t, risks[0].Title, "Accidental Secret Leak (Git)") } func TestAccidentalSecretLeakRuleGenerateRisksTechAssetNotGitContainSecretsRisksCreated(t *testing.T) { rule := NewAccidentalSecretLeakRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Technologies: types.TechnologyList{ { Name: "git repository", Attributes: map[string]bool{ types.MayContainSecrets: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Equal(t, len(risks), 1) assert.Equal(t, "<b>Accidental Secret Leak</b> risk at <b></b>", risks[0].Title) } func TestAccidentalSecretLeakRuleGenerateRisksTechAssetProcessStrictlyConfidentialDataAssetHighImpactRiskCreated(t *testing.T) { rule := NewAccidentalSecretLeakRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Technologies: types.TechnologyList{ { Name: "git repository", Attributes: map[string]bool{ types.MayContainSecrets: true, }, }, }, DataAssetsProcessed: []string{"confidential-data-asset", "strictly-confidential-data-asset"}, }, }, DataAssets: map[string]*types.DataAsset{ "confidential-data-asset": { Confidentiality: types.Confidential, }, "strictly-confidential-data-asset": { Confidentiality: types.StrictlyConfidential, }, }, }) assert.Nil(t, err) assert.Equal(t, len(risks), 1) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/mixed_targets_on_shared_runtime_rule.go
pkg/risks/builtin/mixed_targets_on_shared_runtime_rule.go
package builtin import ( "sort" "github.com/threagile/threagile/pkg/types" ) type MixedTargetsOnSharedRuntimeRule struct{} func NewMixedTargetsOnSharedRuntimeRule() *MixedTargetsOnSharedRuntimeRule { return &MixedTargetsOnSharedRuntimeRule{} } func (*MixedTargetsOnSharedRuntimeRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "mixed-targets-on-shared-runtime", Title: "Mixed Targets on Shared Runtime", Description: "Different attacker targets (like frontend and backend/datastore components) should not be running on the same " + "shared (underlying) runtime.", Impact: "If this risk is unmitigated, attackers successfully attacking other components of the system might have an easy path towards " + "more valuable targets, as they are running on the same shared runtime.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Runtime Separation", Mitigation: "Use separate runtime environments for running different target components or apply similar separation styles to " + "prevent load- or breach-related problems originating from one more attacker-facing asset impacts also the " + "other more critical rated backend/datastore assets.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Operations, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "Shared runtime running technical assets of different trust-boundaries is at risk. " + "Also mixing backend/datastore with frontend components on the same shared runtime is considered a risk.", RiskAssessment: "The risk rating (low or medium) depends on the confidentiality, integrity, and availability rating of " + "the technical asset running on the shared runtime.", FalsePositives: "When all assets running on the shared runtime are hardened and protected to the same extend as if all were " + "containing/processing highly sensitive data.", ModelFailurePossibleReason: false, CWE: 1008, } } func (*MixedTargetsOnSharedRuntimeRule) SupportedTags() []string { return []string{} } func (r *MixedTargetsOnSharedRuntimeRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) // as in Go ranging over map is random order, range over them in sorted (hence reproducible) way: keys := make([]string, 0) for k := range input.SharedRuntimes { keys = append(keys, k) } sort.Strings(keys) for _, key := range keys { sharedRuntime := input.SharedRuntimes[key] currentTrustBoundaryId := "" hasFrontend, hasBackend := false, false riskAdded := false for _, technicalAssetId := range sharedRuntime.TechnicalAssetsRunning { technicalAsset := input.TechnicalAssets[technicalAssetId] if len(currentTrustBoundaryId) > 0 && currentTrustBoundaryId != input.GetTechnicalAssetTrustBoundaryId(technicalAsset) { risks = append(risks, r.createRisk(input, sharedRuntime)) riskAdded = true break } currentTrustBoundaryId = input.GetTechnicalAssetTrustBoundaryId(technicalAsset) if technicalAsset.Technologies.GetAttribute(types.IsExclusivelyFrontendRelated) { hasFrontend = true } if technicalAsset.Technologies.GetAttribute(types.IsExclusivelyBackendRelated) { hasBackend = true } } if !riskAdded && hasFrontend && hasBackend { risks = append(risks, r.createRisk(input, sharedRuntime)) } } return risks, nil } func (r *MixedTargetsOnSharedRuntimeRule) createRisk(input *types.Model, sharedRuntime *types.SharedRuntime) *types.Risk { impact := types.LowImpact if isMoreRisky(input, sharedRuntime) { impact = types.MediumImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: "<b>Mixed Targets on Shared Runtime</b> named <b>" + sharedRuntime.Title + "</b> might enable attackers moving from one less " + "valuable target to a more valuable one", // TODO list at least the assets in the text which are running on the shared HW MostRelevantSharedRuntimeId: sharedRuntime.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: sharedRuntime.TechnicalAssetsRunning, } risk.SyntheticId = risk.CategoryId + "@" + sharedRuntime.Id return risk } func isMoreRisky(input *types.Model, sharedRuntime *types.SharedRuntime) bool { for _, techAssetId := range sharedRuntime.TechnicalAssetsRunning { techAsset := input.TechnicalAssets[techAssetId] if techAsset.Confidentiality == types.StrictlyConfidential || techAsset.Integrity == types.MissionCritical || techAsset.Availability == types.MissionCritical { return true } } return false }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unguarded_direct_datastore_access_rule_test.go
pkg/risks/builtin/unguarded_direct_datastore_access_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestUnguardedDirectDatastoreAccessRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewUnguardedDirectDatastoreAccessRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } type UnguardedDirectDatastoreAccessRuleTest struct { outOfScope bool isIdentityStore bool isFileServer bool assetType types.TechnicalAssetType raa float64 isSourceIdentityProvider bool isAcrossTrustBoundary bool isSharingSameParentTrustBoundary bool protocol types.Protocol usage types.Usage confidentiality types.Confidentiality integrity types.Criticality riskCreated bool expectedImpact types.RiskExploitationImpact } func TestUnguardedDirectDatastoreAccessRuleRuleGenerateRisks(t *testing.T) { testCases := map[string]UnguardedDirectDatastoreAccessRuleTest{ "out of scope": { outOfScope: true, assetType: types.Datastore, riskCreated: false, }, "no data store": { outOfScope: false, assetType: types.ExternalEntity, riskCreated: false, }, "identity store to identity provider is ok": { outOfScope: false, assetType: types.Datastore, isSourceIdentityProvider: true, isIdentityStore: true, }, "no risk when data store is not critical": { outOfScope: false, assetType: types.Datastore, confidentiality: types.Restricted, integrity: types.Operational, }, "not across trust boundary network": { outOfScope: false, assetType: types.Datastore, isAcrossTrustBoundary: false, isSharingSameParentTrustBoundary: false, usage: types.Business, isFileServer: false, protocol: types.HTTP, confidentiality: types.Confidential, integrity: types.Critical, riskCreated: false, }, "sharing same parent trust boundary": { outOfScope: false, assetType: types.Datastore, isAcrossTrustBoundary: true, isSharingSameParentTrustBoundary: true, usage: types.Business, isFileServer: false, protocol: types.HTTP, confidentiality: types.Confidential, integrity: types.Critical, riskCreated: false, }, "devops usage": { outOfScope: false, assetType: types.Datastore, isAcrossTrustBoundary: true, isSharingSameParentTrustBoundary: false, usage: types.DevOps, isFileServer: false, protocol: types.HTTP, confidentiality: types.Confidential, integrity: types.Critical, riskCreated: false, }, "file server access via ftp": { outOfScope: false, assetType: types.Datastore, isAcrossTrustBoundary: true, isSharingSameParentTrustBoundary: false, usage: types.Business, isFileServer: true, protocol: types.FTP, confidentiality: types.Confidential, integrity: types.Critical, riskCreated: false, }, "file server access via ftp (FTPS)": { outOfScope: false, assetType: types.Datastore, isAcrossTrustBoundary: true, isSharingSameParentTrustBoundary: false, usage: types.Business, isFileServer: true, protocol: types.FTPS, confidentiality: types.Confidential, integrity: types.Critical, riskCreated: false, }, "file server access via ftp (SFTP)": { outOfScope: false, assetType: types.Datastore, isAcrossTrustBoundary: true, isSharingSameParentTrustBoundary: false, usage: types.Business, isFileServer: true, protocol: types.SFTP, confidentiality: types.Confidential, integrity: types.Critical, riskCreated: false, }, "low impact": { outOfScope: false, assetType: types.Datastore, isAcrossTrustBoundary: true, isSharingSameParentTrustBoundary: false, usage: types.Business, isFileServer: false, protocol: types.HTTP, confidentiality: types.Confidential, integrity: types.Critical, riskCreated: true, expectedImpact: types.LowImpact, }, "high raa medium impact": { outOfScope: false, assetType: types.Datastore, isAcrossTrustBoundary: true, isSharingSameParentTrustBoundary: false, usage: types.Business, isFileServer: false, protocol: types.HTTP, raa: 50, confidentiality: types.Confidential, integrity: types.Critical, riskCreated: true, expectedImpact: types.MediumImpact, }, "strict confidentiality medium impact": { outOfScope: false, assetType: types.Datastore, isAcrossTrustBoundary: true, isSharingSameParentTrustBoundary: false, usage: types.Business, isFileServer: false, protocol: types.HTTP, confidentiality: types.StrictlyConfidential, integrity: types.Critical, riskCreated: true, expectedImpact: types.MediumImpact, }, "mission critical integrity medium impact": { outOfScope: false, assetType: types.Datastore, isAcrossTrustBoundary: true, isSharingSameParentTrustBoundary: false, usage: types.Business, isFileServer: false, protocol: types.HTTP, confidentiality: types.Confidential, integrity: types.MissionCritical, riskCreated: true, expectedImpact: types.MediumImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewUnguardedDirectDatastoreAccessRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "First Trust Boundary", TechnicalAssetsInside: []string{"source", "target"}, Type: types.NetworkCloudProvider, } tb2 := &types.TrustBoundary{ Id: "tb2", Title: "Second Trust Boundary", Type: types.NetworkCloudProvider, } if testCase.isAcrossTrustBoundary { tb1.TechnicalAssetsInside = []string{"source"} tb2.TechnicalAssetsInside = []string{"target"} } directContainingTrustBoundaryMappedByTechnicalAssetId := map[string]*types.TrustBoundary{ "source": tb1, "target": tb1, } if testCase.isAcrossTrustBoundary { directContainingTrustBoundaryMappedByTechnicalAssetId["target"] = tb2 } tb3 := &types.TrustBoundary{ Id: "tb3", Title: "Sharing Trust Boundary", Type: types.NetworkCloudProvider, } if testCase.isSharingSameParentTrustBoundary { tb3.TrustBoundariesNested = []string{"tb1", "tb2"} } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", Technologies: types.TechnologyList{ { Attributes: map[string]bool{ types.IdentityProvider: testCase.isSourceIdentityProvider, }, }, }, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: testCase.outOfScope, Type: testCase.assetType, RAA: testCase.raa, CommunicationLinks: []*types.CommunicationLink{ { Title: "Test Communication Link", SourceId: "source", TargetId: "target", Protocol: testCase.protocol, Usage: testCase.usage, }, }, Technologies: types.TechnologyList{ { Attributes: map[string]bool{ types.FileServer: testCase.isFileServer, types.IsIdentityStore: testCase.isIdentityStore, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "target": { { Title: "Test Communication Link", SourceId: "source", TargetId: "target", Protocol: testCase.protocol, Usage: testCase.usage, }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, "tb2": tb2, "tb3": tb3, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: directContainingTrustBoundaryMappedByTechnicalAssetId, }) assert.Nil(t, err) if testCase.riskCreated { assert.NotEmpty(t, risks) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) expectedMessage := "<b>Unguarded Direct Datastore Access</b> of <b>Target Technical Asset</b> by <b>Source Technical Asset</b> via <b>Test Communication Link</b>" assert.Equal(t, risks[0].Title, expectedMessage) } else { assert.Empty(t, risks) } }) } } func TestIsSharingSameParentTrustBoundaryBothOutOfTrustBoundaryExpectTrue(t *testing.T) { input := &types.Model{ TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": { Id: "tb1", }, "tb2": { Id: "tb2", }, }, } left := &types.TechnicalAsset{ Id: "ta1", } right := &types.TechnicalAsset{ Id: "ta2", } assert.True(t, isSharingSameParentTrustBoundary(input, left, right)) } func TestIsSharingSameParentTrustBoundaryLeftOutOfTrustBoundaryExpectFalse(t *testing.T) { input := &types.Model{ TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": { Id: "tb1", }, "tb2": { Id: "tb2", TechnicalAssetsInside: []string{"ta2"}, }, }, } left := &types.TechnicalAsset{ Id: "ta1", } right := &types.TechnicalAsset{ Id: "ta2", } assert.False(t, isSharingSameParentTrustBoundary(input, left, right)) } func TestIsSharingSameParentTrustBoundaryRightOutOfTrustBoundaryExpectFalse(t *testing.T) { input := &types.Model{ TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": { Id: "tb1", TechnicalAssetsInside: []string{"ta1"}, }, "tb2": { Id: "tb2", }, }, } left := &types.TechnicalAsset{ Id: "ta1", } right := &types.TechnicalAsset{ Id: "ta2", } assert.False(t, isSharingSameParentTrustBoundary(input, left, right)) } func TestIsSharingSameParentTrustBoundaryInDifferentTrustBoundariesExpectFalse(t *testing.T) { input := &types.Model{ TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": { Id: "tb1", TechnicalAssetsInside: []string{"ta1"}, }, "tb2": { Id: "tb2", }, }, } left := &types.TechnicalAsset{ Id: "ta1", } right := &types.TechnicalAsset{ Id: "ta2", } assert.False(t, isSharingSameParentTrustBoundary(input, left, right)) } func TestIsSharingSameParentTrustBoundarySameTrustBoundariesExpectTrue(t *testing.T) { input := &types.Model{ TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": { Id: "tb1", TechnicalAssetsInside: []string{"ta1", "ta2"}, }, }, } left := &types.TechnicalAsset{ Id: "ta1", } right := &types.TechnicalAsset{ Id: "ta2", } assert.True(t, isSharingSameParentTrustBoundary(input, left, right)) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false