fix(db): Dowload database when missing but metadata still exists (#9393)

Co-authored-by: DmitriyLewen <dmitriy.lewen@smartforce.io>
This commit is contained in:
tom1299
2025-09-26 09:35:03 +02:00
committed by GitHub
parent 42b3bf37bb
commit 92ebc7e4d7
2 changed files with 24 additions and 6 deletions

View File

@@ -110,21 +110,26 @@ func (c *Client) NeedsUpdate(ctx context.Context, cliVersion string, skip bool)
meta = metadata.Metadata{Version: db.SchemaVersion}
}
// We can't use the DB if either `trivy.db` or `metadata.json` is missing.
// In that case, we need to download the DB.
if noRequiredFiles {
if skip {
log.ErrorContext(ctx, "The first run cannot skip downloading DB")
return false, xerrors.New("--skip-db-update cannot be specified on the first run")
}
return true, nil
}
// There are 3 cases when DownloadAt field is zero:
// - metadata file was not created yet. This is the first run of Trivy.
// - trivy-db was downloaded with `oras`. In this case user can use `--skip-db-update` (like for air-gapped) or re-download trivy-db.
// - trivy-db was corrupted while copying from tmp directory to cache directory. We should update this trivy-db.
// We can't detect these cases, so we will show warning for users who use oras + air-gapped.
if !noRequiredFiles && meta.DownloadedAt.IsZero() && !skip {
if meta.DownloadedAt.IsZero() && !skip {
log.WarnContext(ctx, "Trivy DB may be corrupted and will be re-downloaded. If you manually downloaded DB - use the `--skip-db-update` flag to skip updating DB.")
return true, nil
}
if skip && noRequiredFiles {
log.ErrorContext(ctx, "The first run cannot skip downloading DB")
return false, xerrors.New("--skip-db-update cannot be specified on the first run")
}
if db.SchemaVersion < meta.Version {
log.ErrorContext(ctx, "Trivy version is old. Update to the latest version.", log.String("version", cliVersion))
return false, xerrors.Errorf("the version of DB schema doesn't match. Local DB: %d, Expected: %d",

View File

@@ -219,6 +219,19 @@ func TestClient_NeedsUpdate(t *testing.T) {
"The local DB has an old schema version which is not supported by the current version of Trivy CLI. DB needs to be updated.",
},
},
{
name: "trivy.db is missing but metadata with recent DownloadedAt",
dbFileExists: false,
metadata: metadata.Metadata{
Version: db.SchemaVersion,
NextUpdate: timeNextUpdateDay1,
DownloadedAt: time.Date(2019, 9, 30, 23, 30, 0, 0, time.UTC),
},
want: true,
wantLogs: []string{
"There is no db file",
},
},
}
for _, tt := range tests {