summaryrefslogtreecommitdiff
path: root/internal/filter/interaction/interactable.go
blob: 4d088206817155c74a15863ba30b1d256bfd1518 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package interaction

import (
	"context"
	"fmt"
	"slices"

	"github.com/superseriousbusiness/gotosocial/internal/config"
	"github.com/superseriousbusiness/gotosocial/internal/gtserror"
	"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
	"github.com/superseriousbusiness/gotosocial/internal/log"
	"github.com/superseriousbusiness/gotosocial/internal/util"
)

type matchType int

const (
	none     matchType = 0
	implicit matchType = 1
	explicit matchType = 2
)

// startedThread returns true if requester started
// the thread that the given status is part of.
// Ie., requester created the first post in the thread.
func (f *Filter) startedThread(
	ctx context.Context,
	requester *gtsmodel.Account,
	status *gtsmodel.Status,
) (bool, error) {
	parents, err := f.state.DB.GetStatusParents(ctx, status)
	if err != nil {
		return false, fmt.Errorf("db error getting parents of %s: %w", status.ID, err)
	}

	if len(parents) == 0 {
		// No parents available. Just check
		// if this status belongs to requester.
		return status.AccountID == requester.ID, nil
	}

	// Check if OG status owned by requester.
	return parents[0].AccountID == requester.ID, nil
}

// StatusLikeable checks if the given status
// is likeable by the requester account.
//
// Callers to this function should have already
// checked the visibility of status to requester,
// including taking account of blocks, as this
// function does not do visibility checks, only
// interaction policy checks.
func (f *Filter) StatusLikeable(
	ctx context.Context,
	requester *gtsmodel.Account,
	status *gtsmodel.Status,
) (*gtsmodel.PolicyCheckResult, error) {
	if requester.ID == status.AccountID {
		// Status author themself can
		// always like their own status,
		// no need for further checks.
		return &gtsmodel.PolicyCheckResult{
			Permission:         gtsmodel.PolicyPermissionPermitted,
			PermittedMatchedOn: util.Ptr(gtsmodel.PolicyValueAuthor),
		}, nil
	}

	switch {
	// If status has policy set, check against that.
	case status.InteractionPolicy != nil:
		return f.checkPolicy(
			ctx,
			requester,
			status,
			status.InteractionPolicy.CanLike,
		)

	// If status is local and has no policy set,
	// check against the default policy for this
	// visibility, as we're interaction-policy aware.
	case *status.Local:
		policy := gtsmodel.DefaultInteractionPolicyFor(status.Visibility)
		return f.checkPolicy(
			ctx,
			requester,
			status,
			policy.CanLike,
		)

	// Otherwise, assume the status is from an
	// instance that does not use / does not care
	// about interaction policies, and just return OK.
	default:
		return &gtsmodel.PolicyCheckResult{
			Permission: gtsmodel.PolicyPermissionPermitted,
		}, nil
	}
}

// StatusReplyable checks if the given status
// is replyable by the requester account.
//
// Callers to this function should have already
// checked the visibility of status to requester,
// including taking account of blocks, as this
// function does not do visibility checks, only
// interaction policy checks.
func (f *Filter) StatusReplyable(
	ctx context.Context,
	requester *gtsmodel.Account,
	status *gtsmodel.Status,
) (*gtsmodel.PolicyCheckResult, error) {
	if util.PtrOrValue(status.PendingApproval, false) {
		// Target status is pending approval,
		// check who started this thread.
		startedThread, err := f.startedThread(
			ctx,
			requester,
			status,
		)
		if err != nil {
			err := gtserror.Newf("error checking thread ownership: %w", err)
			return nil, err
		}

		if !startedThread {
			// If status is itself still pending approval,
			// and the requester didn't start this thread,
			// then buddy, any status that tries to reply
			// to it must be pending approval too. We do
			// this to prevent someone replying to a status
			// with a policy set that causes that reply to
			// require approval, *THEN* replying to their
			// own reply (which may not have a policy set)
			// and having the reply-to-their-own-reply go
			// through as Permitted. None of that!
			return &gtsmodel.PolicyCheckResult{
				Permission: gtsmodel.PolicyPermissionWithApproval,
			}, nil
		}
	}

	if requester.ID == status.AccountID {
		// Status author themself can
		// always reply to their own status,
		// no need for further checks.
		return &gtsmodel.PolicyCheckResult{
			Permission:         gtsmodel.PolicyPermissionPermitted,
			PermittedMatchedOn: util.Ptr(gtsmodel.PolicyValueAuthor),
		}, nil
	}

	// If requester is replied to by this status,
	// then just return OK, it's functionally equivalent
	// to them being mentioned, and easier to check!
	if status.InReplyToAccountID == requester.ID {
		return &gtsmodel.PolicyCheckResult{
			Permission:         gtsmodel.PolicyPermissionPermitted,
			PermittedMatchedOn: util.Ptr(gtsmodel.PolicyValueMentioned),
		}, nil
	}

	// Check if requester mentioned by this status.
	//
	// Prefer checking by ID, fall back to URI, URL,
	// or NameString for not-yet enriched statuses.
	mentioned := slices.ContainsFunc(
		status.Mentions,
		func(m *gtsmodel.Mention) bool {
			switch {

			// Check by ID - most accurate.
			case m.TargetAccountID != "":
				return m.TargetAccountID == requester.ID

			// Check by URI - also accurate.
			case m.TargetAccountURI != "":
				return m.TargetAccountURI == requester.URI

			// Check by URL - probably accurate.
			case m.TargetAccountURL != "":
				return m.TargetAccountURL == requester.URL

			// Fall back to checking by namestring.
			case m.NameString != "":
				username, host, err := util.ExtractNamestringParts(m.NameString)
				if err != nil {
					log.Debugf(ctx, "error checking if mentioned: %v", err)
					return false
				}

				if requester.IsLocal() {
					// Local requester has empty string
					// domain so check using config.
					return username == requester.Username &&
						(host == config.GetHost() || host == config.GetAccountDomain())
				}

				// Remote requester has domain set.
				return username == requester.Username &&
					host == requester.Domain

			default:
				// Not mentioned.
				return false
			}
		},
	)

	if mentioned {
		// A mentioned account can always
		// reply, no need for further checks.
		return &gtsmodel.PolicyCheckResult{
			Permission:         gtsmodel.PolicyPermissionPermitted,
			PermittedMatchedOn: util.Ptr(gtsmodel.PolicyValueMentioned),
		}, nil
	}

	switch {
	// If status has policy set, check against that.
	case status.InteractionPolicy != nil:
		return f.checkPolicy(
			ctx,
			requester,
			status,
			status.InteractionPolicy.CanReply,
		)

	// If status is local and has no policy set,
	// check against the default policy for this
	// visibility, as we're interaction-policy aware.
	case *status.Local:
		policy := gtsmodel.DefaultInteractionPolicyFor(status.Visibility)
		return f.checkPolicy(
			ctx,
			requester,
			status,
			policy.CanReply,
		)

	// Otherwise, assume the status is from an
	// instance that does not use / does not care
	// about interaction policies, and just return OK.
	default:
		return &gtsmodel.PolicyCheckResult{
			Permission: gtsmodel.PolicyPermissionPermitted,
		}, nil
	}
}

// StatusBoostable checks if the given status
// is boostable by the requester account.
//
// Callers to this function should have already
// checked the visibility of status to requester,
// including taking account of blocks, as this
// function does not do visibility checks, only
// interaction policy checks.
func (f *Filter) StatusBoostable(
	ctx context.Context,
	requester *gtsmodel.Account,
	status *gtsmodel.Status,
) (*gtsmodel.PolicyCheckResult, error) {
	if status.Visibility == gtsmodel.VisibilityDirect {
		log.Trace(ctx, "direct statuses are not boostable")
		return &gtsmodel.PolicyCheckResult{
			Permission: gtsmodel.PolicyPermissionForbidden,
		}, nil
	}

	if requester.ID == status.AccountID {
		// Status author themself can
		// always boost non-directs,
		// no need for further checks.
		return &gtsmodel.PolicyCheckResult{
			Permission:         gtsmodel.PolicyPermissionPermitted,
			PermittedMatchedOn: util.Ptr(gtsmodel.PolicyValueAuthor),
		}, nil
	}

	switch {
	// If status has policy set, check against that.
	case status.InteractionPolicy != nil:
		return f.checkPolicy(
			ctx,
			requester,
			status,
			status.InteractionPolicy.CanAnnounce,
		)

	// If status has no policy set but it's local,
	// check against the default policy for this
	// visibility, as we're interaction-policy aware.
	case *status.Local:
		policy := gtsmodel.DefaultInteractionPolicyFor(status.Visibility)
		return f.checkPolicy(
			ctx,
			requester,
			status,
			policy.CanAnnounce,
		)

	// Status is from an instance that does not use
	// or does not care about interaction policies.
	// We can boost it if it's unlisted or public.
	case status.Visibility == gtsmodel.VisibilityPublic ||
		status.Visibility == gtsmodel.VisibilityUnlocked:
		return &gtsmodel.PolicyCheckResult{
			Permission: gtsmodel.PolicyPermissionPermitted,
		}, nil

	// Not permitted by any of the
	// above checks, so it's forbidden.
	default:
		return &gtsmodel.PolicyCheckResult{
			Permission: gtsmodel.PolicyPermissionForbidden,
		}, nil
	}
}

func (f *Filter) checkPolicy(
	ctx context.Context,
	requester *gtsmodel.Account,
	status *gtsmodel.Status,
	rules gtsmodel.PolicyRules,
) (*gtsmodel.PolicyCheckResult, error) {

	// Wrap context to be able to
	// cache some database calls.
	fctx := new(filterctx)
	fctx.Context = ctx

	// Check if requester matches a PolicyValue
	// to be always allowed to do this.
	matchAlways, matchAlwaysValue, err := f.matchPolicy(fctx,
		requester,
		status,
		rules.Always,
	)
	if err != nil {
		return nil, gtserror.Newf("error checking policy match: %w", err)
	}

	// Check if requester matches a PolicyValue
	// to be allowed to do this pending approval.
	matchWithApproval, _, err := f.matchPolicy(fctx,
		requester,
		status,
		rules.WithApproval,
	)
	if err != nil {
		return nil, gtserror.Newf("error checking policy approval match: %w", err)
	}

	switch {

	// Prefer explicit match,
	// prioritizing "always".
	case matchAlways == explicit:
		return &gtsmodel.PolicyCheckResult{
			Permission:         gtsmodel.PolicyPermissionPermitted,
			PermittedMatchedOn: &matchAlwaysValue,
		}, nil

	case matchWithApproval == explicit:
		return &gtsmodel.PolicyCheckResult{
			Permission: gtsmodel.PolicyPermissionWithApproval,
		}, nil

	// Then try implicit match,
	// prioritizing "always".
	case matchAlways == implicit:
		return &gtsmodel.PolicyCheckResult{
			Permission:         gtsmodel.PolicyPermissionPermitted,
			PermittedMatchedOn: &matchAlwaysValue,
		}, nil

	case matchWithApproval == implicit:
		return &gtsmodel.PolicyCheckResult{
			Permission: gtsmodel.PolicyPermissionWithApproval,
		}, nil
	}

	// No match.
	return &gtsmodel.PolicyCheckResult{
		Permission: gtsmodel.PolicyPermissionForbidden,
	}, nil
}

// matchPolicy returns whether requesting account
// matches any of the policy values for given status,
// returning the policy it matches on and match type.
// uses a *filterctx to cache certain db results.
func (f *Filter) matchPolicy(
	ctx *filterctx,
	requester *gtsmodel.Account,
	status *gtsmodel.Status,
	policyValues []gtsmodel.PolicyValue,
) (
	matchType,
	gtsmodel.PolicyValue,
	error,
) {
	var (
		match = none
		value gtsmodel.PolicyValue
	)

	for _, p := range policyValues {
		switch p {

		// Check if anyone
		// can do this.
		case gtsmodel.PolicyValuePublic:
			match = implicit
			value = gtsmodel.PolicyValuePublic

		// Check if follower
		// of status owner.
		case gtsmodel.PolicyValueFollowers:
			inFollowers, err := f.inFollowers(ctx,
				requester,
				status,
			)
			if err != nil {
				return 0, "", err
			}
			if inFollowers {
				match = implicit
				value = gtsmodel.PolicyValueFollowers
			}

		// Check if followed
		// by status owner.
		case gtsmodel.PolicyValueFollowing:
			inFollowing, err := f.inFollowing(ctx,
				requester,
				status,
			)
			if err != nil {
				return 0, "", err
			}
			if inFollowing {
				match = implicit
				value = gtsmodel.PolicyValueFollowing
			}

		// Check if replied-to by or
		// mentioned in the status.
		case gtsmodel.PolicyValueMentioned:
			if (status.InReplyToAccountID == requester.ID) ||
				status.MentionsAccount(requester.ID) {
				// Return early as we've
				// found an explicit match.
				match = explicit
				value = gtsmodel.PolicyValueMentioned
				return match, value, nil
			}

		// Check if PolicyValue specifies
		// requester explicitly.
		default:
			if string(p) == requester.URI {
				// Return early as we've
				// found an explicit match.
				match = explicit
				value = gtsmodel.PolicyValue(requester.URI)
				return match, value, nil
			}
		}
	}

	// Return either "" or "implicit",
	// and the policy value matched
	// against (if set).
	return match, value, nil
}

// inFollowers returns whether requesting account is following
// status author, uses *filterctx type for db result caching.
func (f *Filter) inFollowers(
	ctx *filterctx,
	requester *gtsmodel.Account,
	status *gtsmodel.Status,
) (
	bool,
	error,
) {
	if ctx.inFollowersOnce == 0 {
		var err error

		// Load the 'inFollowers' result from database.
		ctx.inFollowers, err = f.state.DB.IsFollowing(ctx,
			requester.ID,
			status.AccountID,
		)
		if err != nil {
			return false, gtserror.Newf("error checking follow status: %w", err)
		}

		// Mark value as stored.
		ctx.inFollowersOnce = 1
	}

	// Return stored value.
	return ctx.inFollowers, nil
}

// inFollowing returns whether status author is following
// requesting account, uses *filterctx for db result caching.
func (f *Filter) inFollowing(
	ctx *filterctx,
	requester *gtsmodel.Account,
	status *gtsmodel.Status,
) (
	bool,
	error,
) {
	if ctx.inFollowingOnce == 0 {
		var err error

		// Load the 'inFollowers' result from database.
		ctx.inFollowing, err = f.state.DB.IsFollowing(ctx,
			status.AccountID,
			requester.ID,
		)
		if err != nil {
			return false, gtserror.Newf("error checking follow status: %w", err)
		}

		// Mark value as stored.
		ctx.inFollowingOnce = 1
	}

	// Return stored value.
	return ctx.inFollowing, nil
}

// filterctx wraps a context.Context to also
// store loadable data relevant to a fillter
// operation from the database, such that it
// only needs to be loaded once IF required.
type filterctx struct {
	context.Context

	inFollowers     bool
	inFollowersOnce int32

	inFollowing     bool
	inFollowingOnce int32
}