You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by sb...@apache.org on 2026/09/02 15:37:24 UTC
(tooling-trusted-releases) branch sbp updated: Prevent resource saturation from KEYS files, but leave big margins
This is an automated email from the ASF dual-hosted git repository.
sbp pushed a commit to branch sbp
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git
The following commit(s) were added to refs/heads/sbp by this push:
new 040e0d43 Prevent resource saturation from KEYS files, but leave big margins
040e0d43 is described below
commit 040e0d436d4ed9ca8fb07ab2895c15a980394430
Author: Sean B. Palmer <se...@miscoranda.com>
AuthorDate: Wed Sep 2 16:34:51 2026 +0100
Prevent resource saturation from KEYS files, but leave big margins
---
atr/constants.py | 2 +
atr/shared/keys.py | 3 +-
atr/storage/writers/keys.py | 96 +++++++++++++++++++++++++-----------------
tests/unit/test_keys_writer.py | 59 +++++++++++++++++++++-----
4 files changed, 111 insertions(+), 49 deletions(-)
diff --git a/atr/constants.py b/atr/constants.py
index 164f0622..6aded0ee 100644
--- a/atr/constants.py
+++ b/atr/constants.py
@@ -254,6 +254,8 @@ GENERATED_FILE_SUFFIXES: Final[tuple[str, ...]] = (
INACTIVITY_DELETE_DAYS: Final[int] = 90
INACTIVITY_WARNING_DAYS: Final[int] = 80
+KEYS_FILE_LIMIT_BYTES: Final[int] = 10 * 1024 * 1024
+
# Fixed sub claim on JWTs minted from system PATs, and the UID we log for
# their actions. The minting admin is recorded separately in PAT.created_by.
SYSTEM_SERVICE_UID: Final[str] = "system"
diff --git a/atr/shared/keys.py b/atr/shared/keys.py
index c4e72334..f6a32993 100644
--- a/atr/shared/keys.py
+++ b/atr/shared/keys.py
@@ -23,6 +23,7 @@ from typing import Annotated, Final, Literal
import markupsafe
import pydantic
+import atr.constants as constants
import atr.form as form
import atr.htm as htm
import atr.models.sql as sql
@@ -33,7 +34,7 @@ import atr.template as template
import atr.util as util
# The Apache Subversion KEYS file is largest at 3732091 bytes
-MAX_KEYS_SIZE: Final[int] = 10 * 1024 * 1024
+MAX_KEYS_SIZE: Final[int] = constants.KEYS_FILE_LIMIT_BYTES
MAX_PUBLIC_KEY_SIZE: Final[int] = 1024 * 1024
type DELETE_OPENPGP_KEY = Literal["delete_openpgp_key"]
diff --git a/atr/storage/writers/keys.py b/atr/storage/writers/keys.py
index d594d951..9f42f179 100644
--- a/atr/storage/writers/keys.py
+++ b/atr/storage/writers/keys.py
@@ -93,8 +93,11 @@ _KEY_AUDIT_ACTIONS: Final = (
(datatypes.KeyStatus.REFRESHED, "key_refresh"),
(datatypes.KeyStatus.LINKED, "key_associate_committee"),
)
+_MAX_ARMOR_BLOCKS_PER_REQUEST: Final = 256
_MAX_CERTIFICATE_BYTES: Final = 4 * 1024 * 1024
_MAX_CERTIFICATE_PLACEMENTS: Final = 16384
+_MAX_CERTIFICATES_PER_REQUEST: Final = 512
+_MAX_PACKETS_PER_REQUEST: Final = 32768
_POINTER_SOURCE_SCHEMES: Final = frozenset({"archive", "svn"})
_RSA_ALGORITHMS: Final = frozenset({1, 3})
_RSA_MINIMUM_BITS: Final = 4096
@@ -725,6 +728,7 @@ class FoundationCommitter(GeneralPublic):
return key
def __block_model_create(self, key_block: str, ldap_data: cache.EmailUidLookup) -> datatypes.Key:
+ parts, _ = pgp.certificate_parts(key_block, packet_limit=_MAX_PACKETS_PER_REQUEST)
public_keys, _ = openpgp.composed.SignedPublicKey.from_armor_many(key_block)
if len(public_keys) != 1:
raise ValueError(
@@ -738,7 +742,7 @@ class FoundationCommitter(GeneralPublic):
status=datatypes.KeyStatus.PARSED,
key_model=key_model,
member_ids=sorted(util.openpgp_member_ids(public_key)),
- input=pgp.certificate_spans(key_block)[0],
+ input=parts[0][1],
)
async def __certificate_chain(
@@ -1161,31 +1165,38 @@ class CommitteeParticipant(FoundationCommitter):
linked=bool(status & datatypes.KeyStatus.LINKED),
)
- def __block_models(self, key_block: str, ldap_data: cache.EmailUidLookup) -> list[datatypes.Key | Exception]:
- try:
- parts, _ = pgp.certificate_parts(key_block)
- except Exception as e:
- raise ValueError(f"Error loading OpenPGP key block: {e}") from e
- if not parts:
- raise ValueError("Error loading OpenPGP key block: no keys found")
+ def __block_models(self, keys_file_text: str, ldap_data: cache.EmailUidLookup) -> list[datatypes.Key | Exception]:
+ if len(keys_file_text.encode()) > constants.KEYS_FILE_LIMIT_BYTES:
+ raise pgp.LimitError(f"The KEYS file is larger than {constants.KEYS_FILE_LIMIT_BYTES} bytes")
+ if keys_file_text.count("-----BEGIN PGP PUBLIC KEY BLOCK-----") > _MAX_ARMOR_BLOCKS_PER_REQUEST:
+ raise pgp.LimitError(f"The KEYS file has more than {_MAX_ARMOR_BLOCKS_PER_REQUEST} key blocks")
+ key_blocks = util.parse_key_blocks(keys_file_text)
key_list: list[datatypes.Key | Exception] = []
- for block, span in parts:
+ packets = 0
+ certificates = 0
+ for key_block in key_blocks:
try:
- public_keys, _ = openpgp.composed.SignedPublicKey.from_armor_many(block)
- if len(public_keys) != 1:
- raise ValueError(f"Expected one certificate in the block, got {len(public_keys)}")
- key_model = self.public_key_model(public_keys[0], ldap_data, original_key_block=block)
- _validate_key_strength(public_keys[0])
- key = datatypes.Key(
- status=datatypes.KeyStatus.PARSED,
- key_model=key_model,
- member_ids=sorted(util.openpgp_member_ids(public_keys[0])),
- input=span,
+ parts, used = pgp.certificate_parts(
+ key_block, packet_limit=_MAX_PACKETS_PER_REQUEST, certificate_limit=_MAX_CERTIFICATES_PER_REQUEST
)
- key_list.append(key)
+ if not parts:
+ raise ValueError("no keys found")
+ except pgp.LimitError:
+ raise
except Exception as e:
- key_list.append(e)
- return key_list
+ parts, used = [], len(key_block) * 3 // 8
+ key_list.append(ValueError(f"Error loading OpenPGP key block: {e}"))
+ packets += used
+ certificates += len(parts)
+ self.__check_budget(packets, certificates)
+ key_list.extend(self.__part_models(parts, ldap_data))
+ return _deduplicate_keys(key_list)
+
+ def __check_budget(self, packets: int, certificates: int) -> None:
+ if packets > _MAX_PACKETS_PER_REQUEST:
+ raise pgp.LimitError(f"The KEYS file has more than {_MAX_PACKETS_PER_REQUEST} packets")
+ if certificates > _MAX_CERTIFICATES_PER_REQUEST:
+ raise pgp.LimitError(f"The KEYS file has more than {_MAX_CERTIFICATES_PER_REQUEST} certificates")
async def __database_add_models(
self, outcomes: outcome.List[datatypes.Key], source: str, associate: bool = True
@@ -1270,25 +1281,12 @@ class CommitteeParticipant(FoundationCommitter):
outcomes = outcome.List[datatypes.Key]()
try:
ldap_data = await cache.email_uid_view_or_live()
- key_blocks = util.parse_key_blocks(keys_file_text)
+ # TODO: Change self.__block_models to return outcomes
+ roes = await asyncio.to_thread(self.__block_models, keys_file_text, ldap_data)
except Exception as e:
outcomes.append_error(e)
return outcomes, {}
- # TODO: Change self.__block_models to return outcomes
- tasks = [
- asyncio.create_task(asyncio.to_thread(self.__block_models, key_block, ldap_data))
- for key_block in key_blocks
- ]
- key_model_batches = await asyncio.gather(*tasks, return_exceptions=True)
- roes: list[datatypes.Key | Exception] = []
- for key_model_batch in key_model_batches:
- if isinstance(key_model_batch, Exception):
- roes.append(key_model_batch)
- elif isinstance(key_model_batch, BaseException):
- raise key_model_batch
- else:
- roes.extend(key_model_batch)
- outcomes.extend_roes(Exception, await asyncio.to_thread(_deduplicate_keys, roes))
+ outcomes.extend_roes(Exception, roes)
# Try adding the keys to the database
# If not, all keys will be replaced with a PostParseError
return await self.__database_add_models(outcomes, source, associate=associate)
@@ -1303,6 +1301,28 @@ class CommitteeParticipant(FoundationCommitter):
)
return link_insert_result.one_or_none() is not None
+ def __part_models(
+ self, parts: list[tuple[str, bytes]], ldap_data: cache.EmailUidLookup
+ ) -> list[datatypes.Key | Exception]:
+ key_list: list[datatypes.Key | Exception] = []
+ for block, span in parts:
+ try:
+ public_keys, _ = openpgp.composed.SignedPublicKey.from_armor_many(block)
+ if len(public_keys) != 1:
+ raise ValueError(f"Expected one certificate in the block, got {len(public_keys)}")
+ key_model = self.public_key_model(public_keys[0], ldap_data, original_key_block=block)
+ _validate_key_strength(public_keys[0])
+ key = datatypes.Key(
+ status=datatypes.KeyStatus.PARSED,
+ key_model=key_model,
+ member_ids=sorted(util.openpgp_member_ids(public_keys[0])),
+ input=span,
+ )
+ key_list.append(key)
+ except Exception as e:
+ key_list.append(e)
+ return key_list
+
async def __signature_hints_consume(self, keys: list[datatypes.Key]) -> list[str]:
via = sql.validate_instrumented_attribute
member_map = {key.key_model.fingerprint: set(key.member_ids) for key in keys}
diff --git a/tests/unit/test_keys_writer.py b/tests/unit/test_keys_writer.py
index af96ee15..ed9fc934 100644
--- a/tests/unit/test_keys_writer.py
+++ b/tests/unit/test_keys_writer.py
@@ -177,6 +177,27 @@ def test_block_models_reports_a_failing_certificate_without_losing_its_siblings(
assert isinstance(keys[1], ValueError)
+def test_block_models_rejects_a_keys_file_over_its_packet_budget(monkeypatch) -> None:
+ writer, _write_as = _make_committee_member(MockData(None, committees_after_commit={}), "test")
+ block = pgp_fixtures.EXPIRED_SUBKEY_PUBLIC_KEY_ASC
+ _, packets = pgp.certificate_parts(block)
+ monkeypatch.setattr(keys_writer, "_MAX_PACKETS_PER_REQUEST", packets)
+ lookup = keys_writer.cache.EmailUidLookup({})
+
+ assert len(writer._CommitteeParticipant__block_models(block, lookup)) == 1
+ with pytest.raises(pgp.LimitError, match="KEYS file has more than"):
+ writer._CommitteeParticipant__block_models(block + block, lookup)
+
+
+def test_block_models_rejects_a_keys_file_over_the_byte_limit(monkeypatch) -> None:
+ writer, _write_as = _make_committee_member(MockData(None, committees_after_commit={}), "test")
+ text = "\u00e9" * 8
+ monkeypatch.setattr(keys_writer.constants, "KEYS_FILE_LIMIT_BYTES", len(text) + 1)
+
+ with pytest.raises(pgp.LimitError, match="larger than"):
+ writer._CommitteeParticipant__block_models(text, keys_writer.cache.EmailUidLookup({}))
+
+
@pytest.mark.asyncio
async def test_database_add_model_writes_a_genesis_row_and_audits_the_insert(sqlite_data):
writer, _write, write_as = _make_foundation_committer_with_audit(sqlite_data)
@@ -439,7 +460,6 @@ async def test_ensure_allows_key_without_apache_uid_for_bulk_import() -> None:
mock.patch.object(
keys_writer.cache, "email_uid_view_or_live", new=mock.AsyncMock(return_value=lookup)
) as email_uid_view,
- mock.patch.object(keys_writer.util, "parse_key_blocks", return_value=["block-one"]),
mock.patch.object(writer, "_CommitteeParticipant__block_models", return_value=[key]) as block_models,
mock.patch.object(
writer,
@@ -452,12 +472,37 @@ async def test_ensure_allows_key_without_apache_uid_for_bulk_import() -> None:
assert result is database_outcomes
assert publications == {}
email_uid_view.assert_awaited_once()
- block_models.assert_called_once_with("block-one", lookup)
+ block_models.assert_called_once_with("keys text", lookup)
database_add_models.assert_awaited_once()
parsed_outcomes = database_add_models.await_args.args[0]
assert parsed_outcomes.result_count == 1
+@pytest.mark.asyncio
+async def test_ensure_rejects_a_keys_file_over_budget_before_the_database(monkeypatch) -> None:
+ data = MockData(None, committees_after_commit={})
+ writer, _write_as = _make_foundation_admin(data, "alpha")
+ monkeypatch.setattr(keys_writer, "_MAX_ARMOR_BLOCKS_PER_REQUEST", 1)
+ text = pgp_fixtures.EXPIRED_SUBKEY_PUBLIC_KEY_ASC + pgp_fixtures.REVOKED_SUBKEY_PUBLIC_KEY_ASC
+
+ with (
+ mock.patch.object(
+ keys_writer.cache,
+ "email_uid_view_or_live",
+ new=mock.AsyncMock(return_value=keys_writer.cache.EmailUidLookup({})),
+ ),
+ mock.patch.object(
+ writer, "_CommitteeParticipant__database_add_models", new=mock.AsyncMock()
+ ) as database_add_models,
+ ):
+ result, publications = await writer._CommitteeParticipant__ensure(text, "web:req-1")
+
+ assert (result.result_count, result.error_count) == (0, 1)
+ assert "more than 1 key blocks" in str(result.errors()[0])
+ assert publications == {}
+ database_add_models.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_ensure_stored_one_accepts_key_with_apache_uid() -> None:
data = MockData(None, committees_after_commit={})
@@ -583,14 +628,10 @@ async def test_ensure_uses_cached_email_lookup_for_bulk_import() -> None:
mock.patch.object(
keys_writer.cache, "email_uid_view_or_live", new=mock.AsyncMock(return_value=lookup)
) as email_uid_view,
- mock.patch.object(keys_writer.util, "parse_key_blocks", return_value=["block-one", "block-two"]),
mock.patch.object(
writer,
"_CommitteeParticipant__block_models",
- side_effect=[
- [SimpleNamespace(fingerprint="one")],
- [SimpleNamespace(fingerprint="two")],
- ],
+ return_value=[SimpleNamespace(fingerprint="one"), SimpleNamespace(fingerprint="two")],
) as block_models,
mock.patch.object(
writer,
@@ -602,9 +643,7 @@ async def test_ensure_uses_cached_email_lookup_for_bulk_import() -> None:
assert result is database_outcomes
email_uid_view.assert_awaited_once()
- assert block_models.call_count == 2
- assert {call.args[0] for call in block_models.call_args_list} == {"block-one", "block-two"}
- assert all(call.args[1] is lookup for call in block_models.call_args_list)
+ block_models.assert_called_once_with("keys text", lookup)
database_add_models.assert_awaited_once()
parsed_outcomes = database_add_models.await_args.args[0]
assert parsed_outcomes.result_count == 2
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org