Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

# vim: tabstop=4 shiftwidth=4 softtabstop=4 

 

# Copyright 2012 OpenStack LLC 

# 

# 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 webob.dec 

 

from keystone.common import config 

from keystone.common import logging 

from keystone.common import serializer 

from keystone.common import utils 

from keystone.common import wsgi 

from keystone import exception 

from keystone.openstack.common import jsonutils 

 

 

CONF = config.CONF 

LOG = logging.getLogger(__name__) 

 

 

# Header used to transmit the auth token 

AUTH_TOKEN_HEADER = 'X-Auth-Token' 

 

 

# Header used to transmit the subject token 

SUBJECT_TOKEN_HEADER = 'X-Subject-Token' 

 

 

# Environment variable used to pass the request context 

CONTEXT_ENV = wsgi.CONTEXT_ENV 

 

 

# Environment variable used to pass the request params 

PARAMS_ENV = wsgi.PARAMS_ENV 

 

 

class TokenAuthMiddleware(wsgi.Middleware): 

    def process_request(self, request): 

        token = request.headers.get(AUTH_TOKEN_HEADER) 

        context = request.environ.get(CONTEXT_ENV, {}) 

        context['token_id'] = token 

        if SUBJECT_TOKEN_HEADER in request.headers: 

            context['subject_token_id'] = ( 

                request.headers.get(SUBJECT_TOKEN_HEADER)) 

        request.environ[CONTEXT_ENV] = context 

 

 

class AdminTokenAuthMiddleware(wsgi.Middleware): 

    """A trivial filter that checks for a pre-defined admin token. 

 

    Sets 'is_admin' to true in the context, expected to be checked by 

    methods that are admin-only. 

 

    """ 

 

    def process_request(self, request): 

        token = request.headers.get(AUTH_TOKEN_HEADER) 

        context = request.environ.get(CONTEXT_ENV, {}) 

        context['is_admin'] = (token == CONF.admin_token) 

        request.environ[CONTEXT_ENV] = context 

 

 

class PostParamsMiddleware(wsgi.Middleware): 

    """Middleware to allow method arguments to be passed as POST parameters. 

 

    Filters out the parameters `self`, `context` and anything beginning with 

    an underscore. 

 

    """ 

 

    def process_request(self, request): 

        params_parsed = request.params 

        params = {} 

        for k, v in params_parsed.iteritems(): 

87            if k in ('self', 'context'): 

                continue 

89            if k.startswith('_'): 

                continue 

            params[k] = v 

 

        request.environ[PARAMS_ENV] = params 

 

 

class JsonBodyMiddleware(wsgi.Middleware): 

    """Middleware to allow method arguments to be passed as serialized JSON. 

 

    Accepting arguments as JSON is useful for accepting data that may be more 

    complex than simple primitives. 

 

    In this case we accept it as urlencoded data under the key 'json' as in 

    json=<urlencoded_json> but this could be extended to accept raw JSON 

    in the POST body. 

 

    Filters out the parameters `self`, `context` and anything beginning with 

    an underscore. 

 

    """ 

    def process_request(self, request): 

        # Abort early if we don't have any work to do 

        params_json = request.body 

        if not params_json: 

            return 

 

        # Reject unrecognized content types. Empty string indicates 

        # the client did not explicitly set the header 

        if request.content_type not in ('application/json', ''): 

            e = exception.ValidationError(attribute='application/json', 

                                          target='Content-Type header') 

            return wsgi.render_exception(e) 

 

        params_parsed = {} 

        try: 

            params_parsed = jsonutils.loads(params_json) 

        except ValueError: 

            e = exception.ValidationError(attribute='valid JSON', 

                                          target='request body') 

            return wsgi.render_exception(e) 

        finally: 

            if not params_parsed: 

                params_parsed = {} 

 

        params = {} 

        for k, v in params_parsed.iteritems(): 

136            if k in ('self', 'context'): 

                continue 

138            if k.startswith('_'): 

                continue 

            params[k] = v 

 

        request.environ[PARAMS_ENV] = params 

 

 

class XmlBodyMiddleware(wsgi.Middleware): 

    """De/serializes XML to/from JSON.""" 

 

    def process_request(self, request): 

        """Transform the request from XML to JSON.""" 

        incoming_xml = 'application/xml' in str(request.content_type) 

        if incoming_xml and request.body: 

            request.content_type = 'application/json' 

            try: 

                request.body = jsonutils.dumps( 

                    serializer.from_xml(request.body)) 

            except Exception: 

                LOG.exception('Serializer failed') 

                e = exception.ValidationError(attribute='valid XML', 

                                              target='request body') 

                return wsgi.render_exception(e) 

 

    def process_response(self, request, response): 

        """Transform the response from JSON to XML.""" 

        outgoing_xml = 'application/xml' in str(request.accept) 

        if outgoing_xml and response.body: 

            response.content_type = 'application/xml' 

            try: 

                body_obj = jsonutils.loads(response.body) 

                response.body = serializer.to_xml(body_obj) 

            except Exception: 

                LOG.exception('Serializer failed') 

                raise exception.Error(message=response.body) 

        return response 

 

 

class NormalizingFilter(wsgi.Middleware): 

    """Middleware filter to handle URL normalization.""" 

 

    def process_request(self, request): 

        """Normalizes URLs.""" 

        # Removes a trailing slash from the given path, if any. 

        if (len(request.environ['PATH_INFO']) > 1 and 

                request.environ['PATH_INFO'][-1] == '/'): 

            request.environ['PATH_INFO'] = request.environ['PATH_INFO'][:-1] 

        # Rewrites path to root if no path is given. 

        elif not request.environ['PATH_INFO']: 

            request.environ['PATH_INFO'] = '/' 

 

 

class RequestBodySizeLimiter(wsgi.Middleware): 

    """Limit the size of an incoming request.""" 

 

    def __init__(self, *args, **kwargs): 

        super(RequestBodySizeLimiter, self).__init__(*args, **kwargs) 

 

    @webob.dec.wsgify(RequestClass=wsgi.Request) 

    def __call__(self, req): 

 

        if req.content_length > CONF.max_request_body_size: 

            raise exception.RequestTooLarge() 

        if req.content_length is None and req.is_body_readable: 

            limiter = utils.LimitingReader(req.body_file, 

                                           CONF.max_request_body_size) 

            req.body_file = limiter 

        return self.application