Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure comment is always empty string on export #26

Merged
merged 1 commit into from
May 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/sshkey_tools/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from cryptography.hazmat.primitives.asymmetric import rsa as _RSA

from . import exceptions as _EX
from .utils import ensure_bytestring, ensure_string
from .utils import ensure_bytestring, ensure_string, nullsafe_getattr
from .utils import md5_fingerprint as _FP_MD5
from .utils import sha256_fingerprint as _FP_SHA256
from .utils import sha512_fingerprint as _FP_SHA512
Expand Down Expand Up @@ -129,12 +129,15 @@ def __init__(
_SERIALIZATION.Encoding.OpenSSH,
_SERIALIZATION.PublicFormat.OpenSSH,
]

# Ensure comment is not None
self.comment = nullsafe_getattr(self, "comment", "")

@classmethod
def from_class(
cls,
key_class: PubkeyClasses,
comment: Union[str, bytes] = None,
comment: Union[str, bytes] = "",
key_type: Union[str, bytes] = None,
) -> "PublicKey":
"""
Expand Down Expand Up @@ -266,7 +269,7 @@ def to_string(self, encoding: str = "utf-8") -> str:
return " ".join(
[
ensure_string(self.serialize(), encoding),
ensure_string(getattr(self, "comment", ""), encoding),
ensure_string(nullsafe_getattr(self, "comment", ""), encoding),
]
)

Expand Down
16 changes: 16 additions & 0 deletions src/sshkey_tools/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,22 @@ def sha512_fingerprint(data: bytes, prefix: bool = True) -> str:
)


def nullsafe_getattr(obj, attr: str, default):
"""
Null-safe getattr, ensuring the result is not None.
If the result is None, the default value is returned instead.

Args:
obj: The object
attr: The attribute to get
default: The default value
"""
att = getattr(obj, attr, default)
if att is None:
att = default

return att

def join_dicts(*dicts) -> dict:
"""
Joins two or more dictionaries together.
Expand Down