From afcc7f0def5e8088e54a18ee9d5f37d8f1730f3f Mon Sep 17 00:00:00 2001 From: Michael Jerger Date: Fri, 8 Dec 2023 18:08:54 +0100 Subject: [PATCH] factory instead of parse & validate --- models/activitypub/actor.go | 12 ++++++++++-- models/activitypub/actor_test.go | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/models/activitypub/actor.go b/models/activitypub/actor.go index 9a950cb362..2c877a6ef5 100644 --- a/models/activitypub/actor.go +++ b/models/activitypub/actor.go @@ -7,6 +7,7 @@ import ( "strings" "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/validation" ) type Validatable interface { // ToDo: What is the right package for this interface? @@ -40,8 +41,8 @@ func (a ActorID) Validate() []string { var err = []string{} - if res := validate_is_not_empty(a.schema); res != nil { - err = append(err, strings.Join([]string{res.Error(), "for schema field"}, " ")) + if res := validation.ValidateNotEmpty(a.schema, "schema"); res != nil { + err = append(err, res.Error()) } if res := validate_is_not_empty(a.host); res != nil { @@ -167,3 +168,10 @@ func ParseActorID(validatedURL url.URL, source string) ActorID { // ToDo: Turn t port: validatedURL.Port(), } } + +func NewActorId(uri string, source string) (ActorID, error) { + if !validation.IsValidExternalURL(uri) { + return ActorID{}, fmt.Errorf("uri %s is not a valid external url.", uri) + } + return ActorID{}, nil +} diff --git a/models/activitypub/actor_test.go b/models/activitypub/actor_test.go index 458d56599a..e8eb6e2d81 100644 --- a/models/activitypub/actor_test.go +++ b/models/activitypub/actor_test.go @@ -117,3 +117,20 @@ func TestGetHostAndPort(t *testing.T) { } } + +func TestShouldThrowErrorOnInvalidInput(t *testing.T) { + _, err := NewActorId("", "forgejo") + if err == nil { + t.Errorf("empty input should be invalid.") + } + + _, err = NewActorId("http://localhost:3000/api/v1/something", "forgejo") + if err == nil { + t.Errorf("localhost uris are not external") + } + + _, err = NewActorId("https://an.other.host/api/v1/activitypub/person-id/1", "forgejo") + if err != nil { + t.Errorf("this uri should be valid") + } +}