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/types/risk_severity.go
pkg/types/risk_severity.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type RiskSeverity int const ( LowSeverity RiskSeverity = iota MediumSeverity ElevatedSeverity HighSeverity CriticalSeverity ) func RiskSeverityValues() []TypeEnum { return []TypeEnum{ LowSeverity, MediumSeverity, ElevatedSeverity, HighSeverity, CriticalSeverity, } } var RiskSeverityTypeDescription = [...]TypeDescription{ {"low", "Low"}, {"medium", "Medium"}, {"elevated", "Elevated"}, {"high", "High"}, {"critical", "Critical"}, } func ParseRiskSeverity(value string) (riskSeverity RiskSeverity, err error) { return RiskSeverity(0).Find(value) } func (what RiskSeverity) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return RiskSeverityTypeDescription[what].Name } func (what RiskSeverity) Explain() string { return RiskSeverityTypeDescription[what].Description } func (what RiskSeverity) Title() string { return [...]string{"Low", "Medium", "Elevated", "High", "Critical"}[what] } func (what RiskSeverity) Find(value string) (RiskSeverity, error) { if len(value) == 0 { return MediumSeverity, nil } for index, description := range RiskSeverityTypeDescription { if strings.EqualFold(value, description.Name) { return RiskSeverity(index), nil } } return RiskSeverity(0), fmt.Errorf("unknown risk severity value %q", value) } func (what RiskSeverity) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *RiskSeverity) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.Find(text) if findError != nil { return findError } *what = value return nil } func (what RiskSeverity) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *RiskSeverity) UnmarshalYAML(node *yaml.Node) error { value, findError := what.Find(node.Value) if findError != nil { return findError } *what = value return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk_function_test.go
pkg/types/risk_function_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseRiskFunctionTest struct { input string expected RiskFunction expectedError error } func TestParseRiskFunction(t *testing.T) { testCases := map[string]ParseRiskFunctionTest{ "business-side": { input: "business-side", expected: BusinessSide, }, "architecture": { input: "architecture", expected: Architecture, }, "development": { input: "development", expected: Development, }, "operations": { input: "operations", expected: Operations, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unable to parse into type: unknown"), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseRiskFunction(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/confidentiality.go
pkg/types/confidentiality.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type Confidentiality int const ( Public Confidentiality = iota Internal Restricted Confidential StrictlyConfidential ) func ConfidentialityValues() []TypeEnum { return []TypeEnum{ Public, Internal, Restricted, Confidential, StrictlyConfidential, } } func ParseConfidentiality(value string) (confidentiality Confidentiality, err error) { return Confidentiality(0).Find(value) } var ConfidentialityTypeDescription = [...]TypeDescription{ {"public", "Public available information"}, {"internal", "(Company) internal information - but all people in the institution can access it"}, {"restricted", "Internal and with restricted access"}, {"confidential", "Only a few selected people have access"}, {"strictly-confidential", "Highest secrecy level"}, } func (what Confidentiality) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return ConfidentialityTypeDescription[what].Name } func (what Confidentiality) Explain() string { return ConfidentialityTypeDescription[what].Description } func (what Confidentiality) AttackerAttractivenessForAsset() float64 { // fibonacci starting at 8 return [...]float64{8, 13, 21, 34, 55}[what] } func (what Confidentiality) AttackerAttractivenessForProcessedOrStoredData() float64 { // fibonacci starting at 5 return [...]float64{5, 8, 13, 21, 34}[what] } func (what Confidentiality) AttackerAttractivenessForInOutTransferredData() float64 { // fibonacci starting at 2 return [...]float64{2, 3, 5, 8, 13}[what] } func (what Confidentiality) RatingStringInScale() string { result := "(rated " if what == Public { result += "1" } if what == Internal { result += "2" } if what == Restricted { result += "3" } if what == Confidential { result += "4" } if what == StrictlyConfidential { result += "5" } result += " in scale of 5)" return result } func (what Confidentiality) Find(value string) (Confidentiality, error) { for index, description := range ConfidentialityTypeDescription { if strings.EqualFold(value, description.Name) { return Confidentiality(index), nil } } return Confidentiality(0), fmt.Errorf("unknown confidentiality value %q", value) } func (what Confidentiality) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *Confidentiality) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.Find(text) if findError != nil { return findError } *what = value return nil } func (what Confidentiality) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *Confidentiality) UnmarshalYAML(node *yaml.Node) error { value, findError := what.Find(node.Value) if findError != nil { return findError } *what = value return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk.go
pkg/types/risk.go
package types type Risk struct { CategoryId string `yaml:"category,omitempty" json:"category,omitempty"` // used for better JSON marshalling, is assigned in risk evaluation phase automatically RiskStatus RiskStatus `yaml:"risk_status,omitempty" json:"risk_status,omitempty"` // used for better JSON marshalling, is assigned in risk evaluation phase automatically Severity RiskSeverity `yaml:"severity,omitempty" json:"severity,omitempty"` ExploitationLikelihood RiskExploitationLikelihood `yaml:"exploitation_likelihood,omitempty" json:"exploitation_likelihood,omitempty"` ExploitationImpact RiskExploitationImpact `yaml:"exploitation_impact,omitempty" json:"exploitation_impact,omitempty"` Title string `yaml:"title,omitempty" json:"title,omitempty"` SyntheticId string `yaml:"synthetic_id,omitempty" json:"synthetic_id,omitempty"` MostRelevantDataAssetId string `yaml:"most_relevant_data_asset,omitempty" json:"most_relevant_data_asset,omitempty"` MostRelevantTechnicalAssetId string `yaml:"most_relevant_technical_asset,omitempty" json:"most_relevant_technical_asset,omitempty"` MostRelevantTrustBoundaryId string `yaml:"most_relevant_trust_boundary,omitempty" json:"most_relevant_trust_boundary,omitempty"` MostRelevantSharedRuntimeId string `yaml:"most_relevant_shared_runtime,omitempty" json:"most_relevant_shared_runtime,omitempty"` MostRelevantCommunicationLinkId string `yaml:"most_relevant_communication_link,omitempty" json:"most_relevant_communication_link,omitempty"` DataBreachProbability DataBreachProbability `yaml:"data_breach_probability,omitempty" json:"data_breach_probability,omitempty"` DataBreachTechnicalAssetIDs []string `yaml:"data_breach_technical_assets,omitempty" json:"data_breach_technical_assets,omitempty"` RiskExplanation []string `yaml:"risk_explanation,omitempty" json:"risk_explanation,omitempty"` RatingExplanation []string `yaml:"rating_explanation,omitempty" json:"rating_explanation,omitempty"` // TODO: refactor all "ID" here to "ID"? }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk_status.go
pkg/types/risk_status.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type RiskStatus int const ( Unchecked RiskStatus = iota InDiscussion Accepted InProgress Mitigated FalsePositive ) func RiskStatusValues() []TypeEnum { return []TypeEnum{ Unchecked, InDiscussion, Accepted, InProgress, Mitigated, FalsePositive, } } var RiskStatusTypeDescription = [...]TypeDescription{ {"unchecked", "Risk has not yet been reviewed"}, {"in-discussion", "Risk is currently being discussed (during review)"}, {"accepted", "Risk has been accepted (as possibly a corporate risk acceptance process defines)"}, {"in-progress", "Risk mitigation is currently in progress"}, {"mitigated", "Risk has been mitigated"}, {"false-positive", "Risk is a false positive (i.e. no risk at all or not applicable)"}, } func ParseRiskStatus(value string) (riskStatus RiskStatus, err error) { value = strings.TrimSpace(value) for _, candidate := range RiskStatusValues() { if candidate.String() == value { return candidate.(RiskStatus), err } } return riskStatus, fmt.Errorf("unable to parse into type: %v", value) } func (what RiskStatus) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return RiskStatusTypeDescription[what].Name } func (what RiskStatus) Explain() string { return RiskStatusTypeDescription[what].Description } func (what RiskStatus) Title() string { return [...]string{"Unchecked", "In Discussion", "Accepted", "In Progress", "Mitigated", "False Positive"}[what] } func (what RiskStatus) IsStillAtRisk() bool { return what == Unchecked || what == InDiscussion || what == Accepted || what == InProgress } func (what RiskStatus) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *RiskStatus) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.find(text) if findError != nil { return findError } *what = value return nil } func (what RiskStatus) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *RiskStatus) UnmarshalYAML(node *yaml.Node) error { value, findError := what.find(node.Value) if findError != nil { return findError } *what = value return nil } func (what RiskStatus) find(value string) (RiskStatus, error) { for index, description := range RiskStatusTypeDescription { if strings.EqualFold(value, description.Name) { return RiskStatus(index), nil } } return RiskStatus(0), fmt.Errorf("unknown risk status value %q", value) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/shared_runtime.go
pkg/types/shared_runtime.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types type SharedRuntime struct { Id string `json:"id,omitempty" yaml:"id,omitempty"` Title string `json:"title,omitempty" yaml:"title,omitempty"` Description string `json:"description,omitempty" yaml:"description,omitempty"` Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` TechnicalAssetsRunning []string `json:"technical_assets_running,omitempty" yaml:"technical_assets_running,omitempty"` } func (what SharedRuntime) IsTaggedWithAny(tags ...string) bool { return containsCaseInsensitiveAny(what.Tags, tags...) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/technical_asset_type_test.go
pkg/types/technical_asset_type_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseTechnicalAssetTypeTest struct { input string expected TechnicalAssetType expectedError error } func TestParseTechnicalAssetType(t *testing.T) { testCases := map[string]ParseTechnicalAssetTypeTest{ "external-entity": { input: "external-entity", expected: ExternalEntity, }, "process": { input: "process", expected: Process, }, "datastore": { input: "datastore", expected: Datastore, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unable to parse into type: unknown"), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseTechnicalAssetType(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk_exploitation_likelihood_test.go
pkg/types/risk_exploitation_likelihood_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseRiskExploitationLikelihoodTest struct { input string expected RiskExploitationLikelihood expectedError error } func TestParseRiskExploitationLikelihood(t *testing.T) { testCases := map[string]ParseRiskExploitationLikelihoodTest{ "unlikely": { input: "unlikely", expected: Unlikely, }, "likely": { input: "likely", expected: Likely, }, "very-likely": { input: "very-likely", expected: VeryLikely, }, "frequent": { input: "frequent", expected: Frequent, }, "default": { input: "", expected: Likely, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unknown risk exploration likelihood value \"unknown\""), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseRiskExploitationLikelihood(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/data_breach_probability.go
pkg/types/data_breach_probability.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type DataBreachProbability int const ( Improbable DataBreachProbability = iota Possible Probable ) func DataBreachProbabilityValues() []TypeEnum { return []TypeEnum{ Improbable, Possible, Probable, } } var DataBreachProbabilityTypeDescription = [...]TypeDescription{ {"improbable", "Improbable"}, {"possible", "Possible"}, {"probable", "Probable"}, } func ParseDataBreachProbability(value string) (dataBreachProbability DataBreachProbability, err error) { return DataBreachProbability(0).Find(value) } func (what DataBreachProbability) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return DataBreachProbabilityTypeDescription[what].Name } func (what DataBreachProbability) Explain() string { return DataBreachProbabilityTypeDescription[what].Description } func (what DataBreachProbability) Title() string { return [...]string{"Improbable", "Possible", "Probable"}[what] } func (what DataBreachProbability) Find(value string) (DataBreachProbability, error) { if len(value) == 0 { return Possible, nil } for index, description := range DataBreachProbabilityTypeDescription { if strings.EqualFold(value, description.Name) { return DataBreachProbability(index), nil } } return DataBreachProbability(0), fmt.Errorf("unknown data breach probability value %q", value) } func (what DataBreachProbability) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *DataBreachProbability) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.Find(text) if findError != nil { return findError } *what = value return nil } func (what DataBreachProbability) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *DataBreachProbability) UnmarshalYAML(node *yaml.Node) error { value, findError := what.Find(node.Value) if findError != nil { return findError } *what = value return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/authentication.go
pkg/types/authentication.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type Authentication int const ( NoneAuthentication Authentication = iota Credentials SessionId Token ClientCertificate TwoFactor Externalized ) func AuthenticationValues() []TypeEnum { return []TypeEnum{ NoneAuthentication, Credentials, SessionId, Token, ClientCertificate, TwoFactor, Externalized, } } var AuthenticationTypeDescription = [...]TypeDescription{ {"none", "No authentication"}, {"credentials", "Username and password, pin or passphrase"}, {"session-id", "A server generated session id with limited life span"}, {"token", "A server generated token. Containing session id, other data and is cryptographically signed"}, {"client-certificate", "A certificate file stored on the client identifying this specific client"}, {"two-factor", "Credentials plus another factor like a physical object (card) or biometrics"}, {"externalized", "Some external company handles authentication"}, } func ParseAuthentication(value string) (authentication Authentication, err error) { return Authentication(0).Find(value) } func (what Authentication) String() string { // NOTE: maintain list also in schema.json for validation in IDEs //return [...]string{"none", "credentials", "session-id", "token", "client-certificate", "two-factor", "externalized"}[what] return AuthenticationTypeDescription[what].Name } func (what Authentication) Explain() string { return AuthenticationTypeDescription[what].Description } func (what Authentication) Find(value string) (Authentication, error) { for index, description := range AuthenticationTypeDescription { if strings.EqualFold(value, description.Name) { return Authentication(index), nil } } return Authentication(0), fmt.Errorf("unknown authentication value %q", value) } func (what Authentication) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *Authentication) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.Find(text) if findError != nil { return findError } *what = value return nil } func (what Authentication) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *Authentication) UnmarshalYAML(node *yaml.Node) error { value, findError := what.Find(node.Value) if findError != nil { return findError } *what = value return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/criticality.go
pkg/types/criticality.go
package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type Criticality int const ( Archive Criticality = iota Operational Important Critical MissionCritical ) func CriticalityValues() []TypeEnum { return []TypeEnum{ Archive, Operational, Important, Critical, MissionCritical, } } func ParseCriticality(value string) (criticality Criticality, err error) { return Criticality(0).Find(value) } var CriticalityTypeDescription = [...]TypeDescription{ {"archive", "Stored, not active"}, {"operational", "If this fails, people will just have an ad-hoc coffee break until it is back"}, {"important", "Issues here results in angry people"}, {"critical", "Failure is really expensive or crippling"}, {"mission-critical", "This must not fail"}, } func (what Criticality) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return CriticalityTypeDescription[what].Name } func (what Criticality) Explain() string { return CriticalityTypeDescription[what].Description } func (what Criticality) AttackerAttractivenessForAsset() float64 { // fibonacci starting at 5 return [...]float64{5, 8, 13, 21, 34}[what] } func (what Criticality) AttackerAttractivenessForProcessedOrStoredData() float64 { // fibonacci starting at 3 return [...]float64{3, 5, 8, 13, 21}[what] } func (what Criticality) AttackerAttractivenessForInOutTransferredData() float64 { // fibonacci starting at 2 return [...]float64{2, 3, 5, 8, 13}[what] } func (what Criticality) RatingStringInScale() string { result := "(rated " if what == Archive { result += "1" } if what == Operational { result += "2" } if what == Important { result += "3" } if what == Critical { result += "4" } if what == MissionCritical { result += "5" } result += " in scale of 5)" return result } func (what Criticality) Find(value string) (Criticality, error) { for index, description := range CriticalityTypeDescription { if strings.EqualFold(value, description.Name) { return Criticality(index), nil } } return Criticality(0), fmt.Errorf("unknown criticality value %q", value) } func (what Criticality) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *Criticality) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.Find(text) if findError != nil { return findError } *what = value return nil } func (what Criticality) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *Criticality) UnmarshalYAML(node *yaml.Node) error { value, findError := what.Find(node.Value) if findError != nil { return findError } *what = value return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/data_format.go
pkg/types/data_format.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type DataFormat int const ( JSON DataFormat = iota XML Serialization File CSV YAML ) func DataFormatValues() []TypeEnum { return []TypeEnum{ JSON, XML, Serialization, File, CSV, YAML, } } var DataFormatTypeDescription = [...]TypeDescription{ {"json", "JSON"}, {"xml", "XML"}, {"serialization", "Serialized program objects"}, {"file", "Specific file types for data"}, {"csv", "CSV"}, {"yaml", "YAML"}, } func ParseDataFormat(value string) (dataFormat DataFormat, err error) { value = strings.TrimSpace(value) for _, candidate := range DataFormatValues() { if candidate.String() == value { return candidate.(DataFormat), err } } return dataFormat, fmt.Errorf("unable to parse into type: %v", value) } func (what DataFormat) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return DataFormatTypeDescription[what].Name } func (what DataFormat) Explain() string { return DataFormatTypeDescription[what].Description } func (what DataFormat) Title() string { return [...]string{"JSON", "XML", "Serialization", "File", "CSV", "YAML"}[what] } func (what DataFormat) Description() string { return [...]string{"JSON marshalled object data", "XML structured data", "Serialization-based object graphs", "File input/uploads", "CSV tabular data", "YAML structured configuration format"}[what] } type ByDataFormatAcceptedSort []DataFormat func (what ByDataFormatAcceptedSort) Len() int { return len(what) } func (what ByDataFormatAcceptedSort) Swap(i, j int) { what[i], what[j] = what[j], what[i] } func (what ByDataFormatAcceptedSort) Less(i, j int) bool { return what[i].String() < what[j].String() } func (what DataFormat) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *DataFormat) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.find(text) if findError != nil { return findError } *what = value return nil } func (what DataFormat) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *DataFormat) UnmarshalYAML(node *yaml.Node) error { value, findError := what.find(node.Value) if findError != nil { return findError } *what = value return nil } func (what DataFormat) find(value string) (DataFormat, error) { for index, description := range DataFormatTypeDescription { if strings.EqualFold(value, description.Name) { return DataFormat(index), nil } } return DataFormat(0), fmt.Errorf("unknown data format value %q", value) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/technical_asset_type.go
pkg/types/technical_asset_type.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type TechnicalAssetType int const ( ExternalEntity TechnicalAssetType = iota Process Datastore ) func TechnicalAssetTypeValues() []TypeEnum { return []TypeEnum{ ExternalEntity, Process, Datastore, } } var TechnicalAssetTypeDescription = [...]TypeDescription{ {"external-entity", "This asset is hosted and managed by a third party"}, {"process", "A software process"}, {"datastore", "This asset stores data"}, } func (what TechnicalAssetType) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return TechnicalAssetTypeDescription[what].Name } func (what TechnicalAssetType) Explain() string { return TechnicalAssetTypeDescription[what].Description } func ParseTechnicalAssetType(value string) (technicalAssetType TechnicalAssetType, err error) { value = strings.TrimSpace(value) for _, candidate := range TechnicalAssetTypeValues() { if candidate.String() == value { return candidate.(TechnicalAssetType), err } } return technicalAssetType, fmt.Errorf("unable to parse into type: %v", value) } func (what TechnicalAssetType) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *TechnicalAssetType) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.find(text) if findError != nil { return findError } *what = value return nil } func (what TechnicalAssetType) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *TechnicalAssetType) UnmarshalYAML(node *yaml.Node) error { value, findError := what.find(node.Value) if findError != nil { return findError } *what = value return nil } func (what TechnicalAssetType) find(value string) (TechnicalAssetType, error) { for index, description := range TechnicalAssetTypeDescription { if strings.EqualFold(value, description.Name) { return TechnicalAssetType(index), nil } } return TechnicalAssetType(0), fmt.Errorf("unknown technical asset type value %q", value) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/trust_boundary_type_test.go
pkg/types/trust_boundary_type_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseTrustBoundaryTest struct { input string expected TrustBoundaryType expectedError error } func TestParseTrustBoundaryType(t *testing.T) { testCases := map[string]ParseTrustBoundaryTest{ "network-on-prem": { input: "network-on-prem", expected: NetworkOnPrem, }, "network-dedicated-hoster": { input: "network-dedicated-hoster", expected: NetworkDedicatedHoster, }, "network-virtual-lan": { input: "network-virtual-lan", expected: NetworkVirtualLAN, }, "network-cloud-provider": { input: "network-cloud-provider", expected: NetworkCloudProvider, }, "network-cloud-security-group": { input: "network-cloud-security-group", expected: NetworkCloudSecurityGroup, }, "network-policy-namespace-isolation": { input: "network-policy-namespace-isolation", expected: NetworkPolicyNamespaceIsolation, }, "execution-environment": { input: "execution-environment", expected: ExecutionEnvironment, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unable to parse into type: unknown"), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseTrustBoundary(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/technical_asset.go
pkg/types/technical_asset.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "sort" ) type TechnicalAsset struct { Id string `json:"id,omitempty" yaml:"id,omitempty"` Title string `json:"title,omitempty" yaml:"title,omitempty"` Description string `json:"description,omitempty" yaml:"description,omitempty"` Usage Usage `json:"usage,omitempty" yaml:"usage,omitempty"` Type TechnicalAssetType `json:"type,omitempty" yaml:"type,omitempty"` Size TechnicalAssetSize `json:"size,omitempty" yaml:"size,omitempty"` Technologies TechnologyList `json:"technologies,omitempty" yaml:"technologies,omitempty"` Machine TechnicalAssetMachine `json:"machine,omitempty" yaml:"machine,omitempty"` Internet bool `json:"internet,omitempty" yaml:"internet,omitempty"` MultiTenant bool `json:"multi_tenant,omitempty" yaml:"multi_tenant,omitempty"` Redundant bool `json:"redundant,omitempty" yaml:"redundant,omitempty"` CustomDevelopedParts bool `json:"custom_developed_parts,omitempty" yaml:"custom_developed_parts,omitempty"` OutOfScope bool `json:"out_of_scope,omitempty" yaml:"out_of_scope,omitempty"` UsedAsClientByHuman bool `json:"used_as_client_by_human,omitempty" yaml:"used_as_client_by_human,omitempty"` Encryption EncryptionStyle `json:"encryption,omitempty" yaml:"encryption,omitempty"` JustificationOutOfScope string `json:"justification_out_of_scope,omitempty" yaml:"justification_out_of_scope,omitempty"` Owner string `json:"owner,omitempty" yaml:"owner,omitempty"` Confidentiality Confidentiality `json:"confidentiality,omitempty" yaml:"confidentiality,omitempty"` Integrity Criticality `json:"integrity,omitempty" yaml:"integrity,omitempty"` Availability Criticality `json:"availability,omitempty" yaml:"availability,omitempty"` JustificationCiaRating string `json:"justification_cia_rating,omitempty" yaml:"justification_cia_rating,omitempty"` Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` DataAssetsProcessed []string `json:"data_assets_processed,omitempty" yaml:"data_assets_processed,omitempty"` DataAssetsStored []string `json:"data_assets_stored,omitempty" yaml:"data_assets_stored,omitempty"` DataFormatsAccepted []DataFormat `json:"data_formats_accepted,omitempty" yaml:"data_formats_accepted,omitempty"` CommunicationLinks []*CommunicationLink `json:"communication_links,omitempty" yaml:"communication_links,omitempty"` DiagramTweakOrder int `json:"diagram_tweak_order,omitempty" yaml:"diagram_tweak_order,omitempty"` RAA float64 `json:"raa,omitempty" yaml:"raa,omitempty"` // will be set by separate calculation step } func (what TechnicalAsset) IsTaggedWithAny(tags ...string) bool { return containsCaseInsensitiveAny(what.Tags, tags...) } func (what TechnicalAsset) HighestSensitivityScore() float64 { return what.Confidentiality.AttackerAttractivenessForAsset() + what.Integrity.AttackerAttractivenessForAsset() + what.Availability.AttackerAttractivenessForAsset() } func (what TechnicalAsset) DataFormatsAcceptedSorted() []DataFormat { result := make([]DataFormat, 0) result = append(result, what.DataFormatsAccepted...) sort.Sort(ByDataFormatAcceptedSort(result)) return result } func (what TechnicalAsset) CommunicationLinksSorted() []*CommunicationLink { result := make([]*CommunicationLink, 0) result = append(result, what.CommunicationLinks...) sort.Sort(ByTechnicalCommunicationLinkTitleSort(result)) return result } type ByTechnicalAssetRAAAndTitleSort []*TechnicalAsset func (what ByTechnicalAssetRAAAndTitleSort) Len() int { return len(what) } func (what ByTechnicalAssetRAAAndTitleSort) Swap(i, j int) { what[i], what[j] = what[j], what[i] } func (what ByTechnicalAssetRAAAndTitleSort) Less(i, j int) bool { raaLeft := what[i].RAA raaRight := what[j].RAA if raaLeft == raaRight { return what[i].Title < what[j].Title } return raaLeft > raaRight } type ByTechnicalAssetTitleSort []*TechnicalAsset func (what ByTechnicalAssetTitleSort) Len() int { return len(what) } func (what ByTechnicalAssetTitleSort) Swap(i, j int) { what[i], what[j] = what[j], what[i] } func (what ByTechnicalAssetTitleSort) Less(i, j int) bool { return what[i].Title < what[j].Title } type ByOrderAndIdSort []*TechnicalAsset func (what ByOrderAndIdSort) Len() int { return len(what) } func (what ByOrderAndIdSort) Swap(i, j int) { what[i], what[j] = what[j], what[i] } func (what ByOrderAndIdSort) Less(i, j int) bool { if what[i].DiagramTweakOrder == what[j].DiagramTweakOrder { return what[i].Id > what[j].Id } return what[i].DiagramTweakOrder < what[j].DiagramTweakOrder } /* // Loops over all data assets (stored and processed by this technical asset) and determines for each // data asset, how many percentage of the data risk is reduced when this technical asset has all risks mitigated. // Example: This means if the data asset is loosing a risk and thus getting from red to amber it counts as 1. // Other example: When only one out of four lines (see data risk mapping) leading to red tech assets are removed by // the mitigations, then this counts as 0.25. The overall sum is returned. func (what TechnicalAsset) QuickWins() float64 { result := 0.0 uniqueDataAssetsStoredAndProcessed := make(map[string]interface{}) for _, dataAssetId := range what.DataAssetsStored { uniqueDataAssetsStoredAndProcessed[dataAssetId] = true } for _, dataAssetId := range what.DataAssetsProcessed { uniqueDataAssetsStoredAndProcessed[dataAssetId] = true } highestSeverity := HighestSeverityStillAtRisk(what.GeneratedRisks()) for dataAssetId, _ := range uniqueDataAssetsStoredAndProcessed { dataAsset := ParsedModelRoot.DataAssets[dataAssetId] if dataAsset.IdentifiedRiskSeverityStillAtRisk() <= highestSeverity { howManySameLevelCausingUsagesOfThisData := 0.0 for techAssetId, risks := range dataAsset.IdentifiedRisksByResponsibleTechnicalAssetId() { if !ParsedModelRoot.TechnicalAssets[techAssetId].OutOfScope { for _, risk := range risks { if len(risk.MostRelevantTechnicalAssetId) > 0 { // T O D O caching of generated risks inside the method? if HighestSeverityStillAtRisk(ParsedModelRoot.TechnicalAssets[risk.MostRelevantTechnicalAssetId].GeneratedRisks()) == highestSeverity { howManySameLevelCausingUsagesOfThisData++ break } } } } } if howManySameLevelCausingUsagesOfThisData > 0 { result += 1.0 / howManySameLevelCausingUsagesOfThisData } } } return result } */ /* type ByTechnicalAssetQuickWinsAndTitleSort []TechnicalAsset func (what ByTechnicalAssetQuickWinsAndTitleSort) Len() int { return len(what) } func (what ByTechnicalAssetQuickWinsAndTitleSort) Swap(i, j int) { what[i], what[j] = what[j], what[i] } func (what ByTechnicalAssetQuickWinsAndTitleSort) Less(i, j int) bool { qwLeft := what[i].QuickWins() qwRight := what[j].QuickWins() if qwLeft == qwRight { return what[i].Title < what[j].Title } return qwLeft > qwRight } */
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/trust_boundary.go
pkg/types/trust_boundary.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types type TrustBoundary struct { Id string `json:"id,omitempty" yaml:"id,omitempty"` Title string `json:"title,omitempty" yaml:"title,omitempty"` Description string `json:"description,omitempty" yaml:"description,omitempty"` Type TrustBoundaryType `json:"type,omitempty" yaml:"type,omitempty"` Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` TechnicalAssetsInside []string `json:"technical_assets_inside,omitempty" yaml:"technical_assets_inside,omitempty"` TrustBoundariesNested []string `json:"trust_boundaries_nested,omitempty" yaml:"trust_boundaries_nested,omitempty"` } func (what TrustBoundary) IsTaggedWithAny(tags ...string) bool { return containsCaseInsensitiveAny(what.Tags, tags...) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/protocol.go
pkg/types/protocol.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type Protocol int const ( UnknownProtocol Protocol = iota HTTP HTTPS WS WSS ReverseProxyWebProtocol ReverseProxyWebProtocolEncrypted MQTT JDBC JdbcEncrypted ODBC OdbcEncrypted SqlAccessProtocol SqlAccessProtocolEncrypted NosqlAccessProtocol NosqlAccessProtocolEncrypted BINARY BinaryEncrypted TEXT TextEncrypted SSH SshTunnel SMTP SmtpEncrypted POP3 Pop3Encrypted IMAP ImapEncrypted FTP FTPS SFTP SCP LDAP LDAPS JMS NFS SMB SmbEncrypted LocalFileAccess NRPE XMPP IIOP IiopEncrypted JRMP JrmpEncrypted InProcessLibraryCall InterProcessCommunication ContainerSpawning ) func ProtocolValues() []TypeEnum { return []TypeEnum{ UnknownProtocol, HTTP, HTTPS, WS, WSS, ReverseProxyWebProtocol, ReverseProxyWebProtocolEncrypted, MQTT, JDBC, JdbcEncrypted, ODBC, OdbcEncrypted, SqlAccessProtocol, SqlAccessProtocolEncrypted, NosqlAccessProtocol, NosqlAccessProtocolEncrypted, BINARY, BinaryEncrypted, TEXT, TextEncrypted, SSH, SshTunnel, SMTP, SmtpEncrypted, POP3, Pop3Encrypted, IMAP, ImapEncrypted, FTP, FTPS, SFTP, SCP, LDAP, LDAPS, JMS, NFS, SMB, SmbEncrypted, LocalFileAccess, NRPE, XMPP, IIOP, IiopEncrypted, JRMP, JrmpEncrypted, InProcessLibraryCall, InterProcessCommunication, ContainerSpawning, } } var ProtocolTypeDescription = [...]TypeDescription{ {"unknown-protocol", "Unknown protocol"}, {"http", "HTTP protocol"}, {"https", "HTTPS protocol (encrypted)"}, {"ws", "WebSocket"}, {"wss", "WebSocket but encrypted"}, {"reverse-proxy-web-protocol", "Protocols used by reverse proxies"}, {"reverse-proxy-web-protocol-encrypted", "Protocols used by reverse proxies but encrypted"}, {"mqtt", "MQTT Message protocol. Encryption via TLS is optional"}, {"jdbc", "Java Database Connectivity"}, {"jdbc-encrypted", "Java Database Connectivity but encrypted"}, {"odbc", "Open Database Connectivity"}, {"odbc-encrypted", "Open Database Connectivity but encrypted"}, {"sql-access-protocol", "SQL access protocol"}, {"sql-access-protocol-encrypted", "SQL access protocol but encrypted"}, {"nosql-access-protocol", "NOSQL access protocol"}, {"nosql-access-protocol-encrypted", "NOSQL access protocol but encrypted"}, {"binary", "Some other binary protocol"}, {"binary-encrypted", "Some other binary protocol, encrypted"}, {"text", "Some other text protocol"}, {"text-encrypted", "Some other text protocol, encrypted"}, {"ssh", "Secure Shell to execute commands"}, {"ssh-tunnel", "Secure Shell as a tunnel"}, {"smtp", "Mail transfer protocol (sending)"}, {"smtp-encrypted", "Mail transfer protocol (sending), encrypted"}, {"pop3", "POP 3 mail fetching"}, {"pop3-encrypted", "POP 3 mail fetching, encrypted"}, {"imap", "IMAP mail sync protocol"}, {"imap-encrypted", "IMAP mail sync protocol, encrypted"}, {"ftp", "File Transfer Protocol"}, {"ftps", "FTP with TLS"}, {"sftp", "FTP on SSH"}, {"scp", "Secure Shell to copy files"}, {"ldap", "Lightweight Directory Access Protocol - User directories"}, {"ldaps", "Lightweight Directory Access Protocol - User directories on TLS"}, {"jms", "Jakarta Messaging"}, {"nfs", "Network File System"}, {"smb", "Server Message Block"}, {"smb-encrypted", "Server Message Block, but encrypted"}, {"local-file-access", "Data files are on the local system"}, {"nrpe", "Nagios Remote Plugin Executor"}, {"xmpp", "Extensible Messaging and Presence Protocol"}, {"iiop", "Internet Inter-ORB Protocol "}, {"iiop-encrypted", "Internet Inter-ORB Protocol , encrypted"}, {"jrmp", "Java Remote Method Protocol"}, {"jrmp-encrypted", "Java Remote Method Protocol, encrypted"}, {"in-process-library-call", "Call to local library"}, {"inter-process-communication", "Communication between processes via system sockets or systems like dbus"}, {"container-spawning", "Spawn a container"}, } func ParseProtocol(value string) (protocol Protocol, err error) { value = strings.TrimSpace(value) for _, candidate := range ProtocolValues() { if candidate.String() == value { return candidate.(Protocol), err } } return protocol, fmt.Errorf("unable to parse into type: %v", value) } func (what Protocol) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return ProtocolTypeDescription[what].Name } func (what Protocol) Explain() string { return ProtocolTypeDescription[what].Description } func (what Protocol) IsProcessLocal() bool { return what == InProcessLibraryCall || what == InterProcessCommunication || what == LocalFileAccess || what == ContainerSpawning } func (what Protocol) IsEncrypted() bool { return what == HTTPS || what == WSS || what == JdbcEncrypted || what == OdbcEncrypted || what == NosqlAccessProtocolEncrypted || what == SqlAccessProtocolEncrypted || what == BinaryEncrypted || what == TextEncrypted || what == SSH || what == SshTunnel || what == FTPS || what == SFTP || what == SCP || what == LDAPS || what == ReverseProxyWebProtocolEncrypted || what == IiopEncrypted || what == JrmpEncrypted || what == SmbEncrypted || what == SmtpEncrypted || what == Pop3Encrypted || what == ImapEncrypted } func (what Protocol) IsPotentialDatabaseAccessProtocol() bool { return what == JdbcEncrypted || what == OdbcEncrypted || what == NosqlAccessProtocolEncrypted || what == SqlAccessProtocolEncrypted || what == JDBC || what == ODBC || what == NosqlAccessProtocol || what == SqlAccessProtocol } func (what Protocol) IsPotentialLaxDatabaseAccessProtocol() bool { // include HTTP for REST-based NoSQL-DBs as well as unknown binary return what == HTTPS || what == HTTP || what == BINARY || what == BinaryEncrypted } func (what Protocol) IsPotentialWebAccessProtocol() bool { return what == HTTP || what == HTTPS || what == WS || what == WSS || what == ReverseProxyWebProtocol || what == ReverseProxyWebProtocolEncrypted } func (what Protocol) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *Protocol) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.find(text) if findError != nil { return findError } *what = value return nil } func (what Protocol) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *Protocol) UnmarshalYAML(node *yaml.Node) error { value, findError := what.find(node.Value) if findError != nil { return findError } *what = value return nil } func (what Protocol) find(value string) (Protocol, error) { for index, description := range ProtocolTypeDescription { if strings.EqualFold(value, description.Name) { return Protocol(index), nil } } return Protocol(0), fmt.Errorf("unknown protocol value %q", value) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/stride.go
pkg/types/stride.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type STRIDE int const ( Spoofing STRIDE = iota Tampering Repudiation InformationDisclosure DenialOfService ElevationOfPrivilege ) func STRIDEValues() []TypeEnum { return []TypeEnum{ Spoofing, Tampering, Repudiation, InformationDisclosure, DenialOfService, ElevationOfPrivilege, } } var StrideTypeDescription = [...]TypeDescription{ {"spoofing", "Spoofing - Authenticity"}, {"tampering", "Tampering - Integrity"}, {"repudiation", "Repudiation - Non-repudiability"}, {"information-disclosure", "Information disclosure - Confidentiality"}, {"denial-of-service", "Denial of service - Availability"}, {"elevation-of-privilege", "Elevation of privilege - Authorization"}, } func ParseSTRIDE(value string) (stride STRIDE, err error) { value = strings.TrimSpace(value) for _, candidate := range STRIDEValues() { if candidate.String() == value { return candidate.(STRIDE), err } } return stride, fmt.Errorf("unable to parse into type: %v", value) } func (what STRIDE) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return StrideTypeDescription[what].Name } func (what STRIDE) Explain() string { return StrideTypeDescription[what].Description } func (what STRIDE) Title() string { return [...]string{"Spoofing", "Tampering", "Repudiation", "Information Disclosure", "Denial of Service", "Elevation of Privilege"}[what] } func (what STRIDE) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *STRIDE) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.find(text) if findError != nil { return findError } *what = value return nil } func (what STRIDE) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *STRIDE) UnmarshalYAML(node *yaml.Node) error { value, findError := what.find(node.Value) if findError != nil { return findError } *what = value return nil } func (what STRIDE) find(value string) (STRIDE, error) { for index, description := range StrideTypeDescription { if strings.EqualFold(value, description.Name) { return STRIDE(index), nil } } return STRIDE(0), fmt.Errorf("unknown STRIDE value %q", value) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk_exploitation_impact_test.go
pkg/types/risk_exploitation_impact_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseRiskExploitationImpactTest struct { input string expected RiskExploitationImpact expectedError error } func TestParseRiskExploitationImpact(t *testing.T) { testCases := map[string]ParseRiskExploitationImpactTest{ "low": { input: "low", expected: LowImpact, }, "medium": { input: "medium", expected: MediumImpact, }, "high": { input: "high", expected: HighImpact, }, "very-high": { input: "very-high", expected: VeryHighImpact, }, "default": { input: "", expected: MediumImpact, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unknown risk exploitation impact value \"unknown\""), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseRiskExploitationImpact(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/encryption_style_test.go
pkg/types/encryption_style_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseEncryptionStyleTest struct { input string expected EncryptionStyle expectedError error } func TestParseEncryptionStyle(t *testing.T) { testCases := map[string]ParseEncryptionStyleTest{ "none": { input: "none", expected: NoneEncryption, }, "transparent": { input: "transparent", expected: Transparent, }, "data-with-symmetric-shared-key": { input: "data-with-symmetric-shared-key", expected: DataWithSymmetricSharedKey, }, "data-with-asymmetric-shared-key": { input: "data-with-asymmetric-shared-key", expected: DataWithAsymmetricSharedKey, }, "data-with-end-user-individual-key": { input: "data-with-end-user-individual-key", expected: DataWithEndUserIndividualKey, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unknown encryption style value \"unknown\""), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseEncryptionStyle(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/technology-map.go
pkg/types/technology-map.go
package types import ( "embed" "fmt" "os" "path/filepath" "gopkg.in/yaml.v3" ) //go:embed technologies.yaml var technologiesLocation embed.FS type TechnologyMap map[string]Technology type technologyMapConfigReader interface { GetAppFolder() string GetTechnologyFilename() string } func (what TechnologyMap) LoadWithConfig(config technologyMapConfigReader, defaultFilename string) error { technologiesFilename := filepath.Join(config.GetAppFolder(), defaultFilename) _, statError := os.Stat(technologiesFilename) if statError == nil { technologiesLoadError := what.LoadFromFile(technologiesFilename) if technologiesLoadError != nil { return fmt.Errorf("error loading technologies: %w", technologiesLoadError) } } else { technologiesLoadError := what.LoadDefault() if technologiesLoadError != nil { return fmt.Errorf("error loading technologies: %w", technologiesLoadError) } } if len(config.GetTechnologyFilename()) > 0 { additionalTechnologies := make(TechnologyMap) loadError := additionalTechnologies.LoadFromFile(config.GetTechnologyFilename()) if loadError != nil { return fmt.Errorf("error loading additional technologies from %q: %v", config.GetTechnologyFilename(), loadError) } for name, technology := range additionalTechnologies { what[name] = technology } } return nil } func (what TechnologyMap) LoadDefault() error { defaultTechnologyFile, readError := technologiesLocation.ReadFile("technologies.yaml") if readError != nil { return fmt.Errorf("error reading default technologies: %w", readError) } unmarshalError := yaml.Unmarshal(defaultTechnologyFile, &what) if unmarshalError != nil { return fmt.Errorf("error parsing default technologies: %w", unmarshalError) } return nil } func (what TechnologyMap) LoadFromFile(filename string) error { // #nosec G304 // fine for potential file for now because used mostly internally or as part of CI/CD data, readError := os.ReadFile(filename) if readError != nil { return fmt.Errorf("error reading technologies from %q: %w", filename, readError) } unmarshalError := yaml.Unmarshal(data, &what) if unmarshalError != nil { return fmt.Errorf("error parsing technologies from %q: %w", filename, unmarshalError) } return nil } func (what TechnologyMap) Save(filename string) error { data, marshalError := yaml.Marshal(what) if marshalError != nil { return fmt.Errorf("error marshalling technologies: %w", marshalError) } writeError := os.WriteFile(filename, data, 0600) if writeError != nil { return fmt.Errorf("error writing %q: %w", filename, writeError) } return nil } func (what TechnologyMap) Copy(from Technology) error { data, marshalError := yaml.Marshal(from) if marshalError != nil { return fmt.Errorf("error marshalling technologies: %w", marshalError) } unmarshalError := yaml.Unmarshal(data, &what) if unmarshalError != nil { return fmt.Errorf("error parsing technologies: %w", unmarshalError) } return nil } func (what TechnologyMap) Get(name string) *Technology { technology, exists := what[name] if !exists { return nil } return &technology } func (what TechnologyMap) GetAll(names ...string) ([]*Technology, error) { technologies := make([]*Technology, 0) for _, name := range names { technicalAssetTechnology := what.Get(name) if technicalAssetTechnology == nil { return nil, fmt.Errorf("unknown technology %q", name) } technologies = append(technologies, technicalAssetTechnology) } return technologies, nil } func (what TechnologyMap) PropagateAttributes() { technologyList := make([]Technology, 0) for name, value := range what { technology := new(Technology) *technology = value technology.Attributes = make(map[string]bool) what.propagateAttributes(name, technology.Attributes) technology.Attributes[name] = true technology.Name = name technologyList = append(technologyList, *technology) } for name := range what { delete(what, name) } for _, technology := range technologyList { what[technology.Name] = technology } } func (what TechnologyMap) propagateAttributes(name string, attributes map[string]bool) { tech, ok := what[name] if ok { what.propagateAttributes(tech.Parent, attributes) } for key, value := range tech.Attributes { attributes[key] = value } } func TechnicalAssetTechnologyValues(cfg technologyMapConfigReader) []TypeEnum { technologies := make(TechnologyMap) _ = technologies.LoadWithConfig(cfg, "technologies.yaml") technologies.PropagateAttributes() values := make([]TypeEnum, 0) for _, technology := range technologies { values = append(values, TypeEnum(technology)) } return values }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk-category.go
pkg/types/risk-category.go
package types import "strings" type RiskCategory struct { ID string `json:"id,omitempty" yaml:"id,omitempty"` Title string `json:"title,omitempty" yaml:"title,omitempty"` Description string `json:"description,omitempty" yaml:"description,omitempty"` Impact string `json:"impact,omitempty" yaml:"impact,omitempty"` ASVS string `json:"asvs,omitempty" yaml:"asvs,omitempty"` CheatSheet string `json:"cheat_sheet,omitempty" yaml:"cheat_sheet,omitempty"` Action string `json:"action,omitempty" yaml:"action,omitempty"` Mitigation string `json:"mitigation,omitempty" yaml:"mitigation,omitempty"` Check string `json:"check,omitempty" yaml:"check,omitempty"` Function RiskFunction `json:"function,omitempty" yaml:"function,omitempty"` STRIDE STRIDE `json:"stride,omitempty" yaml:"stride,omitempty"` DetectionLogic string `json:"detection_logic,omitempty" yaml:"detection_logic,omitempty"` RiskAssessment string `json:"risk_assessment,omitempty" yaml:"risk_assessment,omitempty"` FalsePositives string `json:"false_positives,omitempty" yaml:"false_positives,omitempty"` ModelFailurePossibleReason bool `json:"model_failure_possible_reason,omitempty" yaml:"model_failure_possible_reason,omitempty"` CWE int `json:"cwe,omitempty" yaml:"cwe,omitempty"` } type RiskCategories []*RiskCategory func (what *RiskCategories) Add(categories ...*RiskCategory) bool { for _, newCategory := range categories { for _, existingCategory := range *what { if strings.EqualFold(existingCategory.ID, newCategory.ID) { return false } } *what = append(*what, newCategory) } return true }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/authorization.go
pkg/types/authorization.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type Authorization int const ( NoneAuthorization Authorization = iota TechnicalUser EndUserIdentityPropagation ) func AuthorizationValues() []TypeEnum { return []TypeEnum{ NoneAuthorization, TechnicalUser, EndUserIdentityPropagation, } } var AuthorizationTypeDescription = [...]TypeDescription{ {"none", "No authorization"}, {"technical-user", "Technical user (service-to-service) like DB user credentials"}, {"end-user-identity-propagation", "Identity of end user propagates to this service"}, } func ParseAuthorization(value string) (authorization Authorization, err error) { return Authorization(0).Find(value) } func (what Authorization) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return AuthorizationTypeDescription[what].Name } func (what Authorization) Explain() string { return AuthorizationTypeDescription[what].Description } func (what Authorization) Find(value string) (Authorization, error) { for index, description := range AuthorizationTypeDescription { if strings.EqualFold(value, description.Name) { return Authorization(index), nil } } return Authorization(0), fmt.Errorf("unknown authorization value %q", value) } func (what Authorization) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *Authorization) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.Find(text) if findError != nil { return findError } *what = value return nil } func (what Authorization) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *Authorization) UnmarshalYAML(node *yaml.Node) error { value, findError := what.Find(node.Value) if findError != nil { return findError } *what = value return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/encryption_style.go
pkg/types/encryption_style.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type EncryptionStyle int const ( NoneEncryption EncryptionStyle = iota Transparent DataWithSymmetricSharedKey DataWithAsymmetricSharedKey DataWithEndUserIndividualKey ) func EncryptionStyleValues() []TypeEnum { return []TypeEnum{ NoneEncryption, Transparent, DataWithSymmetricSharedKey, DataWithAsymmetricSharedKey, DataWithEndUserIndividualKey, } } func ParseEncryptionStyle(value string) (encryptionStyle EncryptionStyle, err error) { return EncryptionStyle(0).Find(value) } var EncryptionStyleTypeDescription = [...]TypeDescription{ {"none", "No encryption"}, {"transparent", "Encrypted data at rest"}, {"data-with-symmetric-shared-key", "Both communication partners have the same key. This must be kept secret"}, {"data-with-asymmetric-shared-key", "The key is split into public and private. Those two are shared between partners"}, {"data-with-end-user-individual-key", "The key is (managed) by the end user"}, } func (what EncryptionStyle) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return EncryptionStyleTypeDescription[what].Name } func (what EncryptionStyle) Explain() string { return EncryptionStyleTypeDescription[what].Description } func (what EncryptionStyle) Title() string { return [...]string{"None", "Transparent", "Data with Symmetric Shared Key", "Data with Asymmetric Shared Key", "Data with End-User Individual Key"}[what] } func (what EncryptionStyle) Find(value string) (EncryptionStyle, error) { for index, description := range EncryptionStyleTypeDescription { if strings.EqualFold(value, description.Name) { return EncryptionStyle(index), nil } } return EncryptionStyle(0), fmt.Errorf("unknown encryption style value %q", value) } func (what EncryptionStyle) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *EncryptionStyle) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.Find(text) if findError != nil { return findError } *what = value return nil } func (what EncryptionStyle) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *EncryptionStyle) UnmarshalYAML(node *yaml.Node) error { value, findError := what.Find(node.Value) if findError != nil { return findError } *what = value return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/technical_asset_machine_test.go
pkg/types/technical_asset_machine_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseTechnicalAssetMachineTest struct { input string expected TechnicalAssetMachine expectedError error } func TestParseTechnicalAssetMachine(t *testing.T) { testCases := map[string]ParseTechnicalAssetMachineTest{ "physical": { input: "physical", expected: Physical, }, "virtual": { input: "virtual", expected: Virtual, }, "container": { input: "container", expected: Container, }, "serverless": { input: "serverless", expected: Serverless, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unable to parse into type: unknown"), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseTechnicalAssetMachine(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk_exploitation_impact.go
pkg/types/risk_exploitation_impact.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type RiskExploitationImpact int const ( LowImpact RiskExploitationImpact = iota MediumImpact HighImpact VeryHighImpact ) func RiskExploitationImpactValues() []TypeEnum { return []TypeEnum{ LowImpact, MediumImpact, HighImpact, VeryHighImpact, } } var RiskExploitationImpactTypeDescription = [...]TypeDescription{ {"low", "Low"}, {"medium", "Medium"}, {"high", "High"}, {"very-high", "Very High"}, } func ParseRiskExploitationImpact(value string) (riskExploitationImpact RiskExploitationImpact, err error) { return RiskExploitationImpact(0).Find(value) } func (what RiskExploitationImpact) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return RiskExploitationImpactTypeDescription[what].Name } func (what RiskExploitationImpact) Explain() string { return RiskExploitationImpactTypeDescription[what].Description } func (what RiskExploitationImpact) Title() string { return [...]string{"Low", "Medium", "High", "Very High"}[what] } func (what RiskExploitationImpact) Weight() int { return [...]int{1, 2, 3, 4}[what] } func (what RiskExploitationImpact) Find(value string) (RiskExploitationImpact, error) { if len(value) == 0 { return MediumImpact, nil } for index, description := range RiskExploitationImpactTypeDescription { if strings.EqualFold(value, description.Name) { return RiskExploitationImpact(index), nil } } return RiskExploitationImpact(0), fmt.Errorf("unknown risk exploitation impact value %q", value) } func (what RiskExploitationImpact) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *RiskExploitationImpact) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.Find(text) if findError != nil { return findError } *what = value return nil } func (what RiskExploitationImpact) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *RiskExploitationImpact) UnmarshalYAML(node *yaml.Node) error { value, findError := what.Find(node.Value) if findError != nil { return findError } *what = value return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/data_breach_probability_test.go
pkg/types/data_breach_probability_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseDataBreachProbabilityTest struct { input string expected DataBreachProbability expectedError error } func TestParseDataBreachProbability(t *testing.T) { testCases := map[string]ParseDataBreachProbabilityTest{ "improbable": { input: "improbable", expected: Improbable, }, "possible": { input: "possible", expected: Possible, }, "probable": { input: "probable", expected: Probable, }, "default": { input: "", expected: Possible, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unknown data breach probability value \"unknown\""), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseDataBreachProbability(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/technical_asset_machine.go
pkg/types/technical_asset_machine.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type TechnicalAssetMachine int const ( Physical TechnicalAssetMachine = iota Virtual Container Serverless ) func TechnicalAssetMachineValues() []TypeEnum { return []TypeEnum{ Physical, Virtual, Container, Serverless, } } var TechnicalAssetMachineTypeDescription = [...]TypeDescription{ {"physical", "A physical machine"}, {"virtual", "A virtual machine"}, {"container", "A container"}, {"serverless", "A serverless application"}, } func ParseTechnicalAssetMachine(value string) (technicalAssetMachine TechnicalAssetMachine, err error) { value = strings.TrimSpace(value) for _, candidate := range TechnicalAssetMachineValues() { if candidate.String() == value { return candidate.(TechnicalAssetMachine), err } } return technicalAssetMachine, fmt.Errorf("unable to parse into type: %v", value) } func (what TechnicalAssetMachine) String() string { return TechnicalAssetMachineTypeDescription[what].Name } func (what TechnicalAssetMachine) Explain() string { return TechnicalAssetMachineTypeDescription[what].Description } func (what TechnicalAssetMachine) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *TechnicalAssetMachine) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.find(text) if findError != nil { return findError } *what = value return nil } func (what TechnicalAssetMachine) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *TechnicalAssetMachine) UnmarshalYAML(node *yaml.Node) error { value, findError := what.find(node.Value) if findError != nil { return findError } *what = value return nil } func (what TechnicalAssetMachine) find(value string) (TechnicalAssetMachine, error) { for index, description := range TechnicalAssetMachineTypeDescription { if strings.EqualFold(value, description.Name) { return TechnicalAssetMachine(index), nil } } return TechnicalAssetMachine(0), fmt.Errorf("unknown technical asset machine value %q", value) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/overview.go
pkg/types/overview.go
package types type Overview struct { Description string Images []map[string]string // yes, array of map here, as array keeps the order of the image keys }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/technical_asset_size.go
pkg/types/technical_asset_size.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type TechnicalAssetSize int const ( System TechnicalAssetSize = iota Service Application Component ) func TechnicalAssetSizeValues() []TypeEnum { return []TypeEnum{ System, Service, Application, Component, } } var TechnicalAssetSizeDescription = [...]TypeDescription{ {"system", "A system consists of several services"}, {"service", "A specific service (web, mail, ...)"}, {"application", "A single application"}, {"component", "A component of an application (smaller unit like a microservice)"}, } func (what TechnicalAssetSize) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return TechnicalAssetSizeDescription[what].Name } func (what TechnicalAssetSize) Explain() string { return TechnicalAssetSizeDescription[what].Description } func ParseTechnicalAssetSize(value string) (technicalAssetSize TechnicalAssetSize, err error) { return TechnicalAssetSize(0).Find(value) } func (what TechnicalAssetSize) Find(value string) (TechnicalAssetSize, error) { for index, description := range TechnicalAssetSizeDescription { if strings.EqualFold(value, description.Name) { return TechnicalAssetSize(index), nil } } return TechnicalAssetSize(0), fmt.Errorf("unknown technical asset size value %q", value) } func (what TechnicalAssetSize) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *TechnicalAssetSize) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.Find(text) if findError != nil { return findError } *what = value return nil } func (what TechnicalAssetSize) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *TechnicalAssetSize) UnmarshalYAML(node *yaml.Node) error { value, findError := what.Find(node.Value) if findError != nil { return findError } *what = value return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/authentication_test.go
pkg/types/authentication_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseAuthenticationTest struct { input string expected Authentication expectedError error } func TestParseAuthentication(t *testing.T) { testCases := map[string]ParseAuthenticationTest{ "none": { input: "none", expected: NoneAuthentication, }, "credentials": { input: "credentials", expected: Credentials, }, "session-id": { input: "session-id", expected: SessionId, }, "token": { input: "token", expected: Token, }, "client-certificate": { input: "client-certificate", expected: ClientCertificate, }, "two-factor": { input: "two-factor", expected: TwoFactor, }, "externalized": { input: "externalized", expected: Externalized, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unknown authentication value \"unknown\""), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseAuthentication(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/trust_boundary_type.go
pkg/types/trust_boundary_type.go
package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type TrustBoundaryType int const ( NetworkOnPrem TrustBoundaryType = iota NetworkDedicatedHoster NetworkVirtualLAN NetworkCloudProvider NetworkCloudSecurityGroup NetworkPolicyNamespaceIsolation ExecutionEnvironment ) func TrustBoundaryTypeValues() []TypeEnum { return []TypeEnum{ NetworkOnPrem, NetworkDedicatedHoster, NetworkVirtualLAN, NetworkCloudProvider, NetworkCloudSecurityGroup, NetworkPolicyNamespaceIsolation, ExecutionEnvironment, } } var TrustBoundaryTypeDescription = [...]TypeDescription{ {"network-on-prem", "The whole network is on prem"}, {"network-dedicated-hoster", "The network is at a dedicated hoster"}, {"network-virtual-lan", "Network is a VLAN"}, {"network-cloud-provider", "Network is at a cloud provider"}, {"network-cloud-security-group", "Cloud rules controlling network traffic"}, {"network-policy-namespace-isolation", "Segregation in a Kubernetes cluster"}, {"execution-environment", "Logical group of items (not a protective network boundary in that sense). More like a namespace or another logical group of items"}, } func ParseTrustBoundary(value string) (trustBoundary TrustBoundaryType, err error) { value = strings.TrimSpace(value) for _, candidate := range TrustBoundaryTypeValues() { if candidate.String() == value { return candidate.(TrustBoundaryType), err } } return trustBoundary, fmt.Errorf("unable to parse into type: %v", value) } func (what TrustBoundaryType) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return TrustBoundaryTypeDescription[what].Name } func (what TrustBoundaryType) Explain() string { return TrustBoundaryTypeDescription[what].Description } func (what TrustBoundaryType) IsNetworkBoundary() bool { return what == NetworkOnPrem || what == NetworkDedicatedHoster || what == NetworkVirtualLAN || what == NetworkCloudProvider || what == NetworkCloudSecurityGroup || what == NetworkPolicyNamespaceIsolation } func (what TrustBoundaryType) IsWithinCloud() bool { return what == NetworkCloudProvider || what == NetworkCloudSecurityGroup } func (what TrustBoundaryType) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *TrustBoundaryType) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.find(text) if findError != nil { return findError } *what = value return nil } func (what TrustBoundaryType) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *TrustBoundaryType) UnmarshalYAML(node *yaml.Node) error { value, findError := what.find(node.Value) if findError != nil { return findError } *what = value return nil } func (what TrustBoundaryType) find(value string) (TrustBoundaryType, error) { for index, description := range TrustBoundaryTypeDescription { if strings.EqualFold(value, description.Name) { return TrustBoundaryType(index), nil } } return TrustBoundaryType(0), fmt.Errorf("unknown trust boundary type value %q", value) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/data_format_test.go
pkg/types/data_format_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseDataFormatTest struct { input string expected DataFormat expectedError error } func TestParseDataFormat(t *testing.T) { testCases := map[string]ParseDataFormatTest{ "json": { input: "json", expected: JSON, }, "xml": { input: "xml", expected: XML, }, "serialization": { input: "serialization", expected: Serialization, }, "file": { input: "file", expected: File, }, "csv": { input: "csv", expected: CSV, }, "yaml": { input: "yaml", expected: YAML, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unable to parse into type: unknown"), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseDataFormat(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/stride_test.go
pkg/types/stride_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseStrideTest struct { input string expected STRIDE expectedError error } func TestParseStride(t *testing.T) { testCases := map[string]ParseStrideTest{ "spoofing": { input: "spoofing", expected: Spoofing, }, "tampering": { input: "tampering", expected: Tampering, }, "repudiation": { input: "repudiation", expected: Repudiation, }, "information-disclosure": { input: "information-disclosure", expected: InformationDisclosure, }, "denial-of-service": { input: "denial-of-service", expected: DenialOfService, }, "elevation-of-privilege": { input: "elevation-of-privilege", expected: ElevationOfPrivilege, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unable to parse into type: unknown"), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseSTRIDE(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/data_asset.go
pkg/types/data_asset.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types type DataAsset struct { Id string `yaml:"id,omitempty" json:"id,omitempty"` // TODO: tag here still required? Title string `yaml:"title,omitempty" json:"title,omitempty"` // TODO: tag here still required? Description string `yaml:"description,omitempty" json:"description,omitempty"` // TODO: tag here still required? Usage Usage `yaml:"usage,omitempty" json:"usage,omitempty"` Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"` Origin string `yaml:"origin,omitempty" json:"origin,omitempty"` Owner string `yaml:"owner,omitempty" json:"owner,omitempty"` Quantity Quantity `yaml:"quantity,omitempty" json:"quantity,omitempty"` Confidentiality Confidentiality `yaml:"confidentiality,omitempty" json:"confidentiality,omitempty"` Integrity Criticality `yaml:"integrity,omitempty" json:"integrity,omitempty"` Availability Criticality `yaml:"availability,omitempty" json:"availability,omitempty"` JustificationCiaRating string `yaml:"justification_cia_rating,omitempty" json:"justification_cia_rating,omitempty"` } func (what DataAsset) IsTaggedWithAny(tags ...string) bool { return containsCaseInsensitiveAny(what.Tags, tags...) } type ByDataAssetTitleSort []*DataAsset func (what ByDataAssetTitleSort) Len() int { return len(what) } func (what ByDataAssetTitleSort) Swap(i, j int) { what[i], what[j] = what[j], what[i] } func (what ByDataAssetTitleSort) Less(i, j int) bool { return what[i].Title < what[j].Title }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk-tracking.go
pkg/types/risk-tracking.go
package types type RiskTracking struct { SyntheticRiskId string `json:"synthetic_risk_id,omitempty" yaml:"synthetic_risk_id,omitempty"` Justification string `json:"justification,omitempty" yaml:"justification,omitempty"` Ticket string `json:"ticket,omitempty" yaml:"ticket,omitempty"` CheckedBy string `json:"checked_by,omitempty" yaml:"checked_by,omitempty"` Status RiskStatus `json:"status,omitempty" yaml:"status,omitempty"` Date Date `json:"date,omitempty" yaml:"date,omitempty"` }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/usage_test.go
pkg/types/usage_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseUsageTest struct { input string expected Usage expectedError error } func TestParseUsage(t *testing.T) { testCases := map[string]ParseUsageTest{ "business": { input: "business", expected: Business, }, "devops": { input: "devops", expected: DevOps, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unable to parse into type: unknown"), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseUsage(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/model.go
pkg/types/model.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "regexp" "slices" "sort" "strings" ) // TODO: move model out of types package and // rename model to model or something like this to emphasize that it's just a model // maybe type Model struct { ThreagileVersion string `yaml:"threagile_version,omitempty" json:"threagile_version,omitempty"` Includes []string `yaml:"includes,omitempty" json:"includes,omitempty"` Title string `json:"title,omitempty" yaml:"title,omitempty"` Author *Author `json:"author,omitempty" yaml:"author,omitempty"` Contributors []*Author `yaml:"contributors,omitempty" json:"contributors,omitempty"` Date Date `json:"date,omitempty" yaml:"date,omitempty"` AppDescription *Overview `yaml:"application_description,omitempty" json:"application_description,omitempty"` BusinessOverview *Overview `json:"business_overview,omitempty" yaml:"business_overview,omitempty"` TechnicalOverview *Overview `json:"technical_overview,omitempty" yaml:"technical_overview,omitempty"` BusinessCriticality Criticality `json:"business_criticality,omitempty" yaml:"business_criticality,omitempty"` ManagementSummaryComment string `json:"management_summary_comment,omitempty" yaml:"management_summary_comment,omitempty"` SecurityRequirements map[string]string `json:"security_requirements,omitempty" yaml:"security_requirements,omitempty"` Questions map[string]string `json:"questions,omitempty" yaml:"questions,omitempty"` AbuseCases map[string]string `json:"abuse_cases,omitempty" yaml:"abuse_cases,omitempty"` TagsAvailable []string `json:"tags_available,omitempty" yaml:"tags_available,omitempty"` DataAssets map[string]*DataAsset `json:"data_assets,omitempty" yaml:"data_assets,omitempty"` TechnicalAssets map[string]*TechnicalAsset `json:"technical_assets,omitempty" yaml:"technical_assets,omitempty"` TrustBoundaries map[string]*TrustBoundary `json:"trust_boundaries,omitempty" yaml:"trust_boundaries,omitempty"` SharedRuntimes map[string]*SharedRuntime `json:"shared_runtimes,omitempty" yaml:"shared_runtimes,omitempty"` CustomRiskCategories RiskCategories `json:"custom_risk_categories,omitempty" yaml:"custom_risk_categories,omitempty"` BuiltInRiskCategories RiskCategories `json:"built_in_risk_categories,omitempty" yaml:"built_in_risk_categories,omitempty"` RiskTracking map[string]*RiskTracking `json:"risk_tracking,omitempty" yaml:"risk_tracking,omitempty"` CommunicationLinks map[string]*CommunicationLink `json:"communication_links,omitempty" yaml:"communication_links,omitempty"` AllSupportedTags map[string]bool `json:"all_supported_tags,omitempty" yaml:"all_supported_tags,omitempty"` DiagramTweakNodesep int `json:"diagram_tweak_nodesep,omitempty" yaml:"diagram_tweak_nodesep,omitempty"` DiagramTweakRanksep int `json:"diagram_tweak_ranksep,omitempty" yaml:"diagram_tweak_ranksep,omitempty"` DiagramTweakEdgeLayout string `json:"diagram_tweak_edge_layout,omitempty" yaml:"diagram_tweak_edge_layout,omitempty"` DiagramTweakSuppressEdgeLabels bool `json:"diagram_tweak_suppress_edge_labels,omitempty" yaml:"diagram_tweak_suppress_edge_labels,omitempty"` DiagramTweakLayoutLeftToRight bool `json:"diagram_tweak_layout_left_to_right,omitempty" yaml:"diagram_tweak_layout_left_to_right,omitempty"` DiagramTweakInvisibleConnectionsBetweenAssets []string `json:"diagram_tweak_invisible_connections_between_assets,omitempty" yaml:"diagram_tweak_invisible_connections_between_assets,omitempty"` DiagramTweakSameRankAssets []string `json:"diagram_tweak_same_rank_assets,omitempty" yaml:"diagram_tweak_same_rank_assets,omitempty"` // TODO: those are generated based on items above and needs to be private IncomingTechnicalCommunicationLinksMappedByTargetId map[string][]*CommunicationLink `json:"incoming_technical_communication_links_mapped_by_target_id,omitempty" yaml:"incoming_technical_communication_links_mapped_by_target_id,omitempty"` DirectContainingTrustBoundaryMappedByTechnicalAssetId map[string]*TrustBoundary `json:"direct_containing_trust_boundary_mapped_by_technical_asset_id,omitempty" yaml:"direct_containing_trust_boundary_mapped_by_technical_asset_id,omitempty"` GeneratedRisksByCategory map[string][]*Risk `json:"generated_risks_by_category,omitempty" yaml:"generated_risks_by_category,omitempty"` GeneratedRisksBySyntheticId map[string]*Risk `json:"generated_risks_by_synthetic_id,omitempty" yaml:"generated_risks_by_synthetic_id,omitempty"` } type ProgressReporter interface { Info(a ...any) Warn(a ...any) Error(a ...any) Infof(format string, a ...any) Warnf(format string, a ...any) Errorf(format string, a ...any) } func (model *Model) AddToListOfSupportedTags(tags []string) { for _, tag := range tags { model.AllSupportedTags[tag] = true } } func (model *Model) GetDeferredRiskTrackingDueToWildcardMatching() map[string]*RiskTracking { deferredRiskTrackingDueToWildcardMatching := make(map[string]*RiskTracking) for syntheticRiskId, riskTracking := range model.RiskTracking { if strings.Contains(syntheticRiskId, "*") { // contains a wildcard char deferredRiskTrackingDueToWildcardMatching[syntheticRiskId] = riskTracking } } return deferredRiskTrackingDueToWildcardMatching } func (model *Model) HasNotYetAnyDirectNonWildcardRiskTracking(syntheticRiskId string) bool { if _, ok := model.RiskTracking[syntheticRiskId]; ok { return false } return true } func (model *Model) CheckTags(tags []string, where string) ([]string, error) { var tagsUsed = make([]string, 0) if tags != nil { tagsUsed = make([]string, len(tags)) for i, parsedEntry := range tags { referencedTag := fmt.Sprintf("%v", parsedEntry) err := model.CheckTagExists(referencedTag, where) if err != nil { return nil, err } tagsUsed[i] = referencedTag } } return tagsUsed, nil } func (model *Model) ApplyWildcardRiskTrackingEvaluation(ignoreOrphanedRiskTracking bool, progressReporter ProgressReporter) error { progressReporter.Info("Executing risk tracking evaluation") for syntheticRiskIdPattern, riskTracking := range model.GetDeferredRiskTrackingDueToWildcardMatching() { progressReporter.Infof("Applying wildcard risk tracking for risk id: %v", syntheticRiskIdPattern) foundSome := false var matchingRiskIdExpression = regexp.MustCompile(strings.ReplaceAll(regexp.QuoteMeta(syntheticRiskIdPattern), `\*`, `[^@]+`)) for syntheticRiskId := range model.GeneratedRisksBySyntheticId { if matchingRiskIdExpression.Match([]byte(syntheticRiskId)) && model.HasNotYetAnyDirectNonWildcardRiskTracking(syntheticRiskId) { foundSome = true model.RiskTracking[syntheticRiskId] = &RiskTracking{ SyntheticRiskId: strings.TrimSpace(syntheticRiskId), Justification: riskTracking.Justification, CheckedBy: riskTracking.CheckedBy, Ticket: riskTracking.Ticket, Status: riskTracking.Status, Date: riskTracking.Date, } progressReporter.Infof(" => %v", syntheticRiskId) } } if !foundSome { if ignoreOrphanedRiskTracking { progressReporter.Warnf("Wildcard risk tracking does not match any risk id: %v", syntheticRiskIdPattern) } else { return fmt.Errorf("wildcard risk tracking does not match any risk id: %v", syntheticRiskIdPattern) } } } return nil } func (model *Model) CheckRiskTracking(ignoreOrphanedRiskTracking bool, progressReporter ProgressReporter) error { progressReporter.Info("Checking risk tracking") for _, tracking := range model.RiskTracking { foundSome := false var matchingRiskIdExpression = regexp.MustCompile(strings.ReplaceAll(regexp.QuoteMeta(tracking.SyntheticRiskId), `\*`, `[^@]+`)) for syntheticRiskId := range model.GeneratedRisksBySyntheticId { if matchingRiskIdExpression.Match([]byte(syntheticRiskId)) { foundSome = true } } if !foundSome { if ignoreOrphanedRiskTracking { progressReporter.Infof("Risk tracking references unknown risk (risk id not found): %v", tracking.SyntheticRiskId) } else { return fmt.Errorf("Risk tracking references unknown risk (risk id not found) - you might want to use the option -ignore-orphaned-risk-tracking: %v"+ "\n\nNOTE: For risk tracking each risk-id needs to be defined (the string with the @ sign in it). "+ "These unique risk IDs are visible in the PDF report (the small grey string under each risk), "+ "the Excel (column \"ID\"), as well as the JSON responses. Some risk IDs have only one @ sign in them, "+ "while others multiple. The idea is to allow for unique but still speaking IDs. Therefore each risk instance "+ "creates its individual ID by taking all affected elements causing the risk to be within an @-delimited part. "+ "Using wildcards (the * sign) for parts delimited by @ signs allows to handle groups of certain risks at once. "+ "Best is to lookup the IDs to use in the created Excel file. Alternatively a model macro \"seed-risk-tracking\" "+ "is available that helps in initially seeding the risk tracking part here based on already identified and not yet handled risks", tracking.SyntheticRiskId) } } } return nil } func (model *Model) CheckTagExists(referencedTag, where string) error { if !slices.Contains(model.TagsAvailable, referencedTag) { return fmt.Errorf("missing referenced tag in overall tag list at %v: %v", where, referencedTag) } return nil } func (model *Model) CheckDataAssetTargetExists(referencedAsset, where string) error { if _, ok := model.DataAssets[referencedAsset]; !ok { return fmt.Errorf("missing referenced data asset target at %v: %v", where, referencedAsset) } return nil } func (model *Model) CheckTrustBoundaryExists(referencedId, where string) error { if _, ok := model.TrustBoundaries[referencedId]; !ok { return fmt.Errorf("missing referenced trust boundary at %v: %v", where, referencedId) } return nil } func (model *Model) CheckSharedRuntimeExists(referencedId, where string) error { if _, ok := model.SharedRuntimes[referencedId]; !ok { return fmt.Errorf("missing referenced shared runtime at %v: %v", where, referencedId) } return nil } func (model *Model) CheckCommunicationLinkExists(referencedId, where string) error { if _, ok := model.CommunicationLinks[referencedId]; !ok { return fmt.Errorf("missing referenced communication link at %v: %v", where, referencedId) } return nil } func (model *Model) CheckTechnicalAssetExists(referencedAsset, where string, onlyForTweak bool) error { if _, ok := model.TechnicalAssets[referencedAsset]; !ok { suffix := "" if onlyForTweak { suffix = " (only referenced in diagram tweak)" } return fmt.Errorf("missing referenced technical asset target%v at %v: %v", suffix, where, referencedAsset) } return nil } func (model *Model) CheckNestedTrustBoundariesExisting() error { for _, trustBoundary := range model.TrustBoundaries { for _, nestedId := range trustBoundary.TrustBoundariesNested { if _, ok := model.TrustBoundaries[nestedId]; !ok { return fmt.Errorf("missing referenced nested trust boundary: %v", nestedId) } } } return nil } func CalculateSeverity(likelihood RiskExploitationLikelihood, impact RiskExploitationImpact) RiskSeverity { result := likelihood.Weight() * impact.Weight() if result <= 1 { return LowSeverity } if result <= 3 { return MediumSeverity } if result <= 8 { return ElevatedSeverity } if result <= 12 { return HighSeverity } return CriticalSeverity } func (model *Model) InScopeTechnicalAssets() []*TechnicalAsset { result := make([]*TechnicalAsset, 0) for _, asset := range model.TechnicalAssets { if !asset.OutOfScope { result = append(result, asset) } } return result } func (model *Model) SortedTechnicalAssetIDs() []string { res := make([]string, 0) for id := range model.TechnicalAssets { res = append(res, id) } sort.Strings(res) return res } func (model *Model) TagsActuallyUsed() []string { result := make([]string, 0) for _, tag := range model.TagsAvailable { if len(model.TechnicalAssetsTaggedWithAny(tag)) > 0 || len(model.CommunicationLinksTaggedWithAny(tag)) > 0 || len(model.DataAssetsTaggedWithAny(tag)) > 0 || len(model.TrustBoundariesTaggedWithAny(tag)) > 0 || len(model.SharedRuntimesTaggedWithAny(tag)) > 0 { result = append(result, tag) } } return result } func (model *Model) TechnicalAssetsTaggedWithAny(tags ...string) []*TechnicalAsset { result := make([]*TechnicalAsset, 0) for _, candidate := range model.TechnicalAssets { if candidate.IsTaggedWithAny(tags...) { result = append(result, candidate) } } return result } func (model *Model) CommunicationLinksTaggedWithAny(tags ...string) []*CommunicationLink { result := make([]*CommunicationLink, 0) for _, asset := range model.TechnicalAssets { for _, candidate := range asset.CommunicationLinks { if candidate.IsTaggedWithAny(tags...) { result = append(result, candidate) } } } return result } func (model *Model) DataAssetsTaggedWithAny(tags ...string) []*DataAsset { result := make([]*DataAsset, 0) for _, candidate := range model.DataAssets { if candidate.IsTaggedWithAny(tags...) { result = append(result, candidate) } } return result } func (model *Model) TrustBoundariesTaggedWithAny(tags ...string) []*TrustBoundary { result := make([]*TrustBoundary, 0) for _, candidate := range model.TrustBoundaries { if candidate.IsTaggedWithAny(tags...) { result = append(result, candidate) } } return result } func (model *Model) SharedRuntimesTaggedWithAny(tags ...string) []*SharedRuntime { result := make([]*SharedRuntime, 0) for _, candidate := range model.SharedRuntimes { if candidate.IsTaggedWithAny(tags...) { result = append(result, candidate) } } return result } func (model *Model) OutOfScopeTechnicalAssets() []*TechnicalAsset { assets := make([]*TechnicalAsset, 0) for _, asset := range model.TechnicalAssets { if asset.OutOfScope { assets = append(assets, asset) } } sort.Sort(ByTechnicalAssetTitleSort(assets)) return assets } func (model *Model) FindSharedRuntimeHighestConfidentiality(sharedRuntime *SharedRuntime) Confidentiality { highest := Public for _, id := range sharedRuntime.TechnicalAssetsRunning { techAsset := model.TechnicalAssets[id] if model.HighestProcessedConfidentiality(techAsset) > highest { highest = model.HighestProcessedConfidentiality(techAsset) } } return highest } func (model *Model) FindSharedRuntimeHighestIntegrity(sharedRuntime *SharedRuntime) Criticality { highest := Archive for _, id := range sharedRuntime.TechnicalAssetsRunning { techAssetIntegrity := model.HighestProcessedIntegrity(model.TechnicalAssets[id]) if techAssetIntegrity > highest { highest = techAssetIntegrity } } return highest } func (model *Model) FindSharedRuntimeHighestAvailability(sharedRuntime *SharedRuntime) Criticality { highest := Archive for _, id := range sharedRuntime.TechnicalAssetsRunning { techAssetAvailability := model.HighestProcessedAvailability(model.TechnicalAssets[id]) if techAssetAvailability > highest { highest = techAssetAvailability } } return highest } func (model *Model) FindTrustBoundaryHighestConfidentiality(tb *TrustBoundary) Confidentiality { highest := Public for _, id := range model.RecursivelyAllTechnicalAssetIDsInside(tb) { techAsset := model.TechnicalAssets[id] if model.HighestProcessedConfidentiality(techAsset) > highest { highest = model.HighestProcessedConfidentiality(techAsset) } } return highest } func (model *Model) FindTrustBoundaryHighestIntegrity(tb *TrustBoundary) Criticality { highest := Archive for _, id := range model.RecursivelyAllTechnicalAssetIDsInside(tb) { techAssetIntegrity := model.HighestProcessedIntegrity(model.TechnicalAssets[id]) if techAssetIntegrity > highest { highest = techAssetIntegrity } } return highest } func (model *Model) FindTrustBoundaryHighestAvailability(tb *TrustBoundary) Criticality { highest := Archive for _, id := range model.RecursivelyAllTechnicalAssetIDsInside(tb) { techAssetAvailability := model.HighestProcessedAvailability(model.TechnicalAssets[id]) if techAssetAvailability > highest { highest = techAssetAvailability } } return highest } func (model *Model) RecursivelyAllTechnicalAssetIDsInside(tb *TrustBoundary) []string { result := make([]string, 0) model.addAssetIDsRecursively(tb, &result) return result } func (model *Model) addAssetIDsRecursively(tb *TrustBoundary, result *[]string) { *result = append(*result, tb.TechnicalAssetsInside...) for _, nestedBoundaryID := range tb.TrustBoundariesNested { model.addAssetIDsRecursively(model.TrustBoundaries[nestedBoundaryID], result) } } func (model *Model) AllParentTrustBoundaryIDs(what *TrustBoundary) []string { result := make([]string, 0) model.addTrustBoundaryIDsRecursively(what, &result) return result } func (model *Model) addTrustBoundaryIDsRecursively(what *TrustBoundary, result *[]string) { *result = append(*result, what.Id) parent := model.FindParentTrustBoundary(what) if parent != nil { model.addTrustBoundaryIDsRecursively(parent, result) } } func (model *Model) FindParentTrustBoundary(tb *TrustBoundary) *TrustBoundary { if tb == nil { return nil } for _, candidate := range model.TrustBoundaries { if contains(candidate.TrustBoundariesNested, tb.Id) { return candidate } } return nil } // as in Go ranging over map is random order, range over them in sorted (hence reproducible) way: func (model *Model) SortedRiskCategories() []*RiskCategory { categoryMap := make(map[string]*RiskCategory) for categoryId := range model.GeneratedRisksByCategory { category := model.GetRiskCategory(categoryId) if category != nil { categoryMap[categoryId] = category } } categories := make([]*RiskCategory, 0) for categoryId := range categoryMap { categories = append(categories, categoryMap[categoryId]) } model.SortByRiskCategoryHighestContainingRiskSeveritySortStillAtRisk(categories) return categories } func (model *Model) SortedRisksOfCategory(category *RiskCategory) []*Risk { risks := model.GeneratedRisksByCategoryWithCurrentStatus()[category.ID] SortByRiskSeverity(risks) return risks } func (model *Model) SortByRiskCategoryHighestContainingRiskSeveritySortStillAtRisk(riskCategories []*RiskCategory) { sort.Slice(riskCategories, func(i, j int) bool { risksLeft := ReduceToOnlyStillAtRisk(model.GeneratedRisksByCategory[riskCategories[i].ID]) risksRight := ReduceToOnlyStillAtRisk(model.GeneratedRisksByCategory[riskCategories[j].ID]) highestLeft := HighestSeverityStillAtRisk(risksLeft) highestRight := HighestSeverityStillAtRisk(risksRight) if highestLeft == highestRight { if len(risksLeft) == 0 && len(risksRight) > 0 { return false } if len(risksLeft) > 0 && len(risksRight) == 0 { return true } return riskCategories[i].Title < riskCategories[j].Title } return highestLeft > highestRight }) } func (model *Model) GetRiskCategory(categoryID string) *RiskCategory { if len(model.CustomRiskCategories) > 0 { for _, custom := range model.CustomRiskCategories { if strings.EqualFold(custom.ID, categoryID) { return custom } } } if len(model.BuiltInRiskCategories) > 0 { for _, builtIn := range model.BuiltInRiskCategories { if strings.EqualFold(builtIn.ID, categoryID) { return builtIn } } } return nil } func (model *Model) AllRisks() []*Risk { result := make([]*Risk, 0) for _, risks := range model.GeneratedRisksByCategory { result = append(result, risks...) } return result } func (model *Model) IdentifiedDataBreachProbability(what *DataAsset) DataBreachProbability { highestProbability := Improbable for _, risk := range model.AllRisks() { for _, techAsset := range risk.DataBreachTechnicalAssetIDs { if contains(model.TechnicalAssets[techAsset].DataAssetsProcessed, what.Id) { if risk.DataBreachProbability > highestProbability { highestProbability = risk.DataBreachProbability break } } } } return highestProbability } func (model *Model) IdentifiedDataBreachProbabilityRisks(what *DataAsset) []*Risk { result := make([]*Risk, 0) for _, risk := range model.AllRisks() { for _, techAsset := range risk.DataBreachTechnicalAssetIDs { if contains(model.TechnicalAssets[techAsset].DataAssetsProcessed, what.Id) { result = append(result, risk) break } } } return result } func (model *Model) ProcessedByTechnicalAssetsSorted(what *DataAsset) []*TechnicalAsset { result := make([]*TechnicalAsset, 0) for _, technicalAsset := range model.TechnicalAssets { for _, candidateID := range technicalAsset.DataAssetsProcessed { if candidateID == what.Id { result = append(result, technicalAsset) } } } sort.Sort(ByTechnicalAssetTitleSort(result)) return result } func (model *Model) StoredByTechnicalAssetsSorted(what *DataAsset) []*TechnicalAsset { result := make([]*TechnicalAsset, 0) for _, technicalAsset := range model.TechnicalAssets { for _, candidateID := range technicalAsset.DataAssetsStored { if candidateID == what.Id { result = append(result, technicalAsset) } } } sort.Sort(ByTechnicalAssetTitleSort(result)) return result } func (model *Model) SentViaCommLinksSorted(what *DataAsset) []*CommunicationLink { result := make([]*CommunicationLink, 0) for _, technicalAsset := range model.TechnicalAssets { for _, commLink := range technicalAsset.CommunicationLinks { for _, candidateID := range commLink.DataAssetsSent { if candidateID == what.Id { result = append(result, commLink) } } } } sort.Sort(ByTechnicalCommunicationLinkTitleSort(result)) return result } func (model *Model) ReceivedViaCommLinksSorted(what *DataAsset) []*CommunicationLink { result := make([]*CommunicationLink, 0) for _, technicalAsset := range model.TechnicalAssets { for _, commLink := range technicalAsset.CommunicationLinks { for _, candidateID := range commLink.DataAssetsReceived { if candidateID == what.Id { result = append(result, commLink) } } } } sort.Sort(ByTechnicalCommunicationLinkTitleSort(result)) return result } func (model *Model) HighestCommunicationLinkConfidentiality(what *CommunicationLink) Confidentiality { highest := Public for _, dataId := range what.DataAssetsSent { dataAsset := model.DataAssets[dataId] if dataAsset.Confidentiality > highest { highest = dataAsset.Confidentiality } } for _, dataId := range what.DataAssetsReceived { dataAsset := model.DataAssets[dataId] if dataAsset.Confidentiality > highest { highest = dataAsset.Confidentiality } } return highest } func (model *Model) HighestCommunicationLinkIntegrity(what *CommunicationLink) Criticality { highest := Archive for _, dataId := range what.DataAssetsSent { dataAsset := model.DataAssets[dataId] if dataAsset.Integrity > highest { highest = dataAsset.Integrity } } for _, dataId := range what.DataAssetsReceived { dataAsset := model.DataAssets[dataId] if dataAsset.Integrity > highest { highest = dataAsset.Integrity } } return highest } func (model *Model) HighestCommunicationLinkAvailability(what *CommunicationLink) Criticality { highest := Archive for _, dataId := range what.DataAssetsSent { dataAsset := model.DataAssets[dataId] if dataAsset.Availability > highest { highest = dataAsset.Availability } } for _, dataId := range what.DataAssetsReceived { dataAsset := model.DataAssets[dataId] if dataAsset.Availability > highest { highest = dataAsset.Availability } } return highest } func (model *Model) DataAssetsSentSorted(what *CommunicationLink) []*DataAsset { result := make([]*DataAsset, 0) for _, assetID := range what.DataAssetsSent { result = append(result, model.DataAssets[assetID]) } sort.Sort(byDataAssetTitleSort(result)) return result } func (model *Model) DataAssetsReceivedSorted(what *CommunicationLink) []*DataAsset { result := make([]*DataAsset, 0) for _, assetID := range what.DataAssetsReceived { result = append(result, model.DataAssets[assetID]) } sort.Sort(byDataAssetTitleSort(result)) return result } func (model *Model) GetTechnicalAssetTrustBoundaryId(ta *TechnicalAsset) string { for _, trustBoundary := range model.TrustBoundaries { for _, techAssetInside := range trustBoundary.TechnicalAssetsInside { if techAssetInside == ta.Id { return trustBoundary.Id } } } return "" } func (model *Model) HighestTechnicalAssetConfidentiality(what *TechnicalAsset) Confidentiality { highest := what.Confidentiality highestProcessed := model.HighestProcessedConfidentiality(what) if highest < highestProcessed { highest = highestProcessed } highestStored := model.HighestStoredConfidentiality(what) if highest < highestStored { highest = highestStored } return highest } func (model *Model) HighestProcessedConfidentiality(what *TechnicalAsset) Confidentiality { highest := what.Confidentiality for _, dataId := range what.DataAssetsProcessed { dataAsset := model.DataAssets[dataId] if dataAsset.Confidentiality > highest { highest = dataAsset.Confidentiality } } return highest } func (model *Model) HighestStoredConfidentiality(what *TechnicalAsset) Confidentiality { highest := what.Confidentiality for _, dataId := range what.DataAssetsStored { dataAsset := model.DataAssets[dataId] if dataAsset.Confidentiality > highest { highest = dataAsset.Confidentiality } } return highest } func (model *Model) DataAssetsProcessedSorted(what *TechnicalAsset) []*DataAsset { result := make([]*DataAsset, 0) for _, assetID := range what.DataAssetsProcessed { result = append(result, model.DataAssets[assetID]) } sort.Sort(ByDataAssetTitleSort(result)) return result } func (model *Model) DataAssetsStoredSorted(what *TechnicalAsset) []*DataAsset { result := make([]*DataAsset, 0) for _, assetID := range what.DataAssetsStored { result = append(result, model.DataAssets[assetID]) } sort.Sort(ByDataAssetTitleSort(result)) return result } func (model *Model) HighestIntegrity(what *TechnicalAsset) Criticality { highest := what.Integrity highestProcessed := model.HighestProcessedIntegrity(what) if highest < highestProcessed { highest = highestProcessed } highestStored := model.HighestStoredIntegrity(what) if highest < highestStored { highest = highestStored } return highest } func (model *Model) HighestProcessedIntegrity(what *TechnicalAsset) Criticality { highest := what.Integrity for _, dataId := range what.DataAssetsProcessed { dataAsset := model.DataAssets[dataId] if dataAsset.Integrity > highest { highest = dataAsset.Integrity } } return highest } func (model *Model) HighestStoredIntegrity(what *TechnicalAsset) Criticality { highest := what.Integrity for _, dataId := range what.DataAssetsStored { dataAsset := model.DataAssets[dataId] if dataAsset.Integrity > highest { highest = dataAsset.Integrity } } return highest } func (model *Model) HighestAvailability(what *TechnicalAsset) Criticality { highest := what.Availability highestProcessed := model.HighestProcessedAvailability(what) if highest < highestProcessed { highest = highestProcessed } highestStored := model.HighestStoredAvailability(what) if highest < highestStored { highest = highestStored } return highest } func (model *Model) HighestProcessedAvailability(what *TechnicalAsset) Criticality { highest := what.Availability for _, dataId := range what.DataAssetsProcessed { dataAsset := model.DataAssets[dataId] if dataAsset.Availability > highest { highest = dataAsset.Availability } } return highest } func (model *Model) HighestStoredAvailability(what *TechnicalAsset) Criticality { highest := what.Availability for _, dataId := range what.DataAssetsStored { dataAsset := model.DataAssets[dataId] if dataAsset.Availability > highest { highest = dataAsset.Availability } } return highest } func (model *Model) HasDirectConnection(what *TechnicalAsset, otherAssetId string) bool { for _, dataFlow := range model.IncomingTechnicalCommunicationLinksMappedByTargetId[what.Id] { if dataFlow.SourceId == otherAssetId { return true } } // check both directions, hence two times, just reversed for _, dataFlow := range model.IncomingTechnicalCommunicationLinksMappedByTargetId[otherAssetId] { if dataFlow.SourceId == what.Id { return true } } return false } func (model *Model) GeneratedRisks(what *TechnicalAsset) []*Risk { resultingRisks := make([]*Risk, 0) if len(model.SortedRiskCategories()) == 0 { fmt.Println("Uh, strange, no risks generated (yet?) and asking for them by tech asset...") } for _, category := range model.SortedRiskCategories() { risks := model.SortedRisksOfCategory(category) for _, risk := range risks { if risk.MostRelevantTechnicalAssetId == what.Id { resultingRisks = append(resultingRisks, risk) } } } SortByRiskSeverity(resultingRisks) return resultingRisks } func (model *Model) GetRiskTracking(what *Risk) *RiskTracking { // TODO: Unify function naming regarding Get etc. if riskTracking, ok := model.RiskTracking[what.SyntheticId]; ok { return riskTracking } return nil } func (model *Model) GetRiskTrackingWithDefault(what *Risk) RiskTracking { // TODO: Unify function naming regarding Get etc. if riskTracking, ok := model.RiskTracking[what.SyntheticId]; ok { return *riskTracking } return RiskTracking{} } func (model *Model) IsRiskTracked(what *Risk) bool { if _, ok := model.RiskTracking[what.SyntheticId]; ok { return true } return false } func (model *Model) GeneratedRisksByCategoryWithCurrentStatus() map[string][]*Risk { generatedRisksByCategoryWithCurrentStatus := model.GeneratedRisksByCategory for catId, risks := range generatedRisksByCategoryWithCurrentStatus { for idx, risk := range risks { riskTracked, ok := model.RiskTracking[risk.SyntheticId] if ok { generatedRisksByCategoryWithCurrentStatus[catId][idx].RiskStatus = riskTracked.Status } } } return generatedRisksByCategoryWithCurrentStatus }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/authorization_test.go
pkg/types/authorization_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseAuthorizationTest struct { input string expected Authorization expectedError error } func TestParseAuthorization(t *testing.T) { testCases := map[string]ParseAuthorizationTest{ "none": { input: "none", expected: NoneAuthorization, }, "technical-user": { input: "technical-user", expected: TechnicalUser, }, "end-user-identity-propagation": { input: "end-user-identity-propagation", expected: EndUserIdentityPropagation, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unknown authorization value \"unknown\""), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseAuthorization(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/types.go
pkg/types/types.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types // TypeDescription contains a name for a type and its description type TypeDescription struct { Name string Description string } type TypeEnum interface { String() string Explain() string } func GetBuiltinTypeValues(cfg technologyMapConfigReader) map[string][]TypeEnum { return map[string][]TypeEnum{ "Authentication": AuthenticationValues(), "Authorization": AuthorizationValues(), "Confidentiality": ConfidentialityValues(), "Criticality (for integrity and availability)": CriticalityValues(), "Data Breach Probability": DataBreachProbabilityValues(), "Data Format": DataFormatValues(), "Encryption": EncryptionStyleValues(), "Protocol": ProtocolValues(), "Quantity": QuantityValues(), "Risk Exploitation Impact": RiskExploitationImpactValues(), "Risk Exploitation Likelihood": RiskExploitationLikelihoodValues(), "Risk Function": RiskFunctionValues(), "Risk Severity": RiskSeverityValues(), "Risk Status": RiskStatusValues(), "STRIDE": STRIDEValues(), "Technical Asset Machine": TechnicalAssetMachineValues(), "Technical Asset Size": TechnicalAssetSizeValues(), "Technical Asset Technology": TechnicalAssetTechnologyValues(cfg), "Technical Asset Type": TechnicalAssetTypeValues(), "Trust Boundary Type": TrustBoundaryTypeValues(), "Usage": UsageValues(), } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/usage.go
pkg/types/usage.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type Usage int const ( Business Usage = iota DevOps ) func UsageValues() []TypeEnum { return []TypeEnum{ Business, DevOps, } } func ParseUsage(value string) (usage Usage, err error) { value = strings.TrimSpace(value) for _, candidate := range UsageValues() { if candidate.String() == value { return candidate.(Usage), err } } return usage, fmt.Errorf("unable to parse into type: %v", value) } var UsageTypeDescription = [...]TypeDescription{ {"business", "This system is operational and does business tasks"}, {"devops", "This system is for development and/or deployment or other operational tasks"}, } func (what Usage) String() string { // NOTE: maintain list also in schema.json for validation in IDEs //return [...]string{"business", "devops"}[what] return UsageTypeDescription[what].Name } func (what Usage) Explain() string { return UsageTypeDescription[what].Description } func (what Usage) Title() string { return [...]string{"Business", "DevOps"}[what] } func (what Usage) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *Usage) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.find(text) if findError != nil { return findError } *what = value return nil } func (what Usage) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *Usage) UnmarshalYAML(node *yaml.Node) error { value, findError := what.find(node.Value) if findError != nil { return findError } *what = value return nil } func (what Usage) find(value string) (Usage, error) { for index, description := range UsageTypeDescription { if strings.EqualFold(value, description.Name) { return Usage(index), nil } } return Usage(0), fmt.Errorf("unknown usage type value %q", value) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk_severity_test.go
pkg/types/risk_severity_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseRiskSeverityTest struct { input string expected RiskSeverity expectedError error } func TestParseRiskSeverity(t *testing.T) { testCases := map[string]ParseRiskSeverityTest{ "low": { input: "low", expected: LowSeverity, }, "medium": { input: "medium", expected: MediumSeverity, }, "elevated": { input: "elevated", expected: ElevatedSeverity, }, "high": { input: "high", expected: HighSeverity, }, "critical": { input: "critical", expected: CriticalSeverity, }, "default": { input: "", expected: MediumSeverity, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unknown risk severity value \"unknown\""), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseRiskSeverity(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/quantity_test.go
pkg/types/quantity_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "testing" "gopkg.in/yaml.v3" "github.com/stretchr/testify/assert" ) type ParseQuantityTest struct { input string expected Quantity expectedError error } func TestParseQuantity(t *testing.T) { testCases := map[string]ParseQuantityTest{ "very-few": { input: "very-few", expected: VeryFew, }, "few": { input: "few", expected: Few, }, "many": { input: "many", expected: Many, }, "very-many": { input: "very-many", expected: VeryMany, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unknown quantity value \"unknown\""), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseQuantity(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } } type MarshalQuantityTest struct { input Quantity expected string } func TestMarshal(t *testing.T) { testCases := map[string]MarshalQuantityTest{ "very-few": { input: VeryFew, expected: "very-few", }, "few": { input: Few, expected: "few", }, "many": { input: Many, expected: "many", }, "very-many": { input: VeryMany, expected: "very-many", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { var v struct { Quantity Quantity } v.Quantity = testCase.input bytes, err := yaml.Marshal(v) assert.NoError(t, err) assert.Equal(t, fmt.Sprintf("quantity: %s\n", testCase.expected), string(bytes)) jsonBytes, err := json.Marshal(v) assert.NoError(t, err) assert.Equal(t, fmt.Sprintf("{\"Quantity\":\"%s\"}", testCase.expected), string(jsonBytes)) }) } } type UnmarshalQuantityTest struct { input string expected Quantity } func TestUnmarshal(t *testing.T) { testCases := map[string]UnmarshalQuantityTest{ "very-few": { input: "very-few", expected: VeryFew, }, "few": { input: "few", expected: Few, }, "many": { input: "many", expected: Many, }, "very-many": { input: "very-many", expected: VeryMany, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { yamlString := fmt.Sprintf("quantity: %s\n", testCase.input) var v struct { Quantity Quantity } err := yaml.Unmarshal([]byte(yamlString), &v) assert.NoError(t, err) assert.Equal(t, testCase.expected, v.Quantity) jsonString := fmt.Sprintf("{\"Quantity\":\"%s\"}", testCase.input) err = json.Unmarshal([]byte(jsonString), &v) assert.NoError(t, err) assert.Equal(t, testCase.expected, v.Quantity) }) } } func TestUnmarshallJsonError(t *testing.T) { var v struct { Quantity Quantity } err := json.Unmarshal([]byte("{\"Quantity\":\"unknown\"}"), &v) assert.Error(t, err) } func TestUnmarshallYamlError(t *testing.T) { var v struct { Quantity Quantity } err := yaml.Unmarshal([]byte("quantity: unknown\n"), &v) assert.Error(t, err) } func TestQuantityValues(t *testing.T) { assert.Equal(t, []TypeEnum{VeryFew, Few, Many, VeryMany}, QuantityValues()) } func TestQuantityString(t *testing.T) { assert.Equal(t, "very-few", VeryFew.String()) assert.Equal(t, "few", Few.String()) assert.Equal(t, "many", Many.String()) assert.Equal(t, "very-many", VeryMany.String()) } func TestQuantityExplain(t *testing.T) { assert.Equal(t, "Very few", VeryFew.Explain()) assert.Equal(t, "Few", Few.Explain()) assert.Equal(t, "Many", Many.Explain()) assert.Equal(t, "Very many", VeryMany.Explain()) } func TestQuantityTitle(t *testing.T) { assert.Equal(t, "very few", VeryFew.Title()) assert.Equal(t, "few", Few.Title()) assert.Equal(t, "many", Many.Title()) assert.Equal(t, "very many", VeryMany.Title()) } func TestQuantityQuantityFactor(t *testing.T) { assert.Equal(t, float64(1), VeryFew.QuantityFactor()) assert.Equal(t, float64(2), Few.QuantityFactor()) assert.Equal(t, float64(3), Many.QuantityFactor()) assert.Equal(t, float64(5), VeryMany.QuantityFactor()) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/technology.go
pkg/types/technology.go
package types import "strings" const ( AI = "ai" ApplicationServer = "application-server" ArtifactRegistry = "artifact-registry" BatchProcessing = "batch-processing" BigDataPlatform = "big-data-platform" BlockStorage = "block-storage" Browser = "browser" BuildPipeline = "build-pipeline" ClientSystem = "client-system" CLI = "cli" CMS = "cms" CodeInspectionPlatform = "code-inspection-platform" ContainerPlatform = "container-platform" DataLake = "data-lake" Database = "database" Desktop = "desktop" DevOpsClient = "devops-client" EJB = "ejb" ERP = "erp" EventListener = "event-listener" FileServer = "file-server" Function = "function" Gateway = "gateway" HSM = "hsm" IdentityProvider = "identity-provider" IdentityStoreDatabase = "identity-store-database" IdentityStoreLDAP = "identity-store-ldap" IDS = "ids" IoTDevice = "iot-device" IPS = "ips" LDAPServer = "ldap-server" Library = "library" LoadBalancer = "load-balancer" LocalFileSystem = "local-file-system" MailServer = "mail-server" Mainframe = "mainframe" MessageQueue = "message-queue" MobileApp = "mobile-app" Monitoring = "monitoring" ReportEngine = "report-engine" ReverseProxy = "reverse-proxy" Scheduler = "scheduler" SearchEngine = "search-engine" SearchIndex = "search-index" ServiceMesh = "service-mesh" ServiceRegistry = "service-registry" SourcecodeRepository = "sourcecode-repository" StreamProcessing = "stream-processing" Task = "task" Tool = "tool" UnknownTechnology = "unknown-technology" Vault = "vault" WAF = "waf" WebApplication = "web-application" WebServer = "web-server" WebServiceREST = "web-service-rest" WebServiceSOAP = "web-service-soap" ) type Technology struct { Name string `yaml:"name,omitempty" json:"name,omitempty"` Parent string `yaml:"parent,omitempty" json:"parent,omitempty"` Description string `yaml:"description,omitempty" json:"description,omitempty"` Aliases []string `yaml:"aliases,omitempty" json:"aliases,omitempty"` Examples []string `yaml:"examples,omitempty" json:"examples,omitempty"` Attributes map[string]bool `yaml:"attributes,omitempty" json:"attributes,omitempty"` } func (what Technology) String() string { return what.Name } func (what Technology) Is(name string) bool { return strings.EqualFold(what.Name, name) } func (what Technology) GetAttribute(name string) bool { value, valueOk := what.Attributes[name] if valueOk { return value } return false } func (what Technology) Explain() string { text := make([]string, 0) text = append(text, what.Description) if len(what.Aliases) > 0 { text = append(text, "Aliases: ") for _, alias := range what.Aliases { text = append(text, " - "+alias) } } if len(what.Examples) > 0 { text = append(text, "Examples: ") for _, example := range what.Examples { text = append(text, " - "+example) } } return strings.Join(text, "\n") }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk_function.go
pkg/types/risk_function.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type RiskFunction int const ( BusinessSide RiskFunction = iota Architecture Development Operations ) func RiskFunctionValues() []TypeEnum { return []TypeEnum{ BusinessSide, Architecture, Development, Operations, } } var RiskFunctionTypeDescription = [...]TypeDescription{ {"business-side", "Business"}, {"architecture", "Architecture"}, {"development", "Development"}, {"operations", "Operations"}, } func ParseRiskFunction(value string) (riskFunction RiskFunction, err error) { value = strings.TrimSpace(value) for _, candidate := range RiskFunctionValues() { if candidate.String() == value { return candidate.(RiskFunction), err } } return riskFunction, fmt.Errorf("unable to parse into type: %v", value) } func (what RiskFunction) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return RiskFunctionTypeDescription[what].Name } func (what RiskFunction) Explain() string { return RiskFunctionTypeDescription[what].Description } func (what RiskFunction) Title() string { return [...]string{"Business Side", "Architecture", "Development", "Operations"}[what] } func (what RiskFunction) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *RiskFunction) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.find(text) if findError != nil { return findError } *what = value return nil } func (what RiskFunction) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *RiskFunction) UnmarshalYAML(node *yaml.Node) error { value, findError := what.find(node.Value) if findError != nil { return findError } *what = value return nil } func (what RiskFunction) find(value string) (RiskFunction, error) { for index, description := range RiskFunctionTypeDescription { if strings.EqualFold(value, description.Name) { return RiskFunction(index), nil } } return RiskFunction(0), fmt.Errorf("unknown risk function value %q", value) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/author.go
pkg/types/author.go
package types type Author struct { Name string Contact string Homepage string }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/technical_asset_size_test.go
pkg/types/technical_asset_size_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseTechnicalAssetSizeTest struct { input string expected TechnicalAssetSize expectedError error } func TestParseTechnicalAssetSize(t *testing.T) { testCases := map[string]ParseTechnicalAssetSizeTest{ "service": { input: "service", expected: Service, }, "system": { input: "system", expected: System, }, "application": { input: "application", expected: Application, }, "component": { input: "component", expected: Component, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unknown technical asset size value \"unknown\""), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseTechnicalAssetSize(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/confidentiality_test.go
pkg/types/confidentiality_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseConfidentialityTest struct { input string expected Confidentiality expectedError error } func TestParseConfidenitality(t *testing.T) { testCases := map[string]ParseConfidentialityTest{ "public": { input: "public", expected: Public, }, "internal": { input: "internal", expected: Internal, }, "restricted": { input: "restricted", expected: Restricted, }, "confidential": { input: "confidential", expected: Confidential, }, "strictly-confidential": { input: "strictly-confidential", expected: StrictlyConfidential, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unknown confidentiality value \"unknown\""), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseConfidentiality(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/date.go
pkg/types/date.go
package types import ( "time" "gopkg.in/yaml.v3" ) const ( jsonDateFormat = `"2006-01-02"` yamlDateFormat = `2006-01-02` ) type Date struct { time.Time } func (what Date) MarshalJSON() ([]byte, error) { return []byte(what.Format(jsonDateFormat)), nil } func (what *Date) UnmarshalJSON(bytes []byte) error { date, parseError := time.Parse(jsonDateFormat, string(bytes)) if parseError != nil { return parseError } what.Time = date return nil } func (what Date) MarshalYAML() (interface{}, error) { return what.Format(yamlDateFormat), nil } func (what *Date) UnmarshalYAML(node *yaml.Node) error { date, parseError := time.Parse(yamlDateFormat, node.Value) if parseError != nil { return parseError } what.Time = date return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/quantity.go
pkg/types/quantity.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type Quantity int const ( VeryFew Quantity = iota Few Many VeryMany ) func QuantityValues() []TypeEnum { return []TypeEnum{ VeryFew, Few, Many, VeryMany, } } func ParseQuantity(value string) (quantity Quantity, err error) { return Quantity(0).Find(value) } var QuantityTypeDescription = [...]TypeDescription{ {"very-few", "Very few"}, {"few", "Few"}, {"many", "Many"}, {"very-many", "Very many"}, } func (what Quantity) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return QuantityTypeDescription[what].Name } func (what Quantity) Explain() string { return QuantityTypeDescription[what].Description } func (what Quantity) Title() string { return [...]string{"very few", "few", "many", "very many"}[what] } func (what Quantity) QuantityFactor() float64 { // fibonacci starting at 1 return [...]float64{1, 2, 3, 5}[what] } func (what Quantity) Find(value string) (Quantity, error) { for index, description := range QuantityTypeDescription { if strings.EqualFold(value, description.Name) { return Quantity(index), nil } } return Quantity(0), fmt.Errorf("unknown quantity value %q", value) } func (what Quantity) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *Quantity) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.Find(text) if findError != nil { return findError } *what = value return nil } func (what Quantity) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *Quantity) UnmarshalYAML(node *yaml.Node) error { value, findError := what.Find(node.Value) if findError != nil { return findError } *what = value return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk_status_test.go
pkg/types/risk_status_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseRiskStatusTest struct { input string expected RiskStatus expectedError error } func TestParseRiskStatus(t *testing.T) { testCases := map[string]ParseRiskStatusTest{ "unchecked": { input: "unchecked", expected: Unchecked, }, "in-discussion": { input: "in-discussion", expected: InDiscussion, }, "accepted": { input: "accepted", expected: Accepted, }, "in-progress": { input: "in-progress", expected: InProgress, }, "mitigated": { input: "mitigated", expected: Mitigated, }, "false-positive": { input: "false-positive", expected: FalsePositive, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unable to parse into type: unknown"), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseRiskStatus(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk_exploitation_likelihood.go
pkg/types/risk_exploitation_likelihood.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" ) type RiskExploitationLikelihood int const ( Unlikely RiskExploitationLikelihood = iota Likely VeryLikely Frequent ) func RiskExploitationLikelihoodValues() []TypeEnum { return []TypeEnum{ Unlikely, Likely, VeryLikely, Frequent, } } var RiskExploitationLikelihoodTypeDescription = [...]TypeDescription{ {"unlikely", "Unlikely"}, {"likely", "Likely"}, {"very-likely", "Very-Likely"}, {"frequent", "Frequent"}, } func ParseRiskExploitationLikelihood(value string) (riskExploitationLikelihood RiskExploitationLikelihood, err error) { return RiskExploitationLikelihood(0).Find(value) } func (what RiskExploitationLikelihood) String() string { // NOTE: maintain list also in schema.json for validation in IDEs return RiskExploitationLikelihoodTypeDescription[what].Name } func (what RiskExploitationLikelihood) Explain() string { return RiskExploitationLikelihoodTypeDescription[what].Description } func (what RiskExploitationLikelihood) Title() string { return [...]string{"Unlikely", "Likely", "Very Likely", "Frequent"}[what] } func (what RiskExploitationLikelihood) Weight() int { return [...]int{1, 2, 3, 4}[what] } func (what RiskExploitationLikelihood) Find(value string) (RiskExploitationLikelihood, error) { if len(value) == 0 { return Likely, nil } for index, description := range RiskExploitationLikelihoodTypeDescription { if strings.EqualFold(value, description.Name) { return RiskExploitationLikelihood(index), nil } } return RiskExploitationLikelihood(0), fmt.Errorf("unknown risk exploration likelihood value %q", value) } func (what RiskExploitationLikelihood) MarshalJSON() ([]byte, error) { return json.Marshal(what.String()) } func (what *RiskExploitationLikelihood) UnmarshalJSON(data []byte) error { var text string unmarshalError := json.Unmarshal(data, &text) if unmarshalError != nil { return unmarshalError } value, findError := what.Find(text) if findError != nil { return findError } *what = value return nil } func (what RiskExploitationLikelihood) MarshalYAML() (interface{}, error) { return what.String(), nil } func (what *RiskExploitationLikelihood) UnmarshalYAML(node *yaml.Node) error { value, findError := what.Find(node.Value) if findError != nil { return findError } *what = value return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risk-rule.go
pkg/types/risk-rule.go
package types type RiskRule interface { Category() *RiskCategory SupportedTags() []string GenerateRisks(*Model) ([]*Risk, error) } type RiskRules map[string]RiskRule func (what RiskRules) Merge(rules RiskRules) RiskRules { for key, value := range rules { what[key] = value } return what }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/technology-list.go
pkg/types/technology-list.go
package types import "strings" const ( MayContainSecrets = "may_contain_secrets" // #nosec G101 // this is a constant for a string NoAuthenticationRequired = "no_authentication_required" IsHighValueTarget = "high_value_target" IsWebService = "web_service" IsIdentityStore = "identity_store" IsNoNetworkSegmentationRequired = "no_network_segmentation_required" IsIdentityRelated = "identity_related" IsFileStorage = "file_storage" IsSearchRelated = "search_related" IsVulnerableToQueryInjection = "vulnerable_to_query_injection" IsNoStorageAtRest = "no_storage_at_rest" IsHTTPInternetAccessOK = "http_internet_access_ok" IsFTPInternetAccessOK = "ftp_internet_access_ok" IsSecurityControlRelated = "security_control_related" IsUnprotectedCommunicationsTolerated = "unprotected_communications_tolerated" IsUnnecessaryDataTolerated = "unnecessary_data_tolerated" IsCloseToHighValueTargetsTolerated = "close_to_high_value_targets_tolerated" IsClient = "client" IsUsuallyAbleToPropagateIdentityToOutgoingTargets = "propagate_identity_to_outgoing_targets" IsLessProtectedType = "less_protected_type" IsUsuallyProcessingEndUserRequests = "processing_end_user_requests" IsUsuallyStoringEndUserData = "storing_end_user_data" IsExclusivelyFrontendRelated = "frontend_related" IsExclusivelyBackendRelated = "backend_related" IsDevelopmentRelevant = "development_relevant" IsTrafficForwarding = "traffic_forwarding" IsEmbeddedComponent = "embedded_component" ) type TechnologyList []*Technology func (what TechnologyList) String() string { names := make([]string, len(what)) for i, technology := range what { names[i] = technology.String() } return strings.Join(names, "/") } func (what TechnologyList) GetAttribute(firstAttribute string, otherAttributes ...string) bool { for _, attribute := range append(otherAttributes, firstAttribute) { for _, technology := range what { if technology.GetAttribute(attribute) { return true } } } return false } func (what TechnologyList) IsUnknown() bool { if what.GetAttribute(UnknownTechnology) { return true } for _, technology := range what { if len(technology.Attributes) > 0 { return false } } return true }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/criticality_test.go
pkg/types/criticality_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseCriticalityTest struct { input string expected Criticality expectedError error } func TestParseCriticality(t *testing.T) { testCases := map[string]ParseCriticalityTest{ "archive": { input: "archive", expected: Archive, }, "operational": { input: "operational", expected: Operational, }, "important": { input: "important", expected: Important, }, "critical": { input: "critical", expected: Critical, }, "mission-critical": { input: "mission-critical", expected: MissionCritical, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unknown criticality value \"unknown\""), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseCriticality(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/communication_link.go
pkg/types/communication_link.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types type CommunicationLink struct { Id string `json:"id,omitempty" yaml:"id,omitempty"` SourceId string `json:"source_id,omitempty" yaml:"source_id,omitempty"` TargetId string `json:"target_id,omitempty" yaml:"target_id,omitempty"` Title string `json:"title,omitempty" yaml:"title,omitempty"` Description string `json:"description,omitempty" yaml:"description,omitempty"` Protocol Protocol `json:"protocol,omitempty" yaml:"protocol,omitempty"` Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` VPN bool `json:"vpn,omitempty" yaml:"vpn,omitempty"` IpFiltered bool `json:"ip_filtered,omitempty" yaml:"ip_filtered,omitempty"` Readonly bool `json:"readonly,omitempty" yaml:"readonly,omitempty"` Authentication Authentication `json:"authentication,omitempty" yaml:"authentication,omitempty"` Authorization Authorization `json:"authorization,omitempty" yaml:"authorization,omitempty"` Usage Usage `json:"usage,omitempty" yaml:"usage,omitempty"` DataAssetsSent []string `json:"data_assets_sent,omitempty" yaml:"data_assets_sent,omitempty"` DataAssetsReceived []string `json:"data_assets_received,omitempty" yaml:"data_assets_received,omitempty"` DiagramTweakWeight int `json:"diagram_tweak_weight,omitempty" yaml:"diagram_tweak_weight,omitempty"` DiagramTweakConstraint bool `json:"diagram_tweak_constraint,omitempty" yaml:"diagram_tweak_constraint,omitempty"` } func (what CommunicationLink) IsTaggedWithAny(tags ...string) bool { return containsCaseInsensitiveAny(what.Tags, tags...) } func (what CommunicationLink) IsBidirectional() bool { return len(what.DataAssetsSent) > 0 && len(what.DataAssetsReceived) > 0 } type ByTechnicalCommunicationLinkIdSort []*CommunicationLink func (what ByTechnicalCommunicationLinkIdSort) Len() int { return len(what) } func (what ByTechnicalCommunicationLinkIdSort) Swap(i, j int) { what[i], what[j] = what[j], what[i] } func (what ByTechnicalCommunicationLinkIdSort) Less(i, j int) bool { return what[i].Id > what[j].Id } type ByTechnicalCommunicationLinkTitleSort []*CommunicationLink func (what ByTechnicalCommunicationLinkTitleSort) Len() int { return len(what) } func (what ByTechnicalCommunicationLinkTitleSort) Swap(i, j int) { what[i], what[j] = what[j], what[i] } func (what ByTechnicalCommunicationLinkTitleSort) Less(i, j int) bool { return what[i].Title > what[j].Title }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/model/runner.go
pkg/model/runner.go
// TODO: consider moving to internal package model import ( "bytes" "fmt" "gopkg.in/yaml.v3" "os" "os/exec" ) type runner struct { Filename string Parameters []string In any Out any ErrorOutput string } func (p *runner) Load(filename string) (*runner, error) { *p = runner{ Filename: filename, } fileInfo, statError := os.Stat(filename) if statError != nil { return p, statError } if !fileInfo.Mode().IsRegular() { return p, fmt.Errorf("run %q is not a regular file", filename) } return p, nil } func (p *runner) Run(in any, out any, parameters ...string) error { *p = runner{ Filename: p.Filename, Parameters: parameters, In: in, Out: out, } plugin := exec.Command(p.Filename, p.Parameters...) // #nosec G204 stdin, stdinError := plugin.StdinPipe() if stdinError != nil { return stdinError } defer func() { _ = stdin.Close() }() var stdoutBuf bytes.Buffer plugin.Stdout = &stdoutBuf var stderrBuf bytes.Buffer plugin.Stderr = &stderrBuf startError := plugin.Start() if startError != nil { return startError } inData, inError := yaml.Marshal(p.In) if inError != nil { return fmt.Errorf("error encoding input data: %w", inError) } _, writeError := stdin.Write(inData) if writeError != nil { return writeError } inCloseError := stdin.Close() if inCloseError != nil { return inCloseError } waitError := plugin.Wait() p.ErrorOutput = stderrBuf.String() if waitError != nil { return fmt.Errorf("%w: %v", waitError, p.ErrorOutput) } stdout := stdoutBuf.Bytes() unmarshalError := yaml.Unmarshal(stdout, p.Out) if unmarshalError != nil { return unmarshalError } // _ = os.WriteFile(fmt.Sprintf("%v.yaml", rand.Int31()), stdout, 0644) return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/model/raa.go
pkg/model/raa.go
package model import ( "sort" "github.com/threagile/threagile/pkg/types" ) func applyRAA(input *types.Model, progressReporter types.ProgressReporter) string { progressReporter.Infof("Applying RAA calculation") for techAssetID, techAsset := range input.TechnicalAssets { aa := calculateAttackerAttractiveness(input, techAsset) aa += calculatePivotingNeighbourEffectAdjustment(input, techAsset) techAsset.RAA = calculateRelativeAttackerAttractiveness(input, aa) input.TechnicalAssets[techAssetID] = techAsset } // return intro text (for reporting etc., can be short summary-like) return "For each technical asset the <b>\"Relative Attacker Attractiveness\"</b> (RAA) value was calculated " + "in percent. The higher the RAA, the more interesting it is for an attacker to compromise the asset. The calculation algorithm takes " + "the sensitivity ratings and quantities of stored and processed data into account as well as the communication links of the " + "technical asset. Neighbouring assets to high-value RAA targets might receive an increase in their RAA value when they have " + "a communication link towards that target (\"Pivoting-Factor\").<br><br>The following lists all technical assets sorted by their " + "RAA value from highest (most attacker attractive) to lowest. This list can be used to prioritize on efforts relevant for the most " + "attacker-attractive technical assets:" } // set the concrete value in relation to the minimum and maximum of all func calculateRelativeAttackerAttractiveness(input *types.Model, attractiveness float64) float64 { var attackerAttractivenessMinimum, attackerAttractivenessMaximum, spread float64 = 0, 0, 0 if attackerAttractivenessMinimum == 0 || attackerAttractivenessMaximum == 0 { attackerAttractivenessMinimum, attackerAttractivenessMaximum = 9223372036854775807, -9223372036854775808 // determine (only one time required) the min/max of all // first create them in memory (see the link replacement below for nested trust boundaries) - otherwise in Go ranging over map is random order // range over them in sorted (hence re-producible) way: keys := make([]string, 0) for k := range input.TechnicalAssets { keys = append(keys, k) } sort.Strings(keys) for _, key := range keys { techAsset := input.TechnicalAssets[key] if calculateAttackerAttractiveness(input, techAsset) > attackerAttractivenessMaximum { attackerAttractivenessMaximum = calculateAttackerAttractiveness(input, techAsset) } if calculateAttackerAttractiveness(input, techAsset) < attackerAttractivenessMinimum { attackerAttractivenessMinimum = calculateAttackerAttractiveness(input, techAsset) } } if !(attackerAttractivenessMinimum < attackerAttractivenessMaximum) { attackerAttractivenessMaximum = attackerAttractivenessMinimum + 1 } spread = attackerAttractivenessMaximum - attackerAttractivenessMinimum } // calculate the percent value of the value within the defined min/max range value := attractiveness - attackerAttractivenessMinimum percent := value / spread * 100 if percent <= 0 { percent = 1 // since 0 suggests no attacks at all } return percent } // increase the RAA (relative attacker attractiveness) by one third (1/3) of the delta to the highest outgoing neighbour (if positive delta) func calculatePivotingNeighbourEffectAdjustment(input *types.Model, techAsset *types.TechnicalAsset) float64 { if techAsset.OutOfScope { return 0 } adjustment := 0.0 for _, commLink := range techAsset.CommunicationLinks { outgoingNeighbour := input.TechnicalAssets[commLink.TargetId] //if outgoingNeighbour.getTrustBoundary() == techAsset.getTrustBoundary() { // same trust boundary delta := calculateRelativeAttackerAttractiveness(input, calculateAttackerAttractiveness(input, outgoingNeighbour)) - calculateRelativeAttackerAttractiveness(input, calculateAttackerAttractiveness(input, techAsset)) if delta > 0 { potentialIncrease := delta / 3 //fmt.Println("Positive delta from", techAsset.ID, "to", outgoingNeighbour.ID, "is", delta, "yields to pivoting neighbour effect of an increase of", potentialIncrease) if potentialIncrease > adjustment { adjustment = potentialIncrease } } //} } return adjustment } // The sum of all CIAs of the asset itself (fibonacci scale) plus the sum of the comm-links' transferred CIAs // Multiplied by the quantity values of the data asset for C and I (not A) func calculateAttackerAttractiveness(input *types.Model, techAsset *types.TechnicalAsset) float64 { if techAsset.OutOfScope { return 0 } var score = 0.0 score += techAsset.Confidentiality.AttackerAttractivenessForAsset() score += techAsset.Integrity.AttackerAttractivenessForAsset() score += techAsset.Availability.AttackerAttractivenessForAsset() for _, dataAssetProcessed := range techAsset.DataAssetsProcessed { dataAsset := input.DataAssets[dataAssetProcessed] score += dataAsset.Confidentiality.AttackerAttractivenessForProcessedOrStoredData() * dataAsset.Quantity.QuantityFactor() score += dataAsset.Integrity.AttackerAttractivenessForProcessedOrStoredData() * dataAsset.Quantity.QuantityFactor() score += dataAsset.Availability.AttackerAttractivenessForProcessedOrStoredData() } // NOTE: Assuming all stored data is also processed, this effectively scores stored data twice for _, dataAssetStored := range techAsset.DataAssetsStored { dataAsset := input.DataAssets[dataAssetStored] score += dataAsset.Confidentiality.AttackerAttractivenessForProcessedOrStoredData() * dataAsset.Quantity.QuantityFactor() score += dataAsset.Integrity.AttackerAttractivenessForProcessedOrStoredData() * dataAsset.Quantity.QuantityFactor() score += dataAsset.Availability.AttackerAttractivenessForProcessedOrStoredData() } // NOTE: To send or receive data effectively is processing that data and it's questionable if the attractiveness increases further for _, dataFlow := range techAsset.CommunicationLinks { for _, dataAssetSent := range dataFlow.DataAssetsSent { dataAsset := input.DataAssets[dataAssetSent] score += dataAsset.Confidentiality.AttackerAttractivenessForInOutTransferredData() * dataAsset.Quantity.QuantityFactor() score += dataAsset.Integrity.AttackerAttractivenessForInOutTransferredData() * dataAsset.Quantity.QuantityFactor() score += dataAsset.Availability.AttackerAttractivenessForInOutTransferredData() } for _, dataAssetReceived := range dataFlow.DataAssetsReceived { dataAsset := input.DataAssets[dataAssetReceived] score += dataAsset.Confidentiality.AttackerAttractivenessForInOutTransferredData() * dataAsset.Quantity.QuantityFactor() score += dataAsset.Integrity.AttackerAttractivenessForInOutTransferredData() * dataAsset.Quantity.QuantityFactor() score += dataAsset.Availability.AttackerAttractivenessForInOutTransferredData() } } if techAsset.Technologies.GetAttribute(types.LoadBalancer, types.ReverseProxy) { score = score / 5.5 } else if techAsset.Technologies.GetAttribute(types.Monitoring) { score = score / 5 } else if techAsset.Technologies.GetAttribute(types.ContainerPlatform) { score = score * 5 } else if techAsset.Technologies.GetAttribute(types.Vault) { score = score * 2 } else if techAsset.Technologies.GetAttribute(types.BuildPipeline, types.SourcecodeRepository, types.ArtifactRegistry) { score = score * 2 } else if techAsset.Technologies.GetAttribute(types.IdentityProvider, types.IdentityStoreDatabase, types.IdentityStoreLDAP) { score = score * 2.5 } else if techAsset.Type == types.Datastore { score = score * 2 } if techAsset.MultiTenant { score = score * 1.5 } return score }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/model/custom-risk-category.go
pkg/model/custom-risk-category.go
package model import ( "fmt" "path/filepath" "strings" "github.com/threagile/threagile/pkg/types" ) type CustomRiskCategory struct { types.RiskCategory `json:"risk_category" yaml:"risk_category,omitempty"` Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` runner *runner } func (what *CustomRiskCategory) Init(category *types.RiskCategory, tags []string) *CustomRiskCategory { *what = CustomRiskCategory{ RiskCategory: *category, Tags: tags, } return what } func (what *CustomRiskCategory) Category() *types.RiskCategory { return &what.RiskCategory } func (what *CustomRiskCategory) SupportedTags() []string { return what.Tags } func (what *CustomRiskCategory) GenerateRisks(parsedModel *types.Model) ([]*types.Risk, error) { if what.runner == nil { return nil, nil } generatedRisks := make([]*types.Risk, 0) runError := what.runner.Run(parsedModel, &generatedRisks, "-generate-risks") if runError != nil { return nil, fmt.Errorf("failed to generate risks for custom risk rule %q: %w", what.runner.Filename, runError) } return generatedRisks, nil } func LoadCustomRiskRules(pluginDir string, pluginFiles []string, reporter types.ProgressReporter) types.RiskRules { customRiskRuleList := make([]string, 0) customRiskRules := make(types.RiskRules) if len(pluginFiles) > 0 { reporter.Info("Loading custom risk rules:", strings.Join(pluginFiles, ", ")) for _, pluginFile := range pluginFiles { if len(pluginFile) > 0 { newRunner, loadError := new(runner).Load(filepath.Join(pluginDir, pluginFile)) if loadError != nil { reporter.Error(fmt.Sprintf("WARNING: Custom risk rule %q not loaded: %v\n", pluginFile, loadError)) } risk := new(CustomRiskCategory) runError := newRunner.Run(nil, &risk, "-get-info") if runError != nil { reporter.Error(fmt.Sprintf("WARNING: Failed to get info for custom risk rule %q: %v\n", pluginFile, runError)) } risk.runner = newRunner customRiskRules[risk.ID] = risk customRiskRuleList = append(customRiskRuleList, risk.ID) reporter.Info("Custom risk rule loaded:", risk.ID) } } reporter.Info("Loaded custom risk rules:", strings.Join(customRiskRuleList, ", ")) } return customRiskRules }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/model/read.go
pkg/model/read.go
package model import ( "fmt" "gopkg.in/yaml.v3" "os" "path/filepath" "strings" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" ) type ReadResult struct { ModelInput *input.Model ParsedModel *types.Model IntroTextRAA string BuiltinRiskRules types.RiskRules CustomRiskRules types.RiskRules } type explainRiskConfig interface { } type explainRiskReporter interface { } func (what ReadResult) ExplainRisk(cfg explainRiskConfig, risk string, reporter explainRiskReporter) error { return fmt.Errorf("not implemented") } // TODO: consider about splitting this function into smaller ones for better reusability type configReader interface { GetBuildTimestamp() string GetVerbose() bool GetInteractive() bool GetAppFolder() string GetPluginFolder() string GetDataFolder() string GetOutputFolder() string GetServerFolder() string GetTempFolder() string GetKeyFolder() string GetInputFile() string GetImportedInputFile() string GetDataFlowDiagramFilenamePNG() string GetDataAssetDiagramFilenamePNG() string GetDataFlowDiagramFilenameDOT() string GetDataAssetDiagramFilenameDOT() string GetReportFilename() string GetExcelRisksFilename() string GetExcelTagsFilename() string GetJsonRisksFilename() string GetJsonTechnicalAssetsFilename() string GetJsonStatsFilename() string GetTemplateFilename() string GetTechnologyFilename() string GetRiskRulePlugins() []string GetSkipRiskRules() []string GetExecuteModelMacro() string GetRiskExcelConfigHideColumns() []string GetRiskExcelConfigSortByColumns() []string GetRiskExcelConfigWidthOfColumns() map[string]float64 GetServerMode() bool GetDiagramDPI() int GetServerPort() int GetGraphvizDPI() int GetMaxGraphvizDPI() int GetBackupHistoryFilesToKeep() int GetAddModelTitle() bool GetAddLegend() bool GetKeepDiagramSourceFiles() bool GetIgnoreOrphanedRiskTracking() bool GetThreagileVersion() string GetProgressReporter() types.ProgressReporter } func ReadAndAnalyzeModel(config configReader, builtinRiskRules types.RiskRules, progressReporter types.ProgressReporter) (*ReadResult, error) { progressReporter.Infof("Writing into output directory: %v", config.GetOutputFolder()) progressReporter.Infof("Parsing model: %v", config.GetInputFile()) customRiskRules := LoadCustomRiskRules(config.GetPluginFolder(), config.GetRiskRulePlugins(), progressReporter) modelInput := new(input.Model).Defaults() loadError := modelInput.Load(config.GetInputFile()) if loadError != nil { return nil, fmt.Errorf("unable to load model yaml: %w", loadError) } result, analysisError := AnalyzeModel(modelInput, config, builtinRiskRules, customRiskRules, progressReporter) if analysisError == nil { writeToFile("model yaml", result.ParsedModel, config.GetImportedInputFile(), progressReporter) } return result, analysisError } func AnalyzeModel(modelInput *input.Model, config configReader, builtinRiskRules types.RiskRules, customRiskRules types.RiskRules, progressReporter types.ProgressReporter) (*ReadResult, error) { parsedModel, parseError := ParseModel(config, modelInput, builtinRiskRules, customRiskRules) if parseError != nil { return nil, fmt.Errorf("unable to parse model yaml: %w", parseError) } introTextRAA := applyRAA(parsedModel, progressReporter) applyRiskGeneration(parsedModel, builtinRiskRules.Merge(customRiskRules), config.GetSkipRiskRules(), progressReporter) err := parsedModel.ApplyWildcardRiskTrackingEvaluation(config.GetIgnoreOrphanedRiskTracking(), progressReporter) if err != nil { return nil, fmt.Errorf("unable to apply wildcard risk tracking evaluation: %w", err) } err = parsedModel.CheckRiskTracking(config.GetIgnoreOrphanedRiskTracking(), progressReporter) if err != nil { return nil, fmt.Errorf("unable to check risk tracking: %w", err) } return &ReadResult{ ModelInput: modelInput, ParsedModel: parsedModel, IntroTextRAA: introTextRAA, BuiltinRiskRules: builtinRiskRules, CustomRiskRules: customRiskRules, }, nil } func applyRiskGeneration(parsedModel *types.Model, rules types.RiskRules, skipRiskRules []string, progressReporter types.ProgressReporter) { progressReporter.Info("Applying risk generation") skippedRules := make(map[string]bool) if len(skipRiskRules) > 0 { for _, id := range skipRiskRules { skippedRules[id] = true } } for id, rule := range rules { _, ok := skippedRules[id] if ok { progressReporter.Infof("Skipping risk rule: %v", id) delete(skippedRules, id) continue } parsedModel.AddToListOfSupportedTags(rule.SupportedTags()) newRisks, riskError := rule.GenerateRisks(parsedModel) if riskError != nil { progressReporter.Warnf("Error generating risks for %q: %v", id, riskError) continue } if len(newRisks) > 0 { parsedModel.GeneratedRisksByCategory[id] = newRisks } } if len(skippedRules) > 0 { keys := make([]string, 0) for k := range skippedRules { keys = append(keys, k) } if len(keys) > 0 { progressReporter.Infof("Unknown risk rules to skip: %v", keys) } } // save also in map keyed by synthetic risk-id for _, category := range parsedModel.SortedRiskCategories() { someRisks := parsedModel.SortedRisksOfCategory(category) for _, risk := range someRisks { parsedModel.GeneratedRisksBySyntheticId[strings.ToLower(risk.SyntheticId)] = risk } } } func writeToFile(name string, item any, filename string, progressReporter types.ProgressReporter) { if item == nil { return } if filename == "" { return } exported, exportError := yaml.Marshal(item) if exportError != nil { progressReporter.Warnf("Unable to export %v: %v", name, exportError) return } _ = os.MkdirAll(filepath.Dir(filename), 0750) writeError := os.WriteFile(filename, exported, 0600) if writeError != nil { progressReporter.Warnf("Unable to write %v to %q: %v", name, filename, writeError) return } progressReporter.Infof("Wrote %v to %q", name, filename) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/model/parse_test.go
pkg/model/parse_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package model import ( "testing" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" ) func TestDefaultInputNotFail(t *testing.T) { parsedModel, err := ParseModel(&mockConfig{}, createInputModel(make(map[string]input.TechnicalAsset), make(map[string]input.DataAsset)), make(types.RiskRules), make(types.RiskRules)) assert.NoError(t, err) assert.NotNil(t, parsedModel) } func TestInferConfidentiality_NotSet_NoOthers_ExpectTODO(t *testing.T) { ta := make(map[string]input.TechnicalAsset) da := make(map[string]input.DataAsset) _, err := ParseModel(&mockConfig{}, createInputModel(ta, da), make(types.RiskRules), make(types.RiskRules)) // TODO: rename test and check if everyone agree that by default it should be public if there are no other assets assert.NoError(t, err) } func TestInferConfidentiality_ExpectHighestConfidentiality(t *testing.T) { ta := make(map[string]input.TechnicalAsset) da := make(map[string]input.DataAsset) daConfidentialConfidentiality := createDataAsset(types.Confidential, types.Critical, types.Critical) da[daConfidentialConfidentiality.ID] = daConfidentialConfidentiality daRestrictedConfidentiality := createDataAsset(types.Restricted, types.Important, types.Important) da[daRestrictedConfidentiality.ID] = daRestrictedConfidentiality daPublicConfidentiality := createDataAsset(types.Public, types.Archive, types.Archive) da[daPublicConfidentiality.ID] = daPublicConfidentiality taWithConfidentialConfidentialityDataAsset := createTechnicalAsset(types.Internal, types.Operational, types.Operational) taWithConfidentialConfidentialityDataAsset.DataAssetsProcessed = append(taWithConfidentialConfidentialityDataAsset.DataAssetsProcessed, daConfidentialConfidentiality.ID) ta[taWithConfidentialConfidentialityDataAsset.ID] = taWithConfidentialConfidentialityDataAsset taWithRestrictedConfidentialityDataAsset := createTechnicalAsset(types.Internal, types.Operational, types.Operational) taWithRestrictedConfidentialityDataAsset.DataAssetsProcessed = append(taWithRestrictedConfidentialityDataAsset.DataAssetsProcessed, daRestrictedConfidentiality.ID) ta[taWithRestrictedConfidentialityDataAsset.ID] = taWithRestrictedConfidentialityDataAsset taWithPublicConfidentialityDataAsset := createTechnicalAsset(types.Internal, types.Operational, types.Operational) taWithPublicConfidentialityDataAsset.DataAssetsProcessed = append(taWithPublicConfidentialityDataAsset.DataAssetsProcessed, daPublicConfidentiality.ID) ta[taWithPublicConfidentialityDataAsset.ID] = taWithPublicConfidentialityDataAsset parsedModel, err := ParseModel(&mockConfig{}, createInputModel(ta, da), make(types.RiskRules), make(types.RiskRules)) assert.NoError(t, err) assert.Equal(t, types.Confidential, parsedModel.TechnicalAssets[taWithConfidentialConfidentialityDataAsset.ID].Confidentiality) assert.Equal(t, types.Restricted, parsedModel.TechnicalAssets[taWithRestrictedConfidentialityDataAsset.ID].Confidentiality) assert.Equal(t, types.Internal, parsedModel.TechnicalAssets[taWithPublicConfidentialityDataAsset.ID].Confidentiality) } func TestInferIntegrity_NotSet_NoOthers_ExpectTODO(t *testing.T) { ta := make(map[string]input.TechnicalAsset) da := make(map[string]input.DataAsset) _, err := ParseModel(&mockConfig{}, createInputModel(ta, da), make(types.RiskRules), make(types.RiskRules)) // TODO: rename test and check if everyone agree that by default it should be public if there are no other assets assert.NoError(t, err) } func TestInferIntegrity_ExpectHighestIntegrity(t *testing.T) { ta := make(map[string]input.TechnicalAsset) da := make(map[string]input.DataAsset) daCriticalIntegrity := createDataAsset(types.Confidential, types.Critical, types.Critical) da[daCriticalIntegrity.ID] = daCriticalIntegrity daImportantIntegrity := createDataAsset(types.Restricted, types.Important, types.Important) da[daImportantIntegrity.ID] = daImportantIntegrity daArchiveIntegrity := createDataAsset(types.Public, types.Archive, types.Archive) da[daArchiveIntegrity.ID] = daArchiveIntegrity taWithCriticalIntegrityDataAsset := createTechnicalAsset(types.Internal, types.Operational, types.Operational) taWithCriticalIntegrityDataAsset.DataAssetsProcessed = append(taWithCriticalIntegrityDataAsset.DataAssetsProcessed, daCriticalIntegrity.ID) ta[taWithCriticalIntegrityDataAsset.ID] = taWithCriticalIntegrityDataAsset taWithImportantIntegrityDataAsset := createTechnicalAsset(types.Internal, types.Operational, types.Operational) taWithImportantIntegrityDataAsset.DataAssetsProcessed = append(taWithImportantIntegrityDataAsset.DataAssetsProcessed, daImportantIntegrity.ID) ta[taWithImportantIntegrityDataAsset.ID] = taWithImportantIntegrityDataAsset taWithArchiveIntegrityDataAsset := createTechnicalAsset(types.Internal, types.Operational, types.Operational) taWithArchiveIntegrityDataAsset.DataAssetsProcessed = append(taWithArchiveIntegrityDataAsset.DataAssetsProcessed, daArchiveIntegrity.ID) ta[taWithArchiveIntegrityDataAsset.ID] = taWithArchiveIntegrityDataAsset parsedModel, err := ParseModel(&mockConfig{}, createInputModel(ta, da), make(types.RiskRules), make(types.RiskRules)) assert.NoError(t, err) assert.Equal(t, types.Critical, parsedModel.TechnicalAssets[taWithCriticalIntegrityDataAsset.ID].Integrity) assert.Equal(t, types.Important, parsedModel.TechnicalAssets[taWithImportantIntegrityDataAsset.ID].Integrity) assert.Equal(t, types.Operational, parsedModel.TechnicalAssets[taWithArchiveIntegrityDataAsset.ID].Integrity) } func TestInferAvailability_NotSet_NoOthers_ExpectTODO(t *testing.T) { ta := make(map[string]input.TechnicalAsset) da := make(map[string]input.DataAsset) _, err := ParseModel(&mockConfig{}, createInputModel(ta, da), make(types.RiskRules), make(types.RiskRules)) assert.NoError(t, err) } func TestInferAvailability_ExpectHighestAvailability(t *testing.T) { ta := make(map[string]input.TechnicalAsset) da := make(map[string]input.DataAsset) daCriticalAvailability := createDataAsset(types.Confidential, types.Critical, types.Critical) da[daCriticalAvailability.ID] = daCriticalAvailability daImportantAvailability := createDataAsset(types.Restricted, types.Important, types.Important) da[daImportantAvailability.ID] = daImportantAvailability daArchiveAvailability := createDataAsset(types.Public, types.Archive, types.Archive) da[daArchiveAvailability.ID] = daArchiveAvailability taWithCriticalAvailabilityDataAsset := createTechnicalAsset(types.Internal, types.Operational, types.Operational) taWithCriticalAvailabilityDataAsset.DataAssetsProcessed = append(taWithCriticalAvailabilityDataAsset.DataAssetsProcessed, daCriticalAvailability.ID) ta[taWithCriticalAvailabilityDataAsset.ID] = taWithCriticalAvailabilityDataAsset taWithImportantAvailabilityDataAsset := createTechnicalAsset(types.Internal, types.Operational, types.Operational) taWithImportantAvailabilityDataAsset.DataAssetsProcessed = append(taWithImportantAvailabilityDataAsset.DataAssetsProcessed, daImportantAvailability.ID) ta[taWithImportantAvailabilityDataAsset.ID] = taWithImportantAvailabilityDataAsset taWithArchiveAvailabilityDataAsset := createTechnicalAsset(types.Internal, types.Operational, types.Operational) taWithArchiveAvailabilityDataAsset.DataAssetsProcessed = append(taWithArchiveAvailabilityDataAsset.DataAssetsProcessed, daArchiveAvailability.ID) ta[taWithArchiveAvailabilityDataAsset.ID] = taWithArchiveAvailabilityDataAsset parsedModel, err := ParseModel(&mockConfig{}, createInputModel(ta, da), make(types.RiskRules), make(types.RiskRules)) assert.NoError(t, err) assert.Equal(t, types.Critical, parsedModel.TechnicalAssets[taWithCriticalAvailabilityDataAsset.ID].Availability) assert.Equal(t, types.Important, parsedModel.TechnicalAssets[taWithImportantAvailabilityDataAsset.ID].Availability) assert.Equal(t, types.Operational, parsedModel.TechnicalAssets[taWithArchiveAvailabilityDataAsset.ID].Availability) } func createInputModel(technicalAssets map[string]input.TechnicalAsset, dataAssets map[string]input.DataAsset) *input.Model { return &input.Model{ TechnicalAssets: technicalAssets, DataAssets: dataAssets, // set some dummy values to bypass validation BusinessCriticality: "archive", } } func createTechnicalAsset(confidentiality types.Confidentiality, integrity types.Criticality, availability types.Criticality) input.TechnicalAsset { return input.TechnicalAsset{ ID: uuid.New().String(), // those values are required to bypass validation Usage: "business", Type: "process", Size: "system", Technology: "unknown-technology", Encryption: "none", Machine: "virtual", Confidentiality: confidentiality.String(), Integrity: integrity.String(), Availability: availability.String(), } } func createDataAsset(confidentiality types.Confidentiality, integrity types.Criticality, availability types.Criticality) input.DataAsset { return input.DataAsset{ ID: uuid.New().String(), Usage: "business", Quantity: "few", Confidentiality: confidentiality.String(), Integrity: integrity.String(), Availability: availability.String(), } } type mockConfig struct { } func (m *mockConfig) GetAppFolder() string { return "" } func (m *mockConfig) GetTechnologyFilename() string { return "" }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/model/parse.go
pkg/model/parse.go
package model import ( "fmt" "path/filepath" "regexp" "strings" "time" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" ) type technologyMapConfigReader interface { GetAppFolder() string GetTechnologyFilename() string } func ParseModel(config technologyMapConfigReader, modelInput *input.Model, builtinRiskRules types.RiskRules, customRiskRules types.RiskRules) (*types.Model, error) { technologies := make(types.TechnologyMap) technologiesLoadError := technologies.LoadWithConfig(config, "technologies.yaml") if technologiesLoadError != nil { return nil, fmt.Errorf("error loading technologies: %w", technologiesLoadError) } technologies.PropagateAttributes() businessCriticality, err := types.ParseCriticality(modelInput.BusinessCriticality) if err != nil { return nil, fmt.Errorf("unknown 'business_criticality' value of application: %v", modelInput.BusinessCriticality) } reportDate := time.Now() if len(modelInput.Date) > 0 { var parseError error reportDate, parseError = time.Parse("2006-01-02", modelInput.Date) if parseError != nil { return nil, fmt.Errorf("unable to parse 'date' value of model file (expected format: '2006-01-02')") } } parsedModel := types.Model{ ThreagileVersion: modelInput.ThreagileVersion, Title: modelInput.Title, Author: convertAuthor(modelInput.Author), Contributors: convertAuthors(modelInput.Contributors), Date: types.Date{Time: reportDate}, AppDescription: removePathElementsFromImageFiles(modelInput.AppDescription), BusinessOverview: removePathElementsFromImageFiles(modelInput.BusinessOverview), TechnicalOverview: removePathElementsFromImageFiles(modelInput.TechnicalOverview), BusinessCriticality: businessCriticality, ManagementSummaryComment: modelInput.ManagementSummaryComment, SecurityRequirements: modelInput.SecurityRequirements, Questions: modelInput.Questions, AbuseCases: modelInput.AbuseCases, TagsAvailable: lowerCaseAndTrim(modelInput.TagsAvailable), DiagramTweakNodesep: modelInput.DiagramTweakNodesep, DiagramTweakRanksep: modelInput.DiagramTweakRanksep, DiagramTweakEdgeLayout: modelInput.DiagramTweakEdgeLayout, DiagramTweakSuppressEdgeLabels: modelInput.DiagramTweakSuppressEdgeLabels, DiagramTweakLayoutLeftToRight: modelInput.DiagramTweakLayoutLeftToRight, DiagramTweakInvisibleConnectionsBetweenAssets: modelInput.DiagramTweakInvisibleConnectionsBetweenAssets, DiagramTweakSameRankAssets: modelInput.DiagramTweakSameRankAssets, } parsedModel.CommunicationLinks = make(map[string]*types.CommunicationLink) parsedModel.AllSupportedTags = make(map[string]bool) parsedModel.IncomingTechnicalCommunicationLinksMappedByTargetId = make(map[string][]*types.CommunicationLink) parsedModel.DirectContainingTrustBoundaryMappedByTechnicalAssetId = make(map[string]*types.TrustBoundary) parsedModel.GeneratedRisksByCategory = make(map[string][]*types.Risk) parsedModel.GeneratedRisksBySyntheticId = make(map[string]*types.Risk) if parsedModel.DiagramTweakNodesep == 0 { parsedModel.DiagramTweakNodesep = 2 } if parsedModel.DiagramTweakRanksep == 0 { parsedModel.DiagramTweakRanksep = 2 } // Data Assets =============================================================================== parsedModel.DataAssets = make(map[string]*types.DataAsset) for title, asset := range modelInput.DataAssets { id := fmt.Sprintf("%v", asset.ID) usage, err := types.ParseUsage(asset.Usage) if err != nil { return nil, fmt.Errorf("unknown 'usage' value of data asset %q: %v", title, asset.Usage) } quantity, err := types.ParseQuantity(asset.Quantity) if err != nil { return nil, fmt.Errorf("unknown 'quantity' value of data asset %q: %v", title, asset.Quantity) } confidentiality, err := types.ParseConfidentiality(asset.Confidentiality) if err != nil { return nil, fmt.Errorf("unknown 'confidentiality' value of data asset %q: %v", title, asset.Confidentiality) } integrity, err := types.ParseCriticality(asset.Integrity) if err != nil { return nil, fmt.Errorf("unknown 'integrity' value of data asset %q: %v", title, asset.Integrity) } availability, err := types.ParseCriticality(asset.Availability) if err != nil { return nil, fmt.Errorf("unknown 'availability' value of data asset %q: %v", title, asset.Availability) } err = checkIdSyntax(id) if err != nil { return nil, err } if _, exists := parsedModel.DataAssets[id]; exists { return nil, fmt.Errorf("duplicate id used: %v", id) } tags, err := parsedModel.CheckTags(lowerCaseAndTrim(asset.Tags), "data asset '"+title+"'") if err != nil { return nil, err } parsedModel.DataAssets[id] = &types.DataAsset{ Id: id, Title: title, Usage: usage, Description: withDefault(fmt.Sprintf("%v", asset.Description), title), Quantity: quantity, Tags: tags, Origin: fmt.Sprintf("%v", asset.Origin), Owner: fmt.Sprintf("%v", asset.Owner), Confidentiality: confidentiality, Integrity: integrity, Availability: availability, JustificationCiaRating: fmt.Sprintf("%v", asset.JustificationCiaRating), } } // Technical Assets =============================================================================== parsedModel.TechnicalAssets = make(map[string]*types.TechnicalAsset) for title, asset := range modelInput.TechnicalAssets { id := fmt.Sprintf("%v", asset.ID) usage, err := types.ParseUsage(asset.Usage) if err != nil { return nil, fmt.Errorf("unknown 'usage' value of technical asset %q: %v", title, asset.Usage) } var dataAssetsStored = make([]string, 0) if asset.DataAssetsStored != nil { for _, parsedStoredAssets := range asset.DataAssetsStored { referencedAsset := fmt.Sprintf("%v", parsedStoredAssets) if contains(dataAssetsStored, referencedAsset) { continue } err := parsedModel.CheckDataAssetTargetExists(referencedAsset, fmt.Sprintf("technical asset %q", title)) if err != nil { return nil, err } dataAssetsStored = append(dataAssetsStored, referencedAsset) } } var dataAssetsProcessed = dataAssetsStored if asset.DataAssetsProcessed != nil { for _, parsedProcessedAsset := range asset.DataAssetsProcessed { referencedAsset := fmt.Sprintf("%v", parsedProcessedAsset) if contains(dataAssetsProcessed, referencedAsset) { continue } err := parsedModel.CheckDataAssetTargetExists(referencedAsset, "technical asset '"+title+"'") if err != nil { return nil, err } dataAssetsProcessed = append(dataAssetsProcessed, referencedAsset) } } technicalAssetType, err := types.ParseTechnicalAssetType(asset.Type) if err != nil { return nil, fmt.Errorf("unknown 'type' value of technical asset %q: %v", title, asset.Type) } technicalAssetSize, err := types.ParseTechnicalAssetSize(asset.Size) if err != nil { return nil, fmt.Errorf("unknown 'size' value of technical asset %q: %v", title, asset.Size) } technicalAssetTechnologies := make([]*types.Technology, 0) allTechnologies := asset.Technologies if asset.Technology != "" { allTechnologies = append(allTechnologies, asset.Technology) } for _, technologyName := range allTechnologies { technicalAssetTechnology := technologies.Get(technologyName) if technicalAssetTechnology == nil { return nil, fmt.Errorf("unknown 'technology' value of technical asset %q: %v", title, asset.Technology) } technicalAssetTechnologies = append(technicalAssetTechnologies, technicalAssetTechnology) } encryption, err := types.ParseEncryptionStyle(asset.Encryption) if err != nil { return nil, fmt.Errorf("unknown 'encryption' value of technical asset %q: %v", title, asset.Encryption) } technicalAssetMachine, err := types.ParseTechnicalAssetMachine(asset.Machine) if err != nil { return nil, fmt.Errorf("unknown 'machine' value of technical asset %q: %v", title, asset.Machine) } confidentiality, err := types.ParseConfidentiality(asset.Confidentiality) if err != nil { return nil, fmt.Errorf("unknown 'confidentiality' value of technical asset %q: %v", title, asset.Confidentiality) } integrity, err := types.ParseCriticality(asset.Integrity) if err != nil { return nil, fmt.Errorf("unknown 'integrity' value of technical asset %q: %v", title, asset.Integrity) } availability, err := types.ParseCriticality(asset.Availability) if err != nil { return nil, fmt.Errorf("unknown 'availability' value of technical asset %q: %v", title, asset.Availability) } dataFormatsAccepted := make([]types.DataFormat, 0) if asset.DataFormatsAccepted != nil { for _, dataFormatName := range asset.DataFormatsAccepted { dataFormat, err := types.ParseDataFormat(dataFormatName) if err != nil { return nil, fmt.Errorf("unknown 'data_formats_accepted' value of technical asset %q: %v", title, dataFormatName) } dataFormatsAccepted = append(dataFormatsAccepted, dataFormat) } } communicationLinks := make([]*types.CommunicationLink, 0) if asset.CommunicationLinks != nil { for commLinkTitle, commLink := range asset.CommunicationLinks { weight := 1 var dataAssetsSent []string var dataAssetsReceived []string authentication, err := types.ParseAuthentication(commLink.Authentication) if err != nil { return nil, fmt.Errorf("unknown 'authentication' value of technical asset %q communication link %q: %v", title, commLinkTitle, commLink.Authentication) } authorization, err := types.ParseAuthorization(commLink.Authorization) if err != nil { return nil, fmt.Errorf("unknown 'authorization' value of technical asset %q communication link %q: %v", title, commLinkTitle, commLink.Authorization) } usage, err := types.ParseUsage(commLink.Usage) if err != nil { return nil, fmt.Errorf("unknown 'usage' value of technical asset %q communication link %q: %v", title, commLinkTitle, commLink.Usage) } protocol, err := types.ParseProtocol(commLink.Protocol) if err != nil { return nil, fmt.Errorf("unknown 'protocol' value of technical asset %q communication link %q: %v", title, commLinkTitle, commLink.Protocol) } if commLink.DataAssetsSent != nil { for _, dataAssetSent := range commLink.DataAssetsSent { referencedAsset := fmt.Sprintf("%v", dataAssetSent) if !contains(dataAssetsSent, referencedAsset) { err := parsedModel.CheckDataAssetTargetExists(referencedAsset, fmt.Sprintf("communication link %q of technical asset %q", commLinkTitle, title)) if err != nil { return nil, err } dataAssetsSent = append(dataAssetsSent, referencedAsset) if !contains(dataAssetsProcessed, referencedAsset) { dataAssetsProcessed = append(dataAssetsProcessed, referencedAsset) } } } } if commLink.DataAssetsReceived != nil { for _, dataAssetReceived := range commLink.DataAssetsReceived { referencedAsset := fmt.Sprintf("%v", dataAssetReceived) if contains(dataAssetsReceived, referencedAsset) { continue } err := parsedModel.CheckDataAssetTargetExists(referencedAsset, "communication link '"+commLinkTitle+"' of technical asset '"+title+"'") if err != nil { return nil, err } dataAssetsReceived = append(dataAssetsReceived, referencedAsset) if !contains(dataAssetsProcessed, referencedAsset) { dataAssetsProcessed = append(dataAssetsProcessed, referencedAsset) } } } if commLink.DiagramTweakWeight > 0 { weight = commLink.DiagramTweakWeight } dataFlowTitle := fmt.Sprintf("%v", commLinkTitle) commLinkId, err := createDataFlowId(id, dataFlowTitle) if err != nil { return nil, err } tags, err := parsedModel.CheckTags(lowerCaseAndTrim(commLink.Tags), "communication link '"+commLinkTitle+"' of technical asset '"+title+"'") if err != nil { return nil, err } commLink := &types.CommunicationLink{ Id: commLinkId, SourceId: id, TargetId: commLink.Target, Title: dataFlowTitle, Description: withDefault(commLink.Description, dataFlowTitle), Protocol: protocol, Authentication: authentication, Authorization: authorization, Usage: usage, Tags: tags, VPN: commLink.VPN, IpFiltered: commLink.IpFiltered, Readonly: commLink.Readonly, DataAssetsSent: dataAssetsSent, DataAssetsReceived: dataAssetsReceived, DiagramTweakWeight: weight, DiagramTweakConstraint: !commLink.DiagramTweakConstraint, } communicationLinks = append(communicationLinks, commLink) // track all comm links parsedModel.CommunicationLinks[commLink.Id] = commLink // keep track of map of *all* comm links mapped by target-id (to be able to look up "who is calling me" kind of things) parsedModel.IncomingTechnicalCommunicationLinksMappedByTargetId[commLink.TargetId] = append( parsedModel.IncomingTechnicalCommunicationLinksMappedByTargetId[commLink.TargetId], commLink) } } err = checkIdSyntax(id) if err != nil { return nil, err } if _, exists := parsedModel.TechnicalAssets[id]; exists { return nil, fmt.Errorf("duplicate id used: %v", id) } tags, err := parsedModel.CheckTags(lowerCaseAndTrim(asset.Tags), fmt.Sprintf("technical asset %q", title)) if err != nil { return nil, err } parsedModel.TechnicalAssets[id] = &types.TechnicalAsset{ Id: id, Usage: usage, Title: title, //fmt.Sprintf("%v", asset["title"]), Description: withDefault(fmt.Sprintf("%v", asset.Description), title), Type: technicalAssetType, Size: technicalAssetSize, Technologies: technicalAssetTechnologies, Tags: tags, Machine: technicalAssetMachine, Internet: asset.Internet, Encryption: encryption, MultiTenant: asset.MultiTenant, Redundant: asset.Redundant, CustomDevelopedParts: asset.CustomDevelopedParts, UsedAsClientByHuman: asset.UsedAsClientByHuman, OutOfScope: asset.OutOfScope, JustificationOutOfScope: fmt.Sprintf("%v", asset.JustificationOutOfScope), Owner: fmt.Sprintf("%v", asset.Owner), Confidentiality: confidentiality, Integrity: integrity, Availability: availability, JustificationCiaRating: fmt.Sprintf("%v", asset.JustificationCiaRating), DataAssetsProcessed: dataAssetsProcessed, DataAssetsStored: dataAssetsStored, DataFormatsAccepted: dataFormatsAccepted, CommunicationLinks: communicationLinks, DiagramTweakOrder: asset.DiagramTweakOrder, } } // If CIA is lower than that of its data assets, it is implicitly set to the highest CIA value of its data assets for id, techAsset := range parsedModel.TechnicalAssets { dataAssetConfidentiality := parsedModel.HighestTechnicalAssetConfidentiality(techAsset) if techAsset.Confidentiality < dataAssetConfidentiality { techAsset.Confidentiality = dataAssetConfidentiality } dataAssetIntegrity := parsedModel.HighestIntegrity(techAsset) if techAsset.Integrity < dataAssetIntegrity { techAsset.Integrity = dataAssetIntegrity } dataAssetAvailability := parsedModel.HighestAvailability(techAsset) if techAsset.Availability < dataAssetAvailability { techAsset.Availability = dataAssetAvailability } parsedModel.TechnicalAssets[id] = techAsset } // A target of a communication link implicitly processes all data assets that are sent to or received by that target for id, techAsset := range parsedModel.TechnicalAssets { for _, commLink := range techAsset.CommunicationLinks { if commLink.TargetId == id { continue } targetTechAsset := parsedModel.TechnicalAssets[commLink.TargetId] if targetTechAsset == nil { return nil, fmt.Errorf("missing target technical asset %q for communication link: %q", commLink.TargetId, commLink.Title) } dataAssetsProcessedByTarget := targetTechAsset.DataAssetsProcessed for _, dataAssetSent := range commLink.DataAssetsSent { if !contains(dataAssetsProcessedByTarget, dataAssetSent) { dataAssetsProcessedByTarget = append(dataAssetsProcessedByTarget, dataAssetSent) } } for _, dataAssetReceived := range commLink.DataAssetsReceived { if !contains(dataAssetsProcessedByTarget, dataAssetReceived) { dataAssetsProcessedByTarget = append(dataAssetsProcessedByTarget, dataAssetReceived) } } targetTechAsset.DataAssetsProcessed = dataAssetsProcessedByTarget parsedModel.TechnicalAssets[commLink.TargetId] = targetTechAsset } } // Trust Boundaries =============================================================================== checklistToAvoidAssetBeingModeledInMultipleTrustBoundaries := make(map[string]bool) parsedModel.TrustBoundaries = make(map[string]*types.TrustBoundary) for title, boundary := range modelInput.TrustBoundaries { id := fmt.Sprintf("%v", boundary.ID) var technicalAssetsInside = make([]string, 0) if boundary.TechnicalAssetsInside != nil { parsedInsideAssets := boundary.TechnicalAssetsInside technicalAssetsInside = make([]string, len(parsedInsideAssets)) for i, parsedInsideAsset := range parsedInsideAssets { technicalAssetsInside[i] = strings.ToLower(parsedInsideAsset) _, found := parsedModel.TechnicalAssets[technicalAssetsInside[i]] if !found { return nil, fmt.Errorf("missing referenced technical asset %q at trust boundary %q", technicalAssetsInside[i], title) } if checklistToAvoidAssetBeingModeledInMultipleTrustBoundaries[technicalAssetsInside[i]] { return nil, fmt.Errorf("referenced technical asset %q at trust boundary %q is modeled in multiple trust boundaries", technicalAssetsInside[i], title) } checklistToAvoidAssetBeingModeledInMultipleTrustBoundaries[technicalAssetsInside[i]] = true //fmt.Println("asset "+technicalAssetsInside[i]+" at i="+strconv.Itoa(i)) } } var trustBoundariesNested = make([]string, 0) if boundary.TrustBoundariesNested != nil { parsedNestedBoundaries := boundary.TrustBoundariesNested trustBoundariesNested = make([]string, len(parsedNestedBoundaries)) for i, parsedNestedBoundary := range parsedNestedBoundaries { trustBoundariesNested[i] = fmt.Sprintf("%v", parsedNestedBoundary) } } trustBoundaryType, err := types.ParseTrustBoundary(boundary.Type) if err != nil { return nil, fmt.Errorf("unknown 'type' of trust boundary %q: %v", title, boundary.Type) } tags, err := parsedModel.CheckTags(lowerCaseAndTrim(boundary.Tags), fmt.Sprintf("trust boundary %q", title)) if err != nil { return nil, err } trustBoundary := &types.TrustBoundary{ Id: id, Title: title, //fmt.Sprintf("%v", boundary["title"]), Description: withDefault(fmt.Sprintf("%v", boundary.Description), title), Type: trustBoundaryType, Tags: tags, TechnicalAssetsInside: technicalAssetsInside, TrustBoundariesNested: trustBoundariesNested, } err = checkIdSyntax(id) if err != nil { return nil, err } if _, exists := parsedModel.TrustBoundaries[id]; exists { return nil, fmt.Errorf("duplicate id used: %v", id) } parsedModel.TrustBoundaries[id] = trustBoundary for _, technicalAsset := range trustBoundary.TechnicalAssetsInside { parsedModel.DirectContainingTrustBoundaryMappedByTechnicalAssetId[technicalAsset] = trustBoundary //fmt.Println("Asset "+technicalAsset+" is directly in trust boundary "+trustBoundary.ID) } } err = parsedModel.CheckNestedTrustBoundariesExisting() if err != nil { return nil, err } // Shared Runtime =============================================================================== parsedModel.SharedRuntimes = make(map[string]*types.SharedRuntime) for title, inputRuntime := range modelInput.SharedRuntimes { id := fmt.Sprintf("%v", inputRuntime.ID) var technicalAssetsRunning = make([]string, 0) if inputRuntime.TechnicalAssetsRunning != nil { parsedRunningAssets := inputRuntime.TechnicalAssetsRunning technicalAssetsRunning = make([]string, len(parsedRunningAssets)) for i, parsedRunningAsset := range parsedRunningAssets { assetId := fmt.Sprintf("%v", parsedRunningAsset) err := parsedModel.CheckTechnicalAssetExists(assetId, "shared runtime '"+title+"'", false) if err != nil { return nil, err } technicalAssetsRunning[i] = assetId } } tags, err := parsedModel.CheckTags(lowerCaseAndTrim(inputRuntime.Tags), "shared runtime '"+title+"'") if err != nil { return nil, err } sharedRuntime := &types.SharedRuntime{ Id: id, Title: title, //fmt.Sprintf("%v", boundary["title"]), Description: withDefault(fmt.Sprintf("%v", inputRuntime.Description), title), Tags: tags, TechnicalAssetsRunning: technicalAssetsRunning, } err = checkIdSyntax(id) if err != nil { return nil, err } if _, exists := parsedModel.SharedRuntimes[id]; exists { return nil, fmt.Errorf("duplicate id used: %v", id) } parsedModel.SharedRuntimes[id] = sharedRuntime } for _, rule := range builtinRiskRules { parsedModel.BuiltInRiskCategories = append(parsedModel.BuiltInRiskCategories, rule.Category()) } for _, rule := range customRiskRules { parsedModel.CustomRiskCategories = append(parsedModel.CustomRiskCategories, rule.Category()) } // Individual Risk Categories (just used as regular risk categories) =============================================================================== for _, customRiskCategoryCategory := range modelInput.CustomRiskCategories { function, err := types.ParseRiskFunction(customRiskCategoryCategory.Function) if err != nil { return nil, fmt.Errorf("unknown 'function' value of individual risk category %q: %v", customRiskCategoryCategory.Title, customRiskCategoryCategory.Function) } stride, err := types.ParseSTRIDE(customRiskCategoryCategory.STRIDE) if err != nil { return nil, fmt.Errorf("unknown 'stride' value of individual risk category %q: %v", customRiskCategoryCategory.Title, customRiskCategoryCategory.STRIDE) } cat := &types.RiskCategory{ ID: customRiskCategoryCategory.ID, Title: customRiskCategoryCategory.Title, Description: customRiskCategoryCategory.Description, Impact: customRiskCategoryCategory.Impact, ASVS: customRiskCategoryCategory.ASVS, CheatSheet: customRiskCategoryCategory.CheatSheet, Action: customRiskCategoryCategory.Action, Mitigation: customRiskCategoryCategory.Mitigation, Check: customRiskCategoryCategory.Check, DetectionLogic: customRiskCategoryCategory.DetectionLogic, RiskAssessment: customRiskCategoryCategory.RiskAssessment, FalsePositives: customRiskCategoryCategory.FalsePositives, Function: function, STRIDE: stride, ModelFailurePossibleReason: customRiskCategoryCategory.ModelFailurePossibleReason, CWE: customRiskCategoryCategory.CWE, } if cat.Description == "" { cat.Description = customRiskCategoryCategory.Title } err = checkIdSyntax(customRiskCategoryCategory.ID) if err != nil { return nil, err } if !parsedModel.CustomRiskCategories.Add(cat) { return nil, fmt.Errorf("duplicate id used: %v", customRiskCategoryCategory.ID) } // NOW THE INDIVIDUAL RISK INSTANCES: //individualRiskInstances := make([]model.Risk, 0) if customRiskCategoryCategory.RisksIdentified != nil { // TODO: also add syntax checks of input YAML when linked asset is not found or when synthetic-id is already used... for title, individualRiskInstance := range customRiskCategoryCategory.RisksIdentified { var mostRelevantDataAssetId, mostRelevantTechnicalAssetId, mostRelevantCommunicationLinkId, mostRelevantTrustBoundaryId, mostRelevantSharedRuntimeId string var dataBreachProbability types.DataBreachProbability var dataBreachTechnicalAssetIDs []string severity, err := types.ParseRiskSeverity(individualRiskInstance.Severity) if err != nil { return nil, fmt.Errorf("unknown 'severity' value of individual risk instance %q: %v", title, individualRiskInstance.Severity) } exploitationLikelihood, err := types.ParseRiskExploitationLikelihood(individualRiskInstance.ExploitationLikelihood) if err != nil { return nil, fmt.Errorf("unknown 'exploitation_likelihood' value of individual risk instance %q: %v", title, individualRiskInstance.ExploitationLikelihood) } exploitationImpact, err := types.ParseRiskExploitationImpact(individualRiskInstance.ExploitationImpact) if err != nil { return nil, fmt.Errorf("unknown 'exploitation_impact' value of individual risk instance %q: %v", title, individualRiskInstance.ExploitationImpact) } if len(individualRiskInstance.MostRelevantDataAsset) > 0 { mostRelevantDataAssetId = fmt.Sprintf("%v", individualRiskInstance.MostRelevantDataAsset) err := parsedModel.CheckDataAssetTargetExists(mostRelevantDataAssetId, fmt.Sprintf("individual risk %q", title)) if err != nil { return nil, err } } if len(individualRiskInstance.MostRelevantTechnicalAsset) > 0 { mostRelevantTechnicalAssetId = fmt.Sprintf("%v", individualRiskInstance.MostRelevantTechnicalAsset) err := parsedModel.CheckTechnicalAssetExists(mostRelevantTechnicalAssetId, fmt.Sprintf("individual risk %q", title), false) if err != nil { return nil, err } } if len(individualRiskInstance.MostRelevantCommunicationLink) > 0 { mostRelevantCommunicationLinkId = fmt.Sprintf("%v", individualRiskInstance.MostRelevantCommunicationLink) err := parsedModel.CheckCommunicationLinkExists(mostRelevantCommunicationLinkId, fmt.Sprintf("individual risk %q", title)) if err != nil { return nil, err } } if len(individualRiskInstance.MostRelevantTrustBoundary) > 0 { mostRelevantTrustBoundaryId = fmt.Sprintf("%v", individualRiskInstance.MostRelevantTrustBoundary) err := parsedModel.CheckTrustBoundaryExists(mostRelevantTrustBoundaryId, fmt.Sprintf("individual risk %q", title)) if err != nil { return nil, err } } if len(individualRiskInstance.MostRelevantSharedRuntime) > 0 { mostRelevantSharedRuntimeId = fmt.Sprintf("%v", individualRiskInstance.MostRelevantSharedRuntime) err := parsedModel.CheckSharedRuntimeExists(mostRelevantSharedRuntimeId, fmt.Sprintf("individual risk %q", title)) if err != nil { return nil, err } } dataBreachProbability, err = types.ParseDataBreachProbability(individualRiskInstance.DataBreachProbability) if err != nil { return nil, fmt.Errorf("unknown 'data_breach_probability' value of individual risk instance %q: %v", title, individualRiskInstance.DataBreachProbability) } if individualRiskInstance.DataBreachTechnicalAssets != nil { dataBreachTechnicalAssetIDs = make([]string, len(individualRiskInstance.DataBreachTechnicalAssets)) for i, parsedReferencedAsset := range individualRiskInstance.DataBreachTechnicalAssets { assetId := fmt.Sprintf("%v", parsedReferencedAsset) err := parsedModel.CheckTechnicalAssetExists(assetId, fmt.Sprintf("data breach technical assets of individual risk %q", title), false) if err != nil { return nil, err } dataBreachTechnicalAssetIDs[i] = assetId } } parsedModel.GeneratedRisksByCategory[cat.ID] = append(parsedModel.GeneratedRisksByCategory[cat.ID], &types.Risk{ SyntheticId: createSyntheticId(cat.ID, mostRelevantDataAssetId, mostRelevantTechnicalAssetId, mostRelevantCommunicationLinkId, mostRelevantTrustBoundaryId, mostRelevantSharedRuntimeId), Title: title, CategoryId: cat.ID, Severity: severity, ExploitationLikelihood: exploitationLikelihood, ExploitationImpact: exploitationImpact, MostRelevantDataAssetId: mostRelevantDataAssetId, MostRelevantTechnicalAssetId: mostRelevantTechnicalAssetId, MostRelevantCommunicationLinkId: mostRelevantCommunicationLinkId, MostRelevantTrustBoundaryId: mostRelevantTrustBoundaryId, MostRelevantSharedRuntimeId: mostRelevantSharedRuntimeId, DataBreachProbability: dataBreachProbability, DataBreachTechnicalAssetIDs: dataBreachTechnicalAssetIDs, }) } } } // Risk Tracking =============================================================================== parsedModel.RiskTracking = make(map[string]*types.RiskTracking) for syntheticRiskId, riskTracking := range modelInput.RiskTracking { justification := fmt.Sprintf("%v", riskTracking.Justification) checkedBy := fmt.Sprintf("%v", riskTracking.CheckedBy) ticket := fmt.Sprintf("%v", riskTracking.Ticket) var date time.Time if len(riskTracking.Date) > 0 { var parseError error date, parseError = time.Parse("2006-01-02", riskTracking.Date) if parseError != nil { return nil, fmt.Errorf("unable to parse 'date' of risk tracking %q: %v", syntheticRiskId, riskTracking.Date) } } status, err := types.ParseRiskStatus(riskTracking.Status) if err != nil { return nil, fmt.Errorf("unknown 'status' value of risk tracking %q: %v", syntheticRiskId, riskTracking.Status) } tracking := &types.RiskTracking{ SyntheticRiskId: strings.TrimSpace(syntheticRiskId), Justification: justification, CheckedBy: checkedBy, Ticket: ticket, Date: types.Date{Time: date}, Status: status, } parsedModel.RiskTracking[syntheticRiskId] = tracking } // ====================== model consistency check (linking) for _, technicalAsset := range parsedModel.TechnicalAssets { for _, commLink := range technicalAsset.CommunicationLinks { err := parsedModel.CheckTechnicalAssetExists(commLink.TargetId, "communication link '"+commLink.Title+"' of technical asset '"+technicalAsset.Title+"'", false) if err != nil { return nil, err } } } /* data, _ := json.MarshalIndent(parsedModel, "", " ") _ = os.WriteFile(filepath.Join("all.json"), data, 0644) */ /** inYamlData, _ := yaml.Marshal(modelInput) _ = os.WriteFile(filepath.Join("in.yaml"), inYamlData, 0644) inJsonData, _ := json.MarshalIndent(modelInput, "", " ") _ = os.WriteFile(filepath.Join("in.json"), inJsonData, 0644) outYamlData, _ := yaml.Marshal(parsedModel) _ = os.WriteFile(filepath.Join("out.yaml"), outYamlData, 0644) outJsonData, _ := json.MarshalIndent(parsedModel, "", " ") _ = os.WriteFile(filepath.Join("out.json"), outJsonData, 0644) /**/ return &parsedModel, nil } func convertAuthor(author input.Author) *types.Author { return &types.Author{ Name: author.Name, Contact: author.Contact, Homepage: author.Homepage, } } func convertAuthors(authors []input.Author) []*types.Author { result := make([]*types.Author, len(authors)) for i, author := range authors { result[i] = convertAuthor(author) } return result } func checkIdSyntax(id string) error { validIdSyntax := regexp.MustCompile(`^[a-zA-Z0-9\-]+$`) if !validIdSyntax.MatchString(id) { return fmt.Errorf("invalid id syntax used (only letters, numbers, and hyphen allowed): %v", id) } return nil } func createDataFlowId(sourceAssetId, title string) (string, error) { reg, err := regexp.Compile("[^A-Za-z0-9]+") if err != nil { return "", err } return sourceAssetId + ">" + strings.Trim(reg.ReplaceAllString(strings.ToLower(title), "-"), "- "), nil } func createSyntheticId(categoryId string,
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
true
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/enscan.go
enscan.go
package main import ( "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/runner" ) func main() { var enOptions common.ENOptions common.Flag(&enOptions) enOptions.Parse() runner.RunEnumeration(&enOptions) }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/runner/runner.go
runner/runner.go
package runner import ( "encoding/gob" "fmt" "log" "os" "os/signal" "sync" "time" "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "github.com/wgpsec/ENScan/common/utils" _interface "github.com/wgpsec/ENScan/interface" "github.com/wgpsec/ENScan/internal/aiqicha" "github.com/wgpsec/ENScan/internal/app/miit" "github.com/wgpsec/ENScan/internal/kuaicha" "github.com/wgpsec/ENScan/internal/riskbird" "github.com/wgpsec/ENScan/internal/tianyancha" "github.com/wgpsec/ENScan/internal/tycapi" ) type EnJob struct { job _interface.ENScan app _interface.App tpy string Done chan struct{} total int processed int wg sync.WaitGroup enWg sync.WaitGroup mu sync.Mutex task *[]DeepSearchTask data map[string][]gjson.Result taskCh chan DeepSearchTask dataCh chan map[string][]gjson.Result } type ENJobTask struct { Keyword string `json:"keyword"` Typ string `json:"type"` Ref string `json:"ref"` } type ENSCacheDTO struct { JobName string Date string Tasks []ENJobTask Data map[string][]map[string]string Jobs map[string]CacheableENJob } type ESJob struct { JobName string Jobs chan ENJobTask items []ENJobTask ch chan map[string][]map[string]string dt map[string][]map[string]string Done chan struct{} wg sync.WaitGroup esWg sync.WaitGroup mu sync.Mutex total int processed int op *common.ENOptions gobPath string enJobs map[string]_interface.ENScan enApps map[string]_interface.App enJob map[string]*ENJob } type CacheableENJob struct { Task []DeepSearchTask `json:"task"` Data map[string][]gjson.Result `json:"data"` // 将 gjson.Result 转换为字符串存储 } type ENJob struct { Task []DeepSearchTask Data map[string][]gjson.Result TaskCh chan DeepSearchTask DataCh chan map[string][]gjson.Result Total int Processed int } // RunEnumeration 普通任务命令行模式,可批量导入文件查询 func RunEnumeration(options *common.ENOptions) { if options.InputFile != "" { res := utils.ReadFileOutLine(options.InputFile) gologger.Info().Str("FileName", options.InputFile).Msgf("读取到 %d 条信息\n", len(res)) gologger.Info().Msgf("任务将在5秒后开始\n") time.Sleep(5 * time.Second) esjob := NewENTaskQueue(len(res), options) esjob.StartENWorkers() err := esjob.loadCacheFromGob() if err == nil { gologger.Info().Msgf("使用缓存队列进行任务,如需重新开始请删除缓存文件,缓存大小: %d", len(esjob.dt)) } else { for _, v := range res { esjob.AddTask(v) } } // 批量查询任务前需要加载缓存 esjob.wg.Wait() // 等待数据处理完成 esjob.closeCH() esjob.esWg.Wait() _ = esjob.doneCacheGob() //如果没有指定不合并就导出 if !options.IsNoMerge { err := esjob.OutFileByEnInfo(options.InputFile + "批量查询任务结果") if err != nil { gologger.Error().Msgf(err.Error()) } } } else if options.IsApiMode { api(options) } else if options.IsMCPServer { McpServer(options) } else { esjob := NewENTaskQueue(1, options) esjob.StartENWorkers() err := esjob.loadCacheFromGob() if err == nil { gologger.Info().Msgf("使用缓存队列进行任务,如需重新开始请删除缓存文件,缓存大小: %d", len(esjob.dt)) } else { esjob.AddTask(options.KeyWord) } // 等待任务完成 esjob.wg.Wait() // 等待数据处理完成 esjob.closeCH() esjob.esWg.Wait() _ = esjob.OutFileByEnInfo(options.KeyWord) _ = esjob.doneCacheGob() } } // RunJob 运行项目 添加新参数记得去Config添加 func (q *ESJob) processTask(task ENJobTask) { keyword := task.Keyword gologger.Info().Msgf("【%d/%d】正在获取 ⌈%s⌋ 信息 %s", q.processed+1, q.total, keyword, q.op.GetField) gologger.Debug().Msgf("关键词:⌈%s⌋ 数据源:%s 数据字段:%s\n", keyword, task.Typ, q.op.GetField) // 初始化任务模式 enJob := q.NewEnJob(keyword + task.Typ) enJob.enWg.Add(1) enJobLen := len(*enJob.task) enJob.tpy = task.Typ if app, ok := q.enApps[task.Typ]; ok { enJob.app = app } else if job, isJob := q.enJobs[task.Typ]; isJob { enJob.job = job } else { gologger.Error().Msgf("未找到 %s 任务模式", task.Typ) // 如果既没有app也没有job,说明任务类型不支持,应该跳过 enJob.enWg.Done() // 创建一个空的结果数据,避免程序卡住 rdata := map[string][]map[string]string{ "enterprise_info": {}, } q.ch <- rdata q.wg.Done() return } enJob.startCH() // 如果是插件模式就不需要获取企业信息 if enJob.app != nil { if err := enJob.getAppByKeyWord(keyword, q.op.GetField, task.Ref); err != nil { gologger.Error().Msgf("%s 查询信息失败\n%s", enJob.tpy, err.Error()) } } else { if enJobLen > 0 { gologger.Info().Msgf("任务已存在,将直接继续进行任务查询") j := enJob j.newTaskQueue(enJobLen) j.reTaskQueue() j.StartWorkers() j.wg.Wait() j.closeCH() } else { pid := "" var err error if q.op.ISKeyPid { pid = keyword } else { pid, err = enJob.SearchByKeyWord(keyword) if err != nil { gologger.Error().Msgf("搜索关键词失败:%s,跳过该任务", err.Error()) // 即使搜索失败,也要确保任务能够继续 enJob.enWg.Done() // 先调用Done(),然后再Wait() enJob.enWg.Wait() // 创建一个空的结果数据,避免程序卡住 rdata := map[string][]map[string]string{ "enterprise_info": {}, } q.ch <- rdata q.wg.Done() return } } // 获取企业信息,通过查询到的信息 if err = enJob.getInfoById(pid, q.op.GetField); err != nil { gologger.Error().Msgf("获取企业信息失败:%s,跳过该任务", err.Error()) // 即使获取企业信息失败,也要确保任务能够继续 enJob.enWg.Done() // 先调用Done(),然后再Wait() enJob.enWg.Wait() // 创建一个空的结果数据,避免程序卡住 rdata := map[string][]map[string]string{ "enterprise_info": {}, } q.ch <- rdata q.wg.Done() return } } } // 等待数据接受处理完成 enJob.enWg.Wait() rdata := q.InfoToMap(enJob, fmt.Sprintf("%s⌈%s⌋", enJob.tpy, keyword)) // TODO 在实时查询出来信息时自动调用 if q.op.IsPlugins { for _, t := range rdata["enterprise_info"] { q.AddPluginsTask(t["name"]) } } q.ch <- rdata // 处理完成数据进行导出 if !q.op.IsMergeOut { err := common.OutFileByEnInfo(rdata, q.op.KeyWord, q.op.OutPutType, q.op.Output) if err != nil { gologger.Error().Msgf(err.Error()) } } // 完成清理数据 // 完成把任务清理干净 delete(q.enJob, keyword+task.Typ) q.wg.Done() } func (q *ESJob) getENJob(tpy string) (enJob *EnJob) { enJob = q.NewEnJob(tpy) if app, ok := q.enApps[tpy]; ok { enJob.app = app } else if job, isJob := q.enJobs[tpy]; isJob { enJob.job = job } else { gologger.Error().Msgf("未找到 %s 任务模式", tpy) } return enJob } func NewENTaskQueue(capacity int, op *common.ENOptions) *ESJob { jobs := map[string]_interface.ENScan{ "aqc": &aiqicha.AQC{Options: op}, "tyc": &tianyancha.TYC{Options: op}, "tycapi": &tycapi.TycAPI{Options: op}, "kc": &kuaicha.KC{Options: op}, "rb": &riskbird.RB{Options: op}, } apps := map[string]_interface.App{ "miit": &miit.Miit{Options: op}, } return &ESJob{ Jobs: make(chan ENJobTask, capacity), Done: make(chan struct{}), ch: make(chan map[string][]map[string]string, capacity), dt: make(map[string][]map[string]string), op: op, gobPath: "enscan.gob", enJobs: jobs, enApps: apps, enJob: make(map[string]*ENJob), } } func (q *ESJob) AddTask(keyword string) { for _, t := range q.op.GetType { // 如果是插件模式,而且不是指定添加插件跑 if utils.IsInList(t, common.ENSApps) && q.op.IsPlugins { continue } q.AddENJobTask(ENJobTask{Keyword: keyword, Typ: t}) } } func (q *ESJob) AddPluginsTask(keyword string) { for _, t := range q.op.GetType { // 如果是插件模式,而且不是指定添加插件跑 if !utils.IsInList(t, common.ENSApps) { continue } q.AddENJobTask(ENJobTask{Keyword: keyword, Typ: t}) } } func (q *ESJob) AddENJobTask(task ENJobTask) { q.Jobs <- task q.mu.Lock() defer q.mu.Unlock() q.items = append(q.items, task) q.wg.Add(1) q.total++ } func (q *ESJob) StartENWorkers() { q.esWg.Add(1) go func() { for task := range q.Jobs { q.processTask(task) q.items = q.items[1:] q.mu.Lock() q.processed++ q.mu.Unlock() } }() go func() { esJobTicker := time.NewTicker(1 * time.Second) var quitSig = make(chan os.Signal, 1) signal.Notify(quitSig, os.Interrupt, os.Kill) for { select { // 存储跑完的MAP数据 case data, ok := <-q.ch: if !ok { q.esWg.Done() return } if data != nil { q.mu.Lock() for key, newResults := range data { q.dt[key] = append(q.dt[key], newResults...) } q.mu.Unlock() } case <-esJobTicker.C: if err := q.saveCacheToGob(); err != nil { gologger.Error().Msgf("保存缓存失败: %v", err) } case <-quitSig: if !q.op.IsApiMode && !q.op.IsMCPServer { gologger.Error().Msgf("任务未完成退出,将自动保存过程文件!") _ = q.OutFileByEnInfo("未完成任务结果") } log.Fatal("exit.by.signal") } } }() } func (q *ESJob) OutFileByEnInfo(name string) error { err := common.OutFileByEnInfo(q.dt, name, q.op.OutPutType, q.op.Output) if err != nil { gologger.Info().Msgf("尝试导出文件失败: %v", err) return err } return nil } func (q *ESJob) OutDataByEnInfo() map[string][]map[string]string { return q.dt } func (j *ESJob) saveCacheToGob() error { j.mu.Lock() defer j.mu.Unlock() // 创建或打开 Gob 文件 file, err := os.Create(j.gobPath) if err != nil { return err } defer file.Close() // 创建可序列化的 enJob 映射 cacheableEnJobs := make(map[string]CacheableENJob) for key, enJob := range j.enJob { if enJob == nil { continue } // 将 gjson.Result 转换为字符串以便存储 cacheableEnJobs[key] = CacheableENJob{ Task: enJob.Task, Data: enJob.Data, } } // 使用 Gob 编码器 encoder := gob.NewEncoder(file) var c = &ENSCacheDTO{ JobName: "缓存", Date: time.Now().Format("2006-01-02 15:04:05"), Data: j.dt, Tasks: j.items, Jobs: cacheableEnJobs, } return encoder.Encode(c) } func (j *ESJob) loadCacheFromGob() error { file, err := os.Open(j.gobPath) if err != nil { if os.IsNotExist(err) { // 文件不存在,缓存为空 j.dt = make(map[string][]map[string]string) return fmt.Errorf("缓存为空") } return err } defer file.Close() gologger.Info().Msgf("正在加载缓存数据...") decoder := gob.NewDecoder(file) c := &ENSCacheDTO{} if err = decoder.Decode(c); err != nil { return err } if c.Data == nil || c.Tasks == nil { return fmt.Errorf("缓存数据不完整") } j.dt = c.Data j.items = c.Tasks j.total = len(c.Tasks) gologger.Info().Msgf("ENSCAN[%s]加载缓存成功\n缓存时间:%s\n任务缓存数据大小: %d,剩余未完成的批量查询任务 %d\n", c.JobName, c.Date, len(c.Data), len(c.Tasks)) mss := "" if len(c.Tasks) > 1 { for _, task := range c.Tasks { mss += fmt.Sprintf("- TASK[%s]关联原因:%s\n", task.Keyword, task.Ref) } gologger.Debug().Msgf(mss) } cacheableEnJobs := c.Jobs if cacheableEnJobs != nil { mss = "" gologger.Info().Msgf("加载JOB任务数量: %d\n", len(cacheableEnJobs)) for key, cacheableEnJob := range cacheableEnJobs { enJob := &ENJob{ Task: cacheableEnJob.Task, Data: cacheableEnJob.Data, DataCh: make(chan map[string][]gjson.Result, 100), TaskCh: make(chan DeepSearchTask, 100), } j.enJob[key] = enJob gologger.Info().Msgf(fmt.Sprintf("加载成功任务[%s] JOB:%d Data%d\n\n", key, len(cacheableEnJob.Task), len(cacheableEnJob.Data))) for _, task := range cacheableEnJob.Task { mss += fmt.Sprintf("- JOB[%s]关联原因:%s\n", task.Name, task.Ref) } } gologger.Debug().Msgf(mss) } gologger.Info().Msgf("============ 缓存加载完成,将在5S后开始任务!=============") time.Sleep(5 * time.Second) // 添加任务到队列 for _, v := range c.Tasks { j.Jobs <- v j.wg.Add(1) } // TODO 这里需要改进,直接读取任务到队列里而不是添加 //for _, t := range c.Tasks { // j.AddENJobTask(t) //} return nil } // getRunningData 获取正在运行时的项目数据 func (q *ESJob) getRunData() map[string][]map[string]string { return q.dt } func (q *ESJob) getRunTaskData(tpy string) (data map[string][]gjson.Result, err error) { if _, ok := q.enJob[tpy]; ok { data = q.enJob[tpy].Data } else { return data, fmt.Errorf("获取任务数据不存在!") } return data, nil } func (j *ESJob) doneCacheGob() error { err := os.Remove(j.gobPath) if err != nil { if !os.IsNotExist(err) { gologger.Error().Msgf("删除文件失败: %v", err) } } return nil }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/runner/mcpServer.go
runner/mcpServer.go
package runner import ( "encoding/json" "fmt" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "github.com/wgpsec/ENScan/common/utils" "golang.org/x/net/context" "log" "strconv" ) // getInfoPro 顾名思义,PRO方法 func getInfoPro(q *ESJob, tpy string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { return func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { var w webOp err := request.BindArguments(&w) if err != nil { return nil, err } job := q.getENJob(w.ScanType) em := job.job.GetENMap() var jsonBytes []byte switch tpy { case "advance_filter": res, e := job.job.AdvanceFilter(w.OrgName) if e != nil { return mcp.NewToolResultText(fmt.Sprintf("处理异常!")), e } jsonBytes, err = json.Marshal(common.OriginalToMapList(res, em["enterprise_info"])) case "get_ensd": res := job.job.GetEnsD() jsonBytes, err = json.Marshal(res) if err != nil { return mcp.NewToolResultText(string(jsonBytes)), err } case "get_base_info": res, _ := job.job.GetCompanyBaseInfoById(w.OrgName) jsonBytes, err = json.Marshal(common.OriginalToMap(res, em["enterprise_info"])) case "get_page": filed := em[w.Filed] page, err := strconv.Atoi(w.Page) if err != nil { return mcp.NewToolResultText(fmt.Sprintf("处理异常!")), err } res, e := job.job.GetInfoByPage(w.OrgName, page, filed) if e != nil { return mcp.NewToolResultText(fmt.Sprintf("处理异常!")), err } jsonBytes, err = json.Marshal(InfoPage{ res.Total, res.Page, res.Size, res.HasNext, common.OriginalToMapList(res.Data, filed)}) } if err != nil { return mcp.NewToolResultText(fmt.Sprintf("处理异常!")), err } return mcp.NewToolResultText(string(jsonBytes)), nil } } // getInfoByKeyword 根据关键词查企业信息 func getInfoByKeyword(q *ESJob) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { return func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { var w webOp err := request.BindArguments(&w) if err != nil { return nil, err } options := q.op options.KeyWord = w.OrgName options.GetFlags = w.Filed options.ScanType = w.ScanType options.InvestNum = w.Invest options.IsSupplier = w.Supplier options.IsHold = w.Holds options.Deep = w.Depth options.IsMergeOut = true options.Parse() q.AddTask(options.KeyWord) q.wg.Wait() jsonBytes, err := json.Marshal(q.OutDataByEnInfo()) if err != nil { return mcp.NewToolResultText(fmt.Sprintf("处理异常!")), err } return mcp.NewToolResultText(string(jsonBytes)), nil } } func McpServer(options *common.ENOptions) { s := server.NewMCPServer( "EnScan", common.GitTag, ) enTask := NewENTaskQueue(1, options) s.AddTool(mcp.NewTool("根据关键词详细信息", mcp.WithDescription("根据关键词搜索企业列表"), mcp.WithString("type", mcp.Required(), mcp.Description("API类型"), mcp.Enum("aqc", "rb"), ), mcp.WithString("name", mcp.Required(), mcp.Description("企业搜索结果的关键词"), ), ), getInfoPro(enTask, "advance_filter")) s.AddTool(mcp.NewTool("获取企业转换MAP", mcp.WithDescription("获取企业转换MAP"), ), getInfoPro(enTask, "get_ensd")) s.AddTool(mcp.NewTool("根据PID获取企业基本信息", mcp.WithDescription("根据PID获取企业基本信息"), mcp.WithString("type", mcp.Required(), mcp.Description("API类型"), mcp.Enum("aqc", "tyc", "rb"), ), mcp.WithString("name", mcp.Required(), mcp.Description("企业pid"), ), ), getInfoPro(enTask, "get_base_info")) s.AddTool(mcp.NewTool("根据pid分页获取信息", mcp.WithDescription("根据pid依据分类和页码获取对应的信息"), mcp.WithString("type", mcp.Required(), mcp.Description("API类型"), mcp.Enum("aqc", "rb"), ), mcp.WithString("name", mcp.Required(), mcp.Description("企业pid"), ), mcp.WithString("filed", mcp.Required(), mcp.Description("分类,只允许一个"), mcp.Enum("icp", "weibo", "wechat", "app", "weibo", "job", "wx_app", "copyright"), ), mcp.WithString("page", mcp.Required(), mcp.Description("页码信息"), ), ), getInfoPro(enTask, "get_page")) s.AddTool(mcp.NewTool("根据关键词详细信息", mcp.WithDescription("根据关键词搜索企业的icp备案、微博、微信、app、微博、招聘、微信小程序、版权信息"), mcp.WithString("name", mcp.Required(), mcp.Description("企业搜索结果的关键词"), ), mcp.WithString("filed", mcp.Description("获取信息类别多个类别需要以,分隔"), mcp.Enum("icp", "weibo", "wechat", "app", "weibo", "job", "wx_app", "copyright"), ), mcp.WithString("type", mcp.Description("API类型"), mcp.Enum("aqc", "rb"), ), mcp.WithString("invest", mcp.Description("投资比例,选择大于%几的对外投资公司"), ), mcp.WithString("depth", mcp.Description("投资搜索深度,几级的子公司"), ), mcp.WithString("branch", mcp.Description("是否搜索分支机构"), ), ), getInfoByKeyword(enTask)) enTask.StartENWorkers() sseServer := server.NewSSEServer(s, server.WithBaseURL(options.ENConfig.Api.Mcp)) port, err := utils.ExtractPortString(options.ENConfig.Api.Mcp) if err != nil { gologger.Error().Msgf("MCP服务启动失败!") gologger.Fatal().Msgf(err.Error()) } gologger.Info().Msgf("SSE server listening on :" + port) if err := sseServer.Start(":" + port); err != nil { log.Fatalf("Server error: %v", err) } }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/runner/api.go
runner/api.go
package runner import ( "fmt" "github.com/gin-gonic/gin" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "strconv" ) type webOp struct { OrgName string `form:"name" json:"name"` ScanType string `form:"type" json:"type"` Filed string `form:"filed" json:"filed"` Depth int `form:"depth" json:"depth"` Invest float64 `form:"invest" json:"invest"` Holds bool `form:"hold" json:"hold"` Supplier bool `form:"supplier" json:"supplier"` Branch bool `form:"branch" json:"branch"` IsRefresh bool `form:"refresh" json:"refresh"` Page string `form:"page" json:"page"` } func api(options *common.ENOptions) { r := gin.Default() enApiData := make(map[string]map[string][]map[string]string) enApiStatus := make(map[string]bool) enTask := NewENTaskQueue(1, options) getEnInfo := func(c *gin.Context) { w, err := bindWebOp(c) if err != nil { c.JSON(400, gin.H{ "code": 400, "message": err.Error(), }) } var rdata map[string][]map[string]string message := "查询数据中,请稍等..." if is := enApiStatus[w.OrgName]; !is || w.IsRefresh { if data, ok := enApiData[w.OrgName]; !ok || w.IsRefresh { enApiStatus[w.OrgName] = true rdata = enTask.getInfoByApi(w) message = "查询成功" enApiStatus[w.OrgName] = false enApiData[w.OrgName] = rdata } else { rdata = data message = "来源缓存数据" enApiStatus[w.OrgName] = false } } c.JSON(200, gin.H{ "code": 200, "message": message, "data": rdata, }) } r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{ "code": 200, "message": "ENSCAN IS OK!", }) }) r.GET("/status", func(c *gin.Context) { c.JSON(200, gin.H{ "code": 200, "message": "ENSCAN IS OK!", "data": enTask.getStatus(), }) }) getPro := func(c *gin.Context) { h, code, err := advApi(c, enTask, c.Param("type")) if err != nil { return } c.JSON(code, h) } a := r.Group("/api") { a.GET("/info", getEnInfo) a.POST("/info", getEnInfo) a.GET("/pro/:type", getPro) } enTask.StartENWorkers() err := r.Run(options.ENConfig.Api.Api) if err != nil { gologger.Error().Msgf("API服务启动失败!") gologger.Fatal().Msgf(err.Error()) } } type ENStatus struct { JobProcessed int `json:"processed"` JobTotal int `json:"total"` JobItems []ENJobTask `json:"items"` Tasks []ENTask `json:"tasks"` } type ENTask struct { TaskName string `json:"name"` TaskProcessed int `json:"processed"` TaskTotal int `json:"total"` Items []DeepSearchTask `json:"items"` } type InfoPage struct { Total int64 `json:"total"` Page int64 `json:"page"` Size int64 `json:"size"` HasNext bool `json:"has_next"` List []map[string]string `json:"list"` } func (q *ESJob) getStatus() (status ENStatus) { status.JobProcessed = q.processed status.JobTotal = q.total status.JobItems = q.items var taskList []ENTask for s, task := range q.enJob { taskList = append(taskList, ENTask{ TaskName: s, TaskProcessed: task.Processed, TaskTotal: task.Total, Items: task.Task, }) } status.Tasks = taskList return status } func (q *ESJob) getInfoByApi(w webOp) map[string][]map[string]string { options := q.op options.KeyWord = w.OrgName options.GetFlags = w.Filed options.ScanType = w.ScanType options.InvestNum = w.Invest options.IsSupplier = w.Supplier options.IsHold = w.Holds options.Deep = w.Depth options.IsMergeOut = true options.Parse() q.AddTask(w.OrgName) q.wg.Wait() return q.OutDataByEnInfo() } func bindWebOp(c *gin.Context) (w webOp, err error) { err = c.ShouldBind(&w) if err != nil { return w, fmt.Errorf("绑定失败") } if w.OrgName == "" { return w, fmt.Errorf("请输入查询条件") } return w, nil } func advApi(c *gin.Context, enTask *ESJob, tpy string) (r gin.H, code int, err error) { w, err := bindWebOp(c) if err != nil { return r, 400, err } job := enTask.getENJob(w.ScanType) em := job.job.GetENMap() switch tpy { case "advance_filter": res, err := job.job.AdvanceFilter(w.OrgName) if err != nil { return r, 500, err } r = gin.H{ "code": 200, "message": "查询成功", "data": common.OriginalToMapList(res, em["enterprise_info"]), } case "get_ensd": res := job.job.GetEnsD() r = gin.H{ "code": 200, "message": "查询成功", "data": res, } case "get_base_info": res, e := job.job.GetCompanyBaseInfoById(w.OrgName) r = gin.H{ "code": 200, "message": "查询成功", "data": common.OriginalToMap(res, em["enterprise_info"]), "em": e, } case "get_page": filed := em[c.Query("filed")] page, err := strconv.Atoi(c.Query("page")) if err != nil { return r, 500, err } res, err := job.job.GetInfoByPage(w.OrgName, page, filed) if err != nil { return r, 500, err } r = gin.H{ "code": 200, "message": "查询成功", "data": InfoPage{ res.Total, res.Page, res.Size, res.HasNext, common.OriginalToMapList(res.Data, filed), }, } default: return r, 400, fmt.Errorf("接口不存在") } return r, 200, nil }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/runner/enscan.go
runner/enscan.go
package runner import ( "fmt" "github.com/tidwall/gjson" "github.com/tidwall/sjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "github.com/wgpsec/ENScan/common/utils" ) // SearchByKeyWord 根据关键词筛选公司 func (j *EnJob) SearchByKeyWord(keyword string) (string, error) { enList, err := j.job.AdvanceFilter(keyword) if err != nil { gologger.Error().Msg(err.Error()) return "", err } // 检查搜索结果是否为空 if len(enList) == 0 { gologger.Error().Msgf("关键词:\"%s\" 未查询到任何结果", keyword) return "", fmt.Errorf("关键词:\"%s\" 未查询到任何结果", keyword) } enMap := j.job.GetENMap()["enterprise_info"] gologger.Info().Msgf("关键词:\"%s\" 查询到 %d 个结果,默认选择第一个 \n", keyword, len(enList)) //展示结果 utils.TBS(append(enMap.KeyWord[:3], "PID"), append(enMap.Field[:3], enMap.Field[10]), "企业信息", enList) // 选择第一个的PID pid := enList[0].Get(enMap.Field[10]).String() // 检查PID是否为空 if pid == "" { gologger.Error().Msgf("关键词:\"%s\" 获取到的PID为空", keyword) return "", fmt.Errorf("关键词:\"%s\" 获取到的PID为空", keyword) } gologger.Debug().Str("PID", pid).Msgf("搜索") return pid, nil } // getInfoById 根据查询的ID查询公司信息,并关联企业 func (j *EnJob) getInfoById(pid string, searchList []string) error { if pid == "" { gologger.Error().Msgf("获取PID为空!") return fmt.Errorf("获取PID为空") } enMap := j.job.GetENMap() // 基本信息获取 enInfo := j.getCompanyInfoById(pid, searchList, "") enName := enInfo["enterprise_info"][0].Get(enMap["enterprise_info"].Field[0]).String() // 初始化需要深度获取的字段关系 var dps []common.DPS for _, sk := range searchList { // 关联所有DPS数据信息 dps = append(dps, j.getDPS(enInfo[sk], enName, 1, enMap, sk)...) } if len(dps) == 0 { j.closeCH() return nil } gologger.Info().Msgf("DPS长度:%d", len(dps)) // 这里不知道为什么要设置一个很大的队列长度,否则会卡死 j.newTaskQueue(999999) j.StartWorkers() for _, dp := range dps { j.AddTask(DeepSearchTask{ DPS: dp, SearchList: searchList, }) } j.wg.Wait() j.closeCH() return nil } // getCompanyInfoById 获取公司的详细的信息,包含下属列表信息 func (j *EnJob) getCompanyInfoById(pid string, searchList []string, ref string) map[string][]gjson.Result { enData := make(map[string][]gjson.Result) // 获取公司基本信息 res, enMap := j.job.GetCompanyBaseInfoById(pid) gologger.Info().Msgf("正在获取⌈%s⌋信息", res.Get(j.job.GetENMap()["enterprise_info"].Field[0])) format, err := dataFormat(res, "enterprise_info", ref) if err != nil { gologger.Error().Msgf("格式化数据失败: %v", err) } enData["enterprise_info"] = append(enData["enterprise_info"], format) // 适配风鸟 if res.Get("orderNo").String() != "" { pid = res.Get("orderNo").String() } // 批量获取信息 for _, sk := range searchList { // 不支持这个搜索类型就跳过去 if _, ok := enMap[sk]; !ok { continue } s := enMap[sk] // 没有这个数据就跳过去,提高速度 if s.Total <= 0 || s.Api == "" { gologger.Debug().Str("type", sk).Msgf("判定 ⌈%s⌋ 为空,自动跳过获取\n数量:%d\nAPI:%s", s.Name, s.Total, s.Api) continue } listData, err := j.getInfoList(pid, s, sk, ref) if err != nil { gologger.Error().Msgf("尝试获取⌈%s⌋发生异常\n%v", s.Name, err) continue } enData[sk] = append(enData[sk], listData...) } // 实时存入一个查询的完整信息 j.dataCh <- enData return enData } // getInfoList 获取列表信息 func (j *EnJob) getInfoList(pid string, em *common.EnsGo, sk string, ref string) (resData []gjson.Result, err error) { var listData []gjson.Result gologger.Info().Msgf("正在获取 ⌈%s⌋\n", em.Name) data, err := j.getInfoPage(pid, 1, em) if err != nil { // 如果第一页获取失败,就不继续了,判断直接失败 return resData, err } listData = data.Data // 如果一页能获取完就不翻页了 if data.Size < data.Total && data.Size > 0 { pages := int((data.Total + data.Size - 1) / data.Size) for i := 2; i <= pages; i++ { gologger.Info().Msgf("正在获取 ⌈%s⌋ 第⌈%d/%d⌋页\n", em.Name, i, pages) d, e := j.getInfoPage(pid, i, em) if e != nil { gologger.Error().Msgf("GET ⌈%s⌋ 第⌈%d⌋页失败\n", em.Name, i) continue } listData = append(listData, d.Data...) } } if len(listData) == 0 { return resData, err } for _, y := range listData { d, e := dataFormat(y, sk, ref) if e != nil { gologger.Error().Msgf("格式化数据失败: %v", err) } resData = append(resData, d) } // 展示数据 utils.TBS(em.KeyWord, em.Field, em.Name, resData) return resData, err } // processTask 处理企业关系任务,进行关联查询 func (j *EnJob) processTask(task DeepSearchTask) { gologger.Info().Msgf("【%d,%d】正在获取⌈%s⌋信息,关联原因 %s", j.processed, j.total, task.Name, task.Ref) data := j.getCompanyInfoById(task.Pid, task.SearchList, task.Ref) j.wg.Done() // 如果已经到了对应层级就不需要跑了 if task.Deep >= j.job.GetEnsD().Op.Deep { return } gologger.Info().Msgf("⌈%s⌋深度搜索到第⌈%d⌋层", task.Name, task.Deep) // 根据返回结果继续筛选进行关联 dps := j.getDPS(data[task.SK], task.Name, task.Deep+1, j.job.GetENMap(), task.SK) for _, dp := range dps { j.AddTask(DeepSearchTask{ dp, task.SearchList, }) } } // getDPS 根据List和规则筛选需要深度搜索的规则 func (j *EnJob) getDPS(list []gjson.Result, ref string, deep int, ems map[string]*common.EnsGo, sk string) (dpList []common.DPS) { op := j.job.GetEnsD().Op if op.Deep <= 1 { return } // 前置判断 if len(list) == 0 { return } // 跳过非深度搜索字段 if !utils.IsInList(sk, common.DeepSearch) { return } // 初始化判断变量 em := ems[sk] nPid := em.Field[len(em.Field)-2] nEnName := em.Field[0] nStatus := em.Field[2] nScale := em.Field[3] // 初始化关联原因 association := fmt.Sprintf("%s %s", em.Name, ref) gologger.Info().Msgf("%s", association) // 增加数据,该类型下的全部企业数据 for _, r := range list { // 如果不深度搜索分支机构就跳过 if sk == "branch" && !op.IsSearchBranch { continue } tName := r.Get(nEnName).String() // 正则过滤器匹配 if op.NameFilterRegexp != nil && op.NameFilterRegexp.MatchString(tName) { gologger.Info().Msgf("根据过滤器跳过 [%s]", tName) continue } // 判断企业状态 tStatus := r.Get(nStatus).String() if utils.IsInList(tStatus, common.AbnormalStatus) { gologger.Info().Msgf("根据状态跳过[%s]的企业[%s] ", tStatus, tName) continue } // 判断计算投资比例 if sk == "invest" { investNum := utils.FormatInvest(r.Get(nScale).String()) if investNum < op.InvestNum { continue } association = fmt.Sprintf("%s ⌈%d⌋级投资⌈%.2f%%⌋-%s", tName, deep, investNum, ref) } // 关联返回企业的DPS数据 gologger.Debug().Msgf("关联⌈%s⌋企业信息,关联原因 %s", tName, association) pid := r.Get(nPid).String() dpList = append(dpList, common.DPS{ Name: tName, Pid: pid, Ref: association, Deep: deep, SK: sk, }) } return dpList } func (q *ESJob) InfoToMap(j *EnJob, ref string) (res map[string][]map[string]string) { q.mu.Lock() defer q.mu.Unlock() gologger.Debug().Msgf("InfoToMap\nReceived data: %v\n", j.data) res = common.InfoToMap(j.data, j.getENMap(), ref) j.data = map[string][]gjson.Result{} return res } // ListDataFormat 对list数据进行格式化处理 func dataFormat(data gjson.Result, typ string, ref string) (res gjson.Result, e error) { // 对这条数据加入关联原因,为什么会关联到这个数 valueTmp, err := sjson.Set(data.Raw, "ref", ref) if err != nil { return res, err } // 对其他特殊渠道信息进行处理 if typ == "icp" { // TODO 需要完善下针对多个域名在一行的情况,根据,分隔 } // 处理完成恢复返回 res = gjson.Parse(valueTmp) return res, nil }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/runner/bean.go
runner/bean.go
package runner import ( "fmt" "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" ) // ENSOp 用于接收前端传递的参数 type ENSOp struct { OrgName string `form:"name" json:"name"` ScanType string `form:"type" json:"type"` Filed string `form:"filed" json:"filed"` Depth int `form:"depth" json:"depth"` Invest float64 `form:"invest" json:"invest"` Holds bool `form:"hold" json:"hold"` Supplier bool `form:"supplier" json:"supplier"` Branch bool `form:"branch" json:"branch"` } func (q *ESJob) NewEnJob(name string) (n *EnJob) { q.mu.Lock() defer q.mu.Unlock() if _, exists := q.enJob[name]; !exists { q.enJob[name] = &ENJob{ DataCh: make(chan map[string][]gjson.Result, 10), Data: make(map[string][]gjson.Result), Task: []DeepSearchTask{}, TaskCh: make(chan DeepSearchTask), } } n = &EnJob{ dataCh: q.enJob[name].DataCh, data: q.enJob[name].Data, task: &q.enJob[name].Task, taskCh: q.enJob[name].TaskCh, total: q.enJob[name].Total, processed: q.enJob[name].Processed, } return n } // getInfoPage 根据页面获取信息,兼容不同实现 func (j *EnJob) getInfoPage(pid string, page int, em *common.EnsGo) (common.InfoPage, error) { if j == nil { return common.InfoPage{}, fmt.Errorf("EnJob is nil") } if j.job != nil { return j.job.GetInfoByPage(pid, page, em) } if j.app != nil { return j.app.GetInfoByPage(pid, page, em) } return common.InfoPage{}, fmt.Errorf("no valid implementation") } func (j *EnJob) getENMap() map[string]*common.EnsGo { if j == nil { return map[string]*common.EnsGo{} } if j.job != nil { return j.job.GetENMap() } if j.app != nil { return j.app.GetENMap() } return map[string]*common.EnsGo{} } func (j *EnJob) startCH() { go func() { for { select { case data, ok := <-j.dataCh: if !ok { j.enWg.Done() return } if data != nil { j.mu.Lock() gologger.Debug().Msgf("startCH\nReceived data: %v\n", data) for key, newResults := range data { j.data[key] = append(j.data[key], newResults...) } j.mu.Unlock() } } } }() } func (j *EnJob) closeCH() { close(j.dataCh) j.mu.Lock() defer j.mu.Unlock() if j.taskCh != nil { close(j.taskCh) } if j.Done != nil { close(j.Done) } } func (j *ESJob) closeCH() { close(j.ch) j.mu.Lock() defer j.mu.Unlock() if j.Jobs != nil { close(j.Jobs) } if j.Done != nil { close(j.Done) } } type DeepSearchTask struct { common.DPS SearchList []string `json:"search_list"` } func (j *EnJob) newTaskQueue(capacity int) { j.taskCh = make(chan DeepSearchTask, capacity) j.Done = make(chan struct{}) } func (j *EnJob) reTaskQueue() { for _, task := range *j.task { j.taskCh <- task j.wg.Add(1) } } func (q *EnJob) AddTask(task DeepSearchTask) { q.taskCh <- task q.mu.Lock() defer q.mu.Unlock() *q.task = append(*q.task, task) q.wg.Add(1) q.total++ } func (q *EnJob) StartWorkers() { go func() { for { select { case task, ok := <-q.taskCh: if !ok { return } q.processTask(task) *q.task = (*q.task)[1:] q.mu.Lock() q.processed++ q.mu.Unlock() } } }() }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/runner/app.go
runner/app.go
package runner import ( "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common/gologger" "github.com/wgpsec/ENScan/common/utils" ) // getAppById 直接使用关键词调用插件查询 func (j *EnJob) getAppByKeyWord(keyWord string, searchList []string, ref string) (e error) { enData := make(map[string][]gjson.Result) em := j.app.GetENMap() // 批量获取信息 for _, sk := range searchList { // 不支持这个搜索类型就跳过去 if _, ok := em[sk]; !ok { continue } s := em[sk] listData, err := j.getInfoList(keyWord, s, sk, ref) if err != nil { gologger.Error().Msgf("尝试获取⌈%s⌋发生异常\n%v", s.Name, err) e = err continue } enData[sk] = append(enData[sk], listData...) } gologger.Debug().Msgf("getAppByKeyWord\nReceived data: %v\n", enData) j.dataCh <- enData j.closeCH() return e } func (j *EnJob) getAppById(rdata map[string][]map[string]string, searchList []string) (enInfo map[string][]gjson.Result) { enData := make(map[string][]gjson.Result) enMap := j.app.GetENMap() for _, sk := range searchList { if _, ok := enMap[sk]; !ok { continue } s := enMap[sk] var enList []string // 获取需要的参数,比如企业名称、域名等 // 0和1分别表示 ENSMapLN 的 key 和 value,定位出需要的数据 // 暂时没遇到需要多种类型进行匹配的参数 ap := s.AppParams for _, ens := range rdata[ap[0]] { enList = append(enList, ens[ap[1]]) } // 对获取的目标进行去重 utils.SetStr(enList) gologger.Info().Msgf("共获取到【%d】条,开始执行插件获取信息", len(enList)) for i, v := range enList { gologger.Info().Msgf("正在获取第【%d】条数据 【%s】", i+1, v) listData := j.app.GetInfoList(v, sk) enData[sk] = append(enData[sk], listData...) utils.TBS(s.KeyWord, s.Field, s.Name, listData) } } return enData }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/kuaicha/utils.go
internal/kuaicha/utils.go
package kuaicha import ( "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "time" ) func getENMap() map[string]*common.EnsGo { ensInfoMap := make(map[string]*common.EnsGo) ensInfoMap = map[string]*common.EnsGo{ "enterprise_info": { Name: "企业信息", Api: "enterprise_info_api/V1/find_company_basic_info", Field: []string{"name", "legal_person", "state", "telphone", "email", "reg_capital", "established_date", "corp_address", "operating_scope", "unified_social_credit_code", "org_id"}, KeyWord: []string{"企业名称", "法人代表", "经营状态", "电话", "邮箱", "注册资本", "成立日期", "注册地址", "经营范围", "统一社会信用代码", "PID"}, }, //"icp": { // Name: "ICP备案", // Api: "detail/icpinfoAjax", // Field: []string{"siteName", "homeSite", "domain", "icpNo", ""}, // KeyWord: []string{"网站名称", "网址", "域名", "网站备案/许可证号", "公司名称"}, //}, //"app": { // Name: "APP", // Api: "c/appinfoAjax", // Field: []string{"name", "classify", "", "", "logoBrief", "logo", "", "", ""}, // KeyWord: []string{"名称", "分类", "当前版本", "更新时间", "简介", "logo", "Bundle ID", "链接", "market"}, //}, //"weibo": { // Name: "微博", // Api: "c/microblogAjax", // Field: []string{"nickname", "weiboLink", "brief", "logo"}, // KeyWord: []string{"微博昵称", "链接", "简介", "LOGO"}, //}, "wechat": { Name: "微信公众号", Api: "open/commercial/v1/wechat_public_number", Field: []string{"wechat_public_number", "wechat_number", "introduction", "qr_code", ""}, KeyWord: []string{"名称", "ID", "描述", "二维码", "LOGO"}, }, "job": { Name: "招聘信息", Api: "open/commercial/v1/require_info", Field: []string{"position", "background", "location", "publish_time", "url"}, KeyWord: []string{"招聘职位", "学历要求", "工作地点", "发布日期", "招聘描述"}, }, "copyright": { Name: "软件著作权", Api: "open/trademark/v1/software_info", Field: []string{"software_full_name", "software_short_name", "type", "reg_num", ""}, KeyWord: []string{"软件名称", "软件简介", "分类", "登记号", "权利取得方式"}, }, "supplier": { Name: "供应商", Api: "open/commercial/v1/main_suppliers_extend", Field: []string{"", "ratio", "amt", "publish_time", "", "supplier_to_customer_type", "orgid"}, KeyWord: []string{"名称", "金额占比", "金额", "报告期/公开时间", "数据来源", "关联关系", "PID"}, }, "invest": { Name: "投资信息", Api: "open/app/v1/pc_enterprise/invest_abroad/list", Field: []string{"frgn_invest_corp_name", "legal_representative", "", "invest_ratio", "frgn_invest_corp_id"}, KeyWord: []string{"企业名称", "法人", "状态", "投资比例", "PID"}, Fids: "&is_latest=1", }, "holds": { Name: "控股企业", Api: "open/app/v1/pc_enterprise/hold_corp/list", Field: []string{"hold_corp_name", "legal_representative", "", "hold_ratio", "", "hold_corp_code"}, KeyWord: []string{"企业名称", "法人", "状态", "投资比例", "持股层级", "PID"}, }, "branch": { Name: "分支信息", Api: "open/app/v1/pc_enterprise/branch_office/list", Field: []string{"org_name", "person_name", "", "org_id"}, KeyWord: []string{"企业名称", "法人", "状态", "PID"}, }, "partner": { Name: "股东信息", Api: "open/app/v1/pc_enterprise/shareholder/latest_announcement", Field: []string{"shareholder_name", "shareholding_ratio", "share_held_num", "shareholder_id"}, KeyWord: []string{"股东名称", "持股比例", "认缴出资金额", "PID"}, }, } for k := range ensInfoMap { ensInfoMap[k].KeyWord = append(ensInfoMap[k].KeyWord, "数据关联 ") ensInfoMap[k].Field = append(ensInfoMap[k].Field, "ref") } return ensInfoMap } func (h *KC) req(url string, data string) string { c := common.NewClient(map[string]string{ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 Edg/98.0.1108.43", "Accept": "text/html, application/xhtml+xml, image/jxr, */*", "Content-Type": "application/json;charset=UTF-8", "Cookie": h.Options.GetCookie("kc"), "Source": "PC", "Referer": "https://www.kuaicha365.com/search-result?", }, h.Options) method := "GET" if data != "" { method = "POST" c.SetBody(data) } resp, err := c.Send(method, url) if err != nil { gologger.Error().Msgf("【KC】请求发生错误, %s 5秒后重试\n%s\n", url, err) time.Sleep(5 * time.Second) return h.req(url, data) } if resp.IsSuccessState() { return resp.String() } else if resp.StatusCode == 403 { gologger.Error().Msgf("【KC】ip被禁止访问网站,请更换ip\n") } else if resp.StatusCode == 401 { gologger.Error().Msgf("【KC】Cookie有问题或过期,请重新获取\n") } else if resp.StatusCode == 302 { gologger.Error().Msgf("【KC】需要更新Cookie\n") } else if resp.StatusCode == 404 { gologger.Error().Msgf("【KC】请求错误 404 %s \n", url) } else { gologger.Error().Msgf("【KC】未知错误 %s\n", resp.StatusCode) } return "" }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/kuaicha/kuaicha.go
internal/kuaicha/kuaicha.go
package kuaicha import ( "fmt" "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "strconv" "strings" ) type KC struct { Options *common.ENOptions } func (h *KC) AdvanceFilter(name string) ([]gjson.Result, error) { url := "https://www.kuaicha365.com/enterprise_info_app/V1/search/company_search_pc" searchStr := `{"search_conditions":[],"keyword":"` + name + `","page":1,"page_size":20}"}` content := h.req(url, searchStr) content = strings.ReplaceAll(content, "<em>", "⌈") content = strings.ReplaceAll(content, "</em>", "⌋") enList := gjson.Get(content, "data.list").Array() if len(enList) == 0 { gologger.Debug().Str("查询请求", name).Msg(content) return enList, fmt.Errorf("【KC】没有查询到关键词 ⌈%s⌋ \n", name) } return enList, nil } func (h *KC) GetENMap() map[string]*common.EnsGo { return getENMap() } func (h *KC) GetEnsD() common.ENsD { ensD := common.ENsD{Name: h.Options.KeyWord, Pid: h.Options.CompanyID, Op: h.Options} return ensD } func (h *KC) GetCompanyBaseInfoById(pid string) (gjson.Result, map[string]*common.EnsGo) { ensInfoMap := getENMap() detailRess := h.req("https://www.kuaicha365.com/open/app/v1/pc_enterprise/basic/info?org_id="+pid, "") detailRes := gjson.Get(detailRess, "data") // 匹配统计数据,需要从页面中提取数据来判断 for k, _ := range ensInfoMap { ensInfoMap[k].Total = 1 } return detailRes, ensInfoMap } func (h *KC) GetInfoByPage(pid string, page int, em *common.EnsGo) (info common.InfoPage, err error) { urls := "https://www.kuaicha365.com/" + em.Api if strings.Contains(em.Api, "open/app/v1") { urls += "?page_size=10" + "&org_id=" } else { urls += "?pageSize=10&&orgid=" } urls += pid + em.Fids + "&page=" + strconv.Itoa(page) content := h.req(urls, "") data := gjson.Get(content, "data") info = common.InfoPage{ Size: 10, Total: data.Get("total").Int(), Data: data.Get("list").Array(), HasNext: data.Get("next_page").Bool(), } return info, err }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/app/qimai/utils.go
internal/app/qimai/utils.go
package qimai import ( "encoding/base64" "fmt" "github.com/imroc/req/v3" "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "github.com/wgpsec/ENScan/common/utils" "sort" "strings" "time" ) type EnsGo struct { name string api string fids string params map[string]string field []string keyWord []string typeInfo []string } type EnInfos struct { Name string Pid string RegCode string Infos map[string][]gjson.Result } type GetData struct { id string params map[string]string } func getENMap() map[string]*EnsGo { ensInfoMap := make(map[string]*EnsGo) ensInfoMap = map[string]*EnsGo{ "enterprise_info": { name: "企业信息", api: "company/getCompany", params: map[string]string{ "id": "", }, field: []string{"name", "legal", "type", "telephone", "email", "registered", "creatTime", "address", "scope", "creditCode", "id"}, keyWord: []string{"企业名称", "法人代表", "经营状态", "电话", "邮箱", "注册资本", "成立日期", "注册地址", "经营范围", "统一社会信用代码", "PID"}, }, "app": { name: "APP", api: "company/getCompanyApplist", field: []string{"appInfo.appName", "app_category", "", "time", "", "appInfo.icon", "", "", ""}, keyWord: []string{"名称", "分类", "当前版本", "更新时间", "简介", "logo", "Bundle ID", "链接", "market"}, }, } for k, _ := range ensInfoMap { ensInfoMap[k].keyWord = append(ensInfoMap[k].keyWord, "数据关联 ") ensInfoMap[k].field = append(ensInfoMap[k].field, "inFrom") } return ensInfoMap } func sign(params string, url string) string { i := "xyz517cda96efgh" f := -utils.RangeRand(100, 10000) o := time.Now().Unix()*1000 - (f) - 1515125653845 r := base64.StdEncoding.EncodeToString([]byte(params)) r = fmt.Sprintf("%s@#%s@#%d@#1", r, url, o) e := len(r) n := len(i) ne := "" for t := 0; t < e; t++ { ne += string(rune(int(r[t]) ^ int(i[(t+10)%n]))) } ne = base64.StdEncoding.EncodeToString([]byte(ne)) return ne } func GetReq(url string, params map[string]string, options *common.ENOptions) string { client := req.C() client.SetTimeout(time.Duration(options.TimeOut) * time.Minute) if options.Proxy != "" { client.SetProxyURL(options.Proxy) } gologger.Debug().Msgf("[qimai] url: %s, params: %s\n", url, params) cookie := options.ENConfig.Cookies.QiMai cookie = strings.ReplaceAll(cookie, "syncd", "syncds") cookie = cookie + ";synct=1690024926.196; syncd=-1652" client.SetCommonHeaders(map[string]string{ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 Edg/98.0.1108.43", "Accept": "text/html, application/xhtml+xml, image/jxr, */*", "Cookie": cookie, "Referer": "https://www.qimai.cn/", }) var par []string params["analysis"] = "" for _, v := range params { par = append(par, v) } sort.Strings(par) pts := strings.Join(par, "") analysis := sign(pts, "/"+url) params["analysis"] = analysis urls := "https://api.qimai.cn/" + url resp, err := client.R().SetQueryParams(params).Get(urls) gologger.Debug().Msgf("【qimai】%s\n", resp) if err != nil { if options.Proxy != "" { client.SetProxy(nil) } gologger.Error().Msgf("请求发生错误,5秒后重试\n%s\n", err) time.Sleep(5 * time.Second) return GetReq(url, params, options) } if resp.StatusCode == 200 { return resp.String() } else if resp.StatusCode == 403 { gologger.Error().Msgf("ip被禁止访问网站,请更换ip\n") } else if resp.StatusCode == 401 { gologger.Error().Msgf("Cookie有问题或过期,请重新获取\n") } else if resp.StatusCode == 302 { gologger.Error().Msgf("需要更新Cookie\n") } else if resp.StatusCode == 404 { gologger.Error().Msgf("目标不存在\n") } else { gologger.Error().Msgf("未知错误 %s\n", resp.StatusCode) } return "" }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/app/qimai/qimai.go
internal/app/qimai/qimai.go
package qimai import ( "fmt" "github.com/tidwall/gjson" "github.com/tidwall/sjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "strconv" ) func GetInfoByKeyword(options *common.ENOptions) (ensInfos *common.EnInfos, ensOutMap map[string]*common.ENSMap) { ensInfos = &common.EnInfos{} ensInfos.Infos = make(map[string][]gjson.Result) ensOutMap = make(map[string]*common.ENSMap) ensInfos.Name = options.KeyWord params := map[string]string{ "page": "1", "search": options.KeyWord, "market": "1", } res := gjson.Parse(GetReq("search/android", params, options)).Get("appList").Array() if res[0].Get("company.id").Int() != 0 { fmt.Println(res[0].Get("company.name")) ensInfos.Infos = GetInfoByCompanyId(res[0].Get("company.id").Int(), options) } for k, v := range getENMap() { ensOutMap[k] = &common.ENSMap{Name: v.name, JField: v.field, KeyWord: v.keyWord} } return ensInfos, ensOutMap } func GetInfoByCompanyId(companyId int64, options *common.ENOptions) (data map[string][]gjson.Result) { gologger.Info().Msgf("GetInfoByCompanyId: %d\n", companyId) data = map[string][]gjson.Result{} ensMap := getENMap() params := map[string]string{ "id": strconv.Itoa(int(companyId)), } searchInfo := "enterprise_info" //gjson.GetMany(gjson.Get(GetReq(ensMap[searchInfo].api, params, options), "data").Raw, ensMap[searchInfo].field...) r, err := sjson.Set(gjson.Get(GetReq(ensMap[searchInfo].api, params, options), "data").Raw, "id", companyId) if err != nil { gologger.Error().Msgf("Set pid error: %s", err.Error()) } rs := gjson.Parse(r) data[searchInfo] = append(data[searchInfo], rs) params["page"] = "1" params["apptype"] = "2" searchInfo = "app" data[searchInfo] = append(data[searchInfo], getInfoList(ensMap["app"].api, params, options)...) //安卓 params["page"] = "1" params["apptype"] = "3" data[searchInfo] = append(data[searchInfo], getInfoList(ensMap["app"].api, params, options)...) //命令输出展示 var tdata [][]string for _, y := range data[searchInfo] { results := gjson.GetMany(y.Raw, ensMap[searchInfo].field...) var str []string for _, ss := range results { str = append(str, ss.String()) } tdata = append(tdata, str) } //common.TableShow(ensMap[searchInfo].keyWord, tdata, options) return data } func getInfoList(types string, params map[string]string, options *common.ENOptions) (listData []gjson.Result) { data := gjson.Parse(GetReq(types, params, options)) if data.Get("code").String() == "10000" { getPath := "appList" getPage := "maxPage" if types == "company/getCompanyApplist" { if params["apptype"] == "2" { getPath = "ios" } else if params["apptype"] == "3" { getPath = "android" } getPage = getPath + "PageInfo.pageCount" getPath += "AppInfo" data = data.Get("data") } listData = append(listData, data.Get(getPath).Array()...) if data.Get(getPage).Int() <= 1 { return listData } else { for i := 2; i <= int(data.Get(getPage).Int()); i++ { gologger.Info().Msgf("getInfoList: %s %d\n", types, i) params["page"] = fmt.Sprintf("%d", i) listData = append(listData, gjson.Parse(GetReq(types, params, options)).Get("data."+getPath).Array()...) } } if len(listData) == 0 { gologger.Error().Msgf("没有数据") } } else { gologger.Error().Msgf("获取数据失败,请检查是否登陆\n") gologger.Debug().Msgf("%s\n", data.Raw) } return listData }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/app/coolapk/coolapk.go
internal/app/coolapk/coolapk.go
package coolapk import ( "encoding/base64" "github.com/imroc/req/v3" "github.com/olekukonko/tablewriter" "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "github.com/wgpsec/ENScan/common/utils" "os" "strconv" "time" ) func GetReq(options *common.ENOptions) (ensInfos *common.EnInfos, ensOutMap map[string]*common.ENSMap) { defer func() { if x := recover(); x != nil { gologger.Error().Msgf("[coolapk] GetReq panic: %v", x) } }() ensInfos = &common.EnInfos{} ensInfos.Infos = make(map[string][]gjson.Result) ensOutMap = make(map[string]*common.ENSMap) field := []string{"title", "catName", "apkversionname", "lastupdate", "shorttitle", "logo", "apkname", "", "", "ref"} keyWord := []string{"名称", "分类", "当前版本", "更新时间", "简介", "logo", "Bundle ID", "链接", "market", "数据关联"} ensOutMap["app"] = &common.ENSMap{Name: "app", JField: field, KeyWord: keyWord} developer := options.KeyWord gologger.Info().Msgf("酷安API查询 %s\n", developer) deviceId := "34de7eef-8400-3300-8922-a1a34e7b9b4f" ctime := time.Now().Unix() md5Timestamp := utils.Md5(strconv.FormatInt(ctime, 10)) arg1 := "token://com.coolapk.market/c67ef5943784d09750dcfbb31020f0ab?" + md5Timestamp + "$" + deviceId + "&com.coolapk.market" md5Str := utils.Md5(base64.StdEncoding.EncodeToString([]byte(arg1))) token := md5Str + deviceId + "0x" + strconv.FormatInt(ctime, 16) gologger.Debug().Msgf("[coolapk] TOKEN" + token) url := "https://api.coolapk.com/v6/apk/search?searchType=developer&developer=" + developer + "&page=1&firstLaunch=0&installTime=" + strconv.FormatInt(ctime, 10) + "&lastItem=13988" client := req.C() //client.SetTimeout(common.RequestTimeOut) client.SetCommonHeaders(map[string]string{ "X-App-Token": token, "X-App-Version": "10.5.3", "User-Agent": "Dalvik/2.1.0 (Linux; U; Android 6.0.1; Nexus 6P Build/MMB29M) (#Build; google; Nexus 6P; MMB29M; 6.0.1) +CoolMarket/10.5.3-2009271", "X-Api-Version": "10", "X-App-Device": "QZDIzVHel5EI7UGbn92bnByOpV2dhVHSgszQyoTMzoDM2oTQCpDMwoDNyAyOsxWduByO2ADO4kjNxIDM2gjN3YDOgsDZiBTYykzYkZDNlBzY0ITZ", //"Accept-Encoding": {"gzip"}, "X-Dark-Mode": "0", "X-Requested-With": "XMLHttpRequest", "X-App-Code": "2009271", "X-App-Id": "com.coolapk.market", }) resp, err := client.R().Get(url) if err != nil { gologger.Fatal().Msgf("coolapk 请求发生错误\n%s\n", err) } appList := gjson.Get(resp.String(), "data").Array() ensInfos.Infos["app"] = appList ensInfos.Name = options.KeyWord gologger.Info().Msgf("酷安API 查询到 %d 条数据\n", len(appList)) if options.IsShow { table := tablewriter.NewWriter(os.Stdout) table.SetHeader(keyWord) for _, v := range appList { res := gjson.GetMany(v.Raw, field...) var str []string for k, vv := range res { if field[k] == "lastupdate" { str = append(str, time.Unix(vv.Int(), 0).Format("2006-01-02 15:04:05")) } else { str = append(str, vv.String()) } } table.Append(str) } table.Render() } return ensInfos, ensOutMap }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/app/miit/bean.go
internal/app/miit/bean.go
package miit import ( "crypto/tls" "github.com/imroc/req/v3" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "time" ) func getENMap() map[string]*common.EnsGo { ensInfoMap := make(map[string]*common.EnsGo) ensInfoMap = map[string]*common.EnsGo{ "icp": { Name: "ICP备案", Api: "web", Field: []string{"", "domain", "domain", "serviceLicence", "unitName"}, KeyWord: []string{"网站名称", "网址", "域名", "网站备案/许可证号", "公司名称"}, }, "app": { Name: "APP", Api: "app", Field: []string{"serviceName", "serviceType", "version", "updateRecordTime", "", "", "", "", ""}, KeyWord: []string{"名称", "分类", "当前版本", "更新时间", "简介", "logo", "Bundle ID", "链接", "market"}, }, "wx_app": { Name: "小程序", Api: "miniapp", Field: []string{"serviceName", "serviceType", "", "", ""}, KeyWord: []string{"名称", "分类", "头像", "二维码", "阅读量"}, }, "fastapp": { Name: "快应用", Api: "fastapp", Field: []string{"serviceName", "serviceType", "", "", ""}, KeyWord: []string{"名称", "分类", "头像", "二维码", "阅读量"}, }, } for k := range ensInfoMap { // 获取插件需要的信息 ensInfoMap[k].AppParams = [2]string{"enterprise_info", "name"} ensInfoMap[k].KeyWord = append(ensInfoMap[k].KeyWord, "数据关联 ") ensInfoMap[k].Field = append(ensInfoMap[k].Field, "inFrom") } return ensInfoMap } func (h *Miit) getReq(url string, data string) string { options := h.Options client := req.C() client.SetTLSFingerprintChrome() client.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) client.SetTimeout(time.Duration(options.TimeOut) * time.Minute) if options.Proxy != "" { client.SetProxyURL(options.Proxy) } client.SetCommonHeaders(map[string]string{ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 Edg/98.0.1108.43", "Accept": "text/html, application/xhtml+xml, image/jxr, */*", "Content-Type": "application/json;charset=UTF-8", }) //加入随机延时 time.Sleep(time.Duration(options.GetDelayRTime()) * time.Second) clientR := client.R() method := "GET" if data == "" { method = "GET" } else { method = "POST" clientR.SetBody(data) } resp, err := clientR.Send(method, url) if err != nil { if options.Proxy != "" { client.SetProxy(nil) } gologger.Error().Msgf("【miit】请求发生错误, %s 10秒后重试\n%s\n", url, err) time.Sleep(10 * time.Second) return h.getReq(url, data) } if resp.IsSuccessState() { return resp.String() } else { gologger.Error().Msgf("【miit】未知错误 %s\n", resp.StatusCode) } return "" }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/app/miit/miit.go
internal/app/miit/miit.go
package miit import ( urlTool "net/url" "strconv" "time" "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" ) type Miit struct { Options *common.ENOptions } func (h *Miit) GetInfoList(keyword string, types string) []gjson.Result { enMap := getENMap() return h.getInfoList(keyword, enMap[types].Api, h.Options) } func (h *Miit) GetENMap() map[string]*common.EnsGo { return getENMap() } func (h *Miit) GetInfoByPage(keyword string, page int, em *common.EnsGo) (info common.InfoPage, err error) { url := h.Options.ENConfig.App.MiitApi + "/query/" + em.Api + "?page=" + strconv.Itoa(page) + "&search=" + urlTool.QueryEscape(keyword) content := h.getReq(url+"&page=1", "") var listData []gjson.Result data := gjson.Get(content, "params") listData = data.Get("list").Array() info = common.InfoPage{ Total: data.Get("total").Int(), Size: data.Get("pages").Int(), HasNext: data.Get("hasNextPage").Bool(), Data: listData, } return info, err } func (h *Miit) getInfoList(keyword string, types string, options *common.ENOptions) []gjson.Result { url := options.ENConfig.App.MiitApi + "/query/" + types + "?page=1&search=" + urlTool.QueryEscape(keyword) content := h.getReq(url+"&page=1", "") var listData []gjson.Result data := gjson.Get(content, "params") listData = data.Get("list").Array() if data.Get("hasNextPage").Bool() { for i := 2; int(data.Get("pages").Int()) >= i; i++ { gologger.Info().Msgf("当前:%s,%d\n", types, i) reqUrls := url + "&page=" + strconv.Itoa(i) // 强制延时!!特别容易被封 time.Sleep(5 * time.Second) content = h.getReq(reqUrls, "") listData = append(listData, gjson.Get(content, "data.list").Array()...) } } return listData }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/qidian/utils.go
internal/qidian/utils.go
package qidian import ( "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "time" ) func (h *QD) req(url string, data string) string { c := common.NewClient(map[string]string{ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 Edg/98.0.1108.43", "Accept": "text/html, application/xhtml+xml, image/jxr, */*", "Content-Type": "application/json;charset=UTF-8", "Cookie": h.Options.GetCookie("qd"), "Referer": "https://www.dingtalk.com/", }, h.Options) if data == "" { data = "{}" } method := "GET" if data == "{}" { method = "GET" } else { method = "POST" c.SetBody(data) } resp, err := c.Send(method, url) if err != nil { gologger.Error().Msgf("【qidian】请求发生错误, %s 5秒后重试\n%s\n", url, err) time.Sleep(5 * time.Second) return h.req(url, data) } if resp.StatusCode == 200 { return resp.String() } else if resp.StatusCode == 403 { gologger.Error().Msgf("【qidian】ip被禁止访问网站,请更换ip\n") } else if resp.StatusCode == 401 { gologger.Error().Msgf("【qidian】Cookie有问题或过期,请重新获取\n") } else if resp.StatusCode == 302 { gologger.Error().Msgf("【qidian】需要更新Cookie\n") } else if resp.StatusCode == 404 { gologger.Error().Msgf("【qidian】请求错误 404 %s \n", url) } else { gologger.Error().Msgf("【qidian】未知错误 %s\n", resp.StatusCode) } return "" } type EnsGo struct { name string api string dataModuleId int fids string gNum string // 获取数量的json关键词 getDetail->CountInfo sData map[string]string field []string keyWord []string typeInfo []string } type EnInfos struct { Name string Pid string legalPerson string openStatus string email string telephone string branchNum int64 investNum int64 Infos map[string][]gjson.Result } func getENMap() map[string]*common.EnsGo { resEnsMap := map[string]*common.EnsGo{ "enterprise_info": { Name: "企业信息", DataModuleId: 748, Field: []string{"Name", "Oper.Name", "ShortStatus", "ContactInfo.PhoneNumber", "ContactInfo.Email", "RegistCapi", "CheckDate", "Address", "Scope", "CreditCode", "_id"}, KeyWord: []string{"企业名称", "法人代表", "经营状态", "电话", "邮箱", "注册资本", "成立日期", "注册地址", "经营范围", "统一社会信用代码", "PID"}, }, "copyright": { Name: "软件著作权", DataModuleId: 481, Field: []string{"Name", "ShortName", "", "RegisterNo", "PubType"}, KeyWord: []string{"软件全称", "软件简称", "分类", "登记号", "权利取得方式"}, }, "icp": { Name: "ICP备案", DataModuleId: 512, Field: []string{"WebsiteName", "HomeAddress", "DomainName", "WebrecordNo", "CompanyName"}, KeyWord: []string{"网站名称", "站点首页", "域名", "网站备案/许可证号", "公司名称"}, }, "supplier": { Name: "招投标", DataModuleId: 477, Field: []string{"CompanyName", "Proportion", "Quota", "ReportYear", "Source", "Relationship", "KeyNo"}, KeyWord: []string{"名称", "金额占比", "金额", "报告期/公开时间", "数据来源", "关联关系", "PID"}, }, "branch": { Name: "分支机构", DataModuleId: 485, Field: []string{"Name", "Oper.Name", "ShortStatus", "KeyNo"}, //ShortStatus 不兼容列表! KeyWord: []string{"企业名称", "法人", "状态", "PID"}, }, "invest": { Name: "对外投资信息", DataModuleId: 453, Field: []string{"Name", "OperName", "Status", "FundedRatio", "KeyNo"}, KeyWord: []string{"企业名称", "法人", "状态", "持股信息", "PID"}, }, "partner": { Name: "股东信息", DataModuleId: 484, Field: []string{"StockName", "StockPercent", "ShouldCapi", "KeyNo"}, KeyWord: []string{"股东名称", "持股比例", "认缴出资金额", "PID"}, }, } for k, _ := range resEnsMap { resEnsMap[k].KeyWord = append(resEnsMap[k].KeyWord, "信息关联") resEnsMap[k].Field = append(resEnsMap[k].Field, "ref") } return resEnsMap }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/qidian/qidian.go
internal/qidian/qidian.go
package qidian import ( "encoding/json" "fmt" "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" ) import ( "github.com/wgpsec/ENScan/common/gologger" ) type QD struct { Options *common.ENOptions } func (h *QD) AdvanceFilter(name string) ([]gjson.Result, error) { url := "https://holmes.taobao.com/web/corp/customer/searchWithSummary" searchData := map[string]string{ "pageNo": "1", "pageSize": "10", "keyword": name, "orderByType": "5", } searchJsonData, _ := json.Marshal(searchData) content := h.req(url, string(searchJsonData)) res := gjson.Parse(content) enList := res.Get("data.data").Array() if len(enList) == 0 { gologger.Debug().Str("查询请求", name).Msg(content) return enList, fmt.Errorf("【QD】没有查询到关键词 %s", name) } return enList, nil } func (h *QD) GetENMap() map[string]*common.EnsGo { return getENMap() } func (h *QD) GetEnsD() common.ENsD { ensD := common.ENsD{Name: h.Options.KeyWord, Pid: h.Options.CompanyID} return ensD } func (h *QD) GetInfoByPage(pid string, page int, em *common.EnsGo) (info common.InfoPage, err error) { return info, err } func (h *QD) GetCompanyBaseInfoById(pid string) (gjson.Result, map[string]*common.EnsGo) { // 获取的格式不太好写,先放在这了,感兴趣的可以提PR gologger.Error().Msgf("【企典】功能尚未开发,感兴趣的师傅可以提交PR~") return gjson.Result{}, getENMap() }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/aiqicha/bean.go
internal/aiqicha/bean.go
package aiqicha import ( "fmt" "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "strings" "time" ) func getENMap() map[string]*common.EnsGo { ensInfoMap := make(map[string]*common.EnsGo) ensInfoMap = map[string]*common.EnsGo{ "enterprise_info": { Name: "企业信息", Api: "detail/basicAllDataAjax", Field: []string{"entName", "legalPerson", "openStatus", "telephone", "email", "regCapital", "startDate", "regAddr", "scope", "taxNo", "pid"}, KeyWord: []string{"企业名称", "法人代表", "经营状态", "电话", "邮箱", "注册资本", "成立日期", "注册地址", "经营范围", "统一社会信用代码", "PID"}, }, "icp": { Name: "ICP备案", Api: "detail/icpinfoAjax", Field: []string{"siteName", "homeSite", "domain", "icpNo", ""}, KeyWord: []string{"网站名称", "网址", "域名", "网站备案/许可证号", "公司名称"}, }, "app": { Name: "APP", Api: "c/appinfoAjax", Field: []string{"name", "classify", "", "", "logoBrief", "logo", "", "", ""}, KeyWord: []string{"名称", "分类", "当前版本", "更新时间", "简介", "logo", "Bundle ID", "链接", "market"}, }, "weibo": { Name: "微博", Api: "c/microblogAjax", Field: []string{"nickname", "weiboLink", "brief", "logo"}, KeyWord: []string{"微博昵称", "链接", "简介", "LOGO"}, }, "wechat": { Name: "微信公众号", Api: "c/wechatoaAjax", Field: []string{"wechatName", "wechatId", "wechatIntruduction", "qrcode", "wechatLogo"}, KeyWord: []string{"名称", "ID", "描述", "二维码", "LOGO"}, }, "job": { Name: "招聘信息", Api: "c/enterprisejobAjax", Field: []string{"jobTitle", "education", "location", "publishDate", "desc"}, KeyWord: []string{"招聘职位", "学历要求", "工作地点", "发布日期", "招聘描述"}, }, "copyright": { Name: "软件著作权", Api: "detail/copyrightAjax", Field: []string{"softwareName", "shortName", "softwareType", "PubType", ""}, KeyWord: []string{"软件名称", "软件简介", "分类", "登记号", "权利取得方式"}, }, "supplier": { Name: "供应商", Api: "c/supplierAjax", Field: []string{"supplier", "", "", "cooperationDate", "source", "", "supplierId"}, KeyWord: []string{"名称", "金额占比", "金额", "报告期/公开时间", "数据来源", "关联关系", "PID"}, }, "invest": { Name: "投资信息", Api: "detail/investajax", Field: []string{"entName", "legalPerson", "openStatus", "regRate", "pid"}, KeyWord: []string{"企业名称", "法人", "状态", "投资比例", "PID"}, }, "holds": { Name: "控股企业", Api: "detail/holdsAjax", Field: []string{"entName", "", "", "proportion", "", "pid"}, KeyWord: []string{"企业名称", "法人", "状态", "投资比例", "持股层级", "PID"}, }, "branch": { Name: "分支信息", Api: "detail/branchajax", Field: []string{"entName", "legalPerson", "openStatus", "pid"}, KeyWord: []string{"企业名称", "法人", "状态", "PID"}, }, "partner": { Name: "股东信息", Api: "detail/sharesAjax", Field: []string{"name", "subRate", "subMoney", "pid"}, KeyWord: []string{"股东名称", "持股比例", "认缴出资金额", "PID"}, }, } for k := range ensInfoMap { ensInfoMap[k].KeyWord = append(ensInfoMap[k].KeyWord, "数据关联 ") ensInfoMap[k].Field = append(ensInfoMap[k].Field, "ref") } return ensInfoMap } func (h *AQC) req(url string) string { c := common.NewClient(map[string]string{ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 Edg/98.0.1108.43", "Accept": "text/html, application/xhtml+xml, image/jxr, */*", "Cookie": h.Options.GetCookie("aqc"), "Referer": "https://aiqicha.baidu.com/", }, h.Options) resp, err := c.Get(url) if err != nil { gologger.Error().Msgf("【AQC】请求发生错误, %s 5秒后重试\n%s\n", url, err) time.Sleep(5 * time.Second) return h.req(url) } if resp.IsSuccessState() { if strings.Contains(resp.String(), "百度安全验证") { gologger.Error().Msgf("【AQC】需要安全验证,请打开浏览器进行验证后操作,10秒后重试! %s \n", "https://aiqicha.baidu.com/") gologger.Debug().Msgf("URL:%s\n\n%s", url, resp.String()) time.Sleep(10 * time.Second) return h.req(url) } return resp.String() } else if resp.StatusCode == 403 { gologger.Error().Msgf("【AQC】ip被禁止访问网站,请更换ip\n") } else if resp.StatusCode == 401 { gologger.Error().Msgf("【AQC】Cookie有问题或过期,请重新获取\n") } else if resp.StatusCode == 302 { gologger.Error().Msgf("【AQC】需要更新Cookie\n") } else if resp.StatusCode == 404 { gologger.Error().Msgf("【AQC】请求错误 404 %s \n", url) } else { gologger.Error().Msgf("【AQC】未知错误 %s\n", resp.StatusCode) } return "" } // pageParseJson 提取页面中的JSON字段 func pageParseJson(content string) (gjson.Result, error) { tag1 := "window.pageData =" tag2 := "window.isSpider =" //tag2 := "/* eslint-enable */</script><script data-app" idx1 := strings.Index(content, tag1) idx2 := strings.Index(content, tag2) if idx2 > idx1 { str := content[idx1+len(tag1) : idx2] str = strings.Replace(str, "\n", "", -1) str = strings.Replace(str, " ", "", -1) str = str[:len(str)-1] return gjson.Get(string(str), "result"), nil } else { gologger.Error().Msgf("【AQC】无法解析页面数据,请开启Debug检查") gologger.Debug().Msgf("【AQC】页面返回数据\n————\n%s————\n", content) } return gjson.Result{}, fmt.Errorf("无法解析页面数据") } func transformNumber(input string, t int64) string { transformedStr := "" codes := make([]map[rune]rune, 3) codes[1] = map[rune]rune{ '0': '0', '1': '1', '2': '2', '3': '3', '4': '5', '5': '4', '6': '7', '7': '6', '8': '9', '9': '8', } codes[2] = map[rune]rune{ '0': '0', '1': '1', '2': '2', '3': '3', '4': '6', '5': '8', '6': '9', '7': '4', '8': '5', '9': '7', } for _, digitRune := range input { transformedStr += string(codes[t][digitRune]) } return transformedStr } var enMapping = map[string]string{ "webRecord": "icp", "appinfo": "app", "wechatoa": "wechat", "enterprisejob": "job", "microblog": "weibo", "hold": "holds", "shareholders": "partner", }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/aiqicha/aiqicha.go
internal/aiqicha/aiqicha.go
package aiqicha /* Aiqicha By Keac * admin@wgpsec.org */ import ( "fmt" "github.com/tidwall/gjson" "github.com/tidwall/sjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" urlTool "net/url" "strconv" "strings" ) type AQC struct { Options *common.ENOptions } // AdvanceFilter 筛选过滤 func (h *AQC) AdvanceFilter(name string) ([]gjson.Result, error) { urls := "https://aiqicha.baidu.com/s?q=" + urlTool.QueryEscape(name) + "&t=0" //urls := "https://aiqicha.baidu.com/s/advanceFilterAjax?q=" + urlTool.QueryEscape(name) + "&p=1&s=10&f={}" content := h.req(urls) content = strings.ReplaceAll(content, "<em>", "⌈") content = strings.ReplaceAll(content, "<\\/em>", "⌋") rq, _ := pageParseJson(content) enList := rq.Get("resultList").Array() //enList := gjson.Get(content, "data.resultList").Array() if len(enList) == 0 { gologger.Debug().Str("查询请求", name).Msg(content) return enList, fmt.Errorf("【AQC】没有查询到关键词 ⌈%s⌋", name) } // advanceFilterAjax 接口特殊处理 //ddw := gjson.Get(content, "ddw").Int() //for i, v := range enList { // s, _ := sjson.Set(v.Raw, "pid", transformNumber(v.Get("pid").String(), ddw)) // enList[i] = gjson.Parse(s) //} return enList, nil } func (h *AQC) GetENMap() map[string]*common.EnsGo { return getENMap() } func (h *AQC) GetEnsD() common.ENsD { ensD := common.ENsD{Name: h.Options.KeyWord, Pid: h.Options.CompanyID, Op: h.Options} return ensD } func (h *AQC) GetCompanyBaseInfoById(pid string) (gjson.Result, map[string]*common.EnsGo) { // 企业基本信息 urls := "https://aiqicha.baidu.com/detail/basicAllDataAjax?pid=" + pid baseRes := h.req(urls) res := gjson.Get(baseRes, "data.basicData") // 修复没有pid的问题 r, _ := sjson.Set(res.Raw, "pid", pid) res = gjson.Parse(r) //初始化ENMap ensInfoMap := getENMap() // 获取企业信息列表 enInfoUrl := "https://aiqicha.baidu.com/compdata/navigationListAjax?pid=" + pid enInfoRes := h.req(enInfoUrl) // 初始化数量数据 if gjson.Get(enInfoRes, "status").String() == "0" { for _, s := range gjson.Get(enInfoRes, "data").Array() { for _, t := range s.Get("children").Array() { resId := t.Get("id").String() // 判断内容是否在enscan支持范围内 if _, ok := enMapping[resId]; ok { resId = enMapping[resId] } es := ensInfoMap[resId] if es == nil { es = &common.EnsGo{} } //gologger.Debug().Msgf("【AQC】数量" + t.Get("name").String() + "|" + t.Get("total").String() + "|" + t.Get("id").String()) es.Name = t.Get("name").String() es.Total = t.Get("total").Int() es.Available = t.Get("avaliable").Int() ensInfoMap[t.Get("id").String()] = es } } } else { gologger.Error().Msg("初始化数量失败!") gologger.Debug().Str("pid", pid).Msgf("%s", enInfoRes) } return res, ensInfoMap } // GetInfoByPage 分页获取信息 func (h *AQC) GetInfoByPage(pid string, page int, em *common.EnsGo) (info common.InfoPage, err error) { urls := "https://aiqicha.baidu.com/" + em.Api + "?size=10&pid=" + pid + "&p=" + strconv.Itoa(page) content := h.req(urls) data := gjson.Get(content, "data") // 判断投资关系一个获取的特殊值 if em.Api == "relations/relationalMapAjax" { data = gjson.Get(content, "data.investRecordData") } listData := data.Get("list").Array() // 处理下ICP备案把他换成多行 if em.Api == "detail/icpinfoAjax" { var tmp []gjson.Result for _, y := range listData { for _, o := range y.Get("domain").Array() { valueTmp, _ := sjson.Set(y.Raw, "domain", o.String()) tmpHomeSite := y.Get("homeSite").Array() tmpStr := "" if len(tmpHomeSite) > 0 { tmpStr = tmpHomeSite[0].String() } valueTmp, _ = sjson.Set(valueTmp, "homeSite", tmpStr) tmp = append(tmp, gjson.Parse(valueTmp)) } } listData = tmp } info = common.InfoPage{ Size: data.Get("size").Int(), Total: data.Get("total").Int(), Data: listData, } return info, err }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/tianyancha/tianyancha.go
internal/tianyancha/tianyancha.go
package tianyancha import ( "encoding/json" "fmt" "strconv" "strings" "time" "github.com/antchfx/htmlquery" "github.com/tidwall/gjson" "github.com/tidwall/sjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" ) type TYC struct { Options *common.ENOptions } func (h *TYC) AdvanceFilter(name string) ([]gjson.Result, error) { //使用关键词推荐方法进行检索,会出现信息不对的情况 //urls := "https://sp0.tianyancha.com/search/suggestV2.json?key=" + url.QueryEscape(name) urls := "https://capi.tianyancha.com/cloud-tempest/web/searchCompanyV4" searchData := map[string]string{ "key": name, "pageNum": "1", "pageSize": "20", "referer": "search", "sortType": "0", "word": name, } marshal, err := json.Marshal(searchData) if err != nil { return nil, fmt.Errorf("【TYC】关键词处理失败 %s", err.Error()) } content := h.req(urls, string(marshal)) content = strings.ReplaceAll(content, "<em>", "⌈") content = strings.ReplaceAll(content, "</em>", "⌋") enList := gjson.Get(content, "data.companyList").Array() if len(enList) == 0 { gologger.Debug().Str("【TYC】查询请求", name).Msg(content) return enList, fmt.Errorf("【TYC】没有查询到关键词 ⌈%s⌋", name) } return enList, nil } func (h *TYC) GetENMap() map[string]*common.EnsGo { return getENMap() } func (h *TYC) GetEnsD() common.ENsD { ensD := common.ENsD{Name: h.Options.KeyWord, Pid: h.Options.CompanyID, Op: h.Options} return ensD } func (h *TYC) GetCompanyBaseInfoById(pid string) (gjson.Result, map[string]*common.EnsGo) { ensInfoMap := getENMap() // 快速模式跳过企业基本信息 if h.Options.IsFast { for k, _ := range ensInfoMap { ensInfoMap[k].Total = 1 } return gjson.Result{}, ensInfoMap } detailRes, enCount := h.searchBaseInfo(pid, false, h.Options) //修复成立日期信息 ts := time.UnixMilli(detailRes.Get("fromTime").Int()) enJsonTMP, _ := sjson.Set(detailRes.Raw, "fromTime", ts.Format("2006-01-02")) // 匹配统计数据 for k, v := range ensInfoMap { ensInfoMap[k].Total = enCount.Get(v.GNum).Int() } return gjson.Parse(enJsonTMP), ensInfoMap } func (h *TYC) GetInfoByPage(pid string, page int, em *common.EnsGo) (info common.InfoPage, err error) { sd := em.SData urls := "https://capi.tianyancha.com/" + em.Api + "?_=" + strconv.Itoa(int(time.Now().Unix())) var m []byte if len(sd) > 0 { sd["gid"] = pid sd["pageSize"] = "100" sd["pageNum"] = strconv.Itoa(page) info.Page = 100 m, err = json.Marshal(sd) if err != nil { return info, err } } else { urls += "&pageSize=20&graphId=" + pid + "&id=" + pid + "&gid=" + pid + "&pageNum=" + strconv.Itoa(page) + em.GsData info.Page = 20 } content := h.req(urls, string(m)) if gjson.Get(content, "state").String() != "ok" { return info, fmt.Errorf("查询出现错误 %s\n", content) } pList := []string{"itemTotal", "count", "total", "pageBean.total"} for _, k := range gjson.GetMany(gjson.Get(content, "data").Raw, pList...) { if k.Int() != 0 { info.Total = k.Int() } } pats := "data." + em.Rf info.Data = gjson.Get(content, pats).Array() return info, err } // searchBaseInfo 获取基本信息(此操作容易触发验证) func (h *TYC) searchBaseInfo(pid string, tds bool, options *common.ENOptions) (result gjson.Result, enBaseInfo gjson.Result) { // 这里没有获取统计信息的api,故从html获取 if tds { //htmlInfo := htmlquery.FindOne(body, "//*[@class=\"position-rel company-header-container\"]//script") //enBaseInfo = pageParseJson(htmlquery.InnerText(htmlInfo)) result = gjson.Get(h.req("https://capi.tianyancha.com/cloud-other-information/companyinfo/baseinfo/web?id="+pid, ""), "data") return result, gjson.Result{} } else { urls := "https://www.tianyancha.com/company/" + pid body := h.GetReqReturnPage(urls) htmlInfos := htmlquery.FindOne(body, "//*[@id=\"__NEXT_DATA__\"]") enInfo := gjson.Parse(htmlquery.InnerText(htmlInfos)) enInfoD := enInfo.Get("props.pageProps.dehydratedState.queries").Array() result = enInfoD[0].Get("state.data.data") //数量统计 API base_count for i := 0; i < len(enInfoD); i++ { if enInfoD[i].Get("queryKey").String() == "base_count" { enBaseInfo = enInfoD[i].Get("state.data") } } //enBaseInfo = enInfo.Get("props.pageProps.dehydratedState.queries").Array()[11].Get("state.data") } return result, enBaseInfo }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/tianyancha/bean.go
internal/tianyancha/bean.go
package tianyancha import ( "strings" "time" "github.com/antchfx/htmlquery" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "golang.org/x/net/html" ) func getENMap() map[string]*common.EnsGo { ensInfoMap := make(map[string]*common.EnsGo) ensInfoMap = map[string]*common.EnsGo{ "enterprise_info": { Name: "企业信息", Field: []string{"name", "legalPersonName", "regStatus", "phoneNumber", "email", "regCapitalAmount", "fromTime", "taxAddress", "businessScope", "creditCode", "id"}, KeyWord: []string{"企业名称", "法人代表", "经营状态", "电话", "邮箱", "注册资本", "成立日期", "注册地址", "经营范围", "统一社会信用代码", "PID"}, }, "icp": { Name: "ICP备案", Api: "cloud-intellectual-property/intellectualProperty/icpRecordList", GNum: "icpCount", Rf: "item", Field: []string{"webName", "webSite", "ym", "liscense", "companyName"}, KeyWord: []string{"网站名称", "网址", "域名", "网站备案/许可证号", "公司名称"}, }, "app": { Name: "APP", Api: "cloud-business-state/v3/ar/appbkinfo", GNum: "productinfo", Rf: "items", Field: []string{"filterName", "classes", "", "", "brief", "icon", "", "", ""}, KeyWord: []string{"名称", "分类", "当前版本", "更新时间", "简介", "logo", "Bundle ID", "链接", "market"}, }, "weibo": { Name: "微博", Api: "cloud-business-state/weibo/list", GNum: "weiboCount", Rf: "result", Field: []string{"name", "href", "info", "ico"}, KeyWord: []string{"微博昵称", "链接", "简介", "logo"}, }, "wechat": { Name: "微信公众号", Api: "cloud-business-state/wechat/list", GNum: "weChatCount", Rf: "resultList", Field: []string{"title", "publicNum", "recommend", "codeImg", "titleImgURL"}, KeyWord: []string{"名称", "ID", "描述", "二维码", "logo"}, }, "job": { Name: "招聘信息", Api: "cloud-business-state/recruitment/list", GNum: "baipinCount", Rf: "list", Field: []string{"title", "education", "city", "startDate", "wapInfoPath"}, KeyWord: []string{"招聘职位", "学历要求", "工作地点", "发布日期", "招聘描述"}, }, "copyright": { Name: "软件著作权", Api: "cloud-intellectual-property/intellectualProperty/softwareCopyrightListV2", GNum: "copyrightWorks", Rf: "items", Field: []string{"simplename", "fullname", "", "regnum", ""}, KeyWord: []string{"软件名称", "软件简介", "分类", "登记号", "权利取得方式"}, }, "supplier": { Name: "供应商", Api: "cloud-business-state/supply/summaryList", GNum: "suppliesV2Count", Rf: "pageBean.result", GsData: "&year=-100", Field: []string{"supplier_name", "ratio", "amt", "announcement_date", "dataSource", "relationship", "supplier_graphId"}, KeyWord: []string{"名称", "金额占比", "金额", "报告期/公开时间", "数据来源", "关联关系", "PID"}, }, "invest": { Name: "投资信息", Api: "cloud-company-background/company/investListV2", GNum: "inverstCount", Rf: "result", SData: map[string]string{"category": "-100", "percentLevel": "-100", "province": "-100"}, Field: []string{"name", "legalPersonName", "regStatus", "percent", "id"}, KeyWord: []string{"企业名称", "法人", "状态", "投资比例", "PID"}, }, "holds": { Name: "控股企业", Api: "cloud-equity-provider/v4/hold/companyholding", GNum: "finalInvestCount", Rf: "list", Field: []string{"name", "legalPersonName", "regStatus", "percent", "legalType", "cid"}, KeyWord: []string{"企业名称", "法人", "状态", "投资比例", "持股层级", "PID"}, }, "branch": { Name: "分支信息", Api: "cloud-company-background/company/branchList", GNum: "branchCount", Field: []string{"name", "legalPersonName", "regStatus", "id"}, Rf: "result", KeyWord: []string{"企业名称", "法人", "状态", "PID"}, }, "partner": { Name: "股东信息", Api: "cloud-company-background/companyV2/dim/holderForWeb", GNum: "holderCount", Rf: "result", SData: map[string]string{"percentLevel": "-100", "sortField": "capitalAmount", "sortType": "-100"}, Field: []string{"name", "finalBenefitShares", "amount", "id"}, KeyWord: []string{"股东名称", "持股比例", "认缴出资金额", "PID"}, }, } for k, _ := range ensInfoMap { ensInfoMap[k].KeyWord = append(ensInfoMap[k].KeyWord, "数据关联") ensInfoMap[k].Field = append(ensInfoMap[k].Field, "ref") } return ensInfoMap } func (h *TYC) req(url string, data string) string { c := common.NewClient(map[string]string{ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.6367.60 Safari/537.36", "Accept": "text/html,application/json,application/xhtml+xml, image/jxr, */*", "Version": "TYC-Web", "Cookie": h.Options.GetCookie("tyc"), "Origin": "https://www.tianyancha.com", "Referer": "https://www.tianyancha.com/", }, h.Options) if strings.Contains(url, "capi.tianyancha.com") { c.SetHeader("Content-Type", "application/json") //client.Header.Del("Cookie") c.SetHeader("X-Tycid", h.Options.ENConfig.Cookies.Tycid) c.SetHeader("X-Auth-Token", h.Options.ENConfig.Cookies.AuthToken) } method := "GET" if data != "" { method = "POST" c.SetBody(data) } resp, err := c.Send(method, url) if err != nil { gologger.Error().Msgf("【TYC】请求错误 %s 5秒后重试 【%s】\n", url, err) time.Sleep(5 * time.Second) return h.req(url, data) } if resp.StatusCode == 200 { if strings.Contains(resp.String(), "\"message\":\"mustlogin\"") { gologger.Error().Msgf("【TYC】需要登陆后尝试") } if strings.Contains(resp.String(), "账号存在风险") { gologger.Error().Msgf("【TYC】账号存在风险需要认证,打开页面查看是否有提示人机验证,程序将在10秒后重试 %s \n", url) time.Sleep(10 * time.Second) return h.req(url, data) } return resp.String() } else if resp.StatusCode == 403 { gologger.Error().Msgf("【TYC】ip被禁止访问网站,请更换ip\n") } else if resp.StatusCode == 401 { gologger.Error().Msgf("【TYC】Cookie有问题或过期,请重新获取\n") } else if resp.StatusCode == 302 { gologger.Error().Msgf("【TYC】需要更新Cookie\n") } else if resp.StatusCode == 404 { gologger.Error().Msgf("【TYC】请求错误 404 %s \n", url) } else if resp.StatusCode == 429 { gologger.Error().Msgf("【TYC】429请求被拦截,清打开链接滑动验证码,程序将在10秒后重试 %s \n", url) time.Sleep(10 * time.Second) return h.req(url, data) } else if resp.StatusCode == 433 { gologger.Error().Msgf("【TYC】433账号存在风险需要认证,打开页面查看是否有提示人机验证,程序将在10秒后重试 %s \n", url) time.Sleep(10 * time.Second) return h.req(url, data) } else { gologger.Error().Msgf("【TYC】未知状态码:【%d】\n提交报错信息请打开DEBUG模式提交数据包\n", resp.StatusCode) gologger.Debug().Msgf("【TYC】URL:%s\nDATA:%s\n", url, data) gologger.Debug().Msgf("【TYC】\n返回数据包信息:%s\n", resp.String()) } return "" } func (h *TYC) GetReqReturnPage(url string) *html.Node { body := h.req(url, "") if strings.Contains(body, "请输入中国大陆手机号") { gologger.Error().Msgf("[TYC] COOKIE检查失效,请检查COOKIE是否正确!\n") } if strings.Contains(body, "当前暂时无法访问") { gologger.Error().Msgf("[TYC] IP可能被拉黑!请使用代理尝试\n") } page, _ := htmlquery.Parse(strings.NewReader(body)) return page }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/riskbird/riskbird.go
internal/riskbird/riskbird.go
package riskbird import ( "encoding/json" "fmt" "github.com/tidwall/gjson" "github.com/tidwall/sjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "strconv" ) func (h *RB) AdvanceFilter(name string) ([]gjson.Result, error) { urls := "https://www.riskbird.com/riskbird-api/newSearch" searchData := map[string]string{ "searchKey": name, "pageNo": "1", "range": "10", "referer": "search", "queryType": "1", "selectConditionData": "{\"status\":\"\",\"sort_field\":\"\"}", } marshal, err := json.Marshal(searchData) if err != nil { return nil, fmt.Errorf("【RB】关键词处理失败 %s", err.Error()) } content := h.req(urls, string(marshal)) enList := gjson.Get(content, "data.list").Array() if len(enList) == 0 { gologger.Debug().Str("查询请求", name).Msg(content) return enList, fmt.Errorf("【RB】没有查询到关键词 ⌈%s⌋", name) } return enList, nil } func (h *RB) GetENMap() map[string]*common.EnsGo { return getENMap() } func (h *RB) GetEnsD() common.ENsD { ensD := common.ENsD{Name: h.Options.KeyWord, Pid: h.Options.CompanyID, Op: h.Options} return ensD } func (h *RB) GetCompanyBaseInfoById(pid string) (gjson.Result, map[string]*common.EnsGo) { ensInfoMap := getENMap() detailRes, enCount := h.searchBaseInfo(pid) for k, v := range ensInfoMap { ensInfoMap[k].Total = enCount.Get(v.GNum).Int() } return detailRes, ensInfoMap } func (h *RB) GetInfoByPage(pid string, page int, em *common.EnsGo) (info common.InfoPage, err error) { urls := "https://www.riskbird.com/riskbird-api/companyInfo/list" li := map[string]string{ "filterCnd": "1", "page": strconv.Itoa(page), "size": "100", "orderNo": pid, "extractType": em.Api, "sortField": "", } marshal, err := json.Marshal(li) if err != nil { return info, err } content := gjson.Parse(h.req(urls, string(marshal))) if content.Get("code").String() != "20000" { return info, fmt.Errorf("【RB】获取数据失败 %s", content.Get("msg")) } info = common.InfoPage{ Size: 100, Total: content.Get("data.totalCount").Int(), Data: content.Get("data.apiData").Array(), } return info, err } func (h *RB) searchBaseInfo(pid string) (result gjson.Result, enBaseInfo gjson.Result) { r := gjson.Parse(h.req("https://www.riskbird.com/api/ent/query?entId="+pid, "")) result = r.Get("basicResult.apiData.list.jbxxInfo") enJsonTMP, _ := sjson.Set(result.Raw, "orderNo", r.Get("orderNo").String()) enBaseInfo = r.Get("basicResult.apiData.count") return gjson.Parse(enJsonTMP), enBaseInfo }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/riskbird/bean.go
internal/riskbird/bean.go
package riskbird import ( "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "strings" "time" ) type RB struct { Options *common.ENOptions eid string } func getENMap() map[string]*common.EnsGo { ensInfoMap := make(map[string]*common.EnsGo) ensInfoMap = map[string]*common.EnsGo{ "search": { Name: "企业信息", Api: "newSearch", Field: []string{"ENTNAME", "faren", "ENTSTATUS", "tels", "emails", "regConcat", "esDate", "dom", "", "UNISCID", "entid"}, KeyWord: []string{"企业名称", "法人代表", "经营状态", "电话", "邮箱", "注册资本", "成立日期", "注册地址", "经营范围", "统一社会信用代码", "PID"}, }, "enterprise_info": { Name: "企业信息", Api: "api/ent/query", Field: []string{"entName", "personName", "entStatus", "telList", "emailList", "recConcat", "esDate", "yrAddress", "opScope", "uniscid", "entid"}, KeyWord: []string{"企业名称", "法人代表", "经营状态", "电话", "邮箱", "注册资本", "成立日期", "注册地址", "经营范围", "统一社会信用代码", "PID"}, }, "icp": { Name: "ICP备案", Api: "propertyIcp", GNum: "propertyIcpCount", Field: []string{"webname", "", "hostname", "icpnum", ""}, KeyWord: []string{"网站名称", "网址", "域名", "网站备案/许可证号", "公司名称"}, }, "app": { Name: "APP", Api: "propertyApp", GNum: "propertyAppCount", Field: []string{"appname", "", "", "updateDateAndroid", "brief", "iconUrl", "", "", "downloadCountLevel"}, KeyWord: []string{"名称", "分类", "当前版本", "更新时间", "简介", "logo", "Bundle ID", "链接", "market"}, }, "wx_app": { Name: "小程序", Api: "propertyMiniprogram", GNum: "propertyMiniprogramCount", Field: []string{"name", "cate", "logo", "qrcode", ""}, KeyWord: []string{"名称", "分类", "头像", "二维码", "阅读量"}, }, "job": { Name: "招聘信息", Api: "job", GNum: "jobCount", Field: []string{"position", "education", "region", "pdate", "position"}, KeyWord: []string{"招聘职位", "学历要求", "工作地点", "发布日期", "招聘描述"}, }, "copyright": { Name: "软件著作权", Api: "propertyCopyrightSoftware", GNum: "propertyCopyrightSoftwareCount", Field: []string{"sname", "sname", "", "snum", ""}, KeyWord: []string{"软件名称", "软件简介", "分类", "登记号", "权利取得方式"}, }, "invest": { Name: "投资信息", Api: "companyInvest", GNum: "companyInvestCount", SData: map[string]string{"category": "-100", "percentLevel": "-100", "province": "-100"}, Field: []string{"entName", "personName", "entStatus", "funderRatio", "entid"}, KeyWord: []string{"企业名称", "法人", "状态", "投资比例", "PID"}, }, "branch": { Name: "分支机构", GNum: "companyBranchCount", Api: "companyBranch", Field: []string{"brName", "brPrincipal", "entStatus", "entid"}, KeyWord: []string{"企业名称", "法人", "状态", "PID"}, }, "partner": { Name: "股东信息", Api: "shareHolder", GNum: "shareHolderCount", Field: []string{"shaName", "fundedRatio", "subConAm", "shaId"}, KeyWord: []string{"股东名称", "持股比例", "认缴出资金额", "PID"}, }, } for k, _ := range ensInfoMap { ensInfoMap[k].KeyWord = append(ensInfoMap[k].KeyWord, "数据关联") ensInfoMap[k].Field = append(ensInfoMap[k].Field, "ref") } return ensInfoMap } func (h *RB) req(url string, data string) string { c := common.NewClient(map[string]string{ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.6367.60 Safari/537.36", "Accept": "text/html,application/json,application/xhtml+xml, image/jxr, */*", "App-Device": "WEB", "Content-Type": "application/json", "Cookie": h.Options.GetCookie("rb"), "Origin": "https://www.riskbird.com", "Referer": "https://www.riskbird.com/ent/", }, h.Options) if !strings.Contains(url, "newSearch") { c.SetHeader("Xs-Content-Type", "application/json") } method := "GET" if data != "" { method = "POST" c.SetBody(data) } resp, err := c.Send(method, url) if err != nil { gologger.Error().Msgf("【RB】请求错误 %s 5秒后重试 【%s】\n", url, err) time.Sleep(5 * time.Second) return h.req(url, data) } if resp.StatusCode == 200 { rs := gjson.Parse(resp.String()) if rs.Get("state").String() == "limit:auth" { gologger.Error().Msgf("【RB】您今日的查询次数已达到上限!请前往网站检查~ 30秒后重试\n") time.Sleep(30 * time.Second) return h.req(url, data) } return resp.String() } else if resp.StatusCode == 403 { gologger.Error().Msgf("【RB】ip被禁止访问网站,请更换ip\n") } else if resp.StatusCode == 401 { gologger.Error().Msgf("【RB】Cookie有问题或过期,请重新获取\n") } else if resp.StatusCode == 302 { gologger.Error().Msgf("【RB】需要更新Cookie\n") } else if resp.StatusCode == 404 { gologger.Error().Msgf("【RB】请求错误 404 %s \n", url) } else { gologger.Error().Msgf("【RB】未知错误 %s\n", resp.StatusCode) gologger.Debug().Msgf("【RB】\nURL:%s\nDATA:%s\n", url, data) gologger.Debug().Msgf("【RB】\n%s\n", resp.String()) } return "" }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/tycapi/tycapi.go
internal/tycapi/tycapi.go
package tycapi import ( "fmt" "github.com/tidwall/gjson" "github.com/tidwall/sjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "net/url" "strconv" "time" ) type TycAPI struct { Options *common.ENOptions } func (h *TycAPI) AdvanceFilter(name string) ([]gjson.Result, error) { em := getENMap() urls := em["search"].Api + "?word=" + url.QueryEscape(name) content := h.req(urls) enList := gjson.Get(content, "items.items").Array() if len(enList) == 0 { gologger.Debug().Str("【TYC-API】查询请求", name).Msg(content) return enList, fmt.Errorf("【TYC-API】没有查询到关键词 ⌈%s⌋", name) } return enList, nil } func (h *TycAPI) GetENMap() map[string]*common.EnsGo { return getENMap() } func (h *TycAPI) GetEnsD() common.ENsD { ensD := common.ENsD{Name: h.Options.KeyWord, Pid: h.Options.CompanyID, Op: h.Options} return ensD } func (h *TycAPI) GetCompanyBaseInfoById(pid string) (gjson.Result, map[string]*common.EnsGo) { ensInfoMap := getENMap() detailRes := h.searchBaseInfo(pid) //修复成立日期信息 ts := time.UnixMilli(detailRes.Get("fromTime").Int()) enJsonTMP, _ := sjson.Set(detailRes.Raw, "fromTime", ts.Format("2006-01-02")) // 匹配统计数据,API没有该接口,所以全部标记为存在 for k, _ := range ensInfoMap { ensInfoMap[k].Total = 1 } return gjson.Parse(enJsonTMP), ensInfoMap } func (h *TycAPI) GetInfoByPage(pid string, page int, em *common.EnsGo) (info common.InfoPage, err error) { uv := em.Api + "?keyword=" + pid + "&page=" + strconv.Itoa(page) res := gjson.Get(h.req(uv), "result") info = common.InfoPage{ Size: 20, Total: res.Get("total").Int(), Data: res.Get("items").Array(), } return info, err } func (h *TycAPI) getInfo(pid string, s *common.EnsGo) (ef map[string][]gjson.Result) { u := s.Api + "?keyword=" + pid res := gjson.Get(h.req(u), "result") for k, v := range s.SData { ef[v] = res.Get(k).Array() } return ef } // searchBaseInfo 获取企业基本信息 func (h *TycAPI) searchBaseInfo(pid string) (result gjson.Result) { result = gjson.Get(h.req(getENMap()["enterprise_info_normal"].Api+"?keyword="+pid), "result") return result }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/internal/tycapi/bean.go
internal/tycapi/bean.go
package tycapi import ( "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" "github.com/wgpsec/ENScan/common/gologger" "time" ) func getENMap() map[string]*common.EnsGo { ensInfoMap := make(map[string]*common.EnsGo) ensInfoMap = map[string]*common.EnsGo{ "cb_ic": { // 工商信息混合获取接口 Name: "工商信息", Api: "cb/ic/2.0", Price: 1, SData: map[string]string{ "branchList": "branch", // 分支机构 "investList": "invest", // 投资信息 "shareHolderList": "partner", // 股东信息 }, Field: []string{"name", "legalPersonName", "regStatus", "phoneNumber", "email", "regCapital", "estiblishTime", "base", "businessScope", "creditCode", "id"}, KeyWord: []string{"企业名称", "法人代表", "经营状态", "电话", "邮箱", "注册资本", "成立日期", "注册地址", "经营范围", "统一社会信用代码", "PID"}, }, "cb_ipr": { // 知识产权混合获取接口 Name: "知识产权", Api: "cb/ic/2.0", Price: 1.5, SData: map[string]string{ "copyRegList": "copyright", // 软件著作权 "icpList": "icp", // 域名信息 }, }, "search": { Name: "搜索", Api: "search/2.0", Price: 0.01, Field: ensInfoMap["enterprise_info"].Field, KeyWord: ensInfoMap["enterprise_info"].KeyWord, }, "enterprise_info_normal": { Name: "企业信息(基本)", Api: "ic/baseinfo/normal", Price: 0.15, Field: ensInfoMap["enterprise_info"].Field, KeyWord: ensInfoMap["enterprise_info"].KeyWord, }, "enterprise_info": { Name: "企业信息", Api: "ic/baseinfoV2/2.0", Price: 0.2, Field: []string{"name", "legalPersonName", "regStatus", "phoneNumber", "email", "regCapital", "estiblishTime", "base", "regLocation", "creditCode", "id"}, KeyWord: []string{"企业名称", "法人代表", "经营状态", "电话", "邮箱", "注册资本", "成立日期", "注册地址", "经营范围", "统一社会信用代码", "PID"}, }, "icp": { Name: "ICP备案", Api: "ipr/icp/3.0", Price: 0.1, Field: []string{"webName", "webSite", "ym", "liscense", "companyName"}, KeyWord: []string{"网站名称", "网址", "域名", "网站备案/许可证号", "公司名称"}, }, "app": { Name: "APP", Api: "m/appbkInfo/2.0", Price: 0.2, Field: []string{"name", "classes", "", "", "brief", "icon", "", "", ""}, KeyWord: []string{"名称", "领域", "当前版本", "更新时间", "简介", "logo", "Bundle ID", "链接", "market"}, }, "weibo": { Name: "微博", Api: "m/weibo/2.0", Price: 0.2, Field: []string{"name", "href", "info", "ico"}, KeyWord: []string{"微博昵称", "链接", "简介", "logo"}, }, "wechat": { Name: "微信公众号", Api: "ipr/publicWeChat/2.0", Price: 0.2, Field: []string{"title", "publicNum", "recommend", "codeImg", "titleImgURL"}, KeyWord: []string{"名称", "ID", "描述", "二维码", "logo"}, }, "job": { Name: "招聘信息", Api: "ipr/publicWeChat/2.0", Price: 0.2, Field: []string{"title", "education", "city", "startDate", "wapInfoPath"}, KeyWord: []string{"招聘职位", "学历要求", "工作地点", "发布日期", "招聘描述"}, }, "copyright": { Name: "软件著作权", Api: "ipr/copyReg/2.0", Price: 0.1, Field: []string{"simplename", "fullname", "catnum", "regnum", ""}, KeyWord: []string{"软件名称", "软件简介", "分类", "登记号", "权利取得方式"}, }, "supplier": { Name: "供应商", Api: "m/supply/2.0", Price: 0.2, Field: []string{"supplier_name", "ratio", "amt", "announcement_date", "dataSource", "relationship", "supplier_graphId"}, KeyWord: []string{"名称", "金额占比", "金额", "报告期/公开时间", "数据来源", "关联关系", "PID"}, }, "invest": { Name: "投资信息", Api: "ic/inverst/2.0", Price: 0.15, Field: []string{"name", "legalPersonName", "regStatus", "percent", "id"}, KeyWord: []string{"企业名称", "法人", "状态", "投资比例", "PID"}, }, "holds": { Name: "控股企业", Api: "v4/open/companyholding", Price: 1, Field: []string{"name", "legalPersonName", "regStatus", "percent", "legalType", "cid"}, KeyWord: []string{"企业名称", "法人", "状态", "投资比例", "持股层级", "PID"}, }, "branch": { Name: "分支信息", Api: "ic/branch/2.0", Price: 0.15, Field: []string{"name", "legalPersonName", "regStatus", "id"}, KeyWord: []string{"企业名称", "法人", "状态", "PID"}, }, "partner": { Name: "股东信息", Api: "ic/holder/2.0", Price: 0.15, Field: []string{"name", "capital.percent", "capital.amomon", "id"}, KeyWord: []string{"股东名称", "持股比例", "认缴出资金额", "PID"}, }, } base := "http://open.api.tianyancha.com/services/" for k, _ := range ensInfoMap { ensInfoMap[k].KeyWord = append(ensInfoMap[k].KeyWord, "数据关联") ensInfoMap[k].Field = append(ensInfoMap[k].Field, "ref") if k != "holds" { base += "open/" } ensInfoMap[k].Api = base + ensInfoMap[k].Api } return ensInfoMap } var reqMap = map[int]string{ 0: "请求成功", 300000: "经查无结果", 300001: "请求失败", 300002: "账号失效", 300003: "账号过期", 300004: "访问频率过快", 300005: "无权限访问此api", 300006: "余额不足", 300007: "剩余次数不足", 300008: "缺少必要参数", 300009: "账号信息有误", 300010: "URL不存在", 300011: "此IP无权限访问此api", 300012: "报告生成中", } func (h *TycAPI) req(url string) string { c := common.NewClient(map[string]string{ "User-Agent": "ENScanGO/" + common.GitTag, "Accept": "text/html,application/json,application/xhtml+xml, image/jxr, */*", "Authorization": h.Options.ENConfig.Cookies.TycApiToken, }, h.Options) resp, err := c.Get(url) if err != nil { gologger.Error().Msgf("【TYC-API】请求错误 %s 5秒后重试 【%s】\n", url, err) time.Sleep(5 * time.Second) return h.req(url) } if resp.StatusCode == 200 { rs := gjson.Parse(resp.String()) if rs.Get("error_code").Int() != 0 { if rs.Get("error_code").Int() == 300004 { time.Sleep(3 * time.Second) gologger.Error().Msgf("【TYC-API】访问频率过快,3秒后重试 %s\n", url) return h.req(url) } gologger.Error().Msgf("【TYC-API】错误 %s %s\n", rs.Get("error_code").String(), rs.Get("reason").String()) } return resp.String() } else if resp.StatusCode == 403 { gologger.Error().Msgf("【TYC-API】403 IP被禁止访问网站,请更换ip\n") } else if resp.StatusCode == 404 { gologger.Error().Msgf("【TYC-API】请求错误 404 %s \n", url) } else { gologger.Error().Msgf("【TYC-API】未知错误 %d\n", resp.StatusCode) gologger.Debug().Msgf("【TYC-API】\nURL:%s\n\n", url) gologger.Debug().Msgf("【TYC-API】\n%s\n", resp.String()) } return "" }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/common/output.go
common/output.go
package common import ( "encoding/json" "fmt" "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common/gologger" "github.com/wgpsec/ENScan/common/utils" "github.com/xuri/excelize/v2" "os" "path/filepath" "strconv" "strings" "time" ) // ENSMap 单独结构 type ENSMap struct { Name string JField []string KeyWord []string Only string } // ENSMapLN 最终统一导出格式 var ENSMapLN = map[string]*EnsGo{ "enterprise_info": { Name: "企业信息", Field: []string{"name", "legal_person", "status", "phone", "email", "registered_capital", "incorporation_date", "address", "scope", "reg_code", "pid"}, KeyWord: []string{"企业名称", "法人代表", "经营状态", "电话", "邮箱", "注册资本", "成立日期", "注册地址", "经营范围", "统一社会信用代码", "PID"}, }, "icp": { Name: "ICP备案", Field: []string{"website_name", "website", "domain", "icp", "company_name"}, KeyWord: []string{"网站名称", "网址", "域名", "网站备案/许可证号", "公司名称"}, }, "wx_app": { Name: "微信小程序", Field: []string{"name", "category", "logo", "qrcode", "read_num"}, KeyWord: []string{"名称", "分类", "头像", "二维码", "阅读量"}, }, "wechat": { Name: "微信公众号", Field: []string{"name", "wechat_id", "description", "qrcode", "avatar"}, KeyWord: []string{"名称", "ID", "简介", "二维码", "头像"}, }, "weibo": { Name: "微博", Field: []string{"name", "profile_url", "description", "avatar"}, KeyWord: []string{"微博昵称", "链接", "简介", "头像"}, }, "supplier": { Name: "供应商", Field: []string{"name", "scale", "amount", "report_time", "data_source", "relation", "pid"}, KeyWord: []string{"名称", "金额占比", "金额", "报告期/公开时间", "数据来源", "关联关系", "PID"}, }, "job": { Name: "招聘", Field: []string{"name", "education", "location", "publish_time", "salary"}, KeyWord: []string{"招聘职位", "学历", "办公地点", "发布日期", "薪资"}, }, "invest": { Name: "投资", Field: []string{"name", "legal_person", "status", "scale", "pid"}, KeyWord: []string{"企业名称", "法人", "状态", "投资比例", "PID"}, }, "branch": { Name: "分支机构", Field: []string{"name", "legal_person", "status", "pid"}, KeyWord: []string{"企业名称", "法人", "状态", "PID"}, }, "holds": { Name: "控股企业", Field: []string{"name", "legal_person", "status", "scale", "level", "pid"}, KeyWord: []string{"企业名称", "法人", "状态", "投资比例", "持股层级", "PID"}, }, "app": { Name: "APP", Field: []string{"name", "category", "version", "update_at", "description", "logo", "bundle_id", "link", "market"}, KeyWord: []string{"名称", "分类", "当前版本", "更新时间", "简介", "logo", "Bundle ID", "链接", "market"}, }, "copyright": { Name: "软件著作权", Field: []string{"name", "short_name", "category", "reg_num", "pub_type"}, KeyWord: []string{"软件全称", "软件简称", "分类", "登记号", "权利取得方式"}, }, "partner": { Name: "股东信息", Field: []string{"name", "scale", "reg_cap", "pid"}, KeyWord: []string{"股东名称", "持股比例", "认缴出资金额", "PID"}, }, } func DataToMap(info []gjson.Result, en *EnsGo, em *EnsGo, ext string) (res []map[string]string) { for _, v := range info { strData := make(map[string]string, len(em.Field)+1) // 获取字段值并转换为字符串 for i, field := range em.Field { // 判断是否最后一位字符,如果是那就是要加入from字段的 if i == len(em.Field)-1 && i >= len(en.Field) { strData["ref"] = v.Get(field).String() } else { strData[en.Field[i]] = v.Get(field).String() } } // 添加额外信息,用于后期展示 strData["extra"] = ext res = append(res, strData) } return res } // InfoToMap 将输出的json转为统一map格式 func InfoToMap(infos map[string][]gjson.Result, enMap map[string]*EnsGo, extraInfo string) (res map[string][]map[string]string) { res = make(map[string][]map[string]string) for k, info := range infos { // 判断是否有这个类型,有时候数据可能会比较混杂 if _, ok := enMap[k]; !ok { continue } res[k] = DataToMap(info, ENSMapLN[k], enMap[k], extraInfo) } return res } func OutStrByEnInfo(data map[string][]map[string]string, types string) (str string) { var builder strings.Builder s := data[types] em := ENSMapLN[types].Field for _, m := range s { first := true for _, key := range append(em, "ref", "extra") { if !first { // 如果不是第一个元素,则先写入逗号 builder.WriteString(",") } builder.WriteString(m[key]) first = false } builder.WriteString("\n") } str = builder.String() return str } func OriginalToMapList(infos []gjson.Result, em *EnsGo) (res []map[string]string) { for _, info := range infos { res = append(res, OriginalToMap(info, em)) } return res } func OriginalToMap(info gjson.Result, em *EnsGo) (res map[string]string) { // 获取字段值并转换为字符串 res = make(map[string]string) for _, field := range em.Field { // 判断是否最后一位字符,如果是那就是要加入from字段的 res[field] = info.Get(field).String() } return res } func OutFileByEnInfo(data map[string][]map[string]string, name string, types string, dir string) (err error) { if dir == "!" { gologger.Debug().Str("设定DIR", dir).Msgf("不导出文件") return nil } gologger.Info().Msgf("%s 结果导出中", name) // 初始化导出环境 _, err = os.Stat(dir) if err != nil { gologger.Info().Msgf("导出⌈%s⌋目录不存在,尝试创建\n", dir) err = os.Mkdir(dir, os.ModePerm) if err != nil { gologger.Debug().Str("dir", dir).Msgf(err.Error()) return fmt.Errorf("【创建目录失败】\n %s \n", err.Error()) } } // 判断文件名不要太长 if len([]rune(name)) > 20 { name = string([]rune(name)[:20]) gologger.Warning().Msgf("导出文件名过长,自动截断为⌈%s⌋", name) } fileUnix := time.Now().Format("2006-01-02") + "--" + strconv.FormatInt(time.Now().Unix(), 10) fileName := fmt.Sprintf("%s-%s.%s", name, fileUnix, types) savaPath := filepath.Join(dir, fileName) if types == "json" { jsonStr, err := json.Marshal(data) if err != nil { gologger.Debug().Msgf("原始格式\n %s \n", data) return fmt.Errorf("[JSON格式化数据失败]\n %s \n", err.Error()) } err = os.WriteFile(savaPath, jsonStr, 0644) if err != nil { return fmt.Errorf("[JSON导出文件失败]\n%s", err.Error()) } } else if types == "xlsx" { f := excelize.NewFile() for s, v := range data { em := ENSMapLN[s] exData := make([][]interface{}, len(v)) // 转换MAP格式为interface,进行excel写入 for i, m := range v { if len(m) > 0 { // 把信息全部提取出来,转为interface for _, p := range append(em.Field, "ref", "extra") { exData[i] = append(exData[i], m[p]) } } } f, _ = utils.ExportExcel(em.Name, append(em.KeyWord, "数据关联", "补充信息"), exData, f) } f.DeleteSheet("Sheet1") if err := f.SaveAs(savaPath); err != nil { gologger.Fatal().Msgf("表格导出失败:%s", err) } } else { return fmt.Errorf("不支持的导出类型 %s", types) } gologger.Info().Msgf("导出成功⌈%s⌋", savaPath) return err }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/common/flag.go
common/flag.go
package common import ( "flag" "github.com/wgpsec/ENScan/common/gologger" ) const banner = ` ███████╗███╗ ██╗███████╗ ██████╗ █████╗ ███╗ ██╗ ██╔════╝████╗ ██║██╔════╝██╔════╝██╔══██╗████╗ ██║ █████╗ ██╔██╗ ██║███████╗██║ ███████║██╔██╗ ██║ ██╔══╝ ██║╚██╗██║╚════██║██║ ██╔══██║██║╚██╗██║ ███████╗██║ ╚████║███████║╚██████╗██║ ██║██║ ╚████║ ╚══════╝╚═╝ ╚═══╝╚══════╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═══╝ ` func Banner() { gologger.Print().Msgf("%sBuilt At: %s\nGo Version: %s\nAuthor: %s\nBuild SHA: %s\nVersion: %s\n\n", banner, BuiltAt, GoVersion, GitAuthor, BuildSha, GitTag) gologger.Print().Msgf("https://github.com/wgpsec/ENScan_GO\n\n") gologger.Print().Msgf("工具仅用于信息收集,请勿用于非法用途\n") gologger.Print().Msgf("开发人员不承担任何责任,也不对任何滥用或损坏负责.\n") } func Flag(Info *ENOptions) { Banner() //指定参数 flag.StringVar(&Info.KeyWord, "n", "", "关键词 eg 小米") flag.StringVar(&Info.CompanyID, "i", "", "公司PID") flag.StringVar(&Info.InputFile, "f", "", "批量查询,文本按行分隔") flag.StringVar(&Info.ScanType, "type", "aqc", "查询渠道,可多选") //查询参数指定 flag.Float64Var(&Info.InvestNum, "invest", 0, "投资比例 eg 100") flag.StringVar(&Info.GetFlags, "field", "", "获取字段信息 eg icp") flag.IntVar(&Info.Deep, "deep", 1, "递归搜索n层公司") flag.BoolVar(&Info.IsHold, "hold", false, "是否查询控股公司") flag.BoolVar(&Info.IsSupplier, "supplier", false, "是否查询供应商信息") flag.BoolVar(&Info.IsGetBranch, "branch", false, "查询分支机构(分公司)信息") flag.BoolVar(&Info.IsSearchBranch, "is-branch", false, "深度查询分支机构信息(数量巨大)") flag.BoolVar(&Info.IsJsonOutput, "json", false, "json导出") flag.StringVar(&Info.Output, "out-dir", "", "结果输出的文件夹位置(默认为outs)") flag.StringVar(&Info.BranchFilter, "branch-filter", "", "提供一个正则表达式,名称匹配该正则的分支机构和子公司会被跳过") flag.StringVar(&Info.OutPutType, "out-type", "xlsx", "导出的文件后缀 默认xlsx") flag.BoolVar(&Info.IsDebug, "debug", false, "是否显示debug详细信息") flag.BoolVar(&Info.IsShow, "is-show", true, "是否展示信息输出") flag.BoolVar(&Info.IsFast, "is-fast", false, "跳过数量校验,直接开启查询") flag.BoolVar(&Info.IsPlugins, "is-plugin", false, "是否以插件功能运行,默认false") //其他设定 flag.BoolVar(&Info.IsGroup, "is-group", false, "查询关键词为集团") flag.BoolVar(&Info.IsApiMode, "api", false, "API模式运行") flag.BoolVar(&Info.IsMCPServer, "mcp", false, "MCP模式运行") flag.BoolVar(&Info.ISKeyPid, "is-pid", false, "批量查询文件是否为公司PID") flag.IntVar(&Info.DelayTime, "delay", 0, "每个请求延迟(S)-1为随机延迟1-5S") flag.StringVar(&Info.Proxy, "proxy", "", "设置代理") flag.IntVar(&Info.TimeOut, "timeout", 1, "每个请求默认1(分钟)超时") flag.BoolVar(&Info.IsNoMerge, "no-merge", false, "开启后查询文件将单独导出") flag.BoolVar(&Info.Version, "v", false, "版本信息") flag.Parse() }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/common/common.go
common/common.go
package common import ( "crypto/tls" "github.com/imroc/req/v3" "time" ) func NewClient(headers map[string]string, op *ENOptions) *req.Request { c := req.C() c.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) // 忽略证书验证 c.SetTLSFingerprintChrome() c.SetCommonHeaders(headers) if op.GetENConfig().UserAgent != "" { c.SetUserAgent(op.GetENConfig().UserAgent) } if op.Proxy != "" { c.SetProxyURL(op.Proxy) } c.SetTimeout(time.Duration(op.TimeOut) * time.Minute) time.Sleep(time.Duration(op.GetDelayRTime()) * time.Second) return c.R() }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/common/config.go
common/config.go
package common import ( "path/filepath" "regexp" "time" "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common/utils" ) var ( BuiltAt string GoVersion string GitAuthor string BuildSha string GitTag string ) type ENOptions struct { KeyWord string // Keyword of Search CompanyID string // Company ID GroupID string // Company ID InputFile string // Scan Input File Output string ScanType string Proxy string ISKeyPid bool IsGroup bool IsGetBranch bool IsSearchBranch bool InvestNum float64 DelayTime int DelayMaxTime int64 TimeOut int GetFlags string Version bool IsHold bool IsSupplier bool IsShow bool GetField []string GetType []string IsDebug bool IsJsonOutput bool Deep int IsMergeOut bool //聚合 IsNoMerge bool //聚合 OutPutType string // 导出文件类型 IsApiMode bool IsMCPServer bool IsPlugins bool // 是否作为后置插件查询 IsFast bool // 是否快速查询 ENConfig *ENConfig BranchFilter string NameFilterRegexp *regexp.Regexp } // ENSearch 搜索必要的参数 // 暂时没想好如何使用,尤其是在多进程情况下 type ENSearch struct { KeyWord string // Keyword of Search GetField []string GetType []string IsGetBranch bool NameFilterRegexp *regexp.Regexp InvestNum float64 IsHold bool IsSupplier bool Deep int } // EnsGo EnScan 接口请求通用格式接口 type EnsGo struct { Name string // 接口名字 Api string // API 地址 Field []string // 获取的字段名称 看JSON KeyWord []string // 关键词 Total int64 // 统计梳理 AQC Available int64 // 统计梳理 AQC GNum string // 获取数量的json关键词 getDetail->CountInfo QCC TypeInfo []string // 集团获取参数 QCC Fids string // 接口获取参数 QCC SData map[string]string // 接口请求POST参数 QCC GsData string // get请求需要加的特殊参数 TYC Rf string // 返回数据关键词 TYC DataModuleId int // 企点获取数据ID点 AppParams [2]string // 插件需要获取的参数 Price float32 // 价格 Ex []string // 扩展字段 } // ENsD 通用返回内容格式 type ENsD struct { KeyWord string // Keyword of Search Name string // 企业 Pid string // PID Op *ENOptions } type InfoPage struct { Total int64 Page int64 Size int64 HasNext bool Data []gjson.Result } // DPS ENScan深度搜索包 type DPS struct { Name string `json:"name"` // 企业名称 Pid string `json:"pid"` // 企业ID Ref string `json:"ref"` // 关联原因 Deep int `json:"deep"` // 深度 SK string `json:"type"` // 搜索类型 SearchList []string `json:"search_list"` // 深度搜索列表 } func (h *ENOptions) GetDelayRTime() int64 { if h.DelayTime == -1 { return utils.RangeRand(1, 5) } if h.DelayTime != 0 { h.DelayMaxTime = int64(h.DelayTime) return int64(h.DelayTime) } return 0 } func (h *ENOptions) GetENConfig() *ENConfig { return h.ENConfig } func (h *ENOptions) GetCookie(tpy string) (b string) { c := h.ENConfig.Cookies switch tpy { case "aqc": b = c.Aiqicha case "tyc": b = c.Tianyancha case "rb": b = c.RiskBird case "qcc": b = c.Qcc case "xlb": b = c.Xlb case "kc": b = c.KuaiCha case "qimai": b = c.QiMai } return b } type EnInfos struct { Search string Name string Pid string LegalPerson string OpenStatus string Email string Telephone string SType string RegCode string BranchNum int64 InvestNum int64 InTime time.Time PidS map[string]string Infos map[string][]gjson.Result EnInfos map[string][]map[string]interface{} EnInfo []map[string]interface{} } var AbnormalStatus = []string{"注销", "吊销", "停业", "清算", "歇业", "关闭", "撤销", "迁出", "经营异常", "严重违法失信"} // DefaultAllInfos 默认收集信息列表 var DefaultAllInfos = []string{"icp", "weibo", "wechat", "app", "weibo", "job", "wx_app", "copyright"} var DefaultInfos = []string{"icp", "weibo", "wechat", "app", "wx_app"} var CanSearchAllInfos = []string{"enterprise_info", "icp", "weibo", "wechat", "app", "job", "wx_app", "copyright", "supplier", "invest", "branch", "holds", "partner"} var DeepSearch = []string{"invest", "branch", "holds", "supplier"} var ENSTypes = []string{"aqc", "tyc", "kc", "tycapi", "rb"} var ENSApps = []string{"miit"} var ScanTypeKeys = map[string]string{ "aqc": "爱企查", "qcc": "企查查", "tyc": "天眼查", "tycapi": "天眼查", "xlb": "小蓝本", "kc": "快查", "rb": "风鸟", "all": "全部查询", "aldzs": "阿拉丁", "coolapk": "酷安市场", "qimai": "七麦数据", "chinaz": "站长之家", "miit": "miitICP", } // ENConfig YML配置文件,更改时注意变更 cfgYV 版本 type ENConfig struct { Version float64 `yaml:"version"` UserAgent string `yaml:"user_agent"` // 自定义 User-Agent Api struct { Api string `yaml:"api"` Mcp string `yaml:"mcp"` } Cookies struct { Aldzs string `yaml:"aldzs"` Xlb string `yaml:"xlb"` Aiqicha string `yaml:"aiqicha"` Qidian string `yaml:"qidian"` KuaiCha string `yaml:"kuaicha"` Tianyancha string `yaml:"tianyancha"` Tycid string `yaml:"tycid"` TycApiToken string `yaml:"tyc_api_token"` RiskBird string `yaml:"risk_bird"` AuthToken string `yaml:"auth_token"` Qcc string `yaml:"qcc"` QccTid string `yaml:"qcctid"` QiMai string `yaml:"qimai"` ChinaZ string `yaml:"chinaz"` } App struct { MiitApi string `yaml:"miit_api"` } } var cfgYName = filepath.Join(utils.GetConfigPath(), "config.yaml") var cfgYV = 0.7 var configYaml = `version: 0.7 user_agent: "" # 自定义 User-Agent(可设置为获取Cookie的浏览器) app: miit_api: '' # HG-ha的ICP_Query (非狼组维护 https://github.com/HG-ha/ICP_Query) api: api: ':31000' # API监听地址 mcp: 'http://localhost:8080' # MCP SSE监听地址 cookies: aiqicha: '' # 爱企查 Cookie tianyancha: '' # 天眼查 Cookie tycid: '' # 天眼查 CApi ID(capi.tianyancha.com) auth_token: '' # 天眼查 Token (capi.tianyancha.com) tyc_api_token: '' # 天眼查 官方API Key(https://open.tianyancha.com) risk_bird: '' # 风鸟 Cookie qimai: '' # 七麦数据 Cookie `
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/common/parse.go
common/parse.go
package common import ( "flag" "github.com/gin-gonic/gin" "github.com/projectdiscovery/gologger/levels" "github.com/wgpsec/ENScan/common/gologger" "github.com/wgpsec/ENScan/common/utils" "gopkg.in/yaml.v3" "io" "os" "regexp" "strings" ) func (op *ENOptions) Parse() { //DEBUG模式设定 if op.IsDebug { gologger.DefaultLogger.SetMaxLevel(levels.LevelDebug) gin.SetMode(gin.DebugMode) gologger.Debug().Msgf("DEBUG 模式已开启\n") } //判断版本信息 if op.Version { gologger.Info().Msgf("Current Version: %s\n", GitTag) gologger.Info().Msgf("当前所需配置文件版本 V%.1f\n", cfgYV) if ok, _ := utils.PathExists(cfgYName); !ok { f, errs := os.Create(cfgYName) //创建文件 _, errs = io.WriteString(f, configYaml) if errs != nil { gologger.Fatal().Msgf("配置文件创建失败 %s\n", errs) } gologger.Info().Msgf("配置文件生成成功!\n") } os.Exit(0) } // 配置文件检查 if ok, _ := utils.PathExists(cfgYName); !ok { gologger.Fatal().Msgf("没有找到配置文件 %s 请先运行 -v 创建\n", cfgYName) } //加载配置信息~ conf := new(ENConfig) yamlFile, err := os.ReadFile(cfgYName) if err != nil { gologger.Fatal().Msgf("配置文件解析错误 #%v ", err) } if err := yaml.Unmarshal(yamlFile, conf); err != nil { gologger.Fatal().Msgf("【配置文件加载失败】: %v", err) } if conf.Version < cfgYV { gologger.Fatal().Msgf("配置文件当前[V%.1f] 程序需要[V%.1f] 不匹配,请备份配置文件重新运行-v\n", conf.Version, cfgYV) } if op.KeyWord == "" && op.CompanyID == "" && op.InputFile == "" && !op.IsApiMode && !op.IsMCPServer { flag.PrintDefaults() os.Exit(0) } //初始化输出文件夹位置 if op.Output == "" { op.Output = "outs" } if op.IsJsonOutput { op.OutPutType = "json" } if op.Output == "!" { gologger.Info().Msgf("当前模式不会导出文件信息!\n") } if op.Proxy != "" { gologger.Info().Msgf("代理已设定 ⌈%s⌋\n", op.Proxy) } if op.InputFile != "" { if ok := utils.FileExists(op.InputFile); !ok { gologger.Fatal().Msgf("未获取到文件⌈%s⌋请检查文件名是否正确\n", op.InputFile) } } if op.IsNoMerge { gologger.Info().Msgf("批量查询文件将单独导出!\n") } op.IsMergeOut = !op.IsNoMerge op.ENConfig = conf //数据源判断 默认为爱企查 if op.ScanType == "" && len(op.GetType) == 0 { op.ScanType = "aqc" } //如果是指定全部数据 if op.ScanType == "all" { op.GetType = ENSTypes op.IsMergeOut = true } else if op.ScanType != "" { op.GetType = strings.Split(op.ScanType, ",") } op.GetType = utils.SetStr(op.GetType) var tmp []string for _, v := range op.GetType { if _, ok := ScanTypeKeys[v]; !ok { gologger.Error().Msgf("没有这个%s查询方式\n支持列表\n%s", v, ScanTypeKeys) } else { tmp = append(tmp, v) } } op.GetType = tmp // 判断获取数据字段信息 op.GetField = utils.SetStr(op.GetField) if op.GetFlags == "" && len(op.GetField) == 0 { op.GetField = DefaultInfos } else if op.GetFlags == "all" { op.GetField = DefaultAllInfos } else if op.GetFlags != "" { op.GetField = strings.Split(op.GetFlags, ",") if len(op.GetField) <= 0 { gologger.Fatal().Msgf("没有获取字段信息!\n" + op.GetFlags) } } // 是否深度获取分支机构 if op.IsSearchBranch { op.IsGetBranch = true } if op.BranchFilter != "" { op.NameFilterRegexp = regexp.MustCompile(op.BranchFilter) } //是否获取分支机构 if op.IsGetBranch { op.GetField = append(op.GetField, "branch") } // 投资信息如果不等于0,那就收集股东信息和对外投资信息 if op.InvestNum != 0 { op.GetField = append(op.GetField, "invest") op.GetField = append(op.GetField, "partner") gologger.Info().Msgf("获取投资信息,将会获取⌈%d⌋级子公司", op.Deep) } // 控股信息(大部分需要VIP) if op.IsHold { op.GetField = append(op.GetField, "holds") } if op.IsSupplier { op.GetField = append(op.GetField, "supplier") } if op.Deep <= 0 { op.Deep = 1 } op.GetField = utils.SetStr(op.GetField) op.GetField = utils.SetStr(op.GetField) }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/common/utils/excel.go
common/utils/excel.go
package utils /** * @Description * @Author ggr * @Date 2021/7/8 21:06 * @Form https://cloud.tencent.com/developer/article/1846410 **/ import ( "fmt" "github.com/xuri/excelize/v2" "strconv" ) // maxCharCount 最多26个字符A-Z const maxCharCount = 26 // ExportExcel 导出Excel文件 // sheetName 工作表名称, 注意这里不要取sheet1这种名字,否则导致文件打开时发生部分错误。 // headers 列名切片, 表头 // rows 数据切片,是一个二维数组 // f 为了创建多个单元格,得把标签往外放 func ExportExcel(sheetName string, headers []string, rows [][]interface{}, f *excelize.File) (*excelize.File, error) { sheetIndex, err := f.GetSheetIndex(sheetName) if sheetIndex == -1 { sheetIndex, err = f.NewSheet(sheetName) } if err != nil { return nil, err } maxColumnRowNameLen := 1 + len(strconv.Itoa(len(rows))) columnCount := len(headers) if columnCount > maxCharCount { maxColumnRowNameLen++ } else if columnCount > maxCharCount*maxCharCount { maxColumnRowNameLen += 2 } columnNames := make([][]byte, 0, columnCount) for i, header := range headers { columnName := getColumnName(i, maxColumnRowNameLen) columnNames = append(columnNames, columnName) // 初始化excel表头,这里的index从1开始要注意 curColumnName := getColumnRowName(columnName, 1) err := f.SetCellValue(sheetName, curColumnName, header) if err != nil { return nil, err } } for rowIndex, row := range rows { for columnIndex, columnName := range columnNames { // 从第二行开始 err := f.SetCellValue(sheetName, getColumnRowName(columnName, rowIndex+2), row[columnIndex]) if err != nil { return nil, err } } } f.SetActiveSheet(sheetIndex) return f, nil } // getColumnName 生成列名 // Excel的列名规则是从A-Z往后排;超过Z以后用两个字母表示,比如AA,AB,AC;两个字母不够以后用三个字母表示,比如AAA,AAB,AAC // 这里做数字到列名的映射:0 -> A, 1 -> B, 2 -> C // maxColumnRowNameLen 表示名称框的最大长度,假设数据是10行,1000列,则最后一个名称框是J1000(如果有表头,则是J1001),是4位 // 这里根据 maxColumnRowNameLen 生成切片,后面生成名称框的时候可以复用这个切片,而无需扩容 func getColumnName(column, maxColumnRowNameLen int) []byte { const A = 'A' if column < maxCharCount { // 第一次就分配好切片的容量 slice := make([]byte, 0, maxColumnRowNameLen) return append(slice, byte(A+column)) } else { // 递归生成类似AA,AB,AAA,AAB这种形式的列名 return append(getColumnName(column/maxCharCount-1, maxColumnRowNameLen), byte(A+column%maxCharCount)) } } // getColumnRowName 生成名称框 // Excel的名称框是用A1,A2,B1,B2来表示的,这里需要传入前一步生成的列名切片,然后直接加上行索引来生成名称框,就无需每次分配内存 func getColumnRowName(columnName []byte, rowIndex int) (columnRowName string) { l := len(columnName) columnName = strconv.AppendInt(columnName, int64(rowIndex), 10) columnRowName = string(columnName) // 将列名恢复回去 columnName = columnName[:l] return } func StreamWriterFunc(contents [][]string) { //打开工作簿 file, err := excelize.OpenFile("Book1.xlsx") if err != nil { return } sheet_name := "Sheet1" //获取流式写入器 streamWriter, _ := file.NewStreamWriter(sheet_name) if err != nil { fmt.Println(err) } rows, _ := file.GetRows(sheet_name) //获取行内容 cols, _ := file.GetCols(sheet_name) //获取列内容 fmt.Println("行数rows: ", len(rows), "列数cols: ", len(cols)) //将源文件内容先写入excel for rowid, row_pre := range rows { row_p := make([]interface{}, len(cols)) for colID_p := 0; colID_p < len(cols); colID_p++ { //fmt.Println(row_pre) //fmt.Println(colID_p) if row_pre == nil { row_p[colID_p] = nil } else { row_p[colID_p] = row_pre[colID_p] } } cell_pre, _ := excelize.CoordinatesToCellName(1, rowid+1) if err := streamWriter.SetRow(cell_pre, row_p); err != nil { fmt.Println(err) } } //将新加contents写进流式写入器 for rowID := 0; rowID < len(contents); rowID++ { row := make([]interface{}, len(contents[0])) for colID := 0; colID < len(contents[0]); colID++ { row[colID] = contents[rowID][colID] } cell, _ := excelize.CoordinatesToCellName(1, rowID+len(rows)+1) //决定写入的位置 if err := streamWriter.SetRow(cell, row); err != nil { fmt.Println(err) } } //结束流式写入过程 if err := streamWriter.Flush(); err != nil { fmt.Println(err) } //保存工作簿 if err := file.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/common/utils/fileutil.go
common/utils/fileutil.go
package utils import ( "bufio" "io" "os" ) // FileExists checks if a file exists and is not a directory func FileExists(filename string) bool { info, err := os.Stat(filename) if os.IsNotExist(err) { return false } return !info.IsDir() } // FolderExists checks if a folder exists func FolderExists(folderpath string) bool { _, err := os.Stat(folderpath) return !os.IsNotExist(err) } // PathExists 判断文件/文件夹是否存在 func PathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } // HasStdin determines if the user has piped input func HasStdin() bool { stat, err := os.Stdin.Stat() if err != nil { return false } mode := stat.Mode() isPipedFromChrDev := (mode & os.ModeCharDevice) == 0 isPipedFromFIFO := (mode & os.ModeNamedPipe) != 0 return isPipedFromChrDev || isPipedFromFIFO } func ReadImf(input io.Reader) []string { var imf []string scanner := bufio.NewScanner(input) for scanner.Scan() { imf = append(imf, scanner.Text()) } return imf }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/common/utils/utils.go
common/utils/utils.go
package utils import ( "bufio" "crypto/md5" "crypto/rand" "encoding/hex" "fmt" "github.com/olekukonko/tablewriter" "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common/gologger" "math" "math/big" mrand "math/rand" "net" "net/url" "os" "path/filepath" "regexp" "strconv" "strings" ) // Md5 MD5加密 // src 源字符 func Md5(src string) string { m := md5.New() m.Write([]byte(src)) res := hex.EncodeToString(m.Sum(nil)) return res } // SetStr 数据去重 // target 输入数据 func SetStr(target []string) []string { setMap := make(map[string]int) var result []string for _, v := range target { if v != "" { if _, ok := setMap[v]; !ok { setMap[v] = 0 result = append(result, v) } } } return result } // CheckList 检查列表发现空返回false func CheckList(target []string) bool { if len(target) == 0 { return false } for _, v := range target { if v == "" { return false } } return true } // RangeRand 生成区间[-m, n]的安全随机数 func RangeRand(min, max int64) int64 { if min > max { panic("the min is greater than max!") } if min < 0 { f64Min := math.Abs(float64(min)) i64Min := int64(f64Min) result, _ := rand.Int(rand.Reader, big.NewInt(max+1+i64Min)) return result.Int64() - i64Min } else { result, _ := rand.Int(rand.Reader, big.NewInt(max-min+1)) return min + result.Int64() } } func IsInList(target string, list []string) bool { if len(list) == 0 { return false } for _, v := range list { if v == target { return true } } return false } func DelInList(target string, list []string) []string { var result []string for _, v := range list { if v != target { result = append(result, v) } } return result } func DelListInList(original []string, remove []string) []string { removeMap := make(map[string]bool) for _, v := range remove { removeMap[v] = true } n := 0 for _, v := range original { if !removeMap[v] { original[n] = v n++ } } return original[:n] } func ReadFileOutLine(filename string) []string { var result []string if FileExists(filename) { f, err := os.Open(filename) if err != nil { gologger.Fatal().Msgf("read fail", err) } fileScanner := bufio.NewScanner(f) // read line by line for fileScanner.Scan() { result = append(result, fileScanner.Text()) } // handle first encountered error while reading if err := fileScanner.Err(); err != nil { gologger.Fatal().Msgf("Error while reading file: %s\n", err) } _ = f.Close() } result = SetStr(result) return result } func GetConfigPath() string { // 获得配置文件的绝对路径 dir, _ := filepath.Abs(filepath.Dir(os.Args[0])) return dir } func DName(str string) (srt string) { // 获得文件名 str = strings.ReplaceAll(str, "(", "(") str = strings.ReplaceAll(str, ")", ")") str = strings.ReplaceAll(str, "<em>", "") str = strings.ReplaceAll(str, "</em>", "") return str } // CheckPid 检查pid是哪家单位 func CheckPid(pid string) (res string) { if len(pid) == 32 { res = "qcc" } else if len(pid) == 14 { res = "aqc" } else if len(pid) == 8 || len(pid) == 7 || len(pid) == 6 || len(pid) == 9 || len(pid) == 10 { res = "tyc" } else if len(pid) == 33 || len(pid) == 34 { if pid[0] == 'p' { gologger.Error().Msgf("无法查询法人信息\n") res = "" } res = "xlb" } else { gologger.Error().Msgf("pid长度%d不正确,pid: %s\n", len(pid), pid) return "" } return res } func FormatInvest(scale string) float64 { if scale == "-" || scale == "" || scale == " " { return -1 } else { scale = strings.ReplaceAll(scale, "%", "") } num, err := strconv.ParseFloat(scale, 64) if err != nil { gologger.Error().Msgf("转换失败:%s\n", err) return -1 } return num } func WriteFile(str string, path string) { //os.O_WRONLY | os.O_CREATE file, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { fmt.Println("file open error:", err) return } defer file.Close() //使用缓存方式写入 writer := bufio.NewWriter(file) count, w_err := writer.WriteString(str) //将缓存中数据刷新到文本中 writer.Flush() if w_err != nil { fmt.Println("写入出错") } else { fmt.Printf("写入成功,共写入字节:%v", count) } } func VerifyEmailFormat(email string) bool { pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //匹配电子邮箱 reg := regexp.MustCompile(pattern) return reg.MatchString(email) } // TBS 展示表格 func TBS(h []string, ep []string, name string, data []gjson.Result) { table := tablewriter.NewWriter(os.Stdout) table.SetHeader(h) for _, v := range data { var tmp []string for _, r := range gjson.GetMany(v.String(), ep...) { rs := r.String() if len([]rune(rs)) > 30 { rs = string([]rune(rs)[:30]) } tmp = append(tmp, rs) } table.Append(tmp) } gologger.Info().Msgf(name) table.Render() } // MergeMap 合并map // s: 源map,list: 目标map func MergeMap(s map[string][]map[string]string, list map[string][]map[string]string) { for k, v := range s { if l, ok := list[k]; ok { list[k] = append(l, v...) } else { list[k] = v } } } func fd(arr []string, target string) int { // 查找目标字符串在切片中的首次出现位置 for i, word := range arr { if word == target { return i } } return -1 } // RandomElement 从一个字符串切片中随机返回一个元素。 func RandomElement(c string) string { slice := strings.Split(c, "|") // 确保切片不为空,避免 panic if len(slice) == 0 { return "" } if len(slice) == 1 { return slice[0] } // 生成一个在 [0, len(slice)) 范围内的随机索引 index := mrand.Intn(len(slice)) // 返回该索引对应的元素 return slice[index] } func ExtractPortString(rawURL string) (string, error) { // 解析 URL u, err := url.Parse(rawURL) if err != nil { return "", fmt.Errorf("无效的 URL: %v", err) } // 提取 host:port 部分 _, port, err := net.SplitHostPort(u.Host) if err != nil { return "", fmt.Errorf("未指定端口且协议 %q 无默认端口", u.Scheme) } return port, nil // port 已经是字符串 }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/common/gologger/gologger.go
common/gologger/gologger.go
package gologger import ( "fmt" "github.com/projectdiscovery/gologger/formatter" "github.com/projectdiscovery/gologger/levels" "github.com/projectdiscovery/gologger/writer" "os" "strings" "time" ) var ( labels = map[levels.Level]string{ levels.LevelFatal: "FTL", levels.LevelError: "ERR", levels.LevelInfo: "INF", levels.LevelWarning: "WRN", levels.LevelDebug: "DBG", levels.LevelVerbose: "VER", } // DefaultLogger is the default logging instance DefaultLogger *Logger ) func init() { DefaultLogger = &Logger{} DefaultLogger.SetMaxLevel(levels.LevelInfo) DefaultLogger.SetFormatter(formatter.NewCLI(false)) DefaultLogger.SetWriter(writer.NewCLI()) } // Logger is a logger for logging structured data in a beautfiul and fast manner. type Logger struct { writer writer.Writer maxLevel levels.Level formatter formatter.Formatter timestampMinLevel levels.Level timestamp bool } // Log logs a message to a logger instance func (l *Logger) Log(event *Event) { if !isCurrentLevelEnabled(event) { return } event.message = strings.TrimSuffix(event.message, "\n") data, err := l.formatter.Format(&formatter.LogEvent{ Message: event.message, Level: event.level, Metadata: event.metadata, }) if err != nil { return } l.writer.Write(data, event.level) if event.level == levels.LevelFatal { os.Exit(1) } } // SetMaxLevel sets the max logging level for logger func (l *Logger) SetMaxLevel(level levels.Level) { l.maxLevel = level } // SetFormatter sets the formatter instance for a logger func (l *Logger) SetFormatter(formatter formatter.Formatter) { l.formatter = formatter } // SetWriter sets the writer instance for a logger func (l *Logger) SetWriter(writer writer.Writer) { l.writer = writer } // SetTimestamp enables/disables automatic timestamp func (l *Logger) SetTimestamp(timestamp bool, minLevel levels.Level) { l.timestamp = timestamp l.timestampMinLevel = minLevel } // Event is a log event to be written with data type Event struct { logger *Logger level levels.Level message string metadata map[string]string } func newDefaultEventWithLevel(level levels.Level) *Event { return newEventWithLevelAndLogger(level, DefaultLogger) } func newEventWithLevelAndLogger(level levels.Level, l *Logger) *Event { event := &Event{ logger: l, level: level, metadata: make(map[string]string), } if l.timestamp && level >= l.timestampMinLevel { event.TimeStamp() } return event } func (e *Event) setLevelMetadata(level levels.Level) { e.metadata["label"] = labels[level] } // Label applies a custom label on the log event func (e *Event) Label(label string) *Event { e.metadata["label"] = label return e } // TimeStamp adds timestamp to the log event func (e *Event) TimeStamp() *Event { e.metadata["timestamp"] = time.Now().Format(time.RFC3339) return e } // Str adds a string metadata item to the log func (e *Event) Str(key, value string) *Event { e.metadata[key] = value return e } // Msg logs a message to the logger func (e *Event) Msg(message string) { e.message = message e.logger.Log(e) } // Msgf logs a printf style message to the logger func (e *Event) Msgf(format string, args ...interface{}) { e.message = fmt.Sprintf(format, args...) e.logger.Log(e) } // MsgFunc logs a message with lazy evaluation. // Useful when computing the message can be resource heavy. func (e *Event) MsgFunc(messageSupplier func() string) { if !isCurrentLevelEnabled(e) { return } e.message = messageSupplier() e.logger.Log(e) } // Info writes a info message on the screen with the default label func Info() *Event { event := newDefaultEventWithLevel(levels.LevelInfo) event.setLevelMetadata(levels.LevelInfo) return event } // Warning writes a warning message on the screen with the default label func Warning() *Event { event := newDefaultEventWithLevel(levels.LevelWarning) event.setLevelMetadata(levels.LevelWarning) return event } // Error writes a error message on the screen with the default label func Error() *Event { event := newDefaultEventWithLevel(levels.LevelError) event.setLevelMetadata(levels.LevelError) return event } // Debug writes an error message on the screen with the default label func Debug() *Event { event := newDefaultEventWithLevel(levels.LevelDebug) event.setLevelMetadata(levels.LevelDebug) return event } // Fatal exits the program if we encounter a fatal error func Fatal() *Event { event := newDefaultEventWithLevel(levels.LevelFatal) event.setLevelMetadata(levels.LevelFatal) return event } // Silent prints a string on stdout without any extra labels. func Silent() *Event { event := newDefaultEventWithLevel(levels.LevelSilent) return event } // Print prints a string on stderr without any extra labels. func Print() *Event { event := newDefaultEventWithLevel(levels.LevelInfo) return event } // Verbose prints a string only in verbose output mode. func Verbose() *Event { event := newDefaultEventWithLevel(levels.LevelVerbose) event.setLevelMetadata(levels.LevelVerbose) return event } // Info writes a info message on the screen with the default label func (l *Logger) Info() *Event { event := newEventWithLevelAndLogger(levels.LevelInfo, l) event.setLevelMetadata(levels.LevelInfo) return event } // Warning writes a warning message on the screen with the default label func (l *Logger) Warning() *Event { event := newEventWithLevelAndLogger(levels.LevelWarning, l) event.setLevelMetadata(levels.LevelWarning) return event } // Error writes a error message on the screen with the default label func (l *Logger) Error() *Event { event := newEventWithLevelAndLogger(levels.LevelError, l) event.setLevelMetadata(levels.LevelError) return event } // Debug writes an error message on the screen with the default label func (l *Logger) Debug() *Event { event := newEventWithLevelAndLogger(levels.LevelDebug, l) event.setLevelMetadata(levels.LevelDebug) return event } // Fatal exits the program if we encounter a fatal error func (l *Logger) Fatal() *Event { event := newEventWithLevelAndLogger(levels.LevelFatal, l) event.setLevelMetadata(levels.LevelFatal) return event } // Print prints a string on screen without any extra labels. func (l *Logger) Print() *Event { event := newEventWithLevelAndLogger(levels.LevelSilent, l) return event } // Verbose prints a string only in verbose output mode. func (l *Logger) Verbose() *Event { event := newEventWithLevelAndLogger(levels.LevelVerbose, l) event.setLevelMetadata(levels.LevelVerbose) return event } func isCurrentLevelEnabled(e *Event) bool { return e.level <= e.logger.maxLevel }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
wgpsec/ENScan_GO
https://github.com/wgpsec/ENScan_GO/blob/ac0945e09c60c55da76b1fd894773ca374149405/interface/enscan.go
interface/enscan.go
package _interface import ( "github.com/tidwall/gjson" "github.com/wgpsec/ENScan/common" ) type COMMON interface { GetENMap() map[string]*common.EnsGo GetInfoByPage(pid string, page int, em *common.EnsGo) (info common.InfoPage, err error) } type ENScan interface { // AdvanceFilter 筛选公司 AdvanceFilter(name string) ([]gjson.Result, error) GetEnsD() common.ENsD GetCompanyBaseInfoById(pid string) (gjson.Result, map[string]*common.EnsGo) COMMON } type App interface { GetInfoList(keyword string, types string) []gjson.Result COMMON }
go
Apache-2.0
ac0945e09c60c55da76b1fd894773ca374149405
2026-01-07T10:38:05.869723Z
false
smallnest/langgraphgo
https://github.com/smallnest/langgraphgo/blob/600df7fe3e6254f2329f606732feaecfbd52d9f2/doc.go
doc.go
// LangGraph Go - Building Stateful, Multi-Agent Applications in Go // // LangGraph Go is a Go implementation of LangChain's LangGraph framework for building // stateful, multi-agent applications with LLMs. It provides a powerful graph-based // approach to constructing complex AI workflows with support for cycles, checkpoints, // and human-in-the-loop interactions. // // # Quick Start // // Install the package: // // go get github.com/smallnest/langgraphgo // // Basic example: // // package main // // import ( // "context" // "fmt" // // "github.com/smallnest/langgraphgo/graph" // "github.com/smallnest/langgraphgo/prebuilt" // "github.com/tmc/langchaingo/llms/openai" // "github.com/tmc/langchaingo/tools" // ) // // func main() { // // Initialize LLM // llm, _ := openai.New() // // // Create a simple ReAct agent // agent, _ := prebuilt.CreateReactAgent( // llm, // []tools.Tool{&tools.CalculatorTool{}}, // 10, // max iterations // ) // // // Execute the agent // ctx := context.Background() // result, _ := agent.Invoke(ctx, map[string]any{ // "messages": []llms.MessageContent{ // { // Role: llms.ChatMessageTypeHuman, // Parts: []llms.ContentPart{ // llms.TextPart("What is 123 * 456?"), // }, // }, // }, // }) // // fmt.Println(result) // } // // # Key Features // // - Stateful Graphs: Define complex workflows with state persistence // - Agent Orchestration: Build multi-agent systems with specialized roles // - Checkpointing: Save and resume execution state // - Streaming: Real-time event streaming during execution // - Memory Management: Various strategies for conversation memory // - Tool Integration: Extensive ecosystem of built-in tools // - Type Safety: Generic-based typed graphs for compile-time safety // - Visualization: Graph visualization and debugging tools // // # Core Concepts // // # Graph Structure // // LangGraph Go uses a directed graph structure where: // - Nodes represent processing units (agents, tools, functions) // - Edges define the flow of execution // - State flows through the graph and evolves at each node // // # State Management // // State can be managed in different ways: // // - Untyped: Using map[string]any for flexibility // - Typed: Using Go generics for type safety // - Structured: Using predefined schemas // // # Package Structure // // # Core Packages // // graph/ // The core graph construction and execution engine // // // Create a state graph // g := graph.NewStateGraph() // // // Add nodes // g.AddNode("process", func(ctx context.Context, state map[string]any) (map[string]any, error) { // state["processed"] = true // return state, nil // }) // // // Define execution flow // g.SetEntry("process") // g.AddEdge("process", graph.END) // // // Compile and run // runnable, _ := g.Compile() // result, _ := runnable.Invoke(ctx, initialState) // // prebuilt/ // Ready-to-use agent implementations // // Types of agents: // - ReAct Agent: Reason and act pattern // - Supervisor Agent: Orchestrates multiple agents // - Planning Agent: Creates and executes plans // - Reflection Agent: Self-correcting agent // - Tree of Thoughts: Multi-path reasoning // // Example: // // // Create a supervisor with multiple agents // members := map[string]*graph.StateRunnableUntyped // "analyst": analystAgent, // "coder": coderAgent, // "reviewer": reviewerAgent, // } // // supervisor, _ := prebuilt.CreateSupervisor(llm, members, "router") // // ### memory/ // Various memory management strategies // // Types: // - Buffer: Simple FIFO buffer // - Sliding Window: Maintains recent context with overlap // - Summarization: Compresses older conversations // - Hierarchical: Multi-level memory with importance scoring // - OS-like: Sophisticated paging and eviction // // Example: // // // Use summarization memory // memory := memory.NewSummarizationMemory(llm, 2000) // agent, _ := prebuilt.CreateChatAgent(llm, "", memory) // // ### tool/ // Collection of useful tools // // Categories: // - Web Search: Tavily, Brave, EXA, Bocha // - File Operations: Read, write, list files // - Code Execution: Shell, Python // - Web APIs: HTTP requests // // Example: // // // Use web search tool // searchTool, _ := tool.NewTavilySearchTool(apiKey) // agent, _ := prebuilt.CreateReactAgent(llm, []tools.Tool{searchTool}, 10) // // # Storage Packages // // store/ // Checkpoint persistence implementations // // Options: // - SQLite: Lightweight, file-based storage // - PostgreSQL: Scalable relational database // - Redis: High-performance in-memory storage // // Example: // // // PostgreSQL checkpoint store // store, _ := postgres.NewPostgresCheckpointStore(ctx, postgres.PostgresOptions{ // ConnString: "postgres://user:pass@localhost/langgraph", // }) // // g.WithCheckpointing(graph.CheckpointConfig{Store: store}) // // # Adapter Packages // // adapter/ // Integration adapters for external systems // // Adapters: // - GoSkills: Custom Go-based skills // - MCP: Model Context Protocol tools // // Example: // // // Load GoSkills // skills, _ := goskills.LoadSkillsFromDir("./skills") // tools, _ := goskills.ConvertToLangChainTools(skills) // // # Specialized Packages // // ptc/ // Programmatic Tool Calling - agents generate code to use tools // // agent, _ := ptc.CreatePTCAgent(ptc.PTCAgentConfig{ // Model: llm, // Tools: tools, // Language: ptc.LanguagePython, // }) // // log/ // Simple logging utilities // // logger := log.NewDefaultLogger(log.LogLevelInfo) // listener := graph.NewLoggingListener(logger, log.LogLevelInfo, false) // // # RAG (Retrieval-Augmented Generation) Package // // The rag package provides comprehensive RAG capabilities for LangGraph applications: // // // Basic Vector RAG // llm, _ := openai.New() // embedder, _ := openai.NewEmbedder() // vectorStore, _ := pgvector.New(ctx, pgvector.WithEmbedder(embedder)) // // vectorRAG := rag.NewVectorRAG(llm, embedder, vectorStore, 5) // result, _ := vectorRAG.Query(ctx, "What is quantum computing?") // // // GraphRAG with Knowledge Graph // graphRAG, _ := rag.NewGraphRAGEngine(rag.GraphRAGConfig{ // DatabaseURL: "falkordb://localhost:6379", // ModelProvider: "openai", // EntityTypes: []string{"PERSON", "ORGANIZATION", "LOCATION"}, // EnableReasoning: true, // }, llm, embedder) // // // Hybrid RAG combining vector and graph approaches // vectorRetriever := retrievers.NewVectorRetriever(vectorStore, embedder, config) // graphRetriever := retrievers.NewGraphRetriever(knowledgeGraph, embedder, config) // hybridRetriever := retrievers.NewHybridRetriever( // []rag.Retriever{vectorRetriever, graphRetriever}, // []float64{0.6, 0.4}, config) // // # RAG Features // // - Multiple Retrieval Strategies: Vector similarity, graph-based, hybrid // - Knowledge Graph Integration: Automatic entity and relationship extraction // - Document Processing: Various loaders and text splitters // - Flexible Storage: Support for multiple vector stores and graph databases // - LangGraph Integration: Seamless integration with agents and workflows // // # Advanced Examples // // 1. Multi-Agent System with Supervisor // // package main // // import ( // "context" // "fmt" // // "github.com/smallnest/langgraphgo/prebuilt" // "github.com/tmc/langchaingo/llms/openai" // "github.com/tmc/langchaingo/tools" // ) // // func main() { // llm, _ := openai.New() // // // Create specialized agents // researcher, _ := prebuilt.CreateReactAgent(llm, researchTools, 10) // writer, _ := prebuilt.CreateReactAgent(llm, writingTools, 10) // critic, _ := prebuilt.CreateReactAgent(llm, criticTools, 5) // // // Create supervisor // members := map[string]*graph.StateRunnableUntyped // "researcher": researcher, // "writer": writer, // "critic": critic, // } // // supervisor, _ := prebuilt.CreateSupervisor(llm, members, "router") // // // Execute workflow // result, _ := supervisor.Invoke(ctx, map[string]any{ // "messages": []llms.MessageContent{ // { // Role: llms.ChatMessageTypeHuman, // Parts: []llms.ContentPart{ // llms.TextPart("Write a research paper on quantum computing"), // }, // }, // }, // }) // // fmt.Println(result) // } // // 2. RAG (Retrieval-Augmented Generation) System // // package main // // import ( // "context" // // "github.com/smallnest/langgraphgo/prebuilt" // "github.com/smallnest/langgraphgo/memory" // "github.com/smallnest/langgraphgo/store/postgres" // "github.com/tmc/langchaingo/embeddings/openai" // "github.com/tmc/langchaingo/llms" // "github.com/tmc/langchaingo/vectorstores/pgvector" // ) // // func main() { // // Initialize components // llm, _ := openai.NewChat(openai.GPT4) // embedder, _ := openai.NewEmbedder() // // // Setup vector store // store, _ := pgvector.New( // ctx, // pgvector.WithConnString("postgres://localhost/postgres"), // pgvector.WithEmbedder(embedder), // ) // // // Create RAG agent // rag, _ := prebuilt.CreateRAGAgent( // llm, // documentLoader, // textSplitter, // embedder, // store, // 5, // retrieve 5 documents // ) // // // Add memory for conversation // mem := memory.NewBufferMemory(100) // rag.WithMemory(mem) // // // Enable checkpointing // checkpointStore, _ := postgres.NewPostgresCheckpointStore(ctx, postgres.PostgresOptions{ // ConnString: "postgres://localhost/langgraph", // }) // rag.WithCheckpointing(graph.CheckpointConfig{ // Store: checkpointStore, // }) // // // Query the system // result, _ := rag.Invoke(ctx, map[string]any{ // "messages": []llms.MessageContent{ // { // Role: llms.ChatMessageTypeHuman, // Parts: []llms.ContentPart{ // llms.TextPart("What are the latest developments in AI?"), // }, // }, // }, // }) // } // // 3. Typed Graph with Custom State // // package main // // import ( // "context" // "fmt" // // "github.com/smallnest/langgraphgo/graph" // "github.com/smallnest/langgraphgo/prebuilt" // ) // // type WorkflowState struct { // Input string `json:"input"` // Processed string `json:"processed"` // Validated bool `json:"validated"` // Output string `json:"output"` // StepCount int `json:"step_count"` // } // // func main() { // // Create typed graph // g := graph.NewStateGraph[WorkflowState]() // // // Add typed nodes // g.AddNode("process", "Process the input", func(ctx context.Context, state WorkflowState) (WorkflowState, error) { // state.Processed = strings.ToUpper(state.Input) // state.StepCount++ // return state, nil // }) // // g.AddNode("validate", "Validate the output", func(ctx context.Context, state WorkflowState) (WorkflowState, error) { // state.Validated = len(state.Processed) > 0 // state.StepCount++ // return state, nil // }) // // g.AddNode("output", "Generate final output", func(ctx context.Context, state WorkflowState) (WorkflowState, error) { // state.Output = fmt.Sprintf("Processed: %s, Validated: %v", state.Processed, state.Validated) // state.StepCount++ // return state, nil // }) // // // Define flow // g.SetEntryPoint("process") // g.AddEdge("process", "validate") // g.AddConditionalEdge("validate", func(ctx context.Context, state WorkflowState) string { // if state.Validated { // return "output" // } // return "process" // Retry // }) // g.AddEdge("output", graph.END) // // // Compile and run // runnable, _ := g.Compile() // // result, _ := runnable.Invoke(ctx, WorkflowState{ // Input: "hello world", // }) // // fmt.Printf("Result: %+v\n", result) // fmt.Printf("Steps: %d\n", result.StepCount) // } // // # Best Practices // // 1. Choose the right agent type for your use case // - ReAct for general tasks // - Supervisor for multi-agent workflows // - PTC for complex tool interactions // // 2. Use typed graphs when possible for better type safety // // 3. Implement proper error handling in all node functions // // 4. Add checkpoints for long-running or critical workflows // // 5. Use appropriate memory strategy for conversations // // 6. Monitor execution with listeners and logging // // 7. Test thoroughly with various input scenarios // // # Configuration // // The library supports configuration through environment variables: // // - OPENAI_API_KEY: OpenAI API key for LLM access // - LANGGRAPH_LOG_LEVEL: Logging level (debug, info, warn, error) // - LANGGRAPH_CHECKPOINT_DIR: Default directory for checkpoints // - LANGGRAPH_MAX_ITERATIONS: Default max iterations for agents // // # Community and Support // // - GitHub: https://github.com/smallnest/langgraphgo // - Documentation: https://pkg.go.dev/github.com/smallnest/langgraphgo // - Examples: ./examples directory // - Issues: Report bugs and request features on GitHub // // # Contributing // // We welcome contributions! Please see: // - CONTRIBUTING.md for guidelines // - CODE_OF_CONDUCT.md for community standards // - Examples in ./examples for reference implementations // // # License // // This project is licensed under the MIT License - see the LICENSE file for details. package langgraphgo // import "github.com/smallnest/langgraphgo"
go
MIT
600df7fe3e6254f2329f606732feaecfbd52d9f2
2026-01-07T10:38:05.929544Z
false
smallnest/langgraphgo
https://github.com/smallnest/langgraphgo/blob/600df7fe3e6254f2329f606732feaecfbd52d9f2/graph/retry_test.go
graph/retry_test.go
package graph_test import ( "context" "errors" "sync/atomic" "testing" "time" "github.com/smallnest/langgraphgo/graph" ) const ( successResult = "success" ) //nolint:gocognit,cyclop // Comprehensive retry logic test with multiple scenarios func TestRetryNode(t *testing.T) { t.Parallel() t.Run("SuccessOnFirstAttempt", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() callCount := int32(0) g.AddNodeWithRetry("retry_node", "retry_node", func(ctx context.Context, state map[string]any) (map[string]any, error) { atomic.AddInt32(&callCount, 1) return map[string]any{"value": successResult}, nil }, &graph.RetryConfig{ MaxAttempts: 3, InitialDelay: 10 * time.Millisecond, BackoffFactor: 2.0, }, ) g.AddEdge("retry_node", graph.END) g.SetEntryPoint("retry_node") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } result, err := runnable.Invoke(context.Background(), map[string]any{"input": "input"}) if err != nil { t.Fatalf("Execution failed: %v", err) } actualResult, ok := result["value"] if !ok || actualResult != successResult { t.Errorf("Expected success, got %v", result) } if atomic.LoadInt32(&callCount) != 1 { t.Errorf("Expected 1 call, got %d", callCount) } }) t.Run("RetryOnTransientFailure", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() callCount := int32(0) g.AddNodeWithRetry("retry_node", "retry_node", func(ctx context.Context, state map[string]any) (map[string]any, error) { count := atomic.AddInt32(&callCount, 1) if count < 3 { return nil, errors.New("transient error") } return map[string]any{"value": successResult}, nil }, &graph.RetryConfig{ MaxAttempts: 5, InitialDelay: 5 * time.Millisecond, BackoffFactor: 1.5, }, ) g.AddEdge("retry_node", graph.END) g.SetEntryPoint("retry_node") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } result, err := runnable.Invoke(context.Background(), map[string]any{"input": "input"}) if err != nil { t.Fatalf("Execution failed: %v", err) } actualResult, ok := result["value"] if !ok || actualResult != successResult { t.Errorf("Expected success, got %v", result) } if atomic.LoadInt32(&callCount) != 3 { t.Errorf("Expected 3 calls, got %d", callCount) } }) t.Run("MaxAttemptsExceeded", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() callCount := int32(0) g.AddNodeWithRetry("retry_node", "retry_node", func(ctx context.Context, state map[string]any) (map[string]any, error) { atomic.AddInt32(&callCount, 1) return nil, errors.New("persistent error") }, &graph.RetryConfig{ MaxAttempts: 3, InitialDelay: 5 * time.Millisecond, BackoffFactor: 2.0, }, ) g.AddEdge("retry_node", graph.END) g.SetEntryPoint("retry_node") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } _, err = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) if err == nil { t.Error("Expected error for max retries exceeded") } if atomic.LoadInt32(&callCount) != 3 { t.Errorf("Expected 3 attempts, got %d", callCount) } }) t.Run("NonRetryableError", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() callCount := int32(0) g.AddNodeWithRetry("retry_node", "retry_node", func(ctx context.Context, state map[string]any) (map[string]any, error) { atomic.AddInt32(&callCount, 1) return nil, errors.New("critical error") }, &graph.RetryConfig{ MaxAttempts: 3, InitialDelay: 5 * time.Millisecond, BackoffFactor: 2.0, RetryableErrors: func(err error) bool { // Only retry if error message contains "transient" return err != nil && err.Error() == "transient" }, }, ) g.AddEdge("retry_node", graph.END) g.SetEntryPoint("retry_node") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } _, err = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) if err == nil { t.Error("Expected error for non-retryable error") } // Should only try once for non-retryable errors if atomic.LoadInt32(&callCount) != 1 { t.Errorf("Expected 1 attempt for non-retryable error, got %d", callCount) } }) } func TestTimeoutNode(t *testing.T) { t.Parallel() t.Run("SuccessWithinTimeout", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() g.AddNodeWithTimeout("timeout_node", "timeout_node", func(ctx context.Context, state map[string]any) (map[string]any, error) { time.Sleep(10 * time.Millisecond) return map[string]any{"value": successResult}, nil }, 100*time.Millisecond, ) g.AddEdge("timeout_node", graph.END) g.SetEntryPoint("timeout_node") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } result, err := runnable.Invoke(context.Background(), map[string]any{"input": "input"}) if err != nil { t.Fatalf("Execution failed: %v", err) } actualResult, ok := result["value"] if !ok || actualResult != successResult { t.Errorf("Expected success, got %v", result) } }) t.Run("TimeoutExceeded", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() g.AddNodeWithTimeout("timeout_node", "timeout_node", func(ctx context.Context, state map[string]any) (map[string]any, error) { time.Sleep(100 * time.Millisecond) return map[string]any{"value": successResult}, nil }, 20*time.Millisecond, ) g.AddEdge("timeout_node", graph.END) g.SetEntryPoint("timeout_node") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } _, err = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) if err == nil { t.Error("Expected timeout error") } }) t.Run("RespectContextCancellation", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() g.AddNodeWithTimeout("timeout_node", "timeout_node", func(ctx context.Context, _ map[string]any) (map[string]any, error) { select { case <-ctx.Done(): return nil, ctx.Err() case <-time.After(100 * time.Millisecond): return map[string]any{"value": successResult}, nil } }, 200*time.Millisecond, ) g.AddEdge("timeout_node", graph.END) g.SetEntryPoint("timeout_node") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) defer cancel() _, err = runnable.Invoke(ctx, map[string]any{"input": "input"}) if err == nil { t.Error("Expected context cancellation error") } }) } func TestCircuitBreaker(t *testing.T) { t.Parallel() t.Run("CircuitOpensAfterFailures", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() callCount := int32(0) g.AddNodeWithCircuitBreaker("cb_node", "cb_node", func(ctx context.Context, state map[string]any) (map[string]any, error) { atomic.AddInt32(&callCount, 1) return nil, errors.New("service unavailable") }, graph.CircuitBreakerConfig{ FailureThreshold: 2, SuccessThreshold: 2, Timeout: 50 * time.Millisecond, HalfOpenMaxCalls: 1, }, ) g.AddEdge("cb_node", graph.END) g.SetEntryPoint("cb_node") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } // First call - should fail _, _ = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) // Second call - should fail and open circuit _, _ = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) // Third call - circuit should be open _, err = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) if err == nil { t.Error("Expected circuit breaker open error") } // Should have only 2 actual calls (third blocked by circuit breaker) if atomic.LoadInt32(&callCount) != 2 { t.Errorf("Expected 2 calls, got %d", callCount) } }) t.Run("CircuitClosesAfterSuccess", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() callCount := int32(0) g.AddNodeWithCircuitBreaker("cb_node", "cb_node", func(ctx context.Context, state map[string]any) (map[string]any, error) { count := atomic.AddInt32(&callCount, 1) // Fail first 2 calls, succeed afterwards if count <= 2 { return nil, errors.New("service unavailable") } return map[string]any{"value": successResult}, nil }, graph.CircuitBreakerConfig{ FailureThreshold: 2, SuccessThreshold: 1, Timeout: 10 * time.Millisecond, HalfOpenMaxCalls: 2, }, ) g.AddEdge("cb_node", graph.END) g.SetEntryPoint("cb_node") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } // First two calls fail and open circuit _, _ = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) _, _ = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) // Wait for timeout to move to half-open time.Sleep(15 * time.Millisecond) // This call should succeed and close circuit result, err := runnable.Invoke(context.Background(), map[string]any{"input": "input"}) if err != nil { t.Fatalf("Expected success after circuit recovery: %v", err) } actualResult, ok := result["value"] if !ok || actualResult != successResult { t.Errorf("Expected success, got %v", result) } }) } //nolint:gocognit,cyclop // Comprehensive rate limiter test with multiple scenarios func TestRateLimiter(t *testing.T) { t.Parallel() t.Run("AllowsCallsWithinLimit", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() callCount := int32(0) g.AddNodeWithRateLimit("rate_limited", "rate_limited", func(ctx context.Context, state map[string]any) (map[string]any, error) { atomic.AddInt32(&callCount, 1) return map[string]any{"value": successResult}, nil }, 3, 100*time.Millisecond, ) g.AddEdge("rate_limited", graph.END) g.SetEntryPoint("rate_limited") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } // Make 3 calls within the window - all should succeed for i := range 3 { result, err := runnable.Invoke(context.Background(), map[string]any{"input": "input"}) if err != nil { t.Fatalf("Call %d failed: %v", i+1, err) } actualResult, ok := result["value"] if !ok || actualResult != successResult { t.Errorf("Expected success, got %v", result) } } if atomic.LoadInt32(&callCount) != 3 { t.Errorf("Expected 3 calls, got %d", callCount) } }) t.Run("BlocksCallsExceedingLimit", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() callCount := int32(0) g.AddNodeWithRateLimit("rate_limited", "rate_limited", func(ctx context.Context, state map[string]any) (map[string]any, error) { atomic.AddInt32(&callCount, 1) return map[string]any{"value": successResult}, nil }, 2, 100*time.Millisecond, ) g.AddEdge("rate_limited", graph.END) g.SetEntryPoint("rate_limited") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } // Make 2 calls - should succeed _, _ = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) _, _ = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) // Third call should be rate limited _, err = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) if err == nil { t.Error("Expected rate limit error") } if atomic.LoadInt32(&callCount) != 2 { t.Errorf("Expected 2 calls, got %d", callCount) } }) t.Run("AllowsCallsAfterWindowExpires", func(t *testing.T) { g := graph.NewStateGraph[map[string]any]() callCount := int32(0) g.AddNodeWithRateLimit("rate_limited", "rate_limited", func(ctx context.Context, state map[string]any) (map[string]any, error) { atomic.AddInt32(&callCount, 1) return map[string]any{"value": successResult}, nil }, 2, 50*time.Millisecond, ) g.AddEdge("rate_limited", graph.END) g.SetEntryPoint("rate_limited") runnable, err := g.Compile() if err != nil { t.Fatalf("Failed to compile: %v", err) } // Make 2 calls _, _ = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) _, _ = runnable.Invoke(context.Background(), map[string]any{"input": "input"}) // Wait for window to expire time.Sleep(60 * time.Millisecond) // Should be able to make more calls result, err := runnable.Invoke(context.Background(), map[string]any{"input": "input"}) if err != nil { t.Fatalf("Call after window expiry failed: %v", err) } actualResult, ok := result["value"] if !ok || actualResult != successResult { t.Errorf("Expected success, got %v", result) } if atomic.LoadInt32(&callCount) != 3 { t.Errorf("Expected 3 calls, got %d", callCount) } }) } func TestExponentialBackoffRetry(t *testing.T) { t.Parallel() t.Run("SuccessAfterRetries", func(t *testing.T) { attempts := int32(0) fn := func() (any, error) { count := atomic.AddInt32(&attempts, 1) if count < 3 { return nil, errors.New("temporary failure") } return successResult, nil } result, err := graph.ExponentialBackoffRetry( context.Background(), fn, 5, 5*time.Millisecond, ) if err != nil { t.Fatalf("Expected success, got error: %v", err) } // ExponentialBackoffRetry returns result directly, not wrapped if result != successResult { t.Errorf("Expected success, got %v", result) } if atomic.LoadInt32(&attempts) != 3 { t.Errorf("Expected 3 attempts, got %d", attempts) } }) t.Run("MaxAttemptsReached", func(t *testing.T) { attempts := int32(0) fn := func() (any, error) { atomic.AddInt32(&attempts, 1) return nil, errors.New("persistent failure") } _, err := graph.ExponentialBackoffRetry( context.Background(), fn, 3, 5*time.Millisecond, ) if err == nil { t.Error("Expected max attempts error") } if atomic.LoadInt32(&attempts) != 3 { t.Errorf("Expected 3 attempts, got %d", attempts) } }) t.Run("ContextCancellation", func(t *testing.T) { attempts := int32(0) fn := func() (any, error) { atomic.AddInt32(&attempts, 1) return nil, errors.New("failure") } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() _, err := graph.ExponentialBackoffRetry( ctx, fn, 10, 10*time.Millisecond, ) if !errors.Is(err, context.DeadlineExceeded) { t.Errorf("Expected context deadline exceeded, got %v", err) } // Should have made at least 1 attempt but not all 10 count := atomic.LoadInt32(&attempts) if count < 1 || count >= 10 { t.Errorf("Expected 1-3 attempts, got %d", count) } }) }
go
MIT
600df7fe3e6254f2329f606732feaecfbd52d9f2
2026-01-07T10:38:05.929544Z
false
smallnest/langgraphgo
https://github.com/smallnest/langgraphgo/blob/600df7fe3e6254f2329f606732feaecfbd52d9f2/graph/checkpointing_test.go
graph/checkpointing_test.go
package graph_test import ( "context" "fmt" "slices" "strings" "testing" "time" "github.com/smallnest/langgraphgo/graph" st "github.com/smallnest/langgraphgo/store" "github.com/smallnest/langgraphgo/store/redis" ) func TestMemoryCheckpointStore_SaveAndLoad(t *testing.T) { t.Parallel() store := graph.NewMemoryCheckpointStore() ctx := context.Background() checkpoint := &st.Checkpoint{ ID: "test_checkpoint_1", NodeName: testNode, State: "test_state", Timestamp: time.Now(), Version: 1, Metadata: map[string]any{ "execution_id": "exec_123", }, } // Test Save err := store.Save(ctx, checkpoint) if err != nil { t.Fatalf("Failed to save checkpoint: %v", err) } // Test Load loaded, err := store.Load(ctx, "test_checkpoint_1") if err != nil { t.Fatalf("Failed to load checkpoint: %v", err) } if loaded.ID != checkpoint.ID { t.Errorf("Expected ID %s, got %s", checkpoint.ID, loaded.ID) } if loaded.NodeName != checkpoint.NodeName { t.Errorf("Expected NodeName %s, got %s", checkpoint.NodeName, loaded.NodeName) } if loaded.State != checkpoint.State { t.Errorf("Expected State %v, got %v", checkpoint.State, loaded.State) } } func TestMemoryCheckpointStore_LoadNonExistent(t *testing.T) { t.Parallel() store := graph.NewMemoryCheckpointStore() ctx := context.Background() _, err := store.Load(ctx, "non_existent") if err == nil { t.Error("Expected error for non-existent checkpoint") } if !strings.Contains(err.Error(), "checkpoint not found") { t.Errorf("Expected 'checkpoint not found' error, got: %v", err) } } func TestMemoryCheckpointStore_List(t *testing.T) { t.Parallel() store := graph.NewMemoryCheckpointStore() ctx := context.Background() executionID := "exec_123" // Save multiple checkpoints checkpoints := []*st.Checkpoint{ { ID: "checkpoint_1", Metadata: map[string]any{ "execution_id": executionID, }, }, { ID: "checkpoint_2", Metadata: map[string]any{ "execution_id": executionID, }, }, { ID: "checkpoint_3", Metadata: map[string]any{ "execution_id": "different_exec", }, }, } for _, checkpoint := range checkpoints { err := store.Save(ctx, checkpoint) if err != nil { t.Fatalf("Failed to save checkpoint: %v", err) } } // List checkpoints for specific execution listed, err := store.List(ctx, executionID) if err != nil { t.Fatalf("Failed to list checkpoints: %v", err) } if len(listed) != 2 { t.Errorf("Expected 2 checkpoints, got %d", len(listed)) } // Verify correct checkpoints returned ids := make(map[string]bool) for _, checkpoint := range listed { ids[checkpoint.ID] = true } if !ids["checkpoint_1"] || !ids["checkpoint_2"] { t.Error("Wrong checkpoints returned") } } func TestMemoryCheckpointStore_Delete(t *testing.T) { t.Parallel() store := graph.NewMemoryCheckpointStore() ctx := context.Background() checkpoint := &st.Checkpoint{ ID: "test_checkpoint", } // Save and verify err := store.Save(ctx, checkpoint) if err != nil { t.Fatalf("Failed to save checkpoint: %v", err) } _, err = store.Load(ctx, "test_checkpoint") if err != nil { t.Error("Checkpoint should exist before deletion") } // Delete err = store.Delete(ctx, "test_checkpoint") if err != nil { t.Fatalf("Failed to delete checkpoint: %v", err) } // Verify deletion _, err = store.Load(ctx, "test_checkpoint") if err == nil { t.Error("Checkpoint should not exist after deletion") } } func TestMemoryCheckpointStore_Clear(t *testing.T) { t.Parallel() store := graph.NewMemoryCheckpointStore() ctx := context.Background() executionID := "exec_123" // Save checkpoints checkpoints := []*st.Checkpoint{ { ID: "checkpoint_1", Metadata: map[string]any{ "execution_id": executionID, }, }, { ID: "checkpoint_2", Metadata: map[string]any{ "execution_id": executionID, }, }, { ID: "checkpoint_3", Metadata: map[string]any{ "execution_id": "different_exec", }, }, } for _, checkpoint := range checkpoints { err := store.Save(ctx, checkpoint) if err != nil { t.Fatalf("Failed to save checkpoint: %v", err) } } // Clear execution err := store.Clear(ctx, executionID) if err != nil { t.Fatalf("Failed to clear checkpoints: %v", err) } // Verify clearing listed, err := store.List(ctx, executionID) if err != nil { t.Fatalf("Failed to list checkpoints: %v", err) } if len(listed) != 0 { t.Errorf("Expected 0 checkpoints after clear, got %d", len(listed)) } // Verify other execution's checkpoints still exist listed, err = store.List(ctx, "different_exec") if err != nil { t.Fatalf("Failed to list other execution's checkpoints: %v", err) } if len(listed) != 1 { t.Errorf("Expected 1 checkpoint for other execution, got %d", len(listed)) } } func TestFileCheckpointStore_SaveAndLoad(t *testing.T) { t.Parallel() tempDir := t.TempDir() store, err := graph.NewFileCheckpointStore(tempDir) if err != nil { t.Fatalf("Failed to create file checkpoint store: %v", err) } ctx := context.Background() checkpoint := &st.Checkpoint{ ID: "test_checkpoint", NodeName: testNode, State: "test_state", Version: 1, } // Test Save err = store.Save(ctx, checkpoint) if err != nil { t.Fatalf("Failed to save checkpoint: %v", err) } // Test Load loaded, err := store.Load(ctx, "test_checkpoint") if err != nil { t.Fatalf("Failed to load checkpoint: %v", err) } if loaded.ID != checkpoint.ID { t.Errorf("Expected ID %s, got %s", checkpoint.ID, loaded.ID) } } func TestFileCheckpointStore_List(t *testing.T) { t.Parallel() tempDir := t.TempDir() store, err := graph.NewFileCheckpointStore(tempDir) if err != nil { t.Fatalf("Failed to create file checkpoint store: %v", err) } ctx := context.Background() executionID := "exec_123" // Save multiple checkpoints checkpoints := []*st.Checkpoint{ { ID: "checkpoint_1", Metadata: map[string]any{ "execution_id": executionID, }, Version: 1, }, { ID: "checkpoint_2", Metadata: map[string]any{ "execution_id": executionID, }, Version: 2, }, { ID: "checkpoint_3", Metadata: map[string]any{ "execution_id": "different_exec", }, Version: 1, }, } for _, checkpoint := range checkpoints { err := store.Save(ctx, checkpoint) if err != nil { t.Fatalf("Failed to save checkpoint: %v", err) } } // List checkpoints for specific execution listed, err := store.List(ctx, executionID) if err != nil { t.Fatalf("Failed to list checkpoints: %v", err) } if len(listed) != 2 { t.Errorf("Expected 2 checkpoints, got %d", len(listed)) } // Verify correct checkpoints returned ids := make(map[string]bool) for _, checkpoint := range listed { ids[checkpoint.ID] = true } if !ids["checkpoint_1"] || !ids["checkpoint_2"] { t.Error("Wrong checkpoints returned") } // Verify sorting order if listed[0].Version > listed[1].Version { t.Error("Checkpoints should be sorted by version ascending") } } func TestFileCheckpointStore_Delete(t *testing.T) { t.Parallel() tempDir := t.TempDir() store, err := graph.NewFileCheckpointStore(tempDir) if err != nil { t.Fatalf("Failed to create file checkpoint store: %v", err) } ctx := context.Background() checkpoint := &st.Checkpoint{ ID: "test_checkpoint", } // Save and verify err = store.Save(ctx, checkpoint) if err != nil { t.Fatalf("Failed to save checkpoint: %v", err) } _, err = store.Load(ctx, "test_checkpoint") if err != nil { t.Error("Checkpoint should exist before deletion") } // Delete err = store.Delete(ctx, "test_checkpoint") if err != nil { t.Fatalf("Failed to delete checkpoint: %v", err) } // Verify deletion _, err = store.Load(ctx, "test_checkpoint") if err == nil { t.Error("Checkpoint should not exist after deletion") } } func TestFileCheckpointStore_Clear(t *testing.T) { t.Parallel() tempDir := t.TempDir() store, err := graph.NewFileCheckpointStore(tempDir) if err != nil { t.Fatalf("Failed to create file checkpoint store: %v", err) } ctx := context.Background() executionID := "exec_123" // Save checkpoints checkpoints := []*st.Checkpoint{ { ID: "checkpoint_1", Metadata: map[string]any{ "execution_id": executionID, }, }, { ID: "checkpoint_2", Metadata: map[string]any{ "execution_id": executionID, }, }, { ID: "checkpoint_3", Metadata: map[string]any{ "execution_id": "different_exec", }, }, } for _, checkpoint := range checkpoints { err := store.Save(ctx, checkpoint) if err != nil { t.Fatalf("Failed to save checkpoint: %v", err) } } // Clear execution err = store.Clear(ctx, executionID) if err != nil { t.Fatalf("Failed to clear checkpoints: %v", err) } // Verify clearing listed, err := store.List(ctx, executionID) if err != nil { t.Fatalf("Failed to list checkpoints: %v", err) } if len(listed) != 0 { t.Errorf("Expected 0 checkpoints after clear, got %d", len(listed)) } // Verify other execution's checkpoints still exist listed, err = store.List(ctx, "different_exec") if err != nil { t.Fatalf("Failed to list other execution's checkpoints: %v", err) } if len(listed) != 1 { t.Errorf("Expected 1 checkpoint for other execution, got %d", len(listed)) } } func TestCheckpointableRunnable_Basic(t *testing.T) { t.Parallel() // Create graph g := graph.NewListenableStateGraph[map[string]any]() g.AddNode("step1", "step1", func(ctx context.Context, state map[string]any) (map[string]any, error) { return map[string]any{"result": "step1_result"}, nil }) g.AddNode("step2", "step2", func(ctx context.Context, state map[string]any) (map[string]any, error) { return map[string]any{"result": "step2_result"}, nil }) g.AddEdge("step1", "step2") g.AddEdge("step2", graph.END) g.SetEntryPoint("step1") // Compile listenable runnable listenableRunnable, err := g.CompileListenable() if err != nil { t.Fatalf("Failed to compile listenable runnable: %v", err) } // Create checkpointable runnable config := graph.DefaultCheckpointConfig() checkpointableRunnable := graph.NewCheckpointableRunnable(listenableRunnable, config) ctx := context.Background() result, err := checkpointableRunnable.Invoke(ctx, map[string]any{}) if err != nil { t.Fatalf("Execution failed: %v", err) } resultMap := result if resultMap["result"] != "step2_result" { t.Errorf("Expected 'step2_result', got %v", resultMap) } // Wait for async checkpoint operations time.Sleep(100 * time.Millisecond) // Check that checkpoints were created checkpoints, err := checkpointableRunnable.ListCheckpoints(ctx) if err != nil { t.Fatalf("Failed to list checkpoints: %v", err) } if len(checkpoints) != 2 { t.Errorf("Expected 2 checkpoints (one per completed node), got %d", len(checkpoints)) } // Verify checkpoint contents nodeNames := make(map[string]bool) for _, checkpoint := range checkpoints { nodeNames[checkpoint.NodeName] = true if checkpoint.State == nil { t.Error("Checkpoint state should not be nil") } if checkpoint.Timestamp.IsZero() { t.Error("Checkpoint timestamp should be set") } } if !nodeNames["step1"] || !nodeNames["step2"] { t.Error("Expected checkpoints for both step1 and step2") } } func TestCheckpointableRunnable_ManualCheckpoint(t *testing.T) { t.Parallel() g := graph.NewListenableStateGraph[map[string]any]() g.AddNode(testNode, testNode, func(ctx context.Context, state map[string]any) (map[string]any, error) { return map[string]any{"result": testResult}, nil }) g.AddEdge(testNode, graph.END) g.SetEntryPoint(testNode) listenableRunnable, err := g.CompileListenable() if err != nil { t.Fatalf("Failed to compile: %v", err) } config := graph.DefaultCheckpointConfig() checkpointableRunnable := graph.NewCheckpointableRunnable(listenableRunnable, config) ctx := context.Background() // Manual checkpoint save err = checkpointableRunnable.SaveCheckpoint(ctx, testNode, map[string]any{"result": "manual_state"}) if err != nil { t.Fatalf("Failed to save manual checkpoint: %v", err) } checkpoints, err := checkpointableRunnable.ListCheckpoints(ctx) if err != nil { t.Fatalf("Failed to list checkpoints: %v", err) } if len(checkpoints) != 1 { t.Errorf("Expected 1 checkpoint, got %d", len(checkpoints)) } checkpoint := checkpoints[0] if checkpoint.NodeName != testNode { t.Errorf("Expected node name 'test_node', got %s", checkpoint.NodeName) } stateMap, ok := checkpoint.State.(map[string]any) if !ok { t.Fatalf("Expected state to be map[string]any, got %T", checkpoint.State) } if stateMap["result"] != "manual_state" { t.Errorf("Expected state 'manual_state', got %v", checkpoint.State) } } func TestCheckpointableRunnable_LoadCheckpoint(t *testing.T) { t.Parallel() g := graph.NewListenableStateGraph[map[string]any]() g.AddNode(testNode, testNode, func(ctx context.Context, state map[string]any) (map[string]any, error) { return map[string]any{"result": testResult}, nil }) g.AddEdge(testNode, graph.END) g.SetEntryPoint(testNode) listenableRunnable, err := g.CompileListenable() if err != nil { t.Fatalf("Failed to compile: %v", err) } config := graph.DefaultCheckpointConfig() checkpointableRunnable := graph.NewCheckpointableRunnable(listenableRunnable, config) ctx := context.Background() // Save checkpoint err = checkpointableRunnable.SaveCheckpoint(ctx, testNode, map[string]any{"result": "saved_state"}) if err != nil { t.Fatalf("Failed to save checkpoint: %v", err) } checkpoints, err := checkpointableRunnable.ListCheckpoints(ctx) if err != nil { t.Fatalf("Failed to list checkpoints: %v", err) } if len(checkpoints) == 0 { t.Fatal("No checkpoints found") } checkpointID := checkpoints[0].ID // Load checkpoint loaded, err := checkpointableRunnable.LoadCheckpoint(ctx, checkpointID) if err != nil { t.Fatalf("Failed to load checkpoint: %v", err) } stateMap, ok := loaded.State.(map[string]any) if !ok { t.Fatalf("Expected loaded state to be map[string]any, got %T", loaded.State) } if stateMap["result"] != "saved_state" { t.Errorf("Expected loaded state 'saved_state', got %v", loaded.State) } } func TestCheckpointableRunnable_ClearCheckpoints(t *testing.T) { t.Parallel() g := graph.NewListenableStateGraph[map[string]any]() g.AddNode(testNode, testNode, func(ctx context.Context, state map[string]any) (map[string]any, error) { return map[string]any{"result": testResult}, nil }) g.AddEdge(testNode, graph.END) g.SetEntryPoint(testNode) listenableRunnable, err := g.CompileListenable() if err != nil { t.Fatalf("Failed to compile: %v", err) } config := graph.DefaultCheckpointConfig() checkpointableRunnable := graph.NewCheckpointableRunnable(listenableRunnable, config) ctx := context.Background() // Save some checkpoints err = checkpointableRunnable.SaveCheckpoint(ctx, "test_node1", map[string]any{"result": "state1"}) if err != nil { t.Fatalf("Failed to save checkpoint 1: %v", err) } err = checkpointableRunnable.SaveCheckpoint(ctx, "test_node2", map[string]any{"result": "state2"}) if err != nil { t.Fatalf("Failed to save checkpoint 2: %v", err) } // Verify checkpoints exist checkpoints, err := checkpointableRunnable.ListCheckpoints(ctx) if err != nil { t.Fatalf("Failed to list checkpoints: %v", err) } if len(checkpoints) != 2 { t.Errorf("Expected 2 checkpoints, got %d", len(checkpoints)) } // Clear checkpoints err = checkpointableRunnable.ClearCheckpoints(ctx) if err != nil { t.Fatalf("Failed to clear checkpoints: %v", err) } // Verify checkpoints cleared checkpoints, err = checkpointableRunnable.ListCheckpoints(ctx) if err != nil { t.Fatalf("Failed to list checkpoints after clear: %v", err) } if len(checkpoints) != 0 { t.Errorf("Expected 0 checkpoints after clear, got %d", len(checkpoints)) } } func TestCheckpointableStateGraph_CompileCheckpointable(t *testing.T) { t.Parallel() g := graph.NewCheckpointableStateGraph[map[string]any]() g.AddNode(testNode, testNode, func(ctx context.Context, state map[string]any) (map[string]any, error) { return map[string]any{"result": testResult}, nil }) g.AddEdge(testNode, graph.END) g.SetEntryPoint(testNode) checkpointableRunnable, err := g.CompileCheckpointable() if err != nil { t.Fatalf("Failed to compile checkpointable: %v", err) } ctx := context.Background() result, err := checkpointableRunnable.Invoke(ctx, map[string]any{}) if err != nil { t.Fatalf("Execution failed: %v", err) } resultMap := result if resultMap["result"] != testResult { t.Errorf("Expected 'test_result', got %v", resultMap) } } func TestCheckpointableStateGraph_CustomConfig(t *testing.T) { t.Parallel() store := graph.NewMemoryCheckpointStore() config := graph.CheckpointConfig{ Store: store, AutoSave: false, SaveInterval: time.Minute, MaxCheckpoints: 5, } g := graph.NewCheckpointableStateGraphWithConfig[map[string]any](config) // Verify config is set actualConfig := g.GetCheckpointConfig() if actualConfig.AutoSave != false { t.Error("Expected AutoSave to be false") } if actualConfig.SaveInterval != time.Minute { t.Error("Expected SaveInterval to be 1 minute") } if actualConfig.MaxCheckpoints != 5 { t.Error("Expected MaxCheckpoints to be 5") } } // Integration test with comprehensive workflow // //nolint:gocognit,cyclop // Comprehensive integration test requires multiple scenarios func TestCheckpointing_Integration(t *testing.T) { t.Parallel() // Create checkpointable graph g := graph.NewCheckpointableStateGraph[map[string]any]() // Build a multi-step pipeline g.AddNode("analyze", "analyze", func(ctx context.Context, state map[string]any) (map[string]any, error) { state["analyzed"] = true return state, nil }) g.AddNode("process", "process", func(ctx context.Context, state map[string]any) (map[string]any, error) { state["processed"] = true return state, nil }) g.AddNode("finalize", "finalize", func(ctx context.Context, state map[string]any) (map[string]any, error) { state["finalized"] = true return state, nil }) g.AddEdge("analyze", "process") g.AddEdge("process", "finalize") g.AddEdge("finalize", graph.END) g.SetEntryPoint("analyze") // Compile checkpointable runnable runnable, err := g.CompileCheckpointable() if err != nil { t.Fatalf("Failed to compile: %v", err) } // Execute with initial state initialState := map[string]any{ "input": "test_data", } ctx := context.Background() result, err := runnable.Invoke(ctx, initialState) if err != nil { t.Fatalf("Execution failed: %v", err) } // Verify final result finalState := result if !finalState["analyzed"].(bool) { t.Error("Expected analyzed to be true") } if !finalState["processed"].(bool) { t.Error("Expected processed to be true") } if !finalState["finalized"].(bool) { t.Error("Expected finalized to be true") } // Wait for async checkpoint operations time.Sleep(100 * time.Millisecond) // Check checkpoints checkpoints, err := runnable.ListCheckpoints(ctx) if err != nil { t.Fatalf("Failed to list checkpoints: %v", err) } if len(checkpoints) != 3 { t.Errorf("Expected 3 checkpoints, got %d", len(checkpoints)) } // Verify each checkpoint has the correct state progression checkpointsByNode := make(map[string]*st.Checkpoint) for _, checkpoint := range checkpoints { checkpointsByNode[checkpoint.NodeName] = checkpoint } fmt.Printf("checkpoints: %+v\n", checkpointsByNode) // Check analyze checkpoint if analyzeCP, exists := checkpointsByNode["analyze"]; exists { state := analyzeCP.State.(map[string]any) if !state["analyzed"].(bool) { t.Error("Analyze checkpoint should have analyzed=true") } } else { t.Error("Missing checkpoint for analyze node") } // Check process checkpoint if processCP, exists := checkpointsByNode["process"]; exists { state := processCP.State.(map[string]any) if !state["processed"].(bool) { t.Error("Process checkpoint should have processed=true") } } else { t.Error("Missing checkpoint for process node") } // Check finalize checkpoint if finalizeCP, exists := checkpointsByNode["finalize"]; exists { state := finalizeCP.State.(map[string]any) if !state["finalized"].(bool) { t.Error("Finalize checkpoint should have finalized=true") } } else { t.Error("Missing checkpoint for finalize node") } } func TestCheckpointListener_ErrorHandling(t *testing.T) { t.Parallel() g := graph.NewListenableStateGraph[map[string]any]() // Node that will fail g.AddNode("failing_node", "failing_node", func(ctx context.Context, state map[string]any) (map[string]any, error) { return nil, fmt.Errorf("simulated failure") }) g.AddEdge("failing_node", graph.END) g.SetEntryPoint("failing_node") listenableRunnable, err := g.CompileListenable() if err != nil { t.Fatalf("Failed to compile: %v", err) } config := graph.DefaultCheckpointConfig() checkpointableRunnable := graph.NewCheckpointableRunnable(listenableRunnable, config) ctx := context.Background() // This should fail _, err = checkpointableRunnable.Invoke(ctx, map[string]any{}) if err == nil { t.Error("Expected execution to fail") } // Wait for async operations time.Sleep(100 * time.Millisecond) // Should not have checkpoints for failed nodes checkpoints, err := checkpointableRunnable.ListCheckpoints(ctx) if err != nil { t.Fatalf("Failed to list checkpoints: %v", err) } // Should have no checkpoints since node failed if len(checkpoints) != 0 { t.Errorf("Expected no checkpoints for failed execution, got %d", len(checkpoints)) } } // TestAutoResume_WithThreadID tests automatic resume using thread_id // This matches the Python LangGraph behavior where providing thread_id // automatically loads and merges the checkpoint state with new input. func TestAutoResume_WithThreadID(t *testing.T) { t.Parallel() g := graph.NewCheckpointableStateGraph[map[string]any]() // Track execution order executionOrder := []string{} g.AddNode("step1", "step1", func(ctx context.Context, state map[string]any) (map[string]any, error) { executionOrder = append(executionOrder, "step1") state["step1"] = "done" return state, nil }) g.AddNode("step2", "step2", func(ctx context.Context, state map[string]any) (map[string]any, error) { executionOrder = append(executionOrder, "step2") state["step2"] = "done" return state, nil }) g.AddNode("step3", "step3", func(ctx context.Context, state map[string]any) (map[string]any, error) { executionOrder = append(executionOrder, "step3") state["step3"] = "done" return state, nil }) g.AddEdge("step1", "step2") g.AddEdge("step2", "step3") g.AddEdge("step3", graph.END) g.SetEntryPoint("step1") runnable, err := g.CompileCheckpointable() if err != nil { t.Fatalf("Failed to compile: %v", err) } runnable.SetExecutionID("test_auto_resume") // Use consistent execution ID ctx := context.Background() threadID := "test-thread-auto-resume" // First execution - create checkpoint result1, err := runnable.InvokeWithConfig(ctx, map[string]any{"input": "first"}, graph.WithThreadID(threadID)) if err != nil { t.Fatalf("First execution failed: %v", err) } // Wait for checkpoint save time.Sleep(100 * time.Millisecond) // Verify first execution completed all steps if result1["step1"] != "done" || result1["step2"] != "done" || result1["step3"] != "done" { t.Errorf("First execution incomplete: %v", result1) } // Second execution - demonstrate checkpoint state loading // When using thread_id with an existing checkpoint: // - The checkpoint state is loaded and merged with new input // - ResumeFrom is set to continue from where it left off // Reset execution tracker executionOrder = []string{} // Note: For completed graphs, you can manually GetState to retrieve the final state // This is the recommended pattern for "continuing" a completed conversation snapshot, err := runnable.GetState(ctx, graph.WithThreadID(threadID)) if err != nil { t.Fatalf("Failed to get state: %v", err) } // Verify we can retrieve the checkpoint state if snapshot == nil { t.Fatal("Expected non-nil state snapshot") } t.Logf("Retrieved state snapshot: %+v", snapshot.Values) // For a new continuation with additional input, create a new graph execution // with the checkpoint state as base result2, err := runnable.InvokeWithConfig(ctx, map[string]any{"input": "second"}, graph.WithThreadID(threadID)) if err != nil { t.Fatalf("Second execution failed: %v", err) } // The second execution loads checkpoint state and continues t.Logf("Second execution ran nodes: %v", executionOrder) // Note: step3 runs again because ResumeFrom is set to the checkpoint node // This is expected behavior for continuation if result2["input"] != "second" { t.Errorf("Input should be 'second', got: %v", result2["input"]) } } // TestAutoResume_InterruptAndResume tests the interrupt and resume workflow // with automatic state loading. func TestAutoResume_InterruptAndResume(t *testing.T) { t.Parallel() g := graph.NewCheckpointableStateGraph[map[string]any]() executionCount := map[string]int{} g.AddNode("step1", "step1", func(ctx context.Context, state map[string]any) (map[string]any, error) { executionCount["step1"]++ state["step1"] = "done" return state, nil }) g.AddNode("step2", "step2", func(ctx context.Context, state map[string]any) (map[string]any, error) { executionCount["step2"]++ state["step2"] = "done" return state, nil }) g.AddNode("step3", "step3", func(ctx context.Context, state map[string]any) (map[string]any, error) { executionCount["step3"]++ state["step3"] = "done" return state, nil }) g.AddEdge("step1", "step2") g.AddEdge("step2", "step3") g.AddEdge("step3", graph.END) g.SetEntryPoint("step1") runnable, err := g.CompileCheckpointable() if err != nil { t.Fatalf("Failed to compile: %v", err) } runnable.SetExecutionID("test_interrupt_resume") ctx := context.Background() threadID := "test-thread-interrupt" // Phase 1: Run with interrupt after step2 config1 := graph.WithThreadID(threadID) config1.InterruptAfter = []string{"step2"} result1, err := runnable.InvokeWithConfig(ctx, map[string]any{"input": "phase1"}, config1) // InterruptAfter returns a GraphInterrupt error, which is expected if err != nil { if _, ok := err.(*graph.GraphInterrupt); !ok { t.Fatalf("Phase 1 unexpected error: %v", err) } // For GraphInterrupt, the result is still valid (contains state at interrupt point) } // Wait for checkpoint save time.Sleep(100 * time.Millisecond) // Verify phase1 stopped after step2 if result1["step1"] != "done" { t.Error("step1 should be done") } if result1["step2"] != "done" { t.Error("step2 should be done") } if result1["step3"] != nil { t.Error("step3 should not be done (interrupted)") } if executionCount["step1"] != 1 || executionCount["step2"] != 1 || executionCount["step3"] != 0 { t.Errorf("Unexpected execution counts: %v", executionCount) } // Phase 2: Resume with just thread_id - should auto-load state and continue // Use WithThreadID for simplicity // Note: After ResumeFrom step2, step2 and step3 will execute again // The checkpoint state is loaded and merged, but ResumeFrom causes re-execution result2, err := runnable.InvokeWithConfig(ctx, map[string]any{"input": "phase2"}, graph.WithThreadID(threadID)) if err != nil { t.Fatalf("Phase 2 execution failed: %v", err) } // Verify phase2 completed step3 if result2["step3"] != "done" { t.Errorf("Phase 2 should complete step3: %v", result2) } if result2["input"] != "phase2" { t.Errorf("Input should be 'phase2', got: %v", result2["input"]) } // Step3 should have run if executionCount["step3"] < 1 { t.Errorf("step3 should run at least once, ran %d times", executionCount["step3"]) } } // TestAutoResume_MergeStates tests that state merging works correctly // when resuming with new input. func TestAutoResume_MergeStates(t *testing.T) { t.Parallel() g := graph.NewCheckpointableStateGraph[map[string]any]() g.AddNode("process", "process", func(ctx context.Context, state map[string]any) (map[string]any, error) { // Initialize messages slice if not exists if state["messages"] == nil { state["messages"] = []string{} } messages := state["messages"].([]string) messages = append(messages, state["input"].(string)) state["messages"] = messages return state, nil }) g.AddEdge("process", graph.END) g.SetEntryPoint("process") runnable, err := g.CompileCheckpointable() if err != nil { t.Fatalf("Failed to compile: %v", err) } ctx := context.Background() threadID := "test-thread-merge" // First call result1, err := runnable.InvokeWithConfig(ctx, map[string]any{"input": "hello"}, graph.WithThreadID(threadID)) if err != nil { t.Fatalf("First call failed: %v", err) } time.Sleep(50 * time.Millisecond) messages1 := result1["messages"].([]string) if len(messages1) != 1 || messages1[0] != "hello" { t.Errorf("Unexpected messages after first call: %v", messages1) } // Second call - should merge state (in this implementation, input replaces) // For proper append behavior, a reducer would be needed result2, err := runnable.InvokeWithConfig(ctx, map[string]any{"input": "world"}, graph.WithThreadID(threadID)) if err != nil { t.Fatalf("Second call failed: %v", err) } // The state should be preserved across calls messages2 := result2["messages"].([]string) if len(messages2) == 0 { t.Errorf("Messages should be preserved: %v", messages2) } } // TestWithThreadID tests the WithThreadID helper function func TestWithThreadID(t *testing.T) { t.Parallel() config := graph.WithThreadID("test-thread-123") if config == nil { t.Fatal("WithThreadID should return non-nil config") } if config.Configurable == nil { t.Fatal("Configurable should not be nil") } threadID, ok := config.Configurable["thread_id"].(string) if !ok { t.Fatal("thread_id should be a string") } if threadID != "test-thread-123" { t.Errorf("Expected thread_id 'test-thread-123', got '%s'", threadID) } } // TestWithInterruptBeforeAfter tests the helper functions for interrupt configuration func TestWithInterruptBeforeAfter(t *testing.T) { t.Parallel() // Test WithInterruptBefore config1 := graph.WithInterruptBefore("node1", "node2") if len(config1.InterruptBefore) != 2 { t.Errorf("Expected 2 interrupt-before nodes, got %d", len(config1.InterruptBefore)) } if config1.InterruptBefore[0] != "node1" || config1.InterruptBefore[1] != "node2" { t.Error("InterruptBefore nodes not set correctly") } // Test WithInterruptAfter config2 := graph.WithInterruptAfter("node3") if len(config2.InterruptAfter) != 1 { t.Errorf("Expected 1 interrupt-after node, got %d", len(config2.InterruptAfter)) } if config2.InterruptAfter[0] != "node3" { t.Error("InterruptAfter node not set correctly") } } // TestMaxCheckpoints_AutoCleanup tests that MaxCheckpoints automatically // removes old checkpoints when the limit is exceeded. func TestMaxCheckpoints_AutoCleanup(t *testing.T) { t.Parallel() store := graph.NewMemoryCheckpointStore() g := graph.NewCheckpointableStateGraph[map[string]any]() // Add multiple nodes to create multiple checkpoints for i := 1; i <= 5; i++ { nodeName := fmt.Sprintf("step%d", i) g.AddNode(nodeName, nodeName, func(ctx context.Context, state map[string]any) (map[string]any, error) { state[nodeName] = "done" return state, nil }) if i > 1 { prevNode := fmt.Sprintf("step%d", i-1) g.AddEdge(prevNode, nodeName) } } g.AddEdge("step5", graph.END) g.SetEntryPoint("step1") // Set MaxCheckpoints to 3 config := graph.CheckpointConfig{ Store: store, AutoSave: true, MaxCheckpoints: 3, } g.SetCheckpointConfig(config) runnable, err := g.CompileCheckpointable() if err != nil { t.Fatalf("Failed to compile: %v", err) } ctx := context.Background() threadID := "test-max-checkpoints" // Execute the graph with thread_id _, err = runnable.InvokeWithConfig(ctx, map[string]any{"input": "test"}, graph.WithThreadID(threadID)) if err != nil { t.Fatalf("Execution failed: %v", err) } // Wait for async checkpoint operations time.Sleep(100 * time.Millisecond) // Check that only 3 checkpoints remain (most recent ones) checkpoints, err := store.List(ctx, threadID) if err != nil { t.Fatalf("Failed to list checkpoints: %v", err) } if len(checkpoints) != 3 { t.Errorf("Expected 3 checkpoints after MaxCheckpoints cleanup, got %d", len(checkpoints)) }
go
MIT
600df7fe3e6254f2329f606732feaecfbd52d9f2
2026-01-07T10:38:05.929544Z
true
smallnest/langgraphgo
https://github.com/smallnest/langgraphgo/blob/600df7fe3e6254f2329f606732feaecfbd52d9f2/graph/add_messages_test.go
graph/add_messages_test.go
package graph import ( "testing" "github.com/stretchr/testify/assert" "github.com/tmc/langchaingo/llms" ) // Custom message struct with ID type TestMessage struct { ID string Content string } func TestAddMessages(t *testing.T) { // Case 1: Standard llms.MessageContent (No ID, simple append) t.Run("StandardMessages", func(t *testing.T) { current := []llms.MessageContent{ {Role: "user", Parts: []llms.ContentPart{llms.TextPart("Hello")}}, } newMsg := llms.MessageContent{Role: "ai", Parts: []llms.ContentPart{llms.TextPart("Hi")}} res, err := AddMessages(current, newMsg) assert.NoError(t, err) slice, ok := res.([]llms.MessageContent) assert.True(t, ok) assert.Len(t, slice, 2) assert.Equal(t, llms.ChatMessageType("user"), slice[0].Role) assert.Equal(t, llms.ChatMessageType("ai"), slice[1].Role) }) // Case 2: Structs with ID (Upsert logic) t.Run("MessagesWithID", func(t *testing.T) { current := []TestMessage{ {ID: "1", Content: "First"}, {ID: "2", Content: "Second"}, } // Update message 1, add message 3 newMessages := []TestMessage{ {ID: "1", Content: "First Updated"}, {ID: "3", Content: "Third"}, } res, err := AddMessages(current, newMessages) assert.NoError(t, err) slice, ok := res.([]TestMessage) assert.True(t, ok) assert.Len(t, slice, 3) // Check order and content assert.Equal(t, "1", slice[0].ID) assert.Equal(t, "First Updated", slice[0].Content) // Updated assert.Equal(t, "2", slice[1].ID) assert.Equal(t, "Second", slice[1].Content) // Unchanged assert.Equal(t, "3", slice[2].ID) assert.Equal(t, "Third", slice[2].Content) // Appended }) // Case 3: Mixed append (some have ID, some don't) // Note: In Go, slices must be of same type. So we can't easily mix types unless using []any // But we can test structs where ID is optional (empty string) t.Run("OptionalIDs", func(t *testing.T) { current := []TestMessage{ {ID: "1", Content: "Msg1"}, {ID: "", Content: "Msg2"}, // No ID } newMessages := []TestMessage{ {ID: "1", Content: "Msg1-Updated"}, {ID: "", Content: "Msg3"}, } res, err := AddMessages(current, newMessages) assert.NoError(t, err) slice, ok := res.([]TestMessage) assert.True(t, ok) assert.Len(t, slice, 3) // 1 updated, Msg2 kept, Msg3 appended assert.Equal(t, "Msg1-Updated", slice[0].Content) assert.Equal(t, "Msg2", slice[1].Content) assert.Equal(t, "Msg3", slice[2].Content) // Appended // Note: Msg3 is at index 2 or 3 depending on implementation details of non-ID append? // Actually, our implementation: // 1. Copy current: [Msg1(id=1), Msg2(no-id)] // 2. Process new: // - Msg1-Updated (id=1) -> Updates index 0 // - Msg3 (no-id) -> Appends // Result: [Msg1-Updated, Msg2, Msg3] -> Length 3? // Wait, let's re-read the code. // "No ID, just append" -> Yes. // Let's re-verify the length assertion. // Current: [Msg1, Msg2] // New: [Msg1-Upd, Msg3] // Result should be: [Msg1-Upd, Msg2, Msg3] -> Length 3. assert.Len(t, slice, 3) }) }
go
MIT
600df7fe3e6254f2329f606732feaecfbd52d9f2
2026-01-07T10:38:05.929544Z
false