|
| 1 | +package database |
| 2 | + |
| 3 | +import ( |
| 4 | + "archive/zip" |
| 5 | + "bytes" |
| 6 | + "context" |
| 7 | + "crypto/sha256" |
| 8 | + "encoding/csv" |
| 9 | + "encoding/json" |
| 10 | + "errors" |
| 11 | + "fmt" |
| 12 | + "io" |
| 13 | + "net/http" |
| 14 | + "os" |
| 15 | + "path/filepath" |
| 16 | + "strings" |
| 17 | + "time" |
| 18 | +) |
| 19 | + |
| 20 | +type SmartDB struct { |
| 21 | + // memDB |
| 22 | + DirDB |
| 23 | + |
| 24 | + name string |
| 25 | + identifier string |
| 26 | + ArchiveURL string |
| 27 | + WorkingDirectory string |
| 28 | + Offline bool |
| 29 | + UpdatedAt string |
| 30 | +} |
| 31 | + |
| 32 | +func (db *SmartDB) Name() string { return db.name } |
| 33 | +func (db *SmartDB) Identifier() string { return db.identifier } |
| 34 | + |
| 35 | +func (db *SmartDB) cachePath() string { |
| 36 | + hash := sha256.Sum256([]byte(db.ArchiveURL)) |
| 37 | + fileName := fmt.Sprintf("osv-detector-%x-db", hash) |
| 38 | + |
| 39 | + return filepath.Join(os.TempDir(), fileName) |
| 40 | +} |
| 41 | + |
| 42 | +func (db *SmartDB) cacheFile(name string, content []byte) error { |
| 43 | + //nolint:gosec // being world readable is fine |
| 44 | + return os.WriteFile(filepath.Join(db.cachePath(), name), content, 0644) |
| 45 | +} |
| 46 | + |
| 47 | +func (db *SmartDB) loadLastModified() (time.Time, error) { |
| 48 | + b, err := os.ReadFile(filepath.Join(db.cachePath(), "last_modified")) |
| 49 | + |
| 50 | + if err != nil { |
| 51 | + return time.Time{}, err |
| 52 | + } |
| 53 | + |
| 54 | + tim, err := time.Parse(time.RFC3339, string(b)) |
| 55 | + |
| 56 | + if err != nil { |
| 57 | + return time.Time{}, err |
| 58 | + } |
| 59 | + |
| 60 | + return tim, nil |
| 61 | +} |
| 62 | + |
| 63 | +func (db *SmartDB) updateLastModified(lastModified time.Time) error { |
| 64 | + db.UpdatedAt = lastModified.Format(http.TimeFormat) |
| 65 | + |
| 66 | + return db.cacheFile("last_modified", []byte(lastModified.Format(time.RFC3339))) |
| 67 | +} |
| 68 | + |
| 69 | +func (db *SmartDB) writeZipFile(zipFile *zip.File) error { |
| 70 | + dst, err := os.OpenFile(filepath.Join(db.cachePath(), zipFile.Name), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, zipFile.Mode()) |
| 71 | + if err != nil { |
| 72 | + return err |
| 73 | + } |
| 74 | + |
| 75 | + defer dst.Close() |
| 76 | + |
| 77 | + z, err := zipFile.Open() |
| 78 | + if err != nil { |
| 79 | + return err |
| 80 | + } |
| 81 | + |
| 82 | + defer z.Close() |
| 83 | + |
| 84 | + _, err = io.Copy(dst, z) |
| 85 | + |
| 86 | + return err |
| 87 | +} |
| 88 | + |
| 89 | +func (db *SmartDB) populateFromZip() error { |
| 90 | + err := os.MkdirAll(db.cachePath(), 0744) |
| 91 | + |
| 92 | + if err != nil { |
| 93 | + return err |
| 94 | + } |
| 95 | + |
| 96 | + zdb := &ZipDB{ |
| 97 | + name: db.name, |
| 98 | + ArchiveURL: db.ArchiveURL, |
| 99 | + WorkingDirectory: db.WorkingDirectory, |
| 100 | + Offline: db.Offline, |
| 101 | + } |
| 102 | + |
| 103 | + body, err := zdb.fetchZip() |
| 104 | + |
| 105 | + if err != nil { |
| 106 | + return err |
| 107 | + } |
| 108 | + |
| 109 | + zipReader, err := zip.NewReader(bytes.NewReader(body), int64(len(body))) |
| 110 | + if err != nil { |
| 111 | + return fmt.Errorf("could not read OSV database archive: %w", err) |
| 112 | + } |
| 113 | + |
| 114 | + // Read each file from the archive and write it to the db directory |
| 115 | + for _, zipFile := range zipReader.File { |
| 116 | + if !strings.HasPrefix(zipFile.Name, db.WorkingDirectory) { |
| 117 | + continue |
| 118 | + } |
| 119 | + |
| 120 | + if !strings.HasSuffix(zipFile.Name, ".json") { |
| 121 | + continue |
| 122 | + } |
| 123 | + |
| 124 | + err = db.writeZipFile(zipFile) |
| 125 | + |
| 126 | + if err != nil { |
| 127 | + return err |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + return nil |
| 132 | +} |
| 133 | + |
| 134 | +type modifiedIDRow struct { |
| 135 | + id string |
| 136 | + modified time.Time |
| 137 | +} |
| 138 | + |
| 139 | +func parseModifiedIDRow(columns []string) (*modifiedIDRow, error) { |
| 140 | + modified, err := time.Parse(time.RFC3339, columns[0]) |
| 141 | + |
| 142 | + if err != nil { |
| 143 | + return nil, err |
| 144 | + } |
| 145 | + |
| 146 | + return &modifiedIDRow{id: columns[1], modified: modified}, nil |
| 147 | +} |
| 148 | + |
| 149 | +func (db *SmartDB) fetchModifiedIDs(since time.Time) ([]modifiedIDRow, error) { |
| 150 | + url := strings.TrimSuffix(db.ArchiveURL, "/all.zip") + "/modified_id.csv" |
| 151 | + |
| 152 | + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil) |
| 153 | + if err != nil { |
| 154 | + return nil, err |
| 155 | + } |
| 156 | + |
| 157 | + resp, err := http.DefaultClient.Do(req) |
| 158 | + if err != nil { |
| 159 | + return nil, err |
| 160 | + } |
| 161 | + |
| 162 | + defer resp.Body.Close() |
| 163 | + |
| 164 | + if resp.StatusCode != http.StatusOK { |
| 165 | + return nil, fmt.Errorf("%w (%s)", ErrUnexpectedStatusCode, resp.Status) |
| 166 | + } |
| 167 | + |
| 168 | + i := 0 |
| 169 | + r := csv.NewReader(resp.Body) |
| 170 | + |
| 171 | + var rows []modifiedIDRow |
| 172 | + |
| 173 | + for { |
| 174 | + i++ |
| 175 | + record, err := r.Read() |
| 176 | + if errors.Is(err, io.EOF) { |
| 177 | + break |
| 178 | + } |
| 179 | + if err != nil { |
| 180 | + return nil, fmt.Errorf("%w", err) |
| 181 | + } |
| 182 | + |
| 183 | + row, err := parseModifiedIDRow(record) |
| 184 | + if err != nil { |
| 185 | + return nil, fmt.Errorf("row %d: %w", i, err) |
| 186 | + } |
| 187 | + |
| 188 | + // the modified ids are sorted in reverse chronological order so once we hit |
| 189 | + // a row that was modified before our "since" time, we can stop completely |
| 190 | + if row.modified.Before(since) { |
| 191 | + break |
| 192 | + } |
| 193 | + |
| 194 | + rows = append(rows, *row) |
| 195 | + } |
| 196 | + |
| 197 | + return rows, nil |
| 198 | +} |
| 199 | + |
| 200 | +func (db *SmartDB) updateAdvisory(id string) error { |
| 201 | + url := fmt.Sprintf("%s/%s.json", strings.TrimSuffix(db.ArchiveURL, "/all.zip"), id) |
| 202 | + |
| 203 | + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil) |
| 204 | + if err != nil { |
| 205 | + return err |
| 206 | + } |
| 207 | + |
| 208 | + resp, err := http.DefaultClient.Do(req) |
| 209 | + if err != nil { |
| 210 | + return err |
| 211 | + } |
| 212 | + |
| 213 | + defer resp.Body.Close() |
| 214 | + |
| 215 | + if resp.StatusCode != http.StatusOK { |
| 216 | + return fmt.Errorf("%w (%s)", ErrUnexpectedStatusCode, resp.Status) |
| 217 | + } |
| 218 | + |
| 219 | + var body []byte |
| 220 | + |
| 221 | + body, err = io.ReadAll(resp.Body) |
| 222 | + |
| 223 | + if err != nil { |
| 224 | + return err |
| 225 | + } |
| 226 | + |
| 227 | + content, err := json.Marshal(body) |
| 228 | + |
| 229 | + if err == nil { |
| 230 | + err = db.cacheFile(id+".json", content) |
| 231 | + } |
| 232 | + |
| 233 | + return err |
| 234 | +} |
| 235 | + |
| 236 | +func (db *SmartDB) updateModifiedAdvisories(since time.Time) error { |
| 237 | + modifiedIDs, err := db.fetchModifiedIDs(since) |
| 238 | + |
| 239 | + if err != nil { |
| 240 | + return err |
| 241 | + } |
| 242 | + |
| 243 | + for _, row := range modifiedIDs { |
| 244 | + // fmt.Printf("updating %s\n", row.id) |
| 245 | + err = db.updateAdvisory(row.id) |
| 246 | + |
| 247 | + if err != nil { |
| 248 | + return err |
| 249 | + } |
| 250 | + } |
| 251 | + |
| 252 | + return nil |
| 253 | +} |
| 254 | + |
| 255 | +// load fetches a zip archive of the OSV database and loads known vulnerabilities |
| 256 | +// from it (which are assumed to be in json files following the OSV spec). |
| 257 | +// |
| 258 | +// Internally, the archive is cached along with the date that it was fetched |
| 259 | +// so that a new version of the archive is only downloaded if it has been |
| 260 | +// modified, per HTTP caching standards. |
| 261 | +func (db *SmartDB) load() error { |
| 262 | + lastModified, err := db.loadLastModified() |
| 263 | + |
| 264 | + // (re)initialize the database using the zip file |
| 265 | + if err != nil { |
| 266 | + err = db.populateFromZip() |
| 267 | + |
| 268 | + if err != nil { |
| 269 | + return err |
| 270 | + } |
| 271 | + |
| 272 | + // update the last modified time to now |
| 273 | + lastModified = time.Now() |
| 274 | + } |
| 275 | + |
| 276 | + // update any advisories that have changed since the last modified timestamp |
| 277 | + err = db.updateModifiedAdvisories(lastModified) |
| 278 | + if err != nil { |
| 279 | + return err |
| 280 | + } |
| 281 | + |
| 282 | + if err = db.updateLastModified(lastModified); err != nil { |
| 283 | + return err |
| 284 | + } |
| 285 | + |
| 286 | + db.DirDB = DirDB{ |
| 287 | + name: db.name, |
| 288 | + LocalPath: "file:///" + db.cachePath(), |
| 289 | + WorkingDirectory: "", |
| 290 | + Offline: db.Offline, |
| 291 | + } |
| 292 | + |
| 293 | + return db.DirDB.load() |
| 294 | +} |
| 295 | + |
| 296 | +func NewSmartDB(config Config, offline bool) (*SmartDB, error) { |
| 297 | + db := &SmartDB{ |
| 298 | + name: config.Name, |
| 299 | + identifier: config.Identifier(), |
| 300 | + ArchiveURL: config.URL, |
| 301 | + WorkingDirectory: config.WorkingDirectory, |
| 302 | + Offline: offline, |
| 303 | + } |
| 304 | + if err := db.load(); err != nil { |
| 305 | + return nil, fmt.Errorf("unable to fetch OSV database: %w", err) |
| 306 | + } |
| 307 | + |
| 308 | + return db, nil |
| 309 | +} |
0 commit comments