pypubsub.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. #!/usr/bin/env python3
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing,
  13. # software distributed under the License is distributed on an
  14. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. # KIND, either express or implied. See the License for the
  16. # specific language governing permissions and limitations
  17. # under the License.
  18. """PyPubSub - a simple publisher/subscriber service written in Python 3"""
  19. import asyncio
  20. import aiohttp.web
  21. import time
  22. import json
  23. import yaml
  24. import netaddr
  25. import binascii
  26. import base64
  27. import argparse
  28. import plugins.ldap
  29. # Some consts
  30. PUBSUB_VERSION = '0.4.6'
  31. PUBSUB_CONTENT_TYPE = 'application/vnd.pypubsub-stream'
  32. PUBSUB_BAD_REQUEST = "I could not understand your request, sorry! Please see https://pubsub.apache.org/api.html \
  33. for usage documentation.\n"
  34. PUBSUB_PAYLOAD_RECEIVED = "Payload received, thank you very much!\n"
  35. PUBSUB_NOT_ALLOWED = "You are not authorized to deliver payloads!\n"
  36. PUBSUB_BAD_PAYLOAD = "Bad payload type. Payloads must be JSON dictionary objects, {..}!\n"
  37. class Server:
  38. """Main server class, responsible for handling requests and publishing events """
  39. def __init__(self, args):
  40. self.config = yaml.safe_load(open(args.config))
  41. self.lconfig = None
  42. self.no_requests = 0
  43. self.subscribers = []
  44. self.pending_events = []
  45. self.last_ping = time.time()
  46. if 'ldap' in self.config.get('clients', {}):
  47. self.lconfig = self.config['clients']['ldap']
  48. plugins.ldap.vet_settings(self.lconfig)
  49. self.acl = {}
  50. try:
  51. self.acl = yaml.safe_load(open(args.acl))
  52. except FileNotFoundError:
  53. print(f"ACL configuration file {args.acl} not found, private events will not be broadcast.")
  54. self.payloaders = [netaddr.IPNetwork(x) for x in self.config['clients']['payloaders']]
  55. async def poll(self):
  56. """Polls for new stuff to publish, and if found, publishes to whomever wants it."""
  57. while True:
  58. for payload in self.pending_events:
  59. bad_subs = await payload.publish(self.subscribers)
  60. # Cull subscribers we couldn't deliver payload to.
  61. for bad_sub in bad_subs:
  62. print("Culling %r due to connection errors" % bad_sub)
  63. self.subscribers.remove(bad_sub)
  64. self.pending_events = []
  65. await asyncio.sleep(0.5)
  66. async def handle_request(self, request):
  67. """Generic handler for all incoming HTTP requests"""
  68. self.no_requests += 1
  69. # Define response headers first...
  70. headers = {
  71. 'Server': 'PyPubSub/%s' % PUBSUB_VERSION,
  72. 'X-Subscribers': str(len(self.subscribers)),
  73. 'X-Requests': str(self.no_requests),
  74. }
  75. # Are we handling a publisher payload request? (PUT/POST)
  76. if request.method in ['PUT', 'POST']:
  77. ip = netaddr.IPAddress(request.remote)
  78. allowed = False
  79. for network in self.payloaders:
  80. if ip in network:
  81. allowed = True
  82. break
  83. if not allowed:
  84. resp = aiohttp.web.Response(headers=headers, status=403, text=PUBSUB_NOT_ALLOWED)
  85. return resp
  86. if request.can_read_body:
  87. try:
  88. body = await request.json()
  89. assert isinstance(body, dict) # Payload MUST be an dictionary object, {...}
  90. self.pending_events.append(Payload(request.path, body))
  91. resp = aiohttp.web.Response(headers=headers, status=202, text=PUBSUB_PAYLOAD_RECEIVED)
  92. return resp
  93. except json.decoder.JSONDecodeError:
  94. resp = aiohttp.web.Response(headers=headers, status=400, text=PUBSUB_BAD_REQUEST)
  95. return resp
  96. except AssertionError:
  97. resp = aiohttp.web.Response(headers=headers, status=400, text=PUBSUB_BAD_PAYLOAD)
  98. return resp
  99. # Is this a subscriber request? (GET)
  100. elif request.method == 'GET':
  101. resp = aiohttp.web.StreamResponse(headers=headers)
  102. # We do not support HTTP 1.0 here...
  103. if request.version.major == 1 and request.version.minor == 0:
  104. return resp
  105. subscriber = Subscriber(self, resp, request)
  106. # Is there a basic auth in this request? If so, set up ACL
  107. auth = request.headers.get('Authorization')
  108. if auth:
  109. subscriber.acl = await subscriber.parse_acl(auth)
  110. self.subscribers.append(subscriber)
  111. resp.content_type = PUBSUB_CONTENT_TYPE
  112. try:
  113. resp.enable_chunked_encoding()
  114. await resp.prepare(request)
  115. while True:
  116. await subscriber.ping()
  117. if subscriber not in self.subscribers: # If we got dislodged somehow, end session
  118. break
  119. await asyncio.sleep(5)
  120. # We may get exception types we don't have imported, so grab ANY exception and kick out the subscriber
  121. except:
  122. pass
  123. if subscriber in self.subscribers:
  124. self.subscribers.remove(subscriber)
  125. return resp
  126. elif request.method == 'HEAD':
  127. resp = aiohttp.web.Response(headers=headers, status=204, text="")
  128. return resp
  129. # I don't know this type of request :/ (DELETE, PATCH, etc)
  130. else:
  131. resp = aiohttp.web.Response(headers=headers, status=400, text=PUBSUB_BAD_REQUEST)
  132. return resp
  133. async def server_loop(self):
  134. server = aiohttp.web.Server(self.handle_request)
  135. runner = aiohttp.web.ServerRunner(server)
  136. await runner.setup()
  137. site = aiohttp.web.TCPSite(runner, self.config['server']['bind'], self.config['server']['port'])
  138. await site.start()
  139. print("==== PyPubSub v/%s starting... ====" % PUBSUB_VERSION)
  140. print("==== Serving up PubSub goodness at %s:%s ====" % (self.config['server']['bind'], self.config['server']['port']))
  141. await self.poll()
  142. def run(self):
  143. loop = asyncio.get_event_loop()
  144. try:
  145. loop.run_until_complete(self.server_loop())
  146. except KeyboardInterrupt:
  147. pass
  148. loop.close()
  149. class Subscriber:
  150. """Basic subscriber (client) class. Holds information about the connection and ACL"""
  151. def __init__(self, server, connection, request):
  152. self.connection = connection
  153. self.acl = {}
  154. self.server = server
  155. # Set topics subscribed to
  156. self.topics = [x for x in request.path.split('/') if x]
  157. # Is the client old and expecting zero-terminators?
  158. self.old_school = False
  159. for ua in self.server.config['clients'].get('oldschoolers', []):
  160. if ua in request.headers.get('User-Agent', ''):
  161. self.old_school = True
  162. break
  163. async def parse_acl(self, basic):
  164. """Sets the ACL if possible, based on Basic Auth"""
  165. try:
  166. decoded = str(base64.decodebytes(bytes(basic.replace('Basic ', ''), 'ascii')), 'utf-8')
  167. u, p = decoded.split(':', 1)
  168. if u in self.server.acl:
  169. acl_pass = self.server.acl[u].get('password')
  170. if acl_pass and acl_pass == p:
  171. acl = self.server.acl[u].get('acl', {})
  172. # Vet ACL for user
  173. assert isinstance(acl, dict), f"ACL for user {u} " \
  174. f"must be a dictionary of sub-IDs and topics, but is not."
  175. # Make sure each ACL segment is a list of topics
  176. for k, v in acl.items():
  177. assert isinstance(v, list), f"ACL segment {k} for user {u} is not a list of topics!"
  178. print(f"Client {u} successfully authenticated (and ACL is valid).")
  179. return acl
  180. elif self.server.lconfig:
  181. acl = {}
  182. groups = await plugins.ldap.get_groups(self.server.lconfig, u, p)
  183. # Make sure each ACL segment is a list of topics
  184. for k, v in self.server.lconfig['acl'].items():
  185. if k in groups:
  186. assert isinstance(v, dict), f"ACL segment {k} for user {u} is not a dictionary of segments!"
  187. for segment, topics in v.items():
  188. print(f"Enabling ACL segment {segment} for user {u}")
  189. assert isinstance(topics, list), f"ACL segment {segment} for user {u} is not a list of topics!"
  190. acl[segment] = topics
  191. return acl
  192. except binascii.Error as e:
  193. pass # Bad Basic Auth params, bail quietly
  194. except AssertionError as e:
  195. print(e)
  196. print(f"ACL configuration error: ACL scheme for {u} contains errors, setting ACL to nothing.")
  197. except Exception as e:
  198. print(f"Basic unknown exception occurred: {e}")
  199. return {}
  200. async def ping(self):
  201. """Generic ping-back to the client"""
  202. js = b"%s\n" % json.dumps({"stillalive": time.time()}).encode('utf-8')
  203. if self.old_school:
  204. js += b"\0"
  205. await self.connection.write(js)
  206. class Payload:
  207. """A payload (event) object sent by a registered publisher."""
  208. def __init__(self, path, data):
  209. self.json = data
  210. self.topics = [x for x in path.split('/') if x]
  211. self.private = False
  212. # Private payload?
  213. if self.topics[0] == 'private':
  214. self.private = True
  215. del self.topics[0] # Remove the private bit from topics now.
  216. self.json['pubsub_topics'] = self.topics
  217. self.json['pubsub_path'] = path
  218. async def publish(self, subscribers):
  219. """Publishes an object to all subscribers using those topics (or a sub-set thereof)"""
  220. js = b"%s\n" % json.dumps(self.json).encode('utf-8')
  221. ojs = js + b"\0"
  222. bad_subs = []
  223. for sub in subscribers:
  224. # If a private payload, check ACL and bail if not a match
  225. if self.private:
  226. can_see = False
  227. for key, private_topics in sub.acl.items():
  228. if all(el in self.topics for el in private_topics):
  229. can_see = True
  230. break
  231. if not can_see:
  232. continue
  233. # If subscribed to all the topics, tell a subscriber about this
  234. if all(el in self.topics for el in sub.topics):
  235. try:
  236. if sub.old_school:
  237. await sub.connection.write(ojs)
  238. else:
  239. await sub.connection.write(js)
  240. except Exception:
  241. bad_subs.append(sub)
  242. return bad_subs
  243. if __name__ == '__main__':
  244. parser = argparse.ArgumentParser()
  245. parser.add_argument("--config", help="Configuration file to load (default: pypubsub.yaml)", default="pypubsub.yaml")
  246. parser.add_argument("--acl", help="ACL Configuration file to load (default: pypubsub_acl.yaml)", default="pypubsub_acl.yaml")
  247. cliargs = parser.parse_args()
  248. pubsub_server = Server(cliargs)
  249. pubsub_server.run()