package blossom import ( "bytes" "context" "encoding/base64" "io" "net/http" "net/http/cookiejar" "net/http/httptest" "strings" "sync" "testing" "time" "git.smesh.lol/orly/pkg/acl" "git.smesh.lol/orly/pkg/database" "git.smesh.lol/orly/pkg/musiquay/deed" "git.smesh.lol/orly/pkg/nostr/encoders/event" "git.smesh.lol/orly/pkg/nostr/encoders/hex" "git.smesh.lol/orly/pkg/nostr/encoders/kind" ) // TestHTTPGateEndToEnd drives the real handler stack: storage, catalog, gate, // session cookie, deed proof, and the serve hook. func TestHTTPGateEndToEnd(t *testing.T) { dir := t.TempDir() ctx, cancel := context.WithCancel(context.Background()) defer cancel() db, err := database.NewWithConfig(ctx, cancel, &database.DatabaseConfig{ DataDir: dir, LogLevel: "error", BlockCacheMB: 32, IndexCacheMB: 16, QueryCacheSizeMB: 16, }) if err != nil { t.Fatal(err) } defer db.Close() owner := gateSigner(t) buyer := gateSigner(t) body := []byte("musiquay lossless audio bytes") blob := hex.Enc(CalculateSHA256(body)) secret := make([]byte, 32) for i := range secret { secret[i] = byte(i + 1) } var mu sync.Mutex var serves []ServeInfo acl.Registry.SetMode("none") srv := NewServer(db, acl.Registry, &Config{ BaseURL: "http://blossom.example", MaxBlobSize: 10 * 1024 * 1024, Musiquay: &GateConfig{Host: "blossom.example", CookieSecret: secret}, OnServe: func(_ context.Context, info ServeInfo) { mu.Lock() serves = append(serves, info) mu.Unlock() }, }) if err = srv.storage.SaveBlob(CalculateSHA256(body), body, owner.Pub(), "audio/flac", ""); err != nil { t.Fatal(err) } assetEvent := gateEvent(t, owner, kind.Track.ToU16(), []string{"d", "track"}, []string{"x", blob}, []string{"price", "500", "sat"}, []string{"mint", "https://mint.example.com"}, ) assetID, err := deed.DeriveAssetID(assetEvent.ID) if err != nil { t.Fatal(err) } coord := "32210:" + hex.Enc(owner.Pub()) + ":track" record := gateEvent(t, owner, kind.AssetIdentity.ToU16(), []string{"d", assetID}, []string{"source", hex.Enc(assetEvent.ID)}, []string{"a", coord}, []string{"owner", hex.Enc(owner.Pub())}, ) filterEv := gateEvent(t, owner, kind.AccessFilter.ToU16(), []string{"d", "fan:" + coord}, []string{"filter", "gcs"}, []string{"n", "0"}, []string{"hash", "32"}, []string{"x", strings.Repeat("cd", 32)}, []string{"price", "500", "sat"}, []string{"mint", "https://mint.example.com"}, ) for _, ev := range []*event.E{assetEvent, record, filterEv} { if _, err = db.SaveEvent(ctx, ev); err != nil { t.Fatal(err) } } // A Secure cookie is only replayed over TLS, so the integration test uses an // HTTPS test server and its trusting client. ts := httptest.NewTLSServer(srv.Handler()) defer ts.Close() jar, _ := cookiejar.New(nil) client := ts.Client() client.Jar = jar client.Timeout = 30 * time.Second url := ts.URL + "/" + blob // 1. Anonymous: 401, no body, no receipt. status, hdr, respBody := doGet(t, client, url, nil) if status != http.StatusUnauthorized { t.Fatalf("anonymous: %d, want 401", status) } if len(serves) != 0 { t.Fatal("a refused request produced a receipt") } // 2. Identified but unentitled: 402 with a NUT-18 request. now := time.Now().Unix() authTok := makeToken(t, buyer, "get", blob, "blossom.example", now, now+300) status, hdr, _ = doGet(t, client, url, map[string]string{ "Authorization": authTok.header(base64.RawURLEncoding), }) if status != http.StatusPaymentRequired { t.Fatalf("unentitled: %d, want 402", status) } if !strings.HasPrefix(hdr.Get("X-Cashu"), "creqA") { t.Fatalf("402 X-Cashu is %q, want a creqA request", hdr.Get("X-Cashu")) } // 3. Valid deed and proof: 200 with the exact bytes. deedEv, err := deed.Issue(owner, deed.IssueOptions{ AssetID: assetID, Tier: deed.TierFan, Buyer: buyer.Pub(), PriceSats: 500, }) if err != nil { t.Fatal(err) } proof := gateEvent(t, buyer, kind.DeedPresentation.ToU16(), []string{"deed", hex.Enc(deedEv.ID)}, []string{"asset", assetID}, []string{"server", "blossom.example"}, []string{"nonce", "nonce-http-0001"}, []string{"expiration", itoa(time.Now().Add(2 * time.Minute).Unix())}, ) proof.Content = []byte(deed.PresentDomain) proof.ID = proof.GetIDBytes() if err = proof.Sign(buyer); err != nil { t.Fatal(err) } status, _, respBody = doGet(t, client, url, map[string]string{ "Authorization": authTok.header(base64.RawURLEncoding), DeedHeader: base64.RawURLEncoding.EncodeToString(mustJSON(t, deedEv)), DeedProofHeader: base64.RawURLEncoding.EncodeToString(mustJSON(t, proof)), }) if status != http.StatusOK { t.Fatalf("deed: %d, want 200", status) } if !bytes.Equal(respBody, body) { t.Fatal("deed response body does not match the blob") } // 4. The session cookie alone serves the next GET. status, _, respBody = doGet(t, client, url, nil) if status != http.StatusOK { t.Fatalf("cookie session: %d, want 200", status) } if !bytes.Equal(respBody, body) { t.Fatal("cookie response body does not match the blob") } mu.Lock() got := append([]ServeInfo(nil), serves...) mu.Unlock() if len(got) != 2 { t.Fatalf("hook fired %d times, want 2 (deed + cookie)", len(got)) } for _, s := range got { if s.AssetID != assetID || s.Blob != blob || s.Host != "http://blossom.example" { t.Fatalf("serve info wrong: %+v", s) } if !bytes.Equal(s.Buyer, buyer.Pub()) { t.Fatal("serve info has the wrong buyer") } if s.Mode != "download" || s.Bytes != int64(len(body)) { t.Fatalf("serve info mode/bytes wrong: %+v", s) } } } func doGet(t *testing.T, client *http.Client, url string, headers map[string]string) (int, http.Header, []byte) { t.Helper() req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { t.Fatal(err) } for k, v := range headers { req.Header.Set(k, v) } resp, err := client.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() b, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } return resp.StatusCode, resp.Header, b }