http_gate_test.go raw

   1  package blossom
   2  
   3  import (
   4  	"bytes"
   5  	"context"
   6  	"encoding/base64"
   7  	"io"
   8  	"net/http"
   9  	"net/http/cookiejar"
  10  	"net/http/httptest"
  11  	"strings"
  12  	"sync"
  13  	"testing"
  14  	"time"
  15  
  16  	"git.smesh.lol/orly/pkg/acl"
  17  	"git.smesh.lol/orly/pkg/database"
  18  	"git.smesh.lol/orly/pkg/musiquay/deed"
  19  	"git.smesh.lol/orly/pkg/nostr/encoders/event"
  20  	"git.smesh.lol/orly/pkg/nostr/encoders/hex"
  21  	"git.smesh.lol/orly/pkg/nostr/encoders/kind"
  22  )
  23  
  24  // TestHTTPGateEndToEnd drives the real handler stack: storage, catalog, gate,
  25  // session cookie, deed proof, and the serve hook.
  26  func TestHTTPGateEndToEnd(t *testing.T) {
  27  	dir := t.TempDir()
  28  	ctx, cancel := context.WithCancel(context.Background())
  29  	defer cancel()
  30  	db, err := database.NewWithConfig(ctx, cancel, &database.DatabaseConfig{
  31  		DataDir: dir, LogLevel: "error",
  32  		BlockCacheMB: 32, IndexCacheMB: 16, QueryCacheSizeMB: 16,
  33  	})
  34  	if err != nil {
  35  		t.Fatal(err)
  36  	}
  37  	defer db.Close()
  38  
  39  	owner := gateSigner(t)
  40  	buyer := gateSigner(t)
  41  	body := []byte("musiquay lossless audio bytes")
  42  	blob := hex.Enc(CalculateSHA256(body))
  43  
  44  	secret := make([]byte, 32)
  45  	for i := range secret {
  46  		secret[i] = byte(i + 1)
  47  	}
  48  	var mu sync.Mutex
  49  	var serves []ServeInfo
  50  	acl.Registry.SetMode("none")
  51  	srv := NewServer(db, acl.Registry, &Config{
  52  		BaseURL:     "http://blossom.example",
  53  		MaxBlobSize: 10 * 1024 * 1024,
  54  		Musiquay:    &GateConfig{Host: "blossom.example", CookieSecret: secret},
  55  		OnServe: func(_ context.Context, info ServeInfo) {
  56  			mu.Lock()
  57  			serves = append(serves, info)
  58  			mu.Unlock()
  59  		},
  60  	})
  61  	if err = srv.storage.SaveBlob(CalculateSHA256(body), body, owner.Pub(), "audio/flac", ""); err != nil {
  62  		t.Fatal(err)
  63  	}
  64  
  65  	assetEvent := gateEvent(t, owner, kind.Track.ToU16(),
  66  		[]string{"d", "track"},
  67  		[]string{"x", blob},
  68  		[]string{"price", "500", "sat"},
  69  		[]string{"mint", "https://mint.example.com"},
  70  	)
  71  	assetID, err := deed.DeriveAssetID(assetEvent.ID)
  72  	if err != nil {
  73  		t.Fatal(err)
  74  	}
  75  	coord := "32210:" + hex.Enc(owner.Pub()) + ":track"
  76  	record := gateEvent(t, owner, kind.AssetIdentity.ToU16(),
  77  		[]string{"d", assetID},
  78  		[]string{"source", hex.Enc(assetEvent.ID)},
  79  		[]string{"a", coord},
  80  		[]string{"owner", hex.Enc(owner.Pub())},
  81  	)
  82  	filterEv := gateEvent(t, owner, kind.AccessFilter.ToU16(),
  83  		[]string{"d", "fan:" + coord},
  84  		[]string{"filter", "gcs"},
  85  		[]string{"n", "0"},
  86  		[]string{"hash", "32"},
  87  		[]string{"x", strings.Repeat("cd", 32)},
  88  		[]string{"price", "500", "sat"},
  89  		[]string{"mint", "https://mint.example.com"},
  90  	)
  91  	for _, ev := range []*event.E{assetEvent, record, filterEv} {
  92  		if _, err = db.SaveEvent(ctx, ev); err != nil {
  93  			t.Fatal(err)
  94  		}
  95  	}
  96  
  97  	// A Secure cookie is only replayed over TLS, so the integration test uses an
  98  	// HTTPS test server and its trusting client.
  99  	ts := httptest.NewTLSServer(srv.Handler())
 100  	defer ts.Close()
 101  	jar, _ := cookiejar.New(nil)
 102  	client := ts.Client()
 103  	client.Jar = jar
 104  	client.Timeout = 30 * time.Second
 105  	url := ts.URL + "/" + blob
 106  
 107  	// 1. Anonymous: 401, no body, no receipt.
 108  	status, hdr, respBody := doGet(t, client, url, nil)
 109  	if status != http.StatusUnauthorized {
 110  		t.Fatalf("anonymous: %d, want 401", status)
 111  	}
 112  	if len(serves) != 0 {
 113  		t.Fatal("a refused request produced a receipt")
 114  	}
 115  
 116  	// 2. Identified but unentitled: 402 with a NUT-18 request.
 117  	now := time.Now().Unix()
 118  	authTok := makeToken(t, buyer, "get", blob, "blossom.example", now, now+300)
 119  	status, hdr, _ = doGet(t, client, url, map[string]string{
 120  		"Authorization": authTok.header(base64.RawURLEncoding),
 121  	})
 122  	if status != http.StatusPaymentRequired {
 123  		t.Fatalf("unentitled: %d, want 402", status)
 124  	}
 125  	if !strings.HasPrefix(hdr.Get("X-Cashu"), "creqA") {
 126  		t.Fatalf("402 X-Cashu is %q, want a creqA request", hdr.Get("X-Cashu"))
 127  	}
 128  
 129  	// 3. Valid deed and proof: 200 with the exact bytes.
 130  	deedEv, err := deed.Issue(owner, deed.IssueOptions{
 131  		AssetID: assetID, Tier: deed.TierFan, Buyer: buyer.Pub(), PriceSats: 500,
 132  	})
 133  	if err != nil {
 134  		t.Fatal(err)
 135  	}
 136  	proof := gateEvent(t, buyer, kind.DeedPresentation.ToU16(),
 137  		[]string{"deed", hex.Enc(deedEv.ID)},
 138  		[]string{"asset", assetID},
 139  		[]string{"server", "blossom.example"},
 140  		[]string{"nonce", "nonce-http-0001"},
 141  		[]string{"expiration", itoa(time.Now().Add(2 * time.Minute).Unix())},
 142  	)
 143  	proof.Content = []byte(deed.PresentDomain)
 144  	proof.ID = proof.GetIDBytes()
 145  	if err = proof.Sign(buyer); err != nil {
 146  		t.Fatal(err)
 147  	}
 148  	status, _, respBody = doGet(t, client, url, map[string]string{
 149  		"Authorization": authTok.header(base64.RawURLEncoding),
 150  		DeedHeader:      base64.RawURLEncoding.EncodeToString(mustJSON(t, deedEv)),
 151  		DeedProofHeader: base64.RawURLEncoding.EncodeToString(mustJSON(t, proof)),
 152  	})
 153  	if status != http.StatusOK {
 154  		t.Fatalf("deed: %d, want 200", status)
 155  	}
 156  	if !bytes.Equal(respBody, body) {
 157  		t.Fatal("deed response body does not match the blob")
 158  	}
 159  
 160  	// 4. The session cookie alone serves the next GET.
 161  	status, _, respBody = doGet(t, client, url, nil)
 162  	if status != http.StatusOK {
 163  		t.Fatalf("cookie session: %d, want 200", status)
 164  	}
 165  	if !bytes.Equal(respBody, body) {
 166  		t.Fatal("cookie response body does not match the blob")
 167  	}
 168  
 169  	mu.Lock()
 170  	got := append([]ServeInfo(nil), serves...)
 171  	mu.Unlock()
 172  	if len(got) != 2 {
 173  		t.Fatalf("hook fired %d times, want 2 (deed + cookie)", len(got))
 174  	}
 175  	for _, s := range got {
 176  		if s.AssetID != assetID || s.Blob != blob || s.Host != "http://blossom.example" {
 177  			t.Fatalf("serve info wrong: %+v", s)
 178  		}
 179  		if !bytes.Equal(s.Buyer, buyer.Pub()) {
 180  			t.Fatal("serve info has the wrong buyer")
 181  		}
 182  		if s.Mode != "download" || s.Bytes != int64(len(body)) {
 183  			t.Fatalf("serve info mode/bytes wrong: %+v", s)
 184  		}
 185  	}
 186  }
 187  
 188  func doGet(t *testing.T, client *http.Client, url string, headers map[string]string) (int, http.Header, []byte) {
 189  	t.Helper()
 190  	req, err := http.NewRequest(http.MethodGet, url, nil)
 191  	if err != nil {
 192  		t.Fatal(err)
 193  	}
 194  	for k, v := range headers {
 195  		req.Header.Set(k, v)
 196  	}
 197  	resp, err := client.Do(req)
 198  	if err != nil {
 199  		t.Fatal(err)
 200  	}
 201  	defer resp.Body.Close()
 202  	b, err := io.ReadAll(resp.Body)
 203  	if err != nil {
 204  		t.Fatal(err)
 205  	}
 206  	return resp.StatusCode, resp.Header, b
 207  }
 208