summaryrefslogtreecommitdiff
path: root/pycadf/tests/middleware/test_audit.py
blob: b9770bedee315547d5f9e1966ed6b3e4b15596e8 (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
#    Copyright (c) 2014 OpenStack Foundation
#    All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import mock
import webob

from pycadf.audit import api as cadf_api
from pycadf.middleware import audit
from pycadf.tests import base


class FakeApp(object):
    def __call__(self, env, start_response):
        body = 'Some response'
        start_response('200 OK', [
            ('Content-Type', 'text/plain'),
            ('Content-Length', str(sum(map(len, body))))
        ])
        return [body]


class FakeFailingApp(object):
    def __call__(self, env, start_response):
        raise Exception("It happens!")


@mock.patch('oslo.messaging.get_transport', mock.MagicMock())
class AuditMiddlewareTest(base.TestCase):
    ENV_HEADERS = {'HTTP_X_SERVICE_CATALOG':
                   '''[{"endpoints_links": [],
                        "endpoints": [{"adminURL":
                                       "http://host:8774/v2/admin",
                                       "region": "RegionOne",
                                       "publicURL":
                                       "http://host:8774/v2/public",
                                       "internalURL":
                                       "http://host:8774/v2/internal",
                                       "id": "resource_id"}],
                        "type": "compute",
                        "name": "nova"},]''',
                   'HTTP_X_USER_ID': 'user_id',
                   'HTTP_X_USER_NAME': 'user_name',
                   'HTTP_X_AUTH_TOKEN': 'token',
                   'HTTP_X_PROJECT_ID': 'tenant_id',
                   'HTTP_X_IDENTITY_STATUS': 'Confirmed'}

    def setUp(self):
        super(AuditMiddlewareTest, self).setUp()
        self.map_file = 'etc/pycadf/nova_api_audit_map.conf'

    def test_api_request(self):
        middleware = audit.AuditMiddleware(
            FakeApp(),
            audit_map_file='etc/pycadf/nova_api_audit_map.conf',
            service_name='pycadf')
        self.ENV_HEADERS['REQUEST_METHOD'] = 'GET'
        req = webob.Request.blank('/foo/bar',
                                  environ=self.ENV_HEADERS)
        with mock.patch('oslo.messaging.Notifier.info') as notify:
            middleware(req)
            # Check first notification with only 'request'
            call_args = notify.call_args_list[0][0]
            self.assertEqual(call_args[1], 'http.request')
            self.assertEqual(set(call_args[2].keys()),
                             set(['request']))

            request = call_args[2]['request']
            self.assertEqual(request['PATH_INFO'], '/foo/bar')
            self.assertEqual(request['REQUEST_METHOD'], 'GET')
            self.assertIn('CADF_EVENT', request)
            self.assertEqual(request['CADF_EVENT']['outcome'], 'pending')

            # Check second notification with request + response
            call_args = notify.call_args_list[1][0]
            self.assertEqual(call_args[1], 'http.response')
            self.assertEqual(set(call_args[2].keys()),
                             set(['request', 'response']))

            request = call_args[2]['request']
            self.assertEqual(request['PATH_INFO'], '/foo/bar')
            self.assertEqual(request['REQUEST_METHOD'], 'GET')
            self.assertIn('CADF_EVENT', request)
            self.assertEqual(request['CADF_EVENT']['outcome'], 'success')

    def test_api_request_failure(self):
        middleware = audit.AuditMiddleware(
            FakeFailingApp(),
            audit_map_file='etc/pycadf/nova_api_audit_map.conf',
            service_name='pycadf')
        self.ENV_HEADERS['REQUEST_METHOD'] = 'GET'
        req = webob.Request.blank('/foo/bar',
                                  environ=self.ENV_HEADERS)
        with mock.patch('oslo.messaging.Notifier.info') as notify:
            try:
                middleware(req)
                self.fail("Application exception has not been re-raised")
            except Exception:
                pass
            # Check first notification with only 'request'
            call_args = notify.call_args_list[0][0]
            self.assertEqual(call_args[1], 'http.request')
            self.assertEqual(set(call_args[2].keys()),
                             set(['request']))

            request = call_args[2]['request']
            self.assertEqual(request['PATH_INFO'], '/foo/bar')
            self.assertEqual(request['REQUEST_METHOD'], 'GET')
            self.assertIn('CADF_EVENT', request)
            self.assertEqual(request['CADF_EVENT']['outcome'], 'pending')

            # Check second notification with request + response
            call_args = notify.call_args_list[1][0]
            self.assertEqual(call_args[1], 'http.response')
            self.assertEqual(set(call_args[2].keys()),
                             set(['request', 'exception']))

            request = call_args[2]['request']
            self.assertEqual(request['PATH_INFO'], '/foo/bar')
            self.assertEqual(request['REQUEST_METHOD'], 'GET')
            self.assertIn('CADF_EVENT', request)
            self.assertEqual(request['CADF_EVENT']['outcome'], 'unknown')

    def test_process_request_fail(self):
        def func_error(self, req):
            raise Exception('error')
        self.stubs.Set(cadf_api.OpenStackAuditApi, 'append_audit_event',
                       func_error)
        middleware = audit.AuditMiddleware(
            FakeApp(),
            audit_map_file='etc/pycadf/nova_api_audit_map.conf',
            service_name='pycadf')
        req = webob.Request.blank('/foo/bar',
                                  environ={'REQUEST_METHOD': 'GET'})
        middleware.process_request(req)

    def test_process_response_fail(self):
        def func_error(self, req, res):
            raise Exception('error')
        self.stubs.Set(cadf_api.OpenStackAuditApi, 'mod_audit_event',
                       func_error)
        middleware = audit.AuditMiddleware(
            FakeApp(),
            audit_map_file='etc/pycadf/nova_api_audit_map.conf',
            service_name='pycadf')
        req = webob.Request.blank('/foo/bar',
                                  environ={'REQUEST_METHOD': 'GET'})
        middleware.process_response(req, webob.response.Response())