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

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