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

245 lines
7.2 KiB
Go
Raw Normal View History

// Copyright 2023 The forgejo Authors. All rights reserved.
2023-10-20 15:16:04 +02:00
// SPDX-License-Identifier: MIT
package activitypub
2023-12-20 11:27:44 +01:00
// ToDo: Fix linting
// ToDo: Maybe do a request for the node info
// Then maybe save the node info in a DB table - this could be useful for validation
2023-10-20 15:16:04 +02:00
import (
"fmt"
2023-11-29 15:34:02 +01:00
"io"
2023-10-20 15:16:04 +02:00
"net/http"
"strings"
2023-12-07 13:54:07 +01:00
"time"
2023-10-20 15:16:04 +02:00
2023-12-01 17:06:39 +01:00
"code.gitea.io/gitea/models/db"
2023-12-09 14:27:29 +01:00
"code.gitea.io/gitea/models/forgefed"
2023-12-07 13:17:51 +01:00
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
2023-11-28 13:03:45 +01:00
api "code.gitea.io/gitea/modules/activitypub"
2023-10-20 15:16:04 +02:00
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
2023-12-05 10:37:51 +01:00
"code.gitea.io/gitea/modules/util"
2023-11-10 14:26:13 +01:00
"code.gitea.io/gitea/modules/web"
2023-12-05 10:37:51 +01:00
"github.com/google/uuid"
ap "github.com/go-ap/activitypub"
2023-12-05 11:38:36 +01:00
pwd_gen "github.com/sethvargo/go-password/password"
2023-10-20 15:16:04 +02: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 12:10:31 +01:00
link := fmt.Sprintf("%s/api/v1/activitypub/repository-id/%d", strings.TrimSuffix(setting.AppURL, "/"), ctx.Repo.Repository.ID)
2023-11-06 18:29:48 +01:00
repo := forgefed.RepositoryNew(ap.IRI(link))
2023-11-06 18:29:48 +01:00
repo.Name = ap.NaturalLanguageValuesNew()
err := repo.Name.Set("en", ap.Content(ctx.Repo.Repository.Name))
if err != nil {
2023-11-06 18:29:48 +01:00
ctx.ServerError("Set Name", err)
return
}
2023-11-06 18:29:48 +01:00
response(ctx, repo)
2023-10-20 15:16:04 +02: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 08:56:22 +01:00
// - name: body
// in: body
// schema:
// "$ref": "#/definitions/Star"
2023-10-20 15:16:04 +02:00
// responses:
// "204":
// "$ref": "#/responses/empty"
var user *user_model.User
2023-12-08 18:09:22 +01:00
repository := ctx.Repo.Repository
2023-12-15 14:45:20 +01:00
log.Info("RepositoryInbox: repo: %v", repository)
2023-12-08 18:09:22 +01:00
2023-12-01 17:06:39 +01:00
activity := web.GetForm(ctx).(*forgefed.Star)
2023-12-15 14:45:20 +01:00
log.Info("RepositoryInbox: activity:%v", activity)
2023-11-03 17:45:53 +01:00
2023-12-09 19:11:38 +01:00
// parse actorId (person)
2023-12-09 14:53:40 +01:00
actorId, err := forgefed.NewPersonId(activity.Actor.GetID().String(), string(activity.Source))
if err != nil {
2023-12-08 19:52:09 +01:00
ctx.ServerError("Validate actorId", err)
2023-12-08 18:09:22 +01:00
return
}
log.Info("RepositoryInbox: actorId validated: %v", actorId)
2023-12-09 19:11:38 +01:00
// parse objectId (repository)
objectId, err := forgefed.NewRepositoryId(activity.Object.GetID().String(), string(activity.Source))
if err != nil {
2023-12-12 11:04:03 +01:00
ctx.ServerError("Validate objectId", err)
return
}
if objectId.Id != fmt.Sprint(repository.ID) {
ctx.ServerError("Validate objectId", err)
2023-12-09 19:11:38 +01:00
return
}
log.Info("RepositoryInbox: objectId validated: %v", objectId)
2023-12-15 14:45:20 +01:00
actorAsLoginId := actorId.AsLoginName() // used as LoginName in newly created user
2023-12-19 10:19:35 +01:00
log.Info("RepositoryInbox: remoteStargazer: %v", actorAsLoginId)
2023-11-15 12:29:17 +01:00
2023-12-01 15:07:13 +01:00
// Check if user already exists
2023-12-15 14:45:20 +01:00
users, err := SearchUsersByLoginName(actorAsLoginId)
2023-12-05 10:37:51 +01:00
if err != nil {
2023-12-15 16:02:50 +01:00
ctx.ServerError("Searching for user failed", err)
return
2023-12-05 10:37:51 +01:00
}
2023-12-15 14:45:20 +01:00
log.Info("RepositoryInbox: local found users: %v", len(users))
switch len(users) {
case 0:
{
2023-12-15 14:45:20 +01:00
user, err = createUserFromAP(ctx, actorId)
if err != nil {
ctx.ServerError("Creating user failed", err)
2023-12-13 16:44:11 +01:00
return
}
2023-12-15 14:45:20 +01:00
log.Info("RepositoryInbox: created user from ap: %v", user)
}
case 1:
{
user = users[0]
2023-12-15 14:45:20 +01:00
log.Info("RepositoryInbox: found user: %v", user)
2023-12-06 15:37:58 +01:00
}
default:
{
2023-12-15 14:45:20 +01:00
ctx.Error(http.StatusInternalServerError, "StarRepo",
fmt.Errorf("found more than one matches for federated users"))
2023-12-13 16:49:23 +01:00
return
2023-12-05 10:37:51 +01:00
}
}
2023-12-06 15:56:26 +01:00
2023-12-15 14:45:20 +01: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.StatusInternalServerError, "StarRepo", err)
return
2023-12-07 13:24:01 +01:00
}
}
2023-11-30 16:10:26 +01:00
2023-12-07 13:54:07 +01:00
// wait 5 sec.
time.Sleep(5 * time.Second)
2023-11-10 14:10:23 +01:00
2023-10-20 15:16:04 +02:00
ctx.Status(http.StatusNoContent)
}
2023-12-13 16:44:11 +01:00
2023-12-15 14:45:20 +01:00
// TODO: Move this to model.user.search ? or to model.user.externalLoginUser ?
func SearchUsersByLoginName(loginName string) ([]*user_model.User, error) {
var actionsUser = user_model.NewActionsUser()
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
}
2023-12-20 11:27:44 +01:00
// ToDo: Maybe use externalLoginUser
2023-12-15 14:45:20 +01:00
func createUserFromAP(ctx *context.APIContext, personId forgefed.PersonId) (*user_model.User, error) {
2023-12-13 16:44:11 +01:00
// ToDo: Do we get a publicKeyId from server, repo or owner or repo?
2023-12-13 16:49:23 +01:00
var actionsUser = user_model.NewActionsUser()
2023-12-19 10:19:35 +01:00
client, err := api.NewClient(ctx, actionsUser, "no idea where to get key material.")
2023-12-13 16:44:11 +01:00
if err != nil {
return &user_model.User{}, err
}
2023-12-15 14:45:20 +01:00
response, err := client.Get(personId.AsUri())
2023-12-13 16:44:11 +01:00
if err != nil {
return &user_model.User{}, err
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return &user_model.User{}, err
}
2023-12-15 14:45:20 +01:00
log.Info("RepositoryInbox: got body: %v", string(body))
2023-12-13 16:44:11 +01:00
person := ap.Person{}
if strings.Contains(string(body), "user does not exist") {
err = fmt.Errorf("the requested user id did not exist on the remote server: %v", personId.Id)
} else {
err = person.UnmarshalJSON(body)
}
2023-12-13 16:44:11 +01:00
if err != nil {
return &user_model.User{}, err
}
2023-12-15 14:45:20 +01:00
log.Info("RepositoryInbox: got person by ap: %v", person)
email := fmt.Sprintf("%v@%v", uuid.New().String(), personId.Host)
loginName := personId.AsLoginName()
name := fmt.Sprintf("%v%v", person.PreferredUsername.String(), personId.HostSuffix())
log.Info("RepositoryInbox: person.Name: %v", person.Name)
fullName := person.Name.String()
if len(person.Name) == 0 {
fullName = name
}
2023-12-13 16:44:11 +01:00
password, err := pwd_gen.Generate(32, 10, 10, false, true)
if err != nil {
return &user_model.User{}, err
}
user := &user_model.User{
2023-12-15 14:45:20 +01:00
LowerName: strings.ToLower(person.PreferredUsername.String()),
Name: name,
FullName: fullName,
2023-12-13 16:44:11 +01:00
Email: email,
EmailNotificationsPreference: "disabled",
Passwd: password,
MustChangePassword: false,
LoginName: loginName,
Type: user_model.UserTypeRemoteUser,
IsAdmin: false,
}
overwrite := &user_model.CreateUserOverwriteOptions{
IsActive: util.OptionalBoolFalse,
IsRestricted: util.OptionalBoolFalse,
}
if err := user_model.CreateUser(ctx, user, overwrite); err != nil {
return &user_model.User{}, err
}
return user, nil
}