Skip to content

Commit 8a9fd7f

Browse files
Add pure SSH LFS support (#31516)
Fixes #17554 /claim #17554 Docs PR https://gitea.com/gitea/docs/pulls/49 To test, run pushes like: `GIT_TRACE=1` git push. The trace output should mention "pure SSH connection".
1 parent fdb1df9 commit 8a9fd7f

File tree

13 files changed

+945
-53
lines changed

13 files changed

+945
-53
lines changed

assets/go-licenses.json

+10
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

cmd/serv.go

+85-44
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@ import (
2020
asymkey_model "code.gitea.io/gitea/models/asymkey"
2121
git_model "code.gitea.io/gitea/models/git"
2222
"code.gitea.io/gitea/models/perm"
23+
"code.gitea.io/gitea/modules/container"
2324
"code.gitea.io/gitea/modules/git"
2425
"code.gitea.io/gitea/modules/json"
26+
"code.gitea.io/gitea/modules/lfstransfer"
2527
"code.gitea.io/gitea/modules/log"
2628
"code.gitea.io/gitea/modules/pprof"
2729
"code.gitea.io/gitea/modules/private"
@@ -36,7 +38,11 @@ import (
3638
)
3739

3840
const (
39-
lfsAuthenticateVerb = "git-lfs-authenticate"
41+
verbUploadPack = "git-upload-pack"
42+
verbUploadArchive = "git-upload-archive"
43+
verbReceivePack = "git-receive-pack"
44+
verbLfsAuthenticate = "git-lfs-authenticate"
45+
verbLfsTransfer = "git-lfs-transfer"
4046
)
4147

4248
// CmdServ represents the available serv sub-command.
@@ -73,12 +79,18 @@ func setup(ctx context.Context, debug bool) {
7379
}
7480

7581
var (
76-
allowedCommands = map[string]perm.AccessMode{
77-
"git-upload-pack": perm.AccessModeRead,
78-
"git-upload-archive": perm.AccessModeRead,
79-
"git-receive-pack": perm.AccessModeWrite,
80-
lfsAuthenticateVerb: perm.AccessModeNone,
81-
}
82+
// keep getAccessMode() in sync
83+
allowedCommands = container.SetOf(
84+
verbUploadPack,
85+
verbUploadArchive,
86+
verbReceivePack,
87+
verbLfsAuthenticate,
88+
verbLfsTransfer,
89+
)
90+
allowedCommandsLfs = container.SetOf(
91+
verbLfsAuthenticate,
92+
verbLfsTransfer,
93+
)
8294
alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
8395
)
8496

@@ -124,6 +136,45 @@ func handleCliResponseExtra(extra private.ResponseExtra) error {
124136
return nil
125137
}
126138

139+
func getAccessMode(verb, lfsVerb string) perm.AccessMode {
140+
switch verb {
141+
case verbUploadPack, verbUploadArchive:
142+
return perm.AccessModeRead
143+
case verbReceivePack:
144+
return perm.AccessModeWrite
145+
case verbLfsAuthenticate, verbLfsTransfer:
146+
switch lfsVerb {
147+
case "upload":
148+
return perm.AccessModeWrite
149+
case "download":
150+
return perm.AccessModeRead
151+
}
152+
}
153+
// should be unreachable
154+
return perm.AccessModeNone
155+
}
156+
157+
func getLFSAuthToken(ctx context.Context, lfsVerb string, results *private.ServCommandResults) (string, error) {
158+
now := time.Now()
159+
claims := lfs.Claims{
160+
RegisteredClaims: jwt.RegisteredClaims{
161+
ExpiresAt: jwt.NewNumericDate(now.Add(setting.LFS.HTTPAuthExpiry)),
162+
NotBefore: jwt.NewNumericDate(now),
163+
},
164+
RepoID: results.RepoID,
165+
Op: lfsVerb,
166+
UserID: results.UserID,
167+
}
168+
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
169+
170+
// Sign and get the complete encoded token as a string using the secret
171+
tokenString, err := token.SignedString(setting.LFS.JWTSecretBytes)
172+
if err != nil {
173+
return "", fail(ctx, "Failed to sign JWT Token", "Failed to sign JWT token: %v", err)
174+
}
175+
return fmt.Sprintf("Bearer %s", tokenString), nil
176+
}
177+
127178
func runServ(c *cli.Context) error {
128179
ctx, cancel := installSignals()
129180
defer cancel()
@@ -198,15 +249,6 @@ func runServ(c *cli.Context) error {
198249
repoPath := strings.TrimPrefix(words[1], "/")
199250

200251
var lfsVerb string
201-
if verb == lfsAuthenticateVerb {
202-
if !setting.LFS.StartServer {
203-
return fail(ctx, "Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
204-
}
205-
206-
if len(words) > 2 {
207-
lfsVerb = words[2]
208-
}
209-
}
210252

211253
rr := strings.SplitN(repoPath, "/", 2)
212254
if len(rr) != 2 {
@@ -243,53 +285,52 @@ func runServ(c *cli.Context) error {
243285
}()
244286
}
245287

246-
requestedMode, has := allowedCommands[verb]
247-
if !has {
288+
if allowedCommands.Contains(verb) {
289+
if allowedCommandsLfs.Contains(verb) {
290+
if !setting.LFS.StartServer {
291+
return fail(ctx, "Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
292+
}
293+
if verb == verbLfsTransfer && !setting.LFS.AllowPureSSH {
294+
return fail(ctx, "Unknown git command", "LFS SSH transfer connection denied, pure SSH protocol is disabled")
295+
}
296+
if len(words) > 2 {
297+
lfsVerb = words[2]
298+
}
299+
}
300+
} else {
248301
return fail(ctx, "Unknown git command", "Unknown git command %s", verb)
249302
}
250303

251-
if verb == lfsAuthenticateVerb {
252-
if lfsVerb == "upload" {
253-
requestedMode = perm.AccessModeWrite
254-
} else if lfsVerb == "download" {
255-
requestedMode = perm.AccessModeRead
256-
} else {
257-
return fail(ctx, "Unknown LFS verb", "Unknown lfs verb %s", lfsVerb)
258-
}
259-
}
304+
requestedMode := getAccessMode(verb, lfsVerb)
260305

261306
results, extra := private.ServCommand(ctx, keyID, username, reponame, requestedMode, verb, lfsVerb)
262307
if extra.HasError() {
263308
return fail(ctx, extra.UserMsg, "ServCommand failed: %s", extra.Error)
264309
}
265310

311+
// LFS SSH protocol
312+
if verb == verbLfsTransfer {
313+
token, err := getLFSAuthToken(ctx, lfsVerb, results)
314+
if err != nil {
315+
return err
316+
}
317+
return lfstransfer.Main(ctx, repoPath, lfsVerb, token)
318+
}
319+
266320
// LFS token authentication
267-
if verb == lfsAuthenticateVerb {
321+
if verb == verbLfsAuthenticate {
268322
url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, url.PathEscape(results.OwnerName), url.PathEscape(results.RepoName))
269323

270-
now := time.Now()
271-
claims := lfs.Claims{
272-
RegisteredClaims: jwt.RegisteredClaims{
273-
ExpiresAt: jwt.NewNumericDate(now.Add(setting.LFS.HTTPAuthExpiry)),
274-
NotBefore: jwt.NewNumericDate(now),
275-
},
276-
RepoID: results.RepoID,
277-
Op: lfsVerb,
278-
UserID: results.UserID,
279-
}
280-
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
281-
282-
// Sign and get the complete encoded token as a string using the secret
283-
tokenString, err := token.SignedString(setting.LFS.JWTSecretBytes)
324+
token, err := getLFSAuthToken(ctx, lfsVerb, results)
284325
if err != nil {
285-
return fail(ctx, "Failed to sign JWT Token", "Failed to sign JWT token: %v", err)
326+
return err
286327
}
287328

288329
tokenAuthentication := &git_model.LFSTokenResponse{
289330
Header: make(map[string]string),
290331
Href: url,
291332
}
292-
tokenAuthentication.Header["Authorization"] = fmt.Sprintf("Bearer %s", tokenString)
333+
tokenAuthentication.Header["Authorization"] = token
293334

294335
enc := json.NewEncoder(os.Stdout)
295336
err = enc.Encode(tokenAuthentication)

custom/conf/app.example.ini

+2
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,8 @@ RUN_USER = ; git
306306
;; Enables git-lfs support. true or false, default is false.
307307
;LFS_START_SERVER = false
308308
;;
309+
;; Enables git-lfs SSH protocol support. true or false, default is false.
310+
;LFS_ALLOW_PURE_SSH = false
309311
;;
310312
;; LFS authentication secret, change this yourself
311313
;LFS_JWT_SECRET =

go.mod

+4
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ require (
3535
github.com/blevesearch/bleve/v2 v2.4.2
3636
github.com/buildkite/terminal-to-html/v3 v3.12.1
3737
github.com/caddyserver/certmagic v0.21.3
38+
github.com/charmbracelet/git-lfs-transfer v0.2.0
3839
github.com/chi-middleware/proxy v1.1.1
3940
github.com/dimiro1/reply v0.0.0-20200315094148-d0136a4c9e21
4041
github.com/djherbis/buffer v1.2.0
@@ -197,6 +198,7 @@ require (
197198
github.com/fatih/color v1.17.0 // indirect
198199
github.com/felixge/httpsnoop v1.0.4 // indirect
199200
github.com/fxamacker/cbor/v2 v2.6.0 // indirect
201+
github.com/git-lfs/pktline v0.0.0-20230103162542-ca444d533ef1 // indirect
200202
github.com/go-ap/errors v0.0.0-20240304112515-6077fa9c17b0 // indirect
201203
github.com/go-asn1-ber/asn1-ber v1.5.7 // indirect
202204
github.com/go-enry/go-oniguruma v1.2.1 // indirect
@@ -329,6 +331,8 @@ replace github.com/shurcooL/vfsgen => github.com/lunny/vfsgen v0.0.0-20220105142
329331

330332
replace github.com/nektos/act => gitea.com/gitea/act v0.259.1
331333

334+
replace github.com/charmbracelet/git-lfs-transfer => gitea.com/gitea/git-lfs-transfer v0.2.0
335+
332336
// TODO: This could be removed after https://github.com/mholt/archiver/pull/396 merged
333337
replace github.com/mholt/archiver/v3 => github.com/anchore/archiver/v3 v3.5.2
334338

go.sum

+4
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 h1:cliQ4H
1818
git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078/go.mod h1:g/V2Hjas6Z1UHUp4yIx6bATpNzJ7DYtD0FG3+xARWxs=
1919
gitea.com/gitea/act v0.259.1 h1:8GG1o/xtUHl3qjn5f0h/2FXrT5ubBn05TJOM5ry+FBw=
2020
gitea.com/gitea/act v0.259.1/go.mod h1:UxZWRYqQG2Yj4+4OqfGWW5a3HELwejyWFQyU7F1jUD8=
21+
gitea.com/gitea/git-lfs-transfer v0.2.0 h1:baHaNoBSRaeq/xKayEXwiDQtlIjps4Ac/Ll4KqLMB40=
22+
gitea.com/gitea/git-lfs-transfer v0.2.0/go.mod h1:UrXUCm3xLQkq15fu7qlXHUMlrhdlXHoi13KH2Dfiits=
2123
gitea.com/go-chi/binding v0.0.0-20240430071103-39a851e106ed h1:EZZBtilMLSZNWtHHcgq2mt6NSGhJSZBuduAlinMEmso=
2224
gitea.com/go-chi/binding v0.0.0-20240430071103-39a851e106ed/go.mod h1:E3i3cgB04dDx0v3CytCgRTTn9Z/9x891aet3r456RVw=
2325
gitea.com/go-chi/cache v0.2.1 h1:bfAPkvXlbcZxPCpcmDVCWoHgiBSBmZN/QosnZvEC0+g=
@@ -291,6 +293,8 @@ github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nos
291293
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
292294
github.com/fxamacker/cbor/v2 v2.6.0 h1:sU6J2usfADwWlYDAFhZBQ6TnLFBHxgesMrQfQgk1tWA=
293295
github.com/fxamacker/cbor/v2 v2.6.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=
296+
github.com/git-lfs/pktline v0.0.0-20230103162542-ca444d533ef1 h1:mtDjlmloH7ytdblogrMz1/8Hqua1y8B4ID+bh3rvod0=
297+
github.com/git-lfs/pktline v0.0.0-20230103162542-ca444d533ef1/go.mod h1:fenKRzpXDjNpsIBhuhUzvjCKlDjKam0boRAenTE0Q6A=
294298
github.com/gliderlabs/ssh v0.3.7 h1:iV3Bqi942d9huXnzEF2Mt+CY9gLu8DNM4Obd+8bODRE=
295299
github.com/gliderlabs/ssh v0.3.7/go.mod h1:zpHEXBstFnQYtGnB8k8kQLol82umzn/2/snG7alWVD8=
296300
github.com/glycerine/go-unsnap-stream v0.0.0-20181221182339-f9677308dec2/go.mod h1:/20jfyN9Y5QPEAprSgKAUr+glWDY39ZiUEAYOEv5dsE=

0 commit comments

Comments
 (0)