summaryrefslogtreecommitdiff
path: root/apifw/bottleapp.py
blob: ab92f3c92a95e839ba39b196817fb0099ffb5bcb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# Copyright (C) 2017  Lars Wirzenius
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import json
import logging
import re
import time


import bottle
import Crypto.PublicKey.RSA
import jwt


import apifw


class BottleLoggingPlugin(apifw.HttpTransaction):

    # This a binding between Bottle and apifw.HttpTransaction, as a
    # Bottle plugin. We arrange the perform_transaction method to be
    # called with the right arguments, in particular the callback
    # function to call. We also provide Bottle specific methods to log
    # the HTTP request and response, and to amend the response by
    # adding a Date header.

    def apply(self, callback, route):

        def wrapper(*args, **kwargs):
            try:
                return self.perform_transaction(callback, *args, **kwargs)
            except bottle.HTTPError as e:
                self._log_error(e)
                raise e
            except BaseException as e:
                self._log_error(e)
                raise bottle.HTTPError(500, body=str(e))

        return wrapper

    def amend_response(self):
        rfc822 = time.strftime('%a, %d %b %Y %H:%M:%S %z')
        bottle.response.set_header('Date', rfc822)

    def construct_request_log(self):
        r = bottle.request
        return {
            'method': r.method,
            'path': r.path,
        }

    def construct_response_log(self):
        r = bottle.response
        return {
            'status': r.status_code,
            'text': r.body,
        }


class BottleAuthorizationPlugin:

    route_pat = re.compile(r'<[^>]*>')

    def __init__(self):
        self.pubkey = None
        self.iss = None
        self.aud = None
        self._authz_routes = set()

    def set_token_signing_public_key(self, pubkey):
        self.pubkey = Crypto.PublicKey.RSA.importKey(pubkey)

    def set_expected_issuer(self, iss):
        self.iss = iss

    def set_expected_audience(self, aud):
        self.aud = aud

    def set_route_authorization(self, route):
        key = self.route_key(route)
        if route.get('needs-authorization', True):
            self._authz_routes.add(key)
            logging.info('Route %r does DOES need authorization', key)
        else:
            logging.info('Route %r does NOT need authorization', key)

    def route_key(self, route):
        # route can be a dict (from find_missing_route), or a
        # bottle.Route object.
        method = route.get('method', 'GET')
        path = route.get('path')
        if not path:
            rule = route.get('rule')
            path = re.sub(r'/<[^>]+>', '', rule)
        return (method, path)

    def apply(self, callback, route):
        def wrapper(*args, **kwargs):

            if self.needs_authorization(route):
                self.assert_authorized(route)
            return callback(*args, **kwargs)

        return wrapper

    def needs_authorization(self, route):
        key = self.route_key(route)
        logging.debug('route: %r', route)
        logging.debug('route_key: %r', key)
        logging.debug('authz_routes: %r', self._authz_routes)
        return key in self._authz_routes

    def assert_authorized(self, route):
        value = self.get_authorization_header(bottle.request)
        token = self.parse_authorization_header(value)
        claims = self.parse_token(token)
        self.check_issuer(claims)
        if not self.scope_allows_route(claims['scope'], route):
            self.raise_forbidden(
                'insufficient_scope', 'scope does not allow route')

    def get_authorization_header(self, request):
        value = request.get_header('Authorization', '')
        if not value:
            self.raise_unauthorized(
                'no_authorization', 'No Authorization header')
        logging.debug('Request has Authorization header: %r', value)
        return value

    def parse_authorization_header(self, value):
        words = value.split()
        if len(words) != 2 or words[0].lower() != 'bearer':
            self.raise_unauthorized(
                'bad_authorization', 'Authorization should be "Bearer TOKEN"')
        logging.debug(
            'Request Authorization header looks like a bearer token: good')
        return words[1]

    def parse_token(self, token):
        try:
            token = apifw.decode_token(token, self.pubkey, audience=self.aud)
            logging.debug('Request Authorization token can be decoded: good')
            logging.debug('Token: %r', token)
            return token
        except jwt.InvalidTokenError as e:
            self.raise_unauthorized('invalid_token', str(e))

    def check_issuer(self, claims):
        if claims['iss'] != self.iss:
            self.raise_unauthorized(
                'bad_issuer',
                'Expected issuer %s, got %s' % (self.iss, claims['iss']))
        logging.debug('Token issuer is correct: good')

    def scope_allows_route(self, claim_scopes, route):
        scopes = claim_scopes.split(' ')
        route_scope = self.get_scope_for_route(route['method'], route['rule'])
        if route_scope in scopes:
            logging.debug(
                'Route scope %s is in scopes %r', route_scope, scopes)
            return True
        logging.error(
            'Route scope %s is NOT in scopes %r', route_scope, scopes)
        return False

    def get_scope_for_route(self, method, rule):
        scope = re.sub(self.route_pat, 'id', rule)
        scope = scope.replace('/', '_')
        scope = 'uapi%s_%s' % (scope, method)
        return scope.lower()

    def raise_unauthorized(self, error, explanation):
        headers = {
            'WWW-Authenticate': 'Bearer error="{}"'.format(error),
        }
        raise bottle.HTTPError(
            apifw.HTTP_UNAUTHORIZED, body=explanation, headers=headers)

    def raise_forbidden(self, error, explanation):
        headers = {
            'WWW-Authenticate': 'Bearer error="{}"'.format(error),
        }
        raise bottle.HTTPError(
            apifw.HTTP_FORBIDDEN, body=explanation, headers=headers)


class BottleApplication:

    # Provide the interface to bottle.Bottle that we need.
    # Specifically, we set up a hook to call the
    # Api.find_missing_route method when a request would otherwise
    # return 404, and we add the routes it returns to Bottle so that
    # they are there for this and future requests.

    def __init__(self, bottleapp, api):
        self._bottleapp = bottleapp
        self._bottleapp.add_hook('before_request', self._add_missing_route)
        self._api = api
        self._authz = None

    def add_plugin(self, plugin):
        self._bottleapp.install(plugin)

    def set_authorization_plugin(self, plugin):
        self._authz = plugin

    def _add_missing_route(self):
        try:
            self._bottleapp.match(bottle.request.environ)
        except bottle.HTTPError:
            routes = self._api.find_missing_route(bottle.request.path)
            if routes:
                for route in routes:
                    callback = self._callback_with_body(route['callback'])
                    route_dict = {
                        'method': route.get('method', 'GET'),
                        'path': route['path'],
                        'callback': callback,
                    }
                    self._bottleapp.route(**route_dict)
                    self._authz.set_route_authorization(route)
            else:
                raise

    def add_routes_for_resource_type(self, rt):
        routes = self._api.find_missing_route(rt.get_path())
        for route in routes:
            callback = self._callback_with_body(route['callback'])
            route_dict = {
                'method': route.get('method', 'GET'),
                'path': route['path'],
                'callback': callback,
            }
            self._bottleapp.route(**route_dict)
            self._authz.set_route_authorization(route)

    def _callback_with_body(self, callback):
        def wrapper(*args, **kwargs):
            kwargs['raw_uri_path'] = bottle.request.environ.get('RAW_URI', '')
            content_type, body = self._get_request_body()
            response = callback(content_type, body, *args, **kwargs)
            return bottle.HTTPResponse(
                status=response['status'], body=response['body'],
                headers=response['headers'])
        return wrapper

    def _get_request_body(self):
        raw_body = bottle.request.body.read()
        if bottle.request.method in ('POST', 'PUT'):
            if len(raw_body) == 0:
                raise bottle.HTTPError(
                    apifw.HTTP_LENGTH_REQUIRED,
                    body='Empty body not allowed for PUT/POST')

        json_type = 'application/json'
        content_type = bottle.request.get_header('Content-Type')
        if content_type != json_type:
            return content_type, raw_body

        try:
            text_body = raw_body.decode('UTF-8')
            parsed = json.loads(text_body)
            return content_type, parsed
        except json.decoder.JSONDecodeError as e:
            raise bottle.HTTPError(status=apifw.HTTP_BAD_REQUEST, body=str(e))


def create_bottle_application(
        api, counter, logger, config, resource_types=None):
    # Create a new bottle.Bottle application, set it up, and return it
    # so that gunicorn can execute it from the main program.

    bottleapp = bottle.Bottle()
    app = BottleApplication(bottleapp, api)

    plugin = BottleLoggingPlugin()
    plugin.set_transaction_counter(counter)
    if logger:
        plugin.set_dict_logger(logger)
    app.add_plugin(plugin)

    authz = BottleAuthorizationPlugin()
    authz.set_token_signing_public_key(config['token-public-key'])
    authz.set_expected_issuer(config['token-issuer'])
    authz.set_expected_audience(config['token-audience'])
    app.add_plugin(authz)
    app.set_authorization_plugin(authz)

    for rt in resource_types or []:
        app.add_routes_for_resource_type(rt)

    return bottleapp