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