package relayinfo import ( "context" "net/http" "net/http/httptest" "strings" "testing" ) // TestFetchReadsWhatARelayAdvertises: the relay's own answer says who it admits, so a gateway or // an operator can act on it without contacting anyone. func TestFetchReadsWhatARelayAdvertises(t *testing.T) { const key = "8964ed8cae7cb41286f9dc56344154f9491eace55ad6a18d7fb025ac02ec18a7" server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if accept := r.Header.Get("Accept"); !strings.Contains(accept, "application/nostr+json") { t.Errorf("the document was asked for with Accept %q", accept) } w.Header().Set("content-type", "application/nostr+json") _, _ = w.Write([]byte(`{"name":"swaprelay","contact":"blake@smesh.lol","gateways":["` + key + `"]}`)) })) defer server.Close() doc, err := Fetch(context.Background(), server.Client(), "ws"+strings.TrimPrefix(server.URL, "http")) if err != nil { t.Fatalf("fetch: %v", err) } if doc.Name != "swaprelay" || doc.Contact != "blake@smesh.lol" { t.Fatalf("document: %+v", doc) } if !doc.Authorizes(strings.ToUpper(key)) { t.Fatal("the advertised key was not recognised") } if doc.Authorizes(strings.Repeat("0", 64)) { t.Fatal("a key that is not advertised was accepted") } } // TestARelayThatDoesNotAnswerIsAnError: "this relay lists nobody" and "this relay did not answer" // are different answers, and a caller deciding whether it may connect needs to tell them apart. func TestARelayThatDoesNotAnswerIsAnError(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotFound) })) defer server.Close() if _, err := Fetch(context.Background(), server.Client(), "ws"+strings.TrimPrefix(server.URL, "http")); err == nil { t.Fatal("a relay that does not serve NIP-11 was reported as advertising no gateways") } server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("not a relay")) }) if _, err := Fetch(context.Background(), server.Client(), "ws"+strings.TrimPrefix(server.URL, "http")); err == nil { t.Fatal("a non-JSON page was accepted as a NIP-11 document") } } // TestHTTPURL: the relay is dialled over WebSocket and asked about itself over HTTP. func TestHTTPURL(t *testing.T) { cases := map[string]string{ "wss://swaprelay.smesh.lol": "https://swaprelay.smesh.lol/", "ws://127.0.0.1:3337/nostrino": "http://127.0.0.1:3337/", "wss://relay.example/path?x=1": "https://relay.example/", } for in, want := range cases { got, err := HTTPURL(in) if err != nil { t.Fatalf("%s: %v", in, err) } if got != want { t.Fatalf("%s: got %s, want %s", in, got, want) } } if _, err := HTTPURL("ftp://relay"); err == nil { t.Fatal("an unsupported scheme was accepted") } }