8b55e74550f4465dcaa1d232bf2457d0d96fb4d5
[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 urllib.parse
8 import simplejson as json
9 import cgi
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'),
26         "privateKey": privkey.exportKey('PEM')
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':[]})
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 = urllib.parse.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     async with aiohttp.ClientSession(trace_configs=[http_debug()]) as session:
97         async with session.post(inbox, data=data, headers=headers) as resp:
98             resp_payload = await resp.text()
99             logging.debug('%r >> resp %r', inbox, resp_payload)
100
101
102 async def follow_remote_actor(actor_uri):
103     logging.info('following: %r', actor_uri)
104
105     actor = await fetch_actor(actor_uri)
106
107     message = {
108         "@context": "https://www.w3.org/ns/activitystreams",
109         "type": "Follow",
110         "to": [actor['id']],
111         "object": actor['id'],
112         "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
113         "actor": "https://{}/actor".format(AP_CONFIG['host'])
114     }
115     await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
116
117
118 async def unfollow_remote_actor(actor_uri):
119     logging.info('unfollowing: %r', actor_uri)
120
121     actor = await fetch_actor(actor_uri)
122
123     message = {
124         "@context": "https://www.w3.org/ns/activitystreams",
125         "type": "Undo",
126         "to": [actor['id']],
127         "object": {
128              "type": "Follow",
129              "object": actor_uri,
130              "actor": actor['id'],
131              "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4())
132         },
133         "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
134         "actor": "https://{}/actor".format(AP_CONFIG['host'])
135     }
136     await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
137
138
139 tag_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
140 def strip_html(data):
141     no_tags = tag_re.sub('', data)
142     return cgi.escape(no_tags)
143
144
145 def distill_inboxes(actor):
146     global DATABASE
147
148     inbox = get_actor_inbox(actor)
149     targets = [target for target in DATABASE.get('relay-list', []) if target != inbox]
150
151     assert inbox not in targets
152
153     return targets
154
155
156 def distill_object_id(activity):
157     logging.debug('>> determining object ID for %r', activity['object'])
158     obj = activity['object']
159
160     if isinstance(obj, str):
161         return obj
162
163     return obj['id']
164
165
166 async def handle_relay(actor, data, request):
167     global CACHE
168
169     object_id = distill_object_id(data)
170
171     if object_id in CACHE:
172         logging.debug('>> already relayed %r as %r', object_id, CACHE[object_id])
173         return
174
175     # don't relay mastodon announces -- causes LRP fake direction issues
176     if data['type'] == 'Announce' and len(data.get('cc', [])) > 0:
177         return
178
179     activity_id = "https://{}/activities/{}".format(request.host, uuid.uuid4())
180
181     message = {
182         "@context": "https://www.w3.org/ns/activitystreams",
183         "type": "Announce",
184         "to": ["https://{}/actor/followers".format(request.host)],
185         "actor": "https://{}/actor".format(request.host),
186         "object": object_id,
187         "id": activity_id
188     }
189
190     logging.debug('>> relay: %r', message)
191
192     inboxes = distill_inboxes(actor)
193
194     futures = [push_message_to_actor({'inbox': inbox}, message, 'https://{}/actor#main-key'.format(request.host)) for inbox in inboxes]
195     asyncio.ensure_future(asyncio.gather(*futures))
196
197     CACHE[object_id] = activity_id
198
199
200 async def handle_follow(actor, data, request):
201     global DATABASE
202
203     following = DATABASE.get('relay-list', [])
204     inbox = get_actor_inbox(actor)
205
206     if urllib.parse.urlsplit(inbox).hostname in AP_CONFIG['blocked_instances']:
207         return
208
209     if inbox not in following:
210         following += [inbox]
211         DATABASE['relay-list'] = following
212
213         if data['object'].endswith('/actor'):
214             asyncio.ensure_future(follow_remote_actor(actor['id']))
215
216     message = {
217         "@context": "https://www.w3.org/ns/activitystreams",
218         "type": "Accept",
219         "to": [actor["id"]],
220         "actor": "https://{}/actor".format(request.host),
221
222         # this is wrong per litepub, but mastodon < 2.4 is not compliant with that profile.
223         "object": {
224              "type": "Follow",
225              "id": data["id"],
226              "object": "https://{}/actor".format(request.host),
227              "actor": actor["id"]
228         },
229
230         "id": "https://{}/activities/{}".format(request.host, uuid.uuid4()),
231     }
232
233     asyncio.ensure_future(push_message_to_actor(actor, message, 'https://{}/actor#main-key'.format(request.host)))
234
235
236 async def handle_undo(actor, data, request):
237     global DATABASE
238
239     child = data['object']
240     if child['type'] == 'Follow':
241         following = DATABASE.get('relay-list', [])
242
243         inbox = get_actor_inbox(actor)
244
245         if inbox in following:
246             following.remove(inbox)
247             DATABASE['relay-list'] = following
248
249         if child['object'].endswith('/actor'):
250             await unfollow_remote_actor(actor['id'])
251
252
253 processors = {
254     'Announce': handle_relay,
255     'Create': handle_relay,
256     'Follow': handle_follow,
257     'Undo': handle_undo
258 }
259
260
261 async def inbox(request):
262     data = await request.json()
263
264     if 'actor' not in data or not request['validated']:
265         raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
266
267     actor = await fetch_actor(data["actor"])
268     actor_uri = 'https://{}/actor'.format(request.host)
269
270     logging.debug(">> payload %r", data)
271
272     processor = processors.get(data['type'], None)
273     if processor:
274         await processor(actor, data, request)
275
276     return aiohttp.web.Response(body=b'{}', content_type='application/activity+json')
277
278
279 app.router.add_post('/inbox', inbox)