99 lines
4.7 KiB
Python
99 lines
4.7 KiB
Python
# Copyright (c) 2026 Storm Dragon
|
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
"""Offline checks for release authentication and publication guards."""
|
|
|
|
import base64
|
|
import hashlib
|
|
import io
|
|
import re
|
|
from types import SimpleNamespace
|
|
import unittest
|
|
from unittest.mock import Mock, patch
|
|
import urllib.error
|
|
|
|
import paramiko
|
|
|
|
import publish
|
|
|
|
|
|
class PublisherTests(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.signingKey = paramiko.RSAKey.generate(1024)
|
|
|
|
def make_publisher(self, response=b'{"id":1}'):
|
|
publisher = publish.Publisher.__new__(publish.Publisher)
|
|
publisher.key = self.signingKey
|
|
publisher.fingerprint = publisher.key_fingerprint(self.signingKey)
|
|
publisher.opener = SimpleNamespace(open=Mock(return_value=io.BytesIO(response)))
|
|
return publisher
|
|
|
|
def test_upload_signature_authenticates_body_and_query(self):
|
|
publisher = self.make_publisher()
|
|
route = publish.REPO_API + "/releases/1/assets?name=example.tar.gz"
|
|
body = b"example release content"
|
|
with patch.object(publish.time, "time", return_value=1000):
|
|
self.assertEqual(publisher.request("POST", route, body), {"id": 1})
|
|
request = publisher.opener.open.call_args.args[0]
|
|
fields = dict(re.findall(r'(\w+)="([^"]*)"', request.get_header("Signature")))
|
|
digest = "SHA-512=" + base64.b64encode(hashlib.sha512(body).digest()).decode()
|
|
expected = (f"(request-target): post {route}\n(created): 1000\n(expires): 1030\ndigest: {digest}").encode()
|
|
signature = paramiko.Message()
|
|
signature.add_string("rsa-sha2-256")
|
|
signature.add_string(base64.b64decode(fields["signature"]))
|
|
self.assertTrue(self.signingKey.verify_ssh_sig(expected, paramiko.Message(signature.asbytes())))
|
|
self.assertFalse(self.signingKey.verify_ssh_sig(expected + b"changed", paramiko.Message(signature.asbytes())))
|
|
self.assertEqual(request.data, body)
|
|
self.assertEqual(request.get_header("Digest"), digest)
|
|
self.assertEqual(fields["headers"], "(request-target) (created) (expires) digest")
|
|
|
|
def test_repository_boundary_rejects_requests_before_signing(self):
|
|
publisher = self.make_publisher()
|
|
for method, route in (("GET", "https://example.org/"), ("DELETE", publish.REPO_API),
|
|
("POST", "/api/v1/user"), ("GET", publish.REPO_API + "-other"),
|
|
("GET", publish.REPO_API + "/../other")):
|
|
with self.subTest(method=method, route=route), self.assertRaises(RuntimeError):
|
|
publisher.request(method, route)
|
|
publisher.opener.open.assert_not_called()
|
|
|
|
def test_signed_requests_never_follow_redirects(self):
|
|
with self.assertRaisesRegex(RuntimeError, "redirect"):
|
|
publish.NoRedirect().redirect_request(None, None, 302, None, None, "https://example.org/")
|
|
with self.assertRaisesRegex(RuntimeError, "HTTPS"):
|
|
publish.HTTPSRedirect().redirect_request(None, None, 302, None, None, "http://example.org/")
|
|
|
|
def test_missing_release_is_distinct_from_failed_authentication(self):
|
|
publisher = self.make_publisher()
|
|
route = publish.REPO_API + "/releases/tags/example-v0.1.0"
|
|
for status in (401, 403, 404):
|
|
publisher.opener.open.side_effect = urllib.error.HTTPError(publish.ORIGIN + route, status, "", {}, None)
|
|
if status == 404:
|
|
self.assertIsNone(publisher.request("GET", route, allowMissing=True))
|
|
else:
|
|
with self.assertRaisesRegex(RuntimeError, f"HTTP {status}"):
|
|
publisher.request("GET", route, allowMissing=True)
|
|
|
|
def test_ambiguous_agent_keys_require_explicit_selection(self):
|
|
agent = Mock()
|
|
agent.get_keys.return_value = [self.signingKey, self.signingKey]
|
|
with patch.object(publish.paramiko, "Agent", return_value=agent):
|
|
with self.assertRaisesRegex(RuntimeError, "select it"):
|
|
publish.Publisher()
|
|
agent.close.assert_called_once()
|
|
|
|
def test_existing_release_cannot_be_overwritten(self):
|
|
publisher = self.make_publisher()
|
|
publisher.request = Mock(return_value={"id": 1})
|
|
notesPath = Mock()
|
|
notesPath.read_text.return_value = "Example release notes"
|
|
responses = [b"", "a" * 40, "a" * 40 + "\trefs/tags/example-v0.1.0\n"]
|
|
with patch.object(publish.subprocess, "check_output", side_effect=responses):
|
|
with self.assertRaisesRegex(RuntimeError, "already exists"):
|
|
publish.publish(publisher, Mock(), {}, "example-v0.1.0", [], notesPath)
|
|
self.assertEqual(publisher.request.call_count, 1)
|
|
self.assertEqual(publisher.request.call_args.args[0], "GET")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|