internal/lfs/lfs.go

261 lines · 7672 bytes

  1// Package lfs implements Git LFS server storage and authorization.
  2//
  3// The protocol surface lives in httpd (batch API + basic transfers) and
  4// sshd (git-lfs-authenticate); this package owns the pieces both need:
  5// content-addressed blob storage behind a small interface, and the
  6// short-lived tokens that bridge SSH authentication to the HTTP endpoints.
  7//
  8// BlobStore is deliberately minimal so an S3-compatible backend is a
  9// drop-in: implement the four methods against a bucket and the batch and
 10// transfer handlers work unchanged (the server streams as a proxy).
 11// Handing clients presigned URLs instead is a later optimization to the
 12// batch handler, not a rewrite.
 13package lfs
 14
 15import (
 16	"crypto/hmac"
 17	"crypto/rand"
 18	"crypto/sha256"
 19	"encoding/base64"
 20	"encoding/hex"
 21	"fmt"
 22	"io"
 23	"io/fs"
 24	"os"
 25	"path/filepath"
 26	"regexp"
 27	"strconv"
 28	"strings"
 29	"time"
 30)
 31
 32// OIDPat is a lowercase sha256 hex digest — the only object name LFS uses.
 33var OIDPat = regexp.MustCompile(`^[a-f0-9]{64}$`)
 34
 35// BlobStore holds LFS objects by their sha256 content address.
 36type BlobStore interface {
 37	// Put stores the reader's content as oid, verifying both size and
 38	// digest; a mismatch stores nothing.
 39	Put(oid string, r io.Reader, size int64) error
 40	Get(oid string) (io.ReadCloser, int64, error)
 41	Exists(oid string) (int64, bool)
 42	Delete(oid string) error
 43}
 44
 45// LocalStore is the on-disk backend: <root>/<aa>/<bb>/<oid>, written via a
 46// temp file and renamed only after the digest checks out.
 47type LocalStore struct {
 48	Root string
 49}
 50
 51func (s LocalStore) path(oid string) string {
 52	return filepath.Join(s.Root, oid[:2], oid[2:4], oid)
 53}
 54
 55func (s LocalStore) Put(oid string, r io.Reader, size int64) error {
 56	if !OIDPat.MatchString(oid) {
 57		return fmt.Errorf("bad oid %q", oid)
 58	}
 59	dir := filepath.Dir(s.path(oid))
 60	if err := os.MkdirAll(dir, 0o755); err != nil {
 61		return err
 62	}
 63	tmp, err := os.CreateTemp(dir, ".upload-*")
 64	if err != nil {
 65		return err
 66	}
 67	defer func() {
 68		tmp.Close()
 69		os.Remove(tmp.Name())
 70	}()
 71	h := sha256.New()
 72	n, err := io.Copy(io.MultiWriter(tmp, h), io.LimitReader(r, size+1))
 73	if err != nil {
 74		return err
 75	}
 76	if n != size {
 77		return fmt.Errorf("size mismatch: got %d bytes, expected %d", n, size)
 78	}
 79	if sum := hex.EncodeToString(h.Sum(nil)); sum != oid {
 80		return fmt.Errorf("content digest %s does not match oid", sum[:12])
 81	}
 82	if err := tmp.Close(); err != nil {
 83		return err
 84	}
 85	return os.Rename(tmp.Name(), s.path(oid))
 86}
 87
 88func (s LocalStore) Get(oid string) (io.ReadCloser, int64, error) {
 89	if !OIDPat.MatchString(oid) {
 90		return nil, 0, fmt.Errorf("bad oid %q", oid)
 91	}
 92	f, err := os.Open(s.path(oid))
 93	if err != nil {
 94		return nil, 0, err
 95	}
 96	fi, err := f.Stat()
 97	if err != nil {
 98		f.Close()
 99		return nil, 0, err
100	}
101	return f, fi.Size(), nil
102}
103
104func (s LocalStore) Exists(oid string) (int64, bool) {
105	if !OIDPat.MatchString(oid) {
106		return 0, false
107	}
108	fi, err := os.Stat(s.path(oid))
109	if err != nil {
110		return 0, false
111	}
112	return fi.Size(), true
113}
114
115func (s LocalStore) Delete(oid string) error {
116	if !OIDPat.MatchString(oid) {
117		return fmt.Errorf("bad oid %q", oid)
118	}
119	return os.Remove(s.path(oid))
120}
121
122// Tokens bridge SSH authentication to the HTTP endpoints: stateless,
123// HMAC-signed, scoped to one repo and one operation, short-lived, and
124// bound to the SSH key that obtained them, which must still be live
125// when the token is used (#285). The secret persists in the settings
126// table so tokens survive restarts.
127
128const TokenTTL = time.Hour
129
130// Sign mints a token for op ("download" or "upload") on repoID, bound
131// to keyID: the SSH key, user or deploy, that asked for it, or 0 for an
132// anonymous download of a public repository. fingerprint is that key's
133// fingerprint, "" for key 0. Key ids freed before they stopped being
134// reused (#306) may belong to a later key, so the token carries a hash
135// of the fingerprint as well and a new key given the old id does not
136// inherit the old key's tokens (#303).
137func Sign(secret []byte, repoID, keyID int64, fingerprint, op string, now time.Time) string {
138	payload := fmt.Sprintf("%d:%d:%s:%s:%d", repoID, keyID, KeyPin(fingerprint), op, now.Add(TokenTTL).Unix())
139	mac := hmac.New(sha256.New, secret)
140	mac.Write([]byte(payload))
141	return base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." +
142		base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
143}
144
145// KeyPin is the fingerprint's form in a token: the first 16 hex
146// characters of its SHA-256, or "" for no key.
147func KeyPin(fingerprint string) string {
148	if fingerprint == "" {
149		return ""
150	}
151	sum := sha256.Sum256([]byte(fingerprint))
152	return hex.EncodeToString(sum[:8])
153}
154
155// Grant is what a verified token authorizes.
156type Grant struct {
157	RepoID int64
158	KeyID  int64  // 0: an anonymous download of a public repository
159	KeyPin string // KeyPin of the key's fingerprint; "" when KeyID is 0
160	Op     string
161}
162
163// Verify checks a token's MAC, shape and expiry. A token from before
164// tokens named their key, or before they carried its fingerprint, does
165// not verify.
166func Verify(secret []byte, token string, now time.Time) (Grant, bool) {
167	payloadB64, macB64, found := strings.Cut(token, ".")
168	if !found {
169		return Grant{}, false
170	}
171	payload, err := base64.RawURLEncoding.DecodeString(payloadB64)
172	if err != nil {
173		return Grant{}, false
174	}
175	gotMAC, err := base64.RawURLEncoding.DecodeString(macB64)
176	if err != nil {
177		return Grant{}, false
178	}
179	mac := hmac.New(sha256.New, secret)
180	mac.Write(payload)
181	if !hmac.Equal(mac.Sum(nil), gotMAC) {
182		return Grant{}, false
183	}
184	parts := strings.Split(string(payload), ":")
185	if len(parts) != 5 {
186		return Grant{}, false
187	}
188	repoID, err1 := strconv.ParseInt(parts[0], 10, 64)
189	keyID, err2 := strconv.ParseInt(parts[1], 10, 64)
190	exp, err3 := strconv.ParseInt(parts[4], 10, 64)
191	if err1 != nil || err2 != nil || err3 != nil || keyID < 0 || now.Unix() > exp {
192		return Grant{}, false
193	}
194	if (keyID == 0) != (parts[2] == "") {
195		return Grant{}, false
196	}
197	if parts[3] != "download" && parts[3] != "upload" {
198		return Grant{}, false
199	}
200	return Grant{RepoID: repoID, KeyID: keyID, KeyPin: parts[2], Op: parts[3]}, true
201}
202
203// NewSecret returns 32 random bytes, hex-encoded for the settings table.
204func NewSecret() string {
205	buf := make([]byte, 32)
206	rand.Read(buf)
207	return hex.EncodeToString(buf)
208}
209
210// Orphans lists objects in the store that no repository references and
211// that are older than minAge: an object uploaded ahead of the push that
212// will reference it is not an orphan yet. referenced holds the object ids
213// every repository's pointers name.
214func (s LocalStore) Orphans(referenced map[string]bool, minAge time.Duration) ([]Orphan, error) {
215	cutoff := time.Now().Add(-minAge)
216	var out []Orphan
217	err := filepath.WalkDir(s.Root, func(path string, d fs.DirEntry, err error) error {
218		if err != nil || d.IsDir() {
219			return nil
220		}
221		oid := d.Name()
222		if !OIDPat.MatchString(oid) || referenced[oid] {
223			return nil
224		}
225		info, err := d.Info()
226		if err != nil || info.ModTime().After(cutoff) {
227			return nil
228		}
229		out = append(out, Orphan{OID: oid, Size: info.Size()})
230		return nil
231	})
232	return out, err
233}
234
235// Orphan is one unreferenced object.
236type Orphan struct {
237	OID  string
238	Size int64
239}
240
241// Size sums every object in the store.
242func (s LocalStore) Size() int64 {
243	var total int64
244	filepath.WalkDir(s.Root, func(_ string, d fs.DirEntry, err error) error {
245		if err == nil && !d.IsDir() {
246			if fi, err := d.Info(); err == nil {
247				total += fi.Size()
248			}
249		}
250		return nil
251	})
252	return total
253}
254
255// RootFor is the store root a configuration implies.
256func RootFor(lfsRoot, serverRoot string) string {
257	if lfsRoot != "" {
258		return lfsRoot
259	}
260	return filepath.Join(serverRoot, "lfs")
261}