Documentation
¶
Overview ¶
Package scan is the security pipeline: orchestrator, scanner stages S1–S10, the LLM judge interface, the gate, and provenance signing. It operates on the exact archive bytes that will ship, never the repo.
Index ¶
- Constants
- Variables
- func CacheableStages() []string
- func CheckSubmissionPolicy(pol Policy, in registry.PolicySubmission) []error
- func DeclaredMCPServers(manifestJSON []byte) []declaredServer
- func DecodeKnowledgeRecord(detail []byte, into any) error
- func DecodeSubagentRecord(detail []byte, into any) error
- func EnqueueAttestSweepIfBehind(ctx context.Context, st *store.Store, q queue.Client, log *slog.Logger, ...)
- func EnqueueNewRulesetWork(ctx context.Context, q queue.Client, log *slog.Logger, reg RulesetRegistration)
- func EnqueueReattestSweepIfBehind(ctx context.Context, st *store.Store, q queue.Client, log *slog.Logger, ...)
- func ExtractREADME(ctx context.Context, blobs BlobGetter, archiveKey string, archiveSize *int64) ([]byte, error)
- func KeyMatchJSON(keyID string) []byte
- func LoosensBaseline(baseline, org Policy) bool
- func PinnedJudgeModel(model string) bool
- func ReadmeIndexText(raw []byte) string
- func RubricHash(parts ...string) string
- func SeverityAtLeast(a, b string) bool
- type AttestSummary
- type BedrockJudge
- type BlobGetter
- type ClassifierJudge
- type Confidence
- type DSSEEnvelope
- type DSSESignature
- type DraftClaim
- type DraftProvenance
- type DraftRevision
- type ExecTool
- type ExternalTools
- type ExtractLimits
- type FileEntry
- type FileSigner
- type Finding
- type GateDecision
- type GateInput
- type GitHistory
- type HTTPJudge
- type HTTPOSV
- type HTTPRegistries
- type InTotoStatement
- type Input
- type JudgeCategory
- type JudgeConfig
- type JudgeContent
- type JudgeFile
- type JudgeProvider
- type JudgeUsage
- type JudgeVerdict
- type KMSAPI
- type KMSOptions
- type KMSSigner
- type MCPScanCache
- type MCPScanRecord
- type MCPSweepSummary
- type MemoryMCPScanCache
- type NoneProvider
- type OSVClient
- type OSVPackage
- type OSVVulnerability
- type OfflineOSV
- type OfflineRegistries
- type Orchestrator
- func (o *Orchestrator) Run(ctx context.Context, p RunParams) RunResult
- func (o *Orchestrator) ScanPack(ctx context.Context, files []PackFile) PackReport
- func (o *Orchestrator) ScanProse(ctx context.Context, files []PackFile) PackReport
- func (o *Orchestrator) SetExternalTools(t ExternalTools)
- func (o *Orchestrator) SetMCPScanning(client OSVClient, cache MCPScanCache)
- func (o *Orchestrator) SetMetrics(m *metrics.Metrics)
- func (o *Orchestrator) SetPackageRegistries(r PackageRegistries)
- type Outcome
- type PackFile
- type PackFinding
- type PackPart
- type PackRead
- type PackReport
- type PackReview
- type PackStage
- type PackageRegistries
- type PersonaJudge
- type PersonaVerdict
- type Pipeline
- func (p *Pipeline) AttestSweep(ctx context.Context) (AttestSummary, error)
- func (p *Pipeline) Block(ctx context.Context, agentID uuid.UUID, reason string, ev audit.Event) (int, error)
- func (p *Pipeline) CheckSubmission(ctx context.Context, in registry.PolicySubmission) []error
- func (p *Pipeline) DecideReview(ctx context.Context, in ReviewDecision) (handedOff bool, err error)
- func (p *Pipeline) FailToReview(ctx context.Context, v storegen.AgentVersion, agent storegen.GetAgentByIDRow, ...) error
- func (p *Pipeline) MCPScanningEnabled() bool
- func (p *Pipeline) MCPSweep(ctx context.Context) (sum MCPSweepSummary, err error)
- func (p *Pipeline) PublishAdvisory(ctx context.Context, agentID uuid.UUID, ...) error
- func (p *Pipeline) PublishApproved(ctx context.Context, itemID uuid.UUID) error
- func (p *Pipeline) Quarantine(ctx context.Context, versionID uuid.UUID, reason string, ev audit.Event) error
- func (p *Pipeline) ReattestSweep(ctx context.Context) error
- func (p *Pipeline) ReattestSweepWithSummary(ctx context.Context) (ReattestSummary, error)
- func (p *Pipeline) ReconcileApprovedReviews(ctx context.Context) (int, error)
- func (p *Pipeline) ReconcileStuckScans(ctx context.Context) (int, error)
- func (p *Pipeline) RedoReviewQueue(ctx context.Context) error
- func (p *Pipeline) RedoReviewQueueWithSummary(ctx context.Context) (RedoSummary, error)
- func (p *Pipeline) RegisterHandlers(q queue.Client)
- func (p *Pipeline) Reinstate(ctx context.Context, agentID uuid.UUID, reason string) (int, error)
- func (p *Pipeline) RescanSweep(ctx context.Context) error
- func (p *Pipeline) RescanSweepWithSummary(ctx context.Context) (RescanSummary, error)
- func (p *Pipeline) Scan(ctx context.Context, versionID uuid.UUID, trigger string) error
- func (p *Pipeline) SetDraftProvenance(d DraftProvenance)
- func (p *Pipeline) SetGitHistory(h GitHistory)
- func (p *Pipeline) SetMCPScanning(client OSVClient, cache MCPScanCache)
- func (p *Pipeline) SetMetrics(m *metrics.Metrics)
- func (p *Pipeline) SetNotifier(n notify.Notifier)
- func (p *Pipeline) SetOrchestratorForTest(o *Orchestrator)
- func (p *Pipeline) SetPackageRegistries(r PackageRegistries)
- func (p *Pipeline) SetRescanBatchForTest(n int32)
- func (p *Pipeline) SetRulesetForTest(id uuid.UUID, semver string)
- func (p *Pipeline) VersionSubmitted(ctx context.Context, versionID uuid.UUID) error
- type PipelineDeps
- type Policy
- type PublishApprovedArgs
- type PublishPredicate
- type QueuePipeline
- type ReattestSummary
- type ReattestSweepArgs
- type RedoSummary
- type ReinstateScanArgs
- type Report
- type RescanSummary
- type RescanSweepArgs
- type Resume
- type ReviewDecision
- type RotationOptions
- type RulesetRegistration
- type RunParams
- type RunResult
- type S1Inventory
- type S2Secrets
- type S3S4Content
- type S5Judge
- type S6Scripts
- type S7MCPServers
- type S8Metadata
- type S9ReleaseDiff
- type SKKnowledge
- type ScanJobArgs
- type ScanRunRef
- type Severity
- type ShippedPackScan
- type Signer
- type SignerOptions
- type SigningKeyRegistration
- type Stage
- type StageResult
- type StaticProvider
- type Subagent
- type SubagentReach
- type Subject
- type TypeSafeJudge
- func (j *TypeSafeJudge) InputLimit() int
- func (j *TypeSafeJudge) Judge(ctx context.Context, content JudgeContent) (JudgeVerdict, error)
- func (j *TypeSafeJudge) JudgePersona(ctx context.Context, manifestJSON []byte, persona JudgeFile) (PersonaVerdict, error)
- func (j *TypeSafeJudge) ModelID() string
- func (j *TypeSafeJudge) Name() string
- func (j *TypeSafeJudge) RequiresHumanReview() bool
- type UnconfiguredProvider
Constants ¶
const ( JobScanVersion = "scan.version" JobRescanSweep = "scan.rescan_sweep" // JobAttestSweep signs every published version that has no // attestation. JobAttestSweep = "scan.attest_sweep" // JobScanReconcile is the watchdog: sweep versions parked in // `scanning` past the 30-minute cap into review. JobScanReconcile = "scan.reconcile" // JobReattestSweep countersigns every attestation with a newly // registered signing key. On the core queue: it // touches the database and the signer, never untrusted content. JobReattestSweep = "scan.reattest_sweep" // JobPublishApproved publishes and signs a version whose review item a // keyless role approved. On the core queue: it signs, and // touches no untrusted content. JobPublishApproved = "scan.publish_approved" )
Job kinds handled by the scan worker.
const AIReviewNotConfigured = "AI Review not configured"
AIReviewNotConfigured is the review's note on a deployment whose judge provider is none.
const JobMCPSweep = "scan.mcp_sweep"
JobMCPSweep is the queue job kind; the worker process enqueues it once a day (and at start-up), and the handler is idempotent.
const JobRedoReviewQueue = "scan.redo_review_queue"
JobRedoReviewQueue judges every version waiting in the review queue again under a newly registered ruleset and publishes what now passes the gate Enqueued beside the catalogue sweep, which covers published versions only. On the sandbox queue: it scans untrusted content.
const JobReinstateScan = "scan.reinstate_version"
JobReinstateScan judges one version that a platform reinstate released from a block or a quarantine. On the sandbox queue: it scans untrusted content.
const KnowledgeStageID = "SK"
KnowledgeStageID is the stage's id and its findings' scanner prefix.
const MaxIndexedReadmeBytes = 64 << 10
MaxIndexedReadmeBytes bounds the README text denormalized onto the agent row for the weight-C search index.
to_tsvector runs inside a BEFORE trigger on every agent write, and its output is capped at 1 MB — past that Postgres errors, which would turn an oversized README into a failed publish. 64 KB is far more prose than any agent's README carries (agents are small by design) and keeps the trigger's cost bounded and predictable.
const PackReportSchema = "agentry.knowledge-scan/v1"
PackReportSchema names the report's shape.
const PredicateType = attest.PredicateType
PredicateType is the Agentry publish attestation predicate.
const SigningAlgorithm = "ecdsa-p256-sha256"
SigningAlgorithm is the one algorithm the registry signs with; every key the registry publishes or records carries it.
const SourceDrafterRevision = "drafter-revision"
SourceDrafterRevision is the source of a version the scan proved was a hosted Drafter revision of its agent's current release.
const StuckScanCap = 30 * time.Minute
StuckScanCap is the scan timeout: a version in `scanning` longer than this had its scan die, and the watchdog routes it to review.
Variables ¶
var ( VerifyEnvelope = attest.VerifyEnvelope BuildStatement = attest.BuildStatement )
VerifyEnvelope and BuildStatement live in pkg/attest; re-exported for the server-side call sites and tests.
var DefaultLimits = archive.DefaultLimits
DefaultLimits are the release-archive quotas.
var ErrAlreadyDecided = errors.New("scan: review item already decided")
ErrAlreadyDecided is returned when a decision reaches a review item that is no longer pending (a second reviewer acting on a stale page).
var ErrArchiveViolation = archive.ErrArchiveViolation
ErrArchiveViolation marks a rejected archive (structural attack).
var ErrNoReadme = errors.New("scan: archive has no README")
ErrNoReadme means the release archive carries no README.
var ErrNoSigningKey = errors.New("scan: this process holds no signing key; the worker signs")
ErrNoSigningKey is returned when a process that holds no signing key is asked to sign: the api and git roles run without the key, and a version is never published without its attestation, so the transition that needed the signature does not happen there.
var ErrRotationWithoutHandover = errors.New("scan: the signing key changed with no handover")
ErrRotationWithoutHandover refuses a start on a new signing key that the active key has not handed over to.
var Extract = archive.Extract
Extract unpacks a tar.zst archive with full hardening (see archive.Extract).
Functions ¶
func CacheableStages ¶
func CacheableStages() []string
CacheableStages are the deterministic scanners a rescan may answer from the results cache keyed (digest, scanner, ruleset). S1 always runs (it is the inventory), S5 is the judge (re-adjudicated only on major bumps), S9 depends on the previous published version rather than on these bytes.
func CheckSubmissionPolicy ¶
func CheckSubmissionPolicy(pol Policy, in registry.PolicySubmission) []error
CheckSubmissionPolicy is the pure form: effective policy + submission → blocking issues. Exported so the knobs are testable without a database.
func DeclaredMCPServers ¶
func DeclaredMCPServers(manifestJSON []byte) []declaredServer
DeclaredMCPServers lists a manifest's declared servers (ecosystem "npm" or "pypi"). The pipeline uses it to record the version ↔ server join.
func DecodeKnowledgeRecord ¶
DecodeKnowledgeRecord reads SK's record out of its stage row's detail into into (a slice of ShippedPackScan, or the API's shape of it); a detail without one leaves into as it is.
func DecodeSubagentRecord ¶ added in v0.6.1002
DecodeSubagentRecord reads S7's record of the subagents out of its stage row's detail into into (a slice of Subagent, or the API's shape of it); a detail without one leaves into as it is.
func EnqueueAttestSweepIfBehind ¶
func EnqueueAttestSweepIfBehind(ctx context.Context, st *store.Store, q queue.Client, log *slog.Logger, signer Signer)
EnqueueAttestSweepIfBehind enqueues the attest sweep when any published version has no attestation. The state of the table is the trigger, as for the re-attestation sweep, so a sweep that failed part way completes at the next start and a clean table enqueues nothing.
func EnqueueNewRulesetWork ¶
func EnqueueNewRulesetWork(ctx context.Context, q queue.Client, log *slog.Logger, reg RulesetRegistration)
EnqueueNewRulesetWork kicks off the catalogue sweep when a ruleset semver is recorded for the first time, and the redo of the review queue beside it: the sweep judges published versions again, the redo the versions waiting for a person, and publishes those the gate now passes. Together they re-check already-published versions against improved rules, which is the point of versioning the bundle. A restart on the same semver enqueues neither.
func EnqueueReattestSweepIfBehind ¶
func EnqueueReattestSweepIfBehind(ctx context.Context, st *store.Store, q queue.Client, log *slog.Logger, signer Signer, reg SigningKeyRegistration)
EnqueueReattestSweepIfBehind enqueues the re-attestation sweep when any attestation lacks the signer's signature: a rotation, a key rolled back to, a sweep that failed part way, or an enqueue that was lost — every one completes at the next start, because the trigger is the state of the table, not the memory of having enqueued once. A start on a key every attestation already carries enqueues nothing.
func ExtractREADME ¶
func ExtractREADME(ctx context.Context, blobs BlobGetter, archiveKey string, archiveSize *int64) ([]byte, error)
ExtractREADME pulls the README out of a release archive. It reuses the hardened extractor rather than reading the tar directly, so both the rendering path and the search-index path get the same traversal and decompression-bomb protections the scanners do.
func KeyMatchJSON ¶
KeyMatchJSON is the jsonb containment probe for "carries a signature by this key": `[{"keyid": "<id>"}]`. A key id is base64url text, so the encoding cannot fail.
func LoosensBaseline ¶
LoosensBaseline reports whether org would loosen baseline on any knob the API rejects outright. Merge already clamps silently; this gives the author a clear error for the most confusing case — a looser maxAutoPublishSeverity or downgrading wildcardEgress from reject. A requireHumanReview below the baseline's ("never" under a condition, a condition under "always") is a loosening; a capability condition that names other capabilities than the baseline's is not, because Merge keeps both sets.
func PinnedJudgeModel ¶
PinnedJudgeModel reports whether a judge model id names one version — it carries a dotted number — rather than a moving alias (`jev-latest`, `jev-preview`, a bare family name). Thresholds are calibrated per version and the vendor's aliases move without a changelog, so the factory refuses anything else.
func ReadmeIndexText ¶
ReadmeIndexText normalizes README bytes into something safe to store in the tsvector source column: valid UTF-8, no NUL bytes (Postgres text rejects them), and truncated on a rune boundary.
func RubricHash ¶
RubricHash derives the judge_prompt_hash recorded on a scan run (prompt + model id are versioned, the hash is recorded per run, for reproducibility and appeals). Providers hash the exact rubric text they adjudicate with, so changing a rule changes the hash on every later run.
func SeverityAtLeast ¶
SeverityAtLeast reports whether severity a is at least b (by name).
Types ¶
type AttestSummary ¶
AttestSummary is what an attest sweep did.
type BedrockJudge ¶
type BedrockJudge struct {
// contains filtered or unexported fields
}
BedrockJudge adjudicates through Amazon Bedrock's Converse API (the SaaS provider). Same judge contract as HTTPJudge: no tools, temperature 0, bounded output, content presented as data under the shared rubric template, fail closed toward review on any error. Credentials come from the task role / default chain — there is no API key to configure — and the model id from AGENTRY_JUDGE_MODEL (terraform sets it; the default below only keeps the path runnable).
func NewBedrockJudge ¶
func NewBedrockJudge(ctx context.Context, cfg JudgeConfig) (*BedrockJudge, error)
NewBedrockJudge builds the provider from the default AWS credential chain. Region comes from cfg.Region (AGENTRY_JUDGE_REGION) when set, else the SDK's own resolution (AWS_REGION, profile, IMDS).
func (*BedrockJudge) InputLimit ¶
func (j *BedrockJudge) InputLimit() int
InputLimit implements JudgeProvider: the chat providers' limit.
func (*BedrockJudge) Judge ¶
func (j *BedrockJudge) Judge(ctx context.Context, content JudgeContent) (JudgeVerdict, error)
Judge implements JudgeProvider.
func (*BedrockJudge) ModelID ¶
func (j *BedrockJudge) ModelID() string
ModelID implements JudgeProvider: the Bedrock model id.
func (*BedrockJudge) RequiresHumanReview ¶
func (j *BedrockJudge) RequiresHumanReview() bool
RequiresHumanReview implements JudgeProvider: a live judge scores.
type BlobGetter ¶
BlobGetter is the slice of registry.BlobStore this helper needs. Declared here rather than importing registry because registry cannot import scan — the pipeline dependency runs the other way.
type ClassifierJudge ¶
type ClassifierJudge struct {
// contains filtered or unexported fields
}
ClassifierJudge is the PromptGuard-class provider ("classifier"): a text-classification endpoint that returns per-label probabilities for prompt-injection / jailbreak content. It speaks the Hugging Face text-classification wire shape, which the Inference API, TGI/TEI and most self-hosted servers share:
POST <baseUrl> {"inputs": "<text>"}
200 [[{"label":"INJECTION","score":0.98},{"label":"BENIGN","score":0.02}]]
(a flat [{label,score}] list is accepted too). A classifier scores ONE rubric axis — C1_injection — so this provider forces human review (RequiresHumanReview = true, like `none`): it adds evidence for the reviewer and can never auto-clear a version, because C2–C6 go unscored. Operators who want auto-clearing need an LLM provider; a classifier is a cheap, deterministic pre-screen, not a judge of the whole rubric.
func NewClassifierJudge ¶
func NewClassifierJudge(cfg JudgeConfig) *ClassifierJudge
NewClassifierJudge builds the provider. BaseURL is the full classify URL (config validates it is set); APIKey is optional (Bearer); Model names the deployed classifier for the record and defaults to "prompt-guard".
func (*ClassifierJudge) InputLimit ¶
func (j *ClassifierJudge) InputLimit() int
InputLimit implements JudgeProvider: a call is split into requests of classifierMaxInput, and eight of them bound one call.
func (*ClassifierJudge) Judge ¶
func (j *ClassifierJudge) Judge(ctx context.Context, content JudgeContent) (JudgeVerdict, error)
Judge implements JudgeProvider: the C1 score is the max injection probability over all chunks of all prose files, mapped 0.5/0.7/0.9 → 1/2/3.
func (*ClassifierJudge) ModelID ¶
func (j *ClassifierJudge) ModelID() string
ModelID implements JudgeProvider: the classifier's Model is a deployment label ("prompt-guard" by default), not a versioned model id, so the run keeps recording the provider's name.
func (*ClassifierJudge) Name ¶
func (j *ClassifierJudge) Name() string
Name implements JudgeProvider.
func (*ClassifierJudge) RequiresHumanReview ¶
func (j *ClassifierJudge) RequiresHumanReview() bool
RequiresHumanReview implements JudgeProvider: one axis is not the rubric.
type Confidence ¶
type Confidence string
Confidence is a finding confidence.
const ( ConfLow Confidence = "low" ConfMedium Confidence = "medium" ConfHigh Confidence = "high" )
Confidences.
type DSSEEnvelope ¶
type DSSEEnvelope = attest.DSSEEnvelope
Aliases for the promoted public attestation API (pkg/attest).
type DSSESignature ¶
type DSSESignature = attest.DSSESignature
Aliases for the promoted public attestation API (pkg/attest).
type DraftClaim ¶
type DraftClaim struct {
Run uuid.UUID
Account uuid.UUID
AgentID uuid.UUID
Namespace string
Name string
Baseline string
BaselineDigest string
Proof draftproof.Proof
}
DraftClaim is what the pipeline asks DraftProvenance about one version: the draft run the upload named, who submitted it, the agent, S9's baseline for it (the version and its archive digest), and the proof of the submitted files (pkg/draftproof). Every field is the registry's own reading; none is taken from the request but the run's id. It carries no tier and no balance: the verdict never reads either.
type DraftProvenance ¶
type DraftProvenance interface {
Revised(ctx context.Context, c DraftClaim) (bool, error)
}
DraftProvenance answers whether a claimed draft holds: the account ran draft Run, it revised Namespace/Name at Baseline (whose archive is BaselineDigest), and the proof its sandbox host recorded is Proof. Any mismatch, an unknown run or another account's is false with no error; an error is a lookup that could not be made, and the scan is retried rather than read it as either answer. The core has none: without an extension that answers, no version is a Drafter revision.
type DraftRevision ¶
DraftRevision is what S9 reads of a version proved to be a Drafter revision: the draft, the baseline it revised, and the files the proof covers on each side (this version's manifest and instruction file, and the baseline's), which S9's content diff and escalation leave out. Every other file is diffed as for any version.
type ExecTool ¶
type ExecTool struct {
// Bin is the binary path. ResolveExecTool turns "auto" into a PATH lookup.
Bin string
// Rules is the rules file/dir for tools that take one; none do today.
Rules string
// Timeout bounds one invocation; 0 means execToolDefaultTimeout.
Timeout time.Duration
}
ExecTool describes one external binary.
type ExternalTools ¶
type ExternalTools struct {
Gitleaks *ExecTool
}
ExternalTools are the external scanners behind interfaces: gitleaks for S2 and the OSV client for declared MCP servers (SetMCPScanning).
type ExtractLimits ¶
type ExtractLimits = archive.ExtractLimits
ExtractLimits bounds a safe extraction (release-archive quotas + a decompression cap).
type FileEntry ¶
type FileEntry struct {
Path string
Size int64
IsText bool
IsImage bool
Content []byte // populated for text files under the scan cap
}
FileEntry is one inventoried file (S1 output).
type FileSigner ¶
type FileSigner struct {
// contains filtered or unexported fields
}
FileSigner signs with a local ECDSA P-256 key.
func NewFileSigner ¶
func NewFileSigner(keyPath string, devMode bool) (*FileSigner, error)
NewFileSigner loads (or, in dev with keyPath=="", generates) a P-256 key.
func (*FileSigner) PublicKeyPEM ¶
func (s *FileSigner) PublicKeyPEM() string
PublicKeyPEM implements Signer.
func (*FileSigner) Sign ¶
func (s *FileSigner) Sign(stmt InTotoStatement) (DSSEEnvelope, error)
Sign implements Signer: DSSE PAE over the in-toto statement.
func (*FileSigner) SignPayload ¶
func (s *FileSigner) SignPayload(payloadType string, payload []byte) (DSSESignature, error)
SignPayload implements Signer.
type Finding ¶
type Finding struct {
Scanner string // "S1".."S10", optionally with a rule id: "S4/inj-override-001"
Severity Severity
Confidence Confidence
Title string
FilePath string
LineStart int
LineEnd int
Excerpt string
Detail map[string]any
Taxonomy []string // OWASP ids
}
Finding is one pipeline result (mirrors the findings table). It is the common currency across stages; rules.Finding (S3/S4) converts in.
type GateDecision ¶
type GateDecision struct {
Outcome Outcome
// Reason is a short human-readable explanation.
Reason string
// Queue is "platform" or "org" when Outcome is needs_review.
Queue string
// WorstSeverity is the worst gating severity considered.
WorstSeverity Severity
// contains filtered or unexported fields
}
GateDecision is the gate output.
func Evaluate ¶
func Evaluate(in GateInput) GateDecision
Evaluate applies the gate under the effective policy. Pure function: findings + policy → decision. This is the fail-closed heart of the pipeline; the property tests pin that nothing reaches Publish that shouldn't.
type GateInput ¶
type GateInput struct {
// Findings are the open (post-dedup, non-dismissed) findings.
Findings []Finding
// Policy is the effective (merged) policy.
Policy Policy
// JudgeForcesReview is true when the judge provider requires human
// review regardless of scores (the `none` provider) or a stage
// failed closed.
JudgeForcesReview bool
// DeclaredCapabilities are the manifest's declared capability tokens
// (for policy whenCapabilities and wildcard-egress checks).
DeclaredCapabilities map[string]bool
// WildcardEgress is true when the manifest asks for the network
// without naming where: "*" egress, or a browser
// whose scope is any public site (unrestrictedNetwork).
WildcardEgress bool
// Public marks a public agent (platform review queue for high).
Public bool
// NamespaceIsOrg marks an agent in an ORG namespace. Only those have an
// org queue and an org security_reviewer to staff it; a personal-namespace
// agent routed to "org" produces a review item with no org, which no
// listing shows and no principal can decide.
NamespaceIsOrg bool
}
GateInput is what the gate decides on.
type GitHistory ¶
type GitHistory interface {
HistoryPatch(ctx context.Context, repoID uuid.UUID, commit string) (io.ReadCloser, error)
}
PipelineDeps bundles the pipeline's collaborators. GitHistory is the repository seam S2's history scan reads through; the git and all roles provide gitsrv.RepoStore, a worker without repo storage leaves it nil and S2 reports "not scanned".
type HTTPJudge ¶
type HTTPJudge struct {
// contains filtered or unexported fields
}
HTTPJudge adjudicates against any endpoint speaking one of the two common chat wire protocols: OpenAI Chat Completions (provider "openai") or Anthropic Messages (provider "anthropic"). Hosted APIs and self-hosted gateways both work; BaseURL is the API root ("/v1" is appended when missing). Same judge contract as every provider: no tools, temperature 0, bounded output, content presented as data.
func NewHTTPJudge ¶
func NewHTTPJudge(cfg JudgeConfig) *HTTPJudge
NewHTTPJudge builds an HTTPJudge from cfg. The caller guarantees Provider is "openai" or "anthropic" and BaseURL/APIKey are set (config validates).
func (*HTTPJudge) InputLimit ¶
InputLimit implements JudgeProvider.
func (*HTTPJudge) Judge ¶
func (j *HTTPJudge) Judge(ctx context.Context, content JudgeContent) (verdict JudgeVerdict, err error)
Judge implements JudgeProvider over the configured endpoint. Any failure (transport, non-200, unparseable verdict) returns an error: S5 fails closed toward review.
func (*HTTPJudge) RequiresHumanReview ¶
RequiresHumanReview implements JudgeProvider: a live judge scores, so its verdicts follow the normal gate.
type HTTPOSV ¶
type HTTPOSV struct {
// BaseURL is the API origin, e.g. https://api.osv.dev.
BaseURL string
// Client is the HTTP client; nil uses a 20s-timeout default.
Client *http.Client
// MaxAdvisories caps the advisory bodies fetched per Query (0 = 200);
// beyond it, advisories are reported by id with no summary.
MaxAdvisories int
}
HTTPOSV is the OSVClient that consults an OSV API (api.osv.dev or a mirror). Lookups are batched through /v1/querybatch and the advisory bodies fetched once per distinct id, so N declared servers cost ceil(N/queryBatchSize) + distinct-advisory requests.
func (*HTTPOSV) Query ¶
func (c *HTTPOSV) Query(ctx context.Context, pkgs []OSVPackage) (map[string][]OSVVulnerability, error)
Query implements OSVClient.
type HTTPRegistries ¶
type HTTPRegistries struct {
// NPM is the npm registry origin, e.g. https://registry.npmjs.org.
NPM string
// PyPI is PyPI's origin, e.g. https://pypi.org.
PyPI string
// Client is the HTTP client; nil uses a 20s-timeout default.
Client *http.Client
}
HTTPRegistries asks the public npm registry and PyPI's JSON API, the registries the runner installs from by default, through the worker's egress proxy like the OSV client (the default transport reads the proxy variables).
type InTotoStatement ¶
type InTotoStatement = attest.InTotoStatement
Aliases for the promoted public attestation API (pkg/attest).
type Input ¶
type Input struct {
// Dir is the extracted archive root (read-only to stages).
Dir string
// Files is the S1 inventory (populated before S2–S9 run).
Files []FileEntry
// Manifest is the parsed, validated manifest (capabilities drive S6).
ManifestJSON []byte
// Version is this version's semver string; S9 classifies the bump size
// against PrevVersion (a patch bump that changes behaviour is the
// rug-pull shape).
Version string
// Summary is the agent's one-line summary, one of the two ranked fields
// S8's keyword-stuffing heuristic reads.
Summary string
// PrevArchiveDir is the previous published version's extracted archive
// for S9 release-diff; empty on first publish.
PrevArchiveDir string
// PrevManifestJSON is the previous version's manifest for S9.
PrevManifestJSON []byte
// PrevVersion is the previous published version's semver string.
PrevVersion string
// AccountAgeDays and RecentPublishCount feed S8 publisher signals.
AccountAgeDays int
RecentPublishCount int
// IPClusterAccounts / IPClusterVersions: distinct submitting accounts and
// versions that share this version's submitting-address hash in the last
// 24 hours (0 when the signal is off). Counts include this
// submission.
IPClusterAccounts int
IPClusterVersions int
// SubmitterIsStaff: the submitter is platform staff at scan time, which
// exempts the version from S8's two publisher signals.
SubmitterIsStaff bool
// Source is the version's publish source ("git-tag" | "cli-upload" |
// "drafter-revision").
Source string
// DraftRevision is set when the version is a Drafter revision of S9's
// baseline, proved by the extension's DraftProvenance:
// S9 leaves the proved files out of its content diff and escalation.
DraftRevision *DraftRevision
// History streams the git history reachable from the tagged commit as a
// patch (see gitsrv.HistoryPatch); nil when the scanning role has no
// repository access. Only meaningful for Source == "git-tag".
History func(ctx context.Context) (io.ReadCloser, error)
// Subagents are a persistent release's subagents as the pipeline
// resolved them against the registry before the stages ran
// (resolveSubagents); S7 reports each that does not resolve.
Subagents []Subagent
}
Input is the unpacked archive plus context a stage may need.
type JudgeCategory ¶
type JudgeCategory string
JudgeCategory is one rubric axis (S5 categories C1–C6).
const ( CatInjection JudgeCategory = "C1_injection" // override of the consuming agent CatExfiltration JudgeCategory = "C2_exfiltration" // data exfiltration directives CatUndeclaredCap JudgeCategory = "C3_undeclared_capability" CatDeception JudgeCategory = "C4_user_deception" CatObfuscation JudgeCategory = "C5_obfuscation" CatDestructive JudgeCategory = "C6_destructive_actions" )
The six rubric categories.
const ( CatPersonaImpersonation JudgeCategory = judge.PersonaIDImpersonation CatPersonaToolInstructions JudgeCategory = judge.PersonaIDToolInstructions )
The persona questions' categories, the gate's ids for them.
func AllJudgeCategories ¶
func AllJudgeCategories() []JudgeCategory
AllJudgeCategories lists the rubric.
type JudgeConfig ¶
type JudgeConfig struct {
Provider string // openai | anthropic | bedrock | typesafe | classifier | static | none
Model string
BaseURL string
APIKey string
// Region is the AWS region for the bedrock provider (AGENTRY_JUDGE_REGION).
Region string
}
JudgeConfig is everything NewJudgeProvider needs from the deployment config (internal/config.Judge, projected by the API layer).
type JudgeContent ¶
JudgeContent is what the judge sees: manifest plus prose files, presented as DATA inside delimited blocks by the provider.
type JudgeProvider ¶
type JudgeProvider interface {
// Name identifies the provider (openai|anthropic|bedrock|typesafe|classifier|none|static).
Name() string
// Judge adjudicates the presented content (manifest + prose files).
Judge(ctx context.Context, content JudgeContent) (JudgeVerdict, error)
// RequiresHumanReview reports whether this provider forces review
// regardless of scores (the `none` provider does).
RequiresHumanReview() bool
// ModelID names the model this provider adjudicates with, recorded per
// run beside the prompt hash, or "" for a provider
// that has no model to name (`none`, `static`, the classifier's
// deployment label), in which case the run records Name(). It is known
// from configuration, before any verdict exists: the run row is created
// before S5 runs, and a run that fails before adjudication still records
// a judge. JudgeVerdict.Model stays the provider's own label of what
// produced one verdict (the static heuristics' version, say) and is
// evidence on the finding, not the record on the run.
// evidence on the finding, not the record on the run.
ModelID() string
// InputLimit is the most content, in bytes, one Judge call should
// carry: what the provider's model reads in one request, or, for a
// provider that splits a call into requests of its own, what bounds one
// call's requests. A caller with more to adjudicate — a knowledge
// pack's documents and its wiki — splits
// it into chunks of this size. 0 is a provider that reads nothing.
InputLimit() int
}
JudgeProvider is the provider interface.
func BuildJudgeProvider ¶
func BuildJudgeProvider(ctx context.Context, cfg JudgeConfig) (JudgeProvider, error)
BuildJudgeProvider builds the configured provider, returning the construction error for the caller to refuse startup on (a judge the deployment configures must not silently become "review everything").
func NewJudgeProvider ¶
func NewJudgeProvider(cfg JudgeConfig) JudgeProvider
NewJudgeProvider builds the configured provider. A provider whose construction fails (bedrock without an AWS region) degrades to UnconfiguredProvider, which fails closed toward review; use BuildJudgeProvider at startup to surface that error instead.
type JudgeUsage ¶
type JudgeUsage struct {
PromptTokens int `json:"promptTokens"`
CompletionTokens int `json:"completionTokens"`
}
JudgeUsage is what one adjudication cost in tokens, as the provider reported it: the measurement behind pricing a submission. It is operational data about a run, not part of the verdict, so it lives on scan_runs and stays out of the S10 report whose digest is signed.
type JudgeVerdict ¶
type JudgeVerdict struct {
Scores map[JudgeCategory]int `json:"scores"`
// Cited excerpts per category (evidence, not directives).
Excerpts map[JudgeCategory]string `json:"excerpts"`
// Manipulated is set when the provider detected instruction-following
// symptoms in its own output — always routes to review.
Manipulated bool `json:"manipulated"`
// Samples are every probability a provider drew per axis for the chunk
// that set the axis's score, when it samples more than once (the
// typesafe provider's borderline band); they go on the finding's detail
// as evidence for an appeal.
Samples map[JudgeCategory][]float64 `json:"samples,omitempty"`
// Model and PromptHash record reproducibility.
Model string `json:"model"`
PromptHash string `json:"promptHash"`
// Usage is the token count the provider's response reported, or nil
// when it reported none (the static and classifier judges, an endpoint
// that omits it).
Usage *JudgeUsage `json:"usage,omitempty"`
}
JudgeVerdict is the judge's structured output. Scores are 0–3 per category (3 ⇒ high finding, 2 ⇒ medium).
type KMSAPI ¶
type KMSAPI interface {
Sign(ctx context.Context, in *kms.SignInput, opts ...func(*kms.Options)) (*kms.SignOutput, error)
GetPublicKey(ctx context.Context, in *kms.GetPublicKeyInput, opts ...func(*kms.Options)) (*kms.GetPublicKeyOutput, error)
}
KMSAPI is the slice of the KMS client KMSSigner uses. Two calls, so the tests can substitute an in-process fake and never reach AWS.
type KMSOptions ¶
type KMSOptions struct {
// KeyARN is the key id/ARN/alias to sign with.
KeyARN string
// Region overrides the ambient region.
Region string
}
KMSOptions configures the KMS signer.
type KMSSigner ¶
type KMSSigner struct {
// contains filtered or unexported fields
}
KMSSigner signs DSSE envelopes with a KMS-held ECDSA P-256 key. The private key never leaves KMS; only kms:Sign is called, and only from the worker role — which is what makes an alarm on anomalous KMS Sign calls meaningful, since any other caller is by definition unexpected.
func NewKMSSigner ¶
func NewKMSSigner(ctx context.Context, opt KMSOptions) (*KMSSigner, error)
NewKMSSigner builds a signer over the ambient AWS credential chain and verifies up front that the key is usable: an attestation key that cannot be read is a deployment fault, and it should surface at startup rather than on the first publish.
func NewKMSSignerWithAPI ¶
NewKMSSignerWithAPI builds a signer over an existing client (tests, and callers holding a configured kms.Client).
func (*KMSSigner) PublicKeyPEM ¶
PublicKeyPEM implements Signer.
func (*KMSSigner) Sign ¶
func (s *KMSSigner) Sign(stmt InTotoStatement) (DSSEEnvelope, error)
Sign implements Signer: DSSE PAE over the in-toto statement, hashed locally and signed by KMS as a digest. Sending the digest rather than the message keeps the payload out of CloudTrail and off the wire, and is the only option once a statement exceeds the 4 KB raw-message limit.
func (*KMSSigner) SignPayload ¶
func (s *KMSSigner) SignPayload(payloadType string, payload []byte) (DSSESignature, error)
SignPayload implements Signer: the KMS call itself.
type MCPScanCache ¶
type MCPScanCache interface {
Get(ctx context.Context, ecosystem, pkg, version string) (*MCPScanRecord, error)
Put(ctx context.Context, rec MCPScanRecord) error
}
MCPScanCache is the registry of scanned server versions S7 reads and writes; the pipeline implements it over the store, tests in memory.
func NewStoreMCPScanCache ¶
func NewStoreMCPScanCache(st *store.Store) MCPScanCache
NewStoreMCPScanCache returns the store-backed registry of scanned MCP server versions.
type MCPScanRecord ¶
type MCPScanRecord struct {
Ecosystem string
Package string
Version string
// Status is "safe" (no known advisories at LastChecked), "vulnerable",
// "error" (a lookup failed before any answer: no Advisories, and S7
// counts it as no answer) or "not-found" (the server's package registry
// does not publish this version: OSV is not asked, and the
// daily sweep leaves the row as it is). A lookup that fails after an
// answer keeps the answer's Status and only sets LastError.
Status string
MaxSeverity string
Advisories []OSVVulnerability
FirstSeen time.Time
LastChecked time.Time
LastError string
}
MCPScanRecord is one row of the scanned-server registry.
type MCPSweepSummary ¶
type MCPSweepSummary struct {
Checked int
Vulnerable int
AlertsOpened int
AlertsResolved int
LookupErrors int
}
MCPSweepSummary is what one sweep did.
type MemoryMCPScanCache ¶
type MemoryMCPScanCache struct {
// contains filtered or unexported fields
}
MemoryMCPScanCache is an in-memory MCPScanCache for tests and for a process with no store.
func (*MemoryMCPScanCache) Get ¶
func (m *MemoryMCPScanCache) Get(_ context.Context, eco, pkg, ver string) (*MCPScanRecord, error)
Get implements MCPScanCache.
func (*MemoryMCPScanCache) Put ¶
func (m *MemoryMCPScanCache) Put(_ context.Context, rec MCPScanRecord) error
Put implements MCPScanCache.
type NoneProvider ¶
type NoneProvider struct{}
NoneProvider skips S5 and forces human review: self-host without
func (NoneProvider) InputLimit ¶
func (NoneProvider) InputLimit() int
InputLimit implements JudgeProvider: nothing is read.
func (NoneProvider) Judge ¶
func (NoneProvider) Judge(_ context.Context, _ JudgeContent) (JudgeVerdict, error)
Judge implements JudgeProvider: no scores, review forced by the gate. The prompt hash still records WHICH no-op this was, so a run adjudicated by no judge is distinguishable from one adjudicated by a judge that found nothing.
func (NoneProvider) ModelID ¶
func (NoneProvider) ModelID() string
ModelID implements JudgeProvider: no model.
func (NoneProvider) RequiresHumanReview ¶
func (NoneProvider) RequiresHumanReview() bool
RequiresHumanReview implements JudgeProvider.
type OSVClient ¶
type OSVClient interface {
// Query returns advisories per package, keyed by OSVPackage.Key().
// Packages with no advisories may be omitted.
Query(ctx context.Context, pkgs []OSVPackage) (map[string][]OSVVulnerability, error)
}
OSVClient looks up known vulnerabilities for exact package versions. An implementation MUST NOT block beyond its context.
type OSVPackage ¶
type OSVPackage struct {
// Ecosystem is the OSV ecosystem name ("npm", "PyPI").
Ecosystem string
// Name is the package name as the ecosystem knows it.
Name string
// Version is the exact declared version.
Version string
}
OSVPackage identifies one package version to query.
func (OSVPackage) Key ¶
func (p OSVPackage) Key() string
Key is the per-package key Query results are grouped under.
type OSVVulnerability ¶
type OSVVulnerability struct {
// ID is the advisory id (e.g. "GHSA-…", "PYSEC-…").
ID string `json:"id"`
// Aliases are the other ids for the same advisory, CVE ids included.
Aliases []string `json:"aliases,omitempty"`
// Summary is the advisory's one-line summary.
Summary string `json:"summary"`
// Severity is the advisory's own severity mapped onto the finding
// vocabulary ("low".."critical"): the database's word, else the CVSS
// base score's band. The registry stores it and the dependency alerts
// read it; the finding carries AdvisoryGateSeverity.
Severity string `json:"severity"`
// CVSSScore is the highest CVSS base score among the advisory's
// severity entries (v3.x or v4.0 vectors, or plain numbers); nil when
// it carries none.
CVSSScore *float64 `json:"cvssScore,omitempty"`
// Scored is set on every advisory of a registry row that records CVSS
// scores (scoredAdvisories, by the row's two
// writers, S7 and the daily sweep). A row with an advisory that lacks
// it predates the score, so S7 asks the database again rather than
// judge a High with no score as high.
Scored bool `json:"scored,omitempty"`
// FixedIn lists the versions the advisory names as fixed for the
// package, when it names any.
FixedIn []string `json:"fixedIn,omitempty"`
// References are advisory URLs.
References []string `json:"references,omitempty"`
}
OSVVulnerability is one advisory affecting a queried package version.
type OfflineOSV ¶
type OfflineOSV struct{}
OfflineOSV is the default client: it performs no lookup and reports no advisories. It exists so the absence of a vulnerability database is a visible, testable configuration (S7/osv-not-checked) rather than a silently skipped stage.
func (OfflineOSV) Query ¶
func (OfflineOSV) Query(context.Context, []OSVPackage) (map[string][]OSVVulnerability, error)
Query implements OSVClient by returning an empty result.
type OfflineRegistries ¶
type OfflineRegistries struct{}
OfflineRegistries is the PackageRegistries of a deployment told not to ask (AGENTRY_SCAN_NPM_REGISTRY=none): S7 says it did not check.
type Orchestrator ¶
type Orchestrator struct {
// contains filtered or unexported fields
}
Orchestrator runs the scanner DAG: S1 first (builds the inventory), then S2–S9 in parallel, then S10 assembles the report and computes the gate. Each stage has a timeout and fails closed: a stage error becomes an S0/pipeline-error finding that forces review, never a silent pass.
func NewOrchestrator ¶
func NewOrchestrator(bundle *rules.Bundle, judge JudgeProvider, log *slog.Logger) *Orchestrator
NewOrchestrator builds the orchestrator with the loaded ruleset and judge.
func (*Orchestrator) Run ¶
func (o *Orchestrator) Run(ctx context.Context, p RunParams) RunResult
Run executes the full pipeline synchronously. The worker calls this from a queue handler; tests call it directly. Idempotency at the DB layer is handled by the caller (scan_stage_results keys); Run itself is pure over its Input.
func (*Orchestrator) ScanPack ¶
func (o *Orchestrator) ScanPack(ctx context.Context, files []PackFile) PackReport
ScanPack reads a pack's tree. It never fails: a judge that fails on a chunk is counted on the review (Complete reports it) and the rule stages' findings stand.
func (*Orchestrator) ScanProse ¶
func (o *Orchestrator) ScanProse(ctx context.Context, files []PackFile) PackReport
ScanProse reads text files with the rule stages a pack's scan runs (S2, S3, S4, S8) and no AI Review: a Writing Voice's review asks a question set of its own, since the release rubric reads a voice's instructions about writing as instructions to the reader. Its findings carry no excerpt, as a pack's do.
func (*Orchestrator) SetExternalTools ¶
func (o *Orchestrator) SetExternalTools(t ExternalTools)
SetExternalTools wires the external scanners.
func (*Orchestrator) SetMCPScanning ¶
func (o *Orchestrator) SetMCPScanning(client OSVClient, cache MCPScanCache)
SetMCPScanning wires S7's vulnerability database and the scanned-server registry. A nil client leaves S7 reporting "not checked".
func (*Orchestrator) SetMetrics ¶
func (o *Orchestrator) SetMetrics(m *metrics.Metrics)
SetMetrics wires the instrument set.
func (*Orchestrator) SetPackageRegistries ¶
func (o *Orchestrator) SetPackageRegistries(r PackageRegistries)
SetPackageRegistries wires the registries S7 asks whether a declared server's pinned version is published.
type PackFile ¶
PackFile is one file of a pack's tree, by its slash path in the pack ("sources/report.pdf.txt", "wiki/topics/figures.md").
type PackFinding ¶
type PackFinding struct {
Scanner string `json:"scanner"`
Severity Severity `json:"severity"`
Confidence Confidence `json:"confidence"`
Title string `json:"title"`
Part PackPart `json:"part"`
File string `json:"file,omitempty"`
Line int `json:"line,omitempty"`
Chunk int `json:"chunk,omitempty"`
}
PackFinding is one finding, placed in the half and, for AI Review, the chunk it came from (1-based within its half). It carries no excerpt: the report is kept in the clear beside a tree kept sealed, so it names where a finding is, never the words there (the owner, who holds the tree, can read them).
type PackRead ¶
type PackRead struct {
Sources int `json:"sources"`
Wiki int `json:"wiki"`
Bytes int64 `json:"bytes"`
NotRead []string `json:"notRead"`
}
PackRead counts what the scan read: the text files of each half and their bytes, and the files it could not read as text — a source's original, whose extracted text beside it is read in its place.
type PackReport ¶
type PackReport struct {
Schema string `json:"schema"`
Stages []PackStage `json:"stages"`
Read PackRead `json:"read"`
Review PackReview `json:"review"`
Findings []PackFinding `json:"findings"`
}
PackReport is what a pack's scan read and found.
func (PackReport) Complete ¶
func (r PackReport) Complete() bool
Complete says whether every stage finished and every chunk of AI Review was read (or none was to be, with no judge configured).
type PackReview ¶
type PackReview struct {
Configured bool `json:"configured"`
Note string `json:"note,omitempty"`
Provider string `json:"provider"`
Model string `json:"model,omitempty"`
RubricHash string `json:"rubricHash,omitempty"`
ChunkBytes int `json:"chunkBytes,omitempty"`
SourceChunks int `json:"sourceChunks"`
WikiChunks int `json:"wikiChunks"`
Failed int `json:"failed,omitempty"`
Error string `json:"error,omitempty"`
Usage *JudgeUsage `json:"usage,omitempty"`
}
PackReview is AI Review's record: which provider and model, under which rubric, in chunks of how many bytes, how many chunks of each half, and how many of them the judge failed on.
type PackStage ¶
type PackStage struct {
ID string `json:"id"`
Name string `json:"name"`
Failed bool `json:"failed,omitempty"`
}
PackStage is one stage that read the pack, or that failed to (a timeout, a panic): a failed stage is named, its findings are not trusted to be all there are, and the scan is not complete.
type PackageRegistries ¶
type PackageRegistries interface {
// Published reports whether ecosystem ("npm" or "pypi") publishes
// name@version. An error means the registry gave no answer.
Published(ctx context.Context, ecosystem, name, version string) (bool, error)
}
PackageRegistries answers whether a declared MCP server's package registry publishes the version a manifest pins. OSV answers "no advisories" for a version that does not exist, so without this S7 would record such a server as safe and the release would publish, to be refused by every run that tried to install it (mcp-not-resolved).
type PersonaJudge ¶ added in v0.6.1002
type PersonaJudge interface {
// JudgePersona asks the persona questions about the release's persona
// file. Any failure is an error, and S5 fails closed on it.
JudgePersona(ctx context.Context, manifestJSON []byte, persona JudgeFile) (PersonaVerdict, error)
}
PersonaJudge is a JudgeProvider that also asks the persona questions.
type PersonaVerdict ¶ added in v0.6.1002
type PersonaVerdict struct {
// Scores are the categories scored above 0, 0–3.
Scores map[JudgeCategory]int
// Excerpts locate each scored category's strongest evidence.
Excerpts map[JudgeCategory]string
// Model is the model that answered.
Model string
// PromptHash is the persona set's hash.
PromptHash string
// Usage is the token use of the requests, nil when none was reported.
Usage *JudgeUsage
}
PersonaVerdict is what the persona questions found.
type Pipeline ¶
type Pipeline struct {
// contains filtered or unexported fields
}
Pipeline implements registry.Pipeline: it fetches the version's archive, runs the orchestrator, persists the scan run + findings, drives the version state machine per the gate decision, and signs on publish. It runs synchronously from a queue handler (or inline in dev/tests).
func (*Pipeline) AttestSweep ¶
func (p *Pipeline) AttestSweep(ctx context.Context) (AttestSummary, error)
AttestSweep signs every published version that has no attestation row, from its latest finished scan run: the report digest and judge model the attestation names are that run's, and the policy version is the agent's effective one at sweep time (the run's snapshot carries the policy itself, not its version). A version whose latest run has no report digest is skipped and counted as failed — signing an empty digest asserts nothing — and the log names it. Exactly once per version still holds: the insert's ON CONFLICT (version_id) does nothing for a row that appeared meanwhile.
func (*Pipeline) Block ¶
func (p *Pipeline) Block(ctx context.Context, agentID uuid.UUID, reason string, ev audit.Event) (int, error)
Block disables every live version of an agent (`blocked`: downloads return 410, only platform staff set or unset it). Setting agents.quarantine_state alone would leave published versions downloadable and make the download handler's 410 branch unreachable.
func (*Pipeline) CheckSubmission ¶
CheckSubmission implements registry.PolicyGate.
func (*Pipeline) DecideReview ¶
DecideReview records a reviewer's verdict AND performs the version transition in one transaction, signing on approve→published.
Both happen in one commit: a transient failure between two commits would leave the item marked decided while the version stayed in needs_review, and the handler's "already decided" guard would then refuse every retry.
A process that holds no signing key (the api role) cannot publish a version that has no attestation yet. It records the verdict and hands the publish to the worker (JobPublishApproved), which transitions and signs in one transaction; until then the version stays in needs_review, and the watchdog finishes an approval whose job was lost. A version that already carries its attestation (a quarantined one being reinstated) is published here directly: nothing needs signing.
handedOff reports that the publish was handed to the worker, so the caller does not announce a publication that has not happened yet.
func (*Pipeline) FailToReview ¶
func (p *Pipeline) FailToReview(ctx context.Context, v storegen.AgentVersion, agent storegen.GetAgentByIDRow, trigger, kind string, cause error) error
FailToReview implements the fail-closed rule: a version whose scan could not complete is recorded as an errored run with an S0/pipeline-error finding and routed to human review — never silently published, and never left parked in `scanning`. Idempotent.
func (*Pipeline) MCPScanningEnabled ¶
MCPScanningEnabled reports whether the sweep has a vulnerability database to ask.
func (*Pipeline) MCPSweep ¶
func (p *Pipeline) MCPSweep(ctx context.Context) (sum MCPSweepSummary, err error)
MCPSweep re-checks the scanned-server registry and reconciles alerts.
func (*Pipeline) PublishAdvisory ¶
func (p *Pipeline) PublishAdvisory(ctx context.Context, agentID uuid.UUID, affected, severity, summary, detail string) error
PublishAdvisory records a security advisory for an agent and announces it on the org's webhooks.
func (*Pipeline) PublishApproved ¶
PublishApproved publishes and signs, in one transaction, a version whose review item a keyless role approved. It runs where the key is: the worker's publish job, or the watchdog. Idempotent: an item that is not approved, or a version no longer in needs_review, is left alone, so a redelivered job or a job racing the watchdog does nothing the second time.
func (*Pipeline) Quarantine ¶
func (p *Pipeline) Quarantine(ctx context.Context, versionID uuid.UUID, reason string, ev audit.Event) error
Quarantine/Block/Reinstate implement the T&S platform actions.
func (*Pipeline) ReattestSweep ¶
ReattestSweep countersigns every attestation that lacks the current key's signature. One bad row never stops the sweep, but the count comes back to the caller so the worker logs it at error level; the next start counts what still lacks the key and enqueues the sweep again.
func (*Pipeline) ReattestSweepWithSummary ¶
func (p *Pipeline) ReattestSweepWithSummary(ctx context.Context) (ReattestSummary, error)
ReattestSweepWithSummary is ReattestSweep with the counts returned.
Paging is keyset on the attestation id: every row the sweep signs leaves the set it is paging over, so an OFFSET would skip the neighbour of each row just signed. The append is one UPDATE guarded by "carries no signature by this key id", so two sweeps (two roles starting on the same new key) cannot double-sign a row: the second one's guard sees the first one's write.
func (*Pipeline) ReconcileApprovedReviews ¶
ReconcileApprovedReviews publishes every approval a keyless role handed off whose publish never happened (a lost enqueue, a job that ran out of attempts). Run by the watchdog in the worker; a process without the key does nothing.
func (*Pipeline) ReconcileStuckScans ¶
ReconcileStuckScans is the watchdog: versions that entered `scanning` and never came out (terminally failed job, worker killed mid-DAG) are routed to review with an S0/pipeline-error finding once they pass the 30-minute cap. Without it a lost scan job would park a version forever, visible to nobody. Returns how many it moved.
func (*Pipeline) RedoReviewQueue ¶
RedoReviewQueue runs the redo and logs what it did, at error level when a version could not be judged again.
func (*Pipeline) RedoReviewQueueWithSummary ¶
func (p *Pipeline) RedoReviewQueueWithSummary(ctx context.Context) (RedoSummary, error)
RedoReviewQueueWithSummary judges every version in needs_review whose item is still pending again under this process's ruleset and the policy now in force, through the orchestrator and the gate a submission runs. A version the gate now publishes is signed and published, its review item superseded; one it would still hold, or would reject, stays held for the person already asked, with the new run as its report. Only the gate's own verdict on the new run publishes, so a forced review in that run (no judge ran, a stage failed, content went unread, the policy requires a person, wildcard egress) holds the version. A version a finished run of this ruleset already judged is not listed, so a second start on the same ruleset, or a redelivered job, does nothing.
func (*Pipeline) RegisterHandlers ¶
RegisterHandlers wires the pipeline's job handlers onto a queue client. The worker role calls this then Work(); dev/tests can Drain().
func (*Pipeline) Reinstate ¶
Reinstate is the platform's reinstate: it asks for a fresh scan of every blocked or quarantined version of the agent and returns how many it asked for. It publishes nothing itself. A version returns to published only when the gate's verdict on its new scan is publish (reinstateOne); every other version stays held for a person. A version admitted without a scan has no verdict to wait for and is left as it is. The scans run where the queue's sandbox worker is; a pipeline with no queue runs them here.
func (*Pipeline) RescanSweep ¶
RescanSweep re-runs the scanners against published versions when a new ruleset ships. New high/critical findings quarantine the version and draft an advisory. One unreadable version never stops the sweep — the rest of the catalogue still gets checked — but the count comes back to the caller so the worker can log it at error level and alerting can see it.
func (*Pipeline) RescanSweepWithSummary ¶
func (p *Pipeline) RescanSweepWithSummary(ctx context.Context) (RescanSummary, error)
RescanSweepWithSummary is RescanSweep with the counts returned.
Paging is keyset, not LIMIT/OFFSET. The sweep quarantines rows out of the very set it is paging over, so under OFFSET every version it acted on would shift an unscanned one into the gap — the sweep would skip exactly the neighbours of the versions it had just found problems with.
func (*Pipeline) Scan ¶
Scan runs the full pipeline for one version, persists the run, and drives the state machine per the gate.
func (*Pipeline) SetDraftProvenance ¶
func (p *Pipeline) SetDraftProvenance(d DraftProvenance)
SetDraftProvenance installs the extension's answer to a claimed draft.
func (*Pipeline) SetGitHistory ¶
func (p *Pipeline) SetGitHistory(h GitHistory)
SetGitHistory wires the history seam.
func (*Pipeline) SetMCPScanning ¶
func (p *Pipeline) SetMCPScanning(client OSVClient, cache MCPScanCache)
SetMCPScanning wires S7's vulnerability database and scanned-server registry onto the orchestrator.
func (*Pipeline) SetMetrics ¶
SetMetrics wires the instrument set onto the pipeline and the orchestrator it drives.
func (*Pipeline) SetNotifier ¶
SetNotifier overrides the author-notification transport.
func (*Pipeline) SetOrchestratorForTest ¶
func (p *Pipeline) SetOrchestratorForTest(o *Orchestrator)
SetOrchestratorForTest replaces the orchestrator. It exists so tests can simulate "the ruleset learned something after this version was published" without shipping two rule bundles. Not for production use.
func (*Pipeline) SetPackageRegistries ¶
func (p *Pipeline) SetPackageRegistries(r PackageRegistries)
SetPackageRegistries wires the registries S7 asks whether a declared server's pinned version is published.
func (*Pipeline) SetRescanBatchForTest ¶
SetRescanBatchForTest shrinks the sweep page size so paging behaviour is exercisable without publishing hundreds of versions. Not for production use.
func (*Pipeline) SetRulesetForTest ¶
SetRulesetForTest points the pipeline at another ruleset release, so a test can register "the next ruleset" without shipping a second bundle. Not for production use.
type PipelineDeps ¶
type PipelineDeps struct {
Store *store.Store
Registry *registry.Service
Blobs registry.BlobStore
Orchestrator *Orchestrator
Signer Signer
Audit *audit.Writer
// Notifier reaches the author when their published agent is quarantined.
// Defaults to the log notifier.
Notifier notify.Notifier
Log *slog.Logger
RegistryURL string
RulesetID uuid.UUID
RulesetVer string
// Jobs is the queue a keyless role hands an approval to:
// with no Signer, an approve → published is published and signed by the
// worker's publish job, not in the request.
Jobs queue.Client
}
type Policy ¶
type Policy struct {
// RequireHumanReview: "never" | "always" | {"whenCapabilities": [...]}.
RequireHumanReview json.RawMessage `json:"requireHumanReview,omitempty"`
// BlockedCapabilities: submissions declaring these are rejected at
// V-validation (registry enforces; listed here for completeness).
BlockedCapabilities []string `json:"blockedCapabilities,omitempty"`
// AllowedLicenses: public publishes outside this list are rejected.
// An absent or empty list allows any license.
AllowedLicenses []string `json:"allowedLicenses,omitempty"`
// NoPublicLicense: no license is allowed for public publishes, so every
// public publish is rejected. Merge sets it when the baseline's and the
// organization's allowedLicenses have no identifier in common: the
// empty intersection must not read as an absent list, which allows any
// license. A policy document may also set it to stop public publishes.
NoPublicLicense bool `json:"noPublicLicense,omitempty"`
// BlockedMcpServers: submissions whose manifest declares one of these
// MCP servers are rejected at submission (an org blocklist).
// Entries are "npm:<package>" / "pypi:<package>",
// or "url:<host>" for a remote server; path.Match globs
// are allowed ("npm:@evil/*", "pypi:*-fetch", "url:*.example.com").
// Unions toward strict like blockedCapabilities.
BlockedMcpServers []string `json:"blockedMcpServers,omitempty"`
// MaxAutoPublishSeverity tightens the severity table: worst auto-publishable
// severity. "" means the baseline default, which the ruleset carries
// (medium).
MaxAutoPublishSeverity string `json:"maxAutoPublishSeverity,omitempty"`
// RequireEvals: evals/ dir must exist and be non-empty.
RequireEvals bool `json:"requireEvals,omitempty"`
// WildcardEgress: "review" | "reject" for "*" egress, and for a browser
// whose scope is public (unrestrictedNetwork).
WildcardEgress string `json:"wildcardEgress,omitempty"`
}
Policy is the policy document. The platform baseline is the floor; org policies may only tighten (Evaluate enforces this).
func DefaultBaseline ¶
func DefaultBaseline() Policy
DefaultBaseline is the platform baseline policy. Its threshold is the embedded ruleset's: released with the bundle version, so "which ruleset published this" names the threshold too.
func Merge ¶
Merge tightens baseline with an org overlay (org may only tighten). The stricter of each knob wins; org can never loosen the baseline.
func ParsePolicy ¶
ParsePolicy decodes and validates a policy document.
type PublishApprovedArgs ¶
PublishApprovedArgs names the approved review item to publish.
type PublishPredicate ¶
type PublishPredicate = attest.PublishPredicate
Aliases for the promoted public attestation API (pkg/attest).
type QueuePipeline ¶
QueuePipeline adapts the queue into registry.Pipeline: instead of scanning inline, it enqueues a scan.version job. Every role that takes submissions hands them off this way (api.Server.HandOffScans); the synchronous Pipeline remains for tests that drive a scan in-request.
func (QueuePipeline) VersionSubmitted ¶
VersionSubmitted implements registry.Pipeline by enqueueing a scan job. The enqueue error is returned, so "the queue is down" is not a version silently parked in `scanning` with nobody scanning it.
type ReattestSummary ¶
type ReattestSummary struct {
// KeyID is the key that countersigned.
KeyID string
// Signed counts the envelopes that gained a signature.
Signed int
// Failed counts the envelopes the sweep refused or could not sign: an
// undecodable envelope, a statement that does not describe its version
// row, a signer error, or a countersignature that did not verify
// against the signer's own public key. None of them is written.
Failed int
}
ReattestSummary reports what a sweep did.
type ReattestSweepArgs ¶
type ReattestSweepArgs struct {
KeyID string `json:"keyId,omitempty"`
Pending int64 `json:"pending,omitempty"`
}
ReattestSweepArgs records which key scheduled the sweep and how many attestations lacked it. The sweep signs with whatever key the worker holds; the arguments are the log's.
type RedoSummary ¶
type RedoSummary struct {
// Rescanned counts the held versions judged again under this ruleset.
Rescanned int
// Published counts those the gate now published.
Published int
// Held counts those that stay in the queue, their report refreshed.
Held int
// Moved counts those that left the queue by another route while they
// were judged: a reviewer's decision, a yank. That route's result stands.
Moved int
// Failed counts those that could not be judged again; they stay held,
// with their earlier report, until a later ruleset's redo or a person.
Failed int
}
RedoSummary reports what a redo of the review queue did.
type ReinstateScanArgs ¶
type ReinstateScanArgs struct {
VersionID uuid.UUID `json:"versionId"`
Reason string `json:"reason"`
}
ReinstateScanArgs names the version to judge again and carries the reinstate's reason, which the record of the outcome quotes.
type Report ¶
type Report struct {
SchemaVersion string `json:"schemaVersion"`
Findings []Finding `json:"findings"`
StageErrors []string `json:"stageErrors"`
JudgeModel string `json:"judgeModel"`
// Decision is the gate outcome.
Decision GateDecision `json:"decision"`
// Knowledge is what the scan of each pack the release ships read
// (SK); absent for a release that ships none, so such a report's
// digest is what it always was.
Knowledge []ShippedPackScan `json:"knowledge,omitempty"`
// Subagents are a persistent release's subagents as the scan resolved
// them, each with its version and reach or the reason it does not
// resolve; absent for a release that declares none.
Subagents []Subagent `json:"subagents,omitempty"`
}
Report is the S10 canonical report. Field order is fixed and slices are sorted so ReportDigest is reproducible.
type RescanSummary ¶
type RescanSummary struct {
Scanned int
Quarantined int
Failed int
// CachedStages counts stage results that did not have to be re-run —
// results-cache hits, plus any stage an interrupted attempt had already
// completed. The measure of what the cache saved.
CachedStages int
}
RescanSummary reports what a sweep did. Failures are counted rather than swallowed: an unreadable archive for a *published* version is a storage integrity problem, and a sweep that logs it and returns nil looks indistinguishable from a clean run.
type RescanSweepArgs ¶
type RescanSweepArgs struct {
RulesetSemver string `json:"rulesetSemver,omitempty"`
}
RescanSweepArgs records why a sweep was scheduled (the ruleset semver whose arrival triggered it).
type Resume ¶
type Resume struct {
// Skip names stages whose results are already known. S1 is never
// skippable: it builds the file inventory every other stage reads.
Skip map[string]bool
// Findings are the skipped stages' findings.
Findings []Finding
// Knowledge is a skipped SK's record of what it read.
Knowledge []ShippedPackScan
// Subagents is a skipped S7's record of the subagents, which the report
// then carries in place of a new resolution, so the report and the
// findings S7 wrote say the same.
Subagents []Subagent
}
Resume describes work this run does not have to repeat.
type ReviewDecision ¶
type ReviewDecision struct {
ItemID uuid.UUID
VersionID uuid.UUID
// Target is the version state the decision moves the version to.
Target registry.Status
// State is the review_items state ("approved" | "rejected").
State string
Rationale string
DecidedBy uuid.UUID
// SelfDecision marks platform staff deciding a version they submitted:
// allowed, and recorded in the audit event's detail so
// it stays visible after the fact.
SelfDecision bool
// Audit is the caller's audit event (actor, request context); the action
// and target are filled in here.
Audit audit.Event
}
ReviewDecision is one reviewer verdict on a review item.
type RotationOptions ¶ added in v0.7.10
type RotationOptions struct {
// Registry is the registry's base URL, which a handover names.
Registry string
// Previous signs with the outgoing key, when the operator kept it for
// this start. It hands the registry over to the new key.
Previous Signer
// WithoutHandover lets a new key replace the active one with no
// handover: the outgoing key is lost or compromised, and every client
// must re-pin deliberately.
WithoutHandover bool
// DevInstance is a registry in dev mode, which mints and swaps keys
// freely: a new key with no handover is logged there, not refused.
DevInstance bool
// Now is the handover's time; time.Now when nil.
Now func() time.Time
}
RotationOptions say how a start on a new signing key treats the key it replaces.
type RulesetRegistration ¶
type RulesetRegistration struct {
// ID is the ruleset_releases row every scan_run of this process points at.
ID uuid.UUID
// Semver is the bundle version.
Semver string
// New reports that this semver had never been recorded before. A new
// ruleset semver is the trigger for re-scanning the whole published
// catalogue; a restart on the same bundle is not.
New bool
}
RulesetRegistration is the outcome of recording the embedded rule bundle.
func RegisterRuleset ¶
func RegisterRuleset(ctx context.Context, st *store.Store, bundle *rules.Bundle) (RulesetRegistration, error)
RegisterRuleset records the embedded rule bundle and returns its row id. Callers MUST treat an error as fatal to startup: a pipeline whose ruleset id names no row cannot create a single scan run.
type RunParams ¶
type RunParams struct {
Input Input
Policy Policy
Public bool
// NamespaceIsOrg routes review to the org queue. Personal-namespace
// agents have no org, so their reviews belong to the platform queue:
// routing them to "org" would produce an item with a NULL org_id that
// appears in neither queue listing and that nobody could decide.
NamespaceIsOrg bool
// PopularAgentNames + AgentName feed S8.
PopularAgentNames []string
AgentName string
// Resume carries stage results already known for this run: stages a
// previous attempt completed (keyed by scan run and
// scanner) or answered from the results cache. Their findings are
// folded in as though the stages had just run, so the report and the gate
// see the complete set.
Resume Resume
// OnStage, when set, is called once per stage that actually executes,
// before the run finishes. The pipeline uses it to persist stage results
// incrementally so a retry does not re-run — or duplicate — them. It may
// be called concurrently.
OnStage func(StageResult)
}
RunParams configures one scan run.
type RunResult ¶
type RunResult struct {
Report Report
ReportDigest string // sha256 of canonical report JSON
Findings []Finding
Decision GateDecision
JudgeModel string
// JudgePromptHash identifies the rubric/prompt version S5 adjudicated
// with (recorded per run for reproducibility and appeals).
JudgePromptHash string
// JudgeUsage is the token use S5's provider reported, nil when unknown;
// see JudgeUsage for why it is on the run and not in Report.
JudgeUsage *JudgeUsage
// Fatal is set when the run could not produce a usable result at all —
// today, only a report that will not serialize, which would otherwise
// yield an empty report digest and carry that emptiness into a SIGNED
// attestation. The caller must not publish on a fatal run.
Fatal error
// Ran lists the stages that actually executed (skipped ones excluded).
Ran []StageResult
// Skipped names the stages whose results came from Resume rather than
// from running them: results-cache hits, or stages a previous
// attempt at this run had already completed.
Skipped []string
// Knowledge is the report's shipped-pack section (Report.Knowledge).
Knowledge []ShippedPackScan
}
RunResult bundles the report with its digest and the effective judge model.
type S1Inventory ¶
type S1Inventory struct{}
S1 — Inventory & hygiene. Unpacks were done by the orchestrator; S1 builds the file inventory (content-sniffed types), flags binaries and executables (blocked for all kinds in v1), nested archives, and non-UTF-8 text. It populates Input.Files for the downstream stages.
func (S1Inventory) ID ¶
func (S1Inventory) ID() string
func (S1Inventory) Run ¶
func (S1Inventory) Run(sc stageContext, in *Input) StageResult
type S2Secrets ¶
type S2Secrets struct {
// Gitleaks, when set, execs the real tool after the native ruleset and
// folds its report in.
Gitleaks *ExecTool
}
S2 — Secrets. Native high-signal secret detection over the archive (git-history scanning is the git-tag add-on). The mandatory `agy_` PAT rule is included, and the manifest's declared env values are read as values (stages_s2_manifest.go). A gitleaks/trufflehog external adapter can replace this behind the same Stage interface.
func (S2Secrets) Run ¶
func (s S2Secrets) Run(sc stageContext, in *Input) StageResult
type S3S4Content ¶
type S3S4Content struct{}
S3S4Content wraps the pkg/rules S3 hidden-content detectors and S4 signature engine. It runs on the inventoried text files, and on the text recovered from image metadata. The capability families' hits are rated by what the manifest declares: they hold only for a capability it does not declare.
func (S3S4Content) ID ¶
func (S3S4Content) ID() string
func (S3S4Content) Run ¶
func (S3S4Content) Run(sc stageContext, in *Input) StageResult
type S5Judge ¶
type S5Judge struct{}
S5Judge adapts the judge into a Stage.
func (S5Judge) Run ¶
func (S5Judge) Run(sc stageContext, in *Input) StageResult
type S6Scripts ¶
type S6Scripts struct{}
S6 — Support scripts. An instruction package may ship scripts its instructions tell the host to run. This stage reads the shell, Python and JavaScript/TypeScript files in the package and compares what they do with what the manifest declares: network calls against `network.egress` (a host counts only inside a network call, so a documentation URL in a comment or string is not a finding; a shell script's /dev/tcp redirection, socat address, git remote and container registry name their host themselves, see netFormHosts), writes against `filesystem.write`, environment reads against `secrets`, and a script's very presence against `exec` — a package that ships a script under `exec: none` is a high finding. Remote and obfuscated execution (`curl … | sh`, decoded payloads, eval) is reported regardless of declarations. The stage records what it scanned and what it skipped in an informational finding, so the report never implies coverage it did not have.
It also reads the other direction, needed but not declared: the runner tools the instruction calls for (browser_click, run_command, fetch, host_run, fs_write, a declared server's tool) against the grants the manifest declares (pkg/toolgrant). A run of a release that does not declare the grant has no such tool, so the instruction describes a run that cannot happen. Each grant missing is one high finding: the version goes to a person, who can see the instruction and the manifest disagree; it is never rejected.
Not done here, and said so in the trust docs (https://docs.secureagentry.net/trust/): data-flow analysis, evaluating what a fetch returns, other languages.
func (S6Scripts) Run ¶
func (S6Scripts) Run(sc stageContext, in *Input) StageResult
type S7MCPServers ¶
type S7MCPServers struct {
// contains filtered or unexported fields
}
S7MCPServers is the stage.
func (S7MCPServers) Run ¶
func (s S7MCPServers) Run(sc stageContext, in *Input) StageResult
Run implements Stage.
type S8Metadata ¶
type S8Metadata struct {
// PopularAgentNames seeds the anti-typosquat compare; the
// orchestrator injects the live top-N.
PopularAgentNames []string
// AgentName is this agent's name (for self-exclusion).
AgentName string
}
S8 — Metadata, namespace & publisher abuse. Name similarity vs popular agents (normalized edit distance + UTS #39 confusable-skeleton compare), URL reputation in readme/manifest, keyword-stuffing heuristics, and publisher-behaviour signals (young account + publish velocity — the ClawHavoc pattern).
func (S8Metadata) ID ¶
func (S8Metadata) ID() string
func (S8Metadata) Run ¶
func (s S8Metadata) Run(sc stageContext, in *Input) StageResult
type S9ReleaseDiff ¶
type S9ReleaseDiff struct {
// CurrentFindings are this run's other stages' findings, so S9 can
// escalate rather than re-detect. The orchestrator injects the set.
CurrentFindings []Finding
}
S9 — Release-diff risk. Diffs this version against the previous published version — manifest AND content — for new egress hosts/URLs, capability additions, newly added install scripts or dependencies, the first appearance of obfuscation markers, and large instruction rewrites shipped as a patch bump. Escalates findings that arrive VIA the diff (the postmark-mcp rug-pull pattern). First-ever publishes skip S9.
func (S9ReleaseDiff) ID ¶
func (S9ReleaseDiff) ID() string
func (S9ReleaseDiff) Run ¶
func (s S9ReleaseDiff) Run(sc stageContext, in *Input) StageResult
type SKKnowledge ¶
type SKKnowledge struct {
// contains filtered or unexported fields
}
SKKnowledge adapts the pack scan into a stage. It holds the orchestrator, whose pack reading it runs, and the packs the manifest ships.
func (SKKnowledge) Run ¶
func (s SKKnowledge) Run(sc stageContext, in *Input) StageResult
Run implements Stage: one pack scan per shipped pack, over the text files S1 inventoried under the pack's wiki/ and sources/, read whole off disk.
type ScanJobArgs ¶
ScanJobArgs is the payload for a scan.version job.
type ScanRunRef ¶
type ScanRunRef = attest.ScanRunRef
Aliases for the promoted public attestation API (pkg/attest).
type Severity ¶
type Severity string
Severity is a finding severity (ordered).
const ( SevInfo Severity = "info" SevLow Severity = "low" SevMedium Severity = "medium" SevHigh Severity = "high" SevCritical Severity = "critical" )
Severities, ascending.
func AdvisoryGateSeverity ¶
func AdvisoryGateSeverity(v OSVVulnerability) Severity
AdvisoryGateSeverity is the severity the gate gives the finding an advisory makes. A Critical advisory is critical and rejects the version. A High one is high from a CVSS base score of 8.5, medium below it, and high when it carries no usable score. Every other severity is the advisory's own.
The advisory's own severity is what the registry stores and what the dependency alerts and their routing read; this rating is made where the finding is made, and served beside the stored one on the scan route so the runner applies the same rule.
type ShippedPackScan ¶
type ShippedPackScan struct {
Name string `json:"name"`
Report PackReport `json:"report"`
}
ShippedPackScan is what the scan of one shipped pack read and found, in the terms a stored pack's report uses (the findings without excerpts, placed by half and chunk; the same findings are the version's, whole).
type Signer ¶
type Signer interface {
// Sign signs a statement, returning the DSSE envelope.
Sign(stmt InTotoStatement) (DSSEEnvelope, error)
// SignPayload signs an already-encoded DSSE payload and returns the one
// signature. Sign is a marshal plus this; the re-attestation sweep uses
// it directly, because a countersignature must cover the payload bytes
// the envelope already holds — a re-marshalled statement could differ by
// a byte and every old signature would stop verifying.
SignPayload(payloadType string, payload []byte) (DSSESignature, error)
// KeyID identifies the signing key.
KeyID() string
// PublicKeyPEM returns the verification key for the well-known endpoint.
PublicKeyPEM() string
}
Signer produces DSSE envelopes. KMS/HSM implement the same interface; the file signer is the self-host/dev default.
func NewPreviousSigner ¶ added in v0.7.10
NewPreviousSigner builds the outgoing key's signer for the start that rotates away from it: a file key from keyFile, or a KMS key from kmsKeyARN. It is nil when neither is set. The outgoing key signs one thing, the handover to the new key.
type SignerOptions ¶
type SignerOptions struct {
Kind string // none | file | kms
// KeyFile is the file signer's PEM private key.
KeyFile string
// KMSKeyARN identifies the KMS key (kms kind).
KMSKeyARN string
// KMSRegion overrides the ambient region for the KMS client.
KMSRegion string
// DevMode allows the ephemeral in-memory key.
DevMode bool
}
SignerOptions selects and configures the signer (none|file|kms).
type SigningKeyRegistration ¶
type SigningKeyRegistration struct {
// KeyID is the signer's key id.
KeyID string
// New reports that the registry had never signed with this key before:
// a rotation, or the first start. A new key is what triggers the
// re-attestation sweep; a restart on the same key is not.
New bool
// Retired counts the keys the arrival of this one retired.
Retired int64
}
SigningKeyRegistration is the outcome of recording the signer's public key.
func RegisterSigningKey ¶
func RegisterSigningKey(ctx context.Context, st *store.Store, signer Signer) (SigningKeyRegistration, error)
RegisterSigningKey records the signer's public key at start and retires every other key. The public part is what a verifier needs, and the retired keys stay recorded. Callers treat an error as fatal to startup, as with RegisterRuleset: a registry that signs with a key it cannot record would publish attestations nobody can verify.
func RotateSigningKey ¶ added in v0.7.10
func RotateSigningKey(ctx context.Context, st *store.Store, signer Signer, opt RotationOptions, log *slog.Logger) (SigningKeyRegistration, error)
RotateSigningKey records the signer's key as RegisterSigningKey does and, when it replaces the key the registry signed with until now, has the outgoing key hand over to it first. A start on the active key, the first start, and a key already handed over to do nothing more. A new key with no handover is refused unless opt.WithoutHandover or opt.DevInstance says why there is none, so a planned rotation cannot silently cost every client its trust in the new key. The refusal leaves the record as it was.
type Stage ¶
type Stage interface {
// ID is the stage id ("S1".."S9").
ID() string
// Run executes the stage against the (already-inventoried) input.
Run(ctx stageContext, in *Input) StageResult
}
Stage is one scanner (S1–S9). S10 assembly is not a Stage.
type StageResult ¶
type StageResult struct {
Scanner string
Findings []Finding
// Err is set when the stage could not complete; the orchestrator treats
// a stage error as fail-closed.
Err error
// Skipped marks a stage whose result was already known — a completed
// stage of an interrupted run, or a results-cache hit. Skipped
// stages are not re-persisted and not re-cached.
Skipped bool
// NoCache marks a result that depends on more than the archive bytes
// (S2 with a git-history scan) and so must not be reused by digest.
NoCache bool
// PromptHash is set by S5: the hash of the rubric/prompt version the
// judge adjudicated with (recorded on the scan run).
PromptHash string
// JudgeUsage is set by S5 and SK: the token use the provider reported,
// nil when it reported none.
JudgeUsage *JudgeUsage
// Knowledge is set by SK: what the scan of each shipped pack read.
Knowledge []ShippedPackScan
// Subagents is S7's record of a persistent release's subagents as the
// pipeline resolved them (Input.Subagents), kept on its stage row for
// the report.
Subagents []Subagent
}
StageResult is one scanner stage's output.
type StaticProvider ¶
type StaticProvider struct{}
StaticProvider is a deterministic heuristic judge used in dev/tests: it scores categories from strong lexical signals so the gate and review flow are exercisable without a live model. It is NOT a substitute for a real LLM in production and never auto-clears with high confidence beyond what the signals justify.
func (StaticProvider) InputLimit ¶
func (StaticProvider) InputLimit() int
InputLimit implements JudgeProvider: the heuristics read anything, and the limit is the chat providers' so a dev deployment chunks as a live one would.
func (StaticProvider) Judge ¶
func (StaticProvider) Judge(_ context.Context, content JudgeContent) (JudgeVerdict, error)
Judge implements JudgeProvider with deterministic lexical scoring.
func (StaticProvider) ModelID ¶
func (StaticProvider) ModelID() string
ModelID implements JudgeProvider: the heuristics are not a model, and the run keeps recording "static" so existing reports keep their digests.
func (StaticProvider) RequiresHumanReview ¶
func (StaticProvider) RequiresHumanReview() bool
RequiresHumanReview implements JudgeProvider.
type Subagent ¶ added in v0.6.1002
type Subagent struct {
// Ref is the subagent's namespace/name.
Ref string `json:"ref"`
// Constraint is the semver constraint the release declares.
Constraint string `json:"constraint"`
// Why is the release's reason for it.
Why string `json:"why,omitempty"`
// Version is the newest published version the constraint admits that
// may be a subagent; empty when none does.
Version string `json:"version,omitempty"`
// Problem says why the subagent does not resolve; empty when it does.
Problem string `json:"problem,omitempty"`
// Reach is what the resolved version may do; nil when none resolved.
Reach *SubagentReach `json:"reach,omitempty"`
}
Subagent is one subagent as the scan resolved it.
type SubagentReach ¶ added in v0.6.1002
type SubagentReach struct {
// Egress are the hosts it may reach ("*" for any), its own and its
// servers', sorted; none for a release that reaches none.
Egress []string `json:"egress,omitempty"`
// Servers are its declared MCP servers by source id, sorted.
Servers []string `json:"servers,omitempty"`
// Exec are the commands it may run, sorted.
Exec []string `json:"exec,omitempty"`
// Secrets are the secrets it asks for, its own and its servers', sorted.
Secrets []string `json:"secrets,omitempty"`
// Browser is its browser's scope, "site" or "public"; empty for none.
Browser string `json:"browser,omitempty"`
// TargetHosts is how many target hosts it asks for.
TargetHosts int `json:"targetHosts,omitempty"`
}
SubagentReach is what a subagent's resolved version declares, in the terms its own consent lists: where it may connect, the servers it uses, the programs it may run and the secrets it asks for.
type TypeSafeJudge ¶
type TypeSafeJudge struct {
// contains filtered or unexported fields
}
TypeSafeJudge is the `typesafe` provider: TypeSafe AI's Jev, a typed-decision model behind POST /v1/systemone, asked the six rubric axes as yes/no questions ("Nouls") that answer with a probability. It reads the manifest and every text file of the version, one chunk of one file per request, and takes the highest probability over the chunks as the version's score on each axis.
It is not an LLM judge: it returns numbers, no text, so there is nothing in which a manipulated-judge symptom could show, and it has no temperature or seed, so two identical requests may answer differently. The record compensates: the model id is pinned in configuration, checked against every response and in the rubric hash with everything else that changes a verdict; an answer in the borderline band is asked twice more and the maximum is taken, never the mean (disagreement escalates, never averages away), with every sample on the finding for an appeal to read.
The question texts are constants. Nothing from the version — not the manifest, not a path, not a line of content — is rendered into them: the content and the manifest's declared capabilities travel in the request's `state`, the data the questions are asked about, so an attacker-authored manifest can no more rewrite the question than a SKILL.md can (content is data).
func NewTypeSafeJudge ¶
func NewTypeSafeJudge(cfg JudgeConfig) *TypeSafeJudge
NewTypeSafeJudge builds the provider. APIKey is required and Model must be a pinned version id (the factory refuses otherwise; Model defaults to the pinned id when empty); BaseURL defaults to the vendor's API.
func (*TypeSafeJudge) InputLimit ¶
func (j *TypeSafeJudge) InputLimit() int
InputLimit implements JudgeProvider: about 50 KB, what Jev's documented 32k-token window takes with the questions and the state around it. A call is still asked in typesafeChunk pieces.
func (*TypeSafeJudge) Judge ¶
func (j *TypeSafeJudge) Judge(ctx context.Context, content JudgeContent) (JudgeVerdict, error)
Judge implements JudgeProvider.
func (*TypeSafeJudge) JudgePersona ¶ added in v0.6.1002
func (j *TypeSafeJudge) JudgePersona(ctx context.Context, manifestJSON []byte, persona JudgeFile) (PersonaVerdict, error)
JudgePersona implements PersonaJudge with pkg/judge's PersonaScanner, the same client the rubric asks through.
func (*TypeSafeJudge) ModelID ¶
func (j *TypeSafeJudge) ModelID() string
ModelID implements JudgeProvider: the pinned model id.
func (*TypeSafeJudge) RequiresHumanReview ¶
func (j *TypeSafeJudge) RequiresHumanReview() bool
RequiresHumanReview implements JudgeProvider: the six axes are the rubric, so the verdict follows the gate's severity table like an LLM judge's.
type UnconfiguredProvider ¶
UnconfiguredProvider stands in for a provider that could not be built (see NewJudgeProvider); every verdict is an error, so S5 fails closed.
func (UnconfiguredProvider) InputLimit ¶
func (UnconfiguredProvider) InputLimit() int
InputLimit implements JudgeProvider: every call fails, so a caller still makes one and records the failure.
func (UnconfiguredProvider) Judge ¶
func (u UnconfiguredProvider) Judge(_ context.Context, _ JudgeContent) (JudgeVerdict, error)
Judge implements JudgeProvider: returns an error so the orchestrator records an S5 stage error and fails closed to review.
func (UnconfiguredProvider) ModelID ¶
func (UnconfiguredProvider) ModelID() string
ModelID implements JudgeProvider: nothing adjudicated.
func (UnconfiguredProvider) Name ¶
func (u UnconfiguredProvider) Name() string
Name implements JudgeProvider.
func (UnconfiguredProvider) RequiresHumanReview ¶
func (UnconfiguredProvider) RequiresHumanReview() bool
RequiresHumanReview implements JudgeProvider: fail toward review.
Source Files
¶
- bootstrap.go
- cache.go
- cvss.go
- exectool.go
- extract.go
- finding.go
- gate.go
- handover.go
- imagemeta.go
- judge.go
- judge_bedrock.go
- judge_classifier.go
- judge_persona.go
- judge_typesafe.go
- manifestcaps.go
- mcp_sweep.go
- orchestrator.go
- osv.go
- osv_http.go
- pack.go
- pipeline.go
- pipeline_prev.go
- pipeline_subagents.go
- policy.go
- policy_gate.go
- provenance.go
- readme.go
- reattest.go
- redo.go
- registry_http.go
- reinstate.go
- ruleadapter.go
- s2placeholder.go
- s9diff.go
- signing.go
- signing_kms.go
- stage.go
- stages_knowledge.go
- stages_s1_s4.go
- stages_s2.go
- stages_s2_history.go
- stages_s2_manifest.go
- stages_s6.go
- stages_s6_forms.go
- stages_s6_tools.go
- stages_s7_mcp.go
- stages_s8_s9.go
- subagent_advisories.go
- subagents.go
- textutil.go
- worker.go