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.94 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. Score, grade and verdict are computed here from the findings and
 77// dependency counts.
 78func Attest(cur realm, pkgpath, sourceHash, scannerVersion, rulesetHash, toolchain, reportHash, reportURI, findings string, directAtRisk, indirectAtRisk, unverified int) uint64 {
 79	attester := assertAttester(cur)
 80	if !validPkgPath(pkgpath) {
 81		panic("invalid package path")
 82	}
 83	for _, h := range []string{sourceHash, rulesetHash, reportHash} {
 84		if !isHex64(h) {
 85			panic("hashes must be 64 lowercase hex characters")
 86		}
 87	}
 88	if !isToken(scannerVersion) || !isToken(toolchain) {
 89		panic("invalid scanner or toolchain version")
 90	}
 91	if !validReportURI(reportURI) {
 92		panic("report URI must be ipfs://<cid> or an https:// URL")
 93	}
 94	if directAtRisk < 0 || indirectAtRisk < 0 || unverified < 0 || directAtRisk+indirectAtRisk+unverified > 1000 {
 95		panic("invalid dependency counts")
 96	}
 97	fs := parseFindings(findings)
 98	deps := Deps{DirectAtRisk: directAtRisk, IndirectAtRisk: indirectAtRisk, Unverified: unverified}
 99	score, grade, verdict := ScoreFor(fs, deps)
100
101	rec := getRecord(pkgpath)
102	if rec == nil {
103		rec = &record{}
104		records.Set(pkgpath, rec)
105		if author, ok := authorOf(pkgpath); ok {
106			addToAuthor(author, pkgpath)
107		}
108		addToFamily(pkgpath)
109	} else {
110		if len(rec.history) >= maxHistory {
111			panic("attestation history is full for this package")
112		}
113		prev := rec.history[len(rec.history)-1]
114		totalFindings -= len(prev.Findings)
115		totalProven -= countProven(prev.Findings)
116	}
117	id := uint64(attestationID.Next())
118	rec.history = append(rec.history, Attestation{
119		ID:             id,
120		PkgPath:        pkgpath,
121		SourceHash:     sourceHash,
122		ScannerVersion: scannerVersion,
123		RulesetHash:    rulesetHash,
124		Toolchain:      toolchain,
125		ReportHash:     reportHash,
126		ReportURI:      reportURI,
127		Findings:       fs,
128		Deps:           deps,
129		Score:          score,
130		Grade:          grade,
131		Verdict:        verdict,
132		Attester:       attester,
133		Height:         runtime.ChainHeight(),
134		Time:           time.Now().Unix(),
135	})
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}