Example #1
0
    def test_cookies(self):
        strict_eq(
            dict(
                http.parse_cookie(
                    'dismiss-top=6; CP=null*; PHPSESSID=0a539d42abc001cd'
                    'c762809248d4beed; a=42; b="\\\";"')), {
                        'CP': u'null*',
                        'PHPSESSID': u'0a539d42abc001cdc762809248d4beed',
                        'a': u'42',
                        'dismiss-top': u'6',
                        'b': u'\";'
                    })
        rv = http.dump_cookie('foo',
                              'bar baz blub',
                              360,
                              httponly=True,
                              sync_expires=False)
        assert type(rv) is str
        assert set(rv.split('; ')) == set(
            ['HttpOnly', 'Max-Age=360', 'Path=/', 'foo="bar baz blub"'])

        strict_eq(dict(http.parse_cookie('fo234{=bar; blub=Blah')), {
            'fo234{': u'bar',
            'blub': u'Blah'
        })

        strict_eq(http.dump_cookie('key', 'xxx/'), 'key=xxx/; Path=/')
        strict_eq(http.dump_cookie('key', 'xxx='), 'key=xxx=; Path=/')
Example #2
0
    def test_cookies(self):
        strict_eq(
            dict(
                http.parse_cookie(
                    "dismiss-top=6; CP=null*; PHPSESSID=0a539d42abc001cd"
                    'c762809248d4beed; a=42; b="\\";"'
                )
            ),
            {
                "CP": u"null*",
                "PHPSESSID": u"0a539d42abc001cdc762809248d4beed",
                "a": u"42",
                "dismiss-top": u"6",
                "b": u'";',
            },
        )
        rv = http.dump_cookie(
            "foo", "bar baz blub", 360, httponly=True, sync_expires=False
        )
        assert type(rv) is str
        assert set(rv.split("; ")) == {
            "HttpOnly",
            "Max-Age=360",
            "Path=/",
            'foo="bar baz blub"',
        }

        strict_eq(
            dict(http.parse_cookie("fo234{=bar; blub=Blah")),
            {"fo234{": u"bar", "blub": u"Blah"},
        )

        strict_eq(http.dump_cookie("key", "xxx/"), "key=xxx/; Path=/")
        strict_eq(http.dump_cookie("key", "xxx="), "key=xxx=; Path=/")
Example #3
0
    def test_cookies(self):
        strict_eq(
            dict(
                http.parse_cookie(
                    "dismiss-top=6; CP=null*; PHPSESSID=0a539d42abc001cd"
                    'c762809248d4beed; a=42; b="\\";"'
                )
            ),
            {
                "CP": u"null*",
                "PHPSESSID": u"0a539d42abc001cdc762809248d4beed",
                "a": u"42",
                "dismiss-top": u"6",
                "b": u'";',
            },
        )
        rv = http.dump_cookie(
            "foo", "bar baz blub", 360, httponly=True, sync_expires=False
        )
        assert type(rv) is str
        assert set(rv.split("; ")) == {
            "HttpOnly",
            "Max-Age=360",
            "Path=/",
            'foo="bar baz blub"',
        }

        strict_eq(
            dict(http.parse_cookie("fo234{=bar; blub=Blah")),
            {"fo234{": u"bar", "blub": u"Blah"},
        )

        strict_eq(http.dump_cookie("key", "xxx/"), "key=xxx/; Path=/")
        strict_eq(http.dump_cookie("key", "xxx="), "key=xxx=; Path=/")
Example #4
0
    def test_cookie_domain_encoding(self):
        val = http.dump_cookie('foo', 'bar', domain=u'\N{SNOWMAN}.com')
        strict_eq(val, 'foo=bar; Domain=xn--n3h.com; Path=/')

        val = http.dump_cookie('foo', 'bar', domain=u'.\N{SNOWMAN}.com')
        strict_eq(val, 'foo=bar; Domain=.xn--n3h.com; Path=/')

        val = http.dump_cookie('foo', 'bar', domain=u'.foo.com')
        strict_eq(val, 'foo=bar; Domain=.foo.com; Path=/')
Example #5
0
    def test_cookie_domain_encoding(self):
        val = http.dump_cookie("foo", "bar", domain="\N{SNOWMAN}.com")
        assert val == "foo=bar; Domain=xn--n3h.com; Path=/"

        val = http.dump_cookie("foo", "bar", domain=".\N{SNOWMAN}.com")
        assert val == "foo=bar; Domain=.xn--n3h.com; Path=/"

        val = http.dump_cookie("foo", "bar", domain=".foo.com")
        assert val == "foo=bar; Domain=.foo.com; Path=/"
Example #6
0
    def test_cookie_domain_encoding(self):
        val = http.dump_cookie('foo', 'bar', domain=u'\N{SNOWMAN}.com')
        self.assert_strict_equal(val, 'foo=bar; Domain=xn--n3h.com; Path=/')

        val = http.dump_cookie('foo', 'bar', domain=u'.\N{SNOWMAN}.com')
        self.assert_strict_equal(val, 'foo=bar; Domain=.xn--n3h.com; Path=/')

        val = http.dump_cookie('foo', 'bar', domain=u'.foo.com')
        self.assert_strict_equal(val, 'foo=bar; Domain=.foo.com; Path=/')
Example #7
0
    def test_cookie_domain_encoding(self):
        val = http.dump_cookie("foo", "bar", domain=u"\N{SNOWMAN}.com")
        strict_eq(val, "foo=bar; Domain=xn--n3h.com; Path=/")

        val = http.dump_cookie("foo", "bar", domain=u".\N{SNOWMAN}.com")
        strict_eq(val, "foo=bar; Domain=.xn--n3h.com; Path=/")

        val = http.dump_cookie("foo", "bar", domain=u".foo.com")
        strict_eq(val, "foo=bar; Domain=.foo.com; Path=/")
Example #8
0
    def test_cookie_domain_encoding(self):
        val = http.dump_cookie("foo", "bar", domain=u"\N{SNOWMAN}.com")
        strict_eq(val, "foo=bar; Domain=xn--n3h.com; Path=/")

        val = http.dump_cookie("foo", "bar", domain=u".\N{SNOWMAN}.com")
        strict_eq(val, "foo=bar; Domain=.xn--n3h.com; Path=/")

        val = http.dump_cookie("foo", "bar", domain=u".foo.com")
        strict_eq(val, "foo=bar; Domain=.foo.com; Path=/")
Example #9
0
 def test_dump_cookie(self):
     rv = http.dump_cookie(
         "foo", "bar baz blub", 360, httponly=True, sync_expires=False
     )
     assert set(rv.split("; ")) == {
         "HttpOnly",
         "Max-Age=360",
         "Path=/",
         'foo="bar baz blub"',
     }
     assert http.dump_cookie("key", "xxx/") == "key=xxx/; Path=/"
     assert http.dump_cookie("key", "xxx=") == "key=xxx=; Path=/"
Example #10
0
    def test_cookie_maxsize(self, recwarn):
        val = http.dump_cookie('foo', 'bar' * 1360 + 'b')
        assert len(recwarn) == 0
        assert len(val) == 4093

        http.dump_cookie('foo', 'bar' * 1360 + 'ba')
        assert len(recwarn) == 1
        w = recwarn.pop()
        assert 'cookie is too large' in str(w.message)

        http.dump_cookie('foo', b'w' * 502, max_size=512)
        assert len(recwarn) == 1
        w = recwarn.pop()
        assert 'the limit is 512 bytes' in str(w.message)
Example #11
0
    def test_cookie_maxsize(self, recwarn):
        val = http.dump_cookie("foo", "bar" * 1360 + "b")
        assert len(recwarn) == 0
        assert len(val) == 4093

        http.dump_cookie("foo", "bar" * 1360 + "ba")
        assert len(recwarn) == 1
        w = recwarn.pop()
        assert "cookie is too large" in str(w.message)

        http.dump_cookie("foo", b"w" * 502, max_size=512)
        assert len(recwarn) == 1
        w = recwarn.pop()
        assert "the limit is 512 bytes" in str(w.message)
Example #12
0
    def test_cookie_maxsize(self, recwarn):
        val = http.dump_cookie("foo", "bar" * 1360 + "b")
        assert len(recwarn) == 0
        assert len(val) == 4093

        http.dump_cookie("foo", "bar" * 1360 + "ba")
        assert len(recwarn) == 1
        w = recwarn.pop()
        assert "cookie is too large" in str(w.message)

        http.dump_cookie("foo", b"w" * 502, max_size=512)
        assert len(recwarn) == 1
        w = recwarn.pop()
        assert "the limit is 512 bytes" in str(w.message)
Example #13
0
    def test_cookie_maxsize(self, recwarn):
        val = http.dump_cookie('foo', 'bar' * 1360 + 'b')
        assert len(recwarn) == 0
        assert len(val) == 4093

        http.dump_cookie('foo', 'bar' * 1360 + 'ba')
        assert len(recwarn) == 1
        w = recwarn.pop()
        assert 'cookie is too large' in str(w.message)

        http.dump_cookie('foo', b'w' * 502, max_size=512)
        assert len(recwarn) == 1
        w = recwarn.pop()
        assert 'the limit is 512 bytes' in str(w.message)
Example #14
0
 def post_process(self, environ, headers):
     user = User.get_current()
     if not user:
         cookies = http.parse_cookie(environ)
         if self.name in cookies:
             raw = http.dump_cookie(self.name, "", expires=1)
             headers.append((utils.to_native("Set-Cookie"), raw))
         return
     cookie = SecureCookie(
         {"uid": user.id, "session_token": user.get_session_token()}, self.secret
     )
     raw = http.dump_cookie(
         self.name, cookie.serialize(), expires=self.expires, max_age=self.max_age
     )
     headers.append((utils.to_native("Set-Cookie"), raw))
Example #15
0
 def post_process(self, environ, headers):
     user = User.get_current()
     if not user:
         cookies = http.parse_cookie(environ)
         if self.name in cookies:
             raw = http.dump_cookie(self.name, '', expires=1)
             headers.append((utils.to_native('Set-Cookie'), raw))
         return
     cookie = SecureCookie({
         'uid': user.id,
         'session_token': user.get_session_token(),
     }, self.secret)
     raw = http.dump_cookie(self.name, cookie.serialize(),
                            expires=self.expires, max_age=self.max_age)
     headers.append((utils.to_native('Set-Cookie'), raw))
Example #16
0
    def process_response(self, response, request, *args, **kwargs):
        if request.session.should_save:
            self.session_store.save(request.session)
            _securecookie = JSONSecureCookie(dict(sid=request.session.sid),
                                             self.secret_key)
            max_age = self.config.get('SESSION_COOKIE_AGE', 1209600)
            path = self.config.get('SESSION_COOKIE_PATH', '/')
            secure = bool(self.config.get('SESSION_COOKIE_SECURE', '0'))
            domain = self.config.get('SESSION_COOKIE_DOMAIN', None)

            if not isinstance(response, Response):
                status, headers, payload = response_triple(response)
                if headers is None:
                    headers = {}
                headers['Set-Cookie'] = dump_cookie(
                    key=self.cookie_key,
                    value=_securecookie.serialize(),
                    max_age=max_age,
                    path=path,
                    domain=domain,
                    secure=secure,
                    httponly=True)
                return status, headers, payload

            _securecookie.save_cookie(response,
                                      self.cookie_key,
                                      max_age=max_age,
                                      path=path,
                                      domain=domain,
                                      secure=secure,
                                      httponly=True,
                                      force=True)
        return response
Example #17
0
        def injecting_start_response(status, headers, exc_info=None):
            # Iterate through the headers looking for Set-Cookie
            updates = False
            for idx, (header, value)  in enumerate(headers):
                if header == 'Set-Cookie':
                    cookie = parse_cookie(value)
                    if 'zappa' in cookie:
                        # We found a header in the response object that sets
                        # zappa as a cookie. Delete it.
                        del(headers[idx])
                        del(cookie['zappa'])
                        print 'deleted zappa set-cooke header'
                        print 'remaining cookie', cookie
                    if cookie:
                        updates = True
                        request_cookies.update(cookie)
                        print 'setting cookie', cookie

            # Encode cookies into Zappa cookie
            if updates and request_cookies:
                final_cookies = ["{cookie}={value}".format(cookie=k, value=v) for k, v in request_cookies.items()]
                encoded = base58.b58encode(';'.join(final_cookies))
                headers.append(('Set-Cookie', dump_cookie('zappa', value=encoded)))

            return start_response(status, headers, exc_info)
Example #18
0
    def set_cookie(
        self,
        server_name: str,
        key: str,
        value: str = "",
        max_age: Optional[Union[int, timedelta]] = None,
        expires: Optional[Union[int, float, datetime]] = None,
        path: str = "/",
        domain: Optional[str] = None,
        secure: bool = False,
        httponly: bool = False,
        samesite: str = None,
        charset: str = "utf-8",
    ) -> None:
        """Set a cookie in the cookie jar.

        The arguments are the standard cookie morsels and this is a
        wrapper around the stdlib SimpleCookie code.
        """
        cookie = dump_cookie(  # type: ignore
            key,
            value=value,
            max_age=max_age,
            expires=expires,
            path=path,
            domain=domain,
            secure=secure,
            httponly=httponly,
            charset=charset,
            samesite=samesite,
        )
        self.cookie_jar.extract_cookies(
            _TestCookieJarResponse(Headers([("set-cookie", cookie)])),  # type: ignore
            U2Request(f"http://{server_name}{path}"),
        )
Example #19
0
    def set_cookie(self, *args, **kwargs):
        cookie = dump_cookie(*args, **kwargs)
        if ('samesite' in kwargs and kwargs['samesite'] is None
                or 'samesite' not in kwargs):
            cookie = "{}; {}".format(cookie, 'SameSite=Lax;')

        self.headers.add('Set-Cookie', cookie)
Example #20
0
    def post(self):
        parser = CustomRequestParser()
        parser.add_argument('mobile',
                            type=str,
                            required=True,
                            nullable=False,
                            location='json')
        parser.add_argument('password',
                            type=str,
                            required=True,
                            nullable=False,
                            location='json')
        parsed_args = parser.parse_args()

        user = User.query.filter(User.mobile == parsed_args['mobile']).first()
        if user is None:
            user = User(id=str(uuid.uuid4()), mobile=parsed_args['mobile'])
            user.set_password(parsed_args['password'])
            user.generate_auth_token()
            db.session.add(user)
            db.session.commit()
            Wallet.generate_wallet(user.id, None)
        else:
            if not user.verify_password(parsed_args['password']):
                abort(400,
                      code=1002,
                      message={'password': '******'})
            user.generate_auth_token()
            user.save()

        cookie = dump_cookie(key='token',
                             value=user.token,
                             max_age=datetime.timedelta(days=1000))
        return user, {'Set-Cookie': cookie}
Example #21
0
    def test_cookie_quoting(self):
        val = http.dump_cookie("foo", "?foo")
        strict_eq(val, 'foo="?foo"; Path=/')
        strict_eq(dict(http.parse_cookie(val)), {'foo': u'?foo'})

        strict_eq(dict(http.parse_cookie(r'foo="foo\054bar"')),
                  {'foo': u'foo,bar'})
def test_cookie_probe_incorrect(render_template, current_app, app, cookie_kv):
    current_app.config = {
        "DM_COOKIE_PROBE_COOKIE_NAME": "foo",
        "DM_COOKIE_PROBE_COOKIE_VALUE": "bar",
        "DM_COOKIE_PROBE_EXPECT_PRESENT": True,
    }
    render_template.return_value = "<html>Oh dear</html>"

    with app.test_request_context('/',
                                  environ_base=cookie_kv and {
                                      "HTTP_COOKIE": dump_cookie(*cookie_kv),
                                  }):
        app.config['WTF_CSRF_ENABLED'] = True
        app.register_blueprint(external_blueprint)

        response, status_code = csrf_handler(CSRFError())

        assert response == render_template.return_value
        assert status_code == 400
        assert render_template.mock_calls == [
            mock.call(
                "errors/400.html",
                error_message=
                "This feature requires cookies to be enabled for correct operation",
            )
        ]
Example #23
0
    def _construct_cookie(self, session, unset=False):
        params = self.configuration['cookie']
        expires = (LONG_AGO if unset else params.get('expires'))

        return dump_cookie(params['name'], session.sid, params.get('max_age'),
            expires, params.get('path', '/'), params.get('domain'),
            params.get('secure'), params.get('httponly', True))
Example #24
0
    def set_cookie(self, name, value='', max_age=None,
                   path='/', domain=None, secure=False, httponly=True):
        """Add a cookie to the response.

        :param name: Name of the cookie.
        :param value: Value of the cookie (should always be a string).
        :param max_age: Maximum age (leave `None` for "browser session").
        :param path: Path to bind the cookie to [default `'/'`].
        :param domain: Domain to bind the cookie to [default `None`].
        :param secure: Secure the cookie [default `False`],
            handy: `request.ssl`.
        :param httponly: Cookie not accessable by JavaScript [default `true`].

        :type name: str
        :type value: str
        :type max_age: int | None
        :type path: str
        :type domain: str | None
        :type secure: bool
        :type httponly: bool

        """
        self.headers.add('Set-Cookie', dump_cookie(
            name, value=str(value), max_age=max_age,
            path=path, domain=domain,
            secure=secure, httponly=httponly,
            charset='utf-8', sync_expires=True))
Example #25
0
    def set_cookie(
        self,
        key: str,
        value: AnyStr = "",  # type: ignore
        max_age: Optional[Union[int, timedelta]] = None,
        expires: Optional[Union[int, float, datetime]] = None,
        path: str = "/",
        domain: Optional[str] = None,
        secure: bool = False,
        httponly: bool = False,
        samesite: str = None,
    ) -> None:
        """Set a cookie in the response headers.

        The arguments are the standard cookie morsels and this is a
        wrapper around the stdlib SimpleCookie code.
        """
        if isinstance(value, bytes):
            value = value.decode()  # type: ignore
        self.headers.add(
            "Set-Cookie",
            dump_cookie(  # type: ignore
                key,
                value=value,
                max_age=max_age,
                expires=expires,
                path=path,
                domain=domain,
                secure=secure,
                httponly=httponly,
                charset=self.charset,
                max_size=self.max_cookie_size,
                samesite=samesite,
            ),
        )
Example #26
0
 def test_cookie_quoting(self):
     val = http.dump_cookie("foo", "?foo")
     assert val == 'foo="?foo"; Path=/'
     assert http.parse_cookie(val).to_dict() == {"foo": "?foo", "Path": "/"}
     assert http.parse_cookie(r'foo="foo\054bar"').to_dict(), {
         "foo": "foo,bar"
     }
Example #27
0
 def test_cookies(self):
     self.assert_strict_equal(
         dict(
             http.parse_cookie(
                 'dismiss-top=6; CP=null*; PHPSESSID=0a539d42abc001cd'
                 'c762809248d4beed; a=42; b="\\\";"')), {
                     'CP': u'null*',
                     'PHPSESSID': u'0a539d42abc001cdc762809248d4beed',
                     'a': u'42',
                     'dismiss-top': u'6',
                     'b': u'\";'
                 })
     self.assert_strict_equal(
         set(
             http.dump_cookie('foo',
                              'bar baz blub',
                              360,
                              httponly=True,
                              sync_expires=False).split(u'; ')),
         set([
             u'HttpOnly', u'Max-Age=360', u'Path=/', u'foo="bar baz blub"'
         ]))
     self.assert_strict_equal(
         dict(http.parse_cookie('fo234{=bar; blub=Blah')), {
             'fo234{': u'bar',
             'blub': u'Blah'
         })
Example #28
0
 def test_cookie_unicode_keys(self):
     # Yes, this is technically against the spec but happens
     val = http.dump_cookie(u'fö', u'fö')
     self.assert_equal(
         val, wsgi_encoding_dance(u'fö="f\\303\\266"; Path=/', 'utf-8'))
     cookies = http.parse_cookie(val)
     self.assert_equal(cookies[u'fö'], u'fö')
Example #29
0
    def test_cookie_quoting(self):
        val = http.dump_cookie("foo", "?foo")
        self.assert_strict_equal(val, 'foo="?foo"; Path=/')
        self.assert_strict_equal(dict(http.parse_cookie(val)), {'foo': u'?foo'})

        self.assert_strict_equal(dict(http.parse_cookie(r'foo="foo\054bar"')),
                                 {'foo': u'foo,bar'})
Example #30
0
File: user.py Project: q25979/tdb99
    def post(self):
        parser = CustomRequestParser()
        parser.add_argument('mobile',
                            type=str,
                            required=True,
                            nullable=False,
                            location='json')
        # parser.add_argument('pin_code', type=str, required=True, nullable=False, location='json')
        parser.add_argument('password',
                            type=str,
                            required=True,
                            nullable=False,
                            location='json')
        # parser.add_argument('uuid', type=str, required=True, nullable=False, location='json')
        # parser.add_argument('captcha_pin_code', type=str, required=True, nullable=False, location='json')
        parsed_args = parser.parse_args()

        # CaptchaPinCode.flask_check(parsed_args['uuid'], parsed_args['captcha_pin_code'])

        # user = User.reset_password(parsed_args['mobile'], parsed_args['pin_code'], parsed_args['password'])
        user = User.reset_password(parsed_args['mobile'],
                                   parsed_args['password'])
        if not user:
            abort(400, code=1001, message={'mobile': 'user does not exist'})
        db.session.commit()
        cookie = dump_cookie(key='token',
                             value=user.token,
                             max_age=datetime.timedelta(days=365))
        return user, {'Set-Cookie': cookie}
Example #31
0
    def test_cookie_unicode_dumping(self):
        val = http.dump_cookie("foo", u"\N{SNOWMAN}")
        h = datastructures.Headers()
        h.add("Set-Cookie", val)
        assert h["Set-Cookie"] == 'foo="\\342\\230\\203"; Path=/'

        cookies = http.parse_cookie(h["Set-Cookie"])
        assert cookies["foo"] == u"\N{SNOWMAN}"
Example #32
0
 def session_start_response(status, headers, exc_info=None):
     if session.should_save or session == {}:
         # add our cookie to headers
         c = dump_cookie(self.cookie_name,
                         value=environ[self.wsgi_name].serialize(),
                         max_age=datetime.timedelta(days=self.expire_days))
         headers.append(('Set-Cookie', c))
     return start_response(status, headers, exc_info=exc_info)
Example #33
0
 def save(self, session: http.Session) -> typing.Dict[str, str]:
     headers = {}
     if session.is_new:
         cookie = dump_cookie(self.cookie_name, session.session_id)
         headers['set-cookie'] = cookie
     if session.is_new or session.is_modified:
         local_memory_sessions[session.session_id] = session.data
     return headers
Example #34
0
    def test_cookie_unicode_dumping(self):
        val = http.dump_cookie("foo", "\N{SNOWMAN}")
        h = datastructures.Headers()
        h.add("Set-Cookie", val)
        assert h["Set-Cookie"] == 'foo="\\342\\230\\203"; Path=/'

        cookies = http.parse_cookie(h["Set-Cookie"])
        assert cookies["foo"] == "\N{SNOWMAN}"
Example #35
0
    def test_cookie_unicode_dumping(self):
        val = http.dump_cookie('foo', u'\N{SNOWMAN}')
        h = datastructures.Headers()
        h.add('Set-Cookie', val)
        self.assert_equal(h['Set-Cookie'], 'foo="\\342\\230\\203"; Path=/')

        cookies = http.parse_cookie(h['Set-Cookie'])
        self.assert_equal(cookies['foo'], u'\N{SNOWMAN}')
Example #36
0
    def test_cookie_unicode_dumping(self):
        val = http.dump_cookie('foo', u'\N{SNOWMAN}')
        h = datastructures.Headers()
        h.add('Set-Cookie', val)
        assert h['Set-Cookie'] == 'foo="\\342\\230\\203"; Path=/'

        cookies = http.parse_cookie(h['Set-Cookie'])
        assert cookies['foo'] == u'\N{SNOWMAN}'
Example #37
0
    def _construct_cookie(self, session, unset=False):
        params = self.configuration['cookie']
        expires = (LONG_AGO if unset else params.get('expires'))

        return dump_cookie(params['name'], session.sid, params.get('max_age'),
                           expires, params.get('path', '/'),
                           params.get('domain'), params.get('secure'),
                           params.get('httponly', True))
Example #38
0
    def encode_response(self, status, headers, exc_info=None):
        """
        Zappa-ify our application response!

        This means:
            - Updating any existing cookies.
            - Packing all our cookies into a single ZappaCookie.
            - Injecting redirect HTML if setting a Cookie on a redirect.

        """
        # All the non-cookie headers should be sent unharmed.
        new_headers = [(header[0], header[1]) for header in headers if header[0] != 'Set-Cookie']

        # Filter the headers for Set-Cookie header
        cookie_dicts = [
            {header[1].split('=', 1)[0].strip():header[1].split('=', 1)[1]}
            for header
            in headers
            if header[0] == 'Set-Cookie'
        ]

        # Update request_cookies with cookies from the response. If there are
        # multiple occuring cookies, the last one present in the headers wins.
        map(self.request_cookies.update, cookie_dicts)

        # Get the oldest expire time, and set the Zappa cookie age to that.
        # Else, let this be a session cookie.
        expires = None
        for _, exp in self.iter_cookies_expires():
            if exp > expires:
                expires = exp

        # JSON-ify the cookie and encode it.
        pack_s = json.dumps(self.request_cookies)
        encoded = base58.b58encode(pack_s)

        # Set the result as the zappa cookie
        new_headers.append(
            (
                'Set-Cookie',
                dump_cookie('zappa', value=encoded, expires=expires)
            )
        )

        # If setting cookie on a 301/2,
        # return 200 and replace the content with a javascript redirector
        # content_type_header_key = [k for k, v in enumerate(new_headers) if v[0] == 'Content-Type']
        # if len(content_type_header_key) > 0:
        #     if "text/html" in new_headers[content_type_header_key[0]][1]:
        #         if status != '200 OK':
        #             for key, value in new_headers:
        #                 if key != 'Location':
        #                     continue
        #                 self.redirect_content = REDIRECT_HTML.replace('REDIRECT_ME', value)
        #                 status = '200 OK'
        #                 break

        return self.start_response(status, new_headers, exc_info)
Example #39
0
    def test_cookie_script(self):
        """"""
        url = '/test-cookie'
        cookie = dump_cookie('test-cookie', '<script>alert("ho")</script>')
        with self.app.test_request_context(url, method='GET',
                                           headers={'Cookie': cookie}):

            response = self.app.dispatch_request()
            self.assertNotIn('<script>', response.data)
Example #40
0
 def wrapper(request, *args, **kwargs):
     request.cookies = _parse_cookie(request.headers.get('Cookie', 'No Cookie'))
     response = func(request, *args, **kwargs)
     if hasattr(response, 'cookies'):
         cookies_strings = []
         for key, value in response.cookies.items():
             cookies_strings.append(dump_cookie(key, **value))
         response.headers['Set-Cookie'] = cookies_strings
     return response
Example #41
0
 def post_process(self, environ, headers):
     user = User.get_current()
     if not user:
         cookies = http.parse_cookie(environ)
         if self.name in cookies:
             raw = http.dump_cookie(self.name, '', expires=1)
             headers.append(('Set-Cookie', raw))
         return
     cookie = SecureCookie(
         {
             'uid': user.id,
             'session_token': user.get_session_token(),
         }, self.secret)
     raw = http.dump_cookie(self.name,
                            cookie.serialize(),
                            expires=self.expires,
                            max_age=self.max_age)
     headers.append(('Set-Cookie', raw))
Example #42
0
 def wrapper(request):
     request.cookies = _parse_cookie(request.headers.get('Cookie', 'No Cookie'))
     response = func(request)
     if hasattr(response, 'cookies'):
         cookies_strings = []
         for key, value in response.cookies.items():
             cookies_strings.append(dump_cookie(key, **value))
         response.headers['Set-Cookie'] = ",".join(cookies_strings)
     return response
Example #43
0
 def test_cookies(self):
     self.assert_strict_equal(
         dict(http.parse_cookie("dismiss-top=6; CP=null*; PHPSESSID=0a539d42abc001cd" "c762809248d4beed; a=42")),
         {u"CP": u"null*", u"PHPSESSID": u"0a539d42abc001cdc762809248d4beed", u"a": u"42", u"dismiss-top": u"6"},
     )
     self.assert_strict_equal(
         set(http.dump_cookie("foo", "bar baz blub", 360, httponly=True, sync_expires=False).split(u"; ")),
         set([u"HttpOnly", u"Max-Age=360", u"Path=/", u'foo="bar baz blub"']),
     )
     self.assert_strict_equal(dict(http.parse_cookie("fo234{=bar blub=Blah")), {u"blub": u"Blah"})
Example #44
0
def test_cookie_extract(flask_app: Flask, authenticator: Auth0Authenticator,
                        access_token: str):
    cookie_name = "TestCookie"
    authenticator.header_authentication = False
    authenticator.cookie_authentication = True
    authenticator.cookie_name = cookie_name
    header = dump_cookie(cookie_name, access_token)
    with flask_app.test_request_context(headers={"COOKIE": header}):
        token = authenticator._get_token()
        assert token == access_token
Example #45
0
    def test_cookie_script(self):
        """"""
        url = '/test-cookie'
        cookie = dump_cookie('test-cookie', '<script>alert("ho")</script>')
        with self.app.test_request_context(url,
                                           method='GET',
                                           headers={'Cookie': cookie}):

            response = self.app.dispatch_request()
            self.assertNotIn('<script>', response.data)
Example #46
0
def logged_user_headers(user, headers=Headers()):
    app_user = AppUser.query.filter_by(
        id_role=user.id_role,
        id_application=current_app.config['ID_APP'],
    ).one()
    cookie = dump_cookie('token', user_to_token(app_user))
    headers.extend({
        'Cookie': cookie,
    })
    return headers
Example #47
0
def test_rest_uses_sec_cookie_when_env_var_not_set(env_qradar_console_fqdn):
    test_sec_cookie_value = 'seccookie-12345-seccookie'
    cookie = http.dump_cookie("SEC", test_sec_cookie_value)
    app = Flask(__name__)
    with app.test_request_context(headers={"COOKIE": cookie}):
        responses.add('GET', 'https://myhost.ibm.com/testing_endpoint', status=200)
        response = qpylib.REST('GET', 'testing_endpoint', verify='dummycert', headers={'Host': '127.0.0.1'})
        assert response.status_code == 200
        assert responses.calls[0].request.method == 'GET'
        assert responses.calls[0].request.url == 'https://myhost.ibm.com/testing_endpoint'
        assert responses.calls[0].request.headers['SEC'] == test_sec_cookie_value
Example #48
0
def save(app, sess):
    if not sess.should_save:
        return
    app.config['ayame.session.store'].save(sess)
    return ('Set-Cookie', http.dump_cookie(app.config['ayame.session.name'], sess.sid,
                                           app.config['ayame.session.max_age'],
                                           app.config['ayame.session.expires'],
                                           app.config['ayame.session.path'],
                                           app.config['ayame.session.domain'],
                                           app.config['ayame.session.secure'],
                                           app.config['ayame.session.httponly']))
Example #49
0
 def generate_headers(self, token):
     """Generate auth headers"""
     headers = {}
     token = self.encode_token(token)
     if self.config["header"]:
         headers[self.config["header"]] = token
     if self.config["cookie"]:
         headers["Set-Cookie"] = dump_cookie(
             self.config["cookie"], token, httponly=True,
             max_age=self.config["expiration"]
         )
     return headers
Example #50
0
 def test_cookies(self):
     assert http.parse_cookie('dismiss-top=6; CP=null*; PHPSESSID=0a539d42abc001cd'
                         'c762809248d4beed; a=42') == {
         'CP':           u'null*',
         'PHPSESSID':    u'0a539d42abc001cdc762809248d4beed',
         'a':            u'42',
         'dismiss-top':  u'6'
     }
     assert set(http.dump_cookie('foo', 'bar baz blub', 360, httponly=True,
                            sync_expires=False).split('; ')) == \
            set(['HttpOnly', 'Max-Age=360', 'Path=/', 'foo="bar baz blub"'])
     assert http.parse_cookie('fo234{=bar blub=Blah') == {'blub': 'Blah'}
Example #51
0
    def test_cookies(self):
        strict_eq(
            dict(http.parse_cookie('dismiss-top=6; CP=null*; PHPSESSID=0a539d42abc001cd'
                                   'c762809248d4beed; a=42; b="\\\";"')),
            {
                'CP':           u'null*',
                'PHPSESSID':    u'0a539d42abc001cdc762809248d4beed',
                'a':            u'42',
                'dismiss-top':  u'6',
                'b':            u'\";'
            }
        )
        rv = http.dump_cookie('foo', 'bar baz blub', 360, httponly=True,
                              sync_expires=False)
        assert type(rv) is str
        assert set(rv.split('; ')) == set(['HttpOnly', 'Max-Age=360',
                                           'Path=/', 'foo="bar baz blub"'])

        strict_eq(dict(http.parse_cookie('fo234{=bar; blub=Blah')),
                  {'fo234{': u'bar', 'blub': u'Blah'})

        strict_eq(http.dump_cookie('key', 'xxx/'), 'key=xxx/; Path=/')
        strict_eq(http.dump_cookie('key', 'xxx='), 'key=xxx=; Path=/')
Example #52
0
    def _construct_cookie(self, session, unset=False):
        params = self.configuration["cookie"]
        expires = LONG_AGO if unset else params.get("expires")

        return dump_cookie(
            params["name"],
            session.sid,
            params.get("max_age"),
            expires,
            params.get("path", "/"),
            params.get("domain"),
            params.get("secure"),
            params.get("httponly", True),
        )
Example #53
0
 def test_cookies(self):
     self.assert_strict_equal(
         dict(http.parse_cookie('dismiss-top=6; CP=null*; PHPSESSID=0a539d42abc001cd'
                           'c762809248d4beed; a=42')),
         {
             'CP':           u'null*',
             'PHPSESSID':    u'0a539d42abc001cdc762809248d4beed',
             'a':            u'42',
             'dismiss-top':  u'6'
         }
     )
     self.assert_strict_equal(
         set(http.dump_cookie('foo', 'bar baz blub', 360, httponly=True,
                              sync_expires=False).split(u'; ')),
         set([u'HttpOnly', u'Max-Age=360', u'Path=/', u'foo="bar baz blub"'])
     )
     self.assert_strict_equal(dict(http.parse_cookie('fo234{=bar; blub=Blah')),
                              {'fo234{': u'bar', 'blub': u'Blah'})
Example #54
0
 def test_cookie_unicode_keys(self):
     # Yes, this is technically against the spec but happens
     val = http.dump_cookie(u'fö', u'fö')
     self.assert_equal(val, wsgi_encoding_dance(u'fö="f\\303\\266"; Path=/', 'utf-8'))
     cookies = http.parse_cookie(val)
     self.assert_equal(cookies[u'fö'], u'fö')
Example #55
0
 def test_cookie_quoting(self):
     val = http.dump_cookie("foo", "?foo")
     strict_eq(val, 'foo="?foo"; Path=/')
     strict_eq(dict(http.parse_cookie(val)), {"foo": u"?foo", "Path": u"/"})
     strict_eq(dict(http.parse_cookie(r'foo="foo\054bar"')), {"foo": u"foo,bar"})
Example #56
0
 def test_cookie_unicode_keys(self):
     # Yes, this is technically against the spec but happens
     val = http.dump_cookie(u"fö", u"fö")
     assert val == wsgi_encoding_dance(u'fö="f\\303\\266"; Path=/', "utf-8")
     cookies = http.parse_cookie(val)
     assert cookies[u"fö"] == u"fö"
Example #57
0
 def test_cookie_samesite_attribute(self, input, expected):
     val = http.dump_cookie("foo", "bar", samesite=input)
     strict_eq(val, expected)
Example #58
0
 def test_cookie_domain_resolving(self):
     val = http.dump_cookie('foo', 'bar', domain=u'\N{SNOWMAN}.com')
     strict_eq(val, 'foo=bar; Domain=xn--n3h.com; Path=/')
Example #59
0
def make_csrf_cookie(name, tok_length):

    tok = ''.join(
        random.choice(string.ascii_letters) for x in range(tok_length)
    )
    return dump_cookie(name, value=tok)
Example #60
0
    def test_cookie_quoting(self):
        val = http.dump_cookie("foo", "?foo")
        assert val == 'foo="?foo"; Path=/'
        assert http.parse_cookie(val) == {'foo': '?foo'}

        assert http.parse_cookie(r'foo="foo\054bar"') == {'foo': 'foo,bar'}