Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

fix(federation): Fix ActivityPub IDN federation URLs (#4882)

taintedcypherc92709b93ef1
diff --git a/activitypub/apmodels/actor_test.go b/activitypub/apmodels/actor_test.go
index 5ab0864137..72a4ea1d50 100644
--- a/activitypub/apmodels/actor_test.go
+++ b/activitypub/apmodels/actor_test.go
@@ -1,6 +1,7 @@
package apmodels
import (
+ "encoding/json"
"errors"
"io/ioutil"
"net/url"
@@ -156,6 +157,57 @@ func TestMakeServiceForAccount(t *testing.T) {
}
}
+func TestMakeServiceForAccountWithIDNServerURL(t *testing.T) {
+ configRepository := configrepository.Get()
+ configRepository.SetServerURL("https://live.retrospection.みんな")
+ t.Cleanup(func() {
+ configRepository.SetServerURL("https://my.cool.site.biz")
+ })
+
+ person := MakeServiceForAccount("retrots3m")
+ payload, err := Serialize(person)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var actor map[string]interface{}
+ if err := json.Unmarshal(payload, &actor); err != nil {
+ t.Fatal(err)
+ }
+
+ expectedActorURL := "https://live.retrospection.xn--q9jyb4c/federation/user/retrots3m"
+ if actor["id"] != expectedActorURL {
+ t.Errorf("actor id = %v, want %v", actor["id"], expectedActorURL)
+ }
+ if actor["url"] != expectedActorURL {
+ t.Errorf("actor url = %v, want %v", actor["url"], expectedActorURL)
+ }
+ if actor["inbox"] != expectedActorURL+"/inbox" {
+ t.Errorf("actor inbox = %v, want %v", actor["inbox"], expectedActorURL+"/inbox")
+ }
+ if actor["outbox"] != expectedActorURL+"/outbox" {
+ t.Errorf("actor outbox = %v, want %v", actor["outbox"], expectedActorURL+"/outbox")
+ }
+ if actor["followers"] != expectedActorURL+"/followers" {
+ t.Errorf("actor followers = %v, want %v", actor["followers"], expectedActorURL+"/followers")
+ }
+
+ publicKey := actor["publicKey"].(map[string]interface{})
+ if publicKey["id"] != expectedActorURL+"#main-key" {
+ t.Errorf("public key id = %v, want %v", publicKey["id"], expectedActorURL+"#main-key")
+ }
+ if publicKey["owner"] != expectedActorURL {
+ t.Errorf("public key owner = %v, want %v", publicKey["owner"], expectedActorURL)
+ }
+
+ attachments := actor["attachment"].([]interface{})
+ streamAttachment := attachments[0].(map[string]interface{})
+ expectedDisplayValue := `<a href="https://live.retrospection.みんな" rel="me nofollow noopener noreferrer" target="_blank">https://live.retrospection.みんな</a>`
+ if streamAttachment["value"] != expectedDisplayValue {
+ t.Errorf("stream attachment = %v, want %v", streamAttachment["value"], expectedDisplayValue)
+ }
+}
+
// Tests for nil-safe accessor methods
func TestActorIriStringWithNilValue(t *testing.T) {
diff --git a/activitypub/apmodels/utils.go b/activitypub/apmodels/utils.go
index 6d05ef7047..4497d940b4 100644
--- a/activitypub/apmodels/utils.go
+++ b/activitypub/apmodels/utils.go
@@ -10,6 +10,7 @@ import (
"github.com/go-fed/activity/streams"
"github.com/go-fed/activity/streams/vocab"
"github.com/owncast/owncast/persistence/configrepository"
+ "github.com/owncast/owncast/utils"
log "github.com/sirupsen/logrus"
)
@@ -28,12 +29,9 @@ func MakeRemoteIRIForResource(resourcePath string, host string) (*url.URL, error
// MakeLocalIRIForResource will create an IRI for the local server.
func MakeLocalIRIForResource(resourcePath string) *url.URL {
- configRepository := configrepository.Get()
-
- host := configRepository.GetServerURL()
- u, err := url.Parse(host)
+ u, err := GetCanonicalServerURL()
if err != nil {
- log.Errorln("unable to parse local IRI url", host, err)
+ log.Errorln("unable to parse local IRI url", err)
return nil
}
@@ -44,16 +42,39 @@ func MakeLocalIRIForResource(resourcePath string) *url.URL {
// MakeLocalIRIForAccount will return a full IRI for the local server account username.
func MakeLocalIRIForAccount(account string) *url.URL {
+ u, err := GetCanonicalServerURL()
+ if err != nil {
+ log.Errorln("unable to parse local IRI account server url", err)
+ return nil
+ }
+
+ u.Path = path.Join(u.Path, "federation", "user", account)
+
+ return u
+}
+
+// GetCanonicalServerURL returns the local server URL with an ASCII/punycode hostname.
+func GetCanonicalServerURL() (*url.URL, error) {
configRepository := configrepository.Get()
host := configRepository.GetServerURL()
- u, err := url.Parse(host)
+ canonicalHost, err := utils.CanonicalizeURLHostname(host)
if err != nil {
- log.Errorln("unable to parse local IRI account server url", err)
+ return nil, err
+ }
+
+ return url.Parse(canonicalHost)
+}
+
+// MakeLocalURLForPath will return a full URL for a path on the local server.
+func MakeLocalURLForPath(resourcePath string) *url.URL {
+ u, err := GetCanonicalServerURL()
+ if err != nil {
+ log.Errorln("unable to parse local server url", err)
return nil
}
- u.Path = path.Join(u.Path, "federation", "user", account)
+ u.Path = path.Join(u.Path, resourcePath)
return u
}
@@ -69,34 +90,12 @@ func Serialize(obj vocab.Type) ([]byte, error) {
// MakeLocalIRIForStreamURL will return a full IRI for the local server stream url.
func MakeLocalIRIForStreamURL() *url.URL {
- configRepository := configrepository.Get()
-
- host := configRepository.GetServerURL()
- u, err := url.Parse(host)
- if err != nil {
- log.Errorln("unable to parse local IRI stream url", err)
- return nil
- }
-
- u.Path = path.Join(u.Path, "/hls/stream.m3u8")
-
- return u
+ return MakeLocalURLForPath("/hls/stream.m3u8")
}
// MakeLocalIRIforLogo will return a full IRI for the local server logo.
func MakeLocalIRIforLogo() *url.URL {
- configRepository := configrepository.Get()
-
- host := configRepository.GetServerURL()
- u, err := url.Parse(host)
- if err != nil {
- log.Errorln("unable to parse local IRI stream url", err)
- return nil
- }
-
- u.Path = path.Join(u.Path, "/logo/external")
-
- return u
+ return MakeLocalURLForPath("/logo/external")
}
// GetLogoType will return the rel value for the webfinger response and
diff --git a/activitypub/controllers/followers.go b/activitypub/controllers/followers.go
index 04797d617e..6b97bd2571 100644
--- a/activitypub/controllers/followers.go
+++ b/activitypub/controllers/followers.go
@@ -16,7 +16,6 @@ import (
"github.com/owncast/owncast/activitypub/crypto"
"github.com/owncast/owncast/activitypub/persistence/followersrepository"
"github.com/owncast/owncast/activitypub/requests"
- "github.com/owncast/owncast/persistence/configrepository"
)
const (
@@ -147,14 +146,7 @@ func getFollowersPage(page string, r *http.Request) (vocab.ActivityStreamsOrdere
}
func createPageURL(r *http.Request, page *string) (*url.URL, error) {
- configRepository := configrepository.Get()
-
- domain := configRepository.GetServerURL()
- if domain == "" {
- return nil, errors.New("unable to get server URL")
- }
-
- pageURL, err := url.Parse(domain)
+ pageURL, err := apmodels.GetCanonicalServerURL()
if err != nil {
return nil, errors.Wrap(err, "unable to parse server URL")
}
diff --git a/activitypub/controllers/nodeinfo.go b/activitypub/controllers/nodeinfo.go
index 07d0936170..37c59007c1 100644
--- a/activitypub/controllers/nodeinfo.go
+++ b/activitypub/controllers/nodeinfo.go
@@ -32,13 +32,7 @@ func NodeInfoController(w http.ResponseWriter, r *http.Request) {
return
}
- serverURL := configRepository.GetServerURL()
- if serverURL == "" {
- w.WriteHeader(http.StatusNotFound)
- return
- }
-
- v2, err := url.Parse(serverURL)
+ v2, err := apmodels.GetCanonicalServerURL()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
@@ -302,8 +296,8 @@ func HostMetaController(w http.ResponseWriter, r *http.Request) {
return
}
- serverURL := configRepository.GetServerURL()
- if serverURL == "" {
+ serverURL, err := apmodels.GetCanonicalServerURL()
+ if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
@@ -311,7 +305,7 @@ func HostMetaController(w http.ResponseWriter, r *http.Request) {
res := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
<Link rel="lrdd" type="application/json" template="%s/.well-known/webfinger?resource={uri}"/>
- </XRD>`, serverURL)
+ </XRD>`, serverURL.String())
if _, err := w.Write([]byte(res)); err != nil {
log.Errorln(err)
diff --git a/activitypub/controllers/object.go b/activitypub/controllers/object.go
index 0bc3d8fce9..723360cfb6 100644
--- a/activitypub/controllers/object.go
+++ b/activitypub/controllers/object.go
@@ -27,12 +27,26 @@ func ObjectHandler(w http.ResponseWriter, r *http.Request) {
return
}
- iri := strings.Join([]string{strings.TrimSuffix(configRepository.GetServerURL(), "/"), r.URL.Path}, "")
- object, _, _, err := persistence.GetObjectByIRI(iri)
+ serverURL, err := apmodels.GetCanonicalServerURL()
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
+ serverURL.Path = r.URL.Path
+ iri := serverURL.String()
+ object, _, _, err := persistence.GetObjectByIRI(iri)
+ if err != nil {
+ legacyIRI := strings.Join([]string{strings.TrimSuffix(configRepository.GetServerURL(), "/"), r.URL.Path}, "")
+ if legacyIRI == iri {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ object, _, _, err = persistence.GetObjectByIRI(legacyIRI)
+ if err != nil {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ }
accountName := configRepository.GetDefaultFederationUsername()
actorIRI := apmodels.MakeLocalIRIForAccount(accountName)
diff --git a/activitypub/controllers/webfinger.go b/activitypub/controllers/webfinger.go
index d79cd1588c..51e3efcdbc 100644
--- a/activitypub/controllers/webfinger.go
+++ b/activitypub/controllers/webfinger.go
@@ -21,19 +21,13 @@ func WebfingerHandler(w http.ResponseWriter, r *http.Request) {
return
}
- instanceHostURL := configRepository.GetServerURL()
- if instanceHostURL == "" {
+ instanceURL, err := apmodels.GetCanonicalServerURL()
+ if err != nil {
w.WriteHeader(http.StatusNotFound)
- log.Warnln("webfinger request rejected! Federation is enabled but server URL is empty.")
- return
- }
-
- instanceHostString := utils.GetHostnameFromURLString(instanceHostURL)
- if instanceHostString == "" {
- w.WriteHeader(http.StatusNotFound)
- log.Warnln("webfinger request rejected! Federation is enabled but server URL is not set properly. data.GetServerURL(): " + configRepository.GetServerURL())
+ log.Warnln("webfinger request rejected! Federation is enabled but server URL host cannot be canonicalized: " + configRepository.GetServerURL())
return
}
+ instanceHostString := instanceURL.Host
resource := r.URL.Query().Get("resource")
preAcct, account, foundAcct := strings.Cut(resource, "acct:")
@@ -52,6 +46,12 @@ func WebfingerHandler(w http.ResponseWriter, r *http.Request) {
}
host := userComponents[1]
user := userComponents[0]
+ host, err = utils.CanonicalizeHost(host)
+ if err != nil {
+ w.WriteHeader(http.StatusBadRequest)
+ log.Debugln("webfinger request rejected! Invalid host: " + userComponents[1])
+ return
+ }
if _, valid := configRepository.GetFederatedInboxMap()[user]; !valid {
w.WriteHeader(http.StatusNotFound)
diff --git a/activitypub/controllers/webfinger_test.go b/activitypub/controllers/webfinger_test.go
new file mode 100644
index 0000000000..86beb8b2fa
--- /dev/null
+++ b/activitypub/controllers/webfinger_test.go
@@ -0,0 +1,120 @@
+package controllers
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "testing"
+
+ "github.com/owncast/owncast/core/data"
+ "github.com/owncast/owncast/persistence/configrepository"
+)
+
+func TestMain(m *testing.M) {
+ dbFile, err := os.CreateTemp(os.TempDir(), "owncast-test-db.db")
+ if err != nil {
+ panic(err)
+ }
+ defer os.Remove(dbFile.Name())
+
+ if err := data.SetupPersistence(dbFile.Name()); err != nil {
+ panic(err)
+ }
+
+ os.Exit(m.Run())
+}
+
+func TestWebfingerHandlerWithIDNHost(t *testing.T) {
+ tests := []struct {
+ name string
+ serverURL string
+ resource string
+ expectedHost string
+ expectedActorURL string
+ }{
+ {
+ name: "unicode account host",
+ serverURL: "https://live.retrospection.みんな",
+ resource: "acct:[email protected].みんな",
+ expectedHost: "live.retrospection.xn--q9jyb4c",
+ expectedActorURL: "https://live.retrospection.xn--q9jyb4c/federation/user/retrots3m",
+ },
+ {
+ name: "punycode account host",
+ serverURL: "https://live.retrospection.みんな",
+ resource: "acct:[email protected]",
+ expectedHost: "live.retrospection.xn--q9jyb4c",
+ expectedActorURL: "https://live.retrospection.xn--q9jyb4c/federation/user/retrots3m",
+ },
+ {
+ name: "unicode account host with port",
+ serverURL: "https://live.retrospection.みんな:8443",
+ resource: "acct:[email protected].みんな:8443",
+ expectedHost: "live.retrospection.xn--q9jyb4c:8443",
+ expectedActorURL: "https://live.retrospection.xn--q9jyb4c:8443/federation/user/retrots3m",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ configRepository := configrepository.Get()
+ configRepository.SetFederationEnabled(true)
+ configRepository.SetFederationUsername("retrots3m")
+ configRepository.SetServerURL(tt.serverURL)
+
+ req := httptest.NewRequest(http.MethodGet, "/.well-known/webfinger?resource="+url.QueryEscape(tt.resource), nil)
+ w := httptest.NewRecorder()
+
+ WebfingerHandler(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+
+ var response struct {
+ Subject string `json:"subject"`
+ Aliases []string `json:"aliases"`
+ Links []struct {
+ Rel string `json:"rel"`
+ Href string `json:"href"`
+ } `json:"links"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatal(err)
+ }
+
+ if response.Subject != "acct:retrots3m@"+tt.expectedHost {
+ t.Errorf("subject = %v, want acct:retrots3m@%s", response.Subject, tt.expectedHost)
+ }
+ if len(response.Aliases) != 1 || response.Aliases[0] != tt.expectedActorURL {
+ t.Errorf("aliases = %v, want [%s]", response.Aliases, tt.expectedActorURL)
+ }
+
+ var self string
+ var avatar string
+ var alternate string
+ for _, link := range response.Links {
+ switch link.Rel {
+ case "self":
+ self = link.Href
+ case "http://webfinger.net/rel/avatar":
+ avatar = link.Href
+ case "alternate":
+ alternate = link.Href
+ }
+ }
+
+ if self != tt.expectedActorURL {
+ t.Errorf("self href = %v, want %v", self, tt.expectedActorURL)
+ }
+ if avatar != "https://"+tt.expectedHost+"/logo/external" {
+ t.Errorf("avatar href = %v, want punycode logo URL", avatar)
+ }
+ if alternate != "https://"+tt.expectedHost+"/hls/stream.m3u8" {
+ t.Errorf("alternate href = %v, want punycode stream URL", alternate)
+ }
+ })
+ }
+}
diff --git a/activitypub/outbox/outbox.go b/activitypub/outbox/outbox.go
index 96b247981f..50a0262a41 100644
--- a/activitypub/outbox/outbox.go
+++ b/activitypub/outbox/outbox.go
@@ -203,13 +203,12 @@ func SendPublicMessage(textContent string) error {
// if public, cc the followers and to the Public uri, else private, address followers directly.
func getAddressingToFollowers() (vocab.ActivityStreamsToProperty, vocab.ActivityStreamsCcProperty) {
configRepository := configrepository.Get()
- server_url := configRepository.GetServerURL()
- followers_iri, _ := url.Parse(server_url)
username := configRepository.GetDefaultFederationUsername()
- followers_iri = followers_iri.JoinPath("federation", "user", username, "followers")
+ followersIRI := apmodels.MakeLocalIRIForAccount(username)
+ followersIRI = followersIRI.JoinPath("followers")
- return apmodels.MakeAddressingToFollowers(followers_iri, !configRepository.GetFederationIsPrivate())
+ return apmodels.MakeAddressingToFollowers(followersIRI, !configRepository.GetFederationIsPrivate())
}
// nolint: unparam
diff --git a/utils/url.go b/utils/url.go
new file mode 100644
index 0000000000..6baf83b520
--- /dev/null
+++ b/utils/url.go
@@ -0,0 +1,96 @@
+package utils
+
+import (
+ "errors"
+ "net"
+ "net/netip"
+ "net/url"
+ "strings"
+
+ "golang.org/x/net/idna"
+)
+
+// CanonicalizeHostname returns a DNS-compatible ASCII hostname. It expects an
+// unwrapped hostname, such as "::1", not URL host syntax, such as "[::1]".
+func CanonicalizeHostname(hostname string) (string, error) {
+ if hostname == "" {
+ return "", errors.New("hostname is required")
+ }
+
+ if addr, err := netip.ParseAddr(hostname); err == nil {
+ return strings.ToLower(addr.String()), nil
+ }
+
+ asciiHostname, err := idna.Lookup.ToASCII(hostname)
+ if err != nil {
+ return "", err
+ }
+
+ return strings.ToLower(asciiHostname), nil
+}
+
+// CanonicalizeHost returns a DNS-compatible ASCII host, preserving any port.
+func CanonicalizeHost(host string) (string, error) {
+ if strings.Contains(host, "://") {
+ return "", errors.New("host appears to be a full URL; pass only the host[:port] portion")
+ }
+
+ u, err := url.Parse("//" + host)
+ if err != nil {
+ return "", err
+ }
+ if u.Host == "" {
+ return "", errors.New("host is required")
+ }
+ if u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" {
+ return "", errors.New("host must not include user info, path, query, or fragment")
+ }
+
+ hostname, err := CanonicalizeHostname(u.Hostname())
+ if err != nil {
+ return "", err
+ }
+
+ return joinHostPort(hostname, u.Port()), nil
+}
+
+// CanonicalizeURLHostname returns a URL string with its hostname converted to
+// DNS-compatible ASCII form.
+func CanonicalizeURLHostname(rawURL string) (string, error) {
+ u, err := url.Parse(rawURL)
+ if err != nil {
+ return "", err
+ }
+
+ canonicalURL, err := CanonicalizeURL(*u)
+ if err != nil {
+ return "", err
+ }
+
+ return canonicalURL.String(), nil
+}
+
+// CanonicalizeURL returns a copy of the provided URL with its hostname
+// converted to DNS-compatible ASCII form.
+func CanonicalizeURL(u url.URL) (*url.URL, error) {
+ hostname, err := CanonicalizeHostname(u.Hostname())
+ if err != nil {
+ return nil, err
+ }
+
+ u.Host = joinHostPort(hostname, u.Port())
+
+ return &u, nil
+}
+
+func joinHostPort(hostname string, port string) string {
+ if port != "" {
+ return net.JoinHostPort(hostname, port)
+ }
+
+ if strings.Contains(hostname, ":") {
+ return "[" + hostname + "]"
+ }
+
+ return hostname
+}
diff --git a/utils/url_test.go b/utils/url_test.go
new file mode 100644
index 0000000000..6138752d67
--- /dev/null
+++ b/utils/url_test.go
@@ -0,0 +1,96 @@
+package utils
+
+import "testing"
+
+func TestCanonicalizeURLHostname(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ expected string
+ }{
+ {
+ name: "unicode hostname",
+ input: "https://live.retrospection.みんな",
+ expected: "https://live.retrospection.xn--q9jyb4c",
+ },
+ {
+ name: "punycode hostname",
+ input: "https://live.retrospection.xn--q9jyb4c",
+ expected: "https://live.retrospection.xn--q9jyb4c",
+ },
+ {
+ name: "port",
+ input: "https://live.retrospection.みんな:8443",
+ expected: "https://live.retrospection.xn--q9jyb4c:8443",
+ },
+ {
+ name: "path and query",
+ input: "https://live.retrospection.みんな/federation/user/retrots3m?page=1",
+ expected: "https://live.retrospection.xn--q9jyb4c/federation/user/retrots3m?page=1",
+ },
+ {
+ name: "localhost",
+ input: "http://localhost:8080",
+ expected: "http://localhost:8080",
+ },
+ {
+ name: "ipv4",
+ input: "http://203.0.113.10:8080",
+ expected: "http://203.0.113.10:8080",
+ },
+ {
+ name: "ipv6",
+ input: "http://[2001:db8::1]:8080",
+ expected: "http://[2001:db8::1]:8080",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result, err := CanonicalizeURLHostname(tt.input)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if result != tt.expected {
+ t.Errorf("CanonicalizeURLHostname() = %v, want %v", result, tt.expected)
+ }
+ })
+ }
+}
+
+func TestCanonicalizeURLHostnameWithInvalidURL(t *testing.T) {
+ if _, err := CanonicalizeURLHostname("https://"); err == nil {
+ t.Error("CanonicalizeURLHostname() should return an error for a URL without a hostname")
+ }
+}
+
+func TestCanonicalizeHost(t *testing.T) {
+ result, err := CanonicalizeHost("live.retrospection.みんな:8443")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if result != "live.retrospection.xn--q9jyb4c:8443" {
+ t.Errorf("CanonicalizeHost() = %v, want %v", result, "live.retrospection.xn--q9jyb4c:8443")
+ }
+}
+
+func TestCanonicalizeHostRejectsURLParts(t *testing.T) {
+ tests := []string{
+ "",
+ "live.retrospection.みんな/path",
+ "live.retrospection.みんな?query=true",
+ "live.retrospection.みんな#fragment",
+ "[email protected].みんな",
+ "https://live.retrospection.みんな",
+ }
+
+ for _, tt := range tests {
+ t.Run(tt, func(t *testing.T) {
+ if _, err := CanonicalizeHost(tt); err == nil {
+ t.Errorf("CanonicalizeHost(%q) should return an error", tt)
+ }
+ })
+ }
+}
diff --git a/web/tests/validation.test.ts b/web/tests/validation.test.ts
index c31b54210a..7029b11fcc 100644
--- a/web/tests/validation.test.ts
+++ b/web/tests/validation.test.ts
@@ -1,4 +1,4 @@
-import { isValidUrl, isValidAccount } from '../utils/validators';
+import { isValidUrl, isValidAccount, isValidFediverseAccount } from '../utils/validators';
describe('test url validation', () => {
const validURL = 'https://example.com';
@@ -25,3 +25,31 @@ describe('test xmpp account validation', () => {
expect(isValidAccount(invalidAccount, 'xmpp')).toBe(false);
});
});
+
+describe('test fediverse account validation', () => {
+ test('should accept a standard account', () => {
+ expect(isValidFediverseAccount('@[email protected]')).toBe(true);
+ });
+
+ test('should accept a punycode TLD', () => {
+ expect(isValidFediverseAccount('[email protected]')).toBe(true);
+ });
+
+ test('should accept a unicode TLD', () => {
+ expect(isValidFediverseAccount('[email protected].みんな')).toBe(true);
+ });
+
+ test('should accept unicode domain labels', () => {
+ expect(isValidFediverseAccount('person@bière.be')).toBe(true);
+ expect(isValidFediverseAccount('person@みんな.みんな')).toBe(true);
+ });
+
+ test('should reject malformed accounts', () => {
+ expect(isValidFediverseAccount('retrots3m')).toBe(false);
+ expect(isValidFediverseAccount('retrots3m@')).toBe(false);
+ expect(isValidFediverseAccount('@live.retrospection.みんな')).toBe(false);
+ expect(isValidFediverseAccount('[email protected].みんな/path')).toBe(false);
+ expect(isValidFediverseAccount('retrots3m@localhost')).toBe(false);
+ expect(isValidFediverseAccount('retrots3m@owncast')).toBe(false);
+ });
+});
diff --git a/web/utils/validators.ts b/web/utils/validators.ts
index 86b4387817..e5411ee15e 100644
--- a/web/utils/validators.ts
+++ b/web/utils/validators.ts
@@ -18,7 +18,7 @@ export function isValidUrl(url: string, validProtocols: string[] = ['http:', 'ht
) {
return false;
}
- } catch (e) {
+ } catch {
return false;
}
@@ -60,7 +60,31 @@ export function isValidAccount(account: string, protocol: string): boolean {
*/
export function isValidFediverseAccount(account: string): boolean {
const sanitized = account.replace(/^@+/, '');
- const regex =
- /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
- return regex.test(String(sanitized).toLowerCase());
+ const separatorIndex = sanitized.lastIndexOf('@');
+
+ if (separatorIndex <= 0 || separatorIndex === sanitized.length - 1) {
+ return false;
+ }
+
+ const username = sanitized.slice(0, separatorIndex);
+ const host = sanitized.slice(separatorIndex + 1);
+
+ if (!/^[^\s@]+$/.test(username) || /\s/.test(host)) {
+ return false;
+ }
+
+ try {
+ const parsed = new URL(`https://${host}`);
+ const { hostname } = parsed;
+
+ return (
+ hostname !== '' &&
+ hostname.includes('.') &&
+ parsed.pathname === '/' &&
+ parsed.search === '' &&
+ parsed.hash === ''
+ );
+ } catch {
+ return false;
+ }
}
diff --git a/webserver/handlers/remoteFollow.go b/webserver/handlers/remoteFollow.go
index eb5afe57ca..a0fb419751 100644
--- a/webserver/handlers/remoteFollow.go
+++ b/webserver/handlers/remoteFollow.go
@@ -2,11 +2,10 @@ package handlers
import (
"encoding/json"
- "fmt"
"net/http"
- "net/url"
"strings"
+ "github.com/owncast/owncast/activitypub/apmodels"
"github.com/owncast/owncast/activitypub/webfinger"
"github.com/owncast/owncast/persistence/configrepository"
"github.com/owncast/owncast/webserver/handlers/generated"
@@ -37,8 +36,7 @@ func RemoteFollow(w http.ResponseWriter, r *http.Request) {
}
configRepository := configrepository.Get()
- localActorPath, _ := url.Parse(configRepository.GetServerURL())
- localActorPath.Path = fmt.Sprintf("/federation/user/%s", configRepository.GetDefaultFederationUsername())
+ localActorPath := apmodels.MakeLocalIRIForAccount(configRepository.GetDefaultFederationUsername())
var template string
links, err := webfinger.GetWebfingerLinks(*request.Account)
if err != nil {
@@ -55,7 +53,7 @@ func RemoteFollow(w http.ResponseWriter, r *http.Request) {
}
}
- if localActorPath.String() == "" || template == "" {
+ if localActorPath == nil || localActorPath.String() == "" || template == "" {
webutils.WriteSimpleResponse(w, false, "unable to determine remote follow information for "+*request.Account)
return
}