Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def serialize(secret, salt, data):
import hmac
import base64
import json
from hashlib import sha1
from webob.compat import bytes_
salted_secret = bytes_(salt or '', 'utf-8') + bytes_(secret, 'utf-8')
cstruct = bytes_(json.dumps(data))
sig = hmac.new(salted_secret, cstruct, sha1).digest()
return base64.urlsafe_b64encode(sig + cstruct).rstrip(b'=')
# end of headers
break
hname, hval = line.split(colon, 1)
hname = native_(hname, 'utf-8')
hval = native_(hval, 'utf-8').strip()
if hname in r.headers:
hval = r.headers[hname] + ', ' + hval
r.headers[hname] = hval
if r.method in ('PUT', 'POST'):
clen = r.content_length
if clen is None:
body = fp.read()
else:
body = fp.read(clen)
if is_text:
body = bytes_(body, 'utf-8')
r.body = body
return r
def encset(self, key, val, encattr=None):
if encattr:
encoding = getattr(self, encattr)
else:
encoding = 'ascii'
if PY3: # pragma: no cover
self.environ[key] = bytes_(val, encoding).decode('latin-1')
else:
self.environ[key] = bytes_(val, encoding)
"""Like wsgiref.url.request_uri, except eliminates :80 ports
Return the full request URI"""
url = environ['wsgi.url_scheme']+'://'
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url += environ['SERVER_NAME'] + ':' + environ['SERVER_PORT']
if url.endswith(':80') and environ['wsgi.url_scheme'] == 'http':
url = url[:-3]
elif url.endswith(':443') and environ['wsgi.url_scheme'] == 'https':
url = url[:-4]
if PY3: # pragma: no cover
script_name = bytes_(environ.get('SCRIPT_NAME', '/'), 'latin-1')
path_info = bytes_(environ.get('PATH_INFO', ''), 'latin-1')
else:
script_name = environ.get('SCRIPT_NAME', '/')
path_info = environ.get('PATH_INFO', '')
url += url_quote(script_name)
qpath_info = url_quote(path_info)
if not 'SCRIPT_NAME' in environ:
url += qpath_info[1:]
else:
url += qpath_info
return url
"""
if overwrite:
self.unset_cookie(key, strict=False)
if value is None: # delete the cookie from the client
value = ''
max_age = 0
expires = timedelta(days=-5)
elif expires is None and max_age is not None:
if isinstance(max_age, int):
max_age = timedelta(seconds=max_age)
expires = datetime.utcnow() + max_age
elif max_age is None and expires is not None:
max_age = expires - datetime.utcnow()
value = bytes_(value, 'utf8')
key = bytes_(key, 'utf8')
m = Morsel(key, value)
m.path = bytes_(path, 'utf8')
m.domain = bytes_(domain, 'utf8')
m.comment = bytes_(comment, 'utf8')
m.expires = expires
m.max_age = max_age
m.secure = secure
m.httponly = httponly
self.headerlist.append(('Set-Cookie', m.serialize()))
def encset(self, key, val, encattr=None):
if encattr:
encoding = getattr(self, encattr)
else:
encoding = 'ascii'
if PY3: # pragma: no cover
self.environ[key] = bytes_(val, encoding).decode('latin-1')
else:
self.environ[key] = bytes_(val, encoding)
max_age = (max_age.days * 60 * 60 * 24) + max_age.seconds
expires = max_age
elif max_age is not None:
try:
max_age = int(max_age)
except ValueError:
raise ValueError('max_age should be an integer. Amount of seconds until expiration.')
expires = max_age
else:
expires = None
morsel = Morsel(name, value)
if domain is not None:
morsel.domain = bytes_(domain)
if path is not None:
morsel.path = bytes_(path)
if httponly:
morsel.httponly = True
if secure:
morsel.secure = True
if max_age is not None:
morsel.max_age = max_age
if expires is not None:
morsel.expires = expires
if comment is not None:
morsel.comment = bytes_(comment)
return morsel.serialize()
elif max_age is not None:
try:
max_age = int(max_age)
except ValueError:
raise ValueError('max_age should be an integer. Amount of seconds until expiration.')
expires = max_age
else:
expires = None
morsel = Morsel(name, value)
if domain is not None:
morsel.domain = bytes_(domain)
if path is not None:
morsel.path = bytes_(path)
if httponly:
morsel.httponly = True
if secure:
morsel.secure = True
if max_age is not None:
morsel.max_age = max_age
if expires is not None:
morsel.expires = expires
if comment is not None:
morsel.comment = bytes_(comment)
return morsel.serialize()
status304 = self.last_modified <= req.if_modified_since
if status304:
start_response("304 Not Modified", filter_headers(headerlist))
return EmptyResponse(self._app_iter)
if (
req.range
and self in req.if_range
and self.content_range is None
and method in ("HEAD", "GET")
and self.status_code == 200
and self.content_length is not None
):
content_range = req.range.content_range(self.content_length)
if content_range is None:
iter_close(self._app_iter)
body = bytes_("Requested range not satisfiable: %s" % req.range)
headerlist = [
("Content-Length", str(len(body))),
(
"Content-Range",
str(ContentRange(None, None, self.content_length)),
),
("Content-Type", "text/plain"),
] + filter_headers(headerlist)
start_response("416 Requested Range Not Satisfiable", headerlist)
if method == "HEAD":
return ()
return [body]
else:
app_iter = self.app_iter_range(content_range.start, content_range.stop)
if app_iter is not None:
# the following should be guaranteed by
def loads(self, bstruct):
"""
Given a ``bstruct`` (a bytestring), verify the signature and then
deserialize and return the deserialized value.
A ``ValueError`` will be raised if the signature fails to validate.
"""
try:
cstruct = base64.urlsafe_b64decode(bytes_(bstruct))
except (binascii.Error, TypeError) as e:
raise ValueError('Badly formed base64 data: %s' % e)
return self.serializer.loads(cstruct)