control_test.go raw

   1  package net
   2  
   3  import (
   4  	"encoding/json"
   5  	"os"
   6  	"path/filepath"
   7  	"strings"
   8  	"testing"
   9  	"time"
  10  
  11  	"git.smesh.lol/torly/pkg/config"
  12  	"git.smesh.lol/torly/pkg/policy"
  13  )
  14  
  15  const (
  16  	gatewayKey = "8964ed8cae7cb41286f9dc56344154f9491eace55ad6a18d7fb025ac02ec18a7"
  17  	adminKey   = "d023f6eabdd55360e9d29d45dcc0d8a8a49e6708de7cdecd7e86f5eb93e599b8"
  18  	strangerK  = "185624337e5c27e9ccc3ea29a313715097f867dcea21a50be1b54eb2203de8de"
  19  )
  20  
  21  // controlServer builds the smallest relay that has a policy and a ledger.
  22  func controlServer(t *testing.T, ledger Ledger) *server {
  23  	t.Helper()
  24  
  25  	dir := t.TempDir()
  26  	policyPath := filepath.Join(dir, "policy.json")
  27  
  28  	doc := `{"version":1,"default":"deny","rules":[
  29  		{"kinds":[30333],"require_auth":true,"authors":["` + gatewayKey + `"]},
  30  		{"kinds":[23196]}]}`
  31  
  32  	if err := os.WriteFile(policyPath, []byte(doc), 0o600); err != nil {
  33  		t.Fatal(err)
  34  	}
  35  
  36  	engine, err := policy.Load(policyPath)
  37  
  38  	if err != nil {
  39  		t.Fatal(err)
  40  	}
  41  
  42  	body, err := json.Marshal(ledger)
  43  
  44  	if err != nil {
  45  		t.Fatal(err)
  46  	}
  47  
  48  	ledgerPath := filepath.Join(dir, "subscriptions.json")
  49  
  50  	if err := os.WriteFile(ledgerPath, body, 0o600); err != nil {
  51  		t.Fatal(err)
  52  	}
  53  
  54  	t.Setenv("TORLY_LEDGER_FILE", ledgerPath)
  55  	t.Setenv("TORLY_ADMINS", adminKey)
  56  
  57  	return &server{data: Data{Cfg: config.Config{Policy: engine, DataDir: dir}}}
  58  }
  59  
  60  func paidLedger() Ledger {
  61  	return Ledger{
  62  		RateSatsPerDay: 1000,
  63  		Subscriptions: map[string]Subscription{
  64  			gatewayKey: {Gateway: gatewayKey, TotalSats: 2000,
  65  				PaidUntil: time.Now().Add(48 * time.Hour).UTC().Format(time.RFC3339)},
  66  		},
  67  	}
  68  }
  69  
  70  // TestTheRelayAnswersAPaidGateway: the signer is the identity, so the answer is about the signer and
  71  // the remaining time comes from the ledger.
  72  func TestTheRelayAnswersAPaidGateway(t *testing.T) {
  73  	s := controlServer(t, paidLedger())
  74  
  75  	answer := s.subscriptionAnswer(gatewayKey)
  76  
  77  	if answer["paid"] != true {
  78  		t.Fatalf("a paid gateway was reported unpaid: %v", answer)
  79  	}
  80  
  81  	if seconds, _ := answer["remaining_seconds"].(int64); seconds < 47*3600 {
  82  		t.Fatalf("remaining time: %v", answer["remaining_seconds"])
  83  	}
  84  
  85  	// A stranger gets a truthful answer too, but it says no: nothing is invented for a key that
  86  	// has never paid.
  87  	stranger := s.subscriptionAnswer(strangerK)
  88  
  89  	if stranger["paid"] != false || stranger["remaining_seconds"].(int64) != 0 {
  90  		t.Fatalf("unpaid answer: %v", stranger)
  91  	}
  92  }
  93  
  94  // TestTheControlKindIsRefusedToStrangers: only an authorised gateway may ask, and only an admin may
  95  // change the relay's settings.
  96  func TestTheControlKindIsRefusedToStrangers(t *testing.T) {
  97  	s := controlServer(t, paidLedger())
  98  
  99  	if s.authorizedGateway(strangerK) {
 100  		t.Fatal("a key that is not a gateway was authorised")
 101  	}
 102  
 103  	if !s.authorizedGateway(gatewayKey) {
 104  		t.Fatal("the configured gateway was not authorised")
 105  	}
 106  
 107  	if s.adminKey(strangerK) {
 108  		t.Fatal("a stranger was treated as an admin")
 109  	}
 110  
 111  	if !s.adminKey(adminKey) {
 112  		t.Fatal("the configured admin was not recognised")
 113  	}
 114  }
 115  
 116  // TestAnUnpaidGatewayIsRefusedAndAPaidOneIsNot: the gate that makes a price mean anything.
 117  func TestAnUnpaidGatewayIsRefusedAndAPaidOneIsNot(t *testing.T) {
 118  	paid := controlServer(t, paidLedger())
 119  
 120  	if allowed, reason := paid.paidGateway(gatewayKey); !allowed {
 121  		t.Fatalf("a paid gateway was refused: %s", reason)
 122  	}
 123  
 124  	lapsed := controlServer(t, Ledger{
 125  		RateSatsPerDay: 1000,
 126  		Subscriptions: map[string]Subscription{
 127  			gatewayKey: {PaidUntil: time.Now().Add(-time.Hour).UTC().Format(time.RFC3339)},
 128  		},
 129  	})
 130  
 131  	allowed, reason := lapsed.paidGateway(gatewayKey)
 132  
 133  	if allowed || !strings.Contains(reason, "payment-required") {
 134  		t.Fatalf("a lapsed gateway was admitted: %v %s", allowed, reason)
 135  	}
 136  
 137  	// A relay that charges nobody does not need a subscription to exist.
 138  	free := controlServer(t, Ledger{})
 139  
 140  	if allowed, _ := free.paidGateway(gatewayKey); !allowed {
 141  		t.Fatal("a relay with no rate refused a gateway")
 142  	}
 143  }
 144  
 145  // TestTheOperatorCanBlockAPaidGateway: payment buys time, not permission.
 146  func TestTheOperatorCanBlockAPaidGateway(t *testing.T) {
 147  	ledger := paidLedger()
 148  	ledger.Blocked = map[string]bool{gatewayKey: true}
 149  
 150  	s := controlServer(t, ledger)
 151  
 152  	allowed, reason := s.paidGateway(gatewayKey)
 153  
 154  	if allowed || !strings.Contains(reason, "blocked") {
 155  		t.Fatalf("a blocked gateway was admitted: %v %s", allowed, reason)
 156  	}
 157  
 158  	if answer := s.subscriptionAnswer(gatewayKey); answer["blocked"] != true {
 159  		t.Fatalf("the answer does not mention the block: %v", answer)
 160  	}
 161  }
 162  
 163  // TestTheDefaultIsFree: a relay that has never configured a price charges nothing and admits every
 164  // gateway it authorises. Billing must be switched on deliberately, not inherited from a missing or
 165  // unreadable ledger.
 166  func TestTheDefaultIsFree(t *testing.T) {
 167  	dir := t.TempDir()
 168  	policyPath := filepath.Join(dir, "policy.json")
 169  
 170  	doc := `{"version":1,"default":"deny","rules":[
 171  		{"kinds":[30333],"require_auth":true,"authors":["` + gatewayKey + `"]}]}`
 172  
 173  	if err := os.WriteFile(policyPath, []byte(doc), 0o600); err != nil {
 174  		t.Fatal(err)
 175  	}
 176  
 177  	engine, err := policy.Load(policyPath)
 178  
 179  	if err != nil {
 180  		t.Fatal(err)
 181  	}
 182  
 183  	// No ledger file at all: the ordinary state of a relay nobody has billed on yet.
 184  	t.Setenv("TORLY_LEDGER_FILE", filepath.Join(dir, "does-not-exist.json"))
 185  	t.Setenv("TORLY_ADMINS", "")
 186  
 187  	s := &server{data: Data{Cfg: config.Config{Policy: engine, DataDir: dir}}}
 188  
 189  	if allowed, reason := s.paidGateway(gatewayKey); !allowed {
 190  		t.Fatalf("a relay with no ledger refused a gateway: %s", reason)
 191  	}
 192  
 193  	answer := s.subscriptionAnswer(gatewayKey)
 194  
 195  	if answer["paid"] != true || answer["rate_sats_per_day"].(int64) != 0 {
 196  		t.Fatalf("the default answer is not free: %v", answer)
 197  	}
 198  
 199  	// And a ledger that cannot be parsed is the same state, not a lockout.
 200  	broken := filepath.Join(dir, "broken.json")
 201  
 202  	if err := os.WriteFile(broken, []byte("{not json"), 0o600); err != nil {
 203  		t.Fatal(err)
 204  	}
 205  
 206  	t.Setenv("TORLY_LEDGER_FILE", broken)
 207  
 208  	if allowed, reason := s.paidGateway(gatewayKey); !allowed {
 209  		t.Fatalf("an unreadable ledger refused a gateway: %s", reason)
 210  	}
 211  }
 212