api

package
v0.0.0-...-b90014c Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 69 Imported by: 0

Documentation

Overview

ABOUTME: Site admin delivery management API handlers (cross-org). ABOUTME: List failed/stale deliveries, retry single, bulk retry.

ABOUTME: GET /api/v1/admin/doctor handler — runs system health checks and returns results. ABOUTME: Requires site admin auth. Returns 200 if all pass, 503 if any fail.

ABOUTME: Org-level admin handlers for MFA reset and force password reset. ABOUTME: RBAC: owner targets members/admins; admin targets members; site admin targets anyone.

ABOUTME: Site admin organization management API handlers. ABOUTME: GET list (paginated), PATCH update (tier/suspend), GET usage counts.

ABOUTME: Admin endpoint to reload configuration from the secrets file. ABOUTME: Cross-platform alternative to SIGHUP for triggering config reload.

ABOUTME: Site admin API handler for listing security events (cross-org). ABOUTME: Filterable by event_type, severity, actor_email, date range with keyset pagination.

ABOUTME: Site admin system management API handlers. ABOUTME: Search reindex trigger, runtime config view, cross-org audit log.

ABOUTME: Site admin user management API handlers. ABOUTME: List, disable/enable, unlock, force-password-reset.

ABOUTME: GET /api/v1/admin/version handler — returns build metadata. ABOUTME: Requires site admin auth. Fields set via ldflags at build time.

ABOUTME: HTTP handlers for AI-powered NL search and CVE summarization. ABOUTME: Handles quota enforcement, caching, DSL compilation, and request logging.

ABOUTME: HTTP handler for listing alert events with optional filters and, on request, CVE and rule context. ABOUTME: Alert events are created by the evaluator worker; this handler provides read-only access.

ABOUTME: HTTP handlers for alert rule CRUD and DSL validation. ABOUTME: Validates and compiles DSL on every create/update; returns 202 when activating scan is queued.

ABOUTME: HTTP handlers for API key management: create, list, revoke. ABOUTME: Routes use chi middleware for per-group RBAC enforcement.

ABOUTME: HTTP handler for listing audit log entries with RBAC and enterprise tier gating. ABOUTME: Supports keyset cursor pagination and filtering by entity_type, action, actor_id, and date range.

ABOUTME: HTTP handlers for authentication: register, login, refresh, logout, me. ABOUTME: All auth endpoints live at /api/v1/auth/... and are rate-limited.

ABOUTME: HTTP handlers for email verification: verify-email and resend-verification. ABOUTME: verify-email is public; resend-verification requires authentication.

ABOUTME: HTTP handlers for MFA challenge, verify, enrollment, and management. ABOUTME: All MFA endpoints live at /api/v1/auth/mfa/... and consume pending token cookies.

ABOUTME: HTTP handlers for password reset: forgot-password and reset-password. ABOUTME: Public endpoints at /api/v1/auth/forgot-password and /api/v1/auth/reset-password.

ABOUTME: HTTP handlers for notification channel CRUD and signing secret rotation. ABOUTME: signing_secret is returned only on create and rotate-secret responses — never on GET/LIST/PATCH.

ABOUTME: Handler for POST /orgs/{org_id}/check: which advisories affect each listed component version. ABOUTME: Declares the request and response types the spec documents; check.Results produces the same JSON.

ABOUTME: Request context key types and constants for the api package. ABOUTME: Used by middleware to inject auth state and by handlers to read it.

ABOUTME: Shared contract helpers for Chi JSON handlers. ABOUTME: Produces RFC 9457 Problem Details using huma's ErrorModel/ErrorDetail types directly.

ABOUTME: CORS middleware configuration for cross-origin frontend requests. ABOUTME: Returns allowed origins from config, with dev defaults for localhost dev servers.

ABOUTME: HTTP handlers for CVE listing, detail, and search endpoints. ABOUTME: Supports keyset pagination, faceted search, and full-text search via FTS index.

ABOUTME: HTTP handlers for delivery history list, detail, and replay endpoints. ABOUTME: Replay uses an in-memory per-org rate limiter: max 10 replays per hour.

ABOUTME: Admin API handlers for feed status monitoring and manual triggering. ABOUTME: Exposes feed_sync_state and feed_fetch_log data; enqueues manual re-run jobs.

ABOUTME: HTTP handlers for group management: CRUD, soft-delete, and member management. ABOUTME: Routes use chi middleware for per-group RBAC enforcement.

ABOUTME: Inbound webhook endpoint for custom feed data ingestion. ABOUTME: Accepts CVE patches via POST, validates, and routes each to merge.Ingest.

ABOUTME: DB-backed account lockout manager to prevent brute-force login attacks. ABOUTME: Locks accounts after repeated failed login attempts for a configurable duration.

ABOUTME: Middleware that injects a request-scoped slog logger into the context. ABOUTME: Enriches the logger with request_id from chi's RequestID middleware.

ABOUTME: HTTP metrics middleware that records request count and duration per route pattern. ABOUTME: Uses chi's RoutePattern() for cardinality-safe route labels (no UUIDs in labels).

ABOUTME: Middleware that rejects requests with API keys or secrets in query parameters. ABOUTME: Prevents accidental credential leakage in URLs, server logs, and browser history.

ABOUTME: RequireAuthenticated middleware for JWT cookie or API key Bearer auth. ABOUTME: Injects userID and (for API keys) apiKeyRole into the request context.

ABOUTME: Cache-Control middleware for authenticated responses. ABOUTME: Prevents browsers and proxies from caching sensitive API responses.

ABOUTME: CSRF protection middleware using the custom-header pattern. ABOUTME: Cookie-authenticated state-changing requests must include X-Requested-By: CVErt-Ops.

ABOUTME: RequireOrgRole middleware — enforces org membership and minimum RBAC role. ABOUTME: Caps effective role to the minimum of the org role and any API key role.

ABOUTME: SCIM bearer token authentication middleware. ABOUTME: Mounted on /scim/v2/* only. Separate from RequireAuthenticated (no human actor).

ABOUTME: Middleware that restricts access to site-admin-only routes. ABOUTME: Requires RequireAuthenticated to run first to populate ctxUserID.

ABOUTME: Tier resolution middleware and per-org rate limiting middleware. ABOUTME: Must run after RequireOrgRole (which sets ctxOrgID).

ABOUTME: GitHub OAuth2 login flow: init redirect and callback handler. ABOUTME: Matches on GitHub numeric user ID (never email) per PLAN.md §7.2.

ABOUTME: Google OIDC login flow: init redirect and callback handler. ABOUTME: Matches on Google account sub claim (never email) per PLAN.md §7.2.

ABOUTME: OAuth helper functions: state/nonce generation, cookie management. ABOUTME: Used by GitHub OAuth2 and Google OIDC flow handlers.

ABOUTME: Generic OIDC SSO login and identity linking flows. ABOUTME: Dynamically loads SSO connection config from DB; matches on provider identity.

ABOUTME: Declares each API operation's credentials and minimum role in the served OpenAPI spec. ABOUTME: One table for all operations, checked against the running server by openapi_security_test.go.

ABOUTME: Spec-only Huma operation declarations for Chi-backed routes. ABOUTME: Generates OpenAPI specs without affecting production routing or middleware.

ABOUTME: Per-org API rate limiter keyed by organization UUID. ABOUTME: Supports different rates per org (tier-resolved) with idle eviction.

ABOUTME: HTTP handler for GET /api/v1/orgs/{org_id}/tier. ABOUTME: Returns the org's tier, resolved limits, and current usage counts.

ABOUTME: HTTP handlers for org management: create, read, update, members, invitations. ABOUTME: Routes use chi middleware (not huma.Register) for per-group RBAC enforcement.

ABOUTME: Per-IP in-memory rate limiter for auth endpoints, and client IP resolution ABOUTME: that honours forwarded headers only from TRUSTED_PROXIES.

ABOUTME: Readiness probe handler for /readyz — checks DB, migrations, and worker status. ABOUTME: Returns 200 when all checks pass, 503 when any critical check fails.

ABOUTME: HTTP handlers for scheduled digest report CRUD and channel bindings. ABOUTME: Mirrors the alert-rules + channels handler patterns.

ABOUTME: RBAC Role type with ordered integer constants for permission comparison. ABOUTME: parseRole converts a string role name to a Role value.

ABOUTME: HTTP handlers for saved search CRUD and execution. ABOUTME: Supports private and org-shared visibility with RBAC enforcement.

ABOUTME: HTTP handlers for SCIM config admin CRUD (create, read, update, delete, token rotation). ABOUTME: Standard auth (cookie-based), RFC 9457 errors. Enterprise-tier-gated. Owner-only for mutations.

ABOUTME: SCIM 2.0 discovery endpoints (ServiceProviderConfig, Schemas, ResourceTypes). ABOUTME: Static JSON responses per RFC 7643/7644. Declares supported capabilities to IdPs.

ABOUTME: SCIM 2.0 Group endpoint handlers (RFC 7644 §3). ABOUTME: Mounted as chi handlers on /scim/v2/Groups. Supports create, get, list, replace, patch, delete.

ABOUTME: Notification group sync from SCIM group mappings. ABOUTME: Propagates SCIM group membership changes to notification groups.

ABOUTME: Per-org rate limiter for SCIM endpoints. ABOUTME: Separate from the API rate limiter. Keyed by org_id UUID from context.

ABOUTME: Role recomputation from SCIM group mappings. ABOUTME: Called on group membership change and admin mapping change. Apply-on-write.

ABOUTME: SCIM 2.0 request/response types and JSON helpers (RFC 7643/7644). ABOUTME: Used by all SCIM chi handlers. Separate from huma types.

ABOUTME: SCIM 2.0 User resource handlers (RFC 7643/7644). ABOUTME: Implements create, get, list, replace (PUT), patch, and delete for user provisioning.

ABOUTME: HTTP server struct, constructor, and handler wiring for CVErt Ops. ABOUTME: Holds auth dependencies (store, config, argon2 semaphore) used by handlers.

ABOUTME: HTTP handlers for SSO connection CRUD and email domain management. ABOUTME: Enterprise-only, owner-only. Client secrets are encrypted at rest with AES-256-GCM.

ABOUTME: In-memory cache for org tier and overrides, keyed by org UUID. ABOUTME: Short TTL avoids per-request DB round-trip; invalidated on tier writes.

ABOUTME: HTTP handlers for watchlist and watchlist item management. ABOUTME: Supports package (ecosystem+name), CPE and CVE item types, added singly or replaced as a whole list.

ABOUTME: GET /api/v1/whoami describes the calling credential: for an API key, the key, its org, ABOUTME: the role it acts with, the org's tier and rate limit; for a session, each org the user is active in.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AffectedCPEResponse

type AffectedCPEResponse struct {
	CPE           string `json:"cpe"`
	CPENormalized string `json:"cpe_normalized"`
}

AffectedCPEResponse is the API representation of a cve_affected_cpes row.

type AffectedPackageResponse

type AffectedPackageResponse struct {
	Ecosystem   string  `json:"ecosystem"`
	PackageName string  `json:"package_name"`
	Namespace   *string `json:"namespace,omitzero" nullable:"false"`
	RangeType   *string `json:"range_type,omitzero" nullable:"false"`
	Introduced  *string `json:"introduced,omitzero" nullable:"false"`
	Fixed       *string `json:"fixed,omitzero" nullable:"false"`
}

AffectedPackageResponse is the API representation of a cve_affected_packages row.

type AlertEventCVEContext

type AlertEventCVEContext struct {
	Status      *string  `json:"status" doc:"The CVE's status as the feed sent it."`
	Severity    *string  `json:"severity" doc:"Severity as the feed sent it; compare case-insensitively."`
	CVSSv3Score *float64 `json:"cvss_v3_score" doc:"CVSS v3 base score."`
	CVSSv4Score *float64 `json:"cvss_v4_score" doc:"CVSS v4 base score."`
	InCISAKEV   bool     `json:"in_cisa_kev" doc:"Whether the CVE is in the CISA Known Exploited Vulnerabilities catalog."`
	EPSSScore   *float64 `json:"epss_score" doc:"EPSS probability, 0 to 1; null when not scored."`
}

AlertEventCVEContext is the CVE context of an alert event, read with the list.

type AlertEventRuleContext

type AlertEventRuleContext struct {
	Name                  string                     `json:"name" doc:"The rule's name."`
	Deleted               bool                       `json:"deleted" doc:"The rule has been deleted since the event fired."`
	MatchedWatchlistItems []AlertEventWatchlistMatch `` /* 235-byte string literal not displayed */
}

AlertEventRuleContext is the rule context of an alert event.

type AlertEventWatchlistMatch

type AlertEventWatchlistMatch struct {
	WatchlistID string  `json:"watchlist_id" format:"uuid" doc:"Watchlist ID."`
	ItemID      string  `json:"item_id" format:"uuid" doc:"Watchlist item ID."`
	ItemType    string  `json:"item_type" enum:"cve,package,cpe" doc:"Item type."`
	CveID       *string `json:"cve_id,omitzero" nullable:"false" doc:"For a cve item: the CVE ID."`
	Ecosystem   *string `json:"ecosystem,omitzero" nullable:"false" doc:"For a package item: the ecosystem as listed."`
	PackageName *string `json:"package_name,omitzero" nullable:"false" doc:"For a package item: the package name as listed."`
	Namespace   *string `json:"namespace,omitzero" nullable:"false" doc:"For a package item: the namespace, when listed."`
	CPE         *string `json:"cpe,omitzero" nullable:"false" doc:"For a cpe item: the normalized CPE prefix."`
}

AlertEventWatchlistMatch is a watchlist item that matches an alert event's CVE.

type CNAAffectedResponse

type CNAAffectedResponse struct {
	Vendor        *string              `json:"vendor,omitzero" nullable:"false"`
	Product       *string              `json:"product,omitzero" nullable:"false"`
	PackageName   *string              `json:"package_name,omitzero" nullable:"false"`
	CollectionURL *string              `json:"collection_url,omitzero" nullable:"false"`
	DefaultStatus *string              `` /* 141-byte string literal not displayed */
	Versions      []CNAVersionResponse `json:"versions"`
}

CNAAffectedResponse is the API representation of a cve_cna_affected row.

type CNAVersionChangeResponse

type CNAVersionChangeResponse struct {
	At     string `json:"at,omitempty"`
	Status string `json:"status,omitempty"`
}

CNAVersionChangeResponse is one element of a CNA version's changes list.

type CNAVersionResponse

type CNAVersionResponse struct {
	Version         string                     `` /* 168-byte string literal not displayed */
	LessThan        string                     `json:"less_than,omitempty"`
	LessThanOrEqual string                     `json:"less_than_or_equal,omitempty"`
	Status          string                     `json:"status,omitempty" doc:"affected, unaffected or unknown."`
	VersionType     string                     `json:"version_type,omitempty"`
	Changes         []CNAVersionChangeResponse `json:"changes,omitempty" doc:"Versions inside the range where status stops applying, such as a backported fix."`
}

CNAVersionResponse is one element of a CNA's versions list. Its JSON field names match feed.CNAVersion, the form stored in cve_cna_affected.versions.

type CPEMatchResponse

type CPEMatchResponse struct {
	CPE                   string  `json:"cpe"`
	CPENormalized         string  `json:"cpe_normalized"`
	VersionStartIncluding *string `json:"version_start_including,omitzero" nullable:"false"`
	VersionStartExcluding *string `json:"version_start_excluding,omitzero" nullable:"false"`
	VersionEndIncluding   *string `json:"version_end_including,omitzero" nullable:"false"`
	VersionEndExcluding   *string `json:"version_end_excluding,omitzero" nullable:"false"`
}

CPEMatchResponse is the API representation of a vulnerable cve_cpe_matches row.

type CVEDetail

type CVEDetail struct {
	CVEItem
	CVSSv3Vector       *string                   `json:"cvss_v3_vector,omitzero" nullable:"false"`
	CVSSv4Vector       *string                   `json:"cvss_v4_vector,omitzero" nullable:"false"`
	AffectedPackages   []AffectedPackageResponse `json:"affected_packages"`
	AffectedCPEs       []AffectedCPEResponse     `` /* 234-byte string literal not displayed */
	AffectedCPEMatches []CPEMatchResponse        `` /* 305-byte string literal not displayed */
	CNAAffected        []CNAAffectedResponse     `` /* 390-byte string literal not displayed */
	References         []ReferenceResponse       `json:"references"`
}

CVEDetail extends CVEItem with child-table data.

type CVEItem

type CVEItem struct {
	CVEID              string   `json:"cve_id"`
	Status             *string  `json:"status,omitzero" nullable:"false"`
	DatePublished      *string  `json:"date_published,omitzero" nullable:"false"` // RFC3339
	DateModified       string   `json:"date_modified"`                            // RFC3339
	DateFirstSeen      string   `json:"date_first_seen"`                          // RFC3339
	DescriptionPrimary *string  `json:"description_primary,omitzero" nullable:"false"`
	Severity           *string  `json:"severity,omitzero" nullable:"false"`
	CVSSv3Score        *float64 `json:"cvss_v3_score,omitempty"`
	CVSSv4Score        *float64 `json:"cvss_v4_score,omitempty"`
	CVSSScoreDiverges  bool     `json:"cvss_score_diverges"`
	CWEIDs             []string `json:"cwe_ids"`
	ExploitAvailable   bool     `json:"exploit_available"`
	InCISAKEV          bool     `json:"in_cisa_kev"`
	EPSSScore          *float64 `json:"epss_score,omitempty"`
}

CVEItem is the list-view representation of a CVE (no child tables).

type CVESourceResponse

type CVESourceResponse struct {
	SourceName         string          `json:"source_name"`
	SourceID           *string         `json:"source_id,omitzero" nullable:"false"`
	NormalizedJSON     json.RawMessage `json:"normalized_json"`
	SourceDateModified *string         `json:"source_date_modified,omitzero" nullable:"false"` // RFC3339
	SourceURL          *string         `json:"source_url,omitzero" nullable:"false"`
	IngestedAt         string          `json:"ingested_at"` // RFC3339
}

CVESourceResponse is the API representation of a cve_sources row.

type ChannelEntry

type ChannelEntry struct {
	ID        string          `json:"id"`
	OrgID     string          `json:"org_id"`
	Name      string          `json:"name"`
	Type      string          `json:"type"`
	Config    json.RawMessage `` /* 238-byte string literal not displayed */
	CreatedAt string          `json:"created_at"`
	UpdatedAt string          `json:"updated_at"`
}

ChannelEntry is the API shape of a notification channel. It is exported so huma documents its fields where channelCreateEntry embeds it.

type CheckAdvisory

type CheckAdvisory struct {
	AdvisoryID         string              `json:"advisory_id" doc:"Advisory or CVE ID; works with GET /cves/{cve_id}."`
	CVEIDs             []string            `json:"cve_ids" doc:"CVE IDs the advisory names."`
	Verdict            string              `json:"verdict" enum:"affected,cannot_evaluate" doc:"This advisory's verdict for the version."`
	Reason             *string             `` /* 407-byte string literal not displayed */
	FixedVersion       *string             `json:"fixed_version" doc:"The lowest version the advisory data no longer reports as affected; null when none is known."`
	FixMajor           *string             `` /* 152-byte string literal not displayed */
	FixEcosystem       *string             `` /* 327-byte string literal not displayed */
	MatchedRanges      []CheckMatchedRange `json:"matched_ranges" doc:"Ranges that contain the version. At most 20."`
	MatchedRangesTotal int                 `json:"matched_ranges_total" doc:"How many ranges contain the version. Verdicts and fixes use all of them."`
	Severity           *string             `json:"severity" doc:"The advisory's severity, as the feed sent it."`
	CVSSv3Score        *float64            `json:"cvss_v3_score" doc:"The advisory's CVSS v3 base score."`
	EPSSScore          *float64            `json:"epss_score" doc:"Highest EPSS score of the CVEs in cve_ids; null when none of them has a score, which means not known."`
	InCISAKEV          *bool               `` /* 149-byte string literal not displayed */
}

CheckAdvisory is one listed advisory.

type CheckComponent

type CheckComponent struct {
	Kind      string `json:"kind" enum:"package,product" doc:"package for the purl and ecosystem forms, product for the CPE form."`
	Ecosystem string `json:"ecosystem,omitempty" doc:"OSV ecosystem, for a package."`
	Name      string `json:"name,omitempty" doc:"Package name as given, for a package."`
	Part      string `json:"part,omitempty" doc:"CPE part, lower-cased, for a product."`
	Vendor    string `json:"vendor,omitempty" doc:"CPE vendor, lower-cased, for a product."`
	Product   string `json:"product,omitempty" doc:"CPE product, lower-cased, for a product."`
	Version   string `json:"version" doc:"The version as compared."`
	// contains filtered or unexported fields
}

CheckComponent is a package (ecosystem and name) or a product (CPE part, vendor and product), with the version as compared.

type CheckCounts

type CheckCounts struct {
	Affected       int `json:"affected" doc:"Advisory records that report the version affected."`
	CannotEvaluate int `json:"cannot_evaluate" doc:"Advisory records that could not be evaluated for the version."`
	NotAffected    int `json:"not_affected" doc:"Advisory records that do not report the version affected."`
	Retracted      int `json:"retracted" doc:"Advisory records whose CVE is rejected or withdrawn; they take no part in the status."`

	CannotEvaluateByReason map[string]int `` /* 224-byte string literal not displayed */
}

CheckCounts are of advisory records, over every advisory found for the item.

type CheckFeedStatus

type CheckFeedStatus struct {
	Name          string     `json:"name" doc:"Feed name, as feed_sync_state names it."`
	Complete      bool       `json:"complete" doc:"The feed has finished a full walk and succeeded within 7 days."`
	LastSuccessAt *time.Time `json:"last_success_at" doc:"When the feed last succeeded; null if never."`
}

CheckFeedStatus is one feed's completeness.

type CheckItem

type CheckItem struct {
	ID        string `json:"id,omitempty" doc:"Caller's identifier for the item, echoed back. At most 128 characters."`
	Purl      string `` /* 216-byte string literal not displayed */
	Ecosystem string `json:"ecosystem,omitempty" doc:"OSV ecosystem name; a distribution ecosystem must name a release, such as Debian:13."`
	Name      string `json:"name,omitempty" doc:"Package name in the ecosystem. At most 512 characters."`
	CPE       string `json:"cpe,omitempty" doc:"CPE 2.3 formatted string with literal part, vendor and product. At most 512 characters."`
	Version   string `` /* 148-byte string literal not displayed */
}

CheckItem is one component: a purl alone, an ecosystem with a name and version, or a CPE with a version. Its fields match check.RawItem, which it converts to.

type CheckItemError

type CheckItemError struct {
	Code    string `` /* 326-byte string literal not displayed */
	Message string `json:"message" doc:"A fixed sentence explaining the code. It never repeats the item's values."`
	// contains filtered or unexported fields
}

CheckItemError is why an item could not be read.

type CheckItemResult

type CheckItemResult struct {
	Index               int             `json:"index" doc:"Position of the item in the request."`
	ID                  *string         `json:"id" doc:"The item's id, or null when it had none or it was too long."`
	Status              string          `` /* 895-byte string literal not displayed */
	Reason              *string         `` /* 1880-byte string literal not displayed */
	Component           *CheckComponent `json:"component" doc:"What the item was checked as; null for an invalid item."`
	DataComplete        bool            `json:"data_complete" doc:"Every feed this item depends on is complete."`
	Counts              CheckCounts     `json:"counts" doc:"Counts of advisory records found for the item, by verdict."`
	Advisories          []CheckAdvisory `` /* 159-byte string literal not displayed */
	AdvisoriesTruncated bool            `json:"advisories_truncated" doc:"More advisories applied than are listed. Status and counts use all of them."`
	Warnings            []string        `json:"warnings" enum:"cna_product_not_mapped" doc:"Warnings about the answer."`
	Error               *CheckItemError `json:"error" doc:"Why the item could not be read; null unless status is invalid."`
}

CheckItemResult is the answer for one item.

type CheckMatchedRange

type CheckMatchedRange struct {
	Evidence     string `` /* 145-byte string literal not displayed */
	CPE          string `json:"cpe,omitempty" doc:"The CPE of an NVD CPE match."`
	Ecosystem    string `` /* 192-byte string literal not displayed */
	Introduced   string `json:"introduced" doc:"Lower bound, inclusive; empty when the range has none."`
	Fixed        string `json:"fixed,omitempty" doc:"Upper bound, exclusive."`
	LastAffected string `json:"last_affected,omitempty" doc:"Upper bound, inclusive."`
}

CheckMatchedRange is one range that contains the version. An absent bound is omitted.

type CheckRequest

type CheckRequest struct {
	Items []CheckItem `` /* 187-byte string literal not displayed */
}

CheckRequest is the version check request body.

type CheckResults

type CheckResults struct {
	DataComplete bool              `json:"data_complete" doc:"Every feed a valid item depends on has finished a full walk and succeeded within 7 days."`
	Feeds        []CheckFeedStatus `json:"feeds" doc:"The feeds the valid items depend on, sorted by name."`
	Results      []CheckItemResult `json:"results" doc:"One result per request item, in request order."`
}

CheckResults is the version check response. The handler writes check.Results.

type DeliveryEntry

type DeliveryEntry struct {
	ID              string  `json:"id"`
	OrgID           string  `json:"org_id"`
	RuleID          string  `json:"rule_id"`
	ChannelID       string  `json:"channel_id"`
	Kind            string  `json:"kind"`
	ReportID        *string `json:"report_id,omitzero" nullable:"false"`
	Status          string  `json:"status"`
	AttemptCount    int32   `json:"attempt_count"`
	SendAfter       string  `json:"send_after"`
	LastAttemptedAt *string `json:"last_attempted_at,omitzero" nullable:"false"`
	DeliveredAt     *string `json:"delivered_at,omitzero" nullable:"false"`
	LastError       *string `json:"last_error,omitzero" nullable:"false"`
	CreatedAt       string  `json:"created_at"`
	UpdatedAt       string  `json:"updated_at"`
}

DeliveryEntry is the list item shape (no payload to keep list responses small). It is exported so huma documents its fields where deliveryDetail embeds it.

type FeedLogEntry

type FeedLogEntry struct {
	ID            uuid.UUID  `json:"id"`
	StartedAt     time.Time  `json:"started_at"`
	EndedAt       *time.Time `json:"ended_at,omitempty"`
	Status        string     `json:"status"`
	ItemsFetched  int32      `json:"items_fetched"`
	ItemsUpserted int32      `json:"items_upserted"`
	ErrorSummary  string     `json:"error_summary,omitempty"`
}

FeedLogEntry is a single fetch log row.

type FeedStatusEntry

type FeedStatusEntry struct {
	FeedName            string         `json:"feed_name"`
	LastSuccessAt       *time.Time     `json:"last_success_at,omitempty"`
	LastAttemptAt       *time.Time     `json:"last_attempt_at,omitempty"`
	ConsecutiveFailures int32          `json:"consecutive_failures"`
	LastError           string         `json:"last_error,omitempty"`
	BackoffUntil        *time.Time     `json:"backoff_until,omitempty"`
	PausedAt            *time.Time     `json:"paused_at,omitempty"`
	RecentLogs          []FeedLogEntry `json:"recent_logs"`
}

FeedStatusEntry represents one feed's sync state and recent fetch history.

type GetCVEInput

type GetCVEInput struct {
	CVEID string `path:"cve_id" doc:"CVE identifier (e.g. CVE-2024-12345)"`
}

GetCVEInput defines path parameters for the single-CVE endpoint.

type GetCVEOutput

type GetCVEOutput struct {
	Body *CVEDetail
}

GetCVEOutput is the response for GET /cves/{cve_id}.

type GetCVESourcesBody

type GetCVESourcesBody struct {
	Sources []CVESourceResponse `json:"sources"`
}

GetCVESourcesBody wraps the list of source payloads.

type GetCVESourcesInput

type GetCVESourcesInput struct {
	CVEID string `path:"cve_id" doc:"CVE identifier"`
}

GetCVESourcesInput defines path parameters for the sources endpoint.

type GetCVESourcesOutput

type GetCVESourcesOutput struct {
	Body *GetCVESourcesBody
}

GetCVESourcesOutput is the response for GET /cves/{cve_id}/sources.

type ListCVEsBody

type ListCVEsBody struct {
	Items      []CVEItem `json:"items"`
	NextCursor string    `json:"next_cursor,omitempty"`
}

ListCVEsBody is the JSON body of the list response.

type ListCVEsInput

type ListCVEsInput struct {
	Q           string   `query:"q" doc:"Full-text search query (supports quoted phrases and negation)"`
	Severity    []string `query:"severity" doc:"Filter by severity: critical, high, medium, low, unknown"`
	DateFrom    string   `query:"date_from" doc:"Filter CVEs modified on or after this date (ISO 8601); empty = no filter"`
	DateTo      string   `query:"date_to" doc:"Filter CVEs modified on or before this date (ISO 8601); empty = no filter"`
	CWEID       string   `query:"cwe_id" doc:"Filter by CWE ID (e.g. CWE-79); empty = no filter"`
	Ecosystem   string   `` /* 146-byte string literal not displayed */
	PackageName string   `query:"package_name" doc:"Filter by affected package name (requires ecosystem); empty = no filter"`
	// Boolean filters: "true", "false", or "" (no filter).
	InCISAKEV    string `query:"in_cisa_kev" doc:"Filter by CISA KEV status: 'true', 'false', or empty for no filter"`
	ExploitAvail string `query:"exploit_available" doc:"Filter by exploit availability: 'true', 'false', or empty for no filter"`
	Cursor       string `query:"cursor" doc:"Opaque pagination cursor returned in the previous response"`
	Limit        int    `query:"limit" minimum:"1" maximum:"100" default:"25" doc:"Page size (max 100)"`

	// Optional numeric filters resolved from raw query string by Resolve.
	// Not tagged with query: because huma panics on pointer types in query params.
	CVSSMin *float64
	CVSSMax *float64
	EPSSMin *float64
	EPSSMax *float64
	// contains filtered or unexported fields
}

ListCVEsInput defines query parameters for the paginated CVE list.

huma v2 does not support pointer types in query/path/header/form parameters (panics at route registration). Simple optional string params use empty string as "not set". Numeric and boolean optionals that require pointer semantics (0 and false are valid filter values) are parsed from raw query strings in the Resolve method.

func (*ListCVEsInput) Resolve

func (i *ListCVEsInput) Resolve(ctx huma.Context, _ *huma.PathBuffer) []error

Resolve implements huma.Resolver. It delegates to resolveOptionalFilters so the parsing logic can be tested independently of the full huma.Context interface.

type ListCVEsOutput

type ListCVEsOutput struct {
	Body *ListCVEsBody
}

ListCVEsOutput is the response body for GET /cves.

type ReferenceResponse

type ReferenceResponse struct {
	URL  string   `json:"url"`
	Tags []string `json:"tags"`
}

ReferenceResponse is the API representation of a cve_references row.

type Role

type Role int

Role represents an RBAC permission level. Higher integer values grant more permissions.

const (
	RoleViewer Role = 1 // read-only access
	RoleMember Role = 2 // standard org member
	RoleAdmin  Role = 3 // org administrator
	RoleOwner  Role = 4 // full control including org deletion
)

Role permission level constants, ordered from least to most privileged.

func (Role) String

func (r Role) String() string

String returns the role's name as stored in the database.

type SCIMError

type SCIMError struct {
	Schemas  []string `json:"schemas"`
	Status   string   `json:"status"`
	SCIMType string   `json:"scimType,omitempty"`
	Detail   string   `json:"detail"`
}

SCIMError represents an RFC 7644 §3.12 error response.

type SCIMFilterExpr

type SCIMFilterExpr struct {
	Attr  string
	Op    string
	Value string
}

SCIMFilterExpr represents a parsed SCIM filter expression (attr op value).

type SCIMGroup

type SCIMGroup struct {
	Schemas     []string          `json:"schemas"`
	ID          string            `json:"id"`
	ExternalID  string            `json:"externalId,omitempty"`
	DisplayName string            `json:"displayName"`
	Members     []SCIMGroupMember `json:"members"`
	Meta        SCIMMeta          `json:"meta"`
}

SCIMGroup represents a SCIM 2.0 Group resource (RFC 7643 §4.2).

type SCIMGroupMember

type SCIMGroupMember struct {
	Value   string `json:"value"`
	Display string `json:"display,omitempty"`
	Ref     string `json:"$ref,omitempty"`
}

SCIMGroupMember represents a member reference within a SCIM Group.

type SCIMListResponse

type SCIMListResponse struct {
	Schemas      []string `json:"schemas"`
	TotalResults int      `json:"totalResults"`
	ItemsPerPage int      `json:"itemsPerPage"`
	StartIndex   int      `json:"startIndex"`
	Resources    []any    `json:"Resources"`
}

SCIMListResponse represents a SCIM 2.0 ListResponse (RFC 7644 §3.4.2).

type SCIMMeta

type SCIMMeta struct {
	ResourceType string `json:"resourceType"`
	Created      string `json:"created"`
	LastModified string `json:"lastModified"`
	Location     string `json:"location"`
}

SCIMMeta represents resource metadata in SCIM responses.

type SCIMPatchOp

type SCIMPatchOp struct {
	Schemas    []string             `json:"schemas"`
	Operations []SCIMPatchOperation `json:"Operations"`
}

SCIMPatchOp represents a SCIM 2.0 PATCH request (RFC 7644 §3.5.2).

type SCIMPatchOperation

type SCIMPatchOperation struct {
	Op    string          `json:"op"`
	Path  string          `json:"path,omitempty"`
	Value json.RawMessage `json:"value"`
}

SCIMPatchOperation represents a single operation within a SCIM PATCH request.

type SCIMUser

type SCIMUser struct {
	Schemas     []string `json:"schemas"`
	ID          string   `json:"id"`
	ExternalID  string   `json:"externalId"`
	UserName    string   `json:"userName"`
	DisplayName string   `json:"displayName"`
	Active      bool     `json:"active"`
	Meta        SCIMMeta `json:"meta"`
}

SCIMUser represents a SCIM 2.0 User resource (RFC 7643 §4.1).

type Server

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

Server holds the dependencies for the HTTP layer.

func NewServer

func NewServer(s *store.Store, cfg *config.Config, deps ServerDeps) (*Server, error)

NewServer creates a Server. Returns an error if Google OIDC initialization fails. If cfg.GoogleClientID is empty, Google OIDC is skipped.

func (*Server) AddHealthCheck

func (srv *Server) AddHealthCheck(check func() bool)

AddHealthCheck registers an extra readiness check for the /readyz endpoint. Must be called before Handler() — not safe for concurrent use.

func (*Server) Close

func (srv *Server) Close()

Close releases resources held by the server (e.g., the rate limiter cleanup goroutine).

func (*Server) Handler

func (srv *Server) Handler() http.Handler

Handler builds and returns the http.Handler.

func (*Server) RequireAuthenticated

func (srv *Server) RequireAuthenticated() func(http.Handler) http.Handler

RequireAuthenticated returns a middleware that requires a valid JWT access-token cookie or an API key Bearer token. On success it injects ctxUserID (and for API keys also ctxAPIKeyRole) into the request context.

func (*Server) RequireOrgRole

func (srv *Server) RequireOrgRole(minRole Role) func(http.Handler) http.Handler

RequireOrgRole returns a middleware that verifies the authenticated user is a member of the org in the URL ({org_id}) with at least minRole. For API key requests the effective role is capped to min(orgRole, apiKeyRole). On success it injects ctxOrgID and ctxRole into the request context.

Must run after RequireAuthenticated.

func (*Server) RequireSiteAdmin

func (srv *Server) RequireSiteAdmin() func(http.Handler) http.Handler

RequireSiteAdmin returns middleware that rejects requests from non-site-admin users. It expects ctxUserID to be set by RequireAuthenticated upstream. API keys are always rejected: a key is scoped to one org and never carries its creator's site-admin power, whatever the key's role.

type ServerDeps

type ServerDeps struct {
	AlertCache            *alert.RuleCache
	AlertEvaluator        *alert.Evaluator
	LLM                   ai.LLMClient
	AuditWriter           *audit.Writer
	EventWriter           *secure.EventWriter
	ConfigHolder          *config.Holder
	RescanFunc            func() // called after successful config reload
	ExpectedSchemaVersion int
	VersionInfo           VersionInfo
}

ServerDeps holds optional dependencies injected at construction time. All fields are optional (nil/zero means "not configured").

type VersionInfo

type VersionInfo struct {
	Version   string `json:"version"`
	Commit    string `json:"commit"`
	BuildTime string `json:"build_time"`
}

VersionInfo holds build metadata set via ldflags at compile time.

Jump to

Keyboard shortcuts

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