diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 76ff7ed..6cdeb23 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -33,6 +33,10 @@ jobs: env: TAG: ${{ inputs.tag || github.ref_name }} steps: + - name: Check the tag + run: | + [[ $TAG =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "::error::$TAG isn't a tag like v1.2.3"; exit 1; } + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: ref: refs/tags/${{ env.TAG }} @@ -42,7 +46,6 @@ jobs: env: TOKEN: ${{ secrets.REGISTRY_TOKEN }} run: | - [[ $TAG =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "::error::$TAG isn't a tag like v1.2.3"; exit 1; } printf '%s' "$TOKEN" | docker login "${IMAGE%%/*}" -u "$GITHUB_REPOSITORY_OWNER" --password-stdin docker build --platform linux/amd64 -t "$IMAGE:${TAG#v}" -t "$IMAGE:latest" . docker push "$IMAGE:latest" diff --git a/docs/decisions.md b/docs/decisions.md index e1f3f61..2846972 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -960,3 +960,40 @@ never `latest`, so nothing reaches it that Daniel didn't pin. tag's signature. A signature check was tried and dropped: the workflow comes from the tagged commit, so it only stops tags made in Gitea's UI, and the digest pin already guards the server. + +## Signed commits + +Signed commits get Gitea's lock badge: the short hash gets a green edge and +a segment with a lock and the signer's avatar when Gitea verified the +signature, or an open lock when it's signed but not verified. Unsigned +commits look as before. + +- **Gitea's verdict, not git's.** One more anonymous call per repo, + `/commits?sha=&limit=50&stat=false&files=false&verification=true`, + paged up to `max_commits`. Gitea checks the signature against the keys + of the user whose verified email committed it, so the badge matches + Gitea's own. Checking locally would need the keys in an allowed-signers + file, `ssh-keygen` and `gpg` in the image, and Gitea's email matching + rules again. +- **What's kept:** verified or not, the signer's Gitea name and the key + (SSH fingerprint or GPG key ID, read from the `reason`, and only when it + has that exact form). The signer's email, the signature and the payload + are never decoded. The avatar shows only when the signer is the profile's + user; other signers get the lock alone. The API has no trust status, so + Gitea's yellow "untrusted" and red "warning" states aren't shown. +- **Where:** every short hash of a commit on the log page (log rows, the + repo's latest commit bar, the commit page, branches and tags). The commit + page adds Gitea's signature bar: "Verified · signed by daniel with SSH key + `SHA256:…`", or "Signed · Gitea couldn't verify the signature". The + activity feed shows a small lock after verified hashes. Parent hashes + stay plain, as on Gitea. Branches and tags pointing at older commits show + no badge, since only the log page's commits are looked up. +- **Colour:** `--add`, the CI pass green. `--sig` (12% of it over `--box`) + is the badge segment and the bar; `--sig-edge` the border. The contrast + test covers text on `--sig` (lowest: secondary text, 4.94:1). +- **Failure:** 404/401/403 means no badges. Any other error fails the + build, like the CI status call. Empty repos skip the call (Gitea answers + 409). +- **Reuse key:** includes the verdicts, so commit pages are rebuilt when a + key is added in Gitea and old commits turn verified. +- Icons: Octicons `lock` and `unlock` (19.15.0), added to `scripts/icons.py`. diff --git a/internal/build/activity.go b/internal/build/activity.go index 951111b..6018e4a 100644 --- a/internal/build/activity.go +++ b/internal/build/activity.go @@ -51,7 +51,10 @@ type FeedItem struct { More int // push: commits not listed } -type FeedCommit struct{ Short, Subject, Href string } +type FeedCommit struct { + Short, Subject, Href string + Verified bool // Gitea verified its signature +} // activity fills the profile's activity parts from the repos' commits, // releases and pulls. Only allowlisted repos are in repos, so nothing else @@ -129,7 +132,7 @@ func (b *Builder) feedItems(repos []*repo, login string, since time.Time) []Feed } it := &items[i] if it.Count++; len(it.Commits) < feedCommits { - it.Commits = append(it.Commits, FeedCommit{Short: c.Hash[:min(len(c.Hash), 7)], Subject: c.Subject, Href: r.CommitHref(c.Hash)}) + it.Commits = append(it.Commits, FeedCommit{Short: c.Hash[:min(len(c.Hash), 7)], Subject: c.Subject, Href: r.CommitHref(c.Hash), Verified: r.Sigs[c.Hash].Verified}) } else { it.More++ } diff --git a/internal/build/build_test.go b/internal/build/build_test.go index 1220a86..ce35839 100644 --- a/internal/build/build_test.go +++ b/internal/build/build_test.go @@ -3,6 +3,7 @@ package build import ( "bytes" "context" + "encoding/json" "flag" "fmt" "image" @@ -16,6 +17,7 @@ import ( "os/exec" "path/filepath" "regexp" + "strconv" "strings" "testing" "time" @@ -129,6 +131,10 @@ func fakeGitea(t *testing.T) *httptest.Server { w.Write(buf.Bytes()) return } + if r.URL.Path == "/api/v1/repos/daniel/repo-a/commits" { + signedCommits(t, filepath.Join(root, "daniel/repo-a.git"), w, r) + return + } p := statusRe.ReplaceAllString(r.URL.Path, "/status") // any commit's status b, err := os.ReadFile(filepath.Join("../../testdata/gitea", filepath.FromSlash(p)+".json")) if err != nil { @@ -142,6 +148,41 @@ func fakeGitea(t *testing.T) *httptest.Server { return srv } +// signedCommits answers Gitea's commit list for repo-a from the fixture +// repo, with Gitea's verdict on each: the newest commit is verified (SSH), +// the next signed but unverified, the third verified (GPG), the rest +// unsigned. The signer's email must never reach a page. +func signedCommits(t *testing.T, gitDir string, w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + limit, _ := strconv.Atoi(q.Get("limit")) + page, _ := strconv.Atoi(q.Get("page")) + if q.Get("verification") != "true" || q.Get("stat") != "false" || limit < 1 || page < 1 { + t.Errorf("commits query %q", r.URL.RawQuery) + } + skip := (page - 1) * limit + out, err := exec.Command("git", "--git-dir", gitDir, "log", "--format=%H", "--skip", strconv.Itoa(skip), "-n", strconv.Itoa(limit), "--end-of-options", q.Get("sha")).Output() + if err != nil { + t.Errorf("commits: %v", err) + } + type obj = map[string]any + signer := obj{"name": "daniel", "email": "signer-should-never-render@example.com"} + cs := []obj{} + for i, h := range strings.Fields(string(out)) { + v := obj{"verified": false, "reason": "gpg.error.not_signed_commit", "signature": ""} + switch skip + i { + case 0: + v = obj{"verified": true, "reason": "daniel / SHA256:Qm9vZ3VzRmluZ2VycHJpbnRGb3JUZXN0c09ubHkxMjM", "signature": "-----BEGIN SSH SIGNATURE-----", "signer": signer} + case 1: + v = obj{"verified": false, "reason": "gpg.error.no_gpg_keys_found", "signature": "-----BEGIN SSH SIGNATURE-----"} + case 2: + v = obj{"verified": true, "reason": "daniel / 0123456789ABCDEF", "signature": "-----BEGIN PGP SIGNATURE-----", "signer": signer} + } + cs = append(cs, obj{"sha": h, "commit": obj{"message": "x", "verification": v}}) + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(cs) +} + func testBuilder(t *testing.T) *Builder { srv := fakeGitea(t) cfg := &config.Config{ diff --git a/internal/build/loop.go b/internal/build/loop.go index 8e7d7b8..4218f9c 100644 --- a/internal/build/loop.go +++ b/internal/build/loop.go @@ -114,7 +114,7 @@ func (b *Builder) prune(keep ...string) { func (b *Builder) reuse(r *repo, dir string, dirs ...string) bool { // everything the shared repo header and tabs show h, _ := json.Marshal([]any{r.Head, r.Description, r.Website, r.Topics, r.Archived, r.DefaultBranch, r.LatestTag(), - len(r.Branches), len(r.Tags), len(r.Releases), len(r.Pulls), len(r.Issues), r.PackageCount(), r.License, r.Avatar, r.Status, b.ageKey(r)}) + len(r.Branches), len(r.Tags), len(r.Releases), len(r.Pulls), len(r.Issues), r.PackageCount(), r.License, r.Avatar, r.Status, r.Sigs, b.ageKey(r)}) key := fmt.Sprintf("%x", sha256.Sum256(h)) if b.st.next == nil { // -once mode: no previous build return false diff --git a/internal/build/repo.go b/internal/build/repo.go index 78b4f5e..bbdd633 100644 --- a/internal/build/repo.go +++ b/internal/build/repo.go @@ -39,7 +39,8 @@ type repo struct { Owner, OwnerName, Avatar string // for the header and commit rows Commits int Branches, Tags []gitx.Ref - Status *gitea.Status // CI status of HEAD, nil if none + Status *gitea.Status // CI status of HEAD, nil if none + Sigs map[string]gitea.Signature // signed commits among Recent, by hash Langs []Lang License, LicenseHref string Listed map[string]bool // commits that have their own page @@ -69,6 +70,15 @@ func (r *repo) Release(tag string) *gitea.Release { return nil } +// Sig is Gitea's verdict on a commit's signature, nil if it is unsigned or +// not among the log page's commits. +func (r *repo) Sig(hash string) *gitea.Signature { + if s, ok := r.Sigs[hash]; ok { + return &s + } + return nil +} + // CommitHref links a commit to its page, if it has one. func (r *repo) CommitHref(hash string) string { if !r.Listed[hash] { @@ -223,6 +233,9 @@ func (b *Builder) loadRepo(ctx context.Context, name string) (*repo, error) { case err != nil && !errors.Is(err, gitea.ErrNotFound): return nil, err } + if r.Sigs, err = b.Gitea.Signatures(ctx, name, r.Head, b.Cfg.MaxCommits); err != nil && !errors.Is(err, gitea.ErrNotFound) { + return nil, err + } log, err := r.Git.Log(ctx, r.Head, b.Cfg.MaxCommits, "") r.Listed, r.Recent = map[string]bool{}, log for _, c := range log { diff --git a/internal/gitea/gitea.go b/internal/gitea/gitea.go index 9053e9e..3e84456 100644 --- a/internal/gitea/gitea.go +++ b/internal/gitea/gitea.go @@ -11,6 +11,7 @@ import ( "io" "net/http" "net/url" + "regexp" "strings" "time" ) @@ -223,6 +224,80 @@ func (c *Client) Status(ctx context.Context, repo, sha string) (*Status, error) return &s, c.get(ctx, c.repoPath(repo, "/commits/"+url.PathEscape(sha)+"/status"), &s) } +// Signature is Gitea's verdict on a signed commit. Verified means the +// signature matches a key of the Gitea user it names, as Gitea's own lock +// badge does. +type Signature struct { + Verified bool + Signer string // Gitea user name, verified only + KeyType string // "SSH" or "GPG", verified only + Key string // SSH key fingerprint or GPG key ID, verified only +} + +// Label is the badge's hover text. +func (s *Signature) Label() string { + switch { + case !s.Verified: + return "Signed, not verified" + case s.Signer != "": + return "Verified signature by " + s.Signer + } + return "Verified signature" +} + +// sigKey matches the key Gitea names in a verified reason ("daniel / +// SHA256:…" or "daniel / "). +var sigKey = regexp.MustCompile(`^(SHA256:[A-Za-z0-9+/]{43}|[0-9A-F]{16})$`) + +// Signatures returns Gitea's verdict on the signed commits among the n +// newest reachable from sha, by hash. Unsigned commits are left out. Only +// the verdict, signer name and key are kept: never the signer's email. +func (c *Client) Signatures(ctx context.Context, repo, sha string, n int) (map[string]Signature, error) { + out := map[string]Signature{} + for page := 1; (page-1)*50 < n; page++ { + var cs []struct { + SHA string `json:"sha"` + Commit struct { + Verification *struct { + Verified bool `json:"verified"` + Reason string `json:"reason"` + Signature string `json:"signature"` + Signer *struct { + Name string `json:"name"` + } `json:"signer"` + } `json:"verification"` + } `json:"commit"` + } + q := fmt.Sprintf("/commits?sha=%s&limit=50&page=%d&stat=false&files=false&verification=true", url.QueryEscape(sha), page) + if err := c.get(ctx, c.repoPath(repo, q), &cs); err != nil { + return nil, err + } + for _, x := range cs { + v := x.Commit.Verification + if v == nil || v.Signature == "" { + continue + } + s := Signature{Verified: v.Verified} + if v.Verified { + if v.Signer != nil { + s.Signer = v.Signer.Name + } + if _, k, _ := strings.Cut(v.Reason, " / "); sigKey.MatchString(k) { + s.KeyType, s.Key = "GPG", k + if strings.HasPrefix(k, "SHA256:") { + s.KeyType = "SSH" + } + } + } + out[x.SHA] = s + } + if len(cs) < 50 { + break + } + } + return out, nil +} + func (c *Client) Languages(ctx context.Context, repo string) (map[string]int64, error) { var m map[string]int64 return m, c.get(ctx, c.repoPath(repo, "/languages"), &m) diff --git a/internal/gitea/gitea_test.go b/internal/gitea/gitea_test.go index ee0d593..548cf26 100644 --- a/internal/gitea/gitea_test.go +++ b/internal/gitea/gitea_test.go @@ -44,6 +44,7 @@ func TestTokenOnlyForPackages(t *testing.T) { c.Comments(ctx, "a", 1) c.Releases(ctx, "a") c.Languages(ctx, "a") + c.Signatures(ctx, "a", "main", 50) c.User(ctx) c.Avatar(ctx, srv.URL+"/avatars/x") pkgs, err := c.Packages(ctx, []string{"a", "secret"}) @@ -110,3 +111,42 @@ func TestNoTokenIsAnonymous(t *testing.T) { defer srv.Close() New(srv.URL, "daniel").Packages(context.Background(), []string{"a"}) } + +// TestSignatures: unsigned commits are left out, a verified one keeps its +// signer and a well-formed key, and a full page asks for the next one. +func TestSignatures(t *testing.T) { + var pages []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + pages = append(pages, r.URL.Query().Get("page")) + if r.URL.Query().Get("page") == "2" { + w.Write([]byte(`[{"sha":"c","commit":{"verification":{"verified":true,"reason":"daniel / not a key","signature":"s","signer":{"name":"daniel"}}}}]`)) + return + } + cs := []string{ + `{"sha":"a","commit":{"verification":{"verified":true,"reason":"daniel / SHA256:Qm9vZ3VzRmluZ2VycHJpbnRGb3JUZXN0c09ubHkxMjM","signature":"s","signer":{"name":"daniel","email":"d@example.com"}}}}`, + `{"sha":"b","commit":{"verification":{"verified":false,"reason":"gpg.error.no_gpg_keys_found","signature":"s"}}}`, + } + for len(cs) < 50 { + cs = append(cs, `{"sha":"u","commit":{"verification":{"verified":false,"reason":"gpg.error.not_signed_commit","signature":""}}}`) + } + w.Write([]byte("[" + strings.Join(cs, ",") + "]")) + })) + defer srv.Close() + got, err := New(srv.URL, "daniel").Signatures(context.Background(), "a", "main", 60) + if err != nil { + t.Fatal(err) + } + want := map[string]Signature{ + "a": {Verified: true, Signer: "daniel", KeyType: "SSH", Key: "SHA256:Qm9vZ3VzRmluZ2VycHJpbnRGb3JUZXN0c09ubHkxMjM"}, + "b": {}, + "c": {Verified: true, Signer: "daniel"}, + } + if len(got) != len(want) || strings.Join(pages, ",") != "1,2" { + t.Fatalf("got %+v from pages %v, want %+v from pages 1,2", got, pages, want) + } + for k, w := range want { + if got[k] != w { + t.Errorf("%s = %+v, want %+v", k, got[k], w) + } + } +} diff --git a/scripts/icons.py b/scripts/icons.py index c284584..5bc98bd 100644 --- a/scripts/icons.py +++ b/scripts/icons.py @@ -54,6 +54,7 @@ UI = { "issue-closed": "issue-closed", "law": "law", "link": "link", + "lock": "lock", "merge": "git-merge", "organization": "organization", "package": "package", @@ -64,6 +65,7 @@ UI = { "shield": "shield", "support": "comment-discussion", "tag": "tag", + "unlock": "unlock", "user": "person", "users": "people", "x": "x", diff --git a/testdata/golden/index.html b/testdata/golden/index.html index a9e721b..cecdc04 100644 --- a/testdata/golden/index.html +++ b/testdata/golden/index.html @@ -21,13 +21,13 @@ - - - + + + - +