feat(catalogue,helm,ci): add private OCI auth, offline catalogue mirror, CI image/SBOM, metrics config, and OpenShift overlay (#2153)
This commit is contained in:
23 files changed
+1095
-12
No files matched your search
@@ -0,0 +1,63 @@
|
||||
package connectors
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/catalogue"
|
||||
)
|
||||
|
||||
// MirrorOptions configures offline mirroring of a signed extension catalogue.
|
||||
type MirrorOptions struct {
|
||||
From string
|
||||
VerifyPublicKey string
|
||||
DestDir string
|
||||
SignPrivateKey string
|
||||
Auth CatalogueAuth
|
||||
}
|
||||
|
||||
// MirrorResult describes the signed offline catalogue produced by MirrorCatalogue.
|
||||
type MirrorResult = catalogue.MirrorResult
|
||||
|
||||
// MirroredExtension describes one verified extension binary written to a mirror.
|
||||
type MirroredExtension = catalogue.MirroredExtension
|
||||
|
||||
// DefaultCatalogueSource returns the built-in Archipelago catalogue location
|
||||
// and base64 Ed25519 trust root.
|
||||
func DefaultCatalogueSource() (location, publicKey string) {
|
||||
return archipelagoLocation, archipelagoKey
|
||||
}
|
||||
|
||||
// GenerateCatalogueKeypair generates an Ed25519 signing keypair encoded as
|
||||
// base64 private seed and base64 public key.
|
||||
func GenerateCatalogueKeypair() (seedBase64, pubBase64 string, err error) {
|
||||
return catalogue.GenerateKeypair()
|
||||
}
|
||||
|
||||
// MirrorCatalogue verifies the upstream catalogue, downloads all extension
|
||||
// artifacts, and writes a re-signed offline mirror into opts.DestDir.
|
||||
func MirrorCatalogue(ctx context.Context, opts MirrorOptions) (MirrorResult, error) {
|
||||
from := opts.From
|
||||
pubStr := opts.VerifyPublicKey
|
||||
if from == "" {
|
||||
from = archipelagoLocation
|
||||
}
|
||||
if pubStr == "" {
|
||||
pubStr = archipelagoKey
|
||||
}
|
||||
verifyKey, err := catalogue.ParseKey(pubStr)
|
||||
if err != nil {
|
||||
return MirrorResult{}, fmt.Errorf("upstream public key: %w", err)
|
||||
}
|
||||
signKey, err := catalogue.ParsePrivateKey(opts.SignPrivateKey)
|
||||
if err != nil {
|
||||
return MirrorResult{}, fmt.Errorf("mirror signing key: %w", err)
|
||||
}
|
||||
credFn, err := opts.Auth.CredentialFunc()
|
||||
if err != nil {
|
||||
return MirrorResult{}, fmt.Errorf("registry auth: %w", err)
|
||||
}
|
||||
f := catalogue.NewFetcher("")
|
||||
f.Auth = credFn
|
||||
return f.MirrorToDir(ctx, from, opts.DestDir, verifyKey, signKey)
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"oras.land/oras-go/v2/registry/remote/auth"
|
||||
)
|
||||
|
||||
// RegistryAuth configures authentication for private OCI extension registries.
|
||||
type RegistryAuth struct {
|
||||
Username string
|
||||
Password string
|
||||
AuthFile string
|
||||
}
|
||||
|
||||
// Empty reports whether no registry authentication settings are configured.
|
||||
func (a RegistryAuth) Empty() bool {
|
||||
return strings.TrimSpace(a.Username) == "" &&
|
||||
strings.TrimSpace(a.Password) == "" &&
|
||||
strings.TrimSpace(a.AuthFile) == ""
|
||||
}
|
||||
|
||||
type dockerConfig struct {
|
||||
Auths map[string]dockerAuthEntry `json:"auths"`
|
||||
}
|
||||
|
||||
type dockerAuthEntry struct {
|
||||
Auth string `json:"auth"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
IdentityToken string `json:"identitytoken"`
|
||||
}
|
||||
|
||||
// CredentialFunc validates the configured authentication settings and returns
|
||||
// an oras credential resolver. A zero RegistryAuth yields nil with no error.
|
||||
func (a RegistryAuth) CredentialFunc() (auth.CredentialFunc, error) {
|
||||
if a.Empty() {
|
||||
return nil, nil
|
||||
}
|
||||
user := strings.TrimSpace(a.Username)
|
||||
pass := a.Password
|
||||
if (user != "") != (pass != "") {
|
||||
return nil, errors.New("catalogue registry username and password must be set together")
|
||||
}
|
||||
|
||||
var byHost map[string]auth.Credential
|
||||
if path := strings.TrimSpace(a.AuthFile); path != "" {
|
||||
var err error
|
||||
byHost, err = loadDockerAuths(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return func(_ context.Context, hostport string) (auth.Credential, error) {
|
||||
if user != "" {
|
||||
return auth.Credential{Username: user, Password: pass}, nil
|
||||
}
|
||||
if len(byHost) == 0 {
|
||||
return auth.EmptyCredential, nil
|
||||
}
|
||||
key := normaliseRegistryKey(hostport)
|
||||
if cred, ok := byHost[key]; ok {
|
||||
return cred, nil
|
||||
}
|
||||
if key == "registry-1.docker.io" {
|
||||
if cred, ok := byHost["index.docker.io"]; ok {
|
||||
return cred, nil
|
||||
}
|
||||
}
|
||||
return auth.EmptyCredential, nil
|
||||
}, nil
|
||||
}
|
||||
|
||||
func loadDockerAuths(path string) (map[string]auth.Credential, error) {
|
||||
raw, err := os.ReadFile(filepath.Clean(path)) //nolint:gosec // operator-configured Docker auth file path
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read catalogue auth file %s: %w", path, err)
|
||||
}
|
||||
var cfg dockerConfig
|
||||
if err := json.Unmarshal(raw, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("parse catalogue auth file %s: %w", path, err)
|
||||
}
|
||||
out := make(map[string]auth.Credential, len(cfg.Auths))
|
||||
for rawHost, entry := range cfg.Auths {
|
||||
host := normaliseRegistryKey(rawHost)
|
||||
if host == "" {
|
||||
continue
|
||||
}
|
||||
cred, err := decodeDockerAuth(host, entry)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("catalogue auth file %s: %w", path, err)
|
||||
}
|
||||
if cred != auth.EmptyCredential {
|
||||
out[host] = cred
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func decodeDockerAuth(host string, entry dockerAuthEntry) (auth.Credential, error) {
|
||||
if entry.Username != "" || entry.Password != "" {
|
||||
return auth.Credential{Username: entry.Username, Password: entry.Password}, nil
|
||||
}
|
||||
if entry.Auth != "" {
|
||||
decoded, err := base64.StdEncoding.DecodeString(strings.TrimSpace(entry.Auth))
|
||||
if err != nil {
|
||||
return auth.EmptyCredential, fmt.Errorf("registry %s: invalid base64 auth: %w", host, err)
|
||||
}
|
||||
user, pass, ok := strings.Cut(string(decoded), ":")
|
||||
if !ok {
|
||||
return auth.EmptyCredential, fmt.Errorf("registry %s: auth entry must be username:password", host)
|
||||
}
|
||||
return auth.Credential{Username: user, Password: pass}, nil
|
||||
}
|
||||
if entry.IdentityToken != "" {
|
||||
return auth.Credential{RefreshToken: entry.IdentityToken}, nil
|
||||
}
|
||||
return auth.EmptyCredential, nil
|
||||
}
|
||||
|
||||
func normaliseRegistryKey(raw string) string {
|
||||
key := strings.TrimSpace(raw)
|
||||
if key == "" {
|
||||
return ""
|
||||
}
|
||||
if strings.Contains(key, "://") {
|
||||
if u, err := url.Parse(key); err == nil && u.Host != "" {
|
||||
return strings.ToLower(u.Host)
|
||||
}
|
||||
}
|
||||
host, _, _ := strings.Cut(key, "/")
|
||||
return strings.ToLower(strings.TrimSpace(host))
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
digest "github.com/opencontainers/go-digest"
|
||||
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
|
||||
"oras.land/oras-go/v2/registry/remote/auth"
|
||||
)
|
||||
|
||||
func TestRegistryAuthCredentialFunc(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
authJSON := filepath.Join(dir, "config.json")
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte("robot:secret-pass"))
|
||||
if err := os.WriteFile(authJSON, []byte(`{
|
||||
"auths": {
|
||||
"https://registry.internal:5000/v2/": {"auth": "`+encoded+`"},
|
||||
"ghcr.io": {"username": "gh-user", "password": "gh-token"},
|
||||
"https://index.docker.io/v1/": {"username": "hub-user", "password": "hub-pass"}
|
||||
}
|
||||
}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
badJSON := filepath.Join(dir, "bad.json")
|
||||
if err := os.WriteFile(badJSON, []byte(`{not json`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Run("empty config returns nil", func(t *testing.T) {
|
||||
fn, err := (RegistryAuth{}).CredentialFunc()
|
||||
if err != nil || fn != nil {
|
||||
t.Fatalf("got (%v, %v), want (nil, nil)", fn != nil, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("partial static credentials fail closed", func(t *testing.T) {
|
||||
if _, err := (RegistryAuth{Username: "alice"}).CredentialFunc(); err == nil {
|
||||
t.Fatal("expected error for username without password")
|
||||
}
|
||||
if _, err := (RegistryAuth{Password: "secret"}).CredentialFunc(); err == nil {
|
||||
t.Fatal("expected error for password without username")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("bad auth file fails closed", func(t *testing.T) {
|
||||
if _, err := (RegistryAuth{AuthFile: badJSON}).CredentialFunc(); err == nil {
|
||||
t.Fatal("expected error for invalid JSON auth file")
|
||||
}
|
||||
if _, err := (RegistryAuth{AuthFile: filepath.Join(dir, "missing.json")}).CredentialFunc(); err == nil {
|
||||
t.Fatal("expected error for missing auth file")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("static credentials override auth file", func(t *testing.T) {
|
||||
fn, err := (RegistryAuth{Username: "static", Password: "pw", AuthFile: authJSON}).CredentialFunc()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := fn(t.Context(), "ghcr.io")
|
||||
if err != nil || got.Username != "static" || got.Password != "pw" {
|
||||
t.Fatalf("got (%+v, %v), want static/pw", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("docker config lookup normalises schemes and aliases", func(t *testing.T) {
|
||||
fn, err := (RegistryAuth{AuthFile: authJSON}).CredentialFunc()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cases := []struct {
|
||||
host string
|
||||
wantUser string
|
||||
wantPass string
|
||||
}{
|
||||
{"registry.internal:5000", "robot", "secret-pass"},
|
||||
{"ghcr.io", "gh-user", "gh-token"},
|
||||
{"registry-1.docker.io", "hub-user", "hub-pass"},
|
||||
{"unknown.example", "", ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got, err := fn(t.Context(), tc.host)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", tc.host, err)
|
||||
}
|
||||
if got.Username != tc.wantUser || got.Password != tc.wantPass {
|
||||
t.Fatalf("%s: got (%q, %q), want (%q, %q)", tc.host, got.Username, got.Password, tc.wantUser, tc.wantPass)
|
||||
}
|
||||
}
|
||||
if cred, _ := fn(t.Context(), "unknown.example"); cred != auth.EmptyCredential {
|
||||
t.Fatalf("unmatched host returned %+v, want EmptyCredential", cred)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestReadOCISendsRegistryAuth(t *testing.T) {
|
||||
key, signer, err := ed25519.GenerateKey(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const metadata = `apiVersion: dev.archie.package.v1
|
||||
version: 1.0.0
|
||||
contributes:
|
||||
extensions:
|
||||
- surface: guard
|
||||
path: bin/hours
|
||||
files:
|
||||
- path: bin/hours
|
||||
mode: 493`
|
||||
pkg := testManifest(t, []byte("example"), map[string]string{packageDescriptor: metadata})
|
||||
pin := digest.FromBytes(pkg)
|
||||
wantAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte("oci-user:oci-pass"))
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != wantAuth {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="registry"`)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
body := fmt.Appendf(nil, `{"issued_at":"2026-11-23T00:00:00Z","packages":[{"name":"hours","surface":"guards","version":"1.0.0","reference":"%s/guards-hours","digest":"%s"}]}`, r.Host, pin)
|
||||
sig := base64.StdEncoding.EncodeToString(ed25519.Sign(signer, body))
|
||||
media := ocispec.MediaTypeImageManifest
|
||||
var result []byte
|
||||
switch r.URL.Path {
|
||||
case "/v2/catalogue/manifests/latest":
|
||||
result = testManifest(t, body, map[string]string{catalogueSignature: sig})
|
||||
case "/v2/catalogue/blobs/" + digest.FromBytes(body).String():
|
||||
media, result = "application/octet-stream", body
|
||||
case "/v2/guards-hours/manifests/" + pin.String():
|
||||
result = pkg
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", media)
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(result)))
|
||||
w.Header().Set("Docker-Content-Digest", digest.FromBytes(result).String())
|
||||
_, _ = w.Write(result)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
credFn, err := (RegistryAuth{Username: "oci-user", Password: "oci-pass"}).CredentialFunc()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := NewFetcher(t.TempDir())
|
||||
f.Auth = credFn
|
||||
doc, err := f.Read(t.Context(), strings.TrimPrefix(srv.URL, "http://")+"/catalogue", key)
|
||||
if err != nil {
|
||||
t.Fatalf("Read protected OCI catalogue: %v", err)
|
||||
}
|
||||
if _, ok := doc.Entry("hours"); !ok {
|
||||
t.Fatal("missing hours entry from protected OCI catalogue")
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"oras.land/oras-go/v2/registry/remote/auth"
|
||||
)
|
||||
|
||||
// ErrDigestMismatch means an artifact is not the binary the catalogue pins.
|
||||
@@ -29,12 +31,13 @@ const (
|
||||
maxDocument = 1 << 20
|
||||
)
|
||||
|
||||
// Fetcher reads catalogues and artifacts from an https URL or from a path on
|
||||
// this host.
|
||||
// Fetcher reads catalogues and artifacts from an OCI repository, https URL,
|
||||
// or path on this host.
|
||||
type Fetcher struct {
|
||||
// Dir is where verified artifacts are kept, one directory per digest.
|
||||
Dir string
|
||||
Client *http.Client
|
||||
Auth auth.CredentialFunc
|
||||
}
|
||||
|
||||
// NewFetcher returns a Fetcher that keeps artifacts under dir.
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// MirrorResult describes the signed offline catalogue written by MirrorToDir.
|
||||
type MirrorResult struct {
|
||||
IssuedAt time.Time `json:"issued_at"`
|
||||
CataloguePath string `json:"catalogue_path"`
|
||||
SignaturePath string `json:"signature_path"`
|
||||
Mirrored []MirroredExtension `json:"mirrored"`
|
||||
}
|
||||
|
||||
// MirroredExtension records one extension binary included in the offline mirror.
|
||||
type MirroredExtension struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Contract string `json:"contract"`
|
||||
Digest string `json:"digest"`
|
||||
Artifact string `json:"artifact"`
|
||||
}
|
||||
|
||||
// GenerateKeypair creates a fresh Ed25519 signing keypair encoded as base64
|
||||
// seed (private) and base64 public key.
|
||||
func GenerateKeypair() (seedBase64, pubBase64 string, err error) {
|
||||
pub, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("generate Ed25519 keypair: %w", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(priv.Seed()), base64.StdEncoding.EncodeToString(pub), nil
|
||||
}
|
||||
|
||||
// ParsePrivateKey decodes a base64 Ed25519 private key (either a 32-byte seed
|
||||
// or a 64-byte expanded private key).
|
||||
func ParsePrivateKey(s string) (ed25519.PrivateKey, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(s))
|
||||
if err != nil {
|
||||
return nil, errors.New("the signing key must be base64 Ed25519 material")
|
||||
}
|
||||
switch len(raw) {
|
||||
case ed25519.SeedSize:
|
||||
return ed25519.NewKeyFromSeed(raw), nil
|
||||
case ed25519.PrivateKeySize:
|
||||
return ed25519.PrivateKey(raw), nil
|
||||
default:
|
||||
return nil, errors.New("the signing key must be a 32-byte seed or 64-byte private key")
|
||||
}
|
||||
}
|
||||
|
||||
// MirrorToDir downloads and verifies a signed catalogue and all of its extension
|
||||
// binaries from src, copies them into destDir, and emits a re-signed offline
|
||||
// catalogue.json and catalogue.json.sig for air-gapped stages.
|
||||
func (f *Fetcher) MirrorToDir(ctx context.Context, src, destDir string, verifyKey ed25519.PublicKey, signKey ed25519.PrivateKey) (MirrorResult, error) {
|
||||
if destDir == "" {
|
||||
return MirrorResult{}, errors.New("destination directory is required")
|
||||
}
|
||||
if len(verifyKey) != ed25519.PublicKeySize {
|
||||
return MirrorResult{}, errors.New("valid upstream Ed25519 public key is required")
|
||||
}
|
||||
if len(signKey) != ed25519.PrivateKeySize {
|
||||
return MirrorResult{}, errors.New("valid internal Ed25519 private key is required")
|
||||
}
|
||||
|
||||
doc, err := f.Read(ctx, src, verifyKey)
|
||||
if err != nil {
|
||||
return MirrorResult{}, fmt.Errorf("read upstream catalogue %s: %w", src, err)
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(destDir, 0o750); err != nil {
|
||||
return MirrorResult{}, fmt.Errorf("create mirror directory: %w", err)
|
||||
}
|
||||
stagingDir, err := os.MkdirTemp(destDir, ".mirror-stage-*")
|
||||
if err != nil {
|
||||
return MirrorResult{}, fmt.Errorf("create staging directory: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(stagingDir) }()
|
||||
|
||||
stageFetcher := &Fetcher{Dir: stagingDir, Client: f.Client, Auth: f.Auth}
|
||||
outDoc := Document{
|
||||
IssuedAt: doc.IssuedAt,
|
||||
Extensions: make([]Entry, 0, len(doc.Extensions)),
|
||||
}
|
||||
var mirrored []MirroredExtension
|
||||
|
||||
for _, entry := range doc.Extensions {
|
||||
outEntry, items, err := stageFetcher.mirrorEntry(ctx, src, destDir, entry)
|
||||
if err != nil {
|
||||
return MirrorResult{}, err
|
||||
}
|
||||
outDoc.Extensions = append(outDoc.Extensions, outEntry)
|
||||
mirrored = append(mirrored, items...)
|
||||
}
|
||||
|
||||
body, err := json.Marshal(outDoc)
|
||||
if err != nil {
|
||||
return MirrorResult{}, fmt.Errorf("encode mirrored catalogue: %w", err)
|
||||
}
|
||||
sig := base64.StdEncoding.EncodeToString(ed25519.Sign(signKey, body))
|
||||
catPath := filepath.Join(destDir, "catalogue.json")
|
||||
sigPath := filepath.Join(destDir, "catalogue.json.sig")
|
||||
if err := writeAtomic(catPath, body, 0o600); err != nil {
|
||||
return MirrorResult{}, err
|
||||
}
|
||||
if err := writeAtomic(sigPath, append([]byte(sig), '\n'), 0o600); err != nil {
|
||||
return MirrorResult{}, err
|
||||
}
|
||||
return MirrorResult{
|
||||
IssuedAt: doc.IssuedAt,
|
||||
CataloguePath: catPath,
|
||||
SignaturePath: sigPath,
|
||||
Mirrored: mirrored,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *Fetcher) mirrorEntry(ctx context.Context, src, destDir string, entry Entry) (Entry, []MirroredExtension, error) {
|
||||
if !entryName.MatchString(entry.Name) {
|
||||
return Entry{}, nil, fmt.Errorf("extension name %q is invalid", entry.Name)
|
||||
}
|
||||
versions := make([]Version, 0, len(entry.Versions))
|
||||
mirrored := make([]MirroredExtension, 0, len(entry.Versions))
|
||||
for _, v := range entry.Versions {
|
||||
if err := checkMirrorSegment(v.Version); err != nil {
|
||||
return Entry{}, nil, fmt.Errorf("extension %s version %q: %w", entry.Name, v.Version, err)
|
||||
}
|
||||
fetchedPath, digestHex, err := f.FetchVersion(ctx, entry.Name, src, v)
|
||||
if err != nil {
|
||||
return Entry{}, nil, fmt.Errorf("fetch %s %s: %w", entry.Name, v.Version, err)
|
||||
}
|
||||
relArtifact := path.Join("artifacts", entry.Name, v.Version, entry.Name)
|
||||
targetPath := filepath.Join(destDir, filepath.FromSlash(relArtifact))
|
||||
if err := copyVerifiedExecutable(fetchedPath, targetPath, digestHex); err != nil {
|
||||
return Entry{}, nil, fmt.Errorf("stage %s %s: %w", entry.Name, v.Version, err)
|
||||
}
|
||||
versions = append(versions, Version{
|
||||
Version: v.Version,
|
||||
Artifact: relArtifact,
|
||||
Digest: digestHex,
|
||||
Grants: v.Grants,
|
||||
Settings: v.Settings,
|
||||
})
|
||||
mirrored = append(mirrored, MirroredExtension{
|
||||
Name: entry.Name,
|
||||
Version: v.Version,
|
||||
Contract: entry.Contract,
|
||||
Digest: digestHex,
|
||||
Artifact: relArtifact,
|
||||
})
|
||||
}
|
||||
entry.Versions = versions
|
||||
return entry, mirrored, nil
|
||||
}
|
||||
|
||||
func checkMirrorSegment(segment string) error {
|
||||
if segment == "" || segment == "." || segment == ".." || strings.ContainsAny(segment, `/\`) {
|
||||
return errors.New("version contains a forbidden path segment")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func copyVerifiedExecutable(srcPath, dstPath, wantDigest string) error {
|
||||
if err := os.MkdirAll(filepath.Dir(dstPath), 0o750); err != nil {
|
||||
return err
|
||||
}
|
||||
src, err := os.Open(filepath.Clean(srcPath))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = src.Close() }()
|
||||
|
||||
tmp, err := os.CreateTemp(filepath.Dir(dstPath), ".bin-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer func() { _ = os.Remove(tmpName) }()
|
||||
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(io.MultiWriter(tmp, h), src); err != nil {
|
||||
_ = tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if hex.EncodeToString(h.Sum(nil)) != wantDigest {
|
||||
return ErrDigestMismatch
|
||||
}
|
||||
if err := os.Chmod(tmpName, 0o700); err != nil { //nolint:gosec // mirrored extension binary must be executable
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmpName, dstPath)
|
||||
}
|
||||
|
||||
func writeAtomic(dstPath string, data []byte, mode os.FileMode) error {
|
||||
tmp, err := os.CreateTemp(filepath.Dir(dstPath), ".tmp-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("write %s: %w", dstPath, err)
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer func() { _ = os.Remove(tmpName) }()
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("write %s: %w", dstPath, err)
|
||||
}
|
||||
if err := tmp.Chmod(mode); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("chmod %s: %w", dstPath, err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return fmt.Errorf("close %s: %w", dstPath, err)
|
||||
}
|
||||
if err := os.Rename(tmpName, dstPath); err != nil {
|
||||
return fmt.Errorf("rename %s: %w", dstPath, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMirrorToDirOfflineVerification(t *testing.T) {
|
||||
upPub, upPriv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wrongPub, _, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedB64, mirrorPubB64, err := GenerateKeypair()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mirrorSignKey, err := ParsePrivateKey(seedB64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mirrorPubKey, err := ParseKey(mirrorPubB64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
upstreamDir := t.TempDir()
|
||||
binBytes := []byte("#!/bin/sh\necho mirrored\n")
|
||||
sum := sha256.Sum256(binBytes)
|
||||
digestHex := hex.EncodeToString(sum[:])
|
||||
binPath := filepath.Join(upstreamDir, "vault-bin")
|
||||
if err := os.WriteFile(binPath, binBytes, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
body := []byte(`{"issued_at":"2026-11-27T00:00:00Z","extensions":[{"name":"vault","display_name":"Vault","description":"KV secrets","contract":"secretengine","versions":[{"version":"1.2.0","artifact":"vault-bin","digest":"` + digestHex + `"}]}]}`)
|
||||
catFile := filepath.Join(upstreamDir, "catalogue.json")
|
||||
if err := os.WriteFile(catFile, body, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sigFile := catFile + ".sig"
|
||||
if err := os.WriteFile(sigFile, []byte(base64.StdEncoding.EncodeToString(ed25519.Sign(upPriv, body))), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
fetcher := NewFetcher("")
|
||||
mirrorDir := filepath.Join(t.TempDir(), "airgap")
|
||||
|
||||
// A forged upstream signature must fail closed before writing anything.
|
||||
if _, err := fetcher.MirrorToDir(t.Context(), catFile, mirrorDir, mirrorPubKey, mirrorSignKey); !errors.Is(err, ErrBadSignature) {
|
||||
t.Fatalf("expected ErrBadSignature with wrong key, got %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(mirrorDir, "catalogue.json")); !os.IsNotExist(err) {
|
||||
t.Fatalf("failed mirror created catalogue.json")
|
||||
}
|
||||
|
||||
res, err := fetcher.MirrorToDir(t.Context(), catFile, mirrorDir, upPub, mirrorSignKey)
|
||||
if err != nil {
|
||||
t.Fatalf("MirrorToDir: %v", err)
|
||||
}
|
||||
if len(res.Mirrored) != 1 || res.Mirrored[0].Digest != digestHex {
|
||||
t.Fatalf("unexpected mirror result: %+v", res)
|
||||
}
|
||||
|
||||
// Delete the upstream source completely to prove offline independence.
|
||||
if err := os.RemoveAll(upstreamDir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
offline := NewFetcher(filepath.Join(t.TempDir(), "installed"))
|
||||
doc, err := offline.Read(t.Context(), res.CataloguePath, mirrorPubKey)
|
||||
if err != nil {
|
||||
t.Fatalf("offline Read: %v", err)
|
||||
}
|
||||
entry, ok := doc.Entry("vault")
|
||||
if !ok {
|
||||
t.Fatal("mirrored catalogue missing vault")
|
||||
}
|
||||
v, ok := entry.Version("1.2.0")
|
||||
if !ok {
|
||||
t.Fatal("mirrored catalogue missing version 1.2.0")
|
||||
}
|
||||
gotPath, gotDigest, err := offline.FetchVersion(t.Context(), entry.Name, res.CataloguePath, v)
|
||||
if err != nil {
|
||||
t.Fatalf("offline FetchVersion: %v", err)
|
||||
}
|
||||
if gotDigest != digestHex {
|
||||
t.Fatalf("FetchVersion digest = %q, want %q", gotDigest, digestHex)
|
||||
}
|
||||
gotBytes, err := os.ReadFile(gotPath) //nolint:gosec // test fixture output under t.TempDir
|
||||
if err != nil || string(gotBytes) != string(binBytes) {
|
||||
t.Fatalf("mirrored binary mismatch: %v", err)
|
||||
}
|
||||
|
||||
// Ensure wrongPub still rejects against the newly signed mirror.
|
||||
if _, err := offline.Read(t.Context(), res.CataloguePath, wrongPub); !errors.Is(err, ErrBadSignature) {
|
||||
t.Fatalf("expected ErrBadSignature with wrong key on mirror, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,7 @@ func (f *Fetcher) repository(loc string) (*remote.Repository, error) {
|
||||
host = hostname
|
||||
}
|
||||
r.PlainHTTP = loopback(strings.Trim(host, "[]"))
|
||||
r.Client = &auth.Client{Client: f.Client, Cache: auth.NewCache()}
|
||||
r.Client = &auth.Client{Client: f.Client, Credential: f.Auth, Cache: auth.NewCache()}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,23 @@ func (m *Module) UseRemotes(cfg RemoteConfig) error {
|
||||
return m.host.UseRemotes(cfg)
|
||||
}
|
||||
|
||||
// CatalogueAuth configures private OCI registry authentication for fetching
|
||||
// the extension catalogue and artifacts.
|
||||
type CatalogueAuth = catalogue.RegistryAuth
|
||||
|
||||
// UseCatalogueAuth configures private OCI registry authentication for the
|
||||
// catalogue fetcher.
|
||||
func (m *Module) UseCatalogueAuth(cfg CatalogueAuth) error {
|
||||
credFn, err := cfg.CredentialFunc()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m.pkgMu.Lock()
|
||||
m.fetcher.Auth = credFn
|
||||
m.pkgMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// UseDefaultCatalogue overrides the fallback extension catalogue source used
|
||||
// when the control plane has not set a custom location.
|
||||
func (m *Module) UseDefaultCatalogue(location, publicKey string) error {
|
||||
|
||||
Reference in new issue
Block a user