From ea0fa8fcf7a911aaa3023f5efb47db9daa9d2c3c Mon Sep 17 00:00:00 2001 From: Evgeny Kuznetsov Date: Wed, 22 Mar 2023 15:50:06 +0300 Subject: feat: add basic source validation --- main.go | 24 ++++++++++++++++++++++++ main_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 main.go create mode 100644 main_test.go diff --git a/main.go b/main.go new file mode 100644 index 0000000..42e64cf --- /dev/null +++ b/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "net/http" + "net/url" +) + +const ( + errSrcInvalid = "source contains no valid URL" +) + +// endpoint is a webmention receiver. +type endpoint struct { + allowPrefix string +} + +// ServeHTTP is http.Handler implementation. +func (ep endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) { + _, err := url.Parse(r.PostFormValue("source")) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(errSrcInvalid)) + } +} diff --git a/main_test.go b/main_test.go new file mode 100644 index 0000000..d1b864d --- /dev/null +++ b/main_test.go @@ -0,0 +1,30 @@ +package main + +import ( + "io" + "net/http" + "net/http/httptest" + "net/url" + "testing" +) + +func TestSyncRejection(t *testing.T) { + server := httptest.NewServer(endpoint{"my.site"}) + defer server.Close() + + client := http.DefaultClient + r, err := client.PostForm(server.URL, url.Values{ + "source": []string{"https||:example.org/somewhere"}, + "target": []string{"my.site/target"}, + }) + if err != nil { + t.Fatal(err) + } + if r.StatusCode != 400 { + t.Fatalf("want 400, got %v", r.Status) + } + bb, _ := io.ReadAll(r.Body) + if string(bb) != errSrcInvalid { + t.Fatalf("want %s, got %s", errSrcInvalid, string(bb)) + } +} -- cgit v1.2.3