From 4fdc39884f6d083e4266459b550a538c3229cae4 Mon Sep 17 00:00:00 2001 From: Evgeny Kuznetsov Date: Thu, 23 Mar 2023 12:30:08 +0300 Subject: feat: add target check Part of https://www.w3.org/TR/webmention/#request-verification --- main.go | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) (limited to 'main.go') diff --git a/main.go b/main.go index 565f23c..d80ba6a 100644 --- a/main.go +++ b/main.go @@ -3,15 +3,18 @@ package main import ( "net/http" "net/url" + "path" + "strings" ) const ( - errSrcInvalid = "source is not a parsable URL" + errSrcInvalid = "source is not a parsable URL" + errTgtNotAccepted = "can not process webmentions for this target" ) // endpoint is a webmention receiver. type endpoint struct { - allowPrefix string + allowPrefix string // host (or host:port) and path prefix for the targets served by this endpoint } // ServeHTTP is http.Handler implementation. @@ -21,4 +24,21 @@ func (ep endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(errSrcInvalid)) } + target, err := url.Parse(r.PostFormValue("target")) + if err != nil || !ep.targetAllowed(target) { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(errTgtNotAccepted)) + } +} + +// targetAllowed shows whether ep can accept a webmention for the target. +func (ep endpoint) targetAllowed(target *url.URL) bool { + if !strings.HasSuffix(ep.allowPrefix, "/") { + ep.allowPrefix = ep.allowPrefix + "/" + } + tgt := path.Join(target.Host, target.Path) + if !strings.HasSuffix(tgt, "/") { + tgt = tgt + "/" + } + return strings.HasPrefix(tgt, ep.allowPrefix) } -- cgit v1.2.3