internal/control/sig.go

ab56677031290fee18323c467841a25216d45768
gitbay/internal/control/sig.go history · blame · raw

203 lines · 6249 bytes

  1package control
  2
  3import (
  4	"encoding/json"
  5	"errors"
  6	"fmt"
  7	"io"
  8	"strconv"
  9	"time"
 10
 11	"github.com/krazywarez/forge/internal/gitutil"
 12	"github.com/krazywarez/forge/internal/policy"
 13	"github.com/krazywarez/forge/internal/protocol"
 14	"github.com/krazywarez/forge/internal/sig"
 15	"github.com/krazywarez/forge/internal/store"
 16)
 17
 18func init() {
 19	register(Command{Path: []string{"pgp", "add"},
 20		Summary: "register an OpenPGP public key (armored, on stdin)", ReadsStdin: true, Run: runPGPAdd})
 21	register(Command{Path: []string{"pgp", "list"},
 22		Summary: "list registered OpenPGP keys", Run: runPGPList})
 23	register(Command{Path: []string{"pgp", "remove"},
 24		Summary: "remove an OpenPGP key by fingerprint", Run: runPGPRemove})
 25	register(Command{Path: []string{"repo", "log"},
 26		Summary: "commit log with signature states: repo log <owner/name> [--limit n]", Run: runRepoLog})
 27}
 28
 29func runPGPAdd(c *Ctx, args []string) int {
 30	if len(args) != 0 {
 31		return c.fail(protocol.ExitUsage, "usage: pgp add < key.asc")
 32	}
 33	raw, err := io.ReadAll(io.LimitReader(c.Stdin, 1<<20))
 34	if err != nil {
 35		return c.fail(protocol.ExitFailure, "reading key: %v", err)
 36	}
 37	meta, err := sig.ParsePGPKey(raw)
 38	if err != nil {
 39		return c.fail(protocol.ExitUsage, "%v", err)
 40	}
 41	uids, _ := json.Marshal(meta.Emails)
 42	if err := c.Store.AddPGPKey(c.User.ID, meta.Fingerprint, string(raw), string(uids), meta.ExpiresAt, meta.RevokedAt); err != nil {
 43		if errors.Is(err, store.ErrDuplicateKey) {
 44			return c.fail(protocol.ExitUsage, "%v", err)
 45		}
 46		return c.fail(protocol.ExitFailure, "adding key: %v", err)
 47	}
 48	type out struct {
 49		Fingerprint string   `json:"fingerprint"`
 50		Emails      []string `json:"emails"`
 51	}
 52	d := out{meta.Fingerprint, meta.Emails}
 53	return c.emit(d, func(w io.Writer) {
 54		fmt.Fprintf(w, "added %s (%v)\n", d.Fingerprint, d.Emails)
 55	})
 56}
 57
 58func runPGPList(c *Ctx, args []string) int {
 59	keys, err := c.Store.ListPGPKeys(c.User.ID)
 60	if err != nil {
 61		return c.fail(protocol.ExitFailure, "%v", err)
 62	}
 63	type out struct {
 64		Fingerprint string     `json:"fingerprint"`
 65		Emails      string     `json:"emails"`
 66		ExpiresAt   *time.Time `json:"expires_at,omitempty"`
 67		RevokedAt   *time.Time `json:"revoked_at,omitempty"`
 68	}
 69	var ds []out
 70	for _, k := range keys {
 71		ds = append(ds, out{k.Fingerprint, k.UIDsJSON, k.ExpiresAt, k.RevokedAt})
 72	}
 73	return c.emit(ds, func(w io.Writer) {
 74		for _, d := range ds {
 75			fmt.Fprintf(w, "%s\t%s\n", d.Fingerprint, d.Emails)
 76		}
 77	})
 78}
 79
 80func runPGPRemove(c *Ctx, args []string) int {
 81	if len(args) != 1 {
 82		return c.fail(protocol.ExitUsage, "usage: pgp remove <fingerprint>")
 83	}
 84	if err := c.Store.RemovePGPKey(c.User.ID, args[0]); err != nil {
 85		if errors.Is(err, store.ErrNotFound) {
 86			return c.fail(protocol.ExitNotFound, "no key %s on your account", args[0])
 87		}
 88		return c.fail(protocol.ExitFailure, "%v", err)
 89	}
 90	return c.emit(map[string]string{"removed": args[0]}, func(w io.Writer) {
 91		fmt.Fprintf(w, "removed %s\n", args[0])
 92	})
 93}
 94
 95// VerifyCommitCached verifies one commit with the epoch cache. Shared with
 96// the web UI.
 97func VerifyCommitCached(st *store.Store, repo store.Repo, parsed *sig.Commit, sha string) (sig.Result, error) {
 98	epoch, err := st.KeyEpoch()
 99	if err != nil {
100		return sig.Result{}, err
101	}
102	if res, ok, err := st.CachedSignature(repo.ID, sha, epoch); err != nil {
103		return sig.Result{}, err
104	} else if ok {
105		return res, nil
106	}
107	res, err := sig.VerifyCommit(store.SigDB{Store: st}, parsed)
108	if err != nil {
109		return sig.Result{}, err
110	}
111	if err := st.StoreSignature(repo.ID, sha, res, epoch); err != nil {
112		return sig.Result{}, err
113	}
114	return res, nil
115}
116
117func runRepoLog(c *Ctx, args []string) int {
118	limit := 30
119	var path string
120	for i := 0; i < len(args); i++ {
121		switch args[i] {
122		case "--limit":
123			if i+1 >= len(args) {
124				return c.fail(protocol.ExitUsage, "--limit requires a value")
125			}
126			n, err := strconv.Atoi(args[i+1])
127			if err != nil || n < 1 || n > 1000 {
128				return c.fail(protocol.ExitUsage, "--limit must be 1..1000")
129			}
130			limit = n
131			i++
132		default:
133			if path != "" {
134				return c.fail(protocol.ExitUsage, "usage: repo log <owner/name> [--limit n]")
135			}
136			path = args[i]
137		}
138	}
139	if path == "" {
140		return c.fail(protocol.ExitUsage, "usage: repo log <owner/name> [--limit n]")
141	}
142	repo, code := resolveRepo(c, path, policy.CanRead)
143	if code >= 0 {
144		return code
145	}
146	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
147	shas, err := gitutil.RevList(dir, repo.DefaultBranch, limit)
148	if err != nil {
149		return c.fail(protocol.ExitFailure, "reading log: %v", err)
150	}
151
152	type sigOut struct {
153		State       string `json:"state"`
154		Signer      string `json:"signer,omitempty"`
155		Fingerprint string `json:"key_fingerprint,omitempty"`
156	}
157	type out struct {
158		SHA            string `json:"sha"`
159		Subject        string `json:"subject"`
160		AuthorName     string `json:"author_name"`
161		AuthorEmail    string `json:"author_email"`
162		CommitterEmail string `json:"committer_email,omitempty"` // only when it differs
163		Date           string `json:"date"`
164		Signature      sigOut `json:"signature"`
165	}
166	var ds []out
167	for _, sha := range shas {
168		raw, err := gitutil.ReadCommit(dir, sha)
169		if err != nil {
170			return c.fail(protocol.ExitFailure, "%v", err)
171		}
172		parsed, err := sig.ParseCommit(raw)
173		if err != nil {
174			return c.fail(protocol.ExitFailure, "parsing %s: %v", sha, err)
175		}
176		res, err := VerifyCommitCached(c.Store, repo, parsed, sha)
177		if err != nil {
178			return c.fail(protocol.ExitFailure, "verifying %s: %v", sha, err)
179		}
180		d := out{
181			SHA:         sha,
182			Subject:     parsed.Subject,
183			AuthorName:  parsed.AuthorName,
184			AuthorEmail: parsed.AuthorEmail,
185			Date:        time.Unix(parsed.AuthorUnix, 0).UTC().Format(time.RFC3339),
186			Signature:   sigOut{State: string(res.State), Fingerprint: res.KeyFingerprint},
187		}
188		if parsed.CommitterEmail != parsed.AuthorEmail {
189			d.CommitterEmail = parsed.CommitterEmail
190		}
191		if res.SignerUserID != 0 {
192			if u, err := c.Store.UserByID(res.SignerUserID); err == nil {
193				d.Signature.Signer = u.Username
194			}
195		}
196		ds = append(ds, d)
197	}
198	return c.emit(ds, func(w io.Writer) {
199		for _, d := range ds {
200			fmt.Fprintf(w, "%.10s  %-22s %s (%s <%s>)\n", d.SHA, d.Signature.State, d.Subject, d.AuthorName, d.AuthorEmail)
201		}
202	})
203}