apsig 0.3.0__tar.gz → 0.3.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
  MIT License
2
2
 
3
- Copyright (c) 2024 Holo
3
+ Copyright (c) 2025 AmaseCocoa
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: apsig
3
- Version: 0.3.0
3
+ Version: 0.3.2
4
4
  Summary: Signature implementation used in ActivityPub.
5
5
  Author-Email: AmaseCocoa <amase.cocoa@gmail.com>
6
6
  License: MIT
7
- Classifier: Development Status :: 3 - Alpha
7
+ Classifier: Development Status :: 4 - Beta
8
8
  Classifier: Intended Audience :: Developers
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Programming Language :: Python :: 3
@@ -24,6 +24,7 @@ Requires-Dist: pynacl>=1.5.0
24
24
  Requires-Dist: multiformats>=0.3.1.post4
25
25
  Requires-Dist: jcs>=0.2.1
26
26
  Requires-Dist: pyld[aiohttp,requests]>=2.0.4
27
+ Requires-Dist: pyfill>=0.1.1
27
28
  Description-Content-Type: text/markdown
28
29
 
29
30
  # apsig
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "apsig"
3
- version = "0.3.0"
3
+ version = "0.3.2"
4
4
  description = "Signature implementation used in ActivityPub."
5
5
  authors = [
6
6
  { name = "AmaseCocoa", email = "amase.cocoa@gmail.com" },
@@ -11,9 +11,10 @@ dependencies = [
11
11
  "multiformats>=0.3.1.post4",
12
12
  "jcs>=0.2.1",
13
13
  "pyld[aiohttp,requests]>=2.0.4",
14
+ "pyfill>=0.1.1",
14
15
  ]
15
16
  classifiers = [
16
- "Development Status :: 3 - Alpha",
17
+ "Development Status :: 4 - Beta",
17
18
  "Intended Audience :: Developers",
18
19
  "License :: OSI Approved :: MIT License",
19
20
  "Programming Language :: Python :: 3",
@@ -46,7 +47,7 @@ build-backend = "pdm.backend"
46
47
  distribution = true
47
48
 
48
49
  [tool.pdm.scripts]
49
- test = "python test_runner.py"
50
+ test = "python -m unittest discover -s tests"
50
51
 
51
52
  [dependency-groups]
52
53
  e2e = [
@@ -2,16 +2,18 @@ from cryptography.hazmat.primitives.asymmetric import padding, rsa
2
2
  from cryptography.hazmat.primitives import hashes
3
3
  from cryptography.hazmat.backends import default_backend
4
4
 
5
+ from pyfill import datetime
5
6
  import base64
6
7
  from urllib.parse import urlparse
7
8
 
8
9
  class draftSigner:
9
10
  def _generate_digest(body: bytes | str):
10
11
  digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
11
- digest.update(body.encode("utf-8"))
12
+ digest.update(body.encode("utf-8") if isinstance(body, str) else body)
12
13
  hash_bytes = digest.finalize()
13
14
  return "SHA-256=" + base64.b64encode(hash_bytes).decode("utf-8")
14
15
 
16
+ @staticmethod
15
17
  def sign(private_key: rsa.RSAPrivateKey, method: str, url: str, headers: dict, key_id: str, body: bytes="") -> dict:
16
18
  """Signs an HTTP request with a digital signature.
17
19
 
@@ -33,7 +35,10 @@ class draftSigner:
33
35
  request_target = f"(request-target): {method.lower()} {parsed_url.path}"
34
36
 
35
37
  digest = draftSigner._generate_digest(body)
36
- headers["digest"] = digest
38
+ if not headers.get("Host"):
39
+ headers["Host"] = parsed_url.netloc
40
+ headers["Digest"] = digest
41
+ headers["Date"] = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
37
42
 
38
43
  signature_headers = [request_target]
39
44
  for header in headers:
@@ -43,8 +48,13 @@ class draftSigner:
43
48
 
44
49
  signature = private_key.sign(signature_string, padding.PKCS1v15(), hashes.SHA256())
45
50
  signature_b64 = base64.b64encode(signature).decode("utf-8")
51
+ header_keys = []
52
+ for key in headers.keys():
53
+ #if key.lower() != "content-type":
54
+ header_keys.append(key) # .lower()
46
55
 
47
- signature_header = f'keyId="{key_id}",algorithm="rsa-sha256",headers="(request-target) {" ".join(headers.keys())}",signature="{signature_b64}"'
48
- headers["signature"] = signature_header
56
+
57
+ signature_header = f'keyId="{key_id}",algorithm="rsa-sha256",headers="(request-target) {" ".join(header_keys)}",signature="{signature_b64}"'
58
+ headers["Signature"] = signature_header
49
59
  headers["Authorization"] = f"Signature {signature_header}" # Misskeyなどでは必要
50
60
  return headers
@@ -10,11 +10,11 @@ from urllib.parse import urlparse
10
10
  class draftVerifier:
11
11
  def _generate_digest(body: bytes | str):
12
12
  digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
13
- digest.update(body.encode("utf-8") if not isinstance(body, bytes) else body)
13
+ digest.update(body.encode("utf-8") if isinstance(body, str) else body)
14
14
  hash_bytes = digest.finalize()
15
15
  return "SHA-256=" + base64.b64encode(hash_bytes).decode("utf-8")
16
16
 
17
-
17
+ @staticmethod
18
18
  def verify(public_pem: str, method: str, url: str, headers: dict, body: bytes=b"") -> tuple[bool, str]:
19
19
  """Verifies the digital signature of an HTTP request.
20
20
 
@@ -33,7 +33,9 @@ class draftVerifier:
33
33
  Raises:
34
34
  ValueError: If the signature header is missing or if the algorithm is unsupported.
35
35
  """
36
- signature_header = headers.get("signature")
36
+ case_insensitive_headers = {key.lower(): value for key, value in headers.items()}
37
+
38
+ signature_header = case_insensitive_headers.get("signature")
37
39
  if not signature_header:
38
40
  return False, "Signature header is missing"
39
41
 
@@ -43,7 +45,7 @@ class draftVerifier:
43
45
  signature_parts[key.strip()] = value.strip().strip('"')
44
46
 
45
47
  signature = base64.b64decode(signature_parts["signature"])
46
- #keyId = signature_parts["keyId"]
48
+ keyId = signature_parts["keyId"]
47
49
  algorithm = signature_parts["algorithm"]
48
50
 
49
51
  if algorithm != "rsa-sha256":
@@ -74,7 +76,7 @@ class draftVerifier:
74
76
  return False, "Invalid signature"
75
77
 
76
78
  expected_digest = draftVerifier._generate_digest(body)
77
- if headers.get("digest") != expected_digest:
79
+ if case_insensitive_headers.get("digest") != expected_digest:
78
80
  return False, "Digest mismatch"
79
81
 
80
82
  date_header = headers.get("date")
@@ -33,7 +33,7 @@ class TestSignatureFunctions(unittest.TestCase):
33
33
 
34
34
  signed_headers = draftSigner.sign(self.private_key, method, url, headers, "https://example.com/users/johndoe#main-key", body)
35
35
 
36
- is_valid, message = draftVerifier.verify(self.public_pem, method, url, signed_headers, body.encode("utf-8"))
36
+ is_valid, message = draftVerifier.verify(public_pem=self.public_pem, method=method, url=url, headers=signed_headers, body=body.encode("utf-8"))
37
37
 
38
38
  self.assertTrue(is_valid)
39
39
  self.assertEqual(message, "Signature is valid")
@@ -44,7 +44,7 @@ class TestSignatureFunctions(unittest.TestCase):
44
44
  headers = {
45
45
  "Content-Type": "application/json",
46
46
  "Date": "Wed, 21 Oct 2015 07:28:00 GMT",
47
- "signature": 'keyId="your-key-id",algorithm="rsa-sha256",headers="(request-target) Content-Type Date",signature="invalid_signature"'
47
+ "Signature": 'keyId="your-key-id",algorithm="rsa-sha256",headers="(request-target) Content-Type Date",signature="invalid_signature"'
48
48
  }
49
49
  body = '{"key": "value"}'
50
50
 
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