internal/lfs/lfs.go

bd5cf5d7d1f34fa780660fd7562b9ffd9746ee27
gitbay/internal/lfs/lfs.go history · blame · raw

242 lines · 6883 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.
133func Sign(secret []byte, repoID, keyID int64, op string, now time.Time) string {
134	payload := fmt.Sprintf("%d:%d:%s:%d", repoID, keyID, op, now.Add(TokenTTL).Unix())
135	mac := hmac.New(sha256.New, secret)
136	mac.Write([]byte(payload))
137	return base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." +
138		base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
139}
140
141// Grant is what a verified token authorizes.
142type Grant struct {
143	RepoID int64
144	KeyID  int64 // 0: an anonymous download of a public repository
145	Op     string
146}
147
148// Verify checks a token's MAC, shape and expiry. A token from before
149// tokens named their key does not verify.
150func Verify(secret []byte, token string, now time.Time) (Grant, bool) {
151	payloadB64, macB64, found := strings.Cut(token, ".")
152	if !found {
153		return Grant{}, false
154	}
155	payload, err := base64.RawURLEncoding.DecodeString(payloadB64)
156	if err != nil {
157		return Grant{}, false
158	}
159	gotMAC, err := base64.RawURLEncoding.DecodeString(macB64)
160	if err != nil {
161		return Grant{}, false
162	}
163	mac := hmac.New(sha256.New, secret)
164	mac.Write(payload)
165	if !hmac.Equal(mac.Sum(nil), gotMAC) {
166		return Grant{}, false
167	}
168	parts := strings.Split(string(payload), ":")
169	if len(parts) != 4 {
170		return Grant{}, false
171	}
172	repoID, err1 := strconv.ParseInt(parts[0], 10, 64)
173	keyID, err2 := strconv.ParseInt(parts[1], 10, 64)
174	exp, err3 := strconv.ParseInt(parts[3], 10, 64)
175	if err1 != nil || err2 != nil || err3 != nil || keyID < 0 || now.Unix() > exp {
176		return Grant{}, false
177	}
178	if parts[2] != "download" && parts[2] != "upload" {
179		return Grant{}, false
180	}
181	return Grant{RepoID: repoID, KeyID: keyID, Op: parts[2]}, true
182}
183
184// NewSecret returns 32 random bytes, hex-encoded for the settings table.
185func NewSecret() string {
186	buf := make([]byte, 32)
187	rand.Read(buf)
188	return hex.EncodeToString(buf)
189}
190
191// Orphans lists objects in the store that no repository references and
192// that are older than minAge: an object uploaded ahead of the push that
193// will reference it is not an orphan yet. referenced holds the object ids
194// every repository's pointers name.
195func (s LocalStore) Orphans(referenced map[string]bool, minAge time.Duration) ([]Orphan, error) {
196	cutoff := time.Now().Add(-minAge)
197	var out []Orphan
198	err := filepath.WalkDir(s.Root, func(path string, d fs.DirEntry, err error) error {
199		if err != nil || d.IsDir() {
200			return nil
201		}
202		oid := d.Name()
203		if !OIDPat.MatchString(oid) || referenced[oid] {
204			return nil
205		}
206		info, err := d.Info()
207		if err != nil || info.ModTime().After(cutoff) {
208			return nil
209		}
210		out = append(out, Orphan{OID: oid, Size: info.Size()})
211		return nil
212	})
213	return out, err
214}
215
216// Orphan is one unreferenced object.
217type Orphan struct {
218	OID  string
219	Size int64
220}
221
222// Size sums every object in the store.
223func (s LocalStore) Size() int64 {
224	var total int64
225	filepath.WalkDir(s.Root, func(_ string, d fs.DirEntry, err error) error {
226		if err == nil && !d.IsDir() {
227			if fi, err := d.Info(); err == nil {
228				total += fi.Size()
229			}
230		}
231		return nil
232	})
233	return total
234}
235
236// RootFor is the store root a configuration implies.
237func RootFor(lfsRoot, serverRoot string) string {
238	if lfsRoot != "" {
239		return lfsRoot
240	}
241	return filepath.Join(serverRoot, "lfs")
242}