client_views.py 6.55 KB
Newer Older
1
2

import logging
3
import re
4
5
from django.http import HttpResponse
from django.contrib.auth import authenticate
6
from django.contrib.sessions.models import Session
7
from ...models import User, RabbitMQInstance
8
9

LOGGER = logging.getLogger(__name__)
10
CLIENT_DEBUGGING = False
11

12
13
14
ALLOW = HttpResponse('allow')
DENY = HttpResponse('deny')

15

16
def _valid_vhost(request):
17
    if request.POST.get('vhost') == RabbitMQInstance.load().vhost:
18
19
20
21
        return True
    LOGGER.error('illegal vhost requested')
    return False

22
def _valid_permission(request):
23
24
    perm = request.POST.get('permission')
    if  perm != 'write':
25
        return True
26
    LOGGER.error('illegal permission requested %s', perm)
27
28
    return False

29
def _valid_user(request):
30
31
32
33
34
35
36
37
38
    return _apiclient_valid(request) or _webpage_client_userid(request)

def _apiclient_valid(request):
    valid = User.objects.filter(
        user_type='apiclient',
        username=request.POST.get('username'),
    ).exists()
    if valid:
        return True
39
40
    return False

41
42
43
44
45
46
47
48
def _apiclient_get(request):
    user = User.objects.filter(
        user_type='apiclient',
    ).get(
        username=request.POST.get('username'),
    )
    if user:
        return user
49
    LOGGER.error('unable to get user for request')
50
51
    return None

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def _webpage_client_userid(request):
    username = request.POST.get('username')
    if username.startswith('webpage-client:'):
        components = username.split(':', maxsplit=1)
        if len(components) == 2:
            return components[1]
    return ''

def _webpage_client_session(request):
    query = Session.objects.filter(
        session_key=request.POST.get('password'),
    )
    if query.exists() and len(query) == 1:
        return query.first()
    return None
67

68
69
70
def _webpage_client_valid(request):
    userid = _webpage_client_userid(request)
    session = _webpage_client_session(request)
71

72
73
74
75
76
    if (
            _webpage_client_userid(request) != ''
            and session.get_decoded().get('_auth_user_id') == userid
    ):
        return True
77

78
79
    LOGGER.error('Failed to authenticate webpage client for RabbitMQ')
    return False
80

81
82
# VIEWS: authentication and authorization for
# apiclients and webpage-clients
83

84
85
86
87
def user_endpoint(request):
    if _webpage_client_valid(request):
        LOGGER.info('Authenticated webpage client')
        return ALLOW
88

89
90
91
92
93
94
95
    user = authenticate(
        username=request.POST.get('username'),
        password=request.POST.get('password'),
    )
    if user:
        LOGGER.info('Authenticated client as %s', user)
        return ALLOW
96
97


98
99
    LOGGER.error('Failed to authenticate user for RabbitMQ')
    return DENY
100

101
def vhost_endpoint(request):
102
    # check if on the correct virtual host
103
104
    if _valid_vhost(request) and _valid_user(request):
        return ALLOW
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
    LOGGER.error('Authorization check for vhost failed for %s', request.POST)
    return DENY

def _resource_authorized_webpage_client(request):
    resource = request.POST.get('resource')
    name = request.POST.get('name', '')
    permission = request.POST.get('permission', [])
    return (
        resource == 'exchange'
        and name == 'update'
        and not 'write' in permission
    ) or (
        resource == 'queue'
        and name.startswith('stomp-subscription-')
    ) or (
        resource == 'topic'
        and name == _webpage_client_userid(request)
    )

def _resource_authorized_apiclient(request):
    resource = request.POST.get('resource')
    name = request.POST.get('name', '')
    permission = request.POST.get('permission', [])
    return (
        resource == 'queue'
        and name.startswith('amq.gen-')
    ) or (
        resource == 'exchange'
Lukas Burgey's avatar
Lukas Burgey committed
134
135
        # TODO
        #and name in RabbitMQInstance.load().exchanges
136
137
138
139
140
141
142
143
144
145
146
147
148
        and not 'write' in permission
    )

def resource_endpoint(request):
    resource = request.POST.get('resource')
    name = request.POST.get('name', '')
    permission = request.POST.get('permission', [])

    if _valid_vhost(request):
        if (
                _webpage_client_userid(request)
                and _resource_authorized_webpage_client(request)
        ):
149
150
151
152
153
154
155
            if CLIENT_DEBUGGING:
                LOGGER.debug(
                    'Granted %s access to resource %s %s to client',
                    permission,
                    resource,
                    name,
                )
156
157
158
159
160
161
            return ALLOW

        if (
                _apiclient_valid(request)
                and _resource_authorized_apiclient(request)
        ):
162
163
164
165
166
167
168
            if CLIENT_DEBUGGING:
                LOGGER.debug(
                    'Granted %s access to resource %s %s to client',
                    permission,
                    resource,
                    name,
                )
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
            return ALLOW

    LOGGER.error(
        'Authorization check of resource %s %s for client failed',
        resource,
        name,
    )
    return DENY


def topic_endpoint(request):
    permission = request.POST.get('permission', [])
    resource = request.POST.get('resource', '')
    name = request.POST.get('name', '')
    routing_key = request.POST.get('routing_key', '')

    if not _valid_vhost(request) or not _valid_permission(request):
        return DENY

    webpage_client_userid = _webpage_client_userid(request)
    if webpage_client_userid:
        if (
                routing_key == webpage_client_userid
                and not 'write' in permission
        ):
194
195
196
197
198
199
200
            if CLIENT_DEBUGGING:
                LOGGER.debug(
                    'Granted %s access to %s %s to client',
                    permission,
                    resource,
                    routing_key,
                )
201
202
203
204
205
206
207
208
209
210
211
212
            return ALLOW

        LOGGER.error(
            'Authorization check of resource %s %s for client failed',
            resource,
            name,
        )
        return DENY

    user = _apiclient_get(request)
    if user:
        routing_key = request.POST.get('routing_key', '')
Lukas Burgey's avatar
Lukas Burgey committed
213
214
215
216
217
218
219
220
221
222
223
224
225
226
        if name == 'deployments':
            if routing_key.startswith('service.'):
                match = re.search('service.(.+)', routing_key)
                if match:
                    service_name = match.group(1)
                    for service in user.site.services.all():
                        if service_name == service.name:
                            return ALLOW
        elif name == 'sites':
            LOGGER.debug(routing_key)
            if routing_key == user.site.name:
                return ALLOW
            else:
                LOGGER.error("Client of site %s tried to access site %s", user.site, routing_key)
227

228
    LOGGER.error('Authorization check for topic failed for %s', request.POST)
229
    return DENY