forked from toolshed/abra
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9b712d23b8 | ||
|
|
d19f174e2a | ||
|
|
f5af00ae4c | ||
|
|
371b5aadb7 | ||
|
|
bb75ff4136 | ||
|
|
82564ded64 | ||
|
|
b0aa0470f5 | ||
|
|
527d2a6a86 | ||
|
|
e44ac846cf | ||
|
|
cef4dc2e17 | ||
|
|
5c4ffaf279 |
+6
-1
@@ -13,6 +13,7 @@ Releases are tags on the `c4dt` branch, named `<upstream version>-c4dt.<n>`, e.g
|
||||
| [Digest pinning](#digest-pinning) | Recipes can pin images to a digest; `abra recipe upgrade` keeps the pin up to date |
|
||||
| [`abra audit`](#abra-audit) | Checks all deployed apps against reviewed advisories and suggests fixes that are verified to exist |
|
||||
| [Type remote](#type-remote) | Recipes can come from any git URL, and be pinned to a branch, in `RECIPE=` |
|
||||
| [Tables without a terminal](#tables-without-a-terminal) | Table output works in pipes and cron jobs instead of failing |
|
||||
| [Devbox](#devbox) | `devbox.json` with the toolchain, and `build` and `test` scripts |
|
||||
|
||||
## Details
|
||||
@@ -23,12 +24,16 @@ Some upstream images, such as `nextcloud`, are rebuilt under the same tag, so th
|
||||
|
||||
### `abra audit`
|
||||
|
||||
`abra audit` checks every deployed app on every server against the reviewed advisories in [`c4dt/advisories`](https://git.coopcloud.tech/c4dt/advisories), which it pulls on every run. It reads the recipe version and the image digests from each service spec, and the image configs (build time, environment such as `PHP_VERSION`, version labels) from the server's Docker daemon, or from the registry for the server's platform. Advisories match by recipe version range, environment version range, image version, build time, and known-good or known-bad digests. Before suggesting a fix, the audit checks that it works: a redeploy is only suggested if the tag's current image is fixed, and a recipe upgrade names the oldest release whose images are fixed. If no release fixes the problem yet, it says so and warns; recipe repositories are only read from their release tags, so local checkouts are never changed. The output is a short numbered table of failing apps followed by a numbered list of fixes, and the exit code is 1 when anything fails. Unlike the rest of abra, the audit needs an explicitly chosen abra directory (`$ABRA_DIR` or `abraDir` in `abra.yaml`) and never falls back to `~/.abra`. The design, including the planned later versions, is in [`doc/DesignAudit.md`](doc/DesignAudit.md). Commits `e07454ec`, `d699e51c`, `165a81de`, `491ea47f`, `d6912414`, `6fc26afa`.
|
||||
`abra audit` checks every deployed app on every server against the reviewed advisories in [`c4dt/advisories`](https://git.coopcloud.tech/c4dt/advisories), which it pulls on every run. It reads the recipe version and the image digests from each service spec, and the image configs (build time, environment such as `PHP_VERSION`, version labels) from the server's Docker daemon, or from the registry for the server's platform. Advisories match by recipe version range, environment version range, image version, build time, and known-good or known-bad digests. Before suggesting a fix, the audit checks that it works: a redeploy is only suggested if the tag's current image is fixed, and a recipe upgrade names the oldest release whose images are fixed. If no release fixes the problem yet, it says so and warns; recipe repositories are only read from their release tags, so local checkouts are never changed. The output is a short numbered table of failing apps followed by a numbered list of fixes, and the exit code is 1 when anything fails. Unlike the rest of abra, the audit needs an explicitly chosen abra directory (`$ABRA_DIR` or `abraDir` in `abra.yaml`) and never falls back to `~/.abra`. The design, including the planned later versions, is in [`doc/DesignAudit.md`](doc/DesignAudit.md). Apps deployed with `--chaos` are recognised: the table shows the deployed commit, a suggested redeploy keeps `--chaos` (without it, the deploy would replace the chaos deployment with the release in the `.env` file), what a `--chaos` redeploy would use (the app's `COMPOSE_FILE` with its overrides, loaded as deploy does) is checked for fixed images before the releases, and each finding has an action that says who has to act: redeploy, upgrade, recipe must update (a fixed image exists in the registry, found by listing the repository's tags and ordering rebuilds such as `v6.1.0-1` or `v6.1.0-fix1` by build time), upstream must update (no fixed image exists), check by hand, or follow advisory. A redeploy is only suggested if it deploys a fixed image, taking digests pinned in the recipe into account. The table shows what is affected (e.g. `nginx 1.31.8`) instead of the advisory ID, which moves to the end of the fix line together with the advisory's CVEs. Commits `e07454ec`, `d699e51c`, `165a81de`, `491ea47f`, `d6912414`, `6fc26afa`, `cef4dc2e`, `527d2a6a`, `82564ded`, `371b5aad`, `d19f174e`.
|
||||
|
||||
### Type remote
|
||||
|
||||
Recipes no longer have to come from the catalogue. `abra app new` accepts a git URL in any common form (`https://`, `ssh://`, `git@host:path`), which is normalized to a canonical `host/path` name, and the app's `.env` gets a `RECIPE=<host/path>` line so that a later deploy, possibly on another machine, fetches the recipe from the same source. The clone records its source in a `.abra-source` file, and `abra recipe ls` shows these external recipes in a source column. The `:<version>` suffix in `RECIPE=` may now also be a branch name: it is fetched on demand into `refs/remotes/origin/*` and checked out at its tip as a chaos commit, after tags and commit hashes, and fails clearly in offline mode if the branch was never fetched. The deployed version is now stored in a single `.env` field, and upgrade and rollback set the version label themselves, because git-URL recipes often carry a stale label in `compose.yml`. Cherry-picked from `ineiti/abra` branch `type_remote` (commits `73227c9e`, `0a157896`, `0c91585e`, `47d9f732`, `5f80d5e8`); `9170b4d2` fixes one of its tests, which did not test the unfetched case it was named for.
|
||||
|
||||
### Tables without a terminal
|
||||
|
||||
`formatter.PrintTable` read the width of stdin and failed with `operation not supported by device` when it was not a terminal, so `abra audit` and every other table command failed in a pipe or cron job. It now reads the width of stdout and prints the table without a width limit when there is no terminal. Commit `5c4ffaf2`.
|
||||
|
||||
### Devbox
|
||||
|
||||
A `devbox.json` pins the toolchain (Go 1.27, make, gettext): `devbox run build` builds abra, and `devbox run test` runs the tests with a temporary `ABRA_DIR`, which the existing tests require. Along with it, the `vendor/` directory was regenerated with `go mod vendor`, because it was out of sync with `go.mod` after an upstream dependency update and the default build failed. A binary built with a plain `go build`, without the `-ldflags` that set the commit, no longer panics: commit hashes are now truncated safely, and the default commit is `unknown-commit`. Commits `4e88ff9d`, `d699e51c`, `907a7eaa`, `2f0f3880`, `836971d6`.
|
||||
|
||||
+18
-6
@@ -110,9 +110,17 @@ func run() int {
|
||||
for _, app := range apps {
|
||||
recipes = append(recipes, app.Recipe)
|
||||
}
|
||||
byName := make(map[string]appPkg.App)
|
||||
for _, app := range apps {
|
||||
byName[app.Name] = app
|
||||
}
|
||||
checker := auditPkg.FixChecker{
|
||||
Fetch: auditPkg.RegistryFetch,
|
||||
Tags: auditPkg.RegistryTags,
|
||||
Recipes: auditPkg.NewGitRecipes(recipes, internal.Offline),
|
||||
Checkout: func(name string) ([]string, error) {
|
||||
return auditPkg.CheckoutImages(byName[name])
|
||||
},
|
||||
}
|
||||
checker.CheckFixes(context.Background(), findings)
|
||||
}
|
||||
@@ -141,18 +149,22 @@ func run() int {
|
||||
servers[st.Server] = true
|
||||
}
|
||||
log.Info(i18n.G(
|
||||
"audited %d deployed apps on %d servers against %d advisories: %d findings, %d unreachable servers",
|
||||
"audit done: deployed apps: %d, servers: %d, advisories: %d, findings: %d, unreachable servers: %d",
|
||||
len(states), len(servers), used, len(findings), len(serverErrs),
|
||||
))
|
||||
|
||||
var noFix []string
|
||||
// findings that the operator cannot fix alone, by who has to act
|
||||
waiting := make(map[string][]string)
|
||||
for _, f := range findings {
|
||||
if f.NoFix {
|
||||
noFix = append(noFix, fmt.Sprintf("%s (%s)", f.App, auditPkg.ShortRecipeName(f.Recipe)))
|
||||
switch f.Action {
|
||||
case auditPkg.ActionRecipe, auditPkg.ActionUpstream, auditPkg.ActionCheck:
|
||||
waiting[f.Action] = append(waiting[f.Action], fmt.Sprintf("%s (%s)", f.App, auditPkg.ShortRecipeName(f.Recipe)))
|
||||
}
|
||||
}
|
||||
if len(noFix) > 0 {
|
||||
log.Warn(i18n.G("no released fix yet for: %s", strings.Join(noFix, ", ")))
|
||||
for _, action := range []string{auditPkg.ActionUpstream, auditPkg.ActionRecipe, auditPkg.ActionCheck} {
|
||||
if apps := waiting[action]; len(apps) > 0 {
|
||||
log.Warn(fmt.Sprintf("%s: %s", actionLabel(action), strings.Join(apps, ", ")))
|
||||
}
|
||||
}
|
||||
|
||||
if len(findings) > 0 || len(serverErrs) > 0 {
|
||||
|
||||
+78
-7
@@ -32,7 +32,7 @@ func printReport(findings []auditPkg.Finding, serverErrs []auditPkg.ServerError)
|
||||
if showServer {
|
||||
headers = append(headers, i18n.G("SERVER"))
|
||||
}
|
||||
headers = append(headers, i18n.G("APP"), i18n.G("RECIPE"), i18n.G("ADVISORY"), i18n.G("SEVERITY"), i18n.G("STATUS"))
|
||||
headers = append(headers, i18n.G("APP"), i18n.G("RECIPE"), i18n.G("VERSION"), i18n.G("AFFECTED"), i18n.G("SEVERITY"), i18n.G("ACTION"))
|
||||
table.Headers(headers...)
|
||||
|
||||
for i, f := range findings {
|
||||
@@ -40,11 +40,7 @@ func printReport(findings []auditPkg.Finding, serverErrs []auditPkg.ServerError)
|
||||
if showServer {
|
||||
row = append(row, f.Server)
|
||||
}
|
||||
advisory := f.Advisory.ID
|
||||
if f.Advisory.Status == auditPkg.StatusDraft {
|
||||
advisory += " " + i18n.G("(draft)")
|
||||
}
|
||||
row = append(row, f.App, auditPkg.ShortRecipeName(f.Recipe), advisory, f.Advisory.Severity, f.Status)
|
||||
row = append(row, f.App, auditPkg.ShortRecipeName(f.Recipe), displayVersion(f), f.Affected, f.Advisory.Severity, displayAction(f))
|
||||
table.Row(row...)
|
||||
}
|
||||
|
||||
@@ -56,7 +52,7 @@ func printReport(findings []auditPkg.Finding, serverErrs []auditPkg.ServerError)
|
||||
width := termWidth()
|
||||
for i, f := range findings {
|
||||
prefix := fmt.Sprintf("%d. ", i+1)
|
||||
fmt.Println(wrap(prefix+f.App+": "+f.Fix, width, strings.Repeat(" ", len(prefix))))
|
||||
fmt.Println(wrap(prefix+f.App+": "+fixLine(f), width, strings.Repeat(" ", len(prefix))))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +69,81 @@ func printReport(findings []auditPkg.Finding, serverErrs []auditPkg.ServerError)
|
||||
return nil
|
||||
}
|
||||
|
||||
// actionLabel translates a finding action.
|
||||
func actionLabel(action string) string {
|
||||
switch action {
|
||||
case auditPkg.ActionRedeploy:
|
||||
return i18n.G("redeploy")
|
||||
case auditPkg.ActionUpgrade:
|
||||
return i18n.G("upgrade")
|
||||
case auditPkg.ActionRecipe:
|
||||
return i18n.G("recipe must update")
|
||||
case auditPkg.ActionUpstream:
|
||||
return i18n.G("upstream must update")
|
||||
case auditPkg.ActionCheck:
|
||||
return i18n.G("check by hand")
|
||||
case auditPkg.ActionAdvisory:
|
||||
return i18n.G("follow advisory")
|
||||
}
|
||||
return action
|
||||
}
|
||||
|
||||
// displayAction is the action shown in the table. A finding whose images
|
||||
// could not all be checked (status unknown) needs a look first.
|
||||
func displayAction(f auditPkg.Finding) string {
|
||||
if f.Status == auditPkg.FindingUnknown {
|
||||
return actionLabel(auditPkg.ActionCheck)
|
||||
}
|
||||
return actionLabel(f.Action)
|
||||
}
|
||||
|
||||
// fixLine starts with the action, so that the first words say who acts,
|
||||
// and ends with the references to look the advisory up.
|
||||
func fixLine(f auditPkg.Finding) string {
|
||||
line := actionLabel(f.Action) + ". " + f.Fix
|
||||
if f.Status == auditPkg.FindingUnknown {
|
||||
line = i18n.G("%s. Not every image could be checked (see abra audit -d). If it is affected: %s. %s",
|
||||
actionLabel(auditPkg.ActionCheck), actionLabel(f.Action), f.Fix)
|
||||
}
|
||||
return line + " (" + advisoryRefs(f.Advisory) + ")"
|
||||
}
|
||||
|
||||
// advisoryRefs names the advisory and its CVEs: "CCA-2026-0002,
|
||||
// CVE-2026-123007 and 4 more". Drafts are marked.
|
||||
func advisoryRefs(adv *auditPkg.Advisory) string {
|
||||
refs := adv.ID
|
||||
if adv.Status == auditPkg.StatusDraft {
|
||||
refs += " " + i18n.G("(draft)")
|
||||
}
|
||||
|
||||
var cves []string
|
||||
for _, r := range adv.Refs {
|
||||
if strings.HasPrefix(r, "CVE-") {
|
||||
cves = append(cves, strings.Fields(r)[0])
|
||||
}
|
||||
}
|
||||
switch len(cves) {
|
||||
case 0:
|
||||
case 1:
|
||||
refs += ", " + cves[0]
|
||||
default:
|
||||
refs += ", " + i18n.G("%s and %d more", cves[0], len(cves)-1)
|
||||
}
|
||||
return refs
|
||||
}
|
||||
|
||||
// displayVersion shows what is deployed: the recipe version, or for a
|
||||
// --chaos deployment the commit it was deployed from, as abra app ls does.
|
||||
func displayVersion(f auditPkg.Finding) string {
|
||||
if !f.Chaos {
|
||||
return f.Version
|
||||
}
|
||||
if f.ChaosVersion == "" {
|
||||
return f.Version + " " + i18n.G("(chaos)")
|
||||
}
|
||||
return f.ChaosVersion + " " + i18n.G("(chaos)")
|
||||
}
|
||||
|
||||
// termWidth returns the terminal width, or 0 (no wrapping) when stdout is not
|
||||
// a terminal or ABRA_CI is set.
|
||||
func termWidth() int {
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
auditPkg "coopcloud.tech/abra/pkg/audit"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -19,3 +21,33 @@ func TestShortError(t *testing.T) {
|
||||
assert.Equal(t, "ssh: connect to host srv port 22: No route to host", shortError(err))
|
||||
assert.Equal(t, "plain", shortError(errors.New("plain")))
|
||||
}
|
||||
|
||||
func TestDisplayVersion(t *testing.T) {
|
||||
assert.Equal(t, "1.0.0+1.2.3", displayVersion(auditPkg.Finding{Version: "1.0.0+1.2.3"}))
|
||||
assert.Equal(t, "1234abcd+U (chaos)", displayVersion(auditPkg.Finding{Version: "1.0.0+1.2.3", Chaos: true, ChaosVersion: "1234abcd+U"}))
|
||||
assert.Equal(t, "1.0.0+1.2.3 (chaos)", displayVersion(auditPkg.Finding{Version: "1.0.0+1.2.3", Chaos: true}))
|
||||
}
|
||||
|
||||
func TestFixLine(t *testing.T) {
|
||||
adv := &auditPkg.Advisory{ID: "CCA-1", Status: auditPkg.StatusPublished}
|
||||
f := auditPkg.Finding{Advisory: adv, Status: auditPkg.FindingAffected, Action: auditPkg.ActionUpstream, Fix: "No fixed image exists yet."}
|
||||
assert.Equal(t, "upstream must update", displayAction(f))
|
||||
assert.Equal(t, "upstream must update. No fixed image exists yet. (CCA-1)", fixLine(f))
|
||||
|
||||
// an image that could not be checked needs a look first
|
||||
f = auditPkg.Finding{Advisory: adv, Status: auditPkg.FindingUnknown, Action: auditPkg.ActionRedeploy, Fix: "abra app deploy app --force"}
|
||||
assert.Equal(t, "check by hand", displayAction(f))
|
||||
assert.Equal(t, "check by hand. Not every image could be checked (see abra audit -d). If it is affected: redeploy. abra app deploy app --force (CCA-1)", fixLine(f))
|
||||
}
|
||||
|
||||
func TestAdvisoryRefs(t *testing.T) {
|
||||
adv := &auditPkg.Advisory{ID: "CCA-2026-0002", Status: auditPkg.StatusPublished}
|
||||
assert.Equal(t, "CCA-2026-0002", advisoryRefs(adv))
|
||||
|
||||
adv.Refs = []string{"https://nginx.org/en/security_advisories.html", "CVE-2026-123007"}
|
||||
assert.Equal(t, "CCA-2026-0002, CVE-2026-123007", advisoryRefs(adv))
|
||||
|
||||
adv.Refs = append(adv.Refs, "CVE-2026-113425", "CVE-2026-123633")
|
||||
adv.Status = auditPkg.StatusDraft
|
||||
assert.Equal(t, "CCA-2026-0002 (draft), CVE-2026-123007 and 2 more", advisoryRefs(adv))
|
||||
}
|
||||
|
||||
+21
-7
@@ -342,14 +342,28 @@ Answers "which of my apps need attention, and what do I run?" using only a hand-
|
||||
- **Advisories.** Hand-written YAML in `c4dt/advisories`, pulled on every run. The first advisory is the nextcloud same-tag rebuild. Only `published` advisories apply; `--include-drafts` also applies `draft` ones, marked "(draft)" in the output, so a maintainer can try an advisory on real servers before publishing it. `withdrawn` advisories never apply.
|
||||
- **Conditions.** Only recipe ranges (`affected`, `fixed`), `env`, `version`, `created_after` (with the checks for unusable build times), `fixed_digests` and `affected_digests`. Fields v1 does not know are skipped with a warning, so newer advisories do not break older abra versions.
|
||||
- **Reads only.** Service specs (version label and image digests) and image configs. On a single-node server, the common case, the image config is read from the node itself with `docker image inspect`, so no registry is needed.
|
||||
- **Output.** Only failing apps. A narrow numbered table lists app, recipe, advisory, severity and status (`affected` or `unknown`), with a server column only when several servers are audited. Below it, a numbered list gives the suggested fix for each row, wrapped to the terminal width, because fixes are too long for a table column. Unreachable servers follow, with only the useful part of the SSH error. The suggested fixes are:
|
||||
- upgrade: `abra app upgrade <domain> <fixed version>`
|
||||
- refresh: `abra app deploy <domain> --force`, followed by `abra audit` to check the result
|
||||
- manual: the advisory's notes
|
||||
- **Output.** Only failing apps. A narrow numbered table lists app, recipe, deployed version, what is affected, severity and action, with a server column only when several servers are audited. For an app deployed with `--chaos`, the version is the commit it was deployed from, marked `(chaos)`, as in `abra app ls`. The affected column names what is vulnerable, from the condition that matched: the runtime and its version for an `env` condition (`NGINX_VERSION=1.31.8` gives `nginx 1.31.8`), the image's version for a `version` condition, the build date for `created_after`, the recipe and its version for a recipe range, and the image otherwise. Advisory IDs such as `CCA-2026-0002` are local to the advisories repository and mean nothing at a glance, so they are not in the table. Below it, a numbered list gives the fix for each row, starting with the action and ending with the references to look the advisory up: its ID, marked if it is a draft, and its CVEs (`CCA-2026-0002, CVE-2026-123007 and 4 more`). The list is wrapped to the terminal width, because fixes are too long for a table column. Unreachable servers follow, with only the useful part of the SSH error. The findings that the operator cannot fix alone are summarised at the end, grouped by action. The action says who has to act:
|
||||
|
||||
| Action | Meaning | Fix shown |
|
||||
| --- | --- | --- |
|
||||
| redeploy | What a redeploy deploys is fixed: the tag's current image, or the recipe checkout of a `--chaos` deployment | `abra app deploy <domain> --force && abra audit`; for a `--chaos` deployment `abra app deploy <domain> --chaos`, because without `--chaos` the deploy would replace the chaos deployment with the release in the `.env` file |
|
||||
| upgrade | A released recipe version uses fixed images | `abra app upgrade <domain> <version>` |
|
||||
| recipe must update | A fixed image exists in the registry, but no recipe release uses it | The fixed image; for a `--chaos` deployment, use it in the checkout or the app's override and redeploy with `--chaos` |
|
||||
| upstream must update | No fixed image exists yet | Why: the tag was not rebuilt, or rebuilt but still affected, and no later tag is fixed; plus a pointer to the advisory's mitigations |
|
||||
| check by hand | The audit could not decide: an image could not be checked (status `unknown`), the registry could not be searched, or build times are unusable | The reason, and the fix that would apply otherwise |
|
||||
| follow advisory | Strategy `manual` | The advisory's notes |
|
||||
|
||||
- **Fix check.** Every suggestion is checked before it is shown:
|
||||
- Before suggesting a redeploy, the audit reads the tag's current image from the registry and applies the advisory to it. Upstreams stop rebuilding patch-pinned tags such as `nextcloud:35.0.2-fpm` once the next patch is out, so if the current image is not fixed either, the suggestion becomes a recipe upgrade.
|
||||
- For a recipe upgrade, the newer releases of the recipe are searched for the oldest one whose images are fixed. Images are read from the `compose*.yml` files of each release tag, without changing the local checkout. If no release is fixed, the audit says so and warns: a new recipe release is needed first.
|
||||
- For a recipe version range, the advisory's `fixed` version must be a released tag.
|
||||
- A redeploy only helps if what it deploys is fixed. That is the tag's current image in the registry, unless the recipe pins a digest (`image:tag@sha256:...`): then a redeploy keeps the pinned image, which is checked instead. Upstreams stop rebuilding patch-pinned tags such as `nextcloud:35.0.2-fpm` once the next patch is out. If a redeploy does not help, an upgrade is looked for.
|
||||
- A `--chaos` deployment runs the local checkout, so for it the audit first loads what `abra app deploy --chaos` would deploy: the files of the app's `COMPOSE_FILE` (`GetComposeFiles`), overrides outside the recipe directory included, as they are on disk with uncommitted changes, merged and filled in with the app's `.env` values by the same loader as deploy. If those images are fixed, the action is a `--chaos` redeploy. Images already deployed from an override are checked like any other deployed image.
|
||||
- For an upgrade, the newer releases of the recipe are searched for the oldest one whose images are fixed. Images are read from the `compose*.yml` files of each release tag, without changing the local checkout.
|
||||
- If no release is fixed, the registry is searched for a fixed image, to tell "recipe must update" from "upstream must update". The tags of the image's repository are listed, and candidates are checked in this order:
|
||||
1. The deployed tag itself, if its current image is fixed but a redeploy does not pick it up because the recipe pins an older digest.
|
||||
2. Later builds of the same version under a suffixed tag. Upstreams mark such rebuilds in many ways (`v6.1.0-1`, `v6.1.0-fix1`, `v6.1.0_r2`), and in semver `v6.1.0-1` even sorts before `v6.1.0`, so suffixes are not parsed. A candidate is the deployed tag, a separator, and a suffix containing a number; per-architecture copies (`-amd64`), pre-releases (`-preprod`, `-rc1`) and variants (`-fpm`, `-alpine3`) are left out by name. The build time then decides: a candidate must be built at least an hour after the registry's current image of the deployed tag. A pre-release is built before the release, and a variant in the same CI run as it, so neither passes; comparing with the deployed image instead would let a pre-release pushed after an old deployment through. Of the fixed candidates, the latest built is chosen. If the build times are unusable (see [Ordering images by version and build time](#ordering-images-by-version-and-build-time)), the action is "check by hand".
|
||||
3. Newer versions of the same form: `v6.1.1` or `v6.2.0` for `v6.1.0`, but not `v6`, `latest` or `main`. As for releases, the newest is checked first; if it is fixed, the oldest fixed one is chosen.
|
||||
|
||||
Every candidate is checked against the advisory: whether a tag looks newer never decides whether it is fixed. The search is bounded to 20 rebuild and 10 newer-version candidates per image.
|
||||
- For a recipe version range, the advisory's `fixed` version must be a released tag; otherwise the recipe must update.
|
||||
- If the registry or the recipe cannot be read, the suggestion is kept and marked as unchecked.
|
||||
- **Recipe names.** Recipes are shown relative to `git.coopcloud.tech/coop-cloud/`: `nextcloud` for the canonical recipe, `c4dt/nextcloud` for a fork on the same server, and the full path elsewhere. Advisories name recipes the same way, so `nextcloud` in an advisory does not match the fork `c4dt/nextcloud`, which has its own versions.
|
||||
- **Exit code.** 0 when nothing fails, 1 otherwise.
|
||||
|
||||
+104
-18
@@ -15,18 +15,42 @@ const (
|
||||
FindingUnknown = "unknown"
|
||||
)
|
||||
|
||||
// Finding actions say who has to act, and how.
|
||||
const (
|
||||
// ActionRedeploy: redeploying the app picks up a fixed image.
|
||||
ActionRedeploy = "redeploy"
|
||||
// ActionUpgrade: a released recipe version fixes it.
|
||||
ActionUpgrade = "upgrade"
|
||||
// ActionRecipe: a fixed image exists, but no recipe release uses it.
|
||||
ActionRecipe = "recipe must update"
|
||||
// ActionUpstream: no fixed image exists yet.
|
||||
ActionUpstream = "upstream must update"
|
||||
// ActionCheck: the audit could not decide.
|
||||
ActionCheck = "check by hand"
|
||||
// ActionAdvisory: the advisory's notes say what to do.
|
||||
ActionAdvisory = "follow advisory"
|
||||
)
|
||||
|
||||
// Finding is one advisory that applies to one deployed app.
|
||||
type Finding struct {
|
||||
Server string `json:"server"`
|
||||
App string `json:"app"`
|
||||
Recipe string `json:"recipe"`
|
||||
Version string `json:"version"`
|
||||
Advisory *Advisory `json:"-"`
|
||||
Status string `json:"status"`
|
||||
Server string `json:"server"`
|
||||
App string `json:"app"`
|
||||
Recipe string `json:"recipe"`
|
||||
Version string `json:"version"`
|
||||
// Chaos and ChaosVersion are copied from AppState.
|
||||
Chaos bool `json:"chaos"`
|
||||
ChaosVersion string `json:"chaosVersion,omitempty"`
|
||||
Advisory *Advisory `json:"-"`
|
||||
Status string `json:"status"`
|
||||
// Affected names what is vulnerable, e.g. "nginx 1.31.8" or
|
||||
// "lasuite-docs 2.0.0+v6.0.4", from the conditions that matched.
|
||||
Affected string `json:"affected"`
|
||||
// Reasons explains, per recipe or image, why the finding was raised.
|
||||
Reasons []string `json:"reasons"`
|
||||
// Fix is a suggested command, or the advisory's notes for manual fixes.
|
||||
Fix string `json:"fix"`
|
||||
// Action says who has to act, one of the Action constants.
|
||||
Action string `json:"action"`
|
||||
// NoFix is set when no recipe release fixes the finding yet.
|
||||
NoFix bool `json:"noFix"`
|
||||
|
||||
@@ -84,14 +108,17 @@ func Evaluate(states []AppState, advisories []Advisory, opts EvaluateOptions) []
|
||||
|
||||
func evaluateApp(st AppState, adv *Advisory) (Finding, bool) {
|
||||
f := Finding{
|
||||
Server: st.Server,
|
||||
App: st.Name,
|
||||
Recipe: st.Recipe,
|
||||
Version: st.Version,
|
||||
Advisory: adv,
|
||||
Server: st.Server,
|
||||
App: st.Name,
|
||||
Recipe: st.Recipe,
|
||||
Version: st.Version,
|
||||
Chaos: st.Chaos,
|
||||
ChaosVersion: st.ChaosVersion,
|
||||
Advisory: adv,
|
||||
}
|
||||
|
||||
var gotAffected, gotUnknown bool
|
||||
var affectedLabels []string
|
||||
|
||||
// 1. recipe ranges
|
||||
if rr, ok := recipeRange(adv, st.Recipe); ok && st.Version != "" {
|
||||
@@ -100,6 +127,7 @@ func evaluateApp(st AppState, adv *Advisory) (Finding, bool) {
|
||||
gotAffected = true
|
||||
f.recipeAffected = true
|
||||
f.Reasons = append(f.Reasons, i18n.G("recipe version %s is in %s", st.Version, rr.affected.Raw))
|
||||
affectedLabels = appendUnique(affectedLabels, ShortRecipeName(st.Recipe)+" "+st.Version)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,6 +150,7 @@ func evaluateApp(st AppState, adv *Advisory) (Finding, bool) {
|
||||
if !slices.Contains(f.Reasons, reason) {
|
||||
f.Reasons = append(f.Reasons, reason)
|
||||
}
|
||||
affectedLabels = appendUnique(affectedLabels, affectedLabel(rule, img))
|
||||
if !slices.ContainsFunc(f.images, func(i ImageRef) bool { return i.Ref == img.Ref }) {
|
||||
f.images = append(f.images, img)
|
||||
}
|
||||
@@ -137,12 +166,62 @@ func evaluateApp(st AppState, adv *Advisory) (Finding, bool) {
|
||||
return f, false
|
||||
}
|
||||
|
||||
f.Fix = suggestFix(f, st)
|
||||
f.Affected = strings.Join(affectedLabels, ", ")
|
||||
f.Action, f.Fix = suggestFix(f, st)
|
||||
f.os, f.arch = st.OS, st.Arch
|
||||
|
||||
return f, true
|
||||
}
|
||||
|
||||
// affectedLabel names what makes img affected under rule, in a few words:
|
||||
// the runtime and its version for env conditions ("nginx 1.31.8"), the
|
||||
// image's own version for version conditions, its build date for
|
||||
// created_after, and the image itself otherwise.
|
||||
func affectedLabel(rule ImageRule, img ImageRef) string {
|
||||
info := img.Info
|
||||
if info == nil || (img.Digest != "" && slices.Contains(rule.AffectedDigests, img.Digest)) {
|
||||
return img.NameTag()
|
||||
}
|
||||
|
||||
if len(rule.env) > 0 {
|
||||
var keys []string
|
||||
for k := range rule.env {
|
||||
if _, ok := info.Env[k]; ok {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
}
|
||||
if len(keys) == len(rule.env) {
|
||||
slices.Sort(keys)
|
||||
var parts []string
|
||||
for _, k := range keys {
|
||||
parts = append(parts, componentName(k)+" "+info.Env[k])
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
}
|
||||
|
||||
if rule.version != nil && info.Version() != "" {
|
||||
name := img.Name
|
||||
if i := strings.LastIndex(name, "/"); i >= 0 {
|
||||
name = name[i+1:]
|
||||
}
|
||||
return name + " " + info.Version()
|
||||
}
|
||||
|
||||
if rule.createdAfter != nil && info.Created != nil && info.createdUnusable == "" {
|
||||
return i18n.G("%s built %s", img.NameTag(), info.Created.UTC().Format("2006-01-02"))
|
||||
}
|
||||
|
||||
return img.NameTag()
|
||||
}
|
||||
|
||||
// componentName turns a version variable into the name of what it
|
||||
// versions: NGINX_VERSION -> nginx, PHP_VERSION -> php.
|
||||
func componentName(envVar string) string {
|
||||
name := strings.TrimSuffix(envVar, "_VERSION")
|
||||
return strings.ReplaceAll(strings.ToLower(name), "_", "-")
|
||||
}
|
||||
|
||||
// evaluateImage applies one rule to one image that matches it:
|
||||
//
|
||||
// 1. a digest in affected_digests is affected;
|
||||
@@ -267,25 +346,32 @@ func upgradeCommand(adv *Advisory, app, recipe string) string {
|
||||
return fmt.Sprintf("abra app upgrade %s", app)
|
||||
}
|
||||
|
||||
func suggestFix(f Finding, st AppState) string {
|
||||
// suggestFix returns the action and fix for a finding as the advisory
|
||||
// suggests it. FixChecker then verifies the fix and may change both.
|
||||
func suggestFix(f Finding, st AppState) (string, string) {
|
||||
adv := f.Advisory
|
||||
upgrade := func() string { return upgradeCommand(adv, st.Name, st.Recipe) }
|
||||
|
||||
// a recipe version in the affected range is only fixed by upgrading
|
||||
if f.recipeAffected {
|
||||
return upgrade()
|
||||
return ActionUpgrade, upgrade()
|
||||
}
|
||||
|
||||
switch adv.Fix.Strategy {
|
||||
case StrategyUpgrade:
|
||||
return upgrade()
|
||||
return ActionUpgrade, upgrade()
|
||||
case StrategyRefresh:
|
||||
return fmt.Sprintf("abra app deploy %s --force && abra audit", st.Name)
|
||||
// without --chaos, deploy would replace the chaos deployment with
|
||||
// the release in the .env file
|
||||
if st.Chaos {
|
||||
return ActionRedeploy, fmt.Sprintf("abra app deploy %s --chaos && abra audit", st.Name)
|
||||
}
|
||||
return ActionRedeploy, fmt.Sprintf("abra app deploy %s --force && abra audit", st.Name)
|
||||
default:
|
||||
if adv.Fix.Notes != "" {
|
||||
return strings.TrimSpace(adv.Fix.Notes)
|
||||
return ActionAdvisory, strings.TrimSpace(adv.Fix.Notes)
|
||||
}
|
||||
return i18n.G("no fix available yet")
|
||||
return ActionAdvisory, i18n.G("No fix is known yet.")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+213
-61
@@ -18,12 +18,23 @@ func RegistryFetch(ctx context.Context, img ImageRef, os, arch string) (*ImageIn
|
||||
return FetchFromRegistry(ctx, img, os, arch)
|
||||
}
|
||||
|
||||
// FixChecker checks that the suggested fixes actually exist.
|
||||
type FixChecker struct {
|
||||
Fetch FetchFunc
|
||||
Recipes RecipeSource
|
||||
// TagsFunc lists the tags of an image's repository.
|
||||
type TagsFunc func(ctx context.Context, img ImageRef) ([]string, error)
|
||||
|
||||
cache map[string]fetchResult
|
||||
// FixChecker checks that the suggested fixes actually exist, and decides
|
||||
// who has to act on each finding (see the Action constants).
|
||||
type FixChecker struct {
|
||||
Fetch FetchFunc
|
||||
// Tags lists repository tags, to find fixed images that no recipe
|
||||
// release uses yet. If nil, no such search is made.
|
||||
Tags TagsFunc
|
||||
Recipes RecipeSource
|
||||
// Checkout returns the images that abra app deploy --chaos would deploy
|
||||
// for an app, see CheckoutImages. If nil, checkouts are not checked.
|
||||
Checkout func(app string) ([]string, error)
|
||||
|
||||
cache map[string]fetchResult
|
||||
tagsCache map[string]tagsResult
|
||||
}
|
||||
|
||||
type fetchResult struct {
|
||||
@@ -31,16 +42,27 @@ type fetchResult struct {
|
||||
err error
|
||||
}
|
||||
|
||||
// CheckFixes verifies the suggested fix of each finding:
|
||||
type tagsResult struct {
|
||||
tags []string
|
||||
err error
|
||||
}
|
||||
|
||||
// CheckFixes verifies the suggested fix of each finding, and sets its
|
||||
// action:
|
||||
//
|
||||
// - a redeploy only helps if the tag now points to a fixed image. Upstreams
|
||||
// stop rebuilding patch-pinned tags such as nextcloud:35.0.2-fpm once the
|
||||
// next patch is out, so the tag's current image is read from the
|
||||
// registry and checked against the advisory. If it is not fixed, a
|
||||
// recipe upgrade is needed instead;
|
||||
// - for a recipe upgrade, the newer releases of the recipe are searched for
|
||||
// the first one whose images are fixed. If there is none, the finding
|
||||
// says so: a new recipe release is needed first;
|
||||
// - a redeploy only helps if what it deploys is fixed: the tag's current
|
||||
// image in the registry, or the digest the recipe pins. Upstreams stop
|
||||
// rebuilding patch-pinned tags such as nextcloud:35.0.2-fpm once the
|
||||
// next patch is out. If a redeploy does not help, an upgrade is looked
|
||||
// for instead;
|
||||
// - for an app deployed with --chaos, the recipe checkout and the app's
|
||||
// overrides are checked first: if they use fixed images, a --chaos
|
||||
// redeploy is the fix;
|
||||
// - for an upgrade, the newer releases of the recipe are searched for the
|
||||
// oldest one whose images are fixed;
|
||||
// - if no release is fixed, the registry is searched for a fixed image
|
||||
// (see findFixedTag): if one exists, the recipe must update, otherwise
|
||||
// upstream must;
|
||||
// - for a recipe version range, the advisory's fixed version must be a
|
||||
// released tag of the recipe.
|
||||
//
|
||||
@@ -50,6 +72,9 @@ func (c *FixChecker) CheckFixes(ctx context.Context, findings []Finding) {
|
||||
if c.cache == nil {
|
||||
c.cache = make(map[string]fetchResult)
|
||||
}
|
||||
if c.tagsCache == nil {
|
||||
c.tagsCache = make(map[string]tagsResult)
|
||||
}
|
||||
|
||||
for i := range findings {
|
||||
f := &findings[i]
|
||||
@@ -60,7 +85,7 @@ func (c *FixChecker) CheckFixes(ctx context.Context, findings []Finding) {
|
||||
case f.Advisory.Fix.Strategy == StrategyRefresh:
|
||||
c.checkRefresh(ctx, f)
|
||||
case f.Advisory.Fix.Strategy == StrategyUpgrade:
|
||||
c.checkUpgrade(ctx, f, "")
|
||||
c.checkUpgrade(ctx, f, f.images)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,8 +110,10 @@ func (c *FixChecker) checkRecipeRange(f *Finding) {
|
||||
}
|
||||
}
|
||||
|
||||
f.Fix = i18n.G("no fixed release of %s yet: the advisory names %s, but the latest release is %s",
|
||||
ShortRecipeName(f.Recipe), rr.Fixed, lastOr(versions, i18n.G("none")))
|
||||
short := ShortRecipeName(f.Recipe)
|
||||
f.Action = ActionRecipe
|
||||
f.Fix = i18n.G("The advisory names %s %s as fixed, but the latest release is %s. A release of %s with the fix is needed.",
|
||||
short, rr.Fixed, lastOr(versions, i18n.G("none")), short)
|
||||
f.NoFix = true
|
||||
}
|
||||
|
||||
@@ -96,15 +123,20 @@ func (c *FixChecker) checkRefresh(ctx context.Context, f *Finding) {
|
||||
return
|
||||
}
|
||||
|
||||
var stale []string
|
||||
var stale []ImageRef
|
||||
var fetchErr error
|
||||
for _, img := range f.images {
|
||||
if img.Tag == "" {
|
||||
stale = appendUnique(stale, img.Name)
|
||||
// a redeploy deploys the digest the recipe pins, if any, otherwise
|
||||
// whatever the tag points to now
|
||||
target, byDigest := img, false
|
||||
if d := c.pinnedDigest(f, img); d != "" {
|
||||
target.Digest, byDigest = d, true
|
||||
} else if img.Tag == "" {
|
||||
stale = append(stale, img)
|
||||
continue
|
||||
}
|
||||
|
||||
cur, err := c.current(ctx, img, f.os, f.arch, false)
|
||||
cur, err := c.current(ctx, target, f.os, f.arch, byDigest)
|
||||
if err != nil {
|
||||
fetchErr = err
|
||||
log.Debug(i18n.G("%s: unable to read current %s from registry: %s", f.App, img.NameTag(), err))
|
||||
@@ -112,40 +144,87 @@ func (c *FixChecker) checkRefresh(ctx context.Context, f *Finding) {
|
||||
}
|
||||
|
||||
if cur.Digest == img.Digest || !fixedByAdvisory(f.Advisory, *cur) {
|
||||
log.Debug(i18n.G("%s: current %s (%s) is not fixed", f.App, img.NameTag(), shortDigest(cur.Digest)))
|
||||
stale = appendUnique(stale, img.NameTag())
|
||||
if byDigest {
|
||||
f.Reasons = append(f.Reasons, i18n.G("redeploy would not help: the recipe pins %s to %s", img.NameTag(), shortDigest(target.Digest)))
|
||||
} else {
|
||||
f.Reasons = append(f.Reasons, i18n.G("redeploy would not help: the current image of %s (%s) is not fixed either", img.NameTag(), shortDigest(cur.Digest)))
|
||||
}
|
||||
stale = append(stale, img)
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case len(stale) > 0:
|
||||
f.Reasons = append(f.Reasons, i18n.G("redeploy would not help: the current image of %s is not fixed either", strings.Join(stale, ", ")))
|
||||
c.checkUpgrade(ctx, f, i18n.G("%s not rebuilt with a fix", strings.Join(stale, ", ")))
|
||||
c.checkUpgrade(ctx, f, stale)
|
||||
case fetchErr != nil:
|
||||
f.Fix += " " + i18n.G("(unchecked: registry unreachable)")
|
||||
default:
|
||||
var names []string
|
||||
for _, img := range f.images {
|
||||
names = appendUnique(names, img.NameTag())
|
||||
}
|
||||
f.Fix = i18n.G("The registry's %s now has a fixed image: %s", strings.Join(names, ", "), f.Fix)
|
||||
}
|
||||
}
|
||||
|
||||
// checkUpgrade looks for the oldest recipe release newer than the deployed
|
||||
// one whose images are all fixed.
|
||||
func (c *FixChecker) checkUpgrade(ctx context.Context, f *Finding, prefix string) {
|
||||
join := func(msg string) string {
|
||||
if prefix == "" {
|
||||
return msg
|
||||
}
|
||||
return prefix + "; " + msg
|
||||
// pinnedDigest returns the digest that a redeploy of the app would use for
|
||||
// the image, if its compose files pin one: those of the deployed release,
|
||||
// or for a --chaos deployment those of the checkout.
|
||||
func (c *FixChecker) pinnedDigest(f *Finding, img ImageRef) string {
|
||||
var refs []string
|
||||
var err error
|
||||
switch {
|
||||
case f.Chaos && c.Checkout != nil:
|
||||
refs, err = c.Checkout(f.App)
|
||||
case !f.Chaos && c.Recipes != nil && f.Version != "":
|
||||
refs, err = c.Recipes.Images(f.Recipe, f.Version)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
for _, ref := range refs {
|
||||
if r, err := ParseImageRef("", ref); err == nil && r.Name == img.Name && r.Digest != "" {
|
||||
return r.Digest
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// checkUpgrade looks for the oldest recipe release newer than the deployed
|
||||
// one whose images are all fixed. stale are the images a redeploy does not
|
||||
// fix.
|
||||
func (c *FixChecker) checkUpgrade(ctx context.Context, f *Finding, stale []ImageRef) {
|
||||
f.Action = ActionUpgrade
|
||||
generic := upgradeCommand(f.Advisory, f.App, f.Recipe)
|
||||
|
||||
if c.Recipes == nil || f.arch == "" {
|
||||
f.Fix = join(generic + " " + i18n.G("(unchecked: no fixed release looked up)"))
|
||||
f.Fix = generic + " " + i18n.G("(unchecked: no fixed release looked up)")
|
||||
return
|
||||
}
|
||||
|
||||
names := make(map[string]bool)
|
||||
for _, img := range stale {
|
||||
names[img.Name] = true
|
||||
}
|
||||
|
||||
// A chaos deployment runs the recipe checkout: if the checkout already
|
||||
// uses fixed images, redeploying it is the fix.
|
||||
if f.Chaos && c.Checkout != nil {
|
||||
if fixedImgs, ok := c.checkoutFixed(ctx, f, names); ok {
|
||||
f.Action = ActionRedeploy
|
||||
f.Fix = i18n.G("The recipe checkout already uses %s, which is fixed: %s",
|
||||
strings.Join(fixedImgs, ", "), fmt.Sprintf("abra app deploy %s --chaos && abra audit", f.App))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
versions, err := c.Recipes.Versions(f.Recipe)
|
||||
if err != nil {
|
||||
log.Debug(i18n.G("%s: unable to list versions of %s: %s", f.App, f.Recipe, err))
|
||||
f.Fix = join(generic + " " + i18n.G("(unchecked: %s)", err))
|
||||
f.Fix = generic + " " + i18n.G("(unchecked: %s)", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -158,16 +237,9 @@ func (c *FixChecker) checkUpgrade(ctx context.Context, f *Finding, prefix string
|
||||
}
|
||||
}
|
||||
|
||||
names := make(map[string]bool)
|
||||
for _, img := range f.images {
|
||||
names[img.Name] = true
|
||||
}
|
||||
|
||||
short := ShortRecipeName(f.Recipe)
|
||||
if len(newer) == 0 {
|
||||
f.Fix = join(i18n.G("no fixed release of %s yet: %s is the latest; a new release with a fixed image is needed",
|
||||
short, lastOr(versions, f.Version)))
|
||||
f.NoFix = true
|
||||
f.Reasons = append(f.Reasons, i18n.G("no newer release of %s exists", ShortRecipeName(f.Recipe)))
|
||||
c.noRelease(ctx, f, stale)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -176,21 +248,12 @@ func (c *FixChecker) checkUpgrade(ctx context.Context, f *Finding, prefix string
|
||||
latest := newer[len(newer)-1]
|
||||
ok, err := fixedAt(latest)
|
||||
if err != nil {
|
||||
f.Fix = join(generic + " " + i18n.G("(unchecked: %s)", err))
|
||||
f.Fix = generic + " " + i18n.G("(unchecked: %s)", err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
var imgs []string
|
||||
if all, err := c.Recipes.Images(f.Recipe, latest); err == nil {
|
||||
for _, ref := range all {
|
||||
if img, err := ParseImageRef("", ref); err == nil && names[img.Name] {
|
||||
imgs = append(imgs, img.NameTag())
|
||||
}
|
||||
}
|
||||
}
|
||||
f.Fix = join(i18n.G("no fixed release of %s yet: the latest, %s, still uses %s; a new release with a fixed image is needed",
|
||||
short, latest, strings.Join(imgs, ", ")))
|
||||
f.NoFix = true
|
||||
f.Reasons = append(f.Reasons, i18n.G("the latest release of %s, %s, is not fixed", ShortRecipeName(f.Recipe), latest))
|
||||
c.noRelease(ctx, f, stale)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -201,7 +264,69 @@ func (c *FixChecker) checkUpgrade(ctx context.Context, f *Finding, prefix string
|
||||
break
|
||||
}
|
||||
}
|
||||
f.Fix = join(fmt.Sprintf("abra app upgrade %s %s", f.App, best))
|
||||
f.Fix = i18n.G("Release %s uses fixed images: %s", best, fmt.Sprintf("abra app upgrade %s %s", f.App, best))
|
||||
}
|
||||
|
||||
// noRelease handles a finding that no recipe release fixes: it searches the
|
||||
// registry for a fixed image of each stale image. If every one has a fixed
|
||||
// image, the recipe must update, otherwise upstream must.
|
||||
func (c *FixChecker) noRelease(ctx context.Context, f *Finding, stale []ImageRef) {
|
||||
f.NoFix = true
|
||||
short := ShortRecipeName(f.Recipe)
|
||||
|
||||
var found, missing []string
|
||||
var searchErr error
|
||||
for _, img := range stale {
|
||||
res, err := c.findFixedTag(ctx, f, img)
|
||||
switch {
|
||||
case err != nil:
|
||||
log.Debug(i18n.G("%s: unable to search for a fixed %s: %s", f.App, img.Name, err))
|
||||
searchErr = err
|
||||
case res.tag == "":
|
||||
missing = append(missing, upstreamState(img, res.current))
|
||||
case res.sameTag:
|
||||
found = append(found, i18n.G("%s (its current image)", img.Name+":"+res.tag))
|
||||
default:
|
||||
found = append(found, img.Name+":"+res.tag)
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case len(missing) > 0:
|
||||
f.Action = ActionUpstream
|
||||
f.Fix = i18n.G("No fixed image exists yet: %s.", strings.Join(missing, "; "))
|
||||
if f.Advisory.Fix.Notes != "" {
|
||||
f.Fix += " " + i18n.G("Until then, see the advisory's mitigations.")
|
||||
}
|
||||
case searchErr != nil:
|
||||
f.Action = ActionCheck
|
||||
f.Fix = i18n.G("No release of %s fixes it, and the registry could not be searched for a fixed image: %s", short, searchErr)
|
||||
case f.Chaos:
|
||||
f.Action = ActionRecipe
|
||||
checkout := i18n.G("the recipe checkout")
|
||||
if f.ChaosVersion != "" {
|
||||
checkout += " (" + i18n.G("deployed with --chaos from %s", f.ChaosVersion) + ")"
|
||||
}
|
||||
f.Fix = i18n.G("Upstream published a fixed image, %s. Use it in %s or the app's override, then run abra app deploy %s --chaos.",
|
||||
strings.Join(found, ", "), checkout, f.App)
|
||||
default:
|
||||
f.Action = ActionRecipe
|
||||
f.Fix = i18n.G("Upstream published a fixed image, %s, but no release of %s uses it yet. Release %s with it, then run abra app upgrade %s.",
|
||||
strings.Join(found, ", "), short, short, f.App)
|
||||
}
|
||||
}
|
||||
|
||||
// upstreamState says why there is no fixed image of img: its tag was not
|
||||
// rebuilt, or rebuilt but still affected.
|
||||
func upstreamState(img ImageRef, current *ImageRef) string {
|
||||
if current != nil && current.Digest != img.Digest {
|
||||
if current.Info != nil && current.Info.Created != nil && current.Info.createdUnusable == "" {
|
||||
return i18n.G("%s was rebuilt on %s but is still affected, and no later tag is fixed",
|
||||
img.NameTag(), current.Info.Created.UTC().Format(time.DateOnly))
|
||||
}
|
||||
return i18n.G("%s was rebuilt but is still affected, and no later tag is fixed", img.NameTag())
|
||||
}
|
||||
return i18n.G("%s has not been rebuilt with a fix, and no later tag is fixed", img.NameTag())
|
||||
}
|
||||
|
||||
// versionFixed reports whether every image of the recipe version that has
|
||||
@@ -212,22 +337,49 @@ func (c *FixChecker) versionFixed(ctx context.Context, f *Finding, version strin
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
ok, _, err := c.imagesFixed(ctx, f, version, refs, names)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
// checkoutFixed reports whether a --chaos redeploy of the app, from its
|
||||
// recipe checkout and overrides, would use fixed images, and which. A
|
||||
// checkout that drops the affected images is not reported: that is more
|
||||
// likely an unrelated change than a fix.
|
||||
func (c *FixChecker) checkoutFixed(ctx context.Context, f *Finding, names map[string]bool) ([]string, bool) {
|
||||
refs, err := c.Checkout(f.App)
|
||||
if err != nil {
|
||||
log.Debug(i18n.G("%s: unable to read the recipe checkout of %s: %s", f.App, f.Recipe, err))
|
||||
return nil, false
|
||||
}
|
||||
ok, used, err := c.imagesFixed(ctx, f, i18n.G("checkout"), refs, names)
|
||||
if err != nil {
|
||||
log.Debug(i18n.G("%s: unable to check the recipe checkout of %s: %s", f.App, f.Recipe, err))
|
||||
return nil, false
|
||||
}
|
||||
return used, ok && len(used) > 0
|
||||
}
|
||||
|
||||
// imagesFixed reports whether every image in refs that has one of the given
|
||||
// names is fixed, and returns those images. where names the recipe version
|
||||
// for debug messages.
|
||||
func (c *FixChecker) imagesFixed(ctx context.Context, f *Finding, where string, refs []string, names map[string]bool) (bool, []string, error) {
|
||||
var used []string
|
||||
for _, ref := range refs {
|
||||
img, err := ParseImageRef("", ref)
|
||||
if err != nil || !names[img.Name] {
|
||||
continue
|
||||
}
|
||||
used = append(used, img.NameTag())
|
||||
cur, err := c.current(ctx, img, f.os, f.arch, true)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return false, used, err
|
||||
}
|
||||
if !fixedByAdvisory(f.Advisory, *cur) {
|
||||
log.Debug(i18n.G("%s %s: %s is not fixed", ShortRecipeName(f.Recipe), version, img.NameTag()))
|
||||
return false, nil
|
||||
log.Debug(i18n.G("%s %s: %s is not fixed", ShortRecipeName(f.Recipe), where, img.NameTag()))
|
||||
return false, used, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
return true, used, nil
|
||||
}
|
||||
|
||||
// current reads the image a reference points to now: by digest if byDigest
|
||||
|
||||
+140
-26
@@ -9,6 +9,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
appPkg "coopcloud.tech/abra/pkg/app"
|
||||
"coopcloud.tech/abra/pkg/recipe"
|
||||
"github.com/go-git/go-git/v5"
|
||||
"github.com/go-git/go-git/v5/plumbing/object"
|
||||
@@ -71,6 +72,19 @@ func TestCheckFixes(t *testing.T) {
|
||||
app("offline", "nc", "1.0.0+35.0.2", "other:1@"+digestOf("c"), true),
|
||||
app("noplatform", "nc", "1.0.0+35.0.2", "nextcloud:35-fpm@"+digestOf("a"), false),
|
||||
app("ranged", "ranged", "1.0.0+1.0.0", "postgres:15@"+digestOf("f"), true),
|
||||
app("upstream", "up", "1.0.0+1.0.0", "frozen:1.0.0@"+digestOf("9"), true),
|
||||
app("digestpin", "dp", "1.0.0+35", "nextcloud:35-fpm@"+digestOf("a"), true),
|
||||
app("unsearchable", "us", "1.0.0+1.0.0", "private:1.0.0@"+digestOf("8"), true),
|
||||
}
|
||||
// the same apps, deployed with --chaos
|
||||
for _, name := range []string{"floating", "fork", "stale", "pinned"} {
|
||||
for _, st := range states {
|
||||
if st.Name == name {
|
||||
st.Name, st.Chaos, st.ChaosVersion = "chaos-"+name, true, "1234abcd+U"
|
||||
states = append(states, st)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
recipes := fakeRecipes{
|
||||
@@ -88,62 +102,111 @@ func TestCheckFixes(t *testing.T) {
|
||||
"1.0.1+35.0.2": {"nextcloud:35.0.2-fpm"},
|
||||
},
|
||||
"ranged": {"1.0.0+1.0.0": {"postgres:15"}},
|
||||
"up": {"1.0.0+1.0.0": {"frozen:1.0.0"}},
|
||||
// the recipe pins the old digest of a tag that has been rebuilt
|
||||
"dp": {"1.0.0+35": {"nextcloud:35-fpm@" + digestOf("a")}},
|
||||
"us": {"1.0.0+1.0.0": {"private:1.0.0"}},
|
||||
}
|
||||
|
||||
// PHP version per tag; a pinned digest a is the old 35-fpm image
|
||||
php := map[string]string{
|
||||
"nextcloud:35-fpm": "8.5.13",
|
||||
"nextcloud:35.0.2-fpm": "8.5.12",
|
||||
"nextcloud:35.0.1-fpm": "8.5.12",
|
||||
"nextcloud:35.0.3-fpm": "8.5.13",
|
||||
"nextcloud:35.0.4-fpm": "8.5.13",
|
||||
"frozen:1.0.0": "8.5.12",
|
||||
"frozen:1.0.1": "8.5.12",
|
||||
"private:1.0.0": "8.5.12",
|
||||
}
|
||||
var fetched []string
|
||||
fetch := func(_ context.Context, img ImageRef, os, arch string) (*ImageInfo, error) {
|
||||
fetched = append(fetched, img.NameTag())
|
||||
php := map[string]string{
|
||||
"nextcloud:35-fpm": "8.5.13",
|
||||
"nextcloud:35.0.2-fpm": "8.5.12",
|
||||
"nextcloud:35.0.1-fpm": "8.5.12",
|
||||
"nextcloud:35.0.3-fpm": "8.5.13",
|
||||
"nextcloud:35.0.4-fpm": "8.5.13",
|
||||
fetched = append(fetched, img.NameTag()+"@"+img.Digest)
|
||||
if img.Digest == digestOf("a") {
|
||||
return &ImageInfo{Digest: digestOf("a"), Env: map[string]string{"PHP_VERSION": "8.5.12"}}, nil
|
||||
}
|
||||
v, ok := php[img.NameTag()]
|
||||
if !ok {
|
||||
return nil, errors.New("registry down")
|
||||
}
|
||||
d := digestOf("d")
|
||||
if img.NameTag() == "nextcloud:35.0.2-fpm" {
|
||||
switch img.NameTag() {
|
||||
case "nextcloud:35.0.2-fpm":
|
||||
d = digestOf("b")
|
||||
case "frozen:1.0.0":
|
||||
d = digestOf("9")
|
||||
case "private:1.0.0":
|
||||
d = digestOf("8")
|
||||
}
|
||||
return &ImageInfo{Digest: d, Env: map[string]string{"PHP_VERSION": v}}, nil
|
||||
}
|
||||
tags := func(_ context.Context, img ImageRef) ([]string, error) {
|
||||
switch img.Name {
|
||||
case "nextcloud":
|
||||
return []string{"35-fpm", "35.0.1-fpm", "35.0.2-fpm", "35.0.3-fpm", "35.0.4-fpm", "latest"}, nil
|
||||
case "frozen":
|
||||
return []string{"1.0.0", "1.0.1"}, nil
|
||||
}
|
||||
return nil, errors.New("unauthorized")
|
||||
}
|
||||
|
||||
// what a --chaos redeploy would use: chaos-fork's checkout already moved
|
||||
// to a fixed image, chaos-stale's still uses the deployed one, and
|
||||
// chaos-pinned's cannot be read
|
||||
checkout := func(app string) ([]string, error) {
|
||||
switch app {
|
||||
case "chaos-fork":
|
||||
return []string{"nextcloud:35.0.3-fpm"}, nil
|
||||
case "chaos-stale":
|
||||
return []string{"nextcloud:35.0.1-fpm"}, nil
|
||||
case "chaos-floating":
|
||||
return []string{"nextcloud:35-fpm"}, nil
|
||||
}
|
||||
return nil, errors.New("no checkout")
|
||||
}
|
||||
|
||||
findings := Evaluate(states, []Advisory{adv}, EvaluateOptions{})
|
||||
require.Len(t, findings, 7)
|
||||
checker := FixChecker{Fetch: fetch, Recipes: recipes}
|
||||
require.Len(t, findings, 14)
|
||||
checker := FixChecker{Fetch: fetch, Tags: tags, Recipes: recipes, Checkout: checkout}
|
||||
checker.CheckFixes(context.Background(), findings)
|
||||
|
||||
got := map[string]Finding{}
|
||||
for _, f := range findings {
|
||||
got[f.App] = f
|
||||
}
|
||||
check := func(app, action, fix string) {
|
||||
t.Helper()
|
||||
assert.Equal(t, action, got[app].Action, app)
|
||||
assert.Equal(t, fix, got[app].Fix, app)
|
||||
assert.Equal(t, action == ActionRecipe || action == ActionUpstream || action == ActionCheck, got[app].NoFix, app)
|
||||
}
|
||||
|
||||
assert.Equal(t, "abra app deploy floating --force && abra audit", got["floating"].Fix)
|
||||
assert.Equal(t, "nextcloud:35.0.2-fpm not rebuilt with a fix; abra app upgrade pinned 1.0.1+35.0.3", got["pinned"].Fix)
|
||||
assert.False(t, got["pinned"].NoFix)
|
||||
check("floating", ActionRedeploy, "The registry's nextcloud:35-fpm now has a fixed image: abra app deploy floating --force && abra audit")
|
||||
check("pinned", ActionUpgrade, "Release 1.0.1+35.0.3 uses fixed images: abra app upgrade pinned 1.0.1+35.0.3")
|
||||
check("fork", ActionRecipe, "Upstream published a fixed image, nextcloud:35.0.3-fpm, but no release of c4dt/nextcloud uses it yet. Release c4dt/nextcloud with it, then run abra app upgrade fork.")
|
||||
// 35.0.2-fpm is newer but not fixed: the oldest fixed tag is suggested
|
||||
check("stale", ActionRecipe, "Upstream published a fixed image, nextcloud:35.0.3-fpm, but no release of stale uses it yet. Release stale with it, then run abra app upgrade stale.")
|
||||
check("offline", ActionRedeploy, "abra app deploy offline --force && abra audit (unchecked: registry unreachable)")
|
||||
check("noplatform", ActionRedeploy, "abra app deploy noplatform --force && abra audit (unchecked: platform unknown)")
|
||||
check("ranged", ActionRecipe, "The advisory names ranged 2.0.0+1.0.0 as fixed, but the latest release is 1.0.0+1.0.0. A release of ranged with the fix is needed.")
|
||||
check("upstream", ActionUpstream, "No fixed image exists yet: frozen:1.0.0 has not been rebuilt with a fix, and no later tag is fixed.")
|
||||
check("digestpin", ActionRecipe, "Upstream published a fixed image, nextcloud:35-fpm (its current image), but no release of dp uses it yet. Release dp with it, then run abra app upgrade digestpin.")
|
||||
check("unsearchable", ActionCheck, "No release of us fixes it, and the registry could not be searched for a fixed image: unauthorized")
|
||||
|
||||
assert.Equal(t, "nextcloud:35.0.2-fpm not rebuilt with a fix; no fixed release of c4dt/nextcloud yet: 16.2.2+35.0.2-fpm is the latest; a new release with a fixed image is needed", got["fork"].Fix)
|
||||
assert.True(t, got["fork"].NoFix)
|
||||
// a chaos deployment is redeployed with --chaos, and fixed in the checkout
|
||||
check("chaos-floating", ActionRedeploy, "The registry's nextcloud:35-fpm now has a fixed image: abra app deploy chaos-floating --chaos && abra audit")
|
||||
check("chaos-fork", ActionRedeploy, "The recipe checkout already uses nextcloud:35.0.3-fpm, which is fixed: abra app deploy chaos-fork --chaos && abra audit")
|
||||
// without a readable checkout, the releases are checked as usual
|
||||
check("chaos-pinned", ActionUpgrade, "Release 1.0.1+35.0.3 uses fixed images: abra app upgrade chaos-pinned 1.0.1+35.0.3")
|
||||
check("chaos-stale", ActionRecipe, "Upstream published a fixed image, nextcloud:35.0.3-fpm. Use it in the recipe checkout (deployed with --chaos from 1234abcd+U) or the app's override, then run abra app deploy chaos-stale --chaos.")
|
||||
|
||||
assert.Equal(t, "nextcloud:35.0.1-fpm not rebuilt with a fix; no fixed release of stale yet: the latest, 1.0.1+35.0.2, still uses nextcloud:35.0.2-fpm; a new release with a fixed image is needed", got["stale"].Fix)
|
||||
assert.True(t, got["stale"].NoFix)
|
||||
|
||||
assert.Equal(t, "abra app deploy offline --force && abra audit (unchecked: registry unreachable)", got["offline"].Fix)
|
||||
assert.Equal(t, "abra app deploy noplatform --force && abra audit (unchecked: platform unknown)", got["noplatform"].Fix)
|
||||
|
||||
assert.Equal(t, "no fixed release of ranged yet: the advisory names 2.0.0+1.0.0, but the latest release is 1.0.0+1.0.0", got["ranged"].Fix)
|
||||
assert.True(t, got["ranged"].NoFix)
|
||||
|
||||
// each image is fetched once
|
||||
// each image is fetched once, by tag or by digest
|
||||
seen := map[string]int{}
|
||||
for _, f := range fetched {
|
||||
seen[f]++
|
||||
}
|
||||
for img, n := range seen {
|
||||
if img != "other:1" {
|
||||
if !strings.HasPrefix(img, "other:1@") {
|
||||
assert.Equal(t, 1, n, img)
|
||||
}
|
||||
}
|
||||
@@ -215,4 +278,55 @@ func TestGitRecipes(t *testing.T) {
|
||||
data, err := os.ReadFile(filepath.Join(dir, "compose.yml"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "local edit\n", string(data))
|
||||
|
||||
}
|
||||
|
||||
func TestCheckoutImages(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
recipeDir := filepath.Join(root, "recipes", "nc")
|
||||
serverDir := filepath.Join(root, "servers", "srv")
|
||||
require.NoError(t, os.MkdirAll(recipeDir, 0o755))
|
||||
require.NoError(t, os.MkdirAll(serverDir, 0o755))
|
||||
|
||||
write := func(file, content string) {
|
||||
require.NoError(t, os.WriteFile(file, []byte(content), 0o644))
|
||||
}
|
||||
write(filepath.Join(recipeDir, "compose.yml"), `version: "3.8"
|
||||
services:
|
||||
app:
|
||||
image: nextcloud:35.0.4-fpm
|
||||
web:
|
||||
image: nginx:${NGINX_TAG:-1.31.8}
|
||||
db:
|
||||
image: postgres:15
|
||||
`)
|
||||
write(filepath.Join(recipeDir, "compose.smtp.yml"), `version: "3.8"
|
||||
services:
|
||||
smtp:
|
||||
image: postfix:3
|
||||
`)
|
||||
// an override outside the recipe directory pins the app image
|
||||
write(filepath.Join(serverDir, "nc.override.yaml"), `version: "3.8"
|
||||
services:
|
||||
app:
|
||||
image: nextcloud:35.0.2-fpm
|
||||
`)
|
||||
|
||||
app := appPkg.App{
|
||||
Name: "nc.example.com",
|
||||
Recipe: recipe.Recipe{Name: "nc", Dir: recipeDir,
|
||||
ComposePath: filepath.Join(recipeDir, "compose.yml")},
|
||||
Env: map[string]string{
|
||||
"COMPOSE_FILE": "compose.yml:../../servers/srv/nc.override.yaml",
|
||||
"NGINX_TAG": "1.31.9",
|
||||
},
|
||||
}
|
||||
|
||||
images, err := CheckoutImages(app)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"nextcloud:35.0.2-fpm", "nginx:1.31.9", "postgres:15"}, images)
|
||||
|
||||
app.Env = map[string]string{"COMPOSE_FILE": "compose.yml:missing.yml"}
|
||||
_, err = CheckoutImages(app)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
@@ -172,6 +172,18 @@ func FetchFromRegistry(ctx context.Context, img ImageRef, os, arch string) (*Ima
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// RegistryTags lists the tags of the image's repository.
|
||||
func RegistryTags(ctx context.Context, img ImageRef) ([]string, error) {
|
||||
if img.named == nil {
|
||||
return nil, errors.New(i18n.G("invalid image reference %s", img.Ref))
|
||||
}
|
||||
ref, err := docker.ParseReference("//" + reference.TrimNamed(img.named).String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return docker.GetRepositoryTags(ctx, &types.SystemContext{}, ref)
|
||||
}
|
||||
|
||||
func stripTagDigest(name string) string {
|
||||
named, err := reference.ParseNormalizedNamed(name)
|
||||
if err != nil {
|
||||
|
||||
@@ -7,9 +7,11 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
appPkg "coopcloud.tech/abra/pkg/app"
|
||||
"coopcloud.tech/abra/pkg/i18n"
|
||||
"coopcloud.tech/abra/pkg/log"
|
||||
"coopcloud.tech/abra/pkg/recipe"
|
||||
"coopcloud.tech/abra/pkg/upstream/stack"
|
||||
"github.com/go-git/go-git/v5"
|
||||
"github.com/go-git/go-git/v5/plumbing"
|
||||
"github.com/go-git/go-git/v5/plumbing/object"
|
||||
@@ -184,6 +186,31 @@ func (g *GitRecipes) Images(name, version string) ([]string, error) {
|
||||
return images, err
|
||||
}
|
||||
|
||||
// CheckoutImages returns the images that abra app deploy --chaos would
|
||||
// deploy for the app: the compose files of its COMPOSE_FILE, read from the
|
||||
// recipe checkout as they are on disk, merged and with the app's .env
|
||||
// values filled in, exactly as deploy does. Overrides outside the recipe
|
||||
// directory are included.
|
||||
func CheckoutImages(app appPkg.App) ([]string, error) {
|
||||
files, err := app.Recipe.GetComposeFiles(app.Env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
compose, err := appPkg.GetAppComposeConfig(app.Name, stack.Deploy{Composefiles: files}, app.Env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var images []string
|
||||
for _, svc := range compose.Services {
|
||||
if svc.Image != "" && !containsString(images, svc.Image) {
|
||||
images = append(images, svc.Image)
|
||||
}
|
||||
}
|
||||
sort.Strings(images)
|
||||
return images, nil
|
||||
}
|
||||
|
||||
var envDefault = regexp.MustCompile(`\$\{[A-Za-z0-9_]+:?-([^}]*)\}`)
|
||||
|
||||
// composeImages extracts services.*.image from a compose file. Variables with
|
||||
|
||||
+12
-6
@@ -18,12 +18,15 @@ import (
|
||||
|
||||
// AppState is what is deployed for one app.
|
||||
type AppState struct {
|
||||
Server string `json:"server"`
|
||||
Name string `json:"name"`
|
||||
Recipe string `json:"recipe"`
|
||||
Version string `json:"version"`
|
||||
Chaos bool `json:"chaos"`
|
||||
Images []ImageRef `json:"images"`
|
||||
Server string `json:"server"`
|
||||
Name string `json:"name"`
|
||||
Recipe string `json:"recipe"`
|
||||
Version string `json:"version"`
|
||||
// Chaos is set for apps deployed with --chaos. Version is then the
|
||||
// release the checkout was based on, and ChaosVersion the commit.
|
||||
Chaos bool `json:"chaos"`
|
||||
ChaosVersion string `json:"chaosVersion,omitempty"`
|
||||
Images []ImageRef `json:"images"`
|
||||
|
||||
// OS and Arch of the server, used to read per-platform image configs.
|
||||
// Empty when unknown or offline.
|
||||
@@ -144,6 +147,9 @@ func collectServer(server string, apps []appPkg.App, opts CollectOptions) ([]App
|
||||
if c := svc.Spec.Labels[fmt.Sprintf("coop-cloud.%s.chaos", stackName)]; c == "true" {
|
||||
st.Chaos = true
|
||||
}
|
||||
if v := svc.Spec.Labels[fmt.Sprintf("coop-cloud.%s.chaos-version", stackName)]; v != "" {
|
||||
st.ChaosVersion = v
|
||||
}
|
||||
|
||||
if svc.Spec.TaskTemplate.ContainerSpec == nil {
|
||||
continue
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"coopcloud.tech/abra/pkg/i18n"
|
||||
"coopcloud.tech/abra/pkg/log"
|
||||
)
|
||||
|
||||
// Limits for the search of fixed tags, to keep registry requests bounded.
|
||||
const (
|
||||
maxRebuildCandidates = 20
|
||||
maxNewerCandidates = 10
|
||||
// rebuildMargin is how much later than the current image a rebuild must
|
||||
// be built. Variants of one version (-fpm, -alpine) usually come out of
|
||||
// the same CI run within minutes; rebuilds come hours or days later.
|
||||
rebuildMargin = time.Hour
|
||||
)
|
||||
|
||||
// tagSearch is the result of findFixedTag.
|
||||
type tagSearch struct {
|
||||
// tag is a fixed tag, or "" if none was found.
|
||||
tag string
|
||||
// sameTag is set when the deployed tag itself now points to a fixed
|
||||
// image, which a redeploy does not pick up because the recipe pins an
|
||||
// older digest.
|
||||
sameTag bool
|
||||
// current is the registry's current image of the deployed tag.
|
||||
current *ImageRef
|
||||
}
|
||||
|
||||
// findFixedTag searches the registry for a fixed image of img, in this
|
||||
// order:
|
||||
//
|
||||
// 1. the deployed tag itself, if its current image is fixed;
|
||||
// 2. later builds of the same version under a suffixed tag, such as
|
||||
// v6.1.0-1 or v6.1.0-fix1 for v6.1.0. Suffixes are not parsed, since
|
||||
// upstreams use many schemes. A candidate must be built at least
|
||||
// rebuildMargin after the tag's current image: this keeps out
|
||||
// pre-releases such as v6.1.0-preprod, built before the release, and
|
||||
// variants built along with it. The latest-built fixed one is chosen;
|
||||
// 3. newer versions of the same form, e.g. v6.1.1 or v6.2.0, but not
|
||||
// v6 or latest: the oldest fixed one is chosen.
|
||||
//
|
||||
// Every candidate is checked against the advisory: whether a tag looks newer
|
||||
// never decides whether it is fixed.
|
||||
func (c *FixChecker) findFixedTag(ctx context.Context, f *Finding, img ImageRef) (tagSearch, error) {
|
||||
var res tagSearch
|
||||
if c.Tags == nil {
|
||||
return res, errors.New(i18n.G("no tag search"))
|
||||
}
|
||||
if img.Tag == "" {
|
||||
return res, errors.New(i18n.G("%s has no tag", img.Name))
|
||||
}
|
||||
|
||||
cur, err := c.current(ctx, img, f.os, f.arch, false)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
res.current = cur
|
||||
if cur.Digest != img.Digest && fixedByAdvisory(f.Advisory, *cur) {
|
||||
res.tag, res.sameTag = img.Tag, true
|
||||
return res, nil
|
||||
}
|
||||
|
||||
tags, err := c.tags(ctx, img)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
tag, err := c.fixedRebuild(ctx, f, img, cur, tags)
|
||||
if err != nil || tag != "" {
|
||||
res.tag = tag
|
||||
return res, err
|
||||
}
|
||||
|
||||
res.tag = c.fixedNewer(ctx, f, img, tags)
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// fixedRebuild returns the latest-built fixed rebuild of img's version.
|
||||
func (c *FixChecker) fixedRebuild(ctx context.Context, f *Finding, img ImageRef, cur *ImageRef, tags []string) (string, error) {
|
||||
var candidates []string
|
||||
for _, t := range tags {
|
||||
if isRebuildTag(img.Tag, t) {
|
||||
candidates = append(candidates, t)
|
||||
}
|
||||
}
|
||||
if len(candidates) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
if cur.Info == nil || cur.Info.Created == nil || cur.Info.createdUnusable != "" {
|
||||
return "", errors.New(i18n.G("the build time of %s is unusable, so %s cannot be checked", img.NameTag(), strings.Join(candidates, ", ")))
|
||||
}
|
||||
after := cur.Info.Created.Add(rebuildMargin)
|
||||
|
||||
sort.Strings(candidates)
|
||||
if len(candidates) > maxRebuildCandidates {
|
||||
log.Debug(i18n.G("%s: checking only %d of %d rebuild tags", img.Name, maxRebuildCandidates, len(candidates)))
|
||||
candidates = candidates[len(candidates)-maxRebuildCandidates:]
|
||||
}
|
||||
|
||||
var best string
|
||||
var bestTime time.Time
|
||||
var unusable []string
|
||||
for _, t := range candidates {
|
||||
ref, err := ParseImageRef("", img.Name+":"+t)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
cand, err := c.current(ctx, ref, f.os, f.arch, false)
|
||||
if err != nil {
|
||||
log.Debug(i18n.G("%s: skipping %s: %s", f.App, ref.NameTag(), err))
|
||||
continue
|
||||
}
|
||||
info := cand.Info
|
||||
switch {
|
||||
case info.Created == nil || info.createdUnusable != "":
|
||||
unusable = append(unusable, t)
|
||||
continue
|
||||
case info.Created.Before(after):
|
||||
log.Debug(i18n.G("%s: skipping %s: built before %s", f.App, ref.NameTag(), img.NameTag()))
|
||||
continue
|
||||
case !fixedByAdvisory(f.Advisory, *cand):
|
||||
log.Debug(i18n.G("%s: %s is not fixed", f.App, ref.NameTag()))
|
||||
continue
|
||||
}
|
||||
if best == "" || info.Created.After(bestTime) {
|
||||
best, bestTime = t, *info.Created
|
||||
}
|
||||
}
|
||||
|
||||
if best == "" && len(unusable) > 0 {
|
||||
return "", errors.New(i18n.G("the build times of %s are unusable", strings.Join(unusable, ", ")))
|
||||
}
|
||||
return best, nil
|
||||
}
|
||||
|
||||
// fixedNewer returns the oldest fixed newer version of img's tag, of the same
|
||||
// form. As for recipe releases, the newest is checked first: if it is not
|
||||
// fixed, none is.
|
||||
func (c *FixChecker) fixedNewer(ctx context.Context, f *Finding, img ImageRef, tags []string) string {
|
||||
base, ok := parseTagForm(img.Tag)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
var newer []tagForm
|
||||
for _, t := range tags {
|
||||
if tf, ok := parseTagForm(t); ok && tf.sameForm(base) && tf.compare(base) > 0 {
|
||||
newer = append(newer, tf)
|
||||
}
|
||||
}
|
||||
if len(newer) == 0 {
|
||||
return ""
|
||||
}
|
||||
sort.Slice(newer, func(i, j int) bool { return newer[i].compare(newer[j]) < 0 })
|
||||
|
||||
fixedAt := func(tf tagForm) bool {
|
||||
ref, err := ParseImageRef("", img.Name+":"+tf.raw)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
cand, err := c.current(ctx, ref, f.os, f.arch, false)
|
||||
if err != nil {
|
||||
log.Debug(i18n.G("%s: skipping %s: %s", f.App, ref.NameTag(), err))
|
||||
return false
|
||||
}
|
||||
return fixedByAdvisory(f.Advisory, *cand)
|
||||
}
|
||||
|
||||
latest := newer[len(newer)-1]
|
||||
if !fixedAt(latest) {
|
||||
return ""
|
||||
}
|
||||
for i, tf := range newer[:len(newer)-1] {
|
||||
if i >= maxNewerCandidates {
|
||||
break
|
||||
}
|
||||
if fixedAt(tf) {
|
||||
return tf.raw
|
||||
}
|
||||
}
|
||||
return latest.raw
|
||||
}
|
||||
|
||||
func (c *FixChecker) tags(ctx context.Context, img ImageRef) ([]string, error) {
|
||||
if r, ok := c.tagsCache[img.Name]; ok {
|
||||
return r.tags, r.err
|
||||
}
|
||||
tctx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
defer cancel()
|
||||
tags, err := c.Tags(tctx, img)
|
||||
c.tagsCache[img.Name] = tagsResult{tags: tags, err: err}
|
||||
return tags, err
|
||||
}
|
||||
|
||||
var (
|
||||
// suffix words of pre-releases and of variants, which are not rebuilds
|
||||
notRebuildWord = regexp.MustCompile(`^(?i)(pre|preprod|rc|beta|alpha|dev|devel|test|snapshot|nightly|edge|canary|pr|alpine|slim|fpm|apache|debian|ubuntu|bookworm|bullseye|trixie|windowsservercore|nanoserver)\d*$`)
|
||||
archWord = regexp.MustCompile(`^(?i)(amd64|arm64|arm64v8|armv7|armv6|arm|386|i386|ppc64le|s390x|riscv64|x86_64|aarch64)$`)
|
||||
digits = regexp.MustCompile(`\d`)
|
||||
)
|
||||
|
||||
// isRebuildTag reports whether tag looks like a later build of base, such as
|
||||
// v6.1.0-1 or v6.1.0-fix1 for v6.1.0: base, a separator, and a suffix with a
|
||||
// number in it. Patch versions (1.2.3 for 1.2), pre-releases, variants and
|
||||
// per-architecture tags are not rebuilds.
|
||||
func isRebuildTag(base, tag string) bool {
|
||||
if len(tag) < len(base)+2 || !strings.HasPrefix(tag, base) {
|
||||
return false
|
||||
}
|
||||
sep, suffix := tag[len(base)], tag[len(base)+1:]
|
||||
if !strings.ContainsRune("-_.+", rune(sep)) {
|
||||
return false
|
||||
}
|
||||
if sep == '.' && suffix[0] >= '0' && suffix[0] <= '9' {
|
||||
return false
|
||||
}
|
||||
if !digits.MatchString(suffix) {
|
||||
return false
|
||||
}
|
||||
|
||||
words := strings.FieldsFunc(suffix, func(r rune) bool { return strings.ContainsRune("-_.+", r) })
|
||||
for _, w := range words {
|
||||
if notRebuildWord.MatchString(w) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return !archWord.MatchString(words[len(words)-1])
|
||||
}
|
||||
|
||||
// tagForm splits a tag such as v6.1.0 or 35.0.2-fpm into prefix ("v"),
|
||||
// version numbers and the rest ("-fpm").
|
||||
type tagForm struct {
|
||||
raw string
|
||||
prefix string
|
||||
nums []int
|
||||
rest string
|
||||
}
|
||||
|
||||
var tagFormRe = regexp.MustCompile(`^([vV]?)(\d+(?:\.\d+)*)(.*)$`)
|
||||
|
||||
func parseTagForm(tag string) (tagForm, bool) {
|
||||
m := tagFormRe.FindStringSubmatch(tag)
|
||||
if m == nil {
|
||||
return tagForm{}, false
|
||||
}
|
||||
tf := tagForm{raw: tag, prefix: m[1], rest: m[3]}
|
||||
for _, p := range strings.Split(m[2], ".") {
|
||||
n, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
return tagForm{}, false
|
||||
}
|
||||
tf.nums = append(tf.nums, n)
|
||||
}
|
||||
return tf, true
|
||||
}
|
||||
|
||||
// sameForm reports whether two tags differ only in their version numbers,
|
||||
// with as many numbers: v6.1.1 has the form of v6.1.0, but v6.1 and
|
||||
// v6.1.0-1 do not.
|
||||
func (t tagForm) sameForm(o tagForm) bool {
|
||||
return t.prefix == o.prefix && t.rest == o.rest && len(t.nums) == len(o.nums)
|
||||
}
|
||||
|
||||
func (t tagForm) compare(o tagForm) int {
|
||||
for i := range t.nums {
|
||||
if i >= len(o.nums) {
|
||||
return 1
|
||||
}
|
||||
if t.nums[i] != o.nums[i] {
|
||||
if t.nums[i] < o.nums[i] {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
}
|
||||
if len(t.nums) < len(o.nums) {
|
||||
return -1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestIsRebuildTag(t *testing.T) {
|
||||
for tag, want := range map[string]bool{
|
||||
"v6.1.0-1": true,
|
||||
"v6.1.0-fix1": true,
|
||||
"v6.1.0_r2": true,
|
||||
"v6.1.0+build3": true,
|
||||
"v6.1.0-1-amd64": false, // per-architecture copy
|
||||
"v6.1.0-arm64": false,
|
||||
"v6.1.0-preprod": false, // pre-release
|
||||
"v6.1.0-rc1": false,
|
||||
"v6.1.0-fpm": false, // variant, no number
|
||||
"v6.1.0-alpine3": false, // variant
|
||||
"v6.1.0.1": false, // a newer version, not a rebuild
|
||||
"v6.1.0": false,
|
||||
"v6.1.01": false,
|
||||
"v6.1.1-1": false, // rebuild of another version
|
||||
"v6.1.0-": false,
|
||||
} {
|
||||
assert.Equal(t, want, isRebuildTag("v6.1.0", tag), tag)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTagForm(t *testing.T) {
|
||||
base, ok := parseTagForm("35.0.2-fpm")
|
||||
require.True(t, ok)
|
||||
for tag, want := range map[string]bool{
|
||||
"35.0.3-fpm": true,
|
||||
"36.0.0-fpm": true,
|
||||
"35.0.3-apache": false,
|
||||
"35-fpm": false,
|
||||
"v35.0.3-fpm": false,
|
||||
} {
|
||||
tf, ok := parseTagForm(tag)
|
||||
require.True(t, ok, tag)
|
||||
assert.Equal(t, want, tf.sameForm(base), tag)
|
||||
}
|
||||
_, ok = parseTagForm("latest")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
const nginxAdvisory = `
|
||||
id: NGINX
|
||||
status: published
|
||||
images:
|
||||
- match: "*"
|
||||
env: { NGINX_VERSION: "<1.31.9" }
|
||||
fix: {strategy: refresh}
|
||||
`
|
||||
|
||||
// fakeImage is one tag in the fake registry.
|
||||
type fakeImage struct {
|
||||
created time.Time
|
||||
nginx string
|
||||
}
|
||||
|
||||
func TestFindFixedTag(t *testing.T) {
|
||||
adv, _, err := ParseAdvisory([]byte(nginxAdvisory))
|
||||
require.NoError(t, err)
|
||||
|
||||
release := time.Date(2026, 11, 13, 13, 0, 0, 0, time.UTC)
|
||||
day := 24 * time.Hour
|
||||
|
||||
search := func(t *testing.T, deployed string, registry map[string]fakeImage) (tagSearch, error) {
|
||||
t.Helper()
|
||||
fetch := func(_ context.Context, img ImageRef, os, arch string) (*ImageInfo, error) {
|
||||
fi, ok := registry[img.Tag]
|
||||
if !ok {
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
created := fi.created
|
||||
return &ImageInfo{Digest: digestOf(string(rune('a' + len(img.Tag)%6))), Created: &created,
|
||||
Env: map[string]string{"NGINX_VERSION": fi.nginx}}, nil
|
||||
}
|
||||
tags := func(_ context.Context, img ImageRef) ([]string, error) {
|
||||
var out []string
|
||||
for tag := range registry {
|
||||
out = append(out, tag)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
c := FixChecker{Fetch: fetch, Tags: tags, cache: map[string]fetchResult{}, tagsCache: map[string]tagsResult{}}
|
||||
f := &Finding{App: "app", Advisory: &adv, os: "linux", arch: "amd64"}
|
||||
img := mustImage(t, "app", "lasuite/frontend:"+deployed+"@"+digestOf("0"), nil)
|
||||
return c.findFixedTag(context.Background(), f, img)
|
||||
}
|
||||
|
||||
t.Run("latest-built fixed rebuild", func(t *testing.T) {
|
||||
res, err := search(t, "v6.1.0", map[string]fakeImage{
|
||||
"v6.1.0": {release, "1.31.8"},
|
||||
"v6.1.0-preprod": {release.Add(-day), "1.31.9"}, // built before the release
|
||||
"v6.1.0-1": {release.Add(6 * day), "1.31.9"}, // fixed rebuild
|
||||
"v6.1.0-1-amd64": {release.Add(6 * day), "1.31.9"}, // per-arch copy
|
||||
"v6.1.0-fix2": {release.Add(7 * day), "1.31.9"}, // later fixed rebuild
|
||||
"v6.1.0-fix3": {release.Add(8 * day), "1.31.8"}, // later, but not fixed
|
||||
"v6.1.0-r1": {release.Add(10 * time.Minute), "1.31.9"}, // same CI run as the release
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "v6.1.0-fix2", res.tag)
|
||||
assert.False(t, res.sameTag)
|
||||
})
|
||||
|
||||
t.Run("rebuild preferred to newer version", func(t *testing.T) {
|
||||
res, err := search(t, "v6.1.0", map[string]fakeImage{
|
||||
"v6.1.0": {release, "1.31.8"},
|
||||
"v6.1.0-1": {release.Add(6 * day), "1.31.9"},
|
||||
"v6.2.0": {release.Add(7 * day), "1.31.9"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "v6.1.0-1", res.tag)
|
||||
})
|
||||
|
||||
t.Run("oldest fixed newer version", func(t *testing.T) {
|
||||
res, err := search(t, "v6.1.0", map[string]fakeImage{
|
||||
"v6.1.0": {release, "1.31.8"},
|
||||
"v6.1.1": {release.Add(day), "1.31.8"},
|
||||
"v6.2.0": {release.Add(2 * day), "1.31.9"},
|
||||
"v7.0.0": {release.Add(3 * day), "1.31.9"},
|
||||
"v6": {release.Add(3 * day), "1.31.9"},
|
||||
"latest": {release.Add(3 * day), "1.31.9"},
|
||||
"main": {release.Add(4 * day), "1.31.9"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "v6.2.0", res.tag)
|
||||
})
|
||||
|
||||
t.Run("no fixed image", func(t *testing.T) {
|
||||
res, err := search(t, "v6.1.0", map[string]fakeImage{
|
||||
"v6.1.0": {release, "1.31.8"},
|
||||
"v6.1.0-preprod": {release.Add(-day), "1.31.9"},
|
||||
"v6.1.1": {release.Add(day), "1.31.8"},
|
||||
"main": {release.Add(day), "1.31.9"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "", res.tag)
|
||||
require.NotNil(t, res.current)
|
||||
})
|
||||
|
||||
t.Run("unusable build time of the release", func(t *testing.T) {
|
||||
_, err := search(t, "v6.1.0", map[string]fakeImage{
|
||||
"v6.1.0": {time.Unix(0, 0).UTC(), "1.31.8"},
|
||||
"v6.1.0-1": {release.Add(6 * day), "1.31.9"},
|
||||
})
|
||||
assert.ErrorContains(t, err, "build time of lasuite/frontend:v6.1.0 is unusable")
|
||||
})
|
||||
|
||||
t.Run("unusable build time of the rebuild", func(t *testing.T) {
|
||||
_, err := search(t, "v6.1.0", map[string]fakeImage{
|
||||
"v6.1.0": {release, "1.31.8"},
|
||||
"v6.1.0-1": {time.Unix(0, 0).UTC(), "1.31.9"},
|
||||
})
|
||||
assert.ErrorContains(t, err, "build times of v6.1.0-1 are unusable")
|
||||
})
|
||||
}
|
||||
|
||||
func TestAffectedLabel(t *testing.T) {
|
||||
adv, _, err := ParseAdvisory([]byte(`
|
||||
id: X
|
||||
status: published
|
||||
recipes:
|
||||
nc: {affected: "<2.0.0"}
|
||||
images:
|
||||
- match: "lasuite/*"
|
||||
env: { NGINX_VERSION: "<1.31.9" }
|
||||
- match: "grafana/*"
|
||||
version: "<12.0.0"
|
||||
- match: "debian:*"
|
||||
created_after: "2026-11-01T00:00:00Z"
|
||||
`))
|
||||
require.NoError(t, err)
|
||||
|
||||
built := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
|
||||
states := []AppState{
|
||||
{Name: "nginx", Recipe: "x", Images: []ImageRef{mustImage(t, "app", "lasuite/frontend:v6.1.0@"+digestOf("a"),
|
||||
&ImageInfo{Env: map[string]string{"NGINX_VERSION": "1.31.8"}})}},
|
||||
{Name: "version", Recipe: "x", Images: []ImageRef{mustImage(t, "app", "grafana/grafana:11.0@"+digestOf("b"),
|
||||
&ImageInfo{Labels: map[string]string{AnnotationVersion: "11.0.1"}})}},
|
||||
{Name: "built", Recipe: "x", Images: []ImageRef{mustImage(t, "app", "debian:12@"+digestOf("c"),
|
||||
&ImageInfo{Created: &built})}},
|
||||
{Name: "noinfo", Recipe: "x", Images: []ImageRef{mustImage(t, "app", "lasuite/backend:v6.1.0@"+digestOf("d"), nil)}},
|
||||
{Name: "recipe", Recipe: "git.coopcloud.tech/coop-cloud/nc", Version: "1.0.0+30.0.1"},
|
||||
}
|
||||
|
||||
got := map[string]string{}
|
||||
for _, f := range Evaluate(states, []Advisory{adv}, EvaluateOptions{}) {
|
||||
got[f.App] = f.Affected
|
||||
}
|
||||
assert.Equal(t, map[string]string{
|
||||
"nginx": "nginx 1.31.8",
|
||||
"version": "grafana 11.0.1",
|
||||
"built": "debian:12 built 2026-10-01",
|
||||
"noinfo": "lasuite/backend:v6.1.0",
|
||||
"recipe": "nc 1.0.0+30.0.1",
|
||||
}, got)
|
||||
}
|
||||
@@ -96,12 +96,10 @@ func PrintTable(t *table.Table) error {
|
||||
|
||||
tWidth, _ := lipgloss.Size(t.String())
|
||||
|
||||
width, _, err := term.GetSize(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if tWidth > width {
|
||||
// Without a terminal (a pipe, cron), there is no width to fit: print the
|
||||
// table as it is instead of failing.
|
||||
width, _, err := term.GetSize(int(os.Stdout.Fd()))
|
||||
if err == nil && tWidth > width {
|
||||
t.Width(width - 10)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package formatter
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -25,3 +28,34 @@ func TestTruncate(t *testing.T) {
|
||||
assert.Equal(t, "abc", Truncate("abcdef", 3))
|
||||
assert.Equal(t, "ab", Truncate("ab", 7))
|
||||
}
|
||||
|
||||
func TestPrintTableWithoutTerminal(t *testing.T) {
|
||||
t.Setenv("ABRA_CI", "")
|
||||
|
||||
// stdout is a pipe, not a terminal
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stdout := os.Stdout
|
||||
os.Stdout = w
|
||||
defer func() { os.Stdout = stdout }()
|
||||
|
||||
table, err := CreateTable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
table.Headers("A", "B")
|
||||
table.Row("one", "two")
|
||||
|
||||
err = PrintTable(table)
|
||||
w.Close()
|
||||
out, _ := io.ReadAll(r)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("PrintTable without a terminal: %s", err)
|
||||
}
|
||||
if !strings.Contains(string(out), "one") {
|
||||
t.Fatalf("table not printed: %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user