core

package
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 65 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package core is the always-on core module: its migrations and contract tests. The libraries it builds on live in core/ (store, secrets, chain, audit, exec); dependency direction is module -> core, never the reverse (CONTRACT FORBID-2).

Index

Constants

View Source
const (
	CodeInvalidTimezone = "invalid_timezone"
	CodeInvalidFrom     = "invalid_from"
	CodeInvalidTo       = "invalid_to"
)

Error codes of the general settings and the audit filters. The audit ones are invalid_from and invalid_to (not bad_from and bad_to): API_CONVENTIONS 3.2 rule 5 gives one meaning to a code, and bad_from/bad_to already mean "the sender/recipient email is not valid" in notify.

View Source
const (
	CodeInvalidCategories = "invalid_categories"
	CodeInvalidFormat     = "invalid_format"
	CodeInvalidRange      = "invalid_range"
	CodeLogsTooLarge      = "logs_too_large" // not too_large: that code means "the request body is over the limit" (API_CONVENTIONS 3.2 rule 5)
)

Error codes of GET /core/logs/export, the ones of the mock (web/src/features/core/logExport.ts).

View Source
const (
	EngineOff         = "off"
	EngineNeedsSetup  = "needs_setup"
	EngineStarting    = "starting"
	EngineReady       = "ready"
	EngineRunning     = "running"
	EngineError       = "error"
	EngineUnavailable = "unavailable"

	CostWhileOn      = "on"
	CostWhileRunning = "running"
)

Engine groups, cost kinds and states of contract.ts (web/src/features/scanning).

View Source
const (
	SwitchNone   = ""       // no switch of its own: 409 not_toggleable
	SwitchModule = "module" // the switch of its module (core's registry, audited core.module as PATCH /modules/{id})
	SwitchOwn    = "own"    // ScanEngine.Toggle (active discovery, the OpenVAS flag)
)

How an engine is switched (ScanEngine.Switch).

View Source
const (
	CodeAlreadySetup      = "already_setup"
	CodeInvalidOrg        = "invalid_org"
	CodeInvalidLan        = "invalid_lan"
	CodePublicRange       = "public_range"
	CodeOverlapRange      = "overlap_range"
	CodeInvalidBundle     = "invalid_bundle"
	CodeInvalidModule     = "invalid_module"
	CodeSampleUnavailable = "sample_unavailable"
	CodeTermsNotAccepted  = "terms_not_accepted"
)

Error codes of the setup operations, besides those of core/auth and modreg.

View Source
const (
	CodeAddressConflict       = "address_conflict"
	CodeGatewayOutsideSubnet  = "gateway_outside_subnet"
	CodeGatewayNotHost        = "gateway_not_host"
	CodeSpanOnManagement      = "span_on_management"
	CodeBadInterface          = "bad_interface"
	CodeSpanHasAddress        = "span_has_address"
	CodeSpanNotPhysical       = "span_not_physical"
	CodeNetBackendUnsupported = "net_backend_unsupported"
	CodeNothingPending        = "nothing_pending"
	CodeChangePending         = "change_pending"
	CodeConnectivityCheck     = "connectivity_check_failed"
	CodeRevertedByReboot      = "reverted_by_reboot"
	CodeRevertFailed          = "revert_failed"
	CodeNetplanApplyFailed    = "netplan_apply_failed"
	CodeNTPNotApplied         = "ntp_not_applied"
	CodeARPProbeFailed        = "arp_probe_failed"
	CodePendingInvalid        = "pending_invalid"
	CodeConfirmFailed         = "confirm_failed"
	CodeConfirmRequired       = "confirm_required"
	CodeDHCPNoStatic          = "dhcp_no_static"
	CodeInvalidStatic         = "invalid_static"
	CodeIPInUse               = "ip_in_use"
	CodeManagementFixed       = "management_fixed"
	CodeManagementCount       = "management_count"
	CodeManagementNotSet      = "management_not_set"
	CodeSpanCount             = "span_count"
	CodeInvalidRoles          = "invalid_roles"
	CodeNoInterface           = "no_interface"
	CodeNothingSelected       = "nothing_selected"
	CodeBadFilter             = "bad_filter"
	CodeDefaultNoServers      = "default_no_servers"
	CodeBadNTP                = "bad_ntp"
	CodeBadBoxAddress         = "bad_box_address"
)

Error codes of the Box network screen. The host's own refusals and run endings come through mapNetCode.

View Source
const (
	CodeNotAppliance      = "not_appliance"
	CodeHostUnreachable   = "host_unreachable"
	CodeHostError         = "host_error"
	CodeNoCheckYet        = "no_check_yet"
	CodeDpkgLocked        = "dpkg_locked"
	CodeDpkgInconsistent  = "dpkg_inconsistent"
	CodeLowDisk           = "low_disk"
	CodeRebooting         = "rebooting"
	CodeRebootLimit       = "reboot_limit_reached"
	CodeSnapshotRejected  = "snapshot_rejected"
	CodeSnapshotFailed    = "snapshot_failed"
	CodeAptFailed         = "apt_failed"
	CodeHealthCheckFailed = "health_check_failed"
	CodeEffectNotVerified = "effect_not_verified"

	// Refusals of a software switch (host-api 6.8, 6.10).
	CodeNoPrevious            = "no_previous"
	CodePreviousRevoked       = "previous_revoked"
	CodeRollbackNotAllowed    = "rollback_not_allowed"
	CodeRollbackBackupMissing = "rollback_backup_missing"
	CodeRollbackIsUpgrade     = "rollback_is_upgrade"
	CodeCurrentVersionUnknown = "current_version_unknown"
)

Error codes that come from the host (host-api section 11) or from not having one. Where they sit in the API: 409 for what the state of the box refuses, 502 for a helper that failed or answered wrongly, 503 when it cannot be reached.

View Source
const (
	CodeInvalidWindow  = "invalid_window"
	CodeNoDays         = "no_days"
	CodeInvalidTime    = "invalid_time"
	CodeEmptyWindow    = "empty_window"
	CodeInvalidScope   = "invalid_scope"
	CodeInvalidWhen    = "invalid_when"
	CodeNoWindow       = "no_window"
	CodeOutsideWindow  = "outside_window"
	CodeNothingToDo    = "nothing_to_install"
	CodeNothingPlanned = "nothing_scheduled"
	CodeCheckOff       = "check_off"
)

Error codes of the OS endpoints that core decides itself (the host's own are in oshost.go).

View Source
const (
	CodeUpdateSourceUnreachable = "update_source_unreachable"
	CodeUpdateCheckFailed       = "update_check_failed"
)

Error codes of the update check (API_CONVENTIONS 3.3).

View Source
const CodeBackupsDeleted = "backups_already_deleted"

CodeBackupsDeleted is the 500 of a purge that failed after the helper had deleted its backups (API_CONVENTIONS 3.3).

View Source
const CodeConfirmMismatch = "confirm_mismatch"

CodeConfirmMismatch is the 400 of a purge whose typed name is not the organization's (API_CONVENTIONS 3.3).

View Source
const (

	// CodeInvalidSetupCode is the 403 of a missing or wrong setup code.
	CodeInvalidSetupCode = "invalid_setup_code"
)

The one-time setup code. While first-run setup is open (no administrator has been created) the box keeps a random code in core_secret and prints it in its log at every start; POST /core/setup needs it, so whoever can merely reach the port cannot claim the box before its owner does. The code is deleted in the transaction that creates the first administrator. It is 100 bits typed in four groups of five (letters and digits that cannot be mistaken for each other); input is compared without case, spaces and hyphens.

View Source
const CodeTelemetryUnavailable = "telemetry_unavailable"

CodeTelemetryUnavailable is the 400 of a PATCH /core/privacy that turns the anonymous signal on (API_CONVENTIONS 3.3).

View Source
const CodeTransitionPending = "transition_pending"

CodeTransitionPending is the 412 of a purge while core's update journal is pending or unrecoverable (host answer transition_pending).

View Source
const CoreMemoryMB = 2048

CoreMemoryMB is core's own memory cap (the vedette container's --memory=2g, host/ops/quadlet.go): always counted in reserved_mb.

View Source
const DefaultReleaseBase = "https://github.com/KNT048/vedette/releases/download"

DefaultReleaseBase is where the release documents are downloaded from (PRIVACY.md flow 6): the index at <base>/index/index.json and a release's manifest at <base>/v<version>/release-manifest.json, each with .minisig.

View Source
const (
	// UpdateTickEvery is how often the job looks (cmd/vedette registers it as core/software-update). A check is made
	// only when it is due; an install may start at any tick inside the window, so a short window is not missed.
	UpdateTickEvery = 10 * time.Minute
)

Variables

View Source
var (
	ErrDiscoveryModuleOff = errors.New("core: scanning: sensor-active is off")
	ErrDiscoveryOff       = errors.New("core: scanning: active discovery is off")
	ErrScopeNotConfirmed  = errors.New("core: scanning: the scope is not confirmed")
	ErrNmapBusy           = errors.New("core: scanning: discovery is running nmap now")
	ErrNmapUnavailable    = errors.New("core: scanning: nmap is not available")
)

The refusals of DiscoveryRunner.Run.

View Source
var BodyLimits = map[string]int64{"core_post_core_setup_restore_upload": maxUploadBytes, "core_post_core_data_restore_upload": maxUploadBytes}

BodyLimits is the request cap of the backup upload above the server default (operationId -> bytes). cmd/vedette hands it to server.Config through moduleWiring.BodyLimits.

View Source
var ErrNoSensor = errors.New("core: no sensor is measuring the SPAN port")

ErrNoSensor is what a SpanSensor returns when nothing measures (the module is off): the page then shows what the host's counters say.

View Source
var Migrations = mustSub(migrationFiles, "migrations/sqlite")

Migrations holds the SQLite migrations of the core module, rooted at the directory that contains the NNNN_*.sql files. Pass it to store.Migrate(ctx, db, "core", core.Migrations).

Functions

func CompactIfPending

func CompactIfPending(ctx context.Context, db *store.DB, dataDir string) error

CompactIfPending is called at start (cmd/vedette, before the scheduler): when a purge left its marker, the database is compacted so the deleted rows are no longer in the bytes of the file or its log. The marker goes only after a success, so a failure is retried at every start until it works (L4); the error is returned for the caller to log, not to stop the box.

func ExportColumnClass

func ExportColumnClass(table, column string) string

ExportColumnClass is what the export does with table.column: "export", "json", "jsonurl", "url" or "skip"; "" when the column is not classified (it is then not exported). A table that is skipped whole answers "skip" for its columns.

func ExportPolicyColumns

func ExportPolicyColumns(table string) []string

ExportPolicyColumns lists the columns the policy names for a table (every class), so a test can find a column that no longer exists.

func ExportTables

func ExportTables() []string

ExportTables lists the tables the policy knows, whole-skipped ones included.

Types

type APIHandlers

type APIHandlers struct {
	// contains filtered or unexported fields
}

APIHandlers implements the sign-in, account, user, first-run setup, audit and general-settings operations of the core module (S-CORE-1 and S-CORE-3). Embed it in the composite handler beside ModuleHandlers; the two implement disjoint operations. The handlers are thin: the rules live in core/auth, the checks of the contract (route table, roles, CSRF) in core/server.

func NewAPIHandlers

func NewAPIHandlers(c HandlersConfig) (*APIHandlers, error)

NewAPIHandlers returns the handlers.

func (*APIHandlers) CheckSetupCode

func (h *APIHandlers) CheckSetupCode(ctx context.Context, given string) error

CheckSetupCode is the gate of every first-run operation (POST /core/setup, and the restore from a backup): setup must still be open (409 already_setup) and given must be the stored code (403 invalid_setup_code). Every judged guess counts against the client address (auth.BeginSetupAttempt, 429 rate_limited); the right code gives its count back.

func (*APIHandlers) CoreDeleteCoreAccountSessionsID

func (h *APIHandlers) CoreDeleteCoreAccountSessionsID(ctx context.Context, params oas.CoreDeleteCoreAccountSessionsIDParams) error

CoreDeleteCoreAccountSessionsID implements DELETE /core/account/sessions/{id} (viewer): one of my other sessions; the one I am using is 400 current_session (sign out instead).

func (*APIHandlers) CoreDeleteCoreConnectionsID

func (h *APIHandlers) CoreDeleteCoreConnectionsID(ctx context.Context, params oas.CoreDeleteCoreConnectionsIDParams) error

CoreDeleteCoreConnectionsID implements DELETE /core/connections/{id} (admin): 409 in_use while a change made through it is still in force.

func (*APIHandlers) CoreGetCoreAccount

func (h *APIHandlers) CoreGetCoreAccount(ctx context.Context) (*oas.CoreGetCoreAccountOK, error)

CoreGetCoreAccount implements GET /core/account (viewer): my profile, whether the email method of two-step sign-in can be chosen, and my live sessions with the current one marked.

func (*APIHandlers) CoreGetCoreAudit

func (h *APIHandlers) CoreGetCoreAudit(ctx context.Context, params oas.CoreGetCoreAuditParams) (*oas.CoreGetCoreAuditOK, error)

CoreGetCoreAudit implements GET /core/audit (admin): one page of the rows that match, newest first, at most 200 (offset and limit), with the total number of matches and the users and groups present in the log (for the filter lists).

func (*APIHandlers) CoreGetCoreAuditExport

CoreGetCoreAuditExport implements GET /core/audit/export (admin): the matching rows as CSV, newest first, no 200-row limit. The download is itself a row of core_audit (INV-2), written before the file is read, so the file is a snapshot that ends at that row. The rows are read page by page while the response is written, so a large log is never held in memory.

func (*APIHandlers) CoreGetCoreAuthOptions

func (h *APIHandlers) CoreGetCoreAuthOptions(ctx context.Context) (*oas.CoreGetCoreAuthOptionsOK, error)

CoreGetCoreAuthOptions implements GET /core/auth-options (public, auth-oidc INV-4): the SSO button exists only while the auth-oidc module is on and has an issuer. Nothing else about the configuration is said here.

func (*APIHandlers) CoreGetCoreConnections

func (h *APIHandlers) CoreGetCoreConnections(ctx context.Context) (*oas.CoreGetCoreConnectionsOK, error)

CoreGetCoreConnections implements GET /core/connections (admin).

func (*APIHandlers) CoreGetCoreDataExport

func (h *APIHandlers) CoreGetCoreDataExport(ctx context.Context) (oas.CoreGetCoreDataExportOK, error)

CoreGetCoreDataExport implements GET /core/data/export (admin). The file is written row by row into a pipe while one read transaction holds a consistent view, so memory stays at one row whatever the size of the database. At most exportMaxBytes are written: the file then ends cleanly (valid JSON) with "truncated": true and the table it stopped in. One export runs at a time (409 busy). The row of core_audit is written before the first byte, with the administrator's name (SYS-3).

func (*APIHandlers) CoreGetCoreGeneral

func (h *APIHandlers) CoreGetCoreGeneral(ctx context.Context) (*oas.CoreGetCoreGeneralOK, error)

CoreGetCoreGeneral implements GET /core/general (viewer): the name, the box's zone under its current name, and whether the operating system uses it too.

func (*APIHandlers) CoreGetCoreLogsExport

CoreGetCoreLogsExport implements GET /core/logs/export (admin, S-CORE-6): the chosen log categories as one JSON or CSV file. Each category comes from the source its module registered (core/logexport); one without a source is empty and listed as missing. The download is itself a row of core_audit.

func (*APIHandlers) CoreGetCorePrivacy

func (h *APIHandlers) CoreGetCorePrivacy(ctx context.Context) (*oas.CoreGetCorePrivacyOK, error)

CoreGetCorePrivacy implements GET /core/privacy (viewer).

func (*APIHandlers) CoreGetCoreSetupModules

func (h *APIHandlers) CoreGetCoreSetupModules(ctx context.Context) (*oas.CoreGetCoreSetupModulesOK, error)

CoreGetCoreSetupModules implements GET /core/setup/modules (public): module ids, tiers and dependencies for the bundle step. It does not say which modules are on. While setup is open it offers the box's own network (lan) as the first range of the network step; once setup is done lan is null, so the public page tells nobody the box's network afterwards.

func (*APIHandlers) CoreGetCoreTerms

func (h *APIHandlers) CoreGetCoreTerms(ctx context.Context) (*oas.CoreGetCoreTermsOK, error)

CoreGetCoreTerms implements GET /core/terms (viewer): the version of the terms of use this software ships and the acceptance stored on this box, null when there is none (a box set up by an older release). Who accepted is said to administrators only: viewers and operators cannot list users either.

func (*APIHandlers) CoreGetCoreUsers

func (h *APIHandlers) CoreGetCoreUsers(ctx context.Context) (*oas.CoreGetCoreUsersOK, error)

CoreGetCoreUsers implements GET /core/users (admin).

func (*APIHandlers) CoreGetMe

func (h *APIHandlers) CoreGetMe(ctx context.Context) (*oas.CoreGetMeOK, error)

CoreGetMe implements GET /me (viewer).

func (*APIHandlers) CoreGetSetup

func (h *APIHandlers) CoreGetSetup(ctx context.Context) (*oas.CoreGetSetupOK, error)

CoreGetSetup implements GET /setup (public): whether first-run setup is done. Before setup there is no org row.

func (*APIHandlers) CorePatchCoreAccount

func (h *APIHandlers) CorePatchCoreAccount(ctx context.Context, req *oas.CorePatchCoreAccountReq) (*oas.CorePatchCoreAccountOK, error)

CorePatchCoreAccount implements PATCH /core/account (viewer): the display name.

func (*APIHandlers) CorePatchCorePrivacy

func (h *APIHandlers) CorePatchCorePrivacy(ctx context.Context, req *oas.CorePatchCorePrivacyReq) (*oas.CorePatchCorePrivacyOK, error)

CorePatchCorePrivacy implements PATCH /core/privacy (admin): turns the two switches on or off; an absent field is left alone. One audit row per switch in the body.

func (*APIHandlers) CorePatchCoreUsersID

CorePatchCoreUsersID implements PATCH /core/users/{id} (admin): role and/or disabled (INV-7).

func (*APIHandlers) CorePostAuthLogin

func (h *APIHandlers) CorePostAuthLogin(ctx context.Context, req *oas.CorePostAuthLoginReq) (*oas.CorePostAuthLoginOK, error)

CorePostAuthLogin implements POST /auth/login (public): core INV-8. On success it sets the session, CSRF and device cookies; the body only says ok.

func (*APIHandlers) CorePostAuthLoginResendCode

CorePostAuthLoginResendCode implements POST /auth/login/resend-code (public): the password is needed again.

func (*APIHandlers) CorePostAuthLogout

func (h *APIHandlers) CorePostAuthLogout(ctx context.Context) error

CorePostAuthLogout implements POST /auth/logout (public): ends the session of the cookie, if any, and clears both cookies. It is 204 whether or not there was a live session.

func (*APIHandlers) CorePostCoreAccount2FAConfirm

CorePostCoreAccount2FAConfirm implements POST /core/account/2fa/confirm (viewer).

func (*APIHandlers) CorePostCoreAccount2FADisable

CorePostCoreAccount2FADisable implements POST /core/account/2fa/disable (viewer): needs the password.

func (*APIHandlers) CorePostCoreAccount2FAEmailConfirm

CorePostCoreAccount2FAEmailConfirm implements POST /core/account/2fa/email/confirm (viewer).

func (*APIHandlers) CorePostCoreAccount2FAEmailStart

CorePostCoreAccount2FAEmailStart implements POST /core/account/2fa/email/start (viewer): needs the current password.

func (*APIHandlers) CorePostCoreAccount2FAStart

CorePostCoreAccount2FAStart implements POST /core/account/2fa/start (viewer): needs the current password.

func (*APIHandlers) CorePostCoreAccountPassword

CorePostCoreAccountPassword implements POST /core/account/password (viewer): every session ends and the response sets new session and CSRF cookies for this browser.

func (*APIHandlers) CorePostCoreAccountSessionsRevokeOthers

func (h *APIHandlers) CorePostCoreAccountSessionsRevokeOthers(ctx context.Context) (*oas.CorePostCoreAccountSessionsRevokeOthersOK, error)

CorePostCoreAccountSessionsRevokeOthers implements POST /core/account/sessions/revoke-others (viewer).

func (*APIHandlers) CorePostCoreConnections

CorePostCoreConnections implements POST /core/connections (admin, 201).

func (*APIHandlers) CorePostCoreConnectionsIDTest

CorePostCoreConnectionsIDTest implements POST /core/connections/{id}/test (admin): one harmless read over the transport of the connection's kind, with the certificate or host key pinned at the first success. A connection that is off is 409 connection_off and nothing is sent. The admin check runs before the first byte leaves the box and again inside the write transaction that saves the result; the network call itself is in no transaction.

func (*APIHandlers) CorePostCoreDataPurge

func (h *APIHandlers) CorePostCoreDataPurge(ctx context.Context, req *oas.CorePostCoreDataPurgeReq) (*oas.CorePostCoreDataPurgeOK, error)

CorePostCoreDataPurge implements POST /core/data/purge (admin). A wrong name answers 400 confirm_mismatch and deletes nothing: the check runs before the scratch database, the file removal and the transaction, and again inside the transaction. The reply lists how many rows each table lost (tables that were empty are left out); the session ends with the users.

func (*APIHandlers) CorePostCoreSetup

func (h *APIHandlers) CorePostCoreSetup(ctx context.Context, req *oas.CorePostCoreSetupReq) (*oas.CorePostCoreSetupOK, error)

CorePostCoreSetup implements POST /core/setup (public): first-run setup. It creates the organization, the first administrator and a session for them (the response sets the session and CSRF cookies, as a sign-in does; no device cookie), turns the chosen bundle on and writes core_audit, all in one transaction, and only while setup is not done (INV-15). Creating the administrator needs the one-time setup code from the box's log and the acceptance of the terms of use, stored with who, when and which version. Order of refusals: already set up (also for sample data), the build has no sample data, setup code, the terms, then the fields in the order of the form.

func (*APIHandlers) CorePostCoreUsers

CorePostCoreUsers implements POST /core/users (admin): creates the account with a random temporary password that is returned once, in this response, and stored only as a hash.

func (*APIHandlers) CorePostCoreUsersID2FAReset

CorePostCoreUsersID2FAReset implements POST /core/users/{id}/2fa/reset (admin): not for yourself.

func (*APIHandlers) CorePostCoreUsersIDResetPassword

CorePostCoreUsersIDResetPassword implements POST /core/users/{id}/reset-password (admin): a temporary password, returned once; every session of that user ends.

func (*APIHandlers) CorePutCoreConnectionsID

CorePutCoreConnectionsID implements PUT /core/connections/{id} (admin).

func (*APIHandlers) CorePutCoreGeneral

func (h *APIHandlers) CorePutCoreGeneral(ctx context.Context, req *oas.CorePutCoreGeneralReq) (*oas.CorePutCoreGeneralOK, error)

CorePutCoreGeneral implements PUT /core/general (admin): organization name and time zone.

func (*APIHandlers) EnsureSetupCode

func (h *APIHandlers) EnsureSetupCode(ctx context.Context) (string, error)

EnsureSetupCode is called once at start-up. While setup is open it returns the code (making and storing it the first time); once setup is done it removes any code that is left and returns "". The caller prints a non-empty code in the log: that is the one place the code is meant to be read, the same way the first admin password of other self-hosted tools is.

func (*APIHandlers) OrgName

func (h *APIHandlers) OrgName(ctx context.Context) (string, error)

OrgName returns the organization name of the general settings ("" before first-run setup). The reports module offers it as the default of the assessment form.

func (*APIHandlers) OrgTimeZone

func (h *APIHandlers) OrgTimeZone(ctx context.Context) (string, error)

OrgTimeZone returns the IANA name of the organization time zone, the box's one zone (core_org.timezone, under its current name: a zone an older version stored as Asia/Saigon reads as Asia/Ho_Chi_Minh; the column default before first-run setup has made the row). It is the neutral read other modules reach through cmd/vedette (notify quiet hours, the scan window of sensor-active); nobody else reads core_org.

func (*APIHandlers) SetupDone

func (h *APIHandlers) SetupDone(ctx context.Context) (bool, error)

SetupDone reports whether first-run setup has finished (an organization exists and is set up). cmd/vedette asks it before it starts a module's container: nothing beyond core runs on a box before its first administrator exists.

type Adjustment

type Adjustment struct{ From, To string }

Adjustment is a range or exclusion normalized on save.

type AuditNamer

type AuditNamer interface {
	AuditNames(ctx context.Context, ids []string) (map[string]string, error)
}

AuditNamer names the devices and findings that audit rows refer to by id: a device by its host name, else its IP, else what the box knows of it; a finding as "<CVE> on <device>". Ids it does not know are left out. cmd/vedette implements it over inventory and findings, so core imports neither module.

type BoxLinks struct {
	Base       string
	SelfSigned bool
}

BoxLinks is what cmd/vedette tells the Box network page about the links (NetworkConfig.BoxLinks): the start of every link now ("" when the box makes none) and whether the box issues its own certificate (else the owner's -tls-cert, which the box never changes).

type Card

type Card struct {
	Name      string
	MAC       string
	Link      bool
	Addresses []netip.Addr
}

Card is a network card of the box with its global addresses (the link-local ones do not count: a SPAN card has none that matters, host-api 6.5).

type DiscoveryRunner

type DiscoveryRunner interface {
	Run(ctx context.Context, actor string, targets []string, record func(tx *sql.Tx, c RunConsent) error) (RunningJob, error)
}

DiscoveryRunner starts "Scan the LAN now" (no targets) or "Check this device now" (targets) on active discovery (sensor-active). It calls record once the run passed every check and before anything is sent; an error of record refuses the run (nothing starts). Its errors: ErrDiscoveryModuleOff, ErrDiscoveryOff, ErrScopeNotConfirmed, ErrNmapBusy, ErrNmapUnavailable, a *RunTooSoon, a *RunRefusal, record's error, or a failure of the box.

type EngineCost

type EngineCost struct {
	RAMMB     *int
	While     string // CostWhileOn or CostWhileRunning
	Container string // the container it shares with other engines; "" when the figure is its own
}

EngineCost is what an engine may take of the box's memory: RAMMB nil when not known (never an estimate).

type EngineStatus

type EngineStatus struct {
	Enabled bool
	State   string
	Reason  string // "" = none
	Last    *LastRun
	Next    *time.Time
	Running []RunningJob
}

EngineStatus is the live part of a card.

type HandlersConfig

type HandlersConfig struct {
	DB      *store.DB
	Auth    *auth.Service
	Reg     *modreg.Registry
	Audit   *audit.Log
	Secrets *secrets.Store
	Log     *slog.Logger
	Facts   PrivacyFacts // optional
	// Names gives GET /core/audit the display names of the devices and findings its rows name. Optional: without it the
	// rows show their ids only. cmd/vedette reads them from inventory and findings, so core imports neither.
	Names AuditNamer
	Conns *conn.Service // optional: without it /core/connections answers 501 not_implemented
	// SpoolDir is where /core/logs/export writes its temporary file: a directory on the data volume (cmd/vedette gives
	// <data>/tmp/logs-export), created 0700 and swept of leftovers at startup. "" = os.TempDir() (tests).
	SpoolDir string
	Logs     *logexport.Registry // optional: where the modules register their log sources (INV-13); core adds "audit"; nil = a registry of its own
	Clock    func() time.Time    // nil: time.Now

	// The factory reset, POST /core/data/purge. DataDir is core_data (the directory of the database file); DataFiles are plain
	// names of the data files the modules keep there besides vedette.db (today logs.db), checked against dataFileRE; both
	// optional (no DataDir: no files are removed). Schema is the migrations of every module in order and is required for the purge.
	// Restart, when not nil, is called shortly after a purge has answered: the process must start again, because what its modules
	// hold in memory (the sensor CA, caches) belongs to the data that is gone; the supervisor (Quadlet, Restart=always) brings it back.
	DataDir   string
	DataFiles []string
	Schema    []SchemaSet
	Restart   func()
	// KeyPath is the encryption key file (-key): the purge replaces it with a fresh key. Host is vedette-host as far as the purge
	// needs it (nil = no helper: backups are not deleted and the answer says so). OSBusy reports a running OS update of core itself.
	// BeforeWipe runs before anything is deleted and may refuse the purge with an error; cmd/vedette turns the honeypot off (decoy
	// addresses leave the host) and empties its log there. All optional.
	KeyPath    string
	Host       PurgeHost
	OSBusy     func(context.Context) bool
	BeforeWipe func(context.Context) error
	// Gate is shared with the OS and network handlers (OSConfig.Gate, NetworkConfig.Gate): shut while a purge runs (N4). nil = its own.
	Gate *PurgeGate
	// AlsoKept names what a purge leaves on the box besides what it always reports ("honeypot_log": the honeypot's raw log, which the
	// honeypot container owns), and KeepRows the rows that must survive the wipe because they describe it (the honeypot's read position
	// in that log, so old events are not read again). Both set by cmd/vedette.
	AlsoKept []string
	KeepRows []KeepRow
	// AlsoFreeze are the other databases of the box whose files the purge removes or that must not take a write once it has wiped (logs.db,
	// DataFiles): each is frozen under its own write lock (so a write in flight finishes first, and nothing is written after) before the
	// files move, and thawed if the purge fails. After a success they stay frozen until the process stops.
	AlsoFreeze []*store.DB
	// Scope is the inventory as far as first-run setup needs it (INV-15): the LAN ranges and the scan commitment of the wizard become
	// the scope of Settings › Scanning › Safety in the setup's own transaction. nil = a build without the inventory: the ranges stay only
	// in core_setting setup.scope.
	Scope SetupScope
	// BoxLAN is the network of the box's management address (the Box network's management card), offered by GET
	// /core/setup/modules as the first range of the network step while setup is open. nil or ok=false: none (container-only).
	BoxLAN func(context.Context) (netip.Prefix, bool)
}

HandlersConfig wires APIHandlers; every field but Clock and Facts is required.

type HistoryRun

type HistoryRun struct {
	ID, Kind, Engine, Trigger, Label string
	TargetID                         string // "" when none
	StartedAt                        time.Time
	EndedAt                          *time.Time
	Outcome                          string // ok, partial, failed, stopped, running
	Text                             string
}

HistoryRun is one past (or running) run of a LAN engine or a public scan, for Settings › Scanning › History. The outcome text comes from what the run stored; it never claims a result nothing checked.

type Host

type Host interface {
	StateOS(ctx context.Context) (api.OSState, error)
	OSCheck(ctx context.Context, requestID, actor string) (api.Run, error)
	OSInstall(ctx context.Context, scope, snapshot, requestID, actor string) (api.Run, error)
	OSAutoSecuritySet(ctx context.Context, enabled bool, requestID, actor string) (api.Run, error)
	// The box's one time zone (INV-43, host-api 6.18): the operating system's zone, and setting it.
	StateTime(ctx context.Context) (api.TimeState, error)
	OSTimezoneSet(ctx context.Context, zone, requestID, actor string) (api.Run, error)
	OSReboot(ctx context.Context, args api.OSRebootArgs, requestID, actor string) (api.Run, error)
	OSRebootCancel(ctx context.Context, requestID, actor string) (api.Run, error)
	BackupCreate(ctx context.Context, args api.BackupCreateArgs, requestID, actor string) (api.Run, error)
	DownloadBackup(ctx context.Context, backupID string) (io.ReadCloser, int64, error)
	StateBackups(ctx context.Context) (api.BackupList, error)
	BackupRestore(ctx context.Context, backupID, snapshot, requestID, actor string) (api.Run, error)
	GetRun(ctx context.Context, runID string) (api.Run, error)
	ListRuns(ctx context.Context, limit int) ([]api.Run, error)
	Events(ctx context.Context, runID string, after uint64) *client.Stream
	// Software updates (S-CORE-2, host-api 6.7, 6.8, 6.10).
	StateContainers(ctx context.Context) (api.ContainersState, error)
	ContainerPull(ctx context.Context, args api.ContainerPullArgs, requestID, actor string) (api.Run, error)
	ContainerStart(ctx context.Context, args api.ContainerStartArgs, requestID, actor string) (api.Run, error)
	ContainerRollback(ctx context.Context, args api.ContainerRollbackArgs, requestID, actor string) (api.Run, error)
	// The system helper's own update, the first step of a software run (S-CORE-2, host-api 6.14).
	Info(ctx context.Context) (api.Info, error)
	SelfUpdate(ctx context.Context, args api.HostSelfUpdateArgs, requestID, actor string) (api.Run, error)
}

Host is what core needs of vedette-host (docs/specs/host-api.md). *client.Client implements it; tests run the real client against an in-process host. A nil Host is an install without the helper ("container only"): every OS endpoint then answers 409 not_appliance.

type KeepRow

type KeepRow struct{ Table, Column, Value string }

KeepRow names rows that survive the purge: the rows of Table whose Column equals Value. They describe something the purge leaves on the box (the honeypot's read position in its raw log, which the honeypot container owns), so that the fresh box does not read old events as new. The identifiers come from cmd/vedette, never from a request.

type LastRun

type LastRun struct {
	At      time.Time
	Outcome string // ok, partial, failed, stopped
	Text    string
}

LastRun is the newest run of an engine that ended (or the newest report of one that listens).

type ModuleHandlers

type ModuleHandlers struct {
	// contains filtered or unexported fields
}

ModuleHandlers implements GET /modules and PATCH /modules/{id} (S-CORE-1). Embed it in the composite handler; it implements no other operation.

func NewModuleHandlers

func NewModuleHandlers(db *store.DB, reg *modreg.Registry) *ModuleHandlers

NewModuleHandlers returns the handlers for the module list and switch.

func (*ModuleHandlers) CoreGetModules

func (h *ModuleHandlers) CoreGetModules(context.Context) (*oas.CoreGetModulesOK, error)

CoreGetModules implements core_get_modules: the state of every module (viewer).

func (*ModuleHandlers) CorePatchModulesID

CorePatchModulesID implements core_patch_modules_id (admin): turn a module on or off. The registry change and its core_audit row share one transaction; the in-memory state, and with it the routes and the jobs of the module, switches right after the commit, in this request (POST-2).

type NetHost

type NetHost interface {
	StateNet(ctx context.Context) (api.NetState, error)
	NetApply(ctx context.Context, args api.NetApplyArgs, requestID, actor string) (api.Run, error)
	NetConfirm(ctx context.Context, runID, requestID, actor string) (api.Run, error)
	NetRevert(ctx context.Context, runID, requestID, actor string) (api.Run, error)
	GetRun(ctx context.Context, runID string) (api.Run, error)
	Events(ctx context.Context, runID string, after uint64) *client.Stream
}

NetHost is what the Box network screen needs of vedette-host (docs/specs/host-api.md 5 and 6.5). *client.Client implements it; a test gives a fake. A nil NetHost is an install without the helper ("container only"): every /core/network route then answers 409 not_appliance.

type NetworkConfig

type NetworkConfig struct {
	DB    *store.DB
	Auth  *auth.Service
	Audit *audit.Log
	Log   *slog.Logger
	Host  NetHost
	// Sensor measures the SPAN port; nil: the page shows the host's counters only.
	Sensor SpanSensor
	// AddressInUse says whether a device of the inventory already has the address (409 ip_in_use); nil: not asked.
	AddressInUse func(ctx context.Context, ip netip.Addr) (bool, error)
	// AddressesChanged is called after the box's own addresses may have changed (an apply, a confirm, a revert, a
	// timeout): the caches of cmd/vedette that hold them (conn, sensor-active, honeypot) must read them again.
	AddressesChanged func()
	// BoxLinks says how links start now and who issues the certificate (cmd/vedette); nil: no link base shown, own certificate false.
	BoxLinks func(ctx context.Context) BoxLinks
	// AfterFunc runs f after d (nil: time.AfterFunc); the tests hold it back.
	AfterFunc func(d time.Duration, f func())
	Clock     func() time.Time // nil: time.Now
	// Gate is shut while a factory reset runs: every host write then answers 409 busy (N4). nil = never shut.
	Gate *PurgeGate
}

NetworkConfig wires NetworkHandlers. DB, Auth, Audit and Log are required; Host may be nil.

type NetworkHandlers

type NetworkHandlers struct {
	// contains filtered or unexported fields
}

NetworkHandlers implements the Box network operations of Settings (S-CORE-8: /core/network*; the routes belong to the host module, whose handlers these are) on top of vedette-host. Every change is one net.apply with the whole desired state: core merges the part the person changed into what the host reports as running, and keeps only what the host does not know (the SPAN switches, filters and limits, and the old address of a change that waits for confirmation). Nothing here runs a command itself (SYS-1).

func NewNetworkHandlers

func NewNetworkHandlers(c NetworkConfig) (*NetworkHandlers, error)

NewNetworkHandlers returns the handlers.

func (*NetworkHandlers) BoxAddress

func (h *NetworkHandlers) BoxAddress(ctx context.Context) (addr string, previous []string, err error)

BoxAddress is the address every link of the box carries: the saved Box address, else the management IPv4 the host reports (state/net, read through the page's cache, netReadTTL); "" when neither is known (no host, or a management card without an IPv4 address). previous are the earlier Box addresses the box still answers to. An error is a failed read of the setting or of the host: the caller keeps what it had. Safe on nil ("").

func (*NetworkHandlers) Cards

func (h *NetworkHandlers) Cards(ctx context.Context) (cards []Card, ok bool, err error)

Cards lists the cards the host reports. ok is false when there is no host to ask (no socket configured, or its file is absent, or a host that says this is no appliance). Only "no socket configured" (HasHost false) means a container-only install, where sensor-passive takes the box's cards from the sensor's heartbeat; its HostCards turns ok=false with HasHost into an error. A host that is there but does not answer right now gives the last good list (or, before there is one, ok=false): the passive sensor must not fail, or go into back-off, because the helper hiccups.

func (*NetworkHandlers) CoreGetCoreNetwork

func (h *NetworkHandlers) CoreGetCoreNetwork(ctx context.Context) (*oas.CoreGetCoreNetworkOK, error)

CoreGetCoreNetwork implements GET /core/network (viewer).

func (*NetworkHandlers) CoreGetCoreNetworkSpanStatus

func (h *NetworkHandlers) CoreGetCoreNetworkSpanStatus(ctx context.Context) (*oas.CoreGetCoreNetworkSpanStatusOK, error)

CoreGetCoreNetworkSpanStatus implements GET /core/network/span/status (viewer).

func (*NetworkHandlers) CorePostCoreNetworkBoxAddressForget

CorePostCoreNetworkBoxAddressForget implements POST /core/network/box-address/forget (admin): the box stops answering to an earlier Box address (404 not_found when it is not one of them). The certificate drops it at its next re-issue.

func (*NetworkHandlers) CorePostCoreNetworkManagementConfirm

func (h *NetworkHandlers) CorePostCoreNetworkManagementConfirm(ctx context.Context) (*oas.CorePostCoreNetworkManagementConfirmOK, error)

CorePostCoreNetworkManagementConfirm implements POST /core/network/management/confirm (admin).

func (*NetworkHandlers) CorePostCoreNetworkManagementRevert

func (h *NetworkHandlers) CorePostCoreNetworkManagementRevert(ctx context.Context) (*oas.CorePostCoreNetworkManagementRevertOK, error)

CorePostCoreNetworkManagementRevert implements POST /core/network/management/revert (admin).

func (*NetworkHandlers) CorePutCoreNetworkBoxAddress

CorePutCoreNetworkBoxAddress implements PUT /core/network/box-address (admin): the host name or IPv4 address the LAN reaches the box at, which every link the box makes carries; "" goes back to the default, the management IPv4 the host reports. The address it replaces (when one was saved) joins Previous, so what was set up with it keeps working. It touches nothing of the host.

func (*NetworkHandlers) CorePutCoreNetworkInterfaces

CorePutCoreNetworkInterfaces implements PUT /core/network/interfaces (admin): which card is the management one (fixed: the page is reached through it), which the SPAN port, and which are unused.

func (*NetworkHandlers) CorePutCoreNetworkManagement

CorePutCoreNetworkManagement implements PUT /core/network/management (admin).

func (*NetworkHandlers) CorePutCoreNetworkNtp

CorePutCoreNetworkNtp implements PUT /core/network/ntp (admin): the default pool or one to four servers of the person's own. It applies at once.

func (*NetworkHandlers) CorePutCoreNetworkSpan

CorePutCoreNetworkSpan implements PUT /core/network/span (admin).

func (*NetworkHandlers) HasHost

func (h *NetworkHandlers) HasHost() bool

HasHost reports whether core was started with a vedette-host socket (an appliance). False is a container-only install (-host-socket=""), the only case in which the passive sensor's heartbeat may decide the card.

func (*NetworkHandlers) ManagementCard

func (h *NetworkHandlers) ManagementCard(ctx context.Context) (name string, ok bool)

ManagementCard is the card the passive sensor listens on when no SPAN port is chosen: the management card (mgmtIface: the configured one, else the card of the default route, else the one card with an address), and only when it is a card of the box (cardsOf: never loopback, a bridge such as vedette0, or a container link). ok is false when there is no host to ask (no socket, or a host that says this is no appliance): the sensor's heartbeat then decides. A host that does not answer right now gives the last name it gave ("" before there is one), so the sensor does not stop listening because the helper hiccups.

func (*NetworkHandlers) ManagementLAN

func (h *NetworkHandlers) ManagementLAN(ctx context.Context) (netip.Prefix, bool)

ManagementLAN is the network of the management card's IPv4 address (host bits cleared): the range first-run setup offers first. ok is false without a host, when the host has not answered (yet), or when the card has no IPv4 address. The caller is a public page, so a read of the host starts at most once per netReadTTL from here, whatever its outcome (anonymous requests cannot spend core's host budget or fill the log), and the caller waits for it at most managementLANWait; a read that ends later still fills the answer for the next request.

func (*NetworkHandlers) SpanSettings

func (h *NetworkHandlers) SpanSettings(ctx context.Context) (SpanSettings, error)

SpanSettings returns the stored SPAN settings (the defaults before the first save). The passive sensor reads its extraction switches and exclusion filters from here.

type OSConfig

type OSConfig struct {
	DB    *store.DB
	Auth  *auth.Service
	Audit *audit.Log
	Log   *slog.Logger
	Host  Host
	// DataDir is core_data: the directory of the database file, where snapshots/ lives (host-api 6.11).
	DataDir string
	// KeyPath is the master key file that goes into a snapshot for a pre-update backup.
	KeyPath string
	// Zone returns the IANA name of the organization time zone (APIHandlers.OrgTimeZone).
	Zone  func(context.Context) (string, error)
	Clock func() time.Time // nil: time.Now
	// Gate is shut while a factory reset runs: every host write then answers 409 busy (N4). The same gate as HandlersConfig.Gate; nil = never shut.
	Gate *PurgeGate
	// UpdateRetry is the software update follower's wait between two tries; 0 = followRetry (tests shorten it).
	UpdateRetry time.Duration

	// Software update check (updates_check.go). Version is the running release (main.version); ReleaseBase
	// is where the signed release documents are downloaded from ("" = DefaultReleaseBase; tests: a local server);
	// HTTPClient nil = a client with timeouts that follows redirects only to the GitHub hosts of PRIVACY.md flow 6;
	// Trust nil = release.Embedded.
	Version     string
	ReleaseBase string
	HTTPClient  *http.Client
	Trust       func() (release.Trust, error)
	// Wake runs the core/software-update job now (core/jobs Scheduler.Wake): a box that never checked checks
	// firstCheckAfter after its process started, not at the next tick. nil: no early run (tests).
	Wake func()
	// Setup is the first-run gate of the restore from an uploaded backup: the setup code and whether setup is done.
	// Required.
	Setup *APIHandlers
	// Installed is called once after an OS update run that succeeded has been audited: the box's packages changed, so its
	// package list is read again now (wiring: the inventory/box job) instead of at the next hourly run. nil: nothing.
	Installed func()
	// ModuleOn reports whether a module is on (modreg.Registry.Enabled): a software update or rollback never starts the
	// container of a service whose module is off (serviceModule), whatever state systemd shows for its unit. nil: no module
	// is known to be off (the unit's own state decides).
	ModuleOn func(id string) bool
}

OSConfig wires OSHandlers. DB, Auth, Audit, Log and Zone are required; Host may be nil (an install without vedette-host); DataDir and KeyPath are required with a Host.

type OSHandlers

type OSHandlers struct {
	// contains filtered or unexported fields
}

OSHandlers implements the operating system part of Settings → Updates (S-CORE-7: /core/updates/os*) and the backup download (S-CORE-1: /core/data/backup) on top of vedette-host. Embed it in the composite handler beside the other core handlers; its operations are disjoint from theirs. Every host call is made with a fresh idempotency key and an actor label, after a core_audit row for the intent (and one more when it fails); nothing here runs a command itself (SYS-1).

func NewOSHandlers

func NewOSHandlers(c OSConfig) (*OSHandlers, error)

NewOSHandlers returns the handlers and sweeps the snapshot directories an earlier run left behind.

func (*OSHandlers) Busy

func (h *OSHandlers) Busy(ctx context.Context) bool

Busy reports whether an operating system install run or a software update run of this core is in progress (the factory reset refuses to start then).

func (*OSHandlers) Close

func (h *OSHandlers) Close()

Close stops the followers of install runs and waits for them. The run itself goes on in the host.

func (*OSHandlers) CoreDeleteCoreUpdatesOsReboot

func (h *OSHandlers) CoreDeleteCoreUpdatesOsReboot(ctx context.Context) (*oas.CoreDeleteCoreUpdatesOsRebootOK, error)

CoreDeleteCoreUpdatesOsReboot implements DELETE /core/updates/os/reboot (admin): cancel the scheduled reboot.

func (*OSHandlers) CoreGetCoreDataBackup

func (h *OSHandlers) CoreGetCoreDataBackup(ctx context.Context) (oas.CoreGetCoreDataBackupOK, error)

CoreGetCoreDataBackup implements GET /core/data/backup (admin): a backup of the database WITHOUT the master key, streamed from the host's copy. core writes a snapshot without the key (INV-6: a plain backup never holds one; only a password-protected one carries it, inside its encryption), asks for backup.create {manual, include_secrets: false}, deletes the snapshot when that call ends, and copies the host's file to the response as it reads it; nothing is held whole in memory. Every download makes a full snapshot and a manual backup on the box (the host keeps the latest 10), so: 409 busy while an install runs or another download is being made, 429 within a minute of the last one.

func (*OSHandlers) CoreGetCoreDataBackups

func (h *OSHandlers) CoreGetCoreDataBackups(ctx context.Context) (*oas.CoreGetCoreDataBackupsOK, error)

CoreGetCoreDataBackups implements GET /core/data/backups (admin): the backups the helper keeps, newest first. Kinds the API does not name are left out.

func (*OSHandlers) CoreGetCoreDataRestoreRun

func (h *OSHandlers) CoreGetCoreDataRestoreRun(ctx context.Context) (oas.NilCoreGetCoreDataRestoreRunOK, error)

CoreGetCoreDataRestoreRun implements GET /core/data/restore/run (admin): the latest restore, null before the first.

func (*OSHandlers) CoreGetCoreSetupRestore

func (h *OSHandlers) CoreGetCoreSetupRestore(ctx context.Context) (oas.NilCoreGetCoreSetupRestoreOK, error)

CoreGetCoreSetupRestore implements GET /core/setup/restore (public): the first-run restore while setup is open, only its status and the sentence of how it ended. A restore that succeeded brought an organization that finished setup, so once setup is done the answer is done, whoever finished it: it tells nobody more than GET /setup does.

func (*OSHandlers) CoreGetCoreUpdates

func (h *OSHandlers) CoreGetCoreUpdates(ctx context.Context) (*oas.CoreGetCoreUpdatesOK, error)

CoreGetCoreUpdates implements GET /core/updates (viewer).

func (*OSHandlers) CoreGetCoreUpdatesOs

func (h *OSHandlers) CoreGetCoreUpdatesOs(ctx context.Context) (*oas.CoreGetCoreUpdatesOsOK, error)

CoreGetCoreUpdatesOs implements GET /core/updates/os (viewer).

func (*OSHandlers) CoreGetCoreUpdatesOsRun

func (h *OSHandlers) CoreGetCoreUpdatesOsRun(ctx context.Context) (oas.NilCoreGetCoreUpdatesOsRunOK, error)

CoreGetCoreUpdatesOsRun implements GET /core/updates/os/run (viewer): the latest install run with its output so far, null before the first one. It answers from core's copy; the host is asked only to rebuild it after a restart.

func (*OSHandlers) CorePatchCoreUpdates

func (h *OSHandlers) CorePatchCoreUpdates(ctx context.Context, req *oas.CorePatchCoreUpdatesReq) (*oas.CorePatchCoreUpdatesOK, error)

CorePatchCoreUpdates implements PATCH /core/updates (admin): the channel and the mode.

func (*OSHandlers) CorePatchCoreUpdatesOsSettings

CorePatchCoreUpdatesOsSettings implements PATCH /core/updates/os/settings (admin): the maintenance window (core's own) and the automatic security updates switch (applied through os.auto_security.set and read back by the host). A window that no longer holds the scheduled reboot cancels that reboot, as the page says.

func (*OSHandlers) CorePostCoreDataBackup

func (h *OSHandlers) CorePostCoreDataBackup(ctx context.Context, req *oas.CorePostCoreDataBackupReq) (oas.CorePostCoreDataBackupOK, error)

CorePostCoreDataBackup implements POST /core/data/backup (admin): the download of GET, encrypted with password when one is given (encryptBackup: age, scrypt). The password is checked against the sign-in policy before anything is made.

func (*OSHandlers) CorePostCoreDataKey

func (h *OSHandlers) CorePostCoreDataKey(ctx context.Context, req *oas.CorePostCoreDataKeyReq) (oas.CorePostCoreDataKeyOK, error)

CorePostCoreDataKey implements POST /core/data/key (admin): the master key file, to keep apart from the backups. Step-up as for a restore: the current password, then a fresh two-step code when it is on; then one audit row. The bytes go only into this response: never a log line, never another response.

func (*OSHandlers) CorePostCoreDataRestore

CorePostCoreDataRestore implements POST /core/data/restore (admin, 202). Nothing is asked of the host before confirm_data_loss is true (409 confirm_required) and the backup is in the host's list (404 backup_unknown).

func (*OSHandlers) CorePostCoreDataRestoreFile

CorePostCoreDataRestoreFile implements POST /core/data/restore/file (admin, 202): step 2, the restore of the uploaded file as the restore of a kept backup. Everything that can be refused is refused before anything changes, in this order: the confirmation, the key file's shape, the upload, the key (chooseUploadKey, with this box's own key as a choice), an update or restore running, then the step-up of a restore (the current password, a fresh two-step code). A refusal keeps the upload, so the next try needs no new upload. Then the host imports it (importUpload) and the restore starts (startRestore: the copy of the current data first, kept as pre_restore and put back when the restored data does not start).

func (*OSHandlers) CorePostCoreDataRestoreUpload

CorePostCoreDataRestoreUpload implements POST /core/data/restore/upload (admin): step 1 of a restore from a downloaded file on a box that is set up, as the first-run upload (stageChecked: the same file checks, password and carried key) behind an administrator's session instead of the setup code. Nothing on the box changes but the staged upload; box_key says whether this box's own key opens the backup's secrets (a backup of this box), so the page asks for no key file then.

func (*OSHandlers) CorePostCoreSetupRestore

CorePostCoreSetupRestore implements POST /core/setup/restore (public, setup code, 202): step 2. Everything that can be refused is refused before the host is asked: the key's shape and that it opens the backup's secrets, the confirmation without a key, an update or restore running. Then the host imports the upload and the restore starts (startRestore).

func (*OSHandlers) CorePostCoreSetupRestoreUpload

CorePostCoreSetupRestoreUpload implements POST /core/setup/restore/upload (public, setup code): step 1 of the first-run restore. The body is the archive; it is read only after the setup code was accepted, with a read deadline long enough for a large file.

func (*OSHandlers) CorePostCoreUpdatesApply

func (h *OSHandlers) CorePostCoreUpdatesApply(ctx context.Context, req *oas.CorePostCoreUpdatesApplyReq) (*oas.CorePostCoreUpdatesApplyOK, error)

CorePostCoreUpdatesApply implements POST /core/updates/apply (admin): the software only (the other components have no update of their own yet: 404 no_update). It stores the run and answers at once with the run going; a follower does the host calls (pull every installed service, switch core, then start the others).

func (*OSHandlers) CorePostCoreUpdatesCheck

func (h *OSHandlers) CorePostCoreUpdatesCheck(ctx context.Context) (*oas.CorePostCoreUpdatesCheckOK, error)

CorePostCoreUpdatesCheck implements POST /core/updates/check (operator): download and verify the index, the offered manifest and (once per running version) the running release's manifest; store them; answer UpdatesState. 409 check_off when update checks are off under Privacy: the box then makes no request at all. In automatic mode the release on offer is then installed as user "system" when the maintenance window allows (autoInstall, updates_auto.go): the answer shows the run going, and applied stays 0 because the software reports at the end of its run (as the mock).

func (*OSHandlers) CorePostCoreUpdatesOsCheck

func (h *OSHandlers) CorePostCoreUpdatesOsCheck(ctx context.Context) (*oas.CorePostCoreUpdatesOsCheckOK, error)

CorePostCoreUpdatesOsCheck implements POST /core/updates/os/check (operator): apt update and a new list of pending packages. 409 check_off when update checks are off under Privacy: the box then makes no request.

func (*OSHandlers) CorePostCoreUpdatesOsInstall

CorePostCoreUpdatesOsInstall implements POST /core/updates/os/install (admin, 202): core writes a snapshot of its data (with the key: the host keeps the pre_os_update backup on the box), names it in os.install, and follows the run. The snapshot is deleted when the run ends.

func (*OSHandlers) CorePostCoreUpdatesOsReboot

CorePostCoreUpdatesOsReboot implements POST /core/updates/os/reboot (admin). now → host "now"; window → the next start of the maintenance window; custom → the next HH:MM inside the window; both in the organization time zone, sent to the host as one UTC instant (os.reboot "at"). 409 busy while an install runs.

func (*OSHandlers) CorePostCoreUpdatesRollback

CorePostCoreUpdatesRollback implements POST /core/updates/rollback (admin): every service that moved with core goes back to its previous version, core last. 409 confirm_required when the running release says the database must be put back too and the caller did not confirm the loss. The mode becomes manual in the same transaction as the stored run.

func (*OSHandlers) UpdateTick

func (h *OSHandlers) UpdateTick(ctx context.Context) error

UpdateTick is the job: a check when one is due (6 hours ± 30 minutes after the last one this process made, or after the stored last_check when it has made none, never before UpdateTickEvery after the process started; on a box that never checked, firstCheckAfter after the process started, the job being woken then), then the automatic install unless that check failed. Off under Privacy, or before first-run setup (no install id: the administrator has not seen Privacy yet): nothing.

func (*OSHandlers) WakeZoneAlignment

func (h *OSHandlers) WakeZoneAlignment()

WakeZoneAlignment asks the alignment loop to look now (after the first-run setup or a restore set the zone). It never blocks.

type PrivacyFacts

type PrivacyFacts interface {
	AIConfigured(ctx context.Context) bool   // flow 3: a provider is configured
	NTPPublic(ctx context.Context) bool      // flow 10: time requests leave the LAN
	OIDCConfigured(ctx context.Context) bool // flow 11: an issuer is configured
	// ConnectionsConfigured: flow 12, at least one enabled connection exists, so requests may go to the
	// address an administrator typed. Core stores the connections itself from slice 13b-4; until then the binary says false.
	ConnectionsConfigured(ctx context.Context) bool
	// WazuhConnected: flow 14, a Wazuh server is saved in agent-intake, so the box pulls from it while the module is on.
	WazuhConnected(ctx context.Context) bool
}

PrivacyFacts answers the "is it set up" questions of the Privacy page that belong to other modules or are not stored by core yet. Core must not read their tables, so the binary supplies this port (cmd/vedette). A nil port, or a module without a backend yet, gives the truth of today: no AI provider, default NTP servers, no OIDC issuer, no connections.

type PurgeGate

type PurgeGate struct {
	// contains filtered or unexported fields
}

PurgeGate keeps a factory reset and core's own host work apart, in both directions (N4, L1). Host work (an OS update, a backup, a network change) takes the read side for the whole of its call (Enter); the purge takes the write side (TryBegin). Neither waits: a purge that finds host work running, and host work that finds a purge running, answer 409 busy. One gate is shared by the handlers of core; a nil gate is never shut.

func (*PurgeGate) Active

func (g *PurgeGate) Active() bool

Active reports whether a purge is running.

func (*PurgeGate) End

func (g *PurgeGate) End()

End gives the write side back (a purge that failed; after a success the process stops with the gate shut).

func (*PurgeGate) Enter

func (g *PurgeGate) Enter() (leave func(), ok bool)

Enter takes the read side for one piece of host work; ok is false while a purge runs. Call leave when the work is done.

func (*PurgeGate) TryBegin

func (g *PurgeGate) TryBegin() bool

TryBegin takes the write side; false when host work is running or another purge is.

type PurgeHost

type PurgeHost interface {
	ListRuns(ctx context.Context, limit int) ([]api.Run, error)
	BackupPurge(ctx context.Context, requestID, actor string) (deleted int, err error)
}

PurgeHost is the part of vedette-host the purge needs: the runs in progress and the deletion of every backup it holds (host command backup.purge; the host client's method may be named differently, cmd/vedette adapts it).

type RangeAdd

type RangeAdd struct {
	Range            string
	Shown            []string
	ShownConfirmedAt *string // nil: shown as not confirmed
	Confirmed        bool
}

RangeAdd is POST /scanning/safety/ranges: the range and what the dialog showed beside the tick.

type RunConsent

type RunConsent struct {
	ID      string
	Ranges  []string // a sweep: the confirmed scope it covers
	Devices []string // a check: "id (ip)" of each device
	Until   time.Time
}

RunConsent is what a person's run will scan, for its audit row (the consent): the run, and the ranges of a sweep or the devices of a check with their addresses.

type RunHandlers

type RunHandlers struct {
	// contains filtered or unexported fields
}

RunHandlers serve the runs of every engine (core/run): GET /runs, GET /runs/{id}, POST /runs/{id}/stop and /resume. Core serves them so the Runs tab and every "Open the run" link answer while any engine's module is off.

func NewRunHandlers

func NewRunHandlers(m *run.Manager) *RunHandlers

NewRunHandlers returns the handlers over the box's run manager.

func (*RunHandlers) ScanningGetRuns

func (h *RunHandlers) ScanningGetRuns(ctx context.Context, params oas.ScanningGetRunsParams) (*oas.ScanningGetRunsOK, error)

ScanningGetRuns implements GET /runs (viewer): one page of runs, newest first.

func (*RunHandlers) ScanningGetRunsID

func (h *RunHandlers) ScanningGetRunsID(ctx context.Context, params oas.ScanningGetRunsIDParams) (*oas.ScanningGetRunsIDOK, error)

ScanningGetRunsID implements GET /runs/{id} (viewer): the run page.

func (*RunHandlers) ScanningPostRunsIDResume

ScanningPostRunsIDResume implements POST /runs/{id}/resume (operator; admin for a kind with AdminResume): audited scanning.run_resume by core/run.

func (*RunHandlers) ScanningPostRunsIDStop

func (h *RunHandlers) ScanningPostRunsIDStop(ctx context.Context, params oas.ScanningPostRunsIDStopParams) (*oas.ScanningPostRunsIDStopOK, error)

ScanningPostRunsIDStop implements POST /runs/{id}/stop (operator): audited scanning.run_stop by core/run in the same transaction.

type RunRefusal

type RunRefusal struct{ Target, Code, Detail string }

RunRefusal is one target of a run a person may not start: Code is unknown_device, out_of_scope or not_scannable; Detail the inventory's reason behind it.

func (*RunRefusal) Error

func (e *RunRefusal) Error() string

type RunTooSoon

type RunTooSoon struct{ RetryAfter time.Duration }

RunTooSoon refuses a sweep within the least gap after the last one.

func (*RunTooSoon) Error

func (e *RunTooSoon) Error() string

type RunningJob

type RunningJob struct {
	Engine    string
	ID        string
	Label     string
	TargetID  string // "" when none
	StartedAt time.Time
	Progress  *progress.View
	Queued    bool // it has not started (or gave way): it waits for the run in its way or for the scanner; Progress says what for
}

RunningJob is a job of an engine running now.

type Safety

type Safety struct {
	LANRanges                []string
	ConfirmedAt, ConfirmedBy *string
	Days                     []int
	From, To                 string
	PacketsPerS              int
	RequestsPerS             int
	Exclusions               []string
	FragileKinds             []string
	RegularScanKinds         []string
	FragileDevices           int
	Version                  string // names the stored values (inventory SafetyVersion); a full save must name the one it read
}

Safety is the shared block as stored.

type SafetyChanged

type SafetyChanged struct {
	Code, Message string
	Current       Safety
}

SafetyChanged refuses a write built on a block that changed since the person read it (409 Code: safety_changed, scope_changed; review #860 H1/M1). Nothing was stored; Current is the block now, which the answer carries (error.safety) for the page to show.

func (*SafetyChanged) Error

func (e *SafetyChanged) Error() string

type SafetyInput

type SafetyInput struct {
	LANRanges                      []string
	Confirmed                      bool
	Days                           []int
	From, To                       string
	PacketsPerS, RequestsPerS      int
	Exclusions                     []string
	FragileKinds, RegularScanKinds []string
	Version                        string // the version the page read: another one is a *SafetyChanged (safety_changed)
}

SafetyInput is PUT /scanning/safety.

type SafetyStore

type SafetyStore interface {
	Safety(ctx context.Context) (Safety, error)
	// SaveSafety validates and stores in; an error that is an *apierr.Error reaches the person as it is.
	SaveSafety(ctx context.Context, actor string, in SafetyInput) (Safety, []Adjustment, error)
	// AddRange adds one range to the scope in one transaction (read, append, store); the attestation covers what the dialog showed
	// (in.Shown, in.ShownConfirmedAt) and the new range, and a stored list or confirmation other than that is a *SafetyChanged
	// (scope_changed); a range the confirmed scope covers changes nothing. Its other errors as SaveSafety's.
	AddRange(ctx context.Context, actor string, in RangeAdd) (Safety, []Adjustment, error)
	// AddExclusion adds one exclusion in one transaction; one an exclusion covers changes nothing. Its errors as SaveSafety's.
	AddExclusion(ctx context.Context, actor, entry string) (Safety, error)
}

SafetyStore is the inventory as the one store of the shared safety block (inventory INV-32).

type ScanEngine

type ScanEngine struct {
	ID, Group, Module string
	Preview           bool
	Follows           string   // the engine whose switch it obeys; "" when none
	Affects           []string // engines that stop too when it is turned off
	Cost              EngineCost
	Switch            string // SwitchNone, SwitchModule or SwitchOwn
	// Needs is a module turned on first when the engine is turned on (with_dependencies, else 409 missing_dependencies): sensor-active
	// for active discovery. Turning the engine off never turns it off.
	Needs string
	// Precheck refuses a switch before anything changes (active discovery on without a confirmed scope); nil = none.
	Precheck func(ctx context.Context, on bool) error
	// Toggle moves the engine's own switch (SwitchOwn) and writes its audit row.
	Toggle func(ctx context.Context, actor string, on bool) error
	// Status reads the card; it is called whether its module is on or off and must not block on a run.
	Status func(ctx context.Context) (EngineStatus, error)
}

ScanEngine is one card of the page, in display order.

type ScanningConfig

type ScanningConfig struct {
	DB        *store.DB
	Reg       *modreg.Registry
	Audit     *audit.Log
	Log       *slog.Logger
	Safety    SafetyStore
	Engines   []ScanEngine
	Discovery DiscoveryRunner                                                 // nil: the run answers 501
	Estimate  func(ctx context.Context, in ScopeCostInput) (ScopeCost, error) // POST /scanning/safety/estimate; nil: 501
	History   func(ctx context.Context, asset string) ([]HistoryRun, error)   // the runs of GET /scanning/history (asset "": every run; a device id: the runs that reached it), newest first; nil: none
	TimeZone  func(ctx context.Context) string                                // the organization's zone; nil or "": UTC
	MemoryMB  func() (int, bool)                                              // MemTotal of the box; nil or false: unknown
}

ScanningConfig wires ScanningHandlers. DB, Reg, Audit and Safety are required.

type ScanningHandlers

type ScanningHandlers struct {
	// contains filtered or unexported fields
}

ScanningHandlers implements GET /scanning, PUT /scanning/safety, POST /scanning/safety/ranges and /exclusions, PATCH /scanning/engines/{id} and POST /scanning/engines/nmap-discovery/run. Embed it in the composite handler.

func NewScanningHandlers

func NewScanningHandlers(c ScanningConfig) (*ScanningHandlers, error)

NewScanningHandlers returns the handlers.

func (*ScanningHandlers) ScanningGetScanning

func (h *ScanningHandlers) ScanningGetScanning(ctx context.Context) (*oas.ScanningGetScanningOK, error)

ScanningGetScanning implements GET /scanning (viewer).

func (*ScanningHandlers) ScanningGetScanningHistory

ScanningGetScanningHistory implements GET /scanning/history (viewer): the runs of the LAN engines and the stored public scans, newest first, at most historyMax; with asset, only the runs that reached that device (the device page's Last checks).

func (*ScanningHandlers) ScanningPatchScanningEnginesID

ScanningPatchScanningEnginesID implements PATCH /scanning/engines/{id} (admin): the switch the engine maps to, audited by that switch, then the whole page.

func (*ScanningHandlers) ScanningPostScanningEnginesNmapDiscoveryRun

ScanningPostScanningEnginesNmapDiscoveryRun implements POST /scanning/engines/nmap-discovery/run (admin): the run starts in the background and is audited (scanning.run, the person's consent to scan now, like Scan now's).

func (*ScanningHandlers) ScanningPostScanningSafetyEstimate

ScanningPostScanningSafetyEstimate implements POST /scanning/safety/estimate (viewer): the cost of one pass over a scope as typed, before it is saved. Changes nothing.

func (*ScanningHandlers) ScanningPostScanningSafetyExclusions

ScanningPostScanningSafetyExclusions implements POST /scanning/safety/exclusions (admin): "+ New exclusion" where the person is (#842), added in one transaction by the inventory (audited inventory.settings, inventory.settings.changed).

func (*ScanningHandlers) ScanningPostScanningSafetyRanges

ScanningPostScanningSafetyRanges implements POST /scanning/safety/ranges (admin): "+ New range" where the person is (#842). The inventory adds the range in one transaction with the same rules, attestation, audit row (inventory.settings) and event as the PUT.

func (*ScanningHandlers) ScanningPutScanningSafety

ScanningPutScanningSafety implements PUT /scanning/safety (admin): the inventory validates and stores the block, writes its audit row inventory.settings and publishes inventory.settings.changed.

type ScheduleHandlers

type ScheduleHandlers struct {
	// contains filtered or unexported fields
}

ScheduleHandlers serve the schedules a person can set (core/schedule): GET and PUT /schedules/{owner_key}, POST /schedules/{owner_key}/run and POST /schedules/preview. Core serves them so the one editor works the same for every owner.

func NewScheduleHandlers

func NewScheduleHandlers(s *schedule.Service) *ScheduleHandlers

NewScheduleHandlers returns the handlers over the box's schedule service.

func (*ScheduleHandlers) CoreGetSchedulesOwnerKey

CoreGetSchedulesOwnerKey implements GET /schedules/{owner_key} (viewer).

func (*ScheduleHandlers) CorePostSchedulesOwnerKeyRun

CorePostSchedulesOwnerKeyRun implements POST /schedules/{owner_key}/run (operator; admin for an owner that says so): run once now, audited schedule.run_now.

func (*ScheduleHandlers) CorePostSchedulesPreview

CorePostSchedulesPreview implements POST /schedules/preview (viewer): the next start times of a rule not saved yet.

func (*ScheduleHandlers) CorePutSchedulesOwnerKey

CorePutSchedulesOwnerKey implements PUT /schedules/{owner_key} (operator; admin for an owner that says so): audited schedule.save by core/schedule in the same transaction.

type SchemaSet

type SchemaSet struct {
	Module string
	FS     fs.FS
}

SchemaSet is the migrations of one module, in the order main applies them. The purge builds a scratch database from them to learn what a fresh install holds (seed rows) instead of keeping a second list that would go stale.

type ScopeCost

type ScopeCost struct {
	Addresses     int  `json:"addresses"`
	PassSeconds   int  `json:"pass_seconds"`
	WindowSeconds int  `json:"window_seconds"`
	Windows       int  `json:"windows"`
	WeekWindows   int  `json:"week_windows"`
	FitsWindow    bool `json:"fits_window"`
	FitsWeek      bool `json:"fits_week"`
}

ScopeCost is what one pass of active discovery over a scope costs (ScopeCost in contract.ts).

type ScopeCostInput

type ScopeCostInput struct {
	LANRanges, Exclusions []string
	Days                  []int
	From, To              string
	PacketsPerS           int
}

ScopeCostInput is POST /scanning/safety/estimate: the scope, window and rate as typed in the form.

type SetupScope

type SetupScope interface {
	SetupScope(ctx context.Context, tx *sql.Tx, actor string, lan []string, confirmed bool) error
	Settle(ctx context.Context, tx *sql.Tx, committed bool)
}

SetupScope is the inventory port of POST /core/setup (INV-15). SetupScope writes inside the setup's transaction tx and may refuse the ranges with an *apierr.Error (the whole setup is then refused); Settle is called once that transaction is over, with whether it committed.

type SpanExtract

type SpanExtract struct {
	DNS      bool `json:"dns"`
	TLSSNI   bool `json:"tls_sni"`
	HTTPHost bool `json:"http_host"`
	Flows    bool `json:"flows"`
}

SpanExtract says what is read from mirrored traffic (packet contents are never stored).

type SpanFilter

type SpanFilter struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

SpanFilter is one exclusion filter as stored.

type SpanMeasure

type SpanMeasure struct {
	Verdict    string // off, ok, own_only, no_traffic or no_link
	PPS        int
	OtherMACs  int
	LastPacket time.Time // zero when none yet
}

SpanMeasure is what the passive sensor measured on the SPAN port: the one thing the host cannot count (the number of other MAC addresses and the time of the last packet need a look at the traffic).

type SpanSensor

type SpanSensor interface {
	// SpanStats returns the measured health of the mirrored traffic.
	SpanStats(ctx context.Context) (SpanMeasure, error)
	// SetSpanPort tells the sensor which card to listen on; iface "" with span false stops it.
	SetSpanPort(ctx context.Context, actor, iface string, span bool) error
}

SpanSensor is the port to the passive sensor (module sensor-passive). Both calls are best effort: the page works without it.

type SpanSettings

type SpanSettings struct {
	Enabled    bool         `json:"enabled"`
	Extract    SpanExtract  `json:"extract"`
	Filters    []SpanFilter `json:"filters"`
	CPUPercent int          `json:"cpu_percent"`
	MemoryMB   int          `json:"memory_mb"`
}

SpanSettings is what core keeps of the SPAN capture: the host only knows which card it is.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL