| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package main |
| 5 |
|
| 6 |
import ( |
| 7 |
"bufio" |
| 8 |
"bytes" |
| 9 |
"compress/gzip" |
| 10 |
"crypto/rand" |
| 11 |
"crypto/rsa" |
| 12 |
"crypto/sha256" |
| 13 |
"crypto/tls" |
| 14 |
"crypto/x509" |
| 15 |
"crypto/x509/pkix" |
| 16 |
"encoding/base64" |
| 17 |
"encoding/hex" |
| 18 |
"encoding/json" |
| 19 |
"encoding/pem" |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"io" |
| 23 |
"log" |
| 24 |
"math" |
| 25 |
"math/big" |
| 26 |
"net/http" |
| 27 |
"net/http/httptest" |
| 28 |
"net/textproto" |
| 29 |
"net/url" |
| 30 |
"os" |
| 31 |
"os/exec" |
| 32 |
"regexp" |
| 33 |
"slices" |
| 34 |
"sort" |
| 35 |
"strconv" |
| 36 |
"strings" |
| 37 |
"sync" |
| 38 |
"time" |
| 39 |
"unicode" |
| 40 |
|
| 41 |
"github.com/klauspost/compress/zstd" |
| 42 |
) |
| 43 |
|
| 44 |
var ( |
| 45 |
repoDir string |
| 46 |
largeObjects = newLfsStorage() |
| 47 |
server *httptest.Server |
| 48 |
serverTLS *httptest.Server |
| 49 |
serverClientCert *httptest.Server |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
oidHandlers map[string]string |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
contentHandlers = []string{ |
| 62 |
"status-batch-403", "status-batch-404", "status-batch-410", "status-batch-422", "status-batch-500", |
| 63 |
"status-storage-403", "status-storage-404", "status-storage-410", "status-storage-422", "status-storage-500", "status-storage-503", |
| 64 |
"return-expired-action", "return-expired-action-forever", "return-invalid-size", |
| 65 |
"object-authenticated", "storage-upload-retry", "storage-upload-retry-later", "storage-upload-retry-later-no-header", "unknown-oid", |
| 66 |
"storage-download-corrupt", |
| 67 |
"storage-download-retry-later", "storage-download-retry-later-no-header", "storage-download-retry", |
| 68 |
"storage-download-retry-range", "storage-download-retry-range-rejected", "storage-download-retry-no-invalid-range", |
| 69 |
"storage-download-encoding-gzip", "storage-download-encoding-zstd", "storage-download-encoding-zstd-retry-range", |
| 70 |
"storage-download-encoding-zstd-1", "storage-download-encoding-zstd-2", "storage-download-encoding-zstd-3", |
| 71 |
"send-verify-action", "send-deprecated-links", "redirect-storage-upload", "batch-hash-algo-empty", "batch-hash-algo-invalid", |
| 72 |
"auth-bearer", "auth-multistage", |
| 73 |
} |
| 74 |
|
| 75 |
reqCookieReposRE = regexp.MustCompile(`\A/require-cookie-`) |
| 76 |
dekInfoRE = regexp.MustCompile(`DEK-Info: AES-128-CBC,([a-fA-F0-9]*)`) |
| 77 |
multiStageCredRE = regexp.MustCompile(`\Acred(\d+)of(\d+)\z`) |
| 78 |
) |
| 79 |
|
| 80 |
func main() { |
| 81 |
repoDir = os.Getenv("LFSTEST_DIR") |
| 82 |
|
| 83 |
mux := http.NewServeMux() |
| 84 |
server = httptest.NewServer(mux) |
| 85 |
serverTLS = httptest.NewTLSServer(mux) |
| 86 |
serverClientCert = httptest.NewUnstartedServer(mux) |
| 87 |
|
| 88 |
|
| 89 |
rootKey, rootCert := generateCARootCertificates() |
| 90 |
_, clientCertPEM, clientKeyPEM, clientKeyEncPEM := generateClientCertificates(rootCert, rootKey) |
| 91 |
|
| 92 |
certPool := x509.NewCertPool() |
| 93 |
certPool.AddCert(rootCert) |
| 94 |
|
| 95 |
serverClientCert.TLS = &tls.Config{ |
| 96 |
Certificates: []tls.Certificate{serverTLS.TLS.Certificates[0]}, |
| 97 |
ClientAuth: tls.RequireAndVerifyClientCert, |
| 98 |
ClientCAs: certPool, |
| 99 |
} |
| 100 |
serverClientCert.StartTLS() |
| 101 |
|
| 102 |
stopch := make(chan bool) |
| 103 |
|
| 104 |
mux.HandleFunc("/shutdown", func(w http.ResponseWriter, r *http.Request) { |
| 105 |
stopch <- true |
| 106 |
}) |
| 107 |
|
| 108 |
mux.HandleFunc("/storage/", storageHandler) |
| 109 |
mux.HandleFunc("/verify", verifyHandler) |
| 110 |
mux.HandleFunc("/redirect307/", redirect307Handler) |
| 111 |
mux.HandleFunc("/limits/", limitsHandler) |
| 112 |
mux.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) { |
| 113 |
fmt.Fprintf(w, "%s\n", time.Now().String()) |
| 114 |
}) |
| 115 |
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 116 |
id, ok := reqId(w) |
| 117 |
if !ok { |
| 118 |
return |
| 119 |
} |
| 120 |
|
| 121 |
if reqCookieReposRE.MatchString(r.URL.Path) { |
| 122 |
if skipIfNoCookie(w, r, id) { |
| 123 |
return |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
if strings.Contains(r.URL.Path, "/info/lfs") { |
| 128 |
if !skipIfBadAuth(w, r, id) { |
| 129 |
lfsHandler(w, r, id) |
| 130 |
} |
| 131 |
|
| 132 |
return |
| 133 |
} |
| 134 |
|
| 135 |
debug(id, "git http-backend %s %s", r.Method, r.URL) |
| 136 |
gitHandler(w, r) |
| 137 |
}) |
| 138 |
|
| 139 |
urlname := writeTestStateFile([]byte(server.URL), "LFSTEST_URL", "lfstest-gitserver") |
| 140 |
defer os.RemoveAll(urlname) |
| 141 |
|
| 142 |
sslurlname := writeTestStateFile([]byte(serverTLS.URL), "LFSTEST_SSL_URL", "lfstest-gitserver-ssl") |
| 143 |
defer os.RemoveAll(sslurlname) |
| 144 |
|
| 145 |
clientCertUrlname := writeTestStateFile([]byte(serverClientCert.URL), "LFSTEST_CLIENT_CERT_URL", "lfstest-gitserver-client-cert-url") |
| 146 |
defer os.RemoveAll(clientCertUrlname) |
| 147 |
|
| 148 |
block := &pem.Block{} |
| 149 |
block.Type = "CERTIFICATE" |
| 150 |
block.Bytes = serverTLS.TLS.Certificates[0].Certificate[0] |
| 151 |
pembytes := pem.EncodeToMemory(block) |
| 152 |
|
| 153 |
certname := writeTestStateFile(pembytes, "LFSTEST_CERT", "lfstest-gitserver-cert") |
| 154 |
defer os.RemoveAll(certname) |
| 155 |
|
| 156 |
cccertname := writeTestStateFile(clientCertPEM, "LFSTEST_CLIENT_CERT", "lfstest-gitserver-client-cert") |
| 157 |
defer os.RemoveAll(cccertname) |
| 158 |
|
| 159 |
ckcertname := writeTestStateFile(clientKeyPEM, "LFSTEST_CLIENT_KEY", "lfstest-gitserver-client-key") |
| 160 |
defer os.RemoveAll(ckcertname) |
| 161 |
|
| 162 |
ckecertname := writeTestStateFile(clientKeyEncPEM, "LFSTEST_CLIENT_KEY_ENCRYPTED", "lfstest-gitserver-client-key-enc") |
| 163 |
defer os.RemoveAll(ckecertname) |
| 164 |
|
| 165 |
debug("init", "server url: %s", server.URL) |
| 166 |
debug("init", "server tls url: %s", serverTLS.URL) |
| 167 |
debug("init", "server client cert url: %s", serverClientCert.URL) |
| 168 |
|
| 169 |
<-stopch |
| 170 |
server.Close() |
| 171 |
serverTLS.Close() |
| 172 |
serverClientCert.Close() |
| 173 |
debug("close", "git server done") |
| 174 |
} |
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
func writeTestStateFile(contents []byte, envVar, defaultFilename string) string { |
| 180 |
f := os.Getenv(envVar) |
| 181 |
if len(f) == 0 { |
| 182 |
f = defaultFilename |
| 183 |
} |
| 184 |
file, err := os.Create(f) |
| 185 |
if err != nil { |
| 186 |
log.Fatalln(err) |
| 187 |
} |
| 188 |
file.Write(contents) |
| 189 |
file.Close() |
| 190 |
return f |
| 191 |
} |
| 192 |
|
| 193 |
type lfsObject struct { |
| 194 |
Oid string `json:"oid,omitempty"` |
| 195 |
Size int64 `json:"size,omitempty"` |
| 196 |
Authenticated bool `json:"authenticated,omitempty"` |
| 197 |
Actions map[string]*lfsLink `json:"actions,omitempty"` |
| 198 |
Links map[string]*lfsLink `json:"_links,omitempty"` |
| 199 |
Err *lfsError `json:"error,omitempty"` |
| 200 |
} |
| 201 |
|
| 202 |
type lfsLink struct { |
| 203 |
Href string `json:"href"` |
| 204 |
Header map[string]string `json:"header,omitempty"` |
| 205 |
ExpiresAt time.Time `json:"expires_at,omitempty"` |
| 206 |
ExpiresIn int `json:"expires_in,omitempty"` |
| 207 |
} |
| 208 |
|
| 209 |
type lfsError struct { |
| 210 |
Code int `json:"code,omitempty"` |
| 211 |
Message string `json:"message"` |
| 212 |
} |
| 213 |
|
| 214 |
func writeLFSError(w http.ResponseWriter, code int, msg string) { |
| 215 |
by, err := json.Marshal(&lfsError{Message: msg}) |
| 216 |
if err != nil { |
| 217 |
http.Error(w, "json encoding error: "+err.Error(), 500) |
| 218 |
return |
| 219 |
} |
| 220 |
|
| 221 |
w.Header().Set("Content-Type", "application/vnd.git-lfs+json") |
| 222 |
w.WriteHeader(code) |
| 223 |
w.Write(by) |
| 224 |
} |
| 225 |
|
| 226 |
|
| 227 |
func lfsHandler(w http.ResponseWriter, r *http.Request, id string) { |
| 228 |
repo, err := repoFromLfsUrl(r.URL.Path) |
| 229 |
if err != nil { |
| 230 |
w.WriteHeader(500) |
| 231 |
w.Write([]byte(err.Error())) |
| 232 |
return |
| 233 |
} |
| 234 |
|
| 235 |
|
| 236 |
if !strings.Contains(r.Header.Get("Accept"), "application/vnd.git-lfs+json") { |
| 237 |
w.WriteHeader(406) |
| 238 |
return |
| 239 |
} |
| 240 |
|
| 241 |
debug(id, "git lfs %s %s repo: %s", r.Method, r.URL, repo) |
| 242 |
w.Header().Set("Content-Type", "application/vnd.git-lfs+json") |
| 243 |
switch r.Method { |
| 244 |
case "POST": |
| 245 |
|
| 246 |
if !strings.Contains(r.Header.Get("Content-Type"), "application/vnd.git-lfs+json") { |
| 247 |
w.WriteHeader(400) |
| 248 |
return |
| 249 |
} |
| 250 |
|
| 251 |
if strings.HasSuffix(r.URL.String(), "batch") { |
| 252 |
lfsBatchHandler(w, r, id, repo) |
| 253 |
} else { |
| 254 |
locksHandler(w, r, repo) |
| 255 |
} |
| 256 |
case "DELETE": |
| 257 |
lfsDeleteHandler(w, r, id, repo) |
| 258 |
case "GET": |
| 259 |
if strings.Contains(r.URL.String(), "/locks") { |
| 260 |
locksHandler(w, r, repo) |
| 261 |
} else { |
| 262 |
w.WriteHeader(404) |
| 263 |
w.Write([]byte("lock request")) |
| 264 |
} |
| 265 |
default: |
| 266 |
w.WriteHeader(405) |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
func lfsUrl(repo, oid string, redirect bool) string { |
| 271 |
repo = url.QueryEscape(repo) |
| 272 |
if redirect { |
| 273 |
return server.URL + "/redirect307/objects/" + oid + "?r=" + repo |
| 274 |
} |
| 275 |
return server.URL + "/storage/" + oid + "?r=" + repo |
| 276 |
} |
| 277 |
|
| 278 |
const ( |
| 279 |
secondsToRefillTokens = 10 |
| 280 |
refillTokenCount = 5 |
| 281 |
) |
| 282 |
|
| 283 |
var ( |
| 284 |
requestTokens = make(map[string]int) |
| 285 |
retryStartTimes = make(map[string]time.Time) |
| 286 |
laterRetriesMu sync.Mutex |
| 287 |
) |
| 288 |
|
| 289 |
func getResourceKey(api, direction, repo, oid string) string { |
| 290 |
return strings.Join([]string{api, direction, repo, oid}, ":") |
| 291 |
} |
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
func checkRateLimit(api, direction, repo, oid string) (seconds int, isWait bool) { |
| 297 |
laterRetriesMu.Lock() |
| 298 |
defer laterRetriesMu.Unlock() |
| 299 |
|
| 300 |
key := getResourceKey(api, direction, repo, oid) |
| 301 |
if requestsRemaining, ok := requestTokens[key]; !ok || requestsRemaining == 0 { |
| 302 |
if retryStartTimes[key] == (time.Time{}) { |
| 303 |
|
| 304 |
retryStartTimes[key] = time.Now() |
| 305 |
} |
| 306 |
|
| 307 |
|
| 308 |
secsPassed := time.Since(retryStartTimes[key]).Seconds() |
| 309 |
if secsPassed >= float64(secondsToRefillTokens) { |
| 310 |
|
| 311 |
requestTokens[key] = refillTokenCount |
| 312 |
return 0, false |
| 313 |
} |
| 314 |
return secondsToRefillTokens - int(secsPassed) + 1, true |
| 315 |
} |
| 316 |
|
| 317 |
requestTokens[key]-- |
| 318 |
|
| 319 |
|
| 320 |
if requestTokens[key] == 0 { |
| 321 |
retryStartTimes[key] = time.Now() |
| 322 |
} |
| 323 |
|
| 324 |
return 0, false |
| 325 |
} |
| 326 |
|
| 327 |
func setRateLimit(api, direction, repo, oid string, numTokens int) { |
| 328 |
laterRetriesMu.Lock() |
| 329 |
defer laterRetriesMu.Unlock() |
| 330 |
|
| 331 |
key := getResourceKey(api, direction, repo, oid) |
| 332 |
requestTokens[key] = numTokens |
| 333 |
|
| 334 |
|
| 335 |
if requestTokens[key] == 0 { |
| 336 |
retryStartTimes[key] = time.Now() |
| 337 |
} |
| 338 |
} |
| 339 |
|
| 340 |
var ( |
| 341 |
retries = make(map[string]uint32) |
| 342 |
retriesMu sync.Mutex |
| 343 |
) |
| 344 |
|
| 345 |
func incrementRetriesFor(api, direction, repo, oid string, check bool) (after uint32, ok bool) { |
| 346 |
|
| 347 |
|
| 348 |
var fmtStr string |
| 349 |
if check { |
| 350 |
fmtStr = "%s-%s-check-retry" |
| 351 |
} else { |
| 352 |
fmtStr = "%s-%s-retry" |
| 353 |
} |
| 354 |
|
| 355 |
if oidHandlers[oid] != fmt.Sprintf(fmtStr, api, direction) { |
| 356 |
return 0, false |
| 357 |
} |
| 358 |
|
| 359 |
retriesMu.Lock() |
| 360 |
defer retriesMu.Unlock() |
| 361 |
|
| 362 |
retryKey := getResourceKey(api, direction, repo, oid) |
| 363 |
|
| 364 |
retries[retryKey]++ |
| 365 |
retries := retries[retryKey] |
| 366 |
|
| 367 |
return retries, true |
| 368 |
} |
| 369 |
|
| 370 |
func lfsDeleteHandler(w http.ResponseWriter, r *http.Request, id, repo string) { |
| 371 |
parts := strings.Split(r.URL.Path, "/") |
| 372 |
oid := parts[len(parts)-1] |
| 373 |
|
| 374 |
largeObjects.Delete(repo, oid) |
| 375 |
debug(id, "DELETE:", oid) |
| 376 |
w.WriteHeader(200) |
| 377 |
} |
| 378 |
|
| 379 |
type batchReq struct { |
| 380 |
Transfers []string `json:"transfers"` |
| 381 |
Operation string `json:"operation"` |
| 382 |
Objects []lfsObject `json:"objects"` |
| 383 |
Ref *Ref `json:"ref,omitempty"` |
| 384 |
} |
| 385 |
|
| 386 |
func (r *batchReq) RefName() string { |
| 387 |
if r.Ref == nil { |
| 388 |
return "" |
| 389 |
} |
| 390 |
return r.Ref.Name |
| 391 |
} |
| 392 |
|
| 393 |
type batchResp struct { |
| 394 |
Transfer string `json:"transfer,omitempty"` |
| 395 |
Objects []lfsObject `json:"objects"` |
| 396 |
HashAlgorithm string `json:"hash_algo,omitempty"` |
| 397 |
} |
| 398 |
|
| 399 |
func lfsBatchHandler(w http.ResponseWriter, r *http.Request, id, repo string) { |
| 400 |
checkingObject := r.Header.Get("X-Check-Object") == "1" |
| 401 |
if !checkingObject && repo == "batchunsupported" { |
| 402 |
w.WriteHeader(404) |
| 403 |
return |
| 404 |
} |
| 405 |
|
| 406 |
if !checkingObject && repo == "badbatch" { |
| 407 |
w.WriteHeader(203) |
| 408 |
return |
| 409 |
} |
| 410 |
|
| 411 |
if repo == "netrctest" { |
| 412 |
_, user, pass, err := extractAuth(r.Header.Get("Authorization")) |
| 413 |
if err != nil || (user != "netrcuser" || pass != "netrcpass") { |
| 414 |
w.WriteHeader(403) |
| 415 |
return |
| 416 |
} |
| 417 |
} |
| 418 |
|
| 419 |
if missingRequiredCreds(w, r, repo) { |
| 420 |
return |
| 421 |
} |
| 422 |
|
| 423 |
buf := &bytes.Buffer{} |
| 424 |
tee := io.TeeReader(r.Body, buf) |
| 425 |
objs := &batchReq{} |
| 426 |
err := json.NewDecoder(tee).Decode(objs) |
| 427 |
io.Copy(io.Discard, r.Body) |
| 428 |
r.Body.Close() |
| 429 |
|
| 430 |
debug(id, "REQUEST") |
| 431 |
debug(id, buf.String()) |
| 432 |
|
| 433 |
if err != nil { |
| 434 |
log.Fatal(err) |
| 435 |
} |
| 436 |
|
| 437 |
if strings.HasSuffix(repo, "branch-required") { |
| 438 |
parts := strings.Split(repo, "-") |
| 439 |
lenParts := len(parts) |
| 440 |
if lenParts > 3 && "refs/heads/"+parts[lenParts-3] != objs.RefName() { |
| 441 |
w.WriteHeader(403) |
| 442 |
json.NewEncoder(w).Encode(struct { |
| 443 |
Message string `json:"message"` |
| 444 |
}{fmt.Sprintf("Expected ref %q, got %q", "refs/heads/"+parts[lenParts-3], objs.RefName())}) |
| 445 |
return |
| 446 |
} |
| 447 |
} |
| 448 |
|
| 449 |
if strings.HasSuffix(repo, "batch-retry-later") || strings.HasSuffix(repo, "batch-retry-later-exceeds-max") { |
| 450 |
if timeLeft, isWaiting := checkRateLimit("batch", "", repo, ""); isWaiting { |
| 451 |
w.Header().Set("Retry-After", strconv.Itoa(timeLeft)) |
| 452 |
w.WriteHeader(http.StatusTooManyRequests) |
| 453 |
|
| 454 |
w.Write([]byte("rate limit reached")) |
| 455 |
fmt.Println("Setting header to: ", strconv.Itoa(timeLeft)) |
| 456 |
return |
| 457 |
} |
| 458 |
} |
| 459 |
|
| 460 |
if strings.HasSuffix(repo, "batch-retry-later-no-header") { |
| 461 |
if _, isWaiting := checkRateLimit("batch", "", repo, ""); isWaiting { |
| 462 |
w.WriteHeader(http.StatusTooManyRequests) |
| 463 |
|
| 464 |
w.Write([]byte("rate limit reached")) |
| 465 |
fmt.Println("Not setting Retry-After header") |
| 466 |
return |
| 467 |
} |
| 468 |
} |
| 469 |
|
| 470 |
res := []lfsObject{} |
| 471 |
testingChunked := testingChunkedTransferEncoding(repo) |
| 472 |
testingTus := testingTusUploadInBatchReq(repo) |
| 473 |
testingTusInterrupt := testingTusUploadInterruptedInBatchReq(repo) |
| 474 |
testingCustomTransfer := testingCustomTransfer(repo) |
| 475 |
var transferChoice string |
| 476 |
var searchForTransfer string |
| 477 |
hashAlgo := "sha256" |
| 478 |
if testingTus { |
| 479 |
searchForTransfer = "tus" |
| 480 |
} else if testingCustomTransfer { |
| 481 |
searchForTransfer = "testcustom" |
| 482 |
} |
| 483 |
if len(searchForTransfer) > 0 { |
| 484 |
for _, t := range objs.Transfers { |
| 485 |
if t == searchForTransfer { |
| 486 |
transferChoice = searchForTransfer |
| 487 |
break |
| 488 |
} |
| 489 |
|
| 490 |
} |
| 491 |
} |
| 492 |
for _, obj := range objs.Objects { |
| 493 |
handler := oidHandlers[obj.Oid] |
| 494 |
action := objs.Operation |
| 495 |
|
| 496 |
o := lfsObject{ |
| 497 |
Size: obj.Size, |
| 498 |
Actions: make(map[string]*lfsLink), |
| 499 |
} |
| 500 |
|
| 501 |
|
| 502 |
if handler == "unknown-oid" { |
| 503 |
o.Oid = "unknown-oid" |
| 504 |
} else { |
| 505 |
o.Oid = obj.Oid |
| 506 |
} |
| 507 |
|
| 508 |
exists := largeObjects.Has(repo, obj.Oid) |
| 509 |
addAction := true |
| 510 |
if action == "download" { |
| 511 |
if !exists { |
| 512 |
o.Err = &lfsError{Code: 404, Message: fmt.Sprintf("Object %v does not exist", obj.Oid)} |
| 513 |
addAction = false |
| 514 |
} |
| 515 |
} else { |
| 516 |
if exists { |
| 517 |
|
| 518 |
addAction = false |
| 519 |
} |
| 520 |
} |
| 521 |
|
| 522 |
if handler == "object-authenticated" { |
| 523 |
o.Authenticated = true |
| 524 |
} |
| 525 |
|
| 526 |
switch handler { |
| 527 |
case "status-batch-403": |
| 528 |
o.Err = &lfsError{Code: 403, Message: "welp"} |
| 529 |
case "status-batch-404": |
| 530 |
o.Err = &lfsError{Code: 404, Message: "welp"} |
| 531 |
case "status-batch-410": |
| 532 |
o.Err = &lfsError{Code: 410, Message: "welp"} |
| 533 |
case "status-batch-422": |
| 534 |
o.Err = &lfsError{Code: 422, Message: "welp"} |
| 535 |
case "status-batch-500": |
| 536 |
o.Err = &lfsError{Code: 500, Message: "welp"} |
| 537 |
default: |
| 538 |
if handler == "return-invalid-size" { |
| 539 |
o.Size = -1 |
| 540 |
} |
| 541 |
|
| 542 |
if handler == "batch-hash-algo-empty" { |
| 543 |
hashAlgo = "" |
| 544 |
} else if handler == "batch-hash-algo-invalid" { |
| 545 |
hashAlgo = "invalid" |
| 546 |
} |
| 547 |
|
| 548 |
if handler == "send-deprecated-links" { |
| 549 |
o.Links = make(map[string]*lfsLink) |
| 550 |
} |
| 551 |
if addAction { |
| 552 |
a := &lfsLink{ |
| 553 |
Href: lfsUrl(repo, obj.Oid, handler == "redirect-storage-upload"), |
| 554 |
Header: map[string]string{}, |
| 555 |
} |
| 556 |
a = serveExpired(a, repo, handler) |
| 557 |
|
| 558 |
if handler == "send-deprecated-links" { |
| 559 |
o.Links[action] = a |
| 560 |
} else { |
| 561 |
o.Actions[action] = a |
| 562 |
} |
| 563 |
} |
| 564 |
|
| 565 |
if handler == "send-verify-action" { |
| 566 |
o.Actions["verify"] = &lfsLink{ |
| 567 |
Href: server.URL + "/verify", |
| 568 |
Header: map[string]string{ |
| 569 |
"repo": repo, |
| 570 |
}, |
| 571 |
} |
| 572 |
} |
| 573 |
} |
| 574 |
|
| 575 |
if testingChunked && addAction { |
| 576 |
if handler == "send-deprecated-links" { |
| 577 |
o.Links[action].Header["Transfer-Encoding"] = "chunked" |
| 578 |
} else { |
| 579 |
o.Actions[action].Header["Transfer-Encoding"] = "chunked" |
| 580 |
} |
| 581 |
} |
| 582 |
if testingTusInterrupt && addAction { |
| 583 |
if handler == "send-deprecated-links" { |
| 584 |
o.Links[action].Header["Lfs-Tus-Interrupt"] = "true" |
| 585 |
} else { |
| 586 |
o.Actions[action].Header["Lfs-Tus-Interrupt"] = "true" |
| 587 |
} |
| 588 |
} |
| 589 |
|
| 590 |
res = append(res, o) |
| 591 |
} |
| 592 |
|
| 593 |
ores := batchResp{HashAlgorithm: hashAlgo, Transfer: transferChoice, Objects: res} |
| 594 |
|
| 595 |
by, err := json.Marshal(ores) |
| 596 |
if err != nil { |
| 597 |
log.Fatal(err) |
| 598 |
} |
| 599 |
|
| 600 |
debug(id, "RESPONSE: 200") |
| 601 |
debug(id, string(by)) |
| 602 |
|
| 603 |
w.WriteHeader(200) |
| 604 |
w.Write(by) |
| 605 |
} |
| 606 |
|
| 607 |
|
| 608 |
var emu sync.Mutex |
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
var expiredRepos = map[string]bool{} |
| 613 |
|
| 614 |
|
| 615 |
|
| 616 |
func serveExpired(a *lfsLink, repo, handler string) *lfsLink { |
| 617 |
var ( |
| 618 |
dur = -5 * time.Minute |
| 619 |
at = time.Now().Add(dur) |
| 620 |
) |
| 621 |
|
| 622 |
if handler == "return-expired-action-forever" || |
| 623 |
(handler == "return-expired-action" && canServeExpired(repo)) { |
| 624 |
|
| 625 |
emu.Lock() |
| 626 |
expiredRepos[repo] = true |
| 627 |
emu.Unlock() |
| 628 |
|
| 629 |
a.ExpiresAt = at |
| 630 |
return a |
| 631 |
} |
| 632 |
|
| 633 |
switch repo { |
| 634 |
case "expired-absolute": |
| 635 |
a.ExpiresAt = at |
| 636 |
case "expired-relative": |
| 637 |
a.ExpiresIn = -5 |
| 638 |
case "expired-both": |
| 639 |
a.ExpiresAt = at |
| 640 |
a.ExpiresIn = -5 |
| 641 |
} |
| 642 |
|
| 643 |
return a |
| 644 |
} |
| 645 |
|
| 646 |
|
| 647 |
|
| 648 |
|
| 649 |
func canServeExpired(repo string) bool { |
| 650 |
emu.Lock() |
| 651 |
defer emu.Unlock() |
| 652 |
|
| 653 |
return !expiredRepos[repo] |
| 654 |
} |
| 655 |
|
| 656 |
|
| 657 |
var storageDownloadRetryRangeRejectedAttempts = 0 |
| 658 |
var tusStorageAttempts = 0 |
| 659 |
|
| 660 |
var ( |
| 661 |
vmu sync.Mutex |
| 662 |
verifyCounts = make(map[string]int) |
| 663 |
verifyRetryRe = regexp.MustCompile(`verify-fail-(\d+)-times?$`) |
| 664 |
) |
| 665 |
|
| 666 |
func verifyHandler(w http.ResponseWriter, r *http.Request) { |
| 667 |
repo := r.Header.Get("repo") |
| 668 |
var payload struct { |
| 669 |
Oid string `json:"oid"` |
| 670 |
Size int64 `json:"size"` |
| 671 |
} |
| 672 |
|
| 673 |
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { |
| 674 |
writeLFSError(w, http.StatusUnprocessableEntity, err.Error()) |
| 675 |
return |
| 676 |
} |
| 677 |
|
| 678 |
var max int |
| 679 |
if matches := verifyRetryRe.FindStringSubmatch(repo); len(matches) < 2 { |
| 680 |
return |
| 681 |
} else { |
| 682 |
max, _ = strconv.Atoi(matches[1]) |
| 683 |
} |
| 684 |
|
| 685 |
key := strings.Join([]string{repo, payload.Oid}, ":") |
| 686 |
|
| 687 |
vmu.Lock() |
| 688 |
verifyCounts[key] = verifyCounts[key] + 1 |
| 689 |
count := verifyCounts[key] |
| 690 |
vmu.Unlock() |
| 691 |
|
| 692 |
if count < max { |
| 693 |
writeLFSError(w, http.StatusServiceUnavailable, fmt.Sprintf( |
| 694 |
"intentionally failing verify request %d (out of %d)", count, max, |
| 695 |
)) |
| 696 |
return |
| 697 |
} |
| 698 |
} |
| 699 |
|
| 700 |
var zstdHeaderRE = regexp.MustCompile(`(?:\A|, *)(?i:zstd)(?:, *|\z)`) |
| 701 |
|
| 702 |
|
| 703 |
func storageHandler(w http.ResponseWriter, r *http.Request) { |
| 704 |
id, ok := reqId(w) |
| 705 |
if !ok { |
| 706 |
return |
| 707 |
} |
| 708 |
repo := r.URL.Query().Get("r") |
| 709 |
parts := strings.Split(r.URL.Path, "/") |
| 710 |
oid := parts[len(parts)-1] |
| 711 |
if missingRequiredCreds(w, r, repo) { |
| 712 |
return |
| 713 |
} |
| 714 |
|
| 715 |
debug(id, "storage %s %s repo: %s", r.Method, oid, repo) |
| 716 |
switch r.Method { |
| 717 |
case "PUT": |
| 718 |
switch oidHandlers[oid] { |
| 719 |
case "status-storage-403": |
| 720 |
w.WriteHeader(403) |
| 721 |
return |
| 722 |
case "status-storage-404": |
| 723 |
w.WriteHeader(404) |
| 724 |
return |
| 725 |
case "status-storage-410": |
| 726 |
w.WriteHeader(410) |
| 727 |
return |
| 728 |
case "status-storage-422": |
| 729 |
w.WriteHeader(422) |
| 730 |
return |
| 731 |
case "status-storage-500": |
| 732 |
w.WriteHeader(500) |
| 733 |
return |
| 734 |
case "status-storage-503": |
| 735 |
writeLFSError(w, 503, "LFS is temporarily unavailable") |
| 736 |
return |
| 737 |
case "object-authenticated": |
| 738 |
if len(r.Header.Get("Authorization")) > 0 { |
| 739 |
w.WriteHeader(400) |
| 740 |
w.Write([]byte("Should not send authentication")) |
| 741 |
} |
| 742 |
return |
| 743 |
case "storage-upload-retry": |
| 744 |
if retries, ok := incrementRetriesFor("storage", "upload", repo, oid, false); ok && retries < 3 { |
| 745 |
w.WriteHeader(500) |
| 746 |
w.Write([]byte("malformed content")) |
| 747 |
|
| 748 |
return |
| 749 |
} |
| 750 |
case "storage-upload-retry-later": |
| 751 |
if timeLeft, isWaiting := checkRateLimit("storage", "upload", repo, oid); isWaiting { |
| 752 |
w.Header().Set("Retry-After", strconv.Itoa(timeLeft)) |
| 753 |
w.WriteHeader(http.StatusTooManyRequests) |
| 754 |
|
| 755 |
w.Write([]byte("rate limit reached")) |
| 756 |
fmt.Println("Setting header to: ", strconv.Itoa(timeLeft)) |
| 757 |
return |
| 758 |
} |
| 759 |
case "storage-upload-retry-later-no-header": |
| 760 |
if _, isWaiting := checkRateLimit("storage", "upload", repo, oid); isWaiting { |
| 761 |
w.WriteHeader(http.StatusTooManyRequests) |
| 762 |
|
| 763 |
w.Write([]byte("rate limit reached")) |
| 764 |
fmt.Println("Not setting Retry-After header") |
| 765 |
return |
| 766 |
} |
| 767 |
} |
| 768 |
|
| 769 |
if testingChunkedTransferEncoding(repo) { |
| 770 |
if !slices.Contains(r.TransferEncoding, "chunked") { |
| 771 |
w.WriteHeader(http.StatusBadRequest) |
| 772 |
w.Write([]byte("Chunked transfer encoding required")) |
| 773 |
return |
| 774 |
} |
| 775 |
} |
| 776 |
|
| 777 |
hash := sha256.New() |
| 778 |
buf := &bytes.Buffer{} |
| 779 |
|
| 780 |
io.Copy(io.MultiWriter(hash, buf), r.Body) |
| 781 |
oid := hex.EncodeToString(hash.Sum(nil)) |
| 782 |
if !strings.HasSuffix(r.URL.Path, "/"+oid) { |
| 783 |
w.WriteHeader(403) |
| 784 |
return |
| 785 |
} |
| 786 |
|
| 787 |
largeObjects.Set(repo, oid, buf.Bytes()) |
| 788 |
|
| 789 |
case "GET": |
| 790 |
parts := strings.Split(r.URL.Path, "/") |
| 791 |
oid := parts[len(parts)-1] |
| 792 |
statusCode := 200 |
| 793 |
byteLimit := 0 |
| 794 |
compress := false |
| 795 |
zstdCompress := false |
| 796 |
|
| 797 |
if by, ok := largeObjects.Get(repo, oid); ok { |
| 798 |
switch oidHandlers[oid] { |
| 799 |
case "storage-download-corrupt": |
| 800 |
|
| 801 |
|
| 802 |
|
| 803 |
by = bytes.ToUpper(by) |
| 804 |
case "storage-download-retry-later": |
| 805 |
if secsToWait, wait := checkRateLimit("storage", "download", repo, oid); wait { |
| 806 |
statusCode = http.StatusTooManyRequests |
| 807 |
w.Header().Set("Retry-After", strconv.Itoa(secsToWait)) |
| 808 |
by = []byte("rate limit reached") |
| 809 |
fmt.Println("Setting header to: ", strconv.Itoa(secsToWait)) |
| 810 |
} |
| 811 |
case "storage-download-retry-later-no-header": |
| 812 |
if _, wait := checkRateLimit("storage", "download", repo, oid); wait { |
| 813 |
statusCode = http.StatusTooManyRequests |
| 814 |
by = []byte("rate limit reached") |
| 815 |
fmt.Println("Not setting Retry-After header") |
| 816 |
} |
| 817 |
case "storage-download-retry": |
| 818 |
if retries, ok := incrementRetriesFor("storage", "download", repo, oid, false); ok && retries < 3 { |
| 819 |
statusCode = 500 |
| 820 |
by = []byte("malformed content") |
| 821 |
} |
| 822 |
case "storage-download-retry-range": |
| 823 |
|
| 824 |
if handleRangeRequest(w, r, by) { |
| 825 |
return |
| 826 |
} |
| 827 |
byteLimit = len(oidHandlers[oid]) / 2 |
| 828 |
case "storage-download-retry-range-rejected": |
| 829 |
|
| 830 |
|
| 831 |
if rangeHdr := r.Header.Get("Range"); rangeHdr != "" { |
| 832 |
w.WriteHeader(416) |
| 833 |
return |
| 834 |
} |
| 835 |
if storageDownloadRetryRangeRejectedAttempts == 0 { |
| 836 |
|
| 837 |
|
| 838 |
byteLimit = len(oidHandlers[oid]) / 2 |
| 839 |
storageDownloadRetryRangeRejectedAttempts++ |
| 840 |
} |
| 841 |
case "storage-download-retry-no-invalid-range": |
| 842 |
|
| 843 |
if handleRangeRequest(w, r, by) { |
| 844 |
return |
| 845 |
} |
| 846 |
case "storage-download-encoding-gzip": |
| 847 |
if r.Header.Get("Accept-Encoding") != "gzip" { |
| 848 |
statusCode = 500 |
| 849 |
by = []byte("not encoded") |
| 850 |
} else { |
| 851 |
compress = true |
| 852 |
} |
| 853 |
case "storage-download-encoding-zstd", |
| 854 |
"storage-download-encoding-zstd-1", |
| 855 |
"storage-download-encoding-zstd-2", |
| 856 |
"storage-download-encoding-zstd-3": |
| 857 |
if zstdHeaderRE.MatchString(r.Header.Get("Accept-Encoding")) { |
| 858 |
zstdCompress = true |
| 859 |
} else { |
| 860 |
statusCode = http.StatusInternalServerError |
| 861 |
by = []byte("not encoded") |
| 862 |
} |
| 863 |
case "storage-download-encoding-zstd-retry-range": |
| 864 |
|
| 865 |
if handleRangeRequest(w, r, by) { |
| 866 |
return |
| 867 |
} |
| 868 |
|
| 869 |
if zstdHeaderRE.MatchString(r.Header.Get("Accept-Encoding")) { |
| 870 |
zstdCompress = true |
| 871 |
|
| 872 |
|
| 873 |
|
| 874 |
|
| 875 |
|
| 876 |
|
| 877 |
|
| 878 |
byteLimit = 6 |
| 879 |
} else { |
| 880 |
statusCode = http.StatusInternalServerError |
| 881 |
by = []byte("not encoded") |
| 882 |
} |
| 883 |
} |
| 884 |
|
| 885 |
var wrtr io.Writer = w |
| 886 |
if compress { |
| 887 |
w.Header().Set("Content-Encoding", "gzip") |
| 888 |
gz := gzip.NewWriter(w) |
| 889 |
defer gz.Close() |
| 890 |
|
| 891 |
wrtr = gz |
| 892 |
} else if zstdCompress { |
| 893 |
w.Header().Set("Content-Encoding", "zstd") |
| 894 |
enc, err := zstd.NewWriter(w) |
| 895 |
if err == nil { |
| 896 |
defer enc.Close() |
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
|
| 905 |
|
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
|
| 910 |
|
| 911 |
mid := len(by) / 2 |
| 912 |
frame1 := enc.EncodeAll(by[0:mid], make([]byte, 0, mid*2)) |
| 913 |
frame2 := enc.EncodeAll(by[mid:], make([]byte, 0, mid*2)) |
| 914 |
by = append(frame1, frame2...) |
| 915 |
|
| 916 |
if byteLimit > 0 { |
| 917 |
byteLimit += len(frame1) |
| 918 |
} |
| 919 |
} else { |
| 920 |
statusCode = http.StatusInternalServerError |
| 921 |
by = []byte("not encoded") |
| 922 |
byteLimit = 0 |
| 923 |
} |
| 924 |
} |
| 925 |
|
| 926 |
if byteLimit > 0 { |
| 927 |
|
| 928 |
|
| 929 |
|
| 930 |
w.Header().Set("Content-Length", strconv.Itoa(len(by))) |
| 931 |
} |
| 932 |
|
| 933 |
w.WriteHeader(statusCode) |
| 934 |
if byteLimit > 0 { |
| 935 |
wrtr.Write(by[0:byteLimit]) |
| 936 |
} else { |
| 937 |
wrtr.Write(by) |
| 938 |
} |
| 939 |
return |
| 940 |
} |
| 941 |
|
| 942 |
w.WriteHeader(404) |
| 943 |
case "HEAD": |
| 944 |
|
| 945 |
if !validateTusHeaders(r, id) { |
| 946 |
w.WriteHeader(400) |
| 947 |
return |
| 948 |
} |
| 949 |
parts := strings.Split(r.URL.Path, "/") |
| 950 |
oid := parts[len(parts)-1] |
| 951 |
var offset int64 |
| 952 |
if by, ok := largeObjects.GetIncomplete(repo, oid); ok { |
| 953 |
offset = int64(len(by)) |
| 954 |
} |
| 955 |
w.Header().Set("Upload-Offset", strconv.FormatInt(offset, 10)) |
| 956 |
w.WriteHeader(200) |
| 957 |
case "PATCH": |
| 958 |
|
| 959 |
if !validateTusHeaders(r, id) { |
| 960 |
w.WriteHeader(400) |
| 961 |
return |
| 962 |
} |
| 963 |
parts := strings.Split(r.URL.Path, "/") |
| 964 |
oid := parts[len(parts)-1] |
| 965 |
|
| 966 |
offsetHdr := r.Header.Get("Upload-Offset") |
| 967 |
offset, err := strconv.ParseInt(offsetHdr, 10, 64) |
| 968 |
if err != nil { |
| 969 |
log.Fatal("Unable to parse Upload-Offset header in request: ", err) |
| 970 |
w.WriteHeader(400) |
| 971 |
return |
| 972 |
} |
| 973 |
hash := sha256.New() |
| 974 |
buf := &bytes.Buffer{} |
| 975 |
out := io.MultiWriter(hash, buf) |
| 976 |
|
| 977 |
if by, ok := largeObjects.GetIncomplete(repo, oid); ok { |
| 978 |
if offset != int64(len(by)) { |
| 979 |
log.Fatal(fmt.Sprintf("Incorrect offset in request, got %d expected %d", offset, len(by))) |
| 980 |
w.WriteHeader(400) |
| 981 |
return |
| 982 |
} |
| 983 |
_, err := out.Write(by) |
| 984 |
if err != nil { |
| 985 |
log.Fatal("Error reading incomplete bytes from store: ", err) |
| 986 |
w.WriteHeader(500) |
| 987 |
return |
| 988 |
} |
| 989 |
largeObjects.DeleteIncomplete(repo, oid) |
| 990 |
debug(id, "Resuming upload of %v at byte %d", oid, offset) |
| 991 |
} |
| 992 |
|
| 993 |
|
| 994 |
|
| 995 |
|
| 996 |
var copyErr error |
| 997 |
if r.Header.Get("Lfs-Tus-Interrupt") == "true" && offset == 0 { |
| 998 |
chdr := r.Header.Get("Content-Length") |
| 999 |
contentLen, err := strconv.ParseInt(chdr, 10, 64) |
| 1000 |
if err != nil { |
| 1001 |
log.Fatal(fmt.Sprintf("Invalid Content-Length %q", chdr)) |
| 1002 |
w.WriteHeader(400) |
| 1003 |
return |
| 1004 |
} |
| 1005 |
truncated := contentLen / 3 |
| 1006 |
_, _ = io.CopyN(out, r.Body, truncated) |
| 1007 |
r.Body.Close() |
| 1008 |
copyErr = fmt.Errorf("Simulated copy error") |
| 1009 |
} else { |
| 1010 |
_, copyErr = io.Copy(out, r.Body) |
| 1011 |
} |
| 1012 |
if copyErr != nil { |
| 1013 |
b := buf.Bytes() |
| 1014 |
if len(b) > 0 { |
| 1015 |
debug(id, "Incomplete upload of %v, %d bytes", oid, len(b)) |
| 1016 |
largeObjects.SetIncomplete(repo, oid, b) |
| 1017 |
} |
| 1018 |
w.WriteHeader(500) |
| 1019 |
} else { |
| 1020 |
checkoid := hex.EncodeToString(hash.Sum(nil)) |
| 1021 |
if checkoid != oid { |
| 1022 |
log.Fatal(fmt.Sprintf("Incorrect oid after calculation, got %q expected %q", checkoid, oid)) |
| 1023 |
w.WriteHeader(403) |
| 1024 |
return |
| 1025 |
} |
| 1026 |
|
| 1027 |
b := buf.Bytes() |
| 1028 |
largeObjects.Set(repo, oid, b) |
| 1029 |
w.Header().Set("Upload-Offset", strconv.FormatInt(int64(len(b)), 10)) |
| 1030 |
w.WriteHeader(204) |
| 1031 |
} |
| 1032 |
|
| 1033 |
default: |
| 1034 |
w.WriteHeader(405) |
| 1035 |
} |
| 1036 |
} |
| 1037 |
|
| 1038 |
|
| 1039 |
var rangeHeaderRE = regexp.MustCompile(`bytes=(\d+)-(.*)`) |
| 1040 |
|
| 1041 |
func handleRangeRequest(w http.ResponseWriter, r *http.Request, data []byte) bool { |
| 1042 |
rangeHeader := r.Header.Get("Range") |
| 1043 |
if rangeHeader == "" { |
| 1044 |
return false |
| 1045 |
} |
| 1046 |
|
| 1047 |
if r.Header.Get("Accept-Encoding") != "" { |
| 1048 |
|
| 1049 |
|
| 1050 |
w.WriteHeader(http.StatusBadRequest) |
| 1051 |
return true |
| 1052 |
} |
| 1053 |
|
| 1054 |
match := rangeHeaderRE.FindStringSubmatch(rangeHeader) |
| 1055 |
|
| 1056 |
if match == nil || len(match) != 3 { |
| 1057 |
w.WriteHeader(http.StatusBadRequest) |
| 1058 |
return true |
| 1059 |
} |
| 1060 |
|
| 1061 |
|
| 1062 |
startIndex, _ := strconv.ParseInt(match[1], 10, 32) |
| 1063 |
endIndex, err := strconv.ParseInt(match[2], 10, 32) |
| 1064 |
|
| 1065 |
if len(match[2]) > 0 && (err != nil || endIndex < startIndex) { |
| 1066 |
|
| 1067 |
|
| 1068 |
|
| 1069 |
|
| 1070 |
|
| 1071 |
|
| 1072 |
w.WriteHeader(http.StatusBadRequest) |
| 1073 |
return true |
| 1074 |
} |
| 1075 |
|
| 1076 |
|
| 1077 |
|
| 1078 |
contentRange := fmt.Sprintf("bytes %d-%d/%d", startIndex, len(data)-1, len(data)) |
| 1079 |
w.Header().Set("Content-Range", contentRange) |
| 1080 |
|
| 1081 |
w.WriteHeader(http.StatusPartialContent) |
| 1082 |
w.Write(data[startIndex:]) |
| 1083 |
return true |
| 1084 |
} |
| 1085 |
|
| 1086 |
func validateTusHeaders(r *http.Request, id string) bool { |
| 1087 |
if len(r.Header.Get("Tus-Resumable")) == 0 { |
| 1088 |
debug(id, "Missing Tus-Resumable header in request") |
| 1089 |
return false |
| 1090 |
} |
| 1091 |
return true |
| 1092 |
} |
| 1093 |
|
| 1094 |
func gitHandler(w http.ResponseWriter, r *http.Request) { |
| 1095 |
defer func() { |
| 1096 |
io.Copy(io.Discard, r.Body) |
| 1097 |
r.Body.Close() |
| 1098 |
}() |
| 1099 |
|
| 1100 |
cmd := exec.Command("git", "http-backend") |
| 1101 |
cmd.Env = []string{ |
| 1102 |
fmt.Sprintf("GIT_PROJECT_ROOT=%s", repoDir), |
| 1103 |
fmt.Sprintf("GIT_HTTP_EXPORT_ALL="), |
| 1104 |
fmt.Sprintf("PATH_INFO=%s", r.URL.Path), |
| 1105 |
fmt.Sprintf("QUERY_STRING=%s", r.URL.RawQuery), |
| 1106 |
fmt.Sprintf("REQUEST_METHOD=%s", r.Method), |
| 1107 |
fmt.Sprintf("CONTENT_TYPE=%s", r.Header.Get("Content-Type")), |
| 1108 |
} |
| 1109 |
|
| 1110 |
if vals := r.Header.Values("Git-Protocol"); len(vals) == 1 { |
| 1111 |
cmd.Env = append(cmd.Env, fmt.Sprintf("GIT_PROTOCOL=%s", vals[0])) |
| 1112 |
} |
| 1113 |
|
| 1114 |
buffer := &bytes.Buffer{} |
| 1115 |
cmd.Stdin = r.Body |
| 1116 |
cmd.Stdout = buffer |
| 1117 |
cmd.Stderr = os.Stderr |
| 1118 |
|
| 1119 |
if err := cmd.Run(); err != nil { |
| 1120 |
log.Fatal(err) |
| 1121 |
} |
| 1122 |
|
| 1123 |
text := textproto.NewReader(bufio.NewReader(buffer)) |
| 1124 |
|
| 1125 |
code, _, _ := text.ReadCodeLine(-1) |
| 1126 |
|
| 1127 |
if code != 0 { |
| 1128 |
w.WriteHeader(code) |
| 1129 |
} |
| 1130 |
|
| 1131 |
headers, _ := text.ReadMIMEHeader() |
| 1132 |
head := w.Header() |
| 1133 |
for key, values := range headers { |
| 1134 |
for _, value := range values { |
| 1135 |
head.Add(key, value) |
| 1136 |
} |
| 1137 |
} |
| 1138 |
|
| 1139 |
io.Copy(w, text.R) |
| 1140 |
} |
| 1141 |
|
| 1142 |
func redirect307Handler(w http.ResponseWriter, r *http.Request) { |
| 1143 |
id, ok := reqId(w) |
| 1144 |
if !ok { |
| 1145 |
return |
| 1146 |
} |
| 1147 |
|
| 1148 |
|
| 1149 |
|
| 1150 |
parts := strings.Split(r.URL.Path, "/") |
| 1151 |
|
| 1152 |
var redirectTo string |
| 1153 |
if parts[2] == "rel" { |
| 1154 |
redirectTo = "/" + strings.Join(parts[3:], "/") |
| 1155 |
} else if parts[2] == "abs" { |
| 1156 |
redirectTo = server.URL + "/" + strings.Join(parts[3:], "/") |
| 1157 |
} else if parts[2] == "objects" { |
| 1158 |
repo := r.URL.Query().Get("r") |
| 1159 |
redirectTo = server.URL + "/storage/" + strings.Join(parts[3:], "/") + "?r=" + repo |
| 1160 |
} else { |
| 1161 |
debug(id, "Invalid URL for redirect: %v", r.URL) |
| 1162 |
w.WriteHeader(404) |
| 1163 |
return |
| 1164 |
} |
| 1165 |
w.Header().Set("Location", redirectTo) |
| 1166 |
w.WriteHeader(307) |
| 1167 |
} |
| 1168 |
|
| 1169 |
func limitsHandler(w http.ResponseWriter, r *http.Request) { |
| 1170 |
id, ok := reqId(w) |
| 1171 |
if !ok { |
| 1172 |
return |
| 1173 |
} |
| 1174 |
|
| 1175 |
api := r.URL.Query().Get("api") |
| 1176 |
direction := r.URL.Query().Get("direction") |
| 1177 |
repo := r.URL.Query().Get("repo") |
| 1178 |
oid := r.URL.Query().Get("oid") |
| 1179 |
tokens := r.URL.Query().Get("tokens") |
| 1180 |
|
| 1181 |
numTokens, err := strconv.Atoi(tokens) |
| 1182 |
if err != nil { |
| 1183 |
if tokens == "max" { |
| 1184 |
numTokens = refillTokenCount |
| 1185 |
} else { |
| 1186 |
numTokens = 0 |
| 1187 |
} |
| 1188 |
} |
| 1189 |
|
| 1190 |
setRateLimit(api, direction, repo, oid, numTokens) |
| 1191 |
debug(id, "Set rate limit:", api, direction, repo, oid, numTokens) |
| 1192 |
} |
| 1193 |
|
| 1194 |
type User struct { |
| 1195 |
Name string `json:"name"` |
| 1196 |
} |
| 1197 |
|
| 1198 |
type Lock struct { |
| 1199 |
Id string `json:"id"` |
| 1200 |
Path string `json:"path"` |
| 1201 |
Owner User `json:"owner"` |
| 1202 |
LockedAt time.Time `json:"locked_at"` |
| 1203 |
} |
| 1204 |
|
| 1205 |
type LockRequest struct { |
| 1206 |
Path string `json:"path"` |
| 1207 |
Ref *Ref `json:"ref,omitempty"` |
| 1208 |
} |
| 1209 |
|
| 1210 |
func (r *LockRequest) RefName() string { |
| 1211 |
if r.Ref == nil { |
| 1212 |
return "" |
| 1213 |
} |
| 1214 |
return r.Ref.Name |
| 1215 |
} |
| 1216 |
|
| 1217 |
type LockResponse struct { |
| 1218 |
Lock *Lock `json:"lock"` |
| 1219 |
Message string `json:"message,omitempty"` |
| 1220 |
} |
| 1221 |
|
| 1222 |
type UnlockRequest struct { |
| 1223 |
Force bool `json:"force"` |
| 1224 |
Ref *Ref `json:"ref,omitempty"` |
| 1225 |
} |
| 1226 |
|
| 1227 |
func (r *UnlockRequest) RefName() string { |
| 1228 |
if r.Ref == nil { |
| 1229 |
return "" |
| 1230 |
} |
| 1231 |
return r.Ref.Name |
| 1232 |
} |
| 1233 |
|
| 1234 |
type UnlockResponse struct { |
| 1235 |
Lock *Lock `json:"lock"` |
| 1236 |
Message string `json:"message,omitempty"` |
| 1237 |
} |
| 1238 |
|
| 1239 |
type LockList struct { |
| 1240 |
Locks []Lock `json:"locks"` |
| 1241 |
NextCursor string `json:"next_cursor,omitempty"` |
| 1242 |
Message string `json:"message,omitempty"` |
| 1243 |
} |
| 1244 |
|
| 1245 |
type Ref struct { |
| 1246 |
Name string `json:"name,omitempty"` |
| 1247 |
} |
| 1248 |
|
| 1249 |
type VerifiableLockRequest struct { |
| 1250 |
Ref *Ref `json:"ref,omitempty"` |
| 1251 |
Cursor string `json:"cursor,omitempty"` |
| 1252 |
Limit int `json:"limit,omitempty"` |
| 1253 |
} |
| 1254 |
|
| 1255 |
func (r *VerifiableLockRequest) RefName() string { |
| 1256 |
if r.Ref == nil { |
| 1257 |
return "" |
| 1258 |
} |
| 1259 |
return r.Ref.Name |
| 1260 |
} |
| 1261 |
|
| 1262 |
type VerifiableLockList struct { |
| 1263 |
Ours []Lock `json:"ours"` |
| 1264 |
Theirs []Lock `json:"theirs"` |
| 1265 |
NextCursor string `json:"next_cursor,omitempty"` |
| 1266 |
Message string `json:"message,omitempty"` |
| 1267 |
} |
| 1268 |
|
| 1269 |
var ( |
| 1270 |
lmu sync.RWMutex |
| 1271 |
repoLocks = map[string][]Lock{} |
| 1272 |
) |
| 1273 |
|
| 1274 |
func addLocks(repo string, l ...Lock) { |
| 1275 |
lmu.Lock() |
| 1276 |
defer lmu.Unlock() |
| 1277 |
repoLocks[repo] = append(repoLocks[repo], l...) |
| 1278 |
sort.Sort(LocksByCreatedAt(repoLocks[repo])) |
| 1279 |
} |
| 1280 |
|
| 1281 |
func getLocks(repo string) []Lock { |
| 1282 |
lmu.RLock() |
| 1283 |
defer lmu.RUnlock() |
| 1284 |
|
| 1285 |
locks := repoLocks[repo] |
| 1286 |
cp := make([]Lock, len(locks)) |
| 1287 |
for i, l := range locks { |
| 1288 |
cp[i] = l |
| 1289 |
} |
| 1290 |
|
| 1291 |
return cp |
| 1292 |
} |
| 1293 |
|
| 1294 |
func getFilteredLocks(repo, path, cursor, limit string) ([]Lock, string, error) { |
| 1295 |
locks := getLocks(repo) |
| 1296 |
if cursor != "" { |
| 1297 |
lastSeen := -1 |
| 1298 |
for i, l := range locks { |
| 1299 |
if l.Id == cursor { |
| 1300 |
lastSeen = i |
| 1301 |
break |
| 1302 |
} |
| 1303 |
} |
| 1304 |
|
| 1305 |
if lastSeen > -1 { |
| 1306 |
locks = locks[lastSeen:] |
| 1307 |
} else { |
| 1308 |
return nil, "", fmt.Errorf("cursor (%s) not found", cursor) |
| 1309 |
} |
| 1310 |
} |
| 1311 |
|
| 1312 |
if path != "" { |
| 1313 |
var filtered []Lock |
| 1314 |
for _, l := range locks { |
| 1315 |
if l.Path == path { |
| 1316 |
filtered = append(filtered, l) |
| 1317 |
} |
| 1318 |
} |
| 1319 |
|
| 1320 |
locks = filtered |
| 1321 |
} |
| 1322 |
|
| 1323 |
if limit != "" { |
| 1324 |
size, err := strconv.Atoi(limit) |
| 1325 |
if err != nil { |
| 1326 |
return nil, "", errors.New("unable to parse limit amount") |
| 1327 |
} |
| 1328 |
|
| 1329 |
size = int(math.Min(float64(len(locks)), 3)) |
| 1330 |
if size < 0 { |
| 1331 |
return nil, "", nil |
| 1332 |
} |
| 1333 |
|
| 1334 |
if size+1 < len(locks) { |
| 1335 |
return locks[:size], locks[size+1].Id, nil |
| 1336 |
} |
| 1337 |
} |
| 1338 |
|
| 1339 |
return locks, "", nil |
| 1340 |
} |
| 1341 |
|
| 1342 |
func delLock(repo string, id string) *Lock { |
| 1343 |
lmu.RLock() |
| 1344 |
defer lmu.RUnlock() |
| 1345 |
|
| 1346 |
var deleted *Lock |
| 1347 |
locks := make([]Lock, 0, len(repoLocks[repo])) |
| 1348 |
for _, l := range repoLocks[repo] { |
| 1349 |
if l.Id == id { |
| 1350 |
deleted = &l |
| 1351 |
continue |
| 1352 |
} |
| 1353 |
locks = append(locks, l) |
| 1354 |
} |
| 1355 |
repoLocks[repo] = locks |
| 1356 |
return deleted |
| 1357 |
} |
| 1358 |
|
| 1359 |
type LocksByCreatedAt []Lock |
| 1360 |
|
| 1361 |
func (c LocksByCreatedAt) Len() int { return len(c) } |
| 1362 |
func (c LocksByCreatedAt) Less(i, j int) bool { return c[i].LockedAt.Before(c[j].LockedAt) } |
| 1363 |
func (c LocksByCreatedAt) Swap(i, j int) { c[i], c[j] = c[j], c[i] } |
| 1364 |
|
| 1365 |
var ( |
| 1366 |
lockRe = regexp.MustCompile(`/locks/?$`) |
| 1367 |
unlockRe = regexp.MustCompile(`locks/([^/]+)/unlock\z`) |
| 1368 |
) |
| 1369 |
|
| 1370 |
func locksHandler(w http.ResponseWriter, r *http.Request, repo string) { |
| 1371 |
dec := json.NewDecoder(r.Body) |
| 1372 |
enc := json.NewEncoder(w) |
| 1373 |
|
| 1374 |
if repo == "netrctest" { |
| 1375 |
_, user, pass, err := extractAuth(r.Header.Get("Authorization")) |
| 1376 |
if err != nil || (user == "netrcuser" && pass == "badpassretry") { |
| 1377 |
writeLFSError(w, 401, "Error: Bad Auth") |
| 1378 |
return |
| 1379 |
} |
| 1380 |
} |
| 1381 |
|
| 1382 |
switch r.Method { |
| 1383 |
case "GET": |
| 1384 |
if !lockRe.MatchString(r.URL.Path) { |
| 1385 |
w.Header().Set("Content-Type", "application/json") |
| 1386 |
w.WriteHeader(http.StatusNotFound) |
| 1387 |
w.Write([]byte(`{"message":"unknown path: ` + r.URL.Path + `"}`)) |
| 1388 |
return |
| 1389 |
} |
| 1390 |
|
| 1391 |
if err := r.ParseForm(); err != nil { |
| 1392 |
http.Error(w, "could not parse form values", http.StatusInternalServerError) |
| 1393 |
return |
| 1394 |
} |
| 1395 |
|
| 1396 |
if strings.HasSuffix(repo, "branch-required") { |
| 1397 |
parts := strings.Split(repo, "-") |
| 1398 |
lenParts := len(parts) |
| 1399 |
if lenParts > 3 && "refs/heads/"+parts[lenParts-3] != r.FormValue("refspec") { |
| 1400 |
w.WriteHeader(403) |
| 1401 |
enc.Encode(struct { |
| 1402 |
Message string `json:"message"` |
| 1403 |
}{fmt.Sprintf("Expected ref %q, got %q", "refs/heads/"+parts[lenParts-3], r.FormValue("refspec"))}) |
| 1404 |
return |
| 1405 |
} |
| 1406 |
} |
| 1407 |
|
| 1408 |
ll := &LockList{} |
| 1409 |
w.Header().Set("Content-Type", "application/json") |
| 1410 |
locks, nextCursor, err := getFilteredLocks(repo, |
| 1411 |
r.FormValue("path"), |
| 1412 |
r.FormValue("cursor"), |
| 1413 |
r.FormValue("limit")) |
| 1414 |
|
| 1415 |
if err != nil { |
| 1416 |
ll.Message = err.Error() |
| 1417 |
} else { |
| 1418 |
ll.Locks = locks |
| 1419 |
ll.NextCursor = nextCursor |
| 1420 |
} |
| 1421 |
|
| 1422 |
enc.Encode(ll) |
| 1423 |
return |
| 1424 |
case "POST": |
| 1425 |
w.Header().Set("Content-Type", "application/json") |
| 1426 |
if strings.HasSuffix(r.URL.Path, "unlock") { |
| 1427 |
var lockId string |
| 1428 |
if matches := unlockRe.FindStringSubmatch(r.URL.Path); len(matches) > 1 { |
| 1429 |
lockId = matches[1] |
| 1430 |
} |
| 1431 |
|
| 1432 |
if len(lockId) == 0 { |
| 1433 |
enc.Encode(&UnlockResponse{Message: "Invalid lock"}) |
| 1434 |
} |
| 1435 |
|
| 1436 |
unlockRequest := &UnlockRequest{} |
| 1437 |
if err := dec.Decode(unlockRequest); err != nil { |
| 1438 |
enc.Encode(&UnlockResponse{Message: err.Error()}) |
| 1439 |
return |
| 1440 |
} |
| 1441 |
|
| 1442 |
if strings.HasSuffix(repo, "branch-required") { |
| 1443 |
parts := strings.Split(repo, "-") |
| 1444 |
lenParts := len(parts) |
| 1445 |
if lenParts > 3 && "refs/heads/"+parts[lenParts-3] != unlockRequest.RefName() { |
| 1446 |
w.WriteHeader(403) |
| 1447 |
enc.Encode(struct { |
| 1448 |
Message string `json:"message"` |
| 1449 |
}{fmt.Sprintf("Expected ref %q, got %q", "refs/heads/"+parts[lenParts-3], unlockRequest.RefName())}) |
| 1450 |
return |
| 1451 |
} |
| 1452 |
} |
| 1453 |
|
| 1454 |
if l := delLock(repo, lockId); l != nil { |
| 1455 |
enc.Encode(&UnlockResponse{Lock: l}) |
| 1456 |
} else { |
| 1457 |
enc.Encode(&UnlockResponse{Message: "unable to find lock"}) |
| 1458 |
} |
| 1459 |
return |
| 1460 |
} |
| 1461 |
|
| 1462 |
if strings.HasSuffix(r.URL.Path, "/locks/verify") { |
| 1463 |
if strings.HasSuffix(repo, "verify-5xx") { |
| 1464 |
w.WriteHeader(500) |
| 1465 |
return |
| 1466 |
} |
| 1467 |
if strings.HasSuffix(repo, "verify-501") { |
| 1468 |
w.WriteHeader(501) |
| 1469 |
return |
| 1470 |
} |
| 1471 |
if strings.HasSuffix(repo, "verify-403") { |
| 1472 |
w.WriteHeader(403) |
| 1473 |
return |
| 1474 |
} |
| 1475 |
|
| 1476 |
switch repo { |
| 1477 |
case "pre_push_locks_verify_404": |
| 1478 |
w.WriteHeader(http.StatusNotFound) |
| 1479 |
w.Write([]byte(`{"message":"pre_push_locks_verify_404"}`)) |
| 1480 |
return |
| 1481 |
case "pre_push_locks_verify_410": |
| 1482 |
w.WriteHeader(http.StatusGone) |
| 1483 |
w.Write([]byte(`{"message":"pre_push_locks_verify_410"}`)) |
| 1484 |
return |
| 1485 |
} |
| 1486 |
|
| 1487 |
reqBody := &VerifiableLockRequest{} |
| 1488 |
if err := dec.Decode(reqBody); err != nil { |
| 1489 |
w.WriteHeader(http.StatusBadRequest) |
| 1490 |
enc.Encode(struct { |
| 1491 |
Message string `json:"message"` |
| 1492 |
}{"json decode error: " + err.Error()}) |
| 1493 |
return |
| 1494 |
} |
| 1495 |
|
| 1496 |
if strings.HasSuffix(repo, "branch-required") { |
| 1497 |
parts := strings.Split(repo, "-") |
| 1498 |
lenParts := len(parts) |
| 1499 |
if lenParts > 3 && "refs/heads/"+parts[lenParts-3] != reqBody.RefName() { |
| 1500 |
w.WriteHeader(403) |
| 1501 |
enc.Encode(struct { |
| 1502 |
Message string `json:"message"` |
| 1503 |
}{fmt.Sprintf("Expected ref %q, got %q", "refs/heads/"+parts[lenParts-3], reqBody.RefName())}) |
| 1504 |
return |
| 1505 |
} |
| 1506 |
} |
| 1507 |
|
| 1508 |
ll := &VerifiableLockList{} |
| 1509 |
locks, nextCursor, err := getFilteredLocks(repo, "", |
| 1510 |
reqBody.Cursor, |
| 1511 |
strconv.Itoa(reqBody.Limit)) |
| 1512 |
if err != nil { |
| 1513 |
ll.Message = err.Error() |
| 1514 |
} else { |
| 1515 |
ll.NextCursor = nextCursor |
| 1516 |
|
| 1517 |
for _, l := range locks { |
| 1518 |
if strings.Contains(l.Path, "theirs") { |
| 1519 |
ll.Theirs = append(ll.Theirs, l) |
| 1520 |
} else { |
| 1521 |
ll.Ours = append(ll.Ours, l) |
| 1522 |
} |
| 1523 |
} |
| 1524 |
} |
| 1525 |
|
| 1526 |
enc.Encode(ll) |
| 1527 |
return |
| 1528 |
} |
| 1529 |
|
| 1530 |
if strings.HasSuffix(r.URL.Path, "/locks") { |
| 1531 |
lockRequest := &LockRequest{} |
| 1532 |
if err := dec.Decode(lockRequest); err != nil { |
| 1533 |
enc.Encode(&LockResponse{Message: err.Error()}) |
| 1534 |
} |
| 1535 |
|
| 1536 |
if strings.HasSuffix(repo, "branch-required") { |
| 1537 |
parts := strings.Split(repo, "-") |
| 1538 |
lenParts := len(parts) |
| 1539 |
if lenParts > 3 && "refs/heads/"+parts[lenParts-3] != lockRequest.RefName() { |
| 1540 |
w.WriteHeader(403) |
| 1541 |
enc.Encode(struct { |
| 1542 |
Message string `json:"message"` |
| 1543 |
}{fmt.Sprintf("Expected ref %q, got %q", "refs/heads/"+parts[lenParts-3], lockRequest.RefName())}) |
| 1544 |
return |
| 1545 |
} |
| 1546 |
} |
| 1547 |
|
| 1548 |
for _, l := range getLocks(repo) { |
| 1549 |
if l.Path == lockRequest.Path { |
| 1550 |
enc.Encode(&LockResponse{Message: "lock already created"}) |
| 1551 |
return |
| 1552 |
} |
| 1553 |
} |
| 1554 |
|
| 1555 |
var id [20]byte |
| 1556 |
rand.Read(id[:]) |
| 1557 |
|
| 1558 |
lock := &Lock{ |
| 1559 |
Id: fmt.Sprintf("%x", id[:]), |
| 1560 |
Path: lockRequest.Path, |
| 1561 |
Owner: User{Name: "Git LFS Tests"}, |
| 1562 |
LockedAt: time.Now(), |
| 1563 |
} |
| 1564 |
|
| 1565 |
addLocks(repo, *lock) |
| 1566 |
|
| 1567 |
|
| 1568 |
|
| 1569 |
|
| 1570 |
enc.Encode(&LockResponse{ |
| 1571 |
Lock: lock, |
| 1572 |
}) |
| 1573 |
return |
| 1574 |
} |
| 1575 |
} |
| 1576 |
|
| 1577 |
http.NotFound(w, r) |
| 1578 |
} |
| 1579 |
|
| 1580 |
func missingRequiredCreds(w http.ResponseWriter, r *http.Request, repo string) bool { |
| 1581 |
if !strings.HasPrefix(repo, "requirecreds") { |
| 1582 |
return false |
| 1583 |
} |
| 1584 |
|
| 1585 |
auth := r.Header.Get("Authorization") |
| 1586 |
if len(auth) == 0 { |
| 1587 |
writeLFSError(w, 401, "Error: Authorization Required") |
| 1588 |
return true |
| 1589 |
} |
| 1590 |
|
| 1591 |
_, user, pass, err := extractAuth(auth) |
| 1592 |
if err != nil { |
| 1593 |
writeLFSError(w, 403, err.Error()) |
| 1594 |
return true |
| 1595 |
} |
| 1596 |
|
| 1597 |
if user != "requirecreds" || pass != "pass" { |
| 1598 |
writeLFSError(w, 403, fmt.Sprintf("Got: '%s' => '%s' : '%s'", auth, user, pass)) |
| 1599 |
return true |
| 1600 |
} |
| 1601 |
|
| 1602 |
return false |
| 1603 |
} |
| 1604 |
|
| 1605 |
func testingChunkedTransferEncoding(repo string) bool { |
| 1606 |
return repo == "batch-storage-upload-encoding-chunked" |
| 1607 |
} |
| 1608 |
|
| 1609 |
func testingTusUploadInBatchReq(repo string) bool { |
| 1610 |
return strings.HasPrefix(repo, "batch-storage-upload-tus") |
| 1611 |
} |
| 1612 |
|
| 1613 |
func testingTusUploadInterruptedInBatchReq(repo string) bool { |
| 1614 |
return repo == "batch-storage-upload-tus-interrupt" |
| 1615 |
} |
| 1616 |
|
| 1617 |
func testingCustomTransfer(repo string) bool { |
| 1618 |
return strings.HasPrefix(repo, "custom-transfer-") |
| 1619 |
} |
| 1620 |
|
| 1621 |
var lfsUrlRE = regexp.MustCompile(`\A/?([^/]+)/info/lfs`) |
| 1622 |
|
| 1623 |
func repoFromLfsUrl(urlpath string) (string, error) { |
| 1624 |
matches := lfsUrlRE.FindStringSubmatch(urlpath) |
| 1625 |
if len(matches) != 2 { |
| 1626 |
return "", fmt.Errorf("LFS url '%s' does not match %v", urlpath, lfsUrlRE) |
| 1627 |
} |
| 1628 |
|
| 1629 |
repo := matches[1] |
| 1630 |
if strings.HasSuffix(repo, ".git") { |
| 1631 |
return repo[0 : len(repo)-4], nil |
| 1632 |
} |
| 1633 |
return repo, nil |
| 1634 |
} |
| 1635 |
|
| 1636 |
type lfsStorage struct { |
| 1637 |
objects map[string]map[string][]byte |
| 1638 |
incomplete map[string]map[string][]byte |
| 1639 |
mutex *sync.Mutex |
| 1640 |
} |
| 1641 |
|
| 1642 |
func (s *lfsStorage) Get(repo, oid string) ([]byte, bool) { |
| 1643 |
s.mutex.Lock() |
| 1644 |
defer s.mutex.Unlock() |
| 1645 |
repoObjects, ok := s.objects[repo] |
| 1646 |
if !ok { |
| 1647 |
return nil, ok |
| 1648 |
} |
| 1649 |
|
| 1650 |
by, ok := repoObjects[oid] |
| 1651 |
return by, ok |
| 1652 |
} |
| 1653 |
|
| 1654 |
func (s *lfsStorage) Has(repo, oid string) bool { |
| 1655 |
s.mutex.Lock() |
| 1656 |
defer s.mutex.Unlock() |
| 1657 |
repoObjects, ok := s.objects[repo] |
| 1658 |
if !ok { |
| 1659 |
return false |
| 1660 |
} |
| 1661 |
|
| 1662 |
_, ok = repoObjects[oid] |
| 1663 |
return ok |
| 1664 |
} |
| 1665 |
|
| 1666 |
func (s *lfsStorage) Set(repo, oid string, by []byte) { |
| 1667 |
s.mutex.Lock() |
| 1668 |
defer s.mutex.Unlock() |
| 1669 |
repoObjects, ok := s.objects[repo] |
| 1670 |
if !ok { |
| 1671 |
repoObjects = make(map[string][]byte) |
| 1672 |
s.objects[repo] = repoObjects |
| 1673 |
} |
| 1674 |
repoObjects[oid] = by |
| 1675 |
} |
| 1676 |
|
| 1677 |
func (s *lfsStorage) Delete(repo, oid string) { |
| 1678 |
s.mutex.Lock() |
| 1679 |
defer s.mutex.Unlock() |
| 1680 |
repoObjects, ok := s.objects[repo] |
| 1681 |
if ok { |
| 1682 |
delete(repoObjects, oid) |
| 1683 |
} |
| 1684 |
} |
| 1685 |
|
| 1686 |
func (s *lfsStorage) GetIncomplete(repo, oid string) ([]byte, bool) { |
| 1687 |
s.mutex.Lock() |
| 1688 |
defer s.mutex.Unlock() |
| 1689 |
repoObjects, ok := s.incomplete[repo] |
| 1690 |
if !ok { |
| 1691 |
return nil, ok |
| 1692 |
} |
| 1693 |
|
| 1694 |
by, ok := repoObjects[oid] |
| 1695 |
return by, ok |
| 1696 |
} |
| 1697 |
|
| 1698 |
func (s *lfsStorage) SetIncomplete(repo, oid string, by []byte) { |
| 1699 |
s.mutex.Lock() |
| 1700 |
defer s.mutex.Unlock() |
| 1701 |
repoObjects, ok := s.incomplete[repo] |
| 1702 |
if !ok { |
| 1703 |
repoObjects = make(map[string][]byte) |
| 1704 |
s.incomplete[repo] = repoObjects |
| 1705 |
} |
| 1706 |
repoObjects[oid] = by |
| 1707 |
} |
| 1708 |
|
| 1709 |
func (s *lfsStorage) DeleteIncomplete(repo, oid string) { |
| 1710 |
s.mutex.Lock() |
| 1711 |
defer s.mutex.Unlock() |
| 1712 |
repoObjects, ok := s.incomplete[repo] |
| 1713 |
if ok { |
| 1714 |
delete(repoObjects, oid) |
| 1715 |
} |
| 1716 |
} |
| 1717 |
|
| 1718 |
func newLfsStorage() *lfsStorage { |
| 1719 |
return &lfsStorage{ |
| 1720 |
objects: make(map[string]map[string][]byte), |
| 1721 |
incomplete: make(map[string]map[string][]byte), |
| 1722 |
mutex: &sync.Mutex{}, |
| 1723 |
} |
| 1724 |
} |
| 1725 |
|
| 1726 |
func extractAuth(auth string) (string, string, string, error) { |
| 1727 |
if strings.HasPrefix(auth, "Basic ") { |
| 1728 |
decodeBy, err := base64.StdEncoding.DecodeString(auth[6:len(auth)]) |
| 1729 |
decoded := string(decodeBy) |
| 1730 |
|
| 1731 |
if err != nil { |
| 1732 |
return "", "", "", err |
| 1733 |
} |
| 1734 |
|
| 1735 |
parts := strings.SplitN(decoded, ":", 2) |
| 1736 |
if len(parts) == 2 { |
| 1737 |
return "Basic", parts[0], parts[1], nil |
| 1738 |
} |
| 1739 |
return "", "", "", nil |
| 1740 |
} else if strings.HasPrefix(auth, "Bearer ") || strings.HasPrefix(auth, "Multistage ") { |
| 1741 |
authtype, cred, _ := strings.Cut(auth, " ") |
| 1742 |
return authtype, "", cred, nil |
| 1743 |
} |
| 1744 |
|
| 1745 |
return "", "", "", nil |
| 1746 |
} |
| 1747 |
|
| 1748 |
func skipIfNoCookie(w http.ResponseWriter, r *http.Request, id string) bool { |
| 1749 |
cookie := r.Header.Get("Cookie") |
| 1750 |
if strings.Contains(cookie, "secret") { |
| 1751 |
return false |
| 1752 |
} |
| 1753 |
|
| 1754 |
w.WriteHeader(403) |
| 1755 |
debug(id, "No cookie received: %q", r.URL.Path) |
| 1756 |
return true |
| 1757 |
} |
| 1758 |
|
| 1759 |
func skipIfBadAuth(w http.ResponseWriter, r *http.Request, id string) bool { |
| 1760 |
wantedAuth := "Basic realm=\"testsuite\"" |
| 1761 |
authHeader := "Lfs-Authenticate" |
| 1762 |
if strings.HasPrefix(r.URL.Path, "/auth-bearer") { |
| 1763 |
wantedAuth = "Bearer" |
| 1764 |
authHeader = "Www-Authenticate" |
| 1765 |
} |
| 1766 |
|
| 1767 |
if strings.HasPrefix(r.URL.Path, "/auth-multistage") { |
| 1768 |
wantedAuth = "Multistage type=foo" |
| 1769 |
authHeader = "Www-Authenticate" |
| 1770 |
} |
| 1771 |
|
| 1772 |
auth := r.Header.Get("Authorization") |
| 1773 |
if auth == "" { |
| 1774 |
w.Header().Add(authHeader, wantedAuth) |
| 1775 |
w.WriteHeader(401) |
| 1776 |
return true |
| 1777 |
} |
| 1778 |
|
| 1779 |
authtype, user, cred, err := extractAuth(auth) |
| 1780 |
if err != nil { |
| 1781 |
w.WriteHeader(403) |
| 1782 |
debug(id, "Error decoding auth: %s", err) |
| 1783 |
return true |
| 1784 |
} |
| 1785 |
|
| 1786 |
if !strings.HasPrefix(wantedAuth, authtype) { |
| 1787 |
w.WriteHeader(403) |
| 1788 |
debug(id, "Unwanted auth: %s (wanted %q)", authtype, wantedAuth) |
| 1789 |
return true |
| 1790 |
} |
| 1791 |
|
| 1792 |
switch authtype { |
| 1793 |
case "Basic": |
| 1794 |
switch user { |
| 1795 |
case "user": |
| 1796 |
if cred == "pass" { |
| 1797 |
return false |
| 1798 |
} |
| 1799 |
case "netrcuser", "requirecreds": |
| 1800 |
return false |
| 1801 |
case "path": |
| 1802 |
if strings.HasPrefix(r.URL.Path, "/"+cred) { |
| 1803 |
return false |
| 1804 |
} |
| 1805 |
debug(id, "auth attempt against: %q", r.URL.Path) |
| 1806 |
} |
| 1807 |
case "Bearer": |
| 1808 |
if cred == "token" { |
| 1809 |
return false |
| 1810 |
} |
| 1811 |
case "Multistage": |
| 1812 |
if matches := multiStageCredRE.FindStringSubmatch(cred); len(matches) == 3 { |
| 1813 |
if matches[1] == matches[2] { |
| 1814 |
return false |
| 1815 |
} else { |
| 1816 |
wantedAuth = "Multistage type=bar" |
| 1817 |
w.Header().Add(authHeader, wantedAuth) |
| 1818 |
w.WriteHeader(401) |
| 1819 |
debug(id, "auth stage %s of %s succeeded: %q", matches[1], matches[2], auth) |
| 1820 |
return true |
| 1821 |
} |
| 1822 |
} |
| 1823 |
} |
| 1824 |
|
| 1825 |
repo, _ := repoFromLfsUrl(r.URL.Path) |
| 1826 |
if strings.HasSuffix(repo, "-401-unauth") { |
| 1827 |
w.WriteHeader(401) |
| 1828 |
} else { |
| 1829 |
w.WriteHeader(403) |
| 1830 |
} |
| 1831 |
debug(id, "Bad auth: %q", auth) |
| 1832 |
return true |
| 1833 |
} |
| 1834 |
|
| 1835 |
func init() { |
| 1836 |
oidHandlers = make(map[string]string) |
| 1837 |
for _, content := range contentHandlers { |
| 1838 |
h := sha256.New() |
| 1839 |
h.Write([]byte(content)) |
| 1840 |
oidHandlers[hex.EncodeToString(h.Sum(nil))] = content |
| 1841 |
} |
| 1842 |
} |
| 1843 |
|
| 1844 |
func debug(reqid, msg string, args ...interface{}) { |
| 1845 |
fullargs := make([]interface{}, len(args)+1) |
| 1846 |
fullargs[0] = reqid |
| 1847 |
for i, a := range args { |
| 1848 |
fullargs[i+1] = a |
| 1849 |
} |
| 1850 |
log.Printf("[%s] "+msg+"\n", fullargs...) |
| 1851 |
} |
| 1852 |
|
| 1853 |
func reqId(w http.ResponseWriter) (string, bool) { |
| 1854 |
b := make([]byte, 16) |
| 1855 |
_, err := rand.Read(b) |
| 1856 |
if err != nil { |
| 1857 |
http.Error(w, "error generating id: "+err.Error(), 500) |
| 1858 |
return "", false |
| 1859 |
} |
| 1860 |
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]), true |
| 1861 |
} |
| 1862 |
|
| 1863 |
|
| 1864 |
func generateCARootCertificates() (rootKey *rsa.PrivateKey, rootCert *x509.Certificate) { |
| 1865 |
|
| 1866 |
|
| 1867 |
rootKey, err := rsa.GenerateKey(rand.Reader, 2048) |
| 1868 |
if err != nil { |
| 1869 |
log.Fatalf("generating random key: %v", err) |
| 1870 |
} |
| 1871 |
|
| 1872 |
rootCertTmpl, err := CertTemplate() |
| 1873 |
if err != nil { |
| 1874 |
log.Fatalf("creating cert template: %v", err) |
| 1875 |
} |
| 1876 |
|
| 1877 |
rootCertTmpl.IsCA = true |
| 1878 |
rootCertTmpl.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature |
| 1879 |
rootCertTmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth} |
| 1880 |
|
| 1881 |
|
| 1882 |
rootCert, _, err = CreateCert(rootCertTmpl, rootCertTmpl, &rootKey.PublicKey, rootKey) |
| 1883 |
|
| 1884 |
return |
| 1885 |
} |
| 1886 |
|
| 1887 |
func generateClientCertificates(rootCert *x509.Certificate, rootKey interface{}) (clientKey *rsa.PrivateKey, clientCertPEM []byte, clientKeyPEM []byte, clientKeyEncPEM []byte) { |
| 1888 |
|
| 1889 |
|
| 1890 |
clientKey, err := rsa.GenerateKey(rand.Reader, 2048) |
| 1891 |
if err != nil { |
| 1892 |
log.Fatalf("generating random key: %v", err) |
| 1893 |
} |
| 1894 |
|
| 1895 |
|
| 1896 |
clientCertTmpl, err1 := CertTemplate() |
| 1897 |
if err1 != nil { |
| 1898 |
log.Fatalf("creating cert template: %v", err1) |
| 1899 |
} |
| 1900 |
clientCertTmpl.KeyUsage = x509.KeyUsageDigitalSignature |
| 1901 |
clientCertTmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} |
| 1902 |
|
| 1903 |
|
| 1904 |
_, clientCertPEM, err2 := CreateCert(clientCertTmpl, rootCert, &clientKey.PublicKey, rootKey) |
| 1905 |
if err2 != nil { |
| 1906 |
log.Fatalf("error creating cert: %v", err2) |
| 1907 |
} |
| 1908 |
|
| 1909 |
privKey := x509.MarshalPKCS1PrivateKey(clientKey) |
| 1910 |
|
| 1911 |
|
| 1912 |
clientKeyPEM = pem.EncodeToMemory(&pem.Block{ |
| 1913 |
Type: "RSA PRIVATE KEY", Bytes: privKey, |
| 1914 |
}) |
| 1915 |
|
| 1916 |
clientKeyEnc, err := x509.EncryptPEMBlock(bytes.NewBuffer(privKey), "RSA PRIVATE KEY", privKey, ([]byte)("pass"), x509.PEMCipherAES128) |
| 1917 |
if err != nil { |
| 1918 |
log.Fatalf("creating encrypted private key: %v", err) |
| 1919 |
} |
| 1920 |
clientKeyEncPEM = pem.EncodeToMemory(clientKeyEnc) |
| 1921 |
|
| 1922 |
|
| 1923 |
|
| 1924 |
|
| 1925 |
dekInfoIndexes := dekInfoRE.FindSubmatchIndex(clientKeyEncPEM) |
| 1926 |
if dekInfoIndexes == nil || len(dekInfoIndexes) != 4 { |
| 1927 |
log.Fatalf("DEK-Info header not found in encrypted private key: %s", string(clientKeyEncPEM)) |
| 1928 |
} |
| 1929 |
for i := dekInfoIndexes[2]; i < dekInfoIndexes[3]; i++ { |
| 1930 |
c := clientKeyEncPEM[i] |
| 1931 |
if c >= 'a' && c <= 'f' { |
| 1932 |
clientKeyEncPEM[i] = byte(unicode.ToUpper(rune(c))) |
| 1933 |
} |
| 1934 |
} |
| 1935 |
|
| 1936 |
return |
| 1937 |
} |
| 1938 |
|
| 1939 |
|
| 1940 |
func CertTemplate() (*x509.Certificate, error) { |
| 1941 |
|
| 1942 |
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) |
| 1943 |
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) |
| 1944 |
if err != nil { |
| 1945 |
return nil, errors.New("failed to generate serial number: " + err.Error()) |
| 1946 |
} |
| 1947 |
|
| 1948 |
tmpl := x509.Certificate{ |
| 1949 |
SerialNumber: serialNumber, |
| 1950 |
Subject: pkix.Name{Organization: []string{"Yhat, Inc."}}, |
| 1951 |
SignatureAlgorithm: x509.SHA256WithRSA, |
| 1952 |
NotBefore: time.Now(), |
| 1953 |
NotAfter: time.Now().Add(time.Hour), |
| 1954 |
BasicConstraintsValid: true, |
| 1955 |
} |
| 1956 |
return &tmpl, nil |
| 1957 |
} |
| 1958 |
|
| 1959 |
func CreateCert(template, parent *x509.Certificate, pub interface{}, parentPriv interface{}) ( |
| 1960 |
cert *x509.Certificate, certPEM []byte, err error) { |
| 1961 |
|
| 1962 |
certDER, err := x509.CreateCertificate(rand.Reader, template, parent, pub, parentPriv) |
| 1963 |
if err != nil { |
| 1964 |
return |
| 1965 |
} |
| 1966 |
|
| 1967 |
cert, err = x509.ParseCertificate(certDER) |
| 1968 |
if err != nil { |
| 1969 |
return |
| 1970 |
} |
| 1971 |
|
| 1972 |
b := pem.Block{Type: "CERTIFICATE", Bytes: certDER} |
| 1973 |
certPEM = pem.EncodeToMemory(&b) |
| 1974 |
return |
| 1975 |
} |