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

WIP: Add DSSE Envelope #1

Merged
merged 7 commits into from
Jun 20, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
82 changes: 82 additions & 0 deletions securesystemslib/metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""Dead Simple Signing Envelope
"""

from typing import Any, List

from securesystemslib import exceptions
from securesystemslib import formats
from securesystemslib.signer import Signature
from securesystemslib.util import b64dec, b64enc


class Envelope:
"""DSSE Envelope.

Attributes:
payload: Arbitrary byte sequence of Serialized Body
PradyumnaKrishna marked this conversation as resolved.
Show resolved Hide resolved
payloadType: string that identifies how to interpret payload
signatures: List of Signature and GPG Signature

"""

payload: bytes
payloadType: str
PradyumnaKrishna marked this conversation as resolved.
Show resolved Hide resolved
signatures: List[Signature]

def __init__(self, payload, payloadType, signatures):
self.payload = payload
self.payloadType = payloadType
self.signatures = signatures

def __eq__(self, other: Any) -> bool:
if not isinstance(other, Envelope):
return False

return (
self.payload == other.payload
and self.payloadType == other.payloadType
and self.signatures == other.signatures
)

@classmethod
def from_dict(cls, data: dict) -> "Envelope":
"""Creates a Signature object from its JSON/dict representation.

PradyumnaKrishna marked this conversation as resolved.
Show resolved Hide resolved
Arguments:
data:
A dict containing a valid payload, payloadType and signatures
PradyumnaKrishna marked this conversation as resolved.
Show resolved Hide resolved

Raises:
KeyError: If any of the "payload", "payloadType" and "signatures"
fields are missing from the "data".

Returns:
A "Envelope" instance.
"""

payload = b64dec(data['payload'])
payloadType = data['payloadType']

signatures = []
for signature in data['signatures']:
if formats.SIGNATURE_SCHEMA.matches(signature):
signatures.append(Signature.from_dict(signature))

elif formats.GPG_SIGNATURE_SCHEMA.matches(signature):
raise NotImplementedError

else:
raise exceptions.FormatError('Invalid signature')

return cls(payload, payloadType, signatures)

def to_dict(self) -> dict:
"""Returns the JSON-serializable dictionary representation of self."""

return {
"payload": b64enc(self.payload),
"payloadType": self.payloadType,
"signatures": [
signature.to_dict() for signature in self.signatures
],
}
50 changes: 50 additions & 0 deletions securesystemslib/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
that tries to import a working json module, load_json_* functions, etc.
"""

import base64
import binascii
import json
import os
import logging
Expand Down Expand Up @@ -455,3 +457,51 @@ def digests_are_equal(digest1: str, digest2: str) -> bool:
are_equal = False

return are_equal


def b64enc(data: bytes) -> str:
"""
<Purpose>
To encode byte sequence into base64 string

<Arguments>
data:
Byte sequence to encode

<Exceptions>
TypeError: If "data" is not byte sequence

<Side Effects>
None.

<Return>
base64 string
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I appreciate that you adopt the existing code style here (wrt indentation), but I'd say it's okay to deviate from the rest of the file when it comes to docs. Could you please use the same docstring style as above in metadata.py?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ping

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually I was following the docstring used by signer.py. Do I have to add all the fields like Purpose, Arguments, Exceptions, Side Effects and Returns in class methods because many functions don't have any arguments or exceptions. or have to use <> for specifying field in docs.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Our code style guide has some notes about docstrings.

TLDR: In new functions/methods/classes, we should use the Google docstring-style, even if the new code is added to an existing module that otherwise uses the old docstring style, which you used here.

Context: The advantage of the Google docstring-style is that there is a Sphinx-parser that can convert it for Readthedocs. And that it is generally more compact, e.g. the <Purpose> header is omitted because it is implicit and empty sections are also omitted (often times this is the <Side Effects> section).

Please take a quick look at the style guide linked above and let me know if you have more questions.


return base64.standard_b64encode(data).decode('utf-8')


def b64dec(string: str) -> bytes:
"""
<Purpose>
To decode byte sequence from base64 string

<Arguments>
string:
base64 string to decode

<Exceptions>
binascii.Error: If invalid base64-encoded string

<Side Effects>
None.

<Return>
A byte sequence
"""

data = string.encode('utf-8')
try:
return base64.b64decode(data, validate=True)
except binascii.Error:
return base64.b64decode(data, altchars='-_', validate=True)
PradyumnaKrishna marked this conversation as resolved.
Show resolved Hide resolved