blob: 6582190a814327a2203808b9c01ed01db4d6a0f5 [file] [log] [blame]
Brad Bishop68caa1e2016-03-04 15:42:08 -05001# Contributors Listed Below - COPYRIGHT 2016
2# [+] International Business Machines Corp.
3#
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14# implied. See the License for the specific language governing
15# permissions and limitations under the License.
16
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050017import os
Brad Bishopaa65f6e2015-10-27 16:28:51 -040018import dbus
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050019import dbus.exceptions
20import json
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050021from xml.etree import ElementTree
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050022from bottle import Bottle, abort, request, response, JSONPlugin, HTTPError
Brad Bishopb103d2d2016-03-04 16:19:14 -050023import obmc.utils.misc
Brad Bishopb103d2d2016-03-04 16:19:14 -050024from obmc.dbuslib.introspection import IntrospectionNodeParser
25import obmc.mapper
Brad Bishop2f428582015-12-02 10:56:11 -050026import spwd
27import grp
28import crypt
Brad Bishopaa65f6e2015-10-27 16:28:51 -040029
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050030DBUS_UNKNOWN_INTERFACE = 'org.freedesktop.UnknownInterface'
Brad Bishopf4e74982016-04-01 14:53:05 -040031DBUS_UNKNOWN_INTERFACE_ERROR = 'org.freedesktop.DBus.Error.UnknownInterface'
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050032DBUS_UNKNOWN_METHOD = 'org.freedesktop.DBus.Error.UnknownMethod'
33DBUS_INVALID_ARGS = 'org.freedesktop.DBus.Error.InvalidArgs'
Brad Bishopd4578922015-12-02 11:10:36 -050034DBUS_TYPE_ERROR = 'org.freedesktop.DBus.Python.TypeError'
Brad Bishopaac521c2015-11-25 09:16:35 -050035DELETE_IFACE = 'org.openbmc.Object.Delete'
Brad Bishop9ee57c42015-11-03 14:59:29 -050036
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050037_4034_msg = "The specified %s cannot be %s: '%s'"
Brad Bishopaa65f6e2015-10-27 16:28:51 -040038
Brad Bishop87b63c12016-03-18 14:47:51 -040039
Brad Bishop2f428582015-12-02 10:56:11 -050040def valid_user(session, *a, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -040041 ''' Authorization plugin callback that checks
42 that the user is logged in. '''
43 if session is None:
Brad Bishopdc3fbfa2016-09-08 09:51:38 -040044 abort(401, 'Login required')
Brad Bishop87b63c12016-03-18 14:47:51 -040045
Brad Bishop2f428582015-12-02 10:56:11 -050046
47class UserInGroup:
Brad Bishop87b63c12016-03-18 14:47:51 -040048 ''' Authorization plugin callback that checks that the user is logged in
49 and a member of a group. '''
50 def __init__(self, group):
51 self.group = group
Brad Bishop2f428582015-12-02 10:56:11 -050052
Brad Bishop87b63c12016-03-18 14:47:51 -040053 def __call__(self, session, *a, **kw):
54 valid_user(session, *a, **kw)
55 res = False
Brad Bishop2f428582015-12-02 10:56:11 -050056
Brad Bishop87b63c12016-03-18 14:47:51 -040057 try:
58 res = session['user'] in grp.getgrnam(self.group)[3]
59 except KeyError:
60 pass
Brad Bishop2f428582015-12-02 10:56:11 -050061
Brad Bishop87b63c12016-03-18 14:47:51 -040062 if not res:
63 abort(403, 'Insufficient access')
64
Brad Bishop2f428582015-12-02 10:56:11 -050065
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050066class RouteHandler(object):
Brad Bishop6d190602016-04-15 13:09:39 -040067 _require_auth = obmc.utils.misc.makelist(valid_user)
Brad Bishopd0c404a2017-02-21 09:23:25 -050068 _enable_cors = True
Brad Bishopaa65f6e2015-10-27 16:28:51 -040069
Brad Bishop87b63c12016-03-18 14:47:51 -040070 def __init__(self, app, bus, verbs, rules):
71 self.app = app
72 self.bus = bus
Brad Bishopb103d2d2016-03-04 16:19:14 -050073 self.mapper = obmc.mapper.Mapper(bus)
Brad Bishop6d190602016-04-15 13:09:39 -040074 self._verbs = obmc.utils.misc.makelist(verbs)
Brad Bishop87b63c12016-03-18 14:47:51 -040075 self._rules = rules
Brad Bishop0f79e522016-03-18 13:33:17 -040076 self.intf_match = obmc.utils.misc.org_dot_openbmc_match
Brad Bishopaa65f6e2015-10-27 16:28:51 -040077
Brad Bishop88c76a42017-02-21 00:02:02 -050078 if 'GET' in self._verbs:
79 self._verbs = list(set(self._verbs + ['HEAD']))
Brad Bishopd4c1c552017-02-21 00:07:28 -050080 if 'OPTIONS' not in self._verbs:
81 self._verbs.append('OPTIONS')
Brad Bishop88c76a42017-02-21 00:02:02 -050082
Brad Bishop87b63c12016-03-18 14:47:51 -040083 def _setup(self, **kw):
84 request.route_data = {}
Brad Bishopd4c1c552017-02-21 00:07:28 -050085
Brad Bishop87b63c12016-03-18 14:47:51 -040086 if request.method in self._verbs:
Brad Bishopd4c1c552017-02-21 00:07:28 -050087 if request.method != 'OPTIONS':
88 return self.setup(**kw)
Brad Bishop88c76a42017-02-21 00:02:02 -050089
Brad Bishopd4c1c552017-02-21 00:07:28 -050090 # Javascript implementations will not send credentials
91 # with an OPTIONS request. Don't help malicious clients
92 # by checking the path here and returning a 404 if the
93 # path doesn't exist.
94 return None
Brad Bishop88c76a42017-02-21 00:02:02 -050095
Brad Bishopd4c1c552017-02-21 00:07:28 -050096 # Return 405
Brad Bishop88c76a42017-02-21 00:02:02 -050097 raise HTTPError(
98 405, "Method not allowed.", Allow=','.join(self._verbs))
Brad Bishopaa65f6e2015-10-27 16:28:51 -040099
Brad Bishop87b63c12016-03-18 14:47:51 -0400100 def __call__(self, **kw):
101 return getattr(self, 'do_' + request.method.lower())(**kw)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400102
Brad Bishop88c76a42017-02-21 00:02:02 -0500103 def do_head(self, **kw):
104 return self.do_get(**kw)
105
Brad Bishopd4c1c552017-02-21 00:07:28 -0500106 def do_options(self, **kw):
107 for v in self._verbs:
108 response.set_header(
109 'Allow',
110 ','.join(self._verbs))
111 return None
112
Brad Bishop87b63c12016-03-18 14:47:51 -0400113 def install(self):
114 self.app.route(
115 self._rules, callback=self,
Brad Bishopd4c1c552017-02-21 00:07:28 -0500116 method=['OPTIONS', 'GET', 'PUT', 'PATCH', 'POST', 'DELETE'])
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400117
Brad Bishop87b63c12016-03-18 14:47:51 -0400118 @staticmethod
119 def try_mapper_call(f, callback=None, **kw):
120 try:
121 return f(**kw)
122 except dbus.exceptions.DBusException, e:
Brad Bishopfce77562016-11-28 15:44:18 -0500123 if e.get_dbus_name() == \
124 'org.freedesktop.DBus.Error.ObjectPathInUse':
125 abort(503, str(e))
Brad Bishopb103d2d2016-03-04 16:19:14 -0500126 if e.get_dbus_name() != obmc.mapper.MAPPER_NOT_FOUND:
Brad Bishop87b63c12016-03-18 14:47:51 -0400127 raise
128 if callback is None:
129 def callback(e, **kw):
130 abort(404, str(e))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400131
Brad Bishop87b63c12016-03-18 14:47:51 -0400132 callback(e, **kw)
133
134 @staticmethod
135 def try_properties_interface(f, *a):
136 try:
137 return f(*a)
138 except dbus.exceptions.DBusException, e:
139 if DBUS_UNKNOWN_INTERFACE in e.get_dbus_message():
140 # interface doesn't have any properties
141 return None
Brad Bishopf4e74982016-04-01 14:53:05 -0400142 if DBUS_UNKNOWN_INTERFACE_ERROR in e.get_dbus_name():
143 # interface doesn't have any properties
144 return None
Brad Bishop87b63c12016-03-18 14:47:51 -0400145 if DBUS_UNKNOWN_METHOD == e.get_dbus_name():
146 # properties interface not implemented at all
147 return None
148 raise
149
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400150
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500151class DirectoryHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400152 verbs = 'GET'
153 rules = '<path:path>/'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400154
Brad Bishop87b63c12016-03-18 14:47:51 -0400155 def __init__(self, app, bus):
156 super(DirectoryHandler, self).__init__(
157 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400158
Brad Bishop87b63c12016-03-18 14:47:51 -0400159 def find(self, path='/'):
160 return self.try_mapper_call(
161 self.mapper.get_subtree_paths, path=path, depth=1)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400162
Brad Bishop87b63c12016-03-18 14:47:51 -0400163 def setup(self, path='/'):
164 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400165
Brad Bishop87b63c12016-03-18 14:47:51 -0400166 def do_get(self, path='/'):
167 return request.route_data['map']
168
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400169
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500170class ListNamesHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400171 verbs = 'GET'
172 rules = ['/list', '<path:path>/list']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400173
Brad Bishop87b63c12016-03-18 14:47:51 -0400174 def __init__(self, app, bus):
175 super(ListNamesHandler, self).__init__(
176 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400177
Brad Bishop87b63c12016-03-18 14:47:51 -0400178 def find(self, path='/'):
179 return self.try_mapper_call(
180 self.mapper.get_subtree, path=path).keys()
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400181
Brad Bishop87b63c12016-03-18 14:47:51 -0400182 def setup(self, path='/'):
183 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400184
Brad Bishop87b63c12016-03-18 14:47:51 -0400185 def do_get(self, path='/'):
186 return request.route_data['map']
187
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400188
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500189class ListHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400190 verbs = 'GET'
191 rules = ['/enumerate', '<path:path>/enumerate']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400192
Brad Bishop87b63c12016-03-18 14:47:51 -0400193 def __init__(self, app, bus):
194 super(ListHandler, self).__init__(
195 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400196
Brad Bishop87b63c12016-03-18 14:47:51 -0400197 def find(self, path='/'):
198 return self.try_mapper_call(
199 self.mapper.get_subtree, path=path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400200
Brad Bishop87b63c12016-03-18 14:47:51 -0400201 def setup(self, path='/'):
202 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400203
Brad Bishop87b63c12016-03-18 14:47:51 -0400204 def do_get(self, path='/'):
Brad Bishop71527b42016-04-01 14:51:14 -0400205 return {x: y for x, y in self.mapper.enumerate_subtree(
206 path,
207 mapper_data=request.route_data['map']).dataitems()}
Brad Bishop87b63c12016-03-18 14:47:51 -0400208
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400209
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500210class MethodHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400211 verbs = 'POST'
212 rules = '<path:path>/action/<method>'
213 request_type = list
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400214
Brad Bishop87b63c12016-03-18 14:47:51 -0400215 def __init__(self, app, bus):
216 super(MethodHandler, self).__init__(
217 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400218
Brad Bishop87b63c12016-03-18 14:47:51 -0400219 def find(self, path, method):
220 busses = self.try_mapper_call(
221 self.mapper.get_object, path=path)
222 for items in busses.iteritems():
223 m = self.find_method_on_bus(path, method, *items)
224 if m:
225 return m
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400226
Brad Bishop87b63c12016-03-18 14:47:51 -0400227 abort(404, _4034_msg % ('method', 'found', method))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400228
Brad Bishop87b63c12016-03-18 14:47:51 -0400229 def setup(self, path, method):
230 request.route_data['method'] = self.find(path, method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400231
Brad Bishop87b63c12016-03-18 14:47:51 -0400232 def do_post(self, path, method):
233 try:
234 if request.parameter_list:
235 return request.route_data['method'](*request.parameter_list)
236 else:
237 return request.route_data['method']()
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400238
Brad Bishop87b63c12016-03-18 14:47:51 -0400239 except dbus.exceptions.DBusException, e:
240 if e.get_dbus_name() == DBUS_INVALID_ARGS:
241 abort(400, str(e))
242 if e.get_dbus_name() == DBUS_TYPE_ERROR:
243 abort(400, str(e))
244 raise
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400245
Brad Bishop87b63c12016-03-18 14:47:51 -0400246 @staticmethod
247 def find_method_in_interface(method, obj, interface, methods):
248 if methods is None:
249 return None
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400250
Brad Bishop6d190602016-04-15 13:09:39 -0400251 method = obmc.utils.misc.find_case_insensitive(method, methods.keys())
Brad Bishop87b63c12016-03-18 14:47:51 -0400252 if method is not None:
253 iface = dbus.Interface(obj, interface)
254 return iface.get_dbus_method(method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400255
Brad Bishop87b63c12016-03-18 14:47:51 -0400256 def find_method_on_bus(self, path, method, bus, interfaces):
257 obj = self.bus.get_object(bus, path, introspect=False)
258 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
259 data = iface.Introspect()
260 parser = IntrospectionNodeParser(
261 ElementTree.fromstring(data),
Brad Bishopb103d2d2016-03-04 16:19:14 -0500262 intf_match=obmc.utils.misc.ListMatch(interfaces))
Brad Bishop87b63c12016-03-18 14:47:51 -0400263 for x, y in parser.get_interfaces().iteritems():
264 m = self.find_method_in_interface(
265 method, obj, x, y.get('method'))
266 if m:
267 return m
268
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400269
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500270class PropertyHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400271 verbs = ['PUT', 'GET']
272 rules = '<path:path>/attr/<prop>'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400273
Brad Bishop87b63c12016-03-18 14:47:51 -0400274 def __init__(self, app, bus):
275 super(PropertyHandler, self).__init__(
276 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400277
Brad Bishop87b63c12016-03-18 14:47:51 -0400278 def find(self, path, prop):
279 self.app.instance_handler.setup(path)
280 obj = self.app.instance_handler.do_get(path)
281 try:
282 obj[prop]
283 except KeyError, e:
284 if request.method == 'PUT':
285 abort(403, _4034_msg % ('property', 'created', str(e)))
286 else:
287 abort(404, _4034_msg % ('property', 'found', str(e)))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400288
Brad Bishop87b63c12016-03-18 14:47:51 -0400289 return {path: obj}
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500290
Brad Bishop87b63c12016-03-18 14:47:51 -0400291 def setup(self, path, prop):
292 request.route_data['obj'] = self.find(path, prop)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500293
Brad Bishop87b63c12016-03-18 14:47:51 -0400294 def do_get(self, path, prop):
295 return request.route_data['obj'][path][prop]
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500296
Brad Bishop87b63c12016-03-18 14:47:51 -0400297 def do_put(self, path, prop, value=None):
298 if value is None:
299 value = request.parameter_list
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500300
Brad Bishop87b63c12016-03-18 14:47:51 -0400301 prop, iface, properties_iface = self.get_host_interface(
302 path, prop, request.route_data['map'][path])
303 try:
304 properties_iface.Set(iface, prop, value)
305 except ValueError, e:
306 abort(400, str(e))
307 except dbus.exceptions.DBusException, e:
308 if e.get_dbus_name() == DBUS_INVALID_ARGS:
309 abort(403, str(e))
310 raise
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500311
Brad Bishop87b63c12016-03-18 14:47:51 -0400312 def get_host_interface(self, path, prop, bus_info):
313 for bus, interfaces in bus_info.iteritems():
314 obj = self.bus.get_object(bus, path, introspect=True)
315 properties_iface = dbus.Interface(
316 obj, dbus_interface=dbus.PROPERTIES_IFACE)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500317
Brad Bishop87b63c12016-03-18 14:47:51 -0400318 info = self.get_host_interface_on_bus(
319 path, prop, properties_iface, bus, interfaces)
320 if info is not None:
321 prop, iface = info
322 return prop, iface, properties_iface
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500323
Brad Bishop87b63c12016-03-18 14:47:51 -0400324 def get_host_interface_on_bus(self, path, prop, iface, bus, interfaces):
325 for i in interfaces:
326 properties = self.try_properties_interface(iface.GetAll, i)
327 if properties is None:
328 continue
Brad Bishop8b0d3fa2016-11-28 15:41:47 -0500329 prop = obmc.utils.misc.find_case_insensitive(
330 prop, properties.keys())
Brad Bishop87b63c12016-03-18 14:47:51 -0400331 if prop is None:
332 continue
333 return prop, i
334
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500335
Brad Bishop2503bd62015-12-16 17:56:12 -0500336class SchemaHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400337 verbs = ['GET']
338 rules = '<path:path>/schema'
Brad Bishop2503bd62015-12-16 17:56:12 -0500339
Brad Bishop87b63c12016-03-18 14:47:51 -0400340 def __init__(self, app, bus):
341 super(SchemaHandler, self).__init__(
342 app, bus, self.verbs, self.rules)
Brad Bishop2503bd62015-12-16 17:56:12 -0500343
Brad Bishop87b63c12016-03-18 14:47:51 -0400344 def find(self, path):
345 return self.try_mapper_call(
346 self.mapper.get_object,
347 path=path)
Brad Bishop2503bd62015-12-16 17:56:12 -0500348
Brad Bishop87b63c12016-03-18 14:47:51 -0400349 def setup(self, path):
350 request.route_data['map'] = self.find(path)
Brad Bishop2503bd62015-12-16 17:56:12 -0500351
Brad Bishop87b63c12016-03-18 14:47:51 -0400352 def do_get(self, path):
353 schema = {}
354 for x in request.route_data['map'].iterkeys():
355 obj = self.bus.get_object(x, path, introspect=False)
356 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
357 data = iface.Introspect()
358 parser = IntrospectionNodeParser(
359 ElementTree.fromstring(data))
360 for x, y in parser.get_interfaces().iteritems():
361 schema[x] = y
Brad Bishop2503bd62015-12-16 17:56:12 -0500362
Brad Bishop87b63c12016-03-18 14:47:51 -0400363 return schema
364
Brad Bishop2503bd62015-12-16 17:56:12 -0500365
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500366class InstanceHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400367 verbs = ['GET', 'PUT', 'DELETE']
368 rules = '<path:path>'
369 request_type = dict
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500370
Brad Bishop87b63c12016-03-18 14:47:51 -0400371 def __init__(self, app, bus):
372 super(InstanceHandler, self).__init__(
373 app, bus, self.verbs, self.rules)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500374
Brad Bishop87b63c12016-03-18 14:47:51 -0400375 def find(self, path, callback=None):
376 return {path: self.try_mapper_call(
377 self.mapper.get_object,
378 callback,
379 path=path)}
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500380
Brad Bishop87b63c12016-03-18 14:47:51 -0400381 def setup(self, path):
382 callback = None
383 if request.method == 'PUT':
384 def callback(e, **kw):
385 abort(403, _4034_msg % ('resource', 'created', path))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500386
Brad Bishop87b63c12016-03-18 14:47:51 -0400387 if request.route_data.get('map') is None:
388 request.route_data['map'] = self.find(path, callback)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500389
Brad Bishop87b63c12016-03-18 14:47:51 -0400390 def do_get(self, path):
Brad Bishop71527b42016-04-01 14:51:14 -0400391 return self.mapper.enumerate_object(
392 path,
393 mapper_data=request.route_data['map'])
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500394
Brad Bishop87b63c12016-03-18 14:47:51 -0400395 def do_put(self, path):
396 # make sure all properties exist in the request
397 obj = set(self.do_get(path).keys())
398 req = set(request.parameter_list.keys())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500399
Brad Bishop87b63c12016-03-18 14:47:51 -0400400 diff = list(obj.difference(req))
401 if diff:
402 abort(403, _4034_msg % (
403 'resource', 'removed', '%s/attr/%s' % (path, diff[0])))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500404
Brad Bishop87b63c12016-03-18 14:47:51 -0400405 diff = list(req.difference(obj))
406 if diff:
407 abort(403, _4034_msg % (
408 'resource', 'created', '%s/attr/%s' % (path, diff[0])))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500409
Brad Bishop87b63c12016-03-18 14:47:51 -0400410 for p, v in request.parameter_list.iteritems():
411 self.app.property_handler.do_put(
412 path, p, v)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500413
Brad Bishop87b63c12016-03-18 14:47:51 -0400414 def do_delete(self, path):
415 for bus_info in request.route_data['map'][path].iteritems():
416 if self.bus_missing_delete(path, *bus_info):
417 abort(403, _4034_msg % ('resource', 'removed', path))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500418
Brad Bishop87b63c12016-03-18 14:47:51 -0400419 for bus in request.route_data['map'][path].iterkeys():
420 self.delete_on_bus(path, bus)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500421
Brad Bishop87b63c12016-03-18 14:47:51 -0400422 def bus_missing_delete(self, path, bus, interfaces):
423 return DELETE_IFACE not in interfaces
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500424
Brad Bishop87b63c12016-03-18 14:47:51 -0400425 def delete_on_bus(self, path, bus):
426 obj = self.bus.get_object(bus, path, introspect=False)
427 delete_iface = dbus.Interface(
428 obj, dbus_interface=DELETE_IFACE)
429 delete_iface.Delete()
430
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500431
Brad Bishop2f428582015-12-02 10:56:11 -0500432class SessionHandler(MethodHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400433 ''' Handles the /login and /logout routes, manages
434 server side session store and session cookies. '''
Brad Bishop2f428582015-12-02 10:56:11 -0500435
Brad Bishop87b63c12016-03-18 14:47:51 -0400436 rules = ['/login', '/logout']
437 login_str = "User '%s' logged %s"
438 bad_passwd_str = "Invalid username or password"
439 no_user_str = "No user logged in"
440 bad_json_str = "Expecting request format { 'data': " \
441 "[<username>, <password>] }, got '%s'"
442 _require_auth = None
443 MAX_SESSIONS = 16
Brad Bishop2f428582015-12-02 10:56:11 -0500444
Brad Bishop87b63c12016-03-18 14:47:51 -0400445 def __init__(self, app, bus):
446 super(SessionHandler, self).__init__(
447 app, bus)
448 self.hmac_key = os.urandom(128)
449 self.session_store = []
Brad Bishop2f428582015-12-02 10:56:11 -0500450
Brad Bishop87b63c12016-03-18 14:47:51 -0400451 @staticmethod
452 def authenticate(username, clear):
453 try:
454 encoded = spwd.getspnam(username)[1]
455 return encoded == crypt.crypt(clear, encoded)
456 except KeyError:
457 return False
Brad Bishop2f428582015-12-02 10:56:11 -0500458
Brad Bishop87b63c12016-03-18 14:47:51 -0400459 def invalidate_session(self, session):
460 try:
461 self.session_store.remove(session)
462 except ValueError:
463 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500464
Brad Bishop87b63c12016-03-18 14:47:51 -0400465 def new_session(self):
466 sid = os.urandom(32)
467 if self.MAX_SESSIONS <= len(self.session_store):
468 self.session_store.pop()
469 self.session_store.insert(0, {'sid': sid})
Brad Bishop2f428582015-12-02 10:56:11 -0500470
Brad Bishop87b63c12016-03-18 14:47:51 -0400471 return self.session_store[0]
Brad Bishop2f428582015-12-02 10:56:11 -0500472
Brad Bishop87b63c12016-03-18 14:47:51 -0400473 def get_session(self, sid):
474 sids = [x['sid'] for x in self.session_store]
475 try:
476 return self.session_store[sids.index(sid)]
477 except ValueError:
478 return None
Brad Bishop2f428582015-12-02 10:56:11 -0500479
Brad Bishop87b63c12016-03-18 14:47:51 -0400480 def get_session_from_cookie(self):
481 return self.get_session(
482 request.get_cookie(
483 'sid', secret=self.hmac_key))
Brad Bishop2f428582015-12-02 10:56:11 -0500484
Brad Bishop87b63c12016-03-18 14:47:51 -0400485 def do_post(self, **kw):
486 if request.path == '/login':
487 return self.do_login(**kw)
488 else:
489 return self.do_logout(**kw)
Brad Bishop2f428582015-12-02 10:56:11 -0500490
Brad Bishop87b63c12016-03-18 14:47:51 -0400491 def do_logout(self, **kw):
492 session = self.get_session_from_cookie()
493 if session is not None:
494 user = session['user']
495 self.invalidate_session(session)
496 response.delete_cookie('sid')
497 return self.login_str % (user, 'out')
Brad Bishop2f428582015-12-02 10:56:11 -0500498
Brad Bishop87b63c12016-03-18 14:47:51 -0400499 return self.no_user_str
Brad Bishop2f428582015-12-02 10:56:11 -0500500
Brad Bishop87b63c12016-03-18 14:47:51 -0400501 def do_login(self, **kw):
502 session = self.get_session_from_cookie()
503 if session is not None:
504 return self.login_str % (session['user'], 'in')
Brad Bishop2f428582015-12-02 10:56:11 -0500505
Brad Bishop87b63c12016-03-18 14:47:51 -0400506 if len(request.parameter_list) != 2:
507 abort(400, self.bad_json_str % (request.json))
Brad Bishop2f428582015-12-02 10:56:11 -0500508
Brad Bishop87b63c12016-03-18 14:47:51 -0400509 if not self.authenticate(*request.parameter_list):
Brad Bishopdc3fbfa2016-09-08 09:51:38 -0400510 abort(401, self.bad_passwd_str)
Brad Bishop2f428582015-12-02 10:56:11 -0500511
Brad Bishop87b63c12016-03-18 14:47:51 -0400512 user = request.parameter_list[0]
513 session = self.new_session()
514 session['user'] = user
515 response.set_cookie(
516 'sid', session['sid'], secret=self.hmac_key,
517 secure=True,
518 httponly=True)
519 return self.login_str % (user, 'in')
Brad Bishop2f428582015-12-02 10:56:11 -0500520
Brad Bishop87b63c12016-03-18 14:47:51 -0400521 def find(self, **kw):
522 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500523
Brad Bishop87b63c12016-03-18 14:47:51 -0400524 def setup(self, **kw):
525 pass
526
Brad Bishop2f428582015-12-02 10:56:11 -0500527
528class AuthorizationPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -0400529 ''' Invokes an optional list of authorization callbacks. '''
Brad Bishop2f428582015-12-02 10:56:11 -0500530
Brad Bishop87b63c12016-03-18 14:47:51 -0400531 name = 'authorization'
532 api = 2
Brad Bishop2f428582015-12-02 10:56:11 -0500533
Brad Bishop87b63c12016-03-18 14:47:51 -0400534 class Compose:
535 def __init__(self, validators, callback, session_mgr):
536 self.validators = validators
537 self.callback = callback
538 self.session_mgr = session_mgr
Brad Bishop2f428582015-12-02 10:56:11 -0500539
Brad Bishop87b63c12016-03-18 14:47:51 -0400540 def __call__(self, *a, **kw):
541 sid = request.get_cookie('sid', secret=self.session_mgr.hmac_key)
542 session = self.session_mgr.get_session(sid)
Brad Bishopd4c1c552017-02-21 00:07:28 -0500543 if request.method != 'OPTIONS':
544 for x in self.validators:
545 x(session, *a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -0500546
Brad Bishop87b63c12016-03-18 14:47:51 -0400547 return self.callback(*a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -0500548
Brad Bishop87b63c12016-03-18 14:47:51 -0400549 def apply(self, callback, route):
550 undecorated = route.get_undecorated_callback()
551 if not isinstance(undecorated, RouteHandler):
552 return callback
Brad Bishop2f428582015-12-02 10:56:11 -0500553
Brad Bishop87b63c12016-03-18 14:47:51 -0400554 auth_types = getattr(
555 undecorated, '_require_auth', None)
556 if not auth_types:
557 return callback
Brad Bishop2f428582015-12-02 10:56:11 -0500558
Brad Bishop87b63c12016-03-18 14:47:51 -0400559 return self.Compose(
560 auth_types, callback, undecorated.app.session_handler)
561
Brad Bishop2f428582015-12-02 10:56:11 -0500562
Brad Bishopd0c404a2017-02-21 09:23:25 -0500563class CorsPlugin(object):
564 ''' Add CORS headers. '''
565
566 name = 'cors'
567 api = 2
568
569 @staticmethod
570 def process_origin():
571 origin = request.headers.get('Origin')
572 if origin:
573 response.add_header('Access-Control-Allow-Origin', origin)
574 response.add_header(
575 'Access-Control-Allow-Credentials', 'true')
576
577 @staticmethod
578 def process_method_and_headers(verbs):
579 method = request.headers.get('Access-Control-Request-Method')
580 headers = request.headers.get('Access-Control-Request-Headers')
581 if headers:
582 headers = [x.lower() for x in headers.split(',')]
583
584 if method in verbs \
585 and headers == ['content-type']:
586 response.add_header('Access-Control-Allow-Methods', method)
587 response.add_header(
588 'Access-Control-Allow-Headers', 'Content-Type')
589
590 def __init__(self, app):
591 app.install_error_callback(self.error_callback)
592
593 def apply(self, callback, route):
594 undecorated = route.get_undecorated_callback()
595 if not isinstance(undecorated, RouteHandler):
596 return callback
597
598 if not getattr(undecorated, '_enable_cors', None):
599 return callback
600
601 def wrap(*a, **kw):
602 self.process_origin()
603 self.process_method_and_headers(undecorated._verbs)
604 return callback(*a, **kw)
605
606 return wrap
607
608 def error_callback(self, **kw):
609 self.process_origin()
610
611
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500612class JsonApiRequestPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -0400613 ''' Ensures request content satisfies the OpenBMC json api format. '''
614 name = 'json_api_request'
615 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500616
Brad Bishop87b63c12016-03-18 14:47:51 -0400617 error_str = "Expecting request format { 'data': <value> }, got '%s'"
618 type_error_str = "Unsupported Content-Type: '%s'"
619 json_type = "application/json"
620 request_methods = ['PUT', 'POST', 'PATCH']
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500621
Brad Bishop87b63c12016-03-18 14:47:51 -0400622 @staticmethod
623 def content_expected():
624 return request.method in JsonApiRequestPlugin.request_methods
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500625
Brad Bishop87b63c12016-03-18 14:47:51 -0400626 def validate_request(self):
627 if request.content_length > 0 and \
628 request.content_type != self.json_type:
629 abort(415, self.type_error_str % request.content_type)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500630
Brad Bishop87b63c12016-03-18 14:47:51 -0400631 try:
632 request.parameter_list = request.json.get('data')
633 except ValueError, e:
634 abort(400, str(e))
635 except (AttributeError, KeyError, TypeError):
636 abort(400, self.error_str % request.json)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500637
Brad Bishop87b63c12016-03-18 14:47:51 -0400638 def apply(self, callback, route):
639 verbs = getattr(
640 route.get_undecorated_callback(), '_verbs', None)
641 if verbs is None:
642 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500643
Brad Bishop87b63c12016-03-18 14:47:51 -0400644 if not set(self.request_methods).intersection(verbs):
645 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500646
Brad Bishop87b63c12016-03-18 14:47:51 -0400647 def wrap(*a, **kw):
648 if self.content_expected():
649 self.validate_request()
650 return callback(*a, **kw)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500651
Brad Bishop87b63c12016-03-18 14:47:51 -0400652 return wrap
653
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500654
655class JsonApiRequestTypePlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -0400656 ''' Ensures request content type satisfies the OpenBMC json api format. '''
657 name = 'json_api_method_request'
658 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500659
Brad Bishop87b63c12016-03-18 14:47:51 -0400660 error_str = "Expecting request format { 'data': %s }, got '%s'"
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500661
Brad Bishop87b63c12016-03-18 14:47:51 -0400662 def apply(self, callback, route):
663 request_type = getattr(
664 route.get_undecorated_callback(), 'request_type', None)
665 if request_type is None:
666 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500667
Brad Bishop87b63c12016-03-18 14:47:51 -0400668 def validate_request():
669 if not isinstance(request.parameter_list, request_type):
670 abort(400, self.error_str % (str(request_type), request.json))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500671
Brad Bishop87b63c12016-03-18 14:47:51 -0400672 def wrap(*a, **kw):
673 if JsonApiRequestPlugin.content_expected():
674 validate_request()
675 return callback(*a, **kw)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500676
Brad Bishop87b63c12016-03-18 14:47:51 -0400677 return wrap
678
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500679
Brad Bishop080a48e2017-02-21 22:34:43 -0500680class JsonErrorsPlugin(JSONPlugin):
681 ''' Extend the Bottle JSONPlugin such that it also encodes error
682 responses. '''
683
684 def __init__(self, app, **kw):
685 super(JsonErrorsPlugin, self).__init__(**kw)
686 self.json_opts = {
687 x: y for x, y in kw.iteritems()
688 if x in ['indent', 'sort_keys']}
689 app.install_error_callback(self.error_callback)
690
691 def error_callback(self, response_object, response_body, **kw):
692 response_body['body'] = json.dumps(response_object, **self.json_opts)
693 response.content_type = 'application/json'
694
695
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500696class JsonApiResponsePlugin(object):
Brad Bishop080a48e2017-02-21 22:34:43 -0500697 ''' Emits responses in the OpenBMC json api format. '''
Brad Bishop87b63c12016-03-18 14:47:51 -0400698 name = 'json_api_response'
699 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500700
Brad Bishopd4c1c552017-02-21 00:07:28 -0500701 @staticmethod
702 def has_body():
703 return request.method not in ['OPTIONS']
704
Brad Bishop080a48e2017-02-21 22:34:43 -0500705 def __init__(self, app):
706 app.install_error_callback(self.error_callback)
707
Brad Bishop87b63c12016-03-18 14:47:51 -0400708 def apply(self, callback, route):
709 def wrap(*a, **kw):
Brad Bishopd4c1c552017-02-21 00:07:28 -0500710 data = callback(*a, **kw)
711 if self.has_body():
712 resp = {'data': data}
713 resp['status'] = 'ok'
714 resp['message'] = response.status_line
715 return resp
Brad Bishop87b63c12016-03-18 14:47:51 -0400716 return wrap
717
Brad Bishop080a48e2017-02-21 22:34:43 -0500718 def error_callback(self, error, response_object, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -0400719 response_object['message'] = error.status_line
Brad Bishop080a48e2017-02-21 22:34:43 -0500720 response_object.setdefault('data', {})['description'] = str(error.body)
Brad Bishop87b63c12016-03-18 14:47:51 -0400721 if error.status_code == 500:
722 response_object['data']['exception'] = repr(error.exception)
723 response_object['data']['traceback'] = error.traceback.splitlines()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500724
Brad Bishop87b63c12016-03-18 14:47:51 -0400725
Brad Bishop080a48e2017-02-21 22:34:43 -0500726class JsonpPlugin(object):
Brad Bishop80fe37a2016-03-29 10:54:54 -0400727 ''' Json javascript wrapper. '''
728 name = 'jsonp'
729 api = 2
730
Brad Bishop080a48e2017-02-21 22:34:43 -0500731 def __init__(self, app, **kw):
732 app.install_error_callback(self.error_callback)
Brad Bishop80fe37a2016-03-29 10:54:54 -0400733
734 @staticmethod
735 def to_jsonp(json):
736 jwrapper = request.query.callback or None
737 if(jwrapper):
738 response.set_header('Content-Type', 'application/javascript')
739 json = jwrapper + '(' + json + ');'
740 return json
741
742 def apply(self, callback, route):
743 def wrap(*a, **kw):
744 return self.to_jsonp(callback(*a, **kw))
745 return wrap
746
Brad Bishop080a48e2017-02-21 22:34:43 -0500747 def error_callback(self, response_body, **kw):
748 response_body['body'] = self.to_jsonp(response_body['body'])
Brad Bishop80fe37a2016-03-29 10:54:54 -0400749
750
Brad Bishop2c6fc762016-08-29 15:53:25 -0400751class App(Bottle):
Brad Bishop2ddfa002016-08-29 15:11:55 -0400752 def __init__(self):
Brad Bishop2c6fc762016-08-29 15:53:25 -0400753 super(App, self).__init__(autojson=False)
Brad Bishop2ddfa002016-08-29 15:11:55 -0400754 self.bus = dbus.SystemBus()
755 self.mapper = obmc.mapper.Mapper(self.bus)
Brad Bishop080a48e2017-02-21 22:34:43 -0500756 self.error_callbacks = []
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500757
Brad Bishop87b63c12016-03-18 14:47:51 -0400758 self.install_hooks()
759 self.install_plugins()
760 self.create_handlers()
761 self.install_handlers()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500762
Brad Bishop87b63c12016-03-18 14:47:51 -0400763 def install_plugins(self):
764 # install json api plugins
765 json_kw = {'indent': 2, 'sort_keys': True}
Brad Bishop87b63c12016-03-18 14:47:51 -0400766 self.install(AuthorizationPlugin())
Brad Bishopd0c404a2017-02-21 09:23:25 -0500767 self.install(CorsPlugin(self))
Brad Bishop080a48e2017-02-21 22:34:43 -0500768 self.install(JsonpPlugin(self, **json_kw))
769 self.install(JsonErrorsPlugin(self, **json_kw))
770 self.install(JsonApiResponsePlugin(self))
Brad Bishop87b63c12016-03-18 14:47:51 -0400771 self.install(JsonApiRequestPlugin())
772 self.install(JsonApiRequestTypePlugin())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500773
Brad Bishop87b63c12016-03-18 14:47:51 -0400774 def install_hooks(self):
Brad Bishop080a48e2017-02-21 22:34:43 -0500775 self.error_handler_type = type(self.default_error_handler)
776 self.original_error_handler = self.default_error_handler
777 self.default_error_handler = self.error_handler_type(
778 self.custom_error_handler, self, Bottle)
779
Brad Bishop87b63c12016-03-18 14:47:51 -0400780 self.real_router_match = self.router.match
781 self.router.match = self.custom_router_match
782 self.add_hook('before_request', self.strip_extra_slashes)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500783
Brad Bishop87b63c12016-03-18 14:47:51 -0400784 def create_handlers(self):
785 # create route handlers
786 self.session_handler = SessionHandler(self, self.bus)
787 self.directory_handler = DirectoryHandler(self, self.bus)
788 self.list_names_handler = ListNamesHandler(self, self.bus)
789 self.list_handler = ListHandler(self, self.bus)
790 self.method_handler = MethodHandler(self, self.bus)
791 self.property_handler = PropertyHandler(self, self.bus)
792 self.schema_handler = SchemaHandler(self, self.bus)
793 self.instance_handler = InstanceHandler(self, self.bus)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500794
Brad Bishop87b63c12016-03-18 14:47:51 -0400795 def install_handlers(self):
796 self.session_handler.install()
797 self.directory_handler.install()
798 self.list_names_handler.install()
799 self.list_handler.install()
800 self.method_handler.install()
801 self.property_handler.install()
802 self.schema_handler.install()
803 # this has to come last, since it matches everything
804 self.instance_handler.install()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500805
Brad Bishop080a48e2017-02-21 22:34:43 -0500806 def install_error_callback(self, callback):
807 self.error_callbacks.insert(0, callback)
808
Brad Bishop87b63c12016-03-18 14:47:51 -0400809 def custom_router_match(self, environ):
810 ''' The built-in Bottle algorithm for figuring out if a 404 or 405 is
811 needed doesn't work for us since the instance rules match
812 everything. This monkey-patch lets the route handler figure
813 out which response is needed. This could be accomplished
814 with a hook but that would require calling the router match
815 function twice.
816 '''
817 route, args = self.real_router_match(environ)
818 if isinstance(route.callback, RouteHandler):
819 route.callback._setup(**args)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500820
Brad Bishop87b63c12016-03-18 14:47:51 -0400821 return route, args
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500822
Brad Bishop080a48e2017-02-21 22:34:43 -0500823 def custom_error_handler(self, res, error):
824 ''' Allow plugins to modify error reponses too via this custom
825 error handler. '''
826
827 response_object = {}
828 response_body = {}
829 for x in self.error_callbacks:
830 x(error=error,
831 response_object=response_object,
832 response_body=response_body)
833
834 return response_body.get('body', "")
835
Brad Bishop87b63c12016-03-18 14:47:51 -0400836 @staticmethod
837 def strip_extra_slashes():
838 path = request.environ['PATH_INFO']
839 trailing = ("", "/")[path[-1] == '/']
840 parts = filter(bool, path.split('/'))
841 request.environ['PATH_INFO'] = '/' + '/'.join(parts) + trailing