diff --git a/dev-tools/validation/check_dev_demo_summary.py b/dev-tools/validation/check_dev_demo_summary.py index b35529618e..d2e63f3131 100644 --- a/dev-tools/validation/check_dev_demo_summary.py +++ b/dev-tools/validation/check_dev_demo_summary.py @@ -17,19 +17,56 @@ import yaml WORKFLOW_RELATIVE_PATH = Path(".github/workflows/dev-demo.yml") +SUMMARY_HELPER_PATH = "./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh" +SUMMARY_HELPER_NAME = "write-dev-demo-summary.sh" ALLOWED_WORKSPACE_ROOT_VARIABLES = frozenset( {"FIREMUD_REPO_ROOT", "GITHUB_WORKSPACE", "ROOT_DIR"} ) -SUMMARY_HELPER_PATTERN = re.compile( - r"(?(?:" - r"dev-tools/[A-Za-z0-9_./-]+[.]sh|" - r"[.]/dev-tools/[A-Za-z0-9_./-]+[.]sh|" - r"/[^\s;&|\"']+/dev-tools/[A-Za-z0-9_./-]+[.]sh|" - r"(?P\$(?:\{[A-Za-z_][A-Za-z0-9_]*\}|[A-Za-z_][A-Za-z0-9_]*))" - r"/dev-tools/[A-Za-z0-9_./-]+[.]sh" - r"))(?![A-Za-z0-9_./-])" +# The workflow deliberately has one supported summary language. Keep this +# parser narrower than shell itself: a direct, line-continued invocation of +# the canonical helper, followed by the exact plan outputs, is the only +# supported helper form. Unknown shell syntax is rejected rather than being +# silently omitted from the sensitive-output scan. +SUMMARY_HELPER_COMMAND_PATTERN = re.compile( + r"^(?:" + r"(?:target|success|destroyed) " + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]head_sha \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]image_tag \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]hostname \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]telnet_port \}\}"' + r"|" + r"unavailable " + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]head_sha \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]image_tag \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]hostname \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]telnet_port \}\}" ' + r'"cluster-access"' + r"|" + r"failure " + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]head_sha \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]image_tag \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]hostname \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]telnet_port \}\}" ' + r'"\$\{DEV_DEMO_STAGE:-unknown\}"' + r') >> "\$GITHUB_STEP_SUMMARY"$' +) + +SUMMARY_METADATA_LINES = ( + "{", + 'echo ""', + 'echo "- Demo login username: ${DEMO_SMOKE_USERNAME}"', + 'echo "- Demo login email: ${DEMO_SMOKE_EMAIL}"', + 'echo "- Demo login password: repository smoke default (not printed)"', + '} >> "$GITHUB_STEP_SUMMARY"', +) + +REPO_SHELL_HELPER_REFERENCE = re.compile( + r"(?(?:(?:\./)?|\$(?:\{[A-Za-z_][A-Za-z0-9_]*\}|[A-Za-z_][A-Za-z0-9_]*)/|/[^\s\"']+/)" + r"dev-tools/[A-Za-z0-9_./-]+[.]sh)" + r"(?![A-Za-z0-9_./-])" ) FORBIDDEN_SUMMARY_REFERENCE = re.compile( @@ -44,21 +81,8 @@ re.IGNORECASE, ) -SUMMARY_TARGET = re.compile( - r"(?P>{1,2}|tee(?:[ \t]+(?:-a|--append))?)[ \t]*" - r"['\"]?\$\{?GITHUB_STEP_SUMMARY\}?['\"]?" -) -HEREDOC_OPEN = re.compile( - r"<<(?P-)?[ \t]*(?P['\"]?)" - r"(?P[A-Za-z_][A-Za-z0-9_]*)" - r"(?P=quote)" -) SHELL_IF_START = re.compile(r"^if\b.*;[ \t]*then$") -PLAYER_BOOTSTRAP_REQUEST_CALL = re.compile( - r"public_account_url\s*\(\s*(?P['\"])/auth/player-bootstrap" - r"(?P=quote)\s*\)", - re.DOTALL, -) +BOOTSTRAP_PYTHON_HEREDOC_OPENER = 'cat >"${BOOTSTRAP_SCRIPT}" <<\'PY\'' BOOTSTRAP_SECRET_COMMAND_PREFIX = ( "kubectl", "-n", @@ -144,8 +168,6 @@ class WorkflowRunSource: job_name: str step_name: str source: str - summary_reachable: bool = False - resolved_helper_path: Path | None = None def normalize_script(script: str) -> str: @@ -158,61 +180,6 @@ def normalize_nonempty_lines(script: str) -> str: ) -def shell_group_tokens(line: str) -> list[str]: - """Return shell grouping tokens while ignoring quoted/comment text.""" - - tokens: list[str] = [] - quote: str | None = None - escaped = False - word_started = False - index = 0 - while index < len(line): - character = line[index] - if escaped: - escaped = False - word_started = True - index += 1 - continue - if character == "\\" and quote != "'": - escaped = True - word_started = True - index += 1 - continue - if quote is not None: - if character == quote: - quote = None - index += 1 - continue - if character in "'\"": - quote = character - word_started = True - index += 1 - continue - if character == "$" and index + 1 < len(line) and line[index + 1] in "{(": - opener = line[index + 1] - closer = "}" if opener == "{" else ")" - depth = 1 - word_started = True - index += 2 - while index < len(line) and depth: - if line[index] == opener: - depth += 1 - elif line[index] == closer: - depth -= 1 - index += 1 - continue - if character == "#" and not word_started: - break - if character in "{}()": - tokens.append(character) - if character.isspace() or character in ";|&<>()": - word_started = False - else: - word_started = True - index += 1 - return tokens - - def _assert_supported_shell_if(line: str) -> None: if re.match(r"^if(?:\s|$)", line) and not SHELL_IF_START.fullmatch(line): raise AssertionError( @@ -236,87 +203,44 @@ def closing_fi_index(lines: list[str], if_index: int) -> int | None: return None -def _grouped_command_start( - lines: list[str], index: int, target_match: re.Match[str] -) -> int | None: - attached_tokens = shell_group_tokens(lines[index][: target_match.start()]) - if not attached_tokens or attached_tokens[-1] not in "})": - return None - depth = 0 - saw_closing_group = False - for candidate in range(index, -1, -1): - candidate_text = ( - lines[candidate][: target_match.start()] - if candidate == index - else lines[candidate] - ) - for token in reversed(shell_group_tokens(candidate_text)): - if token in "})": - depth += 1 - saw_closing_group = True - elif saw_closing_group and token in "{(": - depth -= 1 - if depth == 0: - return candidate - return None - - -def _summary_heredoc( - lines: list[str], start: int, index: int -) -> re.Match[str] | None: - for opener_index in range(start, index + 1): - if opener_index < index and any( - not lines[candidate].rstrip().endswith("\\") - for candidate in range(opener_index, index) - ): - continue - opener_line = lines[opener_index] - match = HEREDOC_OPEN.search(opener_line) - if match is None: - continue - suffix = opener_line[match.end() :] - if re.search(r"[;&|]", suffix) and not re.fullmatch( - r"\s*\|\s*tee(?:\s+(?:-a|--append))?\s+" - r"['\"]?\$\{?GITHUB_STEP_SUMMARY\}?['\"]?\s*", - suffix, - ): - continue - return match - return None - - def _summary_write_line_ranges(source: str) -> list[tuple[int, int]]: + """Find only the canonical direct helper and metadata summary regions.""" + lines = source.splitlines() ranges: list[tuple[int, int]] = [] - for index, line in enumerate(lines): - target_match = SUMMARY_TARGET.search(line) - if target_match is None: - continue - start = _grouped_command_start(lines, index, target_match) - if start is None: - start = index - while start > 0 and lines[start - 1].rstrip().endswith("\\"): - start -= 1 - end = index - heredoc_match = _summary_heredoc(lines, start, index) - if heredoc_match is not None: - delimiter = heredoc_match.group("delimiter") - strip_tabs = heredoc_match.group("strip_tabs") is not None - for candidate in range(index + 1, len(lines)): - candidate_line = lines[candidate] - if strip_tabs: - candidate_line = candidate_line.lstrip("\t") - if candidate_line == delimiter: - end = candidate + index = 0 + while index < len(lines): + if lines[index].strip() == f"bash {SUMMARY_HELPER_PATH} \\": + end = index + command_lines = [lines[index].strip()] + while command_lines[-1].endswith("\\"): + end += 1 + if end >= len(lines): break - else: - end = len(lines) - 1 - ranges.append((start, end)) + command_lines.append(lines[end].strip()) + if end < len(lines): + command = " ".join( + line.removesuffix("\\").rstrip() for line in command_lines + ) + if SUMMARY_HELPER_COMMAND_PATTERN.fullmatch( + command.removeprefix(f"bash {SUMMARY_HELPER_PATH} ") + ): + ranges.append((index, end)) + index = end + if index + len(SUMMARY_METADATA_LINES) <= len(lines): + candidate = tuple( + line.strip() + for line in lines[index : index + len(SUMMARY_METADATA_LINES)] + ) + if candidate == SUMMARY_METADATA_LINES: + ranges.append((index, index + len(SUMMARY_METADATA_LINES) - 1)) + index += len(SUMMARY_METADATA_LINES) - 1 + index += 1 return ranges def summary_write_regions(source: str) -> list[str]: - """Return shell regions that write to GITHUB_STEP_SUMMARY.""" + """Return supported regions that write to GITHUB_STEP_SUMMARY.""" lines = source.splitlines() return [ @@ -325,38 +249,30 @@ def summary_write_regions(source: str) -> list[str]: ] -def has_forbidden_summary_reference(text: str) -> bool: - normalized_text = re.sub(r"[ \t]+", " ", text) - return FORBIDDEN_SUMMARY_REFERENCE.search(normalized_text) is not None - - -def _variable_name(variable: str) -> str: - return variable[2:-1] if variable.startswith("${") else variable[1:] +def _repo_shell_helper_references(source: str) -> list[tuple[int, str]]: + """Find explicit repository shell-helper paths and their source lines.""" + return [ + (source.count("\n", 0, match.start()), match.group("path")) + for match in REPO_SHELL_HELPER_REFERENCE.finditer(source) + ] -def normalize_summary_helper_path(invocation: str, root_dir: Path) -> Path: - """Resolve a helper path, rejecting unknown variable-rooted forms.""" - root_dir = root_dir.resolve() - if invocation.startswith("$"): - variable, separator, suffix = invocation.partition("/dev-tools/") - if ( - not separator - or _variable_name(variable) not in ALLOWED_WORKSPACE_ROOT_VARIABLES - ): - allowed = ", ".join(sorted(ALLOWED_WORKSPACE_ROOT_VARIABLES)) - raise ValueError( - f"unsupported variable-prefixed summary helper path: {invocation}; " - f"allowed workspace variables: {allowed}" - ) +def _repo_shell_helper_path(reference: str, root_dir: Path) -> Path: + if reference.startswith("$"): + variable, separator, suffix = reference.partition("/dev-tools/") + variable = variable[2:-1] if variable.startswith("${") else variable[1:] + if not separator or variable not in ALLOWED_WORKSPACE_ROOT_VARIABLES: + raise AssertionError(f"unsupported repository shell helper root: {reference}") return (root_dir / "dev-tools" / suffix).resolve() - if invocation.startswith("/"): - return Path(invocation).resolve() - return (root_dir / invocation.removeprefix("./")).resolve() + if reference.startswith("/"): + return Path(reference).resolve() + return (root_dir / reference.removeprefix("./")).resolve() -def _helper_matches(source: str) -> Iterable[re.Match[str]]: - return SUMMARY_HELPER_PATTERN.finditer(source) +def has_forbidden_summary_reference(text: str) -> bool: + normalized_text = re.sub(r"[ \t]+", " ", text) + return FORBIDDEN_SUMMARY_REFERENCE.search(normalized_text) is not None def collect_workflow_run_sources(workflow: dict) -> list[WorkflowRunSource]: @@ -392,71 +308,122 @@ def collect_workflow_run_sources(workflow: dict) -> list[WorkflowRunSource]: def discover_summary_writers( workflow_run_sources: Iterable[WorkflowRunSource], root_dir: Path ) -> list[WorkflowRunSource]: - """Find direct and transitively redirected summary-producing sources.""" + """Find summary writers and reject unsupported shell/source forms.""" root_dir = root_dir.resolve() summary_writers: list[WorkflowRunSource] = [] - pending = list(workflow_run_sources) - seen_sources: dict[tuple[str, str, str], bool] = {} - seen_helpers: dict[tuple[str, Path], bool] = {} - summary_writer_indexes: dict[tuple[str, str, str] | tuple[str, Path], int] = {} - while pending: - current = pending.pop() - if current.resolved_helper_path is None: - traversal_key: tuple[str, str, str] | tuple[str, Path] = ( - current.job_name, - current.step_name, - current.source, - ) - previous_reachability = seen_sources.get(traversal_key) - else: - traversal_key = (current.job_name, current.resolved_helper_path) - previous_reachability = seen_helpers.get(traversal_key) - if previous_reachability is True or ( - previous_reachability is False and not current.summary_reachable - ): - continue - if current.resolved_helper_path is None: - seen_sources[traversal_key] = current.summary_reachable - else: - seen_helpers[traversal_key] = current.summary_reachable + pending_helpers: list[Path] = [] + seen_helpers: set[Path] = set() + for current in workflow_run_sources: direct_ranges = _summary_write_line_ranges(current.source) - if direct_ranges or current.summary_reachable: - existing_index = summary_writer_indexes.get(traversal_key) - if existing_index is None: - summary_writer_indexes[traversal_key] = len(summary_writers) + if any( + marker in current.source + for marker in ("GITHUB_STEP_SUMMARY", SUMMARY_HELPER_NAME) + ): + summary_lines = { + line_index + for line_index, line in enumerate(current.source.splitlines()) + if "GITHUB_STEP_SUMMARY" in line + } + expected_summary_lines = {end for _, end in direct_ranges} + if summary_lines != expected_summary_lines: + raise AssertionError( + "dev-demo summary must use only the canonical direct helper or " + "the exact safe metadata block; unsupported or indirect summary " + f"syntax found in {current.job_name}/{current.step_name}" + ) + helper_lines = { + line_index + for line_index, line in enumerate(current.source.splitlines()) + if SUMMARY_HELPER_NAME in line + } + expected_helper_lines = { + start + for start, _ in direct_ranges + if current.source.splitlines()[start].strip().startswith("bash ") + } + if helper_lines != expected_helper_lines: + raise AssertionError( + "dev-demo summary helper must use the canonical direct invocation; " + f"unsupported or indirect helper syntax found in {current.job_name}/{current.step_name}" + ) + if direct_ranges: summary_writers.append(current) - else: - summary_writers[existing_index] = current - for match in _helper_matches(current.source): - helper_path = normalize_summary_helper_path( - match.group("invocation"), root_dir + direct_helper_starts = { + start + for start, _ in direct_ranges + if current.source.splitlines()[start].strip().startswith("bash ") + } + for line_index, helper_reference in _repo_shell_helper_references( + current.source + ): + helper_path = _repo_shell_helper_path(helper_reference, root_dir) + canonical_path = (root_dir / SUMMARY_HELPER_PATH.removeprefix("./")).resolve() + if helper_path == canonical_path: + if line_index not in direct_helper_starts: + raise AssertionError( + "dev-demo summary helper must use the canonical direct invocation; " + f"unsupported or indirect helper syntax found in {current.job_name}/{current.step_name}" + ) + continue + pending_helpers.append(helper_path) + + while pending_helpers: + helper_path = pending_helpers.pop() + if helper_path in seen_helpers: + continue + seen_helpers.add(helper_path) + try: + helper_path.relative_to(root_dir) + except ValueError as exc: + raise AssertionError( + "repository shell helper path escapes the repository: " + f"{helper_path}" + ) from exc + if not helper_path.is_file(): + raise AssertionError(f"repository shell helper is missing: {helper_path}") + try: + helper_source = helper_path.read_text(encoding="utf-8") + except OSError as exc: + raise AssertionError( + f"repository shell helper cannot be read: {helper_path}" + ) from exc + if "GITHUB_STEP_SUMMARY" in helper_source: + raise AssertionError( + "repository shell helper must not write to GITHUB_STEP_SUMMARY: " + f"{helper_path}" ) - try: - relative_helper = helper_path.relative_to(root_dir) - except ValueError as exc: - raise ValueError( - f"summary helper path escapes repository root: {match.group('invocation')}" - ) from exc - if not helper_path.is_file(): + for _, helper_reference in _repo_shell_helper_references(helper_source): + nested_path = _repo_shell_helper_path(helper_reference, root_dir) + if nested_path == ( + root_dir / SUMMARY_HELPER_PATH.removeprefix("./") + ).resolve(): raise AssertionError( - "summary helper file is missing: " - f"{helper_path} (referenced as {match.group('invocation')})" + "repository shell helper must not invoke the canonical dev-demo " + f"summary helper: {helper_path}" ) - line_index = current.source.count("\n", 0, match.start()) - redirected = current.summary_reachable or any( - start <= line_index <= end for start, end in direct_ranges + pending_helpers.append(nested_path) + + if any( + _summary_write_line_ranges(source.source) + for source in summary_writers + ): + helper_path = root_dir / SUMMARY_HELPER_PATH.removeprefix("./") + if not helper_path.is_file(): + raise AssertionError( + "canonical dev-demo summary helper is missing: " f"{helper_path}" ) + try: helper_source = helper_path.read_text(encoding="utf-8") - pending.append( - WorkflowRunSource( - current.job_name, - f"{current.step_name}:{relative_helper.as_posix()}", - helper_source, - summary_reachable=redirected, - resolved_helper_path=helper_path, - ) + except OSError as exc: + raise AssertionError( + "canonical dev-demo summary helper cannot be read: " f"{helper_path}" + ) from exc + if has_forbidden_summary_reference(helper_source): + raise AssertionError( + "canonical dev-demo summary helper must not reference " + "bootstrap credential material" ) return summary_writers @@ -682,79 +649,58 @@ def _validate_bootstrap_pod_spec(bootstrap_manifest: str) -> None: ) -def _player_bootstrap_payload_end(source: str, start: int) -> int | None: - """Return the end of the first balanced mapping after a request call.""" - - if start >= len(source) or source[start] != "{": - return None - - depth = 0 - quote: str | None = None - triple_quoted = False - escaped = False - index = start - while index < len(source): - character = source[index] - if quote is not None: - if escaped: - escaped = False - elif character == "\\": - escaped = True - elif triple_quoted: - if source.startswith(quote * 3, index): - quote = None - triple_quoted = False - index += 2 - elif character == quote: - quote = None - index += 1 - continue - if character in "'\"": - if source.startswith(character * 3, index): - quote = character - triple_quoted = True - index += 3 - else: - quote = character - index += 1 - continue - if character == "#": - newline = source.find("\n", index) - index = len(source) if newline == -1 else newline + 1 - continue - if character == "{": - depth += 1 - elif character == "}": - depth -= 1 - if depth == 0: - return index + 1 - index += 1 - return None +def _bootstrap_python_source(bootstrap_manifest: str) -> str: + """Extract the Python heredoc so shell comments and strings cannot be calls.""" + + lines = bootstrap_manifest.splitlines() + opener_indices = [ + index + for index, line in enumerate(lines) + if line.strip() == BOOTSTRAP_PYTHON_HEREDOC_OPENER + ] + if len(opener_indices) != 1: + raise AssertionError( + "dev-demo bootstrap must contain exactly one Python script heredoc" + ) + start = opener_indices[0] + 1 + try: + end = next(index for index in range(start, len(lines)) if lines[index] == "PY") + except StopIteration as exc: + raise AssertionError( + "dev-demo bootstrap Python script heredoc is unterminated" + ) from exc + return "\n".join(lines[start:end]) -def _player_bootstrap_payload(source: str, request: re.Match[str]) -> ast.Dict | None: - """Parse the mapping passed to one /auth/player-bootstrap request.""" - - payload_start = request.end() - while payload_start < len(source) and source[payload_start].isspace(): - payload_start += 1 - if payload_start >= len(source) or source[payload_start] != ",": - return None - payload_start += 1 - while payload_start < len(source) and source[payload_start].isspace(): - payload_start += 1 - payload_end = _player_bootstrap_payload_end(source, payload_start) - if payload_end is None: - return None +def _player_bootstrap_requests(bootstrap_manifest: str) -> list[ast.Call]: + """Return actual Python calls, excluding comments and string literals.""" + try: - expression = ast.parse(source[payload_start:payload_end], mode="eval") - except SyntaxError: - return None - return expression.body if isinstance(expression.body, ast.Dict) else None + python_tree = ast.parse(_bootstrap_python_source(bootstrap_manifest)) + except SyntaxError as exc: + raise AssertionError( + "dev-demo bootstrap Python script must be valid Python" + ) from exc + return [ + node + for node in ast.walk(python_tree) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == "post_json" + and len(node.args) >= 2 + and isinstance(node.args[0], ast.Call) + and isinstance(node.args[0].func, ast.Name) + and node.args[0].func.id == "public_account_url" + and node.args[0].args + and isinstance(node.args[0].args[0], ast.Constant) + and node.args[0].args[0].value == "/auth/player-bootstrap" + ] -def _validate_player_bootstrap_payload(source: str, request: re.Match[str]) -> bool: - payload = _player_bootstrap_payload(source, request) +def _validate_player_bootstrap_payload(request: ast.Call) -> bool: + if len(request.args) < 2 or not isinstance(request.args[1], ast.Dict): + return False + payload = request.args[1] if payload is None or len(payload.keys) != 2: return False fields = { @@ -884,18 +830,14 @@ def _validate_bootstrap_manifest(bootstrap_manifest: str) -> None: "dev-demo bootstrap must remove its credential secret after successful pod logging" ) - player_bootstrap_requests = list( - PLAYER_BOOTSTRAP_REQUEST_CALL.finditer(bootstrap_manifest) - ) + player_bootstrap_requests = _player_bootstrap_requests(bootstrap_manifest) player_bootstrap_request_count = len(player_bootstrap_requests) if player_bootstrap_request_count != 1: raise AssertionError( "dev-demo bootstrap must contain exactly one /auth/player-bootstrap request " f"(found {player_bootstrap_request_count})" ) - if not _validate_player_bootstrap_payload( - bootstrap_manifest, player_bootstrap_requests[0] - ): + if not _validate_player_bootstrap_payload(player_bootstrap_requests[0]): raise AssertionError( "dev-demo bootstrap must send exactly accountIdentifier and secret " "to /auth/player-bootstrap" @@ -988,10 +930,7 @@ def validate_workflow(root: Path) -> None: for source in summary_writers if any( has_forbidden_summary_reference(region) - for region in ( - summary_write_regions(source.source) - + ([source.source] if source.summary_reachable else []) - ) + for region in summary_write_regions(source.source) ) ] if offending: diff --git a/dev-tools/validation/test_check_dev_demo_summary.py b/dev-tools/validation/test_check_dev_demo_summary.py index c4de264a87..043a7de034 100644 --- a/dev-tools/validation/test_check_dev_demo_summary.py +++ b/dev-tools/validation/test_check_dev_demo_summary.py @@ -69,9 +69,26 @@ def _write_workflow_fixture( self, root: Path, bootstrap_manifest: str, - summary_run: str = 'echo "safe summary" >> "$GITHUB_STEP_SUMMARY"', + summary_run: str | None = None, smoke_condition: str = "${{ success() }}", ) -> None: + helper_path = root / "dev-tools/hosted/dev-demo/write-dev-demo-summary.sh" + helper_path.parent.mkdir(parents=True) + helper_path.write_text( + ( + ROOT / "dev-tools/hosted/dev-demo/write-dev-demo-summary.sh" + ).read_text(encoding="utf-8"), + encoding="utf-8", + ) + if summary_run is None: + summary_run = ( + 'bash ./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh \\\n' + " success \\\n" + ' "${{ needs.dev-demo-plan.outputs.head_sha }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.image_tag }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.hostname }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.telnet_port }}" >> "$GITHUB_STEP_SUMMARY"' + ) workflow = { "jobs": { "dev-demo-deploy": { @@ -116,8 +133,7 @@ def test_validate_workflow_rejects_bootstrap_credentials_in_summary_writer(self) ) with self.assertRaisesRegex( AssertionError, - "dev-demo summaries must not reference bootstrap credential material; " - "offending summary writers: dev-demo-deploy/Summarize dev-demo access", + "unsupported or indirect summary syntax", ): self.validator.validate_workflow(root) @@ -220,9 +236,19 @@ def test_validate_workflow_rejects_multiple_player_bootstrap_requests(self): " }," ) self.assertIn(canonical_payload, bootstrap_manifest) + canonical_request = ( + "status, bootstrap_body = post_json(\n" + " " + + canonical_payload + + "\n )" + ) + self.assertIn(canonical_request, bootstrap_manifest) + duplicate_request = canonical_request.replace( + "status, bootstrap_body", "duplicate_status, duplicate_body", 1 + ) invalid_manifest = bootstrap_manifest.replace( - canonical_payload, - f"{canonical_payload}\n{canonical_payload}", + canonical_request, + f"{canonical_request}\n {duplicate_request}", 1, ) with tempfile.TemporaryDirectory() as directory: @@ -234,6 +260,37 @@ def test_validate_workflow_rejects_multiple_player_bootstrap_requests(self): ): self.validator.validate_workflow(root) + def test_validate_workflow_does_not_count_fake_bootstrap_call_comment_or_string(self): + bootstrap_manifest = self._bootstrap_manifest_fixture() + canonical_payload = ( + 'public_account_url("/auth/player-bootstrap"),\n' + " {\n" + ' "accountIdentifier": email,\n' + ' "secret": password,\n' + " }," + ) + fake_source = ( + '# public_account_url("/auth/player-bootstrap")\n' + 'fake = "public_account_url(\\"/auth/player-bootstrap\\")"' + ) + self.assertIn(canonical_payload, bootstrap_manifest) + invalid_manifest = bootstrap_manifest.replace(canonical_payload, fake_source, 1) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self._write_workflow_fixture(root, invalid_manifest) + with self.assertRaisesRegex( + AssertionError, + r"dev-demo bootstrap must contain exactly one /auth/player-bootstrap request \(found 0\)", + ): + self.validator.validate_workflow(root) + + def test_bootstrap_python_heredoc_uses_exact_shell_terminator(self): + source = ( + self.validator.BOOTSTRAP_PYTHON_HEREDOC_OPENER + + "\nprint('before')\n PY\nprint('after')\nPY\n" + ) + self.assertIn("print('after')", self.validator._bootstrap_python_source(source)) + def test_validate_workflow_accepts_reformatted_player_bootstrap_payload(self): bootstrap_manifest = self._bootstrap_manifest_fixture() canonical_payload = ( @@ -729,20 +786,6 @@ def test_smoke_account_runtime_does_not_retry_non_retryable_http_failure(self): "HTTP 400 must not be retried", ) - def test_shell_group_tokens_ignore_comments_quotes_and_expansions(self): - fixtures = ( - ("{ echo safe # comment with } and )", ["{"]), - ("{ echo safe#not-a-comment }", ["{", "}"]), - ('{ echo "# not a comment }" }', ["{", "}"]), - (r"{ echo \#not-a-comment }", ["{", "}"]), - ("{ echo '\\' }", ["{", "}"]), - ("{ echo ${value#pattern} }", ["{", "}"]), - ('{ echo $(printf "# not a comment }") }', ["{", "}"]), - ) - for fixture, expected in fixtures: - with self.subTest(fixture=fixture): - self.assertEqual(self.validator.shell_group_tokens(fixture), expected) - def test_cleanup_parsers_handle_nested_groups_and_reject_unsupported_if_forms(self): validator = self.validator nested_if = [ @@ -783,141 +826,114 @@ def test_cleanup_parsers_handle_nested_groups_and_reject_unsupported_if_forms(se ) ) - def test_summary_helper_paths_allow_only_workspace_root_variables(self): + def test_summary_write_regions_accept_only_canonical_direct_forms(self): + validator = self.validator + direct = ( + 'bash ./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh \\\n' + " success \\\n" + ' "${{ needs.dev-demo-plan.outputs.head_sha }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.image_tag }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.hostname }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.telnet_port }}" >> "$GITHUB_STEP_SUMMARY"' + ) + metadata = "\n".join(validator.SUMMARY_METADATA_LINES) + self.assertEqual(len(validator.summary_write_regions(direct)), 1) + self.assertEqual(len(validator.summary_write_regions(metadata)), 1) + self.assertEqual( + validator.summary_write_regions('echo "safe summary" >> "$GITHUB_STEP_SUMMARY"'), + [], + ) + + def test_discovery_rejects_indirect_summary_sink(self): + validator = self.validator + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = [ + validator.WorkflowRunSource( + "job", + "step", + 'summary_file="$GITHUB_STEP_SUMMARY"\necho safe >> "$summary_file"', + ) + ] + with self.assertRaisesRegex(AssertionError, "unsupported or indirect summary syntax"): + validator.discover_summary_writers(source, root) + + def test_discovery_rejects_unsupported_helper_indirection(self): + validator = self.validator + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = [ + validator.WorkflowRunSource( + "job", + "step", + 'summary_helper="./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh"\n' + 'bash "$summary_helper" success >> "$GITHUB_STEP_SUMMARY"', + ) + ] + with self.assertRaisesRegex(AssertionError, "unsupported or indirect summary syntax"): + validator.discover_summary_writers(source, root) + + def test_discovery_rejects_workflow_helper_summary_credential_sink(self): validator = self.validator with tempfile.TemporaryDirectory() as directory: root = Path(directory) - expected = root / "dev-tools/tests/smoke-transport-contract.sh" - fixtures = ( - "dev-tools/tests/smoke-transport-contract.sh", - "./dev-tools/tests/smoke-transport-contract.sh", - "bash dev-tools/tests/smoke-transport-contract.sh", - "bash ./dev-tools/tests/smoke-transport-contract.sh", - f"bash {root}/dev-tools/tests/smoke-transport-contract.sh", - "$FIREMUD_REPO_ROOT/dev-tools/tests/smoke-transport-contract.sh", - "$GITHUB_WORKSPACE/dev-tools/tests/smoke-transport-contract.sh", - "${ROOT_DIR}/dev-tools/tests/smoke-transport-contract.sh", + self._write_workflow_fixture( + root, + self._bootstrap_manifest_fixture(), + 'bash ./dev-tools/other-summary.sh', + ) + helper = root / "dev-tools/other-summary.sh" + helper.write_text( + 'echo "${DEMO_SMOKE_PASSWORD}" >> "$GITHUB_STEP_SUMMARY"\n', + encoding="utf-8", ) - for fixture in fixtures: - with self.subTest(fixture=fixture): - matches = list(validator._helper_matches(fixture)) - self.assertEqual(len(matches), 1) - self.assertEqual( - validator.normalize_summary_helper_path( - matches[0].group("invocation"), root - ), - expected.resolve(), - ) - unsupported = "$HOME/dev-tools/tests/smoke-transport-contract.sh" - match = next(validator._helper_matches(unsupported)) - with self.assertRaisesRegex(ValueError, "unsupported variable-prefixed"): - validator.normalize_summary_helper_path(match.group("invocation"), root) + with self.assertRaisesRegex( + AssertionError, "repository shell helper must not write" + ): + validator.validate_workflow(root) - outside = root.parent / "dev-tools/tests/smoke-transport-contract.sh" + def test_discovery_rejects_nested_workflow_helper_summary_credential_sink(self): + validator = self.validator + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self._write_workflow_fixture( + root, + self._bootstrap_manifest_fixture(), + 'bash ./dev-tools/outer-summary.sh', + ) + (root / "dev-tools/outer-summary.sh").write_text( + "bash ./dev-tools/inner-summary.sh\n", encoding="utf-8" + ) + (root / "dev-tools/inner-summary.sh").write_text( + 'echo "${DEMO_SMOKE_PASSWORD}" >> "$GITHUB_STEP_SUMMARY"\n', + encoding="utf-8", + ) with self.assertRaisesRegex( - ValueError, "summary helper path escapes repository root" + AssertionError, "repository shell helper must not write" ): - validator.discover_summary_writers( - [ - validator.WorkflowRunSource( - "job", - "step", - f'bash {outside} >> "$GITHUB_STEP_SUMMARY"', - ) - ], - root, - ) + validator.validate_workflow(root) - def test_summary_write_regions_preserve_group_and_heredoc_boundaries(self): + def test_discovery_checks_variable_rooted_nested_helper(self): validator = self.validator - fixtures = ( - ('echo "safe summary" > "$GITHUB_STEP_SUMMARY"', False), - ('echo "safe summary" | tee "$GITHUB_STEP_SUMMARY"', False), - ('echo "safe summary" | tee -a "$GITHUB_STEP_SUMMARY"', False), - ( - 'echo "safe summary" | tee --append "$GITHUB_STEP_SUMMARY"', - False, - ), - ( - ( - 'printf "%s" "$DEMO_SMOKE_PASSWORD" >/tmp/password\n' - 'echo "safe summary" >> "$GITHUB_STEP_SUMMARY"' - ), - False, - ), - ( - '{\n echo "unsafe: $DEMO_SMOKE_PASSWORD"\n} >> "$GITHUB_STEP_SUMMARY"', - True, - ), - ( - ( - "cat <<'SUMMARY_EOF' >> \"$GITHUB_STEP_SUMMARY\"\n" - "unsafe: $DEMO_SMOKE_PASSWORD\n" - "SUMMARY_EOF" - ), - True, - ), - ( - ( - "cat <<-'SUMMARY_EOF' >> \"$GITHUB_STEP_SUMMARY\"\n" - "\tunsafe: $DEMO_SMOKE_PASSWORD\n" - "SUMMARY_EOF" - ), - True, - ), - ( - ( - "cat >> \"$GITHUB_STEP_SUMMARY\" <<'SUMMARY_EOF'\n" - "unsafe: $DEMO_SMOKE_PASSWORD\n" - "SUMMARY_EOF" - ), - True, - ), - ( - ( - "cat <<'SUMMARY_EOF' | tee \"$GITHUB_STEP_SUMMARY\"\n" - "unsafe: $DEMO_SMOKE_PASSWORD\n" - "SUMMARY_EOF" - ), - True, - ), - ( - '{ echo "unsafe: $DEMO_SMOKE_PASSWORD"; } >> "$GITHUB_STEP_SUMMARY"', - True, - ), - ( - '( echo "unsafe: $DEMO_SMOKE_PASSWORD" ) >> "$GITHUB_STEP_SUMMARY"', - True, - ), - ( - ( - "cat <<'UNRELATED'\n" - "unsafe: $DEMO_SMOKE_PASSWORD\n" - "UNRELATED\n" - 'echo "safe summary" >> "$GITHUB_STEP_SUMMARY"' - ), - False, - ), - ( - ( - "unrelated() {\n" - ' echo "unsafe: $DEMO_SMOKE_PASSWORD"\n' - "}\n" - 'echo "safe summary" >> "$GITHUB_STEP_SUMMARY"' - ), - False, - ), - ) - for fixture, unsafe in fixtures: - with self.subTest(fixture=fixture): - regions = validator.summary_write_regions(fixture) - self.assertEqual( - any( - validator.has_forbidden_summary_reference(region) - for region in regions - ), - unsafe, - ) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self._write_workflow_fixture( + root, + self._bootstrap_manifest_fixture(), + 'bash ./dev-tools/outer-summary.sh', + ) + (root / "dev-tools/outer-summary.sh").write_text( + 'source "$FIREMUD_REPO_ROOT/dev-tools/inner-summary.sh"\n', + encoding="utf-8", + ) + (root / "dev-tools/inner-summary.sh").write_text( + 'echo "${DEMO_SMOKE_PASSWORD}" >> "$GITHUB_STEP_SUMMARY"\n', + encoding="utf-8", + ) + with self.assertRaisesRegex( + AssertionError, "repository shell helper must not write" + ): + validator.validate_workflow(root) def test_forbidden_summary_reference_detects_secret_pipelines_without_crossing_commands( self, @@ -954,145 +970,31 @@ def test_forbidden_summary_reference_detects_secret_pipelines_without_crossing_c with self.subTest(fixture=fixture): self.assertFalse(validator.has_forbidden_summary_reference(fixture)) - def test_summary_reachability_propagates_through_redirected_helpers(self): + def test_canonical_helper_is_checked_for_forbidden_references(self): validator = self.validator with tempfile.TemporaryDirectory() as directory: root = Path(directory) - helper_one = root / "dev-tools/summary-one.sh" - helper_two = root / "dev-tools/summary-two.sh" - helper_one.parent.mkdir(parents=True) - helper_one.write_text( - "#!/usr/bin/env bash\nbash dev-tools/summary-two.sh\n", - encoding="utf-8", - ) - helper_two.write_text( - '#!/usr/bin/env bash\necho "unsafe: $DEMO_SMOKE_PASSWORD"\n', - encoding="utf-8", + helper_path = root / "dev-tools/hosted/dev-demo/write-dev-demo-summary.sh" + helper_path.parent.mkdir(parents=True) + helper_path.write_text( + 'echo "${DEMO_SMOKE_PASSWORD}"\n', encoding="utf-8" ) - sources = [ - validator.WorkflowRunSource( - "job", - "step", - 'bash dev-tools/summary-one.sh >> "$GITHUB_STEP_SUMMARY"', - ) - ] - writers = validator.discover_summary_writers(sources, root) - self.assertEqual(len(writers), 3) - reachable_helpers = [ - writer - for writer in writers - if writer.resolved_helper_path - in {helper_one.resolve(), helper_two.resolve()} - ] - self.assertEqual(len(reachable_helpers), 2) - self.assertTrue(all(writer.summary_reachable for writer in reachable_helpers)) - self.assertTrue( - any( - validator.has_forbidden_summary_reference(writer.source) - for writer in reachable_helpers - if writer.summary_reachable - ) - ) - - def test_helper_cycles_terminate_without_repeating_resolved_paths(self): - validator = self.validator - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - helper_one = root / "dev-tools/summary-one.sh" - helper_two = root / "dev-tools/summary-two.sh" - helper_one.parent.mkdir(parents=True) - helper_one.write_text( - "#!/usr/bin/env bash\nbash dev-tools/summary-two.sh\n", - encoding="utf-8", - ) - helper_two.write_text( - "#!/usr/bin/env bash\nbash dev-tools/summary-one.sh\n", - encoding="utf-8", - ) - sources = [ - validator.WorkflowRunSource( - "job", - "step", - 'bash dev-tools/summary-one.sh >> "$GITHUB_STEP_SUMMARY"', - ) - ] - writers = validator.discover_summary_writers(sources, root) - self.assertEqual(len(writers), 3) - resolved_helper_paths = [ - writer.resolved_helper_path - for writer in writers - if writer.resolved_helper_path is not None - ] - self.assertCountEqual( - resolved_helper_paths, [helper_one.resolve(), helper_two.resolve()] - ) - self.assertTrue( - all( - writer.summary_reachable - for writer in writers - if writer.resolved_helper_path is not None - ) - ) - - def test_helper_reprocesses_when_reachability_is_upgraded(self): - validator = self.validator - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - helper = root / "dev-tools/summary.sh" - helper.parent.mkdir(parents=True) - helper.write_text( - '#!/usr/bin/env bash\necho "unsafe: $DEMO_SMOKE_PASSWORD"\n', - encoding="utf-8", - ) - sources = [ - validator.WorkflowRunSource( - "job", - "summary-step", - 'bash dev-tools/summary.sh >> "$GITHUB_STEP_SUMMARY"', - ), - validator.WorkflowRunSource( - "job", "non-summary-step", "bash dev-tools/summary.sh" - ), - ] - writers = validator.discover_summary_writers(sources, root) - reachable_helpers = [ - writer - for writer in writers - if writer.resolved_helper_path == helper.resolve() - ] - self.assertEqual(len(reachable_helpers), 1) - self.assertTrue(reachable_helpers[0].summary_reachable) - - def test_missing_helper_fails_closed_with_clear_assertion(self): - validator = self.validator - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) source = [ validator.WorkflowRunSource( "job", "step", - 'bash dev-tools/missing-summary.sh >> "$GITHUB_STEP_SUMMARY"', + 'bash ./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh \\\n' + ' success "${{ needs.dev-demo-plan.outputs.head_sha }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.image_tag }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.hostname }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.telnet_port }}" >> "$GITHUB_STEP_SUMMARY"', ) ] with self.assertRaisesRegex( - AssertionError, "summary helper file is missing" + AssertionError, "canonical dev-demo summary helper must not reference" ): validator.discover_summary_writers(source, root) - def test_discovery_fails_closed_for_unsupported_variable_helper(self): - validator = self.validator - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - source = [ - validator.WorkflowRunSource( - "job", - "step", - 'bash "$UNTRUSTED_ROOT/dev-tools/summary.sh" >> "$GITHUB_STEP_SUMMARY"', - ) - ] - with self.assertRaisesRegex(ValueError, "unsupported variable-prefixed"): - validator.discover_summary_writers(source, root) - if __name__ == "__main__": unittest.main()