From bbceaf53a1fc7df2348211eb3a12e7fd6b49c483 Mon Sep 17 00:00:00 2001 From: Ben McIlwain Date: Thu, 3 Dec 2026 14:53:11 -0500 Subject: [PATCH] Add scoped AGENTS.md rules and static guardrails MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Root GEMINI.md is already near per-file agent context limits (~20.2 KB), so adding more subsystem-specific engineering rules there risks silent truncation and hurts signal for unrelated changes. At the same time, several recurring production and review hazards—Jetty vs. GCLB idle timeout races, GKE requests.memory sizing under -XX:MaxRAMPercentage, one-shot ServletInputStream dual-injection drains, JvmMetrics non_heap and committed-heap semantics, and fail-open Cloud Deploy alert policy checks—are much more reliable when enforced in directory-scoped guides, source Javadoc, unit tests, and automated diff checks than in global prose. Specifically, this change: - Adds console-webapp/AGENTS.md covering Angular zoneless OnPush Signal unions, GlobalLoader lifecycle/teardown, RxJS 7 error observers on BackendService calls, registrarId-keyed effect() cancellation, and console/Gradle review calibration without expanding root GEMINI.md. - Adds core/AGENTS.md covering pre-auth CLI validation and FeatureFlag retention, in-transaction ownership and Console EPP attribution, Gson type guards and real ServletInputStream tests, canonical Base64 SHA-256 checks, JPQL timestamp ordering, log-injection sanitization with monthly_logs.sql parity, and Netty retainedDuplicate() retries. - Adds JettyHttpConfigTest asserting jetty.http.idleTimeout exceeds GCLB's 600s backend keep-alive timeout in jetty/src/main/jetty-base/start.d/http.ini. - Documents JvmMetrics type="heap" vs. non_heap (-1 max) and used/max vs. committed semantics in JvmMetrics.java (plus unit test coverage in JvmMetricsTest), and documents unscoped stream providers and the single-read ServletInputStream invariant in RequestModule.java (plus unit tests in RequestModuleTest). - Extends .gemini/skills/pr-polisher/scripts/check_diff.py (and SKILL.md plus new unit tests in check_diff_test.py) to check GKE requests.memory against -XX:MaxRAMPercentage and flag dual ServletInputStream-reading injections in core production actions. - Adds a pre-apply step in release/cloudbuild-clouddeploy.yaml verifying that every Cloud Monitoring alert policy referenced in the rendered delivery-pipeline.yaml exists and is enabled before gcloud deploy apply. BUG=http://b/593117423 Signed-off-by: Ben McIlwain --- .gemini/skills/pr-polisher/SKILL.md | 4 +- .../skills/pr-polisher/scripts/check_diff.py | 322 ++++++++++++++++++ .../pr-polisher/scripts/check_diff_test.py | 205 +++++++++++ console-webapp/AGENTS.md | 39 +++ core/AGENTS.md | 46 +++ .../monitoring/whitebox/JvmMetrics.java | 18 +- .../registry/request/RequestModule.java | 34 ++ .../registry/config/JettyHttpConfigTest.java | 93 +++++ .../monitoring/whitebox/JvmMetricsTest.java | 12 + .../registry/request/RequestModuleTest.java | 34 ++ release/cloudbuild-clouddeploy.yaml | 32 ++ 11 files changed, 836 insertions(+), 3 deletions(-) create mode 100644 .gemini/skills/pr-polisher/scripts/check_diff_test.py create mode 100644 console-webapp/AGENTS.md create mode 100644 core/AGENTS.md create mode 100644 core/src/test/java/google/registry/config/JettyHttpConfigTest.java diff --git a/.gemini/skills/pr-polisher/SKILL.md b/.gemini/skills/pr-polisher/SKILL.md index ab5da5f869b..f76f7923d0a 100644 --- a/.gemini/skills/pr-polisher/SKILL.md +++ b/.gemini/skills/pr-polisher/SKILL.md @@ -22,7 +22,7 @@ This skill is designed to evolve. If a human code reviewer (or presubmit hook) p ## Workflow Execution Steps 1. **Sync, Rebase, and Run the Automated Analysis Script** - First, fetch the latest `upstream/master` (`git fetch upstream master`) and rebase onto it (`git rebase upstream/master`) whenever creating or updating a PR branch—including in-flight code reviews—so the PR merges cleanly onto `master`. Then execute the packaged Python diff-checker script from the repository root. This script automatically checks commit messages, working tree status, `package-lock.json` modifications, copyright years on new files, missing tests across all tested modules, the 2-PR database schema split (Flyway scripts must not ship with Java or `db-schema.sql.generated` changes), Valkey Protostuff-cached entity field edits, state-machine anti-patterns (`TimedTransitionProperty.fromValueMap`, ordinal `Enum.compareTo`, Angular `setTimeout`/`GlobalLoaderService`/multi-boolean state flags), internal-only links or paths leaking into this public repository, whether the branch is rebased onto `upstream/master` and `FETCH_HEAD` freshness, and a litany of anti-patterns using regex (e.g., fully-qualified names, incorrect clock injections, generic exception catching). + First, fetch the latest `upstream/master` (`git fetch upstream master`) and rebase onto it (`git rebase upstream/master`) whenever creating or updating a PR branch—including in-flight code reviews—so the PR merges cleanly onto `master`. Then execute the packaged Python diff-checker script from the repository root. This script automatically checks commit messages, working tree status, `package-lock.json` modifications, copyright years on new files, missing tests across all tested modules, the 2-PR database schema split (Flyway scripts must not ship with Java or `db-schema.sql.generated` changes), Valkey Protostuff-cached entity field edits, GKE `requests.memory` sizing against `-XX:MaxRAMPercentage`, single-read `ServletInputStream` dual-injection hazards, state-machine anti-patterns (`TimedTransitionProperty.fromValueMap`, ordinal `Enum.compareTo`, Angular `setTimeout`/`GlobalLoaderService`/multi-boolean state flags), internal-only links or paths leaking into this public repository, whether the branch is rebased onto `upstream/master` and `FETCH_HEAD` freshness, and a litany of anti-patterns using regex (e.g., fully-qualified names, incorrect clock injections, generic exception catching). ```bash python3 .gemini/skills/pr-polisher/scripts/check_diff.py @@ -90,4 +90,4 @@ This skill is designed to evolve. If a human code reviewer (or presubmit hook) p git add -u git commit --amend # Or git commit --amend --no-edit if only files changed ``` - **CRITICAL:** You must loop back to Step 1 and run `python3 .gemini/skills/pr-polisher/scripts/check_diff.py` again. Continue this loop of checking and amending until the script definitively returns `0 ERRORS`, the build/presubmits pass, and the working directory is perfectly clean. Do not assume your fixes worked without re-running the check. \ No newline at end of file + **CRITICAL:** You must loop back to Step 1 and run `python3 .gemini/skills/pr-polisher/scripts/check_diff.py` again. Continue this loop of checking and amending until the script definitively returns `0 ERRORS`, the build/presubmits pass, and the working directory is perfectly clean. Do not assume your fixes worked without re-running the check. diff --git a/.gemini/skills/pr-polisher/scripts/check_diff.py b/.gemini/skills/pr-polisher/scripts/check_diff.py index d7103fef5bc..01465c567ff 100644 --- a/.gemini/skills/pr-polisher/scripts/check_diff.py +++ b/.gemini/skills/pr-polisher/scripts/check_diff.py @@ -62,6 +62,39 @@ "core/src/main/java/google/registry/persistence/converter/TimedTransitionBaseUserType.java", )) +K8S_MEMORY_UNITS = { + "": 1, + "Ki": 1024, + "Mi": 1024**2, + "Gi": 1024**3, + "Ti": 1024**4, + "Pi": 1024**5, + "Ei": 1024**6, + "k": 1000, + "K": 1000, + "M": 1000**2, + "G": 1000**3, + "T": 1000**4, + "P": 1000**5, + "E": 1000**6, +} +K8S_MEMORY_QUANTITY_PATTERN = re.compile( + r'^"?([0-9]+(?:\.[0-9]+)?)(Ki|Mi|Gi|Ti|Pi|Ei|k|K|M|G|T|P|E)?"?$' +) +MAX_RAM_PERCENTAGE_PATTERN = re.compile(r'-XX:MaxRAMPercentage=([0-9]+(?:\.[0-9]+)?)') +DEFAULT_NOMULUS_MAX_RAM_PERCENTAGE = 50.0 +DEFAULT_JDK_MAX_RAM_PERCENTAGE = 25.0 + +DIRECT_PAYLOAD_ANNOTATION_PATTERN = re.compile(r'@(OptionalJsonPayload|JsonPayload|Payload)\b') +PARAMETER_ANNOTATION_PATTERN = re.compile(r'@Parameter\s*\(\s*"([^"]+)"\s*\)') +PAYLOAD_BINDING_PATTERN = re.compile( + r'@(OptionalJsonPayload|JsonPayload|Payload)\b|@Parameter\s*\(\s*"([^"]+)"\s*\)' +) +PROVIDES_METHOD_PATTERN = re.compile( + r'@Provides\b(.*?)\{', + re.DOTALL, +) + # Internal-only references that must never land in this public repository. # Buganizer references (b/123, http://b/123) are allowed and do not match. INTERNAL_LEAK_PATTERNS = ( @@ -571,6 +604,293 @@ def check_db_schema_split(): else: log_success("No database schema or JPA entity changes found.") +def parse_k8s_memory_bytes(raw_value): + match = K8S_MEMORY_QUANTITY_PATTERN.match(raw_value.strip()) + if not match: + return None + amount = float(match.group(1)) + unit = match.group(2) or "" + return int(amount * K8S_MEMORY_UNITS[unit]) + +def parse_max_ram_percentage(text): + for line in text.splitlines(): + stripped = line.strip() + if stripped.startswith('#'): + continue + match = MAX_RAM_PERCENTAGE_PATTERN.search(stripped) + if match: + return float(match.group(1)) + return None + +def extract_k8s_containers(yaml_text): + containers = [] + for doc in re.split(r'(?m)^---\s*$', yaml_text): + lines = doc.splitlines() + in_containers = False + containers_indent = -1 + current = None + container_indent = -1 + section = None + section_indent = -1 + env_name = None + env_indent = -1 + + for raw_line in lines: + stripped = raw_line.strip() + if not stripped or stripped.startswith('#'): + continue + indent = len(raw_line) - len(raw_line.lstrip(' ')) + + if not in_containers: + if stripped == 'containers:': + in_containers = True + containers_indent = indent + continue + + if indent <= containers_indent and not stripped.startswith('- '): + in_containers = False + current = None + continue + + if stripped.startswith('- name:') and ( + container_indent == -1 or indent <= container_indent + ): + container_indent = indent + current = { + 'name': stripped.split(':', 1)[1].strip().strip('"\''), + 'image': '', + 'requests_memory': None, + 'limits_memory': None, + 'jdk_java_options': '', + } + containers.append(current) + section = None + section_indent = -1 + env_name = None + env_indent = -1 + continue + + if current is None: + continue + + if section is not None and ( + indent < section_indent + or (indent == section_indent and not (section == 'env' and stripped.startswith('- '))) + ): + section = None + section_indent = -1 + if env_name is not None and indent <= env_indent: + env_name = None + env_indent = -1 + + if stripped.startswith('image:') and section is None: + current['image'] = stripped.split(':', 1)[1].strip().strip('"\'') + elif stripped == 'requests:': + section = 'requests' + section_indent = indent + elif stripped == 'limits:': + section = 'limits' + section_indent = indent + elif stripped == 'env:': + section = 'env' + section_indent = indent + elif section == 'requests' and stripped.startswith('memory:'): + current['requests_memory'] = stripped.split(':', 1)[1].strip() + elif section == 'limits' and stripped.startswith('memory:'): + current['limits_memory'] = stripped.split(':', 1)[1].strip() + elif section == 'env' and stripped.startswith('- name:'): + env_name = stripped.split(':', 1)[1].strip().strip('"\'') + env_indent = indent + elif section == 'env' and env_name == 'JDK_JAVA_OPTIONS' and stripped.startswith('value:'): + current['jdk_java_options'] = stripped.split(':', 1)[1].strip().strip('"\'') + + return containers + +def find_gke_memory_issues(yaml_path, yaml_text, default_nomulus_max_ram_pct=DEFAULT_NOMULUS_MAX_RAM_PERCENTAGE): + issues = [] + for container in extract_k8s_containers(yaml_text): + req_raw = container['requests_memory'] + lim_raw = container['limits_memory'] + if not req_raw or not lim_raw: + continue + req_bytes = parse_k8s_memory_bytes(req_raw) + lim_bytes = parse_k8s_memory_bytes(lim_raw) + if req_bytes is None or lim_bytes is None: + continue + + max_ram_pct = parse_max_ram_percentage(container['jdk_java_options']) + if max_ram_pct is None: + image = container['image'] + if re.search(r'/nomulus(?:[:@]|$)', image): + max_ram_pct = default_nomulus_max_ram_pct + elif re.search(r'/proxy(?:[:@]|$)', image): + max_ram_pct = DEFAULT_JDK_MAX_RAM_PERCENTAGE + else: + continue + + max_heap_bytes = lim_bytes * (max_ram_pct / 100.0) + if req_bytes <= max_heap_bytes: + max_heap_mib = max_heap_bytes / (1024 * 1024) + req_mib = req_bytes / (1024 * 1024) + issues.append( + f"[{yaml_path}] Container '{container['name']}' has requests.memory={req_raw.strip('\"')}" + f" ({req_mib:.0f} MiB) <= {max_ram_pct:g}% of limits.memory={lim_raw.strip('\"')}" + f" ({max_heap_mib:.0f} MiB max JVM heap). -XX:MaxRAMPercentage scales off" + " limits.memory, not requests.memory; size requests.memory strictly above max" + " heap plus non-heap footprint to prevent kubelet evictions." + ) + return issues + +def check_gke_memory_requests(diff_files=None, root_dir="."): + print("\n--- Checking GKE Memory Requests vs -XX:MaxRAMPercentage ---") + if diff_files is None: + diff_files = get_diff_files() + + k8s_files = [] + if "jetty/start.sh" in diff_files: + k8s_dir = os.path.join(root_dir, "jetty", "kubernetes") + if os.path.isdir(k8s_dir): + for name in sorted(os.listdir(k8s_dir)): + if name.endswith(".yaml"): + k8s_files.append(f"jetty/kubernetes/{name}") + + for path in diff_files: + if ( + (path.startswith("jetty/kubernetes/") or path.startswith("proxy/kubernetes/")) + and path.endswith(".yaml") + and path not in k8s_files + ): + k8s_files.append(path) + + if not k8s_files: + log_success("No GKE manifest or JVM heap flag changes found.") + return + + default_nomulus_pct = DEFAULT_NOMULUS_MAX_RAM_PERCENTAGE + start_sh_path = os.path.join(root_dir, "jetty", "start.sh") + if os.path.isfile(start_sh_path): + with open(start_sh_path, "r", encoding="utf-8") as f: + parsed_pct = parse_max_ram_percentage(f.read()) + if parsed_pct is not None: + default_nomulus_pct = parsed_pct + + found_any = False + for rel_path in k8s_files: + full_path = os.path.join(root_dir, rel_path) + if not os.path.isfile(full_path): + continue + with open(full_path, "r", encoding="utf-8") as f: + issues = find_gke_memory_issues(rel_path, f.read(), default_nomulus_pct) + for issue in issues: + found_any = True + log_warning(issue) + + if not found_any: + log_success("GKE requests.memory exceeds configured JVM max heap across touched manifests.") + +def strip_java_comments(java_text): + without_block = re.sub(r'/\*.*?\*/', ' ', java_text, flags=re.DOTALL) + return re.sub(r'//[^\n]*', '', without_block) + +def discover_payload_backed_parameters(root_dir="."): + payload_params = set() + src_root = os.path.join(root_dir, "core", "src", "main", "java") + if not os.path.isdir(src_root): + return frozenset() + for dirpath, _, filenames in os.walk(src_root): + for filename in filenames: + if not filename.endswith("Module.java"): + continue + full_path = os.path.join(dirpath, filename) + with open(full_path, "r", encoding="utf-8") as f: + text = strip_java_comments(f.read()) + for match in PROVIDES_METHOD_PATTERN.finditer(text): + header = match.group(1) + if not DIRECT_PAYLOAD_ANNOTATION_PATTERN.search(header): + continue + for param_match in PARAMETER_ANNOTATION_PATTERN.finditer(header): + payload_params.add(param_match.group(1)) + return frozenset(payload_params) + +def extract_inject_segments(cleaned_java): + segments = [] + n = len(cleaned_java) + for match in re.finditer(r'@Inject\b', cleaned_java): + i = match.end() + paren_depth = 0 + saw_param_list = False + while i < n: + ch = cleaned_java[i] + if ch == '"': + i += 1 + while i < n and cleaned_java[i] != '"': + if cleaned_java[i] == '\\': + i += 1 + i += 1 + elif ch == '(': + paren_depth += 1 + # Distinguish annotation args (@Foo(...)) from constructor/method param list. + prefix = cleaned_java[match.end():i].rstrip() + if paren_depth == 1 and not re.search(r'@[A-Za-z0-9_.]+\s*$', prefix): + saw_param_list = True + elif ch == ')': + paren_depth = max(0, paren_depth - 1) + if paren_depth == 0 and saw_param_list: + i += 1 + break + elif paren_depth == 0 and ch in (';', '=', '{'): + break + i += 1 + segments.append(cleaned_java[match.start():i]) + return segments + +def find_servlet_stream_dual_injections(java_text, payload_backed_params): + cleaned = strip_java_comments(java_text) + if re.search(r'@Module\b', cleaned): + return [] + + bindings = [] + for segment in extract_inject_segments(cleaned): + for match in PAYLOAD_BINDING_PATTERN.finditer(segment): + if match.group(1): + bindings.append(f"@{match.group(1)}") + elif match.group(2) in payload_backed_params: + bindings.append(f'@Parameter("{match.group(2)}")') + return bindings if len(bindings) >= 2 else [] + +def check_servlet_input_stream_dual_injection(diff_files=None, root_dir="."): + print("\n--- Checking Single-Read ServletInputStream Invariant ---") + if diff_files is None: + diff_files = get_diff_files() + + java_files = [ + f for f in diff_files if f.startswith("core/src/main/") and f.endswith(".java") + ] + if not java_files: + log_success("No core production Java files changed.") + return + + payload_backed_params = discover_payload_backed_parameters(root_dir) + found_any = False + for rel_path in java_files: + full_path = os.path.join(root_dir, rel_path) + if not os.path.isfile(full_path): + continue + with open(full_path, "r", encoding="utf-8") as f: + bindings = find_servlet_stream_dual_injections(f.read(), payload_backed_params) + if bindings: + found_any = True + log_error( + f"[{rel_path}] Injects multiple ServletInputStream-reading bindings" + f" ({', '.join(bindings)}). RequestModule payload providers are intentionally" + " unscoped and Jetty's ServletInputStream drains on the first read, leaving" + " subsequent reads empty. Inject @OptionalJsonPayload once and deserialize" + " inside the action with Gson." + ) + + if not found_any: + log_success("No dual ServletInputStream injections detected.") + def check_missing_tests(): print("\n--- Checking for Missing Tests ---") diff_files = get_diff_files() @@ -597,6 +917,8 @@ def main(): check_missing_tests() check_db_schema_split() check_protostuff_cached_entities() + check_gke_memory_requests() + check_servlet_input_stream_dual_injection() check_upstream_freshness() check_formatting() check_package_lock() diff --git a/.gemini/skills/pr-polisher/scripts/check_diff_test.py b/.gemini/skills/pr-polisher/scripts/check_diff_test.py new file mode 100644 index 00000000000..342f683e2ce --- /dev/null +++ b/.gemini/skills/pr-polisher/scripts/check_diff_test.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +# Copyright 2026 The Nomulus Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import check_diff + + +class CheckDiffTest(unittest.TestCase): + + def test_parse_k8s_memory_bytes(self): + self.assertEqual(check_diff.parse_k8s_memory_bytes('"2Gi"'), 2 * 1024**3) + self.assertEqual(check_diff.parse_k8s_memory_bytes("1.5Gi"), int(1.5 * 1024**3)) + self.assertEqual(check_diff.parse_k8s_memory_bytes("700Mi"), 700 * 1024**2) + self.assertEqual(check_diff.parse_k8s_memory_bytes("512M"), 512 * 1000**2) + self.assertIsNone(check_diff.parse_k8s_memory_bytes("not-a-size")) + + def test_parse_max_ram_percentage_ignores_comments(self): + script = ( + "# -XX:MaxRAMPercentage=75.0\n" + "JVM_OPTS=(\n" + " -XX:InitialRAMPercentage=50.0\n" + " -XX:MaxRAMPercentage=50.0\n" + ")\n" + ) + self.assertEqual(check_diff.parse_max_ram_percentage(script), 50.0) + + def test_find_gke_memory_issues_flags_requests_at_or_below_max_heap(self): + manifest = """ +apiVersion: apps/v1 +kind: Deployment +spec: + template: + spec: + containers: + - name: backend + image: gcr.io/GCP_PROJECT/nomulus + resources: + requests: + memory: "2Gi" + limits: + memory: "4Gi" + - name: frontend + image: gcr.io/GCP_PROJECT/nomulus + resources: + requests: + memory: "3Gi" + limits: + memory: "4Gi" + - name: proxy + image: gcr.io/GCP_PROJECT/proxy + resources: + requests: + memory: "350Mi" + limits: + memory: "512Mi" +""" + issues = check_diff.find_gke_memory_issues("jetty/kubernetes/test.yaml", manifest, 50.0) + self.assertEqual(len(issues), 1) + self.assertIn("Container 'backend'", issues[0]) + self.assertIn("requests.memory=2Gi", issues[0]) + + def test_find_gke_memory_issues_respects_container_jdk_java_options_override(self): + manifest = """ +apiVersion: apps/v1 +kind: Deployment +spec: + template: + spec: + containers: + - name: custom + image: gcr.io/GCP_PROJECT/nomulus + resources: + requests: + memory: "2.5Gi" + limits: + memory: "4Gi" + env: + - name: JDK_JAVA_OPTIONS + value: "-XX:MaxRAMPercentage=70.0" +""" + issues = check_diff.find_gke_memory_issues("jetty/kubernetes/custom.yaml", manifest, 50.0) + self.assertEqual(len(issues), 1) + self.assertIn("70%", issues[0]) + + def test_find_servlet_stream_dual_injections_flags_optional_json_plus_param(self): + java_source = """ +@Action(service = Service.CONSOLE, path = "/console-api/test") +public class BadAction { + @Inject + BadAction( + @Parameter("registrar") Optional registrar, + @OptionalJsonPayload Optional payload) {} +} +""" + bindings = check_diff.find_servlet_stream_dual_injections( + java_source, frozenset({"registrar", "contact"}) + ) + self.assertEqual(bindings, ['@Parameter("registrar")', "@OptionalJsonPayload"]) + + def test_find_servlet_stream_dual_injections_flags_field_and_ctor_combo(self): + java_source = """ +@Action(service = Service.CONSOLE, path = "/console-api/test") +public class BadFieldAction { + @Inject @Payload byte[] rawBody; + + @Inject + BadFieldAction(@OptionalJsonPayload Optional payload) {} +} +""" + bindings = check_diff.find_servlet_stream_dual_injections( + java_source, frozenset({"registrar"}) + ) + self.assertEqual(bindings, ["@Payload", "@OptionalJsonPayload"]) + + def test_find_servlet_stream_dual_injections_allows_single_binding_and_modules(self): + good_action = """ +@Action(service = Service.CONSOLE, path = "/console-api/test") +public class GoodAction { + // Never inject @Parameter("registrar") alongside @OptionalJsonPayload. + @Inject + GoodAction( + @Parameter("registrarId") String registrarId, + @OptionalJsonPayload Optional payload) {} +} +""" + module_source = """ +@Module +public final class FakeModule { + @Provides + @Parameter("registrar") + static Optional provideRegistrar(@OptionalJsonPayload Optional p) { + return Optional.empty(); + } +} +""" + self.assertEqual( + check_diff.find_servlet_stream_dual_injections( + good_action, frozenset({"registrar", "contact"}) + ), + [], + ) + self.assertEqual( + check_diff.find_servlet_stream_dual_injections( + module_source, frozenset({"registrar", "contact"}) + ), + [], + ) + + def test_discover_payload_backed_parameters_scans_repo_modules(self): + repo_root = os.path.abspath( + os.path.join(os.path.dirname(__file__), "..", "..", "..", "..") + ) + params = check_diff.discover_payload_backed_parameters(repo_root) + self.assertIn("registrar", params) + self.assertIn("contact", params) + self.assertIn("bulkTransferDomainNames", params) + self.assertNotIn("registrarId", params) + + def test_check_gke_memory_requests_checks_manifests_when_start_sh_changes(self): + with tempfile.TemporaryDirectory() as tmpdir: + os.makedirs(os.path.join(tmpdir, "jetty", "kubernetes")) + with open(os.path.join(tmpdir, "jetty", "start.sh"), "w", encoding="utf-8") as f: + f.write("-XX:MaxRAMPercentage=60.0\n") + with open( + os.path.join(tmpdir, "jetty", "kubernetes", "nomulus-test.yaml"), + "w", + encoding="utf-8", + ) as f: + f.write( + "containers:\n" + "- name: test\n" + " image: gcr.io/GCP_PROJECT/nomulus\n" + " resources:\n" + " requests:\n" + " memory: \"2Gi\"\n" + " limits:\n" + " memory: \"4Gi\"\n" + ) + prev_warnings = check_diff.warnings_found + try: + check_diff.check_gke_memory_requests(["jetty/start.sh"], root_dir=tmpdir) + self.assertEqual(check_diff.warnings_found, prev_warnings + 1) + finally: + check_diff.warnings_found = prev_warnings + + +if __name__ == "__main__": + unittest.main() diff --git a/console-webapp/AGENTS.md b/console-webapp/AGENTS.md new file mode 100644 index 00000000000..a97041ae75f --- /dev/null +++ b/console-webapp/AGENTS.md @@ -0,0 +1,39 @@ +# Console Webapp Agent Guidelines + +Scoped Angular/RxJS/Vitest rules for `console-webapp/`. Root `GEMINI.md` still +applies. + +## Angular Signals, RxJS, and `GlobalLoader` + +- **Prefer Signal Unions Over `GlobalLoaderService`:** Under zoneless + `OnPush`, model async/form/modal state with Signal discriminated unions + (`@switch`) and cancel or bound requests with RxJS `timeout()`, + `switchMap`, and `takeUntilDestroyed` instead of adding new + `GlobalLoaderService` usage or `setTimeout()` calls. +- **`GlobalLoader` Lifecycle:** When maintaining existing `GlobalLoader` + components, call `startGlobalLoader(this)` before `.subscribe(...)` so + synchronous `of(...)` mocks do not leak a 10s timer, clear loaders in + `finalize(() => ...)`, and call `stopGlobalLoader(this)` in `ngOnDestroy()` + on short-lived components (`GlobalLoaderService` is `providedIn: 'root'`). +- **RxJS 7 Error Observers on `BackendService`:** Always pass an `error` + observer (e.g., `{ error: () => {} }` or an error snackbar) to + `.subscribe()` on `BackendService` calls without `mockData`; otherwise + RxJS 7+ forwards errors to `reportUnhandledError` (`setTimeout`), failing + Vitest fake-timer tests. Cover error paths with + `vi.advanceTimersByTime(10000)`. +- **Registrar-Scoped `effect()` Keying and Cancellation:** Track + `registrarService.registrarId()` and reset state unconditionally instead of + gating on `registrar()` (`computed`, which re-fires + on list reloads and yields `undefined` when unmatched). Cancel in-flight + requests on registrar switch via `onCleanup(() => sub.unsubscribe())` or + `switchMap` so stale responses cannot act on the wrong registrar. + +## Review Calibration + +- **Shared State:** Verify DOM, tab, or route mutual exclusivity before + flagging shared state (e.g., `isLoading`) across views or tabs. +- **Nested `@if`:** Never flatten nested `@if (!cond) { @if (...) { ... } }` + into `@if (cond) { } @else if (...)` with a dummy empty block. +- **Build & Screenshots:** Avoid over-engineered Gradle checks (`JsonSlurper` + `angular.json` parsing, `Copy`-to-`Sync` rewrites) and do not block on + `ConsoleScreenshotTest` golden updates that CI catches cleanly. diff --git a/core/AGENTS.md b/core/AGENTS.md new file mode 100644 index 00000000000..0598e1da8a9 --- /dev/null +++ b/core/AGENTS.md @@ -0,0 +1,46 @@ +# Core Backend Agent Guidelines + +Scoped Java/CLI/Console rules for `core/`. Root `GEMINI.md` still applies. + +## CLI Tools and `FeatureFlag` + +- **No Pre-Auth DB Queries During Parsing:** Never query Cloud SQL or + `FeatureFlag` inside JCommander converters or validators before the CLI's + access-justified (`-r`) database connection initializes. +- **Deprecated `FeatureFlag` Constants:** Keep deprecated + `FeatureFlag.FeatureName` enum constants until their rows are deleted from + every environment. + +## Transactions, Console Actions, and Validation + +- **In-Tx Ownership and Console EPP:** Load resources and verify registrar + ownership inside the mutating `tm().transact(...)` (never pre-load + outside), using `isSuperuser = false` for missing/deleted resources and + Console `DELETE`. Reject `null` list entries upfront (HTTP `400`), + deduplicate inputs before DB writes and `toImmutableMap`, and pass + `@Config("registryAdminClientId")`—not sponsoring `registrarId`—to + `StatelessRequestSessionMetadata` for superuser Console EPP + (`SUSPEND`/`UNSUSPEND`). +- **Gson Guards and Real Stream Tests:** Check `isJsonObject()`, + `isJsonArray()`, and `isJsonPrimitive() && getAsJsonPrimitive().isString()` + before `gson.fromJson` (Gson coerces numbers like `1.2e3` into strings), + and catch `JsonSyntaxException` to return HTTP `400`. Wire real request + reads in console action tests via + `ConsoleActionBaseTestCase.createServletInputStream(...)` and + `RequestModule`. +- **Canonical Base64 SHA-256:** Guava `BaseEncoding.base64().omitPadding()` + accepts non-zero trailing bits; verify `decoded.length == 32` and + `base64().omitPadding().encode(decoded).equals(input)`. + +## JPQL, Logging, and Netty Retries + +- **JPQL Timestamp Ordering:** Do not append a trailing `domainName ASC` + tie-breaker when ordering JPQL queries by `creationTime`, `deletionTime`, + or `modificationTime` (nor request one in reviews or tests). +- **Log Injection and `monthly_logs.sql`:** Sanitize `\r`/`\n` to `_` on + untrusted HTTP paths before logging, and update + `reporting/icann/sql/monthly_logs.sql` (and `monthly_logs_test.sql`) in + lockstep when demoting request logs it filters on. +- **Netty Retry Buffers:** Call `ByteBufHolder.retainedDuplicate()` (never + `retain()`) before retryable outbound Netty writes so retries do not share + a mutated `readerIndex`. diff --git a/core/src/main/java/google/registry/monitoring/whitebox/JvmMetrics.java b/core/src/main/java/google/registry/monitoring/whitebox/JvmMetrics.java index 750683986be..7d0a32a94f7 100644 --- a/core/src/main/java/google/registry/monitoring/whitebox/JvmMetrics.java +++ b/core/src/main/java/google/registry/monitoring/whitebox/JvmMetrics.java @@ -27,7 +27,23 @@ import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; -/** Exposes JVM metrics. */ +/** + * Exposes JVM memory gauges ({@code /jvm/memory/used}, {@code /jvm/memory/committed}, and {@code + * /jvm/memory/max}) labeled by {@code type} ({@code "heap"} or {@code "non_heap"}). + * + *

Notes for callers and alerting queries (emitted on the {@code gke_container} monitored + * resource): + * + *

    + *
  • Always filter by {@code type="heap"} when computing heap utilization. Unfiltered queries + * mix in {@code type="non_heap"}, whose {@code /jvm/memory/max} reports {@code -1} whenever + * {@code -XX:MaxMetaspaceSize} is unset (see {@link MemoryUsage#getMax()}). + *
  • Divide {@code used} by {@code max} (guarding {@code max > 0}), not by {@code committed}. + * Under {@code -XX:InitialRAMPercentage} without a fixed {@code -Xms}/{@code -XX:MinHeapSize} + * floor, the JVM garbage collector returns unused committed heap to the OS, so {@code + * committed} can shrink well below {@code max} on low-load services. + *
+ */ @Singleton class JvmMetrics { diff --git a/core/src/main/java/google/registry/request/RequestModule.java b/core/src/main/java/google/registry/request/RequestModule.java index b569941bd93..53cf809480f 100644 --- a/core/src/main/java/google/registry/request/RequestModule.java +++ b/core/src/main/java/google/registry/request/RequestModule.java @@ -168,6 +168,16 @@ static MediaType provideContentType(HttpServletRequest req) { } } + /** + * Decodes the raw HTTP request payload bytes as a string using the request character encoding (or + * UTF-8 if unspecified). + * + *

Intentionally unscoped (do not add {@link RequestScope} or {@link jakarta.inject.Singleton}) + * because {@code RequestModule} is also installed in {@code @Singleton} test components such as + * {@code DnsTestComponent}. Because {@link #providePayloadAsBytes} consumes the underlying + * one-shot {@link jakarta.servlet.ServletInputStream}, each action must inject at most one + * payload-reading binding. + */ @Provides @Payload public static String providePayloadAsString( @@ -182,6 +192,21 @@ public static String providePayloadAsString( return new String(payloadBytes, charset); } + /** + * Reads the HTTP request body from {@link HttpServletRequest#getInputStream()} up to {@link + * #MAX_PAYLOAD_BYTES}. + * + *

Intentionally unscoped (do not add {@link RequestScope} or {@link jakarta.inject.Singleton}) + * because {@code RequestModule} is also installed in {@code @Singleton} test components such as + * {@code DnsTestComponent}. + * + *

Single-read invariant: Jetty's {@link jakarta.servlet.ServletInputStream} is one-shot + * and drains on the first read, returning empty bytes on subsequent reads. Never inject more than + * one binding that depends on {@link Payload} or {@link OptionalJsonPayload} (for example, both + * {@code @OptionalJsonPayload Optional} and a {@link Parameter} provider backed by + * {@code @OptionalJsonPayload}) in the same action; inject {@code @OptionalJsonPayload} once and + * deserialize inside the action via {@link Gson}. + */ @Provides @Payload public static byte[] providePayloadAsBytes(HttpServletRequest req) { @@ -266,6 +291,15 @@ static int provideCloudTasksRetryCount(HttpServletRequest req) { return Integer.parseInt(extractRequiredHeader(req, CLOUD_TASKS_RETRY_HEADER)); } + /** + * Parses the HTTP request body as an optional {@link JsonElement}. + * + *

Intentionally unscoped (see {@link #providePayloadAsBytes}) because {@code RequestModule} is + * also installed in {@code @Singleton} test components such as {@code DnsTestComponent}. Do not + * inject both {@code @OptionalJsonPayload} and a {@link Parameter} entity derived from + * {@code @OptionalJsonPayload} in the same action; the first read drains {@link + * jakarta.servlet.ServletInputStream} and leaves the second binding {@link Optional#empty()}. + */ @Provides @OptionalJsonPayload public static Optional provideJsonBody(@Payload String payloadString, Gson gson) { diff --git a/core/src/test/java/google/registry/config/JettyHttpConfigTest.java b/core/src/test/java/google/registry/config/JettyHttpConfigTest.java new file mode 100644 index 00000000000..c654f042e5a --- /dev/null +++ b/core/src/test/java/google/registry/config/JettyHttpConfigTest.java @@ -0,0 +1,93 @@ +// Copyright 2026 The Nomulus Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package google.registry.config; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; +import static google.registry.util.BuildPathUtils.getProjectRoot; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.google.common.primitives.Longs; +import java.io.IOException; +import java.io.StringReader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Properties; +import org.junit.jupiter.api.Test; + +/** Unit tests guarding critical Jetty HTTP connector settings. */ +class JettyHttpConfigTest { + + private static final Path JETTY_HTTP_INI = + getProjectRoot().resolve("jetty/src/main/jetty-base/start.d/http.ini"); + + /** + * Google Cloud Load Balancing enforces a fixed 600s backend keep-alive timeout. Jetty's idle + * timeout must stay strictly above 600s so GCLB closes idle connections first instead of racing + * with Jetty and returning HTTP 503 connection-termination errors. + */ + private static final long GCLB_KEEPALIVE_TIMEOUT_MILLIS = 600_000L; + + @Test + void testJettyHttpIdleTimeoutExceedsGclbKeepAliveTimeout() throws IOException { + String content = Files.readString(JETTY_HTTP_INI, UTF_8); + long idleTimeoutMillis = parseIdleTimeoutMillis(content); + assertWithMessage( + "jetty.http.idleTimeout in %s must exceed GCLB's %s ms backend keep-alive timeout", + JETTY_HTTP_INI, GCLB_KEEPALIVE_TIMEOUT_MILLIS) + .that(idleTimeoutMillis) + .isGreaterThan(GCLB_KEEPALIVE_TIMEOUT_MILLIS); + } + + @Test + void testParseIdleTimeoutMillis_valid() throws IOException { + assertThat(parseIdleTimeoutMillis("# comment\njetty.http.idleTimeout=620000\n")) + .isEqualTo(620_000L); + } + + @Test + void testParseIdleTimeoutMillis_commentedOutThrows() { + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> parseIdleTimeoutMillis("# jetty.http.idleTimeout=620000\n")); + assertThat(thrown).hasMessageThat().contains("jetty.http.idleTimeout"); + } + + @Test + void testParseIdleTimeoutMillis_nonNumericThrows() { + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> parseIdleTimeoutMillis("jetty.http.idleTimeout=not-a-number\n")); + assertThat(thrown).hasMessageThat().contains("not-a-number"); + } + + private static long parseIdleTimeoutMillis(String iniContent) throws IOException { + Properties properties = new Properties(); + properties.load(new StringReader(iniContent)); + String rawValue = properties.getProperty("jetty.http.idleTimeout"); + if (rawValue == null) { + throw new IllegalStateException("jetty.http.idleTimeout must be explicitly configured"); + } + Long parsed = Longs.tryParse(rawValue.trim()); + if (parsed == null) { + throw new IllegalStateException( + "jetty.http.idleTimeout must be a valid integer: " + rawValue); + } + return parsed; + } +} diff --git a/core/src/test/java/google/registry/monitoring/whitebox/JvmMetricsTest.java b/core/src/test/java/google/registry/monitoring/whitebox/JvmMetricsTest.java index a84fccedf08..234c06c569a 100644 --- a/core/src/test/java/google/registry/monitoring/whitebox/JvmMetricsTest.java +++ b/core/src/test/java/google/registry/monitoring/whitebox/JvmMetricsTest.java @@ -94,4 +94,16 @@ public void testGetMaxMemory() { ImmutableList.of("heap"), 1000L, ImmutableList.of("non_heap"), 500L); } + + @Test + public void testGetMaxMemory_undefinedNonHeapMaxReportedAsNegativeOne() { + when(mockMemoryMXBean.getNonHeapMemoryUsage()) + .thenReturn(new MemoryUsage(/* init= */ 50, /* used= */ 100, /* committed= */ 250, -1)); + jvmMetrics.register(); + + assertThat(jvmMetrics.getMaxMemory()) + .containsExactly( + ImmutableList.of("heap"), 1000L, + ImmutableList.of("non_heap"), -1L); + } } diff --git a/core/src/test/java/google/registry/request/RequestModuleTest.java b/core/src/test/java/google/registry/request/RequestModuleTest.java index a4863301fa7..10f76ee9997 100644 --- a/core/src/test/java/google/registry/request/RequestModuleTest.java +++ b/core/src/test/java/google/registry/request/RequestModuleTest.java @@ -27,11 +27,16 @@ import com.google.common.net.MediaType; import com.google.gson.Gson; +import com.google.gson.JsonElement; import google.registry.request.HttpException.BadRequestException; import google.registry.request.HttpException.PayloadTooLargeException; import google.registry.request.HttpException.UnsupportedMediaTypeException; import google.registry.tools.GsonUtils; +import jakarta.inject.Singleton; +import jakarta.servlet.ServletInputStream; import jakarta.servlet.http.HttpServletRequest; +import java.lang.reflect.Method; +import java.util.Optional; import org.junit.jupiter.api.Test; /** Unit tests for {@link RequestModule}. */ @@ -123,4 +128,33 @@ void testProvideJsonBody_contentLengthExceedsLimit_throws413() { () -> provideJsonBody(providePayloadAsString(providePayloadAsBytes(req), req), GSON)); assertThat(thrown).hasMessageThat().contains("exceeds limit"); } + + @Test + void testPayloadProvidersAreUnscoped() throws Exception { + for (Method method : RequestModule.class.getDeclaredMethods()) { + if (method.getName().equals("providePayloadAsBytes") + || method.getName().equals("providePayloadAsString") + || method.getName().equals("providePayloadAsByteString") + || method.getName().equals("provideJsonBody")) { + assertThat(method.isAnnotationPresent(RequestScope.class)).isFalse(); + assertThat(method.isAnnotationPresent(Singleton.class)).isFalse(); + } + } + } + + @Test + void testProvidePayloadAsBytes_secondReadDrainsServletInputStream() throws Exception { + HttpServletRequest req = mock(HttpServletRequest.class); + ServletInputStream stream = createServletInputStream("{\"k\":\"v\"}".getBytes(UTF_8)); + when(req.getContentLengthLong()).thenReturn(-1L); + when(req.getInputStream()).thenReturn(stream); + + Optional first = + provideJsonBody(providePayloadAsString(providePayloadAsBytes(req), req), GSON); + Optional second = + provideJsonBody(providePayloadAsString(providePayloadAsBytes(req), req), GSON); + + assertThat(first).isPresent(); + assertThat(second).isEmpty(); + } } diff --git a/release/cloudbuild-clouddeploy.yaml b/release/cloudbuild-clouddeploy.yaml index 7c18de683a1..67f669d78db 100644 --- a/release/cloudbuild-clouddeploy.yaml +++ b/release/cloudbuild-clouddeploy.yaml @@ -93,6 +93,38 @@ steps: fi done +# Verify every referenced Cloud Monitoring alert policy exists and is enabled. +# Cloud Deploy's canary analyzer queries ListAlerts without GetAlertPolicy, so +# deleted, recreated, or disabled policy IDs fail open silently. +- name: 'gcr.io/cloud-builders/gcloud' + entrypoint: /bin/bash + args: + - -c + - | + set -e + policies=$( + grep -v '^[[:space:]]*#' release/clouddeploy/delivery-pipeline.yaml \ + | grep -oE 'projects/[^]"'\''[:space:],]+/alertPolicies/[0-9]+' \ + | sort -u || true + ) + if [ -n "$policies" ]; then + failed=0 + for policy in $policies; do + if ! enabled=$(gcloud monitoring policies describe "$policy" --format='value(enabled)'); then + echo "ERROR: Cloud Monitoring alert policy not found or inaccessible: $policy" >&2 + failed=1 + elif [ "$(printf '%s' "$enabled" | tr '[:upper:]' '[:lower:]')" != "true" ]; then + echo "ERROR: Cloud Monitoring alert policy is not enabled (enabled=${enabled:-}): $policy" >&2 + failed=1 + fi + done + if [ "$failed" -ne 0 ]; then + echo "Aborting Cloud Deploy apply: fix missing or disabled alert policies first." >&2 + exit 1 + fi + echo "Verified $(printf '%s\n' "$policies" | wc -l) Cloud Monitoring alert policies exist and are enabled." + fi + # Apply Cloud Deploy configuration - name: 'gcr.io/cloud-builders/gcloud' entrypoint: /bin/bash