Пример #1
0
    def test_session_fixation(self):
        """Ensure if session is empty that a new session is given."""
        user1 = create_account('user1', '*****@*****.**', 'Password')
        activate(user1)
        resp = self.client.post(url_for('auth.signin'), data={
            'username': '******',
            'password': '******'
        })

        session_id = None
        for header in resp.headers:
            if header[0] == 'Set-Cookie':
                session_id = parse_cookie(header[1])['session']
                rs.delete(session_id)

        resp = self.client.post(url_for('auth.signin'), data={
            'username': '******',
            'password': '******'
        })

        # Find the Set-Cookie header so we can parse it and check the session
        # identifier has been updated
        for header in resp.headers:
            if header[0] == 'Set-Cookie':
                self.assertNotEqual(session_id,
                                    parse_cookie(header[1])['session'])
Пример #2
0
 def test_suggest_decorated(self):
     rv = self.app_client.get("/show_btn_decorated")
     assert parse_cookie(rv.headers["Set-Cookie"])["MAB"]
     assert "X-MAB-Debug" in rv.headers.keys()
     chosen_arm = self.get_arm(rv.headers)["color_button"]
     assert self.app.extensions['mab'].bandits["color_button"][chosen_arm]["pulls"] > 0
     assert json.loads(parse_cookie(rv.headers["Set-Cookie"])["MAB"])["color_button"] == chosen_arm
Пример #3
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'})
Пример #4
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=/")
Пример #5
0
 def test_suggest_decorated(self):
     self.app.debug_headers = True
     rv = self.app_client.get("/show_btn_decorated")
     assert parse_cookie(rv.headers["Set-Cookie"])["MAB"]
     assert "X-MAB-Debug" in rv.headers.keys()
     chosen_arm = self.get_arm(rv.headers)[self.name_to_test]
     assert self.app.extensions["mab"].bandits[self.name_to_test][chosen_arm]["pulls"] > 0
     assert json.loads(parse_cookie(rv.headers["Set-Cookie"])["MAB"])[self.name_to_test] == chosen_arm
Пример #6
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"})
Пример #7
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'}
Пример #8
0
 def get_cookie(self, name):
     cookies = self.rsp.headers.getlist('Set-Cookie')
     for cookie in cookies:
         c_key, c_value = parse_cookie(cookie).items()[0]
         if c_key == name:
             return c_value
     return None
Пример #9
0
 def _get_session(self, environ):
     cookie = parse_cookie(environ.get('HTTP_COOKIE', ''))
     id = cookie.get(self.configuration['cookie']['name'], None)
     if id is not None:
         return self.store.get(id)
     else:
         return self.store.new()
Пример #10
0
 def getCookie(self, response, cookie_name):
     cookies = response.headers.getlist('Set-Cookie')
     for cookie in cookies:
         value = parse_cookie(cookie).get(cookie_name)
         if value:
             return value
     return None
Пример #11
0
 def getCookie(self, response, cookie_name):
     cookies = response.headers.getlist('Set-Cookie')
     for cookie in cookies:
         key, value = list(parse_cookie(cookie).items())[0]
         if key == cookie_name:
             return value
     return None
Пример #12
0
 def get_session(self, resp):
   '''
   get the value of the Set-Cookie header, load the value as JSON since that's
   what we're working with for test purposes
   '''
   cookies = parse_cookie(resp.headers.get('Set-Cookie'))
   return loads(cookies.get(session_cookie_name))
Пример #13
0
 def test_empty_keys_are_ignored(self):
     strict_eq(
         dict(
             http.parse_cookie("first=IamTheFirst ; a=1; a=2 ;second=andMeTwo; ; ")
         ),
         {"first": u"IamTheFirst", "a": u"2", "second": u"andMeTwo"},
     )
Пример #14
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)
Пример #15
0
 def test_from_cookie(self):
     print self.name_to_test
     first_req = self.app_client.get("/show_btn_decorated")
     assert "X-MAB-Debug" in first_req.headers.keys()
     chosen_arm = json.loads(parse_cookie(first_req.headers["Set-Cookie"])["MAB"])[self.name_to_test]
     self.app_client.get("/reward_decorated")
     assert self.app.extensions['mab'].bandits[self.name_to_test][chosen_arm]["reward"] > 0
 def test_pull_is_called(self):
     self.bandit_a.pull_arm = Mock()
     self.bandit_b.pull_arm = Mock()
     req = self.app_client.get('/show_btn_decorated')
     chosen_arms = json.loads(parse_cookie(req.headers["Set-Cookie"])["MAB"])
     self.bandit_a.pull_arm.assert_called_with(chosen_arms['color_button'])
     self.bandit_b.pull_arm.assert_called_with(chosen_arms['color_bg'])
Пример #17
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}')
Пример #18
0
 def test_aguid_cookie_domain(self):
     for host in [('http://localhost', '.localhost'),
                  ('http://track.my.jobs', '.my.jobs'),
                  ('http://this.is.a.long.host.com', '.host.com')]:
         response = self.client.get('/pixel.gif',
                                    base_url=host[0])
         domain = parse_cookie(response.headers['Set-Cookie'])['Domain']
         self.assertEqual(domain, host[1])
Пример #19
0
 def is_trusted(self, environ):
     """Checks if the request passed the pin test."""
     if self.pin is None:
         return True
     ts = parse_cookie(environ).get(self.pin_cookie_name, type=int)
     if ts is None:
         return False
     return (time.time() - PIN_TIME) < ts
Пример #20
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}"
Пример #21
0
 def test_bad_cookies(self):
     strict_eq(
         dict(
             http.parse_cookie(
                 "first=IamTheFirst ; a=1; oops ; a=2 ;second = andMeTwo;"
             )
         ),
         {"first": u"IamTheFirst", "a": u"2", "oops": u"", "second": u"andMeTwo"},
     )
Пример #22
0
    def test_proper_configuration(self):
        app = flask.Flask(__name__)
        BanditMiddleware().init_app(app)

        app.add_bandit("some_bandit",makeBandit("EpsilonGreedyBandit", epsilon=1.0))
        app.register_blueprint(self.bp)
        app_client = app.test_client()

        rv = app_client.get("/")
        assert parse_cookie(rv.headers["Set-Cookie"])["MAB"]

        assert "X-MAB-Debug" in rv.headers.keys()
        chosen_arm = self.get_arm(rv.headers)["some_bandit"]
        assert app.extensions['mab'].bandits["some_bandit"][chosen_arm]["pulls"] > 0
        assert json.loads(parse_cookie(rv.headers["Set-Cookie"])["MAB"])["some_bandit"] == chosen_arm

        app_client.get("/reward")
        assert app.extensions['mab'].bandits["some_bandit"][chosen_arm]["reward"] > 0
Пример #23
0
 def check_cookie(self, response, name):
     # Checks for existence of a cookie and verifies the value of it
     cookies = response.headers.getlist('Set-Cookie')
     for cookie in cookies:
         c_key, c_value = parse_cookie(cookie).items()[0]
         if c_key == name:
             return c_value
     # Cookie not found
     return False
Пример #24
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'})
Пример #25
0
    def __call__(self, environ, start_response):
        # Parse cookies from the WSGI environment
        encoded = parse_cookie(environ)

        # Decode the special zappa cookie if present
        if 'zappa' in encoded:
            decoded_zappa = base58.b58decode(encoded['zappa'])
            # Set the WSGI environment cookie to be the decoded value.
            environ[u'HTTP_COOKIE'] = decoded_zappa
            # Save the parsed cookies. We need to send them back on every update.
            request_cookies = parse_cookie(decoded_zappa)
        else:
            request_cookies = dict()


        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)

        # Call the wrapped WSGI-application with the modified WSGI environment
        # and propagate the response to caller
        return ClosingIterator(self.application(environ, injecting_start_response))
Пример #26
0
    def test_session_fixation(self):
        """Ensure if session is empty that a new session is given."""
        user1 = create_account("user1", "*****@*****.**", "Password")
        activate(user1)
        resp = self.client.post(url_for("auth.signin"), data={"username": "******", "password": "******"})

        session_id = None
        for header in resp.headers:
            if header[0] == "Set-Cookie":
                session_id = parse_cookie(header[1])["session"]
                rs.delete(session_id)

        resp = self.client.post(url_for("auth.signin"), data={"username": "******", "password": "******"})

        # Find the Set-Cookie header so we can parse it and check the session
        # identifier has been updated
        for header in resp.headers:
            if header[0] == "Set-Cookie":
                self.assertNotEqual(session_id, parse_cookie(header[1])["session"])
Пример #27
0
    def test_header_set_cookie_samesite(self):
        samesite = 'Strict'
        self.app.config['CSRF_COOKIE_SAMESITE'] = samesite
        self.csrf.init_app(self.app)

        with self.app.test_client() as client:
            res = client.get('/foo')
            cookie = res.headers.get('Set-Cookie')
            c = parse_cookie(cookie)
            self.assertEqual(c['SameSite'], samesite)
Пример #28
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'})
Пример #29
0
 def test_empty_keys_are_ignored(self):
     strict_eq(
         dict(http.parse_cookie(
             'first=IamTheFirst ; a=1; a=2 ;second=andMeTwo; ; '
         )),
         {
             'first': u'IamTheFirst',
             'a': u'2',
             'second': u'andMeTwo'
         }
     )
Пример #30
0
    def _get_session(self, environ):
        cookie = parse_cookie(environ.get("HTTP_COOKIE", ""))
        id = cookie.get(self.configuration["cookie"]["name"], None)

        if id is None:
            id = self._find_session_id(environ)

        if id:
            return self.store.get(id)
        else:
            return self.store.new()
Пример #31
0
def get_session(response):
    """ Return session cookie contents.
    This a base64 encoded json.
    Returns a dict
    """

    # Alas seems like if there are multiple set-cookie headers - we are on our own
    for index, h in enumerate(response.headers):
        if h[0] == "Set-Cookie":
            cookie = parse_cookie(response.headers[index][1])
            encoded_cookie = cookie.get("session", None)
            if encoded_cookie:
                serializer = URLSafeTimedSerializer(
                    "secret", serializer=TaggedJSONSerializer()
                )
                val = serializer.loads_unsafe(encoded_cookie)
                return val[1]
Пример #32
0
def _responses_callback(
    request: PreparedRequest,
    flask_app: Flask,
) -> Tuple[int, Dict[str, str | int | bool | None], bytes]:
    """
    Given a request to the flask app, send an equivalent request to an in
    memory fake of the flask app and return some key details of the
    response.

    :param request: The incoming request to pass onto the flask app.
    :param flask_app: The Flask application to pass requests to.
    :return: A tuple of status code, response headers and response data
        from the flask app.
    """
    test_client = flask_app.test_client()
    # See parameters at
    # https://werkzeug.palletsprojects.com/en/0.15.x/test/#werkzeug.test.EnvironBuilder
    cookie_string = request.headers.get('Cookie', '')
    cookie_list = cookie_string.split(';')
    cookie_list_no_empty = [item for item in cookie_list if item]
    request_cookies = [
        list(parse_cookie(cookie).items())[0]
        for cookie in cookie_list_no_empty
    ]
    cookies_dict = dict(request_cookies)

    for key, value in cookies_dict.items():
        test_client.set_cookie(
            server_name='',
            key=key,
            value=value,
        )

    environ_builder = werkzeug.test.EnvironBuilder(
        path=request.path_url,
        method=str(request.method),
        data=request.body,
        headers=dict(request.headers),
    )
    environ = environ_builder.get_environ()
    if 'Content-Length' in request.headers:
        environ['CONTENT_LENGTH'] = request.headers['Content-Length']
    response = test_client.open(environ)

    result = (response.status_code, dict(response.headers), response.data)
    return result
Пример #33
0
    def detect_and_clobber_dupe_cookies(self) -> Optional[Response]:
        """
        Detect and discard duplicate cookies.

        Legacy components have been known to generate dupe cookies, which
        causes all kinds of havoc. Here we check the request for duplicates
        of the session and permanent cookies and, if we find them, we blow
        them away and redirect back to /login.
        """
        # By default, werkzeug uses a dict-based struct that supports only a
        # single value per key. This isn't really up to speed with RFC 6265.
        # Luckily we can just pass in an alternate struct to parse_cookie()
        # that can cope with multiple values.
        raw_cookie = request.environ.get('HTTP_COOKIE', None)
        if raw_cookie is None:
            return None
        cookies = parse_cookie(raw_cookie, cls=MultiDict)
        classic_cookie_name = self.app.config['CLASSIC_COOKIE_NAME']
        perm_cookie_name = self.app.config['CLASSIC_PERMANENT_COOKIE_NAME']
        domain = self.app.config['AUTH_SESSION_COOKIE_DOMAIN']

        response = None  # If we return None, request is handled normally.
        now = datetime.now(UTC)
        for name in [classic_cookie_name, perm_cookie_name]:
            if len(cookies.getlist(name)) > 1:
                if response is None:
                    # The ui.login route may not exist on an application using
                    # this package, so we will fall back to the logout redirect
                    # URL if the login route is missing. ARXIVNG-2063
                    try:
                        target = url_for('ui.login')
                    except BuildError:
                        target = self.app.config['DEFAULT_LOGOUT_REDIRECT_URL']
                    response = make_response(redirect(target))
                response.set_cookie(name, '', max_age=0, expires=now)
                response.set_cookie(name,
                                    '',
                                    max_age=0,
                                    expires=now,
                                    domain=domain.lstrip('.'))
                response.set_cookie(name,
                                    '',
                                    max_age=0,
                                    expires=now,
                                    domain=domain)
        return response
Пример #34
0
 def check_pin_trust(self, environ):
     """Checks if the request passed the pin test.  This returns `True` if the
     request is trusted on a pin/cookie basis and returns `False` if not.
     Additionally if the cookie's stored pin hash is wrong it will return
     `None` so that appropriate action can be taken.
     """
     if self.pin is None:
         return True
     val = parse_cookie(environ).get(self.pin_cookie_name)
     if not val or '|' not in val:
         return False
     ts, pin_hash = val.split('|', 1)
     if not ts.isdigit():
         return False
     if pin_hash != hash_pin(self.pin):
         return None
     return (time.time() - PIN_TIME) < ts
Пример #35
0
def get_auth_cookies(user: "******") -> List[Dict[Any, Any]]:
    # Login with the user specified to get the reports
    with current_app.test_request_context("/login"):
        login_user(user)
        # A mock response object to get the cookie information from
        response = Response()
        current_app.session_interface.save_session(current_app, session,
                                                   response)

    cookies = []

    # Set the cookies in the driver
    for name, value in response.headers:
        if name.lower() == "set-cookie":
            cookie = parse_cookie(value)
            cookies.append(cookie["session"])
    return cookies
Пример #36
0
 def request_worker(test,iden,q):
     try:
         client = test.app.test_client()
         first_req = client.get("/show_btn_decorated")
         chosen_arm = json.loads(parse_cookie(first_req.headers["Set-Cookie"])["MAB"])["color_button"]
         assert first_req.headers['X-MAB-Debug'].split(';')[0].strip() == 'STORE'
         for i in xrange(400):
             req = client.get("/show_btn_decorated")
             #TODO: refactor this to regex
             assert req.headers['X-MAB-Debug'].split(';')[1].split(':')[1] == chosen_arm
             assert req.headers['X-MAB-Debug'].split(';')[0].strip() == 'SAVED'
         client.cookie_jar.clear()
         final_req = client.get("/show_btn_decorated")
         assert final_req.headers['X-MAB-Debug'].split(';')[0].strip() == 'STORE'
         q.put(True)
     except AssertionError,e:
         q.put(e)
Пример #37
0
def test_wrapper_support():
    req = Request.from_values()
    resp = Response()
    c = SecureCookie.load_cookie(req, secret_key=b"foo")
    assert c.new
    c["foo"] = 42
    assert c.secret_key == b"foo"
    c.save_cookie(resp)

    req = Request.from_values(
        headers={
            "Cookie": 'session="%s"'
            % parse_cookie(resp.headers["set-cookie"])["session"]
        }
    )
    c2 = SecureCookie.load_cookie(req, secret_key=b"foo")
    assert not c2.new
    assert c2 == c
Пример #38
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))
Пример #39
0
def test_cookie_probe_cookie_present(app):
    cookie_probe.init_app(app)

    @app.route('/')
    def error_route():
        return "<html>Success</html>"

    client = app.test_client()
    assert not client.cookie_jar  # i.e. empty

    response = client.get('/')

    assert response.status_code == 200
    assert any(
        name == app.config["DM_COOKIE_PROBE_COOKIE_NAME"]
        and value == app.config["DM_COOKIE_PROBE_COOKIE_VALUE"]
        for name, value in (tuple(parse_cookie(raw).items())[0]
                            for raw in response.headers.getlist("Set-Cookie")))
Пример #40
0
    def __call__(self, environ, start_response):
        adapter = self.ws.url_map.bind_to_environ(environ)
        try:
            handler, values = adapter.match()
            environment = environ['wsgi.websocket']
            cookie = None
            if 'HTTP_COOKIE' in environ:
                cookie = parse_cookie(environ['HTTP_COOKIE'])

            with self.app.app_context():
                with self.app.request_context(environ):

                    request.cookie = cookie

                    handler(environment, **values)
                    return []
        except (NotFound, KeyError):
            return self.wsgi_app(environ, start_response)
Пример #41
0
    def test_load_user_from_token(self):
        """
        A user is loaded if their token is provided to
        ``load_user_from_token``.
        """
        self.app.post('/signup',
                      content_type='application/json',
                      data=json.dumps(USER_DATA))
        response = self.app.post('/login',
                                 content_type='application/json',
                                 data=json.dumps(USER_DATA))
        cookies = response.headers.getlist('Set-Cookie')

        items = [list(parse_cookie(cookie).items())[0] for cookie in cookies]
        headers_dict = {key: value for key, value in items}
        token = headers_dict['remember_token']
        with app.app_context():
            user = load_user_from_id(user_id=USER_DATA['email'])
            self.assertEqual(load_user_from_token(auth_token=token), user)
Пример #42
0
def _get_auth_cookies() -> List["TypeConversionDict[Any, Any]"]:
    # Login with the user specified to get the reports
    with app.test_request_context():
        user = security_manager.find_user(config["EMAIL_REPORTS_USER"])
        login_user(user)

        # A mock response object to get the cookie information from
        response = Response()
        app.session_interface.save_session(app, session, response)

    cookies = []

    # Set the cookies in the driver
    for name, value in response.headers:
        if name.lower() == "set-cookie":
            cookie = parse_cookie(value)
            cookies.append(cookie["session"])

    return cookies
Пример #43
0
def get_session(cookie: http.Header,
                store: SessionStore,
                response_headers: http.ResponseHeaders) -> typing.Generator[http.Session, None, None]:
    if cookie:
        cookies = parse_cookie(cookie)
        session_id = cookies.get('session_id')
    else:
        session_id = None

    if session_id is not None:
        session = store.load(session_id)
    else:
        session = store.new()

    try:
        yield session
    finally:
        session_headers = store.save(session)
        response_headers.update(session_headers)
def test_that_login_returns_a_valid_token(client):
    """
    GIVEN a Flask application
    WHEN the `/api/auth/login` route is posted to (POST) with valid credentials
    THEN check that a valid token is sent through a cookie
    """
    route = '{}/login'.format(base_route)
    credentials = dict(username='******', password='******')
    response = client.post(route, data=credentials)

    # make sure the authentication token is set through a cookie
    cookies = response.headers.getlist('Set-Cookie')
    items = [list(parse_cookie(cookie).items())[0] for cookie in cookies]
    cookies_dict = {key: value for key, value in items}
    token = cookies_dict.get('access_token', '')

    token_regex = r'^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$'

    assert_that(token).matches(token_regex)
Пример #45
0
    def test_remember_me_cookie_set(self):
        """
        A "Remember Me" token is in the response header of a successful login
        with the value of ``User.get_auth_token`` for the logged in user.
        """
        self.app.post('/signup',
                      content_type='application/json',
                      data=json.dumps(USER_DATA))
        response = self.app.post('/login',
                                 content_type='application/json',
                                 data=json.dumps(USER_DATA))
        cookies = response.headers.getlist('Set-Cookie')

        items = [list(parse_cookie(cookie).items())[0] for cookie in cookies]
        headers_dict = {key: value for key, value in items}
        token = headers_dict['remember_token']
        with app.app_context():
            user = load_user_from_id(user_id=USER_DATA['email'])
            self.assertEqual(token, user.get_auth_token())
def test_that_logout_removes_token(client):
    """
    GIVEN a Flask application
    WHEN the `/api/auth/logout` route is posted to (POST) with valid credentials
    THEN check that the current auth token is being removed 
    """
    route = '{}/logout'.format(base_route)
    user = User.query.first()
    access_token = create_access_token(identity=user)

    client.set_cookie('localhost', 'access_token', access_token)
    response = client.post(route)

    cookie = response.headers.getlist('Set-Cookie').pop(0)
    _, cookie_expiration = list(parse_cookie(cookie).items())[1]
    today = datetime.today()
    cookie_expiration_date = datetime.strptime(
        cookie_expiration, '%a, %d-%b-%Y %H:%M:%S GMT')

    assert_that(cookie_expiration_date).is_before(today)
Пример #47
0
    def __call__(self, environ, start_response):
        adapter = self.ws.url_map.bind_to_environ(environ)
        try:
            handler, values = adapter.match()
            #logger.debug(f"handler: {handler}")
            #logger.debug(f"environ: {environ}")
            environment = environ['wsgi.websocket']
            cookie = None
            if 'HTTP_COOKIE' in environ:
                cookie = parse_cookie(environ['HTTP_COOKIE'])

            with self.app.app_context():
                with self.app.request_context(environ):
                    # add cookie to the request to have correct session handling
                    request.cookie = cookie
                    logger.debug(f"cookie: {cookie}")
                    handler(environment, **values)
                    return []
        except (NotFound, KeyError):
            return self.wsgi_app(environ, start_response)
Пример #48
0
    def get_auth_cookies(user: "******") -> Dict[str, str]:
        # Login with the user specified to get the reports
        with current_app.test_request_context("/login"):
            login_user(user)
            # A mock response object to get the cookie information from
            response = Response()
            current_app.session_interface.save_session(current_app, session, response)

        cookies = {}

        # Grab any "set-cookie" headers from the login response
        for name, value in response.headers:
            if name.lower() == "set-cookie":
                # This yields a MultiDict, which is ordered -- something like
                # MultiDict([('session', 'value-we-want), ('HttpOnly', ''), etc...
                # Therefore, we just need to grab the first tuple and add it to our
                # final dict
                cookie = parse_cookie(value)
                cookie_tuple = list(cookie.items())[0]
                cookies[cookie_tuple[0]] = cookie_tuple[1]

        return cookies
Пример #49
0
    def test_wsgi_middleware_unpackcookies(self):
        # Setting the cookies
        def simple_app(environ, start_response):
            status = '200 OK'
            response_headers = [('Set-Cookie', 'foo=123'),
                                ('Set-Cookie', 'bar=456'),
                                ('Set-Cookie', 'baz=789')]
            start_response(status, response_headers)
            return ['Set cookies!']

        # Wrap the app with the middleware
        app = ZappaWSGIMiddleware(simple_app)

        # Call with empty WSGI Environment
        resp = app(dict(), self._start_response)

        # Ensure the encoded zappa cookie is set
        self.assertEqual(self.headers[0][0], 'Set-Cookie')
        zappa_cookie = self.headers[0][1]
        self.assertTrue(zappa_cookie.startswith('zappa='))

        # Reads the hopefully decoded cookies
        def simple_app(environ, start_response):
            status = '200 OK'
            response_headers = []
            start_response(status, response_headers)
            return [environ['HTTP_COOKIE']]

        # Wrap the app with the middleware
        app = ZappaWSGIMiddleware(simple_app)

        # Call the app with the encoded cookie in the environment
        resp = app({'HTTP_COOKIE': zappa_cookie}, self._start_response)

        # Assert that the simple_app, received the decoded cookies
        excpected = {'foo': '123', 'bar': '456', 'baz': '789'}
        received = parse_cookie(''.join(resp))
        self.assertDictEqual(received, excpected)
Пример #50
0
    def __call__(self, environ, start_response):
        """
        A note about the zappa cookie: Only 1 cookie can be passed through API
        Gateway. Hence all cookies are packed into a special cookie, the
        zappa cookie. There are a number of problems with this:

            * updates of single cookies, when there are multiple present results
              in deletion of the ones that are not being updated.
            * expiration of cookies. The client no longer knows when cookies
              expires.

        The first is solved by unpacking the zappa cookie on each request and
        saving all incoming cookies. The response Set-Cookies are then used
        to update the saved cookies, which are packed and set as the zappa
        cookie.

        The second is solved by filtering cookies on their expiration time,
        only passing cookies that are still valid to the WSGI app.
        """
        self.start_response = start_response

        # Parse cookies from the WSGI environment
        parsed = parse_cookie(environ)
        parsed.pop('zappa', None)
        self.request_cookies = parsed
        environ[u'HTTP_COOKIE'] = parsed
        # Call the application with our modifier
        response = self.application(environ, self.encode_response)

        # If we have a redirect, smash in our response content.
        if self.redirect_content:
            response = [self.redirect_content for item in response]

        self.redirect_content = None  # Make sure that nothing is cached from a previous request

        # Return the response as a WSGI-safe iterator
        return ClosingIterator(response)
Пример #51
0
    def legacy_cookies(self) -> List[str]:
        """Gets list of legacy cookies.

        Duplicate cookies occur due to the browser sending both the
        cookies for both arxiv.org and sub.arxiv.org. If this is being
        served at sub.arxiv.org, there is no response that will cause
        the browser to alter its cookie store for arxiv.org. Duplicate
        cookies must be handled gracefully to for the domain and
        subdomain to coexist.

        The standard way to avoid this problem is to append part of
        the domain's name to the cookie key but this needs to work
        even if the configuration is not ideal.

        """
        # By default, werkzeug uses a dict-based struct that supports only a
        # single value per key. This isn't really up to speed with RFC 6265.
        # Luckily we can just pass in an alternate struct to parse_cookie()
        # that can cope with multiple values.
        raw_cookie = request.environ.get('HTTP_COOKIE', None)
        if raw_cookie is None:
            return []
        cookies = parse_cookie(raw_cookie, cls=MultiDict)
        return cookies.getlist(self.app.config['CLASSIC_COOKIE_NAME'])
Пример #52
0
 def _get_session_id(self, environ):
     cookie = parse_cookie(environ.get("HTTP_COOKIE", ""))
     return cookie.get(self.cookie_name, None)
Пример #53
0
 def get_value(self, environ):
     cookie = parse_cookie(environ['HTTP_COOKIE'])
     if self._key not in cookie:
         raise NoValue
     return cookie[self._key]
Пример #54
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'}
Пример #55
0
 def get_cookie_by_name(response, name):
     cookies = response.headers.getlist('Set-Cookie')
     for cookie in cookies:
         if name in parse_cookie(cookie):
             return parse_cookie(cookie)
     return None
Пример #56
0
 def test_cookie_unicode_parsing(self):
     # This is submitted by Firefox if you set a Unicode cookie.
     cookies = http.parse_cookie("fö=fö")
     assert cookies["fö"] == "fö"
Пример #57
0
 def test_cookie_unicode_parsing(self):
     # This is actually a correct test.  This is what is being submitted
     # by firefox if you set an unicode cookie and we get the cookie sent
     # in on Python 3 under PEP 3333.
     cookies = http.parse_cookie(u'fö=fö')
     assert cookies[u'fö'] == u'fö'
Пример #58
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ö'
Пример #59
0
def get(app, environ):
    store = app.config['ayame.session.store']
    c = http.parse_cookie(environ.get('HTTP_COOKIE', ''))
    sid = c.get(app.config['ayame.session.name'])
    return store.new() if sid is None else store.get(sid)
Пример #60
0
 def cookies(self) -> dict:
     return parse_cookie(self.headers.get('cookie'))