示例#1
0
    def test_permits_if_user_has_2fa(
        self,
        monkeypatch,
        owners_require_2fa,
        pypi_mandates_2fa,
        two_factor_requirement_enabled,
        two_factor_mandate_available,
        two_factor_mandate_enabled,
        db_request,
    ):
        db_request.registry.settings = {
            "warehouse.two_factor_requirement.enabled":
            two_factor_requirement_enabled,
            "warehouse.two_factor_mandate.available":
            two_factor_mandate_available,
            "warehouse.two_factor_mandate.enabled": two_factor_mandate_enabled,
        }
        user = pretend.stub(has_two_factor=True)
        db_request.user = user
        get_current_request = pretend.call_recorder(lambda: db_request)
        monkeypatch.setattr(security_policy, "get_current_request",
                            get_current_request)

        permits_result = Allowed("Because")
        backing_policy = pretend.stub(
            permits=pretend.call_recorder(lambda *a, **kw: permits_result))
        policy = security_policy.TwoFactorAuthorizationPolicy(
            policy=backing_policy)
        context = ProjectFactory.create(owners_require_2fa=owners_require_2fa,
                                        pypi_mandates_2fa=pypi_mandates_2fa)
        result = policy.permits(context, pretend.stub(), pretend.stub())

        assert result == permits_result
示例#2
0
    def test_flashes_if_context_requires_2fa_but_not_enabled(
            self, monkeypatch, db_request):
        db_request.registry.settings = {
            "warehouse.two_factor_mandate.enabled": False,
            "warehouse.two_factor_mandate.available": True,
            "warehouse.two_factor_requirement.enabled": True,
        }
        db_request.session.flash = pretend.call_recorder(lambda m, queue: None)
        db_request.user = pretend.stub(has_two_factor=False)
        get_current_request = pretend.call_recorder(lambda: db_request)
        monkeypatch.setattr(security_policy, "get_current_request",
                            get_current_request)

        permits_result = Allowed("Because")
        backing_policy = pretend.stub(
            permits=pretend.call_recorder(lambda *a, **kw: permits_result))
        policy = security_policy.TwoFactorAuthorizationPolicy(
            policy=backing_policy)
        context = ProjectFactory.create(
            owners_require_2fa=False,
            pypi_mandates_2fa=True,
        )
        result = policy.permits(context, pretend.stub(), pretend.stub())

        assert result == permits_result
        assert db_request.session.flash.calls == [
            pretend.call(
                "This project is included in PyPI's two-factor mandate "
                "for critical projects. In the future, you will be unable to "
                "perform this action without enabling 2FA for your account",
                queue="warning",
            ),
        ]
示例#3
0
    def permits(context: ILocation, principals: List[str], permission: str) \
            -> PermitsResult:
        if permission in principals:
            return Allowed("ALLOWED: permission {} present in principals "
                           "{}".format(permission, principals))

        return Denied("DENIED: permission {} not in principals "
                      "{}".format(permission, principals))
示例#4
0
    def test_permits_if_non_2fa_requireable_context(self, monkeypatch):
        request = pretend.stub()
        get_current_request = pretend.call_recorder(lambda: request)
        monkeypatch.setattr(security_policy, "get_current_request",
                            get_current_request)

        permits_result = Allowed("Because")
        backing_policy = pretend.stub(
            permits=pretend.call_recorder(lambda *a, **kw: permits_result))
        policy = security_policy.TwoFactorAuthorizationPolicy(
            policy=backing_policy)
        result = policy.permits(pretend.stub(), pretend.stub(), pretend.stub())

        assert result == permits_result
示例#5
0
 def permits(self, request, context, permission):
     """Return an instance of :class:`pyramid.security.Allowed` if a user
     of the given identity is allowed the ``permission`` in the current
     ``context``, else return an instance of
     :class:`pyramid.security.Denied`.
     """
     if isinstance(context, str):
         # We assume that context is the name of a package
         if request.access.has_permission(context, permission):
             return Allowed("Allowed by ACL")
         return Denied("Permission not granted")
     else:
         userid = self.authenticated_userid(request)
         principals = request.access.user_principals(userid)
         return self.acl_policy.permits(context, principals, permission)
示例#6
0
    def test_resuls_canrun(self, has_permission):
        from pyramid.security import Allowed
        has_permission.return_value = Allowed('Faked allowed')
        request = testing.DummyRequest()
        job = self.fake_job()
        views = InCompleteJobViews(job, request)
        response = views.results()

        self.assertEqual(
            response,
            dict(
                jobid='foo',
                run='bla',
                maxmslevel=3,
                canRun=True,
                job=job,
            ))
        has_permission.assert_called_with('run', job, request)
示例#7
0
def has_permission(request, permission, context=None):
    """ The default has_permission does care about the context,
        but it calls the callback (in our case 'groupfinder') without the correct
        context. This methods hacks in the correct context. Keep it here until
        this has been fixed in Pyramid."""
    if context is None:
        context = request.context
    reg = request.registry
    authn_policy = reg.queryUtility(IAuthenticationPolicy)
    if authn_policy is None:
        return Allowed('No authentication policy in use.')
    authz_policy = reg.queryUtility(IAuthorizationPolicy)
    if authz_policy is None:
        raise ValueError('Authentication policy registered without '
                         'authorization policy')  # should never happen
    with authz_context(context, request):
        principals = authn_policy.effective_principals(request)
        return authz_policy.permits(context, principals, permission)
示例#8
0
 def has_permission(self, permission, context=None):
     if context is None:
         context = self.context
     reg = self.registry
     authn_policy = reg.queryUtility(IAuthenticationPolicy)
     if authn_policy is None:
         return Allowed('No authentication policy in use.')
     authz_policy = reg.queryUtility(IAuthorizationPolicy)
     if authz_policy is None:
         raise ValueError('Authentication policy registered without '
                          'authorization policy')  # should never happen
     principals = authn_policy.effective_principals(self)
     if is_generator(principals):
         principals = yield from principals
     permits = authz_policy.permits(context, principals, permission)
     if is_generator(permits):
         permits = yield from permits
     return permits
示例#9
0
 def has_permission(self, permission, context=None):
     if context is None:
         context = self.context  # pylint: disable=no-member
     try:
         reg = self.registry
     except AttributeError:
         reg = get_current_registry()
     authn_policy = reg.queryUtility(IAuthenticationPolicy)
     if authn_policy is None:
         return Allowed('No authentication policy in use.')
     authz_policy = reg.queryUtility(IAuthorizationPolicy)
     if authz_policy is None:
         raise ValueError('Authentication policy registered without '
                          'authorization policy')  # should never happen
     try:
         principals = authn_policy.effective_principals(self,
                                                        context=context)
     except TypeError:
         principals = authn_policy.effective_principals(self)
     return authz_policy.permits(context, principals, permission)
示例#10
0
    def permits(self, context, principals, permission):
        log.info('AuthorizationPolicy::permits()')
        if principals is not None:
            for p in principals:
                if (p != Everyone):
                    try:
                        result = self._provider.user_has_permission(p, permission)
                        # result = self._provider.query(
                        #     'user.has_permission',
                        #     (p, permission)
                        # )
                        (allowed, ) = result['result'][0]
                        if (allowed):
                            return Allowed('Allowed')
                        else:
                            log.debug('User %s is missing permission %s' % (p, permission))
                            return Denied('Denied')
                    except Exception as e:
                        log.error(e)

        return Denied('Denied')
示例#11
0
    def test_permits_if_context_does_not_require_2fa(self, monkeypatch,
                                                     db_request):
        db_request.registry.settings = {
            "warehouse.two_factor_mandate.enabled": True,
            "warehouse.two_factor_mandate.available": True,
            "warehouse.two_factor_requirement.enabled": True,
        }
        get_current_request = pretend.call_recorder(lambda: db_request)
        monkeypatch.setattr(auth_policy, "get_current_request",
                            get_current_request)

        permits_result = Allowed("Because")
        backing_policy = pretend.stub(
            permits=pretend.call_recorder(lambda *a, **kw: permits_result))
        policy = auth_policy.TwoFactorAuthorizationPolicy(
            policy=backing_policy)
        context = ProjectFactory.create(
            owners_require_2fa=False,
            pypi_mandates_2fa=False,
        )
        result = policy.permits(context, pretend.stub(), pretend.stub())

        assert result == permits_result
示例#12
0
    def test_denies_if_2fa_is_required_but_user_doesnt_have_2fa(
        self,
        monkeypatch,
        owners_require_2fa,
        pypi_mandates_2fa,
        reason,
        db_request,
    ):
        db_request.registry.settings = {
            "warehouse.two_factor_requirement.enabled": owners_require_2fa,
            "warehouse.two_factor_mandate.enabled": pypi_mandates_2fa,
        }
        user = pretend.stub(has_two_factor=False)
        db_request.user = user
        get_current_request = pretend.call_recorder(lambda: db_request)
        monkeypatch.setattr(security_policy, "get_current_request",
                            get_current_request)

        permits_result = Allowed("Because")
        backing_policy = pretend.stub(
            permits=pretend.call_recorder(lambda *a, **kw: permits_result))
        policy = security_policy.TwoFactorAuthorizationPolicy(
            policy=backing_policy)
        context = ProjectFactory.create(owners_require_2fa=owners_require_2fa,
                                        pypi_mandates_2fa=pypi_mandates_2fa)
        result = policy.permits(context, pretend.stub(), pretend.stub())

        summary = {
            "owners_require_2fa":
            ("This project requires two factor authentication to be enabled "
             "for all contributors.", ),
            "pypi_mandates_2fa":
            ("PyPI requires two factor authentication to be enabled "
             "for all contributors to this project.", ),
        }[reason]

        assert result == WarehouseDenied(summary, reason="two_factor_required")
示例#13
0
 def permits(self, request, context, permission):
     userid = self.authenticated_userid(request)
     if userid and permission == 'foo':
         return Allowed('')
     else:
         return Denied('')
示例#14
0
 def permits(self, context, principals, permission):
     if 'bob' in principals and permission == 'foo':
         return Allowed('')
     else:
         return Denied('')
示例#15
0
 def permits(self, request, context, identity, permission):
     if identity and permission == 'foo':
         return Allowed('')
     else:
         return Denied('')