apsig 0.4.0__tar.gz → 0.5.0__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.0
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.0"
35
35
 
36
36
  [project.license]
37
37
  text = "MIT"
@@ -0,0 +1 @@
1
+ __version__ = '0.5.0'
@@ -1,3 +1,4 @@
1
+ from typing import Union
1
2
  import base64
2
3
  from urllib.parse import urlparse
3
4
 
@@ -10,6 +11,7 @@ from pyfill import datetime
10
11
  from typing_extensions import deprecated
11
12
 
12
13
  from .tools import build_string, calculate_digest
14
+ from ..exceptions import MissingSignature, UnknownSignature, VerificationFailed
13
15
 
14
16
 
15
17
  class draftVerifier:
@@ -37,15 +39,28 @@ class draftVerifier:
37
39
  Raises:
38
40
  ValueError: If the signature header is missing or if the algorithm is unsupported.
39
41
  """
40
- return Verifier(
41
- public_pem=public_pem, method=method, url=url, headers=headers, body=body
42
- ).verify()
42
+ try:
43
+ result = Verifier(
44
+ public_pem=public_pem, method=method, url=url, headers=headers, body=body
45
+ ).verify(raise_on_fail=True)
46
+ except Exception as e:
47
+ return False, str(e)
48
+ if result:
49
+ return True, "Signature is valid"
43
50
 
44
51
 
45
52
  class Verifier:
46
53
  def __init__(
47
54
  self, public_pem: str, method: str, url: str, headers: dict, body: bytes = b""
48
55
  ) -> None:
56
+ """
57
+ Args:
58
+ public_pem (str): The public key in PEM format used to verify the signature.
59
+ method (str): The HTTP method (e.g., "GET", "POST").
60
+ url (str): The URL of the request.
61
+ headers (dict): A dictionary of HTTP headers, including the signature and other relevant information.
62
+ body (bytes, optional): The request body. Defaults to an empty byte string.
63
+ """
49
64
  self.public_pem = public_pem
50
65
  self.method = method
51
66
  self.url = url
@@ -56,20 +71,13 @@ class Verifier:
56
71
  def __decode_sign(self, signature):
57
72
  return base64.standard_b64decode(signature)
58
73
 
59
- def verify(self) -> tuple[bool, str]:
74
+ def verify(self, raise_on_fail: bool = False) -> Union[str, None]:
60
75
  """Verifies the digital signature of an HTTP request.
61
76
 
62
77
  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.
78
+ raise_on_fail (bool, optional): Return error on failure. defaults to False.
68
79
 
69
80
  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
81
 
74
82
  Raises:
75
83
  ValueError: If the signature header is missing or if the algorithm is unsupported.
@@ -78,7 +86,11 @@ class Verifier:
78
86
 
79
87
  signature_header = headers.get("signature")
80
88
  if not signature_header:
81
- return False, "Signature header is missing"
89
+ if raise_on_fail:
90
+ raise MissingSignature(
91
+ "Signature header is missing"
92
+ )
93
+ return None
82
94
 
83
95
  signature_parts = {}
84
96
  for item in signature_header.split(","):
@@ -86,11 +98,15 @@ class Verifier:
86
98
  signature_parts[key.strip()] = value.strip().strip('"')
87
99
 
88
100
  signature = self.__decode_sign(signature_parts["signature"])
89
- #keyId = signature_parts["keyId"]
101
+ key_id = signature_parts["keyId"]
90
102
  algorithm = signature_parts["algorithm"]
91
103
 
92
104
  if algorithm != "rsa-sha256":
93
- return False, "Unsupported algorithm"
105
+ if raise_on_fail:
106
+ raise UnknownSignature(
107
+ f"Unsupported algorithm. Algorithm must be rsa-sha256, but passed {algorithm}."
108
+ )
109
+ return None
94
110
 
95
111
  signed_headers = signature_parts["headers"].split()
96
112
 
@@ -113,11 +129,19 @@ class Verifier:
113
129
  signature, signature_string, padding.PKCS1v15(), hashes.SHA256()
114
130
  )
115
131
  except InvalidSignature:
116
- return False, "Invalid signature"
132
+ if raise_on_fail:
133
+ raise VerificationFailed(
134
+ "Invalid signature"
135
+ )
136
+ return None
117
137
 
118
138
  expected_digest = calculate_digest(self.body)
119
139
  if headers.get("digest") != expected_digest:
120
- return False, "Digest mismatch"
140
+ if raise_on_fail:
141
+ raise VerificationFailed(
142
+ "Digest mismatch"
143
+ )
144
+ return None
121
145
 
122
146
  date_header = headers.get("date")
123
147
  if date_header:
@@ -129,6 +153,10 @@ class Verifier:
129
153
  request_time = gmt_time.astimezone(pytz.utc)
130
154
  current_time = datetime.utcnow()
131
155
  if abs((current_time - request_time).total_seconds()) > 3600:
132
- return False, "Date header is too far from current time"
156
+ if raise_on_fail:
157
+ raise VerificationFailed(
158
+ "Date header is too far from current time"
159
+ )
160
+ return None
133
161
 
134
- return True, "Signature is valid"
162
+ 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,10 @@ 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")
56
57
 
57
58
  def test_too_far_date(self):
58
59
  method = "POST"
@@ -81,10 +82,8 @@ class TestSignatureFunctions(unittest.TestCase):
81
82
  body=body.encode("utf-8"),
82
83
  )
83
84
 
84
- is_valid, message = verifier.verify()
85
-
86
- self.assertFalse(is_valid)
87
- self.assertEqual(message, "Date header is too far from current time")
85
+ with self.assertRaises(VerificationFailed, msg="Date header is too far from current time"):
86
+ verifier.verify(raise_on_fail=True)
88
87
 
89
88
  def test_verify_invalid_signature(self):
90
89
  method = "POST"
@@ -104,10 +103,8 @@ class TestSignatureFunctions(unittest.TestCase):
104
103
  body=body.encode("utf-8"),
105
104
  )
106
105
 
107
- is_valid, message = verifier.verify()
108
-
109
- self.assertFalse(is_valid)
110
- self.assertEqual(message, "Invalid signature")
106
+ with self.assertRaises(VerificationFailed, msg="Invalid signature"):
107
+ verifier.verify(raise_on_fail=True)
111
108
 
112
109
  def test_missing_signature_header(self):
113
110
  method = "POST"
@@ -125,10 +122,8 @@ class TestSignatureFunctions(unittest.TestCase):
125
122
  body=body.encode("utf-8"),
126
123
  )
127
124
 
128
- is_valid, message = verifier.verify()
129
-
130
- self.assertFalse(is_valid)
131
- self.assertEqual(message, "Signature header is missing")
125
+ with self.assertRaises(MissingSignature, msg="Signature header is missing"):
126
+ verifier.verify(raise_on_fail=True)
132
127
 
133
128
 
134
129
  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
File without changes