package httpapi import ( "crypto/rand" "crypto/sha256" "database/sql" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "os" osexec "os/exec" "path/filepath" "strings" "sync" "testing" "time" ) func TestDownloadsMySQLIntegration(t *testing.T) { dsn := os.Getenv("DOWNLOAD_TEST_DSN") if dsn == "" { t.Skip("DOWNLOAD_TEST_DSN must name an isolated migrated database") } db, err := sql.Open("mysql", dsn) if err != nil { t.Fatal(err) } defer db.Close() root := t.TempDir() t.Setenv("PACKAGE_STORAGE_ROOT", root) exec := func(q string, args ...any) int64 { t.Helper() r, e := db.Exec(q, args...) if e != nil { t.Fatal(e) } id, _ := r.LastInsertId() return id } suffix := fmt.Sprint(time.Now().UnixNano()) admin := exec("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", suffix, suffix+"@download.test", "unused") raw := make([]byte, 32) rand.Read(raw) sessionHash := sha256.Sum256(raw) exec("INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", admin, sessionHash[:], time.Now().Add(time.Hour)) cookie := &http.Cookie{Name: "lp_session", Value: hex.EncodeToString(raw)} customer := exec("INSERT INTO customers(name,contact_email) VALUES(?,'download@example.test')", suffix) otherCustomer := exec("INSERT INTO customers(name,contact_email) VALUES(?,'other@example.test')", suffix+"other") product := exec("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix, suffix) otherProduct := exec("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix+"other", suffix) license := exec("INSERT INTO licenses(license_key,customer_id,product_id,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,?,?,?,?)", hex.EncodeToString(raw[:16]), customer, product, time.Now().Add(-time.Hour), time.Now().Add(time.Hour), suffix, admin) secret := make([]byte, 32) rand.Read(secret) secretHash := sha256.Sum256(secret) instanceID, _ := newInstanceID() instanceRow := exec("INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,status,created_by) VALUES(?,?,?,?,?,'activated',?)", instanceID, license, customer, product, secretHash[:], admin) r := NewRouter() RegisterBusiness(r, db) req := func(path string, body io.Reader, auth bool) *httptest.ResponseRecorder { q := httptest.NewRequest("POST", path, body) if auth { q.AddCookie(cookie) } w := httptest.NewRecorder() r.ServeHTTP(w, q) return w } publish := func(p int64, v, body string, auth bool) *httptest.ResponseRecorder { return req(fmt.Sprintf("/api/v1/products/%d/releases?version=%s", p, v), strings.NewReader(body), auth) } releaseID := func(w *httptest.ResponseRecorder) int64 { t.Helper() if w.Code != 201 { t.Fatalf("publish %d %s", w.Code, w.Body) } var out struct{ Data struct{ ID int64 } } if e := json.Unmarshal(w.Body.Bytes(), &out); e != nil { t.Fatal(e) } return out.Data.ID } if w := publish(product, "unauth", "body", false); w.Code != 401 { t.Fatal(w.Code) } id := releaseID(publish(product, "v1", "package bytes", true)) otherID := releaseID(publish(otherProduct, "v1", "other bytes", true)) download := func(cust, id int64, sec string) *httptest.ResponseRecorder { body, _ := json.Marshal(map[string]string{"instance_id": instanceID, "secret": sec}) return req(fmt.Sprintf("/api/v1/customers/%d/releases/%d/download", cust, id), strings.NewReader(string(body)), false) } encoded := base64.RawURLEncoding.EncodeToString(secret) auditCount := func(action string) int { t.Helper() var n int if err := db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action=? AND resource_type='license_instance' AND resource_id=?", action, instanceRow).Scan(&n); err != nil { t.Fatal(err) } return n } check := func(cust, id int64, sec string, code int) { t.Helper() w := download(cust, id, sec) if w.Code != code { t.Fatalf("download %d want %d: %s", w.Code, code, w.Body) } if code != 200 && w.Header().Get("X-Accel-Redirect") != "" { t.Fatal("denied request exposes file redirect") } } check(customer, id, encoded, 200) deniedBefore := auditCount("release.download_denied") exec("UPDATE licenses SET expires_at=? WHERE id=?", time.Now().Add(-time.Minute), license) check(customer, id, encoded, 403) if auditCount("release.download_denied") != deniedBefore+1 { t.Fatal("expired download was not audited") } exec("UPDATE licenses SET expires_at=? WHERE id=?", time.Now().Add(time.Hour), license) unpublished := exec("INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,published,created_by) VALUES(?,?,?,?,?,0,?)", product, "unpublished", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bin", strings.Repeat("a", 64), 1, admin) deniedBefore = auditCount("release.download_denied") check(customer, unpublished, encoded, 403) if auditCount("release.download_denied") != deniedBefore+1 { t.Fatal("unpublished download was not audited") } deniedBefore = auditCount("release.download_denied") check(customer, id+999999, encoded, 403) if auditCount("release.download_denied") != deniedBefore+1 { t.Fatal("missing release was not audited") } check(otherCustomer, id, encoded, 403) check(customer, otherID, encoded, 403) check(customer, id, base64.RawURLEncoding.EncodeToString(make([]byte, 32)), 403) for _, state := range []struct{ deny, restore string }{ {"UPDATE license_instances SET freeze_state='frozen' WHERE license_id=?", "UPDATE license_instances SET freeze_state='none' WHERE license_id=?"}, {"UPDATE licenses SET status='revoked' WHERE id=?", "UPDATE licenses SET status='active' WHERE id=?"}, } { exec(state.deny, license) check(customer, id, encoded, 403) exec(state.restore, license) } exec("UPDATE customers SET status='inactive' WHERE id=?", customer) check(customer, id, encoded, 403) exec("UPDATE customers SET status='active' WHERE id=?", customer) exec("UPDATE products SET active=0 WHERE id=?", product) check(customer, id, encoded, 403) exec("UPDATE products SET active=1 WHERE id=?", product) exec("CREATE TRIGGER download_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'") t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS download_audit_failure") }) check(customer, id, encoded, 500) failedBody := "audit fails unique body" digest := sha256.Sum256([]byte(failedBody)) if w := publish(product, "audit-fails", failedBody, true); w.Code != 500 { t.Fatalf("audit upload %d", w.Code) } var count int db.QueryRow("SELECT COUNT(*) FROM product_releases WHERE version='audit-fails'").Scan(&count) if count != 0 { t.Fatal("failed release committed") } if _, e := os.Stat(filepath.Join(root, hex.EncodeToString(digest[:])+".bin")); !os.IsNotExist(e) { t.Fatal("failed upload left new file") } exec("DROP TRIGGER download_audit_failure") var wg sync.WaitGroup codes := make(chan int, 2) for i, p := range []int64{product, otherProduct} { wg.Add(1) go func(i int, p int64) { defer wg.Done() codes <- publish(p, fmt.Sprintf("concurrent-%d", i), "same digest bytes", true).Code }(i, p) } wg.Wait() close(codes) for code := range codes { if code != 201 { t.Fatalf("concurrent digest %d", code) } } digest = sha256.Sum256([]byte("same digest bytes")) data, e := os.ReadFile(filepath.Join(root, hex.EncodeToString(digest[:])+".bin")) if e != nil || string(data) != "same digest bytes" { t.Fatal("shared digest damaged") } if w := publish(product, "v1", "conflicting version bytes", true); w.Code != 409 { t.Fatal(w.Code) } if w := publish(product, "empty", "", true); w.Code != 400 { t.Fatal(w.Code) } for _, n := range []int64{64 << 20, (64 << 20) + 1} { w := req(fmt.Sprintf("/api/v1/products/%d/releases?version=limit-%d", product, n), io.LimitReader(zeroReader{}, n), true) want := 201 if n > 64<<20 { want = 400 } if w.Code != want { t.Fatalf("size %d code=%d want=%d %s", n, w.Code, want, w.Body) } } files, _ := filepath.Glob(filepath.Join(root, ".upload-*")) if len(files) != 0 { t.Fatal("temporary uploads leaked") } if os.Getenv("DOWNLOAD_NGINX_E2E") == "1" { server := &http.Server{Addr: "0.0.0.0:18082", Handler: r} go server.ListenAndServe() defer server.Close() conf, _ := filepath.Abs("../../../deploy/nginx/download-local.conf") cmd := osexec.Command("docker", "run", "-d", "--name", "license-download-e2e", "-p", "127.0.0.1:18181:18181", "--mount", "type=bind,source="+root+",target=/srv/license-packages,readonly", "--mount", "type=bind,source="+conf+",target=/etc/nginx/conf.d/default.conf,readonly", "nginx:stable-alpine") if out, e := cmd.CombinedOutput(); e != nil { t.Fatalf("nginx start: %v %s", e, out) } defer osexec.Command("docker", "stop", "license-download-e2e").Run() defer osexec.Command("docker", "rm", "-f", "license-download-e2e").Run() time.Sleep(2 * time.Second) client := &http.Client{Timeout: 10 * time.Second} body, _ := json.Marshal(map[string]string{"instance_id": instanceID, "secret": encoded}) url := fmt.Sprintf("http://127.0.0.1:18181/api/v1/customers/%d/releases/%d/download", customer, id) for _, partial := range []bool{false, true} { q, _ := http.NewRequest("POST", url, strings.NewReader(string(body))) q.Header.Set("Content-Type", "application/json") if partial { q.Header.Set("Range", "bytes=0-6") } resp, e := client.Do(q) if e != nil { t.Fatal(e) } b, _ := io.ReadAll(resp.Body) resp.Body.Close() if partial { if resp.StatusCode != 206 || string(b) != "package" { t.Fatalf("range %d %q", resp.StatusCode, b) } } else { sum := sha256.Sum256(b) if resp.StatusCode != 200 || string(b) != "package bytes" || hex.EncodeToString(sum[:]) != resp.Header.Get("X-Package-SHA256") { t.Fatalf("bytes/hash %d %q", resp.StatusCode, b) } } } direct := download(customer, id, encoded).Header().Get("X-Accel-Redirect") resp, e := client.Get("http://127.0.0.1:18181" + direct) if e != nil { t.Fatal(e) } resp.Body.Close() if resp.StatusCode != 404 && resp.StatusCode != 403 { t.Fatalf("public internal path %d", resp.StatusCode) } resp, e = client.Post(url, "application/json", strings.NewReader("{}")) if e != nil { t.Fatal(e) } resp.Body.Close() if resp.StatusCode < 400 { t.Fatal("unauthenticated download succeeded") } t.Log("Nginx 18181: actual bytes/SHA256, Range 206, external internal-path denial and unauthenticated denial verified; temporary E2E service stopped") } t.Log("customer/product/state isolation, wrong secret, audit rollback, file cleanup, duplicate digest concurrency and exact 64MiB boundary verified") } type zeroReader struct{} func (zeroReader) Read(p []byte) (int, error) { clear(p); return len(p), nil }