scan

package
v0.1.0-beta Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Batch scanning owned targets

Pipeline for scanning a list of sites you own with unruly, collecting findings and performance data for analysis. Only scan targets you own or hold written permission to test — enumeration and write probing against systems you do not control is unauthorised access in most jurisdictions.

1. Add targets

Edit scan/targets-owned.csv — one row per site, same column layout as supabase-prospects/mixed_10000.csv. Only the url column is read; the rest is metadata for the dataset. # lines are comments.

2. Run

python3 scripts/scan-batch.py --targets scan/targets-owned.csv

Useful options:

  • --rate-limit N — cap requests/second (-rl); set it when the infrastructure is shared, and only to a number the target actually receives
  • --write — enables INSERT probing (-write -yes-i-own-this); owned targets only, it writes to the database
  • --measure — establish exposure without retrieving rows (use whenever the report will leave your machine)
  • --timeout SECONDS — per-target timeout (default 900)
  • --spotcheck N — after the run, re-scan N random targets and byte-diff the JSONL (determinism validation; two scans of an unchanged target must be byte-identical)
  • -- -k KEY ... — extra flags passed through to unruly

Scans run sequentially on purpose: the scanner already runs at the measured PostgREST saturation point, so overlapping runs would push both past the knee where throughput collapses.

3. Monitor progress

The runner prints one line per target and maintains <run>/progress.json (done/total, failures, ETA) atomically, so it can be polled from another shell:

watch cat scan/runs/<timestamp>/progress.json

4. What a run produces

scan/runs/<timestamp>/ (gitignored — findings quote real rows, so a run directory is a copy of the target's data):

file contents
run.json binary, targets file, options, start time
progress.json live progress, rewritten atomically per target
manifest.jsonl one line per target: exit code, duration, retries, error, finding counts
findings/<slug>.jsonl the scanner's report for that target
logs/<slug>.log stdout/stderr of that scan
spotcheck.json determinism re-scan results, if --spotcheck was used
summary.json run-level aggregate, written at the end

5. Error handling

Exit codes 0/2/3 from unruly are scan outcomes (clean / findings / partially unmeasured) and are recorded, not treated as runner failures. An unreachable target yields exit 3 from the tool itself and the batch moves on. Anything else — crash, signal, timeout — is retried once, then recorded in the manifest with error set, and the batch continues. Exit 1 (usage error) aborts the whole batch: it means the invocation is wrong, and continuing would record the same mistake once per target.

6. Analyse

python3 scripts/scan-summary.py scan/runs/<timestamp>

Writes summary.csv (one row per target — the per-target dataset) and analysis.json (severity distribution, finding-id frequency, duration stats, failure breakdown, determinism result), and prints a digest.

7. Validate

  • Ground truth (recall/precision): make eval-fixtures grades the scanner against evals/targets/*.yaml — a vulnerable fixture, a hardened one, and the RLS state-space matrix. Run this before trusting any batch number.
  • Determinism: --spotcheck N on the batch; differing re-scans mean the target changed or the tool is unstable — investigate before using the data.
  • Manual spot-checks: pick a sample of targets, re-run them by hand with -fix and compare against the batch output; verify at least one critical/high finding per finding-id by replaying its evidence.request.
  • Negative controls: make eval-notsupabase must stay quiet against hosts that are not Supabase.

Documentation

Overview

Package scan is the provider-agnostic pipeline that runs a posture scan.

It exists to break up scanTarget(), a single 1,390-line function that carried the whole Supabase scan. That function had 12 author-marked stage boundaries and roughly 30 variables crossing them, and it is the mechanical reason Supabase could not sit behind the same provider seam Firebase already uses: there was no boundary to lift. The stages below are those same 12 boundaries, made into things that can be run -- and therefore tested -- one at a time.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckConsent

func CheckConsent(stages []Stage, c Consent) error

CheckConsent refuses a plan the operator has not authorised.

Consent is already checked INSIDE each stage that writes. That is six places, each of which has to remember, and a stage added tomorrow that forgets is unguarded -- discovered when a row appears in a database nobody agreed to have written to. This makes it structural: the plan as a whole is compared against the permission as a whole, before anything runs.

It does not replace the per-stage checks. Two independent guards for an irreversible action is the right number, and this one is the cheap one: it costs the target nothing because it happens first.

The descriptor describes the CONFIGURED stage, not the type. The same stage with writes disabled mutates nothing and must not be blocked, or every ordinary scan would be refused and the check would be switched off within a week.

func Get

func Get[T any](st *State) (T, bool)

Get returns the artifact of type T and whether one was ever put.

THE BOOL IS THE POINT. A stage that did not run leaves nothing behind, and a consumer must be able to tell that from a stage that ran and found nothing. Returning only T makes the two the same empty struct -- which is how "the probe stage was skipped" comes to read as "the probe found no relations", in a tool whose entire argument is that those are different things.

Callers that genuinely do not care can ignore the bool; callers that steer on the artifact must not.

func Put

func Put[T any](st *State, v T)

Put stores v, replacing any earlier value of the same type.

Replacement rather than accumulation: a stage that runs twice in one scan replaces its own artifact, because silently appending would make the result depend on how many times the pipeline was built.

func Validate

func Validate(stages []Stage) error

Validate checks a plan before anything is sent.

Sequential execution, so "earlier in the list" is the whole of the ordering question and a cycle is impossible by construction -- a consumer above its producer is the shape a cycle takes here, and it is checked directly.

Types

type Access

type Access struct {
	Observed []AccessFact
}

Access is what the scan ESTABLISHED about who may do what.

It is the neutral half of intent verification. The measurements live in a backend's own artifacts -- a probe result knows which relations anon could read, an escalation result knows what a signed-in role gained -- and the command must not read those. So the provider translates, exactly as it does for Coverage.

ONLY MEASURED FACTS BELONG HERE. A relation nobody probed produces no fact, and an expectation about it is therefore unverified rather than satisfied. Filling this in optimistically -- assuming a relation that was never enumerated is denied -- would turn a manifest of intentions into a clean report from a scan that tested none of them.

func MergeAccess

func MergeAccess(parts ...Access) Access

MergeAccess combines provider-neutral measurements without interpreting them. Exact duplicates are removed and output order is stable.

type AccessFact

type AccessFact struct {
	Resource  string
	Operation string
	Subject   string
	// Scope is empty when the probe did not distinguish ownership. "own" and
	// "all" are carried without importing the intent package.
	Scope string
	// Allowed is what happened, not what should have.
	Allowed bool
}

An AccessFact is one measured (resource, operation, subject) outcome.

The fields are strings rather than typed enums because this is the boundary: intent's vocabulary and a backend's vocabulary meet here, and a type shared between them would make the pipeline import one of the two.

type ApplicationCoverage

type ApplicationCoverage struct {
	Routes  int
	Origins int
}

ApplicationCoverage is the denominator for backend-independent route assessment. It is published by the application workload so the engine never needs to import the route implementation merely to count what ran.

type ArtifactType

type ArtifactType string

An ArtifactType names something one stage produces and another consumes.

A string rather than a Go type, because validation happens before anything runs and a plan has to be checkable -- and printable -- without constructing the values it describes. The typed artifact store (Put/Get) is what carries the value; this is what lets the ORDER be argued about in advance.

func ArtifactOf

func ArtifactOf[T any]() ArtifactType

ArtifactOf is the plan identity of T.

The execution store has always been keyed by Go type while StageDescriptor used hand-written strings. That left two contracts for one fact: a producer could declare "probe-result" and publish some other type, the plan would validate, and its consumer would quietly observe absence. Deriving the plan identity from the same type Put and Get use makes that drift impossible.

type Budget

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

Budget is an allowance several stages draw on.

It is the first genuinely SHARED MUTABLE thing to cross the stage seam. Everything before it was either a value passed down (seeds, flags) or a provider-private result handed between stages of one backend. A budget is different: on Supabase the default-schema routine sweep and every per-schema sweep draw on one allowance, and if each sees the full amount the scan issues several times the requests the operator capped it at.

It lives here rather than in a provider package because every backend has a request budget -- the rule already in force is that things EVERY backend has belong to the shared core, and things one backend has stay in its own package.

func NewBudget

func NewBudget(n int) *Budget

NewBudget returns an allowance of n requests.

func (*Budget) Exhausted

func (b *Budget) Exhausted() bool

Exhausted reports whether nothing remains, so a stage can decline cleanly rather than perform a zero-sized sweep and report it as a clean one.

func (*Budget) Left

func (b *Budget) Left() int

Left is how much of the allowance remains. A nil Budget never runs out.

func (*Budget) Take

func (b *Budget) Take(n int) int

Take grants up to n and returns how much was actually granted.

Returning the GRANTED amount rather than a boolean is what lets the caller report its own truncation. The schemas pass was built around this after a real gap: "previously only the default schema's truncation was reported, so a secondary schema whose routine sweep ran out said nothing at all -- a silent coverage gap in the surface most likely to be forgotten". A single global note that names no schema does not close that; the consumer has to know it personally was clipped.

A nil Budget is UNCAPPED and grants everything asked. That is deliberate and load-bearing: every stage written before this type existed runs with no budget, and a zero value that meant "nothing" would silently reduce each of them to zero work and report the result as clean -- the exact false negative this scanner exists to refuse.

type Consent struct {
	// Write authorises requests that change the target: an INSERT probe, a
	// routine invocation, a POST to an application route.
	Write bool
	// ThirdParty authorises telling a party that is not the target about the
	// target -- asking a public archive what a site used to serve, for
	// instance, which discloses what is being scanned to somebody who was not
	// asked.
	ThirdParty bool
}

Consent is what the operator agreed to.

Separate permissions, because they are separate questions. Writing to somebody else's project and telling a third party what you are scanning are different things to agree to, and an operator who said yes to one has not said yes to the other.

type Controls

type Controls struct {
	Write        bool
	Invoke       bool
	NoResidue    bool
	Measure      bool
	SkipRealtime bool
	Subdomains   bool
	History      bool
}

Controls are operator decisions shared by every backend.

type Coverage

type Coverage struct {
	// Relations discovered, across every schema examined.
	Relations int
	// Schemas examined, including the default one.
	Schemas int
	// SeedOrigins is where the candidate names came from, so the summary can
	// say how much of the scan was the application's own vocabulary and how
	// much was a pinned list. The four parts sum to the number actually
	// probed.
	SeedOrigins finding.SeedOrigins
	// OpenSignup reports that anyone can obtain an authenticated role.
	//
	// It belongs here rather than in a backend artifact because it changes a
	// SCAN-LEVEL judgement: an unmeasured escalation surface is an
	// inapplicable check when signup is closed and a genuine blind spot when
	// it is open.
	OpenSignup bool
}

Coverage is what a provider says about the scan as a whole.

It exists to end the last coupling between the command and a backend. The command has to produce two scan-level outputs -- the stored scan summary and the coverage finding that records what was NOT examined -- and it was obtaining the numbers for them by reading supabase.Vocabulary, supabase.Schemas, supabase.EnumerateOutcome and surface.Result. Four backend types, to produce four integers and a boolean.

THE PROVIDER TRANSLATES, THE COMMAND READS. Only the provider knows what its own artifacts mean, so only the provider can fill this in; the command never interprets a backend type to do it. A second backend fills in the same fields or leaves them zero, and neither the command nor this struct changes.

Nil-vs-zero applies as everywhere else here: a provider that published no Coverage has said nothing about how much it covered, which is different from one that covered nothing. Get's bool is what separates them, and the command must not print "0 relations discovered" -- a measurement -- for a provider that never reported.

type Deployment

type Deployment struct {
	Site         string
	ArchiveBase  string
	PreviewHosts []string
	Domain       string
	UserAgent    string
}

Deployment describes application-level context a backend may use for history, previews or domain discovery.

type Describer

type Describer interface {
	Describe() StageDescriptor
}

Describer is implemented by stages that declare their dependencies and side effects. A stage without one is not runnable: optional metadata cannot enforce a graph or a consent boundary.

type Inputs

type Inputs struct {
	// Seeds are candidate relation or collection names discovered upstream:
	// pinned lists, vocabulary harvested from the application, names
	// advertised by the target, and names supplied by an operator or agent.
	//
	// A backend given none of them says nothing rather than inventing any.
	Seeds []string
	// SeedSet is the provenance-preserving form. Seeds remains the merged form
	// for small providers and backwards-compatible external integrations.
	SeedSet SeedSet

	// Redact removes sampled VALUES from findings while keeping them usable,
	// which every backend must honour identically or -redact means something
	// different depending on what the target happens to run.
	Redact bool

	// Client is the shared, rate-limited HTTP client the operator's flags were
	// applied to. It travels with the work because the alternative is each
	// backend building its own, and a stage that does that quietly substitutes
	// package defaults for -rate-limit and -timeout: the flag is accepted, the
	// stage is unpaced, and nothing says so.
	//
	// A backend that receives none must say so rather than improvise one.
	Client      *client.Client
	Limiter     *client.Limiter
	Timeout     time.Duration
	Concurrency int

	// Write is the operator's -write -yes-i-own-this, and it is consent rather
	// than a preference. A backend must check it before BUILDING a request,
	// not before reporting one: a probe whose result is discarded has still
	// changed somebody's data.
	Write      bool
	Controls   Controls
	Limits     Limits
	Deployment Deployment

	// Bearer is a credential the operator supplied for the target, empty when
	// they supplied none.
	//
	// It is separate from Client because its ABSENCE is information a backend
	// has to act on rather than route around. On Neon there is no anonymous
	// tier to fall back to: without a bearer every name answers identically,
	// so the honest contribution is to report the surface unassessed and skip
	// the stages that would otherwise present a refusal as a measurement.
	Bearer string
	// Credential is the public client credential belonging to the detected
	// backend. Bearer is an authenticated identity used for comparisons.
	Credential string

	// Shared routine budgets are mutable because secondary schemas and the
	// default schema draw from one allowance.
	ExtraRoutines *Budget
	RPCRoutines   *Budget
}

Inputs are the operator's choices and the scan's upstream discoveries, in the form every backend can consume.

It exists because Stages(Detection) alone could only build stages that need nothing but the identification, and no real stage is like that: each one needs the candidate names found upstream and the flags the operator set. A seam that cannot carry those forces every provider to reach around it, which is exactly how the orchestration ended up inside main the first time.

The field list is deliberately short and grows one field at a time, each justified by a stage that needs it and a test that fails without it. The failure to avoid is a struct every backend must accept and only one populates -- that is worse than the honest asymmetry it would replace. Anything meaningful to a single backend belongs to that backend's own package, the way probe.Result is handed between Supabase stages.

type Limits

type Limits struct {
	Relations   int
	RPC         int
	Columns     int
	Collections int
	SampleRows  int
}

Limits are scan-wide traffic and evidence bounds. A provider consumes the limits relevant to its protocol and cannot invent a private default without making that divergence visible in its plan tests.

type Note

type Note struct {
	Stage string
	Level NoteLevel
	Text  string
}

A Note is one operator-facing sentence from one stage.

type NoteLevel

type NoteLevel int

NoteLevel separates progress from loss.

The distinction is load-bearing and this project has already got it wrong once: falling back to the pinned wordlist is a CHOICE when there is no site and a LOSS when there is one, and printing both as info told operators nothing had gone wrong when their recall had just dropped.

const (
	// Info is the scan describing what it is doing.
	Info NoteLevel = iota
	// Warn is the scan describing something that reduces what it can find.
	Warn
	// Error is the scan saying its own results cannot be relied on.
	//
	// Distinct from Warn because the consequence is different in kind. A
	// warning says recall dropped; an error says the measurement itself is
	// untrustworthy, which is what a failed control probe means -- read and
	// write classification both start from the discovered set, so nothing
	// downstream of it can be believed.
	Error
)

func (NoteLevel) String

func (l NoteLevel) String() string

type Pipeline

type Pipeline []Stage

Pipeline is an ordered list of stages.

func (Pipeline) Run

func (p Pipeline) Run(ctx context.Context, st *State) ([]finding.Finding, error)

Run executes every stage in order and returns everything they found.

A stage that fails does NOT abort the run. In the single-function version an error returned from scanTarget and every remaining surface -- realtime, storage, historical exposure -- went unexamined while the report said nothing about them. Stopping at the first refusal and reporting whatever was reached before it is precisely the false-negative this project exists to eliminate.

Continuing is only honest because the failure is recorded: each error becomes a not-assessed finding carrying the id the exit code already keys on, so an unexamined surface drives exit 3 rather than passing for a clean one.

type SeedSet

type SeedSet struct {
	Merged      []string
	Pinned      []string
	Harvested   []string
	Advertised  []string
	Supplied    []string
	SourcesRead int
}

SeedSet preserves provenance while providers derive their candidate names. Merged is retained for providers whose protocol has one undifferentiated namespace; the other fields let a provider prefer operator assertions over guesses when probing has side effects or cost.

type Stage

type Stage interface {
	// Name is stable and appears in coverage reporting, so it is part of the
	// output contract, not a debug label.
	Name() string
	// Run performs the step. Returning an error means "this surface could not
	// be assessed", not "the scan failed": see Pipeline.Run.
	Run(ctx context.Context, st *State) error
}

A Stage is one step of a scan.

The interface is deliberately tiny. Anything a stage needs comes from State, and everything it learns goes back into State, because the alternative -- stages that accept and return bespoke tuples -- is how the original function grew 30 variables of shared scope in the first place.

func Skip

func Skip(s Stage, reason string) Stage

Skip wraps a stage the operator turned off, or that a declared limit rules out, so that it does not run and is still reported.

The rule is the one the audit applies to its own checks: a row marked "not run" is not a pass. Two flags once disabled a check AND suppressed any note that it had been disabled, so a scan with them read exactly like a scan where those surfaces came back clean.

type StageDescriptor

type StageDescriptor struct {
	// ID is the stage's name. It is also the ledger label and the resource on
	// its not-assessed finding, so two stages sharing one make the spend
	// breakdown ambiguous in a way no reader can see.
	ID string
	// Requires must be produced by an EARLIER stage. Absent is a planning
	// error, not a run-time surprise.
	Requires []ArtifactType
	// Optional may be absent legitimately. The schemas artifact is the case:
	// absent means no extra schema was discovered, which is the common case,
	// and the default schema is examined either way.
	Optional []ArtifactType
	// Produces is what this stage publishes.
	Produces []ArtifactType

	// MutatesTarget is true when the stage writes to somebody else's project.
	// Declared so a plan can be refused before it starts rather than audited
	// afterwards.
	MutatesTarget bool
	// SendsSecrets is true when the stage transmits a credential the operator
	// supplied to a host that is not the target's own origin.
	SendsSecrets bool
}

A StageDescriptor is what a stage declares about itself.

The Supabase stage list is documented as a dependency graph and its order is tested as one, but until this the dependencies were implicit: a stage called Get and either found something or did not. Reorder two stages, delete a producer, add a consumer above its producer, and the failure is a stage that quietly finds nothing -- at the far end of a scan that has already spent thousands of requests on somebody else's server.

Declaring them makes the graph checkable at the cheapest possible moment: before the first request.

type StageSpend

type StageSpend struct {
	Stage    string
	Requests int
}

StageSpend is how many requests one stage accounted for.

type State

type State struct {
	// Target is where the scan is pointed, used as the Matched value on
	// findings the pipeline itself emits.
	Target string

	// Stage is the stage currently running, set by the pipeline so a note can
	// attribute itself without every stage having to repeat its own name.
	Stage string
	// OnNote, when set, receives each note AS IT IS MADE.
	//
	// Progress lines have to arrive while the stage is still working. Without
	// this, a note is only visible once the stage returns, so "enumerating
	// relations" prints after enumeration -- announcing finished work -- and
	// those lines stay in the command instead of moving to the stage that
	// knows when to say them.
	//
	// Optional. Notes are recorded either way, so a consumer reading the run
	// afterwards sees the same list.
	OnNote func(Note)
	// contains filtered or unexported fields
}

State is what stages share.

It is the migration's hard part and its main risk. Roughly 30 variables cross the stage boundaries in the original function, and the temptation is to move all of them here at once. That would produce a struct every backend must accept and only one populates, which is worse than the honest asymmetry it replaces. Fields arrive here only as a stage that needs them is ported, and each arrival should be justified by a test.

func (*State) Add

func (s *State) Add(fs ...finding.Finding)

Add records findings in the order stages produce them.

Order is stable by construction: stages run in declared order and append. Report-level sorting happens on the way out, but nothing above this layer can be deterministic if this one is not.

func (*State) Attribute

func (s *State) Attribute(stage string, n int)

Attribute records requests a stage spent.

This is ATTRIBUTION, not the authoritative request total, and the distinction is load-bearing. The stored report once said 1,827 requests for a scan that actually sent 88: it was counting what the stages asked for, including the seventeen hundred the circuit breaker declined to make. A report that overstates its own traffic is the same class of error as one that overstates its coverage, because the reader cannot tell effort from intent.

The authoritative total therefore comes from the transport's own counter -- what was actually sent. What this gives is the breakdown: where the traffic went, which the transport counter cannot say.

func (*State) Attributed

func (s *State) Attributed() int

Attributed is the sum of everything stages accounted for. See Attribute for why this is not the number a report should print as its request count.

func (*State) Findings

func (s *State) Findings() []finding.Finding

Findings returns everything recorded so far.

func (*State) Note

func (s *State) Note(level NoteLevel, format string, args ...any)

Note records a sentence for the command to render.

Formatted here rather than by the caller so that the stage's own vocabulary -- counts, names, reasons -- stays with the stage, and so a renderer never receives a half-built string it has to finish.

func (*State) Notes

func (s *State) Notes() []Note

Notes returns everything stages have said, in the order they said it.

Order is the point: the lines describe a scan unfolding, and sorting or grouping them would keep every fact while ceasing to be a description of what happened.

func (*State) Spending

func (s *State) Spending() []StageSpend

Spending is the per-stage breakdown, sorted by stage name.

Sorted by name and not by execution order, because execution order is not stable across a pipeline whose stages can be skipped or reordered by flags, and two scans of an unchanged project have to produce identical bytes.

Jump to

Keyboard shortcuts

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