Template
1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo synced 2024-11-22 09:54:24 +01:00
This commit is contained in:
erik 2023-12-22 14:52:10 +01:00 committed by Michael Jerger
parent 7d78fb8adc
commit 8585edc47a
4 changed files with 109 additions and 110 deletions

View file

@ -14,12 +14,11 @@ import (
type Validateables interface { type Validateables interface {
validation.Validateable validation.Validateable
ActorId | PersonId | RepositoryId ActorID | PersonID | RepositoryID
} }
type ActorId struct { type ActorID struct {
validation.Validateable ID string
Id string
Source string Source string
Schema string Schema string
Path string Path string
@ -28,18 +27,17 @@ type ActorId struct {
UnvalidatedInput string UnvalidatedInput string
} }
type PersonId struct { type PersonID struct {
ActorId ActorID
} }
type RepositoryId struct { type RepositoryID struct {
ActorId ActorID
} }
// newActorId receives already validated inputs // newActorID receives already validated inputs
func newActorId(validatedUri *url.URL, source string) (ActorId, error) { func newActorID(validatedURI *url.URL, source string) (ActorID, error) {
pathWithActorID := strings.Split(validatedURI.Path, "/")
pathWithActorID := strings.Split(validatedUri.Path, "/")
if containsEmptyString(pathWithActorID) { if containsEmptyString(pathWithActorID) {
pathWithActorID = removeEmptyStrings(pathWithActorID) pathWithActorID = removeEmptyStrings(pathWithActorID)
} }
@ -47,14 +45,14 @@ func newActorId(validatedUri *url.URL, source string) (ActorId, error) {
pathWithoutActorID := strings.Join(pathWithActorID[0:length-1], "/") pathWithoutActorID := strings.Join(pathWithActorID[0:length-1], "/")
id := pathWithActorID[length-1] id := pathWithActorID[length-1]
result := ActorId{} result := ActorID{}
result.Id = id result.ID = id
result.Source = source result.Source = source
result.Schema = validatedUri.Scheme result.Schema = validatedURI.Scheme
result.Host = validatedUri.Hostname() result.Host = validatedURI.Hostname()
result.Path = pathWithoutActorID result.Path = pathWithoutActorID
result.Port = validatedUri.Port() result.Port = validatedURI.Port()
result.UnvalidatedInput = validatedUri.String() result.UnvalidatedInput = validatedURI.String()
if valid, err := IsValid(result); !valid { if valid, err := IsValid(result); !valid {
return ActorId{}, err return ActorId{}, err
@ -63,114 +61,115 @@ func newActorId(validatedUri *url.URL, source string) (ActorId, error) {
return result, nil return result, nil
} }
func NewPersonId(uri string, source string) (PersonId, error) { func NewPersonID(uri string, source string) (PersonID, error) {
// TODO: remove after test // TODO: remove after test
//if !validation.IsValidExternalURL(uri) { //if !validation.IsValidExternalURL(uri) {
// return PersonId{}, fmt.Errorf("uri %s is not a valid external url", uri) // return PersonId{}, fmt.Errorf("uri %s is not a valid external url", uri)
//} //}
validatedUri, err := url.ParseRequestURI(uri) validatedURI, err := url.ParseRequestURI(uri)
if err != nil { if err != nil {
return PersonId{}, err return PersonID{}, err
} }
actorId, err := newActorId(validatedUri, source) actorID, err := newActorID(validatedURI, source)
if err != nil { if err != nil {
return PersonId{}, err return PersonID{}, err
} }
// validate Person specific path // validate Person specific path
personId := PersonId{actorId} personID := PersonID{actorID}
if valid, outcome := IsValid(personId); !valid { if valid, outcome := validation.IsValid(personID); !valid {
return PersonId{}, outcome return PersonID{}, outcome
} }
return personId, nil return personID, nil
} }
func NewRepositoryId(uri string, source string) (RepositoryId, error) { func NewRepositoryId(uri string, source string) (RepositoryID, error) {
if !validation.IsAPIURL(uri) { if !validation.IsAPIURL(uri) {
return RepositoryId{}, fmt.Errorf("uri %s is not a valid repo url on this host %s", uri, setting.AppURL+"api") return RepositoryID{}, fmt.Errorf("uri %s is not a valid repo url on this host %s", uri, setting.AppURL+"api")
} }
validatedUri, err := url.ParseRequestURI(uri) validatedURI, err := url.ParseRequestURI(uri)
if err != nil { if err != nil {
return RepositoryId{}, err return RepositoryID{}, err
} }
actorId, err := newActorId(validatedUri, source) actorID, err := newActorID(validatedURI, source)
if err != nil { if err != nil {
return RepositoryId{}, err return RepositoryID{}, err
} }
// validate Person specific path // validate Person specific path
repoId := RepositoryId{actorId} repoID := RepositoryID{actorID}
if valid, outcome := IsValid(repoId); !valid { if valid, outcome := validation.IsValid(repoID); !valid {
return RepositoryId{}, outcome return RepositoryID{}, outcome
} }
return repoId, nil return repoID, nil
} }
func (id ActorId) AsUri() string { func (id ActorID) AsURI() string {
result := "" var result string
if id.Port == "" { if id.Port == "" {
result = fmt.Sprintf("%s://%s/%s/%s", id.Schema, id.Host, id.Path, id.Id) result = fmt.Sprintf("%s://%s/%s/%s", id.Schema, id.Host, id.Path, id.ID)
} else { } else {
result = fmt.Sprintf("%s://%s:%s/%s/%s", id.Schema, id.Host, id.Port, id.Path, id.Id) result = fmt.Sprintf("%s://%s:%s/%s/%s", id.Schema, id.Host, id.Port, id.Path, id.ID)
} }
return result return result
} }
func (id PersonId) AsWebfinger() string { func (id PersonID) AsWebfinger() string {
result := fmt.Sprintf("@%s@%s", strings.ToLower(id.Id), strings.ToLower(id.Host)) result := fmt.Sprintf("@%s@%s", strings.ToLower(id.ID), strings.ToLower(id.Host))
return result return result
} }
func (id PersonId) AsLoginName() string { func (id PersonID) AsLoginName() string {
result := fmt.Sprintf("%s%s", strings.ToLower(id.Id), id.HostSuffix()) result := fmt.Sprintf("%s%s", strings.ToLower(id.ID), id.HostSuffix())
return result return result
} }
func (id PersonId) HostSuffix() string { func (id PersonID) HostSuffix() string {
result := fmt.Sprintf("-%s", strings.ToLower(id.Host)) result := fmt.Sprintf("-%s", strings.ToLower(id.Host))
return result return result
} }
// Validate collects error strings in a slice and returns this // Validate collects error strings in a slice and returns this
func (value ActorId) Validate() []string { func (id ActorID) Validate() []string {
var result = []string{} var result = []string{}
result = append(result, validation.ValidateNotEmpty(value.Id, "userId")...) result = append(result, validation.ValidateNotEmpty(id.ID, "userId")...)
result = append(result, validation.ValidateNotEmpty(value.Source, "source")...) result = append(result, validation.ValidateNotEmpty(id.Source, "source")...)
result = append(result, validation.ValidateNotEmpty(value.Schema, "schema")...) result = append(result, validation.ValidateNotEmpty(id.Schema, "schema")...)
result = append(result, validation.ValidateNotEmpty(value.Path, "path")...) result = append(result, validation.ValidateNotEmpty(id.Path, "path")...)
result = append(result, validation.ValidateNotEmpty(value.Host, "host")...) result = append(result, validation.ValidateNotEmpty(id.Host, "host")...)
result = append(result, validation.ValidateNotEmpty(value.UnvalidatedInput, "unvalidatedInput")...) result = append(result, validation.ValidateNotEmpty(id.UnvalidatedInput, "unvalidatedInput")...)
result = append(result, validation.ValidateOneOf(value.Source, []string{"forgejo", "gitea"})...) result = append(result, validation.ValidateOneOf(id.Source, []string{"forgejo", "gitea"})...)
if value.UnvalidatedInput != value.AsUri() { if id.UnvalidatedInput != id.AsURI() {
result = append(result, fmt.Sprintf("not all input: %q was parsed: %q", value.UnvalidatedInput, value.AsUri())) result = append(result, fmt.Sprintf("not all input: %q was parsed: %q", id.UnvalidatedInput, id.AsURI()))
} }
return result return result
} }
func (value PersonId) Validate() []string { func (id PersonID) Validate() []string {
var result = value.ActorId.Validate() var result = id.ActorID.Validate()
switch value.Source { switch id.Source {
case "forgejo", "gitea": case "forgejo", "gitea":
if strings.ToLower(value.Path) != "api/v1/activitypub/user-id" && strings.ToLower(value.Path) != "api/activitypub/user-id" { if strings.ToLower(id.Path) != "api/v1/activitypub/user-id" && strings.ToLower(id.Path) != "api/activitypub/user-id" {
result = append(result, fmt.Sprintf("path: %q has to be a person specific api path", value.Path)) result = append(result, fmt.Sprintf("path: %q has to be a person specific api path", id.Path))
} }
} }
return result return result
} }
func (value RepositoryId) Validate() []string { func (id RepositoryID) Validate() []string {
var result = value.ActorId.Validate() var result = id.ActorID.Validate()
switch value.Source { switch id.Source {
case "forgejo", "gitea": case "forgejo", "gitea":
if strings.ToLower(value.Path) != "api/v1/activitypub/repository-id" && strings.ToLower(value.Path) != "api/activitypub/repository-id" { if strings.ToLower(id.Path) != "api/v1/activitypub/repository-id" && strings.ToLower(id.Path) != "api/activitypub/repository-id" {
result = append(result, fmt.Sprintf("path: %q has to be a repo specific api path", value.Path)) result = append(result, fmt.Sprintf("path: %q has to be a repo specific api path", id.Path))
} }
} }
return result return result

View file

@ -10,28 +10,28 @@ import (
) )
func TestNewPersonId(t *testing.T) { func TestNewPersonId(t *testing.T) {
expected := PersonId{} expected := PersonID{}
expected.Id = "1" expected.ID = "1"
expected.Source = "forgejo" expected.Source = "forgejo"
expected.Schema = "https" expected.Schema = "https"
expected.Path = "api/v1/activitypub/user-id" expected.Path = "api/v1/activitypub/user-id"
expected.Host = "an.other.host" expected.Host = "an.other.host"
expected.Port = "" expected.Port = ""
expected.UnvalidatedInput = "https://an.other.host/api/v1/activitypub/user-id/1" expected.UnvalidatedInput = "https://an.other.host/api/v1/activitypub/user-id/1"
sut, _ := NewPersonId("https://an.other.host/api/v1/activitypub/user-id/1", "forgejo") sut, _ := NewPersonID("https://an.other.host/api/v1/activitypub/user-id/1", "forgejo")
if sut != expected { if sut != expected {
t.Errorf("expected: %v\n but was: %v\n", expected, sut) t.Errorf("expected: %v\n but was: %v\n", expected, sut)
} }
expected = PersonId{} expected = PersonID{}
expected.Id = "1" expected.ID = "1"
expected.Source = "forgejo" expected.Source = "forgejo"
expected.Schema = "https" expected.Schema = "https"
expected.Path = "api/v1/activitypub/user-id" expected.Path = "api/v1/activitypub/user-id"
expected.Host = "an.other.host" expected.Host = "an.other.host"
expected.Port = "443" expected.Port = "443"
expected.UnvalidatedInput = "https://an.other.host:443/api/v1/activitypub/user-id/1" expected.UnvalidatedInput = "https://an.other.host:443/api/v1/activitypub/user-id/1"
sut, _ = NewPersonId("https://an.other.host:443/api/v1/activitypub/user-id/1", "forgejo") sut, _ = NewPersonID("https://an.other.host:443/api/v1/activitypub/user-id/1", "forgejo")
if sut != expected { if sut != expected {
t.Errorf("expected: %v\n but was: %v\n", expected, sut) t.Errorf("expected: %v\n but was: %v\n", expected, sut)
} }
@ -39,8 +39,8 @@ func TestNewPersonId(t *testing.T) {
func TestNewRepositoryId(t *testing.T) { func TestNewRepositoryId(t *testing.T) {
setting.AppURL = "http://localhost:3000/" setting.AppURL = "http://localhost:3000/"
expected := RepositoryId{} expected := RepositoryID{}
expected.Id = "1" expected.ID = "1"
expected.Source = "forgejo" expected.Source = "forgejo"
expected.Schema = "http" expected.Schema = "http"
expected.Path = "api/activitypub/repository-id" expected.Path = "api/activitypub/repository-id"
@ -54,7 +54,7 @@ func TestNewRepositoryId(t *testing.T) {
} }
func TestActorIdValidation(t *testing.T) { func TestActorIdValidation(t *testing.T) {
sut := ActorId{} sut := ActorID{}
sut.Source = "forgejo" sut.Source = "forgejo"
sut.Schema = "https" sut.Schema = "https"
sut.Path = "api/v1/activitypub/user-id" sut.Path = "api/v1/activitypub/user-id"
@ -65,8 +65,8 @@ func TestActorIdValidation(t *testing.T) {
t.Errorf("validation error expected but was: %v\n", sut.Validate()) t.Errorf("validation error expected but was: %v\n", sut.Validate())
} }
sut = ActorId{} sut = ActorID{}
sut.Id = "1" sut.ID = "1"
sut.Source = "forgejox" sut.Source = "forgejox"
sut.Schema = "https" sut.Schema = "https"
sut.Path = "api/v1/activitypub/user-id" sut.Path = "api/v1/activitypub/user-id"
@ -77,8 +77,8 @@ func TestActorIdValidation(t *testing.T) {
t.Errorf("validation error expected but was: %v\n", sut.Validate()) t.Errorf("validation error expected but was: %v\n", sut.Validate())
} }
sut = ActorId{} sut = ActorID{}
sut.Id = "1" sut.ID = "1"
sut.Source = "forgejo" sut.Source = "forgejo"
sut.Schema = "https" sut.Schema = "https"
sut.Path = "api/v1/activitypub/user-id" sut.Path = "api/v1/activitypub/user-id"
@ -91,8 +91,8 @@ func TestActorIdValidation(t *testing.T) {
} }
func TestPersonIdValidation(t *testing.T) { func TestPersonIdValidation(t *testing.T) {
sut := PersonId{} sut := PersonID{}
sut.Id = "1" sut.ID = "1"
sut.Source = "forgejo" sut.Source = "forgejo"
sut.Schema = "https" sut.Schema = "https"
sut.Path = "path" sut.Path = "path"
@ -105,12 +105,12 @@ func TestPersonIdValidation(t *testing.T) {
} }
func TestWebfingerId(t *testing.T) { func TestWebfingerId(t *testing.T) {
sut, _ := NewPersonId("https://codeberg.org/api/v1/activitypub/user-id/12345", "forgejo") sut, _ := NewPersonID("https://codeberg.org/api/v1/activitypub/user-id/12345", "forgejo")
if sut.AsWebfinger() != "@12345@codeberg.org" { if sut.AsWebfinger() != "@12345@codeberg.org" {
t.Errorf("wrong webfinger: %v", sut.AsWebfinger()) t.Errorf("wrong webfinger: %v", sut.AsWebfinger())
} }
sut, _ = NewPersonId("https://Codeberg.org/api/v1/activitypub/user-id/12345", "forgejo") sut, _ = NewPersonID("https://Codeberg.org/api/v1/activitypub/user-id/12345", "forgejo")
if sut.AsWebfinger() != "@12345@codeberg.org" { if sut.AsWebfinger() != "@12345@codeberg.org" {
t.Errorf("wrong webfinger: %v", sut.AsWebfinger()) t.Errorf("wrong webfinger: %v", sut.AsWebfinger())
} }
@ -122,32 +122,32 @@ func TestShouldThrowErrorOnInvalidInput(t *testing.T) {
t.Errorf("empty input should be invalid.") t.Errorf("empty input should be invalid.")
} }
_, err = NewPersonId("http://localhost:3000/api/v1/something", "forgejo") _, err = NewPersonID("http://localhost:3000/api/v1/something", "forgejo")
if err == nil { if err == nil {
t.Errorf("localhost uris are not external") t.Errorf("localhost uris are not external")
} }
_, err = NewPersonId("./api/v1/something", "forgejo") _, err = NewPersonID("./api/v1/something", "forgejo")
if err == nil { if err == nil {
t.Errorf("relative uris are not alowed") t.Errorf("relative uris are not alowed")
} }
_, err = NewPersonId("http://1.2.3.4/api/v1/something", "forgejo") _, err = NewPersonID("http://1.2.3.4/api/v1/something", "forgejo")
if err == nil { if err == nil {
t.Errorf("uri may not be ip-4 based") t.Errorf("uri may not be ip-4 based")
} }
_, err = NewPersonId("http:///[fe80::1ff:fe23:4567:890a%25eth0]/api/v1/something", "forgejo") _, err = NewPersonID("http:///[fe80::1ff:fe23:4567:890a%25eth0]/api/v1/something", "forgejo")
if err == nil { if err == nil {
t.Errorf("uri may not be ip-6 based") t.Errorf("uri may not be ip-6 based")
} }
_, err = NewPersonId("https://codeberg.org/api/v1/activitypub/../activitypub/user-id/12345", "forgejo") _, err = NewPersonID("https://codeberg.org/api/v1/activitypub/../activitypub/user-id/12345", "forgejo")
if err == nil { if err == nil {
t.Errorf("uri may not contain relative path elements") t.Errorf("uri may not contain relative path elements")
} }
_, err = NewPersonId("https://myuser@an.other.host/api/v1/activitypub/user-id/1", "forgejo") _, err = NewPersonID("https://myuser@an.other.host/api/v1/activitypub/user-id/1", "forgejo")
if err == nil { if err == nil {
t.Errorf("uri may not contain unparsed elements") t.Errorf("uri may not contain unparsed elements")
} }
_, err = NewPersonId("https://an.other.host/api/v1/activitypub/user-id/1", "forgejo") _, err = NewPersonID("https://an.other.host/api/v1/activitypub/user-id/1", "forgejo")
if err != nil { if err != nil {
t.Errorf("this uri should be valid but was: %v", err) t.Errorf("this uri should be valid but was: %v", err)
} }

View file

@ -42,12 +42,12 @@ func StarNew(id ap.ID, ob ap.ID) *Star { // ToDo: May be used later in creating
return &o return &o
} }
func (a Star) MarshalJSON() ([]byte, error) { func (s Star) MarshalJSON() ([]byte, error) {
b := make([]byte, 0) b := make([]byte, 0)
ap.JSONWrite(&b, '{') ap.JSONWrite(&b, '{')
ap.JSONWriteStringProp(&b, "source", string(a.Source)) ap.JSONWriteStringProp(&b, "source", string(s.Source))
if !ap.JSONWriteActivityValue(&b, a.Activity) { if !ap.JSONWriteActivityValue(&b, s.Activity) {
return nil, nil return nil, nil
} }
ap.JSONWrite(&b, '}') ap.JSONWrite(&b, '}')

View file

@ -89,30 +89,30 @@ func RepositoryInbox(ctx *context.APIContext) {
activity := web.GetForm(ctx).(*forgefed.Star) activity := web.GetForm(ctx).(*forgefed.Star)
log.Info("RepositoryInbox: activity:%v", activity) log.Info("RepositoryInbox: activity:%v", activity)
// parse actorId (person) // parse actorID (person)
actorId, err := forgefed.NewPersonId(activity.Actor.GetID().String(), string(activity.Source)) actorID, err := forgefed.NewPersonID(activity.Actor.GetID().String(), string(activity.Source))
if err != nil { if err != nil {
ctx.ServerError("Validate actorId", err) ctx.ServerError("Validate actorId", err)
return return
} }
log.Info("RepositoryInbox: actorId validated: %v", actorId) log.Info("RepositoryInbox: actorId validated: %v", actorID)
// parse objectId (repository) // parse objectID (repository)
objectId, err := forgefed.NewRepositoryId(activity.Object.GetID().String(), string(activity.Source)) objectID, err := forgefed.NewRepositoryId(activity.Object.GetID().String(), string(activity.Source))
if err != nil { if err != nil {
ctx.ServerError("Validate objectId", err) ctx.ServerError("Validate objectId", err)
return return
} }
if objectId.Id != fmt.Sprint(repository.ID) { if objectID.ID != fmt.Sprint(repository.ID) {
ctx.ServerError("Validate objectId", err) ctx.ServerError("Validate objectId", err)
return return
} }
log.Info("RepositoryInbox: objectId validated: %v", objectId) log.Info("RepositoryInbox: objectId validated: %v", objectID)
actorAsLoginId := actorId.AsLoginName() // used as LoginName in newly created user actorAsLoginID := actorID.AsLoginName() // used as LoginName in newly created user
log.Info("RepositoryInbox: remoteStargazer: %v", actorAsLoginId) log.Info("RepositoryInbox: remoteStargazer: %v", actorAsLoginID)
// Check if user already exists // Check if user already exists
users, err := SearchUsersByLoginName(actorAsLoginId) users, err := SearchUsersByLoginName(actorAsLoginID)
if err != nil { if err != nil {
ctx.ServerError("Searching for user failed", err) ctx.ServerError("Searching for user failed", err)
return return
@ -122,7 +122,7 @@ func RepositoryInbox(ctx *context.APIContext) {
switch len(users) { switch len(users) {
case 0: case 0:
{ {
user, err = createUserFromAP(ctx, actorId) user, err = createUserFromAP(ctx, actorID)
if err != nil { if err != nil {
ctx.ServerError("Creating user failed", err) ctx.ServerError("Creating user failed", err)
return return
@ -182,7 +182,7 @@ func SearchUsersByLoginName(loginName string) ([]*user_model.User, error) {
} }
// ToDo: Maybe use externalLoginUser // ToDo: Maybe use externalLoginUser
func createUserFromAP(ctx *context.APIContext, personId forgefed.PersonId) (*user_model.User, error) { func createUserFromAP(ctx *context.APIContext, personID forgefed.PersonID) (*user_model.User, error) {
// ToDo: Do we get a publicKeyId from server, repo or owner or repo? // ToDo: Do we get a publicKeyId from server, repo or owner or repo?
var actionsUser = user_model.NewActionsUser() var actionsUser = user_model.NewActionsUser()
client, err := api.NewClient(ctx, actionsUser, "no idea where to get key material.") client, err := api.NewClient(ctx, actionsUser, "no idea where to get key material.")
@ -190,7 +190,7 @@ func createUserFromAP(ctx *context.APIContext, personId forgefed.PersonId) (*use
return &user_model.User{}, err return &user_model.User{}, err
} }
response, err := client.Get(personId.AsUri()) response, err := client.Get(personID.AsURI())
if err != nil { if err != nil {
return &user_model.User{}, err return &user_model.User{}, err
} }
@ -198,7 +198,7 @@ func createUserFromAP(ctx *context.APIContext, personId forgefed.PersonId) (*use
// validate response; ToDo: Should we widen the restrictions here? // validate response; ToDo: Should we widen the restrictions here?
if response.StatusCode != 200 { if response.StatusCode != 200 {
err = fmt.Errorf("got non 200 status code for id: %v", personId.Id) err = fmt.Errorf("got non 200 status code for id: %v", personID.ID)
return &user_model.User{}, err return &user_model.User{}, err
} }
@ -216,9 +216,9 @@ func createUserFromAP(ctx *context.APIContext, personId forgefed.PersonId) (*use
} }
log.Info("RepositoryInbox: got person by ap: %v", person) log.Info("RepositoryInbox: got person by ap: %v", person)
email := fmt.Sprintf("%v@%v", uuid.New().String(), personId.Host) email := fmt.Sprintf("%v@%v", uuid.New().String(), personID.Host)
loginName := personId.AsLoginName() loginName := personID.AsLoginName()
name := fmt.Sprintf("%v%v", person.PreferredUsername.String(), personId.HostSuffix()) name := fmt.Sprintf("%v%v", person.PreferredUsername.String(), personID.HostSuffix())
log.Info("RepositoryInbox: person.Name: %v", person.Name) log.Info("RepositoryInbox: person.Name: %v", person.Name)
fullName := person.Name.String() fullName := person.Name.String()
if len(person.Name) == 0 { if len(person.Name) == 0 {