Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

attest.gno

package bouncer

import (
	"chain"
	"chain/runtime"
	"strconv"
	"strings"
	"time"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/seqid/v0"
)

// Finding is one attested finding. The detail fields (Snippet onward) are
// filled once, after Attest, by AddDetail.
type Finding struct {
	Rule     string // B01 ...
	Severity string // critical, high, medium
	Label    string // PROVEN, NOT REPRODUCED, STATIC WARNING
	File     string
	Line     int
	Func     string // enclosing function, if known

	Detailed bool   // AddDetail has run for this finding
	Snippet  string // the vulnerable code
	Attack   string // what the exploit did, one line (PROVEN only)
	Exploit  string // the attacker source that ran (PROVEN only)
	Before   string // evidence before the attack (PROVEN only)
	After    string // evidence after the attack (PROVEN only)
}

// Attestation is a scan result posted by an attester.
type Attestation struct {
	ID             uint64
	PkgPath        string
	SourceHash     string // sha256 of the scanned source, hex
	ScannerVersion string
	RulesetHash    string // hex
	Toolchain      string // gno version the exploits ran on
	ReportHash     string // sha256 of the full JSON report, hex
	ReportURI      string // where the full report lives (ipfs:// or https://)
	Findings       []Finding
	Deps           Deps
	Score          int
	Grade          string
	Verdict        string
	Attester       address
	Height         int64
	Time           int64 // unix seconds, block time
}

// AuthorReply is an author's response to a Passport.
type AuthorReply struct {
	Author    address
	Note      string
	Successor string // pkgpath of the fixed version, if any
	Height    int64
}

// record holds everything known about one package.
type record struct {
	history []Attestation // oldest first
	replies []AuthorReply
}

const (
	maxFindings = 64
	maxHistory  = 50
	maxReplies  = 20
	maxNoteLen  = 280
	maxRecent   = 10
)

// Attest records a scan result for pkgpath. Attesters only. findings is a
// ";"-separated list of "RULE,severity,LABEL,file,line[,func]" entries (""
// for none), in the report's order. Score, grade and verdict are computed here from the findings and
// dependency counts.
func Attest(cur realm, pkgpath, sourceHash, scannerVersion, rulesetHash, toolchain, reportHash, reportURI, findings string, directAtRisk, indirectAtRisk, unverified int) uint64 {
	attester := assertAttester(cur)
	if !validPkgPath(pkgpath) {
		panic("invalid package path")
	}
	for _, h := range []string{sourceHash, rulesetHash, reportHash} {
		if !isHex64(h) {
			panic("hashes must be 64 lowercase hex characters")
		}
	}
	if !isToken(scannerVersion) || !isToken(toolchain) {
		panic("invalid scanner or toolchain version")
	}
	if !validReportURI(reportURI) {
		panic("report URI must be ipfs://<cid> or an https:// URL")
	}
	if directAtRisk < 0 || indirectAtRisk < 0 || unverified < 0 || directAtRisk+indirectAtRisk+unverified > 1000 {
		panic("invalid dependency counts")
	}
	fs := parseFindings(findings)
	deps := Deps{DirectAtRisk: directAtRisk, IndirectAtRisk: indirectAtRisk, Unverified: unverified}
	score, grade, verdict := ScoreFor(fs, deps)

	rec := getRecord(pkgpath)
	if rec == nil {
		rec = &record{}
		records.Set(pkgpath, rec)
		if author, ok := authorOf(pkgpath); ok {
			addToAuthor(author, pkgpath)
		}
		addToFamily(pkgpath)
	} else {
		if len(rec.history) >= maxHistory {
			panic("attestation history is full for this package")
		}
		prev := rec.history[len(rec.history)-1]
		totalFindings -= len(prev.Findings)
		totalProven -= countProven(prev.Findings)
	}
	id := uint64(attestationID.Next())
	rec.history = append(rec.history, Attestation{
		ID:             id,
		PkgPath:        pkgpath,
		SourceHash:     sourceHash,
		ScannerVersion: scannerVersion,
		RulesetHash:    rulesetHash,
		Toolchain:      toolchain,
		ReportHash:     reportHash,
		ReportURI:      reportURI,
		Findings:       fs,
		Deps:           deps,
		Score:          score,
		Grade:          grade,
		Verdict:        verdict,
		Attester:       attester,
		Height:         runtime.ChainHeight(),
		Time:           time.Now().Unix(),
	})
	totalFindings += len(fs)
	totalProven += countProven(fs)
	markRecent(pkgpath)
	closeRequestsFor(pkgpath)
	chain.Emit("Attested",
		"id", seqid.ID(id).String(),
		"pkgpath", pkgpath,
		"score", strconv.Itoa(score),
		"grade", grade,
		"verdict", verdict,
		"report_hash", reportHash,
		"attester", attester.String())
	return id
}

func getRecord(pkgpath string) *record {
	v := records.Get(pkgpath)
	if v == nil {
		return nil
	}
	return v.(*record)
}

func addToAuthor(author address, pkgpath string) {
	var t *avl.Tree
	if v := byAuthor.Get(string(author)); v != nil {
		t = v.(*avl.Tree)
	} else {
		t = avl.NewTree()
		byAuthor.Set(string(author), t)
	}
	t.Set(pkgpath, true)
}

func markRecent(pkgpath string) {
	next := []string{pkgpath}
	for _, p := range recent {
		if p != pkgpath && len(next) < maxRecent {
			next = append(next, p)
		}
	}
	recent = next
}

func countProven(fs []Finding) int {
	n := 0
	for _, f := range fs {
		if f.Label == LabelProven {
			n++
		}
	}
	return n
}

// parseFindings validates and decodes the findings argument.
func parseFindings(s string) []Finding {
	out := []Finding{}
	if s == "" {
		return out
	}
	entries := strings.Split(s, ";")
	if len(entries) > maxFindings {
		panic("too many findings")
	}
	for _, e := range entries {
		parts := strings.Split(e, ",")
		if len(parts) != 5 && len(parts) != 6 {
			panic("finding must be RULE,severity,LABEL,file,line[,func]: " + e)
		}
		f := Finding{Rule: parts[0], Severity: parts[1], Label: parts[2], File: parts[3]}
		if !isRuleID(f.Rule) {
			panic("invalid rule id: " + f.Rule)
		}
		switch f.Severity {
		case SeverityCritical, SeverityHigh, SeverityMedium:
		default:
			panic("invalid severity: " + f.Severity)
		}
		switch f.Label {
		case LabelProven, LabelNotReproduced, LabelStaticWarning:
		default:
			panic("invalid label: " + f.Label)
		}
		if !isGnoFile(f.File) {
			panic("invalid file name: " + f.File)
		}
		line, err := strconv.Atoi(parts[4])
		if err != nil || line < 1 || line > 1000000 {
			panic("invalid line: " + parts[4])
		}
		f.Line = line
		if len(parts) == 6 {
			if !isIdent(parts[5]) {
				panic("invalid function name: " + parts[5])
			}
			f.Func = parts[5]
		}
		out = append(out, f)
	}
	return out
}

// isIdent accepts a Go identifier, optionally a method as Type.Method.
func isIdent(s string) bool {
	if s == "" || len(s) > 64 {
		return false
	}
	for _, part := range strings.Split(s, ".") {
		if part == "" || part[0] >= '0' && part[0] <= '9' {
			return false
		}
		for _, c := range part {
			if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_') {
				return false
			}
		}
	}
	return true
}

func isRuleID(s string) bool {
	return len(s) == 3 && s[0] == 'B' && s[1] >= '0' && s[1] <= '9' && s[2] >= '0' && s[2] <= '9'
}

func isGnoFile(s string) bool {
	if len(s) > 64 || !strings.HasSuffix(s, ".gno") || len(s) == len(".gno") {
		return false
	}
	for _, c := range s {
		if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '.' || c == '-') {
			return false
		}
	}
	return true
}

func isHex64(s string) bool {
	if len(s) != 64 {
		return false
	}
	for _, c := range s {
		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
			return false
		}
	}
	return true
}

// isToken accepts short version strings such as "0.1.0" or "master.1+f0f9c70".
func isToken(s string) bool {
	if s == "" || len(s) > 64 {
		return false
	}
	for _, c := range s {
		if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune(".+-_", c)) {
			return false
		}
	}
	return true
}

func validReportURI(s string) bool {
	if len(s) > 200 {
		return false
	}
	rest, ok := strings.CutPrefix(s, "ipfs://")
	if !ok {
		rest, ok = strings.CutPrefix(s, "https://")
	}
	if !ok || rest == "" {
		return false
	}
	for _, c := range rest {
		if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("./-_~", c)) {
			return false
		}
	}
	return true
}

badge.gno

package bouncer

import (
	"strconv"

	"gno.land/p/g19wmd95cwm3s0w0c5592tgu3zh4zgrtlggvugnj/bouncer/badge/v0"
)

// Badge returns a Markdown image of pkgpath's live Bouncer badge (grade,
// score and attestation date), linked to its Passport. A realm shows it by
// adding one line to its Render:
//
//	out += bouncer.Badge("gno.land/r/<address>/myrealm")
//
// The color follows the verdict, not the grade: a package with a PROVEN
// High finding is red even at grade B.
func Badge(pkgpath string) string {
	if !validPkgPath(pkgpath) {
		return ""
	}
	link := webPath() + ":realm/" + pkgpath
	a, ok := Latest(pkgpath)
	if !ok {
		return badge.Markdown("Bouncer: not scanned", badge.SVG("bouncer", "not scanned", badge.Grey), link)
	}
	msg := a.Grade + " " + strconv.Itoa(a.Score) + " · " + date(a.Time)
	return badge.Markdown("Bouncer: grade "+a.Grade+", score "+strconv.Itoa(a.Score)+", "+verdictWords(a.Verdict),
		badge.SVG("bouncer", msg, verdictColor(a.Verdict)), link)
}

func verdictColor(v string) string {
	switch v {
	case VerdictNotRecommended:
		return badge.Red
	case VerdictReview:
		return badge.Orange
	}
	return badge.Green
}

func verdictWords(v string) string {
	switch v {
	case VerdictNotRecommended:
		return "not recommended for integration"
	case VerdictReview:
		return "review before integration"
	}
	return "no known Critical or High issues"
}

bouncer.gno

// Package bouncer is Bouncer's on-chain registry: scan requests,
// attestations, disputes and author replies, plus the reads other realms use
// (Check, Score) and the Tavern pages in Render.
//
// One realm holds all state and every write, and every logic-data type is
// declared here (security guide §3A). Writes are crossing functions that
// check cur.IsCurrent() and take the caller from cur.Previous(). Reads are
// plain functions that return values or copies, never pointers into state,
// and never take callbacks.
package bouncer

import (
	"chain"
	"strings"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/seqid/v0"
)

var (
	admin     address
	attesters = avl.NewTree() // address -> true
	// selfPath is this realm's package path, for links in Render.
	selfPath string

	// Scan requests.
	requests        = avl.NewTree() // request id -> *request
	openByRequester = avl.NewTree() // address -> request id (one open each)
	openRequests    = avl.NewTree() // request id -> true, open ones only
	requestID       seqid.ID

	// Attestations.
	records       = avl.NewTree() // pkgpath -> *record
	byAuthor      = avl.NewTree() // author address -> *avl.Tree (pkgpath -> true)
	attestationID seqid.ID
	recent        []string // pkgpaths, most recently attested first

	// Disputes.
	disputes  = avl.NewTree() // dispute id -> *dispute
	disputeID seqid.ID

	// Totals over the latest attestation of each package.
	totalFindings int
	totalProven   int
)

func init(cur realm) {
	selfPath = cur.PkgPath()
	prev := cur.Previous()
	if !prev.IsUserCall() {
		panic("bouncer must be deployed by a user")
	}
	// The deployer becomes admin and the first attester. Under gno test
	// the deploying user has no address; then no admin is set, which
	// locks every admin action rather than opening it.
	if deployer := prev.Address(); deployer.IsValid() {
		admin = deployer
		attesters.Set(string(admin), true)
	}
}

// ---- admin and attesters ----

func assertAdmin(cur realm) {
	if !cur.IsCurrent() {
		panic("invalid realm")
	}
	if cur.Previous().Address() != admin {
		panic("admin only")
	}
}

func assertAttester(cur realm) address {
	if !cur.IsCurrent() {
		panic("invalid realm")
	}
	caller := cur.Previous().Address()
	if !attesters.Has(string(caller)) {
		panic("attester only")
	}
	return caller
}

// AddAttester allows addr to post attestations.
func AddAttester(cur realm, addr address) {
	assertAdmin(cur)
	if !addr.IsValid() {
		panic("invalid address")
	}
	attesters.Set(string(addr), true)
	chain.Emit("AttesterAdded", "address", addr.String())
}

// RemoveAttester revokes addr. Its past attestations stay on record.
func RemoveAttester(cur realm, addr address) {
	assertAdmin(cur)
	if _, removed := attesters.Remove(string(addr)); !removed {
		panic("not an attester")
	}
	chain.Emit("AttesterRemoved", "address", addr.String())
}

// TransferAdmin hands the admin role to next.
func TransferAdmin(cur realm, next address) {
	assertAdmin(cur)
	if !next.IsValid() {
		panic("invalid address")
	}
	prev := admin
	admin = next
	chain.Emit("AdminTransferred", "from", prev.String(), "to", next.String())
}

// Admin returns the admin address.
func Admin() address { return admin }

// IsAttester reports whether addr may post attestations.
func IsAttester(addr address) bool { return attesters.Has(string(addr)) }

// Attesters returns the attester allowlist, sorted.
func Attesters() []address {
	out := make([]address, 0, attesters.Size())
	attesters.Iterate("", "", func(k string, _ any) bool {
		out = append(out, address(k))
		return false
	})
	return out
}

// ---- package paths ----

const maxPkgPathLen = 200

// validPkgPath accepts gno.land/r/... and gno.land/p/... paths of at least
// a namespace and a name, made of lowercase letters, digits and underscores.
func validPkgPath(p string) bool {
	if len(p) > maxPkgPathLen {
		return false
	}
	rest, ok := strings.CutPrefix(p, "gno.land/")
	if !ok {
		return false
	}
	segs := strings.Split(rest, "/")
	if len(segs) < 3 || (segs[0] != "r" && segs[0] != "p") {
		return false
	}
	for _, s := range segs[1:] {
		if s == "" {
			return false
		}
		for _, c := range s {
			if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_') {
				return false
			}
		}
	}
	return true
}

// authorOf returns the address that owns an address-namespace path
// (gno.land/r/<address>/... or gno.land/p/<address>/...). Only that address
// can deploy there, so authorship is verified by the path alone. Other
// namespaces have no verified author.
func authorOf(pkgpath string) (address, bool) {
	segs := strings.Split(pkgpath, "/")
	if len(segs) < 4 {
		return "", false
	}
	a := address(segs[2])
	if !a.IsValid() {
		return "", false
	}
	return a, true
}

bouncer_test.gno

package bouncer

import (
	"strings"
	"testing"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
)

var (
	adminAddr = testutils.TestAddress("admin")
	botAddr   = testutils.TestAddress("bot")
	alice     = testutils.TestAddress("alice")
	bob       = testutils.TestAddress("bob")
)

// reset gives each test fresh state with a known admin.
func reset() {
	admin = adminAddr
	attesters = avl.NewTree()
	attesters.Set(string(adminAddr), true)
	requests = avl.NewTree()
	openByRequester = avl.NewTree()
	openRequests = avl.NewTree()
	requestID = 0
	records = avl.NewTree()
	byAuthor = avl.NewTree()
	families = avl.NewTree()
	disputes = avl.NewTree()
	recent = nil
	totalFindings, totalProven = 0, 0
}

// testing.SetRealm applies to the frame that calls it, so it is called
// inline right before each crossing call, never from a helper.

func hash(c string) string { return strings.Repeat(c, 64) }

// attest posts an attestation as the bot (which must be an attester).
func attest(cur realm, pkgpath, report, findings string, unverified int) {
	testing.SetRealm(testing.NewUserRealm(botAddr))
	Attest(cross(cur), pkgpath, hash("a"), "0.1.0", hash("b"), "master.1+f0f9c70", report, "ipfs://bafyexample", findings, 0, 0, unverified)
}

func addBot(cur realm) {
	testing.SetRealm(testing.NewUserRealm(adminAddr))
	AddAttester(cross(cur), botAddr)
}

func TestScoreFormula(t *testing.T) {
	f := func(rule, sev, label string) Finding {
		return Finding{Rule: rule, Severity: sev, Label: label, File: "a.gno", Line: 1}
	}
	cases := []struct {
		name    string
		fs      []Finding
		deps    Deps
		score   int
		grade   string
		verdict string
	}{
		{"clean", nil, Deps{}, 100, "A", VerdictClear},
		{"proven critical", []Finding{f("B05", SeverityCritical, LabelProven)}, Deps{}, 60, "C", VerdictNotRecommended},
		{"proven high", []Finding{f("B01", SeverityHigh, LabelProven)}, Deps{}, 75, "B", VerdictNotRecommended},
		{"high warning", []Finding{f("B01", SeverityHigh, LabelNotReproduced)}, Deps{}, 90, "A", VerdictReview},
		{"critical static warning", []Finding{f("B03", SeverityCritical, LabelStaticWarning)}, Deps{}, 85, "B", VerdictReview},
		{"medium only", []Finding{f("B04", SeverityMedium, LabelStaticWarning)}, Deps{}, 95, "A", VerdictClear},
		{"mixed with deps", []Finding{
			f("B05", SeverityCritical, LabelProven),      // 40
			f("B01", SeverityHigh, LabelNotReproduced),   // 10
			f("B04", SeverityMedium, LabelStaticWarning), // 5
		}, Deps{DirectAtRisk: 1, IndirectAtRisk: 1, Unverified: 1}, 28, "F", VerdictNotRecommended}, // 100-55-10-5-2
		{"unverified capped at 10", nil, Deps{Unverified: 7}, 90, "A", VerdictClear},
		{"floor at zero", []Finding{
			f("B05", SeverityCritical, LabelProven),
			f("B05", SeverityCritical, LabelProven),
			f("B05", SeverityCritical, LabelProven),
		}, Deps{}, 0, "F", VerdictNotRecommended},
		{"grade D", []Finding{f("B01", SeverityHigh, LabelProven), f("B01", SeverityHigh, LabelProven), f("B04", SeverityMedium, LabelStaticWarning)}, Deps{}, 45, "D", VerdictNotRecommended},
	}
	for _, c := range cases {
		score, grade, verdict := ScoreFor(c.fs, c.deps)
		if score != c.score || grade != c.grade || verdict != c.verdict {
			t.Errorf("%s: got %d %s %s, want %d %s %s", c.name, score, grade, verdict, c.score, c.grade, c.verdict)
		}
	}
}

func TestRequestScan(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id1 := RequestScan(cross(cur), "gno.land/r/demo/vault")
	uassert.AbortsWithMessage(t, cur, "you already have an open scan request", func() {
		RequestScan(cross(cur), "gno.land/r/demo/other")
	})
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "invalid package path", func() {
		RequestScan(cross(cur), "gno.land/r/Demo/../x")
	})
	id2 := RequestScan(cross(cur), "gno.land/r/demo/token")

	open := OpenRequests(10)
	urequire.Equal(t, 2, len(open))
	uassert.Equal(t, id1, open[0].ID)
	uassert.Equal(t, id2, open[1].ID)
	uassert.Equal(t, alice, open[0].Requester)
	uassert.Equal(t, 1, len(OpenRequests(1)))

	testing.SetRealm(testing.NewUserRealm(alice))
	CancelRequest(cross(cur))
	r, ok := GetRequest(id1)
	uassert.True(t, ok)
	uassert.Equal(t, "cancelled", r.Status)
	RequestScan(cross(cur), "gno.land/r/demo/other") // allowed again
	uassert.Equal(t, 2, len(OpenRequests(10)))
}

func TestAttest(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	reqID := RequestScan(cross(cur), "gno.land/r/demo/vault")

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "attester only", func() {
		Attest(cross(cur), "gno.land/r/demo/vault", hash("a"), "0.1.0", hash("b"), "x", hash("c"), "ipfs://cid", "", 0, 0, 0)
	})
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "admin only", func() { AddAttester(cross(cur), bob) })
	addBot(cur)

	attest(cur, "gno.land/r/demo/vault", hash("c"), "B01,high,PROVEN,vault.gno,64;B05,critical,PROVEN,vault.gno,35", 0)
	a, ok := Latest("gno.land/r/demo/vault")
	urequire.True(t, ok)
	uassert.Equal(t, 35, a.Score) // 100 - 25 - 40
	uassert.Equal(t, "F", a.Grade)
	uassert.Equal(t, VerdictNotRecommended, a.Verdict)
	uassert.Equal(t, botAddr, a.Attester)
	urequire.Equal(t, 2, len(a.Findings))
	uassert.Equal(t, 64, a.Findings[0].Line)

	r, _ := GetRequest(reqID)
	uassert.Equal(t, "attested", r.Status)
	uassert.Equal(t, 0, len(OpenRequests(10)))
	uassert.Equal(t, 2, totalFindings)
	uassert.Equal(t, 2, totalProven)

	// A re-scan replaces the totals for that package.
	attest(cur, "gno.land/r/demo/vault", hash("d"), "", 0)
	uassert.Equal(t, 0, totalFindings)
	uassert.Equal(t, 2, len(History("gno.land/r/demo/vault")))
	s, _ := Score("gno.land/r/demo/vault")
	uassert.Equal(t, 100, s)
}

func TestAttestRejectsBadInput(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	bad := []struct {
		msg                                    string
		pkg, src, report, uri, findings, scanv string
	}{
		{"invalid package path", "vault", hash("a"), hash("c"), "ipfs://x", "", "0.1.0"},
		{"hashes must be 64 lowercase hex characters", "gno.land/r/demo/v", "abc", hash("c"), "ipfs://x", "", "0.1.0"},
		{"hashes must be 64 lowercase hex characters", "gno.land/r/demo/v", hash("A"), hash("c"), "ipfs://x", "", "0.1.0"},
		{"report URI must be ipfs://<cid> or an https:// URL", "gno.land/r/demo/v", hash("a"), hash("c"), "javascript:alert(1)", "", "0.1.0"},
		{"report URI must be ipfs://<cid> or an https:// URL", "gno.land/r/demo/v", hash("a"), hash("c"), "https://x.io/a)b", "", "0.1.0"},
		{"invalid label: SAFE", "gno.land/r/demo/v", hash("a"), hash("c"), "ipfs://x", "B01,high,SAFE,a.gno,1", "0.1.0"},
		{"invalid file name: ../a.gno", "gno.land/r/demo/v", hash("a"), hash("c"), "ipfs://x", "B01,high,PROVEN,../a.gno,1", "0.1.0"},
		{"invalid rule id: X1", "gno.land/r/demo/v", hash("a"), hash("c"), "ipfs://x", "X1,high,PROVEN,a.gno,1", "0.1.0"},
		{"invalid line: 0", "gno.land/r/demo/v", hash("a"), hash("c"), "ipfs://x", "B01,high,PROVEN,a.gno,0", "0.1.0"},
		{"invalid scanner or toolchain version", "gno.land/r/demo/v", hash("a"), hash("c"), "ipfs://x", "", "0.1 0"},
	}
	for _, b := range bad {
		testing.SetRealm(testing.NewUserRealm(botAddr))
		uassert.AbortsWithMessage(t, cur, b.msg, func() {
			Attest(cross(cur), b.pkg, b.src, b.scanv, hash("b"), "gno", b.report, b.uri, b.findings, 0, 0, 0)
		})
	}
	uassert.Equal(t, 0, records.Size())
}

func TestReadsReturnCopies(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	attest(cur, "gno.land/r/demo/vault", hash("c"), "B01,high,PROVEN,vault.gno,64", 0)
	a, _ := Latest("gno.land/r/demo/vault")
	a.Findings[0].Rule = "B99"
	a.Score = 100
	h := History("gno.land/r/demo/vault")
	h[0].Findings[0].Line = 1
	again, _ := Latest("gno.land/r/demo/vault")
	uassert.Equal(t, "B01", again.Findings[0].Rule)
	uassert.Equal(t, 64, again.Findings[0].Line)
	uassert.Equal(t, 75, again.Score)
}

func TestDispute(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	pkg := "gno.land/r/demo/clean"
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "no attestation to dispute", func() { Dispute(cross(cur), pkg, hash("e"), "x") })

	attest(cur, pkg, hash("c"), "", 0)
	uassert.True(t, Check(pkg, Strict()))

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "a dispute needs a report that differs from the attested one", func() {
		Dispute(cross(cur), pkg, hash("c"), "same report")
	})
	testing.SetRealm(testing.NewUserRealm(bob))
	id := Dispute(cross(cur), pkg, hash("e"), "my run finds B01 at vault.gno:12")
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "you already have an open dispute on this package", func() {
		Dispute(cross(cur), pkg, hash("f"), "again")
	})
	uassert.False(t, Check(pkg, Strict()))  // open dispute
	uassert.True(t, Check(pkg, Standard())) // Standard tolerates disputes

	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsWithMessage(t, cur, "admin or attester only", func() { ResolveDispute(cross(cur), id, "no") })
	testing.SetRealm(testing.NewUserRealm(botAddr))
	ResolveDispute(cross(cur), id, "re-ran with 0.1.1: no B01")
	uassert.True(t, Check(pkg, Strict()))
	ds := DisputesFor(pkg)
	urequire.Equal(t, 1, len(ds))
	uassert.True(t, ds[0].Resolved)
}

func TestReply(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	v1 := "gno.land/r/" + alice.String() + "/vault/v1"
	v2 := "gno.land/r/" + alice.String() + "/vault/v2"
	attest(cur, v1, hash("c"), "B01,high,PROVEN,vault.gno,64", 0)
	uassert.Equal(t, 1, len(ByAuthor(alice)))

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "author only", func() { Reply(cross(cur), v1, "not me", "") })
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsWithMessage(t, cur, "the successor must be in the same address namespace", func() {
		Reply(cross(cur), v1, "moved", "gno.land/r/"+bob.String()+"/vault/v2")
	})
	testing.SetRealm(testing.NewUserRealm(alice))
	Reply(cross(cur), v1, "Fixed in v2: getters return copies.", v2)
	rs := Replies(v1)
	urequire.Equal(t, 1, len(rs))
	uassert.Equal(t, v2, rs[0].Successor)

	attest(cur, "gno.land/r/demo/shared", hash("c"), "", 0)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsWithMessage(t, cur, "only address-namespace packages have a verified author", func() {
		Reply(cross(cur), "gno.land/r/demo/shared", "mine", "")
	})
}

func TestCheckPolicies(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	attest(cur, "gno.land/r/demo/clean", hash("c"), "", 0)
	attest(cur, "gno.land/r/demo/warn", hash("c"), "B01,high,NOT REPRODUCED,a.gno,3", 0)
	attest(cur, "gno.land/r/demo/high", hash("c"), "B01,high,PROVEN,a.gno,3", 0)
	attest(cur, "gno.land/r/demo/crit", hash("c"), "B05,critical,PROVEN,a.gno,3", 0)
	attest(cur, "gno.land/r/demo/deps", hash("c"), "", 1)

	cases := []struct {
		pkg              string
		strict, standard bool
	}{
		{"gno.land/r/demo/clean", true, true},
		{"gno.land/r/demo/warn", true, true},  // 90, warnings only
		{"gno.land/r/demo/high", false, true}, // 75, PROVEN High
		{"gno.land/r/demo/crit", false, false},
		{"gno.land/r/demo/deps", false, true}, // unverified dependency
		{"gno.land/r/demo/unknown", false, false},
	}
	for _, c := range cases {
		uassert.Equal(t, c.strict, Check(c.pkg, Strict()), c.pkg+" strict")
		uassert.Equal(t, c.standard, Check(c.pkg, Standard()), c.pkg+" standard")
	}
	custom := Custom(50).WithProvenCritical()
	uassert.True(t, Check("gno.land/r/demo/crit", custom))
	uassert.False(t, Check("gno.land/r/demo/high", custom)) // PROVEN High not allowed
}

func TestAdminTransfer(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(adminAddr))
	TransferAdmin(cross(cur), alice)
	uassert.Equal(t, alice, Admin())
	testing.SetRealm(testing.NewUserRealm(adminAddr))
	uassert.AbortsWithMessage(t, cur, "admin only", func() { AddAttester(cross(cur), bob) })
	testing.SetRealm(testing.NewUserRealm(alice))
	AddAttester(cross(cur), bob)
	uassert.True(t, IsAttester(bob))
	testing.SetRealm(testing.NewUserRealm(alice))
	RemoveAttester(cross(cur), bob)
	uassert.False(t, IsAttester(bob))
}

func TestRender(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	v1 := "gno.land/r/" + alice.String() + "/vault/v1"
	attest(cur, v1, hash("c"), "B01,high,PROVEN,vault.gno,64;B05,critical,PROVEN,vault.gno,35", 0)
	attest(cur, v1, hash("d"), "B05,critical,PROVEN,vault.gno,35", 0)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reply(cross(cur), v1, "fixed [x](javascript:alert(1)) <script>alert(1)</script> | col", "gno.land/r/"+alice.String()+"/vault/v2")

	home := Render("")
	uassert.True(t, strings.Contains(home, `<gno-form exec="RequestScan">`))
	uassert.True(t, strings.Contains(home, Disclaimer))
	uassert.True(t, strings.Contains(home, "/bouncer/v1:realm/"+v1))

	page := Render("realm/" + v1)
	uassert.True(t, strings.Contains(page, "## 60 / 100 · Grade C · 🔴 Not recommended for integration"))
	uassert.True(t, strings.Contains(page, Disclaimer))
	uassert.True(t, strings.Contains(page, "| B05 | critical | **PROVEN** |"))
	uassert.True(t, strings.Contains(page, "B01 resolved"))
	uassert.True(t, strings.Contains(page, "https://ipfs.filebase.io/ipfs/bafyexample"))
	uassert.True(t, strings.Contains(page, "The author points to a newer version"))
	// User text is escaped: no live link, no raw HTML.
	uassert.False(t, strings.Contains(page, "](javascript:"))
	uassert.False(t, strings.Contains(page, "<script>"))

	uassert.True(t, strings.Contains(Render("realm/gno.land/r/demo/none"), "has not attested this package yet"))
	uassert.True(t, strings.Contains(Render("realm/not a path"), "not a valid package path"))
	uassert.True(t, strings.Contains(Render("nope"), "# Not found"))
}

details.gno

package bouncer

import (
	"chain"
	"strconv"
	"strings"
	"unicode/utf8"

	"gno.land/p/nt/seqid/v0"
)

// Size limits for finding details. The full report (ReportURI) has
// everything; the Passport shows what fits here.
const (
	maxSnippetLen  = 1500
	maxAttackLen   = 200
	maxExploitLen  = 6000
	maxEvidenceLen = 1500
	// maxDetailBytes caps the detail text of one attestation.
	maxDetailBytes = 32000
)

// AddDetail attaches the vulnerable snippet and, for a PROVEN finding, the
// exploit and its evidence to finding index of attestation id. Only the
// attester who posted the attestation may call it, once per finding: the
// details are as permanent as the attestation itself.
func AddDetail(cur realm, pkgpath string, id uint64, index int, snippet, attack, exploit, before, after string) {
	caller := assertAttester(cur)
	rec := getRecord(pkgpath)
	if rec == nil {
		panic("no attestation for this package")
	}
	ai := -1
	for i := range rec.history {
		if rec.history[i].ID == id {
			ai = i
			break
		}
	}
	if ai < 0 {
		panic("no such attestation for this package")
	}
	a := &rec.history[ai]
	if a.Attester != caller {
		panic("only the attestation's own attester can add details")
	}
	if index < 0 || index >= len(a.Findings) {
		panic("finding index out of range")
	}
	f := &a.Findings[index]
	if f.Detailed {
		panic("details already added for this finding")
	}
	checkText("snippet", snippet, maxSnippetLen)
	checkText("attack", attack, maxAttackLen)
	checkText("exploit", exploit, maxExploitLen)
	checkText("before", before, maxEvidenceLen)
	checkText("after", after, maxEvidenceLen)
	if strings.ContainsAny(attack, "\n\r") {
		panic("attack must be one line")
	}
	proofLen := len(attack) + len(exploit) + len(before) + len(after)
	if f.Label != LabelProven && proofLen > 0 {
		panic("only PROVEN findings carry an exploit and evidence")
	}
	if detailBytes(a.Findings)+len(snippet)+proofLen > maxDetailBytes {
		panic("detail limit reached for this attestation; see the full report")
	}
	f.Detailed = true
	f.Snippet = snippet
	f.Attack = attack
	f.Exploit = exploit
	f.Before = before
	f.After = after
	chain.Emit("DetailAdded",
		"id", seqid.ID(id).String(),
		"pkgpath", pkgpath,
		"index", strconv.Itoa(index))
}

func detailBytes(fs []Finding) int {
	n := 0
	for _, f := range fs {
		n += len(f.Snippet) + len(f.Attack) + len(f.Exploit) + len(f.Before) + len(f.After)
	}
	return n
}

// checkText rejects text that is too long, not UTF-8, or carries NUL or
// other control characters besides tab and newline.
func checkText(name, s string, max int) {
	if len(s) > max {
		panic(name + " is too long (max " + strconv.Itoa(max) + " bytes)")
	}
	if !utf8.ValidString(s) {
		panic(name + " must be valid UTF-8")
	}
	for _, c := range s {
		if c < 0x20 && c != '\n' && c != '\t' || c == 0x7f {
			panic(name + " contains a control character")
		}
	}
}

disputes.gno

package bouncer

import (
	"chain"
	"chain/runtime"

	"gno.land/p/nt/seqid/v0"
)

// DisputeRecord is a challenge to an attestation, backed by a different report.
type DisputeRecord struct {
	ID            uint64
	PkgPath       string
	AttestationID uint64 // the attestation disputed (the latest at filing time)
	ReportHash    string // the disputer's report
	Note          string
	Filer         address
	Height        int64
	Resolved      bool
	Resolution    string
}

type dispute struct {
	d DisputeRecord
}

func disputeKey(id uint64) string { return seqid.ID(id).String() }

// Dispute files a challenge against the latest attestation of pkgpath,
// backed by a report with a different hash. One open dispute per filer
// per package.
func Dispute(cur realm, pkgpath, reportHash, note string) uint64 {
	if !cur.IsCurrent() {
		panic("invalid realm")
	}
	filer := cur.Previous().Address()
	rec := getRecord(pkgpath)
	if rec == nil {
		panic("no attestation to dispute")
	}
	latest := rec.history[len(rec.history)-1]
	if !isHex64(reportHash) {
		panic("report hash must be 64 lowercase hex characters")
	}
	if reportHash == latest.ReportHash {
		panic("a dispute needs a report that differs from the attested one")
	}
	if note == "" || len(note) > maxNoteLen {
		panic("note must be 1 to 280 bytes")
	}
	if hasOpenDispute(pkgpath, filer) {
		panic("you already have an open dispute on this package")
	}
	id := uint64(disputeID.Next())
	disputes.Set(disputeKey(id), &dispute{d: DisputeRecord{
		ID:            id,
		PkgPath:       pkgpath,
		AttestationID: latest.ID,
		ReportHash:    reportHash,
		Note:          note,
		Filer:         filer,
		Height:        runtime.ChainHeight(),
	}})
	chain.Emit("Disputed", "id", disputeKey(id), "pkgpath", pkgpath, "filer", filer.String(), "report_hash", reportHash)
	return id
}

// ResolveDispute closes a dispute with a resolution note. Admin or an
// attester.
func ResolveDispute(cur realm, id uint64, resolution string) {
	if !cur.IsCurrent() {
		panic("invalid realm")
	}
	caller := cur.Previous().Address()
	if caller != admin && !attesters.Has(string(caller)) {
		panic("admin or attester only")
	}
	if resolution == "" || len(resolution) > maxNoteLen {
		panic("resolution must be 1 to 280 bytes")
	}
	v := disputes.Get(disputeKey(id))
	if v == nil {
		panic("no such dispute")
	}
	d := v.(*dispute)
	if d.d.Resolved {
		panic("dispute already resolved")
	}
	d.d.Resolved = true
	d.d.Resolution = resolution
	chain.Emit("DisputeResolved", "id", disputeKey(id), "pkgpath", d.d.PkgPath)
}

func hasOpenDispute(pkgpath string, filer address) bool {
	found := false
	disputes.Iterate("", "", func(_ string, v any) bool {
		d := v.(*dispute).d
		if d.PkgPath == pkgpath && !d.Resolved && (filer == "" || d.Filer == filer) {
			found = true
		}
		return found
	})
	return found
}

// DisputesFor returns copies of every dispute on pkgpath, oldest first.
func DisputesFor(pkgpath string) []DisputeRecord {
	out := []DisputeRecord{}
	disputes.Iterate("", "", func(_ string, v any) bool {
		if d := v.(*dispute).d; d.PkgPath == pkgpath {
			out = append(out, d)
		}
		return false
	})
	return out
}

// Reply lets the author of an address-namespace package answer its
// Passport and, optionally, name the fixed version (successor) in the same
// namespace.
func Reply(cur realm, pkgpath, note, successor string) {
	if !cur.IsCurrent() {
		panic("invalid realm")
	}
	caller := cur.Previous().Address()
	author, ok := authorOf(pkgpath)
	if !ok {
		panic("only address-namespace packages have a verified author")
	}
	if caller != author {
		panic("author only")
	}
	rec := getRecord(pkgpath)
	if rec == nil {
		panic("no attestation to reply to")
	}
	if note == "" || len(note) > maxNoteLen {
		panic("note must be 1 to 280 bytes")
	}
	if successor != "" {
		if !validPkgPath(successor) || successor == pkgpath {
			panic("invalid successor path")
		}
		if sa, ok := authorOf(successor); !ok || sa != author {
			panic("the successor must be in the same address namespace")
		}
	}
	if len(rec.replies) >= maxReplies {
		panic("reply limit reached for this package")
	}
	rec.replies = append(rec.replies, AuthorReply{Author: caller, Note: note, Successor: successor, Height: runtime.ChainHeight()})
	chain.Emit("Replied", "pkgpath", pkgpath, "author", caller.String(), "successor", successor)
}

gnomod.toml

module = "gno.land/r/g19wmd95cwm3s0w0c5592tgu3zh4zgrtlggvugnj/bouncer/v1"
gno = "0.9"

[addpkg]
  creator = "g19wmd95cwm3s0w0c5592tgu3zh4zgrtlggvugnj"
  height = 1366587
  max_deposit = "20000000ugnot"

guidance.gno

package bouncer

// Guidance is the fix guidance for one rule. It is written once per rule,
// so every Passport says the same thing and it costs nothing per finding.
type Guidance struct {
	Title   string // short name of the bug class
	Guide   string // security guide sections
	Meaning string // what the finding means
	Danger  string // why it is dangerous
	Fix     string // what to change
	Example string // the fixed code, Gno
	Why     string // why the fix works
}

// RuleGuidance returns the guidance for rule, and false for a rule this
// realm has no guidance for yet.
func RuleGuidance(rule string) (Guidance, bool) {
	switch rule {
	case "B01":
		return Guidance{
			Title:   "Getter returns a pointer into state",
			Guide:   "§5.1, §5.1a",
			Meaning: "An exported function hands out a pointer to the realm's own state, and the pointed-to type has an exported method that changes it.",
			Danger:  "Readonly taint stops another realm writing fields through the pointer, but not calling methods on it. Any realm can call the mutating method, and the write commits with this realm's authority: balances, owners and counters change with no check at all.",
			Fix:     "Return copies or plain values, never a pointer into package state. Keep mutating methods unexported and reach them only through crossing functions that check the caller.",
			Example: "type Entry struct {\n\tAddr    address\n\tBalance int64\n}\n\n// Balances returns a copy of the ledger.\nfunc Balances() []Entry {\n\tout := []Entry{}\n\tledger.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tout = append(out, Entry{address(k), v.(int64)})\n\t\treturn false\n\t})\n\treturn out\n}",
			Why:     "A copy has no path back into the realm's storage, so nothing a caller does to it can reach the real state.",
		}, true
	case "B05":
		return Guidance{
			Title:   "IsUser() guards an OriginSend payment",
			Guide:   "§5.5",
			Meaning: "A payment is credited from `OriginSend()` behind an `IsUser()` check.",
			Danger:  "`IsUser()` is also true for a `maketx run` script. In that case the coins in `OriginSend()` go to the script's own realm, not to this one, so the caller is credited for money this realm never received and can withdraw other users' funds.",
			Fix:     "Accept payments only from a direct call: check `cur.Previous().IsUserCall()` before reading `OriginSend()`.",
			Example: "func Deposit(cur realm) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"not current\")\n\t}\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"deposit with maketx call\")\n\t}\n\tamount := unsafe.OriginSend().AmountOf(\"ugnot\")\n\t// credit amount\n}",
			Why:     "`IsUserCall()` is true only for a direct `maketx call`, where the sent coins are guaranteed to land at this realm before it runs.",
		}, true
	case "B03":
		return Guidance{
			Title:   "Caller-supplied callback runs with the realm's authority",
			Guide:   "§3C, §5.3",
			Meaning: "The realm calls a function or interface value that its caller passed in.",
			Danger:  "The callback runs while this realm holds its authority, so it can do anything this realm can: move its coins, or call back in mid-update.",
			Fix:     "Never invoke a caller-supplied function or interface while holding this realm's authority. Take plain data instead.",
			Example: "",
			Why:     "Plain data cannot run code, so there is nothing to hijack.",
		}, true
	case "B09":
		return Guidance{
			Title:   "External Teller used without IsCanonicalTeller",
			Guide:   "§5.4",
			Meaning: "The realm calls a GRC20 Teller that a caller passed in, without checking it.",
			Danger:  "A fake Teller can report transfers that never happened.",
			Fix:     "Check `grc20.IsCanonicalTeller(t)` before using a Teller from a caller, or look the token up yourself.",
			Example: "",
			Why:     "A canonical Teller is the token's own, so its transfers are real.",
		}, true
	}
	return Guidance{}, false
}

passport_test.gno

package bouncer

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
)

const (
	snippet = "func Ledger() *avl.Tree {\n\treturn ledger\n}"
	exploit = "package attacker\n\nfunc main(cur realm) {\n\tvictim.Ledger().Set(\"bouncer-probe\", int64(0))\n}"
)

func TestFindingFunc(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	attest(cur, "gno.land/r/demo/fv", hash("c"), "B01,high,PROVEN,vault.gno,69,Ledger;B05,critical,STATIC WARNING,vault.gno,9,Store.Pay", 0)
	a, _ := Latest("gno.land/r/demo/fv")
	uassert.Equal(t, "Ledger", a.Findings[0].Func)
	uassert.Equal(t, "Store.Pay", a.Findings[1].Func)
	for _, bad := range []string{"1x", "a b", "a..b", "a-b", ""} {
		testing.SetRealm(testing.NewUserRealm(botAddr))
		uassert.AbortsWithMessage(t, cur, "invalid function name: "+bad, func() {
			Attest(cross(cur), "gno.land/r/demo/fv", hash("a"), "0.1.0", hash("b"), "x", hash("c"), "ipfs://bafy", "B01,high,PROVEN,vault.gno,69,"+bad, 0, 0, 0)
		})
	}
}

func TestAddDetail(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	p := "gno.land/r/demo/dv"
	attest(cur, p, hash("c"), "B01,high,PROVEN,vault.gno,69,Ledger;B05,critical,NOT REPRODUCED,vault.gno,35", 0)
	a, _ := Latest(p)

	// Only the attestation's own attester.
	testing.SetRealm(testing.NewUserRealm(adminAddr))
	uassert.AbortsWithMessage(t, cur, "only the attestation's own attester can add details", func() {
		AddDetail(cross(cur), p, a.ID, 0, snippet, "", "", "", "")
	})
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsWithMessage(t, cur, "attester only", func() {
		AddDetail(cross(cur), p, a.ID, 0, snippet, "", "", "", "")
	})
	testing.SetRealm(testing.NewUserRealm(botAddr))
	uassert.AbortsWithMessage(t, cur, "finding index out of range", func() {
		AddDetail(cross(cur), p, a.ID, 2, snippet, "", "", "", "")
	})
	testing.SetRealm(testing.NewUserRealm(botAddr))
	uassert.AbortsWithMessage(t, cur, "no such attestation for this package", func() {
		AddDetail(cross(cur), p, a.ID+100, 0, snippet, "", "", "", "")
	})
	// No exploit on a finding that is not PROVEN.
	testing.SetRealm(testing.NewUserRealm(botAddr))
	uassert.AbortsWithMessage(t, cur, "only PROVEN findings carry an exploit and evidence", func() {
		AddDetail(cross(cur), p, a.ID, 1, snippet, "", exploit, "", "")
	})
	// Text checks.
	testing.SetRealm(testing.NewUserRealm(botAddr))
	uassert.AbortsWithMessage(t, cur, "snippet contains a control character", func() {
		AddDetail(cross(cur), p, a.ID, 0, "a\x00b", "", "", "", "")
	})
	testing.SetRealm(testing.NewUserRealm(botAddr))
	uassert.AbortsWithMessage(t, cur, "attack must be one line", func() {
		AddDetail(cross(cur), p, a.ID, 0, snippet, "a\nb", "", "", "")
	})
	testing.SetRealm(testing.NewUserRealm(botAddr))
	uassert.AbortsWithMessage(t, cur, "exploit is too long (max 6000 bytes)", func() {
		AddDetail(cross(cur), p, a.ID, 0, snippet, "", strings.Repeat("x", 6001), "", "")
	})

	testing.SetRealm(testing.NewUserRealm(botAddr))
	AddDetail(cross(cur), p, a.ID, 0, snippet, "inserted a ledger entry with Set", exploit, "| alice | 5 |", "| alice | 5 |\n| bouncer-probe | 5 |")
	testing.SetRealm(testing.NewUserRealm(botAddr))
	AddDetail(cross(cur), p, a.ID, 1, "if !caller.IsUser() {", "", "", "", "")

	// Set once.
	testing.SetRealm(testing.NewUserRealm(botAddr))
	uassert.AbortsWithMessage(t, cur, "details already added for this finding", func() {
		AddDetail(cross(cur), p, a.ID, 0, "other", "", "", "", "")
	})

	got, _ := Latest(p)
	urequire.True(t, got.Findings[0].Detailed)
	uassert.Equal(t, snippet, got.Findings[0].Snippet)
	uassert.Equal(t, exploit, got.Findings[0].Exploit)
	uassert.Equal(t, "", got.Findings[1].Exploit)
}

func TestAddDetailTotalLimit(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	p := "gno.land/r/demo/big"
	fs := []string{}
	for i := 0; i < 8; i++ {
		fs = append(fs, "B01,high,PROVEN,vault.gno,1")
	}
	attest(cur, p, hash("c"), strings.Join(fs, ";"), 0)
	a, _ := Latest(p)
	big := strings.Repeat("x", 6000)
	for i := 0; i < 5; i++ { // 5 x 6000 = 30000
		testing.SetRealm(testing.NewUserRealm(botAddr))
		AddDetail(cross(cur), p, a.ID, i, "", "", big, "", "")
	}
	testing.SetRealm(testing.NewUserRealm(botAddr))
	uassert.AbortsWithMessage(t, cur, "detail limit reached for this attestation; see the full report", func() {
		AddDetail(cross(cur), p, a.ID, 5, "", "", big, "", "")
	})
}

func TestVersions(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	base := "gno.land/r/" + alice.String() + "/vault"
	attest(cur, base+"/v2", hash("d"), "", 0)
	attest(cur, base+"/v1", hash("c"), "B01,high,PROVEN,vault.gno,69,Ledger;B05,critical,STATIC WARNING,vault.gno,35", 0)
	attest(cur, base+"/v10", hash("e"), "B03,critical,STATIC WARNING,vault.gno,3", 0)
	attest(cur, "gno.land/r/demo/other/v1", hash("f"), "", 0)

	vs := Versions(base + "/v2")
	urequire.Equal(t, 3, len(vs))
	uassert.Equal(t, base+"/v1", vs[0])
	uassert.Equal(t, base+"/v2", vs[1])
	uassert.Equal(t, base+"/v10", vs[2])           // numeric, not string, order
	uassert.Equal(t, 3, len(Versions(base+"/v3"))) // same package, not yet attested
	uassert.Equal(t, 1, len(Versions("gno.land/r/demo/other/v1")))

	for _, c := range []struct {
		in   string
		base string
		n    int
		ok   bool
	}{
		{"gno.land/r/demo/vault/v1", "gno.land/r/demo/vault", 1, true},
		{"gno.land/r/demo/vault/v0", "gno.land/r/demo/vault", 0, true},
		{"gno.land/r/demo/vault", "", 0, false},
		{"gno.land/r/demo/vault/v01", "", 0, false},
		{"gno.land/r/demo/vault/vx", "", 0, false},
		{"gno.land/r/v1", "", 0, false},
	} {
		b, n, ok := familyOf(c.in)
		uassert.Equal(t, c.ok, ok, c.in)
		uassert.Equal(t, c.base, b, c.in)
		uassert.Equal(t, c.n, n, c.in)
	}

	page := Render("realm/" + base + "/v2")
	uassert.True(t, strings.Contains(page, "## Versions"))
	uassert.True(t, strings.Contains(page, "B01 resolved, B05 no longer detected"), page)
	uassert.True(t, strings.Contains(page, "B03 new"))
	uassert.True(t, strings.Contains(page, "(this page)"))
	uassert.True(t, strings.Contains(page, "first version scanned"))
}

func TestPassportFindings(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	p := "gno.land/r/demo/pf/v1"
	attest(cur, p, hash("c"), "B01,high,PROVEN,vault.gno,69,Ledger;B05,critical,NOT REPRODUCED,vault.gno,35,Deposit;B09,high,STATIC WARNING,pay.gno,12;B42,medium,STATIC WARNING,x.gno,1", 0)
	a, _ := Latest(p)
	testing.SetRealm(testing.NewUserRealm(botAddr))
	AddDetail(cross(cur), p, a.ID, 0, snippet, "inserted a ledger entry with Set [x](javascript:alert(1))", exploit+"\n```\n# injected", "| alice | 5 |", "| alice | 5 |\n| bouncer-probe | 5 |")

	page := Render("realm/" + p)
	uassert.True(t, strings.Contains(page, "| 1 | B01 | high | **PROVEN** | `vault.gno:69 in Ledger()` |"), page)
	uassert.True(t, strings.Contains(page, "### 1. B01: Getter returns a pointer into state"))
	uassert.True(t, strings.Contains(page, "**What it means.**"))
	uassert.True(t, strings.Contains(page, "**Why it is dangerous.**"))
	uassert.True(t, strings.Contains(page, "```go\n"+snippet+"\n```"))
	uassert.True(t, strings.Contains(page, "**Fix.**"))
	uassert.True(t, strings.Contains(page, "func Balances() []Entry"))
	uassert.True(t, strings.Contains(page, "**Why it works.**"))
	uassert.True(t, strings.Contains(page, "**Proof.** Bouncer wrote an attacker realm"))
	uassert.True(t, strings.Contains(page, "<gno-columns>"))
	uassert.True(t, strings.Contains(page, "<gno-columns-sep />"))
	uassert.True(t, strings.Contains(page, "| bouncer-probe | 5 |"))
	// The exploit cannot break out of its code block.
	uassert.True(t, strings.Contains(page, "````go\n"+exploit+"\n```\n# injected\n````"), page)
	uassert.False(t, strings.Contains(page, "](javascript:"), page)
	// Labels explained without claiming safety.
	uassert.True(t, strings.Contains(page, "**Not reproduced.** Bouncer's generated exploit did not land. This stays a warning: it is not evidence that the code is safe."))
	uassert.True(t, strings.Contains(page, "**Static warning.**"))
	uassert.True(t, strings.Contains(page, "### 4. B42: see the full report"))
	uassert.False(t, strings.Contains(page, "## Versions")) // only one version
}

func TestBadge(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	p := "gno.land/r/demo/bv/v1"
	uassert.True(t, strings.HasPrefix(Badge(p), "[![Bouncer: not scanned](data:image/svg+xml;base64,"))
	uassert.Equal(t, "", Badge("not a path"))

	attest(cur, p, hash("c"), "B01,high,PROVEN,vault.gno,69", 0)
	got := Badge(p)
	uassert.True(t, strings.HasPrefix(got, "[![Bouncer: grade B, score 75, not recommended for integration](data:image/svg+xml;base64,"), got)
	uassert.True(t, strings.HasSuffix(got, ":realm/"+p+")"), got)
	uassert.True(t, strings.Contains(Render("realm/"+p), got), "badge on page")
	uassert.True(t, strings.Contains(Render("realm/"+p), `out += bouncer.Badge("`+p+`")`), "snippet")

	attest(cur, p, hash("d"), "B01,high,NOT REPRODUCED,vault.gno,69", 0)
	uassert.True(t, strings.Contains(Badge(p), "score 90, review before integration"), Badge(p)[:120])
	attest(cur, p, hash("e"), "", 0)
	uassert.True(t, strings.Contains(Badge(p), "score 100, no known Critical or High issues"))
}

func TestBotReads(cur realm, t *testing.T) {
	reset()
	addBot(cur)
	uassert.Equal(t, "", OpenRequestsText(10))
	testing.SetRealm(testing.NewUserRealm(alice))
	RequestScan(cross(cur), "gno.land/r/demo/a")
	testing.SetRealm(testing.NewUserRealm(bob))
	RequestScan(cross(cur), "gno.land/r/demo/b")
	uassert.Equal(t, "1 gno.land/r/demo/a\n2 gno.land/r/demo/b\n", OpenRequestsText(10))
	uassert.Equal(t, "1 gno.land/r/demo/a\n", OpenRequestsText(1))

	uassert.Equal(t, "", LatestHashes("gno.land/r/demo/a"))
	attest(cur, "gno.land/r/demo/a", hash("c"), "B01,high,PROVEN,My-Vault.gno,3", 0)
	uassert.Equal(t, hash("a")+" "+hash("b"), LatestHashes("gno.land/r/demo/a"))
	uassert.Equal(t, "2 gno.land/r/demo/b\n", OpenRequestsText(10)) // attest closed request 1
}

reads.gno

package bouncer

import "gno.land/p/nt/avl/v0"

// Reads for other realms and for clients. All are plain (non-crossing)
// functions that return values or fresh copies: no pointer into state ever
// leaves this realm, and no caller-supplied function is ever invoked.

// copyAttestation returns a deep copy (the Findings slice is copied too).
func copyAttestation(a Attestation) Attestation {
	fs := make([]Finding, len(a.Findings))
	copy(fs, a.Findings)
	a.Findings = fs
	return a
}

// Latest returns the newest attestation for pkgpath.
func Latest(pkgpath string) (Attestation, bool) {
	rec := getRecord(pkgpath)
	if rec == nil {
		return Attestation{}, false
	}
	return copyAttestation(rec.history[len(rec.history)-1]), true
}

// History returns every attestation for pkgpath, oldest first.
func History(pkgpath string) []Attestation {
	rec := getRecord(pkgpath)
	out := []Attestation{}
	if rec == nil {
		return out
	}
	for _, a := range rec.history {
		out = append(out, copyAttestation(a))
	}
	return out
}

// Replies returns the author's replies on pkgpath, oldest first.
func Replies(pkgpath string) []AuthorReply {
	rec := getRecord(pkgpath)
	out := []AuthorReply{}
	if rec != nil {
		out = append(out, rec.replies...)
	}
	return out
}

// Score returns the latest score for pkgpath.
func Score(pkgpath string) (int, bool) {
	a, ok := Latest(pkgpath)
	return a.Score, ok
}

// ByAuthor returns the attested packages in addr's namespace, sorted.
func ByAuthor(addr address) []string {
	out := []string{}
	v := byAuthor.Get(string(addr))
	if v == nil {
		return out
	}
	v.(*avl.Tree).Iterate("", "", func(k string, _ any) bool {
		out = append(out, k)
		return false
	})
	return out
}

// Policy is an integration policy for Check. The zero value is the most
// conservative: no PROVEN findings, no open disputes, any score.
type Policy struct {
	MinScore int
	// AllowProvenCritical and AllowProvenOther permit PROVEN findings of
	// critical, or of high and medium, severity.
	AllowProvenCritical bool
	AllowProvenOther    bool
	// RequireVerifiedDeps forbids at-risk and unverified dependencies.
	RequireVerifiedDeps bool
	AllowOpenDisputes   bool
}

// Strict: score 90 or more, no PROVEN findings, every dependency verified,
// no open disputes.
func Strict() Policy {
	return Policy{MinScore: 90, RequireVerifiedDeps: true}
}

// Standard: score 75 or more and no PROVEN Critical.
func Standard() Policy {
	return Policy{MinScore: 75, AllowProvenOther: true, AllowOpenDisputes: true}
}

// Custom starts a policy at minScore that is otherwise as strict as the
// zero value; loosen it with the With methods:
//
//	bouncer.Custom(60).WithProvenOther().WithOpenDisputes()
//
// Other realms must build policies this way: the VM refuses to allocate a
// Bouncer type in a foreign realm, so a bouncer.Policy{...} literal written
// in another realm panics.
func Custom(minScore int) Policy { return Policy{MinScore: minScore} }

// WithProvenCritical allows PROVEN critical findings.
func (p Policy) WithProvenCritical() Policy { p.AllowProvenCritical = true; return p }

// WithProvenOther allows PROVEN high and medium findings.
func (p Policy) WithProvenOther() Policy { p.AllowProvenOther = true; return p }

// WithVerifiedDeps requires every dependency to be verified.
func (p Policy) WithVerifiedDeps() Policy { p.RequireVerifiedDeps = true; return p }

// WithOpenDisputes allows open disputes.
func (p Policy) WithOpenDisputes() Policy { p.AllowOpenDisputes = true; return p }

// Check reports whether the latest attestation of pkgpath satisfies p.
// An unattested package never passes.
func Check(pkgpath string, p Policy) bool {
	a, ok := Latest(pkgpath)
	if !ok || a.Score < p.MinScore {
		return false
	}
	for _, f := range a.Findings {
		if f.Label != LabelProven {
			continue
		}
		if f.Severity == SeverityCritical && !p.AllowProvenCritical {
			return false
		}
		if f.Severity != SeverityCritical && !p.AllowProvenOther {
			return false
		}
	}
	if p.RequireVerifiedDeps && (a.Deps.DirectAtRisk > 0 || a.Deps.IndirectAtRisk > 0 || a.Deps.Unverified > 0) {
		return false
	}
	if !p.AllowOpenDisputes && hasOpenDispute(pkgpath, "") {
		return false
	}
	return true
}

render.gno

package bouncer

import (
	"strconv"
	"strings"
	"time"

	"gno.land/p/nt/markdown/sanitize/v0"
)

// Render serves the Tavern pages:
//
//	""                 Noticeboard
//	"realm/<pkgpath>"  Passport
func Render(path string) string {
	if pkgpath, ok := strings.CutPrefix(path, "realm/"); ok {
		return renderPassport(pkgpath)
	}
	if path == "" {
		return renderNoticeboard()
	}
	return "# Not found\n\n[Back to the noticeboard](" + webPath() + ")\n"
}

// webPath is this realm's gnoweb URL path ("/r/...").
func webPath() string {
	return strings.TrimPrefix(selfPath, "gno.land")
}

// passportLink links to pkgpath's Passport. pkgpath is a validated path
// (lowercase letters, digits, underscores and slashes), so it is URL-safe.
func passportLink(pkgpath string) string {
	return "[" + sanitize.InlineCode(pkgpath) + "](" + webPath() + ":realm/" + pkgpath + ")"
}

func verdictText(v string) string {
	switch v {
	case VerdictNotRecommended:
		return "🔴 Not recommended for integration"
	case VerdictReview:
		return "🟠 Review before integration"
	}
	return "🟢 No known Critical or High issues"
}

func date(unix int64) string {
	return time.Unix(unix, 0).UTC().Format("2006-01-02")
}

func renderNoticeboard() string {
	var b strings.Builder
	b.WriteString("# Bouncer\n\n**No exploit, no claim.** Bouncer checks Gno realms against the Gno security guide, proves serious bugs with a working attacker realm, and records the verdict here.\n\n")
	b.WriteString("| Passports | Findings | PROVEN | Open requests |\n| --- | --- | --- | --- |\n")
	b.WriteString("| " + strconv.Itoa(records.Size()) + " | " + strconv.Itoa(totalFindings) + " | " + strconv.Itoa(totalProven) + " | " + strconv.Itoa(openByRequester.Size()) + " |\n\n")

	b.WriteString("## Recent Passports\n\n")
	if len(recent) == 0 {
		b.WriteString("No packages attested yet.\n\n")
	} else {
		b.WriteString("| Package | Score | Grade | Verdict |\n| --- | --- | --- | --- |\n")
		for _, p := range recent {
			a := getRecord(p).history[len(getRecord(p).history)-1]
			b.WriteString("| " + passportLink(p) + " | " + strconv.Itoa(a.Score) + " | " + a.Grade + " | " + verdictText(a.Verdict) + " |\n")
		}
		b.WriteString("\n")
	}

	b.WriteString("## Request a scan\n\nOne open request per address. The scanner bot picks it up, scans and proves, then posts the result.\n\n")
	b.WriteString("<gno-form exec=\"RequestScan\">\n<gno-input name=\"pkgpath\" placeholder=\"gno.land/r/<address>/myrealm\" />\n</gno-form>\n\n")
	b.WriteString("_" + Disclaimer + "_\n")
	return b.String()
}

func renderPassport(pkgpath string) string {
	if !validPkgPath(pkgpath) {
		return "# Not found\n\nThat is not a valid package path.\n"
	}
	rec := getRecord(pkgpath)
	var b strings.Builder
	b.WriteString("# Passport: " + sanitize.InlineCode(pkgpath) + "\n\n")
	if rec == nil {
		b.WriteString("Bouncer has not attested this package yet. [Request a scan](" + webPath() + ").\n")
		return b.String()
	}
	a := rec.history[len(rec.history)-1]

	b.WriteString("## " + strconv.Itoa(a.Score) + " / 100 · Grade " + a.Grade + " · " + verdictText(a.Verdict) + "\n\n")
	b.WriteString(Badge(pkgpath) + "\n\n")
	b.WriteString("_" + Disclaimer + "_\n\n")
	if successor := latestSuccessor(rec); successor != "" {
		b.WriteString("The author points to a newer version: " + passportLink(successor) + "\n\n")
	}

	b.WriteString("## Findings\n\n")
	if len(a.Findings) == 0 {
		b.WriteString("No findings with the current rules.\n\n")
	} else {
		b.WriteString("| # | Rule | Severity | Label | Location |\n| --- | --- | --- | --- | --- |\n")
		for i, f := range a.Findings {
			b.WriteString("| " + strconv.Itoa(i+1) + " | " + f.Rule + " | " + f.Severity + " | **" + f.Label + "** | " + sanitize.InlineCode(location(f)) + " |\n")
		}
		b.WriteString("\n")
		for i, f := range a.Findings {
			renderFinding(&b, i+1, f)
		}
	}

	b.WriteString("## Attestation\n\n| | |\n| --- | --- |\n")
	row := func(k, v string) { b.WriteString("| " + k + " | " + v + " |\n") }
	row("Attested", date(a.Time)+" (block "+strconv.FormatInt(a.Height, 10)+")")
	row("Attester", sanitize.InlineCode(a.Attester.String()))
	row("Source hash", sanitize.InlineCode(a.SourceHash))
	row("Scanner", sanitize.InlineCode(a.ScannerVersion)+", rule set "+sanitize.InlineCode(a.RulesetHash[:12]))
	row("Gno toolchain", sanitize.InlineCode(a.Toolchain))
	if u := reportURL(a.ReportURI); u != "" {
		row("Full report", "[report]("+u+"), hash "+sanitize.InlineCode(a.ReportHash[:12]))
	}
	row("Dependencies", strconv.Itoa(a.Deps.DirectAtRisk)+" direct at risk, "+strconv.Itoa(a.Deps.IndirectAtRisk)+" indirect at risk, "+strconv.Itoa(a.Deps.Unverified)+" unverified")
	b.WriteString("\n")

	if len(rec.replies) > 0 {
		b.WriteString("## Author replies\n\n")
		for _, r := range rec.replies {
			b.WriteString("- " + sanitize.InlineText(r.Note))
			if r.Successor != "" {
				b.WriteString(" (fixed version: " + passportLink(r.Successor) + ")")
			}
			b.WriteString("\n")
		}
		b.WriteString("\n")
	}

	if ds := DisputesFor(pkgpath); len(ds) > 0 {
		b.WriteString("## Disputes\n\n| Filer | Report | Note | Status |\n| --- | --- | --- | --- |\n")
		for _, d := range ds {
			status := "open"
			if d.Resolved {
				status = "resolved: " + sanitize.TableCell(d.Resolution)
			}
			b.WriteString("| " + sanitize.InlineCode(d.Filer.String()) + " | " + sanitize.InlineCode(d.ReportHash[:12]) + " | " + sanitize.TableCell(d.Note) + " | " + status + " |\n")
		}
		b.WriteString("\n")
	}

	renderVersions(&b, pkgpath)

	b.WriteString("## Badge\n\nShow this live badge on your realm's page by adding one line to its `Render`:\n\n")
	b.WriteString(sanitize.LanguageCodeBlock("go", "out += bouncer.Badge(\""+pkgpath+"\") // import \""+selfPath+"\"") + "\n\n")

	if len(rec.history) > 1 {
		b.WriteString("## Scans of this version\n\n| Date | Score | Grade | Findings | Change |\n| --- | --- | --- | --- | --- |\n")
		for i := len(rec.history) - 1; i >= 0; i-- {
			h := rec.history[i]
			change := "first scan"
			if i > 0 {
				change = diffFindings(rec.history[i-1].Findings, h.Findings)
			}
			b.WriteString("| " + date(h.Time) + " | " + strconv.Itoa(h.Score) + " | " + h.Grade + " | " + strconv.Itoa(len(h.Findings)) + " | " + change + " |\n")
		}
	}
	return b.String()
}

// location is "file:line in Func".
func location(f Finding) string {
	loc := f.File + ":" + strconv.Itoa(f.Line)
	if f.Func != "" {
		loc += " in " + f.Func + "()"
	}
	return loc
}

// renderFinding writes one finding: what it means, why it is dangerous, the
// vulnerable code, the fix and why it works, and the exploit if PROVEN.
func renderFinding(b *strings.Builder, n int, f Finding) {
	g, known := RuleGuidance(f.Rule)
	title := g.Title
	if !known {
		title = "see the full report"
	}
	b.WriteString("### " + strconv.Itoa(n) + ". " + f.Rule + ": " + title + "\n\n")
	b.WriteString("**" + f.Label + "** · " + f.Severity + " · " + sanitize.InlineCode(location(f)))
	if g.Guide != "" {
		b.WriteString(" · security guide " + g.Guide)
	}
	b.WriteString("\n\n")
	if known {
		b.WriteString("**What it means.** " + g.Meaning + "\n\n")
		b.WriteString("**Why it is dangerous.** " + g.Danger + "\n\n")
	}
	if f.Snippet != "" {
		b.WriteString("**Vulnerable code** (" + sanitize.InlineCode(f.File) + "):\n\n" + sanitize.LanguageCodeBlock("go", f.Snippet) + "\n\n")
	}
	if known {
		b.WriteString("**Fix.** " + g.Fix + "\n\n")
		if g.Example != "" {
			b.WriteString(sanitize.LanguageCodeBlock("go", g.Example) + "\n\n")
		}
		b.WriteString("**Why it works.** " + g.Why + "\n\n")
	}
	switch f.Label {
	case LabelProven:
		b.WriteString("**Proof.** Bouncer wrote an attacker realm and ran it against this exact source")
		if f.Attack != "" {
			b.WriteString(": " + sanitize.InlineText(f.Attack))
		}
		b.WriteString(".\n\n")
		if f.Exploit != "" {
			b.WriteString("Attacker realm (lines that print Bouncer's evidence markers are left out; the full report has the exact source):\n\n" + sanitize.LanguageCodeBlock("go", f.Exploit) + "\n\n")
		}
		if f.Before != "" || f.After != "" {
			b.WriteString("<gno-columns>\n\n**Before the attack**\n\n" + sanitize.CodeBlock(f.Before) +
				"\n\n<gno-columns-sep />\n\n**After the attack**\n\n" + sanitize.CodeBlock(f.After) + "\n\n</gno-columns>\n\n")
		}
	case LabelNotReproduced:
		b.WriteString("**Not reproduced.** Bouncer's generated exploit did not land. This stays a warning: it is not evidence that the code is safe.\n\n")
	default:
		b.WriteString("**Static warning.** The pattern matched, and Bouncer has no exploit generator for this rule yet.\n\n")
	}
}

// renderVersions lists every attested version of the package, newest first,
// with what changed from the version before it.
func renderVersions(b *strings.Builder, pkgpath string) {
	vs := Versions(pkgpath)
	if len(vs) < 2 {
		return
	}
	b.WriteString("## Versions\n\nPackages on Gno cannot be overwritten, so each fix ships at a new path. Latest scan of each version:\n\n")
	b.WriteString("| Version | Score | Grade | Verdict | Change from the version before |\n| --- | --- | --- | --- | --- |\n")
	for i := len(vs) - 1; i >= 0; i-- {
		cur := getRecord(vs[i]).history
		a := cur[len(cur)-1]
		change := "first version scanned"
		if i > 0 {
			prev := getRecord(vs[i-1]).history
			change = diffFindings(prev[len(prev)-1].Findings, a.Findings)
		}
		name := passportLink(vs[i])
		if vs[i] == pkgpath {
			name = "**" + name + "** (this page)"
		}
		b.WriteString("| " + name + " | " + strconv.Itoa(a.Score) + " | " + a.Grade + " | " + verdictText(a.Verdict) + " | " + change + " |\n")
	}
	b.WriteString("\n")
}

// latestSuccessor returns the newest successor an author named.
func latestSuccessor(rec *record) string {
	for i := len(rec.replies) - 1; i >= 0; i-- {
		if rec.replies[i].Successor != "" {
			return rec.replies[i].Successor
		}
	}
	return ""
}

// diffFindings describes which rules disappeared or appeared between two
// scans. A rule that was PROVEN and is gone is "resolved"; a warning that is
// gone is only "no longer detected", since a missing warning proves nothing.
func diffFindings(prev, next []Finding) string {
	had, has := map[string]bool{}, map[string]bool{}
	proven := map[string]bool{}
	for _, f := range prev {
		had[f.Rule] = true
		if f.Label == LabelProven {
			proven[f.Rule] = true
		}
	}
	for _, f := range next {
		has[f.Rule] = true
	}
	var parts []string
	done := map[string]bool{}
	for _, f := range prev {
		if has[f.Rule] || done[f.Rule] {
			continue
		}
		done[f.Rule] = true
		if proven[f.Rule] {
			parts = append(parts, f.Rule+" resolved")
		} else {
			parts = append(parts, f.Rule+" no longer detected")
		}
	}
	for _, f := range next {
		if had[f.Rule] || done[f.Rule] {
			continue
		}
		done[f.Rule] = true
		parts = append(parts, f.Rule+" new")
	}
	if len(parts) == 0 {
		return "no rule changes"
	}
	return strings.Join(parts, ", ")
}

// reportURL turns a stored report URI into a safe link target. IPFS URIs
// go through the IPFS gateway gnoweb itself uses, since links need https.
func reportURL(uri string) string {
	if cid, ok := strings.CutPrefix(uri, "ipfs://"); ok {
		uri = "https://ipfs.filebase.io/ipfs/" + cid
	}
	return sanitize.URL(uri)
}

requests.gno

package bouncer

import (
	"chain"
	"chain/runtime"
	"strconv"
	"strings"

	"gno.land/p/nt/seqid/v0"
)

// Request is a scan request, as returned by reads.
type Request struct {
	ID        uint64
	PkgPath   string
	Requester address
	Height    int64
	// Status is "open", "attested", "cancelled" or "closed".
	Status string
	// Note explains a closed request.
	Note string
}

type request struct {
	r Request
}

func requestKey(id uint64) string { return seqid.ID(id).String() }

// RequestScan asks the scanner bot to scan pkgpath. Each address may have
// one open request at a time.
func RequestScan(cur realm, pkgpath string) uint64 {
	if !cur.IsCurrent() {
		panic("invalid realm")
	}
	if !validPkgPath(pkgpath) {
		panic("invalid package path")
	}
	caller := cur.Previous().Address()
	if openByRequester.Has(string(caller)) {
		panic("you already have an open scan request")
	}
	id := uint64(requestID.Next())
	requests.Set(requestKey(id), &request{r: Request{
		ID:        id,
		PkgPath:   pkgpath,
		Requester: caller,
		Height:    runtime.ChainHeight(),
		Status:    "open",
	}})
	openByRequester.Set(string(caller), id)
	openRequests.Set(requestKey(id), true)
	chain.Emit("ScanRequested", "id", requestKey(id), "pkgpath", pkgpath, "requester", caller.String())
	return id
}

// CancelRequest withdraws the caller's open request.
func CancelRequest(cur realm) {
	if !cur.IsCurrent() {
		panic("invalid realm")
	}
	caller := cur.Previous().Address()
	v := openByRequester.Get(string(caller))
	if v == nil {
		panic("no open scan request")
	}
	finishRequest(v.(uint64), "cancelled", "")
}

// CloseRequest lets an attester close a request it cannot serve, such as a
// package that does not exist.
func CloseRequest(cur realm, id uint64, note string) {
	assertAttester(cur)
	if len(note) > maxNoteLen {
		panic("note too long")
	}
	v := requests.Get(requestKey(id))
	if v == nil || v.(*request).r.Status != "open" {
		panic("no open request with that id")
	}
	finishRequest(id, "closed", note)
}

func finishRequest(id uint64, status, note string) {
	rq := requests.Get(requestKey(id)).(*request)
	rq.r.Status = status
	rq.r.Note = note
	openByRequester.Remove(string(rq.r.Requester))
	openRequests.Remove(requestKey(id))
	chain.Emit("ScanRequestFinished", "id", requestKey(id), "pkgpath", rq.r.PkgPath, "status", status)
}

// closeRequestsFor marks every open request for pkgpath as attested.
func closeRequestsFor(pkgpath string) {
	var ids []uint64
	openRequests.Iterate("", "", func(k string, _ any) bool {
		r := requests.Get(k).(*request).r
		if r.PkgPath == pkgpath {
			ids = append(ids, r.ID)
		}
		return false
	})
	for _, id := range ids {
		finishRequest(id, "attested", "")
	}
}

// GetRequest returns a copy of request id.
func GetRequest(id uint64) (Request, bool) {
	v := requests.Get(requestKey(id))
	if v == nil {
		return Request{}, false
	}
	return v.(*request).r, true
}

// OpenRequests returns up to limit open requests, oldest first, for the
// scanner bot.
func OpenRequests(limit int) []Request {
	out := []Request{}
	if limit <= 0 {
		return out
	}
	// seqid keys sort in ID order.
	openRequests.Iterate("", "", func(k string, _ any) bool {
		out = append(out, requests.Get(k).(*request).r)
		return len(out) >= limit
	})
	return out
}

// OpenRequestsText is OpenRequests for the scanner bot, as plain text: one
// "id pkgpath" line per open request, oldest first. Package paths never
// contain spaces or newlines.
func OpenRequestsText(limit int) string {
	var b strings.Builder
	for _, r := range OpenRequests(limit) {
		b.WriteString(strconv.FormatUint(r.ID, 10) + " " + r.PkgPath + "\n")
	}
	return b.String()
}

// LatestHashes returns "<source hash> <rule-set hash>" of pkgpath's latest
// attestation, or "" if there is none, so the bot can skip unchanged code.
func LatestHashes(pkgpath string) string {
	a, ok := Latest(pkgpath)
	if !ok {
		return ""
	}
	return a.SourceHash + " " + a.RulesetHash
}

score.gno

package bouncer

// The public, deterministic scoring formula (CLAUDE.md §8). The realm
// computes score, grade and verdict itself from the attested findings and
// dependency counts, so an attestation can never carry a score that
// contradicts its own findings.

// Labels, exactly as the prover writes them.
const (
	LabelProven        = "PROVEN"
	LabelNotReproduced = "NOT REPRODUCED"
	LabelStaticWarning = "STATIC WARNING"
)

// Severities.
const (
	SeverityCritical = "critical"
	SeverityHigh     = "high"
	SeverityMedium   = "medium"
)

// Verdicts.
const (
	VerdictNotRecommended = "not-recommended" // any PROVEN Critical or High
	VerdictReview         = "review"          // any Critical or High warning
	VerdictClear          = "clear"           // no known Critical or High issues
)

// Disclaimer is shown on every Passport.
const Disclaimer = "A high score means Bouncer found no issues with its current rules. It is not a guarantee of safety."

// Deps counts dependency trust for an attestation.
type Deps struct {
	DirectAtRisk   int
	IndirectAtRisk int
	Unverified     int
}

// computeScore applies the formula: start at 100, deduct, floor at 0.
func computeScore(fs []Finding, d Deps) int {
	score := 100
	for _, f := range fs {
		proven := f.Label == LabelProven
		switch {
		case proven && f.Severity == SeverityCritical:
			score -= 40
		case proven && f.Severity == SeverityHigh:
			score -= 25
		case f.Severity == SeverityCritical:
			score -= 15
		case f.Severity == SeverityHigh:
			score -= 10
		default: // medium, proven or not
			score -= 5
		}
	}
	score -= 10 * d.DirectAtRisk
	score -= 5 * d.IndirectAtRisk
	unverified := 2 * d.Unverified
	if unverified > 10 {
		unverified = 10
	}
	score -= unverified
	if score < 0 {
		score = 0
	}
	return score
}

func gradeOf(score int) string {
	switch {
	case score >= 90:
		return "A"
	case score >= 75:
		return "B"
	case score >= 60:
		return "C"
	case score >= 40:
		return "D"
	}
	return "F"
}

func verdictOf(fs []Finding) string {
	verdict := VerdictClear
	for _, f := range fs {
		if f.Severity != SeverityCritical && f.Severity != SeverityHigh {
			continue
		}
		if f.Label == LabelProven {
			return VerdictNotRecommended
		}
		verdict = VerdictReview
	}
	return verdict
}

// ScoreFor exposes the formula, so anyone can check an attestation or score
// a report before attesting it.
func ScoreFor(fs []Finding, d Deps) (score int, grade, verdict string) {
	score = computeScore(fs, d)
	return score, gradeOf(score), verdictOf(fs)
}

versions.gno

package bouncer

import (
	"strconv"
	"strings"

	"gno.land/p/nt/avl/v0"
)

// Versions group the attested paths of one package: gno.land/r/x/vault/v1,
// .../v2 and so on. Packages on Gno cannot be overwritten, so a fix ships
// at a new /vN path, and the Passport shows every version side by side.

var families = avl.NewTree() // base path -> *avl.Tree (zero-padded N -> pkgpath)

// familyOf splits ".../name/vN" into its base and N.
func familyOf(pkgpath string) (base string, n int, ok bool) {
	i := strings.LastIndex(pkgpath, "/")
	if i < 0 {
		return "", 0, false
	}
	last := pkgpath[i+1:]
	if len(last) < 2 || len(last) > 7 || last[0] != 'v' {
		return "", 0, false
	}
	n, err := strconv.Atoi(last[1:])
	if err != nil || n < 0 || last[1:] != strconv.Itoa(n) {
		return "", 0, false
	}
	base = pkgpath[:i]
	if strings.Count(base, "/") < 2 { // need gno.land/r/<ns>/...
		return "", 0, false
	}
	return base, n, true
}

func versionKey(n int) string {
	s := strconv.Itoa(n)
	return strings.Repeat("0", 6-len(s)) + s
}

func addToFamily(pkgpath string) {
	base, n, ok := familyOf(pkgpath)
	if !ok {
		return
	}
	var t *avl.Tree
	if v := families.Get(base); v != nil {
		t = v.(*avl.Tree)
	} else {
		t = avl.NewTree()
		families.Set(base, t)
	}
	t.Set(versionKey(n), pkgpath)
}

// Versions returns every attested version of pkgpath's package, oldest
// first. A path without a /vN suffix is its own only version.
func Versions(pkgpath string) []string {
	out := []string{}
	base, _, ok := familyOf(pkgpath)
	if !ok {
		if getRecord(pkgpath) != nil {
			out = append(out, pkgpath)
		}
		return out
	}
	v := families.Get(base)
	if v == nil {
		return out
	}
	v.(*avl.Tree).Iterate("", "", func(_ string, p any) bool {
		out = append(out, p.(string))
		return false
	})
	return out
}