feat(release): sign checksums and publish an SBOM #132
No files matched your search
@@ -37,8 +37,19 @@ jobs:
|
||||
cp LICENSE README.md .env.example "dist/$dir/"
|
||||
tar -C dist -czf "dist/$dir.tar.gz" "$dir"
|
||||
done
|
||||
(cd dist && sha256sum ./*.tar.gz | sed 's| \./| |' > SHA256SUMS)
|
||||
go run ./tools/release sbom "$GITHUB_REF_NAME" dist/uptimesebi_*_linux_amd64/{api,checker,statuspage} > dist/sbom.spdx.json
|
||||
(cd dist && sha256sum ./*.tar.gz ./sbom.spdx.json | sed 's| \./| |' > SHA256SUMS)
|
||||
cat dist/SHA256SUMS
|
||||
- name: Sign checksums
|
||||
env:
|
||||
RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }}
|
||||
run: |
|
||||
if [ -z "$RELEASE_SIGNING_KEY" ]; then
|
||||
echo "::warning::RELEASE_SIGNING_KEY is not set; the release is not signed."
|
||||
exit 0
|
||||
fi
|
||||
go run ./tools/release sign dist/SHA256SUMS "$GITHUB_REF_NAME"
|
||||
go run ./tools/release verify dist/SHA256SUMS
|
||||
- name: Publish release
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
@@ -52,7 +63,8 @@ jobs:
|
||||
go run ./tools/release notes -json "$GITHUB_REF_NAME" > release.json
|
||||
id="$(curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
--data-binary @release.json "$api/releases" | grep -o '"id":[0-9]*' | head -n1 | cut -d: -f2)"
|
||||
for f in dist/*.tar.gz dist/SHA256SUMS; do
|
||||
for f in dist/*.tar.gz dist/sbom.spdx.json dist/SHA256SUMS dist/SHA256SUMS.minisig; do
|
||||
[ -f "$f" ] || continue
|
||||
curl -fsS -o /dev/null -X POST -H "Authorization: token $TOKEN" \
|
||||
-F "attachment=@$f" "$api/releases/$id/assets?name=$(basename "$f")"
|
||||
done
|
||||
@@ -77,7 +77,14 @@ One image contains all three commands; `api` is the default entrypoint. Images a
|
||||
| `beta` | the newest prerelease (`1.5.0-beta.N`) |
|
||||
| `edge` | every commit on `main` |
|
||||
|
||||
Each [release](https://git.zb-server.de/ZB-Server/uptimesebi/releases) also carries Linux binaries (amd64, arm64) with checksums and the changelog. Or build the image yourself:
|
||||
Each [release](https://git.zb-server.de/ZB-Server/uptimesebi/releases) also carries Linux binaries (amd64, arm64), the changelog, an SPDX SBOM (`sbom.spdx.json`: Go modules and bundled npm packages) and checksums signed with [minisign](https://jedisct1.github.io/minisign/). Verify a download with:
|
||||
|
||||
```sh
|
||||
minisign -Vm SHA256SUMS -P RWRrmAkTu/xZg/o8QCsko5rUujqW/N165cj+dyEcp5CDXPTE2jKbLkyA
|
||||
sha256sum -c --ignore-missing SHA256SUMS
|
||||
```
|
||||
|
||||
The trusted comment names the release, so a signature cannot be passed off for another one. Or build the image yourself:
|
||||
|
||||
```sh
|
||||
docker build -t uptimesebi .
|
||||
@@ -166,7 +173,7 @@ make lint
|
||||
|
||||
The tests run against the `uptime_test` database and Redis database 15 from [`.env.example`](.env.example). CI runs lint, tests, builds and the image for every pull request ([`.gitea/workflows/ci.yaml`](.gitea/workflows/ci.yaml)).
|
||||
|
||||
Commits follow [Conventional Commits](https://www.conventionalcommits.org/), which decide the version: `make release` tags the next one on `main` (breaking changes move the major version, before 1.0 the minor one; `feat` the minor, `fix` and `perf` the patch version), `make release CHANNEL=beta` the next prerelease. Pushing the tag publishes the release with its changelog ([`.gitea/workflows/release.yaml`](.gitea/workflows/release.yaml)). Code comments, commits and issues are in English; the interface is translated (English and German, `internal/i18n/locales`).
|
||||
Commits follow [Conventional Commits](https://www.conventionalcommits.org/), which decide the version: `make release` tags the next one on `main` (breaking changes move the major version, before 1.0 the minor one; `feat` the minor, `fix` and `perf` the patch version), `make release CHANNEL=beta` the next prerelease. Pushing the tag publishes the release with its changelog ([`.gitea/workflows/release.yaml`](.gitea/workflows/release.yaml)), signed with the key in the `RELEASE_SIGNING_KEY` secret. To rotate it, create a key with `go run ./tools/release keygen <file>`, add the printed public key to [`internal/signing/release.pub`](internal/signing/release.pub) (keep the old one, so self-updating agents can update across the change) and replace the secret. Code comments, commits and issues are in English; the interface is translated (English and German, `internal/i18n/locales`).
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# Keys that sign UptimeSebi releases, one per line. Keep retired keys
|
||||
# listed so agents can update across a rotation.
|
||||
untrusted comment: uptimesebi release key 8359FCBB1309986B
|
||||
RWRrmAkTu/xZg/o8QCsko5rUujqW/N165cj+dyEcp5CDXPTE2jKbLkyA
|
||||
@@ -0,0 +1,193 @@
|
||||
// Package signing signs and verifies release files in the minisign format,
|
||||
// so that anyone can check a release with the minisign tool and the
|
||||
// self-updating agents can check what they download.
|
||||
//
|
||||
// Only prehashed signatures (algorithm "ED": Ed25519 over the BLAKE2b-512
|
||||
// hash of the file) are produced and accepted.
|
||||
package signing
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
_ "embed"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/blake2b"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrSignature reports a signature that does not match.
|
||||
ErrSignature = errors.New("signing: signature does not match")
|
||||
// ErrUnknownKey reports a signature made with a key not trusted.
|
||||
ErrUnknownKey = errors.New("signing: signed with an unknown key")
|
||||
)
|
||||
|
||||
const (
|
||||
keyAlg = "Ed"
|
||||
prehashedAlg = "ED"
|
||||
idLen = 8
|
||||
)
|
||||
|
||||
// PublicKey is a minisign public key.
|
||||
type PublicKey struct {
|
||||
ID [idLen]byte
|
||||
Key ed25519.PublicKey
|
||||
}
|
||||
|
||||
// PrivateKey is a signing key with the ID of its public key.
|
||||
type PrivateKey struct {
|
||||
ID [idLen]byte
|
||||
Key ed25519.PrivateKey
|
||||
}
|
||||
|
||||
// Public returns the key that verifies k's signatures.
|
||||
func (k PrivateKey) Public() PublicKey {
|
||||
return PublicKey{ID: k.ID, Key: k.Key.Public().(ed25519.PublicKey)}
|
||||
}
|
||||
|
||||
// String encodes the key like minisign does on the second line of a .pub
|
||||
// file.
|
||||
func (k PublicKey) String() string {
|
||||
raw := append(append([]byte(keyAlg), k.ID[:]...), k.Key...)
|
||||
return base64.StdEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
// IDString is the key ID as minisign prints it.
|
||||
func (k PublicKey) IDString() string {
|
||||
var b strings.Builder
|
||||
for i := idLen - 1; i >= 0; i-- {
|
||||
fmt.Fprintf(&b, "%02X", k.ID[i])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// ParsePublicKey reads a key in minisign's encoding.
|
||||
func ParsePublicKey(s string) (PublicKey, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(s))
|
||||
if err != nil || len(raw) != 2+idLen+ed25519.PublicKeySize || string(raw[:2]) != keyAlg {
|
||||
return PublicKey{}, errors.New("signing: not a minisign public key")
|
||||
}
|
||||
var k PublicKey
|
||||
copy(k.ID[:], raw[2:])
|
||||
k.Key = ed25519.PublicKey(raw[2+idLen:])
|
||||
return k, nil
|
||||
}
|
||||
|
||||
// ParsePublicKeys reads one key per line, skipping blank lines, comments
|
||||
// starting with # and minisign's "untrusted comment:" lines.
|
||||
func ParsePublicKeys(text string) ([]PublicKey, error) {
|
||||
var keys []PublicKey
|
||||
for line := range strings.Lines(text) {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "untrusted comment:") {
|
||||
continue
|
||||
}
|
||||
k, err := ParsePublicKey(line)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keys = append(keys, k)
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
// GenerateKey creates a new signing key.
|
||||
func GenerateKey() (PrivateKey, error) {
|
||||
_, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return PrivateKey{}, err
|
||||
}
|
||||
k := PrivateKey{Key: priv}
|
||||
if _, err := rand.Read(k.ID[:]); err != nil {
|
||||
return PrivateKey{}, err
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
// String encodes the key for storage in a secret: base64 of the key ID and
|
||||
// the Ed25519 seed. It is not minisign's encrypted key format.
|
||||
func (k PrivateKey) String() string {
|
||||
return base64.StdEncoding.EncodeToString(append(k.ID[:], k.Key.Seed()...))
|
||||
}
|
||||
|
||||
// ParsePrivateKey reads a key written by PrivateKey.String.
|
||||
func ParsePrivateKey(s string) (PrivateKey, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(s))
|
||||
if err != nil || len(raw) != idLen+ed25519.SeedSize {
|
||||
return PrivateKey{}, errors.New("signing: not a signing key")
|
||||
}
|
||||
var k PrivateKey
|
||||
copy(k.ID[:], raw)
|
||||
k.Key = ed25519.NewKeyFromSeed(raw[idLen:])
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func digest(msg []byte) []byte {
|
||||
sum := blake2b.Sum512(msg)
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
// Sign returns a minisign signature file for msg. The trusted comment is
|
||||
// signed too; it must be a single line.
|
||||
func Sign(k PrivateKey, msg []byte, trusted string) ([]byte, error) {
|
||||
if strings.ContainsAny(trusted, "\r\n") {
|
||||
return nil, errors.New("signing: the trusted comment must be one line")
|
||||
}
|
||||
sig := ed25519.Sign(k.Key, digest(msg))
|
||||
global := ed25519.Sign(k.Key, append(append([]byte{}, sig...), trusted...))
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "untrusted comment: signature from uptimesebi release key %s\n", k.Public().IDString())
|
||||
b.WriteString(base64.StdEncoding.EncodeToString(append(append([]byte(prehashedAlg), k.ID[:]...), sig...)) + "\n")
|
||||
b.WriteString("trusted comment: " + trusted + "\n")
|
||||
b.WriteString(base64.StdEncoding.EncodeToString(global) + "\n")
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
// Verify checks a minisign signature file for msg against the trusted
|
||||
// keys and returns its trusted comment.
|
||||
func Verify(keys []PublicKey, msg, sigFile []byte) (string, error) {
|
||||
lines := strings.Split(strings.TrimRight(string(sigFile), "\n"), "\n")
|
||||
if len(lines) != 4 || !strings.HasPrefix(lines[0], "untrusted comment:") || !strings.HasPrefix(lines[2], "trusted comment: ") {
|
||||
return "", errors.New("signing: not a minisign signature")
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(lines[1]))
|
||||
if err != nil || len(raw) != 2+idLen+ed25519.SignatureSize {
|
||||
return "", errors.New("signing: not a minisign signature")
|
||||
}
|
||||
if string(raw[:2]) != prehashedAlg {
|
||||
return "", errors.New("signing: only prehashed signatures are accepted")
|
||||
}
|
||||
global, err := base64.StdEncoding.DecodeString(strings.TrimSpace(lines[3]))
|
||||
if err != nil || len(global) != ed25519.SignatureSize {
|
||||
return "", errors.New("signing: not a minisign signature")
|
||||
}
|
||||
sig := raw[2+idLen:]
|
||||
trusted := strings.TrimSuffix(strings.TrimPrefix(lines[2], "trusted comment: "), "\r")
|
||||
for _, k := range keys {
|
||||
if !bytes.Equal(k.ID[:], raw[2:2+idLen]) {
|
||||
continue
|
||||
}
|
||||
if !ed25519.Verify(k.Key, digest(msg), sig) || !ed25519.Verify(k.Key, append(append([]byte{}, sig...), trusted...), global) {
|
||||
return "", ErrSignature
|
||||
}
|
||||
return trusted, nil
|
||||
}
|
||||
return "", ErrUnknownKey
|
||||
}
|
||||
|
||||
//go:embed release.pub
|
||||
var releaseKeys string
|
||||
|
||||
// ReleaseKeys are the keys that sign UptimeSebi releases. Old keys stay
|
||||
// listed after a rotation so that agents can update across it.
|
||||
func ReleaseKeys() []PublicKey {
|
||||
keys, err := ParsePublicKeys(releaseKeys)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package signing
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSignVerify(t *testing.T) {
|
||||
k, err := GenerateKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pub := k.Public()
|
||||
msg := []byte("abc uptimesebi_1.0.0_linux_amd64.tar.gz\n")
|
||||
sig, err := Sign(k, msg, "v1.0.0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := Verify([]PublicKey{pub}, msg, sig); err != nil || got != "v1.0.0" {
|
||||
t.Fatalf("Verify = %q, %v", got, err)
|
||||
}
|
||||
|
||||
other, _ := GenerateKey()
|
||||
if _, err := Verify([]PublicKey{other.Public()}, msg, sig); !errors.Is(err, ErrUnknownKey) {
|
||||
t.Errorf("unknown key: %v", err)
|
||||
}
|
||||
if _, err := Verify([]PublicKey{other.Public(), pub}, msg, sig); err != nil {
|
||||
t.Errorf("rotated key list: %v", err)
|
||||
}
|
||||
if _, err := Verify([]PublicKey{pub}, append(msg, 'x'), sig); !errors.Is(err, ErrSignature) {
|
||||
t.Errorf("changed file: %v", err)
|
||||
}
|
||||
forged := bytes.Replace(sig, []byte("trusted comment: v1.0.0"), []byte("trusted comment: v9.0.0"), 1)
|
||||
if _, err := Verify([]PublicKey{pub}, msg, forged); !errors.Is(err, ErrSignature) {
|
||||
t.Errorf("changed trusted comment: %v", err)
|
||||
}
|
||||
if _, err := Sign(k, msg, "a\nb"); err == nil {
|
||||
t.Error("multi-line trusted comment accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncoding(t *testing.T) {
|
||||
k, _ := GenerateKey()
|
||||
back, err := ParsePrivateKey(k.String())
|
||||
if err != nil || back.ID != k.ID || !back.Key.Equal(k.Key) {
|
||||
t.Fatalf("private key round trip: %v", err)
|
||||
}
|
||||
keys, err := ParsePublicKeys("# comment\nuntrusted comment: minisign public key\n" + k.Public().String() + "\n\n")
|
||||
if err != nil || len(keys) != 1 || keys[0].ID != k.ID || !keys[0].Key.Equal(k.Public().Key) {
|
||||
t.Fatalf("public keys = %v, %v", keys, err)
|
||||
}
|
||||
if !strings.HasPrefix(k.Public().String(), "RW") {
|
||||
t.Errorf("public key %s does not look like minisign's", k.Public())
|
||||
}
|
||||
if _, err := ParsePublicKey("RWQ" + strings.Repeat("A", 10)); err == nil {
|
||||
t.Error("short key accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReleaseKeys(t *testing.T) {
|
||||
if len(ReleaseKeys()) == 0 {
|
||||
t.Error("no release key")
|
||||
}
|
||||
}
|
||||
+30
-1
@@ -5,6 +5,11 @@
|
||||
// release notes [-json] <tag> print the release notes of a tag, with
|
||||
// -json as the body of a Gitea release
|
||||
// release check <tag> fail unless tag is a valid release tag
|
||||
// release sbom <tag> <bin>... print the SPDX SBOM of a release
|
||||
// release sign <file> <tag> write file.minisig with the key in
|
||||
// RELEASE_SIGNING_KEY
|
||||
// release verify <file> check file.minisig against the release keys
|
||||
// release keygen <secret-file> create a signing key, print its public key
|
||||
//
|
||||
// Stable releases follow semantic versioning from the commits since the
|
||||
// last stable release: breaking changes move the major version (the minor
|
||||
@@ -21,7 +26,7 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
const usage = `usage: release next [stable|beta] | notes [-json] <tag> | check <tag>`
|
||||
const usage = `usage: release next [stable|beta] | notes [-json] <tag> | check <tag> | sbom <tag> <binary>... | sign <file> <tag> | verify <file> | keygen <secret-file>`
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args[1:]); err != nil {
|
||||
@@ -97,6 +102,30 @@ func run(args []string) error {
|
||||
}
|
||||
_, err := parseVersion(args[1])
|
||||
return err
|
||||
case "sbom":
|
||||
if len(args) < 3 {
|
||||
return usageError{}
|
||||
}
|
||||
v, err := parseVersion(args[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return writeSBOM(v, args[2:])
|
||||
case "sign":
|
||||
if len(args) != 3 {
|
||||
return usageError{}
|
||||
}
|
||||
return signFile(args[1], args[2])
|
||||
case "verify":
|
||||
if len(args) != 2 {
|
||||
return usageError{}
|
||||
}
|
||||
return verifyFile(args[1])
|
||||
case "keygen":
|
||||
if len(args) != 2 {
|
||||
return usageError{}
|
||||
}
|
||||
return keygen(args[1])
|
||||
default:
|
||||
return usageError{}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"debug/buildinfo"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SPDX 2.3, the subset needed to list the components of a release.
|
||||
type spdxDoc struct {
|
||||
SPDXVersion string `json:"spdxVersion"`
|
||||
DataLicense string `json:"dataLicense"`
|
||||
SPDXID string `json:"SPDXID"`
|
||||
Name string `json:"name"`
|
||||
DocumentNamespace string `json:"documentNamespace"`
|
||||
CreationInfo spdxCreation `json:"creationInfo"`
|
||||
Packages []spdxPackage `json:"packages"`
|
||||
Relationships []spdxRelationship `json:"relationships"`
|
||||
}
|
||||
|
||||
type spdxCreation struct {
|
||||
Created string `json:"created"`
|
||||
Creators []string `json:"creators"`
|
||||
}
|
||||
|
||||
type spdxPackage struct {
|
||||
Name string `json:"name"`
|
||||
SPDXID string `json:"SPDXID"`
|
||||
VersionInfo string `json:"versionInfo"`
|
||||
DownloadLocation string `json:"downloadLocation"`
|
||||
FilesAnalyzed bool `json:"filesAnalyzed"`
|
||||
LicenseConcluded string `json:"licenseConcluded,omitempty"`
|
||||
LicenseDeclared string `json:"licenseDeclared,omitempty"`
|
||||
CopyrightText string `json:"copyrightText,omitempty"`
|
||||
ExternalRefs []spdxExtRef `json:"externalRefs,omitempty"`
|
||||
Checksums []spdxSummary `json:"checksums,omitempty"`
|
||||
}
|
||||
|
||||
type spdxExtRef struct {
|
||||
Category string `json:"referenceCategory"`
|
||||
Type string `json:"referenceType"`
|
||||
Locator string `json:"referenceLocator"`
|
||||
}
|
||||
|
||||
type spdxSummary struct {
|
||||
Algorithm string `json:"algorithm"`
|
||||
Value string `json:"checksumValue"`
|
||||
}
|
||||
|
||||
type spdxRelationship struct {
|
||||
Element string `json:"spdxElementId"`
|
||||
Type string `json:"relationshipType"`
|
||||
Related string `json:"relatedSpdxElement"`
|
||||
}
|
||||
|
||||
// component is one third-party part of a release.
|
||||
type component struct{ purl, name, version string }
|
||||
|
||||
var spdxIDUnsafe = regexp.MustCompile(`[^A-Za-z0-9.-]+`)
|
||||
|
||||
// sbom describes a release: the Go modules and toolchain compiled into the
|
||||
// binaries and the npm packages whose files the frontend build copies.
|
||||
func sbom(v version, binaries []string, packageJSON, packageLock []byte, now time.Time, repoURL string) ([]byte, error) {
|
||||
seen := map[string]component{}
|
||||
for _, path := range binaries {
|
||||
info, err := buildinfo.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("release: %s: %w", path, err)
|
||||
}
|
||||
toolchain := strings.TrimPrefix(strings.SplitN(info.GoVersion, " ", 2)[0], "go")
|
||||
toolchain, _, _ = strings.Cut(toolchain, "-")
|
||||
seen["stdlib"] = component{"pkg:golang/stdlib@v" + toolchain, "stdlib", "v" + toolchain}
|
||||
for _, d := range info.Deps {
|
||||
if d.Replace != nil {
|
||||
d = d.Replace
|
||||
}
|
||||
seen[d.Path] = component{"pkg:golang/" + d.Path + "@" + d.Version, d.Path, d.Version}
|
||||
}
|
||||
}
|
||||
npm, err := bundledNPM(packageJSON, packageLock)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, c := range npm {
|
||||
seen["npm:"+c.name] = c
|
||||
}
|
||||
comps := make([]component, 0, len(seen))
|
||||
for _, c := range seen {
|
||||
comps = append(comps, c)
|
||||
}
|
||||
sort.Slice(comps, func(i, j int) bool { return comps[i].purl < comps[j].purl })
|
||||
|
||||
ns := make([]byte, 8)
|
||||
_, _ = rand.Read(ns)
|
||||
root := spdxPackage{
|
||||
Name: "uptimesebi", SPDXID: "SPDXRef-uptimesebi", VersionInfo: v.String(),
|
||||
DownloadLocation: "NOASSERTION", LicenseConcluded: "AGPL-3.0-only", LicenseDeclared: "AGPL-3.0-only",
|
||||
CopyrightText: "NOASSERTION",
|
||||
}
|
||||
if repoURL != "" {
|
||||
root.DownloadLocation = "git+" + repoURL + ".git@" + v.String()
|
||||
}
|
||||
doc := spdxDoc{
|
||||
SPDXVersion: "SPDX-2.3", DataLicense: "CC0-1.0", SPDXID: "SPDXRef-DOCUMENT",
|
||||
Name: "uptimesebi-" + v.String(),
|
||||
DocumentNamespace: "https://uptimesebi.invalid/spdx/" + v.String() + "-" + hex.EncodeToString(ns),
|
||||
CreationInfo: spdxCreation{Created: now.UTC().Format(time.RFC3339), Creators: []string{"Tool: uptimesebi-release"}},
|
||||
Packages: []spdxPackage{root},
|
||||
Relationships: []spdxRelationship{{"SPDXRef-DOCUMENT", "DESCRIBES", root.SPDXID}},
|
||||
}
|
||||
for _, c := range comps {
|
||||
id := "SPDXRef-" + spdxIDUnsafe.ReplaceAllString(strings.TrimPrefix(c.purl, "pkg:"), "-")
|
||||
doc.Packages = append(doc.Packages, spdxPackage{
|
||||
Name: c.name, SPDXID: id, VersionInfo: c.version, DownloadLocation: "NOASSERTION",
|
||||
ExternalRefs: []spdxExtRef{{"PACKAGE-MANAGER", "purl", c.purl}},
|
||||
})
|
||||
doc.Relationships = append(doc.Relationships, spdxRelationship{root.SPDXID, "CONTAINS", id})
|
||||
}
|
||||
return json.MarshalIndent(doc, "", " ")
|
||||
}
|
||||
|
||||
var nodeModule = regexp.MustCompile(`node_modules/((?:@[^/\s]+/)?[^/\s]+)/`)
|
||||
|
||||
// bundledNPM finds the npm packages the build scripts copy files from, with
|
||||
// their locked versions. Build tools such as Tailwind are not shipped and
|
||||
// stay out.
|
||||
func bundledNPM(packageJSON, packageLock []byte) ([]component, error) {
|
||||
var pkg struct {
|
||||
Scripts map[string]string `json:"scripts"`
|
||||
}
|
||||
var lock struct {
|
||||
Packages map[string]struct {
|
||||
Version string `json:"version"`
|
||||
} `json:"packages"`
|
||||
}
|
||||
if err := json.Unmarshal(packageJSON, &pkg); err != nil {
|
||||
return nil, fmt.Errorf("release: package.json: %w", err)
|
||||
}
|
||||
if err := json.Unmarshal(packageLock, &lock); err != nil {
|
||||
return nil, fmt.Errorf("release: package-lock.json: %w", err)
|
||||
}
|
||||
names := map[string]bool{}
|
||||
for _, s := range pkg.Scripts {
|
||||
for _, m := range nodeModule.FindAllStringSubmatch(s, -1) {
|
||||
names[m[1]] = true
|
||||
}
|
||||
}
|
||||
var out []component
|
||||
for name := range names {
|
||||
p, ok := lock.Packages["node_modules/"+name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("release: %s is not in package-lock.json", name)
|
||||
}
|
||||
// purl encodes the @ of a scope.
|
||||
purl := "pkg:npm/" + strings.Replace(name, "@", "%40", 1) + "@" + p.Version
|
||||
out = append(out, component{purl, name, p.Version})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func writeSBOM(v version, binaries []string) error {
|
||||
pj, err := os.ReadFile("package.json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pl, err := os.ReadFile("package-lock.json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out, err := sbom(v, binaries, pj, pl, time.Now(), repoURL())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = os.Stdout.Write(append(out, '\n'))
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/signing"
|
||||
)
|
||||
|
||||
func TestSBOM(t *testing.T) {
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pj := []byte(`{"scripts":{"build":"tailwindcss -o x && cp node_modules/axios/dist/a.js node_modules/@fontsource/ibm-plex-sans/files/b.woff2 out/"}}`)
|
||||
pl := []byte(`{"packages":{"node_modules/axios":{"version":"1.21.1"},"node_modules/@fontsource/ibm-plex-sans":{"version":"5.3.0"},"node_modules/tailwindcss":{"version":"4.3.5"}}}`)
|
||||
v, _ := parseVersion("v1.2.3")
|
||||
raw, err := sbom(v, []string{self}, pj, pl, time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), "https://git.example/o/r")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var doc spdxDoc
|
||||
if err := json.Unmarshal(raw, &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
purls := map[string]bool{}
|
||||
ids := map[string]bool{}
|
||||
for _, p := range doc.Packages {
|
||||
if ids[p.SPDXID] {
|
||||
t.Errorf("duplicate SPDXID %s", p.SPDXID)
|
||||
}
|
||||
ids[p.SPDXID] = true
|
||||
for _, r := range p.ExternalRefs {
|
||||
purls[r.Locator] = true
|
||||
}
|
||||
}
|
||||
for _, want := range []string{"pkg:npm/axios@1.21.1", "pkg:npm/%40fontsource/ibm-plex-sans@5.3.0", "pkg:golang/golang.org/x/crypto@", "pkg:golang/stdlib@v1."} {
|
||||
if !hasPrefix(purls, want) {
|
||||
t.Errorf("SBOM lacks %s", want)
|
||||
}
|
||||
}
|
||||
if hasPrefix(purls, "pkg:npm/tailwindcss") {
|
||||
t.Error("build tools are not shipped")
|
||||
}
|
||||
if doc.Packages[0].VersionInfo != "v1.2.3" || doc.Packages[0].LicenseDeclared != "AGPL-3.0-only" ||
|
||||
len(doc.Relationships) != len(doc.Packages) || doc.CreationInfo.Created != "2026-01-02T03:04:05Z" {
|
||||
t.Errorf("document = %+v", doc.Packages[0])
|
||||
}
|
||||
|
||||
if _, err := bundledNPM([]byte(`{"scripts":{"b":"cp node_modules/missing/x ."}}`), pl); err == nil {
|
||||
t.Error("a package missing from the lock file was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "SHA256SUMS")
|
||||
if err := os.WriteFile(path, []byte("abc x.tar.gz\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
k, _ := signing.GenerateKey()
|
||||
t.Setenv("RELEASE_SIGNING_KEY", k.String())
|
||||
if err := signFile(path, "v1.0.0"); err == nil || !strings.Contains(err.Error(), "release.pub") {
|
||||
t.Errorf("a key not in release.pub signed: %v", err)
|
||||
}
|
||||
t.Setenv("RELEASE_SIGNING_KEY", "")
|
||||
if err := signFile(path, "v1.0.0"); err == nil {
|
||||
t.Error("signed without a key")
|
||||
}
|
||||
if err := keygen(filepath.Join(dir, "k")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := keygen(filepath.Join(dir, "k")); err == nil {
|
||||
t.Error("keygen overwrote a key")
|
||||
}
|
||||
if st, _ := os.Stat(filepath.Join(dir, "k")); st.Mode().Perm() != 0o600 {
|
||||
t.Errorf("key file mode = %v", st.Mode())
|
||||
}
|
||||
}
|
||||
|
||||
func hasPrefix(set map[string]bool, prefix string) bool {
|
||||
for s := range set {
|
||||
if strings.HasPrefix(s, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/signing"
|
||||
)
|
||||
|
||||
// signFile signs path for release tag; the tag becomes the trusted comment,
|
||||
// so a signature cannot be passed off for another release.
|
||||
func signFile(path, tag string) error {
|
||||
if _, err := parseVersion(tag); err != nil {
|
||||
return err
|
||||
}
|
||||
raw := os.Getenv("RELEASE_SIGNING_KEY")
|
||||
if raw == "" {
|
||||
return errors.New("release: RELEASE_SIGNING_KEY is not set")
|
||||
}
|
||||
key, err := signing.ParsePrivateKey(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !trusted(key.Public()) {
|
||||
return fmt.Errorf("release: key %s is not in internal/signing/release.pub", key.Public().IDString())
|
||||
}
|
||||
msg, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sig, err := signing.Sign(key, msg, tag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path+".minisig", sig, 0o644)
|
||||
}
|
||||
|
||||
func trusted(k signing.PublicKey) bool {
|
||||
for _, r := range signing.ReleaseKeys() {
|
||||
if r.ID == k.ID && r.Key.Equal(k.Key) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func verifyFile(path string) error {
|
||||
msg, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sig, err := os.ReadFile(path + ".minisig")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tag, err := signing.Verify(signing.ReleaseKeys(), msg, sig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("%s: good signature for %s\n", path, tag)
|
||||
return nil
|
||||
}
|
||||
|
||||
// keygen writes a new signing key to secretPath, readable only by the
|
||||
// owner, and prints the public key for internal/signing/release.pub.
|
||||
func keygen(secretPath string) error {
|
||||
k, err := signing.GenerateKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(secretPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintln(f, k.String()); err != nil {
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("untrusted comment: uptimesebi release key %s\n%s\n", k.Public().IDString(), k.Public())
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user