-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_authforge.py
More file actions
216 lines (183 loc) · 7.74 KB
/
test_authforge.py
File metadata and controls
216 lines (183 loc) · 7.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""Unit tests for the AuthForge Python SDK."""
from __future__ import annotations
import base64
import json
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
from authforge import AuthForgeClient
def _load_test_vectors() -> dict:
path = Path(__file__).resolve().parent / "test_vectors.json"
with path.open(encoding="utf-8") as f:
return json.load(f)
class Ed25519VectorTests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.vectors = _load_test_vectors()
cls.public_key = cls.vectors["publicKey"]
def _make_client(self) -> AuthForgeClient:
return AuthForgeClient(
"test-app-id",
"test-app-secret",
self.public_key,
"LOCAL",
heartbeat_interval=86400,
)
def test_valid_vectors_verify(self) -> None:
client = self._make_client()
for case in self.vectors["cases"]:
if not case["shouldVerify"]:
continue
with self.subTest(case=case["id"]):
client._verify_signature(case["payload"], case["signature"])
def test_invalid_vectors_fail(self) -> None:
client = self._make_client()
for case in self.vectors["cases"]:
if case["shouldVerify"]:
continue
with self.subTest(case=case["id"]):
with self.assertRaises(ValueError) as ctx:
client._verify_signature(case["payload"], case["signature"])
self.assertEqual(ctx.exception.args[0], "signature_mismatch")
class MultiKeyRotationTests(unittest.TestCase):
"""The SDK must verify against any public key in the configured trust
list, so a deployment can rotate the server-side key while clients are
still pinned to the old one."""
DECOY_KEY = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
def test_list_form_accepts_real_key(self) -> None:
vectors = _load_test_vectors()
case = next(c for c in vectors["cases"] if c["id"] == "validate_success")
client = AuthForgeClient(
"app",
"secret",
[self.DECOY_KEY, vectors["publicKey"]],
"LOCAL",
heartbeat_interval=86400,
)
# Bogus key is first; verification must walk to the second entry.
client._verify_signature(case["payload"], case["signature"])
self.assertEqual(client.public_keys[0], self.DECOY_KEY)
self.assertEqual(client.public_keys[1], vectors["publicKey"])
def test_comma_separated_form_accepts_real_key(self) -> None:
vectors = _load_test_vectors()
case = next(c for c in vectors["cases"] if c["id"] == "validate_success")
combined = f"{self.DECOY_KEY},{vectors['publicKey']}"
client = AuthForgeClient(
"app", "secret", combined, "LOCAL", heartbeat_interval=86400
)
client._verify_signature(case["payload"], case["signature"])
def test_all_unknown_keys_still_fails(self) -> None:
vectors = _load_test_vectors()
case = next(c for c in vectors["cases"] if c["id"] == "validate_success")
client = AuthForgeClient(
"app",
"secret",
[self.DECOY_KEY],
"LOCAL",
heartbeat_interval=86400,
)
with self.assertRaises(ValueError) as ctx:
client._verify_signature(case["payload"], case["signature"])
self.assertEqual(ctx.exception.args[0], "signature_mismatch")
class ValidateLicenseTests(unittest.TestCase):
def test_validate_license_success_no_heartbeat(self) -> None:
vectors = _load_test_vectors()
success_case = next(
case for case in vectors["cases"] if case["id"] == "validate_success"
)
nonce = "nonce-validate-001"
mock_resp = MagicMock()
mock_resp.status = 200
mock_resp.read.return_value = json.dumps(
{
"status": "ok",
"payload": success_case["payload"],
"signature": success_case["signature"],
"keyId": "signing-key-1",
},
separators=(",", ":"),
).encode("utf-8")
urlopen_cm = MagicMock()
urlopen_cm.__enter__.return_value = mock_resp
urlopen_cm.__exit__.return_value = None
with (
patch("authforge.urllib.request.urlopen", return_value=urlopen_cm),
patch.object(AuthForgeClient, "_generate_nonce", return_value=nonce),
):
client = AuthForgeClient(
"app-id",
"app-secret",
vectors["publicKey"],
"LOCAL",
heartbeat_interval=86400,
)
result = client.validate_license("license-key")
self.assertTrue(result["valid"])
self.assertFalse(client._heartbeat_started)
self.assertFalse(client.is_authenticated())
self.assertEqual(result["session_token"], "session.validate.token")
self.assertEqual(result["app_variables"], {"tier": "pro"})
def test_validate_license_failure_no_heartbeat(self) -> None:
vectors = _load_test_vectors()
mock_resp = MagicMock()
mock_resp.status = 200
mock_resp.read.return_value = json.dumps(
{"status": "invalid_key", "error": "invalid_key"},
separators=(",", ":"),
).encode("utf-8")
urlopen_cm = MagicMock()
urlopen_cm.__enter__.return_value = mock_resp
urlopen_cm.__exit__.return_value = None
with patch("authforge.urllib.request.urlopen", return_value=urlopen_cm):
client = AuthForgeClient(
"app-id",
"app-secret",
vectors["publicKey"],
"LOCAL",
heartbeat_interval=86400,
)
result = client.validate_license("bad")
self.assertFalse(result["valid"])
self.assertEqual(result["code"], "invalid_key")
self.assertFalse(client._heartbeat_started)
class LoginFlowTests(unittest.TestCase):
def test_login_parses_and_stores_signed_payload(self) -> None:
vectors = _load_test_vectors()
success_case = next(case for case in vectors["cases"] if case["id"] == "validate_success")
payload = json.loads(base64.b64decode(success_case["payload"]).decode("utf-8"))
nonce = "nonce-validate-001"
mock_resp = MagicMock()
mock_resp.status = 200
mock_resp.read.return_value = json.dumps(
{
"status": "ok",
"payload": success_case["payload"],
"signature": success_case["signature"],
"keyId": "signing-key-1",
},
separators=(",", ":"),
).encode("utf-8")
urlopen_cm = MagicMock()
urlopen_cm.__enter__.return_value = mock_resp
urlopen_cm.__exit__.return_value = None
with (
patch("authforge.urllib.request.urlopen", return_value=urlopen_cm),
patch.object(AuthForgeClient, "_generate_nonce", return_value=nonce),
):
client = AuthForgeClient(
"app-id",
"app-secret",
vectors["publicKey"],
"LOCAL",
heartbeat_interval=86400,
)
self.assertTrue(client.login("license-key"))
self.assertTrue(client.is_authenticated())
self.assertEqual(client._key_id, "signing-key-1")
self.assertEqual(client._last_nonce, nonce)
self.assertIsNotNone(client.get_session_data())
self.assertEqual(client.get_app_variables(), {"tier": "pro"})
self.assertEqual(client.get_license_variables(), {"region": "us-east-1"})
self.assertEqual(payload["nonce"], nonce)
if __name__ == "__main__":
unittest.main()