Merge branch 'follows' into 'master'
[relay.git/.git] / relay / actor.py
1 import aiohttp
2 import aiohttp.web
3 import asyncio
4 import logging
5 import uuid
6 import re
7 import simplejson as json
8 import cgi
9 import datetime
10
11 from urllib.parse import urlsplit
12 from Crypto.PublicKey import RSA
13 from cachetools import LFUCache
14
15 from . import app, CONFIG
16 from .database import DATABASE
17 from .http_debug import http_debug
18 from .remote_actor import fetch_actor
19 from .http_signatures import sign_headers, generate_body_digest
20
21
22 # generate actor keys if not present
23 if "actorKeys" not in DATABASE:
24     logging.info("No actor keys present, generating 4096-bit RSA keypair.")
25
26     privkey = RSA.generate(4096)
27     pubkey = privkey.publickey()
28
29     DATABASE["actorKeys"] = {
30         "publicKey": pubkey.exportKey('PEM').decode('utf-8'),
31         "privateKey": privkey.exportKey('PEM').decode('utf-8')
32     }
33
34
35 PRIVKEY = RSA.importKey(DATABASE["actorKeys"]["privateKey"])
36 PUBKEY = PRIVKEY.publickey()
37 AP_CONFIG = CONFIG['ap']
38 CACHE_SIZE = CONFIG.get('cache-size', 16384)
39 CACHE = LFUCache(CACHE_SIZE)
40
41 sem = asyncio.Semaphore(500)
42
43
44 async def actor(request):
45     data = {
46         "@context": "https://www.w3.org/ns/activitystreams",
47         "endpoints": {
48             "sharedInbox": "https://{}/inbox".format(request.host)
49         },
50         "followers": "https://{}/followers".format(request.host),
51         "following": "https://{}/following".format(request.host),
52         "inbox": "https://{}/inbox".format(request.host),
53         "name": "ActivityRelay",
54         "type": "Application",
55         "id": "https://{}/actor".format(request.host),
56         "publicKey": {
57             "id": "https://{}/actor#main-key".format(request.host),
58             "owner": "https://{}/actor".format(request.host),
59             "publicKeyPem": DATABASE["actorKeys"]["publicKey"]
60         },
61         "summary": "ActivityRelay bot",
62         "preferredUsername": "relay",
63         "url": "https://{}/actor".format(request.host)
64     }
65     return aiohttp.web.json_response(data)
66
67
68 app.router.add_get('/actor', actor)
69 get_actor_inbox = lambda actor: actor.get('endpoints', {}).get('sharedInbox', actor['inbox'])
70
71
72 async def push_message_to_actor(actor, message, our_key_id):
73     inbox = get_actor_inbox(actor)
74     url = urlsplit(inbox)
75
76     # XXX: Digest
77     data = json.dumps(message)
78     headers = {
79         '(request-target)': 'post {}'.format(url.path),
80         'Content-Length': str(len(data)),
81         'Content-Type': 'application/activity+json',
82         'User-Agent': 'ActivityRelay',
83         'Host': url.netloc,
84         'Digest': 'SHA-256={}'.format(generate_body_digest(data)),
85         'Date': datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
86     }
87     headers['signature'] = sign_headers(headers, PRIVKEY, our_key_id)
88     headers.pop('(request-target)')
89     headers.pop('Host')
90
91     logging.debug('%r >> %r', inbox, message)
92
93     global sem
94     async with sem:
95         try:
96             async with aiohttp.ClientSession(trace_configs=[http_debug()]) as session:
97                 async with session.post(inbox, data=data, headers=headers) as resp:
98                     if resp.status == 202:
99                         return
100                     resp_payload = await resp.text()
101                     logging.debug('%r >> resp %r', inbox, resp_payload)
102         except Exception as e:
103             logging.info('Caught %r while pushing to %r.', e, inbox)
104
105
106 async def follow_remote_actor(actor_uri):
107     actor = await fetch_actor(actor_uri)
108     
109     if not actor:
110         logging.info('failed to fetch actor at: %r', actor_uri)
111         return
112
113     if AP_CONFIG['whitelist_enabled'] is True and urlsplit(actor_uri).hostname not in AP_CONFIG['whitelist']:
114         logging.info('refusing to follow non-whitelisted actor: %r', actor_uri)
115         return
116
117     logging.info('following: %r', actor_uri)
118
119     message = {
120         "@context": "https://www.w3.org/ns/activitystreams",
121         "type": "Follow",
122         "to": [actor['id']],
123         "object": actor['id'],
124         "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
125         "actor": "https://{}/actor".format(AP_CONFIG['host'])
126     }
127     await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
128
129
130 async def unfollow_remote_actor(actor_uri):
131     actor = await fetch_actor(actor_uri)
132     if not actor:
133         logging.info('failed to fetch actor at: %r', actor_uri)
134         return
135
136     logging.info('unfollowing: %r', actor_uri)
137
138     message = {
139         "@context": "https://www.w3.org/ns/activitystreams",
140         "type": "Undo",
141         "to": [actor['id']],
142         "object": {
143              "type": "Follow",
144              "object": actor_uri,
145              "actor": actor['id'],
146              "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4())
147         },
148         "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
149         "actor": "https://{}/actor".format(AP_CONFIG['host'])
150     }
151     await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
152
153
154 tag_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
155 def strip_html(data):
156     no_tags = tag_re.sub('', data)
157     return cgi.escape(no_tags)
158
159
160 def distill_inboxes(actor, object_id):
161     global DATABASE
162
163     origin_hostname = urlsplit(object_id).hostname
164
165     inbox = get_actor_inbox(actor)
166     targets = [target for target in DATABASE.get('relay-list', []) if target != inbox]
167     targets = [target for target in targets if urlsplit(target).hostname != origin_hostname]
168     hostnames = [urlsplit(target).hostname for target in targets]
169
170     assert inbox not in targets
171     assert origin_hostname not in hostnames
172
173     return targets
174
175
176 def distill_object_id(activity):
177     logging.debug('>> determining object ID for %r', activity['object'])
178     obj = activity['object']
179
180     if isinstance(obj, str):
181         return obj
182
183     return obj['id']
184
185
186 async def handle_relay(actor, data, request):
187     global CACHE
188
189     object_id = distill_object_id(data)
190
191     if object_id in CACHE:
192         logging.debug('>> already relayed %r as %r', object_id, CACHE[object_id])
193         return
194
195     activity_id = "https://{}/activities/{}".format(request.host, uuid.uuid4())
196
197     message = {
198         "@context": "https://www.w3.org/ns/activitystreams",
199         "type": "Announce",
200         "to": ["https://{}/followers".format(request.host)],
201         "actor": "https://{}/actor".format(request.host),
202         "object": object_id,
203         "id": activity_id
204     }
205
206     logging.debug('>> relay: %r', message)
207
208     inboxes = distill_inboxes(actor, object_id)
209
210     futures = [push_message_to_actor({'inbox': inbox}, message, 'https://{}/actor#main-key'.format(request.host)) for inbox in inboxes]
211     asyncio.ensure_future(asyncio.gather(*futures))
212
213     CACHE[object_id] = activity_id
214
215
216 async def handle_forward(actor, data, request):
217     object_id = distill_object_id(data)
218
219     logging.debug('>> Relay %r', data)
220
221     inboxes = distill_inboxes(actor, object_id)
222
223     futures = [
224         push_message_to_actor(
225             {'inbox': inbox},
226             data,
227             'https://{}/actor#main-key'.format(request.host))
228         for inbox in inboxes]
229     asyncio.ensure_future(asyncio.gather(*futures))
230
231
232 async def handle_follow(actor, data, request):
233     global DATABASE
234
235     following = DATABASE.get('relay-list', [])
236     inbox = get_actor_inbox(actor)
237
238     if urlsplit(inbox).hostname in AP_CONFIG['blocked_instances']:
239         return
240
241     if inbox not in following:
242         following += [inbox]
243         DATABASE['relay-list'] = following
244
245         asyncio.ensure_future(follow_remote_actor(actor['id']))
246
247     message = {
248         "@context": "https://www.w3.org/ns/activitystreams",
249         "type": "Accept",
250         "to": [actor["id"]],
251         "actor": "https://{}/actor".format(request.host),
252
253         # this is wrong per litepub, but mastodon < 2.4 is not compliant with that profile.
254         "object": {
255             "type": "Follow",
256             "id": data["id"],
257             "object": "https://{}/actor".format(request.host),
258             "actor": actor["id"]
259         },
260
261         "id": "https://{}/activities/{}".format(request.host, uuid.uuid4()),
262     }
263
264     asyncio.ensure_future(push_message_to_actor(actor, message, 'https://{}/actor#main-key'.format(request.host)))
265
266
267 async def handle_undo(actor, data, request):
268     global DATABASE
269
270     child = data['object']
271     if child['type'] == 'Follow':
272         following = DATABASE.get('relay-list', [])
273
274         inbox = get_actor_inbox(actor)
275
276         if inbox in following:
277             following.remove(inbox)
278             DATABASE['relay-list'] = following
279
280         await unfollow_remote_actor(actor['id'])
281
282
283 processors = {
284     'Announce': handle_relay,
285     'Create': handle_relay,
286     'Delete': handle_forward,
287     'Follow': handle_follow,
288     'Undo': handle_undo,
289     'Update': handle_forward,
290 }
291
292
293 async def inbox(request):
294     data = await request.json()
295     instance = urlsplit(data['actor']).hostname
296
297     if 'actor' not in data or not request['validated']:
298         raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
299
300     elif data['type'] != 'Follow' and 'https://{}/inbox'.format(instance) not in DATABASE['relay-list']:
301         raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
302
303     elif AP_CONFIG['whitelist_enabled'] is True and instance not in AP_CONFIG['whitelist']:
304         raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
305
306     actor = await fetch_actor(data["actor"])
307     actor_uri = 'https://{}/actor'.format(request.host)
308
309     logging.debug(">> payload %r", data)
310
311     processor = processors.get(data['type'], None)
312     if processor:
313         await processor(actor, data, request)
314
315     return aiohttp.web.Response(body=b'{}', content_type='application/activity+json')
316
317 app.router.add_post('/inbox', inbox)