blob: 82f71c0f84334786468612163aeeefe757cf59a9 [file] [log] [blame]
Brad Bishopaa65f6e2015-10-27 16:28:51 -04001#!/usr/bin/env python
2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05003import os
4import sys
Brad Bishopaa65f6e2015-10-27 16:28:51 -04005import dbus
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05006import dbus.exceptions
7import json
8import logging
9from xml.etree import ElementTree
10from rocket import Rocket
11from bottle import Bottle, abort, request, response, JSONPlugin, HTTPError
Brad Bishopaa65f6e2015-10-27 16:28:51 -040012import OpenBMCMapper
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050013from OpenBMCMapper import Mapper, PathTree, IntrospectionNodeParser, ListMatch
Brad Bishop2f428582015-12-02 10:56:11 -050014import spwd
15import grp
16import crypt
Brad Bishopaa65f6e2015-10-27 16:28:51 -040017
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050018DBUS_UNKNOWN_INTERFACE = 'org.freedesktop.UnknownInterface'
19DBUS_UNKNOWN_METHOD = 'org.freedesktop.DBus.Error.UnknownMethod'
20DBUS_INVALID_ARGS = 'org.freedesktop.DBus.Error.InvalidArgs'
Brad Bishopd4578922015-12-02 11:10:36 -050021DBUS_TYPE_ERROR = 'org.freedesktop.DBus.Python.TypeError'
Brad Bishopaac521c2015-11-25 09:16:35 -050022DELETE_IFACE = 'org.openbmc.Object.Delete'
Brad Bishop9ee57c42015-11-03 14:59:29 -050023
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050024_4034_msg = "The specified %s cannot be %s: '%s'"
Brad Bishopaa65f6e2015-10-27 16:28:51 -040025
Brad Bishop2f428582015-12-02 10:56:11 -050026def valid_user(session, *a, **kw):
27 ''' Authorization plugin callback that checks that the user is logged in. '''
28 if session is None:
29 abort(403, 'Login required')
30
31class UserInGroup:
32 ''' Authorization plugin callback that checks that the user is logged in
33 and a member of a group. '''
34 def __init__(self, group):
35 self.group = group
36
37 def __call__(self, session, *a, **kw):
38 valid_user(session, *a, **kw)
39 res = False
40
41 try:
42 res = session['user'] in grp.getgrnam(self.group)[3]
43 except KeyError:
44 pass
45
46 if not res:
47 abort(403, 'Insufficient access')
48
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050049def find_case_insensitive(value, lst):
50 return next((x for x in lst if x.lower() == value.lower()), None)
Brad Bishopaa65f6e2015-10-27 16:28:51 -040051
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050052def makelist(data):
53 if isinstance(data, list):
54 return data
55 elif data:
56 return [data]
57 else:
58 return []
Brad Bishopaa65f6e2015-10-27 16:28:51 -040059
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050060class RouteHandler(object):
Brad Bishop2f428582015-12-02 10:56:11 -050061 _require_auth = makelist(valid_user)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050062 def __init__(self, app, bus, verbs, rules):
63 self.app = app
64 self.bus = bus
65 self.mapper = Mapper(bus)
66 self._verbs = makelist(verbs)
67 self._rules = rules
Brad Bishopaa65f6e2015-10-27 16:28:51 -040068
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050069 def _setup(self, **kw):
70 request.route_data = {}
71 if request.method in self._verbs:
72 return self.setup(**kw)
73 else:
74 self.find(**kw)
75 raise HTTPError(405, "Method not allowed.",
76 Allow=','.join(self._verbs))
Brad Bishopaa65f6e2015-10-27 16:28:51 -040077
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050078 def __call__(self, **kw):
79 return getattr(self, 'do_' + request.method.lower())(**kw)
Brad Bishopaa65f6e2015-10-27 16:28:51 -040080
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050081 def install(self):
82 self.app.route(self._rules, callback = self,
83 method = ['GET', 'PUT', 'PATCH', 'POST', 'DELETE'])
Brad Bishopaa65f6e2015-10-27 16:28:51 -040084
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050085 @staticmethod
86 def try_mapper_call(f, callback = None, **kw):
Brad Bishopaa65f6e2015-10-27 16:28:51 -040087 try:
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050088 return f(**kw)
89 except dbus.exceptions.DBusException, e:
90 if e.get_dbus_name() != OpenBMCMapper.MAPPER_NOT_FOUND:
91 raise
92 if callback is None:
93 def callback(e, **kw):
94 abort(404, str(e))
Brad Bishopaa65f6e2015-10-27 16:28:51 -040095
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050096 callback(e, **kw)
Brad Bishopaa65f6e2015-10-27 16:28:51 -040097
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050098 @staticmethod
99 def try_properties_interface(f, *a):
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400100 try:
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500101 return f(*a)
102 except dbus.exceptions.DBusException, e:
103 if DBUS_UNKNOWN_INTERFACE in e.get_dbus_message():
104 # interface doesn't have any properties
105 return None
106 if DBUS_UNKNOWN_METHOD == e.get_dbus_name():
107 # properties interface not implemented at all
108 return None
109 raise
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400110
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500111class DirectoryHandler(RouteHandler):
112 verbs = 'GET'
113 rules = '<path:path>/'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400114
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500115 def __init__(self, app, bus):
116 super(DirectoryHandler, self).__init__(
117 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400118
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500119 def find(self, path = '/'):
120 return self.try_mapper_call(
121 self.mapper.get_subtree_paths,
122 path = path, depth = 1)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400123
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500124 def setup(self, path = '/'):
125 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400126
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500127 def do_get(self, path = '/'):
128 return request.route_data['map']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400129
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500130class ListNamesHandler(RouteHandler):
131 verbs = 'GET'
132 rules = ['/list', '<path:path>/list']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400133
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500134 def __init__(self, app, bus):
135 super(ListNamesHandler, self).__init__(
136 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400137
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500138 def find(self, path = '/'):
139 return self.try_mapper_call(
140 self.mapper.get_subtree, path = path).keys()
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400141
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500142 def setup(self, path = '/'):
143 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400144
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500145 def do_get(self, path = '/'):
146 return request.route_data['map']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400147
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500148class ListHandler(RouteHandler):
149 verbs = 'GET'
150 rules = ['/enumerate', '<path:path>/enumerate']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400151
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500152 def __init__(self, app, bus):
153 super(ListHandler, self).__init__(
154 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400155
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500156 def find(self, path = '/'):
157 return self.try_mapper_call(
158 self.mapper.get_subtree, path = path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400159
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500160 def setup(self, path = '/'):
161 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400162
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500163 def do_get(self, path = '/'):
Brad Bishop936f5fe2015-11-03 15:10:11 -0500164 objs = {}
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500165 mapper_data = request.route_data['map']
Brad Bishop936f5fe2015-11-03 15:10:11 -0500166 tree = PathTree()
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400167 for x,y in mapper_data.iteritems():
Brad Bishop936f5fe2015-11-03 15:10:11 -0500168 tree[x] = y
169
170 try:
171 # Check to see if the root path implements
172 # enumerate in addition to any sub tree
173 # objects.
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500174 root = self.try_mapper_call(self.mapper.get_object,
175 path = path)
176 mapper_data[path] = root
Brad Bishop936f5fe2015-11-03 15:10:11 -0500177 except:
178 pass
179
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500180 have_enumerate = [ (x[0], self.enumerate_capable(*x)) \
181 for x in mapper_data.iteritems() \
182 if self.enumerate_capable(*x) ]
Brad Bishop936f5fe2015-11-03 15:10:11 -0500183
184 for x,y in have_enumerate:
185 objs.update(self.call_enumerate(x, y))
186 tmp = tree[x]
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500187 # remove the subtree
Brad Bishop936f5fe2015-11-03 15:10:11 -0500188 del tree[x]
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500189 # add the new leaf back since enumerate results don't
190 # include the object enumerate is being invoked on
Brad Bishop936f5fe2015-11-03 15:10:11 -0500191 tree[x] = tmp
192
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500193 # make dbus calls for any remaining objects
Brad Bishop936f5fe2015-11-03 15:10:11 -0500194 for x,y in tree.dataitems():
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500195 objs[x] = self.app.instance_handler.do_get(x)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400196
197 return objs
198
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500199 @staticmethod
200 def enumerate_capable(path, bus_data):
201 busses = []
202 for name, ifaces in bus_data.iteritems():
203 if OpenBMCMapper.ENUMERATE_IFACE in ifaces:
204 busses.append(name)
205 return busses
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400206
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500207 def call_enumerate(self, path, busses):
208 objs = {}
209 for b in busses:
210 obj = self.bus.get_object(b, path, introspect = False)
211 iface = dbus.Interface(obj, OpenBMCMapper.ENUMERATE_IFACE)
212 objs.update(iface.enumerate())
213 return objs
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400214
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500215class MethodHandler(RouteHandler):
216 verbs = 'POST'
217 rules = '<path:path>/action/<method>'
218 request_type = list
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400219
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500220 def __init__(self, app, bus):
221 super(MethodHandler, self).__init__(
222 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400223
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500224 def find(self, path, method):
225 busses = self.try_mapper_call(self.mapper.get_object,
226 path = path)
227 for items in busses.iteritems():
228 m = self.find_method_on_bus(path, method, *items)
229 if m:
230 return m
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400231
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500232 abort(404, _4034_msg %('method', 'found', method))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400233
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500234 def setup(self, path, method):
235 request.route_data['method'] = self.find(path, method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400236
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500237 def do_post(self, path, method):
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400238 try:
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500239 if request.parameter_list:
240 return request.route_data['method'](*request.parameter_list)
241 else:
242 return request.route_data['method']()
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400243
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500244 except dbus.exceptions.DBusException, e:
245 if e.get_dbus_name() == DBUS_INVALID_ARGS:
246 abort(400, str(e))
Brad Bishopd4578922015-12-02 11:10:36 -0500247 if e.get_dbus_name() == DBUS_TYPE_ERROR:
248 abort(400, str(e))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500249 raise
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400250
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500251 @staticmethod
252 def find_method_in_interface(method, obj, interface, methods):
253 if methods is None:
254 return None
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400255
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500256 method = find_case_insensitive(method, methods.keys())
257 if method is not None:
258 iface = dbus.Interface(obj, interface)
259 return iface.get_dbus_method(method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400260
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500261 def find_method_on_bus(self, path, method, bus, interfaces):
262 obj = self.bus.get_object(bus, path, introspect = False)
263 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
264 data = iface.Introspect()
265 parser = IntrospectionNodeParser(
266 ElementTree.fromstring(data),
267 intf_match = ListMatch(interfaces))
268 for x,y in parser.get_interfaces().iteritems():
269 m = self.find_method_in_interface(method, obj, x,
270 y.get('method'))
271 if m:
272 return m
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400273
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500274class PropertyHandler(RouteHandler):
275 verbs = ['PUT', 'GET']
276 rules = '<path:path>/attr/<prop>'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400277
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500278 def __init__(self, app, bus):
279 super(PropertyHandler, self).__init__(
280 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400281
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500282 def find(self, path, prop):
283 self.app.instance_handler.setup(path)
284 obj = self.app.instance_handler.do_get(path)
285 try:
286 obj[prop]
287 except KeyError, e:
288 if request.method == 'PUT':
289 abort(403, _4034_msg %('property', 'created', str(e)))
290 else:
291 abort(404, _4034_msg %('property', 'found', str(e)))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400292
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500293 return { path: obj }
294
295 def setup(self, path, prop):
296 request.route_data['obj'] = self.find(path, prop)
297
298 def do_get(self, path, prop):
299 return request.route_data['obj'][path][prop]
300
301 def do_put(self, path, prop, value = None):
302 if value is None:
303 value = request.parameter_list
304
305 prop, iface, properties_iface = self.get_host_interface(
306 path, prop, request.route_data['map'][path])
307 try:
308 properties_iface.Set(iface, prop, value)
309 except ValueError, e:
310 abort(400, str(e))
311 except dbus.exceptions.DBusException, e:
312 if e.get_dbus_name() == DBUS_INVALID_ARGS:
313 abort(403, str(e))
314 raise
315
316 def get_host_interface(self, path, prop, bus_info):
317 for bus, interfaces in bus_info.iteritems():
318 obj = self.bus.get_object(bus, path, introspect = True)
319 properties_iface = dbus.Interface(
320 obj, dbus_interface=dbus.PROPERTIES_IFACE)
321
322 info = self.get_host_interface_on_bus(
323 path, prop, properties_iface,
324 bus, interfaces)
325 if info is not None:
326 prop, iface = info
327 return prop, iface, properties_iface
328
329 def get_host_interface_on_bus(self, path, prop, iface, bus, interfaces):
330 for i in interfaces:
331 properties = self.try_properties_interface(iface.GetAll, i)
332 if properties is None:
333 continue
334 prop = find_case_insensitive(prop, properties.keys())
335 if prop is None:
336 continue
337 return prop, i
338
339class InstanceHandler(RouteHandler):
340 verbs = ['GET', 'PUT', 'DELETE']
341 rules = '<path:path>'
342 request_type = dict
343
344 def __init__(self, app, bus):
345 super(InstanceHandler, self).__init__(
346 app, bus, self.verbs, self.rules)
347
348 def find(self, path, callback = None):
349 return { path: self.try_mapper_call(
350 self.mapper.get_object,
351 callback,
352 path = path) }
353
354 def setup(self, path):
355 callback = None
356 if request.method == 'PUT':
357 def callback(e, **kw):
358 abort(403, _4034_msg %('resource',
359 'created', path))
360
361 if request.route_data.get('map') is None:
362 request.route_data['map'] = self.find(path, callback)
363
364 def do_get(self, path):
365 properties = {}
366 for item in request.route_data['map'][path].iteritems():
367 properties.update(self.get_properties_on_bus(
368 path, *item))
369
370 return properties
371
372 @staticmethod
373 def get_properties_on_iface(properties_iface, iface):
374 properties = InstanceHandler.try_properties_interface(
375 properties_iface.GetAll, iface)
376 if properties is None:
377 return {}
378 return properties
379
380 def get_properties_on_bus(self, path, bus, interfaces):
381 properties = {}
382 obj = self.bus.get_object(bus, path, introspect = False)
383 properties_iface = dbus.Interface(
384 obj, dbus_interface=dbus.PROPERTIES_IFACE)
385 for i in interfaces:
386 properties.update(self.get_properties_on_iface(
387 properties_iface, i))
388
389 return properties
390
391 def do_put(self, path):
392 # make sure all properties exist in the request
393 obj = set(self.do_get(path).keys())
394 req = set(request.parameter_list.keys())
395
396 diff = list(obj.difference(req))
397 if diff:
398 abort(403, _4034_msg %('resource', 'removed',
399 '%s/attr/%s' %(path, diff[0])))
400
401 diff = list(req.difference(obj))
402 if diff:
403 abort(403, _4034_msg %('resource', 'created',
404 '%s/attr/%s' %(path, diff[0])))
405
406 for p,v in request.parameter_list.iteritems():
407 self.app.property_handler.do_put(
408 path, p, v)
409
410 def do_delete(self, path):
411 for bus_info in request.route_data['map'][path].iteritems():
412 if self.bus_missing_delete(path, *bus_info):
413 abort(403, _4034_msg %('resource', 'removed',
414 path))
415
416 for bus in request.route_data['map'][path].iterkeys():
417 self.delete_on_bus(path, bus)
418
419 def bus_missing_delete(self, path, bus, interfaces):
420 return DELETE_IFACE not in interfaces
421
422 def delete_on_bus(self, path, bus):
423 obj = self.bus.get_object(bus, path, introspect = False)
424 delete_iface = dbus.Interface(
425 obj, dbus_interface = DELETE_IFACE)
426 delete_iface.Delete()
427
Brad Bishop2f428582015-12-02 10:56:11 -0500428class SessionHandler(MethodHandler):
429 ''' Handles the /login and /logout routes, manages server side session store and
430 session cookies. '''
431
432 rules = ['/login', '/logout']
433 login_str = "User '%s' logged %s"
434 bad_passwd_str = "Invalid username or password"
435 no_user_str = "No user logged in"
436 bad_json_str = "Expecting request format { 'data': [<username>, <password>] }, got '%s'"
437 _require_auth = None
438 MAX_SESSIONS = 16
439
440 def __init__(self, app, bus):
441 super(SessionHandler, self).__init__(
442 app, bus)
443 self.hmac_key = os.urandom(128)
444 self.session_store = []
445
446 @staticmethod
447 def authenticate(username, clear):
448 try:
449 encoded = spwd.getspnam(username)[1]
450 return encoded == crypt.crypt(clear, encoded)
451 except KeyError:
452 return False
453
454 def invalidate_session(self, session):
455 try:
456 self.session_store.remove(session)
457 except ValueError:
458 pass
459
460 def new_session(self):
461 sid = os.urandom(32)
462 if self.MAX_SESSIONS <= len(self.session_store):
463 self.session_store.pop()
464 self.session_store.insert(0, {'sid': sid})
465
466 return self.session_store[0]
467
468 def get_session(self, sid):
469 sids = [ x['sid'] for x in self.session_store ]
470 try:
471 return self.session_store[sids.index(sid)]
472 except ValueError:
473 return None
474
475 def get_session_from_cookie(self):
476 return self.get_session(
477 request.get_cookie('sid',
478 secret = self.hmac_key))
479
480 def do_post(self, **kw):
481 if request.path == '/login':
482 return self.do_login(**kw)
483 else:
484 return self.do_logout(**kw)
485
486 def do_logout(self, **kw):
487 session = self.get_session_from_cookie()
488 if session is not None:
489 user = session['user']
490 self.invalidate_session(session)
491 response.delete_cookie('sid')
492 return self.login_str %(user, 'out')
493
494 return self.no_user_str
495
496 def do_login(self, **kw):
497 session = self.get_session_from_cookie()
498 if session is not None:
499 return self.login_str %(session['user'], 'in')
500
501 if len(request.parameter_list) != 2:
502 abort(400, self.bad_json_str %(request.json))
503
504 if not self.authenticate(*request.parameter_list):
505 return self.bad_passwd_str
506
507 user = request.parameter_list[0]
508 session = self.new_session()
509 session['user'] = user
510 response.set_cookie('sid', session['sid'], secret = self.hmac_key,
511 secure = True,
512 httponly = True)
513 return self.login_str %(user, 'in')
514
515 def find(self, **kw):
516 pass
517
518 def setup(self, **kw):
519 pass
520
521class AuthorizationPlugin(object):
522 ''' Invokes an optional list of authorization callbacks. '''
523
524 name = 'authorization'
525 api = 2
526
527 class Compose:
528 def __init__(self, validators, callback, session_mgr):
529 self.validators = validators
530 self.callback = callback
531 self.session_mgr = session_mgr
532
533 def __call__(self, *a, **kw):
534 sid = request.get_cookie('sid', secret = self.session_mgr.hmac_key)
535 session = self.session_mgr.get_session(sid)
536 for x in self.validators:
537 x(session, *a, **kw)
538
539 return self.callback(*a, **kw)
540
541 def apply(self, callback, route):
542 undecorated = route.get_undecorated_callback()
543 if not isinstance(undecorated, RouteHandler):
544 return callback
545
546 auth_types = getattr(undecorated,
547 '_require_auth', None)
548 if not auth_types:
549 return callback
550
551 return self.Compose(auth_types, callback,
552 undecorated.app.session_handler)
553
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500554class JsonApiRequestPlugin(object):
555 ''' Ensures request content satisfies the OpenBMC json api format. '''
556 name = 'json_api_request'
557 api = 2
558
559 error_str = "Expecting request format { 'data': <value> }, got '%s'"
560 type_error_str = "Unsupported Content-Type: '%s'"
561 json_type = "application/json"
562 request_methods = ['PUT', 'POST', 'PATCH']
563
564 @staticmethod
565 def content_expected():
566 return request.method in JsonApiRequestPlugin.request_methods
567
568 def validate_request(self):
569 if request.content_length > 0 and \
570 request.content_type != self.json_type:
571 abort(415, self.type_error_str %(request.content_type))
572
573 try:
574 request.parameter_list = request.json.get('data')
575 except ValueError, e:
576 abort(400, str(e))
577 except (AttributeError, KeyError, TypeError):
578 abort(400, self.error_str %(request.json))
579
580 def apply(self, callback, route):
581 verbs = getattr(route.get_undecorated_callback(),
582 '_verbs', None)
583 if verbs is None:
584 return callback
585
586 if not set(self.request_methods).intersection(verbs):
587 return callback
588
589 def wrap(*a, **kw):
590 if self.content_expected():
591 self.validate_request()
592 return callback(*a, **kw)
593
594 return wrap
595
596class JsonApiRequestTypePlugin(object):
597 ''' Ensures request content type satisfies the OpenBMC json api format. '''
598 name = 'json_api_method_request'
599 api = 2
600
601 error_str = "Expecting request format { 'data': %s }, got '%s'"
602
603 def apply(self, callback, route):
604 request_type = getattr(route.get_undecorated_callback(),
605 'request_type', None)
606 if request_type is None:
607 return callback
608
609 def validate_request():
610 if not isinstance(request.parameter_list, request_type):
611 abort(400, self.error_str %(str(request_type), request.json))
612
613 def wrap(*a, **kw):
614 if JsonApiRequestPlugin.content_expected():
615 validate_request()
616 return callback(*a, **kw)
617
618 return wrap
619
620class JsonApiResponsePlugin(object):
621 ''' Emits normal responses in the OpenBMC json api format. '''
622 name = 'json_api_response'
623 api = 2
624
625 def apply(self, callback, route):
626 def wrap(*a, **kw):
627 resp = { 'data': callback(*a, **kw) }
628 resp['status'] = 'ok'
629 resp['message'] = response.status_line
630 return resp
631 return wrap
632
633class JsonApiErrorsPlugin(object):
634 ''' Emits error responses in the OpenBMC json api format. '''
635 name = 'json_api_errors'
636 api = 2
637
638 def __init__(self, **kw):
639 self.app = None
640 self.function_type = None
641 self.original = None
642 self.json_opts = { x:y for x,y in kw.iteritems() \
643 if x in ['indent','sort_keys'] }
644
645 def setup(self, app):
646 self.app = app
647 self.function_type = type(app.default_error_handler)
648 self.original = app.default_error_handler
649 self.app.default_error_handler = self.function_type(
650 self.json_errors, app, Bottle)
651
652 def apply(self, callback, route):
653 return callback
654
655 def close(self):
656 self.app.default_error_handler = self.function_type(
657 self.original, self.app, Bottle)
658
659 def json_errors(self, res, error):
660 response_object = {'status': 'error', 'data': {} }
661 response_object['message'] = error.status_line
662 response_object['data']['description'] = str(error.body)
663 if error.status_code == 500:
664 response_object['data']['exception'] = repr(error.exception)
665 response_object['data']['traceback'] = error.traceback.splitlines()
666
667 json_response = json.dumps(response_object, **self.json_opts)
Brad Bishop9bfeec22015-11-17 09:14:50 -0500668 response.content_type = 'application/json'
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500669 return json_response
670
671class RestApp(Bottle):
672 def __init__(self, bus):
673 super(RestApp, self).__init__(autojson = False)
Brad Bishop53fd4932015-10-30 09:22:30 -0400674 self.bus = bus
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500675 self.mapper = Mapper(bus)
676
677 self.install_hooks()
678 self.install_plugins()
679 self.create_handlers()
680 self.install_handlers()
681
682 def install_plugins(self):
683 # install json api plugins
684 json_kw = {'indent': 2, 'sort_keys': True}
685 self.install(JSONPlugin(**json_kw))
686 self.install(JsonApiErrorsPlugin(**json_kw))
Brad Bishop2f428582015-12-02 10:56:11 -0500687 self.install(AuthorizationPlugin())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500688 self.install(JsonApiResponsePlugin())
689 self.install(JsonApiRequestPlugin())
690 self.install(JsonApiRequestTypePlugin())
691
692 def install_hooks(self):
693 self.real_router_match = self.router.match
694 self.router.match = self.custom_router_match
695 self.add_hook('before_request', self.strip_extra_slashes)
696
697 def create_handlers(self):
698 # create route handlers
Brad Bishop2f428582015-12-02 10:56:11 -0500699 self.session_handler = SessionHandler(self, self.bus)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500700 self.directory_handler = DirectoryHandler(self, self.bus)
701 self.list_names_handler = ListNamesHandler(self, self.bus)
702 self.list_handler = ListHandler(self, self.bus)
703 self.method_handler = MethodHandler(self, self.bus)
704 self.property_handler = PropertyHandler(self, self.bus)
705 self.instance_handler = InstanceHandler(self, self.bus)
706
707 def install_handlers(self):
Brad Bishop2f428582015-12-02 10:56:11 -0500708 self.session_handler.install()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500709 self.directory_handler.install()
710 self.list_names_handler.install()
711 self.list_handler.install()
712 self.method_handler.install()
713 self.property_handler.install()
714 # this has to come last, since it matches everything
715 self.instance_handler.install()
716
717 def custom_router_match(self, environ):
718 ''' The built-in Bottle algorithm for figuring out if a 404 or 405 is
719 needed doesn't work for us since the instance rules match everything.
720 This monkey-patch lets the route handler figure out which response is
721 needed. This could be accomplished with a hook but that would require
722 calling the router match function twice.
723 '''
724 route, args = self.real_router_match(environ)
725 if isinstance(route.callback, RouteHandler):
726 route.callback._setup(**args)
727
728 return route, args
729
730 @staticmethod
731 def strip_extra_slashes():
732 path = request.environ['PATH_INFO']
733 trailing = ("","/")[path[-1] == '/']
734 parts = filter(bool, path.split('/'))
735 request.environ['PATH_INFO'] = '/' + '/'.join(parts) + trailing
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400736
737if __name__ == '__main__':
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500738 log = logging.getLogger('Rocket.Errors')
739 log.setLevel(logging.INFO)
740 log.addHandler(logging.StreamHandler(sys.stdout))
741
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400742 bus = dbus.SystemBus()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500743 app = RestApp(bus)
744 default_cert = os.path.join(sys.prefix, 'share',
745 os.path.basename(__file__), 'cert.pem')
746
747 server = Rocket(('0.0.0.0',
748 443,
749 default_cert,
750 default_cert),
Brad Bishopb7f756c2015-12-02 11:13:20 -0500751 'wsgi', {'wsgi_app': app},
752 min_threads = 1,
753 max_threads = 1)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500754 server.start()