コード例 #1
0
async def test_session_middleware_handling_of_expired_signature():
    app = FakeApplication()

    app.middlewares.append(SessionMiddleware("LOREM_IPSUM", session_max_age=1))

    @app.router.get("/")
    def home(request: Request):
        session = request.session

        assert isinstance(session, Session)
        session["foo"] = "Some value"

        return text("Hello, World")

    @app.router.get("/second")
    def second(request: Request):
        session = request.session

        assert "foo" not in session

        return text("Hello, World")

    await app.start()

    await app(
        get_example_scope(
            "GET",
            "/",
        ),
        MockReceive(),
        MockSend(),
    )

    response = app.response
    assert response.status == 200

    session_set_cookie = response.headers.get_single(b"Set-Cookie")
    assert session_set_cookie is not None

    cookie = parse_cookie(session_set_cookie)

    time.sleep(2)

    await app(
        get_example_scope(
            "GET",
            "/second",
            [
                [b"cookie", b"session=" + cookie.value.encode()],
            ],
        ),
        MockReceive(),
        MockSend(),
    )

    response = app.response
    assert response.status == 200

    session_set_cookie = response.headers.get_first(b"Set-Cookie")
    assert session_set_cookie is None
コード例 #2
0
async def test_session_middleware_with_encryptor(app, mock_receive, mock_send):
    app.middlewares.append(
        SessionMiddleware("LOREM_IPSUM",
                          encryptor=FernetEncryptor(Fernet.generate_key())))

    @app.router.get("/")
    def home(request: Request):
        session = request.session

        assert isinstance(session, Session)
        session["foo"] = "Some value"

        return text("Hello, World")

    @app.router.get("/second")
    def second(request: Request):
        session = request.session

        assert "foo" in session
        assert session["foo"] == "Some value"

        return text("Hello, World")

    await app.start()

    await app(
        get_example_scope(
            "GET",
            "/",
        ),
        mock_receive(),
        mock_send,
    )

    response = app.response
    assert response.status == 200

    session_set_cookie = response.headers.get_single(b"Set-Cookie")
    assert session_set_cookie is not None

    cookie = parse_cookie(session_set_cookie)

    await app(
        get_example_scope(
            "GET",
            "/second",
            [
                [b"cookie", b"session=" + cookie.value.encode()],
            ],
        ),
        mock_receive(),
        mock_send,
    )

    response = app.response
    assert response.status == 200

    session_set_cookie = response.headers.get_first(b"Set-Cookie")
    assert session_set_cookie is None
コード例 #3
0
async def test_session_middleware_handling_of_invalid_encrypted_signature():
    app = FakeApplication()

    app.middlewares.append(
        SessionMiddleware(
            "LOREM_IPSUM", encryptor=FernetEncryptor(Fernet.generate_key())
        )
    )

    @app.router.get("/")
    def home(request: Request):
        session = request.session

        assert isinstance(session, Session)
        assert len(session) == 0
        assert "user_id" not in session

        return text("Hello, World")

    await app.start()

    # arrange invalid session cookie
    impostor_middleware = SessionMiddleware(
        "LOREM_IPSUM", encryptor=FernetEncryptor(Fernet.generate_key())
    )

    forged_cookie = impostor_middleware.write_session(Session({"user_id": "hahaha"}))

    await app(
        get_example_scope(
            "GET",
            "/",
            [
                [b"cookie", b"session=" + forged_cookie.encode()],
            ],
        ),
        MockReceive(),
        MockSend(),
    )

    response = app.response
    assert response.status == 200
コード例 #4
0
async def test_session_middleware_handling_of_invalid_signature(
        app, mock_receive, mock_send):
    app.middlewares.append(SessionMiddleware("LOREM_IPSUM"))

    @app.router.get("/")
    def home(request: Request):
        session = request.session

        assert isinstance(session, Session)
        assert len(session) == 0
        assert "user_id" not in session

        return text("Hello, World")

    await app.start()

    # arrange invalid session cookie
    impostor_middleware = SessionMiddleware("DOLOR_SIT_AMET")

    forged_cookie = impostor_middleware.write_session(
        Session({"user_id": "hahaha"}))

    await app(
        get_example_scope(
            "GET",
            "/",
            [
                [b"cookie", b"session=" + forged_cookie.encode()],
            ],
        ),
        mock_receive(),
        mock_send,
    )

    response = app.response
    assert response.status == 200
コード例 #5
0
 def use_sessions(
     self,
     secret_key: str,
     *,
     session_cookie: str = "session",
     serializer: Optional[SessionSerializer] = None,
     signer: Optional[Signer] = None,
     encryptor: Optional[Encryptor] = None,
     session_max_age: Optional[int] = None,
 ) -> None:
     self._session_middleware = SessionMiddleware(
         secret_key=secret_key,
         session_cookie=session_cookie,
         serializer=serializer,
         signer=signer,
         encryptor=encryptor,
         session_max_age=session_max_age,
     )
コード例 #6
0
def test_exception_for_invalid_max_age():
    with pytest.raises(ValueError):
        SessionMiddleware("example", session_max_age=0)

    with pytest.raises(ValueError):
        SessionMiddleware("example", session_max_age=-10)