views.py 5.69 KB
Newer Older
Izalia Mae's avatar
Izalia Mae committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import logging
import subprocess
import traceback

from aiohttp.web import HTTPForbidden, HTTPUnauthorized, Response, json_response
from urllib.parse import urlparse

from . import __version__, app, misc
from .http_debug import STATS
from .processors import run_processor


try:
	commit_label = subprocess.check_output(["git", "rev-parse", "HEAD"]).strip().decode('ascii')
Izalia Mae's avatar
Izalia Mae committed
15
	version = f'{__version__} {commit_label}'
Izalia Mae's avatar
Izalia Mae committed
16
17

except:
Izalia Mae's avatar
Izalia Mae committed
18
	version = __version__
Izalia Mae's avatar
Izalia Mae committed
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


async def home(request):
	targets = '<br>'.join(app['database'].hostnames)
	text = """
<html><head>
<title>ActivityPub Relay at {host}</title>
<style>
p {{ color: #FFFFFF; font-family: monospace, arial; font-size: 100%; }}
body {{ background-color: #000000; }}
a {{ color: #26F; }}
a:visited {{ color: #46C; }}
a:hover {{ color: #8AF; }}
</style>
</head>
<body>
<p>This is an Activity Relay for fediverse instances.</p>
<p>{note}</p>
<p>You may subscribe to this relay with the address: <a href="https://{host}/actor">https://{host}/actor</a></p>
<p>To host your own relay, you may download the code at this address: <a href="https://git.pleroma.social/pleroma/relay">https://git.pleroma.social/pleroma/relay</a></p>
<br><p>List of {count} registered instances:<br>{targets}</p>
</body></html>""".format(host=request.host, note=app['config'].note, targets=targets, count=len(app['database'].inboxes))

	return Response(
		status = 200,
		content_type = 'text/html',
		charset = 'utf-8',
		text = text
	)


async def actor(request):
	database = app['database']

	data = {
		"@context": "https://www.w3.org/ns/activitystreams",
		"endpoints": {
			"sharedInbox": f"https://{request.host}/inbox"
		},
		"followers": f"https://{request.host}/followers",
		"following": f"https://{request.host}/following",
		"inbox": f"https://{request.host}/inbox",
		"name": "ActivityRelay",
		"type": "Application",
		"id": f"https://{request.host}/actor",
		"publicKey": {
			"id": f"https://{request.host}/actor#main-key",
			"owner": f"https://{request.host}/actor",
			"publicKeyPem": database.pubkey
		},
		"summary": "ActivityRelay bot",
		"preferredUsername": "relay",
		"url": f"https://{request.host}/actor"
	}

	return json_response(data, content_type='application/activity+json')


async def inbox(request):
	config = app['config']
	database = app['database']

	## reject if missing signature header
	if 'signature' not in request.headers:
		logging.verbose('Actor missing signature header')
		raise HTTPUnauthorized(body='missing signature')

	## read message and get actor id and domain
	try:
		data = await request.json()
		actor_id = data['actor']
		actor_domain = urlparse(actor_id).hostname

	except KeyError:
		logging.verbose('actor not in data')
		raise HTTPUnauthorized(body='no actor in message')

	## reject if there is no actor in the message
	except:
		traceback.print_exc()
		logging.verbose('Failed to parse inbox message')
		raise HTTPUnauthorized(body='failed to parse message')

	actor = await misc.request(actor_id)

	## reject if actor is empty
	if not actor:
		logging.verbose(f'Failed to fetch actor: {actor_id}')
		raise HTTPUnauthorized('failed to fetch actor')

	## reject if the actor isn't whitelisted while the whiltelist is enabled
	elif config.whitelist_enabled and not config.is_whitelisted(actor_id):
		logging.verbose(f'Rejected actor for not being in the whitelist: {actor_id}')
		raise HTTPForbidden(body='access denied')

	## reject if actor is banned
	if app['config'].is_banned(actor_id):
		logging.verbose(f'Ignored request from banned actor: {actor_id}')
		raise HTTPForbidden(body='access denied')

	## reject if software used by actor is banned
	if len(config.blocked_software):
Izalia Mae's avatar
fixes    
Izalia Mae committed
121
		software = await misc.fetch_nodeinfo(actor_domain)
Izalia Mae's avatar
Izalia Mae committed
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

		if config.is_banned_software(software):
			logging.verbose(f'Rejected actor for using specific software: {software}')
			raise HTTPForbidden(body='access denied')

	## reject if the signature is invalid
	if not (await misc.validate_signature(actor_id, request)):
		logging.verbose(f'signature validation failed for: {actor_id}')
		raise HTTPUnauthorized(body='signature check failed, signature did not match key')

	## reject if activity type isn't 'Follow' and the actor isn't following
	if data['type'] != 'Follow' and not database.get_inbox(actor_domain):
		logging.verbose(f'Rejected actor for trying to post while not following: {actor_id}')
		raise HTTPUnauthorized(body='access denied')

	logging.debug(f">> payload {data}")

	await run_processor(request, data, actor)
	return Response(body=b'{}', content_type='application/activity+json')


async def webfinger(request):
	config = app['config']
	subject = request.query['resource']

	if subject != f'acct:relay@{request.host}':
		return json_response({'error': 'user not found'}, status=404)

	data = {
		'subject': subject,
		'aliases': [config.actor],
		'links': [
			{'href': config.actor, 'rel': 'self', 'type': 'application/activity+json'},
			{'href': config.actor, 'rel': 'self', 'type': 'application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"'}
		]
	}

	return json_response(data)


async def nodeinfo_2_0(request):
	data = {
		# XXX - is this valid for a relay?
		'openRegistrations': True,
		'protocols': ['activitypub'],
		'services': {
			'inbound': [],
			'outbound': []
		},
		'software': {
			'name': 'activityrelay',
Izalia Mae's avatar
Izalia Mae committed
173
			'version': version
Izalia Mae's avatar
Izalia Mae committed
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
		},
		'usage': {
			'localPosts': 0,
			'users': {
				'total': 1
			}
		},
		'metadata': {
			'peers': app['database'].hostnames
		},
		'version': '2.0'
	}

	return json_response(data)


async def nodeinfo_wellknown(request):
	data = {
		'links': [
			{
				'rel': 'http://nodeinfo.diaspora.software/ns/schema/2.0',
				'href': f'https://{request.host}/nodeinfo/2.0.json'
			}
		]
	}
	return json_response(data)


async def stats(request):
    return json_response(STATS)