Compare commits

..
1 Commits
Author SHA1 Message Date
decentral1se a6d6887127 chore: make deps 2026-05-02 09:58:29 +02:00
521 changed files with 35991 additions and 35182 deletions
+8 -13
View File
@@ -3,22 +3,17 @@ kind: pipeline
name: coopcloud.tech/abra
steps:
- name: make check
image: golang:1.27
image: golang:1.26
commands:
- make check
- name: xgettext-go
image: golang:1.27
environment:
GOPRIVATE: coopcloud.tech
commands:
- go run git.coopcloud.tech/toolshed/xgettext-go@latest
-o pkg/i18n/locales/abra.pot
--keyword=i18n.G
--keyword-ctx=i18n.GC
--sort-output
--add-comments-tag="translators"
$(find . -name "*.go" -not -path "*vendor*" | sort)
image: git.coopcloud.tech/toolshed/drone-xgettext-go:latest
settings:
keyword: i18n.G
keyword_ctx: i18n.GC
out: pkg/i18n/locales/abra.pot
comments_tag: translators
depends_on:
- make check
when:
@@ -43,7 +38,7 @@ steps:
- tag
- name: make test
image: golang:1.27
image: golang:1.26
environment:
ABRA_DIR: /root/.abra_test
commands:
-1
View File
@@ -1 +0,0 @@
vendor/** linguist-generated=true
-3
View File
@@ -7,6 +7,3 @@
/bin
dist/
tests/integration/.bats
tests/resources/path_to_repo
advisories
.devbox
-37
View File
@@ -1,37 +0,0 @@
# AGENTS.md
This is the C4DT fork of [`toolshed/abra`](https://git.coopcloud.tech/toolshed/abra), the Co-op Cloud command-line tool. What differs from upstream is described in [README_C4DT.md](README_C4DT.md); keep that file up to date when adding a change.
## Branches
| Branch | Content |
| --- | --- |
| `main` | Mirror of upstream `toolshed/abra` `main`. No C4DT commits. |
| `c4dt` | The fork's release line: upstream plus all C4DT changes. Release tags are made here. |
| feature branches, e.g. `audit_v1` | Work in progress, merged into `c4dt` when ready. |
- Start new work from `c4dt`, in a feature branch.
- To follow upstream, update `main` from `toolshed/abra`, then merge or rebase `c4dt` onto it. Update the base commit and date in `README.md` and `README_C4DT.md`.
- Changes taken from other forks are cherry-picked with `git cherry-pick -x`, so the original commit stays recorded.
## Tags
Releases are annotated tags on `c4dt`, named `<upstream version>-c4dt.<n>`, e.g. `0.13.0-beta-c4dt.1`:
- `<upstream version>` is the latest upstream tag the fork is based on.
- `<n>` counts the C4DT releases on that base, starting at 1, and restarts at 1 when the upstream version changes.
- Tags are never moved or deleted: users pin them, so a tag must always build the same code.
Build a release with the tag as version, so `abra --version` prints `<tag>-<commit>`:
```bash
go build -ldflags "-X main.Version=<tag> -X main.Commit=$(git rev-parse HEAD)" -o abra ./cmd/abra
```
## Development
- Toolchain: `devbox.json`. Use `devbox run build` and `devbox run test`; the test script sets a temporary `ABRA_DIR`, which the tests require.
- Dependencies are vendored: after changing `go.mod`, run `go mod vendor`.
- `abra audit` is designed in [`doc/DesignAudit.md`](doc/DesignAudit.md), which also lists what later versions will add. Keep the design and the code in sync.
- Advisories for `abra audit` live in a separate repository, [`c4dt/advisories`](https://git.coopcloud.tech/c4dt/advisories), under `advisories/`.
- User-facing strings are wrapped in `i18n.G`.
+2 -2
View File
@@ -1,5 +1,5 @@
# Build image
FROM golang:1.27-alpine AS build
FROM golang:1.26-alpine AS build
ENV GOPRIVATE=coopcloud.tech
@@ -15,7 +15,7 @@ WORKDIR /app
RUN CGO_ENABLED=0 make build
FROM alpine:3.24
FROM alpine:3.22
RUN apk add --no-cache \
ca-certificates \
+8 -12
View File
@@ -1,5 +1,5 @@
ABRA := ./cmd/abra
XGETTEXT := go run git.coopcloud.tech/toolshed/xgettext-go@latest
XGETTEXT := ./bin/xgettext-go
COMMIT := $(shell git rev-list -1 HEAD)
GOPATH := $(shell go env GOPATH)
GOVERSION := 1.26
@@ -62,8 +62,8 @@ update-po:
done
.PHONY: update-pot
update-pot:
@$(XGETTEXT) \
update-pot: $(XGETTEXT)
@${XGETTEXT} \
-o pkg/i18n/locales/$(DOMAIN).pot \
--keyword=i18n.G \
--keyword-ctx=i18n.GC \
@@ -71,6 +71,11 @@ update-pot:
--add-comments-tag="translators" \
$$(find . -name "*.go" -not -path "*vendor*" | sort)
${XGETTEXT}:
@mkdir -p ./bin && \
wget -O ./bin/xgettext-go https://git.coopcloud.tech/toolshed/xgettext-go/raw/branch/main/xgettext-go && \
chmod +x ./bin/xgettext-go
.PHONY: update-pot-po-metadata
update-pot-po-metadata:
@sed -i "s/charset=CHARSET/charset=UTF-8/g" pkg/i18n/locales/*.po pkg/i18n/locales/*.pot
@@ -84,12 +89,3 @@ build-mo:
release:
@goreleaser release --clean
# TEST_INTEGRATION_FILES overrides the default of running all test files
ifdef TEST_INTEGRATION_FILES
test_files := $(TEST_INTEGRATION_FILES);
else
test_files := *;
endif
test-integration: build
@bats -Tp --verbose-run tests/integration/$(test_files)
-4
View File
@@ -5,10 +5,6 @@
[![Go Reference](https://pkg.go.dev/badge/coopcloud.tech/abra.svg)](https://pkg.go.dev/coopcloud.tech/abra)
[![Translation status](https://translate.coopcloud.tech/widget/co-op-cloud/svg-badge.svg)](https://translate.coopcloud.tech/engage/co-op-cloud/)
> [!NOTE]
> This is an LLM-modified version of `abra`, based on upstream [`toolshed/abra`](https://git.coopcloud.tech/toolshed/abra) `main` of 2026-11-18 (`0.13.0-beta` + 163 commits, `9023bb87`).
> See [README_C4DT.md](README_C4DT.md) for the differences.
The Co-op Cloud utility belt 🎩🐇
<a href="https://github.com/egonelbre/gophers"><img align="right" width="150" src="https://github.com/egonelbre/gophers/raw/master/.thumb/sketch/adventure/poking-fire.png"/></a>
-39
View File
@@ -1,39 +0,0 @@
# C4DT changes to `abra`
This fork of [`toolshed/abra`](https://git.coopcloud.tech/toolshed/abra) is maintained by C4DT. The changes were made with the help of an LLM coding assistant.
It is based on upstream `main` at commit `9023bb87` of 2026-11-18, which is 163 commits after the `0.13.0-beta` tag.
Releases are tags on the `c4dt` branch, named `<upstream version>-c4dt.<n>`, e.g. `0.13.0-beta-c4dt.1`. Pin a tag rather than following a branch. See [AGENTS.md](AGENTS.md) for the branch and tag conventions.
## Overview
| Change | Summary |
| --- | --- |
| [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
### Digest pinning
Some upstream images, such as `nextcloud`, are rebuilt under the same tag, so the tag alone cannot tell a vulnerable image from a fixed one. Recipes can now pin an image to a digest, for example `nextcloud:34.0.5-fpm@sha256:...`. `abra recipe upgrade` keeps the digest in sync: when it moves a pinned image to a new tag, it writes the new tag's digest, and when the current tag was re-published upstream, it warns and offers to update the pin. A pinned digest also makes a failed registry lookup at deploy time visible, instead of Docker silently keeping an old local image. To support this, `pkg/client/registry.go` gained `GetRegistryDigest`, which returns the index digest that Docker resolves `image:tag` to, and now requests OCI image indexes, which many multi-arch images on Docker Hub require. Commit `e5804d22`.
### `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). 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`.
+5 -6
View File
@@ -151,12 +151,11 @@ checkout as-is. Recipe commit hashes are also supported as values for
stackName := app.StackName()
deployOpts := stack.Deploy{
Composefiles: composeFiles,
Namespace: stackName,
Prune: false,
ResolveImage: stack.ResolveImageAlways,
Detach: false,
SendRegistryAuth: true,
Composefiles: composeFiles,
Namespace: stackName,
Prune: false,
ResolveImage: stack.ResolveImageAlways,
Detach: false,
}
compose, err := appPkg.GetAppComposeConfig(app.Name, deployOpts, app.Env)
if err != nil {
+1 -7
View File
@@ -222,13 +222,7 @@ synchronize your local app environment values with what is deployed live.`),
mergedEnv[k] = v
}
// The recipe version is always carried by TYPE (RECIPE, when present,
// is a bare source pointer). Stamp the deployed version onto TYPE and
// leave RECIPE untouched so the two never drift apart.
if t, ok := mergedEnv["TYPE"]; ok {
name, _, _ := strings.Cut(t, ":")
mergedEnv["TYPE"] = fmt.Sprintf("%s:%s", name, version)
} else {
if !strings.Contains(recipeEnvVar, ":") {
mergedEnv[recipeKey] = fmt.Sprintf("%s:%s", mergedEnv[recipeKey], version)
}
+2 -22
View File
@@ -32,18 +32,6 @@ deploy <domain>" to do so.
You can see what recipes are available (i.e. values for the [recipe] argument)
by running "abra recipe ls".
In addition to short catalogue names, [recipe] also accepts arbitrary git
URLs to use a recipe from outside the catalogue (e.g. a fork or work in
progress). Any of these forms is accepted:
abra app new git.example.com/user/recipe
abra app new https://git.example.com/user/recipe
abra app new git@git.example.com:user/recipe
In that case a RECIPE=<canonical name> line is written to the app's .env
file so a subsequent "abra app deploy" (on this or another machine) will
re-fetch the recipe from the same git source.
Recipe commit hashes are supported values for "[version]".
Passing the "--secrets/-S" flag will automatically generate secrets for your
@@ -124,11 +112,7 @@ var AppNewCommand = &cobra.Command{
}
}
if recipeVersion != "" {
if _, err := recipe.EnsureVersion(recipeVersion); err != nil {
log.Fatal(err)
}
} else if len(recipeVersions) > 0 {
if len(recipeVersions) > 0 {
latest := recipeVersions[len(recipeVersions)-1]
for tag := range latest {
recipeVersion = tag
@@ -307,7 +291,7 @@ func ensureDomainFlag(recipe recipePkg.Recipe, server string) error {
if appDomain == "" && !internal.NoInput {
prompt := &survey.Input{
Message: i18n.G("Specify app domain"),
Default: fmt.Sprintf("%s.%s", recipe.ShortName(), server),
Default: fmt.Sprintf("%s.%s", recipe.Name, server),
}
if err := survey.AskOne(prompt, &appDomain); err != nil {
return err
@@ -318,10 +302,6 @@ func ensureDomainFlag(recipe recipePkg.Recipe, server string) error {
return errors.New(i18n.G("no domain provided"))
}
if strings.ContainsAny(appDomain, "/\\") {
return errors.New(i18n.G("invalid domain '%s': must not contain '/' or '\\'", appDomain))
}
return nil
}
+5 -12
View File
@@ -166,12 +166,11 @@ beforehand. See "abra app backup" for more.`),
stackName := app.StackName()
deployOpts := stack.Deploy{
Composefiles: composeFiles,
Namespace: stackName,
Prune: false,
ResolveImage: stack.ResolveImageAlways,
Detach: false,
SendRegistryAuth: true,
Composefiles: composeFiles,
Namespace: stackName,
Prune: false,
ResolveImage: stack.ResolveImageAlways,
Detach: false,
}
compose, err := appPkg.GetAppComposeConfig(app.Name, deployOpts, app.Env)
@@ -188,12 +187,6 @@ beforehand. See "abra app backup" for more.`),
appPkg.SetChaosVersionLabel(compose, stackName, chosenDowngrade)
}
// NOTE: stamp the deployed version label ourselves rather than relying
// on the value baked into the recipe's compose.yml. Git-URL/WIP recipes
// often carry a stale or missing label, which would otherwise leave the
// live deployment reporting the wrong version after a rollback.
appPkg.SetVersionLabel(compose, stackName, chosenDowngrade)
// Gather secrets
secretInfo, err := deploy.GatherSecretsForDeploy(cl, app, internal.ShowUnchanged)
if err != nil {
+9 -30
View File
@@ -178,12 +178,11 @@ beforehand. See "abra app backup" for more.`),
stackName := app.StackName()
deployOpts := stack.Deploy{
Composefiles: composeFiles,
Namespace: stackName,
Prune: false,
ResolveImage: stack.ResolveImageAlways,
Detach: false,
SendRegistryAuth: true,
Composefiles: composeFiles,
Namespace: stackName,
Prune: false,
ResolveImage: stack.ResolveImageAlways,
Detach: false,
}
compose, err := appPkg.GetAppComposeConfig(app.Name, deployOpts, app.Env)
@@ -200,12 +199,6 @@ beforehand. See "abra app backup" for more.`),
appPkg.SetChaosVersionLabel(compose, stackName, chosenUpgrade)
}
// NOTE: stamp the deployed version label ourselves rather than relying
// on the value baked into the recipe's compose.yml. Git-URL/WIP recipes
// often carry a stale or missing label, which would otherwise leave the
// live deployment reporting the wrong version after an upgrade.
appPkg.SetVersionLabel(compose, stackName, chosenUpgrade)
envVars, err := appPkg.CheckEnv(app)
if err != nil {
log.Fatal(err)
@@ -352,17 +345,9 @@ func getReleaseNotes(
return errors.New(i18n.G("parsing chosen upgrade version failed: %s", err))
}
// The deployed version can be "unknown" (e.g. deployed without a version
// label, as is common for git-URL/work-in-progress recipes). In that case
// there is no lower bound to filter by, so we gather notes for every
// version below the chosen one instead of failing.
var parsedDeployedVersion tagcmp.Tag
haveDeployedVersion := deployMeta.Version != config.UNKNOWN_DEFAULT
if haveDeployedVersion {
parsedDeployedVersion, err = tagcmp.Parse(deployMeta.Version)
if err != nil {
return errors.New(i18n.G("parsing deployment version failed: %s", err))
}
parsedDeployedVersion, err := tagcmp.Parse(deployMeta.Version)
if err != nil {
return errors.New(i18n.G("parsing deployment version failed: %s", err))
}
for _, version := range internal.SortVersionsDesc(versions) {
@@ -371,7 +356,7 @@ func getReleaseNotes(
return errors.New(i18n.G("parsing recipe version failed: %s", err))
}
if (!haveDeployedVersion || parsedVersion.IsGreaterThan(parsedDeployedVersion)) &&
if parsedVersion.IsGreaterThan(parsedDeployedVersion) &&
parsedVersion.IsLessThan(parsedChosenUpgrade) {
note, err := app.Recipe.GetReleaseNotes(version, app.Domain)
if err != nil {
@@ -434,12 +419,6 @@ func validateUpgradeVersionArg(
return errors.New(i18n.G("'%s' is not a known version for %s", specificVersion, app.Recipe.Name))
}
// Without a known deployed version we cannot tell whether the requested
// version is an upgrade; trust the explicit choice rather than failing.
if deployMeta.Version == config.UNKNOWN_DEFAULT {
return nil
}
parsedDeployedVersion, err := tagcmp.Parse(deployMeta.Version)
if err != nil {
return errors.New(i18n.G("'%s' is not a known version", deployMeta.Version))
-186
View File
@@ -1,186 +0,0 @@
// Package audit implements the `abra audit` command.
package audit
import (
"context"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"coopcloud.tech/abra/cli/internal"
appPkg "coopcloud.tech/abra/pkg/app"
auditPkg "coopcloud.tech/abra/pkg/audit"
"coopcloud.tech/abra/pkg/config"
"coopcloud.tech/abra/pkg/i18n"
"coopcloud.tech/abra/pkg/log"
"coopcloud.tech/abra/pkg/recipe"
"github.com/spf13/cobra"
)
// AuditCommand audits all deployed apps on all servers.
var AuditCommand = &cobra.Command{
// translators: `abra audit` command
Use: i18n.G("audit [flags]"),
// translators: Short description for `abra audit` command
Short: i18n.G("Audit deployed apps against known advisories"),
Long: i18n.G(`Check every deployed app on every server against a curated list of
advisories, and suggest how to fix what fails.
The advisories are pulled from %s into $ABRA_DIR/advisories
on every run. If the repository cannot be reached, the local copy is used.
Only published advisories are applied; use --include-drafts to also apply
drafts, e.g. to try a new advisory before publishing it.
The audit needs an explicitly chosen abra directory: set $ABRA_DIR, or set
abraDir in an abra.yaml file in the current directory or one of its parents.
Only failing apps are listed. The exit code is 0 when nothing fails, and 1
otherwise.`, auditPkg.DefaultAdvisoriesURL),
Example: i18n.G(` # audit all apps on all servers
ABRA_DIR=~/.abra abra audit
# also apply advisories that are still drafts
abra audit --include-drafts`),
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
os.Exit(run())
},
}
func run() int {
abraDir := config.ABRA_DIR_EXPLICIT
if abraDir == "" {
log.Fatal(i18n.G("abra audit needs an explicitly chosen abra directory: set $ABRA_DIR, or abraDir in an abra.yaml file"))
}
advDir := filepath.Join(abraDir, "advisories")
if err := auditPkg.SyncAdvisories(advDir, auditPkg.DefaultAdvisoriesURL, internal.Offline); err != nil {
log.Fatal(err)
}
advisories, warnings, err := auditPkg.LoadAdvisories(filepath.Join(advDir, "advisories"))
if err != nil {
log.Fatal(err)
}
for _, w := range warnings {
log.Warn(w)
}
evalOpts := auditPkg.EvaluateOptions{IncludeDrafts: includeDrafts}
var used, drafts int
for _, a := range advisories {
if evalOpts.Applies(a) {
used++
if a.Status == auditPkg.StatusDraft {
drafts++
}
}
}
log.Debug(i18n.G("loaded %d advisories, using %d", len(advisories), used))
if includeDrafts {
log.Info(i18n.G("including %d draft advisories, which have not been reviewed yet", drafts))
}
if entries, err := os.ReadDir(config.SERVERS_DIR); err == nil && len(entries) == 0 {
log.Info(i18n.G("no apps found in %s", config.SERVERS_DIR))
return 0
}
appFiles, err := appPkg.LoadAppFiles("") // "" means all servers
if err != nil {
log.Fatal(err)
}
apps, err := appPkg.GetApps(appFiles, "")
if err != nil {
log.Fatal(err)
}
if len(apps) == 0 {
log.Info(i18n.G("no apps found in %s", config.SERVERS_DIR))
return 0
}
states, serverErrs := auditPkg.CollectState(apps, auditPkg.CollectOptions{Offline: internal.Offline})
findings := auditPkg.Evaluate(states, advisories, evalOpts)
if !internal.Offline {
var recipes []recipe.Recipe
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)
}
for _, f := range findings {
for _, r := range f.Reasons {
log.Debug(fmt.Sprintf("%s %s: %s", f.App, f.Advisory.ID, r))
}
}
sort.SliceStable(findings, func(i, j int) bool {
if findings[i].Server != findings[j].Server {
return findings[i].Server < findings[j].Server
}
return findings[i].App < findings[j].App
})
if len(findings) > 0 || len(serverErrs) > 0 {
if err := printReport(findings, serverErrs); err != nil {
log.Fatal(err)
}
}
servers := make(map[string]bool)
for _, st := range states {
servers[st.Server] = true
}
log.Info(i18n.G(
"audit done: deployed apps: %d, servers: %d, advisories: %d, findings: %d, unreachable servers: %d",
len(states), len(servers), used, len(findings), len(serverErrs),
))
// findings that the operator cannot fix alone, by who has to act
waiting := make(map[string][]string)
for _, f := range findings {
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)))
}
}
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 {
return 1
}
return 0
}
var includeDrafts bool
func init() {
AuditCommand.Flags().BoolVar(
&includeDrafts,
i18n.G("include-drafts"),
false,
i18n.G("also apply draft advisories, to try them before publishing"),
)
}
-194
View File
@@ -1,194 +0,0 @@
package audit
import (
"fmt"
"os"
"strconv"
"strings"
auditPkg "coopcloud.tech/abra/pkg/audit"
"coopcloud.tech/abra/pkg/formatter"
"coopcloud.tech/abra/pkg/i18n"
"golang.org/x/term"
)
// printReport prints a narrow overview table, followed by a numbered list
// with the fix for each row. Long texts do not fit in a table, so they go in
// the list, wrapped to the terminal width.
func printReport(findings []auditPkg.Finding, serverErrs []auditPkg.ServerError) error {
servers := make(map[string]bool)
for _, f := range findings {
servers[f.Server] = true
}
showServer := len(servers) > 1
if len(findings) > 0 {
table, err := formatter.CreateTable()
if err != nil {
return err
}
headers := []string{"#"}
if showServer {
headers = append(headers, i18n.G("SERVER"))
}
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 {
row := []string{strconv.Itoa(i + 1)}
if showServer {
row = append(row, f.Server)
}
row = append(row, f.App, auditPkg.ShortRecipeName(f.Recipe), displayVersion(f), f.Affected, f.Advisory.Severity, displayAction(f))
table.Row(row...)
}
if err := formatter.PrintTable(table); err != nil {
return err
}
fmt.Println()
width := termWidth()
for i, f := range findings {
prefix := fmt.Sprintf("%d. ", i+1)
fmt.Println(wrap(prefix+f.App+": "+fixLine(f), width, strings.Repeat(" ", len(prefix))))
}
}
if len(serverErrs) > 0 {
if len(findings) > 0 {
fmt.Println()
}
width := termWidth()
for _, e := range serverErrs {
fmt.Println(wrap(i18n.G("unreachable: %s: %s", e.Server, shortError(e.Err)), width, " "))
}
}
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 {
if os.Getenv("ABRA_CI") == "1" {
return 0
}
w, _, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil || w < 40 {
return 0
}
return w - 1
}
// wrap breaks text into lines of at most width characters at spaces,
// indenting continuation lines. A width of 0 disables wrapping.
func wrap(text string, width int, indent string) string {
if width <= 0 || len(text) <= width {
return text
}
var lines []string
line := ""
for _, word := range strings.Fields(text) {
switch {
case line == "":
line = word
case len(line)+1+len(word) > width:
lines = append(lines, line)
line = indent + word
default:
line += " " + word
}
}
if line != "" {
lines = append(lines, line)
}
return strings.Join(lines, "\n")
}
// shortError keeps the useful part of docker/SSH connection errors, which
// otherwise contain several lines of boilerplate.
func shortError(err error) string {
msg := err.Error()
if i := strings.LastIndex(msg, "stderr="); i >= 0 {
msg = msg[i+len("stderr="):]
}
return strings.TrimSpace(msg)
}
-53
View File
@@ -1,53 +0,0 @@
package audit
import (
"errors"
"testing"
auditPkg "coopcloud.tech/abra/pkg/audit"
"github.com/stretchr/testify/assert"
)
func TestWrap(t *testing.T) {
assert.Equal(t, "short", wrap("short", 40, " "))
assert.Equal(t, "1. one two\n three\n four five", wrap("1. one two three four five", 12, " "))
assert.Equal(t, "no wrapping at all here", wrap("no wrapping at all here", 0, " "))
}
func TestShortError(t *testing.T) {
err := errors.New(`error during connect: Get "http://docker.example.com/v1.51/info": command [ssh -- host docker system dial-stdio] has exited with exit status 255, please make sure the URL is valid, and Docker 18.09 or later is installed on the remote host: stderr=ssh: connect to host srv port 22: No route to host
`)
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))
}
+3 -9
View File
@@ -59,15 +59,9 @@ func ValidateRecipe(args []string, cmdName string) recipe.Recipe {
log.Fatal(i18n.G("no recipe name provided"))
}
recipeName = recipe.NormalizeRecipeName(recipeName)
lookupName := recipeName
if i := strings.LastIndex(lookupName, ":"); i >= 0 {
lookupName = lookupName[:i]
}
if _, ok := knownRecipes[lookupName]; !ok {
if !strings.Contains(lookupName, "/") {
log.Fatal(i18n.G("no recipe '%s' exists? pass a git URL (e.g. https://git.example.com/user/recipe) to use a recipe outside the catalogue", lookupName))
if _, ok := knownRecipes[recipeName]; !ok {
if !strings.Contains(recipeName, "/") {
log.Fatal(i18n.G("no recipe '%s' exists?", recipeName))
}
}
-45
View File
@@ -2,13 +2,11 @@ package recipe
import (
"fmt"
"path"
"sort"
"strconv"
"strings"
"coopcloud.tech/abra/cli/internal"
"coopcloud.tech/abra/pkg/config"
"coopcloud.tech/abra/pkg/formatter"
"coopcloud.tech/abra/pkg/i18n"
"coopcloud.tech/abra/pkg/log"
@@ -43,7 +41,6 @@ var RecipeListCommand = &cobra.Command{
headers := []string{
i18n.G("name"),
i18n.G("source"),
i18n.G("category"),
i18n.G("status"),
i18n.G("healthcheck"),
@@ -59,7 +56,6 @@ var RecipeListCommand = &cobra.Command{
for _, recipe := range recipes {
row := []string{
recipe.Name,
i18n.G("catalogue"),
recipe.Category,
strconv.Itoa(recipe.Features.Status),
recipe.Features.Healthcheck,
@@ -80,23 +76,6 @@ var RecipeListCommand = &cobra.Command{
}
}
externals := externalRecipes(catl)
sort.Strings(externals)
for _, name := range externals {
row := []string{
name,
i18n.G("external"),
"-", "-", "-", "-", "-", "-", "-",
}
if pattern != "" {
if !strings.Contains(name, pattern) {
continue
}
}
table.Row(row...)
rows = append(rows, row)
}
if len(rows) > 0 {
if internal.MachineReadable {
out, err := formatter.ToJSON(headers, rows)
@@ -114,30 +93,6 @@ var RecipeListCommand = &cobra.Command{
},
}
// externalRecipes returns canonical names of locally-cloned recipes that
// were sourced from an arbitrary git URL (i.e. they carry a .abra-source
// sidecar) and are not already listed in the catalogue.
func externalRecipes(catl recipe.RecipeCatalogue) []string {
dirs, err := recipe.GetRecipesLocal()
if err != nil {
log.Debug(i18n.G("can't read local recipes: %s", err))
return nil
}
var names []string
for _, dir := range dirs {
canonical := recipe.ReadRecipeSource(path.Join(config.RECIPES_DIR, dir))
if canonical == "" {
continue
}
if _, inCatalogue := catl[canonical]; inCatalogue {
continue
}
names = append(names, canonical)
}
return names
}
var (
pattern string
)
-51
View File
@@ -129,9 +129,6 @@ interface.`),
log.Fatal(err)
}
// digest pinned images shared between services are only checked once
digestChecked := make(map[string]bool)
for _, service := range config.Services {
img, err := reference.ParseNormalizedNamed(service.Image)
if err != nil {
@@ -181,13 +178,6 @@ interface.`),
sort.Sort(tagcmp.ByTagDesc(compatible))
if canonical, ok := img.(reference.Canonical); ok && !digestChecked[service.Image] {
digestChecked[service.Image] = true
if err := refreshDigest(recipe, img, image, canonical.Digest().String()); err != nil {
log.Fatal(err)
}
}
if len(compatible) == 0 && !allTags {
log.Info(i18n.G("no new versions available for %s, assuming %s is the latest (use -a/--all-tags to see all anyway)", image, tag))
continue // skip on to the next tag and don't update any compose files
@@ -374,47 +364,6 @@ interface.`),
},
}
// refreshDigest checks whether the current tag of a digest pinned image was
// re-published upstream with a new digest and offers to update the pin.
func refreshDigest(recipe recipePkg.Recipe, img reference.Named, image, digest string) error {
tag := img.(reference.NamedTagged).Tag()
registryDigest, err := client.GetRegistryDigest(img, tag)
if err != nil {
return err
}
if registryDigest == digest {
log.Debug(i18n.G("digest of %s:%s is up to date", image, tag))
return nil
}
log.Warn(i18n.G("%s:%s was re-published upstream (digest %s → %s)", image, tag, digest, registryDigest))
update := false
if !internal.NoInput {
prompt := &survey.Confirm{
Message: i18n.G("update digest of %s:%s?", image, tag),
Default: true,
}
if err := survey.AskOne(prompt, &update); err != nil {
return err
}
}
if !update {
return nil
}
if _, err := recipe.UpdateTag(image, tag); err != nil {
return err
}
log.Info(i18n.G("digest updated for %s:%s", image, tag))
return nil
}
var (
allTags bool
createCommit bool
+1 -5
View File
@@ -7,7 +7,6 @@ import (
"strings"
"coopcloud.tech/abra/cli/app"
"coopcloud.tech/abra/cli/audit"
"coopcloud.tech/abra/cli/catalogue"
"coopcloud.tech/abra/cli/internal"
"coopcloud.tech/abra/cli/recipe"
@@ -86,12 +85,10 @@ func Run(version, commit string) {
Config:
$ABRA_DIR: %s`, config.ABRA_DIR),
Version: fmt.Sprintf("%s-%s", version, formatter.Truncate(commit, 7)),
Version: fmt.Sprintf("%s-%s", version, commit[:7]),
ValidArgs: []string{
// translators: `abra app` command for autocompletion
i18n.G("app"),
// translators: `abra audit` command for autocompletion
i18n.G("audit"),
// translators: `abra autocomplete` command for autocompletion
i18n.G("autocomplete"),
// translators: `abra catalogue` command for autocompletion
@@ -257,7 +254,6 @@ Config:
AutocompleteCommand,
manCommand,
app.AppCommand,
audit.AuditCommand,
catalogue.CatalogueCommand,
server.ServerCommand,
recipe.RecipeCommand,
+1 -1
View File
@@ -16,7 +16,7 @@ func main() {
Version = "dev"
}
if Commit == "" {
Commit = "unknown-commit"
Commit = " "
}
cli.Run(Version, Commit)
-17
View File
@@ -1,17 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/main/.schema/devbox.schema.json",
"packages": [
"go@1.27",
"gnumake@latest",
"gettext@latest",
"gnused@latest"
],
"shell": {
"scripts": {
"build": "make build",
"test": "export ABRA_DIR=\"$(mktemp -d)/abra\"; rc=0; make test || rc=$?; rm -rf \"$(dirname \"$ABRA_DIR\")\"; exit $rc",
"update-pot": "make update-pot",
"i18n": "make i18n"
}
}
}
-305
View File
@@ -1,305 +0,0 @@
{
"lockfile_version": "1",
"packages": {
"gettext@latest": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473#gettext",
"source": "devbox-search",
"version": "1.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/36c168mc93w4mlmqknam03ffyi6qg0w6-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/38mvyy6a3ga3xqbzzbzfhpmmd4dll8hl-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/4i2r8pmdirlpig74ymxmi03sgl0inyd4-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/ml58bdjablvqamxwc28ws5y9222hdvpx-gettext-1.0-info"
}
],
"store_path": "/nix/store/36c168mc93w4mlmqknam03ffyi6qg0w6-gettext-1.0"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/qh35hki623iqrj2mqfxnzjqawxn93gk7-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/v0arqmc3cx4ls1vwg4c62kz7apcn76ml-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/4ficj1yfkd8bn17mlv81jsib04hfyg8c-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/w0slr4m7ywbkmlm8dbksjp22adcab935-gettext-1.0-info"
}
],
"store_path": "/nix/store/qh35hki623iqrj2mqfxnzjqawxn93gk7-gettext-1.0"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/r87hlf9pn8q3a8rnplzhy9lbgaadqcr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/xmssbi5i2w3fv67hrv6c29wdiv8gxywi-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/j4lz4zqicd1mw2l5c272ialxhl0nkc0b-gettext-1.0-info"
}
],
"store_path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8qdw9shgr7dd3315jim8sfva2dnhq86c-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/4acc3iagl3xlljb1aqn8j25vx5n400bc-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/dnz19fkr7spnpc7affh8ivcmk32g9xda-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/v3z399ilsdjn461y0l2gi8h0z7jzsy6a-gettext-1.0-info"
}
],
"store_path": "/nix/store/8qdw9shgr7dd3315jim8sfva2dnhq86c-gettext-1.0"
}
}
},
"github:NixOS/nixpkgs/nixpkgs-unstable": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473?lastModified=1792506237&narHash=sha256-Q%2F8KLB6jNfpaUN1HAedE%2Fu%2FEt9feE%2FzYSsutBLKrCFk%3D"
},
"gnumake@latest": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473#gnumake",
"source": "devbox-search",
"version": "4.4.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/306s97mvw5slpgg7hnb26xy37dhy4xk0-gnumake-4.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/g0hyk9rpf10di0l5x6gxjahh5rip30kn-gnumake-4.4.1-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/xl1nz3znzjb27wrig0vrf5fj3z7jqh5s-gnumake-4.4.1-doc"
},
{
"name": "info",
"path": "/nix/store/99bqn610vynhvhwg8srd9g2l990cfa7a-gnumake-4.4.1-info"
}
],
"store_path": "/nix/store/306s97mvw5slpgg7hnb26xy37dhy4xk0-gnumake-4.4.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/nk0i2hc4x8qpshj326jzn36hkbgi7j7z-gnumake-4.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/nacivbyfzp1w0xydskbxrkapp2gn552s-gnumake-4.4.1-man",
"default": true
},
{
"name": "debug",
"path": "/nix/store/f7yag335k3y4ymn9hb5q1yzqc1njf1hi-gnumake-4.4.1-debug"
},
{
"name": "doc",
"path": "/nix/store/782lakmsm9nxf4hpnn8whmq541cphv6r-gnumake-4.4.1-doc"
},
{
"name": "info",
"path": "/nix/store/51cb4z2jrvqdnab9cc8hjf478c8f55hw-gnumake-4.4.1-info"
}
],
"store_path": "/nix/store/nk0i2hc4x8qpshj326jzn36hkbgi7j7z-gnumake-4.4.1"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/0bg5b97b9hbhz8907bfcrch1i116xppa-gnumake-4.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/wb4yn3d7vmi1hr4f8pz38rjvcl7f70ma-gnumake-4.4.1-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/3b9cjf16jx4ncpp3b4k6m8q01nxsrw1n-gnumake-4.4.1-doc"
},
{
"name": "info",
"path": "/nix/store/rriz5p4q8a6sca7sw3p3js1m5dl09ia8-gnumake-4.4.1-info"
}
],
"store_path": "/nix/store/0bg5b97b9hbhz8907bfcrch1i116xppa-gnumake-4.4.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/vs2sa1msvkjxbb70h47819zq8a9srj21-gnumake-4.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/ncw4l9vr02fh2prknq5dhmdycb00rdmr-gnumake-4.4.1-man",
"default": true
},
{
"name": "debug",
"path": "/nix/store/k7lz9zpj52al794kkw0d80hwj2v7pn9h-gnumake-4.4.1-debug"
},
{
"name": "doc",
"path": "/nix/store/7c3i6ivjqgc7hz21bchima12lxk8c1s4-gnumake-4.4.1-doc"
},
{
"name": "info",
"path": "/nix/store/9lbfzcvwx1c859fy6k0l9cbkp6fcxd9l-gnumake-4.4.1-info"
}
],
"store_path": "/nix/store/vs2sa1msvkjxbb70h47819zq8a9srj21-gnumake-4.4.1"
}
}
},
"gnused@latest": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473#gnused",
"source": "devbox-search",
"version": "4.10",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8fyr2rna4vqibkqsbzyfd4z6fna5c09p-gnused-4.10",
"default": true
},
{
"name": "info",
"path": "/nix/store/6c8gqzdibqfzgnp8876lp4zh1z9f13g1-gnused-4.10-info"
}
],
"store_path": "/nix/store/8fyr2rna4vqibkqsbzyfd4z6fna5c09p-gnused-4.10"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/03rgyjxclvhxnif2klf13nkr92rpxqqg-gnused-4.10",
"default": true
},
{
"name": "info",
"path": "/nix/store/sgxd46ij300v6jwrxj5cfjz7a8029jxy-gnused-4.10-info"
}
],
"store_path": "/nix/store/03rgyjxclvhxnif2klf13nkr92rpxqqg-gnused-4.10"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/9wc73n5izv0m7ppjbibi4hbr68rba1lj-gnused-4.10",
"default": true
},
{
"name": "info",
"path": "/nix/store/4gfax7m36hw70wn2cqy0dh3dr1r3rlr3-gnused-4.10-info"
}
],
"store_path": "/nix/store/9wc73n5izv0m7ppjbibi4hbr68rba1lj-gnused-4.10"
}
}
},
"go@1.27": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473#go_1_27",
"source": "devbox-search",
"version": "1.27.3",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/s5m10yz53f8778k4mi1irdqzy8iaqri1-go-1.27.3",
"default": true
}
],
"store_path": "/nix/store/s5m10yz53f8778k4mi1irdqzy8iaqri1-go-1.27.3"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/0940szmkaskjshd3z0gp2m2kfxcnc424-go-1.27.3",
"default": true
}
],
"store_path": "/nix/store/0940szmkaskjshd3z0gp2m2kfxcnc424-go-1.27.3"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/1fng2iqlx5y8rqvhjp9203mymzyny6cz-go-1.27.3",
"default": true
}
],
"store_path": "/nix/store/1fng2iqlx5y8rqvhjp9203mymzyny6cz-go-1.27.3"
}
}
}
}
}
-450
View File
@@ -1,450 +0,0 @@
# abra audit — design
2026-11-20 · Linus Gasser
## Summary
Add a top-level `abra audit` command. It checks every deployed app on every server against a curated list of advisories, and offers to fix what fails. A maintainer-side `abra audit update` turns upstream vulnerability sources into proposed advisories.
## Problem
Operators of Co-op Cloud servers cannot easily tell whether their apps are safe:
- **Mutable tags.** Images such as `php` or `nextcloud` are often rebuilt under the same tag. A server can run a vulnerable image while its compose file looks current.
- **Stale base images.** An image like `nextcloud` is built on `php`. When `php` is fixed, `nextcloud` is not fixed until upstream rebuilds it.
- **Old recipe versions.** Some recipe versions ship known-vulnerable upstream versions, and nothing tells the operator.
- **Unreliable redeploys.** A redeploy should pull the new image. If the registry is overloaded at deploy time, Docker falls back to the bare tag and each node may keep its old local image, with only a warning.
## Goals and non-goals
Goals:
- One command reports, for every deployed app, whether it matches a known advisory.
- Detect vulnerable images even when the tag has not changed, including vulnerable base images.
- Propose a fix for each finding and, on request, apply it and verify the result.
- Help advisory maintainers find new problems from upstream sources, without missing images that were fixed before anyone looked.
- Work on mixed amd64 and arm64 swarms.
Non-goals:
- A full CVE scanner. Deep scanning is delegated to Trivy or Grype as an option.
- Rebuilding upstream images. abra can detect a stale base image but not patch it.
- Publishing advisories automatically. A human reviews every advisory before operators see it.
## Commands
`abra audit` is a top-level command, because an audit spans servers, apps and recipes. `abra app check` already exists (it checks `.env` variables), so that name is not available.
| Command | Who | What it does |
| --- | --- | --- |
| `abra audit` | operator | Audit all deployed apps on all servers |
| `abra audit app <domain>` | operator | Audit one deployed app |
| `abra audit server <server>` | operator | Audit all apps on one server |
| `abra audit recipe <recipe>` | maintainer, CI | Static check of recipe versions and pinned images; nothing deployed needed |
| `abra audit list` | anyone | List advisories, filtered by `--recipe` or `--severity` |
| `abra audit show <id>` | anyone | Details and fix notes for one advisory |
| `abra audit update` | advisory maintainer | Propose new or changed advisories from a CVE, from minimum versions, or from upstream sources |
Two aliases are kept, because operators look under `app` and `server` first:
- `abra app audit <domain>` is the same as `abra audit app <domain>`.
- `abra server audit <server>` is the same as `abra audit server <server>`.
**Storage.** The audit needs an explicitly chosen abra directory. It is taken from, in order:
1. `$ABRA_DIR`;
2. the `abraDir` setting of an `abra.yaml` file in the current directory or one of its parents, as the rest of abra already supports.
If neither exists, all `abra audit` commands fail with a clear error. They do not fall back to `~/.abra`, unlike the rest of abra. Below, `$ABRA_DIR` means this directory. Everything the audit stores lives below it:
| Path | Contents |
| --- | --- |
| `$ABRA_DIR/servers` | Server and app `.env` files, as for the rest of abra |
| `$ABRA_DIR/advisories` | Checkout of the advisories repo: shared, reviewed data |
| `$ABRA_DIR/.cache/audit/images` | Local cache of image configs, by digest; from v2 on, safe to delete |
**Fetching.** There is no cache lifetime: every invocation checks whether the advisory list has changed, and pulls it if so. The list is a git repo, so this is a `git fetch` of a few KB when nothing changed. When the repo cannot be reached, the audit warns, says how old the local copy is, and uses it.
### Options for `audit`, `app` and `server`
```
-s, --server <name> only apps on this server
-r, --recipe <name> only apps of this recipe
-a, --advisories <url|path> advisory source (default: c4dt/advisories)
--severity <level> minimum severity: low, medium, high, critical
--include-drafts also apply draft advisories (marked as such)
-f, --fix propose fixes, apply after confirmation
-n, --no-input apply fixes without asking
--refresh-only only re-pull images, never upgrade the recipe
--retries <n> re-checks after a fix, with backoff (default 3)
-o, --offline no registry or advisory fetch; recipe checks only
--deep also scan running digests with Trivy or Grype
--report send unknown digests to the advisories repo (opt-in)
-m, --machine JSON output for cron and monitoring
```
`abra audit recipe` takes only `--machine`, so CI can fail on findings.
### Exit codes
The exit code describes the state **after** the run, so a finding that was fixed and verified no longer counts.
| Code | Meaning |
| --- | --- |
| 0 | No findings remain: none were found, or all were fixed and verified |
| 1 | Findings remain that were not fixed: no `--fix`, fix declined, or strategy `manual` |
| 2 | A fix was tried but could not be verified, for example because the registry was unreachable |
With several apps, the highest code wins. The report lists every finding with its final status (`fixed`, `affected`, `unknown`, `unverified`), so fixed findings stay visible in the output and in `--machine` JSON.
## Advisory format
Advisories are YAML files, one per advisory, in a separate git repo under `advisories/`. They are kept apart from the recipe catalogue because they change on a different schedule and need their own review. The repo starts as `c4dt/advisories` and can move to `coop-cloud/advisories` once the format has settled.
```yaml
id: CCA-2026-0012
title: PHP 8.3 CGI argument injection
severity: critical # low | medium | high | critical
status: published # draft | published | withdrawn
refs: [CVE-2026-12345, https://example.org/advisory]
published: 2026-10-20
# Recipe versions: semver range on the recipe part of the tag
recipes:
nextcloud:
affected: "<7.0.3+30.0.1"
fixed: "7.0.3+30.0.1"
# Images: an image is fixed if ANY condition holds
images:
- match: "nextcloud:30*-apache"
fixed_from: sha256:2222... # this digest and all first seen after it
affected_digests: [sha256:1111...]
- match: "*" # any image...
base: "php:8.3*" # ...built on php 8.3
env: { PHP_VERSION: "<8.3.14" } # read from the image config
fix:
strategy: refresh # upgrade | refresh | manual
notes: "Upstream images rebuilt on 2026-10-18; a redeploy is enough."
```
### Image conditions
Digests are hashes and have no order, so "newer than digest X" cannot be computed from the digest itself. Instead, the format uses what the image says about itself, in order of preference:
| Condition | Field | Reliability | Notes |
| --- | --- | --- | --- |
| Version in the image | `env`, `version` | Best | Tests the fix itself, per platform, without pulling layers |
| Build time | `created_after` | Good, if the image records its real build time | Covers rebuilds where no version changes; see below |
| Base ancestry | `base`, `base_digest_from` | Good | Docker Official Images record their base in OCI annotations |
| Allowlist | `fixed_digests` | Exact but closed | Later rebuilds need the list updated |
| Denylist | `affected_digests` | Exact but incomplete | For one known-bad digest |
| Digest history | `fixed_from` | Good | Fallback for images whose build time is unusable; later version |
An image that matches `match` but satisfies no condition is reported as **unknown**, never as OK.
How the conditions combine, for an image that matches `match`:
1. A digest in `affected_digests` is affected; a digest in `fixed_digests` is fixed.
2. `env` both selects and tests. If the image lacks one of the variables, the entry does not apply, because the image is not built on that runtime. Otherwise the ranges are **affected** ranges: if every variable is in its range, `env` says affected, else fixed. Write `">=8.3.0 <8.3.14"` to limit the entry to one release series.
3. `version` is an affected range on `org.opencontainers.image.version`.
4. `created_after` says fixed for images built at or after that time, and affected for older ones, unless the build time is unusable.
5. If any condition says fixed, the image is fixed. Otherwise, if one says affected, it is affected. Otherwise it is unknown.
`match` is a glob where `*` matches any characters. A pattern with a `:` is matched against `name:tag`, otherwise against the name only, using Docker's short names (`nextcloud`, not `docker.io/library/nextcloud`). Version ranges are space- or comma-separated constraints (`<`, `<=`, `>`, `>=`, `=`, `!=`) that must all hold, with `||` between alternatives. A recipe range without an upstream part (`<7.0.3`) only compares the recipe part of the tag.
### Ordering images by version and build time
Most fixes change a version that the image shows, so no digest bookkeeping is needed:
- **Application version.** `NEXTCLOUD_VERSION` in the config, or the annotation `org.opencontainers.image.version` (for example `35.0.3-apache`).
- **Inherited runtime version.** Images inherit environment variables from their base, so `nextcloud:apache` also carries `PHP_VERSION=8.5.13`. A nextcloud rebuilt on a fixed php shows the new `PHP_VERSION`, even though `NEXTCLOUD_VERSION` is unchanged.
That leaves rebuilds where every visible version stays the same, typically a Debian package such as openssl patched in the base image. For these, the build time decides: `created_after` is the `Created` time of the first fixed image, and any image of that tag built later counts as fixed.
**Is the build time monotonic?** Per tag, in practice yes: every rebuild is a new build run with a later timestamp. On Docker Hub on 2026-11-20, `php:8.3-apache` recorded its real build time (2026-11-19 14:40 UTC), and `nextcloud:apache` was built 33 minutes later on top of it. Both also carry the annotations `org.opencontainers.image.base.name` and `base.digest`. The exceptions are known:
| Case | Effect | Handling |
| --- | --- | --- |
| Reproducible builds (`SOURCE_DATE_EPOCH`, ko, Nix, Bazel) set `Created` to a commit date or to 1970 | A base-only rebuild keeps the same `Created`, so old and new cannot be told apart | Detect it, then report unknown |
| Upstream moves a tag back to an older image | The older `Created` is reported as affected | Correct as is |
| Clock skew between build machines | Minutes | Irrelevant next to fix dates days apart |
The audit treats `Created` as unusable, and reports unknown, when:
- it is before 2000, which catches the 1970 epoch;
- it is earlier than the `Created` of the base image named in `base.digest`, because an image cannot be built before its base;
- two different digests of the same tag have the same `Created`.
The advisory can then fall back to `fixed_digests`, or later to the digest history.
### Fix strategies
| Strategy | Meaning | What `--fix` does |
| --- | --- | --- |
| `upgrade` | A newer recipe version fixes it | `abra app upgrade <domain> <fixed version>` |
| `refresh` | The same tag now points to a fixed image | Redeploy the same version, then verify the running digest |
| `manual` | No fixed image exists yet | Report only, with the notes and options such as pinning a digest |
## Digest history (fallback, later version)
The digest history is only needed for images whose build time is unusable, as listed above. It is deferred to v4, and built only if such images turn out to matter.
The advisories repo would keep an append-only history per image tag, recording when each digest was first seen:
```yaml
# digests/nextcloud/30-apache.yml (append-only)
- digest: sha256:1111...
first_seen: 2026-10-02T08:00:00Z
config: { created: 2026-10-01, NEXTCLOUD_VERSION: 30.0.3, PHP_VERSION: 8.3.12 }
- digest: sha256:2222...
first_seen: 2026-10-18T14:00:00Z
config: { created: 2026-10-18, NEXTCLOUD_VERSION: 30.0.3, PHP_VERSION: 8.3.14 }
```
It would be filled from three sources:
1. **`abra audit update`** runs regularly from CI and appends every new digest it sees, with its image config. The config is stored because registries may delete old digests once they are untagged.
2. **Backfill from `docker-library/repo-info`**, which keeps years of per-tag digests for official images in git.
3. **Running servers.** With `--report`, `abra audit` sends digests it finds that are not in the history. This is opt-in.
## Images fixed before anyone looked
Suppose a CVE is published and upstream pushes a fixed image under the same tag before `update` runs. `update` never sees the vulnerable image, but old installations still run it. This is handled because advisories are driven by the CVE, not by the current image:
- The CVE creates the advisory, whether or not today's image is clean.
- A clean current image only sets the strategy to `refresh`. Its versions become the `env` condition, or its `Created` time becomes `created_after`.
- On a server, an image with older versions or an earlier build time is reported as affected. Both lead to a refresh and a verification.
`update` only needs to see the fixed image, and that is the one available when it runs.
## Audit and fix
`abra audit` checks each app in the same way, and a fix counts only after the running digest has been verified.
1. **Read state.** From the service spec, read the recipe version label and each image reference `image:tag@sha256:...`. For per-platform checks, read the node's platform and fetch that image config from the registry.
2. **Match advisories.** First recipe ranges, then image conditions.
3. **Classify** each finding as affected or unknown. No finding means clean.
4. **Fix** (with `--fix`) according to the advisory's strategy, then verify.
```mermaid
flowchart TD
read[Read service spec] --> match[Match advisories]
match --> finding{Finding?}
finding -- no --> clean[Clean, exit 0]
finding -- affected or unknown --> strategy[Pick fix strategy]
strategy -- manual --> report[Report, exit 1]
strategy -- upgrade or refresh --> apply[Upgrade / refresh]
apply --> verified{Digest fixed?}
verified -- yes --> fixed[Fixed, exit 0]
verified -- no --> retry[Retry, backoff]
retry -- within --retries --> apply
retry -- retries used up --> unverified[Unverified, exit 2]
```
Verification waits for the service to converge, then reads the spec again. It fails if the spec holds a bare tag (the registry lookup failed) or a digest that still matches the advisory. Retries use backoff, for example 30 s, 2 min and 10 min, before giving up with exit code 2.
## `abra audit update`
`abra audit update` is a maintainer tool. It compares the recipes in the catalogue with a vulnerability, and proposes new or changed advisories for a human to review. It has three modes; the first two come first (see [Versions](#versions)).
```
abra audit update --cve <CVE-ID> # one known vulnerability
abra audit update --require <lib>=<v>[,<v>...] # minimum patched versions
abra audit update --sources [recipe...] # scan upstream sources (later)
--repo <path> local checkout of the advisories repo (default $ABRA_DIR/advisories)
--source <list> with --sources: endoflife,osv,ghsa,kev,repo-info,trivy (default: all but trivy)
--since <date> with --sources: only upstream changes after this date (default: last run)
-n, --no-input write all proposals as drafts without asking
--pr commit accepted proposals on a branch and open a PR
```
### Sources
| Source | Gives | Becomes |
| --- | --- | --- |
| [endoflife.date](https://endoflife.date) | End-of-life dates for runtimes such as php and postgres | `medium` advisory, strategy `upgrade` |
| [OSV.dev](https://osv.dev) and [GitHub Advisory Database](https://github.com/advisories) | CVEs with affected and fixed upstream versions | Recipe ranges, mapped through the `+UPSTREAM` part of recipe tags |
| [CISA KEV](https://www.cisa.gov/known-exploited-vulnerabilities-catalog) | CVEs exploited in the wild | Severity raised to `critical` |
| [docker-library/repo-info](https://github.com/docker-library/repo-info) | Digest and package history of official images | Digest history; `fixed_from` for rebuilt images |
| Trivy (opt-in, slow) | CVEs found in current catalogue images | Proposals the other sources missed |
### Steps
1. **Inventory.** List every recipe version in the catalogue and its images. Fetch each image config for runtime versions (`PHP_VERSION`, `NODE_VERSION`) and find its base image.
2. **Record digests.** Append new digests and their configs to the digest history.
3. **Query sources** for the upstream apps and runtimes found in step 1.
4. **Classify.** For each CVE, write a condition that separates affected from fixed images. Look at the current image only to choose the strategy: `refresh` if the current image is clean, `manual` if it is not.
5. **Deduplicate.** Match on CVE ID and affected recipe or image. If an advisory already covers the finding, propose a change (wider range, new fixed digest, higher severity) instead of a new entry.
6. **Review.** Show each proposal as a YAML diff: accept, edit, skip, or ignore permanently. Ignored findings go to `ignore.yml` with a reason, so they do not return.
7. **Write** accepted proposals with `status: draft`, optionally on a branch with a PR. Only a human sets `status: published`.
A human is needed because the sources say what is vulnerable upstream. Only a maintainer can judge whether it matters for the recipe's configuration and which fix strategy applies.
## Multiple platforms
abra already works on mixed amd64 and arm64 swarms, because it leaves the platform choice to Docker. The audit must compare digests at the right level.
**Current behaviour.** abra has no platform-specific code. `deploy`, `upgrade` and `rollback` use `ResolveImageAlways` (`cli/app/deploy.go:157`), so Docker resolves `image:tag` to the index digest that covers all platforms. Each node then pulls its own variant. `GetRegistryDigest` in `pkg/client/registry.go` also returns the index digest, so pinned `image:tag@sha256:...` references work on every platform.
| Question | Compare | Where to read it |
| --- | --- | --- |
| Has the tag moved? | Index digest | Service spec, and a registry HEAD request |
| Which PHP version is inside? | Per-platform image config | Pick the node's platform from the index (`docker node inspect` gives `Description.Platform`) |
| Is it built on the fixed base? | Per-platform layers | Same per-platform manifest |
Pitfalls:
- **A new index digest does not prove the fix for your platform.** Any platform's rebuild changes the index digest. Some upstreams rebuild arm64 later or not at all, so important fixes are checked per platform.
- **Copied per-platform digests.** The Docker Hub web page shows per-platform digests most prominently. A maintainer who pins one breaks other platforms with `no matching manifest`. `abra recipe lint` should warn when a pinned digest is not an index but the image is multi-arch.
- **Containers show the image ID.** `docker inspect` on a container gives the config digest, not the manifest digest. Use the service spec for comparisons.
## What Docker allows
abra can detect almost any stale or vulnerable layer, but it can only fix an image that upstream has already rebuilt.
| Possible | How |
| --- | --- |
| Know exactly what is running | Swarm stores `image:tag@sha256:...` in the service spec |
| Tell whether a tag has moved | Registry HEAD request for the tag's manifest digest |
| Read versions without pulling | Fetch the image config (a few KB): `Created` and `Env`, which often inherits `PHP_VERSION` or `NGINX_VERSION` from the base |
| Find the base image | OCI annotations `org.opencontainers.image.base.name` and `base.digest` where set; otherwise layer-prefix matching against the base's layers |
| Go deeper, to libc or openssl | SBOM and provenance attestations, which Docker Official Images publish |
| Not possible | Consequence |
| --- | --- |
| Patch a base layer of someone else's image | If upstream has not rebuilt, the options are waiting, pinning a known-good older digest, or having the recipe build its own image |
| Trust a redeploy without checking | On registry failure Docker deploys the bare tag; every refresh must be verified |
**Undeploy is not needed.** `undeploy` then `deploy` has the same registry problem as a plain redeploy, and adds downtime. A redeploy of the same version with `ResolveImageAlways` already asks the registry again.
**Pinned digests make failures visible.** With `image: nextcloud:30-apache@sha256:...` in the recipe, a failed registry lookup fails the deploy instead of running a stale image. The `allow_digest` branch adds this support to `abra recipe upgrade`.
## Versions
The feature is built in four versions. Each one is usable on its own, and is tried on real servers before the next one starts.
| Version | Adds | Changes servers? |
| --- | --- | --- |
| v1 | `abra audit`: report failing apps and suggest commands | No |
| v2 | `abra audit update --cve` and `--require`: draft advisories for one vulnerability | No |
| v3 | Subcommands, options, `--fix` with verification, deploy warnings | Yes, with `--fix` |
| v4 | Automatic advisory proposals from upstream sources, digest history | No |
### v1: basic audit
Answers "which of my apps need attention, and what do I run?" using only a hand-written advisory list.
- **Command.** `abra audit`, without arguments. It goes through every server in `$ABRA_DIR/servers` and every deployed app on it, using the same data as `abra app ls -S`.
- **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, 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:
- 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.
- **Errors.** An unreachable server is listed as such and the run continues.
**Test.** On a test server, deploy one old nextcloud recipe version and one app with a stale image under a current tag. Write an advisory for each. Check that both are reported, that following the suggestions fixes them, and that a second `abra audit` is clean.
### v2: `abra audit update` for one vulnerability
Turns a single vulnerability into draft advisories, so the maintainer does not have to check every recipe by hand. There are two ways to describe the vulnerability.
**By CVE: `abra audit update --cve CVE-2026-12345`.** The CVE is looked up in [OSV.dev](https://osv.dev), which also covers GitHub advisories and package ecosystems such as Packagist, npm, PyPI, Debian and Alpine. This gives the affected packages and their fixed versions. Recipes are then matched in two ways:
- applications, such as nextcloud, through the `+UPSTREAM` part of the recipe tags;
- runtimes and libraries, such as php, through the image config (next paragraph).
**By minimum versions: `abra audit update --require php=8.5.12,8.4.27,8.3.36,8.2.35`.** One minimum version per release series. For every image in the catalogue that contains the library:
| Image contains | Result |
| --- | --- |
| A listed series, below its minimum (php 8.4.20) | Affected |
| A listed series, at or above its minimum (php 8.4.27) | Fixed |
| A series that is not listed (php 8.1.x) | Unsupported, proposed as a separate end-of-life advisory |
Libraries are found through environment variables in the image config, which images inherit from their base:
| Library | Variable |
| --- | --- |
| php | `PHP_VERSION` |
| node | `NODE_VERSION` |
| python | `PYTHON_VERSION` |
| nginx | `NGINX_VERSION` |
| postgres | `PG_VERSION` |
| redis | `REDIS_VERSION` |
An unknown library is an error that lists the known ones. Finding libraries through SBOMs comes later.
**Which recipe versions.** Every published version of each recipe that uses the library is checked, so the proposal gets a correct `affected` range. Image configs are a few KB and are cached by digest in `$ABRA_DIR/.cache/audit/images/`, so this is cheap after the first run. A digest never changes its content, so this cache never expires.
**Strategy.** For each affected recipe, the current image under the same tag is checked too:
- a newer recipe version uses a fixed image → `upgrade` to that version;
- the same tag now points to a fixed image → `refresh`, with the current digest in `fixed_digests`;
- nothing is fixed yet → `manual`.
**Output.** Draft advisory files in the local checkout, each shown as a diff to accept, edit or skip. v2 does not commit or open pull requests.
**Test.** Run `--require` with the versions of a recent php security release, and compare the proposals with a list made by hand. Run `--cve` with a recent nextcloud CVE and check the recipe range.
### v3: arguments and fixes
Makes the audit usable for single apps and for automation, and lets it apply fixes.
- **Subcommands.** `abra audit app`, `server`, `recipe`, `list` and `show`, plus the aliases `abra app audit` and `abra server audit`.
- **Options.** `--server`, `--recipe`, `--severity`, `--machine`, `--offline` and `--advisories`.
- **Fixes.** `--fix`, `--refresh-only`, `--no-input` and `--retries`, with verification after each fix and exit code 2 when verification fails.
- **Deploy warnings.** `abra app deploy` and `abra app upgrade` warn, without refusing, when the target version matches an advisory.
- **Platforms.** `env` conditions are checked per platform on mixed amd64 and arm64 swarms.
**Test.** Run `abra audit --fix` against the v1 test setup, with the registry blocked for one attempt (for example with a firewall rule), and check that the retry succeeds and that the exit code is right in each case.
### v4: more automatic updates
Moves advisory maintenance from "react to a CVE" to "be told about new problems".
- `abra audit update --sources`, run on a schedule in CI, with endoflife.date, OSV, GHSA, CISA KEV and docker-library/repo-info.
- Deduplication against existing advisories, `ignore.yml`, and `--pr`.
- Digest history and `fixed_from`, only if images with unusable build times (reproducible builds) turn out to matter.
- Optional extras: `--deep` scanning with Trivy or Grype, the lint rule for per-platform digests, a status column in `abra app list`, and `--report`.
- Moving the advisories repo to `coop-cloud/advisories`.
## Decisions
| Question | Decision |
| --- | --- |
| Who maintains the advisories, and how fast? | Linus Gasser, manually, in `c4dt/advisories`, for now |
| Should `--report` exist? | Not in the first versions |
| How long to cache the advisory list? | No cache: every invocation checks for the latest list |
| What does `abra app deploy` do when the target version matches an advisory? | It warns, and does not refuse |
## Open questions
- [ ] Do the registries we depend on keep untagged digests long enough to read their config later? This matters only for the digest history (v4), because the config of a running image can be read from the node. To find out, take old `php` digests from docker-library/repo-info and try to fetch their manifests from Docker Hub.
- [ ] Which images used by recipes are built reproducibly, so that their `Created` time is unusable? `abra audit update` could list them while scanning the catalogue.
Generated
-99
View File
@@ -1,99 +0,0 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"microvm": {
"inputs": {
"nixpkgs": [
"nixpkgs"
],
"spectrum": "spectrum"
},
"locked": {
"lastModified": 1784666190,
"narHash": "sha256-xgfS6slV7J3baMooNN1UuBi51RIgg9y0DbCxfSA0668=",
"owner": "astro",
"repo": "microvm.nix",
"rev": "fa5340ac684cdce8a22b6d4a0bcebb0cc999275e",
"type": "github"
},
"original": {
"owner": "astro",
"repo": "microvm.nix",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1778443072,
"narHash": "sha256-zi7/fsqM/kFdNuED//4WOCUtezGtKKqRNORjMvfwjnA=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "da5ad661ba4e5ef59ba743f0d112cbc30e474f32",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"microvm": "microvm",
"nixpkgs": "nixpkgs"
}
},
"spectrum": {
"flake": false,
"locked": {
"lastModified": 1783694892,
"narHash": "sha256-xO8f7Qng+18FK2UlB9vcrkxCaQMCt5WjCH24aW/11eg=",
"ref": "refs/heads/main",
"rev": "24c4346e30fdea8d8e80f34aec3554a15a667d24",
"revCount": 1410,
"type": "git",
"url": "https://spectrum-os.org/git/spectrum"
},
"original": {
"type": "git",
"url": "https://spectrum-os.org/git/spectrum"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}
-106
View File
@@ -1,106 +0,0 @@
{
description = "The Co-op Cloud utility belt";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
microvm = {
url = "github:astro/microvm.nix";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs =
{
self,
nixpkgs,
microvm,
flake-utils,
}:
let
system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system};
publicKey = builtins.readFile ./tests/resources/local_integration_ssh.pub;
privateKey = builtins.readFile ./tests/resources/local_integration_ssh;
pathToRepo = builtins.readFile ./tests/resources/path_to_repo;
# local DNS aliases for the server host
extraHosts = builtins.readFile ./tests/resources/extra_hosts;
username = "abra";
password = "abra";
defaultDNS = [
# Quad9.net
"9.9.9.9"
"149.112.112.112"
"2620:fe::fe"
"2620:fe::9"
];
in
{
nixosConfigurations = {
abra-client = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules = [
microvm.nixosModules.microvm
./nix/hosts/client/configuration.nix
];
specialArgs = {
inherit
publicKey
privateKey
username
password
defaultDNS
extraHosts
pathToRepo
;
};
};
abra-server = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules = [
microvm.nixosModules.microvm
./nix/hosts/server/configuration.nix
];
specialArgs = {
inherit
publicKey
privateKey
username
password
defaultDNS
;
};
};
};
nixosModules = rec {
host = {
imports = [
microvm.nixosModules.host
./nix/modules/host.nix
];
};
default = host;
};
packages = rec {
abra = pkgs.callPackage ./nix/package.nix { };
default = abra;
};
apps = rec {
abra = flake-utils.lib.mkApp { drv = self.packages.${system}.abra; };
default = abra;
};
devShells.${system}.default = pkgs.mkShell {
# testing env variables
BATS_LIB_PATH = "~/.local/share/bats/";
TEST_SERVER = "abra.local";
ABRA_DIR = "$HOME/.abra_test";
packages = with pkgs; [
go_1_26
gnumake
gopls
];
};
};
}
+55 -49
View File
@@ -1,34 +1,26 @@
module coopcloud.tech/abra
go 1.27
go 1.26.0
require (
coopcloud.tech/tagcmp v0.0.0-20260515102403-c26951b55977
coopcloud.tech/tagcmp v0.0.0-20250818180036-0ec1b205b5ca
git.coopcloud.tech/toolshed/godotenv v1.5.2-0.20250103171850-4d0ca41daa5c
github.com/AlecAivazis/survey/v2 v2.3.7
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/lipgloss v1.1.0
github.com/charmbracelet/log v1.0.0
github.com/containers/image v3.0.2+incompatible
github.com/decentral1se/passgen v1.0.1
github.com/distribution/reference v0.6.0
github.com/docker/cli v28.4.0+incompatible
github.com/docker/docker v28.5.2+incompatible
github.com/docker/go-units v0.5.0
github.com/go-git/go-git/v5 v5.19.3
github.com/go-git/go-git/v5 v5.18.0
github.com/google/go-cmp v0.7.0
github.com/hashicorp/go-retryablehttp v0.7.8
github.com/leonelquinteros/gotext v1.8.0
github.com/leonelquinteros/gotext v1.7.2
github.com/moby/sys/signal v0.7.1
github.com/moby/term v0.5.2
github.com/opencontainers/go-digest v1.0.0
github.com/opencontainers/image-spec v1.1.1
github.com/pkg/errors v0.9.1
github.com/schollz/progressbar/v3 v3.19.1
github.com/spf13/cobra v1.10.1
github.com/stretchr/testify v1.12.1
golang.org/x/sys v0.50.0
golang.org/x/term v0.48.0
github.com/schollz/progressbar/v3 v3.19.0
golang.org/x/term v0.42.0
gopkg.in/yaml.v3 v3.0.1
gotest.tools/v3 v3.5.2
)
@@ -45,7 +37,7 @@ require (
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect
github.com/charmbracelet/x/ansi v0.11.6 // indirect
github.com/charmbracelet/x/ansi v0.11.7 // indirect
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
@@ -56,49 +48,44 @@ require (
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/containerd/platforms v0.2.1 // indirect
github.com/containers/storage v1.38.2 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect
github.com/cyphar/filepath-securejoin v0.6.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/docker/distribution v2.8.3+incompatible // indirect
github.com/docker/docker-credential-helpers v0.9.5 // indirect
github.com/docker/go-connections v0.6.0 // indirect
github.com/docker/go-connections v0.7.0 // indirect
github.com/docker/go-metrics v0.0.1 // indirect
github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fvbommel/sortorder v1.1.0 // indirect
github.com/ghodss/yaml v1.0.0 // indirect
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
github.com/go-git/go-billy/v5 v5.9.2 // indirect
github.com/go-git/go-billy/v5 v5.8.0 // indirect
github.com/go-logfmt/logfmt v0.6.1 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/mux v1.8.1 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/kevinburke/ssh_config v1.6.0 // indirect
github.com/klauspost/compress v1.18.5 // indirect
github.com/klauspost/compress v1.18.6 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/lucasb-eyer/go-colorful v1.4.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.21 // indirect
github.com/mattn/go-runewidth v0.0.23 // indirect
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
github.com/miekg/pkcs11 v1.1.1 // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.1.0 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/go-archive v0.2.0 // indirect
github.com/moby/sys/atomicwriter v0.1.0 // indirect
github.com/moby/sys/sequential v0.6.0 // indirect
github.com/moby/sys/user v0.4.0 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/morikuni/aec v1.1.0 // indirect
@@ -106,52 +93,71 @@ require (
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/termenv v0.16.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/runc v1.1.13 // indirect
github.com/opencontainers/runtime-spec v1.1.0 // indirect
github.com/pjbgf/sha1cd v0.7.0 // indirect
github.com/prometheus/client_golang v1.23.2 // indirect
github.com/pjbgf/sha1cd v0.6.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.67.5 // indirect
github.com/prometheus/procfs v0.20.1 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sergi/go-diff v1.4.0 // indirect
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/skeema/knownhosts v1.3.2 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/theupdateframework/notary v0.7.0 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect
go.opentelemetry.io/otel v1.42.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect
go.opentelemetry.io/otel v1.43.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 // indirect
go.opentelemetry.io/otel/metric v1.42.0 // indirect
go.opentelemetry.io/otel/sdk v1.42.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect
go.opentelemetry.io/otel/trace v1.42.0 // indirect
go.opentelemetry.io/otel/metric v1.43.0 // indirect
go.opentelemetry.io/otel/sdk v1.43.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect
go.opentelemetry.io/otel/trace v1.43.0 // indirect
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/crypto v0.56.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/crypto v0.50.0 // indirect
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
golang.org/x/net v0.57.0 // indirect
golang.org/x/text v0.41.0 // indirect
golang.org/x/net v0.53.0 // indirect
golang.org/x/text v0.36.0 // indirect
golang.org/x/time v0.15.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260427160629-7cedc36a6bc4 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4 // indirect
google.golang.org/grpc v1.80.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
require (
github.com/containers/image v3.0.2+incompatible
github.com/containers/storage v1.38.2 // indirect
github.com/decentral1se/passgen v1.0.1
github.com/docker/docker-credential-helpers v0.9.6 // indirect
github.com/fvbommel/sortorder v1.1.0 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/gorilla/mux v1.8.1 // indirect
github.com/hashicorp/go-retryablehttp v0.7.8
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/sys/sequential v0.6.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/prometheus/client_golang v1.23.2 // indirect
github.com/sergi/go-diff v1.4.0 // indirect
github.com/spf13/cobra v1.10.1
github.com/stretchr/testify v1.11.1
github.com/theupdateframework/notary v0.7.0 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
golang.org/x/sys v0.43.0
)
replace github.com/docker/cli v28.4.0+incompatible => git.coopcloud.tech/toolshed/docker-cli v28.5.3-0.20260202112816-30df2d0b3a00+incompatible
replace github.com/spf13/cobra => github.com/decentral1se/cobra v1.10.2
replace github.com/spf13/cobra => github.com/decentral1se/cobra v1.10.2-i18n
+91 -32
View File
@@ -22,8 +22,8 @@ cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIA
cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw=
cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos=
cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk=
coopcloud.tech/tagcmp v0.0.0-20260515102403-c26951b55977 h1:J7I0HFjwVAj/kkX6lwSTHmlXDRjQRsdIFNUUqu55ADY=
coopcloud.tech/tagcmp v0.0.0-20260515102403-c26951b55977/go.mod h1:ESVm0wQKcbcFi06jItF3rI7enf4Jt2PvbkWpDDHk1DQ=
coopcloud.tech/tagcmp v0.0.0-20250818180036-0ec1b205b5ca h1:gSD53tBAsbIGq4SnFfq+mEep6foekQ2a5ea7b38qkm0=
coopcloud.tech/tagcmp v0.0.0-20250818180036-0ec1b205b5ca/go.mod h1:ESVm0wQKcbcFi06jItF3rI7enf4Jt2PvbkWpDDHk1DQ=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
@@ -130,6 +130,7 @@ github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyY
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
@@ -144,6 +145,8 @@ github.com/charmbracelet/log v1.0.0 h1:HVVVMmfOorfj3BA9i8X8UL69Hoz9lI0PYwXfJvOdR
github.com/charmbracelet/log v1.0.0/go.mod h1:uYgY3SmLpwJWxmlrPwXvzVYujxis1vAKRV/0VQB7yWA=
github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=
github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=
github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dAYC84jI=
github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ=
github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI=
github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
@@ -306,9 +309,10 @@ github.com/d2g/dhcp4client v1.0.0/go.mod h1:j0hNfjhrt2SxUOw55nL0ATM/z4Yt3t2Kd1mW
github.com/d2g/dhcp4server v0.0.0-20181031114812-7d4a0a7f59a5/go.mod h1:Eo87+Kg/IX2hfWJfwxMzLyuSZyxSoAug2nGa1G2QAi8=
github.com/d2g/hardwareaddr v0.0.0-20190221164911-e7d9fbe030e4/go.mod h1:bMl4RjIciD2oAxI7DmWRx6gbeqrkoLqv3MV0vzNad+I=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decentral1se/cobra v1.10.2 h1:MZ8Ifi/jRels9sZrpSccDbUlK++3b2HlBODfv0Bh6x0=
github.com/decentral1se/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/decentral1se/cobra v1.10.2-i18n h1:XR+6AHHfnf4k5NM9f09oLMrEVwz3rkQIAIcqgL8R08g=
github.com/decentral1se/cobra v1.10.2-i18n/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/decentral1se/passgen v1.0.1 h1:j2AxK/kHKxDHWZZfkJj8Wgae9+O+DYEqR5sjKthIYKA=
github.com/decentral1se/passgen v1.0.1/go.mod h1:530V+lNoPhKtkrX2fIVsIfLhkl47CuiOM7HRgi7C+SU=
github.com/denisenkom/go-mssqldb v0.0.0-20191128021309-1d7a30a10f73/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=
@@ -330,11 +334,15 @@ github.com/docker/docker v28.5.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bc
github.com/docker/docker-credential-helpers v0.6.3/go.mod h1:WRaJzqw3CTB9bk10avuGsjVBZsD05qeibJ1/TYlvc0Y=
github.com/docker/docker-credential-helpers v0.9.5 h1:EFNN8DHvaiK8zVqFA2DT6BjXE0GzfLOZ38ggPTKePkY=
github.com/docker/docker-credential-helpers v0.9.5/go.mod h1:v1S+hepowrQXITkEfw6o4+BMbGot02wiKpzWhGUZK6c=
github.com/docker/docker-credential-helpers v0.9.6 h1:cT2PbRPSlnMmNTfT2TDMXRyQ1KMWHG7xoTLBcn1ZNv0=
github.com/docker/docker-credential-helpers v0.9.6/go.mod h1:v1S+hepowrQXITkEfw6o4+BMbGot02wiKpzWhGUZK6c=
github.com/docker/go v1.5.1-1.0.20160303222718-d30aec9fd63c h1:lzqkGL9b3znc+ZUgi7FlLnqjQhcXxkNM/quxIjBVMD0=
github.com/docker/go v1.5.1-1.0.20160303222718-d30aec9fd63c/go.mod h1:CADgU4DSXK5QUlFslkQu2yW2TKzFZcXq/leZfM0UH5Q=
github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pMmjSD94=
github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vmaMAntpSFH5BFKE=
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
github.com/docker/go-events v0.0.0-20170721190031-9461782956ad/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA=
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA=
github.com/docker/go-metrics v0.0.0-20180209012529-399ea8c73916/go.mod h1:/u0gXw0Gay3ceNrsHubL3BtdOL2fHf93USgMTe0W5dI=
@@ -388,12 +396,14 @@ github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic=
github.com/go-git/go-billy/v5 v5.9.2 h1:OXFSRyz4g20upsGDJgQG9Bak1l/ZEv8GHVYB52O71sE=
github.com/go-git/go-billy/v5 v5.9.2/go.mod h1:ExsU+jcGwXTBOnyilvAnEM1wug1IxHr4yP2ZXsNRtV0=
github.com/go-git/go-billy/v5 v5.8.0 h1:I8hjc3LbBlXTtVuFNJuwYuMiHvQJDq1AT6u4DwDzZG0=
github.com/go-git/go-billy/v5 v5.8.0/go.mod h1:RpvI/rw4Vr5QA+Z60c6d6LXH0rYJo0uD5SqfmrrheCY=
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4=
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII=
github.com/go-git/go-git/v5 v5.19.3 h1:qHttbZ+Am7wEjdTpR1XMQ4rl42FK9SIXzZ4o9x7s6M4=
github.com/go-git/go-git/v5 v5.19.3/go.mod h1:Ye4C8dVigkqrv9UsB4NMdSLV4yAIkLiIhW61gcOyhl4=
github.com/go-git/go-git/v5 v5.17.2 h1:B+nkdlxdYrvyFK4GPXVU8w1U+YkbsgciIR7f2sZJ104=
github.com/go-git/go-git/v5 v5.17.2/go.mod h1:pW/VmeqkanRFqR6AljLcs7EA7FbZaN5MQqO7oZADXpo=
github.com/go-git/go-git/v5 v5.18.0 h1:O831KI+0PR51hM2kep6T8k+w0/LIAD490gvqMCvL5hM=
github.com/go-git/go-git/v5 v5.18.0/go.mod h1:pW/VmeqkanRFqR6AljLcs7EA7FbZaN5MQqO7oZADXpo=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
@@ -524,9 +534,12 @@ github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:Fecb
github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo=
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed/go.mod h1:tMWxXQ9wFIaZeTI9F+hmhFiGpFmhOHzyShyFUhRm0H4=
github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
@@ -585,6 +598,10 @@ github.com/klauspost/compress v1.11.13/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdY
github.com/klauspost/compress v1.14.2/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE=
github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
@@ -602,8 +619,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/leonelquinteros/gotext v1.8.0 h1:wwpxINWmWq3JN3WFI9BoSupBFrvAqxZTtf3qppijYkU=
github.com/leonelquinteros/gotext v1.8.0/go.mod h1:Wqke380+8unZq2F4oTmmqmbUY9zWQMzwImdC34XOAo8=
github.com/leonelquinteros/gotext v1.7.2 h1:bDPndU8nt+/kRo1m4l/1OXiiy2v7Z7dfPQ9+YP7G1Mc=
github.com/leonelquinteros/gotext v1.7.2/go.mod h1:9/haCkm5P7Jay1sxKDGJ5WIg4zkz8oZKw4ekNpALob8=
github.com/lib/pq v0.0.0-20150723085316-0dad96c0b94f/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/linuxkit/virtsock v0.0.0-20201010232012-f8cee7dfc7a3/go.mod h1:3r6x7q95whyfWQpmGZTu3gk3v2YkMi05HEzl7Tf7YEo=
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
@@ -620,6 +637,8 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
@@ -627,6 +646,8 @@ github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+Ei
github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.21 h1:jJKAZiQH+2mIinzCJIaIG9Be1+0NR+5sz/lYEEjdM8w=
github.com/mattn/go-runewidth v0.0.21/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mattn/go-shellwords v1.0.3/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o=
github.com/mattn/go-shellwords v1.0.6/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o=
github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y=
@@ -651,6 +672,8 @@ github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3N
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/go-archive v0.1.0 h1:Kk/5rdW/g+H8NHdJW2gsXyZ7UnzvJNOy6VKJqueWdcQ=
github.com/moby/go-archive v0.1.0/go.mod h1:G9B+YoujNohJmrIYFBpSd54GTUB4lt9S+xVQvsJyFuo=
github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8=
github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU=
github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc=
github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U=
github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=
@@ -750,13 +773,16 @@ github.com/opencontainers/selinux v1.10.0/go.mod h1:2i0OySw99QjzBBQByd1Gr9gSjvuh
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc=
github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU=
github.com/pjbgf/sha1cd v0.7.0 h1:ZRNPKHj+gfkLBf0KJv/p1Hmz+7bqCT5o311YX0nq+DA=
github.com/pjbgf/sha1cd v0.7.0/go.mod h1:pKR5Li+qTCo+ebqITZfwPlJGoCFCvSO00qxjbNtTUFQ=
github.com/pjbgf/sha1cd v0.5.0 h1:a+UkboSi1znleCDUNT3M5YxjOnN1fz2FhN48FlwCxs0=
github.com/pjbgf/sha1cd v0.5.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1-0.20171018195549-f15c970de5b7/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pquerna/cachecontrol v0.0.0-20171018203845-0dec1b30a021/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA=
github.com/prometheus/client_golang v0.0.0-20180209125602-c332b6f63c06/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
@@ -799,13 +825,15 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday v1.6.0 h1:KqfZb0pUVN2lYqZUYRddxF4OR8ZMURnJIG5Y3VRLtww=
github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/safchain/ethtool v0.0.0-20190326074333-42ed695e3de8/go.mod h1:Z0q5wiBQGYcxhMZ6gUqHn6pYNLypFAvaL3UvgZLR0U4=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/schollz/progressbar/v3 v3.19.1 h1:iv8BgwOvdML/S3p84uBpy/IMigv4U9594vPZYa2EdrU=
github.com/schollz/progressbar/v3 v3.19.1/go.mod h1:LFL7jqimKxfhero4K1eCkUr/6R39AgQeiPCJtlTWIW8=
github.com/schollz/progressbar/v3 v3.19.0 h1:Ea18xuIRQXLAUidVDox3AbwfUhD0/1IvohyTutOIFoc=
github.com/schollz/progressbar/v3 v3.19.0/go.mod h1:IsO3lpbaGuzh8zIMzgY3+J8l4C8GjO0Y9S69eFvNsec=
github.com/sclevine/spec v1.2.0/go.mod h1:W4J29eT/Kzv7/b9IWLB055Z+qvVC9vt0Arko24q7p+U=
github.com/seccomp/libseccomp-golang v0.9.1/go.mod h1:GbW5+tmTXfcxTToHLXlScSlAvWlF4P2Ca7zGrPiEpWo=
github.com/seccomp/libseccomp-golang v0.9.2-0.20210429002308-3879420cc921/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg=
@@ -853,8 +881,8 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/syndtr/gocapability v0.0.0-20170704070218-db04d3cc01c8/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww=
github.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww=
github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 h1:kdXcSzyDtseVEc4yCz2qF8ZrQvIDBJLl4S1c3GCXmoI=
@@ -913,24 +941,42 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo=
go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=
go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 h1:MdKucPl/HbzckWWEisiNqMPhRrAOQX8r4jTuGr636gk=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0/go.mod h1:RolT8tWtfHcjajEH5wFIZ4Dgh5jpPdFXYV9pTAk/qjc=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0 h1:8UQVDcZxOJLtX6gxtDt3vY2WTgvZqMQRzjsqiIHQdkc=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0/go.mod h1:2lmweYCiHYpEjQ/lSJBYhj9jP1zvCvQW4BqL9dnT7FQ=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 h1:88Y4s2C8oTui1LGM6bTWkw0ICGcOLCAI5l6zsD1j20k=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0/go.mod h1:Vl1/iaggsuRlrHf/hfPJPvVag77kKyvrLeD10kpMl+A=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 h1:zWWrB1U6nqhS/k6zYB74CjRpuiitRtLLi68VcgmOEto=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0/go.mod h1:2qXPNBX1OVRC0IwOnfo1ljoid+RD0QK3443EaqVlsOU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0 h1:RAE+JPfvEmvy+0LzyUA25/SGawPwIUbZ6u0Wug54sLc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0/go.mod h1:AGmbycVGEsRx9mXMZ75CsOyhSP6MFIcj/6dnG+vhVjk=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 h1:IeMeyr1aBvBiPVYihXIaeIZba6b8E1bYp7lbdxK8CQg=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0/go.mod h1:oVdCUtjq9MK9BlS7TtucsQwUcXcymNiEDjgDD2jMtZU=
go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=
go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=
go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=
go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=
go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
@@ -942,9 +988,8 @@ go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.0.0-20171113213409-9f005a07e0d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181009213950-7c1a557ab941/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
@@ -963,8 +1008,10 @@ golang.org/x/crypto v0.0.0-20201117144127-c1f2f97bffc9/go.mod h1:jdWPYTVW3xRLrWP
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -975,6 +1022,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20260312153236-7ab1446f8b90 h1:jiDhWWeC7jfWqR9c/uplMOqJ0sbNlNWv0UkzE0vX1MA=
golang.org/x/exp v0.0.0-20260312153236-7ab1446f8b90/go.mod h1:xE1HEv6b+1SCZ5/uscMRjUBKtIxworgEcEi+/n9NQDQ=
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM=
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
@@ -1040,8 +1089,10 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b
golang.org/x/net v0.0.0-20210825183410-e898025ed96a/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -1136,17 +1187,18 @@ golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk=
golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4=
golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU=
golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=
golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -1156,8 +1208,10 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -1263,8 +1317,12 @@ google.golang.org/genproto v0.0.0-20200527145253-8367513e4ece/go.mod h1:jDfRM7Fc
google.golang.org/genproto v0.0.0-20201110150050-8816d57aaa9a/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA=
google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M=
google.golang.org/genproto/googleapis/api v0.0.0-20260427160629-7cedc36a6bc4 h1:yOzSCGPx+cp5VO7IxvZ9SBFF7j1tZVcNtlHR2iYKtVo=
google.golang.org/genproto/googleapis/api v0.0.0-20260427160629-7cedc36a6bc4/go.mod h1:Q9HWtNeE7tM9npdIsEvqXj1QJIvVoeAV3rtXtS715Cw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 h1:m8qni9SQFH0tJc1X0vmnpw/0t+AImlSvp30sEupozUg=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4 h1:tEkOQcXgF6dH1G+MVKZrfpYvozGrzb91k6ha7jireSM=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v0.0.0-20160317175043-d3ddb4469d5a/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
google.golang.org/grpc v1.0.5/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
@@ -1338,6 +1396,7 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo=
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=
gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk=
gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8=
-43
View File
@@ -1,43 +0,0 @@
GIT_ROOT := $$(git rev-parse --show-toplevel)
test-integration:
@$(GIT_ROOT)/nix/test_integration.sh
test-integration-hosts:
$(GIT_ROOT)/scripts/tests/extra_hosts
CLIENT_VM := abra-client
vm-client-status:
sudo systemctl status microvm@$(CLIENT_VM).service
vm-client-create:test-integration-hosts
cd $(GIT_ROOT) && sudo microvm -f git+file://$(GIT_ROOT) -c $(CLIENT_VM)
vm-client-start:
sudo systemctl start microvm@$(CLIENT_VM).service
vm-client-update:test-integration-hosts
cd $(GIT_ROOT) && sudo microvm -R -f git+file://$(GIT_ROOT) -u $(CLIENT_VM)
vm-client-run:
sudo microvm -f git+file://$(GIT_ROOT) -r $(CLIENT_VM)
vm-client-stop:
sudo systemctl stop microvm@$(CLIENT_VM)
vm-client-delete: vm-client-stop
sudo rm -rf /var/lib/microvms/$(CLIENT_VM)
vm-client-connect:
ssh abra@10.0.0.2 -i $(GIT_ROOT)/tests/resources/local_integration_ssh
SERVER_VM := abra-server
vm-server-status:
sudo systemctl status microvm@$(SERVER_VM).service
vm-server-create:
cd $(GIT_ROOT) && sudo microvm -f git+file://$(GIT_ROOT) -c $(SERVER_VM)
vm-server-start:
sudo systemctl start microvm@$(SERVER_VM).service
vm-server-update:
cd $(GIT_ROOT) && sudo microvm -R -f git+file://$(GIT_ROOT) -u $(SERVER_VM)
vm-server-run:
cd $(GIT_ROOT) && sudo microvm -f git+file://$(GIT_ROOT) -r $(SERVER_VM)
vm-server-stop:
sudo systemctl stop microvm@$(SERVER_VM)
vm-server-delete: vm-server-stop
sudo rm -rf /var/lib/microvms/$(SERVER_VM)
vm-server-connect:
ssh abra@10.0.0.3 -i $(GIT_ROOT)/tests/resources/local_integration_ssh
-48
View File
@@ -1,48 +0,0 @@
# Hosts
These hosts are VMs used for running the integration tests on your local machine.
The hosts contain a client where abra with the tests will be run and a server
to simulate a remote machine.
## Prepare the host
For this setup to work you need a machine with NixOS and flakes enabled.
1. Import the abra flake
The install example is based on the [using nix flakes wiki page](https://nixos.wiki/wiki/flakes#Using_nix_flakes_with_NixOS).
```nix
inputs = {
abra = {
url = "git+https://git.coopcloud.tech/toolshed/abra.git";
};
};
```
2. Add the host module to your configuration
Now add the host module to your configuration. At the toplevel of a flake it could look like this:
```nix
desktop = inputs.nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules = [
abra.nixosModules.host
./configuration.nix
];
specialArgs = inputs;
};
```
3. Adjust the required config
```nix
abra.testing = {
enable = true; # loads the required config, when set true
externalInterface = "eth1"; # adjust this to your network interface that has access to the internet
};
```
You can look up the interface with `ip link`. After that rebuild your system and you are ready to go.
## Get started
After preparing the host run:
```
make test-integration
```
This runs the automatic setup of the VMs and network. You will be prompted if you want to run all
or specific files.
-145
View File
@@ -1,145 +0,0 @@
{
lib,
pkgs,
publicKey,
username,
pathToRepo,
defaultDNS,
extraHosts,
...
}:
let
index = 2;
mac = "00:00:00:00:00:01";
serverIp = "10.0.0.3";
in
{
imports = [
../../modules/ssh.nix
../../modules/user.nix
../../modules/docker.nix
];
microvm = {
vcpu = 4;
mem = 2049; # see issue related in microvm repo with 2048, so add 1MB
interfaces = [
{
id = "vm${toString index}";
type = "tap";
inherit mac;
}
];
shares = [
{
proto = "virtiofs";
tag = "repo";
# Source path can be absolute or relative
# to /var/lib/microvms/$hostName
source = "${lib.trim pathToRepo}";
mountPoint = "/home/${username}/abra";
}
];
};
boot.tmp = {
useTmpfs = true;
tmpfsSize = "2G";
};
networking = {
hostName = "abra-client";
useNetworkd = true;
};
systemd.network.networks."10-eth" = {
matchConfig.MACAddress = mac;
# Static IP configuration
address = [
"10.0.0.${toString index}/32"
"fec0::${lib.toHexString index}/128"
];
routes = [
{
# A route to the host
Destination = "10.0.0.0/32";
GatewayOnLink = true;
}
{
# Route to server
Destination = "${serverIp}/32";
Gateway = "10.0.0.0";
GatewayOnLink = true;
}
{
# Default route
Destination = "0.0.0.0/0";
Gateway = "10.0.0.0";
GatewayOnLink = true;
}
{
# Default route
Destination = "::/0";
Gateway = "fec0::";
GatewayOnLink = true;
}
];
networkConfig = {
# DNS servers no longer come from DHCP nor Router
# Advertisements. Perhaps you want to change the defaults:
DNS = defaultDNS;
};
};
# open the ports to allow ssh access from the host
networking.firewall.allowedTCPPorts = [ 22 ];
networking.firewall.allowedUDPPorts = [ 22 ];
networking.extraHosts = extraHosts;
environment.variables = {
CGO_ENABLED = 0;
TEST_SERVER = "abra.local";
ABRA_DIR = "$HOME/.abra_test";
};
programs.ssh = {
startAgent = true;
knownHostsFiles = [
(pkgs.writeText "local.keys" ''
abra.local ${publicKey}
'')
];
extraConfig = ''
Host abra.local
HostName abra.local
Port 22
User ${username}
'';
};
programs.git = {
enable = true;
# many recipe commands need a preset git user
config = [
{
user = {
name = "abra dev";
email = "helo@coopcloud.tech";
};
}
];
};
environment.systemPackages = with pkgs; [
# build dependencies, copied from flake.nix
go_1_26
gnumake
# testing dependencies
(bats.withLibraries (p: [
p.bats-assert
p.bats-file
p.bats-support
]))
jq
wget
];
}
-42
View File
@@ -1,42 +0,0 @@
{
serverIp,
username,
...
}:
{
# Home Manager needs a bit of information about you and the
# paths it should manage.
home.username = username;
home.homeDirectory = "/home/${username}";
# This value determines the Home Manager release that your
# configuration is compatible with. This helps avoid breakage
# when a new Home Manager release introduces backwards
# incompatible changes.
#
# You can update Home Manager without changing this value. See
# the Home Manager release notes for a list of state version
# changes in each release.
home.stateVersion = "26.05";
# Let Home Manager install and manage itself.
programs.home-manager.enable = true;
programs.ssh = {
enable = true;
enableDefaultConfig = false;
settings = {
"abra.local" = {
HostName = serverIp;
User = username;
Port = 22;
IdentityFile = "/home/${username}/abra/tests/resources/local_integration_ssh";
};
"*.abra.local" = {
HostName = serverIp;
User = username;
Port = 22;
IdentityFile = "/home/${username}/abra/tests/resources/local_integration_sshn";
};
};
};
}
-91
View File
@@ -1,91 +0,0 @@
{
lib,
defaultDNS,
...
}:
let
index = 3;
mac = "00:00:00:00:00:02";
clientIp = "10.0.0.2";
in
{
imports = [
../../modules/ssh.nix
../../modules/user.nix
../../modules/docker.nix
];
microvm = {
vcpu = 4;
mem = 8097; # see issue related in microvm repo with 2048, so add 1MB
interfaces = [
{
id = "vm${toString index}";
type = "tap";
inherit mac;
}
];
};
boot.tmp = {
useTmpfs = true;
tmpfsSize = "8G";
};
networking = {
hostName = "abra-server";
useNetworkd = true;
};
systemd.network.networks."11-eth" = {
matchConfig.MACAddress = mac;
# Static IP configuration
address = [
"10.0.0.${toString index}/32"
"fec0::${lib.toHexString index}/128"
];
routes = [
{
# A route to the host
Destination = "10.0.0.0/32";
GatewayOnLink = true;
}
{
# Route to server
Destination = "${clientIp}/32";
Gateway = "10.0.0.0";
GatewayOnLink = true;
}
{
# Default route
Destination = "0.0.0.0/0";
Gateway = "10.0.0.0";
GatewayOnLink = true;
}
{
# Default route
Destination = "::/0";
Gateway = "fec0::";
GatewayOnLink = true;
}
];
networkConfig = {
# DNS servers no longer come from DHCP nor Router
# Advertisements. Perhaps you want to change the defaults:
DNS = defaultDNS;
};
};
# open the ports to allow ssh access from the host
networking.firewall.allowedTCPPorts = [
22
80
443
1312 # deploy with udp and tcp on same port test
];
networking.firewall.allowedUDPPorts = [
22
80
443
1312 # deploy with udp and tcp on same port test
];
}
-7
View File
@@ -1,7 +0,0 @@
{ ... }:
{
virtualisation.docker = {
enable = true;
liveRestore = false;
};
}
-59
View File
@@ -1,59 +0,0 @@
{
lib,
config,
...
}:
let
maxVMs = 3;
in
{
options = {
abra.testing.enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Enable the abra integration testing framework";
};
abra.testing.externalInterface = lib.mkOption {
type = lib.types.str;
default = null;
description = "Change this to the interface with upstream Internet access";
};
};
config = lib.mkIf config.abra.testing.enable {
networking.useNetworkd = true;
systemd.network.wait-online.enable = false;
systemd.network.networks = builtins.listToAttrs (
map (index: {
name = "30-vm${toString index}";
value = {
matchConfig.Name = "vm${toString index}";
# Host's addresses
address = [
"10.0.0.0/32"
"fec0::/128"
];
# Setup routes to the VM
routes = [
{
Destination = "10.0.0.${toString index}/32";
}
{
Destination = "fec0::${lib.toHexString index}/128";
}
];
# Enable routing
networkConfig = {
IPv4Forwarding = true;
IPv6Forwarding = true;
};
};
}) (lib.genList (i: i + 1) maxVMs)
);
networking.nat = {
enable = true;
internalIPs = [ "10.0.0.0/24" ];
externalInterface = config.abra.testing.externalInterface;
};
};
}
-33
View File
@@ -1,33 +0,0 @@
{
privateKey,
publicKey,
username,
...
}:
{
# default host key location
environment.etc."ssh/ssh_host_ed25519_key" = {
text = privateKey;
mode = "0600";
};
environment.etc."ssh/ssh_host_ed25519_key.pub" = {
text = publicKey;
mode = "0644";
};
services.openssh = {
enable = true;
settings = {
PasswordAuthentication = false;
PermitRootLogin = "no";
AllowUsers = [ "${username}" ];
};
generateHostKeys = false;
hostKeys = [
{
path = "/etc/ssh/ssh_host_ed25519_key";
type = "ed25519";
}
];
};
}
-22
View File
@@ -1,22 +0,0 @@
{
username,
password,
publicKey,
...
}:
{
users.users."${username}" = {
isNormalUser = true;
password = password;
home = "/home/${username}";
description = "Abra user";
extraGroups = [
"wheel"
"networkmanager"
"docker"
];
openssh.authorizedKeys.keys = [
publicKey
];
};
}
-54
View File
@@ -1,54 +0,0 @@
{
buildGo126Module,
fetchgit,
lib,
installShellFiles,
}:
buildGo126Module rec {
pname = "abra";
version = "0.13.0-beta";
rev = "06a57ded025a43c80f94d4e65299add8a31830dc";
src = fetchgit {
url = "https://git.coopcloud.tech/toolshed/abra.git";
tag = version;
hash = "sha256-rgoK0TY0WLSQ39lPvVM80zW/qJF40VFBSxYDOaKXZQo=";
};
vendorHash = null;
nativeBuildInputs = [
installShellFiles
];
env.CGO_ENABLED = 0;
buildPhase = ''
runHook preBuild
go build -ldflags="-s -w -X 'main.Commit=${rev}' -X 'main.Version=${version}'" ./cmd/abra
runHook postBuild
'';
installPhase = ''
runHook preInstall
install -D abra $out/bin/abra
runHook postInstall
'';
postInstall = ''
export ABRA_DIR="$out"
$out/bin/abra autocomplete bash >abra.bash
$out/bin/abra autocomplete fish >abra.fish
$out/bin/abra autocomplete zsh >abra.zsh
installShellCompletion abra.{bash,fish,zsh}
'';
meta = with lib; {
description = "The Co-op Cloud utility belt";
homepage = "https://docs.coopcloud.tech/abra";
changelog = "https://git.coopcloud.tech/toolshed/abra/releases/tag/${version}";
mainProgram = "abra";
license = licenses.gpl3Plus;
maintainers = "devydave";
};
}
-40
View File
@@ -1,40 +0,0 @@
#!/usr/bin/env bash
GIT_ROOT=$(git rev-parse --show-toplevel)
# write path to repo
echo "$GIT_ROOT" > "$GIT_ROOT/tests/resources/path_to_repo"
# create or update a VM, start it and wait for successful ping
start_vm () {
if [ -d "/var/lib/microvms/abra-$1" ]; then
make "vm-$1-update"
else
make "vm-$1-create"
fi
make "vm-$1-start"
host_available=0
while [ $host_available == 0 ]; do
if ping -c 1 "$2" &> /dev/null
then
host_available=1
else
echo "could not ping $1, waiting for 5 seconds..."
sleep 5
fi
done
}
start_vm "client" "10.0.0.2"
start_vm "server" "10.0.0.3"
# revert dynamic content of file to prevent commiting changes
git restore -- "$GIT_ROOT/tests/resources/path_to_repo"
read -rp "Press enter to run all tests or specify test files: " TEST_INTEGRATION_FILES
# -t option is needed for stdin output that is checked in integration tests
# sleep is needed because adding ssh key sometimes does not find agent when adding without timeout
ssh -t abra@10.0.0.2 -i "$GIT_ROOT/tests/resources/local_integration_ssh" "cd abra; sleep 5; chmod 600 ./tests/resources/local_integration_ssh; ssh-add ./tests/resources/local_integration_ssh; make test-integration TEST_INTEGRATION_FILES=$TEST_INTEGRATION_FILES"
+50 -110
View File
@@ -260,30 +260,12 @@ func ReadAppEnvFile(appFile AppFile, name AppName) (App, error) {
func NewApp(env envfile.AppEnv, name string, appFile AppFile) (App, error) {
domain := env["DOMAIN"]
typeVar, hasType := env["TYPE"]
recipeVar, hasRecipe := env["RECIPE"]
if !hasType && !hasRecipe {
return App{}, errors.New(i18n.G("%s is missing the TYPE env var?", name))
}
// The recipe identity is taken from RECIPE when present (it records the
// canonical git source for externally-sourced recipes), otherwise from
// TYPE. The deployed version is always carried by TYPE when a TYPE line
// exists; only legacy apps that set RECIPE alone carry it there. RECIPE
// itself must stay a bare source pointer, never a versioned value.
identity := typeVar
if hasRecipe {
identity = recipeVar
}
versionSource := identity
if hasType {
versionSource = typeVar
}
recipeName, _, _ := strings.Cut(identity, ":")
if _, version, found := strings.Cut(versionSource, ":"); found && version != "" {
recipeName = fmt.Sprintf("%s:%s", recipeName, version)
recipeName, exists := env["RECIPE"]
if !exists {
recipeName, exists = env["TYPE"]
if !exists {
return App{}, errors.New(i18n.G("%s is missing the TYPE env var?", name))
}
}
return App{
@@ -410,15 +392,11 @@ func TemplateAppEnvSample(r recipe.Recipe, appName, server, domain string) error
newContents := strings.Replace(
string(read),
fmt.Sprintf("%s.example.com", r.ShortName()),
fmt.Sprintf("%s.example.com", r.Name),
domain,
-1,
)
if strings.Contains(r.Name, "/") {
newContents = injectRecipeLine(newContents, r.Name)
}
err = os.WriteFile(appEnvPath, []byte(newContents), 0)
if err != nil {
return err
@@ -429,37 +407,6 @@ func TemplateAppEnvSample(r recipe.Recipe, appName, server, domain string) error
return nil
}
// injectRecipeLine ensures the env file carries a RECIPE=<canonical name>
// line so a downstream `abra app deploy` (potentially on another machine)
// can re-fetch the recipe from its original git source. If a RECIPE= line
// already exists in the copied .env.sample it is replaced; otherwise a new
// line is inserted immediately after the TYPE= line, or appended at the
// end if no TYPE= line is present.
func injectRecipeLine(contents, canonicalName string) string {
lines := strings.Split(contents, "\n")
for i, line := range lines {
trimmed := strings.TrimLeft(line, " \t")
if strings.HasPrefix(trimmed, "RECIPE=") {
lines[i] = "RECIPE=" + canonicalName
return strings.Join(lines, "\n")
}
}
for i, line := range lines {
trimmed := strings.TrimLeft(line, " \t")
if strings.HasPrefix(trimmed, "TYPE=") {
out := make([]string, 0, len(lines)+1)
out = append(out, lines[:i+1]...)
out = append(out, "RECIPE="+canonicalName)
out = append(out, lines[i+1:]...)
return strings.Join(out, "\n")
}
}
if contents != "" && !strings.HasSuffix(contents, "\n") {
contents += "\n"
}
return contents + "RECIPE=" + canonicalName + "\n"
}
// SanitiseAppName makes a app name usable with Docker by replacing illegal
// characters.
func SanitiseAppName(name string) string {
@@ -567,22 +514,10 @@ func ExposeAllEnv(
_, exists := service.Environment[k]
if !exists {
value := v
switch k {
case "TYPE":
if k == "TYPE" || k == "RECIPE" {
// NOTE(d1): don't use the wrong version from the app env
// since we are deploying a new version. Keep the
// recipe name already recorded in TYPE and only
// swap in the version being deployed.
name, _, _ := strings.Cut(v, ":")
if _, version, found := strings.Cut(toDeployVersion, ":"); found {
value = fmt.Sprintf("%s:%s", name, version)
} else {
value = name
}
case "RECIPE":
// RECIPE records the canonical git source only; the
// version is carried by TYPE, so keep it bare here.
value, _, _ = strings.Cut(toDeployVersion, ":")
// since we are deploying a new version
value = toDeployVersion
}
service.Environment[k] = &value
log.Debug(i18n.G("%s: %s: %s", stackName, k, value))
@@ -707,55 +642,60 @@ func (a App) WriteRecipeVersion(version string, dryRun bool) error {
if err != nil {
return err
}
defer file.Close()
var (
lines []string
hasType bool
scanner = bufio.NewScanner(file)
dirtyVersion string
skipped bool
lines []string
scanner = bufio.NewScanner(file)
)
for scanner.Scan() {
line := scanner.Text()
lines = append(lines, line)
if strings.HasPrefix(line, "TYPE=") {
hasType = true
}
}
if err := scanner.Err(); err != nil {
file.Close()
log.Fatal(err)
}
file.Close()
// The recipe version is carried by a single field: TYPE when present (the
// standard recipe key), otherwise the legacy RECIPE key. When both exist
// (git-URL recipes) RECIPE stays a bare source pointer and only TYPE is
// versioned, so the two can never drift apart.
targetPrefix := "RECIPE="
if hasType {
targetPrefix = "TYPE="
}
for i, line := range lines {
if !strings.HasPrefix(line, targetPrefix) || strings.HasPrefix(line, "#") {
if !strings.HasPrefix(line, "RECIPE=") && !strings.HasPrefix(line, "TYPE=") {
lines = append(lines, line)
continue
}
name, _, _ := strings.Cut(line, ":")
lines[i] = fmt.Sprintf("%s:%s", name, version)
if strings.HasPrefix(line, "#") {
lines = append(lines, line)
continue
}
if strings.Contains(line, version) && !a.Recipe.Dirty && !strings.HasSuffix(line, config.DIRTY_DEFAULT) {
skipped = true
lines = append(lines, line)
continue
}
splitted := strings.Split(line, ":")
line = fmt.Sprintf("%s:%s", splitted[0], version)
lines = append(lines, line)
}
if dryRun {
log.Debug(i18n.G("skipping writing version %s because dry run", version))
return nil
}
if err := os.WriteFile(a.Path, []byte(strings.Join(lines, "\n")), os.ModePerm); err != nil {
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
log.Debug(i18n.G("version %s saved to %s.env", version, a.Domain))
if a.Recipe.Dirty && dirtyVersion != "" {
version = dirtyVersion
}
if !dryRun {
if err := os.WriteFile(a.Path, []byte(strings.Join(lines, "\n")), os.ModePerm); err != nil {
log.Fatal(err)
}
} else {
log.Debug(i18n.G("skipping writing version %s because dry run", version))
}
if !skipped {
log.Debug(i18n.G("version %s saved to %s.env", version, a.Domain))
} else {
log.Debug(i18n.G("skipping version %s write as already exists in %s.env", version, a.Domain))
}
return nil
}
-56
View File
@@ -3,8 +3,6 @@ package app_test
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"testing"
@@ -273,60 +271,6 @@ func TestWriteRecipeVersionOverwrite(t *testing.T) {
assert.Equal(t, "foo", app.Recipe.EnvVersion)
}
// TestWriteRecipeVersionSingleField ensures the version is written to exactly
// one field: TYPE when present (even alongside a RECIPE source pointer, as with
// git-URL recipes), otherwise the legacy RECIPE field. RECIPE must stay bare
// when a TYPE line exists so the two can never drift apart.
func TestWriteRecipeVersionSingleField(t *testing.T) {
cases := []struct {
name string
input string
want string
}{
{
name: "git recipe: TYPE and RECIPE both present",
input: "TYPE=myrecipe\nRECIPE=git.example.com/user/myrecipe\nDOMAIN=x\n",
want: "TYPE=myrecipe:1.2.3+4.5.6\nRECIPE=git.example.com/user/myrecipe\nDOMAIN=x",
},
{
name: "git recipe: re-versioning replaces only TYPE",
input: "TYPE=myrecipe:0.1.0+1.0.0\nRECIPE=git.example.com/user/myrecipe\nDOMAIN=x\n",
want: "TYPE=myrecipe:1.2.3+4.5.6\nRECIPE=git.example.com/user/myrecipe\nDOMAIN=x",
},
{
name: "legacy recipe: only RECIPE present",
input: "RECIPE=test_recipe\nDOMAIN=x\n",
want: "RECIPE=test_recipe:1.2.3+4.5.6\nDOMAIN=x",
},
{
name: "catalogue recipe: only TYPE present",
input: "TYPE=nextcloud\nDOMAIN=x\n",
want: "TYPE=nextcloud:1.2.3+4.5.6\nDOMAIN=x",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
p := filepath.Join(t.TempDir(), "app.env")
if err := os.WriteFile(p, []byte(tc.input), 0o644); err != nil {
t.Fatal(err)
}
app := appPkg.App{Path: p, Domain: "x"}
if err := app.WriteRecipeVersion("1.2.3+4.5.6", false); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(p)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, tc.want, string(got))
})
}
}
func TestWriteRecipeVersionUnknown(t *testing.T) {
test.Setup()
t.Cleanup(func() { test.Teardown() })
-30
View File
@@ -1,30 +0,0 @@
package app
import "testing"
func TestInjectRecipeLineAfterType(t *testing.T) {
in := "DOMAIN=example.com\nTYPE=foo\nVERSION=1.0\n"
want := "DOMAIN=example.com\nTYPE=foo\nRECIPE=org/foo\nVERSION=1.0\n"
got := injectRecipeLine(in, "org/foo")
if got != want {
t.Errorf("injectRecipeLine inserted RECIPE in wrong position\nwant:\n%q\ngot:\n%q", want, got)
}
}
func TestInjectRecipeLineReplacesExisting(t *testing.T) {
in := "TYPE=foo\nRECIPE=old\nDOMAIN=example.com\n"
want := "TYPE=foo\nRECIPE=org/foo\nDOMAIN=example.com\n"
got := injectRecipeLine(in, "org/foo")
if got != want {
t.Errorf("injectRecipeLine should replace existing RECIPE line\nwant:\n%q\ngot:\n%q", want, got)
}
}
func TestInjectRecipeLineNoTypeAppends(t *testing.T) {
in := "DOMAIN=example.com\n"
want := "DOMAIN=example.com\nRECIPE=org/foo\n"
got := injectRecipeLine(in, "org/foo")
if got != want {
t.Errorf("injectRecipeLine should append when TYPE is missing\nwant:\n%q\ngot:\n%q", want, got)
}
}
-310
View File
@@ -1,310 +0,0 @@
// Package audit checks deployed apps against a curated list of advisories.
package audit
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"time"
"coopcloud.tech/abra/pkg/i18n"
"gopkg.in/yaml.v3"
)
// Advisory statuses.
const (
StatusDraft = "draft"
StatusPublished = "published"
StatusWithdrawn = "withdrawn"
)
// Fix strategies.
const (
StrategyUpgrade = "upgrade"
StrategyRefresh = "refresh"
StrategyManual = "manual"
)
var severities = []string{"low", "medium", "high", "critical"}
// Advisory describes one known problem and which recipe versions and images
// it affects.
type Advisory struct {
ID string `yaml:"id"`
Title string `yaml:"title"`
Severity string `yaml:"severity"`
Status string `yaml:"status"`
Refs []string `yaml:"refs"`
Published string `yaml:"published"`
Recipes map[string]RecipeRange `yaml:"recipes"`
Images []ImageRule `yaml:"images"`
Fix Fix `yaml:"fix"`
// Path is the file the advisory was read from.
Path string `yaml:"-"`
}
// RecipeRange gives the affected recipe versions of one recipe.
type RecipeRange struct {
Affected string `yaml:"affected"`
Fixed string `yaml:"fixed"`
affected Range
}
// ImageRule describes which images are affected. An image that matches
// Match is fixed if ANY of the fixing conditions holds. See Evaluate.
type ImageRule struct {
Match string `yaml:"match"`
Env map[string]string `yaml:"env"`
Version string `yaml:"version"`
CreatedAfter string `yaml:"created_after"`
FixedDigests []string `yaml:"fixed_digests"`
AffectedDigests []string `yaml:"affected_digests"`
// Skipped lists the fields this version of abra does not understand.
Skipped []string `yaml:"-"`
env map[string]Range
version *Range
createdAfter *time.Time
}
// Fix describes how to fix the advisory.
type Fix struct {
Strategy string `yaml:"strategy"`
Notes string `yaml:"notes"`
}
var (
knownTopLevel = []string{"id", "title", "severity", "status", "refs", "published", "recipes", "images", "fix"}
knownRecipe = []string{"affected", "fixed"}
knownImage = []string{"match", "env", "version", "created_after", "fixed_digests", "affected_digests"}
knownFix = []string{"strategy", "notes"}
)
// LoadAdvisories reads every *.yml / *.yaml file below dir. Advisories that
// cannot be parsed are skipped and reported as warnings, so that one broken
// file does not stop the audit. Fields that this version of abra does not
// know are skipped with a warning, so newer advisories do not break older
// abra versions.
func LoadAdvisories(dir string) ([]Advisory, []string, error) {
var advisories []Advisory
var warnings []string
if _, err := os.Stat(dir); err != nil {
return nil, nil, errors.New(i18n.G("no advisories found: %s", err))
}
err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
ext := filepath.Ext(path)
if ext != ".yml" && ext != ".yaml" {
return nil
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
adv, warns, err := ParseAdvisory(data)
rel, _ := filepath.Rel(dir, path)
for _, w := range warns {
warnings = append(warnings, fmt.Sprintf("%s: %s", rel, w))
}
if err != nil {
warnings = append(warnings, i18n.G("%s: skipping advisory: %s", rel, err))
return nil
}
adv.Path = path
advisories = append(advisories, adv)
return nil
})
if err != nil {
return nil, warnings, err
}
sort.Slice(advisories, func(i, j int) bool { return advisories[i].ID < advisories[j].ID })
return advisories, warnings, nil
}
// ParseAdvisory parses and validates one advisory.
func ParseAdvisory(data []byte) (Advisory, []string, error) {
var adv Advisory
var warnings []string
var root yaml.Node
if err := yaml.Unmarshal(data, &root); err != nil {
return adv, nil, err
}
if len(root.Content) == 0 {
return adv, nil, errors.New(i18n.G("empty file"))
}
doc := root.Content[0]
if doc.Kind != yaml.MappingNode {
return adv, nil, errors.New(i18n.G("advisory is not a mapping"))
}
unknown := func(n *yaml.Node, known []string, where string) []string {
var skipped []string
if n == nil || n.Kind != yaml.MappingNode {
return nil
}
for i := 0; i+1 < len(n.Content); i += 2 {
key := n.Content[i].Value
if !slices.Contains(known, key) {
skipped = append(skipped, key)
warnings = append(warnings, i18n.G("unknown field %s%s skipped", where, key))
}
}
return skipped
}
unknown(doc, knownTopLevel, "")
if n := mapValue(doc, "recipes"); n != nil && n.Kind == yaml.MappingNode {
for i := 0; i+1 < len(n.Content); i += 2 {
unknown(n.Content[i+1], knownRecipe, fmt.Sprintf("recipes.%s.", n.Content[i].Value))
}
}
if n := mapValue(doc, "fix"); n != nil {
unknown(n, knownFix, "fix.")
}
if err := doc.Decode(&adv); err != nil {
return adv, warnings, err
}
if n := mapValue(doc, "images"); n != nil && n.Kind == yaml.SequenceNode {
for i, img := range n.Content {
if i < len(adv.Images) {
adv.Images[i].Skipped = unknown(img, knownImage, fmt.Sprintf("images[%d].", i))
}
}
}
if err := adv.validate(); err != nil {
return adv, warnings, err
}
return adv, warnings, nil
}
func mapValue(n *yaml.Node, key string) *yaml.Node {
if n == nil || n.Kind != yaml.MappingNode {
return nil
}
for i := 0; i+1 < len(n.Content); i += 2 {
if n.Content[i].Value == key {
return n.Content[i+1]
}
}
return nil
}
func (a *Advisory) validate() error {
if a.ID == "" {
return errors.New(i18n.G("missing id"))
}
a.Severity = strings.ToLower(a.Severity)
if a.Severity != "" && !slices.Contains(severities, a.Severity) {
return errors.New(i18n.G("%s: unknown severity %s", a.ID, a.Severity))
}
a.Status = strings.ToLower(a.Status)
if a.Status == "" {
a.Status = StatusDraft
}
if !slices.Contains([]string{StatusDraft, StatusPublished, StatusWithdrawn}, a.Status) {
return errors.New(i18n.G("%s: unknown status %s", a.ID, a.Status))
}
a.Fix.Strategy = strings.ToLower(a.Fix.Strategy)
if a.Fix.Strategy != "" && !slices.Contains([]string{StrategyUpgrade, StrategyRefresh, StrategyManual}, a.Fix.Strategy) {
return errors.New(i18n.G("%s: unknown fix strategy %s", a.ID, a.Fix.Strategy))
}
if len(a.Recipes) == 0 && len(a.Images) == 0 {
return errors.New(i18n.G("%s: neither recipes nor images given", a.ID))
}
for name, rr := range a.Recipes {
raw := rr.Affected
if raw == "" {
if rr.Fixed == "" {
return errors.New(i18n.G("%s: recipe %s needs affected or fixed", a.ID, name))
}
raw = "<" + rr.Fixed
}
r, err := ParseRange(raw)
if err != nil {
return errors.New(i18n.G("%s: recipe %s: %s", a.ID, name, err))
}
rr.affected = r
a.Recipes[name] = rr
}
for i := range a.Images {
img := &a.Images[i]
if img.Match == "" {
return errors.New(i18n.G("%s: images[%d] has no match", a.ID, i))
}
if len(img.Env) > 0 {
img.env = make(map[string]Range)
for k, v := range img.Env {
r, err := ParseRange(v)
if err != nil {
return errors.New(i18n.G("%s: images[%d].env.%s: %s", a.ID, i, k, err))
}
img.env[k] = r
}
}
if img.Version != "" {
r, err := ParseRange(img.Version)
if err != nil {
return errors.New(i18n.G("%s: images[%d].version: %s", a.ID, i, err))
}
img.version = &r
}
if img.CreatedAfter != "" {
t, err := parseTime(img.CreatedAfter)
if err != nil {
return errors.New(i18n.G("%s: images[%d].created_after: %s", a.ID, i, err))
}
img.createdAfter = &t
}
for _, d := range append(slices.Clone(img.FixedDigests), img.AffectedDigests...) {
if !strings.HasPrefix(d, "sha256:") {
return errors.New(i18n.G("%s: images[%d]: digest %s must start with sha256:", a.ID, i, d))
}
}
}
return nil
}
func parseTime(s string) (time.Time, error) {
layouts := []string{time.RFC3339Nano, "2006-01-02T15:04:05", "2006-01-02 15:04:05", "2006-01-02"}
for _, l := range layouts {
if t, err := time.Parse(l, s); err == nil {
return t, nil
}
}
return time.Time{}, errors.New(i18n.G("unable to parse time %s", s))
}
-282
View File
@@ -1,282 +0,0 @@
package audit
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRange(t *testing.T) {
tests := []struct {
rng string
version string
want bool
}{
{"<7.0.3+30.0.1", "7.0.2+30.0.1", true},
{"<7.0.3+30.0.1", "7.0.3+30.0.1", false},
{"<7.0.3+30.0.1", "7.0.3+30.0.0", true},
{"<7.0.3", "7.0.2+31.0.0", true},
{"<7.0.3", "7.0.3+29.0.0", false},
{"<8.3.14", "8.3.12", true},
{">=8.3.0 <8.3.14", "8.2.20", false},
{">=8.3.0, <8.3.14", "8.3.13", true},
{">=8.3.0 <8.3.14 || >=8.4.0 <8.4.2", "8.4.1", true},
{">=8.3.0 <8.3.14 || >=8.4.0 <8.4.2", "8.4.2", false},
{"< 35.0.4", "35.0.3-apache", true},
{"8.3", "8.3.0", true},
{"!=1.2.3", "1.2.3", false},
{"<=v1.2", "1.2.0", true},
}
for _, tc := range tests {
r, err := ParseRange(tc.rng)
require.NoError(t, err, tc.rng)
v, err := ParseVersion(tc.version)
require.NoError(t, err, tc.version)
assert.Equal(t, tc.want, r.Contains(v), "%s in %s", tc.version, tc.rng)
}
for _, bad := range []string{"", "<", "<foo", "1.2 || "} {
_, err := ParseRange(bad)
assert.Error(t, err, bad)
}
}
const sampleAdvisory = `
id: CCA-2026-0012
title: PHP 8.3 CGI argument injection
severity: critical
status: published
refs: [CVE-2026-12345]
published: 2026-10-20
future_field: whatever
recipes:
nextcloud:
affected: "<7.0.3+30.0.1"
fixed: "7.0.3+30.0.1"
images:
- match: "nextcloud:30*-apache"
created_after: 2026-10-18
affected_digests: [sha256:1111111111111111111111111111111111111111111111111111111111111111]
fixed_digests: [sha256:2222222222222222222222222222222222222222222222222222222222222222]
- match: "*"
base: "php:8.3*"
env: { PHP_VERSION: ">=8.3.0 <8.3.14" }
fix:
strategy: refresh
notes: "Upstream images rebuilt on 2026-10-18; a redeploy is enough."
`
func TestParseAdvisory(t *testing.T) {
adv, warns, err := ParseAdvisory([]byte(sampleAdvisory))
require.NoError(t, err)
assert.Equal(t, "CCA-2026-0012", adv.ID)
assert.Equal(t, StatusPublished, adv.Status)
assert.Equal(t, "2026-10-20", adv.Published)
assert.Equal(t, "7.0.3+30.0.1", adv.Recipes["nextcloud"].Fixed)
require.Len(t, adv.Images, 2)
require.NotNil(t, adv.Images[0].createdAfter)
assert.Equal(t, time.Date(2026, 10, 18, 0, 0, 0, 0, time.UTC), *adv.Images[0].createdAfter)
assert.Equal(t, []string{"base"}, adv.Images[1].Skipped)
joined := strings.Join(warns, "\n")
assert.Contains(t, joined, "future_field")
assert.Contains(t, joined, "images[1].base")
}
func TestParseAdvisoryInvalid(t *testing.T) {
for name, doc := range map[string]string{
"no id": "status: published\nrecipes: {a: {fixed: 1.0.0}}",
"bad severity": "id: X\nseverity: extreme\nrecipes: {a: {fixed: 1.0.0}}",
"no conditions": "id: X",
"bad range": "id: X\nrecipes: {a: {affected: '<foo'}}",
"bad digest": "id: X\nimages: [{match: a, fixed_digests: [abc]}]",
"bad strategy": "id: X\nrecipes: {a: {fixed: 1.0.0}}\nfix: {strategy: pray}",
"image no match": "id: X\nimages: [{env: {A: '<1'}}]",
} {
_, _, err := ParseAdvisory([]byte(doc))
assert.Error(t, err, name)
}
}
func TestLoadAdvisories(t *testing.T) {
dir := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(dir, "2026"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(dir, "2026", "good.yml"), []byte(sampleAdvisory), 0o644))
require.NoError(t, os.WriteFile(filepath.Join(dir, "broken.yaml"), []byte("id: [\n"), 0o644))
require.NoError(t, os.WriteFile(filepath.Join(dir, "README.md"), []byte("# hi"), 0o644))
advs, warns, err := LoadAdvisories(dir)
require.NoError(t, err)
require.Len(t, advs, 1)
assert.Contains(t, strings.Join(warns, "\n"), "broken.yaml")
}
func mustImage(t *testing.T, service, ref string, info *ImageInfo) ImageRef {
t.Helper()
img, err := ParseImageRef(service, ref)
require.NoError(t, err)
if info != nil {
cp := *info
img.Info = &cp
}
return img
}
func at(s string) *time.Time {
tm, err := time.Parse(time.RFC3339, s)
if err != nil {
panic(err)
}
return &tm
}
func TestEvaluate(t *testing.T) {
adv, _, err := ParseAdvisory([]byte(sampleAdvisory))
require.NoError(t, err)
advs := []Advisory{adv}
newImg := &ImageInfo{Created: at("2026-10-19T10:00:00Z"), Env: map[string]string{"PHP_VERSION": "8.3.14"}}
oldImg := &ImageInfo{Created: at("2026-10-01T10:00:00Z"), Env: map[string]string{"PHP_VERSION": "8.3.12"}}
noPHP := &ImageInfo{Created: at("2026-10-01T10:00:00Z"), Env: map[string]string{}}
states := []AppState{
{
// clean: fixed recipe, rebuilt image
Server: "s1", Name: "clean.example.com", Recipe: "nextcloud", Version: "7.0.3+30.0.1",
Images: []ImageRef{
mustImage(t, "app", "nextcloud:30.0.1-apache@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", newImg),
mustImage(t, "db", "postgres:15@sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", noPHP),
},
},
{
// old recipe version
Server: "s1", Name: "old.example.com", Recipe: "nextcloud", Version: "7.0.2+30.0.0",
Images: []ImageRef{mustImage(t, "app", "nextcloud:30.0.0-apache@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", newImg)},
},
{
// current recipe, stale image under the same tag
Server: "s1", Name: "stale.example.com", Recipe: "nextcloud", Version: "7.0.3+30.0.1",
Images: []ImageRef{mustImage(t, "app", "nextcloud:30.0.1-apache@sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", oldImg)},
},
{
// some other recipe built on old php
Server: "s2", Name: "wp.example.com", Recipe: "wordpress", Version: "1.0.0+6.0.0",
Images: []ImageRef{mustImage(t, "app", "wordpress:6@sha256:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", oldImg)},
},
{
// known bad digest
Server: "s2", Name: "bad.example.com", Recipe: "nextcloud", Version: "7.0.3+30.0.1",
Images: []ImageRef{mustImage(t, "app", "nextcloud:30.0.1-apache@sha256:1111111111111111111111111111111111111111111111111111111111111111",
&ImageInfo{Created: at("2026-10-20T10:00:00Z"), Env: map[string]string{"PHP_VERSION": "8.3.14"}})},
},
{
// no image config and no digest: unknown
Server: "s2", Name: "nocfg.example.com", Recipe: "nextcloud", Version: "7.0.3+30.0.1",
Images: []ImageRef{mustImage(t, "app", "nextcloud:30.0.1-apache", nil)},
},
{
// reproducible build: unusable build time, php fixed by env
Server: "s2", Name: "repro.example.com", Recipe: "nextcloud", Version: "7.0.3+30.0.1",
Images: []ImageRef{mustImage(t, "app", "nextcloud:30.0.1-apache@sha256:eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
&ImageInfo{Created: at("1970-01-01T00:00:00Z"), Env: map[string]string{"PHP_VERSION": "8.3.13"}})},
},
}
markUnusableCreated(states)
findings := Evaluate(states, advs, EvaluateOptions{})
got := map[string]Finding{}
for _, f := range findings {
got[f.App] = f
}
assert.NotContains(t, got, "clean.example.com")
require.Contains(t, got, "old.example.com")
assert.Equal(t, FindingAffected, got["old.example.com"].Status)
assert.Equal(t, "abra app upgrade old.example.com 7.0.3+30.0.1", got["old.example.com"].Fix)
require.Contains(t, got, "stale.example.com")
assert.Equal(t, FindingAffected, got["stale.example.com"].Status)
assert.Equal(t, "abra app deploy stale.example.com --force && abra audit", got["stale.example.com"].Fix)
require.Contains(t, got, "wp.example.com")
assert.Equal(t, FindingAffected, got["wp.example.com"].Status)
require.Contains(t, got, "bad.example.com")
assert.Equal(t, FindingAffected, got["bad.example.com"].Status)
require.Contains(t, got, "nocfg.example.com")
assert.Equal(t, FindingUnknown, got["nocfg.example.com"].Status)
require.Contains(t, got, "repro.example.com")
assert.Equal(t, FindingAffected, got["repro.example.com"].Status, "env still says affected")
assert.Contains(t, strings.Join(got["repro.example.com"].Reasons, " "), "PHP_VERSION=8.3.13")
// drafts are ignored, unless asked for
advs[0].Status = StatusDraft
assert.Empty(t, Evaluate(states, advs, EvaluateOptions{}))
assert.Len(t, Evaluate(states, advs, EvaluateOptions{IncludeDrafts: true}), len(findings))
// withdrawn advisories are always ignored
advs[0].Status = StatusWithdrawn
assert.Empty(t, Evaluate(states, advs, EvaluateOptions{IncludeDrafts: true}))
}
func TestCreatedUnusable(t *testing.T) {
adv, _, err := ParseAdvisory([]byte(`
id: X
status: published
images:
- match: "app:1"
created_after: 2026-10-18
fix: {strategy: refresh}
`))
require.NoError(t, err)
same := at("2026-10-01T00:00:00Z")
states := []AppState{
{Server: "a", Name: "a1", Images: []ImageRef{mustImage(t, "app", "app:1@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", &ImageInfo{Created: same})}},
{Server: "b", Name: "b1", Images: []ImageRef{mustImage(t, "app", "app:1@sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", &ImageInfo{Created: same})}},
{Server: "c", Name: "c1", Images: []ImageRef{mustImage(t, "app", "app:1@sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
&ImageInfo{Created: at("2026-10-01T00:00:00Z"), BaseCreated: at("2026-10-05T00:00:00Z")})}},
{Server: "d", Name: "d1", Images: []ImageRef{mustImage(t, "app", "app:1@sha256:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", &ImageInfo{Created: at("2026-10-02T00:00:00Z")})}},
{Server: "e", Name: "e1", Images: []ImageRef{mustImage(t, "app", "app:1@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &ImageInfo{Created: at("2026-10-20T00:00:00Z")})}},
}
markUnusableCreated(states)
got := map[string]string{}
for _, f := range Evaluate(states, []Advisory{adv}, EvaluateOptions{}) {
got[f.App] = f.Status
}
assert.Equal(t, map[string]string{
"a1": FindingUnknown, // shares build time with b1
"b1": FindingUnknown, // shares build time with a1
"c1": FindingUnknown, // built before its base
"d1": FindingAffected, // usable and old
}, got)
}
func TestGlobMatch(t *testing.T) {
img, err := ParseImageRef("app", "git.coopcloud.tech/coop-cloud/foo:1.2-apache@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
require.NoError(t, err)
assert.True(t, globMatch("*", img))
assert.True(t, globMatch("git.coopcloud.tech/coop-cloud/foo", img))
assert.True(t, globMatch("*/foo:1.*-apache", img))
assert.False(t, globMatch("foo:*", img))
img, err = ParseImageRef("app", "docker.io/library/nextcloud:30.0.1-apache")
require.NoError(t, err)
assert.Equal(t, "nextcloud", img.Name)
assert.True(t, globMatch("nextcloud:30*-apache", img))
}
-415
View File
@@ -1,415 +0,0 @@
package audit
import (
"fmt"
"regexp"
"slices"
"strings"
"coopcloud.tech/abra/pkg/i18n"
)
// Finding statuses.
const (
FindingAffected = "affected"
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"`
// 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"`
recipeAffected bool
// images that are affected or unknown, for VerifyRefresh
images []ImageRef
os, arch string
}
// verdict of one image rule for one image.
type verdict int
const (
notApplicable verdict = iota
fixed
affected
unknown
)
// EvaluateOptions configures Evaluate.
type EvaluateOptions struct {
// IncludeDrafts also applies advisories with status draft, so that a
// maintainer can try an advisory before publishing it.
IncludeDrafts bool
}
// Applies reports whether an advisory is used: published advisories always,
// drafts only on request, withdrawn advisories never.
func (o EvaluateOptions) Applies(adv Advisory) bool {
switch adv.Status {
case StatusPublished:
return true
case StatusDraft:
return o.IncludeDrafts
}
return false
}
// Evaluate matches every app against every advisory that applies.
func Evaluate(states []AppState, advisories []Advisory, opts EvaluateOptions) []Finding {
var findings []Finding
for _, st := range states {
for i := range advisories {
adv := &advisories[i]
if !opts.Applies(*adv) {
continue
}
if f, ok := evaluateApp(st, adv); ok {
findings = append(findings, f)
}
}
}
return findings
}
func evaluateApp(st AppState, adv *Advisory) (Finding, bool) {
f := Finding{
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 != "" {
v, err := ParseVersion(st.Version)
if err == nil && rr.affected.Contains(v) {
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)
}
}
// 2. image conditions
for _, img := range st.Images {
for _, rule := range adv.Images {
if !globMatch(rule.Match, img) {
continue
}
v, reason := evaluateImage(rule, img)
reason = fmt.Sprintf("%s (%s): %s", img.Service, img.NameTag(), reason)
switch v {
case affected:
gotAffected = true
case unknown:
gotUnknown = true
default:
continue
}
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)
}
}
}
switch {
case gotAffected:
f.Status = FindingAffected
case gotUnknown:
f.Status = FindingUnknown
default:
return f, false
}
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;
// 2. a digest in fixed_digests is fixed;
// 3. the env block selects images: if a variable is missing, the rule does
// not apply (the image is not built on that runtime). If every variable
// is in its range, env votes affected, otherwise fixed;
// 4. version is an affected range on the image version, and votes the same way;
// 5. created_after votes fixed for images built at or after that time, and
// affected for older images, but only when the build time is usable.
//
// The image is fixed if any condition votes fixed, affected if one votes
// affected, and unknown otherwise: an image that matches but satisfies no
// condition is never reported as OK.
func evaluateImage(rule ImageRule, img ImageRef) (verdict, string) {
if img.Digest != "" && slices.Contains(rule.AffectedDigests, img.Digest) {
return affected, i18n.G("digest %s is known to be affected", shortDigest(img.Digest))
}
if img.Digest != "" && slices.Contains(rule.FixedDigests, img.Digest) {
return fixed, ""
}
needsConfig := len(rule.env) > 0 || rule.version != nil || rule.createdAfter != nil
info := img.Info
if needsConfig && info == nil {
if img.InfoErr != nil {
return unknown, i18n.G("image config unavailable: %s", img.InfoErr)
}
return unknown, i18n.G("image config unavailable")
}
var votedAffected []string
var notes []string
if len(rule.env) > 0 {
for k := range rule.env {
if _, ok := info.Env[k]; !ok {
return notApplicable, ""
}
}
allIn := true
var vals []string
for k, r := range rule.env {
val := info.Env[k]
vals = append(vals, fmt.Sprintf("%s=%s", k, val))
v, err := ParseVersion(val)
if err != nil {
allIn = false
notes = append(notes, i18n.G("unable to parse %s=%s", k, val))
continue
}
if !r.Contains(v) {
return fixed, ""
}
}
if allIn {
slices.Sort(vals)
votedAffected = append(votedAffected, strings.Join(vals, ", "))
}
}
if rule.version != nil {
raw := info.Version()
if raw == "" {
notes = append(notes, i18n.G("image has no version"))
} else if v, err := ParseVersion(raw); err != nil {
notes = append(notes, i18n.G("unable to parse image version %s", raw))
} else if rule.version.Contains(v) {
votedAffected = append(votedAffected, i18n.G("version %s is in %s", raw, rule.version.Raw))
} else {
return fixed, ""
}
}
if rule.createdAfter != nil {
switch {
case info.Created == nil:
notes = append(notes, i18n.G("image has no build time"))
case info.createdUnusable != "":
notes = append(notes, info.createdUnusable)
case !info.Created.Before(*rule.createdAfter):
return fixed, ""
default:
votedAffected = append(votedAffected, i18n.G("built %s, before %s", info.Created.UTC().Format("2006-01-02 15:04"), rule.createdAfter.UTC().Format("2006-01-02 15:04")))
}
}
if len(votedAffected) > 0 {
return affected, strings.Join(votedAffected, "; ")
}
if img.Digest == "" {
notes = append(notes, i18n.G("service spec has no digest (registry lookup failed at deploy?)"))
}
if len(rule.Skipped) > 0 {
notes = append(notes, i18n.G("conditions not supported by this abra: %s", strings.Join(rule.Skipped, ", ")))
}
if len(notes) == 0 {
notes = append(notes, i18n.G("no condition proves digest %s fixed", shortDigest(img.Digest)))
}
return unknown, strings.Join(notes, "; ")
}
// recipeRange looks up the advisory's range for a recipe. Advisories name
// recipes in the short form of ShortRecipeName, so "nextcloud" covers
// git.coopcloud.tech/coop-cloud/nextcloud but not a fork such as
// git.coopcloud.tech/c4dt/nextcloud, which has its own versions.
func recipeRange(adv *Advisory, recipe string) (RecipeRange, bool) {
if rr, ok := adv.Recipes[recipe]; ok {
return rr, true
}
rr, ok := adv.Recipes[ShortRecipeName(recipe)]
return rr, ok
}
func upgradeCommand(adv *Advisory, app, recipe string) string {
if rr, ok := recipeRange(adv, recipe); ok && rr.Fixed != "" {
return fmt.Sprintf("abra app upgrade %s %s", app, rr.Fixed)
}
return fmt.Sprintf("abra app upgrade %s", app)
}
// 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 ActionUpgrade, upgrade()
}
switch adv.Fix.Strategy {
case StrategyUpgrade:
return ActionUpgrade, upgrade()
case StrategyRefresh:
// 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 ActionAdvisory, strings.TrimSpace(adv.Fix.Notes)
}
return ActionAdvisory, i18n.G("No fix is known yet.")
}
}
// globMatch matches an advisory pattern against an image. "*" matches any
// sequence of characters, "?" a single one. Patterns with a ":" are matched
// against "name:tag", others against the name only.
func globMatch(pattern string, img ImageRef) bool {
target := img.Name
if strings.Contains(pattern, ":") {
target = img.NameTag()
}
return globToRegexp(pattern).MatchString(target)
}
func globToRegexp(pattern string) *regexp.Regexp {
var b strings.Builder
b.WriteString("^")
for _, r := range pattern {
switch r {
case '*':
b.WriteString(".*")
case '?':
b.WriteString(".")
default:
b.WriteString(regexp.QuoteMeta(string(r)))
}
}
b.WriteString("$")
return regexp.MustCompile(b.String())
}
func shortDigest(d string) string {
if d == "" {
return i18n.G("(none)")
}
d = strings.TrimPrefix(d, "sha256:")
if len(d) > 12 {
d = d[:12]
}
return "sha256:" + d
}
-442
View File
@@ -1,442 +0,0 @@
package audit
import (
"context"
"fmt"
"strings"
"time"
"coopcloud.tech/abra/pkg/i18n"
"coopcloud.tech/abra/pkg/log"
)
// FetchFunc reads the config of an image for a platform from a registry.
type FetchFunc func(ctx context.Context, img ImageRef, os, arch string) (*ImageInfo, error)
// RegistryFetch is the default FetchFunc.
func RegistryFetch(ctx context.Context, img ImageRef, os, arch string) (*ImageInfo, error) {
return FetchFromRegistry(ctx, img, os, arch)
}
// TagsFunc lists the tags of an image's repository.
type TagsFunc func(ctx context.Context, img ImageRef) ([]string, error)
// 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 {
img *ImageRef
err error
}
type tagsResult struct {
tags []string
err error
}
// CheckFixes verifies the suggested fix of each finding, and sets its
// action:
//
// - 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.
//
// When the registry or the recipe cannot be read, the suggestion is kept and
// marked as unchecked.
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]
switch {
case f.recipeAffected:
c.checkRecipeRange(f)
case len(f.images) == 0:
case f.Advisory.Fix.Strategy == StrategyRefresh:
c.checkRefresh(ctx, f)
case f.Advisory.Fix.Strategy == StrategyUpgrade:
c.checkUpgrade(ctx, f, f.images)
}
}
}
func (c *FixChecker) checkRecipeRange(f *Finding) {
rr, ok := recipeRange(f.Advisory, f.Recipe)
if !ok || rr.Fixed == "" || c.Recipes == nil {
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 += " " + i18n.G("(unchecked: %s)", err)
return
}
want, _ := ParseVersion(rr.Fixed)
for _, v := range versions {
if pv, err := ParseVersion(v); err == nil && pv.Compare(want) >= 0 {
return
}
}
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
}
func (c *FixChecker) checkRefresh(ctx context.Context, f *Finding) {
if f.arch == "" {
f.Fix += " " + i18n.G("(unchecked: platform unknown)")
return
}
var stale []ImageRef
var fetchErr error
for _, img := range f.images {
// 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, 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))
continue
}
if cur.Digest == img.Digest || !fixedByAdvisory(f.Advisory, *cur) {
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:
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)
}
}
// 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 = 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 = generic + " " + i18n.G("(unchecked: %s)", err)
return
}
current, curErr := ParseVersion(f.Version)
var newer []string
for _, v := range versions {
pv, _ := ParseVersion(v)
if curErr != nil || pv.Compare(current) > 0 {
newer = append(newer, v)
}
}
if len(newer) == 0 {
f.Reasons = append(f.Reasons, i18n.G("no newer release of %s exists", ShortRecipeName(f.Recipe)))
c.noRelease(ctx, f, stale)
return
}
// Check the latest release first: if it is not fixed, no release is.
fixedAt := func(v string) (bool, error) { return c.versionFixed(ctx, f, v, names) }
latest := newer[len(newer)-1]
ok, err := fixedAt(latest)
if err != nil {
f.Fix = generic + " " + i18n.G("(unchecked: %s)", err)
return
}
if !ok {
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
}
best := latest
for _, v := range newer[:len(newer)-1] {
if ok, err := fixedAt(v); err == nil && ok {
best = v
break
}
}
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
// one of the given names is fixed. An image that is no longer used counts as
// fixed.
func (c *FixChecker) versionFixed(ctx context.Context, f *Finding, version string, names map[string]bool) (bool, error) {
refs, err := c.Recipes.Images(f.Recipe, version)
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, used, err
}
if !fixedByAdvisory(f.Advisory, *cur) {
log.Debug(i18n.G("%s %s: %s is not fixed", ShortRecipeName(f.Recipe), where, img.NameTag()))
return false, used, nil
}
}
return true, used, nil
}
// current reads the image a reference points to now: by digest if byDigest
// is set and the reference has one, by tag otherwise.
func (c *FixChecker) current(ctx context.Context, img ImageRef, os, arch string, byDigest bool) (*ImageRef, error) {
ref := img
if !byDigest {
ref.Digest = ""
}
key := strings.Join([]string{ref.NameTag(), ref.Digest, os, arch}, "|")
if r, ok := c.cache[key]; ok {
return r.img, r.err
}
ref.Info, ref.InfoErr = nil, nil
fctx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
info, err := c.Fetch(fctx, ref, os, arch)
if err != nil {
c.cache[key] = fetchResult{err: err}
return nil, err
}
info.createdUnusable = createdUnusable(info)
if info.Digest != "" {
ref.Digest = info.Digest
}
ref.Info = info
c.cache[key] = fetchResult{img: &ref}
return &ref, nil
}
// fixedByAdvisory reports whether no image rule of the advisory flags img.
func fixedByAdvisory(adv *Advisory, img ImageRef) bool {
for _, rule := range adv.Images {
if !globMatch(rule.Match, img) {
continue
}
if v, _ := evaluateImage(rule, img); v == affected || v == unknown {
return false
}
}
return true
}
func appendUnique(list []string, s string) []string {
if containsString(list, s) {
return list
}
return append(list, s)
}
func lastOr(list []string, def string) string {
if len(list) == 0 {
return def
}
return list[len(list)-1]
}
-332
View File
@@ -1,332 +0,0 @@
package audit
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"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"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const phpAdvisory = `
id: PHP
status: published
recipes:
ranged: {fixed: 2.0.0+1.0.0}
images:
- match: "*"
env: { PHP_VERSION: ">=8.5.0 <8.5.13" }
fix: {strategy: refresh}
`
// fakeRecipes maps recipe -> version -> images.
type fakeRecipes map[string]map[string][]string
func (f fakeRecipes) Versions(name string) ([]string, error) {
vs, ok := f[name]
if !ok {
return nil, errors.New("no such recipe")
}
var out []string
for v := range vs {
out = append(out, v)
}
sortVersions(out)
return out, nil
}
func (f fakeRecipes) Images(name, version string) ([]string, error) {
return f[name][version], nil
}
func digestOf(c string) string { return "sha256:" + strings.Repeat(c, 64) }
func TestCheckFixes(t *testing.T) {
adv, _, err := ParseAdvisory([]byte(phpAdvisory))
require.NoError(t, err)
old := &ImageInfo{Env: map[string]string{"PHP_VERSION": "8.5.12"}}
app := func(name, recipe, version, image string, platform bool) AppState {
st := AppState{Server: "s", Name: name, Recipe: recipe, Version: version,
Images: []ImageRef{mustImage(t, "app", image, old)}}
if platform {
st.OS, st.Arch = "linux", "amd64"
}
return st
}
states := []AppState{
app("floating", "nc", "1.0.0+35.0.2", "nextcloud:35-fpm@"+digestOf("a"), true),
app("pinned", "nc", "1.0.0+35.0.2", "nextcloud:35.0.2-fpm@"+digestOf("b"), true),
app("fork", "git.coopcloud.tech/c4dt/nextcloud", "16.2.2+35.0.2-fpm", "nextcloud:35.0.2-fpm@"+digestOf("b"), true),
app("stale", "stale", "1.0.0+35.0.1", "nextcloud:35.0.1-fpm@"+digestOf("e"), true),
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{
"nc": {
"1.0.0+35.0.2": {"nextcloud:35.0.2-fpm", "postgres:15"},
"1.0.1+35.0.3": {"nextcloud:35.0.3-fpm", "postgres:15"},
"1.1.0+35.0.4": {"nextcloud:35.0.4-fpm", "postgres:15"},
},
"git.coopcloud.tech/c4dt/nextcloud": {
"16.2.1+35.0.2-fpm": {"nextcloud:35.0.2-fpm"},
"16.2.2+35.0.2-fpm": {"nextcloud:35.0.2-fpm"},
},
"stale": {
"1.0.0+35.0.1": {"nextcloud:35.0.1-fpm"},
"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()+"@"+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")
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, 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)
}
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")
// 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.")
// 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 !strings.HasPrefix(img, "other:1@") {
assert.Equal(t, 1, n, img)
}
}
}
func TestShortRecipeName(t *testing.T) {
for in, want := range map[string]string{
"nextcloud": "nextcloud",
"git.coopcloud.tech/coop-cloud/nextcloud": "nextcloud",
"git.coopcloud.tech/c4dt/nextcloud": "c4dt/nextcloud",
"https://git.coopcloud.tech/c4dt/nextcloud.git": "c4dt/nextcloud",
"github.com/foo/nextcloud": "github.com/foo/nextcloud",
} {
assert.Equal(t, want, ShortRecipeName(in), in)
}
}
func TestRecipeRangeForks(t *testing.T) {
adv, _, err := ParseAdvisory([]byte("id: X\nstatus: published\nrecipes: {nextcloud: {fixed: 7.0.0}}\n"))
require.NoError(t, err)
_, ok := recipeRange(&adv, "nextcloud")
assert.True(t, ok)
_, ok = recipeRange(&adv, "git.coopcloud.tech/coop-cloud/nextcloud")
assert.True(t, ok)
_, ok = recipeRange(&adv, "git.coopcloud.tech/c4dt/nextcloud")
assert.False(t, ok, "a fork has its own versions")
}
func TestComposeImages(t *testing.T) {
assert.Equal(t, []string{"nextcloud:35.0.2-fpm", "nginx:1.29", "postgres:15"}, composeImages(`
services:
app: {image: nextcloud:35.0.2-fpm}
web: {image: "${WEB_IMAGE:-nginx:1.29}"}
db: {image: postgres:15}
custom: {image: "${CUSTOM_IMAGE}"}
build: {build: .}
`))
}
func TestGitRecipes(t *testing.T) {
dir := t.TempDir()
repo, err := git.PlainInit(dir, false)
require.NoError(t, err)
sig := &object.Signature{Name: "t", Email: "t@example.com", When: time.Now()}
release := func(version, image string) {
commitFile(t, repo, dir, "compose.yml", "services:\n app:\n image: "+image+"\n")
head, err := repo.Head()
require.NoError(t, err)
_, err = repo.CreateTag(version, head.Hash(), &git.CreateTagOptions{Tagger: sig, Message: version})
require.NoError(t, err)
}
release("1.0.0+35.0.2-fpm", "nextcloud:35.0.2-fpm")
release("1.0.1+35.0.3-fpm", "nextcloud:35.0.3-fpm")
// a local edit must survive
require.NoError(t, os.WriteFile(filepath.Join(dir, "compose.yml"), []byte("local edit\n"), 0o644))
g := NewGitRecipes([]recipe.Recipe{{Name: "nc", Dir: dir}}, true)
versions, err := g.Versions("nc")
require.NoError(t, err)
assert.Equal(t, []string{"1.0.0+35.0.2-fpm", "1.0.1+35.0.3-fpm"}, versions)
images, err := g.Images("nc", "1.0.0+35.0.2-fpm")
require.NoError(t, err)
assert.Equal(t, []string{"nextcloud:35.0.2-fpm"}, images)
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)
}
-326
View File
@@ -1,326 +0,0 @@
package audit
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"time"
"coopcloud.tech/abra/pkg/i18n"
"github.com/containers/image/docker"
"github.com/containers/image/manifest"
"github.com/containers/image/pkg/blobinfocache/none"
"github.com/containers/image/types"
"github.com/distribution/reference"
dockerClient "github.com/docker/docker/client"
"github.com/opencontainers/go-digest"
imgspecv1 "github.com/opencontainers/image-spec/specs-go/v1"
)
// OCI annotations and labels read by the audit.
const (
AnnotationVersion = "org.opencontainers.image.version"
AnnotationBaseName = "org.opencontainers.image.base.name"
AnnotationBaseDigest = "org.opencontainers.image.base.digest"
)
// ImageRef is one image as referenced in a service spec.
type ImageRef struct {
Service string `json:"service"`
// Ref is the reference as stored in the service spec, typically
// image:tag@sha256:...
Ref string `json:"ref"`
// Name is the familiar image name, e.g. "nextcloud" or "git.coopcloud.tech/coop-cloud/foo".
Name string `json:"name"`
Tag string `json:"tag"`
Digest string `json:"digest"`
Info *ImageInfo `json:"-"`
InfoErr error `json:"-"`
named reference.Named
}
// ImageInfo holds what the image says about itself.
type ImageInfo struct {
// Digest is the manifest (index) digest, set when read from a registry.
Digest string
Created *time.Time
Env map[string]string
Labels map[string]string
Annotations map[string]string
// BaseCreated is the build time of the base image named in the
// base.digest annotation, if it could be read.
BaseCreated *time.Time
// Source is "node" or "registry".
Source string
// createdUnusable is set when the build time cannot be trusted.
createdUnusable string
}
// ParseImageRef parses an image reference from a service spec.
func ParseImageRef(service, ref string) (ImageRef, error) {
img := ImageRef{Service: service, Ref: ref}
named, err := reference.ParseNormalizedNamed(ref)
if err != nil {
return img, err
}
img.named = named
img.Name = reference.FamiliarName(named)
if t, ok := named.(reference.Tagged); ok {
img.Tag = t.Tag()
}
if d, ok := named.(reference.Digested); ok {
img.Digest = d.Digest().String()
}
return img, nil
}
// NameTag returns "name:tag", the string matched against advisory patterns.
func (i ImageRef) NameTag() string {
if i.Tag == "" {
return i.Name
}
return i.Name + ":" + i.Tag
}
// Version returns the image's version from its label or annotation.
func (i *ImageInfo) Version() string {
if v := i.Labels[AnnotationVersion]; v != "" {
return v
}
return i.Annotations[AnnotationVersion]
}
// InspectOnNode reads the image config from the docker daemon of the server.
// This needs no registry, and works on single-node servers where the running
// image is always present.
func InspectOnNode(ctx context.Context, cl *dockerClient.Client, img ImageRef) (*ImageInfo, error) {
ref := img.Ref
if img.Digest != "" && img.named != nil {
ref = fmt.Sprintf("%s@%s", reference.TrimNamed(img.named).String(), img.Digest)
}
resp, err := cl.ImageInspect(ctx, ref)
if err != nil {
return nil, err
}
info := &ImageInfo{Source: "node", Env: map[string]string{}, Labels: map[string]string{}}
if resp.Created != "" {
if t, err := time.Parse(time.RFC3339Nano, resp.Created); err == nil {
info.Created = &t
}
}
if resp.Config != nil {
info.Env = parseEnv(resp.Config.Env)
if resp.Config.Labels != nil {
info.Labels = resp.Config.Labels
}
}
return info, nil
}
// manifestDoc covers the fields needed from image indexes, Docker manifest
// lists and image manifests.
type manifestDoc struct {
MediaType string `json:"mediaType"`
Annotations map[string]string `json:"annotations"`
Config *struct {
Digest string `json:"digest"`
MediaType string `json:"mediaType"`
Size int64 `json:"size"`
} `json:"config"`
Manifests []struct {
Digest string `json:"digest"`
Annotations map[string]string `json:"annotations"`
Platform *struct {
Architecture string `json:"architecture"`
OS string `json:"os"`
Variant string `json:"variant"`
} `json:"platform"`
} `json:"manifests"`
}
// FetchFromRegistry reads the image config for the given platform from the
// registry. Only a few KB are transferred; no layers are pulled. When the
// image records its base in the base.digest annotation, the base image's
// build time is read as well.
func FetchFromRegistry(ctx context.Context, img ImageRef, os, arch string) (*ImageInfo, error) {
info, err := fetchConfig(ctx, img, os, arch)
if err != nil {
return nil, err
}
baseName := info.Annotations[AnnotationBaseName]
baseDigest := info.Annotations[AnnotationBaseDigest]
if baseName != "" && baseDigest != "" {
if base, err := ParseImageRef("", fmt.Sprintf("%s@%s", stripTagDigest(baseName), baseDigest)); err == nil {
if bi, err := fetchConfig(ctx, base, os, arch); err == nil {
info.BaseCreated = bi.Created
}
}
}
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 {
return name
}
return reference.TrimNamed(named).String()
}
func fetchConfig(ctx context.Context, img ImageRef, os, arch string) (*ImageInfo, error) {
if img.named == nil {
return nil, errors.New(i18n.G("invalid image reference %s", img.Ref))
}
// NOTE: containers/image refuses references with both tag and digest
refStr := reference.TrimNamed(img.named).String()
if img.Digest != "" {
refStr += "@" + img.Digest
} else if img.Tag != "" {
refStr += ":" + img.Tag
}
ref, err := docker.ParseReference("//" + refStr)
if err != nil {
return nil, err
}
src, err := ref.NewImageSource(ctx, &types.SystemContext{})
if err != nil {
return nil, err
}
defer src.Close()
raw, _, err := src.GetManifest(ctx, nil)
if err != nil {
return nil, err
}
topDigest, err := manifest.Digest(raw)
if err != nil {
return nil, err
}
var doc manifestDoc
if err := json.Unmarshal(raw, &doc); err != nil {
return nil, err
}
annotations := map[string]string{}
for k, v := range doc.Annotations {
annotations[k] = v
}
if len(doc.Manifests) > 0 {
var chosen string
for _, m := range doc.Manifests {
if m.Platform != nil && m.Platform.OS == os && m.Platform.Architecture == arch {
chosen = m.Digest
for k, v := range m.Annotations {
annotations[k] = v
}
break
}
}
if chosen == "" {
return nil, errors.New(i18n.G("%s has no image for %s/%s", img.Ref, os, arch))
}
d := digest.Digest(chosen)
raw, _, err = src.GetManifest(ctx, &d)
if err != nil {
return nil, err
}
doc = manifestDoc{}
if err := json.Unmarshal(raw, &doc); err != nil {
return nil, err
}
for k, v := range doc.Annotations {
annotations[k] = v
}
}
if doc.Config == nil || doc.Config.Digest == "" {
return nil, errors.New(i18n.G("%s: unsupported manifest type %s", img.Ref, doc.MediaType))
}
blob, _, err := src.GetBlob(ctx, types.BlobInfo{Digest: digest.Digest(doc.Config.Digest), Size: doc.Config.Size}, none.NoCache)
if err != nil {
return nil, err
}
defer blob.Close()
cfgBytes, err := io.ReadAll(io.LimitReader(blob, 4<<20))
if err != nil {
return nil, err
}
var cfg imgspecv1.Image
if err := json.Unmarshal(cfgBytes, &cfg); err != nil {
return nil, err
}
info := &ImageInfo{
Source: "registry",
Digest: topDigest.String(),
Created: cfg.Created,
Env: parseEnv(cfg.Config.Env),
Labels: cfg.Config.Labels,
Annotations: annotations,
}
if info.Labels == nil {
info.Labels = map[string]string{}
}
return info, nil
}
func parseEnv(env []string) map[string]string {
out := make(map[string]string, len(env))
for _, e := range env {
k, v, _ := strings.Cut(e, "=")
out[k] = v
}
return out
}
// NormaliseArch maps the architecture names reported by the docker daemon
// (uname -m style) to OCI platform names.
func NormaliseArch(arch string) string {
switch arch {
case "x86_64", "amd64":
return "amd64"
case "aarch64", "arm64":
return "arm64"
case "armv7l", "armv7", "armhf", "arm":
return "arm"
case "i386", "i686", "386":
return "386"
}
return arch
}
-256
View File
@@ -1,256 +0,0 @@
package audit
import (
"errors"
"path"
"regexp"
"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"
"gopkg.in/yaml.v3"
)
const canonicalRecipePrefix = "git.coopcloud.tech/coop-cloud/"
// ShortRecipeName returns the shortest unambiguous form of a recipe name,
// relative to the canonical git.coopcloud.tech/coop-cloud/ location:
//
// nextcloud -> nextcloud
// git.coopcloud.tech/coop-cloud/nextcloud -> nextcloud
// git.coopcloud.tech/c4dt/nextcloud -> c4dt/nextcloud
// github.com/foo/nextcloud -> github.com/foo/nextcloud
func ShortRecipeName(name string) string {
name = strings.TrimPrefix(name, "https://")
name = strings.TrimSuffix(name, ".git")
if strings.HasPrefix(name, canonicalRecipePrefix) {
return strings.TrimPrefix(name, canonicalRecipePrefix)
}
if strings.HasPrefix(name, "git.coopcloud.tech/") {
return strings.TrimPrefix(name, "git.coopcloud.tech/")
}
return name
}
// RecipeSource lists the released versions of a recipe and the images each
// version uses.
type RecipeSource interface {
Versions(recipeName string) ([]string, error)
Images(recipeName, version string) ([]string, error)
}
// GitRecipes reads recipe versions from the local recipe checkouts. It never
// changes the working tree: tags are fetched into the repository, and compose
// files are read from the tag's tree.
type GitRecipes struct {
Offline bool
recipes map[string]recipe.Recipe
repos map[string]*git.Repository
errs map[string]error
}
// NewGitRecipes prepares access to the recipes of the given recipes.
func NewGitRecipes(recipes []recipe.Recipe, offline bool) *GitRecipes {
g := &GitRecipes{
Offline: offline,
recipes: make(map[string]recipe.Recipe),
repos: make(map[string]*git.Repository),
errs: make(map[string]error),
}
for _, r := range recipes {
g.recipes[r.Name] = r
}
return g
}
func (g *GitRecipes) open(name string) (*git.Repository, error) {
if repo, ok := g.repos[name]; ok {
return repo, nil
}
if err, ok := g.errs[name]; ok {
return nil, err
}
repo, err := g.openUncached(name)
if err != nil {
g.errs[name] = err
return nil, err
}
g.repos[name] = repo
return repo, nil
}
func (g *GitRecipes) openUncached(name string) (*git.Repository, error) {
r, ok := g.recipes[name]
if !ok {
return nil, errors.New(i18n.G("unknown recipe %s", name))
}
repo, err := git.PlainOpen(r.Dir)
if err != nil {
if g.Offline {
return nil, err
}
if err := r.EnsureExists(); err != nil {
return nil, err
}
if repo, err = git.PlainOpen(r.Dir); err != nil {
return nil, err
}
}
if !g.Offline {
err := repo.Fetch(&git.FetchOptions{RemoteName: "origin", Tags: git.AllTags})
if err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
log.Debug(i18n.G("%s: unable to fetch tags, using local tags: %s", name, err))
}
}
return repo, nil
}
// Versions returns the parseable release tags, oldest first.
func (g *GitRecipes) Versions(name string) ([]string, error) {
repo, err := g.open(name)
if err != nil {
return nil, err
}
iter, err := repo.Tags()
if err != nil {
return nil, err
}
var tags []string
_ = iter.ForEach(func(ref *plumbing.Reference) error {
tag := ref.Name().Short()
if _, err := ParseVersion(tag); err == nil {
tags = append(tags, tag)
}
return nil
})
sortVersions(tags)
return tags, nil
}
// Images returns the images used by a recipe version, read from the
// compose.yml and compose.*.yml files of that tag.
func (g *GitRecipes) Images(name, version string) ([]string, error) {
repo, err := g.open(name)
if err != nil {
return nil, err
}
hash, err := repo.ResolveRevision(plumbing.Revision("refs/tags/" + version))
if err != nil {
return nil, err
}
commit, err := repo.CommitObject(*hash)
if err != nil {
return nil, err
}
tree, err := commit.Tree()
if err != nil {
return nil, err
}
var images []string
err = tree.Files().ForEach(func(f *object.File) error {
if strings.Contains(f.Name, "/") {
return nil
}
if ok, _ := path.Match("compose*yml", f.Name); !ok {
return nil
}
content, err := f.Contents()
if err != nil {
return err
}
for _, img := range composeImages(content) {
if !containsString(images, img) {
images = append(images, img)
}
}
return nil
})
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
// a default (${FOO:-bar}) are replaced by the default; images with other
// variables are skipped.
func composeImages(content string) []string {
var doc struct {
Services map[string]struct {
Image string `yaml:"image"`
} `yaml:"services"`
}
if err := yaml.Unmarshal([]byte(content), &doc); err != nil {
return nil
}
var images []string
for _, svc := range doc.Services {
img := envDefault.ReplaceAllString(svc.Image, "$1")
if img == "" || strings.Contains(img, "$") {
continue
}
images = append(images, img)
}
sort.Strings(images)
return images
}
func sortVersions(tags []string) {
sort.SliceStable(tags, func(i, j int) bool {
a, _ := ParseVersion(tags[i])
b, _ := ParseVersion(tags[j])
return a.Compare(b) < 0
})
}
func containsString(list []string, s string) bool {
for _, l := range list {
if l == s {
return true
}
}
return false
}
-33
View File
@@ -1,33 +0,0 @@
package audit
import (
"context"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestFetchFromRegistry talks to Docker Hub, so it only runs with
// ABRA_TEST_NETWORK=1.
func TestFetchFromRegistry(t *testing.T) {
if os.Getenv("ABRA_TEST_NETWORK") != "1" {
t.Skip("set ABRA_TEST_NETWORK=1 to run")
}
for _, arch := range []string{"amd64", "arm64"} {
img, err := ParseImageRef("app", "nextcloud:apache")
require.NoError(t, err)
info, err := FetchFromRegistry(context.Background(), img, "linux", arch)
require.NoError(t, err)
assert.NotEmpty(t, info.Env["PHP_VERSION"], arch)
assert.NotEmpty(t, info.Env["NEXTCLOUD_VERSION"], arch)
require.NotNil(t, info.Created, arch)
t.Logf("%s: created=%s php=%s nextcloud=%s base=%s baseCreated=%v",
arch, info.Created, info.Env["PHP_VERSION"], info.Env["NEXTCLOUD_VERSION"],
info.Annotations[AnnotationBaseName], info.BaseCreated)
}
}
-114
View File
@@ -1,114 +0,0 @@
package audit
import (
"errors"
"os"
"path/filepath"
"time"
gitPkg "coopcloud.tech/abra/pkg/git"
"coopcloud.tech/abra/pkg/i18n"
"coopcloud.tech/abra/pkg/log"
"github.com/go-git/go-git/v5"
)
// DefaultAdvisoriesURL is the git repository holding the reviewed advisories.
const DefaultAdvisoriesURL = "https://git.coopcloud.tech/c4dt/advisories.git"
// fetchMarker is touched after each successful fetch, so the age of the local
// copy can be reported when the remote cannot be reached.
const fetchMarker = "abra-audit-last-fetch"
// SyncAdvisories makes sure dir holds an up-to-date checkout of the
// advisories repository. There is no cache lifetime: every call checks the
// remote. When the remote cannot be reached, a warning with the age of the
// local copy is logged and the local copy is used.
//
// A directory that is not a git checkout is used as is, which is handy for
// testing advisories locally.
func SyncAdvisories(dir, url string, offline bool) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
if offline {
return errors.New(i18n.G("no local advisories in %s and offline mode is on", dir))
}
log.Info(i18n.G("fetching advisories from %s", url))
if err := gitPkg.Clone(dir, url); err != nil {
_ = os.RemoveAll(dir)
return errors.New(i18n.G("unable to fetch advisories from %s: %s", url, err))
}
if _, err := git.PlainOpen(dir); err != nil {
_ = os.RemoveAll(dir)
return errors.New(i18n.G("unable to fetch advisories from %s: %s", url, err))
}
touchMarker(dir)
return nil
}
repo, err := git.PlainOpen(dir)
if err != nil {
log.Warn(i18n.G("%s is not a git checkout, using it as is", dir))
return nil
}
if offline {
log.Info(i18n.G("offline mode: using local advisories (%s)", localAge(dir, repo)))
return nil
}
wt, err := repo.Worktree()
if err != nil {
return err
}
err = wt.Pull(&git.PullOptions{RemoteName: "origin"})
if err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
log.Warn(i18n.G("unable to update advisories: %s", err))
log.Warn(i18n.G("using local advisories (%s)", localAge(dir, repo)))
return nil
}
if err == nil {
log.Debug(i18n.G("advisories updated"))
} else {
log.Debug(i18n.G("advisories already up to date"))
}
touchMarker(dir)
return nil
}
func touchMarker(dir string) {
p := filepath.Join(dir, ".git", fetchMarker)
now := time.Now()
if err := os.WriteFile(p, []byte(now.UTC().Format(time.RFC3339)+"\n"), 0o644); err != nil {
log.Debug(i18n.G("unable to write %s: %s", p, err))
}
}
// localAge describes how old the local copy is: the time of the last
// successful fetch, or of the last commit if abra never fetched it.
func localAge(dir string, repo *git.Repository) string {
if st, err := os.Stat(filepath.Join(dir, ".git", fetchMarker)); err == nil {
return i18n.G("last fetched %s ago", humanAge(time.Since(st.ModTime())))
}
if head, err := repo.Head(); err == nil {
if c, err := repo.CommitObject(head.Hash()); err == nil {
return i18n.G("last commit %s ago", humanAge(time.Since(c.Committer.When)))
}
}
return i18n.G("age unknown")
}
func humanAge(d time.Duration) string {
switch {
case d < time.Hour:
return i18n.G("%d minutes", int(d.Minutes()))
case d < 48*time.Hour:
return i18n.G("%d hours", int(d.Hours()))
default:
return i18n.G("%d days", int(d.Hours()/24))
}
}
-59
View File
@@ -1,59 +0,0 @@
package audit
import (
"os"
"path/filepath"
"testing"
"time"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func commitFile(t *testing.T, repo *git.Repository, dir, name, content string) {
t.Helper()
require.NoError(t, os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644))
wt, err := repo.Worktree()
require.NoError(t, err)
_, err = wt.Add(name)
require.NoError(t, err)
_, err = wt.Commit("add "+name, &git.CommitOptions{
Author: &object.Signature{Name: "test", Email: "test@example.com", When: time.Now()},
})
require.NoError(t, err)
}
func TestSyncAdvisories(t *testing.T) {
upstream := t.TempDir()
repo, err := git.PlainInit(upstream, false)
require.NoError(t, err)
commitFile(t, repo, upstream, "advisories/a.yml", "id: A\nrecipes: {x: {fixed: 1.0.0}}\n")
local := filepath.Join(t.TempDir(), "advisories")
// offline without a local copy fails
require.Error(t, SyncAdvisories(local, upstream, true))
// first run clones
require.NoError(t, SyncAdvisories(local, upstream, false))
assert.FileExists(t, filepath.Join(local, "advisories", "a.yml"))
assert.FileExists(t, filepath.Join(local, ".git", fetchMarker))
// next run pulls new advisories
commitFile(t, repo, upstream, "advisories/b.yml", "id: B\nrecipes: {x: {fixed: 1.0.0}}\n")
require.NoError(t, SyncAdvisories(local, upstream, false))
assert.FileExists(t, filepath.Join(local, "advisories", "b.yml"))
// already up to date
require.NoError(t, SyncAdvisories(local, upstream, false))
// unreachable remote: warn and use the local copy
require.NoError(t, os.RemoveAll(upstream))
require.NoError(t, SyncAdvisories(local, upstream, false))
advs, _, err := LoadAdvisories(filepath.Join(local, "advisories"))
require.NoError(t, err)
assert.Len(t, advs, 2)
}
-273
View File
@@ -1,273 +0,0 @@
package audit
import (
"context"
"fmt"
"sort"
"sync"
"time"
appPkg "coopcloud.tech/abra/pkg/app"
"coopcloud.tech/abra/pkg/client"
"coopcloud.tech/abra/pkg/i18n"
"coopcloud.tech/abra/pkg/log"
"coopcloud.tech/abra/pkg/upstream/convert"
"coopcloud.tech/abra/pkg/upstream/stack"
dockerClient "github.com/docker/docker/client"
)
// 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 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.
OS string `json:"-"`
Arch string `json:"-"`
}
// ServerError records a server that could not be audited.
type ServerError struct {
Server string
Err error
}
// CollectOptions configures CollectState.
type CollectOptions struct {
// Offline disables registry lookups; image configs are then only read
// from the server's docker daemon.
Offline bool
}
// CollectState reads the deployed state of all given apps. Servers are
// queried in parallel. Apps that are not deployed are left out. A server that
// cannot be reached is returned as a ServerError, and the other servers are
// still audited.
func CollectState(apps []appPkg.App, opts CollectOptions) ([]AppState, []ServerError) {
byServer := make(map[string][]appPkg.App)
for _, app := range apps {
byServer[app.Server] = append(byServer[app.Server], app)
}
var (
mu sync.Mutex
wg sync.WaitGroup
states []AppState
errs []ServerError
)
for server, serverApps := range byServer {
wg.Add(1)
go func(server string, serverApps []appPkg.App) {
defer wg.Done()
s, err := collectServer(server, serverApps, opts)
mu.Lock()
defer mu.Unlock()
if err != nil {
errs = append(errs, ServerError{Server: server, Err: err})
return
}
states = append(states, s...)
}(server, serverApps)
}
wg.Wait()
sort.Slice(states, func(i, j int) bool {
if states[i].Server != states[j].Server {
return states[i].Server < states[j].Server
}
return states[i].Name < states[j].Name
})
sort.Slice(errs, func(i, j int) bool { return errs[i].Server < errs[j].Server })
markUnusableCreated(states)
return states, errs
}
func collectServer(server string, apps []appPkg.App, opts CollectOptions) ([]AppState, error) {
cl, err := client.New(server, client.WithTimeout(10))
if err != nil {
return nil, err
}
status := stack.GetAllDeployedServices(cl, server)
if status.Err != nil {
return nil, status.Err
}
ctx := context.Background()
var platformOS, platformArch string
if !opts.Offline {
if info, err := cl.Info(ctx); err == nil {
platformOS = info.OSType
platformArch = NormaliseArch(info.Architecture)
} else {
log.Debug(i18n.G("%s: unable to read platform: %s", server, err))
}
}
byStack := make(map[string]*AppState)
var order []string
for _, app := range apps {
byStack[app.StackName()] = &AppState{
Server: server,
Name: app.Name,
Recipe: app.Recipe.Name,
OS: platformOS,
Arch: platformArch,
}
}
deployed := make(map[string]bool)
cache := make(map[string]imageResult)
for _, svc := range status.Services {
stackName := svc.Spec.Labels[convert.LabelNamespace]
st, ok := byStack[stackName]
if !ok {
continue
}
if !deployed[stackName] {
deployed[stackName] = true
order = append(order, stackName)
}
if v, ok := svc.Spec.Labels[fmt.Sprintf("coop-cloud.%s.version", stackName)]; ok && v != "" {
st.Version = v
}
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
}
ref := svc.Spec.TaskTemplate.ContainerSpec.Image
serviceName := svc.Spec.Name
if ns := stackName + "_"; len(serviceName) > len(ns) && serviceName[:len(ns)] == ns {
serviceName = serviceName[len(ns):]
}
img, err := ParseImageRef(serviceName, ref)
if err != nil {
img.InfoErr = err
st.Images = append(st.Images, img)
continue
}
res, ok := cache[ref]
if !ok {
res = inspectImage(ctx, cl, img, platformOS, platformArch, opts)
cache[ref] = res
}
img.Info, img.InfoErr = res.info, res.err
st.Images = append(st.Images, img)
}
var states []AppState
for _, stackName := range order {
st := byStack[stackName]
sort.Slice(st.Images, func(i, j int) bool { return st.Images[i].Service < st.Images[j].Service })
states = append(states, *st)
}
return states, nil
}
type imageResult struct {
info *ImageInfo
err error
}
func inspectImage(ctx context.Context, cl *dockerClient.Client, img ImageRef, platformOS, platformArch string, opts CollectOptions) imageResult {
nodeCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
info, nodeErr := InspectOnNode(nodeCtx, cl, img)
if nodeErr == nil {
return imageResult{info: info}
}
log.Debug(i18n.G("%s: not found on node: %s", img.Ref, nodeErr))
if opts.Offline || platformArch == "" {
return imageResult{err: nodeErr}
}
regCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
info, err := FetchFromRegistry(regCtx, img, platformOS, platformArch)
if err != nil {
return imageResult{err: fmt.Errorf("%s", i18n.G("node: %s; registry: %s", nodeErr, err))}
}
return imageResult{info: info}
}
// markUnusableCreated flags build times that cannot be trusted:
// - before 2000, which catches reproducible builds using the 1970 epoch;
// - earlier than the build time of the base image;
// - shared by two different digests of the same tag.
func markUnusableCreated(states []AppState) {
// tag -> created -> digests
seen := make(map[string]map[time.Time]map[string]bool)
for _, st := range states {
for _, img := range st.Images {
if img.Info == nil || img.Info.Created == nil || img.Digest == "" {
continue
}
c := img.Info.Created.UTC()
if seen[img.NameTag()] == nil {
seen[img.NameTag()] = make(map[time.Time]map[string]bool)
}
if seen[img.NameTag()][c] == nil {
seen[img.NameTag()][c] = make(map[string]bool)
}
seen[img.NameTag()][c][img.Digest] = true
}
}
for _, st := range states {
for _, img := range st.Images {
info := img.Info
if info == nil || info.Created == nil {
continue
}
c := info.Created.UTC()
switch {
case createdUnusable(info) != "":
info.createdUnusable = createdUnusable(info)
case len(seen[img.NameTag()][c]) > 1:
info.createdUnusable = i18n.G("several digests of %s share the build time %s", img.NameTag(), c.Format(time.RFC3339))
}
}
}
}
// createdUnusable runs the checks that need only the image itself: a build
// time before 2000, or earlier than the base image's.
func createdUnusable(info *ImageInfo) string {
if info.Created == nil {
return ""
}
c := info.Created.UTC()
switch {
case c.Before(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)):
return i18n.G("build time %s is before 2000 (reproducible build?)", c.Format(time.RFC3339))
case info.BaseCreated != nil && c.Before(*info.BaseCreated):
return i18n.G("build time %s is earlier than its base image", c.Format(time.RFC3339))
}
return ""
}
-290
View File
@@ -1,290 +0,0 @@
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
}
-206
View File
@@ -1,206 +0,0 @@
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)
}
-169
View File
@@ -1,169 +0,0 @@
package audit
import (
"errors"
"regexp"
"strconv"
"strings"
"coopcloud.tech/abra/pkg/i18n"
)
// Version is a loosely parsed version. Recipe tags have the form
// RECIPE+UPSTREAM (e.g. 7.0.3+30.0.1), so a version is a list of groups
// separated by "+", each group a list of numbers. Anything after the leading
// numeric part of a group (e.g. "-apache" in "35.0.3-apache") is ignored.
type Version struct {
Raw string
Groups [][]int
}
var numericPrefix = regexp.MustCompile(`^[vV]?(\d+(?:\.\d+)*)`)
// ParseVersion parses a version such as "8.3.14", "v1.2", "35.0.3-apache" or
// "7.0.3+30.0.1".
func ParseVersion(raw string) (Version, error) {
v := Version{Raw: raw}
raw = strings.TrimSpace(raw)
if raw == "" {
return v, errors.New(i18n.G("empty version"))
}
for _, group := range strings.Split(raw, "+") {
m := numericPrefix.FindStringSubmatch(group)
if m == nil {
return v, errors.New(i18n.G("unable to parse version %s", raw))
}
var nums []int
for _, part := range strings.Split(m[1], ".") {
n, err := strconv.Atoi(part)
if err != nil {
return v, errors.New(i18n.G("unable to parse version %s", raw))
}
nums = append(nums, n)
}
v.Groups = append(v.Groups, nums)
}
return v, nil
}
// Compare returns -1, 0 or 1. Only the groups present in both versions are
// compared, so "7.0.3" equals "7.0.3+30.0.1": a constraint without an
// upstream part only constrains the recipe part. Missing numbers inside a
// group count as 0.
func (v Version) Compare(o Version) int {
groups := min(len(v.Groups), len(o.Groups))
for g := 0; g < groups; g++ {
a, b := v.Groups[g], o.Groups[g]
for i := 0; i < max(len(a), len(b)); i++ {
var x, y int
if i < len(a) {
x = a[i]
}
if i < len(b) {
y = b[i]
}
if x < y {
return -1
}
if x > y {
return 1
}
}
}
return 0
}
type constraint struct {
op string
version Version
}
// Range is a set of version constraints. Constraints separated by spaces or
// commas must all hold; alternatives are separated by "||". For example
// ">=8.3.0 <8.3.14 || >=8.4.0 <8.4.2".
type Range struct {
Raw string
alts [][]constraint
}
var constraintRe = regexp.MustCompile(`^(<=|>=|==|!=|<|>|=)?\s*(.+)$`)
// ParseRange parses a version range.
func ParseRange(raw string) (Range, error) {
r := Range{Raw: raw}
if strings.TrimSpace(raw) == "" {
return r, errors.New(i18n.G("empty version range"))
}
for _, alt := range strings.Split(raw, "||") {
// NOTE: allow "< 1.2" by gluing a lone operator to the next token
fields := strings.FieldsFunc(alt, func(r rune) bool { return r == ' ' || r == ',' || r == '\t' })
var tokens []string
for i := 0; i < len(fields); i++ {
if constraintRe.MatchString(fields[i]) && strings.Trim(fields[i], "<>=!") == "" && i+1 < len(fields) {
tokens = append(tokens, fields[i]+fields[i+1])
i++
continue
}
tokens = append(tokens, fields[i])
}
if len(tokens) == 0 {
return r, errors.New(i18n.G("empty alternative in version range %s", raw))
}
var cs []constraint
for _, tok := range tokens {
m := constraintRe.FindStringSubmatch(tok)
if m == nil {
return r, errors.New(i18n.G("unable to parse version range %s", raw))
}
op := m[1]
if op == "" || op == "==" {
op = "="
}
v, err := ParseVersion(m[2])
if err != nil {
return r, errors.New(i18n.G("unable to parse version range %s: %s", raw, err))
}
cs = append(cs, constraint{op: op, version: v})
}
r.alts = append(r.alts, cs)
}
return r, nil
}
// Contains reports whether the version satisfies the range.
func (r Range) Contains(v Version) bool {
for _, alt := range r.alts {
ok := true
for _, c := range alt {
cmp := v.Compare(c.version)
switch c.op {
case "<":
ok = cmp < 0
case "<=":
ok = cmp <= 0
case ">":
ok = cmp > 0
case ">=":
ok = cmp >= 0
case "=":
ok = cmp == 0
case "!=":
ok = cmp != 0
}
if !ok {
break
}
}
if ok {
return true
}
}
return false
}
+1 -52
View File
@@ -4,35 +4,18 @@ import (
"context"
"errors"
"fmt"
"slices"
"coopcloud.tech/abra/pkg/i18n"
"github.com/containers/image/docker"
"github.com/containers/image/manifest"
"github.com/containers/image/types"
"github.com/distribution/reference"
imgspecv1 "github.com/opencontainers/image-spec/specs-go/v1"
)
func init() {
// NOTE: containers/image does not request OCI image indexes by default.
// Many multi-arch images (e.g. on Docker Hub) are published as OCI indexes
// and the registry refuses to serve them without the matching Accept header.
if !slices.Contains(manifest.DefaultRequestedManifestMIMETypes, imgspecv1.MediaTypeImageIndex) {
manifest.DefaultRequestedManifestMIMETypes = append(
manifest.DefaultRequestedManifestMIMETypes,
imgspecv1.MediaTypeImageIndex,
)
}
}
// GetRegistryTags retrieves all tags of an image from a container registry.
func GetRegistryTags(img reference.Named) ([]string, error) {
var tags []string
// NOTE: strip tag and digest, containers/image refuses references
// which have both (e.g. nextcloud:34.0.5-fpm@sha256:...)
ref, err := docker.ParseReference(fmt.Sprintf("//%s", reference.TrimNamed(img)))
ref, err := docker.ParseReference(fmt.Sprintf("//%s", img))
if err != nil {
return tags, errors.New(i18n.G("failed to parse image %s, saw: %s", img, err.Error()))
}
@@ -45,37 +28,3 @@ func GetRegistryTags(img reference.Named) ([]string, error) {
return tags, nil
}
// GetRegistryDigest retrieves the manifest digest of an image tag from a
// container registry. For multi-arch images, this is the digest of the image
// index, which is what Docker resolves "image:tag" to.
func GetRegistryDigest(img reference.Named, tag string) (string, error) {
tagged, err := reference.WithTag(reference.TrimNamed(img), tag)
if err != nil {
return "", errors.New(i18n.G("failed to parse image %s, saw: %s", img, err.Error()))
}
ref, err := docker.ParseReference(fmt.Sprintf("//%s", tagged))
if err != nil {
return "", errors.New(i18n.G("failed to parse image %s, saw: %s", tagged, err.Error()))
}
ctx := context.Background()
src, err := ref.NewImageSource(ctx, &types.SystemContext{})
if err != nil {
return "", err
}
defer src.Close()
manifestBytes, _, err := src.GetManifest(ctx, nil)
if err != nil {
return "", err
}
digest, err := manifest.Digest(manifestBytes)
if err != nil {
return "", err
}
return digest.String(), nil
}
+2 -13
View File
@@ -73,17 +73,6 @@ type Abra struct {
// 2. check if abraDir was set in a config file
// 3. use $HOME/.abra when above two options failed
func (a Abra) GetAbraDir() string {
if dir := a.GetExplicitAbraDir(); dir != "" {
return dir
}
log.Debug(i18n.G("using default abra dir"))
return os.ExpandEnv("$HOME/.abra")
}
// GetExplicitAbraDir returns the abra dir only when it was explicitly chosen,
// either through $ABRA_DIR or through the abraDir setting of a config file.
// It returns an empty string otherwise, and never falls back to $HOME/.abra.
func (a Abra) GetExplicitAbraDir() string {
if dir, exists := os.LookupEnv("ABRA_DIR"); exists && dir != "" {
log.Debug(i18n.G("read abra dir from $ABRA_DIR"))
return dir
@@ -96,7 +85,8 @@ func (a Abra) GetExplicitAbraDir() string {
// Make the path absolute
return path.Join(a.configPath, a.AbraDir)
}
return ""
log.Debug(i18n.G("using default abra dir"))
return os.ExpandEnv("$HOME/.abra")
}
func (a Abra) GetServersDir() string { return path.Join(a.GetAbraDir(), "servers") }
@@ -108,7 +98,6 @@ var config = LoadAbraConfig()
var (
ABRA_DIR = config.GetAbraDir()
ABRA_DIR_EXPLICIT = config.GetExplicitAbraDir()
SERVERS_DIR = config.GetServersDir()
RECIPES_DIR = config.GetRecipesDir()
LOGS_DIR = config.GetLogsDir()
+8 -18
View File
@@ -26,24 +26,12 @@ var BoldUnderlineStyle = lipgloss.NewStyle().
Bold(true).
Underline(true)
// ShortenID returns the first 12 characters of an ID, or the whole ID if it
// is shorter.
func ShortenID(str string) string {
return Truncate(str, 12)
return str[:12]
}
// SmallSHA returns the first 8 characters of a hash, or the whole hash if it
// is shorter (e.g. the placeholder commit of a build without ldflags).
func SmallSHA(hash string) string {
return Truncate(hash, 8)
}
// Truncate returns the first n characters of str, or str if it is shorter.
func Truncate(str string, n int) string {
if len(str) <= n {
return str
}
return str[:n]
return hash[:8]
}
// RemoveSha remove image sha from a string that are added in some docker outputs
@@ -96,10 +84,12 @@ func PrintTable(t *table.Table) error {
tWidth, _ := lipgloss.Size(t.String())
// 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 {
width, _, err := term.GetSize(0)
if err != nil {
return err
}
if tWidth > width {
t.Width(width - 10)
}
-50
View File
@@ -1,9 +1,6 @@
package formatter
import (
"io"
"os"
"strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -12,50 +9,3 @@ import (
func TestBoldDirtyDefault(t *testing.T) {
assert.Equal(t, "foo", BoldDirtyDefault("foo"))
}
func TestSmallSHA(t *testing.T) {
assert.Equal(t, "d699e51c", SmallSHA("d699e51c4c2a8f0e"))
assert.Equal(t, " ", SmallSHA(" "))
assert.Equal(t, "", SmallSHA(""))
}
func TestShortenID(t *testing.T) {
assert.Equal(t, "0123456789ab", ShortenID("0123456789abcdef"))
assert.Equal(t, "abc", ShortenID("abc"))
}
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)
}
}
+2
View File
@@ -52,6 +52,7 @@ func Clone(dir, url string) error {
URL: url,
Tags: git.AllTags,
ReferenceName: plumbing.ReferenceName("refs/heads/main"),
SingleBranch: true,
})
if err != nil && gitCloneIgnoreErr(err) {
@@ -70,6 +71,7 @@ func Clone(dir, url string) error {
URL: url,
Tags: git.AllTags,
ReferenceName: plumbing.ReferenceName("refs/heads/master"),
SingleBranch: true,
})
if err != nil && gitCloneIgnoreErr(err) {
-5
View File
@@ -36,11 +36,6 @@ func IsClean(repoPath string) (bool, error) {
return false, err
}
// Ignore the abra-managed sidecar file that records the canonical
// source URL for externally-cloned recipes; it lives alongside the
// recipe but is not part of the upstream tree.
patterns = append(patterns, gitignore.ParsePattern(".abra-source", nil))
if len(patterns) > 0 {
worktree.Excludes = append(patterns, worktree.Excludes...)
}
-36
View File
@@ -2,8 +2,6 @@ package git
import (
"errors"
"os"
"path/filepath"
"testing"
"github.com/go-git/go-git/v5"
@@ -15,37 +13,3 @@ func TestIsClean(t *testing.T) {
assert.Equal(t, isClean, false)
assert.True(t, errors.Is(err, git.ErrRepositoryNotExists))
}
// TestIsCleanIgnoresAbraSource confirms that the .abra-source sidecar
// file written by abra next to externally-cloned recipes does not cause
// IsClean to report the worktree as dirty.
func TestIsCleanIgnoresAbraSource(t *testing.T) {
dir := t.TempDir()
if _, err := git.PlainInit(dir, false); err != nil {
t.Fatalf("git init failed: %s", err)
}
sidecar := filepath.Join(dir, ".abra-source")
if err := os.WriteFile(sidecar, []byte("git.example.com/u/recipe\n"), 0o644); err != nil {
t.Fatalf("writing sidecar failed: %s", err)
}
isClean, err := IsClean(dir)
if err != nil {
t.Fatalf("IsClean returned error: %s", err)
}
assert.True(t, isClean, "expected worktree with only .abra-source to be reported clean")
// Sanity check: an unrelated untracked file should still mark it dirty.
other := filepath.Join(dir, "random.txt")
if err := os.WriteFile(other, []byte("hello"), 0o644); err != nil {
t.Fatalf("writing extra file failed: %s", err)
}
isClean, err = IsClean(dir)
if err != nil {
t.Fatalf("IsClean returned error: %s", err)
}
assert.False(t, isClean, "expected worktree with unrelated untracked file to be reported dirty")
}
+180 -205
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
+774 -283
View File
File diff suppressed because one or more lines are too long
+5 -49
View File
@@ -6,10 +6,8 @@ import (
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"coopcloud.tech/abra/pkg/client"
"coopcloud.tech/abra/pkg/formatter"
"coopcloud.tech/abra/pkg/i18n"
"coopcloud.tech/abra/pkg/log"
@@ -112,14 +110,7 @@ func (r Recipe) GetVersionLabelLocal() (string, error) {
return label, nil
}
// getRegistryDigest is a variable so that it can be stubbed in tests.
var getRegistryDigest = client.GetRegistryDigest
// UpdateTag updates an image tag in-place on file system local compose files.
// Images which are pinned to a digest (e.g. "nextcloud:34.0.5-fpm@sha256:...")
// have their digest updated to the one of the new tag, as retrieved from the
// container registry. Passing the current tag of a digest pinned image
// refreshes the digest, e.g. when upstream re-published the same tag.
func (r Recipe) UpdateTag(image, tag string) (bool, error) {
fullPattern := fmt.Sprintf("%s/compose**yml", r.Dir)
image = formatter.StripTagMeta(image)
@@ -131,11 +122,6 @@ func (r Recipe) UpdateTag(image, tag string) (bool, error) {
log.Debug(i18n.G("considering %s config(s) for tag update", strings.Join(composeFiles, ", ")))
var (
updated bool
newDigest string
)
for _, composeFile := range composeFiles {
opts := stack.Deploy{Composefiles: []string{composeFile}}
@@ -154,7 +140,7 @@ func (r Recipe) UpdateTag(image, tag string) (bool, error) {
continue // may be a compose.$optional.yml file
}
img, err := reference.ParseNormalizedNamed(service.Image)
img, _ := reference.ParseNormalizedNamed(service.Image)
if err != nil {
return false, err
}
@@ -168,60 +154,30 @@ func (r Recipe) UpdateTag(image, tag string) (bool, error) {
continue
}
var composeDigest string
if canonical, ok := img.(reference.Canonical); ok {
composeDigest = canonical.Digest().String()
}
composeImage := formatter.StripTagMeta(reference.Path(img))
log.Debug(i18n.G("parsed %s from %s", composeTag, service.Image))
if image == composeImage {
bytes, err := os.ReadFile(composeFile)
bytes, err := ioutil.ReadFile(composeFile)
if err != nil {
return false, err
}
old := fmt.Sprintf("%s:%s", composeImage, composeTag)
new := fmt.Sprintf("%s:%s", composeImage, tag)
if composeDigest != "" {
if newDigest == "" {
newDigest, err = getRegistryDigest(img, tag)
if err != nil {
return false, errors.New(i18n.G("unable to retrieve digest for %s: %s", new, err))
}
}
old = fmt.Sprintf("%s@%s", old, composeDigest)
new = fmt.Sprintf("%s@%s", new, newDigest)
}
if old == new {
continue
}
// NOTE: only match the full image reference, so that "foo:1.2" does
// not match "foo:1.2.3" or the "foo:1.2" part of "foo:1.2@sha256:..."
pattern := regexp.MustCompile(regexp.QuoteMeta(old) + `([^@\w.\-]|$)`)
replaced := pattern.ReplaceAllString(string(bytes), new+"${1}")
if replaced == string(bytes) {
continue
}
replacedBytes := strings.Replace(string(bytes), old, new, -1)
log.Debug(i18n.G("updating %s to %s in %s", old, new, compose.Filename))
if err := os.WriteFile(compose.Filename, []byte(replaced), 0o764); err != nil {
if err := os.WriteFile(compose.Filename, []byte(replacedBytes), 0o764); err != nil {
return false, err
}
updated = true
}
}
}
return updated, nil
return false, nil
}
// UpdateLabel updates a label in-place on file system local compose files.
-127
View File
@@ -1,127 +0,0 @@
package recipe
import (
"os"
"path"
"testing"
"github.com/distribution/reference"
"github.com/stretchr/testify/assert"
)
const (
oldDigest = "sha256:1111111111111111111111111111111111111111111111111111111111111111"
newDigest = "sha256:2222222222222222222222222222222222222222222222222222222222222222"
)
func setupUpdateTagRecipe(t *testing.T, compose string) (Recipe, string) {
t.Helper()
dir := t.TempDir()
composePath := path.Join(dir, "compose.yml")
envPath := path.Join(dir, ".env.sample")
assert.NoError(t, os.WriteFile(composePath, []byte(compose), 0o644))
assert.NoError(t, os.WriteFile(envPath, []byte("TYPE=foo\n"), 0o644))
return Recipe{
Name: "foo",
Dir: dir,
ComposePath: composePath,
SampleEnvPath: envPath,
}, composePath
}
func stubRegistryDigest(t *testing.T, digest string) *[]string {
t.Helper()
var calls []string
orig := getRegistryDigest
getRegistryDigest = func(img reference.Named, tag string) (string, error) {
calls = append(calls, reference.Path(img)+":"+tag)
return digest, nil
}
t.Cleanup(func() { getRegistryDigest = orig })
return &calls
}
func TestUpdateTag(t *testing.T) {
testcases := []struct {
name string
compose string
image string
tag string
expected string
updated bool
lookups int
}{
{
name: "plain tag",
compose: "version: \"3.8\"\nservices:\n app:\n image: nginx:1.31.7\n",
image: "nginx",
tag: "1.31.8",
expected: "version: \"3.8\"\nservices:\n app:\n image: nginx:1.31.8\n",
updated: true,
},
{
name: "shorter tag does not mangle longer tag",
compose: "version: \"3.8\"\nservices:\n app:\n image: nginx:1.31\n web:\n image: nginx:1.31.7\n",
image: "nginx",
tag: "1.32",
expected: "version: \"3.8\"\nservices:\n app:\n image: nginx:1.32\n web:\n image: nginx:1.32\n",
updated: true,
},
{
name: "digest is updated with tag",
compose: "version: \"3.8\"\nservices:\n app:\n image: nextcloud:34.0.5-fpm@" + oldDigest + "\n",
image: "nextcloud",
tag: "34.0.6-fpm",
expected: "version: \"3.8\"\nservices:\n app:\n image: nextcloud:34.0.6-fpm@" + newDigest + "\n",
updated: true,
lookups: 1,
},
{
name: "digest is refreshed for same tag",
compose: "version: \"3.8\"\nservices:\n app:\n image: \"nextcloud:34.0.5-fpm@" + oldDigest + "\"\n",
image: "nextcloud",
tag: "34.0.5-fpm",
expected: "version: \"3.8\"\nservices:\n app:\n image: \"nextcloud:34.0.5-fpm@" + newDigest + "\"\n",
updated: true,
lookups: 1,
},
{
name: "same tag without digest is a no-op",
compose: "version: \"3.8\"\nservices:\n app:\n image: nextcloud:34.0.5-fpm\n",
image: "nextcloud",
tag: "34.0.5-fpm",
expected: "version: \"3.8\"\nservices:\n app:\n image: nextcloud:34.0.5-fpm\n",
updated: false,
},
{
name: "pinned and unpinned services sharing an image",
compose: "version: \"3.8\"\nservices:\n app:\n image: nextcloud:34.0.5-fpm@" + oldDigest + "\n cron:\n image: nextcloud:34.0.5-fpm\n",
image: "nextcloud",
tag: "34.0.6-fpm",
expected: "version: \"3.8\"\nservices:\n app:\n image: nextcloud:34.0.6-fpm@" + newDigest + "\n cron:\n image: nextcloud:34.0.6-fpm\n",
updated: true,
lookups: 1,
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
r, composePath := setupUpdateTagRecipe(t, tc.compose)
calls := stubRegistryDigest(t, newDigest)
updated, err := r.UpdateTag(tc.image, tc.tag)
assert.NoError(t, err)
assert.Equal(t, tc.updated, updated)
assert.Len(t, *calls, tc.lookups)
content, err := os.ReadFile(composePath)
assert.NoError(t, err)
assert.Equal(t, tc.expected, string(content))
})
}
}
+11 -109
View File
@@ -4,7 +4,6 @@ import (
"errors"
"fmt"
"os"
"path"
"slices"
"sort"
"strings"
@@ -17,15 +16,9 @@ import (
"coopcloud.tech/tagcmp"
"github.com/distribution/reference"
"github.com/go-git/go-git/v5"
gitCfg "github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
)
// SourceFile is the sidecar file written next to an externally-cloned
// recipe so the canonical "host/path" name can be recovered later (the
// on-disk directory name escapes "/" and "." to "_", which is lossy).
const SourceFile = ".abra-source"
type EnsureContext struct {
Chaos bool
Offline bool
@@ -65,7 +58,7 @@ func (r Recipe) Ensure(ctx EnsureContext) error {
return errors.New(i18n.G(`cannot redeploy previous chaos version (%s), did you mean to use "--chaos"?`))
}
if _, err := r.EnsureVersionCtx(ctx, r.EnvVersion); err != nil {
if _, err := r.EnsureVersion(r.EnvVersion); err != nil {
return err
}
@@ -85,12 +78,6 @@ func (r Recipe) EnsureExists() error {
if err := gitPkg.Clone(r.Dir, r.GitURL); err != nil {
return err
}
if strings.Contains(r.Name, "/") {
sidecar := path.Join(r.Dir, SourceFile)
if err := os.WriteFile(sidecar, []byte(r.Name+"\n"), 0o644); err != nil {
log.Debug(i18n.G("failed to write recipe source sidecar %s: %s", sidecar, err))
}
}
}
if err := gitPkg.EnsureGitRepo(r.Dir); err != nil {
@@ -100,18 +87,6 @@ func (r Recipe) EnsureExists() error {
return nil
}
// ReadRecipeSource returns the canonical name recorded in the .abra-source
// sidecar inside the given recipe directory, or the empty string if no
// sidecar exists. This lets callers recover the unescaped "host/path"
// form for externally-cloned recipes.
func ReadRecipeSource(recipeDir string) string {
data, err := os.ReadFile(path.Join(recipeDir, SourceFile))
if err != nil {
return ""
}
return strings.TrimSpace(string(data))
}
// IsChaosCommit determines if a version sttring is a chaos commit or not.
func (r Recipe) IsChaosCommit(version string) (bool, error) {
isChaosCommit := false
@@ -149,13 +124,6 @@ func (r Recipe) IsChaosCommit(version string) (bool, error) {
// EnsureVersion checks whether a specific version exists for a recipe.
func (r Recipe) EnsureVersion(version string) (bool, error) {
return r.EnsureVersionCtx(EnsureContext{}, version)
}
// EnsureVersionCtx is like EnsureVersion but is aware of the surrounding
// EnsureContext, so that e.g. offline mode can skip network fetches when
// resolving a branch name that isn't already available locally.
func (r Recipe) EnsureVersionCtx(ctx EnsureContext, version string) (bool, error) {
isChaosCommit := false
if err := gitPkg.EnsureGitRepo(r.Dir); err != nil {
@@ -190,46 +158,30 @@ func (r Recipe) EnsureVersionCtx(ctx EnsureContext, version string) (bool, error
}
var opts *git.CheckoutOptions
var checkedOutRef string
if tagRef.String() == "" {
log.Debug(i18n.G("attempting to checkout '%s' as chaos commit", version))
hash, hashErr := repo.ResolveRevision(plumbing.Revision(version))
if hashErr != nil {
branchHash, found, branchErr := resolveBranch(repo, version, ctx.Offline)
if errors.Is(branchErr, errOfflineBranchUnresolved) {
return isChaosCommit, errors.New(i18n.G("'%s' is not available locally and cannot be fetched in offline mode; retry without --offline", version))
}
if branchErr != nil {
return isChaosCommit, branchErr
}
if !found {
return isChaosCommit, errors.New(i18n.G("unable to resolve '%s': %s", version, hashErr))
}
opts = &git.CheckoutOptions{Hash: branchHash, Create: false, Force: true}
isChaosCommit = true
checkedOutRef = version
} else {
opts = &git.CheckoutOptions{Hash: *hash, Create: false, Force: true}
isChaosCommit = true
checkedOutRef = hash.String()
hash, err := repo.ResolveRevision(plumbing.Revision(version))
if err != nil {
log.Fatal(i18n.G("unable to resolve '%s': %s", version, err))
}
opts = &git.CheckoutOptions{Hash: *hash, Create: false, Force: true}
isChaosCommit = true
} else {
opts = &git.CheckoutOptions{Branch: tagRef, Create: false, Force: true}
checkedOutRef = tagRef.Short()
}
worktree, err := repo.Worktree()
if err != nil {
return isChaosCommit, err
return isChaosCommit, nil
}
if err := worktree.Checkout(opts); err != nil {
return isChaosCommit, err
return isChaosCommit, nil
}
log.Debug(i18n.G("successfully checked %s out to %s in %s", r.Name, checkedOutRef, r.Dir))
log.Debug(i18n.G("successfully checked %s out to %s in %s", r.Name, tagRef.Short(), r.Dir))
return isChaosCommit, nil
}
@@ -310,12 +262,7 @@ func (r Recipe) EnsureUpToDate() error {
return errors.New(i18n.G("unable to check out default branch in %s: %s", r.Dir, err))
}
// the refspec is passed explicitly, because a repository cloned by an older abra has a
// single-branch refspec stored in its config and would otherwise never see other branches
fetchOpts := &git.FetchOptions{
Tags: git.AllTags,
RefSpecs: []gitCfg.RefSpec{"+refs/heads/*:refs/remotes/origin/*"},
}
fetchOpts := &git.FetchOptions{Tags: git.AllTags}
if err := repo.Fetch(fetchOpts); err != nil {
if !strings.Contains(err.Error(), "already up-to-date") {
return errors.New(i18n.G("unable to fetch tags in %s: %s", r.Dir, err))
@@ -532,51 +479,6 @@ func (r Recipe) GetRecipeVersions() (RecipeVersions, []string, error) {
return versions, uniqueWarnings, nil
}
// resolveBranch resolves name as a branch on the "origin" remote, fetching
// it on demand into a remote-tracking ref (never into refs/heads/*, which
// would corrupt GetDefaultBranch's local-branch-name heuristic). It returns
// (hash, true, nil) if name is a branch, (_, false, nil) if name is
// confirmed not to be a branch, and a non-nil error for any other failure
// (e.g. network/auth issues) that should not be silently treated as "not a
// branch". When offline is true, no fetch is attempted and only an
// already-fetched remote-tracking ref is consulted.
func resolveBranch(repo *git.Repository, name string, offline bool) (plumbing.Hash, bool, error) {
remoteTrackingRef := plumbing.NewRemoteReferenceName("origin", name)
if !offline {
refSpec := gitCfg.RefSpec(fmt.Sprintf("+refs/heads/%s:%s", name, remoteTrackingRef))
err := repo.Fetch(&git.FetchOptions{
RemoteName: "origin",
RefSpecs: []gitCfg.RefSpec{refSpec},
Force: true,
})
if err != nil {
var noMatch git.NoMatchingRefSpecError
switch {
case errors.Is(err, git.NoErrAlreadyUpToDate):
case errors.As(err, &noMatch):
return plumbing.ZeroHash, false, nil
default:
return plumbing.ZeroHash, false, errors.New(i18n.G("unable to fetch branch '%s': %s", name, err))
}
}
}
ref, err := repo.Reference(remoteTrackingRef, true)
if err != nil {
if offline {
return plumbing.ZeroHash, false, errOfflineBranchUnresolved
}
return plumbing.ZeroHash, false, errors.New(i18n.G("unable to resolve fetched branch '%s': %s", name, err))
}
return ref.Hash(), true, nil
}
// errOfflineBranchUnresolved is returned by resolveBranch when offline mode
// prevents fetching a branch that isn't already available locally.
var errOfflineBranchUnresolved = errors.New(i18n.G("not fetched and cannot resolve offline"))
// Head retrieves latest HEAD metadata.
func (r Recipe) Head() (*plumbing.Reference, error) {
repo, err := git.PlainOpen(r.Dir)
-131
View File
@@ -6,8 +6,6 @@ import (
"testing"
"coopcloud.tech/abra/pkg/test"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/stretchr/testify/assert"
)
@@ -38,132 +36,3 @@ func TestIsDirty(t *testing.T) {
assert.True(t, dirty)
}
func TestEnsureVersionBranch(t *testing.T) {
test.SetupWithUpstream()
t.Cleanup(func() { test.Teardown() })
upstream, err := git.PlainOpen(test.UpstreamRecipeDir)
if err != nil {
t.Fatal(err)
}
featureRef, err := upstream.Reference(plumbing.NewBranchReferenceName(test.FeatureBranch), true)
if err != nil {
t.Fatal(err)
}
r := Get(test.RecipeName)
isChaosCommit, err := r.EnsureVersion(test.FeatureBranch)
if err != nil {
t.Fatal(err)
}
assert.True(t, isChaosCommit)
head, err := r.Head()
if err != nil {
t.Fatal(err)
}
assert.Equal(t, featureRef.Hash(), head.Hash())
}
func TestEnsureVersionBranchRefetchesOnRedeploy(t *testing.T) {
test.SetupWithUpstream()
t.Cleanup(func() { test.Teardown() })
r := Get(test.RecipeName)
if _, err := r.EnsureVersion(test.FeatureBranch); err != nil {
t.Fatal(err)
}
if err := test.CreateBranchWithCommit(test.UpstreamRecipeDir, test.FeatureBranch, "feature2.txt", "more feature work"); err != nil {
t.Fatal(err)
}
upstream, err := git.PlainOpen(test.UpstreamRecipeDir)
if err != nil {
t.Fatal(err)
}
featureRef, err := upstream.Reference(plumbing.NewBranchReferenceName(test.FeatureBranch), true)
if err != nil {
t.Fatal(err)
}
if _, err := r.EnsureVersion(test.FeatureBranch); err != nil {
t.Fatal(err)
}
head, err := r.Head()
if err != nil {
t.Fatal(err)
}
assert.Equal(t, featureRef.Hash(), head.Hash())
}
func TestEnsureVersionOfflineUnfetchedBranch(t *testing.T) {
test.SetupWithUpstream()
t.Cleanup(func() { test.Teardown() })
r := Get(test.RecipeName)
// SetupWithUpstream creates the branch before cloning, so the clone
// already has it: remove the remote-tracking ref to make it unfetched.
repo, err := git.PlainOpen(r.Dir)
if err != nil {
t.Fatal(err)
}
if err := repo.Storer.RemoveReference(plumbing.NewRemoteReferenceName("origin", test.FeatureBranch)); err != nil {
t.Fatal(err)
}
headBefore, err := r.Head()
if err != nil {
t.Fatal(err)
}
_, err = r.EnsureVersionCtx(EnsureContext{Offline: true}, test.FeatureBranch)
assert.ErrorContains(t, err, "offline")
headAfter, err := r.Head()
if err != nil {
t.Fatal(err)
}
assert.Equal(t, headBefore.Hash(), headAfter.Hash())
}
func TestEnsureVersionUnknownNameErrors(t *testing.T) {
test.SetupWithUpstream()
t.Cleanup(func() { test.Teardown() })
r := Get(test.RecipeName)
_, err := r.EnsureVersion("does-not-exist-anywhere")
assert.Error(t, err)
}
func TestEnsureBranchPinnedRecipe(t *testing.T) {
test.SetupWithUpstream()
t.Cleanup(func() { test.Teardown() })
upstream, err := git.PlainOpen(test.UpstreamRecipeDir)
if err != nil {
t.Fatal(err)
}
featureRef, err := upstream.Reference(plumbing.NewBranchReferenceName(test.FeatureBranch), true)
if err != nil {
t.Fatal(err)
}
r := Get(test.RecipeName + ":" + test.FeatureBranch)
if err := r.Ensure(EnsureContext{}); err != nil {
t.Fatal(err)
}
head, err := r.Head()
if err != nil {
t.Fatal(err)
}
assert.Equal(t, featureRef.Hash(), head.Hash())
}
+18 -103
View File
@@ -8,7 +8,6 @@ import (
"net/url"
"os"
"path"
"regexp"
"sort"
"strconv"
"strings"
@@ -122,84 +121,7 @@ type Features struct {
SSO string `json:"sso"`
}
// scpURLPattern matches SCP-style git URLs like git@host:path or git@host:port/path.
// Captures: 1=host(:port)?, 2=path.
var scpURLPattern = regexp.MustCompile(`^[\w.-]+@([\w.-]+(?::\d+)?):(.+)$`)
// NormalizeRecipeName canonicalizes a recipe identifier to a stable
// "host/path" form (or returns short catalog names unchanged). Accepts:
//
// - https://host/path[.git][:version]
// - http://host/path[.git][:version]
// - ssh://git@host[:port]/path[.git][:version]
// - git@host:path[.git][:version] (SCP-style)
// - host/path[.git][:version] (already canonical)
// - short-name[:version] (catalog recipe, pass through)
//
// The optional trailing :version suffix is preserved verbatim. The .git
// suffix and trailing slashes on the path are stripped so the four URL
// forms of the same repository collapse to one canonical value.
func NormalizeRecipeName(input string) string {
input = strings.TrimSpace(input)
// Split off the version suffix first, but only if it's not part of a
// scheme (https://) or SCP-style git@host: prefix. The simplest way is
// to detect those prefixes and treat the rest as the path-with-version.
var (
body = input
version string
)
switch {
case strings.HasPrefix(input, "https://") || strings.HasPrefix(input, "http://") || strings.HasPrefix(input, "ssh://"):
u, err := url.Parse(input)
if err != nil {
return input
}
host := u.Hostname() // strip port to keep canonical form colon-free
p := strings.TrimPrefix(u.Path, "/")
p, version = splitVersion(p)
body = host + "/" + p
case scpURLPattern.MatchString(input):
m := scpURLPattern.FindStringSubmatch(input)
host := m[1]
if i := strings.Index(host, ":"); i >= 0 {
host = host[:i] // strip port
}
p, v := splitVersion(m[2])
body = host + "/" + p
version = v
default:
body, version = splitVersion(input)
}
body = strings.TrimSuffix(body, "/")
body = strings.TrimSuffix(body, ".git")
if version != "" {
return body + ":" + version
}
return body
}
// splitVersion separates a trailing ":version" suffix from a recipe path.
// It only treats the final colon-separated segment as a version when it is
// non-empty and contains no slash (a slash means the colon belonged to the
// path, e.g. a host:port or scheme separator).
func splitVersion(s string) (string, string) {
idx := strings.LastIndex(s, ":")
if idx < 0 {
return s, ""
}
candidate := s[idx+1:]
if candidate == "" || strings.Contains(candidate, "/") {
return s, ""
}
return s[:idx], candidate
}
func Get(name string) Recipe {
name = NormalizeRecipeName(name)
version := ""
versionRaw := ""
if strings.Contains(name, ":") {
@@ -287,16 +209,6 @@ func (r Recipe) String() string {
return out
}
// ShortName returns the final path segment of the recipe name, i.e. the
// bare recipe name without any "host/org/" prefix carried by externally
// sourced (git URL) recipes. For catalogue recipes it returns Name unchanged.
func (r Recipe) ShortName() string {
if i := strings.LastIndex(r.Name, "/"); i >= 0 {
return r.Name[i+1:]
}
return r.Name
}
func escapeRecipeName(recipeName string) string {
recipeName = strings.ReplaceAll(recipeName, "/", "_")
recipeName = strings.ReplaceAll(recipeName, ".", "_")
@@ -680,7 +592,15 @@ func ReadReposMetadata(debug bool) (RepoCatalogue, error) {
// sortRecipeVersions sorts the recipe semver versions
func sortRecipeVersions(versions RecipeVersions) {
sort.Slice(versions, func(i, j int) bool {
return safeCompareVersions(getVersionString(versions[i]), getVersionString(versions[j]))
version1, err := tagcmp.Parse(getVersionString(versions[i]))
if err != nil {
panic(err)
}
version2, err := tagcmp.Parse(getVersionString(versions[j]))
if err != nil {
panic(err)
}
return version1.IsLessThan(version2)
})
}
@@ -696,23 +616,18 @@ func getVersionString(versionMap map[string]map[string]ServiceMeta) string {
// sortVersionStrings sorts a list of semver version strings
func sortVersionStrings(versions []string) {
sort.Slice(versions, func(i, j int) bool {
return safeCompareVersions(versions[i], versions[j])
version1, err := tagcmp.Parse(versions[i])
if err != nil {
panic(err)
}
version2, err := tagcmp.Parse(versions[j])
if err != nil {
panic(err)
}
return version1.IsLessThan(version2)
})
}
// Invalid versions are sorted as less than valid ones.
func safeCompareVersions(v1, v2 string) bool {
version1, err1 := tagcmp.Parse(v1)
if err1 != nil {
return true
}
version2, err2 := tagcmp.Parse(v2)
if err2 != nil {
return false
}
return version1.IsLessThan(version2)
}
// GetRecipeCatalogueVersions list the recipe versions listed in the recipe catalogue.
func GetRecipeCatalogueVersions(recipeName string, catl RecipeCatalogue) ([]string, error) {
var versions []string
-163
View File
@@ -88,88 +88,6 @@ func TestGet(t *testing.T) {
AbraShPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/abra.sh"),
},
},
{
name: "https://mygit.org/myorg/cool-recipe",
recipe: Recipe{
Name: "mygit.org/myorg/cool-recipe",
Dir: path.Join(cfg.GetAbraDir(), "/recipes/mygit_org_myorg_cool-recipe"),
GitURL: "https://mygit.org/myorg/cool-recipe.git",
SSHURL: "ssh://git@mygit.org/myorg/cool-recipe.git",
ComposePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/compose.yml"),
ReadmePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/README.md"),
SampleEnvPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/.env.sample"),
AbraShPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/abra.sh"),
},
},
{
name: "https://mygit.org/myorg/cool-recipe.git",
recipe: Recipe{
Name: "mygit.org/myorg/cool-recipe",
Dir: path.Join(cfg.GetAbraDir(), "/recipes/mygit_org_myorg_cool-recipe"),
GitURL: "https://mygit.org/myorg/cool-recipe.git",
SSHURL: "ssh://git@mygit.org/myorg/cool-recipe.git",
ComposePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/compose.yml"),
ReadmePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/README.md"),
SampleEnvPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/.env.sample"),
AbraShPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/abra.sh"),
},
},
{
name: "https://mygit.org/myorg/cool-recipe.git:1.2.4",
recipe: Recipe{
Name: "mygit.org/myorg/cool-recipe",
EnvVersion: "1.2.4",
EnvVersionRaw: "1.2.4",
Dir: path.Join(cfg.GetAbraDir(), "/recipes/mygit_org_myorg_cool-recipe"),
GitURL: "https://mygit.org/myorg/cool-recipe.git",
SSHURL: "ssh://git@mygit.org/myorg/cool-recipe.git",
ComposePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/compose.yml"),
ReadmePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/README.md"),
SampleEnvPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/.env.sample"),
AbraShPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/abra.sh"),
},
},
{
name: "ssh://git@mygit.org/myorg/cool-recipe.git",
recipe: Recipe{
Name: "mygit.org/myorg/cool-recipe",
Dir: path.Join(cfg.GetAbraDir(), "/recipes/mygit_org_myorg_cool-recipe"),
GitURL: "https://mygit.org/myorg/cool-recipe.git",
SSHURL: "ssh://git@mygit.org/myorg/cool-recipe.git",
ComposePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/compose.yml"),
ReadmePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/README.md"),
SampleEnvPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/.env.sample"),
AbraShPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/abra.sh"),
},
},
{
name: "git@mygit.org:myorg/cool-recipe.git",
recipe: Recipe{
Name: "mygit.org/myorg/cool-recipe",
Dir: path.Join(cfg.GetAbraDir(), "/recipes/mygit_org_myorg_cool-recipe"),
GitURL: "https://mygit.org/myorg/cool-recipe.git",
SSHURL: "ssh://git@mygit.org/myorg/cool-recipe.git",
ComposePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/compose.yml"),
ReadmePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/README.md"),
SampleEnvPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/.env.sample"),
AbraShPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/abra.sh"),
},
},
{
name: "git@mygit.org:myorg/cool-recipe:1.2.4",
recipe: Recipe{
Name: "mygit.org/myorg/cool-recipe",
EnvVersion: "1.2.4",
EnvVersionRaw: "1.2.4",
Dir: path.Join(cfg.GetAbraDir(), "/recipes/mygit_org_myorg_cool-recipe"),
GitURL: "https://mygit.org/myorg/cool-recipe.git",
SSHURL: "ssh://git@mygit.org/myorg/cool-recipe.git",
ComposePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/compose.yml"),
ReadmePath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/README.md"),
SampleEnvPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/.env.sample"),
AbraShPath: path.Join(cfg.GetAbraDir(), "recipes/mygit_org_myorg_cool-recipe/abra.sh"),
},
},
}
for _, tc := range testcases {
@@ -183,49 +101,6 @@ func TestGet(t *testing.T) {
}
}
func TestNormalizeRecipeName(t *testing.T) {
cases := []struct {
in, want string
}{
// catalog short names pass through
{"foo", "foo"},
{"foo:1.2.3", "foo:1.2.3"},
// bare host/path form
{"mygit.org/myorg/cool-recipe", "mygit.org/myorg/cool-recipe"},
{"mygit.org/myorg/cool-recipe.git", "mygit.org/myorg/cool-recipe"},
{"mygit.org/myorg/cool-recipe.git:1.2.3", "mygit.org/myorg/cool-recipe:1.2.3"},
{"mygit.org/myorg/cool-recipe/", "mygit.org/myorg/cool-recipe"},
// https://
{"https://mygit.org/myorg/cool-recipe", "mygit.org/myorg/cool-recipe"},
{"https://mygit.org/myorg/cool-recipe.git", "mygit.org/myorg/cool-recipe"},
{"https://mygit.org/myorg/cool-recipe.git:1.2.3", "mygit.org/myorg/cool-recipe:1.2.3"},
{"http://mygit.org/myorg/cool-recipe", "mygit.org/myorg/cool-recipe"},
// ssh://, with and without port
{"ssh://git@mygit.org/myorg/cool-recipe.git", "mygit.org/myorg/cool-recipe"},
{"ssh://git@mygit.org:2222/myorg/cool-recipe.git", "mygit.org/myorg/cool-recipe"},
// SCP-style git@host:path
{"git@mygit.org:myorg/cool-recipe", "mygit.org/myorg/cool-recipe"},
{"git@mygit.org:myorg/cool-recipe.git", "mygit.org/myorg/cool-recipe"},
{"git@mygit.org:myorg/cool-recipe:1.2.3", "mygit.org/myorg/cool-recipe:1.2.3"},
// whitespace
{" https://mygit.org/myorg/cool-recipe ", "mygit.org/myorg/cool-recipe"},
}
for _, tc := range cases {
t.Run(tc.in, func(t *testing.T) {
got := NormalizeRecipeName(tc.in)
if got != tc.want {
t.Errorf("NormalizeRecipeName(%q) = %q, want %q", tc.in, got, tc.want)
}
})
}
}
func TestGetVersionLabelLocalDoesNotUseTimeoutLabel(t *testing.T) {
test.Setup()
t.Cleanup(func() { test.Teardown() })
@@ -248,41 +123,3 @@ func TestGetVersionLabelLocalDoesNotUseTimeoutLabel(t *testing.T) {
assert.NotEqual(t, label, timeout)
}
}
// This is not a full test of comparison, as that occurs in the external
// tagcmp package. This is a sunny-day integration test
func TestSortRecipeVersionsSortsTwoValidStrings(t *testing.T) {
versions := RecipeVersions{
{"2.0.0": {}}, // Index 0
{"1.0.0": {}}, // Index 1
}
sortRecipeVersions(versions)
assert.Equal(t, "1.0.0", getVersionString(versions[0]), "Version 1.0.0 should be first")
assert.Equal(t, "2.0.0", getVersionString(versions[1]), "Version 2.0.0 should be second")
}
func TestSortRecipeVersionsSortsInvalidVersionStringToTheBottom(t *testing.T) {
versions := RecipeVersions{
{"2.0.0": {}}, // Index 0
{"invalid": {}}, // Index 1
}
sortRecipeVersions(versions)
assert.Equal(t, "invalid", getVersionString(versions[0]), "The invalid version should be first")
assert.Equal(t, "2.0.0", getVersionString(versions[1]), "Version 2.0.0 should be second")
}
func TestSortRecipeVersionsSortsInvalidVersionStringToTheBottomInReverse(t *testing.T) {
versions := RecipeVersions{
{"invalid": {}}, // Index 0
{"2.0.0": {}}, // Index 1
}
sortRecipeVersions(versions)
assert.Equal(t, "invalid", getVersionString(versions[0]), "The invalid version should be first")
assert.Equal(t, "2.0.0", getVersionString(versions[1]), "Version 2.0.0 should be second")
}
+1 -1
View File
@@ -3,7 +3,7 @@ version: "3.8"
services:
app:
image: nginx:1.31.9
image: nginx:1.21.0
secrets:
- test_pass_one
- test_pass_two
-123
View File
@@ -8,9 +8,6 @@ import (
gitPkg "coopcloud.tech/abra/pkg/git"
"git.coopcloud.tech/toolshed/godotenv"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
)
var (
@@ -79,126 +76,6 @@ func Setup() {
}
}
// UpstreamRecipeDir is the "remote" repo used by SetupWithUpstream, kept
// outside recipes/ so Teardown's blanket removal of $ABRA_DIR still cleans
// it up.
var UpstreamRecipeDir = os.ExpandEnv("$ABRA_DIR/_upstream/test_recipe")
// FeatureBranch is the non-default branch created by SetupWithUpstream.
const FeatureBranch = "feature"
// SetupWithUpstream is like Setup, but the recipe under $ABRA_DIR/recipes
// is a real clone of a separate "upstream" repo (UpstreamRecipeDir) rather
// than a git-inited copy of the fixture. The upstream repo additionally has
// a FeatureBranch with one extra commit not present on main, so tests can
// exercise resolving/fetching a non-default branch as a recipe :version.
func SetupWithUpstream() {
Teardown()
if err := os.Mkdir(os.ExpandEnv("$ABRA_DIR"), 0764); err != nil {
if !os.IsExist(err) {
log.Fatal(err)
}
}
if err := os.Mkdir(os.ExpandEnv("$ABRA_DIR/servers"), 0700); err != nil {
if !os.IsExist(err) {
log.Fatal(err)
}
}
if err := os.Mkdir(os.ExpandEnv("$ABRA_DIR/recipes"), 0764); err != nil {
if !os.IsExist(err) {
log.Fatal(err)
}
}
serverSrcDir := os.ExpandEnv("$PWD/../../tests/resources/test_server")
serverDestDir := os.ExpandEnv("$ABRA_DIR/servers/test_server")
if err := os.CopyFS(serverDestDir, os.DirFS(serverSrcDir)); err != nil {
log.Fatal(err)
}
if err := os.MkdirAll(path.Dir(UpstreamRecipeDir), 0764); err != nil {
log.Fatal(err)
}
recipeSrcDir := os.ExpandEnv("$PWD/../../tests/resources/test_recipe")
if err := os.CopyFS(UpstreamRecipeDir, os.DirFS(recipeSrcDir)); err != nil {
log.Fatal(err)
}
if err := os.WriteFile(path.Join(UpstreamRecipeDir, ".env.sample"), []byte("TYPE=test_recipe\n"), 0o644); err != nil {
log.Fatal(err)
}
if err := gitPkg.Init(UpstreamRecipeDir, true, "tester", "helo@coopcloud.tech"); err != nil {
log.Fatal(err)
}
if err := CreateBranchWithCommit(UpstreamRecipeDir, FeatureBranch, "feature.txt", "feature work"); err != nil {
log.Fatal(err)
}
recipeDestDir := os.ExpandEnv("$ABRA_DIR/recipes/test_recipe")
if err := gitPkg.Clone(recipeDestDir, UpstreamRecipeDir); err != nil {
log.Fatal(err)
}
}
// CreateBranchWithCommit checks out branchName in repoPath (creating it off
// the current HEAD if it doesn't exist yet, or extending it if it does),
// writes fileName with contents, commits it, then returns to the repo's
// default branch (leaving the new commit reachable only via the branch's
// ref, matching how a contributor would push a feature branch upstream
// without switching the repo's HEAD away from main).
func CreateBranchWithCommit(repoPath, branchName, fileName, contents string) error {
repo, err := git.PlainOpen(repoPath)
if err != nil {
return err
}
head, err := repo.Head()
if err != nil {
return err
}
worktree, err := repo.Worktree()
if err != nil {
return err
}
branchRef := plumbing.NewBranchReferenceName(branchName)
create := true
if _, err := repo.Reference(branchRef, true); err == nil {
create = false
}
checkoutOpts := &git.CheckoutOptions{Branch: branchRef, Create: create}
if create {
checkoutOpts.Hash = head.Hash()
}
if err := worktree.Checkout(checkoutOpts); err != nil {
return err
}
if err := os.WriteFile(path.Join(repoPath, fileName), []byte(contents), 0o644); err != nil {
return err
}
if _, err := worktree.Add(fileName); err != nil {
return err
}
if _, err := worktree.Commit(fileName, &git.CommitOptions{
Author: &object.Signature{Name: "tester", Email: "helo@coopcloud.tech"},
}); err != nil {
return err
}
return worktree.Checkout(&git.CheckoutOptions{Branch: head.Name()})
}
func AddEnv(envKey, envValue string) error {
filePath := os.ExpandEnv(fmt.Sprintf("$ABRA_DIR/servers/%s/%s.env", ServerName, AppName))
-31
View File
@@ -1,31 +0,0 @@
#!/usr/bin/env bash
# This file generates local DNS aliases for the client VM for integration testing
GIT_ROOT=$(git rev-parse --show-toplevel)
echo "generating hosts file..."
hosts_file_path="$GIT_ROOT/tests/resources/extra_hosts"
echo "removing old file..."
rm -f "$hosts_file_path"
# the server domain
server_ip="10.0.0.3"
domain="abra.local"
echo "$server_ip $domain" >> "$hosts_file_path"
# static subdomains used in integration tests
subdomains=("gitea" "zammad" "custom-html" "foo" "foobar")
for subdomain in "${subdomains[@]}"
do
echo "$server_ip $subdomain.$domain" >> "$hosts_file_path"
done
search_dir="$GIT_ROOT/tests/integration"
for entry in "$search_dir"/*.bats
do
file_name=$(basename "${entry}")
# converting file names to testing subdomains
subdomain=$(echo "$file_name" | tr . _)
echo "$server_ip $subdomain.$domain" >> "$hosts_file_path"
done
echo "writing extra hosts success"
+1 -2
View File
@@ -7,5 +7,4 @@
* Integration tests are in `./tests/integration`. Please see [these
docs](https://docs.coopcloud.tech/abra/hack/#integration-tests) for
instructions and tips on how to run them. If you want to run it locally via nix,
read the [nix testing docs](../nix/hosts/README.md).
instructions and tips on how to run them.
+5 -9
View File
@@ -598,7 +598,8 @@ teardown(){
run $ABRA app deploy "$TEST_APP_DOMAIN" --no-input
assert_success
_inspect_env_test_app
run docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' \
$(docker ps -f name="$TEST_APP_DOMAIN_$TEST_SERVER" -q)
assert_success
assert_output --partial "WITH_COMMENT=foo"
@@ -609,7 +610,8 @@ teardown(){
run $ABRA app deploy "$TEST_APP_DOMAIN" --no-input --force
assert_success
_inspect_env_test_app
run docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' \
$(docker ps -f name="$TEST_APP_DOMAIN_$TEST_SERVER" -q)
assert_success
refute_output --partial "WITH_COMMENT=foo"
assert_output --partial "WITH_COMMENT=bar"
@@ -627,14 +629,8 @@ teardown(){
run $ABRA app deploy "$TEST_APP_DOMAIN" --no-input
assert_success
if _is_local;
then
run docker service inspect --format "{{ range .Endpoint.Ports }}{{ .Protocol }}={{ .PublishedPort }}{{ end }}" \
run docker service inspect --format '{{ range .Endpoint.Ports }}{{ .Protocol }}={{ .PublishedPort }}{{ end }}' \
"${TEST_APP_DOMAIN//./_}_app"
else
run ssh "$TEST_SERVER" "docker service inspect --format '{{ range .Endpoint.Ports }}{{ .Protocol }}={{ .PublishedPort }}{{ end }}' ${TEST_APP_DOMAIN//./_}_app"
fi
assert_success
assert_output --partial "tcp=1312"
assert_output --partial "udp=1312"
@@ -133,7 +133,8 @@ teardown(){
run $ABRA app deploy "$TEST_APP_DOMAIN" "0.1.0+1.20.0" --no-input
assert_success
_inspect_env_test_app
run docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' \
$(docker ps -f name="$TEST_APP_DOMAIN_$TEST_SERVER" -q)
assert_success
assert_output --partial "$TEST_RECIIPE:0.1.0+1.20.0"
}
-53
View File
@@ -61,16 +61,6 @@ teardown(){
run grep -q "TYPE=$TEST_RECIPE:0.3.0+1.21.0" \
"$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
assert_success
# 0.3.0-only
run grep -q "NETWORK_WITH_COMMENT=BAZ" \
"$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
assert_success
# latest-only
run grep -q "TIMEOUT=120" \
"$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
assert_failure
}
@test "ensure recipe is up-to-date" {
@@ -110,49 +100,6 @@ teardown(){
run grep -q "TYPE=$TEST_RECIPE:${tagHash}" \
"$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
assert_success
# 0.3.0-only
run grep -q "NETWORK_WITH_COMMENT=BAZ" \
"$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
assert_success
# latest-only
run grep -q "TIMEOUT=120" \
"$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
assert_failure
}
@test "create new app with commit from another branch" {
branchHash=$(_get_other_branch_hash)
if [[ -z "$branchHash" ]]; then
skip "$TEST_RECIPE has no branch besides main"
fi
# re-clone the recipe the way an older abra did, with a single-branch refspec. --no-local
# forces a real transfer, a local clone would hardlink the whole object database and leave
# the commit reachable
run rm -rf "$ABRA_DIR/recipes/$TEST_RECIPE"
assert_success
run git clone -q --no-local --single-branch --branch main \
"$ABRA_DIR/origin-recipes/$TEST_RECIPE.git" "$ABRA_DIR/recipes/$TEST_RECIPE"
assert_success
# the commit has to be genuinely missing, otherwise this test passes for the wrong reason
run git -C "$ABRA_DIR/recipes/$TEST_RECIPE" rev-parse --verify "$branchHash^{commit}"
assert_failure
run $ABRA app new "$TEST_RECIPE" "$branchHash" \
--no-input \
--server "$TEST_SERVER" \
--domain "$TEST_APP_DOMAIN"
assert_success
assert_exists "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
# the recipe names itself in TYPE, which differs per branch, so only the version is checked
run grep -q "TYPE=.*:${branchHash}$" \
"$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
assert_success
}
@test "does not overwrite existing env files" {
+4 -11
View File
@@ -140,22 +140,15 @@ teardown(){
_undeploy_app
sanitisedDomainName="${TEST_APP_DOMAIN//./_}"
remote_ssh_command=""
if _is_local;
then
run docker config create "${sanitisedDomainName}_test_conf_v99" "$ABRA_DIR/recipes/abra-test-recipe/abra.sh"
else
remote_ssh_command="ssh '$TEST_SERVER'"
run cat "$ABRA_DIR/recipes/abra-test-recipe/abra.sh" | ssh "$TEST_SERVER" docker config create "${sanitisedDomainName}_test_conf_v99 -"
assert_success
fi
run docker config create "${sanitisedDomainName}_test_conf_v99" "$ABRA_DIR/recipes/abra-test-recipe/abra.sh"
assert_success
assert bash -c "$remote_ssh_command docker config ls | grep -q test_conf_v99"
assert bash -c "docker config ls | grep -q test_conf_v99"
run $ABRA app rm "$TEST_APP_DOMAIN" --no-input
assert_success
refute bash -c "$remote_ssh_command docker config ls | grep -q test_conf_v99"
refute bash -c "docker config ls | grep -q test_conf_v99"
}
@test "remove .env file" {
@@ -54,7 +54,8 @@ teardown(){
--no-input
assert_success
_inspect_env_test_app
run docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' \
$(docker ps -f name="$TEST_APP_DOMAIN_$TEST_SERVER" -q)
assert_success
assert_output --partial "$TEST_RECIIPE:0.1.0+1.20.0"
}
@@ -53,7 +53,8 @@ teardown(){
run $ABRA app upgrade "$TEST_APP_DOMAIN" "0.2.0+1.21.0" --no-input
assert_success
_inspect_env_test_app
run docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' \
$(docker ps -f name="$TEST_APP_DOMAIN_$TEST_SERVER" -q)
assert_success
assert_output --partial "$TEST_RECIPE:0.2.0+1.21.0"
assert_output --partial "$TEST_RECIIPE:0.2.0+1.21.0"
}
+2 -11
View File
@@ -31,18 +31,9 @@ _ensure_ssh_agent() {
exit 1
fi
if [[ ! -v SSH_AUTH_SOCK ]]; then
export SSH_AUTH_SOCK="$HOME/.ssh/ssh_auth_sock"
export SSH_AUTH_SOCK="$HOME/.ssh/ssh_auth_sock"
if [ ! -S ~/.ssh/ssh_auth_sock ]; then
eval `ssh-agent`
ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
fi
}
_is_local() {
if [[ "$TEST_SERVER" == "default" ]];
then
return 0
else
return 1
fi
}
+6 -30
View File
@@ -1,37 +1,13 @@
#!/usr/bin/env bash
_ensure_swarm() {
if [ "$(docker info | grep Swarm | sed 's/Swarm: //g' | tr -d ' ')" == "inactive" ]; then
run docker swarm init --advertise-addr 127.0.0.1:2377
assert_success
if [ "$(docker info | grep Swarm | sed 's/Swarm: //g' | tr -d ' ')" == "inactive" ]; then
run docker swarm init --advertise-addr 127.0.0.1:2377
assert_success
fi
if ! docker network ls | grep -q 'proxy'; then
run docker network create -d overlay proxy
assert_success
if ! $(docker network ls | grep -q 'proxy'); then
run docker network create -d overlay proxy
assert_success
fi
if ! _is_local;
then
if [ "$(ssh "$TEST_SERVER" docker info | grep Swarm | sed 's/Swarm: //g' | tr -d ' ')" == "inactive" ]; then
run ssh "$TEST_SERVER" docker swarm init --advertise-addr 127.0.0.1:2377
assert_success
fi
if ! ssh "$TEST_SERVER" docker network ls | grep -q 'proxy'; then
run ssh "$TEST_SERVER" docker network create -d overlay proxy
assert_success
fi
fi
}
_inspect_env_test_app() {
if _is_local;
then
containerId="$(docker ps -f name="$TEST_APP_DOMAIN_$TEST_SERVER" -q)"
run docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' "$containerId"
else
containerId="$(ssh "$TEST_SERVER" docker ps -f name="$TEST_APP_DOMAIN" -q)"
run ssh "$TEST_SERVER" "docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' '$containerId'"
fi
}
-7
View File
@@ -56,13 +56,6 @@ _get_tag_hash() {
echo $(git -C "$ABRA_DIR/recipes/$TEST_RECIPE" rev-list -n 1 "$1")
}
_get_other_branch_hash() {
# asked from the origin mirror, not from the recipe checkout, so that the result does not
# depend on what has been fetched. empty when the recipe only has a default branch
echo $(git ls-remote "$ABRA_DIR/origin-recipes/$TEST_RECIPE.git" \
| grep 'refs/heads/' | grep -v 'refs/heads/main$' | head -1 | cut -f1)
}
_get_head_hash() {
echo $(git -C "$ABRA_DIR/recipes/$TEST_RECIPE" show -s --format="%H" HEAD)
}
+7 -5
View File
@@ -30,15 +30,17 @@ teardown(){
}
@test "retrieve recipe if missing" {
if [[ -d "$ABRA_DIR/recipe/traefik" ]]; then
run rm -rf "$ABRA_DIR/recipes/traefik"
if [[ -d "$ABRA_DIR/recipe/custom-html" ]]; then
run rm -rf "$ABRA_DIR/recipes/custom-html"
assert_success
assert_not_exists "$ABRA_DIR/recipes/traefik"
assert_not_exists "$ABRA_DIR/recipes/custom-html"
fi
run $ABRA recipe upgrade "traefik" --no-input
run $ABRA recipe upgrade "custom-html" --no-input
assert_success
assert_exists "$ABRA_DIR/recipes/traefik"
assert_output --partial 'can upgrade service: app'
assert_exists "$ABRA_DIR/recipes/custom-html"
}
@test "error if unstaged changes" {
+3 -3
View File
@@ -27,7 +27,7 @@ teardown(){
assert bash -c "docker context ls | grep -q $TEST_SERVER"
server_dir_perms=$(stat -c "%a" "$ABRA_DIR/servers/$TEST_SERVER")
assert_equal "$server_dir_perms" "700"
assert_equal $server_dir_perms "700"
}
@test "error if using name and --local together" {
@@ -43,8 +43,8 @@ teardown(){
assert bash -c "docker context ls | grep -q default"
assert_output --partial 'local server successfully added'
server_dir_perms=$(stat -c "%a" "$ABRA_DIR/servers/default")
assert_equal "$server_dir_perms" "700"
server_dir_perms=$(stat -c "%a" "$ABRA_DIR/servers/$TEST_SERVER")
assert_equal $server_dir_perms "700"
}
@test "create local server fails when no docker swarm" {
-57
View File
@@ -1,57 +0,0 @@
10.0.0.3 abra.local
10.0.0.3 gitea.abra.local
10.0.0.3 zammad.abra.local
10.0.0.3 custom-html.abra.local
10.0.0.3 foo.abra.local
10.0.0.3 foobar.abra.local
10.0.0.3 app_check_bats.abra.local
10.0.0.3 app_cmd_bats.abra.local
10.0.0.3 app_config_bats.abra.local
10.0.0.3 app_cp_bats.abra.local
10.0.0.3 app_deploy_bats.abra.local
10.0.0.3 app_deploy_env_version_bats.abra.local
10.0.0.3 app_deploy_overview_bats.abra.local
10.0.0.3 app_deploy_remote_recipes_bats.abra.local
10.0.0.3 app_env_bats.abra.local
10.0.0.3 app_env_version_bats.abra.local
10.0.0.3 app_labels_bats.abra.local
10.0.0.3 app_list_bats.abra.local
10.0.0.3 app_logs_bats.abra.local
10.0.0.3 app_move_bats.abra.local
10.0.0.3 app_new_bats.abra.local
10.0.0.3 app_ps_bats.abra.local
10.0.0.3 app_remove_bats.abra.local
10.0.0.3 app_restart_bats.abra.local
10.0.0.3 app_rollback_bats.abra.local
10.0.0.3 app_rollback_env_version_bats.abra.local
10.0.0.3 app_rollback_overview_bats.abra.local
10.0.0.3 app_run_bats.abra.local
10.0.0.3 app_secret_bats.abra.local
10.0.0.3 app_secret_env_version_bats.abra.local
10.0.0.3 app_services_bats.abra.local
10.0.0.3 app_undeploy_bats.abra.local
10.0.0.3 app_undeploy_env_version_bats.abra.local
10.0.0.3 app_undeploy_overview_bats.abra.local
10.0.0.3 app_upgrade_bats.abra.local
10.0.0.3 app_upgrade_env_version_bats.abra.local
10.0.0.3 app_upgrade_overview_bats.abra.local
10.0.0.3 app_volume_bats.abra.local
10.0.0.3 autocomplete_bats.abra.local
10.0.0.3 catalogue_bats.abra.local
10.0.0.3 dirs_bats.abra.local
10.0.0.3 install_bats.abra.local
10.0.0.3 recipe_diff_bats.abra.local
10.0.0.3 recipe_fetch_bats.abra.local
10.0.0.3 recipe_lint_bats.abra.local
10.0.0.3 recipe_list_bats.abra.local
10.0.0.3 recipe_new_bats.abra.local
10.0.0.3 recipe_release_bats.abra.local
10.0.0.3 recipe_reset_bats.abra.local
10.0.0.3 recipe_upgrade_bats.abra.local
10.0.0.3 recipe_version_bats.abra.local
10.0.0.3 server_add_bats.abra.local
10.0.0.3 server_list_bats.abra.local
10.0.0.3 server_prune_bats.abra.local
10.0.0.3 server_remove_bats.abra.local
10.0.0.3 upgrade_bats.abra.local
10.0.0.3 version_bats.abra.local
-7
View File
@@ -1,7 +0,0 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACBQ967UhxmFkq71WXvVRkEmtehCGsEnBVppAXxgtHHm7wAAAJhFGwTnRRsE
5wAAAAtzc2gtZWQyNTUxOQAAACBQ967UhxmFkq71WXvVRkEmtehCGsEnBVppAXxgtHHm7w
AAAEAnHEZcf2NeRQEcJC/aVgUWsdOz+vQgEG9ZY+3ErCeaKFD3rtSHGYWSrvVZe9VGQSa1
6EIawScFWmkBfGC0cebvAAAAFWFicmEgaW50ZWdyYXRpb24gdGVzdA==
-----END OPENSSH PRIVATE KEY-----
@@ -1 +0,0 @@
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFD3rtSHGYWSrvVZe9VGQSa16EIawScFWmkBfGC0cebv abra integration test
-1
View File
@@ -1 +0,0 @@
/path/to/this/repo
+1 -1
View File
@@ -3,7 +3,7 @@ version: "3.8"
services:
app:
image: nginx:1.31.9
image: nginx:1.29.0
networks:
- proxy
deploy:
+3 -3
View File
@@ -3,16 +3,16 @@ kind: pipeline
name: coopcloud.tech/tagcmp
steps:
- name: gofmt
image: golang:1.26
image: golang:1.21
commands:
- test -z "$(gofmt -l .)"
- name: go build
image: golang:1.26
image: golang:1.21
commands:
- go build -v .
- name: go test
image: golang:1.26
image: golang:1.21
commands:
- go test . -cover
-6
View File
@@ -1,6 +0,0 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:recommended"
]
}
+1 -1
View File
@@ -87,7 +87,7 @@ func stringWidth(m Method, s string) int {
for i := 0; i < len(s); i++ {
state, action := parser.Table.Transition(pstate, s[i])
if state == parser.Utf8State {
if action == parser.PrintAction || state == parser.Utf8State {
cluster, w := FirstGraphemeCluster(s[i:], m)
width += w
@@ -18,7 +18,6 @@
// tag is deprecated and thus should not be used.
// Go versions prior to 1.4 are disabled because they use a different layout
// for interfaces which make the implementation of unsafeReflectValue more complex.
//go:build !js && !appengine && !safe && !disableunsafe && go1.4
// +build !js,!appengine,!safe,!disableunsafe,go1.4
package spew
@@ -16,7 +16,6 @@
// when the code is running on Google App Engine, compiled by GopherJS, or
// "-tags safe" is added to the go build command line. The "disableunsafe"
// tag is deprecated and thus should not be used.
//go:build js || appengine || safe || disableunsafe || !go1.4
// +build js appengine safe disableunsafe !go1.4
package spew
@@ -254,15 +254,15 @@ pointer addresses used to indirect to the final value. It provides the
following features over the built-in printing facilities provided by the fmt
package:
- Pointers are dereferenced and followed
- Circular data structures are detected and handled properly
- Custom Stringer/error interfaces are optionally invoked, including
on unexported types
- Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
- Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output
* Pointers are dereferenced and followed
* Circular data structures are detected and handled properly
* Custom Stringer/error interfaces are optionally invoked, including
on unexported types
* Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
* Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output
The configuration options are controlled by modifying the public members
of c. See ConfigState for options documentation.
@@ -295,12 +295,12 @@ func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{})
// NewDefaultConfig returns a ConfigState with the following default settings.
//
// Indent: " "
// MaxDepth: 0
// DisableMethods: false
// DisablePointerMethods: false
// ContinueOnMethod: false
// SortKeys: false
// Indent: " "
// MaxDepth: 0
// DisableMethods: false
// DisablePointerMethods: false
// ContinueOnMethod: false
// SortKeys: false
func NewDefaultConfig() *ConfigState {
return &ConfigState{Indent: " "}
}

Some files were not shown because too many files have changed in this diff Show More