apsig 0.4.0__tar.gz → 0.5.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: apsig
3
- Version: 0.4.0
3
+ Version: 0.5.2
4
4
  Summary: Signature implementation used in ActivityPub.
5
5
  Author-Email: AmaseCocoa <amase.cocoa@gmail.com>
6
6
  License: MIT
@@ -31,7 +31,7 @@ classifiers = [
31
31
  ]
32
32
  requires-python = ">=3.10"
33
33
  readme = "README.md"
34
- version = "0.4.0"
34
+ version = "0.5.2"
35
35
 
36
36
  [project.license]
37
37
  text = "MIT"
@@ -0,0 +1 @@
1
+ __version__ = '0.5.2'
@@ -1,5 +1,7 @@
1
1
  from typing import Any
2
2
  from typing_extensions import deprecated
3
+ import json
4
+
3
5
  from cryptography.hazmat.primitives.asymmetric import padding, rsa
4
6
  from cryptography.hazmat.primitives import hashes
5
7
 
@@ -17,7 +19,7 @@ class draftSigner:
17
19
  return signer.sign()
18
20
 
19
21
  class Signer:
20
- def __init__(self, headers: dict[Any, Any], private_key: rsa.RSAPrivateKey, method: str, url: str, key_id: str, body: bytes=b"") -> None:
22
+ def __init__(self, headers: dict[Any, Any], private_key: rsa.RSAPrivateKey, method: str, url: str, key_id: str, body: bytes | dict=b"") -> None:
21
23
  """Signs an HTTP request with a digital signature.
22
24
 
23
25
  Args:
@@ -45,12 +47,16 @@ class Signer:
45
47
  self.method = method
46
48
  self.url = url
47
49
  self.key_id = key_id
48
- self.body = body
50
+ if isinstance(body, dict):
51
+ self.body = json.dumps(body, separators=(',', ':')).encode("utf-8")
52
+ else:
53
+ self.body = body
49
54
 
50
55
  if not self.headers.get("Host"):
51
56
  self.headers["Host"] = self.parsed_url.netloc
52
57
 
53
- self.__generate_digest(self.body)
58
+ if method.upper() != "GET":
59
+ self.__generate_digest(self.body)
54
60
 
55
61
  def __generate_sign_header(self, signature: str):
56
62
  self.headers["Signature"] = signature
@@ -1,15 +1,18 @@
1
+ from typing import Union
1
2
  import base64
2
3
  from urllib.parse import urlparse
4
+ import json
3
5
 
4
6
  import pytz
5
7
  from cryptography.exceptions import InvalidSignature
6
8
  from cryptography.hazmat.backends import default_backend
7
9
  from cryptography.hazmat.primitives import hashes, serialization
8
- from cryptography.hazmat.primitives.asymmetric import padding
10
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
9
11
  from pyfill import datetime
10
12
  from typing_extensions import deprecated
11
13
 
12
14
  from .tools import build_string, calculate_digest
15
+ from ..exceptions import MissingSignature, UnknownSignature, VerificationFailed
13
16
 
14
17
 
15
18
  class draftVerifier:
@@ -18,7 +21,7 @@ class draftVerifier:
18
21
  "apsig.draft.verify.draftVerifier is deprecated; use apsig.draft.verify.Verifier instead. This will be removed in apsig 1.0."
19
22
  )
20
23
  def verify(
21
- public_pem: str, method: str, url: str, headers: dict, body: bytes = b""
24
+ public_pem: str, method: str, url: str, headers: dict, body: bytes = None
22
25
  ) -> tuple[bool, str]:
23
26
  """Verifies the digital signature of an HTTP request.
24
27
 
@@ -37,39 +40,53 @@ class draftVerifier:
37
40
  Raises:
38
41
  ValueError: If the signature header is missing or if the algorithm is unsupported.
39
42
  """
40
- return Verifier(
41
- public_pem=public_pem, method=method, url=url, headers=headers, body=body
42
- ).verify()
43
+ try:
44
+ result = Verifier(
45
+ public_pem=public_pem, method=method, url=url, headers=headers, body=body
46
+ ).verify(raise_on_fail=True)
47
+ except Exception as e:
48
+ return False, str(e)
49
+ if result:
50
+ return True, "Signature is valid"
43
51
 
44
52
 
45
53
  class Verifier:
46
54
  def __init__(
47
- self, public_pem: str, method: str, url: str, headers: dict, body: bytes = b""
55
+ self, public_pem: Union[rsa.RSAPublicKey, str], method: str, url: str, headers: dict, body: bytes | dict = None
48
56
  ) -> None:
49
- self.public_pem = public_pem
57
+ """
58
+ Args:
59
+ public_pem (str): The public key in PEM format used to verify the signature.
60
+ method (str): The HTTP method (e.g., "GET", "POST").
61
+ url (str): The URL of the request.
62
+ headers (dict): A dictionary of HTTP headers, including the signature and other relevant information.
63
+ body (bytes, optional): The request body. Defaults to an empty byte string.
64
+ """
65
+ if isinstance(public_pem, str) or isinstance(public_pem, bytes):
66
+ self.public_key = serialization.load_pem_public_key(
67
+ public_pem.encode("utf-8") if isinstance(public_pem, str) else public_pem, backend=default_backend()
68
+ )
69
+ else:
70
+ self.public_key = public_pem
50
71
  self.method = method
51
72
  self.url = url
52
73
  self.headers_raw = headers
53
74
  self.headers = {key.lower(): value for key, value in headers.items()}
54
- self.body = body
75
+ if isinstance(body, dict):
76
+ self.body = json.dumps(body, separators=(',', ':')).encode("utf-8")
77
+ else:
78
+ self.body = body
55
79
 
56
80
  def __decode_sign(self, signature):
57
81
  return base64.standard_b64decode(signature)
58
82
 
59
- def verify(self) -> tuple[bool, str]:
83
+ def verify(self, raise_on_fail: bool = False) -> Union[str, None]:
60
84
  """Verifies the digital signature of an HTTP request.
61
85
 
62
86
  Args:
63
- public_pem (str): The public key in PEM format used to verify the signature.
64
- method (str): The HTTP method (e.g., "GET", "POST").
65
- url (str): The URL of the request.
66
- headers (dict): A dictionary of HTTP headers, including the signature and other relevant information.
67
- body (bytes, optional): The request body. Defaults to an empty byte string.
87
+ raise_on_fail (bool, optional): Return error on failure. defaults to False.
68
88
 
69
89
  Returns:
70
- tuple: A tuple containing:
71
- - bool: True if the signature is valid, False otherwise.
72
- - str: A message indicating the result of the verification.
73
90
 
74
91
  Raises:
75
92
  ValueError: If the signature header is missing or if the algorithm is unsupported.
@@ -78,7 +95,11 @@ class Verifier:
78
95
 
79
96
  signature_header = headers.get("signature")
80
97
  if not signature_header:
81
- return False, "Signature header is missing"
98
+ if raise_on_fail:
99
+ raise MissingSignature(
100
+ "Signature header is missing"
101
+ )
102
+ return None
82
103
 
83
104
  signature_parts = {}
84
105
  for item in signature_header.split(","):
@@ -86,11 +107,15 @@ class Verifier:
86
107
  signature_parts[key.strip()] = value.strip().strip('"')
87
108
 
88
109
  signature = self.__decode_sign(signature_parts["signature"])
89
- #keyId = signature_parts["keyId"]
110
+ key_id = signature_parts["keyId"]
90
111
  algorithm = signature_parts["algorithm"]
91
112
 
92
113
  if algorithm != "rsa-sha256":
93
- return False, "Unsupported algorithm"
114
+ if raise_on_fail:
115
+ raise UnknownSignature(
116
+ f"Unsupported algorithm. Algorithm must be rsa-sha256, but passed {algorithm}."
117
+ )
118
+ return None
94
119
 
95
120
  signed_headers = signature_parts["headers"].split()
96
121
 
@@ -104,20 +129,25 @@ class Verifier:
104
129
  signature_headers, headers=signed_headers
105
130
  ).encode("utf-8")
106
131
 
107
- public_key = serialization.load_pem_public_key(
108
- self.public_pem.encode("utf-8"), backend=default_backend()
109
- )
110
-
111
132
  try:
112
- public_key.verify(
133
+ self.public_key.verify(
113
134
  signature, signature_string, padding.PKCS1v15(), hashes.SHA256()
114
135
  )
115
136
  except InvalidSignature:
116
- return False, "Invalid signature"
117
-
118
- expected_digest = calculate_digest(self.body)
119
- if headers.get("digest") != expected_digest:
120
- return False, "Digest mismatch"
137
+ if raise_on_fail:
138
+ raise VerificationFailed(
139
+ "Invalid signature"
140
+ )
141
+ return None
142
+
143
+ if self.body:
144
+ expected_digest = calculate_digest(self.body)
145
+ if headers.get("digest") != expected_digest:
146
+ if raise_on_fail:
147
+ raise VerificationFailed(
148
+ "Digest mismatch"
149
+ )
150
+ return None
121
151
 
122
152
  date_header = headers.get("date")
123
153
  if date_header:
@@ -129,6 +159,10 @@ class Verifier:
129
159
  request_time = gmt_time.astimezone(pytz.utc)
130
160
  current_time = datetime.utcnow()
131
161
  if abs((current_time - request_time).total_seconds()) > 3600:
132
- return False, "Date header is too far from current time"
162
+ if raise_on_fail:
163
+ raise VerificationFailed(
164
+ "Date header is too far from current time"
165
+ )
166
+ return None
133
167
 
134
- return True, "Signature is valid"
168
+ return key_id
@@ -1,5 +1,6 @@
1
1
  # This code was ported from Takahe.
2
2
 
3
+ from typing import Union
3
4
  import datetime
4
5
  import base64
5
6
  from cryptography.hazmat.primitives import hashes
@@ -82,7 +83,7 @@ class LDSignature:
82
83
  },
83
84
  }
84
85
 
85
- def verify(self, doc: dict, public_key: rsa.RSAPublicKey | str):
86
+ def verify(self, doc: dict, public_key: rsa.RSAPublicKey | str, raise_on_fail: bool = False) -> Union[str, None]:
86
87
  """Verifies the signature of the provided document against the given public key.
87
88
 
88
89
  Args:
@@ -100,7 +101,9 @@ class LDSignature:
100
101
  if isinstance(public_key, str):
101
102
  codec, data = multicodec.unwrap(multibase.decode(public_key))
102
103
  if codec.name != "rsa-pub":
103
- raise ValueError("public_key must be RSA PublicKey.")
104
+ if raise_on_fail:
105
+ raise ValueError("public_key must be RSA PublicKey.")
106
+ return None
104
107
  public_key = serialization.load_pem_public_key(data, backend=default_backend())
105
108
  try:
106
109
  document = doc.copy()
@@ -111,9 +114,13 @@ class LDSignature:
111
114
  "created": signature["created"],
112
115
  }
113
116
  except KeyError:
114
- raise MissingSignature("Invalid signature section")
117
+ if raise_on_fail:
118
+ raise MissingSignature("Invalid signature section")
119
+ return None
115
120
  if signature["type"].lower() != "rsasignature2017":
116
- raise UnknownSignature("Unknown signature type")
121
+ if raise_on_fail:
122
+ raise UnknownSignature("Unknown signature type")
123
+ return None
117
124
  final_hash = self.__normalized_hash(options) + self.__normalized_hash(document)
118
125
  try:
119
126
  public_key.verify(
@@ -122,5 +129,8 @@ class LDSignature:
122
129
  padding.PKCS1v15(),
123
130
  hashes.SHA256(),
124
131
  )
132
+ return signature["creator"]
125
133
  except InvalidSignature:
126
- raise VerificationFailed("LDSignature mismatch")
134
+ if raise_on_fail:
135
+ raise VerificationFailed("LDSignature mismatch")
136
+ return None
@@ -1,9 +1,11 @@
1
+ from typing import Union
1
2
  import hashlib
2
3
 
3
4
  import jcs
4
5
  from cryptography.hazmat.primitives.asymmetric import ed25519
5
6
  from multiformats import multibase, multicodec
6
7
 
8
+ from ..exceptions import VerificationFailed, UnknownSignature
7
9
 
8
10
  class ProofVerifier:
9
11
  """
@@ -66,7 +68,7 @@ class ProofVerifier:
66
68
  ).digest()
67
69
  return proof_config_hash + transformed_document_hash
68
70
 
69
- def verify_proof(self, secured_document: dict):
71
+ def verify_proof(self, secured_document: dict, raise_on_fail: bool = False) -> Union[str, bool]:
70
72
  """
71
73
  Verifies the proof contained in the secured document.
72
74
 
@@ -76,6 +78,7 @@ class ProofVerifier:
76
78
 
77
79
  Args:
78
80
  secured_document (dict): The document containing the proof to be verified.
81
+ raise_on_fail (bool, optional): Return error on failure. defaults to False.
79
82
 
80
83
  Returns:
81
84
  dict: A dictionary containing:
@@ -86,36 +89,49 @@ class ProofVerifier:
86
89
  ValueError: If the proof is not found in the document.
87
90
  """
88
91
  if not secured_document.get("proof"):
89
- raise ValueError("Proof not found in the object")
92
+ if raise_on_fail:
93
+ raise ValueError("Proof not found in the object")
94
+ return None
90
95
  unsecured_document = secured_document.copy()
91
96
  proof_value = unsecured_document["proof"].pop("proofValue")
92
97
  proof_bytes = multibase.decode(proof_value)
93
98
 
94
99
  proof_options = unsecured_document["proof"]
100
+ verification_method = proof_options.get("verificationMethod")
101
+ if not verification_method:
102
+ if raise_on_fail:
103
+ raise ValueError("verificationMethod not found in proof")
104
+ return None
95
105
 
96
106
  if "@context" in proof_options:
97
107
  if isinstance(secured_document["@context"], str):
98
108
  if not secured_document["@context"].startswith(
99
109
  tuple(proof_options["@context"])
100
110
  ):
101
- return {"verified": False, "verifiedDocument": None}
111
+ if raise_on_fail:
112
+ raise UnknownSignature
113
+ return None
102
114
  elif isinstance(secured_document["@context"], list):
103
115
  if not any(item.startswith(tuple(proof_options["@context"])) for item in secured_document["@context"] if isinstance(item, str)):
104
- return {"verified": False, "verifiedDocument": None}
116
+ if raise_on_fail:
117
+ raise UnknownSignature
118
+ return None
105
119
 
106
- unsecured_document["@context"] = proof_options["@context"]
107
120
 
121
+ unsecured_document.pop("proof")
108
122
  transformed_data = self.transform(unsecured_document, proof_options)
109
123
  proof_config = self.canonicalize(proof_options)
110
124
  hash_data = self.hashing(transformed_data, proof_config)
111
125
 
112
126
  try:
113
127
  self.verify_signature(proof_bytes, hash_data)
114
- return {"verified": True, "verifiedDocument": unsecured_document}
115
- except Exception:
116
- return {"verified": False, "verifiedDocument": None}
128
+ return verification_method
129
+ except Exception as e:
130
+ if raise_on_fail:
131
+ raise VerificationFailed(str(e))
132
+ return None
117
133
 
118
- def verify(self, secured_document: dict) -> dict:
134
+ def verify(self, secured_document: dict, raise_on_fail: bool = False) -> Union[str, bool]:
119
135
  """
120
136
  An alias for the verify_proof method.
121
137
 
@@ -128,4 +144,4 @@ class ProofVerifier:
128
144
  Returns:
129
145
  dict: The result of the proof verification.
130
146
  """
131
- return self.verify_proof(secured_document)
147
+ return self.verify_proof(secured_document, raise_on_fail)
@@ -0,0 +1,8 @@
1
+ from typing import Any
2
+
3
+ def get_draft_signature_parts(signature: str) -> dict[Any, Any]:
4
+ signature_parts = {}
5
+ for item in signature.split(","):
6
+ key, value = item.split("=", 1)
7
+ signature_parts[key.strip()] = value.strip().strip('"')
8
+ return signature_parts
@@ -6,6 +6,7 @@ from cryptography.hazmat.primitives import serialization
6
6
  from cryptography.hazmat.backends import default_backend
7
7
 
8
8
  from apsig.draft import Signer, Verifier
9
+ from apsig.exceptions import VerificationFailed, MissingSignature
9
10
 
10
11
  class TestSignatureFunctions(unittest.TestCase):
11
12
  @classmethod
@@ -49,10 +50,41 @@ class TestSignatureFunctions(unittest.TestCase):
49
50
  body=body.encode("utf-8"),
50
51
  )
51
52
 
52
- is_valid, message = verifier.verify()
53
+ result = verifier.verify(raise_on_fail=True)
53
54
 
54
- self.assertTrue(is_valid)
55
- self.assertEqual(message, "Signature is valid")
55
+ self.assertIsInstance(result, str)
56
+ self.assertEqual(result, "https://example.com/users/johndoe#main-key")
57
+
58
+ def test_create_and_verify_signature_method_get(self):
59
+ date = email.utils.formatdate(usegmt=True)
60
+
61
+ method = "GET"
62
+ url = "https://example.com/api/resource"
63
+ headers = {
64
+ "Content-Type": "application/json",
65
+ "Date": date,
66
+ }
67
+
68
+ signer = Signer(
69
+ headers=headers,
70
+ private_key=self.private_key,
71
+ method=method,
72
+ url=url,
73
+ key_id="https://example.com/users/johndoe#main-key",
74
+ )
75
+
76
+ signed_headers = signer.sign()
77
+ verifier = Verifier(
78
+ public_pem=self.public_pem,
79
+ method=method,
80
+ url=url,
81
+ headers=signed_headers,
82
+ )
83
+
84
+ result = verifier.verify(raise_on_fail=True)
85
+
86
+ self.assertIsInstance(result, str)
87
+ self.assertEqual(result, "https://example.com/users/johndoe#main-key")
56
88
 
57
89
  def test_too_far_date(self):
58
90
  method = "POST"
@@ -81,10 +113,8 @@ class TestSignatureFunctions(unittest.TestCase):
81
113
  body=body.encode("utf-8"),
82
114
  )
83
115
 
84
- is_valid, message = verifier.verify()
85
-
86
- self.assertFalse(is_valid)
87
- self.assertEqual(message, "Date header is too far from current time")
116
+ with self.assertRaises(VerificationFailed, msg="Date header is too far from current time"):
117
+ verifier.verify(raise_on_fail=True)
88
118
 
89
119
  def test_verify_invalid_signature(self):
90
120
  method = "POST"
@@ -104,10 +134,8 @@ class TestSignatureFunctions(unittest.TestCase):
104
134
  body=body.encode("utf-8"),
105
135
  )
106
136
 
107
- is_valid, message = verifier.verify()
108
-
109
- self.assertFalse(is_valid)
110
- self.assertEqual(message, "Invalid signature")
137
+ with self.assertRaises(VerificationFailed, msg="Invalid signature"):
138
+ verifier.verify(raise_on_fail=True)
111
139
 
112
140
  def test_missing_signature_header(self):
113
141
  method = "POST"
@@ -125,10 +153,8 @@ class TestSignatureFunctions(unittest.TestCase):
125
153
  body=body.encode("utf-8"),
126
154
  )
127
155
 
128
- is_valid, message = verifier.verify()
129
-
130
- self.assertFalse(is_valid)
131
- self.assertEqual(message, "Signature header is missing")
156
+ with self.assertRaises(MissingSignature, msg="Signature header is missing"):
157
+ verifier.verify(raise_on_fail=True)
132
158
 
133
159
 
134
160
  if __name__ == "__main__":
@@ -26,29 +26,25 @@ class TestJsonLdSigner(unittest.TestCase):
26
26
  self.signed_data = self.ld.sign(self.data, "https://example.com/users/johndoe#main-key", private_key=self.private_key)
27
27
 
28
28
  def test_sign_and_verify(self):
29
- self.ld.verify(self.signed_data, self.public_key)
29
+ result = self.ld.verify(self.signed_data, self.public_key, raise_on_fail=True)
30
+ self.assertIsInstance(result, str)
31
+ self.assertEqual(result, "https://example.com/users/johndoe#main-key")
30
32
 
31
33
  def test_verify_invalid_signature_value(self):
32
34
  signed_data = self.ld.sign(self.data, "https://example.com/users/johndoe#main-key", private_key=self.private_key)
33
35
  signed_data["signature"]["signatureValue"] = "invalid_signature"
34
- with self.assertRaises(VerificationFailed) as context:
35
- self.ld.verify(signed_data, self.public_key)
36
- self.assertEqual(str(context.exception), "LDSignature mismatch")
36
+ with self.assertRaises(VerificationFailed, msg="LDSignature mismatch"):
37
+ self.ld.verify(signed_data, self.public_key, raise_on_fail=True)
37
38
 
38
39
  def test_verify_missing_signature(self):
39
- try:
40
- self.ld.verify(self.data, self.public_key)
41
- is_fail = False
42
- except MissingSignature:
43
- is_fail = True
44
- self.assertTrue(is_fail)
40
+ with self.assertRaises(MissingSignature, msg="Invalid signature section"):
41
+ self.ld.verify(self.data, self.public_key, raise_on_fail=True)
45
42
 
46
43
  def test_verify_invalid_signature(self):
47
44
  signed_data = self.ld.sign(self.data, "https://example.com/users/johndoe#main-key", private_key=self.private_key)
48
45
  signed_data["signature"]["type"] = "RsaSignatureHoge"
49
- with self.assertRaises(UnknownSignature) as context:
50
- self.ld.verify(signed_data, self.public_key)
51
- self.assertEqual(str(context.exception), "Unknown signature type")
46
+ with self.assertRaises(UnknownSignature, msg="Unknown signature type"):
47
+ self.ld.verify(signed_data, self.public_key, raise_on_fail=True)
52
48
 
53
49
  if __name__ == '__main__':
54
50
  unittest.main()
@@ -37,9 +37,10 @@ class TestProofSignerVerifier(unittest.TestCase):
37
37
  })
38
38
 
39
39
  verifier = ProofVerifier(self.public_key)
40
- is_valid = verifier.verify(signed_object)
40
+ result = verifier.verify(signed_object)
41
41
 
42
- self.assertTrue(is_valid)
42
+ self.assertIsInstance(result, str)
43
+ self.assertEqual(result, "https://example.com/keys/1")
43
44
 
44
45
  def test_verify_invalid_signature(self):
45
46
  json_object = {
@@ -68,7 +69,7 @@ class TestProofSignerVerifier(unittest.TestCase):
68
69
  verifier = ProofVerifier(self.public_key)
69
70
  result = verifier.verify(signed_object)
70
71
 
71
- self.assertFalse(result["verified"])
72
+ self.assertIsNone(result)
72
73
 
73
74
  def test_missing_proof(self):
74
75
  json_object = {
@@ -84,10 +85,8 @@ class TestProofSignerVerifier(unittest.TestCase):
84
85
 
85
86
  verifier = ProofVerifier(self.public_key)
86
87
 
87
- with self.assertRaises(ValueError) as context:
88
- verifier.verify(json_object)
89
-
90
- self.assertEqual(str(context.exception), "Proof not found in the object")
88
+ with self.assertRaises(ValueError, msg="Proof not found in the object"):
89
+ verifier.verify(json_object, raise_on_fail=True)
91
90
 
92
91
 
93
92
  if __name__ == "__main__":
@@ -1 +0,0 @@
1
- __version__ = '0.4.0'
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes