Skip to content

Commit

Permalink
Improve error types and messages (#154)
Browse files Browse the repository at this point in the history
Signed-off-by: Max Lambrecht <[email protected]>
  • Loading branch information
maxlambrecht authored Mar 26, 2024
1 parent 89384c0 commit 55f8f3d
Show file tree
Hide file tree
Showing 41 changed files with 670 additions and 921 deletions.
39 changes: 39 additions & 0 deletions spiffe/src/spiffe/bundle/jwt_bundle/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""
(C) Copyright 2021 Hewlett Packard Enterprise Development LP
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
"""

"""
This module handles JWT bundle exceptions.
"""

from spiffe.errors import PySpiffeError


class JwtBundleError(PySpiffeError):
"""Exception raised for JwtBundle module related errors."""


class ParseJWTBundleError(JwtBundleError):
"""Error raised when unable to parse a JWT bundle from bytes."""

def __init__(self, detail: str) -> None:
super().__init__(f'Error parsing JWT bundle: {detail}')


class AuthorityNotFoundError(JwtBundleError):
"""Error raised when an authority is not found for a given key ID."""

def __init__(self, key_id: str) -> None:
super().__init__(f'Authority not found for key ID: {key_id}')
68 changes: 0 additions & 68 deletions spiffe/src/spiffe/bundle/jwt_bundle/exceptions.py

This file was deleted.

18 changes: 8 additions & 10 deletions spiffe/src/spiffe/bundle/jwt_bundle/jwt_bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
from cryptography.hazmat.primitives.asymmetric import ec, rsa, dsa, ed25519, ed448

from spiffe.spiffe_id.spiffe_id import TrustDomain
from spiffe.bundle.jwt_bundle.exceptions import JwtBundleError, ParseJWTBundleError
from spiffe.exceptions import ArgumentError
from spiffe.bundle.jwt_bundle.errors import JwtBundleError, ParseJWTBundleError
from spiffe.errors import ArgumentError

_PUBLIC_KEY_TYPES = Union[
dsa.DSAPublicKey,
Expand Down Expand Up @@ -118,20 +118,18 @@ def parse(cls, trust_domain: TrustDomain, bundle_bytes: bytes) -> 'JwtBundle':

try:
jwks = PyJWKSet.from_json(bundle_bytes.decode('utf-8'))
except InvalidKeyError as ike:
except InvalidKeyError as err:
raise ParseJWTBundleError(str(err)) from err
except (JSONDecodeError, AttributeError) as err:
raise ParseJWTBundleError(
'Cannot parse jwks from bundle_bytes: ' + str(ike)
)
except (JSONDecodeError, AttributeError):
raise ParseJWTBundleError(
'Cannot parse jwks. bundle_bytes does not represent a valid jwks'
)
'"bundle_bytes" does not represent a valid jwks'
) from err

jwt_authorities = {}
for jwk in jwks.keys:
if not jwk.key_id:
raise ParseJWTBundleError(
'Error adding authority from JWKS: keyID cannot be empty'
'Error adding authority from JWKS: "keyID" cannot be empty'
)

jwt_authorities[jwk.key_id] = jwk.key
Expand Down
46 changes: 46 additions & 0 deletions spiffe/src/spiffe/bundle/x509_bundle/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""
(C) Copyright 2021 Hewlett Packard Enterprise Development LP
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
"""

"""
This module defines X.509 Bundle exceptions.
"""

from spiffe.errors import PySpiffeError


class X509BundleError(PySpiffeError):
"""Exception raised for X509Bundle module related errors."""


class ParseX509BundleError(X509BundleError):
"""Error raised when unable to parse an X.509 bundle from bytes."""

def __init__(self, detail: str) -> None:
super().__init__(f'Error parsing X.509 bundle: {detail}')


class LoadX509BundleError(X509BundleError):
"""Error raised when unable to load an X.509 bundle from a file."""

def __init__(self, path: str) -> None:
super().__init__(f'Error loading X.509 bundle from {path}')


class SaveX509BundleError(X509BundleError):
"""Error raised when unable to save an X.509 bundle to a file."""

def __init__(self, path: str) -> None:
super().__init__(f'Error saving X.509 bundle to {path}')
79 changes: 0 additions & 79 deletions spiffe/src/spiffe/bundle/x509_bundle/exceptions.py

This file was deleted.

20 changes: 9 additions & 11 deletions spiffe/src/spiffe/bundle/x509_bundle/x509_bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@

from cryptography.hazmat.primitives import serialization
from cryptography.x509 import Certificate
from spiffe.exceptions import ArgumentError
from spiffe.bundle.x509_bundle.exceptions import (
from spiffe.errors import ArgumentError
from spiffe.bundle.x509_bundle.errors import (
X509BundleError,
SaveX509BundleError,
ParseX509BundleError,
Expand Down Expand Up @@ -116,9 +116,7 @@ def save(
try:
write_certificates_to_file(bundle_path, encoding, self._x509_authorities)
except Exception as err:
raise SaveX509BundleError(
'Error writing X.509 bundle to file: {}'.format(str(err))
)
raise SaveX509BundleError(bundle_path) from err

@classmethod
def parse(cls, trust_domain: TrustDomain, bundle_bytes: bytes) -> 'X509Bundle':
Expand All @@ -138,8 +136,8 @@ def parse(cls, trust_domain: TrustDomain, bundle_bytes: bytes) -> 'X509Bundle':

try:
authorities = parse_pem_certificates(bundle_bytes)
except Exception as e:
raise ParseX509BundleError(str(e))
except Exception as err:
raise ParseX509BundleError(str(err)) from err

return X509Bundle(trust_domain, set(authorities))

Expand All @@ -161,8 +159,8 @@ def parse_raw(cls, trust_domain: TrustDomain, bundle_bytes: bytes) -> 'X509Bundl

try:
authorities = parse_der_certificates(bundle_bytes)
except Exception as e:
raise ParseX509BundleError(str(e))
except Exception as err:
raise ParseX509BundleError(str(err)) from err

return X509Bundle(trust_domain, set(authorities))

Expand Down Expand Up @@ -190,8 +188,8 @@ def load(

try:
bundle_bytes = load_certificates_bytes_from_file(bundle_path)
except Exception as e:
raise LoadX509BundleError(str(e))
except Exception as err:
raise LoadX509BundleError(str(err)) from err

if encoding == serialization.Encoding.PEM:
return cls.parse(trust_domain, bundle_bytes)
Expand Down
2 changes: 1 addition & 1 deletion spiffe/src/spiffe/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import ipaddress
from urllib.parse import ParseResult, urlparse
from typing import List, Optional, Tuple, Dict, cast
from spiffe.exceptions import ArgumentError
from spiffe.errors import ArgumentError


_SPIFFE_ENDPOINT_SOCKET = 'SPIFFE_ENDPOINT_SOCKET'
Expand Down
27 changes: 27 additions & 0 deletions spiffe/src/spiffe/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""
(C) Copyright 2021 Hewlett Packard Enterprise Development LP
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
"""

"""
This module defines py-spiffe top level exceptions.
"""


class PySpiffeError(Exception):
"""Top level exception for py-spiffe library."""


class ArgumentError(PySpiffeError):
"""Validation error for py-spiffe library."""
Loading

0 comments on commit 55f8f3d

Please sign in to comment.