Documentation
¶
Overview ¶
Package store keeps assets, scans and their history in one SQLite file.
It uses the pure-Go modernc.org/sqlite driver, so the program stays a single static binary (CGO_ENABLED=0). Invariants that matter to the product are enforced by the schema, not only by callers: at most one active scan per asset (a partial unique index), history deleted with its asset (a cascading foreign key), and the next queued scan claimed by a single atomic statement.
Index ¶
- Constants
- Variables
- func IsEndpoint(kind string) bool
- func IsSystemField(name string) bool
- func ProtocolOf(kind string) string
- func ValidateSystemPatch(p SystemPatch) error
- type ActivityEntry
- type ActivityFilter
- type AnchorCert
- type Asset
- type AssetPatch
- type AttentionRow
- type AuditEntry
- type AuthEvent
- type CertificatePlace
- type CertificateRow
- type ConflictError
- type Entity
- type Event
- type FindingStatus
- type Fleet
- type GraphCounts
- type GraphStats
- type HistoryPoint
- type HostSnapshot
- type ImportInput
- type ImportRecord
- type Link
- type ObservationRow
- type ProtocolSummary
- type Result
- type RootSetChange
- type SSLv2Key
- type ScanFilter
- type ScanSummary
- type ScanWithAsset
- type Session
- type Store
- func (s *Store) Activity(f ActivityFilter) ([]ActivityEntry, error)
- func (s *Store) AddAuthEvent(e AuthEvent) error
- func (s *Store) AddEvent(scanID int64, message string) error
- func (s *Store) AddHostSnapshot(assetID int64, cbom, summary []byte) (int64, error)
- func (s *Store) AddHostSnapshotAs(assetID int64, cbom, summary []byte, class estate.SourceClass, ...) (int64, error)
- func (s *Store) AddImport(in ImportInput) (rec ImportRecord, duplicate bool, err error)
- func (s *Store) AddTrustAnchors(systemID int64, certs []AnchorCert, actor string) ([]TrustAnchor, error)
- func (s *Store) AllFindingStatuses() (map[int64]map[string]FindingStatus, error)
- func (s *Store) AllLinks() (map[int64][]int64, error)
- func (s *Store) Audit(kind string, id int64, limit int) ([]AuditEntry, error)
- func (s *Store) AuthEvents(limit int) ([]AuthEvent, error)
- func (s *Store) BackupTo(dst string) error
- func (s *Store) CancelScan(id int64) error
- func (s *Store) CertificatePlaces(fingerprint string) (places []CertificatePlace, found bool, err error)
- func (s *Store) Certificates() ([]CertificateRow, error)
- func (s *Store) ClaimNext() (ScanSummary, error)
- func (s *Store) ClearFindingStatus(assetID int64, key string) error
- func (s *Store) Close() error
- func (s *Store) ConfirmLink(id int64, actor, reason string) (Link, error)
- func (s *Store) Correlate() error
- func (s *Store) CountUsers() (int, error)
- func (s *Store) CreateAsset(a Asset) (Asset, error)
- func (s *Store) CreateFirstAdmin(username, displayName, passwordHash string) (User, error)
- func (s *Store) CreateSession(tokenHash string, userID int64, expires time.Time, client, userAgent string) (Session, error)
- func (s *Store) CreateUser(username, displayName, role, passwordHash string, mustChange bool, ...) (User, error)
- func (s *Store) DeleteAsset(id int64) error
- func (s *Store) DeleteSession(id, userID int64) error
- func (s *Store) DeleteUser(id int64) error
- func (s *Store) DueAssets(now time.Time) ([]Asset, error)
- func (s *Store) EndAllSessions() (int, error)
- func (s *Store) EnqueueScan(assetID int64, trigger, startedBy string) (v ScanSummary, existing bool, err error)
- func (s *Store) Entities(kind string, limit int) ([]Entity, error)
- func (s *Store) Evaluation(id int64) ([]byte, error)
- func (s *Store) Events(scanID int64) ([]Event, error)
- func (s *Store) FailInterrupted() (int, error)
- func (s *Store) FailScan(id int64, reason string, partialReport []byte) error
- func (s *Store) FindAsset(kind, host string, port int) (Asset, error)
- func (s *Store) FindingStatuses(assetID int64) (map[string]FindingStatus, error)
- func (s *Store) FinishScan(id int64, r Result) error
- func (s *Store) FleetSummary(trendDays int) (Fleet, error)
- func (s *Store) GetAsset(id int64) (Asset, error)
- func (s *Store) GetImport(id int64) (ImportRecord, error)
- func (s *Store) GetLink(id int64) (Link, error)
- func (s *Store) GetScan(id int64) (ScanSummary, error)
- func (s *Store) GetSystem(id int64) (System, error)
- func (s *Store) GetUser(id int64) (User, error)
- func (s *Store) History(assetID int64, limit int) ([]HistoryPoint, error)
- func (s *Store) HostCBOM(snapshotID int64) ([]byte, error)
- func (s *Store) HostSnapshots(assetID int64, limit int) ([]HostSnapshot, error)
- func (s *Store) ImportDocument(id int64) ([]byte, error)
- func (s *Store) Imports() ([]ImportRecord, error)
- func (s *Store) LatestDoneScans(systemID int64) (map[int64]int64, error)
- func (s *Store) LatestHostSnapshots() (map[int64]HostSnapshot, error)
- func (s *Store) LinkAssets(a, b int64) error
- func (s *Store) LinkAssetsAs(a, b int64, actor string) error
- func (s *Store) LinkedAssetIDs(assetID int64) ([]int64, error)
- func (s *Store) Links(state string) ([]Link, error)
- func (s *Store) ListAssets(kind string) ([]Asset, error)
- func (s *Store) ListScans(f ScanFilter) ([]ScanWithAsset, error)
- func (s *Store) ListSystems() ([]System, error)
- func (s *Store) ListUsers() ([]User, error)
- func (s *Store) Maintain() error
- func (s *Store) PriorityInputs() ([]eval.PriorityInput, error)
- func (s *Store) PruneSessions(idle time.Duration) error
- func (s *Store) RebuildGraph() (GraphCounts, error)
- func (s *Store) RecordAction(actor, client, kind string, id int64, action, detail, reason string) error
- func (s *Store) RecordLoginFailure(id int64, threshold int, lockFor time.Duration) (int, *time.Time, error)
- func (s *Store) RecordLoginSuccess(id int64) error
- func (s *Store) RejectLink(id int64, actor, reason string) (Link, error)
- func (s *Store) RemoveTrustAnchor(systemID int64, sha, actor string) error
- func (s *Store) ReplaceEvaluation(scanID int64, r Result, event string) error
- func (s *Store) Report(id int64) ([]byte, error)
- func (s *Store) RootSetChanges() ([]RootSetChange, error)
- func (s *Store) SSLv2LeafKeys() ([]SSLv2Key, error)
- func (s *Store) SessionByHash(tokenHash string) (Session, User, error)
- func (s *Store) SetClock(now func() time.Time)
- func (s *Store) SetFindingStatus(assetID int64, key, status, note string) error
- func (s *Store) SetLogger(l *slog.Logger)
- func (s *Store) SetPassword(id int64, hash string, mustChange bool, keepSession int64) error
- func (s *Store) SetSetting(key, value string) error
- func (s *Store) Setting(key string) (string, error)
- func (s *Store) Stats() (GraphStats, error)
- func (s *Store) SystemLinks(systemID int64) ([]Link, error)
- func (s *Store) SystemObservations(systemID int64, currentOnly bool) ([]ObservationRow, error)
- func (s *Store) TouchSession(id int64) error
- func (s *Store) TrustAnchorDER(systemID int64) ([][]byte, error)
- func (s *Store) TrustAnchors(systemID int64) ([]TrustAnchor, error)
- func (s *Store) UnlinkAssets(a, b int64) error
- func (s *Store) UnlinkAssetsAs(a, b int64, actor string) error
- func (s *Store) UnlockUser(id int64) error
- func (s *Store) UpdateAsset(id int64, p AssetPatch) (Asset, error)
- func (s *Store) UpdateProgress(id int64, stage string, pct, connections int) error
- func (s *Store) UpdateSystem(id int64, patch SystemPatch, actor, reason string) (System, error)
- func (s *Store) UpdateSystems(patches []SystemPatchByID, actor, reason string) error
- func (s *Store) UpdateUser(id int64, displayName, role string, disabled bool) (User, error)
- func (s *Store) UpsertHostAsset(name string) (a Asset, created bool, err error)
- func (s *Store) UserByName(username string) (User, error)
- func (s *Store) UserSessions(userID int64) ([]Session, error)
- func (s *Store) WithdrawImport(id int64, actor, reason string) error
- type System
- type SystemAsset
- type SystemPatch
- type SystemPatchByID
- type TrendPoint
- type TrustAnchor
- type User
Constants ¶
const ( ProtocolTLS = "tls" ProtocolSSH = "ssh" )
Protocol names of the fleet breakdown.
const ( LinkProposed = "proposed" LinkConfirmed = "confirmed" LinkRejected = "rejected" )
Link states.
const ( StatusQueued = "queued" StatusRunning = "running" StatusDone = "done" StatusFailed = "failed" StatusCanceled = "canceled" )
Scan statuses.
const ( KindTLS = "tls-endpoint" KindSSH = "ssh-endpoint" // PRD-008: an SSH server, scanned by internal/sshprobe KindHost = "host" // KindEndpoint is not stored: ListAssets reads it as every network endpoint (TLS and SSH). KindEndpoint = "endpoint" )
Asset kinds.
const ( FindingAcknowledged = "acknowledged" FindingAcceptedRisk = "accepted-risk" )
Finding triage statuses. "Resolved" is never one of these: it is not a decision to persist, it is what a finding_status row becomes, unprompted, the moment its finding stops appearing in an asset's latest result — the product will not let a user assert "fixed" while it still observes the problem.
const ( RoleAdmin = "admin" // everything, including accounts RoleAnalyst = "analyst" // scan, upload, triage, edit systems RoleViewer = "viewer" // read and download only )
Roles, from most to least able.
const MaxAnchorsPerSystem = 50
MaxAnchorsPerSystem bounds the per-system bundle.
const MaxTrendDays = 366
MaxTrendDays is the longest readiness trend FleetSummary returns: a year and a day.
const ProjectionVersion = 1
ProjectionVersion identifies the projection code. When it changes the graph is rebuilt from the stored documents on the next start (ENG-HANDOFF-002 D1), so a fix to a projection reaches old data without a data migration.
const ( // SettingSignIn is "on" when every request needs a signed-in account (ADR-0018), anything // else when the server runs without sign-in. Absent means off. SettingSignIn = "sign_in" )
Setting keys.
Variables ¶
var ( HostSnapshotsKept = 50 HostSnapshotBytesKept int64 = 256 << 20 HostSnapshotQuota int64 = 8 << 30 )
Retention and quota of uploaded host CBOMs. Each upload can be up to 32 MiB, so a count alone does not bound the disk: per host, the oldest uploads go once the host's total passes HostSnapshotBytesKept (the newest is always kept); across all hosts, an upload that would take the total past HostSnapshotQuota is refused rather than deleting another host's history.
var ( ErrNotFound = errors.New("not found") ErrDuplicate = errors.New("already exists") )
Errors callers can test for.
var ( Environments = []string{"production", "staging", "development", "other"} Criticalities = []string{"low", "moderate", "high"} // the FIPS 199 impact vocabulary Exposures = []string{"internet", "internal", "restricted"} FIPS199Levels = []string{"low", "moderate", "high"} HostingKinds = []string{"on-premises", "commercial-cloud", "government-cloud", "hybrid"} )
The allowed values of the enumerated fields. An empty value is always allowed.
var ErrAlreadyImported = errors.New("this document is already imported for another system")
ErrAlreadyImported means the same document is active on another system.
var ErrConflict = errors.New("conflict")
ErrConflict marks a merge that would overwrite different operator-set values.
var ErrInvalid = errors.New("invalid")
ErrInvalid marks input the store refuses. The wrapped message names the field.
var ErrLastAdmin = errors.New("this is the only enabled administrator; add another before removing this one")
ErrLastAdmin is returned by a change that would leave no enabled administrator.
var ErrQuota = errors.New("the server's storage quota for uploaded host inventories is full")
ErrQuota is returned when an upload would take stored host CBOMs past HostSnapshotQuota.
var ErrTooManyAnchors = fmt.Errorf("a system holds at most %d trust anchors", MaxAnchorsPerSystem)
ErrTooManyAnchors is returned when an upload would exceed MaxAnchorsPerSystem.
var ErrUsernameTaken = errors.New("an account with that username already exists")
ErrUsernameTaken is returned when an account with the name exists.
var ObservationCap = 50000
ObservationCap is the most observations one document contributes to the graph. It is a variable so tests can lower it.
var Retention = 200
Retention is how many finished scans are kept per asset.
var Roles = []string{RoleAdmin, RoleAnalyst, RoleViewer}
Roles lists the valid roles.
var SystemFields = []string{"name", "owner", "environment", "criticality", "exposure", "dataLifetimeYears",
"fismaId", "fips199", "hvaId", "hosting", "hostingProvider", "notes"}
SystemFields lists the editable fields, in display order. They are also the CSV columns.
Functions ¶
func IsEndpoint ¶
IsEndpoint reports whether an asset kind is a network endpoint (scanned, as opposed to a host).
func IsSystemField ¶
IsSystemField reports whether name is an editable system field.
func ValidateSystemPatch ¶
func ValidateSystemPatch(p SystemPatch) error
ValidateSystemPatch checks a patch without applying it, so a bulk import can report every problem before changing anything.
Types ¶
type ActivityEntry ¶
type ActivityEntry struct {
At time.Time `json:"at"`
Source string `json:"source"` // "change" or "sign-in"
Actor string `json:"actor"` // who did it ("" for a failed sign-in by nobody known)
Action string `json:"action"`
ObjectKind string `json:"objectKind,omitempty"`
ObjectID int64 `json:"objectId,omitempty"`
Username string `json:"username,omitempty"` // the account a sign-in event is about
Client string `json:"client,omitempty"`
Detail string `json:"detail,omitempty"`
Reason string `json:"reason,omitempty"`
}
ActivityEntry is one line of the Activity list: a change (from the audit log) or a sign-in event (from the sign-in log), in one shape.
type ActivityFilter ¶
type ActivityFilter struct {
Person string // the actor, or the account a sign-in event is about
Source string // "change" or "sign-in"
Limit int // at most 5000; default 500
}
ActivityFilter narrows the Activity list. Empty fields match everything.
type AnchorCert ¶
AnchorCert is a certificate being added.
type Asset ¶
type Asset struct {
ID int64 `json:"id"`
SystemID int64 `json:"systemId"`
Kind string `json:"kind"`
Name string `json:"name"`
Host string `json:"host"`
Port int `json:"port"`
StartTLS string `json:"starttls"` // "auto" (by well-known port), "none" or a protocol
Tags []string `json:"tags"`
Notes string `json:"notes"`
IntervalSeconds int `json:"intervalSeconds"`
NextScanAt *time.Time `json:"nextScanAt"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
// Latest is the most recent scan of any status (what is happening now);
// LastDone is the most recent completed scan (what is currently known).
Latest *ScanSummary `json:"latest"`
LastDone *ScanSummary `json:"lastDone"`
}
Asset is something to scan.
type AssetPatch ¶
type AssetPatch struct {
Name *string
Tags *[]string
Notes *string
IntervalSeconds *int
StartTLS *string
}
AssetPatch changes editable fields; nil means "leave as is".
type AttentionRow ¶
type AttentionRow struct {
AssetID int64 `json:"assetId"`
Name string `json:"name"`
Address string `json:"address"`
Protocol string `json:"protocol"`
Band string `json:"band"` // TLS only; empty for SSH, which has no score
Score int `json:"score"`
ReadinessLevel *int `json:"readinessLevel"`
HNDLExposed bool `json:"hndlExposed"`
Critical int `json:"critical"`
High int `json:"high"`
Why string `json:"why"`
}
AttentionRow is an asset that needs looking at, worst first.
type AuditEntry ¶
type AuditEntry struct {
ID int64 `json:"id"`
At time.Time `json:"at"`
Actor string `json:"actor"`
ObjectKind string `json:"objectKind"`
ObjectID int64 `json:"objectId"`
Action string `json:"action"`
Before json.RawMessage `json:"before"`
After json.RawMessage `json:"after"`
Reason string `json:"reason,omitempty"`
}
AuditEntry is one recorded change.
type AuthEvent ¶
type AuthEvent struct {
At time.Time `json:"at"`
Kind string `json:"kind"`
Username string `json:"username"`
Actor string `json:"actor"`
Client string `json:"client"`
Detail string `json:"detail"`
}
AuthEvent is one line of the sign-in audit trail.
type CertificatePlace ¶
type CertificatePlace struct {
SystemID int64 `json:"systemId"`
SystemName string `json:"systemName"`
AssetID int64 `json:"assetId,omitempty"`
AssetKind string `json:"assetKind,omitempty"`
SourceClass string `json:"sourceClass"`
Stream string `json:"stream"`
Relation string `json:"relation"`
Rung string `json:"rung"`
Method string `json:"method"`
Quality string `json:"methodQuality"`
Position string `json:"position,omitempty"` // leaf or chain, for a presented certificate
Location string `json:"location,omitempty"` // where a host holds it
PrivateKey string `json:"privateKey,omitempty"` // yes, no or unknown
ObservedAt time.Time `json:"observedAt"`
Current bool `json:"current"`
}
CertificatePlace is one sighting of a certificate.
type CertificateRow ¶
type CertificateRow struct {
Fingerprint string `json:"fingerprint"`
Name string `json:"name"`
Attrs map[string]string `json:"attrs"`
FirstSeen time.Time `json:"firstSeen"`
LastSeen time.Time `json:"lastSeen"`
// Current is true while a current source still observes it.
Current bool `json:"current"`
// Places is how many current observations there are; Systems how many systems they span.
Places int `json:"places"`
Systems int `json:"systems"`
// Origins lists the source classes (scanner, collector, imported) that currently observe it.
Origins []string `json:"origins"`
}
CertificateRow is one certificate in the estate graph: its public attributes and where and when it was seen. Nothing here is key material; the graph has no field that could hold it.
func (CertificateRow) Facts ¶
func (c CertificateRow) Facts() eval.CertificateFacts
Facts describes the certificate for the certificate rules.
func (CertificateRow) Role ¶
func (c CertificateRow) Role() string
Role is what the certificate is in a chain: a root (a CA that signed itself), an intermediate (any other CA) or an end-entity certificate.
type ConflictError ¶
type ConflictError struct{ Fields []string }
ConflictError lists the fields on which two systems disagree.
func (*ConflictError) Error ¶
func (e *ConflictError) Error() string
func (*ConflictError) Is ¶
func (e *ConflictError) Is(target error) bool
Is makes errors.Is(err, ErrConflict) true.
type Entity ¶
type Entity struct {
ID int64 `json:"id"`
Kind string `json:"kind"`
Key string `json:"key"`
Name string `json:"name"`
Attrs map[string]string `json:"attrs"`
FirstSeen time.Time `json:"firstSeen"`
LastSeen time.Time `json:"lastSeen"`
// Current is true when a current source (the latest picture of an asset, or an
// active import) still observes it. False means "no longer observed", not deleted.
Current bool `json:"current"`
Seen int `json:"observations"`
}
Entity is a thing in the graph with when it was first and last observed.
type FindingStatus ¶
type FindingStatus struct {
AssetID int64 `json:"assetId"`
FindingKey string `json:"findingKey"`
Status string `json:"status"`
Note string `json:"note,omitempty"`
SetAt time.Time `json:"setAt"`
}
FindingStatus is a persisted triage decision on one finding of one asset. finding_key is a rule ID (e.g. "CIPHER.RC4") for a TLS finding, or "pqc:<algorithm name>" for a host algorithm verdict — the two finding systems have no shared identity otherwise (see internal/eval vs internal/pqc).
type Fleet ¶
type Fleet struct {
Assets int `json:"assets"`
Scanned int `json:"scanned"`
HNDLExposed int `json:"hndlExposed"`
Critical int `json:"critical"` // critical findings across the fleet
High int `json:"high"`
// CertsExpiring counts assets whose certificate expires within 30 days (or already has).
CertsExpiring int `json:"certsExpiring"`
// Readiness counts assets per level; -1 is undetermined. Bands counts per TLS hygiene band.
Readiness map[int]int `json:"readiness"`
Bands map[string]int `json:"bands"`
NeedsAttention []AttentionRow `json:"needsAttention"`
Recent []ScanWithAsset `json:"recent"`
Trend []TrendPoint `json:"trend"`
// Protocols breaks the fleet down by protocol ("tls", "ssh") for the Overview's protocol
// cards (PRD-008 REQ-SHW-4). Each protocol keeps its own measure: hygiene bands for TLS,
// the baseline verdict for SSH. Nothing adds the two together.
Protocols map[string]*ProtocolSummary `json:"protocols"`
}
Fleet is everything the dashboard shows, computed from each asset's latest completed scan.
type GraphCounts ¶
type GraphCounts struct {
Sources int `json:"sources"`
Entities int `json:"entities"`
Observations int `json:"observations"`
}
GraphCounts says what a rebuild produced.
type GraphStats ¶
type GraphStats struct {
Entities map[string]int `json:"entities"`
Observations map[string]int `json:"observationsBySourceClass"`
Sources int `json:"sources"`
BuiltAt string `json:"builtAt"`
Version int `json:"projectionVersion"`
Stale bool `json:"stale"`
}
GraphStats counts the graph by kind and by source class, for the API and for QA.
type HistoryPoint ¶
type HistoryPoint struct {
ScanID int64 `json:"scanId"`
At time.Time `json:"at"`
Status string `json:"status"`
Band string `json:"band"`
Score int `json:"score"`
ReadinessLevel *int `json:"readinessLevel"`
HNDLExposed bool `json:"hndlExposed"`
Critical int `json:"critical"`
High int `json:"high"`
Medium int `json:"medium"`
Error string `json:"error"`
Incomplete bool `json:"incomplete"`
Trigger string `json:"trigger"`
StartedBy string `json:"startedBy"`
// The SSH baseline verdict (ScanSummary has the meanings); nil for TLS and when not judged.
BaselineMeets *bool `json:"baselineMeets,omitempty"`
BaselineChanges int `json:"baselineChanges,omitempty"`
}
HistoryPoint is one completed scan on an asset's timeline.
type HostSnapshot ¶
type HostSnapshot struct {
ID int64 `json:"id"`
AssetID int64 `json:"assetId"`
At time.Time `json:"at"`
Summary []byte `json:"-"`
}
HostSnapshot is one uploaded CBOM of a host, with its analysis summary.
type ImportInput ¶
type ImportInput struct {
Raw []byte
SHA256 string
SpecVersion string
Profile string
Kind estate.ImportKind
ToolName string
ToolVersion string
SubjectClaim string
SubmittedBy string
SystemID int64 // an existing system, or
NewSystemName string // the name of one to create
}
ImportInput is a third-party document that passed the importer, with the operator's decision about which system it describes. The subject is the operator's: SubjectClaim is what the document says about itself and is only recorded (SECARCH-001 SR-04).
type ImportRecord ¶
type ImportRecord struct {
ID int64 `json:"id"`
SHA256 string `json:"sha256"`
SpecVersion string `json:"specVersion"`
Profile string `json:"profile"`
Kind string `json:"kind"`
ToolName string `json:"toolName"`
ToolVersion string `json:"toolVersion"`
SubjectClaim string `json:"subjectClaim"`
SubmittedBy string `json:"submittedBy"`
Size int `json:"size"`
ReceivedAt time.Time `json:"receivedAt"`
SystemID int64 `json:"systemId"`
SystemName string `json:"systemName"`
Status string `json:"status"`
Observations int `json:"observations"`
NotInterpreted map[string]int `json:"notInterpreted"`
}
ImportRecord is an import as listed: its provenance and what became of it.
type Link ¶
type Link struct {
ID int64 `json:"id"`
AssetID int64 `json:"assetId"`
AssetName string `json:"assetName"`
AssetKind string `json:"assetKind"`
AssetAddr string `json:"assetAddress"`
SystemID int64 `json:"systemId"`
SystemName string `json:"systemName"`
State string `json:"state"`
Strength string `json:"strength"`
Rules []estate.RuleHit `json:"rules"`
Ambiguous bool `json:"ambiguous"`
Note string `json:"note,omitempty"`
Stale bool `json:"stale"`
DecidedBy string `json:"decidedBy,omitempty"`
DecidedAt *time.Time `json:"decidedAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Reason string `json:"reason,omitempty"`
Competes int `json:"competingProposals"`
}
Link is a reviewable statement that an asset (typically a TLS endpoint) belongs to a system (typically the machine's): the rules that produced it with the values that matched, a strength from a fixed table, a state, and who decided. It is never a silent merge (PRD-003 REQ-COR-2).
type ObservationRow ¶
type ObservationRow struct {
ID int64 `json:"id"`
SourceID int64 `json:"sourceId"`
SourceKind string `json:"sourceKind"`
Class string `json:"sourceClass"`
Stream string `json:"stream"`
AssetID int64 `json:"assetId,omitempty"`
SystemID int64 `json:"systemId"`
Entity Entity `json:"entity"`
Relation string `json:"relation"`
Via string `json:"via,omitempty"`
Rung string `json:"rung"`
EvClass int `json:"evidenceClass"`
Method string `json:"method"`
Quality string `json:"methodQuality"`
ObservedAt time.Time `json:"observedAt"`
Attrs map[string]string `json:"attrs,omitempty"`
Current bool `json:"current"`
}
ObservationRow is one observation with where it came from.
type ProtocolSummary ¶
type ProtocolSummary struct {
Assets int `json:"assets"`
Scanned int `json:"scanned"`
HNDLExposed int `json:"hndlExposed"`
Critical int `json:"critical"`
High int `json:"high"`
Readiness map[int]int `json:"readiness"`
// TLS only.
Bands map[string]int `json:"bands,omitempty"`
CertsExpiring int `json:"certsExpiring"`
// SSH only: servers judged against their baseline, and those that speak only SSH-1 (L0).
BaselineMeets int `json:"baselineMeets"`
BaselineFails int `json:"baselineFails"`
SSH1 int `json:"ssh1"`
}
ProtocolSummary is one protocol's share of the fleet.
type Result ¶
type Result struct {
Report []byte
Evaluation []byte
Band string
Score int
ReadinessLevel int
HNDLExposed bool
Critical int
High int
Medium int
Low int
Info int
CertNotAfter *time.Time
Incomplete bool
Service string
HostKey string
// The SSH baseline verdict (ScanSummary has the meanings).
Baseline string
BaselineMeets *bool
BaselineChanges int
// FinalEvent, if set, is logged with the result in one transaction.
FinalEvent string
}
Result is what a finished scan stores.
type RootSetChange ¶
type RootSetChange struct {
AssetID int64 `json:"assetId"`
AssetName string `json:"assetName"`
SystemID int64 `json:"systemId"`
Previous time.Time `json:"previous"`
Latest time.Time `json:"latest"`
Added []string `json:"added"` // fingerprints
Removed []string `json:"removed"` // fingerprints
AddedName []string `json:"addedNames"`
RemovedNames []string `json:"removedNames"`
}
RootSetChange says which trust anchors a host gained or lost between its two most recent uploads. A change to the set of roots a machine trusts is worth a person's attention even though no individual root is a finding (PRD-003 REQ-CERT-5).
type SSLv2Key ¶
type SSLv2Key struct {
AssetID int64
Address string
SPKI string // SHA-256 of the SubjectPublicKeyInfo, lower-case hex
}
SSLv2Key is a leaf public key served by an endpoint whose latest completed scan accepted SSLv2.
type ScanFilter ¶
type ScanFilter struct {
AssetID int64
Status string
// Kind limits the list to one asset kind (KindTLS, KindSSH); empty means any.
Kind string
Limit int
}
ScanFilter narrows ListScans.
type ScanSummary ¶
type ScanSummary struct {
ID int64 `json:"id"`
AssetID int64 `json:"assetId"`
Status string `json:"status"`
Trigger string `json:"trigger"`
StartedBy string `json:"startedBy"` // a user name, "api-token", "schedule", or "" (before 1.0)
Stage string `json:"stage"`
ProgressPct int `json:"progressPct"`
Connections int `json:"connections"`
QueuedAt time.Time `json:"queuedAt"`
StartedAt *time.Time `json:"startedAt"`
FinishedAt *time.Time `json:"finishedAt"`
Error string `json:"error"`
Band string `json:"band"` // TLS hygiene band, e.g. Strong; empty until a scan completes
Score int `json:"score"` // TLS hygiene score 0-100; -1 when not rated
ReadinessLevel *int `json:"readinessLevel"`
HNDLExposed bool `json:"hndlExposed"`
Critical int `json:"critical"`
High int `json:"high"`
Medium int `json:"medium"`
Low int `json:"low"`
Info int `json:"info"`
CertNotAfter *time.Time `json:"certNotAfter"`
Incomplete bool `json:"incomplete"`
// Service and HostKey describe an SSH endpoint for lists ("OpenSSH_10.0", "Ed25519"); empty for TLS.
Service string `json:"service"`
HostKey string `json:"hostKey"`
// Baseline, BaselineMeets and BaselineChanges are an SSH server's baseline verdict (PRD-008
// WP-G); BaselineMeets is nil when the server was not judged, and for TLS.
Baseline string `json:"baseline,omitempty"`
BaselineMeets *bool `json:"baselineMeets,omitempty"`
BaselineChanges int `json:"baselineChanges,omitempty"`
}
ScanSummary is a scan without its (large) report and evaluation.
type ScanWithAsset ¶
type ScanWithAsset struct {
ScanSummary
AssetName string `json:"assetName"`
AssetAddress string `json:"assetAddress"`
AssetKind string `json:"assetKind"`
}
ScanWithAsset is a scan row plus the asset it belongs to, for lists.
type Session ¶
type Session struct {
ID int64 `json:"id"`
UserID int64 `json:"-"`
CreatedAt time.Time `json:"createdAt"`
LastSeenAt time.Time `json:"lastSeenAt"`
ExpiresAt time.Time `json:"expiresAt"`
Client string `json:"client"`
UserAgent string `json:"userAgent"`
}
Session is a signed-in browser. The token itself is never stored.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the database handle. It is safe for concurrent use.
func Open ¶
Open opens (creating if needed) the database at path and applies migrations.
The file holds an organisation's scan results and host inventories, so it is created owner-only (0600) and an existing one is tightened. SQLite gives its -wal and -shm files the same mode as the database. On Windows the mode bits are not enforced and the profile's ACL applies instead. Every transaction is opened IMMEDIATE: a write transaction takes the write lock when it begins, so two of them queue behind the busy timeout instead of one failing at its first write with "database is locked" (a deferred transaction that read first cannot be upgraded under WAL).
func (*Store) Activity ¶
func (s *Store) Activity(f ActivityFilter) ([]ActivityEntry, error)
Activity lists changes and sign-in events together, newest first.
func (*Store) AddAuthEvent ¶
AddAuthEvent appends to the audit trail. Never pass a password or a token.
func (*Store) AddHostSnapshot ¶
AddHostSnapshot stores an uploaded CBOM and its analysis as an imported document: the safe default, since nothing here proves who made it.
func (*Store) AddHostSnapshotAs ¶
func (s *Store) AddHostSnapshotAs(assetID int64, cbom, summary []byte, class estate.SourceClass, submittedBy string) (int64, error)
AddHostSnapshotAs stores an uploaded CBOM attributed to a source class, and projects it into the graph. The caller decides the class from the channel, not from anything the document claims about itself (SECARCH-001 T-03).
func (*Store) AddImport ¶
func (s *Store) AddImport(in ImportInput) (rec ImportRecord, duplicate bool, err error)
AddImport stores a document and projects it. Importing the same bytes again for the same system changes nothing and returns the existing record (duplicate); for another system it is refused. A withdrawn import is reactivated. Every import is audited.
func (*Store) AddTrustAnchors ¶
func (s *Store) AddTrustAnchors(systemID int64, certs []AnchorCert, actor string) ([]TrustAnchor, error)
AddTrustAnchors stores the certificates on a system, skipping ones already there, and audits each addition. It returns the anchors added.
func (*Store) AllFindingStatuses ¶
func (s *Store) AllFindingStatuses() (map[int64]map[string]FindingStatus, error)
AllFindingStatuses returns every triage decision across every asset, keyed by asset ID then finding_key, for the fleet-wide findings view.
func (*Store) AllLinks ¶
AllLinks returns every asset's linked-asset IDs in one query, symmetric (each link appears under both asset IDs), for batch list rendering.
func (*Store) AuthEvents ¶
AuthEvents returns the newest events first.
func (*Store) BackupTo ¶
BackupTo writes a consistent copy of the database to dst, owner-only, while it stays in use (VACUUM INTO reads one snapshot). dst must not exist: a backup never overwrites anything.
func (*Store) CancelScan ¶
CancelScan marks a queued or running scan canceled.
func (*Store) CertificatePlaces ¶
func (s *Store) CertificatePlaces(fingerprint string) (places []CertificatePlace, found bool, err error)
CertificatePlaces lists every sighting of one certificate, newest first. found is false when no such certificate is in the graph.
func (*Store) Certificates ¶
func (s *Store) Certificates() ([]CertificateRow, error)
Certificates lists every certificate entity.
func (*Store) ClaimNext ¶
func (s *Store) ClaimNext() (ScanSummary, error)
ClaimNext atomically takes the oldest queued scan and marks it running. It returns ErrNotFound when the queue is empty.
func (*Store) ClearFindingStatus ¶
ClearFindingStatus removes a triage decision, returning the finding to "new".
func (*Store) ConfirmLink ¶
ConfirmLink accepts a proposed link: the asset's system is merged into the target. If the two systems hold different operator-set values the confirmation is refused with a ConflictError naming them and nothing changes (REQ-COR-7, DN-1).
func (*Store) CountUsers ¶
CountUsers returns how many accounts exist (zero means the server still needs its first administrator).
func (*Store) CreateAsset ¶
CreateAsset inserts an asset, and the system it belongs to. It returns ErrDuplicate if the same kind, host and port already exist.
func (*Store) CreateFirstAdmin ¶
CreateFirstAdmin adds the first administrator, but only while there are no accounts: two people racing through first-run setup cannot both become administrators.
func (*Store) CreateSession ¶
func (s *Store) CreateSession(tokenHash string, userID int64, expires time.Time, client, userAgent string) (Session, error)
CreateSession stores a new session under the hash of its token.
func (*Store) CreateUser ¶
func (s *Store) CreateUser(username, displayName, role, passwordHash string, mustChange bool, createdBy string) (User, error)
CreateUser adds an account.
func (*Store) DeleteAsset ¶
DeleteAsset removes an asset and, by cascade, its scans, events and observations. The system it belonged to goes too, unless something else still needs it: another asset, an imported source, or anything a person recorded about it.
func (*Store) DeleteSession ¶
DeleteSession ends one session; userID, when not 0, must own it.
func (*Store) DeleteUser ¶
DeleteUser removes an account and its sessions; the last enabled administrator stays.
func (*Store) DueAssets ¶
DueAssets returns assets whose scheduled scan is due and that have no active scan.
func (*Store) EndAllSessions ¶
EndAllSessions signs every browser out (sign-in being turned off: UX-REVIEW-008 D2) and says how many sessions there were.
func (*Store) EnqueueScan ¶
func (s *Store) EnqueueScan(assetID int64, trigger, startedBy string) (v ScanSummary, existing bool, err error)
EnqueueScan queues a scan of an asset, recording who asked for it. If the asset already has an active (queued or running) scan, that one is returned with existing=true and nothing is added: the schema allows only one (AC-02.6).
func (*Store) Entities ¶
Entities lists entities of a kind (all kinds when empty), most recently seen first.
func (*Store) Evaluation ¶
Evaluation returns a scan's stored evaluation JSON.
func (*Store) FailInterrupted ¶
FailInterrupted marks scans left running by a previous process as failed, so none stays "running" forever after a restart (AC-12.2). Queued scans were not interrupted: they keep their place and run once the workers start.
func (*Store) FailScan ¶
FailScan marks a running scan failed with a reason, optionally keeping a partial report.
func (*Store) FindingStatuses ¶
func (s *Store) FindingStatuses(assetID int64) (map[string]FindingStatus, error)
FindingStatuses returns one asset's triage decisions, keyed by finding_key.
func (*Store) FinishScan ¶
FinishScan stores a completed scan's result. If the result carries a final event, it is recorded in the same transaction, so a reader can never see a finished scan whose summary line is still to come.
func (*Store) FleetSummary ¶
FleetSummary computes the dashboard data. trendDays is how many days of trend to return.
func (*Store) GetImport ¶
func (s *Store) GetImport(id int64) (ImportRecord, error)
GetImport returns one import.
func (*Store) GetScan ¶
func (s *Store) GetScan(id int64) (ScanSummary, error)
GetScan returns a scan without its report.
func (*Store) History ¶
func (s *Store) History(assetID int64, limit int) ([]HistoryPoint, error)
History returns an asset's finished scans, oldest first (for charts).
func (*Store) HostSnapshots ¶
func (s *Store) HostSnapshots(assetID int64, limit int) ([]HostSnapshot, error)
HostSnapshots lists a host's uploads, newest first.
func (*Store) ImportDocument ¶
ImportDocument returns an active import's stored CBOM.
func (*Store) Imports ¶
func (s *Store) Imports() ([]ImportRecord, error)
Imports lists every import, newest first.
func (*Store) LatestDoneScans ¶
LatestDoneScans returns, for every asset, the ID of its most recent completed scan. systemID > 0 limits it to that system's assets.
func (*Store) LatestHostSnapshots ¶
func (s *Store) LatestHostSnapshots() (map[int64]HostSnapshot, error)
LatestHostSnapshots returns, for every machine, its most recent snapshot (without the summary).
func (*Store) LinkAssets ¶
LinkAssets records that two assets (typically a TLS endpoint and a host) are known, by a person, to be the same machine. Never inferred by the product itself. Order does not matter; the link is symmetric.
The two assets also become one system (their systems are merged, keeping the host's), so the metadata a person records is about the machine, not one of its faces. If the two systems hold different operator-set values the link is refused with a ConflictError naming the fields, and nothing changes.
func (*Store) LinkAssetsAs ¶
LinkAssetsAs is LinkAssets recording who made the link.
func (*Store) LinkedAssetIDs ¶
LinkedAssetIDs returns the IDs of every asset linked to assetID.
func (*Store) ListAssets ¶
ListAssets returns every asset, newest first, with their latest scans.
func (*Store) ListScans ¶
func (s *Store) ListScans(f ScanFilter) ([]ScanWithAsset, error)
ListScans returns scans, newest first.
func (*Store) ListSystems ¶
ListSystems returns every system with its assets, ordered by name.
func (*Store) Maintain ¶
Maintain repairs derived data in the background: it rebuilds the graph if a projection or a correlation failed since the last build, and sweeps orphans left by deleted assets. The server calls it periodically, so a failure is repaired without waiting for a restart.
func (*Store) PriorityInputs ¶
func (s *Store) PriorityInputs() ([]eval.PriorityInput, error)
PriorityInputs gathers, for every system, what ranking reads: the metadata a person entered, the latest completed scan of each of its endpoints, its current end-entity certificates, and how it is known. It is a handful of queries, not one per system.
func (*Store) PruneSessions ¶
PruneSessions deletes sessions past their absolute expiry or idle longer than idle.
func (*Store) RebuildGraph ¶
func (s *Store) RebuildGraph() (GraphCounts, error)
RebuildGraph drops the projection and rebuilds it from the stored documents, in one transaction: it is complete or it does not happen. Imported documents are the one thing kept as sources rather than re-derived from another table, so they are re-projected by their own rebuild step when that exists.
func (*Store) RecordAction ¶
func (s *Store) RecordAction(actor, client, kind string, id int64, action, detail, reason string) error
RecordAction appends one change made through the API to the audit log (PRD-007 REQ-AC-2): who, what kind of object, which one, what was done, and a short detail. The detail names objects (ids, finding keys, an endpoint's address), never a secret or a request body.
client is the address the request came from; it matters most while sign-in is off, when the actor is the anonymous "local" operator (UX-REVIEW-008 D4).
func (*Store) RecordLoginFailure ¶
func (s *Store) RecordLoginFailure(id int64, threshold int, lockFor time.Duration) (int, *time.Time, error)
RecordLoginFailure counts a failed password for an account and locks it for lockFor once the count reaches threshold. It returns the new count and the lock, if one was set.
func (*Store) RecordLoginSuccess ¶
RecordLoginSuccess clears the failure count and stamps the sign-in time.
func (*Store) RejectLink ¶
RejectLink refuses a link. A rejected link is never proposed again (REQ-COR-5). Rejecting a link that had been confirmed also takes the asset back out into a system of its own.
func (*Store) RemoveTrustAnchor ¶
RemoveTrustAnchor deletes one anchor from a system and audits it.
func (*Store) ReplaceEvaluation ¶
ReplaceEvaluation stores a re-evaluation of a completed scan's report (REQ-TNFR-4). The report itself is never rewritten. The event records the old and new versions.
func (*Store) RootSetChanges ¶
func (s *Store) RootSetChanges() ([]RootSetChange, error)
RootSetChanges compares, for each host with at least two uploads that recorded certificates, the roots of the latest against the one before.
func (*Store) SSLv2LeafKeys ¶
SSLv2LeafKeys lists the leaf keys of every endpoint whose latest completed scan accepted SSLv2 (the inputs of the DROWN shared-key check). It reads the graph, where those facts are already indexed, instead of decoding every stored report on every evaluation.
func (*Store) SessionByHash ¶
SessionByHash returns a session and its account.
func (*Store) SetFindingStatus ¶
SetFindingStatus records or replaces a triage decision.
func (*Store) SetLogger ¶
SetLogger sets where the store reports what it does on its own (derived data it could not rebuild, maintenance that failed). Default: discarded.
func (*Store) SetPassword ¶
SetPassword replaces an account's password hash, clears any lockout and ends every session of the account except keepSession (the one making the change, or 0 for none).
func (*Store) SetSetting ¶
SetSetting stores a server setting.
func (*Store) SystemLinks ¶
SystemLinks lists the links that touch one system, either as target or through an asset it holds.
func (*Store) SystemObservations ¶
func (s *Store) SystemObservations(systemID int64, currentOnly bool) ([]ObservationRow, error)
SystemObservations returns the observations of a system: those made through its assets and those from sources assigned to it. Current-only limits it to the latest picture of each source.
func (*Store) TouchSession ¶
TouchSession records activity on a session.
func (*Store) TrustAnchorDER ¶
TrustAnchorDER returns the certificates of a system's anchors.
func (*Store) TrustAnchors ¶
func (s *Store) TrustAnchors(systemID int64) ([]TrustAnchor, error)
TrustAnchors lists a system's anchors, oldest first.
func (*Store) UnlinkAssets ¶
UnlinkAssets removes a link in either direction. If that leaves the two assets unconnected by any other link, the second asset (and whatever is still linked to it) moves to a system of its own; the metadata stays with the original system.
func (*Store) UnlinkAssetsAs ¶
UnlinkAssetsAs is UnlinkAssets recording who removed the link.
func (*Store) UnlockUser ¶
UnlockUser clears a lockout (an administrator's action).
func (*Store) UpdateAsset ¶
func (s *Store) UpdateAsset(id int64, p AssetPatch) (Asset, error)
UpdateAsset applies a patch. Setting an interval schedules the next scan.
func (*Store) UpdateProgress ¶
UpdateProgress records the running scan's stage, percentage and connection count.
func (*Store) UpdateSystem ¶
UpdateSystem applies a validated patch and records who changed what, in the same transaction (SR-11). A patch that changes nothing writes nothing.
func (*Store) UpdateSystems ¶
func (s *Store) UpdateSystems(patches []SystemPatchByID, actor, reason string) error
UpdateSystems applies several patches atomically: all of them, or none.
func (*Store) UpdateUser ¶
UpdateUser changes an account's display name, role and enabled state. Demoting or disabling the last enabled administrator is refused. Disabling ends the account's sessions.
func (*Store) UpsertHostAsset ¶
UpsertHostAsset returns the host asset called name, creating it if needed.
func (*Store) UserByName ¶
UserByName returns an account by username (case-insensitive).
func (*Store) UserSessions ¶
UserSessions lists an account's sessions, newest first.
func (*Store) WithdrawImport ¶
WithdrawImport removes an import's observations from the graph. The raw document and the record of the import are kept for audit (they are how a withdrawn import is explained), and the withdrawal is audited.
type System ¶
type System struct {
ID int64 `json:"id"`
Name string `json:"name"`
Owner string `json:"owner"`
Environment string `json:"environment"`
Criticality string `json:"criticality"`
Exposure string `json:"exposure"`
DataLifetimeYears *int `json:"dataLifetimeYears"`
FISMAID string `json:"fismaId"`
FIPS199 string `json:"fips199"`
HVAID string `json:"hvaId"`
Hosting string `json:"hosting"`
HostingProvider string `json:"hostingProvider"`
Notes string `json:"notes"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Assets []SystemAsset `json:"assets"`
}
System is the unit an owner answers for: one or more assets (a host, the endpoints it serves) plus what a person knows about it that no scanner can observe. Every field a person may set is optional; an empty one means "not provided", never a default (PRD-003 REQ-SYS-1). The M-23-02 items 1, 2, 3, 7 and 8 live here because CISA says no tool can collect them.
type SystemAsset ¶
type SystemAsset struct {
ID int64 `json:"id"`
Kind string `json:"kind"`
Name string `json:"name"`
Address string `json:"address"`
}
SystemAsset is an asset as listed under its system.
type SystemPatch ¶
SystemPatch changes some fields of a system. A key that is absent is left alone; a nil value clears the field; a string (or, for dataLifetimeYears, a number) sets it.
type SystemPatchByID ¶
type SystemPatchByID struct {
ID int64
Patch SystemPatch
}
SystemPatchByID is one row of a bulk update.
type TrendPoint ¶
TrendPoint is the fleet's readiness distribution at the end of a day.
type TrustAnchor ¶
type TrustAnchor struct {
SHA256 string `json:"fingerprint"`
Subject string `json:"subject"`
NotAfter time.Time `json:"notAfter"`
AddedAt time.Time `json:"addedAt"`
AddedBy string `json:"addedBy"`
}
TrustAnchor is one stored anchor.
type User ¶
type User struct {
ID int64 `json:"id"`
Username string `json:"username"`
DisplayName string `json:"displayName"`
Role string `json:"role"`
PasswordHash string `json:"-"`
Disabled bool `json:"disabled"`
MustChange bool `json:"mustChangePassword"`
FailedCount int `json:"-"`
LockedUntil *time.Time `json:"lockedUntil,omitempty"`
CreatedAt time.Time `json:"createdAt"`
CreatedBy string `json:"createdBy"`
PasswordChangedAt time.Time `json:"passwordChangedAt"`
LastLoginAt *time.Time `json:"lastLoginAt,omitempty"`
}
User is an account. PasswordHash never leaves the server.