service.activitypub.inbox.go

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

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"encoding/pem"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
)

type InboxRequestSimple struct {
	ID    string `json:"id"`
	Type  string `json:"type"`
	Actor string `json:"actor"`
}

type InboxRequestBasic struct {
	InboxRequestSimple
	Object string `json:"object"`
}

type BasicObject struct {
	ID   string `json:"id"`
	Type string `json:"type"`
}
type InboxRequestComplex struct {
	Context StringOrArray `json:"@context"`
	InboxRequestSimple
	Object BasicObject
}

type InboxRequestBasicWithContext struct {
	Context StringOrArray `json:"@context"`
	InboxRequestBasic
}

type FollowResponse struct {
	Context StringOrArray `json:"@context"`
	InboxRequestSimple
	Object InboxRequestBasic `json:"object"`
}

type Actor struct {
	ID        string        `json:"id"`
	Inbox     string        `json:"inbox"`
	UserName  string        `json:"preferredUsername"`
	Name      string        `json:"name"`
	Icon      ImageMeta     `json:"icon"`
	PublicKey PublicKeyMeta `json:"publicKey"`
	Error     string        `json:"error"`
}

func (a *Actor) Handle() string {
	if uri, err := url.Parse(a.ID); err == nil {
		return fmt.Sprintf("@%s@%s", a.UserName, uri.Host)
	}
	return a.ID
}

func DoError(w http.ResponseWriter, r *http.Request, reason string) {
	fmt.Printf("[error] %v\n", reason)
	w.WriteHeader(http.StatusInternalServerError)
	w.Write([]byte("500 - Something bad happened!"))
}

func (user *User) VerifyRequest(actorInfo *Actor, r *http.Request, body []byte) error {
	spkiBlock, _ := pem.Decode([]byte(actorInfo.PublicKey.PublicKey))
	if spkiBlock == nil {
		return fmt.Errorf("no key found for [%v]", actorInfo.ID)
	}
	var spkiKey *rsa.PublicKey
	pubInterface, _ := x509.ParsePKIXPublicKey(spkiBlock.Bytes)
	spkiKey = pubInterface.(*rsa.PublicKey)

	hashs := sha256.Sum256(body)
	digest := base64.StdEncoding.EncodeToString(hashs[:])

	if "SHA-256="+digest != r.Header.Get("digest") {
		return fmt.Errorf("non matching digest")
	}

	sigHeader := r.Header.Get("Signature")
	parts := strings.Split(sigHeader, ",")
	b64Sig := sigHeader
	verifyHeaders := ""
	for _, part := range parts {
		kv := strings.SplitN(strings.TrimSpace(part), "=", 2)
		if len(kv) == 2 && kv[0] == "signature" {
			b64Sig = strings.ReplaceAll(kv[1], "\"", "")
		}

		if len(kv) == 2 && kv[0] == "headers" {
			headers := strings.Split(strings.ReplaceAll(kv[1], "\"", ""), " ")
			for _, header := range headers {
				headerValue := r.Header.Get(header)
				if header == "(request-target)" {
					headerValue = strings.ToLower(r.Method) + " /" + strings.TrimPrefix(user.UserName, "@") + "/inbox"
				} else if header == "host" {
					headerValue = user.config.Host
				}
				verifyHeaders += fmt.Sprintf("%s: %s\n", header, headerValue)
			}
		}
	}
	verifyHeaders = strings.TrimSpace(verifyHeaders)
	sigBytes, err := base64.StdEncoding.DecodeString(b64Sig)
	if err != nil {
		return fmt.Errorf("invalid base 64 signature: %v", b64Sig)
	}

	date := r.Header.Get("Date")
	dateParsed, err := time.Parse(http.TimeFormat, date)
	if err != nil {
		return fmt.Errorf("invalid http date: %v\n,", date)
	}

	if time.Since(dateParsed) > time.Minute*10 {
		return fmt.Errorf("signature has expired")
	}

	hashS := sha256.Sum256([]byte(verifyHeaders))
	if rsa.VerifyPKCS1v15(spkiKey, crypto.SHA256, hashS[:], sigBytes[:]) != nil {
		return fmt.Errorf("signature does not verify: %v\n", actorInfo.PublicKey.PublicKey)
	}

	// finally if we've got this far, the request has been verified as authentically signed by the actor...
	return nil
}

func (user *User) processInbox(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(r.Body)
	if err != nil {
		DoError(w, r, "http read error")
		return
	}

	var inboxRequest InboxRequestSimple
	err = json.Unmarshal([]byte(body), &inboxRequest)
	if err != nil {
		DoError(w, r, fmt.Sprintf("could not unmarshal inbox message:%v\n", err))
		return
	}

	if uri, err := url.Parse(inboxRequest.Actor); err == nil {
		if !user.config.IsHostAllowed(uri.Host) {
			fmt.Printf("[inbox] blocked message from disallowed host:%s\n", inboxRequest.Actor)
			return
		}
	} else {
		DoError(w, r, fmt.Sprintf("could not derive actor info for non uri %v:%v\n", inboxRequest.Actor, err))
		return
	}

	fmt.Printf("[inbox] new message to %s from %s\n", user.ID, inboxRequest.Actor)
	actorInfo, err := user.fetchActorInfo(inboxRequest.Actor, false)
	if err != nil {
		DoError(w, r, fmt.Sprintf("could not fetch actor info for %v:%v\n", inboxRequest.Actor, err))
		return
	}

	//SECURITY: verify that the request has been cryptographically signed by the actors private key...
	if user.VerifyRequest(actorInfo, r, body) != nil {
		DoError(w, r, fmt.Sprintf("could not verify signed request %v:%v\n", inboxRequest.Actor, err))
		return
	}

	if inboxRequest.Type == "Create" {
		fmt.Printf("%v\n", r)
		fmt.Printf("%v\n", r.Header)
		var inboxRequest PostMeta
		err = json.Unmarshal([]byte(body), &inboxRequest)

		if err != nil {
			fmt.Printf("%s\n", string(body))
			fmt.Printf("[error] could not unmarshal inbox object: %v\n", err)
			DoError(w, r, "create json does not parse")
			return
		}
		user.processReplyOrMention(inboxRequest)
		return
	}

	if inboxRequest.Type == "Follow" || inboxRequest.Type == "Like" || inboxRequest.Type == "Announce" {
		var inboxRequest InboxRequestBasic
		err = json.Unmarshal([]byte(body), &inboxRequest)

		if err != nil {
			fmt.Printf("%s\n", string(body))
			fmt.Printf("[error] could not unmarshal inbox object: %v\n", err)
			DoError(w, r, "basic json does not parse")
			return
		}

		switch inboxRequest.Type {
		case "Follow":
			fmt.Printf("[info] processing follow request from %v\n", inboxRequest.Actor)
			user.processFollow(inboxRequest)
			return
		case "Like":
			fmt.Printf("[info] processing like notification from %v\n", inboxRequest.Actor)
			if note := user.NoteFromCache(inboxRequest.Object); note != nil {
				CacheData(user, "likes", note.LocalID(), inboxRequest.Actor, []byte{})
			} else {
				DoError(w, r, fmt.Sprintf("could not handle like for user at this inbox: %s\n", inboxRequest.Object))
			}

			return
		case "Announce":
			fmt.Printf("[info] processing share notification from %v\n", inboxRequest.Actor)
			if note := user.NoteFromCache(inboxRequest.Object); note != nil {
				CacheData(user, "shares", note.LocalID(), inboxRequest.Actor, []byte{})
			} else {
				DoError(w, r, fmt.Sprintf("could not handle like for user at this inbox: %s\n", inboxRequest.Object))
			}

			return
		default:
			fmt.Printf("[info] ignoring inbox message of type: %v\n", inboxRequest.Type)
		}
		return
	}

	if inboxRequest.Type == "Undo" {
		var inboxRequestComplex InboxRequestComplex
		if err = json.Unmarshal([]byte(body), &inboxRequestComplex); err != nil {
			DoError(w, r, fmt.Sprintf("could not handle complex inbox request object from %s: %s\n", inboxRequest.Actor, err))
			return
		}
		switch inboxRequestComplex.Type {
		case "Undo":
			fmt.Printf("[info] processing undo notification from %v\n", inboxRequestComplex.Actor)
			switch inboxRequestComplex.Object.Type {
			case "Follow":
				// SECURITY NOTE: we technically deviate from the spec here, which says we should only undo a follow if
				// the activity being undone shares an actor with the Undo activity.
				// We assume we have long thrown away the activity and have no way to verify it as being real or relevent.
				// Instead, we assume that a verified Undo request signed by an actor over an object of type Follow is sufficient
				// to remove the actor from the followers list of the user the inbox was sent to.
				// We can do this safely because of the HTTP signature verification which binds any such request to a specific inbox and
				// and time period. And the fact that we don't have a shared server inbox.
				// Because of this, the only valid requests that reach this far must be Undo Follow requests, and the specific Follow request they
				// are responding to doesn't matter.
				fmt.Printf("[info] processing undo follow from %v\n", inboxRequestComplex.Actor)
				user.RemoveFollower(inboxRequestComplex.Actor)
			default:
				fmt.Printf("[info] could not undo object of type: %v\n", inboxRequestComplex.Object.Type)
			}
		default:
			fmt.Printf("[info] ignoring complex inbox message: %v\n", inboxRequestComplex.Object.Type)
		}
		return
	}

	fmt.Printf("[info] ignoring inbox message of type: %v\n", inboxRequest.Type)
}

func (user *User) processFollow(follow InboxRequestBasic) {
	fmt.Printf("[follow] looking up info for actor: %v\n", follow.Actor)
	if actor, err := user.fetchActorInfo(follow.Actor, true); err == nil {
		id := rand.Text()
		response := FollowResponse{}
		response.Context = []string{"https://www.w3.org/ns/activitystreams"}
		response.ID = "https://" + user.config.Host + "/" + id
		response.Type = "Accept"
		response.Actor = user.ID
		response.Object = follow
		if data, err := json.Marshal(response); err == nil {
			if err := postSigned(user, data, actor.Inbox); err == nil {
				user.AddFollower(*actor)
			} else {
				fmt.Printf("[follow] could not post accept for %v: %v\n", follow.Actor, err)
			}
		}
	} else {
		fmt.Printf("[follow] could not fetch actor info for %v: %v\n", follow.Actor, err)
	}
}

func (user *User) processReplyOrMention(inboxRequest PostMeta) {
	fmt.Printf("[inbox] processing reply from: %v\n", inboxRequest.Actor)
	replyTo := inboxRequest.Object.InReplyTo
	if replyTo != "" {
		if post := user.NoteFromCache(replyTo); post != nil {
			id := post.LocalID()
			data, _ := json.Marshal(inboxRequest)
			CacheData(user, "replies", id, rand.Text(), data)
		} else {
			fmt.Printf("[inbox] processing conversation mention from: %v\n", inboxRequest.Actor)
			data, _ := json.Marshal(inboxRequest)
			CacheData(user, "mentions", "remote", rand.Text(), data)
		}
	} else {
		fmt.Printf("[inbox] processing direct mention from: %v\n", inboxRequest.Actor)
		data, _ := json.Marshal(inboxRequest)
		CacheData(user, "mentions", "direct", rand.Text(), data)
	}
}