pypubsub.py 12 KB

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