internal/store/security.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/store/security.go

209 lines · 6210 bytes

15 symbols in this file
  1package store
  2
  3import (
  4	"database/sql"
  5	"errors"
  6)
  7
  8// SecurityScan is a repo's code scanning state. A row exists only while
  9// scanning is enabled.
 10type SecurityScan struct {
 11	RepoID      int64
 12	NextRun     string
 13	LastResults string // when results were last uploaded, '' for never
 14	IssueNumber int64
 15	Aside       string // what the last scan set aside, as JSON
 16}
 17
 18// SecurityFinding is one result from a scan, as last reported.
 19type SecurityFinding struct {
 20	Fingerprint string
 21	Tool        string
 22	Rule        string
 23	Level       string
 24	Path        string
 25	Line        int
 26	Message     string
 27}
 28
 29func (s *Store) EnableSecurityScan(repoID int64, nextRun string) error {
 30	_, err := s.DB.Exec("INSERT OR IGNORE INTO security_scans (repo_id, next_run) VALUES (?, ?)", repoID, nextRun)
 31	return err
 32}
 33
 34// DisableSecurityScan stops scanning and forgets what was reported.
 35func (s *Store) DisableSecurityScan(repoID int64) error {
 36	tx, err := s.DB.Begin()
 37	if err != nil {
 38		return err
 39	}
 40	defer tx.Rollback()
 41	if _, err := tx.Exec("DELETE FROM security_findings WHERE repo_id = ?", repoID); err != nil {
 42		return err
 43	}
 44	if _, err := tx.Exec("DELETE FROM security_scans WHERE repo_id = ?", repoID); err != nil {
 45		return err
 46	}
 47	return tx.Commit()
 48}
 49
 50func (s *Store) SecurityScanFor(repoID int64) (SecurityScan, error) {
 51	var sc SecurityScan
 52	err := s.DB.QueryRow(
 53		"SELECT repo_id, next_run, last_results, issue_number, aside FROM security_scans WHERE repo_id = ?", repoID).
 54		Scan(&sc.RepoID, &sc.NextRun, &sc.LastResults, &sc.IssueNumber, &sc.Aside)
 55	if errors.Is(err, sql.ErrNoRows) {
 56		return sc, ErrNotFound
 57	}
 58	return sc, err
 59}
 60
 61// DueSecurityScans returns the repos whose next scan is at or before now.
 62// Archived repos are skipped: nobody is going to act on the findings.
 63func (s *Store) DueSecurityScans(nowISO string) ([]Repo, error) {
 64	rows, err := s.DB.Query(repoSelect+`
 65		JOIN security_scans sc ON sc.repo_id = r.id
 66		WHERE sc.next_run <= ?
 67		ORDER BY sc.next_run, r.id`, nowISO)
 68	if err != nil {
 69		return nil, err
 70	}
 71	defer rows.Close()
 72	var out []Repo
 73	for rows.Next() {
 74		r, err := scanRepo(rows)
 75		if err != nil {
 76			return nil, err
 77		}
 78		if r.Settings.Archived {
 79			continue
 80		}
 81		out = append(out, r)
 82	}
 83	return out, rows.Err()
 84}
 85
 86func (s *Store) SetSecurityNext(repoID int64, nextRun string) error {
 87	_, err := s.DB.Exec("UPDATE security_scans SET next_run = ? WHERE repo_id = ?", nextRun, repoID)
 88	return err
 89}
 90
 91func (s *Store) SetSecurityIssue(repoID, number int64) error {
 92	_, err := s.DB.Exec("UPDATE security_scans SET issue_number = ? WHERE repo_id = ?", number, repoID)
 93	return err
 94}
 95
 96func (s *Store) ReportedFindings(repoID int64) ([]SecurityFinding, error) {
 97	rows, err := s.DB.Query(`
 98		SELECT fingerprint, tool, rule, level, path, line, message FROM security_findings
 99		WHERE repo_id = ? ORDER BY fingerprint`, repoID)
100	if err != nil {
101		return nil, err
102	}
103	defer rows.Close()
104	var out []SecurityFinding
105	for rows.Next() {
106		var f SecurityFinding
107		if err := rows.Scan(&f.Fingerprint, &f.Tool, &f.Rule, &f.Level, &f.Path, &f.Line, &f.Message); err != nil {
108			return nil, err
109		}
110		out = append(out, f)
111	}
112	return out, rows.Err()
113}
114
115// ReplaceFindings swaps in an upload's findings wholesale, with what it set
116// aside.
117func (s *Store) ReplaceFindings(repoID int64, findings []SecurityFinding, aside string) error {
118	tx, err := s.DB.Begin()
119	if err != nil {
120		return err
121	}
122	defer tx.Rollback()
123	if _, err := tx.Exec("UPDATE security_scans SET aside = ? WHERE repo_id = ?", aside, repoID); err != nil {
124		return err
125	}
126	if _, err := tx.Exec("DELETE FROM security_findings WHERE repo_id = ?", repoID); err != nil {
127		return err
128	}
129	for _, f := range findings {
130		if _, err := tx.Exec(`
131			INSERT OR IGNORE INTO security_findings (repo_id, fingerprint, tool, rule, level, path, line, message)
132			VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
133			repoID, f.Fingerprint, f.Tool, f.Rule, f.Level, f.Path, f.Line, f.Message); err != nil {
134			return err
135		}
136	}
137	return tx.Commit()
138}
139
140// StampSecurityResults records that a scan's results arrived.
141func (s *Store) StampSecurityResults(repoID int64) error {
142	_, err := s.DB.Exec(`UPDATE security_scans SET last_results = strftime('%Y-%m-%dT%H:%M:%fZ','now')
143		WHERE repo_id = ?`, repoID)
144	return err
145}
146
147// SecurityDismissal is a finding a repository dismissed.
148type SecurityDismissal struct {
149	Fingerprint string
150	Reason      string
151	By          string // username, '' once the account is gone
152	CreatedAt   string
153}
154
155// DismissFindings dismisses findings by fingerprint, replacing the reason
156// of any already dismissed.
157func (s *Store) DismissFindings(repoID, byID int64, fingerprints []string, reason string) error {
158	tx, err := s.DB.Begin()
159	if err != nil {
160		return err
161	}
162	defer tx.Rollback()
163	for _, fp := range fingerprints {
164		if _, err := tx.Exec(`
165			INSERT INTO security_dismissals (repo_id, fingerprint, reason, by_id) VALUES (?, ?, ?, ?)
166			ON CONFLICT (repo_id, fingerprint) DO UPDATE SET reason = excluded.reason, by_id = excluded.by_id,
167				created_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`,
168			repoID, fp, reason, byID); err != nil {
169			return err
170		}
171	}
172	return tx.Commit()
173}
174
175// ReopenFindings takes dismissals back.
176func (s *Store) ReopenFindings(repoID int64, fingerprints []string) error {
177	tx, err := s.DB.Begin()
178	if err != nil {
179		return err
180	}
181	defer tx.Rollback()
182	for _, fp := range fingerprints {
183		if _, err := tx.Exec("DELETE FROM security_dismissals WHERE repo_id = ? AND fingerprint = ?", repoID, fp); err != nil {
184			return err
185		}
186	}
187	return tx.Commit()
188}
189
190// SecurityDismissals returns a repo's dismissals by fingerprint.
191func (s *Store) SecurityDismissals(repoID int64) (map[string]SecurityDismissal, error) {
192	rows, err := s.DB.Query(`
193		SELECT d.fingerprint, d.reason, COALESCE(u.username, ''), d.created_at
194		FROM security_dismissals d LEFT JOIN users u ON u.id = d.by_id
195		WHERE d.repo_id = ?`, repoID)
196	if err != nil {
197		return nil, err
198	}
199	defer rows.Close()
200	out := map[string]SecurityDismissal{}
201	for rows.Next() {
202		var d SecurityDismissal
203		if err := rows.Scan(&d.Fingerprint, &d.Reason, &d.By, &d.CreatedAt); err != nil {
204			return nil, err
205		}
206		out[d.Fingerprint] = d
207	}
208	return out, rows.Err()
209}