Apply 1 suggestion(s) to 1 file(s)
[relay.git/.git] / relay / actor.py
index 4c61f75..b45ee6f 100644 (file)
@@ -6,12 +6,17 @@ import uuid
 import re
 import simplejson as json
 import cgi
+import datetime
+
 from urllib.parse import urlsplit
 from Crypto.PublicKey import RSA
+from cachetools import LFUCache
+
+from . import app, CONFIG
 from .database import DATABASE
 from .http_debug import http_debug
-
-from cachetools import LFUCache
+from .remote_actor import fetch_actor
+from .http_signatures import sign_headers, generate_body_digest
 
 
 # generate actor keys if not present
@@ -29,19 +34,12 @@ if "actorKeys" not in DATABASE:
 
 PRIVKEY = RSA.importKey(DATABASE["actorKeys"]["privateKey"])
 PUBKEY = PRIVKEY.publickey()
-
-sem = asyncio.Semaphore(500)
-
-from . import app, CONFIG
-from .remote_actor import fetch_actor
-
-
 AP_CONFIG = CONFIG['ap']
 CACHE_SIZE = CONFIG.get('cache-size', 16384)
-
-
 CACHE = LFUCache(CACHE_SIZE)
 
+sem = asyncio.Semaphore(500)
+
 
 async def actor(request):
     data = {
@@ -64,15 +62,10 @@ async def actor(request):
         "preferredUsername": "relay",
         "url": "https://{}/actor".format(request.host)
     }
-    return aiohttp.web.json_response(data)
+    return aiohttp.web.json_response(data, content_type='application/activity+json')
 
 
 app.router.add_get('/actor', actor)
-
-
-from .http_signatures import sign_headers
-
-
 get_actor_inbox = lambda actor: actor.get('endpoints', {}).get('sharedInbox', actor['inbox'])
 
 
@@ -86,10 +79,14 @@ async def push_message_to_actor(actor, message, our_key_id):
         '(request-target)': 'post {}'.format(url.path),
         'Content-Length': str(len(data)),
         'Content-Type': 'application/activity+json',
-        'User-Agent': 'ActivityRelay'
+        'User-Agent': 'ActivityRelay',
+        'Host': url.netloc,
+        'Digest': 'SHA-256={}'.format(generate_body_digest(data)),
+        'Date': datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
     }
     headers['signature'] = sign_headers(headers, PRIVKEY, our_key_id)
     headers.pop('(request-target)')
+    headers.pop('Host')
 
     logging.debug('%r >> %r', inbox, message)
 
@@ -106,6 +103,29 @@ async def push_message_to_actor(actor, message, our_key_id):
             logging.info('Caught %r while pushing to %r.', e, inbox)
 
 
+async def fetch_nodeinfo(domain):
+    headers = {'Accept': 'application/activity+json'}
+    nodeinfo_url = None
+
+    wk_nodeinfo = await fetch_actor(f'https://{domain}/.well-known/nodeinfo', headers=headers)
+
+    if not wk_nodeinfo:
+        return
+
+    for link in wk_nodeinfo.get('links', ''):
+        if link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0':
+            nodeinfo_url = link['href']
+            break
+
+    if not nodeinfo_url:
+        return
+
+    nodeinfo_data = await fetch_actor(nodeinfo_url, headers=headers)
+    software = nodeinfo_data.get('software')
+
+    return software.get('name') if software else None
+
+
 async def follow_remote_actor(actor_uri):
     actor = await fetch_actor(actor_uri)
     
@@ -238,6 +258,7 @@ async def handle_follow(actor, data, request):
     following = DATABASE.get('relay-list', [])
     inbox = get_actor_inbox(actor)
 
+
     if urlsplit(inbox).hostname in AP_CONFIG['blocked_instances']:
         return
 
@@ -245,8 +266,7 @@ async def handle_follow(actor, data, request):
         following += [inbox]
         DATABASE['relay-list'] = following
 
-        if data['object'].endswith('/actor'):
-            asyncio.ensure_future(follow_remote_actor(actor['id']))
+        asyncio.ensure_future(follow_remote_actor(actor['id']))
 
     message = {
         "@context": "https://www.w3.org/ns/activitystreams",
@@ -256,10 +276,10 @@ async def handle_follow(actor, data, request):
 
         # this is wrong per litepub, but mastodon < 2.4 is not compliant with that profile.
         "object": {
-             "type": "Follow",
-             "id": data["id"],
-             "object": "https://{}/actor".format(request.host),
-             "actor": actor["id"]
+            "type": "Follow",
+            "id": data["id"],
+            "object": "https://{}/actor".format(request.host),
+            "actor": actor["id"]
         },
 
         "id": "https://{}/activities/{}".format(request.host, uuid.uuid4()),
@@ -281,8 +301,7 @@ async def handle_undo(actor, data, request):
             following.remove(inbox)
             DATABASE['relay-list'] = following
 
-        if child['object'].endswith('/actor'):
-            await unfollow_remote_actor(actor['id'])
+        await unfollow_remote_actor(actor['id'])
 
 
 processors = {
@@ -299,6 +318,12 @@ async def inbox(request):
     data = await request.json()
     instance = urlsplit(data['actor']).hostname
 
+    if AP_CONFIG['blocked_software']:
+        software = await fetch_nodeinfo(instance)
+
+        if software and software.lower() in AP_CONFIG['blocked_software']:
+            raise aiohttp.web.HTTPUnauthorized(body='relays have been blocked', content_type='text/plain')
+
     if 'actor' not in data or not request['validated']:
         raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')