pypubsub.py 10 KB

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