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.

attest.gno

6.82 Kb · 280 lines
  1package bouncer
  2
  3import (
  4	"chain"
  5	"chain/runtime"
  6	"strconv"
  7	"strings"
  8	"time"
  9
 10	"gno.land/p/nt/avl/v0"
 11	"gno.land/p/nt/seqid/v0"
 12)
 13
 14// Finding is one attested finding.
 15type Finding struct {
 16	Rule     string // B01 ...
 17	Severity string // critical, high, medium
 18	Label    string // PROVEN, NOT REPRODUCED, STATIC WARNING
 19	File     string
 20	Line     int
 21}
 22
 23// Attestation is a scan result posted by an attester.
 24type Attestation struct {
 25	ID             uint64
 26	PkgPath        string
 27	SourceHash     string // sha256 of the scanned source, hex
 28	ScannerVersion string
 29	RulesetHash    string // hex
 30	Toolchain      string // gno version the exploits ran on
 31	ReportHash     string // sha256 of the full JSON report, hex
 32	ReportURI      string // where the full report lives (ipfs:// or https://)
 33	Findings       []Finding
 34	Deps           Deps
 35	Score          int
 36	Grade          string
 37	Verdict        string
 38	Attester       address
 39	Height         int64
 40	Time           int64 // unix seconds, block time
 41}
 42
 43// AuthorReply is an author's response to a Passport.
 44type AuthorReply struct {
 45	Author    address
 46	Note      string
 47	Successor string // pkgpath of the fixed version, if any
 48	Height    int64
 49}
 50
 51// record holds everything known about one package.
 52type record struct {
 53	history []Attestation // oldest first
 54	replies []AuthorReply
 55}
 56
 57const (
 58	maxFindings = 64
 59	maxHistory  = 50
 60	maxReplies  = 20
 61	maxNoteLen  = 280
 62	maxRecent   = 10
 63)
 64
 65// Attest records a scan result for pkgpath. Attesters only. findings is a
 66// ";"-separated list of "RULE,severity,LABEL,file,line" entries ("" for
 67// none). Score, grade and verdict are computed here from the findings and
 68// dependency counts.
 69func Attest(cur realm, pkgpath, sourceHash, scannerVersion, rulesetHash, toolchain, reportHash, reportURI, findings string, directAtRisk, indirectAtRisk, unverified int) uint64 {
 70	attester := assertAttester(cur)
 71	if !validPkgPath(pkgpath) {
 72		panic("invalid package path")
 73	}
 74	for _, h := range []string{sourceHash, rulesetHash, reportHash} {
 75		if !isHex64(h) {
 76			panic("hashes must be 64 lowercase hex characters")
 77		}
 78	}
 79	if !isToken(scannerVersion) || !isToken(toolchain) {
 80		panic("invalid scanner or toolchain version")
 81	}
 82	if !validReportURI(reportURI) {
 83		panic("report URI must be ipfs://<cid> or an https:// URL")
 84	}
 85	if directAtRisk < 0 || indirectAtRisk < 0 || unverified < 0 || directAtRisk+indirectAtRisk+unverified > 1000 {
 86		panic("invalid dependency counts")
 87	}
 88	fs := parseFindings(findings)
 89	deps := Deps{DirectAtRisk: directAtRisk, IndirectAtRisk: indirectAtRisk, Unverified: unverified}
 90	score, grade, verdict := ScoreFor(fs, deps)
 91
 92	rec := getRecord(pkgpath)
 93	if rec == nil {
 94		rec = &record{}
 95		records.Set(pkgpath, rec)
 96		if author, ok := authorOf(pkgpath); ok {
 97			addToAuthor(author, pkgpath)
 98		}
 99	} else {
100		if len(rec.history) >= maxHistory {
101			panic("attestation history is full for this package")
102		}
103		prev := rec.history[len(rec.history)-1]
104		totalFindings -= len(prev.Findings)
105		totalProven -= countProven(prev.Findings)
106	}
107	id := uint64(attestationID.Next())
108	rec.history = append(rec.history, Attestation{
109		ID:             id,
110		PkgPath:        pkgpath,
111		SourceHash:     sourceHash,
112		ScannerVersion: scannerVersion,
113		RulesetHash:    rulesetHash,
114		Toolchain:      toolchain,
115		ReportHash:     reportHash,
116		ReportURI:      reportURI,
117		Findings:       fs,
118		Deps:           deps,
119		Score:          score,
120		Grade:          grade,
121		Verdict:        verdict,
122		Attester:       attester,
123		Height:         runtime.ChainHeight(),
124		Time:           time.Now().Unix(),
125	})
126	totalFindings += len(fs)
127	totalProven += countProven(fs)
128	markRecent(pkgpath)
129	closeRequestsFor(pkgpath)
130	chain.Emit("Attested",
131		"id", seqid.ID(id).String(),
132		"pkgpath", pkgpath,
133		"score", strconv.Itoa(score),
134		"grade", grade,
135		"verdict", verdict,
136		"report_hash", reportHash,
137		"attester", attester.String())
138	return id
139}
140
141func getRecord(pkgpath string) *record {
142	v := records.Get(pkgpath)
143	if v == nil {
144		return nil
145	}
146	return v.(*record)
147}
148
149func addToAuthor(author address, pkgpath string) {
150	var t *avl.Tree
151	if v := byAuthor.Get(string(author)); v != nil {
152		t = v.(*avl.Tree)
153	} else {
154		t = avl.NewTree()
155		byAuthor.Set(string(author), t)
156	}
157	t.Set(pkgpath, true)
158}
159
160func markRecent(pkgpath string) {
161	next := []string{pkgpath}
162	for _, p := range recent {
163		if p != pkgpath && len(next) < maxRecent {
164			next = append(next, p)
165		}
166	}
167	recent = next
168}
169
170func countProven(fs []Finding) int {
171	n := 0
172	for _, f := range fs {
173		if f.Label == LabelProven {
174			n++
175		}
176	}
177	return n
178}
179
180// parseFindings validates and decodes the findings argument.
181func parseFindings(s string) []Finding {
182	out := []Finding{}
183	if s == "" {
184		return out
185	}
186	entries := strings.Split(s, ";")
187	if len(entries) > maxFindings {
188		panic("too many findings")
189	}
190	for _, e := range entries {
191		parts := strings.Split(e, ",")
192		if len(parts) != 5 {
193			panic("finding must be RULE,severity,LABEL,file,line: " + e)
194		}
195		f := Finding{Rule: parts[0], Severity: parts[1], Label: parts[2], File: parts[3]}
196		if !isRuleID(f.Rule) {
197			panic("invalid rule id: " + f.Rule)
198		}
199		switch f.Severity {
200		case SeverityCritical, SeverityHigh, SeverityMedium:
201		default:
202			panic("invalid severity: " + f.Severity)
203		}
204		switch f.Label {
205		case LabelProven, LabelNotReproduced, LabelStaticWarning:
206		default:
207			panic("invalid label: " + f.Label)
208		}
209		if !isGnoFile(f.File) {
210			panic("invalid file name: " + f.File)
211		}
212		line, err := strconv.Atoi(parts[4])
213		if err != nil || line < 1 || line > 1000000 {
214			panic("invalid line: " + parts[4])
215		}
216		f.Line = line
217		out = append(out, f)
218	}
219	return out
220}
221
222func isRuleID(s string) bool {
223	return len(s) == 3 && s[0] == 'B' && s[1] >= '0' && s[1] <= '9' && s[2] >= '0' && s[2] <= '9'
224}
225
226func isGnoFile(s string) bool {
227	if len(s) > 64 || !strings.HasSuffix(s, ".gno") || len(s) == len(".gno") {
228		return false
229	}
230	for _, c := range s {
231		if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_' || c == '.') {
232			return false
233		}
234	}
235	return true
236}
237
238func isHex64(s string) bool {
239	if len(s) != 64 {
240		return false
241	}
242	for _, c := range s {
243		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
244			return false
245		}
246	}
247	return true
248}
249
250// isToken accepts short version strings such as "0.1.0" or "master.1+f0f9c70".
251func isToken(s string) bool {
252	if s == "" || len(s) > 64 {
253		return false
254	}
255	for _, c := range s {
256		if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune(".+-_", c)) {
257			return false
258		}
259	}
260	return true
261}
262
263func validReportURI(s string) bool {
264	if len(s) > 200 {
265		return false
266	}
267	rest, ok := strings.CutPrefix(s, "ipfs://")
268	if !ok {
269		rest, ok = strings.CutPrefix(s, "https://")
270	}
271	if !ok || rest == "" {
272		return false
273	}
274	for _, c := range rest {
275		if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("./-_~", c)) {
276			return false
277		}
278	}
279	return true
280}