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.
type Finding struct {
	Rule     string // B01 ...
	Severity string // critical, high, medium
	Label    string // PROVEN, NOT REPRODUCED, STATIC WARNING
	File     string
	Line     int
}

// 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" entries ("" for
// none). 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)
		}
	} 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 {
			panic("finding must be RULE,severity,LABEL,file,line: " + 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
		out = append(out, f)
	}
	return out
}

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 >= '0' && c <= '9' || 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
}

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()
	records = avl.NewTree()
	byAuthor = 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/v0: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"))
}

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/v0"
gno = "0.9"

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

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("_" + 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 _, f := range a.Findings {
			b.WriteString("| " + f.Rule + " | " + f.Severity + " | **" + f.Label + "** | " + sanitize.InlineCode(f.File+":"+strconv.Itoa(f.Line)) + " |\n")
		}
		b.WriteString("\n")
		seen := map[string]bool{}
		for _, f := range a.Findings {
			if seen[f.Rule] {
				continue
			}
			seen[f.Rule] = true
			title, guide, fix := ruleGuidance(f.Rule)
			b.WriteString("### " + f.Rule + ": " + title + "\n\nGuide " + guide + ". **Fix:** " + fix + "\n\n")
		}
	}

	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")
	}

	b.WriteString("## History\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 = diffRules(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()
}

// 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 ""
}

// diffRules describes which rules appeared or were resolved between scans.
func diffRules(prev, next []Finding) string {
	had, has := map[string]bool{}, map[string]bool{}
	for _, f := range prev {
		had[f.Rule] = true
	}
	for _, f := range next {
		has[f.Rule] = true
	}
	var parts []string
	for _, f := range prev {
		if !has[f.Rule] {
			parts = append(parts, f.Rule+" resolved")
			has[f.Rule] = true // report once
		}
	}
	for _, f := range next {
		if !had[f.Rule] {
			parts = append(parts, f.Rule+" new")
			had[f.Rule] = true
		}
	}
	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)
}

// ruleGuidance is the fix guidance, written once per rule.
func ruleGuidance(rule string) (title, guide, fix string) {
	switch rule {
	case "B01":
		return "getter returns a pointer into state", "§5.1, §5.1a",
			"return copies or plain values, never a pointer into package state, and keep mutating methods unexported."
	case "B05":
		return "IsUser() guards an OriginSend payment", "§5.5",
			"use `cur.Previous().IsUserCall()` with the `OriginSend()` amount check; `IsUser()` also accepts `maketx run` callers that keep the coins."
	case "B03":
		return "caller-supplied callback under the realm's authority", "§3C, §5.3",
			"never invoke a caller-supplied function or interface while holding this realm's authority."
	case "B09":
		return "external Teller used without IsCanonicalTeller", "§5.4",
			"check `grc20.IsCanonicalTeller(t)` before calling a Teller passed in by a caller."
	}
	return "see the full report", "", "see the full report."
}

requests.gno

package bouncer

import (
	"chain"
	"chain/runtime"

	"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
}

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)
}