forgejo/routers/api/v1/activitypub/repository.go

315 lines
9.5 KiB
Go
Raw Normal View History

2024-01-13 15:08:12 +00:00
// Copyright 2023, 2024 The forgejo Authors. All rights reserved.
2023-10-20 13:16:04 +00:00
// SPDX-License-Identifier: MIT
package activitypub
import (
"fmt"
2023-10-20 13:16:04 +00:00
"net/http"
"net/url"
"strings"
2023-10-20 13:16:04 +00:00
2023-12-01 16:06:39 +00:00
"code.gitea.io/gitea/models/db"
2023-12-09 13:27:29 +00:00
"code.gitea.io/gitea/models/forgefed"
2023-12-07 12:17:51 +00:00
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
2023-11-28 12:03:45 +00:00
api "code.gitea.io/gitea/modules/activitypub"
2023-10-20 13:16:04 +00:00
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
2023-12-05 09:37:51 +00:00
"code.gitea.io/gitea/modules/util"
2024-01-03 17:52:41 +00:00
"code.gitea.io/gitea/modules/validation"
2023-11-10 13:26:13 +00:00
"code.gitea.io/gitea/modules/web"
2023-12-05 09:37:51 +00:00
"github.com/google/uuid"
ap "github.com/go-ap/activitypub"
2023-12-05 10:38:36 +00:00
pwd_gen "github.com/sethvargo/go-password/password"
2023-10-20 13:16:04 +00:00
)
// Repository function returns the Repository actor for a repo
func Repository(ctx *context.APIContext) {
// swagger:operation GET /activitypub/repository-id/{repository-id} activitypub activitypubRepository
// ---
// summary: Returns the Repository actor for a repo
// produces:
// - application/json
// parameters:
// - name: repository-id
// in: path
// description: repository ID of the repo
// type: integer
// required: true
// responses:
// "200":
// "$ref": "#/responses/ActivityPub"
2023-11-15 11:10:31 +00:00
link := fmt.Sprintf("%s/api/v1/activitypub/repository-id/%d", strings.TrimSuffix(setting.AppURL, "/"), ctx.Repo.Repository.ID)
2023-11-06 17:29:48 +00:00
repo := forgefed.RepositoryNew(ap.IRI(link))
2023-11-06 17:29:48 +00:00
repo.Name = ap.NaturalLanguageValuesNew()
err := repo.Name.Set("en", ap.Content(ctx.Repo.Repository.Name))
if err != nil {
ctx.Error(http.StatusInternalServerError, "Set Name", err)
return
}
2023-11-06 17:29:48 +00:00
response(ctx, repo)
2023-10-20 13:16:04 +00:00
}
// PersonInbox function handles the incoming data for a repository inbox
func RepositoryInbox(ctx *context.APIContext) {
// swagger:operation POST /activitypub/repository-id/{repository-id}/inbox activitypub activitypubRepository
// ---
// summary: Send to the inbox
// produces:
// - application/json
// parameters:
// - name: repository-id
// in: path
// description: repository ID of the repo
// type: integer
// required: true
2023-11-08 07:56:22 +00:00
// - name: body
// in: body
// schema:
2024-01-03 17:29:12 +00:00
// "$ref": "#/definitions/ForgeLike"
2023-10-20 13:16:04 +00:00
// responses:
// "204":
// "$ref": "#/responses/empty"
var user *user_model.User
2023-12-08 17:09:22 +00:00
repository := ctx.Repo.Repository
2023-12-15 13:45:20 +00:00
log.Info("RepositoryInbox: repo: %v", repository)
2023-12-08 17:09:22 +00:00
2024-01-03 17:29:12 +00:00
activity := web.GetForm(ctx).(*forgefed.ForgeLike)
2024-01-03 17:52:41 +00:00
if res, err := validation.IsValid(activity); !res {
ctx.Error(http.StatusNotAcceptable, "RepositoryInbox: Validate activity", err)
2024-01-03 17:52:41 +00:00
return
}
log.Info("RepositoryInbox: activity validated:%v", activity)
2023-11-03 16:45:53 +00:00
2023-12-22 13:52:10 +00:00
// parse actorID (person)
2024-01-13 16:06:40 +00:00
actorURI := activity.Actor.GetID().String()
rawActorID, err := forgefed.NewActorID(actorURI)
2024-01-14 12:03:51 +00:00
if err != nil {
ctx.Error(http.StatusInternalServerError,
"RepositoryInbox: Validating ActorID", err)
return
}
federationInfo, err := forgefed.FindFederationHostByFqdn(ctx, rawActorID.Host)
2024-01-12 16:00:17 +00:00
if err != nil {
ctx.Error(http.StatusInternalServerError,
"RepositoryInbox: Error while loading FederationInfo", err)
2024-01-12 16:00:17 +00:00
return
}
if federationInfo == nil {
result, err := createFederationInfo(ctx, rawActorID)
if err != nil {
ctx.Error(http.StatusNotAcceptable, "RepositoryInbox: Validate actorId", err)
2024-01-12 16:00:17 +00:00
return
}
federationInfo = &result
2024-01-12 16:27:52 +00:00
log.Info("RepositoryInbox: federationInfo validated: %v", federationInfo)
2024-01-12 16:00:17 +00:00
}
if !activity.IsNewer(federationInfo.LatestActivity) {
ctx.Error(http.StatusNotAcceptable, "RepositoryInbox: Validate Activity",
fmt.Errorf("Activity already processed"))
return
}
2023-12-29 11:10:07 +00:00
2024-01-13 16:06:40 +00:00
actorID, err := forgefed.NewPersonID(actorURI, string(federationInfo.NodeInfo.Source))
if err != nil {
ctx.Error(http.StatusNotAcceptable, "RepositoryInbox: Validate actorId", err)
2023-12-08 17:09:22 +00:00
return
}
2023-12-22 13:52:10 +00:00
log.Info("RepositoryInbox: actorId validated: %v", actorID)
// parse objectID (repository)
2024-01-12 16:00:17 +00:00
objectID, err := forgefed.NewRepositoryID(activity.Object.GetID().String(), string(forgefed.ForgejoSourceType))
2023-12-09 18:11:38 +00:00
if err != nil {
ctx.Error(http.StatusNotAcceptable, "RepositoryInbox: Validate objectId", err)
2023-12-12 10:04:03 +00:00
return
}
2023-12-22 14:10:21 +00:00
if objectID.ID != fmt.Sprint(repository.ID) {
ctx.Error(http.StatusNotAcceptable, "RepositoryInbox: Validate objectId", err)
2023-12-09 18:11:38 +00:00
return
}
2023-12-22 13:52:10 +00:00
log.Info("RepositoryInbox: objectId validated: %v", objectID)
2023-12-22 13:52:10 +00:00
actorAsLoginID := actorID.AsLoginName() // used as LoginName in newly created user
log.Info("RepositoryInbox: remoteStargazer: %v", actorAsLoginID)
2023-11-15 11:29:17 +00:00
2023-12-01 14:07:13 +00:00
// Check if user already exists
2023-12-22 13:52:10 +00:00
users, err := SearchUsersByLoginName(actorAsLoginID)
2023-12-05 09:37:51 +00:00
if err != nil {
ctx.Error(http.StatusInternalServerError, "RepositoryInbox: Searching for user failed", err)
return
2023-12-05 09:37:51 +00:00
}
2023-12-15 13:45:20 +00:00
log.Info("RepositoryInbox: local found users: %v", len(users))
switch len(users) {
case 0:
{
2023-12-22 13:52:10 +00:00
user, err = createUserFromAP(ctx, actorID)
if err != nil {
ctx.Error(http.StatusInternalServerError,
"RepositoryInbox: Creating federated user failed", err)
2023-12-13 15:44:11 +00:00
return
}
2023-12-15 13:45:20 +00:00
log.Info("RepositoryInbox: created user from ap: %v", user)
}
case 1:
{
user = users[0]
2023-12-15 13:45:20 +00:00
log.Info("RepositoryInbox: found user: %v", user)
2023-12-06 14:37:58 +00:00
}
default:
{
ctx.Error(http.StatusInternalServerError, "RepositoryInbox",
fmt.Errorf(" more than one matches for federated users"))
2023-12-13 15:49:23 +00:00
return
2023-12-05 09:37:51 +00:00
}
}
2023-12-06 14:56:26 +00:00
2023-12-15 13:45:20 +00:00
// execute the activity if the repo was not stared already
alreadyStared := repo_model.IsStaring(ctx, user.ID, repository.ID)
if !alreadyStared {
err = repo_model.StarRepo(ctx, user.ID, repository.ID, true)
if err != nil {
ctx.Error(http.StatusNotAcceptable, "RepositoryInbox: Star operation", err)
2023-12-15 13:45:20 +00:00
return
2023-12-07 12:24:01 +00:00
}
}
federationInfo.LatestActivity = activity.StartTime
err = forgefed.UpdateFederationHost(ctx, *federationInfo)
if err != nil {
ctx.Error(http.StatusNotAcceptable, "RepositoryInbox: error updateing federateionInfo", err)
return
}
2023-11-30 15:10:26 +00:00
2023-10-20 13:16:04 +00:00
ctx.Status(http.StatusNoContent)
}
2023-12-13 15:44:11 +00:00
2023-12-15 13:45:20 +00:00
// TODO: Move this to model.user.search ? or to model.user.externalLoginUser ?
func SearchUsersByLoginName(loginName string) ([]*user_model.User, error) {
2023-12-22 14:00:42 +00:00
actionsUser := user_model.NewActionsUser()
2023-12-15 13:45:20 +00:00
actionsUser.IsAdmin = true
options := &user_model.SearchUserOptions{
LoginName: loginName,
Actor: actionsUser,
Type: user_model.UserTypeRemoteUser,
OrderBy: db.SearchOrderByAlphabetically,
ListOptions: db.ListOptions{PageSize: 1},
IsActive: util.OptionalBoolFalse,
IncludeReserved: true,
}
users, _, err := user_model.SearchUsers(db.DefaultContext, options)
if err != nil {
return []*user_model.User{}, fmt.Errorf("search failed: %v", err)
}
return users, nil
}
func createFederationInfo(ctx *context.APIContext, actorID forgefed.ActorID) (forgefed.FederationHost, error) {
2023-12-22 14:00:42 +00:00
actionsUser := user_model.NewActionsUser()
2023-12-19 09:19:35 +00:00
client, err := api.NewClient(ctx, actionsUser, "no idea where to get key material.")
2023-12-13 15:44:11 +00:00
if err != nil {
return forgefed.FederationHost{}, err
2023-12-13 15:44:11 +00:00
}
2024-01-13 16:06:40 +00:00
body, err := client.GetBody(actorID.AsWellKnownNodeInfoURI())
2023-12-13 15:44:11 +00:00
if err != nil {
return forgefed.FederationHost{}, err
2023-12-29 14:48:45 +00:00
}
nodeInfoWellKnown, err := forgefed.NewNodeInfoWellKnown(body)
if err != nil {
return forgefed.FederationHost{}, err
2023-12-13 15:44:11 +00:00
}
2023-12-29 14:48:45 +00:00
body, err = client.GetBody(nodeInfoWellKnown.Href)
if err != nil {
return forgefed.FederationHost{}, err
2024-01-12 16:00:17 +00:00
}
nodeInfo, err := forgefed.NewNodeInfo(body)
if err != nil {
return forgefed.FederationHost{}, err
2024-01-12 16:00:17 +00:00
}
result, err := forgefed.NewFederationHost(nodeInfo, actorID.Host)
2024-01-13 15:08:12 +00:00
if err != nil {
return forgefed.FederationHost{}, err
2023-12-29 14:48:45 +00:00
}
err = forgefed.CreateFederationHost(ctx, result)
2024-01-12 16:27:52 +00:00
if err != nil {
return forgefed.FederationHost{}, err
2024-01-12 16:27:52 +00:00
}
2024-01-12 16:00:17 +00:00
return result, nil
2023-12-29 14:48:45 +00:00
}
2023-12-29 14:48:45 +00:00
// ToDo: Maybe use externalLoginUser
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?
actionsUser := user_model.NewActionsUser()
client, err := api.NewClient(ctx, actionsUser, "no idea where to get key material.")
if err != nil {
return &user_model.User{}, err
}
2023-12-29 14:48:45 +00:00
body, err := client.GetBody(personID.AsURI())
2023-12-13 15:44:11 +00:00
if err != nil {
return &user_model.User{}, err
}
2023-12-20 11:23:13 +00:00
2024-01-04 17:04:46 +00:00
person := forgefed.ForgePerson{}
2023-12-20 11:23:13 +00:00
err = person.UnmarshalJSON(body)
2023-12-13 15:44:11 +00:00
if err != nil {
return &user_model.User{}, err
}
2024-01-04 17:04:46 +00:00
if res, err := validation.IsValid(person); !res {
return &user_model.User{}, err
}
log.Info("RepositoryInbox: validated person: %q", person)
2024-01-03 17:10:24 +00:00
localFqdn, err := url.ParseRequestURI(setting.AppURL)
if err != nil {
return &user_model.User{}, err
}
email := fmt.Sprintf("f%v@%v", uuid.New().String(), localFqdn.Hostname())
2023-12-22 13:52:10 +00:00
loginName := personID.AsLoginName()
name := fmt.Sprintf("%v%v", person.PreferredUsername.String(), personID.HostSuffix())
2023-12-15 13:45:20 +00:00
log.Info("RepositoryInbox: person.Name: %v", person.Name)
fullName := person.Name.String()
if len(person.Name) == 0 {
fullName = name
}
2023-12-21 08:30:07 +00:00
2023-12-13 15:44:11 +00:00
password, err := pwd_gen.Generate(32, 10, 10, false, true)
if err != nil {
return &user_model.User{}, err
}
2023-12-21 08:30:07 +00:00
2023-12-13 15:44:11 +00:00
user := &user_model.User{
2023-12-15 13:45:20 +00:00
LowerName: strings.ToLower(person.PreferredUsername.String()),
Name: name,
FullName: fullName,
2023-12-13 15:44:11 +00:00
Email: email,
EmailNotificationsPreference: "disabled",
Passwd: password,
MustChangePassword: false,
LoginName: loginName,
Type: user_model.UserTypeRemoteUser,
IsAdmin: false,
}
2023-12-21 08:30:07 +00:00
2023-12-13 15:44:11 +00:00
overwrite := &user_model.CreateUserOverwriteOptions{
IsActive: util.OptionalBoolFalse,
IsRestricted: util.OptionalBoolFalse,
}
2023-12-21 08:30:07 +00:00
2023-12-13 15:44:11 +00:00
if err := user_model.CreateUser(ctx, user, overwrite); err != nil {
return &user_model.User{}, err
}
return user, nil
}