Esempio n. 1
0
    def test_read_token_from_header(self, app, db, user_class, client):
        """
        This test verifies that a token may be properly read from a flask
        request's header using the configuration settings for header name and
        type
        """
        guard = Praetorian(app, user_class)
        the_dude = user_class(
            username='******',
            password=guard.encrypt_password('abides'),
            roles='admin,operator',
        )
        db.session.add(the_dude)
        db.session.commit()

        moment = pendulum.parse('2017-05-21 18:39:55')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(the_dude)

        client.get(
            '/unprotected',
            headers={
                'Content-Type': 'application/json',
                DEFAULT_JWT_HEADER_NAME: DEFAULT_JWT_HEADER_TYPE + ' ' + token,
            },
        )

        assert guard.read_token_from_header() == token
Esempio n. 2
0
 def test_encode_jwt_token(self, app, user_class):
     """
     This test verifies that the encode_jwt_token correctly encodes jwt
     data based on a user instance
     """
     guard = Praetorian(app, user_class)
     the_dude = user_class(
         username='******',
         password=guard.encrypt_password('abides'),
         roles='admin,operator',
     )
     moment = pendulum.parse('2017-05-21 18:39:55')
     with freezegun.freeze_time(moment):
         token = guard.encode_jwt_token(the_dude)
         token_data = jwt.decode(
             token, guard.encode_key, algorithms=guard.allowed_algorithms,
         )
         assert token_data['iat'] == moment.int_timestamp
         assert token_data['exp'] == (
             moment + DEFAULT_JWT_ACCESS_LIFESPAN
         ).int_timestamp
         assert token_data['rf_exp'] == (
             moment + DEFAULT_JWT_REFRESH_LIFESPAN
         ).int_timestamp
         assert token_data['id'] == the_dude.id
         assert token_data['rls'] == 'admin,operator'
Esempio n. 3
0
    def test_read_token_from_header(self, app, db, user_class, client):
        """
        This test verifies that a token may be properly read from a flask
        request's header using the configuration settings for header name and
        type
        """
        guard = Praetorian(app, user_class)
        the_dude = user_class(
            username="******",
            password=guard.hash_password("abides"),
            roles="admin,operator",
        )
        db.session.add(the_dude)
        db.session.commit()

        with plummet.frozen_time('2017-05-21 18:39:55'):
            token = guard.encode_jwt_token(the_dude)

        client.get(
            "/unprotected",
            headers={
                "Content-Type": "application/json",
                DEFAULT_JWT_HEADER_NAME: DEFAULT_JWT_HEADER_TYPE + " " + token,
            },
        )

        assert guard.read_token_from_header() == token
        assert guard.read_token() == token
Esempio n. 4
0
    def test_get_user_from_registration_token(self, app, user_class, db):
        """
        This test verifies that a user can be extracted from an email based
        registration token. Also verifies that a token that has expired
        cannot be used to fetch a user. Also verifies that a registration
        token may not be refreshed
        """
        app.config['TESTING'] = True
        default_guard = Praetorian(app, user_class)

        # create our default test user
        the_dude = user_class(
            username='******',
            email='*****@*****.**',
            password=default_guard.hash_password('abides'),
        )
        db.session.add(the_dude)
        db.session.commit()

        reg_token = default_guard.encode_jwt_token(
            the_dude,
            bypass_user_check=True,
            is_registration_token=True,
        )
        extracted_user = default_guard.get_user_from_registration_token(
            reg_token)
        assert extracted_user == the_dude
        """
           test to ensure a registration token that is expired
               sets off an 'ExpiredAccessError' exception
        """
        moment = pendulum.parse('2019-01-30 16:30:00')
        with freezegun.freeze_time(moment):
            expired_reg_token = default_guard.encode_jwt_token(
                the_dude,
                bypass_user_check=True,
                override_access_lifespan=pendulum.Duration(minutes=1),
                is_registration_token=True,
            )

        moment = pendulum.parse('2019-01-30 16:40:00')
        with freezegun.freeze_time(moment):
            with pytest.raises(ExpiredAccessError):
                default_guard.get_user_from_registration_token(
                    expired_reg_token)
Esempio n. 5
0
    def test_refresh_jwt_token(self, app, db, user_class):
        """
        This test  verifies that the refresh_jwt_token properly generates
        a refreshed jwt token. It ensures that a token who's access permission
        has not expired may not be refreshed. It also ensures that a token
        who's access permission has expired must not have an expired refresh
        permission for a new token to be issued
        """
        guard = Praetorian(app, user_class)
        the_dude = user_class(
            username='******',
            password=guard.encrypt_password('abides'),
            roles='admin,operator',
        )
        db.session.add(the_dude)
        db.session.commit()
        moment = pendulum.parse('2017-05-21 18:39:55')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(the_dude)

        new_moment = (
            pendulum.parse('2017-05-21 18:39:55')
            .add_timedelta(DEFAULT_JWT_ACCESS_LIFESPAN)
            .add(minutes=1)
        )
        with freezegun.freeze_time(new_moment):
            new_token = guard.refresh_jwt_token(token)
            new_token_data = jwt.decode(
                new_token, guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert new_token_data['iat'] == new_moment.int_timestamp
            assert new_token_data['exp'] == (
                new_moment + DEFAULT_JWT_ACCESS_LIFESPAN
            ).int_timestamp
            assert new_token_data['rf_exp'] == (
                moment + DEFAULT_JWT_REFRESH_LIFESPAN
            ).int_timestamp
            assert new_token_data['id'] == the_dude.id
            assert new_token_data['rls'] == 'admin,operator'
Esempio n. 6
0
    def test_read_token_from_cookie(self, app, db, user_class, client,
                                    use_cookie):
        """
        This test verifies that a token may be properly read from a flask
        request's cookies using the configuration settings for cookie
        """
        guard = Praetorian(app, user_class)
        the_dude = user_class(
            username="******",
            password=guard.hash_password("abides"),
            roles="admin,operator",
        )
        db.session.add(the_dude)
        db.session.commit()

        with plummet.frozen_time('2017-05-21 18:39:55'):
            token = guard.encode_jwt_token(the_dude)
            with use_cookie(token):
                client.get("/unprotected", )

        assert guard.read_token_from_cookie() == token
        assert guard.read_token() == token
Esempio n. 7
0
    def test_read_token_from_cookie(self, app, db, user_class, client):
        """
        This test verifies that a token may be properly read from a flask
        request's cookies using the configuration settings for cookie
        """
        guard = Praetorian(app, user_class)
        the_dude = user_class(
            username='******',
            password=guard.hash_password('abides'),
            roles='admin,operator',
        )
        db.session.add(the_dude)
        db.session.commit()

        moment = pendulum.parse('2017-05-21 18:39:55')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(the_dude)

        client.set_cookie('localhost', DEFAULT_JWT_COOKIE_NAME, token)
        client.get('/unprotected', )

        assert guard.read_token_from_cookie() == token
Esempio n. 8
0
    def test_refresh_jwt_token(
        self,
        app,
        db,
        user_class,
        validating_user_class,
    ):
        """
        This test::
            * verifies that the refresh_jwt_token properly generates
              a refreshed jwt token.
            * ensures that a token who's access permission has not expired may
              not be refreshed.
            * ensures that a token who's access permission has expired must not
              have an expired refresh permission for a new token to be issued.
            * ensures that if an override_access_lifespan argument is supplied
              that it is used instead of the instance's access_lifespan.
            * ensures that the access_lifespan may not exceed the refresh
              lifespan.
            * ensures that if the user_class has the instance method
              validate(), it is called an any exceptions it raises are wrapped
              in an InvalidUserError.
            * verifies that if a user is no longer identifiable that a
              MissingUserError is raised
            * verifies that any custom claims in the original token's
              payload are also packaged in the new token's payload
        """
        guard = Praetorian(app, user_class)
        the_dude = user_class(
            username='******',
            password=guard.encrypt_password('abides'),
            roles='admin,operator',
        )
        db.session.add(the_dude)
        db.session.commit()

        moment = pendulum.parse('2017-05-21 18:39:55')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(the_dude)
        new_moment = (pendulum.parse('2017-05-21 18:39:55') +
                      pendulum.Duration(**DEFAULT_JWT_ACCESS_LIFESPAN) +
                      pendulum.Duration(minutes=1))
        with freezegun.freeze_time(new_moment):
            new_token = guard.refresh_jwt_token(token)
            new_token_data = jwt.decode(
                new_token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert new_token_data['iat'] == new_moment.int_timestamp
            assert new_token_data['exp'] == (
                new_moment +
                pendulum.Duration(**DEFAULT_JWT_ACCESS_LIFESPAN)).int_timestamp
            assert new_token_data['rf_exp'] == (moment + pendulum.Duration(
                **DEFAULT_JWT_REFRESH_LIFESPAN)).int_timestamp
            assert new_token_data['id'] == the_dude.id
            assert new_token_data['rls'] == 'admin,operator'

        moment = pendulum.parse('2017-05-21 18:39:55')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(the_dude)
        new_moment = (pendulum.parse('2017-05-21 18:39:55') +
                      pendulum.Duration(**DEFAULT_JWT_ACCESS_LIFESPAN) +
                      pendulum.Duration(minutes=1))
        with freezegun.freeze_time(new_moment):
            new_token = guard.refresh_jwt_token(
                token,
                override_access_lifespan=pendulum.Duration(hours=2),
            )
            new_token_data = jwt.decode(
                new_token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert new_token_data['exp'] == (
                new_moment + pendulum.Duration(hours=2)).int_timestamp

        moment = pendulum.parse('2017-05-21 18:39:55')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(
                the_dude,
                override_refresh_lifespan=pendulum.Duration(hours=2),
                override_access_lifespan=pendulum.Duration(minutes=30),
            )
        new_moment = moment + pendulum.Duration(minutes=31)
        with freezegun.freeze_time(new_moment):
            new_token = guard.refresh_jwt_token(
                token,
                override_access_lifespan=pendulum.Duration(hours=2),
            )
            new_token_data = jwt.decode(
                new_token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert new_token_data['exp'] == new_token_data['rf_exp']

        expiring_interval = (pendulum.Duration(**DEFAULT_JWT_ACCESS_LIFESPAN) +
                             pendulum.Duration(minutes=1))
        validating_guard = Praetorian(app, validating_user_class)
        brandt = validating_user_class(
            username='******',
            password=guard.encrypt_password("can't watch"),
            is_active=True,
        )
        db.session.add(brandt)
        db.session.commit()
        moment = pendulum.parse('2017-05-21 18:39:55')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(brandt)
        new_moment = moment + expiring_interval
        with freezegun.freeze_time(new_moment):
            validating_guard.refresh_jwt_token(token)
        brandt.is_active = False
        db.session.merge(brandt)
        db.session.commit()
        new_moment = new_moment + expiring_interval
        with freezegun.freeze_time(new_moment):
            with pytest.raises(InvalidUserError) as err_info:
                validating_guard.refresh_jwt_token(token)
        expected_message = 'The user is not valid or has had access revoked'
        assert expected_message in str(err_info.value)

        expiring_interval = (pendulum.Duration(**DEFAULT_JWT_ACCESS_LIFESPAN) +
                             pendulum.Duration(minutes=1))
        guard = Praetorian(app, user_class)
        bunny = user_class(
            username='******',
            password=guard.encrypt_password("can't blow that far"),
        )
        db.session.add(bunny)
        db.session.commit()
        moment = pendulum.parse('2017-05-21 18:39:55')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(bunny)
        db.session.delete(bunny)
        db.session.commit()
        new_moment = moment + expiring_interval
        with freezegun.freeze_time(new_moment):
            with pytest.raises(MissingUserError) as err_info:
                validating_guard.refresh_jwt_token(token)
        expected_message = 'Could not find the requested user'
        assert expected_message in str(err_info.value)

        moment = pendulum.parse('2018-08-14 09:05:24')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(
                the_dude,
                duder='brief',
                el_duderino='not brief',
            )
        new_moment = (pendulum.parse('2018-08-14 09:05:24') +
                      pendulum.Duration(**DEFAULT_JWT_ACCESS_LIFESPAN) +
                      pendulum.Duration(minutes=1))
        with freezegun.freeze_time(new_moment):
            new_token = guard.refresh_jwt_token(token)
            new_token_data = jwt.decode(
                new_token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert new_token_data['iat'] == new_moment.int_timestamp
            assert new_token_data['exp'] == (
                new_moment +
                pendulum.Duration(**DEFAULT_JWT_ACCESS_LIFESPAN)).int_timestamp
            assert new_token_data['rf_exp'] == (moment + pendulum.Duration(
                **DEFAULT_JWT_REFRESH_LIFESPAN)).int_timestamp
            assert new_token_data['id'] == the_dude.id
            assert new_token_data['rls'] == 'admin,operator'
            assert new_token_data['duder'] == 'brief'
            assert new_token_data['el_duderino'] == 'not brief'
Esempio n. 9
0
    def test_encode_jwt_token(self, app, user_class, validating_user_class):
        """
        This test::
            * verifies that the encode_jwt_token correctly encodes jwt
              data based on a user instance.
            * verifies that if a user specifies an override for the access
              lifespan it is used in lieu of the instance's access_lifespan.
            * verifies that the access_lifespan cannot exceed the refresh
              lifespan.
            * ensures that if the user_class has the instance method
              validate(), it is called an any exceptions it raises are wrapped
              in an InvalidUserError
            * verifies that custom claims may be encoded in the token and
              validates that the custom claims do not collide with reserved
              claims
        """
        guard = Praetorian(app, user_class)
        the_dude = user_class(
            username='******',
            password=guard.encrypt_password('abides'),
            roles='admin,operator',
        )
        moment = pendulum.parse('2017-05-21 18:39:55')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(the_dude)
            token_data = jwt.decode(
                token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert token_data['iat'] == moment.int_timestamp
            assert token_data['exp'] == (
                moment +
                pendulum.Duration(**DEFAULT_JWT_ACCESS_LIFESPAN)).int_timestamp
            assert token_data['rf_exp'] == (moment + pendulum.Duration(
                **DEFAULT_JWT_REFRESH_LIFESPAN)).int_timestamp
            assert token_data['id'] == the_dude.id
            assert token_data['rls'] == 'admin,operator'

        moment = pendulum.parse('2017-05-21 18:39:55')
        override_access_lifespan = pendulum.Duration(minutes=1)
        override_refresh_lifespan = pendulum.Duration(hours=1)
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(
                the_dude,
                override_access_lifespan=override_access_lifespan,
                override_refresh_lifespan=override_refresh_lifespan,
            )
            token_data = jwt.decode(
                token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert token_data['iat'] == moment.int_timestamp
            assert token_data['exp'] == (
                moment + override_access_lifespan).int_timestamp
            assert token_data['rf_exp'] == (
                moment + override_refresh_lifespan).int_timestamp
            assert token_data['id'] == the_dude.id
            assert token_data['rls'] == 'admin,operator'

        moment = pendulum.parse('2017-05-21 18:39:55')
        override_access_lifespan = pendulum.Duration(hours=1)
        override_refresh_lifespan = pendulum.Duration(minutes=1)
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(
                the_dude,
                override_access_lifespan=override_access_lifespan,
                override_refresh_lifespan=override_refresh_lifespan,
            )
            token_data = jwt.decode(
                token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert token_data['iat'] == moment.int_timestamp
            assert token_data['exp'] == token_data['rf_exp']
            assert token_data['rf_exp'] == (
                moment + override_refresh_lifespan).int_timestamp
            assert token_data['id'] == the_dude.id
            assert token_data['rls'] == 'admin,operator'

        validating_guard = Praetorian(app, validating_user_class)
        brandt = validating_user_class(
            username='******',
            password=guard.encrypt_password("can't watch"),
            is_active=True,
        )
        validating_guard.encode_jwt_token(brandt)
        brandt.is_active = False
        with pytest.raises(InvalidUserError) as err_info:
            validating_guard.encode_jwt_token(brandt)
        expected_message = 'The user is not valid or has had access revoked'
        assert expected_message in str(err_info.value)

        moment = pendulum.parse('2018-08-18 08:55:12')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(
                the_dude,
                duder='brief',
                el_duderino='not brief',
            )
            token_data = jwt.decode(
                token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert token_data['iat'] == moment.int_timestamp
            assert token_data['exp'] == (
                moment +
                pendulum.Duration(**DEFAULT_JWT_ACCESS_LIFESPAN)).int_timestamp
            assert token_data['rf_exp'] == (moment + pendulum.Duration(
                **DEFAULT_JWT_REFRESH_LIFESPAN)).int_timestamp
            assert token_data['id'] == the_dude.id
            assert token_data['rls'] == 'admin,operator'
            assert token_data['duder'] == 'brief'
            assert token_data['el_duderino'] == 'not brief'

        with pytest.raises(ClaimCollisionError) as err_info:
            guard.encode_jwt_token(the_dude, exp='nice marmot')
        expected_message = 'custom claims collide'
        assert expected_message in str(err_info.value)
Esempio n. 10
0
    def test_encode_jwt_token(self, app, user_class, validating_user_class):
        """
        This test::
            * verifies that the encode_jwt_token correctly encodes jwt
              data based on a user instance.
            * verifies that if a user specifies an override for the access
              lifespan it is used in lieu of the instance's access_lifespan.
            * verifies that the access_lifespan cannot exceed the refresh
              lifespan.
            * ensures that if the user_class has the instance method
              validate(), it is called an any exceptions it raises are wrapped
              in an InvalidUserError
            * verifies that custom claims may be encoded in the token and
              validates that the custom claims do not collide with reserved
              claims
        """
        guard = Praetorian(app, user_class)
        the_dude = user_class(
            username="******",
            password=guard.hash_password("abides"),
            roles="admin,operator",
        )
        moment = plummet.momentize('2017-05-21 18:39:55')
        with plummet.frozen_time(moment):
            token = guard.encode_jwt_token(the_dude)
            token_data = jwt.decode(
                token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert token_data["iat"] == moment.int_timestamp
            assert (token_data["exp"] == (
                moment + DEFAULT_JWT_ACCESS_LIFESPAN).int_timestamp)
            assert (token_data[REFRESH_EXPIRATION_CLAIM] == (
                moment + DEFAULT_JWT_REFRESH_LIFESPAN).int_timestamp)
            assert token_data["id"] == the_dude.id
            assert token_data["rls"] == "admin,operator"

        override_access_lifespan = pendulum.Duration(minutes=1)
        override_refresh_lifespan = pendulum.Duration(hours=1)
        moment = plummet.momentize('2017-05-21 18:39:55')
        with plummet.frozen_time(moment):
            token = guard.encode_jwt_token(
                the_dude,
                override_access_lifespan=override_access_lifespan,
                override_refresh_lifespan=override_refresh_lifespan,
            )
            token_data = jwt.decode(
                token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert token_data["iat"] == moment.int_timestamp
            assert (token_data["exp"] == (
                moment + override_access_lifespan).int_timestamp)
            assert (token_data[REFRESH_EXPIRATION_CLAIM] == (
                moment + override_refresh_lifespan).int_timestamp)
            assert token_data["id"] == the_dude.id
            assert token_data["rls"] == "admin,operator"

        override_access_lifespan = pendulum.Duration(hours=1)
        override_refresh_lifespan = pendulum.Duration(minutes=1)
        moment = plummet.momentize('2017-05-21 18:39:55')
        with plummet.frozen_time(moment):
            token = guard.encode_jwt_token(
                the_dude,
                override_access_lifespan=override_access_lifespan,
                override_refresh_lifespan=override_refresh_lifespan,
            )
            token_data = jwt.decode(
                token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert token_data["iat"] == moment.int_timestamp
            assert token_data["exp"] == token_data[REFRESH_EXPIRATION_CLAIM]
            assert (token_data[REFRESH_EXPIRATION_CLAIM] == (
                moment + override_refresh_lifespan).int_timestamp)
            assert token_data["id"] == the_dude.id
            assert token_data["rls"] == "admin,operator"

        validating_guard = Praetorian(app, validating_user_class)
        brandt = validating_user_class(
            username="******",
            password=guard.hash_password("can't watch"),
            is_active=True,
        )
        validating_guard.encode_jwt_token(brandt)
        brandt.is_active = False
        with pytest.raises(InvalidUserError) as err_info:
            validating_guard.encode_jwt_token(brandt)
        expected_message = "The user is not valid or has had access revoked"
        assert expected_message in str(err_info.value)

        moment = plummet.momentize('2018-08-18 08:55:12')
        with plummet.frozen_time(moment):
            token = guard.encode_jwt_token(
                the_dude,
                duder="brief",
                el_duderino="not brief",
            )
            token_data = jwt.decode(
                token,
                guard.encode_key,
                algorithms=guard.allowed_algorithms,
            )
            assert token_data["iat"] == moment.int_timestamp
            assert (token_data["exp"] == (
                moment + DEFAULT_JWT_ACCESS_LIFESPAN).int_timestamp)
            assert (token_data[REFRESH_EXPIRATION_CLAIM] == (
                moment + DEFAULT_JWT_REFRESH_LIFESPAN).int_timestamp)
            assert token_data["id"] == the_dude.id
            assert token_data["rls"] == "admin,operator"
            assert token_data["duder"] == "brief"
            assert token_data["el_duderino"] == "not brief"

        with pytest.raises(ClaimCollisionError) as err_info:
            guard.encode_jwt_token(the_dude, exp="nice marmot")
        expected_message = "custom claims collide"
        assert expected_message in str(err_info.value)