aboutsummaryrefslogtreecommitdiffstats
path: root/cmd/git-lfs-authenticate/main.go
diff options
context:
space:
mode:
authorLibravatar Rutger Broekhoff2024-01-09 18:13:01 +0100
committerLibravatar Rutger Broekhoff2024-01-09 18:13:01 +0100
commitbc465de960aa5d53b28d51bd6bbead28433f2010 (patch)
tree2beb723462e122ad61a83eab04df2f682c2e7480 /cmd/git-lfs-authenticate/main.go
parent6345d7df02784887311a403ce1267fc4e82f13aa (diff)
downloadgitolfs3-bc465de960aa5d53b28d51bd6bbead28433f2010.tar.gz
gitolfs3-bc465de960aa5d53b28d51bd6bbead28433f2010.zip
Simplify git-lfs-authenticate, rip out Gitolite
Zero dependencies for git-lfs-authenticate now. Not compatible with the LFS server. Assumes that any user who has access to the Git user, should have access to all repositories.
Diffstat (limited to 'cmd/git-lfs-authenticate/main.go')
-rw-r--r--cmd/git-lfs-authenticate/main.go188
1 files changed, 55 insertions, 133 deletions
diff --git a/cmd/git-lfs-authenticate/main.go b/cmd/git-lfs-authenticate/main.go
index 3d2c1ea..3db0efe 100644
--- a/cmd/git-lfs-authenticate/main.go
+++ b/cmd/git-lfs-authenticate/main.go
@@ -2,91 +2,28 @@ package main
2 2
3import ( 3import (
4 "bytes" 4 "bytes"
5 "crypto/ed25519" 5 "crypto/hmac"
6 "crypto/sha256"
7 "encoding/binary"
6 "encoding/hex" 8 "encoding/hex"
7 "encoding/json" 9 "encoding/json"
8 "errors" 10 "errors"
9 "fmt" 11 "fmt"
10 "io" 12 "io"
11 "net/url" 13 "io/fs"
12 "os" 14 "os"
13 "os/exec"
14 "path" 15 "path"
15 "strings" 16 "strings"
16 "time" 17 "time"
17
18 "github.com/golang-jwt/jwt/v5"
19 "github.com/rs/xid"
20) 18)
21 19
22type logger struct {
23 reqID string
24 time time.Time
25 wc io.WriteCloser
26}
27
28func newLogger(reqID string) *logger {
29 return &logger{reqID: reqID, time: time.Now()}
30}
31
32func (l *logger) writer() io.WriteCloser {
33 if l.wc == nil {
34 os.MkdirAll(".gitolfs3/logs/", 0o700) // Mode: drwx------
35 ts := l.time.Format("2006-01-02")
36 path := fmt.Sprintf(".gitolfs3/logs/gitolfs3-%s-%s.log", ts, l.reqID)
37 l.wc, _ = os.Create(path)
38 }
39 return l.wc
40}
41
42func (l *logger) logf(msg string, args ...any) {
43 fmt.Fprintf(l.writer(), msg, args...)
44}
45
46func (l *logger) close() {
47 if l.wc != nil {
48 l.wc.Close()
49 }
50}
51
52func die(msg string, args ...any) { 20func die(msg string, args ...any) {
53 fmt.Fprint(os.Stderr, "Error: ") 21 fmt.Fprint(os.Stderr, "Fatal: ")
54 fmt.Fprintf(os.Stderr, msg, args...) 22 fmt.Fprintf(os.Stderr, msg, args...)
55 fmt.Fprint(os.Stderr, "\n") 23 fmt.Fprint(os.Stderr, "\n")
56 os.Exit(1) 24 os.Exit(1)
57} 25}
58 26
59func dieReqID(reqID string, msg string, args ...any) {
60 fmt.Fprint(os.Stderr, "Error: ")
61 fmt.Fprintf(os.Stderr, msg, args...)
62 fmt.Fprintf(os.Stderr, " (request ID: %s)\n", reqID)
63 os.Exit(1)
64}
65
66func getGitoliteAccess(logger *logger, reqID, path, user, gitolitePerm string) bool {
67 // gitolite access -q: returns only exit code
68 cmd := exec.Command("gitolite", "access", "-q", path, user, gitolitePerm)
69 err := cmd.Run()
70 permGranted := err == nil
71 var exitErr *exec.ExitError
72 if err != nil && !errors.As(err, &exitErr) {
73 logger.logf("Failed to query access information (%s): %s", cmd, err)
74 dieReqID(reqID, "failed to query access information")
75 }
76 return permGranted
77}
78
79type gitolfs3Claims struct {
80 Type string `json:"type"`
81 Repository string `json:"repository"`
82 Permission string `json:"permission"`
83}
84
85type customClaims struct {
86 Gitolfs3 gitolfs3Claims `json:"gitolfs3"`
87 *jwt.RegisteredClaims
88}
89
90type authenticateResponse struct { 27type authenticateResponse struct {
91 // When providing href, the Git LFS client will use href as the base URL 28 // When providing href, the Git LFS client will use href as the base URL
92 // instead of building the base URL using the Service Discovery mechanism. 29 // instead of building the base URL using the Service Discovery mechanism.
@@ -97,7 +34,8 @@ type authenticateResponse struct {
97 // In seconds. 34 // In seconds.
98 ExpiresIn int64 `json:"expires_in,omitempty"` 35 ExpiresIn int64 `json:"expires_in,omitempty"`
99 // The expires_at (RFC3339) property could also be used, but we leave it 36 // The expires_at (RFC3339) property could also be used, but we leave it
100 // out since we don't use it. 37 // out since we don't use it. The Git LFS docs recommend using expires_in
38 // instead (???)
101} 39}
102 40
103func wipe(b []byte) { 41func wipe(b []byte) {
@@ -106,7 +44,7 @@ func wipe(b []byte) {
106 } 44 }
107} 45}
108 46
109const usage = "Usage: git-lfs-authenticate <REPO> <OPERATION (upload/download)>" 47const usage = "Usage: git-lfs-authenticate <REPO> upload/download"
110 48
111func main() { 49func main() {
112 // Even though not explicitly described in the Git LFS documentation, the 50 // Even though not explicitly described in the Git LFS documentation, the
@@ -116,101 +54,85 @@ func main() {
116 // code and print the error message in plain text to standard error. See 54 // code and print the error message in plain text to standard error. See
117 // https://github.com/git-lfs/git-lfs/blob/baf40ac99850a62fe98515175d52df5c513463ec/lfshttp/ssh.go#L76-L117 55 // https://github.com/git-lfs/git-lfs/blob/baf40ac99850a62fe98515175d52df5c513463ec/lfshttp/ssh.go#L76-L117
118 56
119 reqID := xid.New().String()
120 logger := newLogger(reqID)
121
122 if len(os.Args) != 3 { 57 if len(os.Args) != 3 {
123 fmt.Println(usage) 58 fmt.Println(usage)
124 os.Exit(1) 59 os.Exit(1)
125 } 60 }
126 61
127 repo := strings.TrimPrefix(strings.TrimSuffix(os.Args[1], ".git"), "/") 62 repo := strings.TrimPrefix(path.Clean(strings.TrimSuffix(os.Args[1], ".git")), "/")
128 operation := os.Args[2] 63 operation := os.Args[2]
129 if operation != "download" && operation != "upload" { 64 if operation != "download" && operation != "upload" {
130 fmt.Println(usage) 65 fmt.Println(usage)
131 os.Exit(1) 66 os.Exit(1)
132 } 67 }
68 if repo == ".." || strings.HasPrefix(repo, "../") {
69 die("highly illegal repo name (Anzeige ist raus)")
70 }
133 71
134 repoHRefBaseStr := os.Getenv("REPO_HREF_BASE") 72 repoDir := path.Join(repo + ".git")
135 var repoHRefBase *url.URL 73 finfo, err := os.Stat(repoDir)
136 var err error 74 if err != nil {
137 if repoHRefBaseStr != "" { 75 if errors.Is(err, fs.ErrNotExist) {
138 if repoHRefBase, err = url.Parse(repoHRefBaseStr); err != nil { 76 die("repo not found")
139 logger.logf("Failed to parse URL in environment variable REPO_HREF_BASE: %s", err)
140 dieReqID(reqID, "internal error")
141 } 77 }
78 die("could not stat repo: %s", err)
79 }
80 if !finfo.IsDir() {
81 die("repo not found")
142 } 82 }
143 83
144 user := os.Getenv("GL_USER") 84 hrefBase := os.Getenv("GITOLFS3_HREF_BASE")
145 if user == "" { 85 if hrefBase == "" {
146 logger.logf("Environment variable GL_USER is not set") 86 die("incomplete configuration: base URL not provided")
147 dieReqID(reqID, "internal error")
148 } 87 }
88 if !strings.HasSuffix(hrefBase, "/") {
89 hrefBase += "/"
90 }
91
149 keyPath := os.Getenv("GITOLFS3_KEY_PATH") 92 keyPath := os.Getenv("GITOLFS3_KEY_PATH")
150 if keyPath == "" { 93 if keyPath == "" {
151 logger.logf("Environment variable GITOLFS3_KEY_PATH is not set") 94 die("incomplete configuration: key path not provided")
152 dieReqID(reqID, "internal error")
153 } 95 }
96
154 keyStr, err := os.ReadFile(keyPath) 97 keyStr, err := os.ReadFile(keyPath)
155 if err != nil { 98 if err != nil {
156 logger.logf("Cannot read key in GITOLFS3_KEY_PATH: %s", err) 99 wipe(keyStr)
157 dieReqID(reqID, "internal error") 100 die("cannot read key")
158 } 101 }
159 keyStr = bytes.TrimSpace(keyStr) 102 keyStr = bytes.TrimSpace(keyStr)
160 defer wipe(keyStr) 103 defer wipe(keyStr)
161 104 if hex.DecodedLen(len(keyStr)) != 64 {
162 if hex.DecodedLen(len(keyStr)) != ed25519.SeedSize { 105 die("bad key length")
163 logger.logf("Fatal: provided private key (seed) is invalid: does not have expected length")
164 dieReqID(reqID, "internal error")
165 } 106 }
166 107 key := make([]byte, 64)
167 seed := make([]byte, ed25519.SeedSize) 108 defer wipe(key)
168 defer wipe(seed) 109 if _, err = hex.Decode(key, keyStr); err != nil {
169 if _, err = hex.Decode(seed, keyStr); err != nil { 110 die("cannot decode key")
170 logger.logf("Fatal: cannot decode provided private key (seed): %s", err)
171 dieReqID(reqID, "internal error")
172 }
173 privateKey := ed25519.NewKeyFromSeed(seed)
174
175 if !getGitoliteAccess(logger, reqID, repo, user, "R") {
176 die("repository not found")
177 }
178 if operation == "upload" && !getGitoliteAccess(logger, reqID, repo, user, "W") {
179 // User has read access but no write access
180 die("forbidden")
181 } 111 }
182 112
183 expiresIn := time.Minute * 5 113 expiresIn := time.Minute * 5
184 claims := customClaims{ 114 expiresAtUnix := time.Now().Add(expiresIn).Unix()
185 Gitolfs3: gitolfs3Claims{ 115
186 Type: "batch-api", 116 tag := hmac.New(sha256.New, key)
187 Repository: repo, 117 io.WriteString(tag, "git-lfs-authenticate")
188 Permission: operation, 118 tag.Write([]byte{0})
189 }, 119 io.WriteString(tag, repo)
190 RegisteredClaims: &jwt.RegisteredClaims{ 120 tag.Write([]byte{0})
191 Subject: user, 121 io.WriteString(tag, operation)
192 IssuedAt: jwt.NewNumericDate(time.Now()), 122 tag.Write([]byte{0})
193 ExpiresAt: jwt.NewNumericDate(time.Now().Add(expiresIn)), 123 binary.Write(tag, binary.BigEndian, &expiresAtUnix)
194 }, 124 tagStr := hex.EncodeToString(tag.Sum(nil))
195 }
196
197 token := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims)
198 ss, err := token.SignedString(privateKey)
199 if err != nil {
200 logger.logf("Fatal: failed to generate JWT: %s", err)
201 die("failed to generate token")
202 }
203 125
204 response := authenticateResponse{ 126 response := authenticateResponse{
205 Header: map[string]string{ 127 Header: map[string]string{
206 "Authorization": "Bearer " + ss, 128 "Authorization": "Tag " + tagStr,
207 }, 129 },
208 ExpiresIn: int64(expiresIn.Seconds()), 130 ExpiresIn: int64(expiresIn.Seconds()),
209 } 131 HRef: fmt.Sprintf("%s%s?p=1&te=%d",
210 if repoHRefBase != nil { 132 hrefBase,
211 response.HRef = repoHRefBase.ResolveReference(&url.URL{ 133 path.Join(repo+".git", "/info/lfs"),
212 Path: path.Join(repo+".git", "/info/lfs"), 134 expiresAtUnix,
213 }).String() 135 ),
214 } 136 }
215 json.NewEncoder(os.Stdout).Encode(response) 137 json.NewEncoder(os.Stdout).Encode(response)
216} 138}