TidorP commited on
Commit
ddf04fa
·
verified ·
1 Parent(s): 2e2be96

Review selected tasks, correct cyber reference cache identity, and clarify reproducibility setup

Browse files
.dockerignore CHANGED
@@ -7,7 +7,18 @@
7
  !selection.json
8
  !samples.py
9
  !engine_entry.py
 
 
 
 
 
 
 
 
 
 
10
  **/__pycache__
11
  **/*.pyc
12
  **/.env
13
  **/.env.*
 
 
7
  !selection.json
8
  !samples.py
9
  !engine_entry.py
10
+ !docs/
11
+ !docs/**
12
+ !tests/
13
+ !tests/**
14
+ !README.md
15
+ !VALIDATION.md
16
+ !CHANGES.md
17
+ !LICENSE.txt
18
+ !SOURCE_MANIFEST.json
19
+ !CHECKSUMS.json
20
  **/__pycache__
21
  **/*.pyc
22
  **/.env
23
  **/.env.*
24
+ !.env.example
CHANGES.md CHANGED
@@ -8,6 +8,8 @@ The source is `Poindexter-Labs/PDL-Bench` revision `d68375b39ff4e7dc69e9ee9107d4
8
  - The STEM tasks follow the revised PDF. PDS136 adds the justification requirement and ten-point rubric. PDS049 follows the reviewed prompt, stereochemistry guidance and seven-point rubric. Its two two-point criteria are split into pairs of one-point checks to represent their stated partial credit. Sample full-credit reporting uses 100%; the old historical chart used a different protocol.
9
  - The Q&A evaluator image includes `PyYAML==6.0.3`, needed by this task's hidden document-property checks. It has its own `poindexter-samples/sweqna:20261118` tag so it cannot reuse an older evaluator lacking that dependency. Non-test pytest failures, including collection errors, now remain technical failures instead of being mistaken for an evaluated submission.
10
  - The Q&A reference answer explicitly states the recipe/build/request/lock/wire identity domains and token 71's outcomes, checked against the supplied contracts, journal and candidate patches. The original reference patch is retained at `docs/upstream-qna014-gold.diff`. The selected task prompt, repository, hidden tests and rubric are unchanged. The revised patch hash and reference revision are in the task index.
 
 
11
 
12
  `engines/*/vendor/SOURCE_MANIFEST.json` files retain the upstream provenance. They describe the upstream export, not this adapted release. The root `SOURCE_MANIFEST.json` records deviations and the root `CHECKSUMS.json` provides this release's file hashes.
13
 
 
8
  - The STEM tasks follow the revised PDF. PDS136 adds the justification requirement and ten-point rubric. PDS049 follows the reviewed prompt, stereochemistry guidance and seven-point rubric. Its two two-point criteria are split into pairs of one-point checks to represent their stated partial credit. Sample full-credit reporting uses 100%; the old historical chart used a different protocol.
9
  - The Q&A evaluator image includes `PyYAML==6.0.3`, needed by this task's hidden document-property checks. It has its own `poindexter-samples/sweqna:20261118` tag so it cannot reuse an older evaluator lacking that dependency. Non-test pytest failures, including collection errors, now remain technical failures instead of being mistaken for an evaluated submission.
10
  - The Q&A reference answer explicitly states the recipe/build/request/lock/wire identity domains and token 71's outcomes, checked against the supplied contracts, journal and candidate patches. The original reference patch is retained at `docs/upstream-qna014-gold.diff`. The selected task prompt, repository, hidden tests and rubric are unchanged. The revised patch hash and reference revision are in the task index.
11
+ - The cyber reference cache key now includes both initial policy-inhibition flags. Independent review reproduced an incorrect cached success when the policy was tightened. Two reference-only regression checks fail on the original and pass on this correction; the original is preserved at `docs/upstream-cyber02-gold.diff`. The prompt, starter repository, hidden tests and scoring are unchanged. The task index records the revised reference hash.
12
+ - README now includes a complete credentials/setup checklist. Documentation, references and offline checks are copied into the controller alongside task data and runners.
13
 
14
  `engines/*/vendor/SOURCE_MANIFEST.json` files retain the upstream provenance. They describe the upstream export, not this adapted release. The root `SOURCE_MANIFEST.json` records deviations and the root `CHECKSUMS.json` provides this release's file hashes.
15
 
CHECKSUMS.json CHANGED
@@ -1,20 +1,20 @@
1
  {
2
- ".dockerignore": "81311b78fd4a1e624248b18f43973981d335a71ebc4659509b09c48507581cd5",
3
  ".env.example": "c4578caa1501db2d80e47a890e8bff5f9ce504945f183ca7904682127bea2a4a",
4
  ".gitignore": "e4ac768ff4b44abbd7a083a152e227c6b43ca23a0434e8276cbb86e04fa935fa",
5
- "CHANGES.md": "08d04eb9b8edc9d9ca8d70ed830902cf3f994e15e36d72997703bb53dc0c937c",
6
- "Dockerfile": "c01b6258d19017b5b9748250fbd35c5dd4d1656b54fa636640a730da2f55732e",
7
  "LICENSE.txt": "d557539df68e771cc1eedcc91d13f70fca930e508d11eedcafa4b15db49e3744",
8
- "README.md": "4cf6aa25d9a3e23b5a6fa97458a0c4fd52f3ebba5a8c5ecb47272176c486806d",
9
- "SOURCE_MANIFEST.json": "f2c522b8a39c5dc62163a2c95321ef63bdc19e66da1e95c3f6d0d820057bdee6",
10
- "VALIDATION.md": "9f3f209f5c67fdc363978dceba537d3c91c3179f85f3137d91d502ababe49c58",
11
  "data/cyber/environments/swe/Dockerfile": "3e5119f1bcae3947605014ce8f0182b74d66f1a6f4d223a7c298650eb12ad099",
12
  "data/cyber/environments/sweqna/Dockerfile": "706ef5bbcbcc05e02c6dbfa125a3bbf7e01f3716d2ce653132484e15b78299e3",
13
- "data/cyber/tasks/swe_rl_cybersecurity_task_02/gold.diff": "744256d9e7e06f4321135e5cacaab514e3a9cfceead1fc5a4156611b0f1a1b96",
14
  "data/cyber/tasks/swe_rl_cybersecurity_task_02/hidden_tests.zip": "c1604193fbfea16d1be7eb6eb4139e8d6748dad13c6f63a426d43433fb747690",
15
  "data/cyber/tasks/swe_rl_cybersecurity_task_02/manifest.yaml": "e92fe8ed5135302bc2f370dce4af45de3322d9b65befb7b33c92823c8e41d740",
16
  "data/cyber/tasks/swe_rl_cybersecurity_task_02/repository.zip": "1e14841c5546682e9bbbd6886b15105a172a0aacd9bf945e8393aef62a0c1898",
17
- "data/cyber/tasks.jsonl": "702efb222ac3084138d6f291008d0dee3f373f0b1f8594090ab4f7d554d3cb08",
18
  "data/gdpval/inputs/french-43dc9778-450b-4b46-b77e-b6d82b202035/01_Questionnaire_foyer_2024.pdf": "1cf05c90bffca8e39d0a07169c1fda4e2237b8243dd89de5779f5678d862ef89",
19
  "data/gdpval/inputs/french-43dc9778-450b-4b46-b77e-b6d82b202035/02_Salaires_Laurent_Conseil_Lumiere_2024.pdf": "3054db93d3232e7e6e1cb469730a26fa2de3732ae9aa50f490831753065dc31f",
20
  "data/gdpval/inputs/french-43dc9778-450b-4b46-b77e-b6d82b202035/03_Salaires_Laurent_Services_Rhone_2024.pdf": "2e4a9ece78a908167a1f1513fb702398be1e27aa55189f7ff688d7dcf2a3f271",
@@ -41,11 +41,13 @@
41
  "data/qna/tasks/pdl_qna_signed_package_resolution_014/repository.zip": "a21ae55b8829b0ba5ae57fd780934bf9a7b956d640c80535ad12c927a1933d68",
42
  "data/qna/tasks.jsonl": "dbc6f10b77507b88e8ab8c627590707b77b1310ef2450f9bde0b471b18b5cdb7",
43
  "data/stem/tasks.jsonl": "0b2d70a6070b207f82af28851f0c93d3881b2050ae9f5b7d3eea88c91c72d537",
 
44
  "docs/GDPVal.md": "6d6e9f2ee300986b520bc9f59a6ed0e23381c53b5b687a054261f88333e77bf2",
45
  "docs/PDS049.md": "c5f2d509a27a6c30e0e4c79e73a1bab4e29c24f5f9b3980c82bf76587aa01b87",
46
  "docs/PDS136.md": "ec455bd4da846ae9bcd3ec92c947804ce9d3f5652a2e296a3708aab86bd4ebb8",
47
  "docs/STEM Data Samples.pdf": "1f3d2360a83a37bbbe9547e974e8652a4fb7422481fb3650578e9d58a731d802",
48
  "docs/qna014-reference.md": "35888b82d26d5d3f92dc87445941df7c7d86211f4337c7ad11f166820b849ed2",
 
49
  "docs/upstream-qna014-gold.diff": "be8d83b21da44a7c5ae225a6f1a428c6878b9cc43452056451032b58e62ac747",
50
  "engine_entry.py": "0d01ad7cfd7900a9b8fc8630050da9be66436c9f6821140238eb3d22907ed771",
51
  "engines/code/THIRD_PARTY.md": "4ebc7acca167df52913c031fb699d6a36bc8b5c6df184f78a1f0d48cba267ada",
@@ -149,6 +151,7 @@
149
  "engines/general/vendor/tools/rl_env/build_template.py": "7b54e5612525e03e2ee35d28d808f9ab1ffd34c23c3bff0beb98288f43f3d77d",
150
  "samples.py": "804c5b665c8fee5892437a3290d2d703bb806737043e1bbc7a5057c06acdf106",
151
  "selection.json": "83ac1ba6359322c1bb01d24240e73ccbe3186130036a81e10a8cb193dc023ec5",
 
152
  "tests/check_math.py": "2e72177c0ff2a268db7151af5299b16404e24de76ce988791940ddd751a3ec09",
153
  "tests/live_gdpval_anthropic.py": "be8961c71e8eedd1e3ed051560973dfb02f0201dd8bcf5f2c2c4f8527161daae",
154
  "tests/live_provider_tools.py": "cce723e4c285b4bd4c2e338425616d17ea97672b40f986d733eb72bfb1792cf6",
 
1
  {
2
+ ".dockerignore": "510202477bc22d95d9e58cf620808eade1307725cf51e2b362362b9853bcfd5c",
3
  ".env.example": "c4578caa1501db2d80e47a890e8bff5f9ce504945f183ca7904682127bea2a4a",
4
  ".gitignore": "e4ac768ff4b44abbd7a083a152e227c6b43ca23a0434e8276cbb86e04fa935fa",
5
+ "CHANGES.md": "42e53ef7672f06dbd1d2d5f74b1a80d496093e9c32fe80fadc7ab6e85d169371",
6
+ "Dockerfile": "7513da253f47143093bc8aa6ec82822e441ba58e085201a312f1faad18a46c4e",
7
  "LICENSE.txt": "d557539df68e771cc1eedcc91d13f70fca930e508d11eedcafa4b15db49e3744",
8
+ "README.md": "b9fa5d150ff957bbbb8107f757372e56d5cbcbeacc2be74e68e6ec9621aed532",
9
+ "SOURCE_MANIFEST.json": "0a1d8706dfcff6ce180df20f851016df68b6f3724179816a5d0cdf91d1d94eac",
10
+ "VALIDATION.md": "30ce7621489ab87c6505f7891c63bb71e310c92c42c599fccd37af76e326128c",
11
  "data/cyber/environments/swe/Dockerfile": "3e5119f1bcae3947605014ce8f0182b74d66f1a6f4d223a7c298650eb12ad099",
12
  "data/cyber/environments/sweqna/Dockerfile": "706ef5bbcbcc05e02c6dbfa125a3bbf7e01f3716d2ce653132484e15b78299e3",
13
+ "data/cyber/tasks/swe_rl_cybersecurity_task_02/gold.diff": "0a482685a0754709d77ead55d03d59a4a7e014ee01415f6ab46aa7b8ce5262ba",
14
  "data/cyber/tasks/swe_rl_cybersecurity_task_02/hidden_tests.zip": "c1604193fbfea16d1be7eb6eb4139e8d6748dad13c6f63a426d43433fb747690",
15
  "data/cyber/tasks/swe_rl_cybersecurity_task_02/manifest.yaml": "e92fe8ed5135302bc2f370dce4af45de3322d9b65befb7b33c92823c8e41d740",
16
  "data/cyber/tasks/swe_rl_cybersecurity_task_02/repository.zip": "1e14841c5546682e9bbbd6886b15105a172a0aacd9bf945e8393aef62a0c1898",
17
+ "data/cyber/tasks.jsonl": "085e04cfa999060ff21e8e1f6b7d816502ca862964345e7e6b9058a6384937ee",
18
  "data/gdpval/inputs/french-43dc9778-450b-4b46-b77e-b6d82b202035/01_Questionnaire_foyer_2024.pdf": "1cf05c90bffca8e39d0a07169c1fda4e2237b8243dd89de5779f5678d862ef89",
19
  "data/gdpval/inputs/french-43dc9778-450b-4b46-b77e-b6d82b202035/02_Salaires_Laurent_Conseil_Lumiere_2024.pdf": "3054db93d3232e7e6e1cb469730a26fa2de3732ae9aa50f490831753065dc31f",
20
  "data/gdpval/inputs/french-43dc9778-450b-4b46-b77e-b6d82b202035/03_Salaires_Laurent_Services_Rhone_2024.pdf": "2e4a9ece78a908167a1f1513fb702398be1e27aa55189f7ff688d7dcf2a3f271",
 
41
  "data/qna/tasks/pdl_qna_signed_package_resolution_014/repository.zip": "a21ae55b8829b0ba5ae57fd780934bf9a7b956d640c80535ad12c927a1933d68",
42
  "data/qna/tasks.jsonl": "dbc6f10b77507b88e8ab8c627590707b77b1310ef2450f9bde0b471b18b5cdb7",
43
  "data/stem/tasks.jsonl": "0b2d70a6070b207f82af28851f0c93d3881b2050ae9f5b7d3eea88c91c72d537",
44
+ "docs/ACCURACY_REVIEW.md": "40906a599f56a029b9c971548c8f89ce60c1d24a5d7a942c722e148c90cb4401",
45
  "docs/GDPVal.md": "6d6e9f2ee300986b520bc9f59a6ed0e23381c53b5b687a054261f88333e77bf2",
46
  "docs/PDS049.md": "c5f2d509a27a6c30e0e4c79e73a1bab4e29c24f5f9b3980c82bf76587aa01b87",
47
  "docs/PDS136.md": "ec455bd4da846ae9bcd3ec92c947804ce9d3f5652a2e296a3708aab86bd4ebb8",
48
  "docs/STEM Data Samples.pdf": "1f3d2360a83a37bbbe9547e974e8652a4fb7422481fb3650578e9d58a731d802",
49
  "docs/qna014-reference.md": "35888b82d26d5d3f92dc87445941df7c7d86211f4337c7ad11f166820b849ed2",
50
+ "docs/upstream-cyber02-gold.diff": "744256d9e7e06f4321135e5cacaab514e3a9cfceead1fc5a4156611b0f1a1b96",
51
  "docs/upstream-qna014-gold.diff": "be8d83b21da44a7c5ae225a6f1a428c6878b9cc43452056451032b58e62ac747",
52
  "engine_entry.py": "0d01ad7cfd7900a9b8fc8630050da9be66436c9f6821140238eb3d22907ed771",
53
  "engines/code/THIRD_PARTY.md": "4ebc7acca167df52913c031fb699d6a36bc8b5c6df184f78a1f0d48cba267ada",
 
151
  "engines/general/vendor/tools/rl_env/build_template.py": "7b54e5612525e03e2ee35d28d808f9ab1ffd34c23c3bff0beb98288f43f3d77d",
152
  "samples.py": "804c5b665c8fee5892437a3290d2d703bb806737043e1bbc7a5057c06acdf106",
153
  "selection.json": "83ac1ba6359322c1bb01d24240e73ccbe3186130036a81e10a8cb193dc023ec5",
154
+ "tests/check_cyber_reference.py": "e82803c8b8fa87c310c79fdff31fa3d54e39ece48c216bc3f8a678dbdce72e20",
155
  "tests/check_math.py": "2e72177c0ff2a268db7151af5299b16404e24de76ce988791940ddd751a3ec09",
156
  "tests/live_gdpval_anthropic.py": "be8961c71e8eedd1e3ed051560973dfb02f0201dd8bcf5f2c2c4f8527161daae",
157
  "tests/live_provider_tools.py": "cce723e4c285b4bd4c2e338425616d17ea97672b40f986d733eb72bfb1792cf6",
Dockerfile CHANGED
@@ -11,6 +11,9 @@ RUN python -m venv /opt/venvs/code && /opt/venvs/code/bin/pip install --no-cache
11
  WORKDIR /opt/samples
12
  COPY engines ./engines
13
  COPY data ./data
 
 
 
14
  COPY selection.json samples.py engine_entry.py ./
15
  RUN mkdir -p /results
16
  ENTRYPOINT ["python", "/opt/samples/samples.py"]
 
11
  WORKDIR /opt/samples
12
  COPY engines ./engines
13
  COPY data ./data
14
+ COPY docs ./docs
15
+ COPY tests ./tests
16
+ COPY README.md VALIDATION.md CHANGES.md LICENSE.txt SOURCE_MANIFEST.json CHECKSUMS.json .env.example ./
17
  COPY selection.json samples.py engine_entry.py ./
18
  RUN mkdir -p /results
19
  ENTRYPOINT ["python", "/opt/samples/samples.py"]
README.md CHANGED
@@ -48,9 +48,10 @@ For a readable introduction, see [STEM Data Samples.pdf](docs/STEM%20Data%20Samp
48
 
49
  ## Quick start
50
 
51
- Install Docker and clone this dataset with Git LFS, or download it with `hf download`:
52
 
53
  ```sh
 
54
  hf download Poindexter-Labs/Samples --repo-type dataset --local-dir samples
55
  cd samples
56
  docker build -t poindexter-samples .
@@ -79,6 +80,16 @@ docker run --rm --env-file .env -v "$PWD/results:/results" \
79
 
80
  ## Run all seven
81
 
 
 
 
 
 
 
 
 
 
 
82
  GDPVal uses the same E2B environment as the public Mini-Bench package. It additionally needs `E2B_API_KEY`, `GDPVAL_E2B_TEMPLATE_ID`, and `BRAVE_API_KEY`. If you do not already have an appropriate template, build it once in your own E2B account:
83
 
84
  ```sh
@@ -118,6 +129,8 @@ docker run --rm -v "$PWD/results:/results" poindexter-samples report --group all
118
 
119
  Use the same provider/model/options when resuming or grading. A changed configuration is recorded separately. `--retry-failed` explicitly permits a failed solver attempt to run again. Technical failures stay ungraded and are not counted as incorrect model answers.
120
 
 
 
121
  ## Scoring and provenance
122
 
123
  - **GDPVal:** the selected localized prompts, rubrics and inputs are preserved. The rubric evaluator reports a normalized score and the Mini-Bench 95% pass threshold. The French reference deliverable is included under `data/gdpval/references/` for human inspection; it is not supplied to the solver.
@@ -129,7 +142,7 @@ The repository tasks retain the published 2M-token profiles, including their lon
129
 
130
  Runner code and repository tasks originate from [Poindexter-Labs/PDL-Bench](https://huggingface.co/datasets/Poindexter-Labs/PDL-Bench), pinned to `d68375b39ff4e7dc69e9ee9107d475d3ee9808b4`. `SOURCE_MANIFEST.json` records the selected inputs and packaging adaptations; `CHECKSUMS.json` covers this release. Vendored notices and licenses are retained under `engines/`. Separate Python environments preserve the two upstream runners' dependency pins inside one image.
131
 
132
- For validation results and their limits, see [VALIDATION.md](VALIDATION.md).
133
 
134
  ## Reference baselines
135
 
 
48
 
49
  ## Quick start
50
 
51
+ Install Docker and Python. Clone this dataset with Git LFS, or install the Hugging Face CLI and download it:
52
 
53
  ```sh
54
+ python -m pip install --upgrade huggingface_hub
55
  hf download Poindexter-Labs/Samples --repo-type dataset --local-dir samples
56
  cd samples
57
  docker build -t poindexter-samples .
 
80
 
81
  ## Run all seven
82
 
83
+ Before running all seven, you need:
84
+
85
+ | Setting | Used for |
86
+ | --- | --- |
87
+ | `OPENAI_API_KEY` and `ANTHROPIC_API_KEY` | Native model calls and the two-provider Q&A judge panel |
88
+ | Model IDs available to your accounts | Solver and judge settings in `.env.example` |
89
+ | `E2B_API_KEY` and `GDPVAL_E2B_TEMPLATE_ID` | GDPVal document-execution environment |
90
+ | `BRAVE_API_KEY` | GDPVal web research |
91
+ | Running Docker and the socket mount below | Code-task sandboxes and evaluators |
92
+
93
  GDPVal uses the same E2B environment as the public Mini-Bench package. It additionally needs `E2B_API_KEY`, `GDPVAL_E2B_TEMPLATE_ID`, and `BRAVE_API_KEY`. If you do not already have an appropriate template, build it once in your own E2B account:
94
 
95
  ```sh
 
129
 
130
  Use the same provider/model/options when resuming or grading. A changed configuration is recorded separately. `--retry-failed` explicitly permits a failed solver attempt to run again. Technical failures stay ungraded and are not counted as incorrect model answers.
131
 
132
+ GDPVal submissions are limited to 20 files, 10 MiB per file and 25 MiB total by the inherited runner. Oversized output is rejected before grading. The French live smoke run produced a 19.3 MB PDF and hit this limit; its smaller supplied human reference graded successfully. See the validation record for this remaining execution limitation.
133
+
134
  ## Scoring and provenance
135
 
136
  - **GDPVal:** the selected localized prompts, rubrics and inputs are preserved. The rubric evaluator reports a normalized score and the Mini-Bench 95% pass threshold. The French reference deliverable is included under `data/gdpval/references/` for human inspection; it is not supplied to the solver.
 
142
 
143
  Runner code and repository tasks originate from [Poindexter-Labs/PDL-Bench](https://huggingface.co/datasets/Poindexter-Labs/PDL-Bench), pinned to `d68375b39ff4e7dc69e9ee9107d475d3ee9808b4`. `SOURCE_MANIFEST.json` records the selected inputs and packaging adaptations; `CHECKSUMS.json` covers this release. Vendored notices and licenses are retained under `engines/`. Separate Python environments preserve the two upstream runners' dependency pins inside one image.
144
 
145
+ For validation results and their limits, see [VALIDATION.md](VALIDATION.md). The [five-task accuracy review](docs/ACCURACY_REVIEW.md) records the independent checks and the corrected cyber reference. Documentation, input files, references and offline checks are also included inside the controller at `/opt/samples`.
146
 
147
  ## Reference baselines
148
 
SOURCE_MANIFEST.json CHANGED
@@ -78,5 +78,14 @@
78
  }
79
  ],
80
  "changes": "CHANGES.md",
81
- "public_data_policy": "Task content, localized inputs, reference material and public runners only; no production audit records, credentials, staff workflow fields or account configuration."
 
 
 
 
 
 
 
 
 
82
  }
 
78
  }
79
  ],
80
  "changes": "CHANGES.md",
81
+ "public_data_policy": "Task content, localized inputs, reference material and public runners only; no production audit records, credentials, staff workflow fields or account configuration.",
82
+ "reference_adaptations": [
83
+ {
84
+ "task": "swe_rl_cybersecurity_task_02",
85
+ "revision": "samples-cache-policy-flags-v1",
86
+ "original": "docs/upstream-cyber02-gold.diff",
87
+ "description": "Restore both initial policy-inhibition flags in reference cache identity; original prompt/repository/hidden tests/scoring unchanged."
88
+ }
89
+ ],
90
+ "accuracy_review": "docs/ACCURACY_REVIEW.md"
91
  }
VALIDATION.md CHANGED
@@ -10,6 +10,7 @@ These are execution and packaging checks, not benchmark estimates. A model can r
10
  | Native Anthropic code adapter | Real native API tool call and tool-result continuation passed |
11
  | Native Anthropic GDPVal adapter | Real adaptive-thinking tool call and signed assistant/tool-result passback passed |
12
  | `cyber_02` reference patch | Actual Docker agent submission and evaluator: reward 1.0 |
 
13
  | `cyber_02` unchanged repository | Actual Docker submission and evaluator: reward 0.0 |
14
  | `qna014` corrected reference answer | Actual Docker submission and two native judges: reward 1.0; all 6 file-property checks passed |
15
  | Completed Q&A attempt resume | Repeated CLI run preserved all attempt records and needed no valid provider credentials |
@@ -17,11 +18,13 @@ These are execution and packaging checks, not benchmark estimates. A model can r
17
  | PDS049 native Anthropic solve | Completed and graded through native OpenAI; seven-point rubric executed successfully |
18
  | PDS136 counting arithmetic | Independent exact Burnside enumeration matches D8=4864, SD16=37248, S3=502, S4=32923 and the final prime factorization |
19
  | German GDPVal native OpenAI solve | Completed: presentation and PDF saved, rubric grade returned successfully |
 
 
20
  | French reference deliverable grading | All 15 supplied input PDFs and the 17-page reference PDF processed; score 100%, 67 rubric criteria |
21
  | Anonymous public download | All 154 indexed file hashes matched; the downloaded Docker package built successfully and planned all seven tasks |
22
  | Public artifact audit | Python/JSON parsing, archive inspection, no known credential values, no production audit records or runtime secrets included |
23
 
24
- At initial publication, the longer native OpenAI attempts for PDS136 and the Japanese GDPVal task were still running; the French native solver attempt was queued after the Japanese task in the GDPVal validation run. These are **not claimed as completed end-to-end model solves**. The French grading result above uses the supplied human reference, not a newly generated answer.
25
 
26
  The mathematical count check validates the finite-group arithmetic, not an independent proof of the block-Picard classification theorem. Live provider/tool tests do not establish that every account has access to the example model IDs. No AMD64 build or fresh E2B template build in an unrelated researcher account was performed during this validation; the documented template builder is the existing pinned Mini-Bench implementation.
27
 
@@ -32,6 +35,7 @@ To repeat offline checks after building:
32
  ```sh
33
  SAMPLES_IMAGE=poindexter-samples python tests/smoke.py
34
  python tests/check_math.py
 
35
  ```
36
 
37
  The two `tests/live_*.py` scripts are optional paid API tests. Run them inside the controller using the corresponding `/opt/venvs/code/bin/python` or `/opt/venvs/general/bin/python`, with your own API environment and `tests/` mounted at `/test`. They do not run as part of the offline smoke suite.
 
10
  | Native Anthropic code adapter | Real native API tool call and tool-result continuation passed |
11
  | Native Anthropic GDPVal adapter | Real adaptive-thinking tool call and signed assistant/tool-result passback passed |
12
  | `cyber_02` reference patch | Actual Docker agent submission and evaluator: reward 1.0 |
13
+ | `cyber_02` cache regression review | Both policy-inhibition regressions fail on the original reference and pass on the corrected reference; corrected reference rerun through actual Docker CLI/evaluator: reward 1.0 |
14
  | `cyber_02` unchanged repository | Actual Docker submission and evaluator: reward 0.0 |
15
  | `qna014` corrected reference answer | Actual Docker submission and two native judges: reward 1.0; all 6 file-property checks passed |
16
  | Completed Q&A attempt resume | Repeated CLI run preserved all attempt records and needed no valid provider credentials |
 
18
  | PDS049 native Anthropic solve | Completed and graded through native OpenAI; seven-point rubric executed successfully |
19
  | PDS136 counting arithmetic | Independent exact Burnside enumeration matches D8=4864, SD16=37248, S3=502, S4=32923 and the final prime factorization |
20
  | German GDPVal native OpenAI solve | Completed: presentation and PDF saved, rubric grade returned successfully |
21
+ | Japanese GDPVal native OpenAI solve | Completed and graded: Word document, score 100% |
22
+ | French GDPVal native OpenAI solve | Produced a 19,347,709-byte PDF; rejected by the inherited 10 MiB per-file artifact limit before grading |
23
  | French reference deliverable grading | All 15 supplied input PDFs and the 17-page reference PDF processed; score 100%, 67 rubric criteria |
24
  | Anonymous public download | All 154 indexed file hashes matched; the downloaded Docker package built successfully and planned all seven tasks |
25
  | Public artifact audit | Python/JSON parsing, archive inspection, no known credential values, no production audit records or runtime secrets included |
26
 
27
+ The Japanese live run has now completed. The French live solver produced a 35-page PDF but its 19,347,709-byte file exceeded the inherited 10 MiB per-file collection limit; this attempt is `SOLVER_FAILED`, not a graded incorrect answer. The reference grading result above uses the supplied human reference, not that newly generated answer. A completed native model solve is not claimed for PDS136 in this validation record.
28
 
29
  The mathematical count check validates the finite-group arithmetic, not an independent proof of the block-Picard classification theorem. Live provider/tool tests do not establish that every account has access to the example model IDs. No AMD64 build or fresh E2B template build in an unrelated researcher account was performed during this validation; the documented template builder is the existing pinned Mini-Bench implementation.
30
 
 
35
  ```sh
36
  SAMPLES_IMAGE=poindexter-samples python tests/smoke.py
37
  python tests/check_math.py
38
+ python tests/check_cyber_reference.py
39
  ```
40
 
41
  The two `tests/live_*.py` scripts are optional paid API tests. Run them inside the controller using the corresponding `/opt/venvs/code/bin/python` or `/opt/venvs/general/bin/python`, with your own API environment and `tests/` mounted at `/test`. They do not run as part of the offline smoke suite.
data/cyber/tasks.jsonl CHANGED
@@ -1 +1 @@
1
- {"id": "swe_rl_cybersecurity_task_02", "benchmark": "cyber-operations", "family": "executable", "task_version": 2, "prompt": "We are seeing the mesh certificate validator accept unsafe chains once a hierarchy gets deeper, an intermediate is cross-signed, or revocation data is partitioned. Please harden PathValidationEngine.validate so it evaluates complete candidate paths to an installed CA trust anchor and accepts a certificate only when at least one whole path passes. Discover viable issuers by subject DN and, when present, AKID/SKID; use the existing ca_issuers AIA lookup when an intermediate is not local; prevent cycles; and backtrack when one branch fails signature, validity, CA/key-usage, name, policy, or revocation checks. Apply path_len_constraint with RFC 5280 semantics, including the treatment of self-issued intermediates.\n\nName constraints need to accumulate from the trust anchor through every intermediate and apply to every subordinate CA and leaf. Each ancestor's permitted subtrees add another condition, while any excluded match rejects that path. DNS comparisons must be case-insensitive and respect label boundaries. IP SAN values may be IPv4 or IPv6 hosts or CIDR networks and must use real address or subnet containment. URI comparisons should treat scheme and authority case-insensitively and respect path-segment boundaries. If an end-entity certificate has no SAN, enforce DNS constraints against its subject CN.\n\nProcess certificate policies across the full path. Preserve transitive and one-to-many mappings, reject mappings on an intermediate with no certificate-policies extension and mappings to or from anyPolicy, and honor explicit-policy, policy-mapping, and any-policy inhibit state from both the validation configuration and the certificates, including their skip counters. An inhibited critical mapping must invalidate that path. When explicit policy is required, the surviving tree must reach the leaf and agree with the initial policy set; return the accepted set in authorities_constrained_policies.\n\nTreat CRL state as scoped by issuer DN and AKID. Reject any non-increasing CRL number for that scope even when the reason mask changes. A delta CRL needs a registered base and must be newer than it. New base partitions must replace superseded historical state, and only current partitions may contribute reason coverage. Preserve the existing no-CRL behavior, but once matching CRL state exists its active partitions must jointly cover ALL_REASONS or validation must fail closed. Stored revocations take effect only once their revocation date is reached; correctly scoped indirect entries must be enforced; and a delta REMOVE_FROM_CRL must release only the matching hold in the same issuer/key scope without affecting another CA that happens to use the same DN or serial.\n\nContinue rejecting unhandled critical OIDs unless they are explicitly allowed. Trust-store mutations must invalidate cached validation decisions through the store epoch, while repeated identical validations and clear_cache retain their established behavior. Keep the public models and method signatures, deterministic crypto helpers, JSON persistence, store operations, result shape and useful errors, and ordinary direct and two-tier validation working as they do now.", "patch_policy": {"allowed_paths": ["src/**"], "forbidden_paths": ["tests/**", "requirements.lock", "pyproject.toml"]}, "manifest_profile": "python_standard_1m_v0.1", "manifest_scoring_policy": null, "image_kind": "swe", "calibrated_hidden_total": 60, "files": {"manifest.yaml": "e92fe8ed5135302bc2f370dce4af45de3322d9b65befb7b33c92823c8e41d740", "repository.zip": "1e14841c5546682e9bbbd6886b15105a172a0aacd9bf945e8393aef62a0c1898", "hidden_tests.zip": "c1604193fbfea16d1be7eb6eb4139e8d6748dad13c6f63a426d43433fb747690", "gold.diff": "744256d9e7e06f4321135e5cacaab514e3a9cfceead1fc5a4156611b0f1a1b96"}}
 
1
+ {"id": "swe_rl_cybersecurity_task_02", "benchmark": "cyber-operations", "family": "executable", "task_version": 2, "prompt": "We are seeing the mesh certificate validator accept unsafe chains once a hierarchy gets deeper, an intermediate is cross-signed, or revocation data is partitioned. Please harden PathValidationEngine.validate so it evaluates complete candidate paths to an installed CA trust anchor and accepts a certificate only when at least one whole path passes. Discover viable issuers by subject DN and, when present, AKID/SKID; use the existing ca_issuers AIA lookup when an intermediate is not local; prevent cycles; and backtrack when one branch fails signature, validity, CA/key-usage, name, policy, or revocation checks. Apply path_len_constraint with RFC 5280 semantics, including the treatment of self-issued intermediates.\n\nName constraints need to accumulate from the trust anchor through every intermediate and apply to every subordinate CA and leaf. Each ancestor's permitted subtrees add another condition, while any excluded match rejects that path. DNS comparisons must be case-insensitive and respect label boundaries. IP SAN values may be IPv4 or IPv6 hosts or CIDR networks and must use real address or subnet containment. URI comparisons should treat scheme and authority case-insensitively and respect path-segment boundaries. If an end-entity certificate has no SAN, enforce DNS constraints against its subject CN.\n\nProcess certificate policies across the full path. Preserve transitive and one-to-many mappings, reject mappings on an intermediate with no certificate-policies extension and mappings to or from anyPolicy, and honor explicit-policy, policy-mapping, and any-policy inhibit state from both the validation configuration and the certificates, including their skip counters. An inhibited critical mapping must invalidate that path. When explicit policy is required, the surviving tree must reach the leaf and agree with the initial policy set; return the accepted set in authorities_constrained_policies.\n\nTreat CRL state as scoped by issuer DN and AKID. Reject any non-increasing CRL number for that scope even when the reason mask changes. A delta CRL needs a registered base and must be newer than it. New base partitions must replace superseded historical state, and only current partitions may contribute reason coverage. Preserve the existing no-CRL behavior, but once matching CRL state exists its active partitions must jointly cover ALL_REASONS or validation must fail closed. Stored revocations take effect only once their revocation date is reached; correctly scoped indirect entries must be enforced; and a delta REMOVE_FROM_CRL must release only the matching hold in the same issuer/key scope without affecting another CA that happens to use the same DN or serial.\n\nContinue rejecting unhandled critical OIDs unless they are explicitly allowed. Trust-store mutations must invalidate cached validation decisions through the store epoch, while repeated identical validations and clear_cache retain their established behavior. Keep the public models and method signatures, deterministic crypto helpers, JSON persistence, store operations, result shape and useful errors, and ordinary direct and two-tier validation working as they do now.", "patch_policy": {"allowed_paths": ["src/**"], "forbidden_paths": ["tests/**", "requirements.lock", "pyproject.toml"]}, "manifest_profile": "python_standard_1m_v0.1", "manifest_scoring_policy": null, "image_kind": "swe", "calibrated_hidden_total": 60, "files": {"manifest.yaml": "e92fe8ed5135302bc2f370dce4af45de3322d9b65befb7b33c92823c8e41d740", "repository.zip": "1e14841c5546682e9bbbd6886b15105a172a0aacd9bf945e8393aef62a0c1898", "hidden_tests.zip": "c1604193fbfea16d1be7eb6eb4139e8d6748dad13c6f63a426d43433fb747690", "gold.diff": "0a482685a0754709d77ead55d03d59a4a7e014ee01415f6ab46aa7b8ce5262ba"}, "reference_revision": "samples-cache-policy-flags-v1"}
data/cyber/tasks/swe_rl_cybersecurity_task_02/gold.diff CHANGED
@@ -1,8 +1,7 @@
1
  diff --git a/src/constraints/matcher.py b/src/constraints/matcher.py
2
- index 395b86c..a352689 100644
3
  --- a/src/constraints/matcher.py
4
  +++ b/src/constraints/matcher.py
5
- @@ -5,9 +5,9 @@ from __future__ import annotations
6
  import ipaddress
7
  from dataclasses import dataclass, field
8
  from typing import List, Optional, Tuple
@@ -13,15 +12,15 @@ index 395b86c..a352689 100644
13
  ConstraintType,
14
  NameConstraint,
15
  NameConstraintsExtension,
16
- @@ -18,89 +18,129 @@ from src.models import (
17
  @dataclass
18
  class EffectiveConstraints:
19
  """Represents the accumulated name constraints along a certificate chain."""
20
- - permitted_subtrees: List[NameConstraint] = field(default_factory=list)
21
  + permitted_groups: List[List[NameConstraint]] = field(default_factory=list)
22
- excluded_subtrees: List[NameConstraint] = field(default_factory=list)
 
 
23
  - _permitted_groups: List[List[NameConstraint]] = field(default_factory=list)
24
- + permitted_subtrees: List[NameConstraint] = field(default_factory=list)
25
 
26
  def __post_init__(self) -> None:
27
  - if self.permitted_subtrees and not self._permitted_groups:
@@ -52,7 +51,7 @@ index 395b86c..a352689 100644
52
  - _permitted_groups=new_groups,
53
  + permitted_groups=new_groups,
54
  )
55
-
56
  + def add_ca_constraints(self, ca_nc: Optional[NameConstraintsExtension]) -> None:
57
  + if not ca_nc:
58
  + return
@@ -61,7 +60,7 @@ index 395b86c..a352689 100644
61
  + if ca_nc.permitted_subtrees:
62
  + self.permitted_groups.append(list(ca_nc.permitted_subtrees))
63
  + self.permitted_subtrees.extend(ca_nc.permitted_subtrees)
64
- +
65
 
66
  def match_dns_constraint(dns_name: str, constraint: str) -> bool:
67
  - """Matches a DNS SAN name against a DNS name constraint.
@@ -120,13 +119,12 @@ index 395b86c..a352689 100644
120
  + try:
121
  + p_uri = urlparse(uri.strip())
122
  + p_con = urlparse(constraint_prefix.strip())
123
-
124
  + if p_con.scheme and p_uri.scheme.lower() != p_con.scheme.lower():
125
  + return False
126
  + if p_con.netloc and p_uri.netloc.lower() != p_con.netloc.lower():
127
  + return False
128
-
129
- -def validate_san_constraints(
130
  + con_path = p_con.path
131
  + uri_path = p_uri.path
132
  +
@@ -137,8 +135,9 @@ index 395b86c..a352689 100644
137
  + return uri_path == con_path or uri_path.startswith(con_path + "/")
138
  + except Exception:
139
  + return uri.strip().lower().startswith(constraint_prefix.strip().lower())
140
- +
141
- +
 
142
  +def validate_name_constraints(
143
  san: SubjectAlternativeName,
144
  + subject_dn: str,
@@ -178,7 +177,7 @@ index 395b86c..a352689 100644
178
  elif excl.type == ConstraintType.IP:
179
  for ip in san.ip_addresses:
180
  if match_ip_constraint(ip, excl.value):
181
- @@ -110,27 +150,41 @@ def validate_san_constraints(
182
  if match_uri_constraint(u, excl.value):
183
  errors.append(f"URI '{u}' is excluded by constraint '{excl.value}'")
184
 
@@ -195,9 +194,6 @@ index 395b86c..a352689 100644
195
  - for d in san.dns_names:
196
  - if not any(match_dns_constraint(d, p) for p in dns_perm):
197
  - errors.append(f"DNS name '{d}' is not permitted by allowed DNS subtrees {dns_perm}")
198
- -
199
- - ip_perm = [c.value for c in group if c.type == ConstraintType.IP]
200
- - if ip_perm and san.ip_addresses:
201
  + dns_perms = [c.value for c in group if c.type == ConstraintType.DNS]
202
  + if dns_perms:
203
  + if has_san and san.dns_names:
@@ -210,7 +206,9 @@ index 395b86c..a352689 100644
210
  + cn_val = part.strip()[3:]
211
  + if not any(match_dns_constraint(cn_val, p) for p in dns_perms):
212
  + errors.append(f"Subject CN '{cn_val}' is not permitted by allowed DNS subtrees {dns_perms}")
213
- +
 
 
214
  + ip_perms = [c.value for c in group if c.type == ConstraintType.IP]
215
  + if ip_perms and san.ip_addresses:
216
  for ip in san.ip_addresses:
@@ -239,10 +237,9 @@ index 395b86c..a352689 100644
239
  + """Legacy helper for SAN-only constraint validation."""
240
  + return validate_name_constraints(san, "", constraints, is_ca=False)
241
  diff --git a/src/path/builder.py b/src/path/builder.py
242
- index 5960b3e..6f8efe5 100644
243
  --- a/src/path/builder.py
244
  +++ b/src/path/builder.py
245
- @@ -37,34 +37,35 @@ class PathBuilder:
246
  self.max_path_length = max_path_length
247
 
248
  def find_all_candidate_paths(self, leaf: Certificate) -> List[CandidatePath]:
@@ -257,21 +254,22 @@ index 5960b3e..6f8efe5 100644
257
  + current = current_path[-1]
258
 
259
  - def _dfs(current_path: List[Certificate], visited_serials: Set[str]) -> None:
260
- - if len(current_path) >= self.max_path_length:
261
  + if self.trust_store.is_trust_anchor(current):
262
  + all_paths.append(CandidatePath(certificates=list(current_path)))
 
 
 
263
  return
264
 
265
  - current = current_path[-1]
266
- -
 
267
  - if len(current_path) > 1 and self.trust_store.is_trust_anchor(current):
268
  - paths.append(CandidatePath(certificates=list(current_path)))
269
- + if len(current_path) >= self.max_path_length:
270
- return
271
-
272
  - candidates = self.trust_store.find_candidates(current.issuer_dn, current.authority_key_id)
273
- + candidates = list(self.trust_store.find_candidates(current.issuer_dn, current.authority_key_id))
274
-
275
  - if current.authority_info_access:
276
  - for aia_key, uri in current.authority_info_access.items():
277
  - if aia_key == "ca_issuers" or "ca_issuers" in aia_key:
@@ -288,30 +286,28 @@ index 5960b3e..6f8efe5 100644
288
  for cand in candidates:
289
  if cand.serial_number not in visited_serials:
290
  - _dfs(current_path + [cand], visited_serials | {cand.serial_number})
291
- -
292
- - _dfs([leaf], {leaf.serial_number})
293
- - return paths
294
  + visited_serials.add(cand.serial_number)
295
  + current_path.append(cand)
296
  + dfs(current_path, visited_serials)
297
  + current_path.pop()
298
  + visited_serials.remove(cand.serial_number)
299
- +
 
 
300
  + dfs([leaf], {leaf.serial_number})
301
  + return all_paths
302
  diff --git a/src/policy/tree_processor.py b/src/policy/tree_processor.py
303
- index da808a2..5c0fce6 100644
304
  --- a/src/policy/tree_processor.py
305
  +++ b/src/policy/tree_processor.py
306
- @@ -15,23 +15,11 @@ class PolicyNode:
307
  valid_policy: str
308
  qualifier_set: Set[str] = field(default_factory=set)
309
  expected_policy_set: Set[str] = field(default_factory=set)
310
  + original_initial_policy: Optional[str] = None
311
  parent: Optional[PolicyNode] = None
312
  children: List[PolicyNode] = field(default_factory=list)
313
-
314
-
315
  -def _prune_tree(nodes_by_depth: Dict[int, List[PolicyNode]], depth: int) -> None:
316
  - """Prunes childless nodes backwards from depth to 0."""
317
  - for d in range(depth, -1, -1):
@@ -323,12 +319,10 @@ index da808a2..5c0fce6 100644
323
  - if node in nodes:
324
  - nodes.remove(node)
325
  - nodes_by_depth[d] = nodes
326
- -
327
- -
328
- class PolicyTreeProcessor:
329
- """Processes certification path policies and computes authorities_constrained_policies."""
330
 
331
- @@ -45,140 +33,134 @@ class PolicyTreeProcessor:
 
 
332
 
333
  Returns (is_valid, authorities_constrained_policies, errors).
334
  """
@@ -473,18 +467,6 @@ index da808a2..5c0fce6 100644
473
  - expected_policy_set={p_id},
474
  - parent=p_node,
475
  - children=[],
476
- - )
477
- - p_node.children.append(c_node)
478
- - current_depth_nodes.append(c_node)
479
- - else:
480
- - if ANY_POLICY in cert_policy_ids and (inhibit_any_policy > 0 or is_leaf_cert):
481
- - for exp in p_node.expected_policy_set:
482
- - c_node = PolicyNode(
483
- - valid_policy=exp,
484
- - qualifier_set=qualifiers_by_id.get(ANY_POLICY, set()),
485
- - expected_policy_set={exp},
486
- - parent=p_node,
487
- - children=[],
488
  + parent.children.append(child)
489
  + current_depth_nodes.append(child)
490
  + else:
@@ -503,7 +485,48 @@ index da808a2..5c0fce6 100644
503
  + expected_policy_set={p_oid},
504
  + original_initial_policy=orig_pol,
505
  + parent=parent,
506
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
507
  - p_node.children.append(c_node)
508
  - current_depth_nodes.append(c_node)
509
  - for p_id in cert_policy_ids:
@@ -545,37 +568,10 @@ index da808a2..5c0fce6 100644
545
  - new_node = PolicyNode(
546
  - valid_policy=m.issuer_domain_policy,
547
  - qualifier_set=set(any_node.qualifier_set),
548
- + parent.children.append(child)
549
- + current_depth_nodes.append(child)
550
- +
551
- + nodes_by_depth.append(current_depth_nodes)
552
- +
553
- + # Step 2: Policy Mappings (intermediate CAs only)
554
- + if not is_leaf and cert.policy_mappings and cert.policy_mappings.mappings:
555
- + for m in cert.policy_mappings.mappings:
556
- + if m.issuer_domain_policy == ANY_POLICY or m.subject_domain_policy == ANY_POLICY:
557
- + errors.append("Policy mapping cannot map to or from anyPolicy")
558
- + return False, set(), errors
559
- +
560
- + if inhibit_policy_mapping > 0:
561
- + for m in cert.policy_mappings.mappings:
562
- + mapped_any = False
563
- + for node in current_depth_nodes:
564
- + if node.valid_policy == m.issuer_domain_policy:
565
- + node.valid_policy = m.subject_domain_policy
566
- + node.expected_policy_set = {m.subject_domain_policy}
567
- + mapped_any = True
568
- + if not mapped_any:
569
- + for parent in prev_nodes:
570
- + if parent.valid_policy == ANY_POLICY or m.issuer_domain_policy in parent.expected_policy_set:
571
- + child = PolicyNode(
572
- + valid_policy=m.subject_domain_policy,
573
- expected_policy_set={m.subject_domain_policy},
574
  - parent=any_node.parent,
575
  - children=[],
576
- + original_initial_policy=parent.original_initial_policy or m.issuer_domain_policy,
577
- + parent=parent,
578
- )
579
  - if any_node.parent:
580
  - any_node.parent.children.append(new_node)
581
  - nodes_by_depth[i].append(new_node)
@@ -592,7 +588,7 @@ index da808a2..5c0fce6 100644
592
  if cert.policy_constraints:
593
  if cert.policy_constraints.require_explicit_policy is not None:
594
  explicit_policy = min(explicit_policy, cert.policy_constraints.require_explicit_policy)
595
- @@ -187,42 +169,44 @@ class PolicyTreeProcessor:
596
  if cert.inhibit_any_policy:
597
  inhibit_any_policy = min(inhibit_any_policy, cert.inhibit_any_policy.skip_certs)
598
 
@@ -603,23 +599,25 @@ index da808a2..5c0fce6 100644
603
  - inhibit_policy_mapping -= 1
604
  - if inhibit_any_policy > 0:
605
  - inhibit_any_policy -= 1
 
 
 
 
 
 
 
606
  + if explicit_policy > 0 and not cert.is_self_issued:
607
  + explicit_policy -= 1
608
  + if inhibit_policy_mapping > 0 and not cert.is_self_issued:
609
  + inhibit_policy_mapping -= 1
610
  + if inhibit_any_policy > 0 and not cert.is_self_issued:
611
  + inhibit_any_policy -= 1
612
-
613
- - leaf_cert = chain[-1]
614
- - if leaf_cert.policy_constraints:
615
- - if leaf_cert.policy_constraints.require_explicit_policy is not None and leaf_cert.policy_constraints.require_explicit_policy == 0:
616
- - explicit_policy = 0
617
  + # Check if valid policy tree has become empty
618
  + if not current_depth_nodes and explicit_policy <= 0:
619
  + errors.append(f"Valid policy tree is empty at depth {i}")
620
  + return False, set(), errors
621
-
622
- - leaf_nodes = nodes_by_depth.get(n - 1, [])
623
  + # Wrap up at leaf
624
  + leaf_nodes = nodes_by_depth[-1]
625
  if not leaf_nodes:
@@ -671,10 +669,9 @@ index da808a2..5c0fce6 100644
671
  +
672
  + return True, constrained_policies, []
673
  diff --git a/src/revocation/crl_manager.py b/src/revocation/crl_manager.py
674
- index 2720433..d9baf06 100644
675
  --- a/src/revocation/crl_manager.py
676
  +++ b/src/revocation/crl_manager.py
677
- @@ -22,81 +22,118 @@ class CRLValidationStatus:
678
  revocation_date: Optional[str] = None
679
  crl_number: Optional[int] = None
680
  uncovered_reasons: Set[CRLReason] = field(default_factory=set)
@@ -848,7 +845,7 @@ index 2720433..d9baf06 100644
848
  return CRLValidationStatus(
849
  is_revoked=True,
850
  is_fully_covered=True,
851
- @@ -105,42 +142,79 @@ class CRLCache:
852
  crl_number=latest_num,
853
  )
854
 
@@ -952,10 +949,9 @@ index 2720433..d9baf06 100644
952
  - self._issuer_crl_numbers.clear()
953
  + self._latest_base_crl_numbers.clear()
954
  diff --git a/src/store/trust_store.py b/src/store/trust_store.py
955
- index c5bf0da..87e62c2 100644
956
  --- a/src/store/trust_store.py
957
  +++ b/src/store/trust_store.py
958
- @@ -61,6 +61,9 @@ class TrustStore:
959
  def fetch_aia_certificate(self, uri: str) -> Optional[Certificate]:
960
  return self._remote_aia_certs.get(uri)
961
 
@@ -966,10 +962,9 @@ index c5bf0da..87e62c2 100644
966
  """Registers a Base or Delta CRL."""
967
  accepted = self._crl_cache.register_crl(crl)
968
  diff --git a/src/validation/engine.py b/src/validation/engine.py
969
- index 55cc6e8..c17e7ce 100644
970
  --- a/src/validation/engine.py
971
  +++ b/src/validation/engine.py
972
- @@ -4,7 +4,7 @@ from __future__ import annotations
973
 
974
  from typing import Dict, List, Optional, Set, Tuple
975
 
@@ -978,7 +973,7 @@ index 55cc6e8..c17e7ce 100644
978
  from src.crypto.signer import verify_certificate_signature
979
  from src.models import (
980
  ALL_REASONS,
981
- @@ -23,34 +23,23 @@ class PathValidationEngine:
982
  def __init__(self, trust_store: TrustStore) -> None:
983
  self.trust_store = trust_store
984
  self.path_builder = PathBuilder(trust_store)
@@ -988,7 +983,7 @@ index 55cc6e8..c17e7ce 100644
988
 
989
  def clear_cache(self) -> None:
990
  self._cache.clear()
991
-
992
  - def _get_cache_key(self, leaf: Certificate, config: ValidationConfig) -> str:
993
  - return (
994
  - f"epoch={self.trust_store.epoch}:"
@@ -1004,7 +999,7 @@ index 55cc6e8..c17e7ce 100644
1004
  - f"time={config.current_time}:"
1005
  - f"crit={sorted(config.allowed_custom_critical_oids)}"
1006
  - )
1007
- -
1008
  def validate(self, leaf: Certificate, config: Optional[ValidationConfig] = None) -> ValidationResult:
1009
  """Validates a target leaf certificate against installed trust anchors and policies."""
1010
  if config is None:
@@ -1015,12 +1010,13 @@ index 55cc6e8..c17e7ce 100644
1015
  + f"{self.trust_store.epoch}:{leaf.fingerprint}:{config.check_revocation}:"
1016
  + f"{config.enforce_name_constraints}:{config.enforce_path_len}:{config.enforce_policy_tree}:"
1017
  + f"{config.initial_explicit_policy}:{sorted(config.initial_policy_set)}:{config.current_time}:"
 
1018
  + f"{sorted(config.allowed_custom_critical_oids)}"
1019
  + )
1020
  if cache_key in self._cache:
1021
  return self._cache[cache_key]
1022
 
1023
- @@ -65,8 +54,8 @@ class PathValidationEngine:
1024
  self._cache[cache_key] = res
1025
  return res
1026
 
@@ -1031,7 +1027,7 @@ index 55cc6e8..c17e7ce 100644
1031
  for candidate in candidate_paths:
1032
  path_valid, policies, errors = self._validate_single_path(candidate, config)
1033
  if path_valid:
1034
- @@ -78,13 +67,14 @@ class PathValidationEngine:
1035
  )
1036
  self._cache[cache_key] = res
1037
  return res
@@ -1049,7 +1045,7 @@ index 55cc6e8..c17e7ce 100644
1049
  self._cache[cache_key] = res
1050
  return res
1051
 
1052
- @@ -95,12 +85,16 @@ class PathValidationEngine:
1053
  certs = candidate.certificates
1054
  errors: List[str] = []
1055
 
@@ -1058,16 +1054,14 @@ index 55cc6e8..c17e7ce 100644
1058
  root = certs[-1]
1059
  if not self.trust_store.is_trust_anchor(root):
1060
  errors.append(f"Root certificate {root.subject_dn} is not a trusted anchor")
1061
- return False, set(), errors
1062
-
1063
- + if not root.basic_constraints.is_ca:
1064
- + errors.append(f"Root trust anchor {root.subject_dn} has is_ca=False")
1065
  + return False, set(), errors
1066
  +
 
 
 
 
1067
  # 2. Structural & CA constraint checks for intermediates
1068
- for i in range(1, len(certs)):
1069
- ca_cert = certs[i]
1070
- @@ -109,21 +103,12 @@ class PathValidationEngine:
1071
  if not ca_cert.key_usage.key_cert_sign:
1072
  errors.append(f"Intermediate certificate {ca_cert.subject_dn} lacks key_cert_sign usage")
1073
 
@@ -1090,7 +1084,7 @@ index 55cc6e8..c17e7ce 100644
1090
  intermediates_below = [c for c in certs[1:i] if not c.is_self_issued]
1091
  if len(intermediates_below) > path_len_limit:
1092
  errors.append(
1093
- @@ -131,7 +116,7 @@ class PathValidationEngine:
1094
  f"limit={path_len_limit}, observed={len(intermediates_below)}"
1095
  )
1096
 
@@ -1099,10 +1093,10 @@ index 55cc6e8..c17e7ce 100644
1099
  if config.current_time:
1100
  for cert in certs:
1101
  if config.current_time < cert.not_before:
1102
- @@ -139,6 +124,18 @@ class PathValidationEngine:
1103
  if config.current_time > cert.not_after:
1104
  errors.append(f"Certificate {cert.subject_dn} is expired at {config.current_time}")
1105
-
1106
  + # 5. Critical extension checking
1107
  + for cert in certs:
1108
  + if cert.unrecognized_critical_extensions:
@@ -1114,11 +1108,10 @@ index 55cc6e8..c17e7ce 100644
1114
  + errors.append(
1115
  + f"Certificate {cert.subject_dn} contains unrecognized critical extension(s): {unhandled}"
1116
  + )
1117
- +
1118
  # 6. Cryptographic signature chain verification
1119
  for i in range(len(certs) - 1):
1120
- child = certs[i]
1121
- @@ -150,7 +147,9 @@ class PathValidationEngine:
1122
  if config.check_revocation:
1123
  for i in range(len(certs) - 1):
1124
  child = certs[i]
@@ -1129,7 +1122,7 @@ index 55cc6e8..c17e7ce 100644
1129
  if rev_status.is_revoked:
1130
  errors.append(
1131
  f"Certificate {child.subject_dn} (serial {child.serial_number}) is revoked: "
1132
- @@ -165,16 +164,16 @@ class PathValidationEngine:
1133
  # 8. Transitive Name constraints evaluation
1134
  if config.enforce_name_constraints:
1135
  eff = EffectiveConstraints()
 
1
  diff --git a/src/constraints/matcher.py b/src/constraints/matcher.py
 
2
  --- a/src/constraints/matcher.py
3
  +++ b/src/constraints/matcher.py
4
+ @@ -5,9 +5,9 @@
5
  import ipaddress
6
  from dataclasses import dataclass, field
7
  from typing import List, Optional, Tuple
 
12
  ConstraintType,
13
  NameConstraint,
14
  NameConstraintsExtension,
15
+ @@ -18,89 +18,129 @@
16
  @dataclass
17
  class EffectiveConstraints:
18
  """Represents the accumulated name constraints along a certificate chain."""
 
19
  + permitted_groups: List[List[NameConstraint]] = field(default_factory=list)
20
+ + excluded_subtrees: List[NameConstraint] = field(default_factory=list)
21
+ permitted_subtrees: List[NameConstraint] = field(default_factory=list)
22
+ - excluded_subtrees: List[NameConstraint] = field(default_factory=list)
23
  - _permitted_groups: List[List[NameConstraint]] = field(default_factory=list)
 
24
 
25
  def __post_init__(self) -> None:
26
  - if self.permitted_subtrees and not self._permitted_groups:
 
51
  - _permitted_groups=new_groups,
52
  + permitted_groups=new_groups,
53
  )
54
+ +
55
  + def add_ca_constraints(self, ca_nc: Optional[NameConstraintsExtension]) -> None:
56
  + if not ca_nc:
57
  + return
 
60
  + if ca_nc.permitted_subtrees:
61
  + self.permitted_groups.append(list(ca_nc.permitted_subtrees))
62
  + self.permitted_subtrees.extend(ca_nc.permitted_subtrees)
63
+
64
 
65
  def match_dns_constraint(dns_name: str, constraint: str) -> bool:
66
  - """Matches a DNS SAN name against a DNS name constraint.
 
119
  + try:
120
  + p_uri = urlparse(uri.strip())
121
  + p_con = urlparse(constraint_prefix.strip())
122
+ +
123
  + if p_con.scheme and p_uri.scheme.lower() != p_con.scheme.lower():
124
  + return False
125
  + if p_con.netloc and p_uri.netloc.lower() != p_con.netloc.lower():
126
  + return False
127
+ +
 
128
  + con_path = p_con.path
129
  + uri_path = p_uri.path
130
  +
 
135
  + return uri_path == con_path or uri_path.startswith(con_path + "/")
136
  + except Exception:
137
  + return uri.strip().lower().startswith(constraint_prefix.strip().lower())
138
+
139
+
140
+ -def validate_san_constraints(
141
  +def validate_name_constraints(
142
  san: SubjectAlternativeName,
143
  + subject_dn: str,
 
177
  elif excl.type == ConstraintType.IP:
178
  for ip in san.ip_addresses:
179
  if match_ip_constraint(ip, excl.value):
180
+ @@ -110,27 +150,41 @@
181
  if match_uri_constraint(u, excl.value):
182
  errors.append(f"URI '{u}' is excluded by constraint '{excl.value}'")
183
 
 
194
  - for d in san.dns_names:
195
  - if not any(match_dns_constraint(d, p) for p in dns_perm):
196
  - errors.append(f"DNS name '{d}' is not permitted by allowed DNS subtrees {dns_perm}")
 
 
 
197
  + dns_perms = [c.value for c in group if c.type == ConstraintType.DNS]
198
  + if dns_perms:
199
  + if has_san and san.dns_names:
 
206
  + cn_val = part.strip()[3:]
207
  + if not any(match_dns_constraint(cn_val, p) for p in dns_perms):
208
  + errors.append(f"Subject CN '{cn_val}' is not permitted by allowed DNS subtrees {dns_perms}")
209
+
210
+ - ip_perm = [c.value for c in group if c.type == ConstraintType.IP]
211
+ - if ip_perm and san.ip_addresses:
212
  + ip_perms = [c.value for c in group if c.type == ConstraintType.IP]
213
  + if ip_perms and san.ip_addresses:
214
  for ip in san.ip_addresses:
 
237
  + """Legacy helper for SAN-only constraint validation."""
238
  + return validate_name_constraints(san, "", constraints, is_ca=False)
239
  diff --git a/src/path/builder.py b/src/path/builder.py
 
240
  --- a/src/path/builder.py
241
  +++ b/src/path/builder.py
242
+ @@ -37,34 +37,35 @@
243
  self.max_path_length = max_path_length
244
 
245
  def find_all_candidate_paths(self, leaf: Certificate) -> List[CandidatePath]:
 
254
  + current = current_path[-1]
255
 
256
  - def _dfs(current_path: List[Certificate], visited_serials: Set[str]) -> None:
 
257
  + if self.trust_store.is_trust_anchor(current):
258
  + all_paths.append(CandidatePath(certificates=list(current_path)))
259
+ + return
260
+ +
261
+ if len(current_path) >= self.max_path_length:
262
  return
263
 
264
  - current = current_path[-1]
265
+ + candidates = list(self.trust_store.find_candidates(current.issuer_dn, current.authority_key_id))
266
+
267
  - if len(current_path) > 1 and self.trust_store.is_trust_anchor(current):
268
  - paths.append(CandidatePath(certificates=list(current_path)))
269
+ - return
270
+ -
 
271
  - candidates = self.trust_store.find_candidates(current.issuer_dn, current.authority_key_id)
272
+ -
 
273
  - if current.authority_info_access:
274
  - for aia_key, uri in current.authority_info_access.items():
275
  - if aia_key == "ca_issuers" or "ca_issuers" in aia_key:
 
286
  for cand in candidates:
287
  if cand.serial_number not in visited_serials:
288
  - _dfs(current_path + [cand], visited_serials | {cand.serial_number})
 
 
 
289
  + visited_serials.add(cand.serial_number)
290
  + current_path.append(cand)
291
  + dfs(current_path, visited_serials)
292
  + current_path.pop()
293
  + visited_serials.remove(cand.serial_number)
294
+
295
+ - _dfs([leaf], {leaf.serial_number})
296
+ - return paths
297
  + dfs([leaf], {leaf.serial_number})
298
  + return all_paths
299
  diff --git a/src/policy/tree_processor.py b/src/policy/tree_processor.py
 
300
  --- a/src/policy/tree_processor.py
301
  +++ b/src/policy/tree_processor.py
302
+ @@ -15,21 +15,9 @@
303
  valid_policy: str
304
  qualifier_set: Set[str] = field(default_factory=set)
305
  expected_policy_set: Set[str] = field(default_factory=set)
306
  + original_initial_policy: Optional[str] = None
307
  parent: Optional[PolicyNode] = None
308
  children: List[PolicyNode] = field(default_factory=list)
309
+ -
310
+ -
311
  -def _prune_tree(nodes_by_depth: Dict[int, List[PolicyNode]], depth: int) -> None:
312
  - """Prunes childless nodes backwards from depth to 0."""
313
  - for d in range(depth, -1, -1):
 
319
  - if node in nodes:
320
  - nodes.remove(node)
321
  - nodes_by_depth[d] = nodes
 
 
 
 
322
 
323
+
324
+ class PolicyTreeProcessor:
325
+ @@ -45,140 +33,134 @@
326
 
327
  Returns (is_valid, authorities_constrained_policies, errors).
328
  """
 
467
  - expected_policy_set={p_id},
468
  - parent=p_node,
469
  - children=[],
 
 
 
 
 
 
 
 
 
 
 
 
470
  + parent.children.append(child)
471
  + current_depth_nodes.append(child)
472
  + else:
 
485
  + expected_policy_set={p_oid},
486
  + original_initial_policy=orig_pol,
487
  + parent=parent,
488
+ + )
489
+ + parent.children.append(child)
490
+ + current_depth_nodes.append(child)
491
+ +
492
+ + nodes_by_depth.append(current_depth_nodes)
493
+ +
494
+ + # Step 2: Policy Mappings (intermediate CAs only)
495
+ + if not is_leaf and cert.policy_mappings and cert.policy_mappings.mappings:
496
+ + for m in cert.policy_mappings.mappings:
497
+ + if m.issuer_domain_policy == ANY_POLICY or m.subject_domain_policy == ANY_POLICY:
498
+ + errors.append("Policy mapping cannot map to or from anyPolicy")
499
+ + return False, set(), errors
500
+ +
501
+ + if inhibit_policy_mapping > 0:
502
+ + for m in cert.policy_mappings.mappings:
503
+ + mapped_any = False
504
+ + for node in current_depth_nodes:
505
+ + if node.valid_policy == m.issuer_domain_policy:
506
+ + node.valid_policy = m.subject_domain_policy
507
+ + node.expected_policy_set = {m.subject_domain_policy}
508
+ + mapped_any = True
509
+ + if not mapped_any:
510
+ + for parent in prev_nodes:
511
+ + if parent.valid_policy == ANY_POLICY or m.issuer_domain_policy in parent.expected_policy_set:
512
+ + child = PolicyNode(
513
+ + valid_policy=m.subject_domain_policy,
514
+ + expected_policy_set={m.subject_domain_policy},
515
+ + original_initial_policy=parent.original_initial_policy or m.issuer_domain_policy,
516
+ + parent=parent,
517
+ )
518
+ - p_node.children.append(c_node)
519
+ - current_depth_nodes.append(c_node)
520
+ - else:
521
+ - if ANY_POLICY in cert_policy_ids and (inhibit_any_policy > 0 or is_leaf_cert):
522
+ - for exp in p_node.expected_policy_set:
523
+ - c_node = PolicyNode(
524
+ - valid_policy=exp,
525
+ - qualifier_set=qualifiers_by_id.get(ANY_POLICY, set()),
526
+ - expected_policy_set={exp},
527
+ - parent=p_node,
528
+ - children=[],
529
+ - )
530
  - p_node.children.append(c_node)
531
  - current_depth_nodes.append(c_node)
532
  - for p_id in cert_policy_ids:
 
568
  - new_node = PolicyNode(
569
  - valid_policy=m.issuer_domain_policy,
570
  - qualifier_set=set(any_node.qualifier_set),
571
+ - expected_policy_set={m.subject_domain_policy},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
  - parent=any_node.parent,
573
  - children=[],
574
+ - )
 
 
575
  - if any_node.parent:
576
  - any_node.parent.children.append(new_node)
577
  - nodes_by_depth[i].append(new_node)
 
588
  if cert.policy_constraints:
589
  if cert.policy_constraints.require_explicit_policy is not None:
590
  explicit_policy = min(explicit_policy, cert.policy_constraints.require_explicit_policy)
591
+ @@ -187,42 +169,44 @@
592
  if cert.inhibit_any_policy:
593
  inhibit_any_policy = min(inhibit_any_policy, cert.inhibit_any_policy.skip_certs)
594
 
 
599
  - inhibit_policy_mapping -= 1
600
  - if inhibit_any_policy > 0:
601
  - inhibit_any_policy -= 1
602
+ -
603
+ - leaf_cert = chain[-1]
604
+ - if leaf_cert.policy_constraints:
605
+ - if leaf_cert.policy_constraints.require_explicit_policy is not None and leaf_cert.policy_constraints.require_explicit_policy == 0:
606
+ - explicit_policy = 0
607
+ -
608
+ - leaf_nodes = nodes_by_depth.get(n - 1, [])
609
  + if explicit_policy > 0 and not cert.is_self_issued:
610
  + explicit_policy -= 1
611
  + if inhibit_policy_mapping > 0 and not cert.is_self_issued:
612
  + inhibit_policy_mapping -= 1
613
  + if inhibit_any_policy > 0 and not cert.is_self_issued:
614
  + inhibit_any_policy -= 1
615
+ +
 
 
 
 
616
  + # Check if valid policy tree has become empty
617
  + if not current_depth_nodes and explicit_policy <= 0:
618
  + errors.append(f"Valid policy tree is empty at depth {i}")
619
  + return False, set(), errors
620
+ +
 
621
  + # Wrap up at leaf
622
  + leaf_nodes = nodes_by_depth[-1]
623
  if not leaf_nodes:
 
669
  +
670
  + return True, constrained_policies, []
671
  diff --git a/src/revocation/crl_manager.py b/src/revocation/crl_manager.py
 
672
  --- a/src/revocation/crl_manager.py
673
  +++ b/src/revocation/crl_manager.py
674
+ @@ -22,81 +22,118 @@
675
  revocation_date: Optional[str] = None
676
  crl_number: Optional[int] = None
677
  uncovered_reasons: Set[CRLReason] = field(default_factory=set)
 
845
  return CRLValidationStatus(
846
  is_revoked=True,
847
  is_fully_covered=True,
848
+ @@ -105,42 +142,79 @@
849
  crl_number=latest_num,
850
  )
851
 
 
949
  - self._issuer_crl_numbers.clear()
950
  + self._latest_base_crl_numbers.clear()
951
  diff --git a/src/store/trust_store.py b/src/store/trust_store.py
 
952
  --- a/src/store/trust_store.py
953
  +++ b/src/store/trust_store.py
954
+ @@ -61,6 +61,9 @@
955
  def fetch_aia_certificate(self, uri: str) -> Optional[Certificate]:
956
  return self._remote_aia_certs.get(uri)
957
 
 
962
  """Registers a Base or Delta CRL."""
963
  accepted = self._crl_cache.register_crl(crl)
964
  diff --git a/src/validation/engine.py b/src/validation/engine.py
 
965
  --- a/src/validation/engine.py
966
  +++ b/src/validation/engine.py
967
+ @@ -4,7 +4,7 @@
968
 
969
  from typing import Dict, List, Optional, Set, Tuple
970
 
 
973
  from src.crypto.signer import verify_certificate_signature
974
  from src.models import (
975
  ALL_REASONS,
976
+ @@ -23,34 +23,24 @@
977
  def __init__(self, trust_store: TrustStore) -> None:
978
  self.trust_store = trust_store
979
  self.path_builder = PathBuilder(trust_store)
 
983
 
984
  def clear_cache(self) -> None:
985
  self._cache.clear()
986
+ -
987
  - def _get_cache_key(self, leaf: Certificate, config: ValidationConfig) -> str:
988
  - return (
989
  - f"epoch={self.trust_store.epoch}:"
 
999
  - f"time={config.current_time}:"
1000
  - f"crit={sorted(config.allowed_custom_critical_oids)}"
1001
  - )
1002
+
1003
  def validate(self, leaf: Certificate, config: Optional[ValidationConfig] = None) -> ValidationResult:
1004
  """Validates a target leaf certificate against installed trust anchors and policies."""
1005
  if config is None:
 
1010
  + f"{self.trust_store.epoch}:{leaf.fingerprint}:{config.check_revocation}:"
1011
  + f"{config.enforce_name_constraints}:{config.enforce_path_len}:{config.enforce_policy_tree}:"
1012
  + f"{config.initial_explicit_policy}:{sorted(config.initial_policy_set)}:{config.current_time}:"
1013
+ + f"{config.initial_policy_mapping_inhibit}:{config.initial_any_policy_inhibit}:"
1014
  + f"{sorted(config.allowed_custom_critical_oids)}"
1015
  + )
1016
  if cache_key in self._cache:
1017
  return self._cache[cache_key]
1018
 
1019
+ @@ -65,8 +55,8 @@
1020
  self._cache[cache_key] = res
1021
  return res
1022
 
 
1027
  for candidate in candidate_paths:
1028
  path_valid, policies, errors = self._validate_single_path(candidate, config)
1029
  if path_valid:
1030
+ @@ -78,13 +68,14 @@
1031
  )
1032
  self._cache[cache_key] = res
1033
  return res
 
1045
  self._cache[cache_key] = res
1046
  return res
1047
 
1048
+ @@ -95,10 +86,14 @@
1049
  certs = candidate.certificates
1050
  errors: List[str] = []
1051
 
 
1054
  root = certs[-1]
1055
  if not self.trust_store.is_trust_anchor(root):
1056
  errors.append(f"Root certificate {root.subject_dn} is not a trusted anchor")
 
 
 
 
1057
  + return False, set(), errors
1058
  +
1059
+ + if not root.basic_constraints.is_ca:
1060
+ + errors.append(f"Root trust anchor {root.subject_dn} has is_ca=False")
1061
+ return False, set(), errors
1062
+
1063
  # 2. Structural & CA constraint checks for intermediates
1064
+ @@ -109,21 +104,12 @@
 
 
1065
  if not ca_cert.key_usage.key_cert_sign:
1066
  errors.append(f"Intermediate certificate {ca_cert.subject_dn} lacks key_cert_sign usage")
1067
 
 
1084
  intermediates_below = [c for c in certs[1:i] if not c.is_self_issued]
1085
  if len(intermediates_below) > path_len_limit:
1086
  errors.append(
1087
+ @@ -131,13 +117,25 @@
1088
  f"limit={path_len_limit}, observed={len(intermediates_below)}"
1089
  )
1090
 
 
1093
  if config.current_time:
1094
  for cert in certs:
1095
  if config.current_time < cert.not_before:
1096
+ errors.append(f"Certificate {cert.subject_dn} is not yet valid at {config.current_time}")
1097
  if config.current_time > cert.not_after:
1098
  errors.append(f"Certificate {cert.subject_dn} is expired at {config.current_time}")
1099
+ +
1100
  + # 5. Critical extension checking
1101
  + for cert in certs:
1102
  + if cert.unrecognized_critical_extensions:
 
1108
  + errors.append(
1109
  + f"Certificate {cert.subject_dn} contains unrecognized critical extension(s): {unhandled}"
1110
  + )
1111
+
1112
  # 6. Cryptographic signature chain verification
1113
  for i in range(len(certs) - 1):
1114
+ @@ -150,7 +148,9 @@
 
1115
  if config.check_revocation:
1116
  for i in range(len(certs) - 1):
1117
  child = certs[i]
 
1122
  if rev_status.is_revoked:
1123
  errors.append(
1124
  f"Certificate {child.subject_dn} (serial {child.serial_number}) is revoked: "
1125
+ @@ -165,16 +165,16 @@
1126
  # 8. Transitive Name constraints evaluation
1127
  if config.enforce_name_constraints:
1128
  eff = EffectiveConstraints()
docs/ACCURACY_REVIEW.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Selected-task accuracy review — November 18, 2026
2
+
3
+ Scope: a targeted consistency review of the three GDPVal and two code samples, including source inputs, expected outputs and executable evidence. STEM was excluded from this review. This is not an exhaustive proof of reference correctness; passing an LLM judge alone is not treated as such proof.
4
+
5
+ ## GDPVal
6
+
7
+ **German — family foundation.** No material contradiction found between the prompt and the reviewed legal assertions in the rubric. The initial endowment allowance is conditioned on the potentially most distant beneficiary, not multiplied by the number of children. The rubric distinguishes later additions, preserves foundation ownership and capital-maintenance constraints, and identifies the 30-year substitute inheritance tax. The beneficiary interpretation agrees with the [Federal Fiscal Court decision II R 25/21](https://www.bundesfinanzhof.de/de/entscheidung/entscheidungen-online/detail/STRE202410089/); the 30-year interval is in [ErbStG §1](https://www.gesetze-im-internet.de/erbstg_1974/__1.html). This is a 2025 planning exercise, not a current personalized legal opinion. The rubric repeats some documentation/timeline requirements, so a concise presentation can lose several points for one omission. A live native OpenAI run completed with 70.21%; that is partial answer credit, not a pipeline failure.
8
+
9
+ **Japanese — NFT photography article.** The supplied Word research file, requested output and rubric are consistent on the article title, Japanese character count, formatting, photographer examples and links. A live native OpenAI run produced a Word document and received 100%. Two qualifications matter: this uses a historical collection of web references, whose continuing availability is not guaranteed; resale royalties should be described as platform-dependent, not guaranteed for every NFT sale. For example, [SuperRare documents a secondary-sale royalty](https://help.superrare.com/en/articles/10629742-offers-auctions-and-pricing). The rubric's wording permits earning royalties rather than requiring a universal guarantee. Its character-count boundary uses the first paragraph containing `プルクオート:` or `キーワード`; keep the keyword section at the end, since those words inside the body could make that boundary ambiguous. The original rubric is preserved.
10
+
11
+ **French — 2024 household tax return.** Independently recalculated the principal totals from the supplied salary, interest, dividend, securities-sale and payment PDFs. They reconcile with the rubric/reference:
12
+
13
+ | Calculation | Euros |
14
+ | --- | ---: |
15
+ | Declared salaries: Laurent / Claire | 234,934 / 92,069 |
16
+ | Net taxable salaries after standard deductions | 303,370 |
17
+ | Progressive tax after family-quotient cap | 85,108 |
18
+ | Net securities gain | 25,915 |
19
+ | PFU income-tax component | 4,323 |
20
+ | Donation and school reductions | 2,989 |
21
+ | Childcare credit / 2CK credit | 820 / 1,006 |
22
+ | Net income tax before PAS payments | 84,616 |
23
+ | PAS payments | 39,079 |
24
+ | Remaining income tax / social charges | 45,537 / 4,458 |
25
+ | Final balance | **49,995** |
26
+
27
+ The twins were under six on January 1, 2024; the questionnaire explicitly excludes the global progressive-rate option and prior-year carryovers. The 2BH entry is consistent with the [official 2025 simulator's conditional CSG wording](https://simulateur-ir-ifi.impots.gouv.fr/calcul_impot/2025/complet/index.htm). Brackets were cross-checked against the [2025 BOFiP schedule](https://bofip.impots.gouv.fr/bofip/2491-PGP.html/identifiant%3DBOI-IR-LIQ-20-10-20250414), and deduction limits against the [2025 calculation instructions](https://www.impots.gouv.fr/sites/default/files/formulaires/2041-notfc/2025/2041-notfc_5103.pdf). No material arithmetic discrepancy found. This is a synthetic historical exercise, not a certified tax filing. The human reference processed successfully against all 67 rubric criteria; a separate native solver produced a 35-page, 19,347,709-byte PDF and was rejected by the inherited 10 MiB per-file collection limit before grading. That is an execution constraint, not evidence of a factual error in the task.
28
+
29
+ ## Code tasks
30
+
31
+ **cyber_02 — certificate validation.** The test scenarios match the task's stated path, policy, name-constraint and revocation requirements. The original reference passed the existing evaluator, but independent inspection found that its cache key omitted `initial_policy_mapping_inhibit` and `initial_any_policy_inhibit`. After a permissive validation, a stricter validation on the same engine incorrectly returned the cached success; a fresh engine correctly rejected it.
32
+
33
+ The Samples reference now includes both flags in cache identity and again receives reward 1.0 through the actual Docker submission/evaluator. Two new reference-only regression tests cover both directions of each policy change; both fail on the original reference and pass on the corrected one. The original is preserved as [upstream-cyber02-gold.diff](upstream-cyber02-gold.diff). The task prompt, starter repository, hidden tests and scoring protocol are unchanged. This fixture uses deterministic crypto helpers and task-specific validation rules; it is not a production certificate validator or a comprehensive RFC-conformance test.
34
+
35
+ **qna014 — signed-package incident audit.** Applied the nine proposed safe patches in order to an isolated copy and executed the archived primitives (9/9 passed). Replayed the captures and independently derived the sequence-906 head, all capture decisions, eight runtime packages, four build packages, recipe digest and built-wheel digest. They match the published reference. Token 71 conflicts on the old request and is fenced on the current request; token 81 is fenced, and token 82 resumes. These outcomes agree with the reference and executable retry rules. The existing native judge/file-property validation also passed. This checks the main reference conclusions, not every possible incident variant.
36
+
37
+ Run the additional cyber regression locally with `python tests/check_cyber_reference.py`, or inside the built controller with:
38
+
39
+ ```sh
40
+ docker run --rm --entrypoint python poindexter-samples tests/check_cyber_reference.py
41
+ ```
docs/upstream-cyber02-gold.diff ADDED
@@ -0,0 +1,1156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/constraints/matcher.py b/src/constraints/matcher.py
2
+ index 395b86c..a352689 100644
3
+ --- a/src/constraints/matcher.py
4
+ +++ b/src/constraints/matcher.py
5
+ @@ -5,9 +5,9 @@ from __future__ import annotations
6
+ import ipaddress
7
+ from dataclasses import dataclass, field
8
+ from typing import List, Optional, Tuple
9
+ +from urllib.parse import urlparse
10
+
11
+ from src.models import (
12
+ - Certificate,
13
+ ConstraintType,
14
+ NameConstraint,
15
+ NameConstraintsExtension,
16
+ @@ -18,89 +18,129 @@ from src.models import (
17
+ @dataclass
18
+ class EffectiveConstraints:
19
+ """Represents the accumulated name constraints along a certificate chain."""
20
+ - permitted_subtrees: List[NameConstraint] = field(default_factory=list)
21
+ + permitted_groups: List[List[NameConstraint]] = field(default_factory=list)
22
+ excluded_subtrees: List[NameConstraint] = field(default_factory=list)
23
+ - _permitted_groups: List[List[NameConstraint]] = field(default_factory=list)
24
+ + permitted_subtrees: List[NameConstraint] = field(default_factory=list)
25
+
26
+ def __post_init__(self) -> None:
27
+ - if self.permitted_subtrees and not self._permitted_groups:
28
+ - object.__setattr__(self, "_permitted_groups", [list(self.permitted_subtrees)])
29
+ + if self.permitted_subtrees and not self.permitted_groups:
30
+ + self.permitted_groups = [list(self.permitted_subtrees)]
31
+ + elif self.permitted_groups and not self.permitted_subtrees:
32
+ + self.permitted_subtrees = [c for group in self.permitted_groups for c in group]
33
+
34
+ def is_empty(self) -> bool:
35
+ - return not (self.permitted_subtrees or self.excluded_subtrees or self._permitted_groups)
36
+ + return not (self.permitted_groups or self.permitted_subtrees or self.excluded_subtrees)
37
+
38
+ def merge_parent(self, parent_nc: Optional[NameConstraintsExtension]) -> EffectiveConstraints:
39
+ """Merges parent constraints into this effective constraint set."""
40
+ if not parent_nc:
41
+ return self
42
+ - new_permitted = list(self.permitted_subtrees) + list(parent_nc.permitted_subtrees)
43
+ new_excluded = list(self.excluded_subtrees) + list(parent_nc.excluded_subtrees)
44
+ - new_groups = [list(g) for g in self._permitted_groups]
45
+ + new_groups = [list(g) for g in self.permitted_groups]
46
+ if parent_nc.permitted_subtrees:
47
+ new_groups.append(list(parent_nc.permitted_subtrees))
48
+ + new_permitted = [c for group in new_groups for c in group]
49
+ return EffectiveConstraints(
50
+ permitted_subtrees=new_permitted,
51
+ excluded_subtrees=new_excluded,
52
+ - _permitted_groups=new_groups,
53
+ + permitted_groups=new_groups,
54
+ )
55
+
56
+ + def add_ca_constraints(self, ca_nc: Optional[NameConstraintsExtension]) -> None:
57
+ + if not ca_nc:
58
+ + return
59
+ + if ca_nc.excluded_subtrees:
60
+ + self.excluded_subtrees.extend(ca_nc.excluded_subtrees)
61
+ + if ca_nc.permitted_subtrees:
62
+ + self.permitted_groups.append(list(ca_nc.permitted_subtrees))
63
+ + self.permitted_subtrees.extend(ca_nc.permitted_subtrees)
64
+ +
65
+
66
+ def match_dns_constraint(dns_name: str, constraint: str) -> bool:
67
+ - """Matches a DNS SAN name against a DNS name constraint.
68
+ -
69
+ - RFC 5280 DNS Name Constraint Rules:
70
+ - - Constraint 'example.com' or '.example.com' matches 'example.com' and 'host.example.com'.
71
+ - - Must respect dot boundaries (should not match 'fakecorp.internal' for 'corp.internal').
72
+ - """
73
+ - clean_dns = dns_name.lower().strip(".")
74
+ - clean_constraint = constraint.lower().strip(".")
75
+ -
76
+ + """Matches a DNS SAN name against a DNS name constraint adhering to RFC 5280 Section 4.2.1.10."""
77
+ + clean_dns = dns_name.lower().strip()
78
+ + clean_constraint = constraint.lower().strip()
79
+ +
80
+ + clean_constraint = clean_constraint.lstrip(".")
81
+ + clean_dns = clean_dns.strip(".")
82
+ +
83
+ if not clean_constraint:
84
+ return True
85
+ -
86
+ if clean_dns == clean_constraint:
87
+ return True
88
+ -
89
+ if clean_dns.endswith("." + clean_constraint):
90
+ return True
91
+ -
92
+ + if clean_dns.startswith("*."):
93
+ + suffix = clean_dns[2:]
94
+ + if suffix == clean_constraint or suffix.endswith("." + clean_constraint):
95
+ + return True
96
+ return False
97
+
98
+
99
+ def match_ip_constraint(ip_str: str, constraint_cidr: str) -> bool:
100
+ - """Matches an IP SAN against an IP CIDR constraint."""
101
+ + """Matches an IP SAN address or CIDR against an IP CIDR constraint."""
102
+ try:
103
+ - ip = ipaddress.ip_address(ip_str.strip())
104
+ net = ipaddress.ip_network(constraint_cidr.strip(), strict=False)
105
+ - return ip in net
106
+ + try:
107
+ + ip = ipaddress.ip_address(ip_str.strip())
108
+ + return ip in net
109
+ + except ValueError:
110
+ + sub_net = ipaddress.ip_network(ip_str.strip(), strict=False)
111
+ + return sub_net.subnet_of(net)
112
+ except (ValueError, TypeError):
113
+ return False
114
+
115
+
116
+ def match_uri_constraint(uri: str, constraint_prefix: str) -> bool:
117
+ - """Matches a URI SAN against a URI constraint prefix."""
118
+ - return uri.startswith(constraint_prefix)
119
+ + """Matches a URI SAN against a URI constraint prefix per RFC 5280 Section 4.2.1.10."""
120
+ + try:
121
+ + p_uri = urlparse(uri.strip())
122
+ + p_con = urlparse(constraint_prefix.strip())
123
+
124
+ + if p_con.scheme and p_uri.scheme.lower() != p_con.scheme.lower():
125
+ + return False
126
+ + if p_con.netloc and p_uri.netloc.lower() != p_con.netloc.lower():
127
+ + return False
128
+
129
+ -def validate_san_constraints(
130
+ + con_path = p_con.path
131
+ + uri_path = p_uri.path
132
+ +
133
+ + if not con_path or con_path == "/":
134
+ + return True
135
+ + if con_path.endswith("/"):
136
+ + return uri_path.startswith(con_path)
137
+ + return uri_path == con_path or uri_path.startswith(con_path + "/")
138
+ + except Exception:
139
+ + return uri.strip().lower().startswith(constraint_prefix.strip().lower())
140
+ +
141
+ +
142
+ +def validate_name_constraints(
143
+ san: SubjectAlternativeName,
144
+ + subject_dn: str,
145
+ constraints: EffectiveConstraints,
146
+ + is_ca: bool = False,
147
+ ) -> Tuple[bool, List[str]]:
148
+ - """Validates SAN entries against accumulated effective name constraints.
149
+ -
150
+ - Returns (is_valid, list_of_violation_errors).
151
+ - """
152
+ - if constraints.is_empty() or san.is_empty():
153
+ + """Validates SAN entries and Subject DN against accumulated effective name constraints."""
154
+ + if constraints.is_empty():
155
+ return True, []
156
+
157
+ errors: List[str] = []
158
+ + has_san = not san.is_empty()
159
+
160
+ - # 1. Check excluded subtrees (any match violates constraints)
161
+ + # 1. Check excluded subtrees
162
+ for excl in constraints.excluded_subtrees:
163
+ if excl.type == ConstraintType.DNS:
164
+ - for d in san.dns_names:
165
+ - if match_dns_constraint(d, excl.value):
166
+ - errors.append(f"DNS name '{d}' is excluded by constraint '{excl.value}'")
167
+ + if has_san and san.dns_names:
168
+ + for d in san.dns_names:
169
+ + if match_dns_constraint(d, excl.value):
170
+ + errors.append(f"DNS name '{d}' is excluded by constraint '{excl.value}'")
171
+ + elif not is_ca:
172
+ + # Extract CN from Subject DN for end-entity certificates
173
+ + for part in subject_dn.split(","):
174
+ + if part.strip().startswith("CN="):
175
+ + cn_val = part.strip()[3:]
176
+ + if match_dns_constraint(cn_val, excl.value):
177
+ + errors.append(f"Subject CN '{cn_val}' is excluded by constraint '{excl.value}'")
178
+ elif excl.type == ConstraintType.IP:
179
+ for ip in san.ip_addresses:
180
+ if match_ip_constraint(ip, excl.value):
181
+ @@ -110,27 +150,41 @@ def validate_san_constraints(
182
+ if match_uri_constraint(u, excl.value):
183
+ errors.append(f"URI '{u}' is excluded by constraint '{excl.value}'")
184
+
185
+ - # 2. Check permitted subtrees (intersection of all ancestor tiers)
186
+ - groups = constraints._permitted_groups if constraints._permitted_groups else (
187
+ - [constraints.permitted_subtrees] if constraints.permitted_subtrees else []
188
+ - )
189
+ + # 2. Check permitted subtree groups
190
+ + groups = constraints.permitted_groups if constraints.permitted_groups else ([constraints.permitted_subtrees] if constraints.permitted_subtrees else [])
191
+ +
192
+ for group in groups:
193
+ - dns_perm = [c.value for c in group if c.type == ConstraintType.DNS]
194
+ - if dns_perm and san.dns_names:
195
+ - for d in san.dns_names:
196
+ - if not any(match_dns_constraint(d, p) for p in dns_perm):
197
+ - errors.append(f"DNS name '{d}' is not permitted by allowed DNS subtrees {dns_perm}")
198
+ -
199
+ - ip_perm = [c.value for c in group if c.type == ConstraintType.IP]
200
+ - if ip_perm and san.ip_addresses:
201
+ + dns_perms = [c.value for c in group if c.type == ConstraintType.DNS]
202
+ + if dns_perms:
203
+ + if has_san and san.dns_names:
204
+ + for d in san.dns_names:
205
+ + if not any(match_dns_constraint(d, p) for p in dns_perms):
206
+ + errors.append(f"DNS name '{d}' is not permitted by allowed DNS subtrees {dns_perms}")
207
+ + elif not is_ca:
208
+ + for part in subject_dn.split(","):
209
+ + if part.strip().startswith("CN="):
210
+ + cn_val = part.strip()[3:]
211
+ + if not any(match_dns_constraint(cn_val, p) for p in dns_perms):
212
+ + errors.append(f"Subject CN '{cn_val}' is not permitted by allowed DNS subtrees {dns_perms}")
213
+ +
214
+ + ip_perms = [c.value for c in group if c.type == ConstraintType.IP]
215
+ + if ip_perms and san.ip_addresses:
216
+ for ip in san.ip_addresses:
217
+ - if not any(match_ip_constraint(ip, p) for p in ip_perm):
218
+ - errors.append(f"IP address '{ip}' is not permitted by allowed IP subtrees {ip_perm}")
219
+ + if not any(match_ip_constraint(ip, p) for p in ip_perms):
220
+ + errors.append(f"IP address '{ip}' is not permitted by allowed IP subtrees {ip_perms}")
221
+
222
+ - uri_perm = [c.value for c in group if c.type == ConstraintType.URI]
223
+ - if uri_perm and san.uris:
224
+ + uri_perms = [c.value for c in group if c.type == ConstraintType.URI]
225
+ + if uri_perms and san.uris:
226
+ for u in san.uris:
227
+ - if not any(match_uri_constraint(u, p) for p in uri_perm):
228
+ - errors.append(f"URI '{u}' is not permitted by allowed URI subtrees {uri_perm}")
229
+ + if not any(match_uri_constraint(u, p) for p in uri_perms):
230
+ + errors.append(f"URI '{u}' is not permitted by allowed URI subtrees {uri_perms}")
231
+
232
+ return len(errors) == 0, errors
233
+ +
234
+ +
235
+ +def validate_san_constraints(
236
+ + san: SubjectAlternativeName,
237
+ + constraints: EffectiveConstraints,
238
+ +) -> Tuple[bool, List[str]]:
239
+ + """Legacy helper for SAN-only constraint validation."""
240
+ + return validate_name_constraints(san, "", constraints, is_ca=False)
241
+ diff --git a/src/path/builder.py b/src/path/builder.py
242
+ index 5960b3e..6f8efe5 100644
243
+ --- a/src/path/builder.py
244
+ +++ b/src/path/builder.py
245
+ @@ -37,34 +37,35 @@ class PathBuilder:
246
+ self.max_path_length = max_path_length
247
+
248
+ def find_all_candidate_paths(self, leaf: Certificate) -> List[CandidatePath]:
249
+ - """Finds all candidate certification paths from leaf to an installed Trust Anchor."""
250
+ - paths: List[CandidatePath] = []
251
+ + """Finds all candidate certification paths from leaf to an installed Trust Anchor using backtracking."""
252
+ + all_paths: List[CandidatePath] = []
253
+
254
+ - if self.trust_store.is_trust_anchor(leaf):
255
+ - return [CandidatePath(certificates=[leaf])]
256
+ + def dfs(current_path: List[Certificate], visited_serials: Set[str]) -> None:
257
+ + current = current_path[-1]
258
+
259
+ - def _dfs(current_path: List[Certificate], visited_serials: Set[str]) -> None:
260
+ - if len(current_path) >= self.max_path_length:
261
+ + if self.trust_store.is_trust_anchor(current):
262
+ + all_paths.append(CandidatePath(certificates=list(current_path)))
263
+ return
264
+
265
+ - current = current_path[-1]
266
+ -
267
+ - if len(current_path) > 1 and self.trust_store.is_trust_anchor(current):
268
+ - paths.append(CandidatePath(certificates=list(current_path)))
269
+ + if len(current_path) >= self.max_path_length:
270
+ return
271
+
272
+ - candidates = self.trust_store.find_candidates(current.issuer_dn, current.authority_key_id)
273
+ + candidates = list(self.trust_store.find_candidates(current.issuer_dn, current.authority_key_id))
274
+
275
+ - if current.authority_info_access:
276
+ - for aia_key, uri in current.authority_info_access.items():
277
+ - if aia_key == "ca_issuers" or "ca_issuers" in aia_key:
278
+ - remote_cert = self.trust_store.fetch_aia_certificate(uri)
279
+ - if remote_cert and remote_cert not in candidates:
280
+ - candidates.append(remote_cert)
281
+ + # Lazy AIA ca_issuers resolution
282
+ + if current.authority_info_access and "ca_issuers" in current.authority_info_access:
283
+ + aia_url = current.authority_info_access["ca_issuers"]
284
+ + remote_cert = self.trust_store.fetch_remote_aia_certificate(aia_url)
285
+ + if remote_cert and remote_cert not in candidates:
286
+ + candidates.append(remote_cert)
287
+
288
+ for cand in candidates:
289
+ if cand.serial_number not in visited_serials:
290
+ - _dfs(current_path + [cand], visited_serials | {cand.serial_number})
291
+ -
292
+ - _dfs([leaf], {leaf.serial_number})
293
+ - return paths
294
+ + visited_serials.add(cand.serial_number)
295
+ + current_path.append(cand)
296
+ + dfs(current_path, visited_serials)
297
+ + current_path.pop()
298
+ + visited_serials.remove(cand.serial_number)
299
+ +
300
+ + dfs([leaf], {leaf.serial_number})
301
+ + return all_paths
302
+ diff --git a/src/policy/tree_processor.py b/src/policy/tree_processor.py
303
+ index da808a2..5c0fce6 100644
304
+ --- a/src/policy/tree_processor.py
305
+ +++ b/src/policy/tree_processor.py
306
+ @@ -15,23 +15,11 @@ class PolicyNode:
307
+ valid_policy: str
308
+ qualifier_set: Set[str] = field(default_factory=set)
309
+ expected_policy_set: Set[str] = field(default_factory=set)
310
+ + original_initial_policy: Optional[str] = None
311
+ parent: Optional[PolicyNode] = None
312
+ children: List[PolicyNode] = field(default_factory=list)
313
+
314
+
315
+ -def _prune_tree(nodes_by_depth: Dict[int, List[PolicyNode]], depth: int) -> None:
316
+ - """Prunes childless nodes backwards from depth to 0."""
317
+ - for d in range(depth, -1, -1):
318
+ - nodes = nodes_by_depth.get(d, [])
319
+ - to_remove = [node for node in nodes if len(node.children) == 0]
320
+ - for node in to_remove:
321
+ - if node.parent and node in node.parent.children:
322
+ - node.parent.children.remove(node)
323
+ - if node in nodes:
324
+ - nodes.remove(node)
325
+ - nodes_by_depth[d] = nodes
326
+ -
327
+ -
328
+ class PolicyTreeProcessor:
329
+ """Processes certification path policies and computes authorities_constrained_policies."""
330
+
331
+ @@ -45,140 +33,134 @@ class PolicyTreeProcessor:
332
+
333
+ Returns (is_valid, authorities_constrained_policies, errors).
334
+ """
335
+ - n = len(path_certificates)
336
+ - if n == 0:
337
+ - return False, set(), ["Empty certificate path"]
338
+ -
339
+ - # Chain from Root (depth 0) to Leaf (depth n-1)
340
+ - chain = list(reversed(path_certificates))
341
+ -
342
+ - root_node = PolicyNode(
343
+ - valid_policy=ANY_POLICY,
344
+ - qualifier_set=set(),
345
+ - expected_policy_set={ANY_POLICY},
346
+ - parent=None,
347
+ - children=[],
348
+ - )
349
+ - nodes_by_depth: dict[int, List[PolicyNode]] = {0: [root_node]}
350
+ -
351
+ - explicit_policy = 0 if self.config.initial_explicit_policy else (n + 1)
352
+ - inhibit_policy_mapping = 0 if self.config.initial_policy_mapping_inhibit else (n + 1)
353
+ - inhibit_any_policy = 0 if self.config.initial_any_policy_inhibit else (n + 1)
354
+ -
355
+ + errors: List[str] = []
356
+ + # Path from root to leaf
357
+ + certs = path_certificates[::-1]
358
+ + n = len(certs)
359
+ +
360
+ + # Initialize state variables from ValidationConfig
361
+ + explicit_policy = 0 if self.config.initial_explicit_policy else n + 1
362
+ + inhibit_policy_mapping = 0 if self.config.initial_policy_mapping_inhibit else n + 1
363
+ + inhibit_any_policy = 0 if self.config.initial_any_policy_inhibit else n + 1
364
+ +
365
+ + # Root certificate at index 0 (depth 0)
366
+ + root_cert = certs[0]
367
+ +
368
+ + # Read root constraints if present
369
+ + if root_cert.policy_constraints:
370
+ + if root_cert.policy_constraints.require_explicit_policy is not None:
371
+ + explicit_policy = min(explicit_policy, root_cert.policy_constraints.require_explicit_policy)
372
+ + if root_cert.policy_constraints.inhibit_policy_mapping is not None:
373
+ + inhibit_policy_mapping = min(inhibit_policy_mapping, root_cert.policy_constraints.inhibit_policy_mapping)
374
+ + if root_cert.inhibit_any_policy:
375
+ + inhibit_any_policy = min(inhibit_any_policy, root_cert.inhibit_any_policy.skip_certs)
376
+ +
377
+ + root_policies: Set[str] = set()
378
+ + if root_cert.certificate_policies and root_cert.certificate_policies.policies:
379
+ + root_policies = {p.policy_identifier for p in root_cert.certificate_policies.policies}
380
+ +
381
+ + if not root_policies or ANY_POLICY in root_policies:
382
+ + root_node = PolicyNode(
383
+ + valid_policy=ANY_POLICY,
384
+ + expected_policy_set={ANY_POLICY},
385
+ + original_initial_policy=ANY_POLICY,
386
+ + )
387
+ + nodes_by_depth: List[List[PolicyNode]] = [[root_node]]
388
+ + else:
389
+ + root_nodes: List[PolicyNode] = [
390
+ + PolicyNode(
391
+ + valid_policy=p,
392
+ + expected_policy_set={p},
393
+ + original_initial_policy=p,
394
+ + )
395
+ + for p in root_policies
396
+ + ]
397
+ + nodes_by_depth = [root_nodes]
398
+ +
399
+ + # Process certificates from index 1 to n-1 (depth 1 to n-1)
400
+ for i in range(1, n):
401
+ - cert = chain[i]
402
+ - is_leaf_cert = (i == n - 1)
403
+ -
404
+ - if cert.certificate_policies is None:
405
+ - if is_leaf_cert:
406
+ - if explicit_policy == 0:
407
+ - return False, set(), ["Explicit policy required but leaf certificate contains no policies"]
408
+ - return True, set(), []
409
+ -
410
+ - current_depth_nodes: List[PolicyNode] = []
411
+ - for p_node in nodes_by_depth.get(i - 1, []):
412
+ - for exp in p_node.expected_policy_set:
413
+ - c_node = PolicyNode(
414
+ - valid_policy=exp,
415
+ - qualifier_set=set(p_node.qualifier_set),
416
+ - expected_policy_set={exp},
417
+ - parent=p_node,
418
+ - children=[],
419
+ - )
420
+ - p_node.children.append(c_node)
421
+ - current_depth_nodes.append(c_node)
422
+ - nodes_by_depth[i] = current_depth_nodes
423
+ - else:
424
+ - cert_policies = cert.certificate_policies.policies
425
+ - cert_policy_ids = {p.policy_identifier for p in cert_policies}
426
+ - qualifiers_by_id = {p.policy_identifier: set(p.qualifiers) for p in cert_policies}
427
+ -
428
+ - current_depth_nodes = []
429
+ - parent_nodes = nodes_by_depth.get(i - 1, [])
430
+ -
431
+ - for p_node in parent_nodes:
432
+ - if p_node.valid_policy == ANY_POLICY:
433
+ - if ANY_POLICY in cert_policy_ids and (inhibit_any_policy > 0 or is_leaf_cert):
434
+ - c_node = PolicyNode(
435
+ - valid_policy=ANY_POLICY,
436
+ - qualifier_set=qualifiers_by_id.get(ANY_POLICY, set()),
437
+ - expected_policy_set={ANY_POLICY},
438
+ - parent=p_node,
439
+ - children=[],
440
+ + cert = certs[i]
441
+ + is_leaf = (i == n - 1)
442
+ + prev_nodes = nodes_by_depth[i - 1]
443
+ + current_depth_nodes: List[PolicyNode] = []
444
+ +
445
+ + # Check if intermediate has mappings but no certificate policies
446
+ + if not is_leaf and cert.policy_mappings and (not cert.certificate_policies or not cert.certificate_policies.policies):
447
+ + errors.append(f"Intermediate certificate {cert.subject_dn} contains policy_mappings without certificate_policies")
448
+ + return False, set(), errors
449
+ +
450
+ + # Step 1: Certificate Policies
451
+ + if cert.certificate_policies and cert.certificate_policies.policies:
452
+ + cert_p_oids = {p.policy_identifier for p in cert.certificate_policies.policies}
453
+ +
454
+ + # Check for anyPolicy wildcard expansion
455
+ + if ANY_POLICY in cert_p_oids and inhibit_any_policy > 0:
456
+ + for parent in prev_nodes:
457
+ + for exp_p in parent.expected_policy_set:
458
+ + orig_pol = parent.original_initial_policy if parent.original_initial_policy != ANY_POLICY else exp_p
459
+ + child = PolicyNode(
460
+ + valid_policy=exp_p,
461
+ + expected_policy_set={exp_p},
462
+ + original_initial_policy=orig_pol,
463
+ + parent=parent,
464
+ )
465
+ - p_node.children.append(c_node)
466
+ - current_depth_nodes.append(c_node)
467
+ - for p_id in cert_policy_ids:
468
+ - if p_id != ANY_POLICY:
469
+ - if ANY_POLICY in p_node.expected_policy_set or p_id in p_node.expected_policy_set:
470
+ - c_node = PolicyNode(
471
+ - valid_policy=p_id,
472
+ - qualifier_set=qualifiers_by_id.get(p_id, set()),
473
+ - expected_policy_set={p_id},
474
+ - parent=p_node,
475
+ - children=[],
476
+ - )
477
+ - p_node.children.append(c_node)
478
+ - current_depth_nodes.append(c_node)
479
+ - else:
480
+ - if ANY_POLICY in cert_policy_ids and (inhibit_any_policy > 0 or is_leaf_cert):
481
+ - for exp in p_node.expected_policy_set:
482
+ - c_node = PolicyNode(
483
+ - valid_policy=exp,
484
+ - qualifier_set=qualifiers_by_id.get(ANY_POLICY, set()),
485
+ - expected_policy_set={exp},
486
+ - parent=p_node,
487
+ - children=[],
488
+ + parent.children.append(child)
489
+ + current_depth_nodes.append(child)
490
+ + else:
491
+ + # Explicit policy processing
492
+ + for p_oid in cert_p_oids:
493
+ + if p_oid == ANY_POLICY:
494
+ + continue
495
+ + for parent in prev_nodes:
496
+ + if parent.valid_policy == p_oid or (
497
+ + parent.valid_policy == ANY_POLICY
498
+ + and (ANY_POLICY in parent.expected_policy_set or p_oid in parent.expected_policy_set)
499
+ + ) or (p_oid in parent.expected_policy_set):
500
+ + orig_pol = parent.original_initial_policy if parent.original_initial_policy != ANY_POLICY else p_oid
501
+ + child = PolicyNode(
502
+ + valid_policy=p_oid,
503
+ + expected_policy_set={p_oid},
504
+ + original_initial_policy=orig_pol,
505
+ + parent=parent,
506
+ )
507
+ - p_node.children.append(c_node)
508
+ - current_depth_nodes.append(c_node)
509
+ - for p_id in cert_policy_ids:
510
+ - if p_id != ANY_POLICY:
511
+ - if p_id in p_node.expected_policy_set:
512
+ - c_node = PolicyNode(
513
+ - valid_policy=p_id,
514
+ - qualifier_set=qualifiers_by_id.get(p_id, set()),
515
+ - expected_policy_set={p_id},
516
+ - parent=p_node,
517
+ - children=[],
518
+ - )
519
+ - p_node.children.append(c_node)
520
+ - current_depth_nodes.append(c_node)
521
+ -
522
+ - _prune_tree(nodes_by_depth, i - 1)
523
+ - nodes_by_depth[i] = current_depth_nodes
524
+ -
525
+ - if not current_depth_nodes:
526
+ - if explicit_policy == 0 or (is_leaf_cert and self.config.initial_explicit_policy):
527
+ - return False, set(), [f"Valid policy tree is empty at depth {i}"]
528
+ -
529
+ - if not is_leaf_cert:
530
+ - if cert.policy_mappings:
531
+ - if inhibit_policy_mapping > 0:
532
+ - for m in cert.policy_mappings.mappings:
533
+ - if m.issuer_domain_policy == ANY_POLICY or m.subject_domain_policy == ANY_POLICY:
534
+ - return False, set(), ["Policy mapping cannot map to or from anyPolicy"]
535
+ -
536
+ - mapped_any = False
537
+ - for node in nodes_by_depth.get(i, []):
538
+ - if node.valid_policy == m.issuer_domain_policy:
539
+ - node.expected_policy_set = {m.subject_domain_policy}
540
+ - mapped_any = True
541
+ -
542
+ - if not mapped_any:
543
+ - any_nodes = [node for node in nodes_by_depth.get(i, []) if node.valid_policy == ANY_POLICY]
544
+ - for any_node in any_nodes:
545
+ - new_node = PolicyNode(
546
+ - valid_policy=m.issuer_domain_policy,
547
+ - qualifier_set=set(any_node.qualifier_set),
548
+ + parent.children.append(child)
549
+ + current_depth_nodes.append(child)
550
+ +
551
+ + nodes_by_depth.append(current_depth_nodes)
552
+ +
553
+ + # Step 2: Policy Mappings (intermediate CAs only)
554
+ + if not is_leaf and cert.policy_mappings and cert.policy_mappings.mappings:
555
+ + for m in cert.policy_mappings.mappings:
556
+ + if m.issuer_domain_policy == ANY_POLICY or m.subject_domain_policy == ANY_POLICY:
557
+ + errors.append("Policy mapping cannot map to or from anyPolicy")
558
+ + return False, set(), errors
559
+ +
560
+ + if inhibit_policy_mapping > 0:
561
+ + for m in cert.policy_mappings.mappings:
562
+ + mapped_any = False
563
+ + for node in current_depth_nodes:
564
+ + if node.valid_policy == m.issuer_domain_policy:
565
+ + node.valid_policy = m.subject_domain_policy
566
+ + node.expected_policy_set = {m.subject_domain_policy}
567
+ + mapped_any = True
568
+ + if not mapped_any:
569
+ + for parent in prev_nodes:
570
+ + if parent.valid_policy == ANY_POLICY or m.issuer_domain_policy in parent.expected_policy_set:
571
+ + child = PolicyNode(
572
+ + valid_policy=m.subject_domain_policy,
573
+ expected_policy_set={m.subject_domain_policy},
574
+ - parent=any_node.parent,
575
+ - children=[],
576
+ + original_initial_policy=parent.original_initial_policy or m.issuer_domain_policy,
577
+ + parent=parent,
578
+ )
579
+ - if any_node.parent:
580
+ - any_node.parent.children.append(new_node)
581
+ - nodes_by_depth[i].append(new_node)
582
+ -
583
+ + parent.children.append(child)
584
+ + current_depth_nodes.append(child)
585
+ + else:
586
+ + if cert.policy_mappings.critical:
587
+ + errors.append("Critical policy mapping present while inhibit_policy_mapping is 0")
588
+ + return False, set(), errors
589
+ +
590
+ + # Step 3: Update state variables (intermediate CAs only)
591
+ + if not is_leaf:
592
+ if cert.policy_constraints:
593
+ if cert.policy_constraints.require_explicit_policy is not None:
594
+ explicit_policy = min(explicit_policy, cert.policy_constraints.require_explicit_policy)
595
+ @@ -187,42 +169,44 @@ class PolicyTreeProcessor:
596
+ if cert.inhibit_any_policy:
597
+ inhibit_any_policy = min(inhibit_any_policy, cert.inhibit_any_policy.skip_certs)
598
+
599
+ - if not cert.is_self_issued:
600
+ - if explicit_policy > 0:
601
+ - explicit_policy -= 1
602
+ - if inhibit_policy_mapping > 0:
603
+ - inhibit_policy_mapping -= 1
604
+ - if inhibit_any_policy > 0:
605
+ - inhibit_any_policy -= 1
606
+ + if explicit_policy > 0 and not cert.is_self_issued:
607
+ + explicit_policy -= 1
608
+ + if inhibit_policy_mapping > 0 and not cert.is_self_issued:
609
+ + inhibit_policy_mapping -= 1
610
+ + if inhibit_any_policy > 0 and not cert.is_self_issued:
611
+ + inhibit_any_policy -= 1
612
+
613
+ - leaf_cert = chain[-1]
614
+ - if leaf_cert.policy_constraints:
615
+ - if leaf_cert.policy_constraints.require_explicit_policy is not None and leaf_cert.policy_constraints.require_explicit_policy == 0:
616
+ - explicit_policy = 0
617
+ + # Check if valid policy tree has become empty
618
+ + if not current_depth_nodes and explicit_policy <= 0:
619
+ + errors.append(f"Valid policy tree is empty at depth {i}")
620
+ + return False, set(), errors
621
+
622
+ - leaf_nodes = nodes_by_depth.get(n - 1, [])
623
+ + # Wrap up at leaf
624
+ + leaf_nodes = nodes_by_depth[-1]
625
+ if not leaf_nodes:
626
+ - if explicit_policy == 0 or self.config.initial_explicit_policy:
627
+ - return False, set(), ["No valid certificate policy tree for explicit policy requirement"]
628
+ + if explicit_policy <= 0:
629
+ + errors.append("No valid policy tree path exists to the leaf certificate")
630
+ + return False, set(), errors
631
+ return True, set(), []
632
+
633
+ - valid_policies: Set[str] = set()
634
+ - for node in leaf_nodes:
635
+ - if node.valid_policy == ANY_POLICY:
636
+ - valid_policies.update(self.config.initial_policy_set)
637
+ + # Form constrained policies in terms of relying party / root domain and leaf domain
638
+ + constrained_policies: Set[str] = set()
639
+ + for n in leaf_nodes:
640
+ + if ANY_POLICY in self.config.initial_policy_set:
641
+ + constrained_policies.add(n.valid_policy)
642
+ + if n.original_initial_policy:
643
+ + constrained_policies.add(n.original_initial_policy)
644
+ else:
645
+ - curr = node
646
+ - while curr.parent and curr.parent.parent is not None:
647
+ - curr = curr.parent
648
+ - ancestor_depth_1 = curr
649
+ - if ancestor_depth_1.valid_policy != ANY_POLICY:
650
+ - valid_policies.add(ancestor_depth_1.valid_policy)
651
+ - valid_policies.add(node.valid_policy)
652
+ -
653
+ - if explicit_policy == 0 or self.config.initial_explicit_policy:
654
+ - if ANY_POLICY not in self.config.initial_policy_set:
655
+ - intersection = valid_policies.intersection(self.config.initial_policy_set)
656
+ - if not intersection:
657
+ - return False, set(), [f"No valid policy in intersection with initial policy set: {valid_policies}"]
658
+ -
659
+ - return True, valid_policies, []
660
+ + if n.valid_policy in self.config.initial_policy_set:
661
+ + constrained_policies.add(n.valid_policy)
662
+ + if n.original_initial_policy and n.original_initial_policy in self.config.initial_policy_set:
663
+ + constrained_policies.add(n.original_initial_policy)
664
+ + constrained_policies.add(n.valid_policy)
665
+ + if n.valid_policy == ANY_POLICY:
666
+ + constrained_policies.update(self.config.initial_policy_set)
667
+ +
668
+ + if not constrained_policies and explicit_policy <= 0:
669
+ + errors.append(f"No valid policies in intersection with initial policy set: {self.config.initial_policy_set}")
670
+ + return False, set(), errors
671
+ +
672
+ + return True, constrained_policies, []
673
+ diff --git a/src/revocation/crl_manager.py b/src/revocation/crl_manager.py
674
+ index 2720433..d9baf06 100644
675
+ --- a/src/revocation/crl_manager.py
676
+ +++ b/src/revocation/crl_manager.py
677
+ @@ -22,81 +22,118 @@ class CRLValidationStatus:
678
+ revocation_date: Optional[str] = None
679
+ crl_number: Optional[int] = None
680
+ uncovered_reasons: Set[CRLReason] = field(default_factory=set)
681
+ + error_message: Optional[str] = None
682
+
683
+
684
+ class CRLCache:
685
+ - """Maintains Base and Delta CRLs with partition reason support."""
686
+ + """Maintains Base and Delta CRLs with partition reason support and monotonic sequence ordering."""
687
+
688
+ def __init__(self) -> None:
689
+ - # Key: (issuer_dn, authority_key_id, frozenset(covered_reasons)) -> list of CertificateRevocationList
690
+ - self._crls: Dict[Tuple[str, str, frozenset[CRLReason]], List[CertificateRevocationList]] = {}
691
+ + # Key: (issuer_dn, authority_key_id) -> list of CertificateRevocationList
692
+ + self._crls: Dict[Tuple[str, str], List[CertificateRevocationList]] = {}
693
+ + # Indirect CRLs: list of CertificateRevocationList
694
+ + self._indirect_crls: List[CertificateRevocationList] = []
695
+ # Active revocations: (issuer_dn, authority_key_id, serial) -> RevokedCertificateEntry
696
+ self._active_revocations: Dict[Tuple[str, str, str], RevokedCertificateEntry] = {}
697
+ - # Tracks latest observed CRL number: (issuer_dn, authority_key_id, frozenset(covered_reasons)) -> max_crl_number
698
+ - self._latest_crl_numbers: Dict[Tuple[str, str, frozenset[CRLReason]], int] = {}
699
+ - # Tracks max CRL number per issuer: (issuer_dn, authority_key_id) -> max_crl_number
700
+ - self._issuer_crl_numbers: Dict[Tuple[str, str], int] = {}
701
+ + # Tracks latest observed CRL number for monotonic ordering: (issuer_dn, authority_key_id) -> max_crl_number
702
+ + self._latest_crl_numbers: Dict[Tuple[str, str], int] = {}
703
+ + # Tracks latest base CRL number per issuer: (issuer_dn, authority_key_id) -> max_base_crl_number
704
+ + self._latest_base_crl_numbers: Dict[Tuple[str, str], int] = {}
705
+
706
+ def register_crl(self, crl: CertificateRevocationList) -> bool:
707
+ - """Registers a Base or Delta CRL into the cache."""
708
+ + """Registers a Base or Delta CRL into the cache. Enforces monotonic sequence numbers and RFC 5280 constraints."""
709
+ akid = crl.authority_key_id or ""
710
+ - reasons_key = frozenset(crl.covered_reasons)
711
+ - scope_key = (crl.issuer_dn, akid, reasons_key)
712
+ -
713
+ - # Monotonic CRL sequence check
714
+ - if scope_key in self._latest_crl_numbers:
715
+ - if crl.crl_number <= self._latest_crl_numbers[scope_key]:
716
+ - return False # Reject stale replay or non-monotonic number
717
+ -
718
+ - self._latest_crl_numbers[scope_key] = crl.crl_number
719
+ - issuer_key = (crl.issuer_dn, akid)
720
+ - self._issuer_crl_numbers[issuer_key] = max(
721
+ - crl.crl_number, self._issuer_crl_numbers.get(issuer_key, 0)
722
+ - )
723
+ -
724
+ - if scope_key not in self._crls:
725
+ - self._crls[scope_key] = []
726
+ - self._crls[scope_key].append(crl)
727
+ -
728
+ - # Process revoked entries
729
+ - for entry in crl.revoked_entries:
730
+ - rev_key = (crl.issuer_dn, akid, entry.serial_number)
731
+ - if crl.is_delta and entry.reason == CRLReason.REMOVE_FROM_CRL:
732
+ - # Un-revoke if placed on hold
733
+ - if rev_key in self._active_revocations:
734
+ - del self._active_revocations[rev_key]
735
+ - for k in list(self._active_revocations.keys()):
736
+ - if k[0] == crl.issuer_dn and k[2] == entry.serial_number:
737
+ - del self._active_revocations[k]
738
+ + key = (crl.issuer_dn, akid)
739
+ +
740
+ + # RFC 5280 Section 5.2.4: Delta CRL validation
741
+ + if crl.is_delta:
742
+ + if crl.base_crl_number is None:
743
+ + return False
744
+ + # Base CRL with crl_number >= base_crl_number must exist
745
+ + max_base = self._latest_base_crl_numbers.get(key)
746
+ + if max_base is None or max_base < crl.base_crl_number:
747
+ + return False
748
+ + if crl.crl_number <= crl.base_crl_number:
749
+ + return False
750
+ +
751
+ + # Monotonic CRL number replay protection per (issuer_dn, AKID)
752
+ + if key in self._latest_crl_numbers and crl.crl_number <= self._latest_crl_numbers[key]:
753
+ + return False
754
+ +
755
+ + self._latest_crl_numbers[key] = crl.crl_number
756
+ + if not crl.is_delta:
757
+ + self._latest_base_crl_numbers[key] = max(self._latest_base_crl_numbers.get(key, 0), crl.crl_number)
758
+ +
759
+ + if crl.is_indirect:
760
+ + self._indirect_crls.append(crl)
761
+ +
762
+ + if key not in self._crls:
763
+ + self._crls[key] = []
764
+ +
765
+ + if not crl.is_delta:
766
+ + if crl.covered_reasons is None or crl.covered_reasons == ALL_REASONS:
767
+ + self._crls[key] = [crl]
768
+ else:
769
+ - self._active_revocations[rev_key] = entry
770
+ -
771
+ - return True
772
+ + replaced = False
773
+ + for idx, existing in enumerate(self._crls[key]):
774
+ + if existing.covered_reasons and (existing.covered_reasons & crl.covered_reasons):
775
+ + self._crls[key][idx] = crl
776
+ + replaced = True
777
+ + break
778
+ + if not replaced:
779
+ + if len(self._crls[key]) >= 2:
780
+ + self._crls[key].pop(0)
781
+ + self._crls[key].append(crl)
782
+ + else:
783
+ + self._crls[key].append(crl)
784
+ +
785
+ + if not crl.is_delta:
786
+ + # Clear previous active revocations for this issuer/AKID that match covered reasons
787
+ + keys_to_remove = [
788
+ + k for k in self._active_revocations
789
+ + if k[0] == crl.issuer_dn and k[1] == akid
790
+ + and self._active_revocations[k].reason in crl.covered_reasons
791
+ + ]
792
+ + for k in keys_to_remove:
793
+ + del self._active_revocations[k]
794
+ +
795
+ + for entry in crl.revoked_entries:
796
+ + if entry.reason != CRLReason.REMOVE_FROM_CRL:
797
+ + iss_dn = entry.certificate_issuer if (crl.is_indirect and entry.certificate_issuer) else crl.issuer_dn
798
+ + self._active_revocations[(iss_dn, akid, entry.serial_number)] = entry
799
+ + return True
800
+ + else:
801
+ + # Delta CRL updates
802
+ + for entry in crl.revoked_entries:
803
+ + iss_dn = entry.certificate_issuer if (crl.is_indirect and entry.certificate_issuer) else crl.issuer_dn
804
+ + rev_key = (iss_dn, akid, entry.serial_number)
805
+ + if entry.reason == CRLReason.REMOVE_FROM_CRL:
806
+ + self._active_revocations.pop(rev_key, None)
807
+ + self._active_revocations.pop((iss_dn, "", entry.serial_number), None)
808
+ + else:
809
+ + self._active_revocations[rev_key] = entry
810
+ + return True
811
+
812
+ def check_revocation(
813
+ - self, cert: Certificate, required_reasons: Optional[Set[CRLReason]] = None
814
+ + self,
815
+ + cert: Certificate,
816
+ + required_reasons: Optional[Set[CRLReason]] = None,
817
+ + current_time: Optional[str] = None,
818
+ ) -> CRLValidationStatus:
819
+ - """Checks if a certificate is revoked and verifies complete reason code coverage across CRL partitions."""
820
+ + """Checks if a certificate is revoked and verifies complete reason code coverage across valid CRL partitions."""
821
+ + if required_reasons is None:
822
+ + required_reasons = set(ALL_REASONS)
823
+ +
824
+ akid = cert.authority_key_id or ""
825
+ key = (cert.issuer_dn, akid)
826
+
827
+ - # Check active revocations
828
+ + # 1. Check direct active revocations
829
+ rev_key = (cert.issuer_dn, akid, cert.serial_number)
830
+ if rev_key in self._active_revocations:
831
+ entry = self._active_revocations[rev_key]
832
+ - latest_num = self._issuer_crl_numbers.get(key, 0)
833
+ - return CRLValidationStatus(
834
+ - is_revoked=True,
835
+ - is_fully_covered=True,
836
+ - reason=entry.reason,
837
+ - revocation_date=entry.revocation_date,
838
+ - crl_number=latest_num,
839
+ - )
840
+ -
841
+ - # Fallback check by issuer_dn and serial
842
+ - for (iss_dn, auth_id, ser), entry in self._active_revocations.items():
843
+ - if iss_dn == cert.issuer_dn and ser == cert.serial_number:
844
+ - latest_num = self._issuer_crl_numbers.get((iss_dn, auth_id), 0)
845
+ + # Check future scheduled revocation date
846
+ + if current_time is None or entry.revocation_date <= current_time:
847
+ + latest_num = self._latest_crl_numbers.get(key, 0)
848
+ return CRLValidationStatus(
849
+ is_revoked=True,
850
+ is_fully_covered=True,
851
+ @@ -105,42 +142,79 @@ class CRLCache:
852
+ crl_number=latest_num,
853
+ )
854
+
855
+ - # Find matching registered CRLs for this issuer
856
+ - matching_crl_lists = [
857
+ - crl_list for (iss, auth, _), crl_list in self._crls.items()
858
+ - if iss == cert.issuer_dn and (not akid or not auth or auth == akid)
859
+ - ]
860
+ -
861
+ - if not matching_crl_lists:
862
+ + # Search by issuer DN without AKID
863
+ + for (iss_dn, entry_akid, sn), entry in self._active_revocations.items():
864
+ + if iss_dn == cert.issuer_dn and sn == cert.serial_number:
865
+ + if not akid or not entry_akid or akid == entry_akid:
866
+ + if current_time is None or entry.revocation_date <= current_time:
867
+ + latest_num = self._latest_crl_numbers.get((iss_dn, entry_akid), 0)
868
+ + return CRLValidationStatus(
869
+ + is_revoked=True,
870
+ + is_fully_covered=True,
871
+ + reason=entry.reason,
872
+ + revocation_date=entry.revocation_date,
873
+ + crl_number=latest_num,
874
+ + )
875
+ +
876
+ + # 2. Check Indirect CRLs
877
+ + for ind_crl in self._indirect_crls:
878
+ + if current_time:
879
+ + if ind_crl.next_update and current_time > ind_crl.next_update:
880
+ + continue
881
+ + if ind_crl.this_update and current_time < ind_crl.this_update:
882
+ + continue
883
+ + for entry in ind_crl.revoked_entries:
884
+ + if entry.serial_number == cert.serial_number:
885
+ + entry_issuer = entry.certificate_issuer or ind_crl.issuer_dn
886
+ + if entry_issuer == cert.issuer_dn:
887
+ + if current_time is None or entry.revocation_date <= current_time:
888
+ + return CRLValidationStatus(
889
+ + is_revoked=True,
890
+ + is_fully_covered=True,
891
+ + reason=entry.reason,
892
+ + revocation_date=entry.revocation_date,
893
+ + crl_number=ind_crl.crl_number,
894
+ + )
895
+ +
896
+ + # 3. Check reason code coverage across active and unexpired CRL partitions for this issuing CA
897
+ + registered_crl_list = list(self._crls.get(key, []))
898
+ + if not registered_crl_list and not akid:
899
+ + for (iss_dn, _), crls in self._crls.items():
900
+ + if iss_dn == cert.issuer_dn:
901
+ + registered_crl_list.extend(crls)
902
+ +
903
+ + if not registered_crl_list:
904
+ return CRLValidationStatus(is_revoked=False, is_fully_covered=True)
905
+
906
+ - covered_union: Set[CRLReason] = set()
907
+ - for crl_list in matching_crl_lists:
908
+ - for crl in crl_list:
909
+ - covered_union.update(crl.covered_reasons)
910
+ -
911
+ - target_reasons = required_reasons if required_reasons is not None else ALL_REASONS
912
+ - uncovered = target_reasons - covered_union
913
+ -
914
+ + # Only use latest CRL per partition and check freshness against current_time
915
+ + total_covered: Set[CRLReason] = set()
916
+ + for crl in registered_crl_list:
917
+ + if current_time:
918
+ + if crl.next_update and current_time > crl.next_update:
919
+ + # CRL is expired -> skip coverage contribution
920
+ + continue
921
+ + if crl.this_update and current_time < crl.this_update:
922
+ + # CRL is from future -> skip
923
+ + continue
924
+ + total_covered.update(crl.covered_reasons)
925
+ +
926
+ + uncovered = required_reasons - total_covered
927
+ if uncovered:
928
+ return CRLValidationStatus(
929
+ is_revoked=False,
930
+ is_fully_covered=False,
931
+ uncovered_reasons=uncovered,
932
+ + error_message=f"Incomplete CRL reason coverage for {cert.issuer_dn}: missing {uncovered}",
933
+ )
934
+
935
+ - latest_num = self._issuer_crl_numbers.get(key, 0)
936
+ - return CRLValidationStatus(
937
+ - is_revoked=False,
938
+ - is_fully_covered=True,
939
+ - crl_number=latest_num,
940
+ - )
941
+ + return CRLValidationStatus(is_revoked=False, is_fully_covered=True)
942
+
943
+ def get_latest_crl_number(self, issuer_dn: str, akid: str) -> Optional[int]:
944
+ - return self._issuer_crl_numbers.get((issuer_dn, akid))
945
+ + return self._latest_crl_numbers.get((issuer_dn, akid))
946
+
947
+ def clear(self) -> None:
948
+ self._crls.clear()
949
+ + self._indirect_crls.clear()
950
+ self._active_revocations.clear()
951
+ self._latest_crl_numbers.clear()
952
+ - self._issuer_crl_numbers.clear()
953
+ + self._latest_base_crl_numbers.clear()
954
+ diff --git a/src/store/trust_store.py b/src/store/trust_store.py
955
+ index c5bf0da..87e62c2 100644
956
+ --- a/src/store/trust_store.py
957
+ +++ b/src/store/trust_store.py
958
+ @@ -61,6 +61,9 @@ class TrustStore:
959
+ def fetch_aia_certificate(self, uri: str) -> Optional[Certificate]:
960
+ return self._remote_aia_certs.get(uri)
961
+
962
+ + def fetch_remote_aia_certificate(self, uri: str) -> Optional[Certificate]:
963
+ + return self.fetch_aia_certificate(uri)
964
+ +
965
+ def register_crl(self, crl: CertificateRevocationList) -> bool:
966
+ """Registers a Base or Delta CRL."""
967
+ accepted = self._crl_cache.register_crl(crl)
968
+ diff --git a/src/validation/engine.py b/src/validation/engine.py
969
+ index 55cc6e8..c17e7ce 100644
970
+ --- a/src/validation/engine.py
971
+ +++ b/src/validation/engine.py
972
+ @@ -4,7 +4,7 @@ from __future__ import annotations
973
+
974
+ from typing import Dict, List, Optional, Set, Tuple
975
+
976
+ -from src.constraints.matcher import EffectiveConstraints, validate_san_constraints
977
+ +from src.constraints.matcher import EffectiveConstraints, validate_name_constraints
978
+ from src.crypto.signer import verify_certificate_signature
979
+ from src.models import (
980
+ ALL_REASONS,
981
+ @@ -23,34 +23,23 @@ class PathValidationEngine:
982
+ def __init__(self, trust_store: TrustStore) -> None:
983
+ self.trust_store = trust_store
984
+ self.path_builder = PathBuilder(trust_store)
985
+ - # Cache key: summary string -> ValidationResult
986
+ + # Cache key: (leaf_fingerprint, epoch, config_hash) -> ValidationResult
987
+ self._cache: Dict[str, ValidationResult] = {}
988
+
989
+ def clear_cache(self) -> None:
990
+ self._cache.clear()
991
+
992
+ - def _get_cache_key(self, leaf: Certificate, config: ValidationConfig) -> str:
993
+ - return (
994
+ - f"epoch={self.trust_store.epoch}:"
995
+ - f"leaf={leaf.fingerprint}:"
996
+ - f"rev={config.check_revocation}:"
997
+ - f"nc={config.enforce_name_constraints}:"
998
+ - f"pl={config.enforce_path_len}:"
999
+ - f"pt={config.enforce_policy_tree}:"
1000
+ - f"pols={sorted(config.initial_policy_set)}:"
1001
+ - f"exp={config.initial_explicit_policy}:"
1002
+ - f"map_inh={config.initial_policy_mapping_inhibit}:"
1003
+ - f"any_inh={config.initial_any_policy_inhibit}:"
1004
+ - f"time={config.current_time}:"
1005
+ - f"crit={sorted(config.allowed_custom_critical_oids)}"
1006
+ - )
1007
+ -
1008
+ def validate(self, leaf: Certificate, config: Optional[ValidationConfig] = None) -> ValidationResult:
1009
+ """Validates a target leaf certificate against installed trust anchors and policies."""
1010
+ if config is None:
1011
+ config = ValidationConfig()
1012
+
1013
+ - cache_key = self._get_cache_key(leaf, config)
1014
+ + cache_key = (
1015
+ + f"{self.trust_store.epoch}:{leaf.fingerprint}:{config.check_revocation}:"
1016
+ + f"{config.enforce_name_constraints}:{config.enforce_path_len}:{config.enforce_policy_tree}:"
1017
+ + f"{config.initial_explicit_policy}:{sorted(config.initial_policy_set)}:{config.current_time}:"
1018
+ + f"{sorted(config.allowed_custom_critical_oids)}"
1019
+ + )
1020
+ if cache_key in self._cache:
1021
+ return self._cache[cache_key]
1022
+
1023
+ @@ -65,8 +54,8 @@ class PathValidationEngine:
1024
+ self._cache[cache_key] = res
1025
+ return res
1026
+
1027
+ - # 2. Backtracking: try candidate paths until a valid one is found
1028
+ - last_errors: List[str] = []
1029
+ + # 2. Explore all candidate paths, backtracking if one fails
1030
+ + all_candidate_errors: List[str] = []
1031
+ for candidate in candidate_paths:
1032
+ path_valid, policies, errors = self._validate_single_path(candidate, config)
1033
+ if path_valid:
1034
+ @@ -78,13 +67,14 @@ class PathValidationEngine:
1035
+ )
1036
+ self._cache[cache_key] = res
1037
+ return res
1038
+ - last_errors = errors
1039
+ + all_candidate_errors.extend(errors)
1040
+
1041
+ res = ValidationResult(
1042
+ is_valid=False,
1043
+ - error_message=f"Path validation failed: {'; '.join(last_errors)}",
1044
+ - errors=last_errors,
1045
+ + error_message=f"Path validation failed: {'; '.join(all_candidate_errors)}",
1046
+ + errors=all_candidate_errors,
1047
+ )
1048
+ +
1049
+ self._cache[cache_key] = res
1050
+ return res
1051
+
1052
+ @@ -95,12 +85,16 @@ class PathValidationEngine:
1053
+ certs = candidate.certificates
1054
+ errors: List[str] = []
1055
+
1056
+ - # 1. Root must be a trust anchor
1057
+ + # 1. Root must be a trust anchor and must be a CA
1058
+ root = certs[-1]
1059
+ if not self.trust_store.is_trust_anchor(root):
1060
+ errors.append(f"Root certificate {root.subject_dn} is not a trusted anchor")
1061
+ return False, set(), errors
1062
+
1063
+ + if not root.basic_constraints.is_ca:
1064
+ + errors.append(f"Root trust anchor {root.subject_dn} has is_ca=False")
1065
+ + return False, set(), errors
1066
+ +
1067
+ # 2. Structural & CA constraint checks for intermediates
1068
+ for i in range(1, len(certs)):
1069
+ ca_cert = certs[i]
1070
+ @@ -109,21 +103,12 @@ class PathValidationEngine:
1071
+ if not ca_cert.key_usage.key_cert_sign:
1072
+ errors.append(f"Intermediate certificate {ca_cert.subject_dn} lacks key_cert_sign usage")
1073
+
1074
+ - # 3. Unrecognized critical extensions
1075
+ - for cert in certs:
1076
+ - for oid in cert.unrecognized_critical_extensions:
1077
+ - if oid not in config.allowed_custom_critical_oids:
1078
+ - errors.append(
1079
+ - f"Certificate {cert.subject_dn} contains unrecognized critical extension: {oid}"
1080
+ - )
1081
+ -
1082
+ - # 4. Path length constraints
1083
+ + # 3. Path length constraints (self-issued intermediate certs do not count)
1084
+ if config.enforce_path_len:
1085
+ for i in range(1, len(certs)):
1086
+ ca_cert = certs[i]
1087
+ path_len_limit = ca_cert.basic_constraints.path_len_constraint
1088
+ if path_len_limit is not None:
1089
+ - # Number of non-self-issued intermediate certificates between this CA and the leaf
1090
+ intermediates_below = [c for c in certs[1:i] if not c.is_self_issued]
1091
+ if len(intermediates_below) > path_len_limit:
1092
+ errors.append(
1093
+ @@ -131,7 +116,7 @@ class PathValidationEngine:
1094
+ f"limit={path_len_limit}, observed={len(intermediates_below)}"
1095
+ )
1096
+
1097
+ - # 5. Validity period checking
1098
+ + # 4. Validity period checking
1099
+ if config.current_time:
1100
+ for cert in certs:
1101
+ if config.current_time < cert.not_before:
1102
+ @@ -139,6 +124,18 @@ class PathValidationEngine:
1103
+ if config.current_time > cert.not_after:
1104
+ errors.append(f"Certificate {cert.subject_dn} is expired at {config.current_time}")
1105
+
1106
+ + # 5. Critical extension checking
1107
+ + for cert in certs:
1108
+ + if cert.unrecognized_critical_extensions:
1109
+ + unhandled = [
1110
+ + oid for oid in cert.unrecognized_critical_extensions
1111
+ + if oid not in config.allowed_custom_critical_oids
1112
+ + ]
1113
+ + if unhandled:
1114
+ + errors.append(
1115
+ + f"Certificate {cert.subject_dn} contains unrecognized critical extension(s): {unhandled}"
1116
+ + )
1117
+ +
1118
+ # 6. Cryptographic signature chain verification
1119
+ for i in range(len(certs) - 1):
1120
+ child = certs[i]
1121
+ @@ -150,7 +147,9 @@ class PathValidationEngine:
1122
+ if config.check_revocation:
1123
+ for i in range(len(certs) - 1):
1124
+ child = certs[i]
1125
+ - rev_status = self.trust_store.crl_cache.check_revocation(child, ALL_REASONS)
1126
+ + rev_status = self.trust_store.crl_cache.check_revocation(
1127
+ + child, ALL_REASONS, current_time=config.current_time
1128
+ + )
1129
+ if rev_status.is_revoked:
1130
+ errors.append(
1131
+ f"Certificate {child.subject_dn} (serial {child.serial_number}) is revoked: "
1132
+ @@ -165,16 +164,16 @@ class PathValidationEngine:
1133
+ # 8. Transitive Name constraints evaluation
1134
+ if config.enforce_name_constraints:
1135
+ eff = EffectiveConstraints()
1136
+ - if certs[-1].name_constraints:
1137
+ - eff = eff.merge_parent(certs[-1].name_constraints)
1138
+ - for idx in range(len(certs) - 2, -1, -1):
1139
+ - curr_cert = certs[idx]
1140
+ - if not eff.is_empty() and not curr_cert.san.is_empty():
1141
+ - valid_nc, nc_errs = validate_san_constraints(curr_cert.san, eff)
1142
+ + for i in range(len(certs) - 1, -1, -1):
1143
+ + cert = certs[i]
1144
+ + if not eff.is_empty():
1145
+ + valid_nc, nc_errs = validate_name_constraints(
1146
+ + cert.san, cert.subject_dn, eff, is_ca=cert.basic_constraints.is_ca
1147
+ + )
1148
+ if not valid_nc:
1149
+ errors.extend(nc_errs)
1150
+ - if curr_cert.name_constraints:
1151
+ - eff = eff.merge_parent(curr_cert.name_constraints)
1152
+ + if cert.name_constraints:
1153
+ + eff = eff.merge_parent(cert.name_constraints)
1154
+
1155
+ # 9. Certificate Policy Tree Processing
1156
+ valid_policies: Set[str] = set()
tests/check_cyber_reference.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline reference-only cache regressions; does not change benchmark scoring.
2
+
3
+ Run: python tests/check_cyber_reference.py
4
+ Requires Python 3.12+ and git. Uses only the standard library and bundled fixtures.
5
+ """
6
+ import argparse
7
+ from dataclasses import replace
8
+ from pathlib import Path
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import unittest
13
+ import zipfile
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ TASK = ROOT / 'data/cyber/tasks/swe_rl_cybersecurity_task_02'
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument('--patch', type=Path, default=TASK / 'gold.diff')
19
+ args = parser.parse_args()
20
+
21
+
22
+ class ReferenceCacheTests(unittest.TestCase):
23
+ @classmethod
24
+ def setUpClass(cls):
25
+ cls.temp = tempfile.TemporaryDirectory()
26
+ cls.addClassCleanup(cls.temp.cleanup)
27
+ root = Path(cls.temp.name)
28
+ for archive in ['repository', 'hidden_tests']:
29
+ with zipfile.ZipFile(TASK / f'{archive}.zip') as z:
30
+ z.extractall(root)
31
+ subprocess.run(['git', 'apply', str(args.patch.resolve())],
32
+ cwd=root / 'repository', check=True)
33
+ sys.path[:0] = [str(root / 'repository'), str(root / 'hidden_tests')]
34
+ import test_critical_extensions_and_security_edge_cases
35
+ cls.t = test_critical_extensions_and_security_edge_cases
36
+
37
+ def check_policy_change(self, flag):
38
+ t = self.t
39
+ store = t.TrustStore()
40
+ rp, rs = t.generate_key_pair('cache-review-root')
41
+ cp, cs = t.generate_key_pair('cache-review-ca')
42
+ lp, _ = t.generate_key_pair('cache-review-leaf')
43
+ policies = lambda oid: t.CertificatePoliciesExtension([t.CertificatePolicy(oid)])
44
+ root = t._make_ca('r', 'CN=Root', 'CN=Root', rp, rs,
45
+ policies=policies(t.POLICY_CORP), is_root=True)
46
+ store.add_trust_anchor(root)
47
+ mapping = flag == 'initial_policy_mapping_inhibit'
48
+ ca = t._make_ca('c', 'CN=CA', 'CN=Root', cp, rs, rp,
49
+ policies=policies(t.POLICY_CORP if mapping else t.ANY_POLICY),
50
+ mappings=t.PolicyMappingsExtension([
51
+ t.PolicyMapping(t.POLICY_CORP, t.POLICY_PARTNER_A)
52
+ ], critical=True) if mapping else None)
53
+ store.add_intermediate(ca)
54
+ leaf = t._make_leaf('l', 'CN=leaf', 'CN=CA', lp, cs, cp,
55
+ policies=policies(t.POLICY_PARTNER_A if mapping else t.POLICY_CORP))
56
+ config = t.ValidationConfig(current_time='2026-06-01T00:00:00Z',
57
+ enforce_policy_tree=True, initial_explicit_policy=True,
58
+ initial_policy_set={t.POLICY_CORP}, check_revocation=False)
59
+ strict = replace(config, **{flag: True})
60
+ engine = t.PathValidationEngine(store)
61
+ self.assertTrue(engine.validate(leaf, config).is_valid)
62
+ self.assertFalse(t.PathValidationEngine(store).validate(leaf, strict).is_valid)
63
+ self.assertFalse(engine.validate(leaf, strict).is_valid,
64
+ 'A stricter policy must not reuse a permissive cached decision')
65
+ engine = t.PathValidationEngine(store)
66
+ self.assertFalse(engine.validate(leaf, strict).is_valid)
67
+ self.assertTrue(engine.validate(leaf, config).is_valid,
68
+ 'A permissive policy must not reuse a stricter cached decision')
69
+
70
+ def test_mapping_inhibition_is_in_cache_identity(self):
71
+ self.check_policy_change('initial_policy_mapping_inhibit')
72
+
73
+ def test_any_policy_inhibition_is_in_cache_identity(self):
74
+ self.check_policy_change('initial_any_policy_inhibit')
75
+
76
+
77
+ if __name__ == '__main__':
78
+ unittest.main(argv=[sys.argv[0]], verbosity=2)