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
package test

import (
	"encoding/json"
	"fmt"
	"rss_parrot/dal"
	"rss_parrot/dto"
	"rss_parrot/logic"
	"rss_parrot/shared"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

const callerHost = "stardust.community"
const callerName = "pixie"
const callerNameExtra = "ziggy"
const birbHost = "test-parrot.net"
const birbName = "birb"
const publicStream = "https://www.w3.org/ns/activitystreams#Public"
const requestedHost = "cute-animals.xyz"
const requestedPath = "blog"

type Visibility int

const (
	vizPublic Visibility = iota
	vizUnlisted
	vizFollowers
	vizDirect
)

type AtBirbMessageKind int

const (
	abmkNoUrl = iota
	abmkOneUrlGotFeed
	abmkOneUrlFeedError
	abmkOneUrlMastodonFeed
	abmkOneUrlBlockedFeed
	abmkOneUrlFeedOptedOut
)

type ReplyKind int

const (
	rkNotAReply = iota
	rkInReplyTo
)

type inboxHarness struct {
	cfg         *shared.Config
	repo        dal.IRepo
	texts       *fakeTexts
	messenger   *recordingMessenger
	ff          *fakeFeedFollower
	sender      *dto.UserInfo
	birbUrl     string
	birbMoniker string
}

// setupInboxTest builds a real inbox on a real (temporary) database. Only the
// parts it hands work off to are fakes: the feed follower, which would fetch
// from the network, and the messenger, which would deliver replies.
func setupInboxTest(t *testing.T) (*inboxHarness, logic.IInbox) {

	h := &inboxHarness{
		cfg: &shared.Config{
			Host: birbHost,
			Birb: &shared.UserInfo{
				User:      birbName,
				Published: time.Now().UTC(),
				PubKey:    birbPubKey,
				PrivKey:   birbPrivKey,
			},
		},
		texts:     &fakeTexts{},
		messenger: newRecordingMessenger(),
		ff:        &fakeFeedFollower{},
		sender:    makeCallerUserInfo(callerHost, callerName, callerPubKey1),
	}
	h.repo = newTestRepo(t, h.cfg)
	h.birbUrl = fmt.Sprintf("https://%s/u/%s", h.cfg.Host, h.cfg.Birb.User)
	h.birbMoniker = fmt.Sprintf("@%s@%s", h.cfg.Birb.User, h.cfg.Host)

	// The user directory, key store and activity sender are not reached by
	// HandleCreateNote; nil makes that an explicit claim, which a panic
	// would refute.
	inbox := logic.NewInbox(h.cfg, newTestLogger(), h.repo, h.texts, nopMetrics{}, nil,
		nil, nil, h.messenger, h.ff)

	return h, inbox
}

func checkSenderMention(sender *dto.UserInfo, callerHost string, withParrot bool) func(x any) bool {
	res := func(x any) bool {
		val, ok := x.([]*logic.MsgMention)
		expectedLen := 1
		if withParrot {
			expectedLen = 2
		}
		if !ok || len(val) != expectedLen {
			return false
		}
		if val[0].UserUrl != sender.Id {
			return false
		}
		senderMoniker := fmt.Sprintf("@%s@%s", sender.Name, callerHost)
		if val[0].Moniker != senderMoniker {
			return false
		}
		if withParrot {
			acct := makeRequestedAccount()
			if val[1].UserUrl != acct.UserUrl {
				return false
			}
			accountMoniker := fmt.Sprintf("@%s@%s", acct.Handle, birbHost)
			if val[1].Moniker != accountMoniker {
				return false
			}
		}
		return true
	}
	return res
}

func makeRequestedAccount() *dal.Account {
	handle := requestedHost + "." + requestedPath
	handle = strings.ReplaceAll(handle, "/", ".")
	handle = strings.ReplaceAll(handle, "-", ".")
	return &dal.Account{
		Id:              1,
		CreatedAt:       time.Now().UTC(),
		UserUrl:         fmt.Sprintf("https://%s/u/%s", birbHost, handle),
		Handle:          handle,
		FeedName:        "Test feed",
		FeedSummary:     "Description of test feed",
		SiteUrl:         fmt.Sprintf("https://%s/%s", requestedHost, requestedPath),
		FeedUrl:         fmt.Sprintf("https://%s/%s/feed", requestedHost, requestedPath),
		FeedLastUpdated: time.Now(),
		NextCheckDue:    time.Now().Add(time.Hour * 6),
		PubKey:          accountPubKey1,
		ProfileImageUrl: "",
		HeaderImageUrl:  "",
	}
}

func testInbox_CreateNoteActivity(t *testing.T, viz Visibility, content string,
	repk ReplyKind, msgKind AtBirbMessageKind) {

	h, inbox := setupInboxTest(t)

	// Set up "Create Note" activity
	tags := `[{"type":"Mention","href": "` + h.birbUrl + `","name": "` + h.birbMoniker + `"}]`
	var actTo []string
	var actCC []string
	if viz == vizDirect {
		actTo = []string{h.birbUrl}
	} else if viz == vizFollowers {
		actTo = []string{h.sender.Followers}
		actCC = []string{h.birbUrl}
	} else if viz == vizUnlisted {
		actTo = []string{h.sender.Followers}
		actCC = []string{h.birbUrl, publicStream}
	} else if viz == vizPublic {
		actTo = []string{publicStream}
		actCC = []string{h.birbUrl, h.sender.Followers}
	}
	var inReplyTo *string = nil
	if repk == rkInReplyTo {
		statusId := fmt.Sprintf("https://%s/users/%s/status/170829", callerHost, callerNameExtra)
		inReplyTo = &statusId
	} else if repk != rkNotAReply {
		panic(fmt.Sprintf("Reply kind not impleneted: %v", repk))
	}
	bodyBytes := makeCreateNote(callerHost, callerName, content, actTo, actCC, inReplyTo, tags)
	var act dto.ActivityInBase
	if err := json.Unmarshal(bodyBytes, &act); err != nil {
		panic(err)
	}

	// What the feed follower answers
	switch msgKind {
	case abmkOneUrlGotFeed:
		h.ff.acct, h.ff.status = makeRequestedAccount(), logic.FsNew
	case abmkOneUrlFeedError:
		h.ff.status, h.ff.err = logic.FsError, fmt.Errorf("error getting feed")
	case abmkOneUrlMastodonFeed:
		h.ff.status, h.ff.err = logic.FsMastodon, fmt.Errorf("feed is from mastodon")
	case abmkOneUrlFeedOptedOut:
		h.ff.status, h.ff.err = logic.FsOptOut, fmt.Errorf("feed opted out")
	case abmkOneUrlBlockedFeed:
		h.ff.status, h.ff.err = logic.FsBanned, fmt.Errorf("feed is blocked")
	}

	// Execute
	inbox.HandleCreateNote(act, h.sender, bodyBytes)

	// Birb must do absolutely nothing if message is a reply.
	if repk == rkInReplyTo {
		h.messenger.none(t)
		assert.Empty(t, h.ff.requests(), "a reply must not request a feed")
		alreadyHandled, err := h.repo.MarkActivityHandled(act.Id, time.Now())
		assert.Nil(t, err)
		assert.False(t, alreadyHandled, "a reply must not be marked as handled")
		return
	}

	// Otherwise it replies exactly once...
	sent := h.messenger.next(t)
	h.messenger.none(t)

	// ...and remembers the activity, so a redelivery is ignored.
	alreadyHandled, err := h.repo.MarkActivityHandled(act.Id, time.Now())
	assert.Nil(t, err)
	assert.True(t, alreadyHandled, "the activity should have been marked as handled")

	// Expect inbox to get feed's account from FeedFollower
	requestedUrl := fmt.Sprintf("https://%s/%s", requestedHost, requestedPath)
	if msgKind == abmkNoUrl {
		assert.Empty(t, h.ff.requests())
	} else {
		assert.Equal(t, []string{requestedUrl}, h.ff.requests())
	}

	// Expected response content
	var respTemplate string
	if msgKind == abmkNoUrl {
		respTemplate = "reply_no_single_url.html"
	} else if msgKind == abmkOneUrlGotFeed {
		respTemplate = "reply_got_feed.html"
	} else if msgKind == abmkOneUrlFeedError {
		respTemplate = "reply_site_not_found.html"
	} else if msgKind == abmkOneUrlMastodonFeed {
		respTemplate = "reply_feed_mastodon.html"
	} else if msgKind == abmkOneUrlFeedOptedOut {
		respTemplate = "reply_feed_optout.html"
	} else if msgKind == abmkOneUrlBlockedFeed {
		respTemplate = "reply_feed_banned.html"
	}
	assert.Equal(t, []string{respTemplate}, h.texts.usedIds())
	assert.True(t, strings.HasPrefix(sent.msg, respTemplate), "message %q", sent.msg)

	// Details of expected response message
	var respTo []string
	var respCC []string
	if viz == vizDirect {
		respTo = []string{h.sender.Id}
	} else {
		respTo = []string{publicStream}
		respCC = []string{h.sender.Id, h.sender.Followers}
	}
	mentionWithParrot := msgKind == abmkOneUrlGotFeed
	assert.Equal(t, birbName, sent.byUser)
	assert.Equal(t, h.sender.Inbox, sent.toInbox)
	assert.True(t, checkSenderMention(h.sender, callerHost, mentionWithParrot)(sent.mentions),
		"unexpected mentions: %+v", sent.mentions)
	assert.True(t, checkStrSlice(respTo)(sent.to), "to: %v, want %v", sent.to, respTo)
	assert.True(t, checkStrSlice(respCC)(sent.cc), "cc: %v, want %v", sent.cc, respCC)
	assert.Equal(t, act.Id, sent.inReplyTo)
}

const contentBirbNoUrl = `<p><span class=\"h-card\" translate=\"no\"><a href=\"https://rss-parrot.zydeo.net/u/birb\" class=\"u-url mention\">@<span>birb</span></a></span> Henlo</p>`
const contentBirbOneUrl = `<p><span class=\"h-card\" translate=\"no\"><a href=\"https://rss-parrot.zydeo.net/u/birb\" class=\"u-url mention\">@<span>birb</span></a></span> <a href=\"https://{{requested-url}}\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" translate=\"no\"><span class=\"invisible\">https://</span><span class=\"\">{{requested-url}}</span><span class=\"invisible\"></span></a></p>`

// Message to birb with no URL
// -------------------------------------------
func TestInbox_BirbMentioned_NoUrl_Direct(t *testing.T) {
	testInbox_CreateNoteActivity(t, vizDirect, contentBirbNoUrl, rkNotAReply, abmkNoUrl)
}
func TestInbox_BirbMentioned_NoUrl_Followers(t *testing.T) {
	testInbox_CreateNoteActivity(t, vizFollowers, contentBirbNoUrl, rkNotAReply, abmkNoUrl)
}
func TestInbox_BirbMentioned_NoUrl_Unlisted(t *testing.T) {
	testInbox_CreateNoteActivity(t, vizUnlisted, contentBirbNoUrl, rkNotAReply, abmkNoUrl)
}
func TestInbox_BirbMentioned_NoUrl_Public(t *testing.T) {
	testInbox_CreateNoteActivity(t, vizPublic, contentBirbNoUrl, rkNotAReply, abmkNoUrl)
}

// Message to birb with no URL that's a reply
// -------------------------------------------
func TestInbox_BirbMentioned_Reply_NoUrl_Direct(t *testing.T) {
	testInbox_CreateNoteActivity(t, vizDirect, contentBirbNoUrl, rkInReplyTo, abmkNoUrl)
}
func TestInbox_BirbMentioned_Reply_NoUrl_Followers(t *testing.T) {
	testInbox_CreateNoteActivity(t, vizFollowers, contentBirbNoUrl, rkInReplyTo, abmkNoUrl)
}
func TestInbox_BirbMentioned_Reply_NoUrl_Unlisted(t *testing.T) {
	testInbox_CreateNoteActivity(t, vizUnlisted, contentBirbNoUrl, rkInReplyTo, abmkNoUrl)
}
func TestInbox_BirbMentioned_Reply_NoUrl_Public(t *testing.T) {
	testInbox_CreateNoteActivity(t, vizPublic, contentBirbNoUrl, rkInReplyTo, abmkNoUrl)
}

// Message to birb with one URL; feed found
// -------------------------------------------
func Test_BirbMentioned_OneUrl_GotFeed_Direct(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizDirect, content, rkNotAReply, abmkOneUrlGotFeed)
}
func Test_BirbMentioned_OneUrl_GotFeed_Followers(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizFollowers, content, rkNotAReply, abmkOneUrlGotFeed)
}
func Test_BirbMentioned_OneUrl_GotFeed_Unlisted(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizUnlisted, content, rkNotAReply, abmkOneUrlGotFeed)
}
func Test_BirbMentioned_OneUrl_GotFeed_Public(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizPublic, content, rkNotAReply, abmkOneUrlGotFeed)
}

// Message to birb with one URL; feed cannot be retrieved (error)
// -------------------------------------------
func Test_BirbMentioned_OneUrl_FeedNotFound_Direct(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizDirect, content, rkNotAReply, abmkOneUrlFeedError)
}
func Test_BirbMentioned_OneUrl_FeedNotFound_Followers(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizFollowers, content, rkNotAReply, abmkOneUrlFeedError)
}
func Test_BirbMentioned_OneUrl_FeedNotFound_Unlisted(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizUnlisted, content, rkNotAReply, abmkOneUrlFeedError)
}
func Test_BirbMentioned_OneUrl_FeedNotFound_Public(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizPublic, content, rkNotAReply, abmkOneUrlFeedError)
}

// Message to birb with one URL; feed is from Mastodon, not parroting
// -------------------------------------------
func Test_BirbMentioned_OneUrl_MastodonFeed_Direct(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizDirect, content, rkNotAReply, abmkOneUrlMastodonFeed)
}
func Test_BirbMentioned_OneUrl_MastodonFeed_Folowers(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizFollowers, content, rkNotAReply, abmkOneUrlMastodonFeed)
}
func Test_BirbMentioned_OneUrl_MastodonFeed_Unlisted(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizUnlisted, content, rkNotAReply, abmkOneUrlMastodonFeed)
}
func Test_BirbMentioned_OneUrl_MastodonFeed_Public(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizPublic, content, rkNotAReply, abmkOneUrlMastodonFeed)
}

// Message to birb with one URL; feed owner has opted out
// -------------------------------------------
func Test_BirbMentioned_OneUrl_FeedOptedOut_Direct(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizDirect, content, rkNotAReply, abmkOneUrlFeedOptedOut)
}
func Test_BirbMentioned_OneUrl_FeedOptedOut_Followers(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizFollowers, content, rkNotAReply, abmkOneUrlFeedOptedOut)
}
func Test_BirbMentioned_OneUrl_FeedOptedOut_Unlisted(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizUnlisted, content, rkNotAReply, abmkOneUrlFeedOptedOut)
}
func Test_BirbMentioned_OneUrl_FeedOptedOut_Public(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizPublic, content, rkNotAReply, abmkOneUrlFeedOptedOut)
}

// Message to birb with one URL; feed is blocked
// -------------------------------------------
func Test_BirbMentioned_OneUrl_BlockedFeed_Direct(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizDirect, content, rkNotAReply, abmkOneUrlBlockedFeed)
}
func Test_BirbMentioned_OneUrl_BlockedFeed_Followers(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizFollowers, content, rkNotAReply, abmkOneUrlBlockedFeed)
}
func Test_BirbMentioned_OneUrl_BlockedFeed_Unlisted(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizUnlisted, content, rkNotAReply, abmkOneUrlBlockedFeed)
}
func Test_BirbMentioned_OneUrl_BlockedFeed_Public(t *testing.T) {
	content := strings.ReplaceAll(contentBirbOneUrl, "{{requested-url}}", requestedHost+"/"+requestedPath)
	testInbox_CreateNoteActivity(t, vizPublic, content, rkNotAReply, abmkOneUrlBlockedFeed)
}