pypubsub.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 pypubsub_ldap
  28. # Some consts
  29. PUBSUB_VERSION = '0.4.0'
  30. PUBSUB_BAD_REQUEST = "I could not understand your request, sorry! Please see https://pubsub.apache.org/api.html \
  31. for usage documentation.\n"
  32. PUBSUB_PAYLOAD_RECEIVED = "Payload received, thank you very much!\n"
  33. PUBSUB_NOT_ALLOWED = "You are not authorized to deliver payloads!\n"
  34. PUBSUB_BAD_PAYLOAD = "Bad payload type. Payloads must be JSON dictionary objects, {..}!\n"
  35. class Server:
  36. """Main server class, responsible for handling requests and publishing events """
  37. def __init__(self):
  38. self.config = yaml.safe_load(open('pypubsub.yaml'))
  39. self.lconfig = None
  40. self.no_requests = 0
  41. self.subscribers = []
  42. self.pending_events = []
  43. self.last_ping = time.time()
  44. if 'ldap' in self.config.get('clients', {}):
  45. self.lconfig = self.config['clients']['ldap']
  46. pypubsub_ldap.vet_settings(self.lconfig)
  47. self.acl = {}
  48. try:
  49. self.acl = yaml.safe_load(open('pypubsub_acl.yaml'))
  50. except FileNotFoundError:
  51. print("No ACL configuration file found, private events will not be broadcast.")
  52. self.payloaders = [netaddr.IPNetwork(x) for x in self.config['clients']['payloaders']]
  53. async def poll(self):
  54. """Polls for new stuff to publish, and if found, publishes to whomever wants it."""
  55. while True:
  56. for payload in self.pending_events:
  57. await payload.publish(self.subscribers)
  58. self.pending_events = []
  59. await asyncio.sleep(0.5)
  60. async def handle_request(self, request):
  61. """Generic handler for all incoming HTTP requests"""
  62. self.no_requests += 1
  63. # Define response headers first...
  64. headers = {
  65. 'Server': 'PyPubSub/%s' % PUBSUB_VERSION,
  66. 'X-Subscribers': str(len(self.subscribers)),
  67. 'X-Requests': str(self.no_requests),
  68. }
  69. # Are we handling a publisher payload request? (PUT/POST)
  70. if request.method in ['PUT', 'POST']:
  71. ip = netaddr.IPAddress(request.remote)
  72. allowed = False
  73. for network in self.payloaders:
  74. if ip in network:
  75. allowed = True
  76. break
  77. if not allowed:
  78. resp = aiohttp.web.Response(headers=headers, status=403, text=PUBSUB_NOT_ALLOWED)
  79. return resp
  80. if request.can_read_body:
  81. try:
  82. body = await request.json()
  83. assert isinstance(body, dict) # Payload MUST be an dictionary object, {...}
  84. self.pending_events.append(Payload(request.path, body))
  85. resp = aiohttp.web.Response(headers=headers, status=202, text=PUBSUB_PAYLOAD_RECEIVED)
  86. return resp
  87. except json.decoder.JSONDecodeError:
  88. resp = aiohttp.web.Response(headers=headers, status=400, text=PUBSUB_BAD_REQUEST)
  89. return resp
  90. except AssertionError:
  91. resp = aiohttp.web.Response(headers=headers, status=400, text=PUBSUB_BAD_PAYLOAD)
  92. return resp
  93. # Is this a subscriber request? (GET)
  94. elif request.method == 'GET':
  95. resp = aiohttp.web.StreamResponse(headers=headers)
  96. # We do not support HTTP 1.0 here...
  97. if request.version.major == 1 and request.version.minor == 0:
  98. return resp
  99. subscriber = Subscriber(self, resp, request)
  100. # Is there a basic auth in this request? If so, set up ACL
  101. auth = request.headers.get('Authorization')
  102. if auth:
  103. subscriber.acl = await subscriber.parse_acl(auth)
  104. self.subscribers.append(subscriber)
  105. # We'll change the content type once we're ready
  106. # resp.content_type = 'application/vnd.apache-pubsub-stream'
  107. resp.content_type = 'application/json'
  108. try:
  109. resp.enable_chunked_encoding()
  110. await resp.prepare(request)
  111. while True:
  112. await subscriber.ping()
  113. await asyncio.sleep(5)
  114. # We may get exception types we don't have imported, so grab ANY exception and kick out the subscriber
  115. except:
  116. pass
  117. self.subscribers.remove(subscriber)
  118. return resp
  119. elif request.method == 'HEAD':
  120. resp = aiohttp.web.Response(headers=headers, status=204, text="")
  121. return resp
  122. # I don't know this type of request :/ (DELETE, PATCH, etc)
  123. else:
  124. resp = aiohttp.web.Response(headers=headers, status=400, text=PUBSUB_BAD_REQUEST)
  125. return resp
  126. async def server_loop(self):
  127. server = aiohttp.web.Server(self.handle_request)
  128. runner = aiohttp.web.ServerRunner(server)
  129. await runner.setup()
  130. site = aiohttp.web.TCPSite(runner, self.config['server']['bind'], self.config['server']['port'])
  131. await site.start()
  132. print("==== PyPubSub v/%s starting... ====" % PUBSUB_VERSION)
  133. print("==== Serving up PubSub goodness at %s:%s ====" % (self.config['server']['bind'], self.config['server']['port']))
  134. await self.poll()
  135. def run(self):
  136. loop = asyncio.get_event_loop()
  137. try:
  138. loop.run_until_complete(self.server_loop())
  139. except KeyboardInterrupt:
  140. pass
  141. loop.close()
  142. class Subscriber:
  143. """Basic subscriber (client) class. Holds information about the connection and ACL"""
  144. def __init__(self, server, connection, request):
  145. self.connection = connection
  146. self.acl = {}
  147. self.server = server
  148. # Set topics subscribed to
  149. self.topics = [x for x in request.path.split('/') if x]
  150. # Is the client old and expecting zero-terminators?
  151. self.old_school = False
  152. for ua in self.server.config['clients'].get('oldscoolers', []):
  153. if ua in request.headers.get('User-Agent', ''):
  154. self.old_school = True
  155. break
  156. async def parse_acl(self, basic):
  157. """Sets the ACL if possible, based on Basic Auth"""
  158. try:
  159. decoded = str(base64.decodebytes(bytes(basic.replace('Basic ', ''), 'ascii')), 'utf-8')
  160. u, p = decoded.split(':', 1)
  161. if u in self.server.acl:
  162. acl_pass = self.server.acl[u].get('password')
  163. if acl_pass and acl_pass == p:
  164. acl = self.server.acl[u].get('acl', {})
  165. # Vet ACL for user
  166. assert isinstance(acl, dict), f"ACL for user {u} " \
  167. f"must be a dictionary of sub-IDs and topics, but is not."
  168. # Make sure each ACL segment is a list of topics
  169. for k, v in acl.items():
  170. assert isinstance(v, list), f"ACL segment {k} for user {u} is not a list of topics!"
  171. print(f"Client {u} successfully authenticated (and ACL is valid).")
  172. return acl
  173. elif self.server.lconfig:
  174. acl = {}
  175. groups = await pypubsub_ldap.get_groups(self.server.lconfig, u, p)
  176. # Make sure each ACL segment is a list of topics
  177. for k, v in self.server.lconfig['acl'].items():
  178. if k in groups:
  179. assert isinstance(v, list), f"ACL segment {k} for user {u} is not a list of topics!"
  180. print(f"Enabling ACL segment {k} for user {u}")
  181. acl[k] = v
  182. return acl
  183. except binascii.Error as e:
  184. pass # Bad Basic Auth params, bail quietly
  185. except AssertionError as e:
  186. print(e)
  187. print(f"ACL configuration error: ACL scheme for {u} contains errors, setting ACL to nothing.")
  188. except Exception as e:
  189. print(f"Basic unknown exception occurred: {e}")
  190. return {}
  191. async def ping(self):
  192. """Generic ping-back to the client"""
  193. js = b"%s\n" % json.dumps({"stillalive": time.time()}).encode('utf-8')
  194. if self.old_school:
  195. js += b"\0"
  196. await self.connection.write(js)
  197. class Payload:
  198. """A payload (event) object sent by a registered publisher."""
  199. def __init__(self, path, data):
  200. self.json = data
  201. self.topics = [x for x in path.split('/') if x]
  202. self.private = False
  203. # Private payload?
  204. if self.topics[0] == 'private':
  205. self.private = True
  206. del self.topics[0] # Remove the private bit from topics now.
  207. self.json['pubsub_topics'] = self.topics
  208. self.json['pubsub_path'] = path
  209. async def publish(self, subscribers):
  210. """Publishes an object to all subscribers using those topics (or a sub-set thereof)"""
  211. js = b"%s\n" % json.dumps(self.json).encode('utf-8')
  212. ojs = js + b"\0"
  213. for sub in subscribers:
  214. # If a private payload, check ACL and bail if not a match
  215. if self.private:
  216. can_see = False
  217. for key, private_topics in sub.acl.items():
  218. if all(el in self.topics for el in private_topics):
  219. can_see = True
  220. break
  221. if not can_see:
  222. continue
  223. # If subscribed to all the topics, tell a subscriber about this
  224. if all(el in self.topics for el in sub.topics):
  225. try:
  226. if sub.old_school:
  227. await sub.connection.write(ojs)
  228. else:
  229. await sub.connection.write(js)
  230. except ConnectionResetError:
  231. pass
  232. except RuntimeError:
  233. pass
  234. except AssertionError: # drain helper throws these sometimes
  235. pass
  236. if __name__ == '__main__':
  237. pubsub_server = Server()
  238. pubsub_server.run()