copycheck

package
v0.123.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: BSD-3-Clause Imports: 24 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package copycheck is the engine of the copycheck gate: it decides whether a repository's source resembles the source of references it declared reading, in a way its declared roles and their licences do not allow.

⛔ THE RULE THIS TURNS INTO A GATE: copyleft reference code (ffmpeg, FAAD2...) may be READ to understand, never copied or translated, and its tables never copied verbatim. A rule nobody has to remember is a rule a program checks.

Two measurements, because each is blind where the other sees:

  • numeric tables: runs of numeric literals, normalised so that 0x10, 16 and 16.0f are one value, compared by winnowing. A copied or re-typed table survives any change of language, formatting or variable name.
  • code shape: token streams normalised across C and Go, compared by winnowing (Schleimer, Wilkerson, Aiken, "Winnowing: Local Algorithms for Document Fingerprinting", SIGMOD 2003, the algorithm behind MOSS). A C to Go translation keeps the shape of the control flow and the spelling of the names, and loses the punctuation.

The lexer below is shared by both, and reads untrusted bytes: it never panics, never loops without consuming input, and is linear.

Index

Constants

View Source
const (
	KindPolicy      = "policy"
	KindTable       = "table"
	KindShape       = "shape"
	KindAttribution = "attribution"
	// KindDeclaration: a values entry that points at nothing.
	KindDeclaration = "declaration"
	// KindUndeclared: a table with no provenance at all, in a path that requires it.
	KindUndeclared = "undeclared-table"
	// KindDeclared is not a finding: a table that matches a reference and was
	// ACCEPTED because the symbol is declared. It is listed in Report.Accepted
	// so that the exemption is auditable, not silent.
	KindDeclared = "declared-values"
)

Finding kinds.

View Source
const (
	RoleStudied    = "studied"     // read to understand; nothing may be copied
	RoleOracle     = "oracle"      // run to compare outputs; nothing may be copied
	RoleTablesFrom = "tables-from" // numeric tables taken, permissive licence only
	RolePortedFrom = "ported-from" // code translated, permissive licence only
)

Roles of a reference. The role is what the repository's author PROMISES about how the reference was used; the gate checks the promise against the bytes.

View Source
const (
	// ValueNormative: the table is the bare numeric content of a standard's
	// normative table. ⛔ THE DECISION (2026-11-10): such values may be
	// reproduced, as FFmpeg and FAAD2 do, because values dictated by technical
	// constraints are not original works (Feist v. Rural, 1991; Football
	// Dataco v. Yahoo, CJEU 2012) -- but never the standard's TEXT and never its
	// reference CODE. The exemption covers numbers; it never covers shape.
	ValueNormative = "normative-values"
	// ValueDerived: the values are computed in code from a published formula,
	// and the declaration names the source.
	ValueDerived = "derived"
)

Kinds of a Value declaration.

View Source
const DefaultManifest = ".provenance.yml"

DefaultManifest is where a checked repository declares what it read.

⛔ WHY A YAML FILE AND NOT A MARKDOWN BLOCK. A PROVENANCE.md with a fenced block would be read by people, and a gate that parses prose finds the paragraph that is easiest to edit by hand and hardest to notice edited. A file that is only data cannot be half-updated: it parses or the gate says so. YAML over TOML because the module already carries a YAML reader (a new dependency for a gate is a new thing to audit), and because it allows the one thing a provenance record needs most: a comment saying WHY a reference is there. The prose belongs in the README, which can link to this file.

Variables

This section is empty.

Functions

func Canon

func Canon(text string) (canon string, ok bool)

Canon normalises a numeric literal so that the same VALUE has the same spelling whatever the language wrote: 0x10, 16, 020 (C octal), 0b10000, 16.0f, 1.6e1 and 1_6 (Go) are all "16". Integral floats collapse to the integer, so a table written with ints in C and floats in Go still matches. Other floats are rounded to 7 significant digits, the precision of a C `float`, so 0.70710678f and 0.70710678118654752 are the same number.

ok is false for what is not a plain number (a Go imaginary, a malformed literal): the caller treats that as the end of a run, never as a value.

func CheckCacheDir

func CheckCacheDir(dir string) (string, error)

CheckCacheDir refuses a directory under a `.git` parent.

func DefaultCacheDir

func DefaultCacheDir() (string, error)

DefaultCacheDir is under os.UserCacheDir and refuses to be inside a git working tree: a downloaded reference committed by `git add -A` is a copyleft source tree in our history.

func Extract

func Extract(archive, dst string, paths []string, strip int, lim Limits) error

Extract unpacks the source files of a tar.gz or zip under paths into dst. Symlinks, hard links and devices inside the selected paths are refused; every name is checked, selected or not.

func TreeHash

func TreeHash(root string) (string, error)

TreeHash is the hash a manifest records: over the sorted relative paths and the SHA-256 of each kept file. It does not depend on how the archive was compressed, which a host may change without changing one byte of source (a GitHub archive's own hash is not promised stable).

Types

type Class

type Class int

Class is what a licence lets a derivative do.

const (
	// Permissive: copying is allowed with attribution.
	Permissive Class = iota
	// FileCopyleft: copying is allowed only into a file that is itself under the
	// same licence (MPL, EPL, CDDL). The gate checks the FILE, not the repository.
	FileCopyleft
	// Copyleft: copying or translating makes the result a derivative under the
	// reference's licence. The project does not do that, by decision.
	Copyleft
	// Unknown: not in the table. Treated as Copyleft for every decision and
	// reported as unknown, so that the table is extended on purpose.
	Unknown
)

func ClassOf

func ClassOf(expr string) Class

ClassOf classifies an SPDX expression. `A OR B` is the licensee's choice, so the most permissive operand wins; `A AND B` binds both, so the strictest wins; `X WITH exception` is X (the exception narrows X, and the gate declines to guess how). An expression it cannot read is Unknown.

func (Class) String

func (c Class) String() string

type Fetcher

type Fetcher struct {
	Client   *http.Client
	CacheDir string
	Limits   Limits
}

Fetcher downloads, extracts and verifies references into a durable cache.

func (*Fetcher) Fetch

func (f *Fetcher) Fetch(ref Reference) (dir, tree string, err error)

Fetch makes the reference available under the cache and returns its directory. When ref.Tree is empty the hash is not checked and is returned (that is `copycheck pin`); otherwise a mismatch is an error, never a fallback.

type Finding

type Finding struct {
	Kind       string    `json:"kind"`
	Message    string    `json:"message"`
	Ours       *Location `json:"ours,omitempty"`
	Reference  string    `json:"reference"`
	License    string    `json:"license,omitempty"`
	Role       string    `json:"role,omitempty"`
	Theirs     *Location `json:"theirs,omitempty"`
	Numbers    int       `json:"matching_numbers,omitempty"`
	Tokens     int       `json:"tokens,omitempty"`
	Similarity float64   `json:"similarity,omitempty"` // 0..1
}

Finding is one thing the gate refuses, with both ends of it.

type Fingerprint

type Fingerprint struct {
	Hash uint64
	Pos  int
}

Fingerprint is one selected k-gram: its hash and where it starts in the sequence it came from.

func Winnow

func Winnow(seq []string, k, w int, skip func(gram []string) bool) []Fingerprint

Winnow selects fingerprints from seq: the hash of every k-gram is computed, and from every window of w consecutive hashes the smallest is kept (the rightmost on a tie), once.

The guarantee that makes it a detector and not a sampler: any substring shared by two sequences and at least k+w-1 long yields at least one common fingerprint, whatever surrounds it. skip, when not nil, drops the k-grams it returns true for BEFORE selection (a table of zeros says nothing).

type Kind

type Kind uint8

Kind is the class of a Token.

const (
	KIdent Kind = iota + 1
	KNum
	KStr
	KChar
	KPunct
)

type Limits

type Limits struct {
	ArchiveBytes int64 // the download, as sent
	StreamBytes  int64 // the archive after decompression, everything in it
	TotalBytes   int64 // what is kept
	FileBytes    int64 // one kept file
	Files        int   // kept files
	Entries      int   // entries read, kept or not
}

Limits bound what an archive may make us do. A reference is untrusted input: a URL in a manifest can point at anything, and an archive's declared sizes are numbers the archive chose.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits are above the largest reference we meant to read (a pinned frameworks/base is about 1 GiB unpacked) and far below a bomb.

type Location

type Location struct {
	File  string `json:"file"`
	Start int    `json:"start_line"`
	End   int    `json:"end_line"`
}

Location is a line range in a file.

type Manifest

type Manifest struct {
	Version         int              `yaml:"version"`
	Notice          string           `yaml:"notice"`  // attribution file, default NOTICE
	Exclude         []string         `yaml:"exclude"` // our paths not to compare: a directory prefix ending in /, or a file
	References      []Reference      `yaml:"references"`
	Values          []Value          `yaml:"values"`
	RequireDeclared *RequireDeclared `yaml:"require_declared"`
}

Manifest is the file a checked repository carries.

func LoadManifest

func LoadManifest(path string) (*Manifest, error)

LoadManifest reads and validates a manifest. Unknown keys are an error: a misspelt `tree_sha256` would otherwise be an unverified reference.

func ParseManifest

func ParseManifest(b []byte) (*Manifest, error)

ParseManifest is LoadManifest over bytes.

type NumRun

type NumRun struct {
	Vals  []string
	Lines []int
}

NumRun is a maximal run of numeric literals separated only by what a table separates its entries with.

func NumRuns

func NumRuns(toks []Token, minLen int) []NumRun

NumRuns extracts the numeric runs of at least minLen values.

What may sit between two numbers of one run: `,` `{` `}` `(` `)`, a unary sign, and an ALL_CAPS name (FAAD2 writes FRAC_CONST(0.5), COEF_CONST(1.0): the macro is the table's spelling, the number is its content). Anything else (an identifier, `;`, `=`, an operator between two numbers) ends the run.

type Options

type Options struct {
	Root       string
	Manifest   *Manifest
	Fetcher    *Fetcher
	Thresholds Thresholds
}

Options are what Check needs.

type PolicyFinding

type PolicyFinding struct {
	Reference string
	Message   string
}

PolicyFinding is a refusal that needs no source to be read.

func CheckPolicy

func CheckPolicy(m *Manifest) []PolicyFinding

CheckPolicy refuses the declarations that cannot be honoured: taking from a licence that does not allow it, and licences the table does not know.

type RefStatus

type RefStatus struct {
	Name  string `json:"name"`
	Pin   string `json:"pin"`
	Tree  string `json:"tree_sha256"`
	Files int    `json:"files"`
}

RefStatus records that a reference was read and which bytes it was.

type Reference

type Reference struct {
	Name    string   `yaml:"name"`
	URL     string   `yaml:"url"` // https archive (tar.gz or zip) of the PINNED revision
	Pin     string   `yaml:"pin"` // commit or tag; must appear in the URL
	Tree    string   `yaml:"tree_sha256"`
	License string   `yaml:"license"` // SPDX expression
	Role    string   `yaml:"role"`
	Paths   []string `yaml:"paths"` // only these subtrees are fetched and compared (a directory prefix, no leading slash)
	Note    string   `yaml:"note"`
	// Strip is how many leading path components of the archive to drop: 1 (the
	// default) for GitHub archives, 0 for android.googlesource.com +archive.
	Strip *int `yaml:"strip_components"`
	// Restrictions express what a licence cannot: a FILE that carries its own
	// notice. PacketVideo's AAC decoder is Apache-2.0 as a whole, yet 114 of
	// its files also carry an MPEG copyright notice, so for those files the
	// role is studied whatever the manifest says for the reference.
	Restrictions []Restriction `yaml:"restrictions"`
}

Reference is one body of source the repository's authors read.

type Report

type Report struct {
	Thresholds Thresholds  `json:"thresholds"`
	OurFiles   int         `json:"our_files"`
	References []RefStatus `json:"references"`
	Findings   []Finding   `json:"findings"`
	// Accepted lists the table matches that were let through because the symbol
	// is declared normative-values or derived. Never code.
	Accepted []Finding `json:"accepted,omitempty"`
}

Report is the whole answer.

func Check

func Check(opt Options) (*Report, error)

Check runs the whole gate. A non-nil error means the question could not be answered (exit 2); findings are in the report (exit 1 when any).

type RequireDeclared

type RequireDeclared struct {
	MinNumbers int      `yaml:"min_numbers"`
	Paths      []string `yaml:"paths"`
}

RequireDeclared turns on the rule that every table above MinNumbers numbers in the named files must be declared in Values (or be attributed to a permissive tables-from reference). Paths are prefixes of our files' relative paths: "aac" covers aac.go, aac_tables.go and aac/anything.go. Absent, the rule is off, so a repository adopts it package by package.

type Restriction

type Restriction struct {
	Name     string   `yaml:"name"`
	Contains []string `yaml:"contains"` // case-insensitive substrings
}

Restriction names a notice that, when found anywhere in a reference file, makes that file READ-ONLY for us: a match against it is a finding under every role, tables-from and ported-from included.

type ST

type ST struct {
	Text string
	Line int
}

ST is one normalised token.

func Shape

func Shape(toks []Token) []ST

Shape normalises a token stream so that the same algorithm written in C and in Go gives the same stream:

  • identifiers are lower-cased and lose their underscores;
  • numbers, strings and chars become N, S and N (a C char is a number);
  • for/while/do/range become one keyword; `->` becomes `.`; `:=` becomes `=`;
  • braces, parentheses and semicolons are dropped (C needs them where Go does not, and they carry no information the other tokens lack);
  • type words and declaration keywords are dropped.

type ShapeFile

type ShapeFile struct {
	Path string
	Toks []ST
	FPs  []Fingerprint
}

ShapeFile is one file's normalised stream and fingerprints.

func NewShapeFile

func NewShapeFile(path string, src []byte, k, w int) *ShapeFile

NewShapeFile lexes, normalises and fingerprints src.

type ShapeIndex

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

ShapeIndex is the fingerprints of our files.

func NewShapeIndex

func NewShapeIndex(files []*ShapeFile, k int) *ShapeIndex

NewShapeIndex indexes our files.

func (*ShapeIndex) Match

func (ix *ShapeIndex) Match(ref *ShapeFile, minTokens int, minSim float64, maxGap, maxDrift int) []ShapeMatch

Match streams one reference file past the index.

A block is a chain of hits sorted by position in OUR file, cut where the gap exceeds maxGap tokens or where the offset between the two files drifts by more than maxDrift. The second cut is what keeps a few lines of boilerplate that happen to occur all over a large reference from adding up to a "block".

type ShapeMatch

type ShapeMatch struct {
	OurFile          string
	OurStart, OurEnd int // lines
	RefFile          string
	RefStart, RefEnd int
	Tokens           int     // length of the block, in normalised tokens
	Similarity       float64 // matched fingerprints / our fingerprints inside the block
}

ShapeMatch is a block of our file whose fingerprints are found, in the same order and at nearly the same distance from each other, in one reference file.

type TableFile

type TableFile struct {
	Path string
	Runs []NumRun
	// contains filtered or unexported fields
}

TableFile is one file's runs with their fingerprints.

func NewTableFile

func NewTableFile(path string, src []byte, k, w int) *TableFile

NewTableFile lexes src and fingerprints its numeric runs.

type TableIndex

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

TableIndex is the fingerprints of OUR files, looked up while a reference is streamed past it.

func NewTableIndex

func NewTableIndex(files []*TableFile, k int) *TableIndex

NewTableIndex indexes our files.

func (*TableIndex) Match

func (ix *TableIndex) Match(ref *TableFile, minRun, minDistinct int) []TableMatch

Match streams one reference file past the index and returns every maximal common run of at least minRun values with at least minDistinct different values (a run of one repeated value is a constant, not a table).

type TableMatch

type TableMatch struct {
	OurFile          string
	OurStart, OurEnd int // lines
	RefFile          string
	RefStart, RefEnd int
	Len              int
	Distinct         int
}

TableMatch is a run of values common to one of our files and one reference file, verified value by value (a hash is a hint, never the evidence).

type Thresholds

type Thresholds struct {
	TableK           int `json:"table_k"`            // window of numbers (>= 8)
	TableW           int `json:"table_w"`            // winnowing window
	TableMinRun      int `json:"table_min_run"`      // matching numbers that make a finding
	TableMinDistinct int `json:"table_min_distinct"` // different values a run must hold

	ShapeK        int     `json:"shape_k"`          // window of normalised tokens
	ShapeW        int     `json:"shape_w"`          // winnowing window
	ShapeMinToks  int     `json:"shape_min_tokens"` // block size that makes a finding
	ShapeMinSim   float64 `json:"shape_min_sim"`    // matched fingerprints / ours, in the block
	ShapeMaxGap   int     `json:"shape_max_gap"`    // tokens between hits of one block
	ShapeMaxDrift int     `json:"shape_max_drift"`  // offset change between hits of one block
}

Thresholds are the numbers the two measurements decide by. They are tuned on a control and a planted positive (see the README and the tests), and every one can be overridden on the command line, in which case the report says so.

func DefaultThresholds

func DefaultThresholds() Thresholds

DefaultThresholds are the tuned values.

func (Thresholds) Validate

func (t Thresholds) Validate() error

Validate refuses thresholds that would make the gate a sampler: a window under 8 numbers matches every small table in the world, and a minimum run under k+w-1 is below winnowing's guarantee of detection.

type Token

type Token struct {
	Kind Kind
	Text string
	Line int
}

Token is one lexeme with the line it started on (1-based).

func Lex

func Lex(src []byte) []Token

Lex splits C, C++ or Go source into tokens. Comments are dropped. Of the preprocessor only `#define` is kept (its body may hold a table); every other directive line is dropped. Strings and chars become one token each. Anything unterminated ends at the end of its line (strings, chars) or of the input (comments, raw strings), which bounds the damage of malformed input.

type Value

type Value struct {
	Kind      string `yaml:"kind"`
	File      string `yaml:"file"`   // our file, relative to the root
	Symbol    string `yaml:"symbol"` // a Go var/const/func name in that file
	Standard  string `yaml:"standard"`
	Clause    string `yaml:"clause"`
	Source    string `yaml:"source"` // derived: the paper and equation number
	Rationale string `yaml:"rationale"`
}

Value declares the provenance of one table (or one function that computes one): where in OUR source it is, and why its numbers are ours to hold.

Jump to

Keyboard shortcuts

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