lint

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MPL-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package lint holds the three custom static analyzers the tenant-isolation ADR fixes (proof signatures, SQL predicate confinement, proof-forgery guard). They run against the real repository from this package's tests, so a violation is a build failure in CI. Each is a guardrail with its evasion limits stated in the ADR — logic bugs inside the trusted set are review's job, not lint's.

The ADR sketches these as go/analysis passes; they are implemented directly over go/packages type information instead — same inputs, same build-failing effect, less framework. The checks return findings as strings so the tests (and the invariant suite) can assert emptiness and print every violation at once.

Index

Constants

View Source
const Module = "github.com/Hikyo-Org/hikyo"

Module is the module path the analyzers reason about.

Variables

View Source
var Contexts = []BuildContext{
	{Name: "default"},
	{Name: "ui", BuildFlags: []string{"-tags=ui"}},
	{Name: "darwin", GOOS: "darwin", ProductionOnly: true},
	{Name: "windows", GOOS: "windows", ProductionOnly: true},
}

Contexts is the supported analysis matrix, shared by the lint and boundary loaders. The default context is first, and Load/LoadRepo use it.

View Source
var ResolutionSurfaceWriters = map[string]bool{}/* 151 elements not displayed */

ResolutionSurfaceWriters is the PINNED enumerated write list of the authorization resolution surface. It is the review artifact: adding a name here is how a new proof-free write path gets noticed, and everything not named still fails the build.

The audit-model ADR's amendment part 4 pinned exactly one entry, WriteDenial, because a failed authorize() mints no proof and its denial event therefore cannot travel the proof-carrying store surface. Human authentication (#47) is the same circularity seen from the other side: resolving, minting and revoking the artifact that decides WHO a caller is cannot run under a proof, because the proof is what that answer produces.

Stated as a deviation rather than smuggled in: the ADR says "exactly one", and this is more than one. What is preserved is the property the "exactly one" was protecting — every proof-free write is named, in one place, with a build failure behind it. See docs/handoff/47-first-slice.md, which routes the wording to human disposition.

View Source
var SensitiveTypes = map[string]bool{
	Module + "/internal/crypto.LocalKeys":      true,
	Module + "/internal/crypto.Keyring":        true,
	Module + "/internal/crypto.ProjectSealer":  true,
	Module + "/internal/crypto.InstanceSealer": true,
	Module + "/internal/crypto.swapHandle":     true,
	Module + "/internal/crypto.TransitKey":     true,
}

SensitiveTypes pins the material-holding types; crypto's compile-time redactionSurface pins name the same exported set. The synchronization test documents internal-only exceptions; CheckRedactionSurfaces asserts this list actually carries the five methods. Neither discovers unlisted holders.

Functions

func CheckAuditAppendOnly

func CheckAuditAppendOnly(repoRoot string) []string

CheckAuditAppendOnly scans every query file on both engines.

func CheckDenialWriter

func CheckDenialWriter(pkgs []*packages.Package, repoRoot string) []string

CheckDenialWriter enforces the enumerated-writer rule as a build failure, not a comment. The import boundary alone cannot see this — internal/store/authn already holds the generated query handles, so a mutating call inside it would be a proof-free writer that every other guard admits. Every call to a generated mutating query from that package must sit inside a function named in ResolutionSurfaceWriters.

func CheckDenialWriterIn

func CheckDenialWriterIn(pkgs []*packages.Package, surface string, writers, mutating map[string]bool) []string

CheckDenialWriterIn is CheckDenialWriter with the surface named, so the negative fixture can prove the check actually fires on an unlisted writer rather than merely on a package that has none.

func CheckDriverHandles

func CheckDriverHandles(pkgs []*packages.Package) []string

CheckDriverHandles enforces both allowlists across the module, test packages included — a bypass in a test is still a bypass of the property the tests exist to prove.

func CheckFenceCompleteness

func CheckFenceCompleteness(pkgs []*packages.Package, servicePath string) []string

CheckFenceCompleteness enforces the writer fence's coverage (encryption-model ADR § Rotation, invariant 7): every ciphertext a service seals for storage must be guarded, in its write transaction, by the writer fence — otherwise a row sealed under a DEK version a concurrent rotate-dek is retiring can strand under a key `reencrypt` has already walked past.

The rule, per top-level function in internal/service: a function that calls ProjectSealer.SealValue/SealField or InstanceSealer.SealField must also call one of the fence helpers (fenceProject / fenceInstance / fenceInstanceVersion) or the authentication-surface fence (TxAuthorizer.AssertActiveInstanceDEKVersion). The granularity is the function, not the individual write, because the FOR SHARE lock the fence takes is held to the transaction's commit and so covers every sealed write committed in the same function.

Two escape hatches, both explicit and reviewable — never silent:

  • a `fence:delegated` marker in the function's doc comment: the function seals but returns the ciphertext and its DEK version to a caller that fences on that version before writing (the sealVerifier / sealSecret / generateSPKey helpers).
  • a `fence:exempt` marker: the sealed bytes are never written to any table (the recovery timing-equalisation dummy), so no row can be stranded.

reencrypt.go is exempt wholesale: it IS the mover, re-sealing rows under the new active version; fencing it against the version it is installing would be circular.

Stated limits, in the spirit of the other analyzers — each is a build-time surfacing, not the enforcement, which is the runtime fence itself:

  • A function that seals on one path and fences on an unrelated path would pass. The service methods are one operation each, so this does not arise.
  • The analyzer proves a seal and a fence CO-OCCUR in a function; it does not prove the fence runs after the seal and inside the SAME transaction as the store write. A function that sealed, fenced-and-committed in transaction A, then wrote in a separate transaction B would pass while leaving the write unfenced. Proving transaction co-location needs dataflow this type-only pass does not attempt; all current sealing sites were verified in-tx by hand (each fences immediately before its write, in the write's own tx).
  • `fence:delegated` / `fence:exempt` markers are trusted, not verified: a reviewer owns that a delegated helper's version truly reaches a fencing caller, and that an exempt seal truly never reaches a table.

func CheckGrantLock

func CheckGrantLock(pkgs []*packages.Package, repoRoot string) []string

CheckGrantLock enforces the obligation over EVERY module package that can call a generated grant-mutation query, not only the resolution surface: a grant write is a grant write wherever it is issued from. It scans all loaded packages except the generated query packages themselves (whose method bodies ARE the queries, not callers of them). testdata fixtures are never loaded by the `module/...` pattern, so the negative fixture does not false-positive the repo run.

func CheckGrantLockIn

func CheckGrantLockIn(pkgs []*packages.Package, surface string, writers map[string]bool, lock string) []string

CheckGrantLockIn is CheckGrantLock scoped to ONE named surface, so the negative fixture can prove the check fires on a lockless grant writer and stays silent outside the surface it is pointed at.

func CheckProofForgery

func CheckProofForgery(pkgs []*packages.Package) []string

CheckProofForgery is analyzer 3 (tenant-isolation ADR, invariant 9). The concrete proof type is unexported, so it cannot be named outside internal/authz at all — what remains expressible, and is flagged here:

  • a nil literal in a Proof-typed position (call argument, variable initialisation, assignment, return, struct literal): the only forgeable Proof value. The store boundary already rejects nil at runtime; the guard removes the expression at build time.
  • reflect or unsafe imported by a package that handles Proof values: conservative by design — the pair is how a forged proof would be assembled, and no package outside authz has business combining them.

The authorization package itself (and its tests) are exempt: boundary tests must construct exactly these invalid values.

func CheckProofSignatures

func CheckProofSignatures(pkgs []*packages.Package, storePath string) []string

CheckProofSignatures is analyzer 1 (tenant-isolation ADR, invariant 7): every store method reachable through the repository bundles takes a proof as its first parameter after ctx, and no store-method signature — nor any struct type reachable from its parameters, transitively — carries a tenant-identifier-typed value (domain.OrgID / ProjectID / EnvID). Caller arguments must be structurally unable to reach a chain predicate; the stated limit is that a raw string can still smuggle an id, which never reaches a chain column because only the proof binds those.

The repository surface is discovered, not curated: starting from store.Repos and store.ReadRepos, every interface reachable through method results is part of the surface. A new aggregate wired into the bundles is covered automatically; one not wired in is unreachable by services and therefore dead code.

func CheckRawSQL

func CheckRawSQL(pkgs []*packages.Package, repoRoot, packagePrefix string, protocols map[string]RawSQLProtocol, buildContext ...string) []string

CheckRawSQL confines handwritten execution to the reviewed protocol owners. Generated sqlc files and test fixtures are excluded from production ownership. Method values, aliases and interface calls are checked by their typed call signature, so changing the receiver spelling cannot hide an execution site.

func CheckRedactionSurfaces

func CheckRedactionSurfaces(pkgs []*packages.Package) []string

CheckRedactionSurfaces asserts rule 1 against the loaded repo.

func CheckReencryptCoverage

func CheckReencryptCoverage(sqliteMigrationsDir string) []string

CheckReencryptCoverage is the reencrypt-coverage gate (encryption-model ADR § Rotation, invariant 7 / #187). A DEK version is retired only once zero ciphertexts reference it, and reencrypt proves that by walking every table that holds tier-3-DEK-enveloped ciphertext. If a NEW enveloped column is added to the schema but not to the walk, its rows are never moved and never scanned by the retire's dryness gate (which scans only the walk's tables) — so the retire would destroy a still-referenced key. This gate makes that impossible to add silently: every BLOB/BYTEA column in the schema must be classified as either reencrypt-covered or explicitly exempt, and an unclassified new column fails the build until someone decides which it is.

The covered set must equal reencrypt's walk (service.Reencrypt). The exempt set is every other BLOB column, each a reviewed non-target: a wrapped KEY (master/tier3 — a different tier, rotated by rotate-master-key/rotate-dek, not reencrypt), a hashed/single-use VERIFIER (never envelope-decryptable), a short-lived FLOW artifact (OAuth/SAML/WebAuthn transaction state), or PUBLIC material (certificates, public keys, opaque handles).

func CheckSQLPredicates

func CheckSQLPredicates(repoRoot string) []string

CheckSQLPredicates runs analyzer 2 over both engines' migration and query directories under repoRoot, including the cross-engine agreement checks (same tables, directives, and query contracts on both engines).

func CheckSensitiveFormatting

func CheckSensitiveFormatting(pkgs []*packages.Package) []string

CheckSensitiveFormatting asserts rules 2 and 3 across the module, tests included.

func CheckServiceSeams

func CheckServiceSeams(pkgs []*packages.Package, servicePath, storePath string) []string

CheckServiceSeams confines global reauthentication duration and schema-revision advancement to their policy helpers. Type identity catches renamed receivers and method values while allowing unrelated fields and methods with those names. This checks the access boundary, not policy correctness inside the helpers.

func CheckTestObservers

func CheckTestObservers(pkgs []*packages.Package) []string

CheckTestObservers prohibits production references to mutable acceptance-test hook installers, including function values and uses in their defining files. Type resolution recognizes import aliases and ignores unrelated names.

func CheckTransactionResults

func CheckTransactionResults(pkgs []*packages.Package) []string

CheckTransactionResults keeps tx.WriteResult's generic result channel detached from transaction-owned authority. Runtime reflection is forbidden in packages that handle Proof values, so this repository-wide type walk is the fail-closed enforcement point.

func CollectTables

func CollectTables(dir string) (live, named []string, err error)

CollectTables replays the migration set's table statements in version order and returns two sets: the tables that exist at rest (`live`), and every name a CREATE ever mentioned (`named`).

They differ because of the sqlite rebuild — create a twin, copy, drop the original, rename the twin over it — which is the only way that engine reaches a column with no default, since it can neither add a NOT NULL column without one nor drop one afterwards (migration 00006 established the shape, 00009 reuses it). The two sets exist because the two checks that consume them want opposite things: "every table is classified" must ask about live tables only, or it would demand a directive for a name that is gone by commit; "no directive dangles" must ask about every name, or declaring the twin — which 00006 does on both engines — would look like a stale entry.

func GrantWriters

func GrantWriters(repoRoot string) (map[string]bool, error)

GrantWriters returns the mutating generated queries that target the grant table, derived from the query files rather than a curated list so a new grant writer is covered the moment it is added. Classification is by SQL verb/target, NOT the sqlc command annotation: an `INSERT ... RETURNING` is a `:one` yet writes a grant row (the old cmd-based skip classified it as a read and let it through). Only a SELECT on the grant table is a read.

func Load

func Load(patterns ...string) ([]*packages.Package, error)

Load loads arbitrary patterns under the default context (the negative-fixture tests use it on testdata packages).

The mode deliberately omits NeedDeps. The type checker still resolves every imported symbol — a root package's direct imports get their Types from compiler export data as a side effect of type-checking the root — so the analyzers, which reason about type identity (authz.Proof, driver handles), see everything they need. Adding NeedDeps alongside NeedSyntax|NeedTypesInfo would instead mark the entire transitive dependency closure (pgx, x/tools, stdlib) as "needs source", parsing every dependency's AST and building a full types.Info for each and keeping them all resident. On this package's test suite that was the difference between a ~7GB and a ~1.2GB peak RSS, and it made each tiny testdata load carry the full closure too; macOS Activity Monitor's "Memory" column inflated the former past 20GB once compression and -race shadow footprint were counted.

The one seam: flatten() walks into imported module packages that are not roots of the load and therefore have Types (from export data) but no TypesInfo. Analyzers that reach those either select their target packages by path first (never touching a non-root's TypesInfo) or guard on nil type information before dereferencing it. In LoadRepo every module package is a root, so no module package is skipped there regardless.

func LoadIn

func LoadIn(ctx BuildContext, patterns ...string) ([]*packages.Package, error)

LoadIn loads arbitrary patterns under one supported context.

func LoadRepo

func LoadRepo() ([]*packages.Package, error)

LoadRepo loads every package in the module under the default context, with syntax and type information, exactly once per test process.

func LoadRepoIn

func LoadRepoIn(ctx BuildContext) ([]*packages.Package, error)

LoadRepoIn is LoadRepo under one supported context, cached per context.

func MutatingQueries

func MutatingQueries(repoRoot string) (map[string]bool, []string, error)

MutatingQueries derives the set of generated queries that write, from the sqlc command annotation on each query rather than from its name.

The previous version guessed from a prefix list, and that was FAIL-OPEN in the worst way: `ConsumeCredentialAuthority`, `TouchSession` and `AdvancePrincipalGeneration` all mutate and none of them starts with a listed prefix, so three real writers slipped past the enforcement that exists to catch exactly them. A classifier that has to be remembered is a classifier that will be forgotten.

`:exec`, `:execrows`, `:execresult` and `:execlastid` are sqlc's write commands; `:one` and `:many` read. An unrecognised command is treated as MUTATING — the fail-closed direction — and reported, so a sqlc release that adds a command cannot silently widen the hole.

func ParseScopeDirectives

func ParseScopeDirectives(dir string) (map[string]TableRule, error)

ParseScopeDirectives reads the hikyo:table directives from every migration file in dir.

func UpgradeBuildAuthority

func UpgradeBuildAuthority(pkgs []*packages.Package) []string

UpgradeBuildAuthority confines the empty-database build primitive to the release generator. Resolve symbols through Go types so import aliases and captured function values cannot turn this into a runtime migration bypass.

Types

type BuildContext

type BuildContext struct {
	Name string
	// BuildFlags are passed to the build system (for example -tags=ui).
	BuildFlags []string
	// GOOS overrides the target operating system; empty keeps the host's.
	GOOS string
	// ProductionOnly leaves test packages out of the load. The windows
	// context needs it: internal/upgradecustody's test package only
	// typechecks on unix (local_test.go names a helper declared in a
	// unix-only test file), so windows-only test files are not analysed.
	ProductionOnly bool
}

BuildContext is one supported analysis context: a source set a release build selects. The analyzers and the boundary tests run under every context, so a file selected only by a build tag or by GOOS is inspected rather than left to whatever the host's ambient build context happens to pick.

func (BuildContext) Env

func (c BuildContext) Env() []string

Env is the explicit environment for a build-system query under the context. GOFLAGS is cleared so the ambient shell cannot change file selection, and GOOS is pinned when the context names one.

func (BuildContext) Overlay

func (c BuildContext) Overlay() (map[string][]byte, error)

Overlay returns the go/packages overlay the context needs: the webui dist placeholder for the ui context when no dist file exists, otherwise nil.

func (BuildContext) WriteOverlay

func (c BuildContext) WriteOverlay(dir string) (string, error)

WriteOverlay materializes Overlay as a `go list -overlay` file inside dir and returns its path, or "" when the context needs no overlay.

type Query

type Query struct {
	Name       string
	Cmd        string
	Annotation string // hikyo annotation, "" if none
	Reason     string // explicit authority justification for new annotations
	SQL        string
}

Query is one parsed sqlc query block.

func ParseQueries

func ParseQueries(dir string) ([]Query, error)

ParseQueries reads every sqlc query block in dir, with its hikyo annotation if the line directly above the name line carries one.

func (Query) Hash

func (q Query) Hash() string

Hash returns the content pin for annotated queries: sha256 over the whitespace-normalized statement.

type RawSQLProtocol

type RawSQLProtocol struct {
	Hash              string                       `json:"hash"`
	Reason            string                       `json:"reason"`
	BuildContexts     []string                     `json:"build_contexts,omitempty"`
	Callers           map[string]string            `json:"callers,omitempty"`
	Dependencies      map[string]string            `json:"dependencies,omitempty"`
	BuildDependencies map[string]map[string]string `json:"build_dependencies,omitempty"`
}

RawSQLProtocol grants one source-owned engine operation raw execution, not ambient authority to a package or file. Hash pins the formatted function body and resolved constant bindings; named helper dependency bodies bind SQL builders, escaping and admission paths without granting them raw execution.

type TableRule

type TableRule struct {
	Class string   // org | project | environment | folder | key | instance | authn | system
	Chain []string // chain columns required as top-level conjuncts ("-" = none)
}

This file is analyzer 2 (tenant-isolation ADR, invariant 8): sqlc queries are static SQL, so predicate confinement is checked at build time. The analyzer is conservative by design: for every statement touching a tenant-owned table it requires the full owning-scope chain predicate as top-level conjuncts and rejects shapes it cannot prove. Bounded qualified joins, binding-membership reads and atomic INSERT SELECT retain a separate proof for every source. Parenthesized non-chain conditions only narrow rows already confined by those chain conjuncts. UNION, CTE and arbitrary nested reads remain refused. The tenant-table registry is derived from the scope-class directives in migration metadata, never curated: a table without a directive fails the build.

Two annotations exempt a query from the chain-predicate requirement, both content-pinned (invariant 13) so drift is a reviewed diff:

-- hikyo:instance-scoped    cross-tenant by definition (operator surface)
-- hikyo:authn-resolution   the authorization package's bootstrap reads

Jump to

Keyboard shortcuts

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