exposure

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: GPL-3.0 Imports: 14 Imported by: 0 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 exposure implements the application service for the exposure bounded context — orchestrates pkg/domain/exposure entities and cross-cutting concerns (audit, notifications, RBAC).

Index

Constants

This section is empty.

Variables

View Source
var ErrTicketingNotConfigured = fmt.Errorf("%w: campaign ticketing is not configured", shared.ErrValidation)

ErrTicketingNotConfigured is returned by CreateTicket when no epic creator / ticket store is wired (e.g. no Jira integration configured).

Functions

This section is empty.

Types

type BulkIngestResult added in v0.4.0

type BulkIngestResult struct {
	Events   []*exposuredom.ExposureEvent
	Failures []IngestItemError
}

BulkIngestResult carries the successfully-ingested events plus the per-item validation failures that were partial-success dropped. This lets callers report what was rejected instead of silently returning a lower count.

type CampaignEpicCreator added in v0.3.0

type CampaignEpicCreator interface {
	CreateEpic(ctx context.Context, tenantID shared.ID, projectKey, summary, description string, labels []string) (issueKey, issueURL string, err error)
	// TransitionEpic moves the linked epic to a target status name (echo-safe,
	// comment fallback). Best-effort outbound campaign→epic status sync.
	TransitionEpic(ctx context.Context, tenantID shared.ID, issueKey, targetStatus, comment string) error
}

CampaignEpicCreator creates and transitions an external tracker epic for a tenant. Implemented by *jira.SyncService. Declared here with primitive types so this package needs no dependency on the jira package.

type CampaignFindingResolver added in v0.4.0

type CampaignFindingResolver interface {
	ResolveOpenByFilter(ctx context.Context, tenantID string, filter vulnerability.FindingFilter, in CampaignResolveInput) (resolvedCount int, err error)
}

CampaignFindingResolver bulk-resolves the OPEN findings matching a filter, turning a campaign from a passive progress tracker into an active closer (RFC-015 Phase 3). Nil → the resolve action is unavailable. Implemented by an adapter over the finding bulk-status path + its abuse guard.

type CampaignKeyResolver added in v0.4.0

type CampaignKeyResolver interface {
	// CountByKey returns (total, resolved) findings sharing the remediation key.
	CountByKey(ctx context.Context, tenantID shared.ID, key string) (total, resolved int64, err error)
	// ResolveGroupByKey bulk-resolves the OPEN findings under the key, reusing
	// the same guarded bulk-status path as the standalone group resolve.
	ResolveGroupByKey(ctx context.Context, tenantID string, key string, in CampaignResolveInput) (resolvedCount int, err error)
}

CampaignKeyResolver serves campaigns scoped to a remediation-group key (a "solution family" — every finding one fix resolves). Progress and resolution for such a campaign are computed from the remediation side-table, NOT from a generic FindingFilter (the key isn't expressible as one). Nil → keyed campaigns cannot compute progress or resolve. Implemented by an adapter over the remediation key repository + group resolver at the composition root.

type CampaignResolveInput added in v0.4.0

type CampaignResolveInput struct {
	Status              string // fix_applied (default) or resolved
	Resolution          string
	ActorID             string
	HasVerifyPermission bool
	Approved            bool
}

CampaignResolveInput parameterizes a campaign resolve.

type CampaignTicketInfo added in v0.3.0

type CampaignTicketInfo struct {
	CampaignID     string `json:"campaign_id"`
	Provider       string `json:"provider"`
	IssueKey       string `json:"issue_key"`
	IssueURL       string `json:"issue_url"`
	AlreadyExisted bool   `json:"already_existed"`
}

CampaignTicketInfo describes a campaign's external tracker link.

type CampaignTicketLink struct {
	Provider string `json:"provider"`
	IssueKey string `json:"issue_key"`
	IssueURL string `json:"issue_url"`
}

CampaignTicketLink is the external tracker link surfaced on a campaign in read responses (so the UI can show / link to the epic).

type ChangeStateInput

type ChangeStateInput struct {
	ExposureID string `validate:"required,uuid"`
	NewState   string `validate:"required"`
	UserID     string `validate:"required,uuid"`
	Reason     string `validate:"max=500"`
}

ChangeStateInput represents the input for changing exposure state.

type CreateExposureInput

type CreateExposureInput struct {
	TenantID string `validate:"required,uuid"`

	AssetID     string         `validate:"omitempty,uuid"`
	EventType   string         `validate:"required"`
	Severity    string         `validate:"required"`
	Title       string         `validate:"required,min=1,max=500"`
	Description string         `validate:"max=2000"`
	Source      string         `validate:"required,max=100"`
	Details     map[string]any `validate:"omitempty"`
}

CreateExposureInput represents the input for creating an exposure event.

type CreateRemediationCampaignInput

type CreateRemediationCampaignInput struct {
	TenantID      string
	Name          string
	Description   string
	Priority      string
	FindingFilter map[string]any
	AssignedTo    string
	AssignedTeam  string
	StartDate     string
	DueDate       string
	Tags          []string
	ActorID       string
}

CreateRemediationCampaignInput holds input for creating a campaign.

type ExposureService

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

ExposureService handles exposure event business operations.

func NewExposureService

func NewExposureService(
	repo exposuredom.Repository,
	historyRepo exposuredom.StateHistoryRepository,
	log *logger.Logger,
) *ExposureService

NewExposureService creates a new ExposureService.

func (*ExposureService) AcceptExposure

func (s *ExposureService) AcceptExposure(ctx context.Context, tenantID, exposureID, userID, notes string) (*exposuredom.ExposureEvent, error)

AcceptExposure marks an exposure event as accepted risk.

func (*ExposureService) BulkIngestExposures

func (s *ExposureService) BulkIngestExposures(ctx context.Context, inputs []CreateExposureInput) ([]*exposuredom.ExposureEvent, error)

BulkIngestExposures ingests multiple exposure events, returning only the successfully-created events. Retained for callers/tests that don't need the per-item failure report; delegates to BulkIngestExposuresReport. OPTIMIZED: Uses batch upsert instead of individual upserts to reduce N+1 queries.

func (*ExposureService) BulkIngestExposuresReport added in v0.4.0

func (s *ExposureService) BulkIngestExposuresReport(ctx context.Context, inputs []CreateExposureInput) (BulkIngestResult, error)

BulkIngestExposuresReport ingests multiple exposure events with partial success: items that fail enum/asset validation are dropped (not fatal), and reported back in Result.Failures so the caller can surface them.

func (*ExposureService) CreateExposure

CreateExposure creates a new exposure event.

func (*ExposureService) DeleteExposure

func (s *ExposureService) DeleteExposure(ctx context.Context, exposureID, tenantID string) error

DeleteExposure deletes an exposure event.

func (*ExposureService) GetExposure

func (s *ExposureService) GetExposure(ctx context.Context, eventID string) (*exposuredom.ExposureEvent, error)

GetExposure retrieves an exposure event by ID.

func (*ExposureService) GetExposureSecure

func (s *ExposureService) GetExposureSecure(ctx context.Context, tenantID, eventID string) (*exposuredom.ExposureEvent, error)

GetExposureSecure retrieves an exposure event by tenant and ID (tenant-scoped access control).

func (*ExposureService) GetExposureStats

func (s *ExposureService) GetExposureStats(ctx context.Context, tenantID string) (map[string]any, error)

GetExposureStats returns statistics for a tenant.

func (*ExposureService) GetStateHistory

func (s *ExposureService) GetStateHistory(ctx context.Context, tenantID, exposureID string) ([]*exposuredom.StateHistory, error)

GetStateHistory retrieves the state change history for an exposure event. Scoped to the caller's tenant: it first verifies the exposure belongs to the tenant (GetExposureSecure returns NotFound cross-tenant) — otherwise any authenticated user with findings:read could read any tenant's exposure history (state changes, reasons, changed_by) by guessing the UUID.

func (*ExposureService) IngestExposure

IngestExposure creates or updates an exposure event based on fingerprint (deduplication).

func (*ExposureService) ListExposures

ListExposures lists exposure events with filtering and pagination.

func (*ExposureService) MarkFalsePositive

func (s *ExposureService) MarkFalsePositive(ctx context.Context, tenantID, exposureID, userID, notes string) (*exposuredom.ExposureEvent, error)

MarkFalsePositive marks an exposure event as a false positive.

func (*ExposureService) ReactivateExposure

func (s *ExposureService) ReactivateExposure(ctx context.Context, tenantID, exposureID, userID string) (*exposuredom.ExposureEvent, error)

ReactivateExposure marks an exposure event as active again. tenantID is required — prevents IDOR where user in tenant A reactivates a resolved exposure in tenant B (restarts their SLA clock, floods their SOC with re-alerts).

func (*ExposureService) ResolveExposure

func (s *ExposureService) ResolveExposure(ctx context.Context, tenantID, exposureID, userID, notes string) (*exposuredom.ExposureEvent, error)

ResolveExposure marks an exposure event as resolved. tenantID is required — the lookup is scoped to (tenantID, exposureID) so a caller from tenant A cannot flip an exposure owned by tenant B.

func (*ExposureService) SetOutboxService

func (s *ExposureService) SetOutboxService(db *sql.DB, svc *outbox.Service)

SetOutboxService sets the notification service for transactional outbox pattern.

type FindingCounter added in v0.3.0

type FindingCounter interface {
	Count(ctx context.Context, filter vulnerability.FindingFilter) (int64, error)
}

FindingCounter is the narrow slice of the finding repository the campaign service needs to compute progress: how many findings match a filter. Satisfied by *postgres.FindingRepository.

type IngestItemError added in v0.4.0

type IngestItemError struct {
	Index  int    `json:"index"`
	Reason string `json:"reason"`
}

IngestItemError describes a single input item that was dropped during bulk ingest because it failed enum/asset validation. Index is the item's position in the request slice; Reason is a short human-readable cause.

type ListExposuresInput

type ListExposuresInput struct {
	TenantID string

	AssetID         string
	EventTypes      []string
	Severities      []string
	States          []string
	Sources         []string
	Search          string
	FirstSeenAfter  int64
	FirstSeenBefore int64
	LastSeenAfter   int64
	LastSeenBefore  int64
	Page            int
	PerPage         int
	SortBy          string
	SortOrder       string
}

ListExposuresInput represents the input for listing exposure events.

type RemediationCampaignService

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

RemediationCampaignService manages remediation campaigns.

func NewRemediationCampaignService

func NewRemediationCampaignService(repo remediation.CampaignRepository, log *logger.Logger) *RemediationCampaignService

NewRemediationCampaignService creates a new service.

func (*RemediationCampaignService) CampaignTicketFor added in v0.3.0

func (s *RemediationCampaignService) CampaignTicketFor(ctx context.Context, tenantID, campaignID shared.ID) (*CampaignTicketLink, error)

CampaignTicketFor returns the campaign's linked ticket, or nil when there is none / ticketing isn't wired. Never errors on "no link" — absence is normal.

func (*RemediationCampaignService) CampaignTicketsFor added in v0.3.0

func (s *RemediationCampaignService) CampaignTicketsFor(ctx context.Context, tenantID shared.ID, campaignIDs []shared.ID) (map[string]*CampaignTicketLink, error)

CampaignTicketsFor batch-loads ticket links for the given campaigns, keyed by campaign id string. Campaigns with no link are absent. Returns an empty map when ticketing isn't wired.

func (*RemediationCampaignService) CreateCampaign

CreateCampaign creates a new remediation campaign.

func (*RemediationCampaignService) CreateTicket added in v0.3.0

func (s *RemediationCampaignService) CreateTicket(ctx context.Context, tenantID, campaignID, projectKey string) (*CampaignTicketInfo, error)

CreateTicket creates a Jira epic for a campaign and links it. Idempotent: if the campaign already has a Jira ticket, the existing link is returned without creating a duplicate epic. Requires the ticketing integration to be wired (SetTicketing) and the tenant to have a connected Jira integration.

func (*RemediationCampaignService) DeleteCampaign

func (s *RemediationCampaignService) DeleteCampaign(ctx context.Context, tenantID, campaignID string) error

DeleteCampaign deletes a campaign.

func (*RemediationCampaignService) GetCampaign

func (s *RemediationCampaignService) GetCampaign(ctx context.Context, tenantID, campaignID string) (*remediation.Campaign, error)

GetCampaign retrieves a campaign, refreshing its finding counts live so the detail view always reflects current finding statuses. The recompute is best-effort: on any error the last-persisted counts are returned unchanged.

func (*RemediationCampaignService) HandleEpicStatusChange added in v0.3.0

func (s *RemediationCampaignService) HandleEpicStatusChange(ctx context.Context, tenantID shared.ID, issueKey, jiraStatus string) error

HandleEpicStatusChange is the inbound half of campaign↔epic sync: when a Jira webhook reports a campaign's linked epic moved to a done-ish status, the campaign is marked completed. No-op when: ticketing is unwired, the status isn't a done state, the issue isn't a campaign epic, or the campaign is already terminal / not in a completable state. Idempotent and loop-safe — it persists via repo.Update directly (not UpdateCampaignStatus), so it does NOT re-trigger the outbound epic transition.

func (*RemediationCampaignService) ListCampaigns

ListCampaigns lists campaigns with filtering.

func (*RemediationCampaignService) ReconcileProgress added in v0.3.0

func (s *RemediationCampaignService) ReconcileProgress(ctx context.Context) (int, error)

ReconcileProgress refreshes finding counts for every non-terminal campaign across all tenants, auto-completing any whose findings are all resolved. Returns the number of campaigns whose persisted state changed. Driven by the remediation-progress controller. A failure on one campaign is logged and does not abort the sweep.

func (*RemediationCampaignService) RefreshCampaignProgress added in v0.3.0

func (s *RemediationCampaignService) RefreshCampaignProgress(ctx context.Context, tenantID, campaignID string) (*remediation.Campaign, error)

RefreshCampaignProgress recomputes a single campaign's finding counts, applies auto-complete when every finding is resolved, and persists the result. Returns the up-to-date campaign. This is the on-demand path behind the "refresh" endpoint; the controller drives the same logic in bulk.

func (*RemediationCampaignService) ResolveCampaignFindings added in v0.4.0

func (s *RemediationCampaignService) ResolveCampaignFindings(ctx context.Context, tenantID, campaignID string, in CampaignResolveInput) (int, error)

ResolveCampaignFindings resolves every OPEN finding matching the campaign's filter in one action — reusing the finding bulk-status path + abuse guard. Defaults to fix_applied ("patched, pending rescan verification"). Returns the number of findings transitioned.

func (*RemediationCampaignService) SetFindingCounter added in v0.3.0

func (s *RemediationCampaignService) SetFindingCounter(c FindingCounter)

SetFindingCounter wires the finding counter used to compute campaign progress. When unset, progress stays at zero (the service still functions as plain CRUD). Kept as a setter so the constructor signature is stable and to avoid an import cycle at the composition root.

func (*RemediationCampaignService) SetFindingResolver added in v0.4.0

func (s *RemediationCampaignService) SetFindingResolver(r CampaignFindingResolver)

SetFindingResolver wires the bulk resolver that makes ResolveCampaignFindings available (RFC-015 Phase 3). When unset, the resolve action is unavailable.

func (*RemediationCampaignService) SetKeyResolver added in v0.4.0

func (s *RemediationCampaignService) SetKeyResolver(r CampaignKeyResolver)

SetKeyResolver wires progress + resolution for campaigns scoped to a remediation-group key (a solution family). When unset, such campaigns keep zero progress and their resolve fails closed (never a tenant-wide resolve).

func (*RemediationCampaignService) SetTicketing added in v0.3.0

SetTicketing wires the campaign→Jira-epic integration. Safe to call after construction; when either dependency is nil, CreateTicket returns an error (the feature degrades off, the rest of the service is unaffected).

func (*RemediationCampaignService) UpdateCampaign

func (s *RemediationCampaignService) UpdateCampaign(ctx context.Context, tenantID, campaignID string, input UpdateRemediationCampaignInput) (*remediation.Campaign, error)

UpdateCampaign updates campaign fields (name, description, priority, tags, due_date).

func (*RemediationCampaignService) UpdateCampaignStatus

func (s *RemediationCampaignService) UpdateCampaignStatus(ctx context.Context, tenantID, campaignID, newStatus string) (*remediation.Campaign, error)

UpdateCampaignStatus transitions campaign status.

type UpdateRemediationCampaignInput

type UpdateRemediationCampaignInput struct {
	Name        *string
	Description *string
	Priority    *string
	Tags        []string
	StartDate   *time.Time
	DueDate     *time.Time
	// FindingFilter re-scopes the campaign (e.g. a task's "link to finding").
	// nil = leave the existing scope untouched; non-nil (incl. {}) = replace it.
	FindingFilter map[string]any
	// AssignedTo sets the owner. nil = leave unchanged; ptr to "" = unassign;
	// ptr to a user UUID = assign that user.
	AssignedTo *string
	// AssignedTeam sets the validator (the "who verifies" — segregation from the
	// fixer). Same nil/""/uuid semantics as AssignedTo.
	AssignedTeam *string
}

UpdateRemediationCampaignInput holds fields for partial campaign update.

Jump to

Keyboard shortcuts

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