summaryrefslogtreecommitdiff
path: root/api.py
blob: 0eb850fdafcb2b200149d2dad4dbe1e44b5f621e (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
import logging
import sys

import Crypto.PublicKey.RSA
import bottle
import jwt


class TokenParser:

    def __init__(self, pubkey):
        self._pubkey = pubkey

    def parse_token(self, token_text):
        return jwt.decode(
            token_text,
            key=self._pubkey.exportKey('OpenSSH'),
            audience=None,
            options={'verify_aud': False})


class AccessChecker:

    def __init__(self, pubkey):
        self._parser = TokenParser(pubkey)

    def access_is_allowed(self, headers, required_scopes):
        token = self._get_token(headers)
        logging.debug('Access token %r', token)
        if token is None and len(required_scopes) != 0:
            logging.error('No valid access token')
            return False

        scopes = token.get('scope', '').split()
        missing = set(required_scopes).difference(scopes)
        if missing:
            logging.error(
                'Required scopes that are missing from token: %r', missing)
            return False

        return True

    def _get_token(self, headers):
        token_text = self._get_token_text(headers)
        if token_text is None:
            return None
        return self._parser.parse_token(token_text)

    def _get_token_text(self, headers):
        v = headers.get('Authorization', '')
        words = v.split()
        if len(words) == 2:
            keyword, token_text = words
            if keyword.lower() == 'bearer':
                return token_text


class API:

    def __init__(self, app, token_pubkey):
        self._checker = AccessChecker(token_pubkey)
        self._add_routes(app, self.get_routes())

    def get_routes(self):
        raise NotImplementedError()

    def _add_routes(self, app, routes):
        for route in routes:
            func = route.pop('func')
            scopes = route.pop('scopes')
            callback = lambda **kwargs: self.check(func, scopes, kwargs)
            route = dict(route)
            route['callback'] = callback
            app.route(**route)

    def check(self, func, required_scopes, kwargs):
        r = bottle.request
        logging.debug('Checking access for request %s %s', r.method, r.path)

        if self._checker.access_is_allowed(bottle.request.headers, required_scopes):
            logging.info('Serving request %s %s', r.method, r.path)
            ret = func(**kwargs)
            logging.info('Result: %r', ret)
            return ret

        logging.error('Request denied %s %s', r.method, r.path)
        return bottle.HTTPError(400)
        

class Controller(API):

    def get_routes(self):
        return [
            {
                'method': 'GET',
                'path': '/status',
                'func': self._status,
                'scopes': ['status'],
            },
            {
                'method': 'GET',
                'path': '/hello/<name>',
                'func': self._hello,
                'scopes': [],
            },
        ]

    def _status(self):
        return {
            'queue': [],
            'running': [],
            'finished': [],
        }

    def _hello(self, name=None):
        return 'hello {}\n'.format(name)


def get_key_from_file(filename):
    with open(filename) as f:
        key_text = f.read()
    return Crypto.PublicKey.RSA.importKey(key_text)

        
def main():
    logging.basicConfig(
        filename='api.log',
        level=logging.DEBUG,
        format='%(levelname)s %(message)s')

    filename = sys.argv[1]
    key = get_key_from_file(filename)

    app = bottle.Bottle()
    api = Controller(app, key)
    app.run(host='localhost', port=2222)

main()