summaryrefslogtreecommitdiff
path: root/yarns/lib.py
blob: 3293a5d27ae9349f4574cba4335943c55f2e40cc (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
# Copyright (C) 2018  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 os
import re
import signal
import subprocess
import time

import Crypto.PublicKey.RSA
import jwt
import requests

from yarnutils import *


srcdir = os.environ['SRCDIR']
datadir = os.environ['DATADIR']
V = Variables(datadir)


json_mime_type = 'application/json'


def start_muck():
    pathname = os.path.join(srcdir, 'muck_poc')
    pubkey = os.path.join(srcdir, 'test-key.pub')

    config = {
        'pid': 'muck.pid',
        'port': 9999,
        'log': 'muck.log',
        'store': datadir,
        'signing-key-filename': pubkey,
    }

    config_filename = os.path.join(datadir, 'mock.conf')
    with open(config_filename, 'w') as f:
        json.dump(config, f)

    out = os.path.join(datadir, 'muck.out')
    err = os.path.join(datadir, 'muck.err')
    argv = [
        '/usr/sbin/daemonize', '-o', out, '-e', err, '-c', '.',
        pathname, config_filename,
    ]
    subprocess.check_call(argv)
    time.sleep(2)
    V['base_url'] = 'http://127.0.0.1:{}'.format(config['port'])


def stop_muck():
    pid = int(read('muck.pid'))
    os.kill(pid, signal.SIGTERM)


def create_test_token(sub):
    key_filename = os.path.join(srcdir, 'test-key')
    key_text = open(key_filename).read()

    iss = 'test-issuer'
    aud = 'test-audience'
    scopes = ['create', 'update', 'show', 'delete']
    if sub in (V['superusers'] or []):
        scopes.append('super')
    lifetime = 3600

    return create_token(key_text, iss, aud, sub, scopes, lifetime)

def create_token(key_text, iss, aud, sub, scopes, lifetime):
    key = Crypto.PublicKey.RSA.importKey(key_text)

    now = int(time.time())
    claims = {
        'iss': iss,
        'sub': sub,
        'aud': aud,
        'exp': now + lifetime,
        'scope': ' '.join(scopes),
    }

    token = jwt.encode(claims, key.exportKey('PEM'), algorithm='RS512')
    return token.decode('ascii')


def POST(sub, path, headers, body):
    return request(sub, requests.post, path, headers, body)


def PUT(sub, path, headers, body):
    return request(sub, requests.put, path, headers, body)


def GET(sub, path, headers, body=None):
    return request(sub, requests.get, path, headers, body=body)


def DELETE(sub, path, headers):
    return request(sub, requests.delete, path, headers)


def request(sub, func, path, headers, body=None):
    url = '{}{}'.format(V['base_url'], path)
    if 'Content-Type' not in headers:
        headers['Content-Type'] = json_mime_type
    if 'Authorization' not in headers:
        token = create_test_token(sub)
        headers['Authorization'] = 'Bearer {}'.format(token)
    if body is not None:
        body = json.dumps(body)
    V['request_url'] = url
    V['request_func'] = repr(func)
    V['request_headers'] = repr(headers)
    V['request_body'] = repr(body)
    r = func(url, headers=headers, data=body)
    V['status_code'] = r.status_code
    V['response_body'] = r.text
    V['response_headers'] = dict(r.headers)
    return r


def read(filename):
    with open(filename, 'r') as f:
        return f.read()


def get_expanded_match():
    match = get_next_match()
    return expand(match, V)


def expand(text, variables):
    result = ''
    while text:
        m = re.search(r'\${(?P<name>[^}]+)}', text)
        if not m:
            result += text
            break
        name = m.group('name')
        print('expanding ', name, repr(variables[name]))
        result += text[:m.start()] + variables[name]
        text = text[m.end():]
    return result


def get_json_body():
    return json.loads(V['response_body'])


def get_header(header_name):
    headers = V['response_headers']
    assert headers is not None
    return headers.get(header_name, '')


def save_header(header_name, var_name):
    V[var_name] = get_header(header_name)