jira

package
v0.5.0 Latest Latest
Warning

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

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

Index

Constants

This section is empty.

Variables

View Source
var ErrNoMatchingTransition = errors.New("no jira transition to target status")

ErrNoMatchingTransition mirrors the infra client's sentinel at the app layer (the adapter maps the infra error to this one) so SyncService can fall back to a comment without importing the infra package.

View Source
var ErrNoTicketingIntegration = fmt.Errorf("%w: no connected Jira integration configured for this tenant", shared.ErrValidation)

ErrNoTicketingIntegration is returned by a ClientResolver when the tenant has no connected Jira integration to create tickets against. It wraps ErrValidation so the HTTP layer maps it to a 400 rather than a 500.

Functions

This section is empty.

Types

type AssetRouteResolver added in v0.3.0

type AssetRouteResolver interface {
	ResolveAssetRoute(ctx context.Context, tenantID, assetID shared.ID) (scope, criticality string, groups []string, err error)
}

AssetRouteResolver supplies a finding's asset-level routing attributes so routing rules can match on them. Optional: when nil, routing matches only on finding-level fields (severity, tags). Implemented in infra by loading the asset (+ its group memberships).

type CampaignEpicSink added in v0.3.0

type CampaignEpicSink interface {
	HandleEpicStatusChange(ctx context.Context, tenantID shared.ID, issueKey, jiraStatus string) error
}

CampaignEpicSink receives inbound Jira epic status changes so a linked remediation campaign can react (e.g. epic Done → campaign completed). Implemented by *exposure.RemediationCampaignService. Declared here so the jira package needs no dependency on the remediation/exposure packages.

type ChangeItem

type ChangeItem struct {
	Field      string `json:"field"`
	FromString string `json:"fromString"`
	ToString   string `json:"toString"`
}

ChangeItem is one entry in the changelog.

type Changelog

type Changelog struct {
	Items []ChangeItem `json:"items"`
}

Changelog carries the before/after values of changed fields.

type Client

type Client interface {
	CreateIssue(ctx context.Context, input CreateIssueInput) (*CreateIssueResult, error)
	// GetIssueStatus returns the issue's current status name (echo-guard).
	GetIssueStatus(ctx context.Context, issueKey string) (string, error)
	// TransitionToStatus moves the issue to a target status NAME, attaching an
	// optional comment. Returns ErrNoMatchingTransition when the workflow offers
	// no transition to that status (caller falls back to AddComment).
	TransitionToStatus(ctx context.Context, issueKey, targetStatus, comment string) error
	// AddComment posts a comment on the issue.
	AddComment(ctx context.Context, issueKey, body string) error
	// ListProjects returns the projects visible to the configured credentials,
	// for the admin project picker (so an operator chooses the destination
	// project from a list instead of typing a key). Paginated server-side.
	ListProjects(ctx context.Context) ([]ProjectRef, error)
	TestConnection(ctx context.Context) error
}

Client defines the interface for Jira REST API operations.

type ClientResolver added in v0.3.0

type ClientResolver interface {
	Resolve(ctx context.Context, tenantID shared.ID) (Client, error)
}

ClientResolver builds a Jira Client for a given tenant from that tenant's configured ticketing integration (base URL + decrypted credentials). It is the outbound counterpart to the inbound webhook path: without a resolver the SyncService has no client and CreateTicketFromFinding is inert.

Implementations live in the infra layer (they decrypt credentials and open HTTP clients). Returning ErrNoTicketingIntegration means the tenant has no usable Jira integration — callers surface that as a 4xx, not a 5xx.

type CreateIssueInput

type CreateIssueInput struct {
	ProjectKey  string
	Summary     string
	Description string
	IssueType   string
	Priority    string
	Labels      []string
}

CreateIssueInput contains fields for creating a Jira issue.

type CreateIssueResult

type CreateIssueResult struct {
	ID        string
	Key       string
	BrowseURL string
}

CreateIssueResult contains the response from creating a Jira issue.

type CreateTicketInput

type CreateTicketInput struct {
	TenantID   string `json:"tenant_id"`
	FindingID  string `json:"finding_id"`
	ProjectKey string `json:"project_key"` // e.g. "SEC"
	IssueType  string `json:"issue_type"`  // e.g. "Bug"
}

CreateTicketInput is the payload for auto-creating a Jira ticket from a finding.

type FindingByIDReader

type FindingByIDReader interface {
	GetByID(ctx context.Context, tenantID, findingID shared.ID) (*vulnerability.Finding, error)
}

FindingByIDReader is the narrow Finding-repo surface the hook uses to look up the scanner that originally produced the finding.

type FixAppliedHook

type FixAppliedHook func(ctx context.Context, tenantID, findingID shared.ID) error

FixAppliedHook is called when a Jira webhook transitions a finding into the fix_applied state. Typical implementation: enqueue a verification scan on the finding's asset. Wired via SetPostFixAppliedHook; nil → no action (legacy behaviour).

Implementations MUST be idempotent — the B3 rate-limiting guard in the implementation layer decides whether to actually enqueue a scan (e.g. max one per finding per 24h).

type LinkTicketInput

type LinkTicketInput struct {
	TenantID  string `json:"tenant_id"`
	FindingID string `json:"finding_id"`
	TicketKey string `json:"ticket_key"` // e.g. "PROJ-123"
	TicketURL string `json:"ticket_url"` // e.g. "https://myorg.atlassian.net/browse/PROJ-123"
}

LinkTicketInput is the payload for linking a Jira ticket to a finding.

type MappingConfig added in v0.3.0

type MappingConfig struct {
	// SeverityToPriority maps a finding severity (lower-case) to a Jira priority
	// name, e.g. "critical" -> "Highest".
	SeverityToPriority map[string]string

	// StatusInbound maps a Jira status name (lower-case) to a finding status,
	// e.g. "done" -> "fix_applied". Used by the inbound webhook.
	StatusInbound map[string]vulnerability.FindingStatus

	// StatusOutbound maps a finding status (lower-case) to a target Jira status
	// NAME, e.g. "resolved" -> "Done". Used by outbound status sync (RFC-006
	// Phase 3) to transition the linked issue. A finding status absent from this
	// map produces no push. Defaults use Jira's stock workflow names; customers
	// with custom workflows override via config.ticketing.status_outbound.
	StatusOutbound map[string]string

	// SyncEnabled is the per-integration master switch for OUTBOUND status sync.
	// Defaults to false so connecting a ticketing integration never silently
	// starts writing back to Jira until the operator opts in.
	SyncEnabled bool

	// DefaultPriority is returned when a severity has no explicit mapping.
	DefaultPriority string

	// DefaultIssueType is the Jira issue type used when a request omits one.
	DefaultIssueType string

	// DefaultProjectKey is the Jira project a finding's ticket lands in when the
	// caller does not specify one (the per-tenant "where do tickets go" setting,
	// chosen once in the integration's ticketing config). Empty = none, in which
	// case the caller MUST pass a project key explicitly. Loaded from
	// config.ticketing.project_key.
	DefaultProjectKey string

	// Routing selects a destination project (and optionally issue type) by
	// matching attributes of the finding and its asset — e.g. route the Payments
	// team's critical findings to the PAY project. Rules are evaluated in order;
	// the first match wins. Falls through to DefaultProjectKey when nothing
	// matches. Loaded from config.ticketing.routing.
	Routing []RoutingRule
}

MappingConfig holds the configurable severity/status mappings for a ticketing integration. The zero value is not useful; build one with DefaultMappingConfig (today's hardcoded behaviour) and optionally overlay per-integration overrides with ParseMappingConfig.

It is loaded from the integration record's JSONB config under the "ticketing" key; see ParseMappingConfig. When a tenant has no overrides, the defaults preserve the platform's original behaviour exactly.

func DefaultMappingConfig added in v0.3.0

func DefaultMappingConfig() MappingConfig

DefaultMappingConfig returns the mapping that reproduces the platform's original hardcoded behaviour. Customers with non-default Jira workflows overlay overrides via ParseMappingConfig.

func ParseMappingConfig added in v0.3.0

func ParseMappingConfig(config map[string]any) MappingConfig

ParseMappingConfig builds a MappingConfig from an integration's JSONB config. It starts from DefaultMappingConfig and overlays any overrides found under config["ticketing"], so partial configs only change what they specify.

Expected shape (all optional):

{ "ticketing": {
    "issue_type": "Task",
    "default_priority": "P3",
    "severity_to_priority": { "critical": "P1", "high": "P2" },
    "status_inbound": { "Shipped": "fix_applied", "QA": "in_progress" }
}}

Keys are matched case-insensitively (Jira statuses/severities vary by site). Status values that are not valid finding statuses are skipped (logged by the caller if desired) rather than corrupting the map.

func (MappingConfig) FindingStatusForJira added in v0.3.0

func (m MappingConfig) FindingStatusForJira(jiraStatus string) (vulnerability.FindingStatus, bool)

FindingStatusForJira maps a Jira status name to a finding status. Returns (status, true) when a mapping exists and resolves to a valid finding status, (_, false) otherwise (the inbound webhook then ignores the transition).

func (MappingConfig) JiraStatusForFinding added in v0.3.0

func (m MappingConfig) JiraStatusForFinding(findingStatus string) (string, bool)

JiraStatusForFinding maps a finding status to the target Jira status NAME for outbound sync. Returns (name, true) when a mapping exists; (_, false) when the finding status should not move the issue.

func (MappingConfig) PriorityForSeverity added in v0.3.0

func (m MappingConfig) PriorityForSeverity(severity string) string

PriorityForSeverity returns the Jira priority for a finding severity, falling back to DefaultPriority when unmapped.

func (MappingConfig) RouteFor added in v0.3.0

func (m MappingConfig) RouteFor(rc RouteContext) (RoutingRule, bool)

RouteFor returns the first routing rule that matches the context, or (RoutingRule{}, false) when none match.

type MappingResolver added in v0.3.0

type MappingResolver interface {
	ResolveMapping(ctx context.Context, tenantID shared.ID) (MappingConfig, error)
}

MappingResolver loads a tenant's ticketing MappingConfig (status maps + sync_enabled) from its integration config. Counterpart to ClientResolver, used by outbound status sync to decide whether/where to push. Returning ErrNoTicketingIntegration means the tenant has no Jira integration.

type ProjectRef added in v0.3.0

type ProjectRef struct {
	ID   string `json:"id"`
	Key  string `json:"key"`
	Name string `json:"name"`
}

ProjectRef is a Jira project as surfaced to the admin project picker.

type RescanHook

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

RescanHook wraps the verification trigger with a per-finding cooldown. Install via SyncService.SetPostFixAppliedHook(hook.Hook).

func NewRescanHook

func NewRescanHook(
	actions VerificationScanRequester,
	repo FindingByIDReader,
	log *logger.Logger,
) *RescanHook

NewRescanHook wires the deps + cooldown.

func (*RescanHook) Hook

func (h *RescanHook) Hook(ctx context.Context, tenantID, findingID shared.ID) error

Hook is the callback installed on SyncService. Matches the FixAppliedHook function signature in jira_sync_service.go.

func (*RescanHook) SetCooldown

func (h *RescanHook) SetCooldown(d time.Duration)

SetCooldown overrides the default 24h cooldown. Useful for tests.

type RouteContext added in v0.3.0

type RouteContext struct {
	Severity    string
	Tags        []string
	Scope       string
	Criticality string
	Groups      []string
}

RouteContext carries the finding + asset attributes a RoutingRule matches against. Finding-level fields (severity, tags) are always available; the asset-level fields are populated by an AssetRouteResolver when one is wired, and are otherwise empty (so asset-conditioned rules simply don't match).

type RoutingRule added in v0.3.0

type RoutingRule struct {
	// Match conditions (lower-cased, case-insensitive). Empty slice = any.
	Severity    []string // finding severity: critical/high/medium/low/info
	Tag         []string // finding tags (any overlap matches)
	Scope       []string // asset scope: external/internal/cloud/partner/vendor/shadow
	Criticality []string // asset criticality: critical/high/medium/low/none
	AssetGroup  []string // asset group name/slug (any overlap matches)

	// Target.
	ProjectKey string // destination project (required for a usable rule)
	IssueType  string // optional issue-type override for this route
}

RoutingRule maps findings matching ALL of its (non-empty) conditions to a destination project. Within a condition the values are OR'd; across conditions they are AND'd; an empty condition is a wildcard. This is how "each Jira project = a team/business unit" is expressed without making a project an asset.

type SyncService

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

SyncService handles bidirectional sync between findings and Jira tickets.

Capabilities:

  1. POST /findings/{id}/link-ticket — manually link a Jira ticket to a finding
  2. POST /findings/{id}/create-ticket — auto-create Jira ticket from finding
  3. POST /webhooks/incoming/jira — receive Jira status-change webhooks

func NewSyncService

func NewSyncService(findingRepo vulnerability.FindingRepository, jiraClient Client, log *logger.Logger) *SyncService

NewSyncService creates a new SyncService.

func (*SyncService) CreateEpic added in v0.3.0

func (s *SyncService) CreateEpic(ctx context.Context, tenantID shared.ID, projectKey, summary, description string, labels []string) (issueKey, issueURL string, err error)

CreateEpic creates a Jira epic for the given tenant and returns its key and browse URL. It is provider-plumbing only — campaign-agnostic — so the remediation campaign service can own the "campaign -> epic" orchestration (idempotency + persistence) without coupling the jira package to the remediation domain. Summary/description are secret-redacted defensively. The signature uses primitives so callers can depend on a narrow interface without importing the jira package.

func (*SyncService) CreateTicketFromFinding

func (s *SyncService) CreateTicketFromFinding(ctx context.Context, input CreateTicketInput) (*TicketInfo, error)

CreateTicketFromFinding auto-creates a Jira ticket from a finding and links it.

func (*SyncService) HandleJiraWebhook

func (s *SyncService) HandleJiraWebhook(ctx context.Context, tenantID shared.ID, payload WebhookPayload) error

HandleJiraWebhook processes an inbound Jira webhook and syncs finding status.

Status mapping:

Jira "In Progress"  → finding "in_progress"
Jira "In Review"    → finding "in_progress"
Jira "Done"         → finding "fix_applied"  (triggers verification flow)
Jira "Resolved"     → finding "fix_applied"
Jira "Closed"       → finding "fix_applied"

func (*SyncService) LinkTicket

func (s *SyncService) LinkTicket(ctx context.Context, input LinkTicketInput) error

LinkTicket adds a Jira ticket reference to a finding's work_item_uris. Idempotent — re-adding the same URL is a no-op at the domain level.

func (*SyncService) ListProjects added in v0.3.0

func (s *SyncService) ListProjects(ctx context.Context, tenantID shared.ID) ([]ProjectRef, error)

ListProjects returns the Jira projects visible to the tenant's connected ticketing integration, for the admin project picker. Returns ErrNoTicketingIntegration when the tenant has no connected Jira integration.

func (*SyncService) SetAssetRouteResolver added in v0.3.0

func (s *SyncService) SetAssetRouteResolver(r AssetRouteResolver)

SetAssetRouteResolver wires the optional asset-context resolver used by routing rules. Safe to call after construction.

func (*SyncService) SetCampaignSink added in v0.3.0

func (s *SyncService) SetCampaignSink(sink CampaignEpicSink)

SetCampaignSink wires the inbound epic→campaign sync. Safe to call after construction; nil disables it.

func (*SyncService) SetClientResolver added in v0.3.0

func (s *SyncService) SetClientResolver(r ClientResolver)

SetClientResolver wires the per-tenant Jira client resolver. Safe to call after construction. Once set, CreateTicketFromFinding resolves a client from the tenant's integration instead of relying on the static client.

func (*SyncService) SetMappingResolver added in v0.3.0

func (s *SyncService) SetMappingResolver(r MappingResolver)

SetMappingResolver wires the per-tenant mapping resolver for outbound status sync. Safe to call after construction; nil disables outbound sync.

func (*SyncService) SetPostFixAppliedHook

func (s *SyncService) SetPostFixAppliedHook(h FixAppliedHook)

SetPostFixAppliedHook wires the verification-scan trigger. Safe to call after construction; nil value disables the hook.

func (*SyncService) SyncFindingStatus added in v0.3.0

func (s *SyncService) SyncFindingStatus(ctx context.Context, tenantID, findingID shared.ID) error

SyncFindingStatus is the async entrypoint for outbound status sync: it resolves the tenant's mapping then pushes the finding's status to its linked Jira issue. No-op when no mapping resolver is wired or the tenant has no Jira integration. Called by the jira-sync asynq handler.

func (*SyncService) SyncFindingStatusToTicket added in v0.3.0

func (s *SyncService) SyncFindingStatusToTicket(ctx context.Context, tenantID, findingID shared.ID, mapping MappingConfig) error

SyncFindingStatusToTicket pushes a finding's status to its linked Jira issue (the outbound half of bidirectional sync — RFC-006 Phase 3). It is a no-op unless the integration opted in (mapping.SyncEnabled) and the finding status maps to a target Jira status. Echo-safe: it only acts on the OpenCTEM-initiated status-change path (the inbound webhook updates findings directly, bypassing this), and additionally skips when the issue is already at the target.

On a workflow with no transition to the target, it falls back to a comment so the change is visible to a human rather than failing.

func (*SyncService) TransitionEpic added in v0.3.0

func (s *SyncService) TransitionEpic(ctx context.Context, tenantID shared.ID, issueKey, targetStatus, comment string) error

TransitionEpic moves a campaign's linked Jira epic to a target status NAME, best-effort and echo-safe: it skips when the epic is already at the target, and falls back to a comment when the workflow offers no transition (so the change is visible to a human rather than failing). Campaign-agnostic plumbing — the caller decides when/where to call it.

func (*SyncService) UnlinkTicket

func (s *SyncService) UnlinkTicket(ctx context.Context, tenantIDStr, findingIDStr, ticketURL string) error

UnlinkTicket removes a Jira ticket reference from a finding.

type TicketInfo

type TicketInfo struct {
	FindingID string    `json:"finding_id"`
	TicketKey string    `json:"ticket_key"`
	TicketURL string    `json:"ticket_url"`
	LinkedAt  time.Time `json:"linked_at"`
}

TicketInfo is returned by LinkTicket to the HTTP handler for the response body.

type VerificationScanRequester

type VerificationScanRequester interface {
	RequestVerificationScan(ctx context.Context, tenantID, userID string, input app.RequestVerificationScanInput) (*app.RequestVerificationScanResult, error)
}

VerificationScanRequester is the narrow surface the hook needs from FindingActionsService. Kept as an interface so the hook is testable without standing up the full finding-actions graph. *FindingActionsService satisfies it directly.

type WebhookIssue

type WebhookIssue struct {
	Key    string                 `json:"key"`  // e.g. "PROJ-123"
	Self   string                 `json:"self"` // e.g. "https://myorg.atlassian.net/rest/api/2/issue/10001"
	Fields map[string]interface{} `json:"fields"`
}

WebhookIssue represents the issue block inside a Jira webhook payload.

type WebhookPayload

type WebhookPayload struct {
	WebhookEvent string       `json:"webhookEvent"` // "jira:issue_updated"
	Issue        WebhookIssue `json:"issue"`
	Changelog    *Changelog   `json:"changelog,omitempty"`
}

WebhookPayload is the envelope sent by Jira issue-updated webhooks. See https://developer.atlassian.com/cloud/jira/platform/webhooks/

Jump to

Keyboard shortcuts

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