knobe

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 15 Imported by: 1 module, 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

knobe-go

A KNOBE verifier for Go: it verifies KNOBE Protocol v1 .knobe.md files and is written as a sibling of the reference verifier lens.py in KnobeOne/knobe-protocol.

The current release is v0.1.3, with API documentation on pkg.go.dev. It follows lens.py as of knobe-protocol commit fd75d2d, which includes ERRATA E12, upstream's hostile-input hardening and the display patch series merged as upstream PR #19 (see Changes in v0.1.2).

A match proves integrity, not truth. A valid proves conformance, not truth. Inspect before trusting.

What it does and does not do

knobe-go reads a .knobe.md file and reports three independent results from spec §7. status (integrity) is verified, verified-body-modified, failed or unreadable. body_verified (the optional body hash) is yes, modified or omitted. conformance (schema compliance) is valid, warnings or invalid. To get these it applies the §5 canonical hash rule and the §6 body normalization, and it rejects as unreadable any payload with duplicate keys, keys that collide under NFC, a number that overflows to infinity, an unpaired surrogate, a non-object payload, or an unsupported spec_version. Following ERRATA E12, hash and date formats are ASCII-strict (exactly 64 lowercase hex characters, exactly YYYY-MM-DD, nothing after either), and only ASCII space, tab, CR and LF may be stripped from a payload block. Its reports and exit codes match lens.py field for field, and every payload-derived string is escaped before it is printed. It does not seal, create or transform KNOBE files. It does not check that content is accurate, that attribution is honest, or that a file is fit for any use: a verified result only proves the payload is byte-identical to what was sealed. It runs entirely locally and never makes a network request.

Install and use

Requires Go 1.22 or later.

go install github.com/KnobeDev/knobe-go/cmd/knobe-verify@latest

To install exactly this release rather than the newest one, use @v0.1.3 in place of @latest.

knobe-verify path/to/file.knobe.md
knobe-verify --json path/to/file.knobe.md

The human report and the --json document have the same layout and keys as python3 lens.py and python3 lens.py --json.

Exit code Meaning
0 verified or verified-body-modified, and conformance valid or warnings
1 Integrity holds but conformance is invalid, or status is failed
2 unreadable, or a usage or file error
As a library
go get github.com/KnobeDev/knobe-go@v0.1.3
import knobe "github.com/KnobeDev/knobe-go"

r := knobe.VerifyFile("file.knobe.md") // or knobe.VerifyBytes(data)
fmt.Println(r.Status, r.BodyVerified, r.Conformance, r.ConformanceIssues)

The full API is on pkg.go.dev.

Test vector results

These are the results against the 33 published vectors at knobe-protocol commit fd75d2d. Every one matches the expected result in that directory's README. The first nine are the conformance bar. ERRATA E12 changed no vector's result.

file status body_verified conformance exit
minimal-valid.knobe.md verified omitted valid 0
full-valid.knobe.md verified yes valid 0
body-modified.knobe.md verified-body-modified modified valid 0
payload-modified.knobe.md failed omitted valid 1
unreadable.knobe.md unreadable omitted (null) invalid 2
unicode-valid.knobe.md verified yes valid 0
numeric-violation.knobe.md verified yes invalid 1
omitted-body-hash.knobe.md verified omitted valid 0
multi-block.knobe.md verified omitted warnings 0
adversarial/bad-attribution-sources-type.knobe.md verified omitted invalid 1
adversarial/bad-body-hash-format.knobe.md verified-body-modified modified invalid 1
adversarial/bad-created-date.knobe.md verified omitted invalid 1
adversarial/bidi-title.knobe.md failed omitted invalid 1
adversarial/bigint-payload.knobe.md failed omitted invalid 1
adversarial/control-character-title.knobe.md verified omitted valid 0
adversarial/duplicate-key.knobe.md unreadable omitted (null) invalid 2
adversarial/float-overflow.knobe.md unreadable omitted (null) invalid 2
adversarial/lone-surrogate.knobe.md unreadable omitted (null) invalid 2
adversarial/multi-block-warning.knobe.md verified omitted warnings 0
adversarial/nested-payload-hash.knobe.md verified omitted valid 0
adversarial/nfc-key-collision.knobe.md unreadable omitted (null) invalid 2
adversarial/no-frontmatter-valid-payload.knobe.md verified omitted invalid 1
adversarial/null-payload-hash.knobe.md failed omitted invalid 1
adversarial/payload-array.knobe.md unreadable omitted (null) invalid 2
adversarial/spec-version-array.knobe.md unreadable omitted (null) invalid 2
adversarial/unsupported-spec-version.knobe.md unreadable omitted (null) invalid 2
interpretation/astral-unicode-literal.knobe.md verified omitted valid 0
interpretation/attribution-missing.knobe.md verified omitted invalid 1
interpretation/base64-unpadded.knobe.md unreadable omitted (null) invalid 2
interpretation/begin-marker-mid-line.knobe.md verified yes valid 0
interpretation/boolean-null-values.knobe.md verified omitted valid 0
interpretation/nel-block-whitespace.knobe.md unreadable omitted (null) invalid 2
interpretation/spec-version-frontmatter-mismatch.knobe.md verified omitted warnings 0

For an unreadable file, --json prints body_verified as null, as lens.py does. ERRATA E11 accepts either null or omitted.

The control-character title prints escaped, never raw:

title:             ALERT\x1b[31mINJECTED\x1b[0m\x0astatus:            verified (SPOOFED)

How it is tested

go test needs a checkout of knobe-protocol at ../knobe-protocol. Set KNOBE_PROTOCOL_DIR to use a different location. The differential tests also need python3, and they skip themselves when it is missing.

Test What it checks
vectors_test.go All 33 published vectors (core, adversarial, interpretation) against the expected results in their READMEs, plus exit codes and the ERRATA E5/E9 issue text
parity_test.go Runs lens.py side by side with this verifier over every published .knobe.md (91 files) and 214 crafted hostile files. It first compares state, conformance, body_verified, computed and stored hash, block count and exit code, the fields upstream's knobe-core.selftest.mjs compares. It then requires the complete --json document, every conformance issue and unreadable reason included, and the human report with its exit code, to be byte-identical on all 305 files. The hostile files are sealed by an independent Python oracle (testdata/pyhash.py), never by the code under test.
display_test.go The display rules: SafeString's exact escape set and truncation, duplicate keys holding surrogates, Python repr() (checked against str.isprintable() on every code point), the UTF-8 error text, file names and OSError text, and the human report fields
unit_test.go The JSON parser, Python-compatible float repr and string helpers, Base64 rules, canonical form, body normalization, block and frontmatter parsing, and the lone-surrogate and nesting walk
cmd/knobe-verify/paths_unix_test.go File names holding 0xFF, ESC, U+202E or a quote, for a missing file, a valid file, a directory, an unreadable file and a path through a file: knobe-verify must print what lens.py prints, --json and human, exit code included, and the reasons must read as specified
cmd/knobe-verify/main_test.go The command-line guard that reports an internal error as unreadable

CI runs against upstream main on Python 3.13, so an upstream change that breaks parity shows up immediately. The nesting limits below are CPython 3.13's. On another Python version, the seventeen cases that depend on its json.loads limits are skipped, with a note in the test log.

Upstream merged the display patch series as PR #19 (see Changes in v0.1.2). The tests check once whether the lens.py under test has it. If it does, every file and path must match byte for byte. If it does not, as in a checkout from before PR #19, a listed set of cases, each with its reason, must differ (an unpatched lens.py crashes on some of them), and every other case must match. The test log says which mode ran.

Hostile input

Since upstream PR #11, lens.py reports hostile input as unreadable instead of crashing, and knobe-go reports exactly what it reports, reason text included:

Input Reported as
A float that overflows to infinity, such as 1e400, anywhere in the payload, payload_hash included unreadable: non-JSON numeric constant
A non-string spec_version, such as a list unreadable: unsupported spec_version, shown as Python str() shows it
A value or key nested 499 or more levels below the payload unreadable: verifier error (RecursionError); rejected, with a block count of 0
An object, a float, or NaN/Infinity nested more than 9995 levels below the payload unreadable: payload could not be decoded or parsed
An object holding a duplicate key nested more than 9994 levels below the payload unreadable: payload could not be decoded or parsed, not the duplicate key
An array nested more than 9997 levels below the payload unreadable: payload could not be decoded or parsed

The last four limits come from CPython 3.13. lens.py's lone-surrogate check spends two stack frames per level against Python's 1000-frame limit, and json.loads stops at its C recursion limit, two levels earlier for a node that calls one of lens.py's Python hooks (objects, floats and the non-JSON constants), and three levels earlier for an object whose hook raises on a duplicate key. Integers, strings, true, false and null call no hook and may sit as deep as their array.

Hostile text is printed escaped, never raw, in reasons, conformance issues and the human report. C0 and C1 control characters and DEL show as \xNN. Bidi embeddings, overrides and isolates (U+202A to U+202E, U+2066 to U+2069), the line and paragraph separators (U+2028, U+2029) and unpaired surrogates show as \uNNNN. Everything else, including zero-width characters and U+FEFF, prints as it is. A duplicate key or spec_version in a reason is cut at 300 characters, and so are the human report's unreadable status line and its title (a string; any other title is shown whole), spec_version, quarantine_status, privacy_level and stored_hash lines. File names and conformance issues are never cut. A file name shows as Python holds it, so a byte that is not UTF-8 shows as \udcXX. A file that cannot be read is reported with Python's error text, such as could not read file: [Errno 13] Permission denied: '/tmp/x\udcff.knobe.md'.

knobe-go never crashes on any input. As a last line of defense, as in lens.py, knobe-verify would report an internal error as unreadable (verifier error (panic); rejected) rather than print a stack trace.

Behavior beyond lens.py

knobe-verify reads at most 64 MiB (knobe.MaxFileSize) and reports a larger file as unreadable. An ordinary file takes about 25 bytes of memory per input byte to verify. A crafted file of many deeply nested arrays takes far more: about 9 GB at the 64 MiB limit, in v0.1.0 as in v0.1.1. lens.py takes about 5 GB on the same file and has no size limit. Library callers of VerifyBytes should bound their input to what their host can spare.

Against a lens.py from before the display patch series (upstream PR #19), knobe-go's output differs where hostile text is shown: a duplicate key, spec_version, title or privacy_level holding a bidi control or U+2028/U+2029, a stored_hash or conformance issue holding a control character, a long stored_hash, and the name of a missing file or a directory. Where that lens.py crashes printing a report (a duplicate key holding an unpaired surrogate, or a file name that is not UTF-8), knobe-go prints the report. Otherwise verdicts and exit codes are the same.

Changes in v0.1.3

v0.1.3 changes no code: the library and knobe-verify behave exactly as in v0.1.2. It brings the tests and documentation up to date with upstream.

  • Tests. vectors_test.go finds the vector tables' columns by their headers, so it reads the body_verified column upstream added to the core table (upstream PR #30), and it checks body_verified for every vector that lists it. All 33 published vectors at knobe-protocol fd75d2d pass, and the lens.py comparison matches on all 305 files.
  • Wording. The README and NOTICE no longer call knobe-go "independent", and the Provenance section carries the steward's provenance line.

Changes in v0.1.2

v0.1.2 follows a common display contract for KNOBE verifiers. It is the one in the patch series proposed to KnobeOne/knobe-protocol ("Never crash printing a report; escape the same characters in lens.py and knobe-core.js"), which upstream has since merged as PR #19. knobe-rs follows it too. No verdict or exit code changes.

  • Escaping. Hostile text is escaped by an exact set of characters (see Hostile input). v0.1.1 escaped every Unicode format character, zero-width characters and U+FEFF included, and showed an unpaired surrogate in a duplicate key as U+FFFD.
  • Human report. stored_hash, and a non-string spec_version, quarantine_status or privacy_level, are shown as Python str() shows the value, escaped and cut at 300 characters. v0.1.1 printed them whole.
  • File names. A missing file, a directory or an oversized file is named as Python holds the name, escaped, with \udcXX for a byte that is not UTF-8. v0.1.1 printed the raw bytes, and its --json output could be invalid UTF-8. Other read errors are reported with Python's OSError text.
  • Invalid UTF-8. A file that is not valid UTF-8 is reported with Python's codec detail, as lens.py reports it, such as file is not valid UTF-8: 'utf-8' codec can't decode byte 0xc3 in position 39: invalid continuation byte.
  • Nesting. An object, a float, or NaN/Infinity nested more than 9995 levels deep makes the payload unparseable, as in CPython 3.13, and so does an object holding a duplicate key more than 9994 levels deep. v0.1.1 applied the array limit (9997) to objects too, so it reported, for example, a duplicate key that lens.py cannot parse.
  • Tests. The human report is now compared with lens.py on every hostile file too, and file names are compared in a new test. 58 new hostile cases (214 total), five of them at the duplicate-key limit. The full --json and human comparisons have no exceptions left against the patched lens.py on Python 3.13.

Changes in v0.1.1

v0.1.0 predates two upstream changes merged on 2026-11-04, and its tests fail against upstream main. v0.1.1 matches them.

  • ERRATA E12, hash format. A payload_hash, body_hash or parents[i].payload_hash followed by a newline is now invalid. v0.1.0 accepted the newline, as Python's $ did.
  • ERRATA E12, block whitespace. Only ASCII space, tab, CR and LF are stripped from a payload block. Any other whitespace, such as NEL (U+0085), NBSP, VT, FF or U+001C to U+001F, makes the file unreadable. v0.1.0 stripped everything Python's str.split() does.
  • ERRATA E12, date format. created_date must be ASCII digits with nothing after. Such dates were already invalid; the issue now reads "not in YYYY-MM-DD form", as lens.py's does.
  • Overflowing numbers. A float such as 1e400 makes the file unreadable wherever it appears. In payload_hash, v0.1.0 reported failed and printed a bare Infinity in --json, which is not valid JSON.
  • Check order and nesting. The lone-surrogate check now runs before the NFC and spec_version checks. A duplicate key is reported only if the rest of its object parses, as Python does. Nesting limits follow lens.py (see Hostile input).
  • Command-line guard. knobe-verify reports an internal error as unreadable instead of crashing, as lens.py now does.
  • Tests. The complete --json output is now compared with lens.py on every published and hostile file, and the human report on every published file.

Provenance

knobe-go is maintained by Joshua Hori (KnobeDev). It does not count toward the two-independent-implementations trigger in the protocol's GOVERNANCE.md. It is not an official or reference KNOBE implementation, and the KNOBE steward did not build, review or endorse it.

It was written with AI assistance (Claude) at the maintainer's direction. As the steward's governance notes ask, the reliance on the reference engines is disclosed here: lens.py was consulted throughout, along with the maintainer's Rust port, knobe-rs (on crates.io as knobe), which follows the same reference. Every ambiguous case was settled by observing lens.py and is pinned by the parity tests above.

License

Apache-2.0, matching the upstream verifier code. knobe-go shares no code with upstream but follows the behavior of lens.py. See NOTICE.

Documentation

Index

Constants

View Source
const (
	BeginMarker = "-----BEGIN KNOBE B64-----"
	EndMarker   = "-----END KNOBE B64-----"
)
View Source
const MaxFileSize = 64 << 20

MaxFileSize bounds what VerifyFile reads. Verifying an ordinary file costs about 25 bytes of memory per input byte, and a crafted file of many deeply nested arrays far more (about 9 GB at this limit), so an unbounded hostile file could exhaust a constrained host. Larger files are reported unreadable.

Variables

This section is empty.

Functions

func BodyHash

func BodyHash(text string) string

BodyHash is the §6 body hash.

func NormalizeBody

func NormalizeBody(text string) string

NormalizeBody applies the §6 body normalization.

func PayloadHash

func PayloadHash(payload Value) (string, error)

PayloadHash is the §5 payload hash of a payload object; its own payload_hash member is ignored.

func SafeString

func SafeString(s string, limit int) string

SafeString is lens.py safe() for a string, so a crafted string cannot spoof the report, inject terminal escape sequences or visually reorder text. It escapes C0 and C1 controls and DEL as \xNN; bidi embeddings, overrides and isolates (U+202A-202E, U+2066-2069), the line and paragraph separators (U+2028, U+2029) and unpaired surrogates as \uNNNN; and keeps everything else, backslashes included. The result is then cut to limit code points plus "…" (limit <= 0: no limit). An unpaired surrogate is read from its WTF-8 form, as the JSON parser keeps it.

Types

type BodyVerified

type BodyVerified string

BodyVerified is the optional body-hash result (spec §6, §7).

const (
	BodyYes      BodyVerified = "yes"
	BodyModified BodyVerified = "modified"
	BodyOmitted  BodyVerified = "omitted"
)

type Conformance

type Conformance string

Conformance is the schema/spec compliance result (spec §7).

const (
	Valid    Conformance = "valid"
	Warnings Conformance = "warnings"
	Invalid  Conformance = "invalid"
)

type Kind

type Kind int

Kind is the JSON type of a Value.

const (
	Null Kind = iota
	Bool
	Int   // integer lexeme kept exactly as written (arbitrary precision, like Python int)
	Float // float64, parsed with correct rounding like Python float()
	String
	Array
	Object
)

type Member

type Member struct {
	Key string
	Val Value
}

Member is one key/value pair of an Object.

type ParseError

type ParseError struct {
	DuplicateKey string
	IsDuplicate  bool
	NonJSONConst bool
	Msg          string
	Offset       int
}

ParseError kinds, so the verifier can word its unreadable reason as lens.py does.

func (*ParseError) Error

func (e *ParseError) Error() string

type ParseResult

type ParseResult struct {
	Value         Value
	LoneSurrogate bool
}

ParseResult carries the parsed value plus a flag for unpaired UTF-16 surrogate escapes anywhere in it. Python accepts those while parsing but cannot UTF-8-encode them. The flag is for callers: the verifier does not consult it, but finds them with its own walk, which (like lens.py's) stops at the first surrogate or at a nesting depth lens.py cannot reach.

func ParseJSON

func ParseJSON(text string) (ParseResult, error)

ParseJSON parses one strict RFC 8259 document. Duplicate keys at any depth, NaN/Infinity and numbers that overflow to infinity are errors. Only JSON whitespace may surround the value. Errors are reported in the order Python's json.loads with lens.py's hooks raises them.

type Report

type Report struct {
	Status Status
	// Computed is the recomputed payload hash; empty when unreadable.
	Computed string
	// Stored is the payload_hash member as found (any JSON type; the empty
	// string if absent). Nil when unreadable.
	Stored *Value
	// Payload is the decoded payload, when one was decoded.
	Payload *Value
	// BodyVerified is empty when unreadable (machine output then says null).
	BodyVerified      BodyVerified
	Conformance       Conformance
	ConformanceIssues []string
	// BlockCount is the number of payload blocks found; the last is evaluated.
	BlockCount int
	// Reason says why the file is unreadable; empty otherwise.
	Reason string
}

Report is a verification result with lens.py's fields and semantics.

func VerifyBytes

func VerifyBytes(data []byte) Report

VerifyBytes verifies the contents of a .knobe.md file. Callers passing untrusted input should bound its size, as VerifyFile does.

func VerifyFile

func VerifyFile(path string) Report

VerifyFile reads and verifies a .knobe.md file of at most MaxFileSize bytes. It never panics on file contents; read errors are reported as unreadable, worded as lens.py words them. The path in a reason is shown as Python shows a command-line path: escaped with SafeString, with each byte that is not valid UTF-8 as \udcXX.

func (Report) BlockUsed

func (r Report) BlockUsed() int

BlockUsed is the 1-based index of the evaluated block: always the last (spec §3.3).

func (Report) ExitCode

func (r Report) ExitCode() int

ExitCode is lens.py's: 0 when integrity holds and conformance is valid or warnings; 1 when the payload failed or conformance is invalid; 2 when the file is unreadable.

func (Report) JSON

func (r Report) JSON() string

JSON renders the report exactly as `python3 lens.py --json` does: the same keys in the same order, two-space indent, literal UTF-8.

func (Report) MultipleBlocks

func (r Report) MultipleBlocks() bool

MultipleBlocks reports whether more than one payload block was present.

func (Report) WriteHuman

func (r Report) WriteHuman(w io.Writer)

WriteHuman writes the human-readable report in lens.py's layout. Every payload-derived string is escaped first, so control characters and terminal escape sequences in a hostile file are shown, never executed.

type Status

type Status string

Status is the integrity result (spec §7).

const (
	Verified             Status = "verified"
	VerifiedBodyModified Status = "verified-body-modified"
	Failed               Status = "failed"
	Unreadable           Status = "unreadable"
)

type Value

type Value struct {
	Kind Kind
	B    bool
	Num  string // Int lexeme
	F    float64
	S    string
	Arr  []Value
	Obj  []Member
}

Value is a parsed JSON value. Objects keep insertion order; the parser guarantees their keys are unique.

func (Value) Get

func (v Value) Get(key string) (Value, bool)

Get returns the value of key in an Object.

func (Value) Has

func (v Value) Has(key string) bool

Has reports whether an Object contains key.

func (Value) Str

func (v Value) Str() (string, bool)

Str returns the string value and whether v is a String.

Directories

Path Synopsis
cmd
knobe-verify command
Command knobe-verify checks a KNOBE Protocol v1 file and reports its integrity (status), body hash result (body_verified) and spec conformance, with the same report and exit codes as the reference verifier lens.py.
Command knobe-verify checks a KNOBE Protocol v1 file and reports its integrity (status), body hash result (body_verified) and spec conformance, with the same report and exit codes as the reference verifier lens.py.
internal
lenstest
Package lenstest holds what the differential tests share: where the KNOBE Protocol checkout is, how to run its lens.py, and whether that lens.py already carries the display patch that is pending upstream.
Package lenstest holds what the differential tests share: where the KNOBE Protocol checkout is, how to run its lens.py, and whether that lens.py already carries the display patch that is pending upstream.

Jump to

Keyboard shortcuts

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