forgejo/models/user/user_repository.go
Earl Warren b2c8a1cfd3 Revert "fix: assorted ActivityPub code only refactors (#8274)" (#8705)
This reverts commit e271c24100.

It was an experiment to verify that adding a delay to the test make a difference. But it does not so... reverting.

@jerger before engaging in a refactor, it is necessary to get to the bottom of this:

- Find the root cause of those failures
- Fix it in a minimal way

Refs https://codeberg.org/forgejo/forgejo/pulls/8274#issuecomment-5987215

---

- https://codeberg.org/forgejo/forgejo/actions/runs/92182/jobs/9
- https://codeberg.org/forgejo/forgejo/actions/runs/92182/jobs/10

```
--- FAIL: TestFederationHttpSigValidation (11.34s)
    testlogger.go:411: 2025/07/28 00:23:46 ...les/storage/local.go:33:NewLocalStorage() [I] Creating new Local Storage at /workspace/forgejo/forgejo/tests/gitea-lfs-meta
    testlogger.go:411: 2025/07/28 00:23:52 ...ypub/reqsignature.go:76:func1() [W] verifyHttpSignatures failed: neither "Signature" nor "Authorization" have signature parameters
    testlogger.go:411: 2025/07/28 00:23:52 ...eb/routing/logger.go:102:func1() [I] router: completed GET http://127.0.0.1:3002/api/v1/activitypub/user-id/2 for test-mock:12345, 400 Bad Request in 5.3ms @ activitypub/reqsignature.go:74(activitypub.ReqHTTPUserOrInstanceSignature)
    testlogger.go:411: 2025/07/28 00:23:52 ...ces/auth/httpsign.go:70:Verify() [W] Failed authentication attempt from 127.0.0.1:43244
    testlogger.go:411: 2025/07/28 00:23:55 ...eb/routing/logger.go:68:func1() [W] router: slow      GET /api/v1/activitypub/user-id/2 for 127.0.0.1:43244, elapsed 3684.7ms @ activitypub/reqsignature.go:74(activitypub.ReqHTTPUserOrInstanceSignature)
    --- FAIL: TestFederationHttpSigValidation/SignedRequest (5.01s)
        api_federation_httpsig_test.go:50:
            	Error Trace:	/workspace/forgejo/forgejo/tests/integration/api_federation_httpsig_test.go:50
            	Error:      	Received unexpected error:
            	            	Get "http://127.0.0.1:3002/api/v1/activitypub/user-id/2": context deadline exceeded (Client.Timeout exceeded while awaiting headers)
            	Test:       	TestFederationHttpSigValidation/SignedRequest
    --- FAIL: TestFederationHttpSigValidation/ValidateCaches (0.00s)
        api_federation_httpsig_test.go:64:
            	Error Trace:	/workspace/forgejo/forgejo/tests/integration/api_federation_httpsig_test.go:64
            	Error:      	Expected value not to be nil.
            	Test:       	TestFederationHttpSigValidation/ValidateCaches
    test_utils.go:247: PrepareTestEnv:Process "GET: /api/v1/activitypub/user-id/2" cancelled
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
	panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4cc464a]
```

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/8705
Reviewed-by: jerger <jerger@noreply.codeberg.org>
Co-authored-by: Earl Warren <contact@earl-warren.org>
Co-committed-by: Earl Warren <contact@earl-warren.org>
2025-07-28 10:55:04 +02:00

226 lines
6.1 KiB
Go

// Copyright 2024, 2025 The Forgejo Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package user
import (
"context"
"fmt"
"forgejo.org/models/db"
"forgejo.org/modules/log"
"forgejo.org/modules/optional"
"forgejo.org/modules/validation"
)
func init() {
db.RegisterModel(new(FederatedUser))
db.RegisterModel(new(FederatedUserFollower))
}
func CreateFederatedUser(ctx context.Context, user *User, federatedUser *FederatedUser) error {
if res, err := validation.IsValid(user); !res {
return err
}
overwrite := CreateUserOverwriteOptions{
IsActive: optional.Some(false),
IsRestricted: optional.Some(false),
}
// Begin transaction
ctx, committer, err := db.TxContext((ctx))
if err != nil {
return err
}
defer func() {
err := committer.Close()
if err != nil {
log.Error("Error closing committer: %v", err)
}
}()
if err := CreateUser(ctx, user, &overwrite); err != nil {
return err
}
federatedUser.UserID = user.ID
if res, err := validation.IsValid(federatedUser); !res {
return err
}
_, err = db.GetEngine(ctx).Insert(federatedUser)
if err != nil {
return err
}
// Commit transaction
return committer.Commit()
}
func FindFederatedUser(ctx context.Context, externalID string, federationHostID int64) (*User, *FederatedUser, error) {
federatedUser := new(FederatedUser)
user := new(User)
has, err := db.GetEngine(ctx).Where("external_id=? and federation_host_id=?", externalID, federationHostID).Get(federatedUser)
if err != nil {
return nil, nil, err
} else if !has {
return nil, nil, nil
}
has, err = db.GetEngine(ctx).ID(federatedUser.UserID).Get(user)
if err != nil {
return nil, nil, err
} else if !has {
return nil, nil, fmt.Errorf("User %v for federated user is missing", federatedUser.UserID)
}
if res, err := validation.IsValid(*user); !res {
return nil, nil, err
}
if res, err := validation.IsValid(*federatedUser); !res {
return nil, nil, err
}
return user, federatedUser, nil
}
func GetFederatedUser(ctx context.Context, externalID string, federationHostID int64) (*User, *FederatedUser, error) {
user, federatedUser, err := FindFederatedUser(ctx, externalID, federationHostID)
if err != nil {
return nil, nil, err
} else if federatedUser == nil {
return nil, nil, fmt.Errorf("FederatedUser for externalId = %v and federationHostId = %v does not exist", externalID, federationHostID)
}
return user, federatedUser, nil
}
func GetFederatedUserByUserID(ctx context.Context, userID int64) (*User, *FederatedUser, error) {
federatedUser := new(FederatedUser)
user := new(User)
has, err := db.GetEngine(ctx).Where("user_id=?", userID).Get(federatedUser)
if err != nil {
return nil, nil, err
} else if !has {
return nil, nil, fmt.Errorf("Federated user %v does not exist", federatedUser.UserID)
}
has, err = db.GetEngine(ctx).ID(federatedUser.UserID).Get(user)
if err != nil {
return nil, nil, err
} else if !has {
return nil, nil, fmt.Errorf("User %v for federated user is missing", federatedUser.UserID)
}
if res, err := validation.IsValid(*user); !res {
return nil, nil, err
}
if res, err := validation.IsValid(*federatedUser); !res {
return nil, nil, err
}
return user, federatedUser, nil
}
func FindFederatedUserByKeyID(ctx context.Context, keyID string) (*User, *FederatedUser, error) {
federatedUser := new(FederatedUser)
user := new(User)
has, err := db.GetEngine(ctx).Where("key_id=?", keyID).Get(federatedUser)
if err != nil {
return nil, nil, err
} else if !has {
return nil, nil, nil
}
has, err = db.GetEngine(ctx).ID(federatedUser.UserID).Get(user)
if err != nil {
return nil, nil, err
} else if !has {
return nil, nil, fmt.Errorf("User %v for federated user is missing", federatedUser.UserID)
}
if res, err := validation.IsValid(*user); !res {
return nil, nil, err
}
if res, err := validation.IsValid(*federatedUser); !res {
return nil, nil, err
}
return user, federatedUser, nil
}
func UpdateFederatedUser(ctx context.Context, federatedUser *FederatedUser) error {
if res, err := validation.IsValid(federatedUser); !res {
return err
}
_, err := db.GetEngine(ctx).ID(federatedUser.ID).Update(federatedUser)
return err
}
func DeleteFederatedUser(ctx context.Context, userID int64) error {
_, err := db.GetEngine(ctx).Delete(&FederatedUser{UserID: userID})
return err
}
func GetFollowersForUser(ctx context.Context, user *User) ([]*FederatedUserFollower, error) {
if res, err := validation.IsValid(user); !res {
return nil, err
}
followers := make([]*FederatedUserFollower, 0, 8)
err := db.GetEngine(ctx).
Where("followed_user_id = ?", user.ID).
Find(&followers)
if err != nil {
return nil, err
}
for _, element := range followers {
if res, err := validation.IsValid(*element); !res {
return nil, err
}
}
return followers, nil
}
func AddFollower(ctx context.Context, followedUser *User, followingUser *FederatedUser) (*FederatedUserFollower, error) {
if res, err := validation.IsValid(followedUser); !res {
return nil, err
}
if res, err := validation.IsValid(followingUser); !res {
return nil, err
}
federatedUserFollower, err := NewFederatedUserFollower(followedUser.ID, followingUser.UserID)
if err != nil {
return nil, err
}
_, err = db.GetEngine(ctx).Insert(&federatedUserFollower)
if err != nil {
return nil, err
}
return &federatedUserFollower, err
}
func RemoveFollower(ctx context.Context, followedUser *User, followingUser *FederatedUser) error {
if res, err := validation.IsValid(followedUser); !res {
return err
}
if res, err := validation.IsValid(followingUser); !res {
return err
}
_, err := db.GetEngine(ctx).Delete(&FederatedUserFollower{
FollowedUserID: followedUser.ID,
FollowingUserID: followingUser.UserID,
})
return err
}
func IsFollowingAp(ctx context.Context, followedUser *User, followingUser *FederatedUser) (bool, error) {
if res, err := validation.IsValid(followedUser); !res {
return false, err
}
if res, err := validation.IsValid(followingUser); !res {
return false, err
}
return db.GetEngine(ctx).Get(&FederatedUserFollower{
FollowedUserID: followedUser.ID,
FollowingUserID: followingUser.UserID,
})
}