Documentation
¶
Index ¶
- Constants
- Variables
- func DeriveIdentifier(name string) string
- func IdentifierPrefixes(id string) []string
- func ParseTMTemplate(mdTemplate string) (*template.Template, error)
- func ReservedIdSegment(s string) bool
- func Slugify(s string) string
- func SlugifyUnderscore(s string) string
- func ValidIdentifier(s string) bool
- func ValidateUniqueIdentifiers(tms []Threatmodel) error
- func VersionConstraints(tmw *ThreatmodelWrapped, emit bool) (string, error)
- func VersionConstraintsToWriter(tmw *ThreatmodelWrapped, w io.Writer) (string, error)
- type AdditionalAttribute
- type Attribute
- type Backend
- type Component
- type Control
- type ControlAttribute
- type DataFlowDiagram
- func (d *DataFlowDiagram) GenerateD2(tmName string, opts DfdRenderOptions) (string, error)
- func (d *DataFlowDiagram) GenerateDfdPng(filepath, tmName string, opts DfdRenderOptions) error
- func (d *DataFlowDiagram) GenerateDfdPngBytes(tmName string, opts DfdRenderOptions) ([]byte, error)
- func (d *DataFlowDiagram) GenerateDfdSvg(filepath, tmName string, opts DfdRenderOptions) error
- func (d *DataFlowDiagram) GenerateDfdSvgBytes(tmName string, opts DfdRenderOptions) ([]byte, error)
- func (d *DataFlowDiagram) GenerateDot(tmName string, opts DfdRenderOptions) (string, error)
- func (d *DataFlowDiagram) GenerateMermaid(tmName string, opts DfdRenderOptions) (string, error)
- type DfdData
- type DfdExternal
- type DfdFlow
- type DfdProcess
- type DfdRenderOptions
- type DfdTrustZone
- type Exclusion
- type InformationAsset
- type LegacyDataFlowDiagram
- type MermaidDiagram
- type NamedInput
- type ProposedControl
- type ProtocolStyle
- type Risk
- type RiskModel
- type ThirdPartyDependency
- type Threat
- type Threatmodel
- func (tm *Threatmodel) Identifier() string
- func (tm *Threatmodel) Include(cfg *ThreatmodelSpecConfig, myfilename string) error
- func (tm *Threatmodel) RenderMarkdown(mdTemplate string) (io.Reader, error)
- func (tm *Threatmodel) RenderOtm() (otm.OtmSchemaJson, error)
- func (tm *Threatmodel) ValidateTm(p *ThreatmodelParser) error
- type ThreatmodelParser
- func (p *ThreatmodelParser) AddTMAndWrite(tm Threatmodel, f io.Writer, debug bool) error
- func (p *ThreatmodelParser) GetWrapped() *ThreatmodelWrapped
- func (p *ThreatmodelParser) HclString() string
- func (p *ThreatmodelParser) ParseFile(filename string, isChild bool) error
- func (p *ThreatmodelParser) ParseHCLFile(filename string, isChild bool) error
- func (p *ThreatmodelParser) ParseHCLRaw(input []byte) error
- func (p *ThreatmodelParser) ParseHCLRawSet(inputs []NamedInput) error
- func (p *ThreatmodelParser) ParseJSONFile(filename string, isChild bool) error
- func (p *ThreatmodelParser) ParseJSONRaw(input []byte) error
- func (p *ThreatmodelParser) SetSkipExtendsResolution(skip bool)
- type ThreatmodelSpecConfig
- type ThreatmodelWrapped
- type UptimeDependencyClassification
- type UseCase
- type Variable
Constants ¶
const ( TmMDTemplate = `# {{.Name}} Author: {{.Author}}{{ if .Description }} ## Overview {{ .Description }} {{- end }} {{- if .Link }} See more: {{ .Link }} {{- end }} {{- if .DiagramLink }} {{- if isImage .DiagramLink }}  {{- else }} Diagram: {{ .DiagramLink }} {{- end }} {{- end }} {{- range .AllDiagrams }} {{- if isImage . }}  {{- else }} Diagram: {{ . }} {{- end }} {{- end }} {{- with .Repository }} ## Repositories {{ range . }} * {{ . }} {{- end }} {{- end }} {{- with .Attributes }} | | | | -- | -- | | Internet Facing | {{ if (eq .InternetFacing true) }}✅ {{ else }}❌ {{ end }} | | New Initiative | {{ if (eq .NewInitiative true) }}✅ {{ else }}❌ {{ end }} | | Initiative Size | {{ .InitiativeSize }} | {{- end }} {{- range .AdditionalAttributes }} | {{ .Name }} | {{ .Value }} |{{- end }} {{- with .UseCases }} ## Use Cases {{ range . }} * {{ .Description }} {{- end }} {{- end }} {{- with .Exclusions }} ## Exclusions {{ range . }} * {{ .Description }} {{- end }} {{- end }} {{- with .InformationAssets }} ## Information Assets {{ range . }} ### {{ .Name }} [{{ .InformationClassification }}] {{ .Description }} {{ if .Source }} > Source: {{ .Source }}{{- end }} {{- end }} {{- end }} {{- with .Threats }} ## Threat Scenarios {{ range . }} ### {{ .Name }} {{ .Description }} {{- if .ImpactType }} > Impact Type: {{ $impact := .ImpactType }}{{ range $index, $elem := .ImpactType }}{{ if $index}}, {{end}}{{.}}{{end}} {{- end }} {{- if .Stride}} > STRIDE: {{ $stride := .Stride }}{{ range $index, $elem := .Stride }}{{ if $index}}, {{end}}{{.}}{{end}} {{- end}} {{- with .Risk }} > Risk: Likelihood _{{ .Likelihood }}_ × Impact _{{ .Impact }}_ → Inherent Severity **{{ .Severity }}** (score {{ .InherentScore }}) {{- if .Rationale }} > > {{ .Rationale }} {{- end }} {{- end }} {{- if and .Risk (gt .ResidualRiskReduction 0.0) }} > Residual Risk (after implemented controls): score {{ .ResidualScore }} (**{{ .ResidualSeverity }}**, {{ .ResidualRiskReduction }}% reduced) {{- end }} {{- if .InformationAssetRefs }} Impacted Information Assets: {{ range .InformationAssetRefs }}* {{.}} {{ end}} {{- end}} {{- if .Control }} #### Legacy Control Description {{ .Control }} {{- end }} {{- if .Controls }} #### Controls {{ range .Controls }} ##### {{ .Name }} {{ if .Implemented }} > Implemented: ✅ {{- else }}> Implemented: ❌ {{- end }} {{ .Description }}{{- if .ImplementationNotes }} _Implementation Notes_ {{ .ImplementationNotes}}{{- end }} | | | | -- | -- | {{- if .RiskReduction }} | Risk Reduction | {{ .RiskReduction }} |{{- end }} {{- range .Attributes }} | {{ .Name }} | {{ .Value }} |{{- end }} {{- end }} {{- end }} {{- if .ProposedControls }} #### Proposed Controls {{ range .ProposedControls }}{{- if .Implemented }}- [x] {{- else }}- [ ] {{- end }} {{ .Description }} {{ end }} {{- end }} {{- end }} {{- end }} {{- with .ThirdPartyDependencies }} ## Third Party Dependencies {{ range . }} ### {{ .Name }} {{ .Description }} {{- if .Saas }} {{ .Name }} is a SaaS product that we (the company) {{ if .PayingCustomer }}pays for{{ else }}does NOT pay for{{- end}}. {{- end }} {{- if .Infrastructure }} {{ .Name }} is an infrastructure product. {{- end }} {{- if .OpenSource }} {{ .Name }} is an open source dependency. {{- end }} {{- if ne .UptimeDependency ""}} > Uptime Classification: {{ .UptimeDependency | ToUpper }} {{ .RenderUptime }} {{- end }} {{- end }} {{- end}} {{- with .MermaidDiagrams }} ## Diagrams {{ range . }} ### {{ .Name }} {{- if .Description }} {{ .Description }} {{- end }} ` + "```" + `mermaid {{ .Content }} ` + "```" + ` {{- end }} {{- end }} {{- if .CreatedAt }} {{- if .UpdatedAt }} --- Created: {{ (unixToTime .CreatedAt) }} - Updated: {{ (unixToTime .UpdatedAt) }} {{- end }} {{- end }} ` TmDashboardTemplate = `` /* 309-byte string literal not displayed */ )
const ( RiskLevelVeryLow = "very_low" RiskLevelLow = "low" RiskLevelMedium = "medium" RiskLevelHigh = "high" RiskLevelVeryHigh = "very_high" )
Risk levels (ordinal likelihood/impact enums) in canonical form.
const ( SeverityInfo = "info" SeverityLow = "low" SeverityMedium = "medium" SeverityHigh = "high" SeverityCritical = "critical" )
Severity bands, ordered info < low < medium < high < critical.
Variables ¶
var OtmVersion = "0.2.0"
OtmVersion is the Open Threat Model format version. This can be overridden at build time using:
go build -ldflags "-X github.com/threatcl/spec.OtmVersion=x.y.z"
var RiskLevels = []string{ RiskLevelVeryLow, RiskLevelLow, RiskLevelMedium, RiskLevelHigh, RiskLevelVeryHigh, }
RiskLevels is the ordered set of valid likelihood/impact enums.
var SeverityLevels = []string{ SeverityInfo, SeverityLow, SeverityMedium, SeverityHigh, SeverityCritical, }
SeverityLevels is the ordered set of valid severity bands.
var Version = "0.8.6"
Version is the current spec version. This can be overridden at build time using:
go build -ldflags "-X github.com/threatcl/spec.Version=x.y.z"
Functions ¶
func DeriveIdentifier ¶
DeriveIdentifier converts a display name to identifier form: "Tower of London" → "tower_of_london". It is SlugifyUnderscore, which shares its derivation with the OTM exporter's ids (those use dashes instead of underscores). The result is not guaranteed to satisfy ValidIdentifier — a name like "3rd Party Gateway" derives to a digit-leading token — so consumers offering dotted references should check.
func IdentifierPrefixes ¶
IdentifierPrefixes returns the proper namespace prefixes of a dotted id: "apps.web.tower" → ["apps", "apps.web"]. A flat id has none. When a prefix is itself another model's declared id, that model is the namespace's parent: it lives at the prefix address and its children sit beneath it (subject to ReservedIdSegment).
func ReservedIdSegment ¶
ReservedIdSegment reports whether s can't be used as an id segment directly beneath a parent model's id.
func Slugify ¶
Slugify converts a free-form element name into its canonical identifier-safe slug: lowercase alphanumerics separated by single hyphens, with a divider inserted at case boundaries, so "Web App!" and "WebApp" both become "web-app". This is the same slugification the OTM exporter uses for element ids. Reference resolution treats the two divider forms as equivalent, so a quoted reference may use either this kebab form or the underscore form.
func SlugifyUnderscore ¶
SlugifyUnderscore is Slugify with underscores instead of hyphens. This is the divider used for dot-notation reference namespaces (process.web_app) — underscores rather than hyphens, because a hyphen inside a bare HCL expression is easily confused with subtraction — and for OTM attribute keys. It matches the threatmodel id derivation convention.
func ValidIdentifier ¶
ValidIdentifier reports whether s is acceptable as a declared threat model id.
func ValidateUniqueIdentifiers ¶
func ValidateUniqueIdentifiers(tms []Threatmodel) error
ValidateUniqueIdentifiers checks a set of threat models for identifier collisions. Parse-time validation only ever sees one file's models, so consumers that aggregate models across files (e.g. to build a reference registry keyed by Identifier()) should run their combined set through this before relying on identifiers as addresses.
Every declared id must be identifier-safe, and no two models may share an effective Identifier() — declared or derived — since a registry needs one address per model. Derived identifiers are only collision-checked, never format-checked: a derivation like "3rd Party Gateway" → "3rd_party_gateway" isn't addressable in dotted form but is still a legal registry key.
func VersionConstraints ¶
func VersionConstraints(tmw *ThreatmodelWrapped, emit bool) (string, error)
VersionConstraints checks all threat models in tmw against all known constraints, and returns the matching warnings joined by newlines. If emit is true, warnings are also printed to stdout. New callers should prefer VersionConstraintsToWriter and control the output themselves.
func VersionConstraintsToWriter ¶
func VersionConstraintsToWriter(tmw *ThreatmodelWrapped, w io.Writer) (string, error)
VersionConstraintsToWriter checks all threat models in tmw against all known constraints, in a fixed order, writing each matching warning to w as a newline-terminated line. It returns the same warnings joined by newlines.
Types ¶
type AdditionalAttribute ¶
type Backend ¶
type Backend struct {
BackendName string `json:"backendName" hcl:"backend_name,label"`
BackendOrg string `json:"organization" hcl:"organization,attr"`
BackendTMShort string `json:"threatmodel,omitempty" hcl:"threatmodel,optional"`
BackendProject string `json:"project,omitempty" hcl:"project,optional"`
}
type Component ¶
type Component struct {
ComponentType string `json:"componentType" hcl:"component_type,label"`
ComponentName string `json:"componentName" hcl:"component_name,label"`
Description string `json:"description" hcl:"description,attr"`
Implemented bool `json:"implemented,omitempty" hcl:"implemented,optional"`
ImplementationNotes string `json:"implementationNotes,omitempty" hcl:"implementation_notes,optional"`
RiskReduction int `json:"riskReduction,omitempty" hcl:"risk_reduction,optional"`
Attributes []*ControlAttribute `json:"attribute,omitempty" hcl:"attribute,block"`
}
type Control ¶
type Control struct {
Name string `json:"name" hcl:"name,label" cty:"name"`
Implemented bool `json:"implemented,omitempty" hcl:"implemented,optional" cty:"implemented"`
Description string `json:"description" hcl:"description" cty:"description"`
ImplementationNotes string `json:"implementationNotes,omitempty" hcl:"implementation_notes,optional" cty:"implementation_notes"`
Ref string `json:"ref,omitempty" hcl:"ref,optional" cty:"ref"`
RiskReduction int `json:"riskReduction,omitempty" hcl:"risk_reduction,optional" cty:"risk_reduction"`
Attributes []*ControlAttribute `json:"attribute,omitempty" hcl:"attribute,block" cty:"attribute"`
}
type ControlAttribute ¶
type DataFlowDiagram ¶
type DataFlowDiagram struct {
Name string `json:"name" hcl:"name,label"`
ShiftedFromLegacy bool `json:"-"`
Processes []*DfdProcess `json:"process,omitempty" hcl:"process,block"`
ExternalElements []*DfdExternal `json:"externalElement,omitempty" hcl:"external_element,block"`
DataStores []*DfdData `json:"dataStore,omitempty" hcl:"data_store,block"`
Flows []*DfdFlow `json:"flow,omitempty" hcl:"flow,block"`
TrustZones []*DfdTrustZone `json:"trustZone,omitempty" hcl:"trust_zone,block"`
ImportFile string `json:"-" hcl:"import,optional"`
}
func (*DataFlowDiagram) GenerateD2 ¶
func (d *DataFlowDiagram) GenerateD2(tmName string, opts DfdRenderOptions) (string, error)
GenerateD2 returns the DFD rendered as D2 source (https://d2lang.com). The text can be rendered to SVG/PNG with the d2 CLI or the d2lib Go library; this emitter only produces source so the package keeps its small dependency footprint.
func (*DataFlowDiagram) GenerateDfdPng ¶
func (d *DataFlowDiagram) GenerateDfdPng(filepath, tmName string, opts DfdRenderOptions) error
GenerateDfdPng writes the DFD as a PNG to filepath.
func (*DataFlowDiagram) GenerateDfdPngBytes ¶
func (d *DataFlowDiagram) GenerateDfdPngBytes(tmName string, opts DfdRenderOptions) ([]byte, error)
GenerateDfdPngBytes returns the DFD as PNG bytes.
func (*DataFlowDiagram) GenerateDfdSvg ¶
func (d *DataFlowDiagram) GenerateDfdSvg(filepath, tmName string, opts DfdRenderOptions) error
GenerateDfdSvg writes the DFD as an SVG to filepath.
func (*DataFlowDiagram) GenerateDfdSvgBytes ¶
func (d *DataFlowDiagram) GenerateDfdSvgBytes(tmName string, opts DfdRenderOptions) ([]byte, error)
GenerateDfdSvgBytes returns the DFD as SVG bytes.
func (*DataFlowDiagram) GenerateDot ¶
func (d *DataFlowDiagram) GenerateDot(tmName string, opts DfdRenderOptions) (string, error)
GenerateDot returns the DFD rendered as Graphviz DOT source.
func (*DataFlowDiagram) GenerateMermaid ¶
func (d *DataFlowDiagram) GenerateMermaid(tmName string, opts DfdRenderOptions) (string, error)
GenerateMermaid returns the DFD rendered as a Mermaid flowchart. The output is plain text suitable for embedding in Markdown rendered by GitHub, GitLab, or any Mermaid-aware viewer.
type DfdExternal ¶
type DfdProcess ¶
type DfdRenderOptions ¶
type DfdRenderOptions struct {
ProtocolStyle ProtocolStyle
}
DfdRenderOptions configures how a DataFlowDiagram is rendered. The zero value (ProtocolStyleLabel) preserves the simplest behavior: protocol shown inline in labels, no color machinery.
type DfdTrustZone ¶
type DfdTrustZone struct {
Name string `json:"name" hcl:"name,label"`
Processes []*DfdProcess `json:"process,omitempty" hcl:"process,block"`
ExternalElements []*DfdExternal `json:"externalElement,omitempty" hcl:"external_element,block"`
DataStores []*DfdData `json:"dataStore,omitempty" hcl:"data_store,block"`
}
type Exclusion ¶
type Exclusion struct {
Description string `json:"description" hcl:"description,attr"`
}
type InformationAsset ¶
type InformationAsset struct {
Name string `json:"name" hcl:"name,label"`
Description string `json:"description,omitempty" hcl:"description,optional"`
InformationClassification string `json:"informationClassification,omitempty" hcl:"information_classification,optional"`
Source string `json:"source,omitempty" hcl:"source,optional"`
Ref string `json:"ref,omitempty" hcl:"ref,optional"`
}
type LegacyDataFlowDiagram ¶
type LegacyDataFlowDiagram struct {
Processes []*DfdProcess `json:"process,omitempty" hcl:"process,block"`
ExternalElements []*DfdExternal `json:"externalElement,omitempty" hcl:"external_element,block"`
DataStores []*DfdData `json:"dataStore,omitempty" hcl:"data_store,block"`
Flows []*DfdFlow `json:"flow,omitempty" hcl:"flow,block"`
TrustZones []*DfdTrustZone `json:"trustZone,omitempty" hcl:"trust_zone,block"`
ImportFile string `json:"import,omitempty" hcl:"import,optional"`
}
type MermaidDiagram ¶
type MermaidDiagram struct {
Name string `json:"name" hcl:"name,label"`
Description string `json:"description,omitempty" hcl:"description,optional"`
Content string `json:"content" hcl:"content"`
}
MermaidDiagram is a free-form mermaid diagram embedded in a threat model. The block label is the diagram's title and Content holds the raw mermaid source verbatim (a heredoc is the idiomatic input form). Mermaid infers the diagram type from the first line of Content, so there is deliberately no type/engine attribute.
type NamedInput ¶
NamedInput pairs raw HCL content with the name used to attribute diagnostics to it — typically the name of the file it came from.
type ProposedControl ¶
type ProtocolStyle ¶
type ProtocolStyle int
ProtocolStyle controls how the optional `protocol` attribute on a DfdFlow is surfaced in rendered diagrams.
const ( // ProtocolStyleLabel appends " (protocol)" to each flow's label. Default. ProtocolStyleLabel ProtocolStyle = iota // ProtocolStyleNone ignores the protocol attribute entirely. ProtocolStyleNone // ProtocolStyleColor colors each flow's edge by protocol and emits a legend. ProtocolStyleColor // ProtocolStyleBoth combines Label and Color: appended labels plus colored // edges and a legend. ProtocolStyleBoth )
type Risk ¶
type Risk struct {
Likelihood string `json:"likelihood" hcl:"likelihood,attr"`
Impact string `json:"impact" hcl:"impact,attr"`
// SeverityOverride is the optional author-supplied `severity` value. When
// empty, severity is computed from the likelihood×impact matrix. Use the
// Severity() method to get the resolved (override-or-computed) band.
SeverityOverride string `json:"severity,omitempty" hcl:"severity,optional"`
Rationale string `json:"rationale,omitempty" hcl:"rationale,optional"`
}
Risk is an optional, methodology-neutral risk rating attached to a threat. Likelihood and Impact are ordinal enums (very_low|low|medium|high|very_high) and are required when the risk block is present. Severity is normally COMPUTED from the likelihood×impact matrix (see Risk.Severity), but an author may override it. Rationale is free text that maps onto OTM's likelihoodComment/impactComment on export. The risk block as a whole is optional on a threat, so existing models stay valid.
func (*Risk) InherentScore ¶
InherentScore returns the threat's inherent (pre-control) risk score on a 0–100 scale.
type RiskModel ¶
type RiskModel struct {
// Ordinals maps each risk level to its 1–5 ordinal.
Ordinals map[string]int
// OtmValues maps each risk level to its OTM 0–100 value.
OtmValues map[string]int
// Matrix maps [likelihood][impact] to a severity band.
Matrix map[string]map[string]string
// Thresholds maps a numeric score to a severity band (residual view),
// ordered high→low.
Thresholds []severityThreshold
}
RiskModel bundles the tunable pieces of the risk scoring scheme: the ordinal and OTM (0–100) mappings for likelihood/impact, the likelihood×impact → severity matrix, and the score→band thresholds used for residual severity.
A single built-in defaultRiskModel ships with the spec so a solo CLI user gets ratings with zero config. It is deliberately the only place these numbers live, so a future per-repo (hcltmrc) or org-wide (Cloud) override can swap the model without touching the Risk/Threat methods below.
func DefaultRiskModel ¶
func DefaultRiskModel() *RiskModel
DefaultRiskModel returns the built-in risk scoring scheme.
type ThirdPartyDependency ¶
type ThirdPartyDependency struct {
Name string `json:"name" hcl:"name,label"`
Saas bool `json:"saas,omitempty" hcl:"saas,optional"`
PayingCustomer bool `json:"payingCustomer,omitempty" hcl:"paying_customer,optional"`
OpenSource bool `json:"openSource,omitempty" hcl:"open_source,optional"`
UptimeDependency UptimeDependencyClassification `json:"uptimeDependency" hcl:"uptime_dependency,attr"`
UptimeNotes string `json:"uptimeNotes,omitempty" hcl:"uptime_notes,optional"`
Infrastructure bool `json:"infrastructure,omitempty" hcl:"infrastructure,optional"`
Description string `json:"description" hcl:"description,attr"`
}
func (*ThirdPartyDependency) RenderUptime ¶
func (dep *ThirdPartyDependency) RenderUptime() string
type Threat ¶
type Threat struct {
Name string `json:"name" hcl:"name,label"`
ImpactType []string `json:"impacts,omitempty" hcl:"impacts,optional"`
Description string `json:"description" hcl:"description,attr"`
Control string `json:"control,omitempty" hcl:"control,optional"`
Stride []string `json:"stride,omitempty" hcl:"stride,optional"`
InformationAssetRefs []string `json:"informationAssetRefs,omitempty" hcl:"information_asset_refs,optional"`
ProposedControls []*ProposedControl `json:"proposedControl,omitempty" hcl:"proposed_control,block"`
Controls []*Control `json:"expandedControl,omitempty" hcl:"control,block"`
ExpandedControls []*Control `json:"-" hcl:"expanded_control,block"`
ControlImports []string `json:"-" hcl:"control_imports,optional"`
Ref string `json:"ref,omitempty" hcl:"ref,optional"`
Risk *Risk `json:"risk,omitempty" hcl:"risk,block"`
}
func (*Threat) ResidualRiskReduction ¶
ResidualRiskReduction returns the aggregate percentage by which implemented controls reduce the inherent risk, i.e. (1 − Π(1 − rᵢ/100)) × 100.
func (*Threat) ResidualScore ¶
ResidualScore returns the residual (post-control) risk score: the inherent score reduced by the aggregate risk_reduction of implemented controls. It returns 0 if the threat has no risk block.
func (*Threat) ResidualSeverity ¶
ResidualSeverity returns the severity band for the residual score. Note this is the coarse score-band view (see RiskModel.Thresholds) used for the "inherent → residual" narrative; the authoritative inherent band comes from Risk.Severity. Returns "" if the threat has no risk block.
type Threatmodel ¶
type Threatmodel struct {
Name string `json:"name" hcl:"name,label"`
// Id is an optional stable, identifier-safe handle for the threat model:
// dot-separated lowercase segments, unique within a parsed set. Unlike
// Name — an arbitrary display string — a declared id survives renames and
// can be used in dotted references by tooling. Dotted ids place the model
// in a namespace hierarchy (a model with id "buildings" may have children
// "buildings.tower", "buildings.bridge"). See Identifier().
Id string `json:"id,omitempty" hcl:"id,optional"`
// Extends names another threat model's declared id in the same parsed
// set. The extending model inherits the parent's collections (threats,
// information assets, use cases, exclusions, third-party dependencies —
// same-named items in the child win) and its attributes block when the
// child declares none. Purely declarative: a dotted id alone does NOT
// imply inheritance.
Extends string `json:"extends,omitempty" hcl:"extends,optional"`
Description string `json:"description,omitempty" hcl:"description,optional"`
Imports []string `json:"-" hcl:"imports,optional"`
Including string `json:"including,omitempty" hcl:"including,optional"`
Link string `json:"link,omitempty" hcl:"link,optional"`
DiagramLink string `json:"diagramLink,omitempty" hcl:"diagram_link,optional"`
Repository []string `json:"repository,omitempty" hcl:"repository,optional"`
AllDiagrams []string `json:"-"` // Used for templates
Author string `json:"author" hcl:"author,attr"`
CreatedAt int64 `json:"createdAt,omitempty" hcl:"created_at,optional"`
UpdatedAt int64 `json:"updatedAt,omitempty" hcl:"updated_at,optional"`
Attributes *Attribute `json:"attributes,omitempty" hcl:"attributes,block"`
AdditionalAttributes []*AdditionalAttribute `json:"additionalAttribute,omitempty" hcl:"additional_attribute,block"`
InformationAssets []*InformationAsset `json:"informationAsset,omitempty" hcl:"information_asset,block"`
Threats []*Threat `json:"threat,omitempty" hcl:"threat,block"`
UseCases []*UseCase `json:"useCase,omitempty" hcl:"usecase,block"`
Exclusions []*Exclusion `json:"exclusion,omitempty" hcl:"exclusion,block"`
ThirdPartyDependencies []*ThirdPartyDependency `json:"thirdPartyDependency,omitempty" hcl:"third_party_dependency,block"`
DataFlowDiagrams []*DataFlowDiagram `json:"dataFlowDiagram,omitempty" hcl:"data_flow_diagram_v2,block"`
MermaidDiagrams []*MermaidDiagram `json:"mermaidDiagram,omitempty" hcl:"mermaid,block"`
LegacyDfd *LegacyDataFlowDiagram `json:"legacyDataFlowDiagram,omitempty" hcl:"data_flow_diagram,block"`
}
func (*Threatmodel) Identifier ¶
func (tm *Threatmodel) Identifier() string
Identifier returns the threat model's addressable identity: the declared id when present, otherwise one derived from the name. Only declared ids are validated and rename-stable; derived ones shift with the name.
func (*Threatmodel) Include ¶
func (tm *Threatmodel) Include(cfg *ThreatmodelSpecConfig, myfilename string) error
func (*Threatmodel) RenderMarkdown ¶
func (tm *Threatmodel) RenderMarkdown(mdTemplate string) (io.Reader, error)
func (*Threatmodel) RenderOtm ¶
func (tm *Threatmodel) RenderOtm() (otm.OtmSchemaJson, error)
func (*Threatmodel) ValidateTm ¶
func (tm *Threatmodel) ValidateTm(p *ThreatmodelParser) error
type ThreatmodelParser ¶
type ThreatmodelParser struct {
// contains filtered or unexported fields
}
func NewThreatmodelParser ¶
func NewThreatmodelParser(cfg *ThreatmodelSpecConfig) *ThreatmodelParser
func (*ThreatmodelParser) AddTMAndWrite ¶
func (p *ThreatmodelParser) AddTMAndWrite(tm Threatmodel, f io.Writer, debug bool) error
func (*ThreatmodelParser) GetWrapped ¶
func (p *ThreatmodelParser) GetWrapped() *ThreatmodelWrapped
func (*ThreatmodelParser) HclString ¶
func (p *ThreatmodelParser) HclString() string
func (*ThreatmodelParser) ParseFile ¶
func (p *ThreatmodelParser) ParseFile(filename string, isChild bool) error
ParseFile parses a single Threatmodel file, and will account for either JSON or HCL (this is a wrapper sort of for the two different methods)
func (*ThreatmodelParser) ParseHCLFile ¶
func (p *ThreatmodelParser) ParseHCLFile(filename string, isChild bool) error
ParseHCLFile parses a single HCL Threatmodel file
func (*ThreatmodelParser) ParseHCLRaw ¶
func (p *ThreatmodelParser) ParseHCLRaw(input []byte) error
ParseHCLRaw parses a byte slice into HCL Threatmodels This is used for piping in STDIN
func (*ThreatmodelParser) ParseHCLRawSet ¶
func (p *ThreatmodelParser) ParseHCLRawSet(inputs []NamedInput) error
ParseHCLRawSet parses multiple named HCL inputs into one parsed set. Each input decodes with its own name so diagnostics point at the right input, and imports, variables and `including` are handled per input, the same way ParseHCLFile/ParseFile treat a top-level file — a relative `including` or import path resolves against the input's name, so names should be real file paths when inputs use either. Set-level validation — unique names and ids, reserved segments, extends resolution — runs once over the merged set, so a model may extend a parent declared in another input regardless of input order. Unlike single-input parsing, each input may carry its own backend block (at most one per input); all of them are exposed on the wrapped result, and any cross-input backend agreement is left to the consumer.
func (*ThreatmodelParser) ParseJSONFile ¶
func (p *ThreatmodelParser) ParseJSONFile(filename string, isChild bool) error
ParseJSONFile parses a single JSON Threatmodel file
func (*ThreatmodelParser) ParseJSONRaw ¶
func (p *ThreatmodelParser) ParseJSONRaw(input []byte) error
ParseJSONRaw parses a byte slice into HCL Threatmodels from JSON This is used for piping in STDIN
func (*ThreatmodelParser) SetSkipExtendsResolution ¶
func (p *ThreatmodelParser) SetSkipExtendsResolution(skip bool)
SetSkipExtendsResolution controls whether parsing resolves `extends` inheritance across the parsed content. When skipped, an extends target missing from the parsed content is not an error and no inherited entities are materialized — the Extends field stays populated for the consumer to resolve later, so a single file of a multi-file set can be parsed file-faithfully. All other validation and normalization is unchanged.
type ThreatmodelSpecConfig ¶
type ThreatmodelSpecConfig struct {
Version string
InitiativeSizes []string `hcl:"initiative_sizes,optional"`
DefaultInitiativeSize string `hcl:"default_initiative_size,optional"`
InfoClassifications []string `hcl:"info_classifications,optional"`
DefaultInfoClassification string `hcl:"default_info_classification,optional"`
ImpactTypes []string `hcl:"impact_types,optional"`
STRIDE []string `hcl:"strides,optional"`
UptimeDepClassifications []string `hcl:"uptime_dep_classifications,optional"`
DefaultUptimeDepClassification string `hcl:"default_uptime_dep_classification,optional"`
// AllowRemoteImports gates whether a threat model's `imports` /
// `including` may reference remote sources (http, https, git, s3, gcs,
// ...). It defaults to false: parsing an untrusted model must not be
// able to trigger arbitrary network fetches (SSRF) or pull in remote
// content. Operators who intentionally process trusted models that
// reference remote sources opt in with `allow_remote_imports = true`.
// Local file includes are always permitted (subject to path
// containment) regardless of this flag.
AllowRemoteImports bool `hcl:"allow_remote_imports,optional"`
}
func LoadSpecConfig ¶
func LoadSpecConfig() (*ThreatmodelSpecConfig, error)
func (*ThreatmodelSpecConfig) LoadSpecConfigFile ¶
func (t *ThreatmodelSpecConfig) LoadSpecConfigFile(file string) error
type ThreatmodelWrapped ¶
type ThreatmodelWrapped struct {
Threatmodels []Threatmodel `json:"threatmodels" hcl:"threatmodel,block"`
SpecVersion string `json:"specVersion,omitempty" hcl:"spec_version,optional"`
Components []*Component `json:"components,omitempty" hcl:"component,block"`
Variables []*Variable `json:"variables,omitempty" hcl:"variable,block"`
Backends []*Backend `json:"backend,omitempty" hcl:"backend,block"`
}
type UptimeDependencyClassification ¶
type UptimeDependencyClassification string
const ( NoneUptime UptimeDependencyClassification = "none" DegradedUptime UptimeDependencyClassification = "degraded" HardUptime UptimeDependencyClassification = "hard" OperationalUptime UptimeDependencyClassification = "operational" )
Source Files
¶
- config.go
- dashboard-templates.go
- dfd.go
- dfd_d2.go
- dfd_mermaid.go
- dfd_render.go
- dfd_render_options.go
- identifier.go
- parser.go
- parser_constraints.go
- parser_extends.go
- parser_hcl_encode.go
- parser_normalization.go
- parser_populate.go
- parser_refs.go
- parser_threatmodel.go
- render.go
- render_otm.go
- risk.go
- slug.go
- spec.go
- version.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package invariants implements org-wide, machine-checked rules ("invariants") that are evaluated against parsed threat models.
|
Package invariants implements org-wide, machine-checked rules ("invariants") that are evaluated against parsed threat models. |
|
Package lang provides language-server primitives for threatcl threat models: error-tolerant positional parsing, an explicit (drift-guarded) schema model with docs, range-carrying diagnostics, and completion/hover/symbol/format computation.
|
Package lang provides language-server primitives for threatcl threat models: error-tolerant positional parsing, an explicit (drift-guarded) schema model with docs, range-carrying diagnostics, and completion/hover/symbol/format computation. |