security

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ArtifactSlices          = "security-slices.json"
	ArtifactFindingsV2      = "security-findings.v2.json"
	ArtifactDroppedFindings = "security-dropped-findings.json"

	EnvRepositoryScanName   = "ORKA_SECURITY_REPOSITORY_SCAN"
	EnvReviewSliceJSON      = "ORKA_SECURITY_REVIEW_SLICE_JSON"
	EnvStage                = "ORKA_SECURITY_STAGE"
	EnvScanID               = "ORKA_SECURITY_SCAN_ID"
	EnvSliceID              = "ORKA_SECURITY_SLICE_ID"
	EnvFindingID            = "ORKA_SECURITY_FINDING_ID"
	EnvPatchBranch          = "ORKA_SECURITY_PATCH_BRANCH"
	EnvScanBaseCommit       = "ORKA_SECURITY_SCAN_BASE_COMMIT"
	EnvScanHeadCommit       = "ORKA_SECURITY_SCAN_HEAD_COMMIT"
	EnvScannerPolicyVersion = "ORKA_SECURITY_SCANNER_POLICY_VERSION"
	EnvPolicyDigest         = "ORKA_SECURITY_POLICY_DIGEST"
	EnvPolicyProvenance     = "ORKA_SECURITY_POLICY_PROVENANCE"

	ScannerPolicyVersion = "2026-06-orka-fp-policy-v1"

	SchemaVersionReviewSlices  = 1
	SchemaVersionReviewContext = 1
	SchemaVersionFindingsV2    = 2
	SchemaVersionPatchSummary  = 1
)
View Source
const (
	DefaultPolicyConfigMapKey   = "policy"
	PolicyConfigMapAllowedLabel = "orka.ai/security-policy"
	MaxCustomPolicyBytes        = 32 * 1024
)
View Source
const (
	AgentResultSchemaVersion = 1

	AgentResultKindThreatModel = "orka.security.threat-model.v1"
	AgentResultKindFindings    = "orka.security.findings.v1"
	AgentResultKindValidation  = "orka.security.validation.v1"
	AgentResultKindPatch       = "orka.security.patch.v1"

	// MaxPatchSummaryArtifactBytes bounds a pre-existing patch summary
	// artifact before it is decoded; it matches the terminal-result cap.
	MaxPatchSummaryArtifactBytes = maxPatchResultBytes
)
View Source
const (
	ArtifactThreatModel    = "security-threat-model.md"
	ArtifactValidation     = "security-validation.json"
	ArtifactValidationText = "security-validation.txt"
	// ArtifactWorkspaceDir is the repo-root symlink the worker exposes for
	// writing security artifacts from inside the agent workspace.
	ArtifactWorkspaceDir = ".orka-artifacts"
)
View Source
const (
	StageThreatModel = "threat-model"
	StageMapper      = "mapper"
	StageReview      = "review"
	StageValidation  = "validation"
	StagePatch       = "patch"
)
View Source
const (
	RepositoryScanRunFinalizer = "orka.ai/security-scan-runs"
)

Variables

View Source
var ErrScanRunCancellationPending = fmt.Errorf("%w: scan run cancellation is pending", store.ErrConflict)

Functions

func ArtifactWorkspacePath

func ArtifactWorkspacePath(subPath string) string

ArtifactWorkspacePath returns the relative path from the agent working directory to the repo-root artifacts symlink.

func AutoValidationTaskName added in v0.2.0

func AutoValidationTaskName(repositoryScanName, findingID, scanRunID string) string

AutoValidationTaskName binds automatic validation to one finding occurrence so a delayed retry cannot create another Task after a lost creation response.

func BuildPatchPrompt

func BuildPatchPrompt(scan *corev1alpha1.RepositoryScan, finding *store.Finding, patchBranch string) string

BuildPatchPrompt returns the harness-v2 prompt for patch proposal tasks: the agent edits the workspace and returns an identity-bound patch result envelope; Orka publishes the delta and derives the reviewable diff from the published commit.

func BuildReviewResultPrompt added in v0.2.0

func BuildReviewResultPrompt(
	scan *corev1alpha1.RepositoryScan,
	mode, baseCommit, headCommit, threatModel string,
	slice store.ReviewSlice,
	binding AgentResultBinding,
	manifest ReviewContextManifest,
	repository FindingsV2Repository,
	policies ...PromptPolicy,
) string

BuildReviewResultPrompt returns the harness-v2 prompt with mapper-owned bounded context and an identity-bound findings result contract.

func BuildThreatModelResultPrompt added in v0.2.0

func BuildThreatModelResultPrompt(scan *corev1alpha1.RepositoryScan, mode, baseCommit, headCommit, threatModel string, binding AgentResultBinding, policies ...PromptPolicy) string

BuildThreatModelResultPrompt returns the harness-v2 prompt whose only output is a bounded, identity-bound terminal result.

func BuildValidationResultPrompt added in v0.2.0

func BuildValidationResultPrompt(scan *corev1alpha1.RepositoryScan, finding *store.Finding, binding AgentResultBinding, policies ...PromptPolicy) string

BuildValidationResultPrompt returns the harness-v2 validation prompt whose terminal result is bound to the finding and scanner policy.

func CancelScanRun added in v0.2.0

func CancelScanRun(ctx context.Context, s store.SecurityStore, c client.Client, reader client.Reader, scan *corev1alpha1.RepositoryScan, run *store.ScanRun, reason string) error

CancelScanRun records intent before requesting Task deletion so reconciliation can retry failures even when the run still matches the current configuration.

func CanonicalRepositoryCloneURL added in v0.2.0

func CanonicalRepositoryCloneURL(repoURL string) string

CanonicalRepositoryCloneURL returns the canonical credential-free HTTPS clone URL for GitHub repository URLs accepted by ParseGitHubRepositoryURL, converting SSH roots (git@github.com:owner/repo[.git]) and normalizing HTTPS forms to https://github.com/owner/repo. This is the only repository form the ACP workspace preflight and the general worker's header-credential clone support. Non-GitHub URLs are returned trimmed and unchanged.

func CanonicalWorkspaceRepositoryCloneURL added in v0.2.0

func CanonicalWorkspaceRepositoryCloneURL(raw string) (string, error)

CanonicalWorkspaceRepositoryCloneURL canonicalizes a workspace repository URL to the only form the controller's workspace preflight accepts: a credential-free HTTPS URL without query or fragment. GitHub-style SSH roots (git@github.com:owner/repo[.git]) are first converted with CanonicalRepositoryCloneURL. The reject conditions mirror the RULE enforced by the controller's canonicalWorkspaceRepositoryURL — keep them in exact behavior parity (not stricter and not looser) so an accepted URL never fails the controller preflight after a Task is created. Empty input is allowed and returns an empty URL; error text describes only the failed condition so callers can prefix their own field name.

func ConfidenceMeetsMinimum

func ConfidenceMeetsMinimum(value, minimum string) bool

func CreateInitialScanTask added in v0.2.0

func CreateInitialScanTask(ctx context.Context, s store.SecurityStore, c client.Client, reader client.Reader, scan *corev1alpha1.RepositoryScan, run *store.ScanRun, task *corev1alpha1.Task) error

CreateInitialScanTask keeps a failed admission reserved until cleanup confirms that no Task remains, including when Create returns an ambiguous response.

func CurrentRepositoryScanTasks added in v0.2.0

func CurrentRepositoryScanTasks(ctx context.Context, s store.SecurityStore, scan *corev1alpha1.RepositoryScan, tasks []corev1alpha1.Task) ([]corev1alpha1.Task, error)

CurrentRepositoryScanTasks excludes foreign owners and pipeline Tasks whose persisted run belongs to a previous RepositoryScan incarnation or generation.

func DeleteScanRunPipelineTasks added in v0.2.0

func DeleteScanRunPipelineTasks(ctx context.Context, c client.Client, reader client.Reader, scan *corev1alpha1.RepositoryScan, run *store.ScanRun) (bool, error)

DeleteScanRunPipelineTasks requests cancellation through Task deletion before releasing a run reservation. Terminal Tasks and other owners are preserved. The result reports whether this live read observed any nonterminal owned Tasks.

func DroppedFindingSampleJSON

func DroppedFindingSampleJSON(diagnostic DroppedFindingDiagnostic) string

func EffectiveBranch

func EffectiveBranch(scan *corev1alpha1.RepositoryScan) string

EffectiveBranch returns the configured branch or the standard default.

func EffectiveHistoryDays

func EffectiveHistoryDays(scan *corev1alpha1.RepositoryScan) int32

EffectiveHistoryDays returns the configured history window or a conservative default.

func EffectiveMaxFindingsPerRun

func EffectiveMaxFindingsPerRun(scan *corev1alpha1.RepositoryScan) int32

EffectiveMaxFindingsPerRun returns the configured cap or a conservative default.

func EffectiveRef

func EffectiveRef(scan *corev1alpha1.RepositoryScan) string

EffectiveRef returns the configured checkout ref, if any.

func EffectiveValidationMaxFindingsPerRun

func EffectiveValidationMaxFindingsPerRun(scan *corev1alpha1.RepositoryScan) int32

EffectiveValidationMaxFindingsPerRun returns the automatic validation cap for light mode.

func EffectiveValidationMinConfidence

func EffectiveValidationMinConfidence(scan *corev1alpha1.RepositoryScan) string

EffectiveValidationMinConfidence returns the minimum confidence eligible for automatic validation.

func EffectiveValidationMinSeverity

func EffectiveValidationMinSeverity(scan *corev1alpha1.RepositoryScan) string

EffectiveValidationMinSeverity returns the minimum severity eligible for automatic validation.

func EffectiveValidationMode

func EffectiveValidationMode(scan *corev1alpha1.RepositoryScan) string

EffectiveValidationMode returns the configured validation mode or the default.

func EffectiveWorkspaceBranch

func EffectiveWorkspaceBranch(scan *corev1alpha1.RepositoryScan) string

EffectiveWorkspaceBranch returns the branch to pass to git clone for scan workspaces. Ref-only scans must not force the default branch before the worker can check out the ref.

func EnsureRepositoryScanRunFinalizer added in v0.2.0

func EnsureRepositoryScanRunFinalizer(ctx context.Context, c client.Client, reader client.Reader, scan *corev1alpha1.RepositoryScan) error

EnsureRepositoryScanRunFinalizer installs deletion cleanup before reserving a run. The live reader prevents stale cache entries from retiring newer runs; the optimistic patch cannot attach the finalizer to a recreated or edited object.

func FindingID

func FindingID(fingerprint string) string

FindingID returns a stable finding identifier derived from its fingerprint.

func FindingV2Fingerprint

func FindingV2Fingerprint(namespace, repositoryScan, repoURL, branch, subPath, sliceID string, finding FindingsV2Finding) string

FindingV2Fingerprint computes an Orka-owned stable fingerprint for a v2 finding.

func FindingV2TargetKey added in v0.2.0

func FindingV2TargetKey(repoURL, branch, subPath string) string

FindingV2TargetKey identifies the repository branch or ref and subpath that produced a finding without exposing those values through the store API.

func IsSuspended

func IsSuspended(scan *corev1alpha1.RepositoryScan) bool

IsSuspended returns whether scheduled scans are paused.

func LooksLikeSecret

func LooksLikeSecret(text string) bool

LooksLikeSecret reports whether text carries a credential-shaped value: known token prefixes, JWTs, PEM blocks, or an assignment/header whose value is long enough to be a real secret. Bare keywords such as "OPENAI_API_KEY=dummy" or "Authorization: Bearer $TOKEN" are not secrets and must not block documentation or code that merely mentions them.

Each pattern is evaluated only around the keywords it requires (see secretScan); the verdict is the same as evaluating every pattern over the whole text.

func NewScanRunID added in v0.2.0

func NewScanRunID() string

NewScanRunID does not depend on second-resolution Task names. The full ID fits in a Kubernetes label and remains stable for every stage of the run.

func ParseGitHubRepositoryURL

func ParseGitHubRepositoryURL(repoURL string) (owner string, repository string, err error)

ParseGitHubRepositoryURL validates a credential-free GitHub repository URL and returns its owner and repository name.

func ParseRepositoryURL

func ParseRepositoryURL(repoURL string) (owner string, repository string)

ParseRepositoryURL extracts owner and repo name from GitHub URLs.

func ParseThreatModelResult added in v0.2.0

func ParseThreatModelResult(data []byte, expected AgentResultBinding) (string, error)

ParseThreatModelResult strictly decodes and identity-binds a terminal ACP result. Markdown is kept inside JSON so unrelated assistant prose cannot be mistaken for scanner output.

func PatchBranch

func PatchBranch(findingID, taskName string) string

PatchBranch returns the default branch name for a security patch proposal.

func PatchProposalID

func PatchProposalID(taskName string) string

PatchProposalID returns a stable patch proposal ID for a task.

func PatchTaskName

func PatchTaskName(repositoryScanName, findingID, scanRunID string) string

PatchTaskName returns a task name for a patch proposal bound to one finding occurrence.

func PolicyProvenanceEnv

func PolicyProvenanceEnv(policy ScannerPolicy) string

func PolicyTextDigest

func PolicyTextDigest(text string) string

func RemediationPullRequestBody added in v0.2.0

func RemediationPullRequestBody(finding *store.Finding, summary *PatchSummaryArtifact) string

RemediationPullRequestBody renders the reviewer-facing body of a remediation pull request: the finding's summary, root cause, and remediation guidance, plus the patch agent's own account of the change. The caller appends the publisher's intent marker so the clean-room publisher still recognizes the pull request as its own.

func RemediationPullRequestTitle added in v0.2.0

func RemediationPullRequestTitle(finding *store.Finding) string

RemediationPullRequestTitle renders the reviewer-facing title of a remediation pull request from the finding.

func RetireStaleScanRuns added in v0.2.0

func RetireStaleScanRuns(ctx context.Context, s store.SecurityStore, c client.Client, reader client.Reader, scan *corev1alpha1.RepositoryScan) (bool, error)

RetireStaleScanRuns releases reservations from an earlier object or spec. It also reports a stale status binding even if that run is already terminal. Legacy rows remain unbound; no identity is inferred from the current object.

func ReviewContextArtifactName

func ReviewContextArtifactName(sliceID string) string

ReviewContextArtifactName returns the context manifest artifact for a slice.

func ReviewContextDigest added in v0.2.0

func ReviewContextDigest(manifest ReviewContextManifest) (string, error)

ReviewContextDigest returns the canonical digest used to bind a review Task and its result to one mapper-generated context manifest.

func RollbackScanRunAdmission added in v0.2.0

func RollbackScanRunAdmission(ctx context.Context, s store.SecurityStore, c client.Client, reader client.Reader, scan *corev1alpha1.RepositoryScan, run *store.ScanRun) error

RollbackScanRunAdmission cancels work whose admission lost status ownership. Failed cancellation keeps the reservation and durable cleanup intent.

func SafeRepoPath

func SafeRepoPath(p string) bool

SafeRepoPath returns true when p is a clean relative repository path.

func SameWorkspaceRepositoryIdentity added in v0.2.0

func SameWorkspaceRepositoryIdentity(first, second string) bool

SameWorkspaceRepositoryIdentity mirrors the controller's identity comparison: exact match, or case-insensitive match for github.com identities.

func SanitizeThreatModel added in v0.2.0

func SanitizeThreatModel(content string) string

SanitizeThreatModel redacts common credential shapes in generated and edited threat models. Strip invisible runes first so they cannot split a credential past the redactor; preserve newlines and tabs for markdown structure.

func ScanRunID

func ScanRunID(taskName string) string

ScanRunID returns a scan run ID derived from task identity.

func ScanRunIdempotencyKey

func ScanRunIdempotencyKey(namespace, repositoryScan, mode, baseSHA, headSHA, subPath, policyDigest string) string

func ScanRunMatchesRepositoryScan added in v0.2.0

func ScanRunMatchesRepositoryScan(run *store.ScanRun, scan *corev1alpha1.RepositoryScan) bool

ScanRunMatchesRepositoryScan never adopts an unbound historical run into a live RepositoryScan, whose Kubernetes UID and generation are nonzero.

func ScanStageRetryTaskName added in v0.2.0

func ScanStageRetryTaskName(repositoryScanName, scanRunID, stage, scope string, attempt int) string

ScanStageRetryTaskName returns a deterministic task name for one bounded retry of a specific stage within an existing scan run.

func ScanStageTaskName

func ScanStageTaskName(repositoryScanName, mode, stage, scope string) string

ScanStageTaskName returns a task name for a specific scan stage and optional scope.

func ScanStageTaskNameForRun added in v0.2.0

func ScanStageTaskNameForRun(repositoryScanName, mode, stage, scope, runID string) string

ScanStageTaskNameForRun gives a stage the same name on every reconciliation while keeping separate runs distinct, including runs started in one second.

func ScannerFindingQualityPolicy

func ScannerFindingQualityPolicy() string

ScannerFindingQualityPolicy is the default non-overridable quality policy for repository security scanner prompts and validation prompts.

func ScannerPolicyDigest

func ScannerPolicyDigest(policy ScannerPolicy) string

func ScannerValidationQualityPolicy

func ScannerValidationQualityPolicy() string

func SecretLikeLineDigests added in v0.2.0

func SecretLikeLineDigests(text string) []string

SecretLikeLineDigests returns one SHA-256 hex digest for every line of text that LooksLikeSecret flags on its own. Each digest covers the flagged line's code block together with the previous and the next code block and everything in between (blank and comment-only lines), so a caller that recognises a pre-existing secret-like line (a demo credential a repository already ships) also proves nothing was inserted, appended, or continued anywhere an expression could still reach it. Digests may repeat when identical windows occur more than once; callers compare them as multisets. No content is retained.

func SeverityMeetsMinimum

func SeverityMeetsMinimum(value, minimum string) bool

func StripLinesByDigest added in v0.2.0

func StripLinesByDigest(text string, known map[string]struct{}) string

StripLinesByDigest removes every secret-like line whose window digest (see SecretLikeLineDigests) is in known and returns the remaining text, so the caller can re-check that nothing secret-like remains once the recognised lines are taken out. Only secret-like lines can carry a known digest, so only they are hashed.

func ToFindingV2

func ToFindingV2(
	namespace string,
	repositoryScan string,
	scanRunID string,
	taskName string,
	repo FindingsV2Repository,
	scan FindingsV2Scan,
	item FindingsV2Finding,
) *store.Finding

ToFindingV2 converts a validated v2 finding to durable store shape.

func ValidateCustomPolicyText

func ValidateCustomPolicyText(text string) error

func ValidateScanStageRun added in v0.2.0

func ValidateScanStageRun(ctx context.Context, s store.SecurityStore, reader client.Reader, scan *corev1alpha1.RepositoryScan, run *store.ScanRun) error

ValidateScanStageRun checks live parent identity and durable run ownership.

func WorkspaceRepositoryURLIdentity added in v0.2.0

func WorkspaceRepositoryURLIdentity(canonicalURL string) (string, error)

WorkspaceRepositoryURLIdentity derives the canonical repository identity for a clone URL that already passed CanonicalWorkspaceRepositoryCloneURL, mirroring the controller's canonicalWorkspaceRepositoryURL derivation: lower-cased host plus the cleaned path with any .git suffix removed, with the path additionally lower-cased for github.com.

Types

type AgentResultBinding added in v0.2.0

type AgentResultBinding struct {
	RepositoryScan string
	ScanID         string
	PolicyDigest   string
	ContextDigest  string
}

AgentResultBinding is controller-owned identity that every SecurityScan agent result must echo exactly. It contains no credentials or mutable runtime configuration.

type ChangedLineRange

type ChangedLineRange = store.ChangedLineRange

type DroppedFindingArtifact

type DroppedFindingArtifact struct {
	SchemaVersion int                        `json:"schemaVersion"`
	Dropped       []DroppedFindingDiagnostic `json:"dropped"`
}

type DroppedFindingDiagnostic

type DroppedFindingDiagnostic struct {
	Index  int    `json:"index"`
	Reason string `json:"reason"`
	Sample any    `json:"sample,omitempty"`
	Layer  string `json:"layer"`
}

type FindingFilterResult

type FindingFilterResult struct {
	Kept    []*store.Finding
	Dropped []DroppedFindingDiagnostic
}

func FilterFindings

func FilterFindings(findings []*store.Finding) FindingFilterResult

FilterFindings applies deterministic hard false-positive exclusions after schema/evidence validation and before durable finding persistence.

type FindingValidationOptions

type FindingValidationOptions struct {
	Namespace            string
	RepositoryScan       string
	ScanRunID            string
	TaskName             string
	WorkspaceRoot        string
	TrustedRepository    FindingsV2Repository
	UseTrustedRepository bool
}

type FindingValidationResult

type FindingValidationResult struct {
	Accepted []*store.Finding
	Dropped  []DroppedFindingDiagnostic
}

func ValidateFindingsV2

ValidateFindingsV2 validates and partitions a v2 findings artifact.

type FindingsResultEnvelope added in v0.2.0

type FindingsResultEnvelope struct {
	SchemaVersion  int                `json:"schemaVersion"`
	Kind           string             `json:"kind"`
	RepositoryScan string             `json:"repositoryScan"`
	ScanID         string             `json:"scanId"`
	SliceID        string             `json:"sliceId"`
	PolicyDigest   string             `json:"policyDigest"`
	ContextDigest  string             `json:"contextDigest"`
	Findings       FindingsV2Artifact `json:"findings"`
}

FindingsResultEnvelope is the only accepted terminal result for one review slice. The context digest binds evidence to mapper-generated excerpts.

type FindingsResultExpectation added in v0.2.0

type FindingsResultExpectation struct {
	Binding    AgentResultBinding
	SliceID    string
	Mode       string
	Repository FindingsV2Repository
}

type FindingsV2Artifact

type FindingsV2Artifact struct {
	SchemaVersion int                  `json:"schemaVersion"`
	Repository    FindingsV2Repository `json:"repository"`
	Scan          FindingsV2Scan       `json:"scan"`
	Findings      []FindingsV2Finding  `json:"findings"`
}

FindingsV2Artifact captures evidence-backed slice review output.

func ParseFindingsResult added in v0.2.0

func ParseFindingsResult(data []byte, expected FindingsResultExpectation) (*FindingsV2Artifact, error)

ParseFindingsResult strictly decodes a terminal review result and requires exact controller-owned repository, run, slice, policy, and context identity.

func ParseFindingsV2Artifact

func ParseFindingsV2Artifact(data []byte) (*FindingsV2Artifact, error)

ParseFindingsV2Artifact parses and validates only the top-level contract.

type FindingsV2EvidenceRef

type FindingsV2EvidenceRef struct {
	Path      string  `json:"path"`
	StartLine int     `json:"startLine"`
	EndLine   int     `json:"endLine"`
	Symbol    *string `json:"symbol"`
	Quote     *string `json:"quote"`
}

type FindingsV2Finding

type FindingsV2Finding struct {
	Title                         string                  `json:"title"`
	Category                      string                  `json:"category"`
	Severity                      string                  `json:"severity"`
	Confidence                    string                  `json:"confidence"`
	Triage                        string                  `json:"triage"`
	Evidence                      []FindingsV2EvidenceRef `json:"evidence"`
	Summary                       string                  `json:"summary"`
	RootCause                     string                  `json:"rootCause"`
	Reproduction                  string                  `json:"reproduction"`
	Remediation                   string                  `json:"remediation"`
	SuggestedAction               string                  `json:"suggestedAction"`
	WhyTestsDoNotAlreadyCoverThis string                  `json:"whyTestsDoNotAlreadyCoverThis"`
	SuggestedRegressionTest       string                  `json:"suggestedRegressionTest"`
	MinimumFixScope               string                  `json:"minimumFixScope"`
}

type FindingsV2Repository

type FindingsV2Repository struct {
	RepoURL string `json:"repoURL"`
	Branch  string `json:"branch"`
	SubPath string `json:"subPath"`
	BaseSHA string `json:"baseSHA"`
	HeadSHA string `json:"headSHA"`
}

type FindingsV2Scan

type FindingsV2Scan struct {
	Mode    string `json:"mode"`
	SliceID string `json:"sliceId"`
	Summary string `json:"summary"`
}

type PatchResultEnvelope added in v0.2.0

type PatchResultEnvelope struct {
	SchemaVersion  int            `json:"schemaVersion"`
	Kind           string         `json:"kind"`
	RepositoryScan string         `json:"repositoryScan"`
	FindingID      string         `json:"findingId"`
	Summary        string         `json:"summary"`
	ChangedFiles   []string       `json:"changedFiles"`
	TestsRun       []PatchTestRun `json:"testsRun,omitempty"`
	Risk           string         `json:"risk"`
}

PatchResultEnvelope is the harness-v2 terminal result of a security patch task. The agent applies the fix to the workspace and returns this envelope as its only output; it never writes artifact files. The authoritative diff is derived by the controller from the governed publication, so the envelope carries only the agent's account of what it changed.

type PatchResultExpectation added in v0.2.0

type PatchResultExpectation struct {
	RepositoryScan string
	FindingID      string
}

PatchResultExpectation is the controller-owned identity a patch result must match exactly.

type PatchSummaryArtifact

type PatchSummaryArtifact struct {
	SchemaVersion int            `json:"schemaVersion"`
	FindingID     string         `json:"findingId"`
	Summary       string         `json:"summary"`
	ChangedFiles  []string       `json:"changedFiles"`
	TestsRun      []PatchTestRun `json:"testsRun,omitempty"`
	Risk          string         `json:"risk"`
}

func NormalizePatchSummaryArtifact added in v0.2.0

func NormalizePatchSummaryArtifact(artifact PatchSummaryArtifact) (*PatchSummaryArtifact, error)

NormalizePatchSummaryArtifact applies the bounded, credential-rejecting validation every durable patch summary must pass, whether it arrived as a harness-v2 terminal result or as a pre-existing artifact written through the upload API. Summary text, changed-file paths, and test commands are agent-controlled and persist in artifacts, status, and PR bodies, so a credential-shaped value in any of them fails closed; the value itself is deliberately kept out of the error.

func ParsePatchResult added in v0.2.0

func ParsePatchResult(data []byte, expected PatchResultExpectation) (*PatchSummaryArtifact, error)

ParsePatchResult strictly decodes a terminal patch result and requires the exact repository scan and finding identity. It returns the bounded patch summary the controller persists alongside the publication-derived diff.

type PatchTestRun

type PatchTestRun struct {
	Command  string `json:"command"`
	ExitCode int    `json:"exitCode"`
}

type PolicySource

type PolicySource struct {
	Name   string `json:"name,omitempty"`
	Key    string `json:"key,omitempty"`
	Digest string `json:"digest,omitempty"`
}

func (PolicySource) String

func (s PolicySource) String() string

type PromptPolicy

type PromptPolicy struct {
	CustomScanInstructions string
	FalsePositivePolicy    string
	PolicyDigest           string
	CustomScanSource       string
	FalsePositiveSource    string
}

type ReviewContextIncludedFile

type ReviewContextIncludedFile struct {
	Path               string                   `json:"path"`
	Role               string                   `json:"role"`
	Bytes              int                      `json:"bytes"`
	IncludedBytes      int                      `json:"includedBytes"`
	IncludedLineRanges []ReviewContextLineRange `json:"includedLineRanges"`
	Excerpt            string                   `json:"excerpt,omitempty"`
	Truncated          bool                     `json:"truncated"`
	Readable           bool                     `json:"readable"`
	SkippedReason      *string                  `json:"skippedReason"`
}

type ReviewContextLineRange

type ReviewContextLineRange struct {
	StartLine int `json:"startLine"`
	EndLine   int `json:"endLine"`
}

type ReviewContextManifest

type ReviewContextManifest struct {
	SchemaVersion     int                         `json:"schemaVersion"`
	SliceID           string                      `json:"sliceId"`
	ChangedFiles      []string                    `json:"changedFiles,omitempty"`
	ChangedLineRanges []ChangedLineRange          `json:"changedLineRanges,omitempty"`
	IncludedFiles     []ReviewContextIncludedFile `json:"includedFiles"`
	OmittedFiles      []ReviewContextOmittedFile  `json:"omittedFiles,omitempty"`
	PromptBytes       int                         `json:"promptBytes"`
	ApproximateTokens int                         `json:"approximateTokens"`
	Prompt            string                      `json:"prompt,omitempty"`
}

func BuildReviewContext

func BuildReviewContext(root string, slice store.ReviewSlice, opts ReviewContextOptions) (string, ReviewContextManifest, error)

BuildReviewContext builds a bounded deterministic prompt excerpt and manifest for a review slice.

func ParseReviewContextManifest

func ParseReviewContextManifest(data []byte) (*ReviewContextManifest, error)

ParseReviewContextManifest parses and minimally validates a review context manifest.

func ParseTrustedReviewContextManifest added in v0.2.0

func ParseTrustedReviewContextManifest(data []byte) (*ReviewContextManifest, string, error)

ParseTrustedReviewContextManifest validates the mapper-owned context used as an evidence boundary for a review Task.

type ReviewContextOmittedFile

type ReviewContextOmittedFile struct {
	Path   string `json:"path"`
	Role   string `json:"role"`
	Reason string `json:"reason"`
}

type ReviewContextOptions

type ReviewContextOptions struct {
	MaxFiles int
	MaxBytes int
}

type ReviewSlicesArtifact

type ReviewSlicesArtifact struct {
	SchemaVersion        int                 `json:"schemaVersion"`
	BaseCommit           string              `json:"baseCommit,omitempty"`
	HeadCommit           string              `json:"headCommit,omitempty"`
	ChangedFilesComputed bool                `json:"changedFilesComputed,omitempty"`
	ChangedFiles         []string            `json:"changedFiles,omitempty"`
	ChangedLineRanges    []ChangedLineRange  `json:"changedLineRanges,omitempty"`
	DiffSummary          string              `json:"diffSummary,omitempty"`
	ChangedFilesError    string              `json:"changedFilesError,omitempty"`
	Slices               []store.ReviewSlice `json:"slices"`
}

ReviewSlicesArtifact is the deterministic mapper output.

func ParseReviewSlicesArtifact

func ParseReviewSlicesArtifact(data []byte) (*ReviewSlicesArtifact, error)

ParseReviewSlicesArtifact parses and minimally validates mapper output.

type ScannerPolicy

type ScannerPolicy struct {
	CustomScanInstructions string
	FalsePositivePolicy    string
	CustomScanSource       PolicySource
	FalsePositiveSource    PolicySource
	Digest                 string
}

func LoadScannerPolicy

func LoadScannerPolicy(ctx context.Context, reader client.Reader, namespace string, spec corev1alpha1.RepositoryScanSpec) (ScannerPolicy, error)

func (ScannerPolicy) PromptPolicy

func (p ScannerPolicy) PromptPolicy() PromptPolicy

type ThreatModelResultEnvelope added in v0.2.0

type ThreatModelResultEnvelope struct {
	SchemaVersion  int    `json:"schemaVersion"`
	Kind           string `json:"kind"`
	RepositoryScan string `json:"repositoryScan"`
	ScanID         string `json:"scanId"`
	PolicyDigest   string `json:"policyDigest"`
	ThreatModel    string `json:"threatModel"`
}

ThreatModelResultEnvelope is the only accepted terminal result for the threat-model agent stage.

type ValidationArtifact

type ValidationArtifact struct {
	Version            int                            `json:"version"`
	FindingID          string                         `json:"finding_id"`
	Status             string                         `json:"status"`
	Summary            string                         `json:"summary"`
	ValidationSteps    []string                       `json:"validation_steps,omitempty"`
	Reproduction       string                         `json:"reproduction,omitempty"`
	AttackPathAnalysis string                         `json:"attack_path_analysis,omitempty"`
	Likelihood         string                         `json:"likelihood,omitempty"`
	Impact             string                         `json:"impact,omitempty"`
	Assumptions        []string                       `json:"assumptions,omitempty"`
	Controls           []string                       `json:"controls,omitempty"`
	Blindspots         []string                       `json:"blindspots,omitempty"`
	Evidence           ValidationArtifactEvidenceRefs `json:"evidence,omitempty"`
}

ValidationArtifact captures the per-finding validator/repro payload.

func ParseValidationResult added in v0.2.0

func ParseValidationResult(data []byte, expected ValidationResultExpectation) (*ValidationArtifact, error)

ParseValidationResult strictly decodes a terminal validation result and restricts new evidence to the already accepted finding evidence boundary.

type ValidationArtifactEvidenceRefs

type ValidationArtifactEvidenceRefs []store.FindingEvidenceRef

ValidationArtifactEvidenceRefs accepts the structured validation evidence array and the existing shorthand forms used by validation agents.

func (*ValidationArtifactEvidenceRefs) UnmarshalJSON

func (e *ValidationArtifactEvidenceRefs) UnmarshalJSON(data []byte) error

type ValidationResultEnvelope added in v0.2.0

type ValidationResultEnvelope struct {
	SchemaVersion  int                `json:"schemaVersion"`
	Kind           string             `json:"kind"`
	RepositoryScan string             `json:"repositoryScan"`
	ScanID         string             `json:"scanId"`
	FindingID      string             `json:"findingId"`
	PolicyDigest   string             `json:"policyDigest"`
	Validation     ValidationArtifact `json:"validation"`
}

ValidationResultEnvelope is the only accepted terminal result for the per-finding validation stage.

type ValidationResultExpectation added in v0.2.0

type ValidationResultExpectation struct {
	Binding AgentResultBinding
	Finding *store.Finding
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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