Exemple #1
0
def full_access_auth_header(
        full_access_authz_payload,  # pylint: disable=redefined-outer-name
) -> str:
    return Authorizer.sign_authz(
        full_access_authz_payload,
        SAMPLE_PRIVATE_KEY,
    )
Exemple #2
0
 def test_validate_one_with_expired(self,
                                    full_access_authz_payload) -> None:
     expired_timestamp = int(
         (datetime.utcnow() - timedelta(seconds=1)).timestamp())
     with pytest.raises(Unauthorized):
         Authorizer(
             Authorizer.sign_authz(
                 {
                     **full_access_authz_payload,
                     "exp": expired_timestamp,
                 },
                 SAMPLE_PRIVATE_KEY,
             ),
             "test_resource",
             "permission_name",
         )
Exemple #3
0
 def test_sign_authz(self) -> None:
     token = Authorizer.sign_authz({
         "allow": {
             ALL: ALL
         },
         "deny": {}
     }, SAMPLE_PRIVATE_KEY)
     assert token == EXPECTED_TOKEN
Exemple #4
0
 def test__init__(self, full_access_auth_header) -> None:
     authz = Authorizer(full_access_auth_header, "test_resource",
                        "permission_name")
     assert authz.allow == {ALL: ALL}
     assert authz.deny == {}
     assert authz.outcome == DENY
     assert authz.allowed_resource is None
     assert authz.allowed_resource is None
     assert authz.resource == "test_resource"
     assert authz.permission == "permission_name"
Exemple #5
0
 def test_expired_jwt(self) -> None:
     iat = int((datetime.utcnow() - timedelta(hours=12)).timestamp())
     exp = int((datetime.utcnow() - timedelta(hours=6)).timestamp())
     token_payload = {
         "exp": exp,
         "iat": iat,
         "iss": "test-issuer",
         "aud": "test-audience",
     }
     jwt_token = Authorizer.sign_authz(token_payload, SAMPLE_PRIVATE_KEY)
     with pytest.raises(Unauthorized,
                        match="Your token has expired. Please refresh it."):
         decode_jwt(jwt_token)
Exemple #6
0
 def test_missing_correct_audiences(
         self, caplog: pytest.LogCaptureFixture) -> None:
     iat = int(datetime.utcnow().timestamp())
     exp = int((datetime.utcnow() + timedelta(hours=6)).timestamp())
     token_payload = {
         "exp": exp,
         "iat": iat,
         "iss": "test-issuer",
         "aud": "test"
     }
     jwt_token = Authorizer.sign_authz(token_payload, SAMPLE_PRIVATE_KEY)
     with pytest.raises(Unauthorized):
         decode_jwt(jwt_token)
     assert "Failed decoding JWT with any of JWK - details" in caplog.text
Exemple #7
0
def limited_access_auth_header(
        full_access_authz_payload,  # pylint: disable=redefined-outer-name
) -> str:
    return Authorizer.sign_authz(
        {
            **full_access_authz_payload,
            "allow": {
                "test_res": {
                    "perm-name": {
                        "allow": "*"
                    }
                }
            },
            "deny": {},
        },
        SAMPLE_PRIVATE_KEY,
    )
Exemple #8
0
def check_permission(resource: Resource, permission_name: str) -> dict:
    """
    Check if requester has sufficient permissions to do something on specific resource.

    Raises if not.
    """
    base_permission_policy = resource.get_guest_authorization()
    if (authorization_header :=
            resource.request.headers.get("Authorization")) is None:
        if not base_permission_policy:
            raise Unauthorized("Authorization header missing or empty")

    authorizer = Authorizer(
        auth_jwt=authorization_header,
        resource_name=resource.get_name(),
        permission_name=permission_name,
        base_permission_policy=base_permission_policy,
    )
    authorizer.check_access()
    return authorizer.restrictions


def has_permission(resource: Resource, permission_name: str) -> bool:
    """
    Safe Check if requester has sufficient permissions to do something on specific resource.

    Does not raise.
    """
    try:
        check_permission(resource, permission_name)
    except (Unauthorized, PermissionDenied):
Exemple #9
0
 def _make_mocked_authorizer(token_payload: dict) -> Authorizer:
     with patch("lbz.authz.authorizer.decode_jwt", lambda _: token_payload):
         return Authorizer("xx", "test_resource", "permission_name")
Exemple #10
0
 def test_sign_authz_no_kid_error(self) -> None:
     with pytest.raises(ValueError,
                        match="private_key_jwk must have the 'kid' field"):
         Authorizer.sign_authz({}, private_key_jwk={})
Exemple #11
0
 def test_sign_authz_not_a_dict_error(self) -> None:
     with pytest.raises(ValueError,
                        match="private_key_jwk must be a jwk dict"):
         Authorizer.sign_authz({}, private_key_jwk="")
Exemple #12
0
 def test__repr__(self, full_access_auth_header) -> None:
     authz = Authorizer(full_access_auth_header, "test_resource",
                        "permission_name")
     assert repr(authz) == ("Authorizer(auth_jwt=<jwt>, "
                            "resource_name='test_resource', "
                            "permission_name='permission_name')")