From 92ebc7e4d72424c17d93c54e5f24891710c85a60 Mon Sep 17 00:00:00 2001 From: tom1299 Date: Fri, 26 Sep 2025 09:35:03 +0200 Subject: [PATCH] fix(db): Dowload database when missing but metadata still exists (#9393) Co-authored-by: DmitriyLewen --- pkg/db/db.go | 17 +++++++++++------ pkg/db/db_test.go | 13 +++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/pkg/db/db.go b/pkg/db/db.go index 1b6ce90959..906fd3fb73 100644 --- a/pkg/db/db.go +++ b/pkg/db/db.go @@ -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", diff --git a/pkg/db/db_test.go b/pkg/db/db_test.go index 4fcf01ab25..04f78449a7 100644 --- a/pkg/db/db_test.go +++ b/pkg/db/db_test.go @@ -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 {