diff --git a/plugins/magpie-security/skills/issue-import-from-md/SKILL.md b/plugins/magpie-security/skills/issue-import-from-md/SKILL.md index 0938e6892..8201f2a6e 100644 --- a/plugins/magpie-security/skills/issue-import-from-md/SKILL.md +++ b/plugins/magpie-security/skills/issue-import-from-md/SKILL.md @@ -25,9 +25,9 @@ when_to_use: | anchor the import on (`security-issue-import-from-pr`). argument-hint: "[path-to-markdown-file]" capability: capability:intake -surface_hash: sha256:e2437e84cdf98aa5 +surface_hash: sha256:b741b2de80b78093 license: Apache-2.0 -measured_tokens: 6282 +measured_tokens: 6272 --- + +The configured skill is `security-issue-import-from-md`. +All configuration and override-anchor checks pass. +Tracker backend: `github`. + +Saved caller grants include `rollup-append` and +`issue-create-labeled`. + +The saved label allowlist contains `needs triage` +but lacks `security issue`. + +The proposed diff adds only `security issue`. +The operator explicitly declined the change. +The saved policy remains unchanged. + +The skill must not be stamped clean. diff --git a/tools/skill-evals/evals/setup/step-reconcile-confirmation/fixtures/output-spec.md b/tools/skill-evals/evals/setup/step-reconcile-confirmation/fixtures/output-spec.md index ed8818bf5..d96967010 100644 --- a/tools/skill-evals/evals/setup/step-reconcile-confirmation/fixtures/output-spec.md +++ b/tools/skill-evals/evals/setup/step-reconcile-confirmation/fixtures/output-spec.md @@ -7,7 +7,7 @@ Return ONLY valid JSON with these fields: - `decision`: `"declined"` or `"confirmed"` - `policy_verified`: boolean; true only when the saved policy has been - re-read and all required grants are present. + re-read and all required grants and applicable GitHub import labels are present. - `policy_changed`: boolean; whether the saved policy actually changed. - `stamp_written`: boolean; whether this skill was stamped clean. diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-4-import-policy-grants/expected.json b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-4-import-policy-grants/expected.json index 9e6886291..46d67ca1d 100644 --- a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-4-import-policy-grants/expected.json +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-4-import-policy-grants/expected.json @@ -4,19 +4,19 @@ "kind": "policy", "skill": "security-issue-import", "override_file": null, - "detail": "Missing caller security-issue-import in .apache-magpie-overrides/tools/vetted-ops/config.toml; propose issue-list-with-bodies and rollup-append." + "detail": "Missing caller security-issue-import in .apache-magpie-overrides/tools/vetted-ops/config.toml; propose issue-list-with-bodies and rollup-append. Also require issue-create-labeled." }, { "kind": "policy", "skill": "security-issue-import-from-md", "override_file": null, - "detail": "Existing caller security-issue-import-from-md lacks rollup-append; preserve its issue-view grant." + "detail": "Existing caller security-issue-import-from-md lacks rollup-append; preserve its issue-view grant. Also require issue-create-labeled." }, { "kind": "policy", "skill": "security-issue-import-from-pr", "override_file": null, - "detail": "Existing caller security-issue-import-from-pr lacks pr-view-with-body; preserve its rollup-append grant." + "detail": "Existing caller security-issue-import-from-pr lacks pr-view-with-body; preserve its rollup-append grant. Also require issue-create-labeled." } ], "unchecked": [], diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-4-import-policy-grants/report.md b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-4-import-policy-grants/report.md index 419c62fa3..af9a48dd9 100644 --- a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-4-import-policy-grants/report.md +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-4-import-policy-grants/report.md @@ -30,8 +30,12 @@ Tracker backend: `github`. The framework's vetted-ops README provides this example: [callers] -"security-issue-import" = ["issue-list-with-bodies", "rollup-append"] -"security-issue-import-from-md" = ["rollup-append"] -"security-issue-import-from-pr" = ["pr-view-with-body", "rollup-append"] +"security-issue-import" = ["issue-list-with-bodies", "rollup-append", "issue-create-labeled"] +"security-issue-import-from-md" = ["rollup-append", "issue-create-labeled"] +"security-issue-import-from-pr" = ["pr-view-with-body", "rollup-append", "issue-create-labeled"] + +The PR importer is configured for `scope:core` and a merged PR. +The existing `[values] labels` contains `needs triage`, `security issue`, +`scope:core`, and `pr merged`; all applicable required labels are approved. No policy changes have been confirmed during this run. diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-5-declined-import-grant/expected.json b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-5-declined-import-grant/expected.json index dbc075b62..c7725e2ee 100644 --- a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-5-declined-import-grant/expected.json +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-5-declined-import-grant/expected.json @@ -4,7 +4,7 @@ "kind": "policy", "skill": "security-issue-import-from-md", "override_file": null, - "detail": "Caller security-issue-import-from-md lacks rollup-append. The operator declined the grant; preserve issue-view and leave the policy finding unresolved." + "detail": "Caller security-issue-import-from-md lacks rollup-append and issue-create-labeled. The operator declined the grants; preserve issue-view and leave the policy finding unresolved." } ], "unchecked": [], diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-5-declined-import-grant/report.md b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-5-declined-import-grant/report.md index 5007d4473..81c7f8386 100644 --- a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-5-declined-import-grant/report.md +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-5-declined-import-grant/report.md @@ -16,10 +16,11 @@ The policy is valid TOML. Its caller entry is: "security-issue-import-from-md" = ["issue-view"] The vetted-ops README configuration example contains: - "security-issue-import-from-md" = ["rollup-append"] + "security-issue-import-from-md" = ["rollup-append", "issue-create-labeled"] During confirmation, the operator declined the proposal -to add `rollup-append` to this caller. +to add `rollup-append` and `issue-create-labeled` to this caller. The policy remains unchanged. +Its label allowlist already contains `needs triage` and `security issue`. The current reconciliation stamp contains no entry for this skill. diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-6-upgrade-old-import-policy/expected.json b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-6-upgrade-old-import-policy/expected.json new file mode 100644 index 000000000..faf857266 --- /dev/null +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-6-upgrade-old-import-policy/expected.json @@ -0,0 +1,12 @@ +{ + "proposals": [ + { + "kind": "policy", + "skill": "security-issue-import", + "override_file": null, + "detail": "Existing caller lacks issue-create-labeled and the label allowlist lacks security issue. Do not stamp clean." + } + ], + "unchecked": [], + "stamp_written": false +} diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-6-upgrade-old-import-policy/report.md b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-6-upgrade-old-import-policy/report.md new file mode 100644 index 000000000..e03806657 --- /dev/null +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-6-upgrade-old-import-policy/report.md @@ -0,0 +1,25 @@ + + +Install method: `git-branch` (pinned snapshot). + +The configured skill `security-issue-import` is in scope. +Required configuration and override-anchor checks pass. + +Existing stamp hash: `sha256:079bd7106b8b78ef`. +Current skill hash: `sha256:3210ccb4763beb17`. + +Tracker backend: `github`. + +Existing policy: + + [callers] + "security-issue-import" = ["issue-list-with-bodies", "rollup-append"] + + [values] + labels = ["needs triage"] + +The new requirements include `issue-create-labeled` and the +`security issue` label. + +No policy changes have been approved or applied. diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-7-missing-intake-label/expected.json b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-7-missing-intake-label/expected.json new file mode 100644 index 000000000..daf9bc833 --- /dev/null +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-7-missing-intake-label/expected.json @@ -0,0 +1,12 @@ +{ + "proposals": [ + { + "kind": "policy", + "skill": "security-issue-import-from-md", + "override_file": null, + "detail": "Caller grants are complete, but security issue is missing from the label allowlist. Propose the missing label; do not stamp clean." + } + ], + "unchecked": [], + "stamp_written": false +} diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-7-missing-intake-label/report.md b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-7-missing-intake-label/report.md new file mode 100644 index 000000000..1c22d8370 --- /dev/null +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-7-missing-intake-label/report.md @@ -0,0 +1,20 @@ + + +Install method: `git-branch` (pinned snapshot). + +The configured skill `security-issue-import-from-md` is in scope. +All configuration and override-anchor checks pass. +Tracker backend: `github`. + +Existing policy: + + [callers] + "security-issue-import-from-md" = ["rollup-append", "issue-create-labeled"] + + [values] + labels = ["needs triage"] + +All required caller grants exist. +The required `security issue` label is missing. +No policy change has been approved or applied. diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-8-missing-pr-scope-label/expected.json b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-8-missing-pr-scope-label/expected.json new file mode 100644 index 000000000..48c7c6003 --- /dev/null +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-8-missing-pr-scope-label/expected.json @@ -0,0 +1,12 @@ +{ + "proposals": [ + { + "kind": "policy", + "skill": "security-issue-import-from-pr", + "override_file": null, + "detail": "Caller grants are complete, but scope:core is missing from the label allowlist. Propose only that label; do not stamp clean." + } + ], + "unchecked": [], + "stamp_written": false +} diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-8-missing-pr-scope-label/report.md b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-8-missing-pr-scope-label/report.md new file mode 100644 index 000000000..358099224 --- /dev/null +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-8-missing-pr-scope-label/report.md @@ -0,0 +1,23 @@ + + +Install method: `git-branch` (pinned snapshot). + +The configured skill `security-issue-import-from-pr` is in scope. +All configuration and override-anchor checks pass. +Tracker backend: `github`. + +The configured PR importer requires these labels: +`security issue`, `scope:core`, `pr merged`. + +Existing policy: + + [callers] + "security-issue-import-from-pr" = ["pr-view-with-body", "rollup-append", "issue-create-labeled"] + + [values] + labels = ["security issue", "pr merged"] + +All caller grants exist. +The required project-specific `scope:core` label is missing. +No policy change has been approved or applied. diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-9-missing-pr-state-label/expected.json b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-9-missing-pr-state-label/expected.json new file mode 100644 index 000000000..8f566ec53 --- /dev/null +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-9-missing-pr-state-label/expected.json @@ -0,0 +1,12 @@ +{ + "proposals": [ + { + "kind": "policy", + "skill": "security-issue-import-from-pr", + "override_file": null, + "detail": "Caller grants are complete, but pr merged is missing from the label allowlist. Propose only that label; do not stamp clean." + } + ], + "unchecked": [], + "stamp_written": false +} diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-9-missing-pr-state-label/report.md b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-9-missing-pr-state-label/report.md new file mode 100644 index 000000000..655541722 --- /dev/null +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/case-9-missing-pr-state-label/report.md @@ -0,0 +1,23 @@ + + +Install method: `git-branch` (pinned snapshot). + +The configured skill `security-issue-import-from-pr` is in scope. +All configuration and override-anchor checks pass. +Tracker backend: `github`. + +The configured PR importer requires these labels: +`security issue`, `scope:core`, `pr merged`. + +Existing policy: + + [callers] + "security-issue-import-from-pr" = ["pr-view-with-body", "rollup-append", "issue-create-labeled"] + + [values] + labels = ["security issue", "scope:core"] + +All caller grants exist. +The required project-specific `pr merged` label is missing. +No policy change has been approved or applied. diff --git a/tools/skill-evals/evals/setup/step-reconcile/fixtures/output-spec.md b/tools/skill-evals/evals/setup/step-reconcile/fixtures/output-spec.md index 6bfb5a1db..90272165f 100644 --- a/tools/skill-evals/evals/setup/step-reconcile/fixtures/output-spec.md +++ b/tools/skill-evals/evals/setup/step-reconcile/fixtures/output-spec.md @@ -12,7 +12,7 @@ Return ONLY valid JSON with this structure: "kind": "reanchor" | "config" | "policy", "skill": "", "override_file": "", - "detail": "" + "detail": "" } ], "unchecked": ["anchor-resolution" | "requires_config" | "policy-grants"], @@ -24,16 +24,19 @@ Return ONLY valid JSON with this structure: when an override's referenced anchor no longer resolves in the target skill's current `SKILL.md`; `kind: "config"` when a `requires_config` entry does not resolve through the lookup chain; `kind: "policy"` when - an applicable import caller or required operation is absent from an + an applicable import caller, required operation, or required label is absent from an existing vetted-ops policy. Use the caller name as `skill` and name - the exact missing operations in `detail`. Empty when all applicable + the exact missing operations or labels in `detail`. + Policy findings may group missing grants and labels for the same caller. + Required labels include intake labels and the configured PR scope, PR-state, and security-marker labels, as applicable. + Empty when all applicable checks pass cleanly for everything in scope. - `unchecked` — which check(s) could not be completed for at least one skill in scope, because that skill's `SKILL.md` was not readable this session (a marketplace install's plugin cache, denied under the sandbox). `requires_config` resolution needs only files already in the repository, so it is never unchecked. Use `policy-grants` when an - existing vetted-ops policy cannot be read or parsed. A missing + existing vetted-ops policy or its required label values cannot be verified. A missing policy is not applicable, not unchecked. Empty when nothing was skipped. - `stamp_written` is `true` only when `proposals` and `unchecked` are both empty — nothing changed, so the stamp is written immediately with no diff --git a/tools/vetted-ops/README.md b/tools/vetted-ops/README.md index 1697d53b5..f39edfc44 100644 --- a/tools/vetted-ops/README.md +++ b/tools/vetted-ops/README.md @@ -189,7 +189,7 @@ tracker = "acme/tracker" # optional — see below upstream = "acme/product" [values] -labels = ["needs triage", "cve allocated", "pr merged"] +labels = ["needs triage", "security issue", "cve allocated", "pr merged"] upstream_labels = ["ready for maintainer review", "area:scheduler"] # issues *and* PRs milestones = ["1.2.3", "1.3.0"] assignees = ["alice", "bob"] @@ -217,9 +217,9 @@ board_status_field_id = "PVTSSF_…" # its Status field id "body-field-get", "body-field-set"] "security-issue-fix" = ["rollup-append", "rollup-fold", "body-field-get", "body-field-set"] -"security-issue-import" = ["issue-list-with-bodies", "rollup-append"] -"security-issue-import-from-md" = ["rollup-append"] -"security-issue-import-from-pr" = ["pr-view-with-body", "rollup-append"] +"security-issue-import" = ["issue-list-with-bodies", "issue-create-labeled", "rollup-append"] +"security-issue-import-from-md" = ["issue-create-labeled", "rollup-append"] +"security-issue-import-from-pr" = ["pr-view-with-body", "issue-create-labeled", "rollup-append"] # Non-GitHub tracker additions, per import caller. # Add these to the corresponding existing caller array; preserve base grants. @@ -615,10 +615,11 @@ The guarantees above carry over, because the translation lives in reviewed code The full mapping, from the `gh` shape in the skills to the vetted operation to the backend subcommand, is in the contract's [skill-command table](../security-tracker/contract.md#from-skill-commands-to-vetted-operations). -Ten operations exist for it: +Eleven operations exist for it: | Operation | Kind | Parameters | Notes | |---|---|---|---| +| `issue-create-labeled` | write | `title body labels` | GitHub only: create a private tracker with a JSON array of policy-approved labels, applied atomically. `title` and `body` are paths to workspace files: the title is read and validated here, and the body travels on stdin. Returns `number`, `node_id`, and `url`. | | `issue-create` | write | `title body` | GitHub: `gh api …/issues -f title=… -F body=@-`. | | `issue-reopen` | write | `number` | | | `issue-list-label` | read | `state label` | `issue-list` filtered by one configured label. | diff --git a/tools/vetted-ops/src/vetted_ops/cli.py b/tools/vetted-ops/src/vetted_ops/cli.py index b2385ff08..c15c55707 100644 --- a/tools/vetted-ops/src/vetted_ops/cli.py +++ b/tools/vetted-ops/src/vetted_ops/cli.py @@ -101,6 +101,8 @@ def _validate_params( ) body = ops_mod.read_body(raw, workspace=config.workspace) resolved[name] = "-" + elif name in op.title_files: + resolved[name] = ops_mod.read_title(raw, workspace=config.workspace) elif ( name == "number" and config.tracker_backend is not None @@ -118,6 +120,8 @@ def _validate_params( resolved[name] = ops_mod.login(raw) elif name == "team": resolved[name] = ops_mod.team(raw) + elif name == "labels": + resolved[name] = raw # Validated against policy by the operation builder. elif name == "title": resolved[name] = ops_mod.title(raw) elif name == "query": @@ -151,6 +155,14 @@ def _validate_params( return resolved, body +def _without_file_titles(op: ops_mod.Op, params: dict[str, str], command: list[str]) -> list[str]: + """A dry run's argv for display: like a body, a title read from a file shows only as its size.""" + hidden = { + f"title={params[name]}": f"title=" for name in op.title_files + } + return [hidden.get(argument, argument) for argument in command] + + def build_argv( op: ops_mod.Op, params: dict[str, str], config: Config ) -> list[str] | dict[str, object] | procedures.Plan | tracker_backends.BackendCall: @@ -331,7 +343,7 @@ def main(argv: list[str] | None = None, *, read_only: bool = False, tracker_only if op.backend == "gh": if not isinstance(command, list): raise ops_mod.ParamError(f"operation {op.name!r} produced invalid command type") - print(" ".join(command)) + print(" ".join(_without_file_titles(op, params, command))) else: if not isinstance(command, dict): raise ops_mod.ParamError(f"operation {op.name!r} produced invalid request descriptor") diff --git a/tools/vetted-ops/src/vetted_ops/ops.py b/tools/vetted-ops/src/vetted_ops/ops.py index 4a5fa3ef0..7e5f603a5 100644 --- a/tools/vetted-ops/src/vetted_ops/ops.py +++ b/tools/vetted-ops/src/vetted_ops/ops.py @@ -38,6 +38,7 @@ from collections.abc import Callable, Sequence from dataclasses import dataclass, field from pathlib import Path +from typing import cast from . import procedures from .procedures import Plan @@ -436,6 +437,20 @@ def save_output(name: str, data: bytes, *, workspace: Path) -> Path: return root / SAVED_DIR / name +def read_title(value: str, *, workspace: Path) -> str: + """ + Read a title from a workspace file, under the same checks as an inline one. + + A refusal never quotes the file: a dry run accepts any `--config`, so its + workspace can be one the agent chose, and this runs outside the sandbox. + """ + data = read_body(value, workspace=workspace) + try: + return title(data.decode("utf-8").strip()) + except (UnicodeDecodeError, ParamError): + raise ParamError(f"title file must hold one UTF-8 line of 1 to 256 characters: {value!r}") from None + + def read_body(value: str, *, workspace: Path) -> bytes: """ Validate and read body text, returning its **content**. @@ -516,6 +531,9 @@ class Op: enums: dict[str, str] = field(default_factory=dict) #: Parameters holding a path to body content. body_files: tuple[str, ...] = () + #: Parameters holding a path to a title, for one too untrusted to write on a + #: command line: the agent saves it verbatim, and the dispatcher reads it. + title_files: tuple[str, ...] = () #: Admitted on `vetted-op-tracker` although not a `procedure` — a tracker #: write that must run outside the sandbox (the local tracker's push). tracker_entry: bool = False @@ -1070,6 +1088,55 @@ def _register(op: Op) -> None: ) ) + +def _issue_create_labeled(cfg: dict[str, str], title: str, body: str, labels: str) -> list[str]: + """Create a tracker with policy-approved labels in the same API request.""" + tracker = _tracker(cfg) + allowed = cast(object, cfg.get("labels")) + if not isinstance(allowed, (list, dict)): + raise ParamError("issue-create-labeled requires configured labels") + + try: + selected = json.loads(labels) + except (ValueError, TypeError) as exc: + raise ParamError("labels must be a JSON array") from exc + + if ( + not isinstance(selected, list) + or not 1 <= len(selected) <= 20 + or any(not isinstance(label, str) for label in selected) + ): + raise ParamError("labels must be a non-empty JSON array of up to 20 strings") + + if len(selected) != len(set(selected)): + raise ParamError("duplicate labels are not allowed") + + if any(label not in allowed for label in selected): + raise ParamError("labels contain a value not approved by policy") + + argv = [ + "gh", + "api", + f"repos/{tracker}/issues", + "--method", + "POST", + "-f", + f"title={title}", + "-F", + "body=@-", + ] + for label in selected: + argv.extend(["-f", f"labels[]={label}"]) + + argv.extend( + [ + "--jq", + "{number: .number, node_id: .node_id, url: .html_url}", + ] + ) + return argv + + _register( Op( name="issue-create", @@ -1097,6 +1164,19 @@ def _register(op: Op) -> None: ) ) +_register( + Op( + name="issue-create-labeled", + params=("title", "body", "labels"), + writes=True, + summary="Create a GitHub tracker with policy-approved labels atomically.", + body_files=("body",), + title_files=("title",), + build=_issue_create_labeled, + ) +) + + _register( Op( name="issue-search", diff --git a/tools/vetted-ops/src/vetted_ops/tracker_backends.py b/tools/vetted-ops/src/vetted_ops/tracker_backends.py index 746dc8e8f..5bd44ea54 100644 --- a/tools/vetted-ops/src/vetted_ops/tracker_backends.py +++ b/tools/vetted-ops/src/vetted_ops/tracker_backends.py @@ -186,6 +186,7 @@ def _close_reason(reason: str) -> str: #: Tracker operations with no counterpart on a non-GitHub backend, and why. NOT_ON_BACKEND: dict[str, str] = { + "issue-create-labeled": "atomic GitHub labels and node_id are GitHub-specific; use issue-create", "issue-list-with-bodies": "the non-GitHub list contract does not return issue bodies; refuse instead of declaring unmatched reports untracked", "milestone-list": "milestones are free values here; the policy's `milestones` list is the set", "milestone-create": "milestones are free values here and need no creating", diff --git a/tools/vetted-ops/tests/test_issue_create_labeled.py b/tools/vetted-ops/tests/test_issue_create_labeled.py new file mode 100644 index 000000000..223f982ad --- /dev/null +++ b/tools/vetted-ops/tests/test_issue_create_labeled.py @@ -0,0 +1,260 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +"""Regression tests for guarded security-tracker creation (issue #1979).""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from vetted_ops import cli, config, ops, tracker_backends + + +@pytest.fixture +def policy(tmp_path: Path) -> Path: + workspace = tmp_path / "scratch" + workspace.mkdir(mode=0o700) + cfg = tmp_path / "policy.toml" + cfg.write_text( + f'workspace = "{workspace}"\n' + "[repos]\n" + 'upstream = "apache/public"\n' + 'tracker = "apache/private-tracker"\n' + "[values]\n" + 'labels = ["needs triage", "security issue", "scope:core"]\n' + "[callers]\n" + '"security-issue-import" = ["issue-create-labeled"]\n' + ) + return cfg + + +def _title_file(policy: Path, text: str) -> str: + path = policy.parent / "scratch" / "title.txt" + path.write_text(text) + return str(path) + + +def test_creation_is_pinned_to_private_tracker(policy: Path) -> None: + command = ops.OPS["issue-create-labeled"].build( + config.load(policy).as_mapping(), + title="Possible vulnerability", + body="-", + labels='["needs triage","security issue"]', + ) + assert isinstance(command, list) + assert command[:3] == ["gh", "api", "repos/apache/private-tracker/issues"] + assert "repos/apache/public/issues" not in command + assert "body=@-" in command + assert ".node_id" in " ".join(command) + + +def test_labels_are_applied_at_creation(policy: Path) -> None: + command = ops.OPS["issue-create-labeled"].build( + config.load(policy).as_mapping(), + title="Possible vulnerability", + body="-", + labels='["needs triage","security issue"]', + ) + assert isinstance(command, list) + assert "labels[]=needs triage" in command + assert "labels[]=security issue" in command + + +def test_missing_tracker_refused() -> None: + with pytest.raises(ops.ParamError, match="tracker"): + ops.OPS["issue-create-labeled"].build( + {"upstream_repo": "apache/public"}, + title="Report", + body="-", + labels='["security issue"]', + ) + + +def test_non_github_backends_cannot_fall_through_to_gh() -> None: + assert "issue-create-labeled" in tracker_backends.NOT_ON_BACKEND + + +def test_existing_issue_create_contract_unchanged() -> None: + assert ops.OPS["issue-create"].params == ("title", "body") + + +def test_unapproved_label_refused(policy: Path, capsys: pytest.CaptureFixture[str]) -> None: + body = policy.parent / "scratch" / "body.md" + body.write_text("CVE vulnerability report\n") + + code = cli.main( + [ + "--config", + str(policy), + "--caller", + "security-issue-import", + "--dry-run", + "issue-create-labeled", + _title_file(policy, "Security report\n"), + str(body), + json.dumps(["public-disclosure"]), + ] + ) + assert code != cli.EXIT_OK + assert "label" in capsys.readouterr().err.lower() + + +def test_sensitive_body_uses_stdin(policy: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Confidential text must not enter argv or target the public upstream.""" + import subprocess + + body = policy.parent / "scratch" / "report.md" + secret = "CVE-2026-12345: vulnerability reported to security@example.org" + body.write_text(secret) + + loaded = config.load(policy) + monkeypatch.setattr(cli, "load", lambda _path, *, approved_only: loaded) + + observed: dict[str, list[str] | bytes] = {} + + def fake_run(argv: list[str], *, check: bool, input: bytes) -> subprocess.CompletedProcess[bytes]: + observed["argv"] = argv + observed["body"] = input + return subprocess.CompletedProcess(argv, 0) + + monkeypatch.setattr(cli.subprocess, "run", fake_run) + + result = cli.main( + [ + "--caller", + "security-issue-import", + "issue-create-labeled", + _title_file(policy, "Private security report\n"), + str(body), + '["needs triage","security issue"]', + ] + ) + + assert result == cli.EXIT_OK + assert observed["body"] == secret.encode() + assert isinstance(observed["argv"], list) + assert all(secret not in arg for arg in observed["argv"]) + assert "repos/apache/private-tracker/issues" in observed["argv"] + assert "repos/apache/public/issues" not in observed["argv"] + assert "labels[]=needs triage" in observed["argv"] + assert "labels[]=security issue" in observed["argv"] + assert "title=Private security report" in observed["argv"] + + +@pytest.mark.parametrize("title", ["", " \n", "two\nlines"]) +def test_a_title_file_gets_the_title_checks( + policy: Path, title: str, capsys: pytest.CaptureFixture[str] +) -> None: + body = policy.parent / "scratch" / "body.md" + body.write_text("Report\n") + code = cli.main( + [ + "--config", + str(policy), + "--caller", + "security-issue-import", + "--dry-run", + "issue-create-labeled", + _title_file(policy, title), + str(body), + '["needs triage"]', + ] + ) + assert code != cli.EXIT_OK + assert "title" in capsys.readouterr().err.lower() + + +@pytest.mark.parametrize("secret", ["hunter2", "hunter2\nsecond line", "hunter2" * 50]) +def test_a_title_file_is_never_echoed(policy: Path, secret: str, capsys: pytest.CaptureFixture[str]) -> None: + """A dry run takes any --config, so its output must not disclose a file it read.""" + body = policy.parent / "scratch" / "body.md" + body.write_text("Report\n") + cli.main( + [ + "--config", + str(policy), + "--caller", + "security-issue-import", + "--dry-run", + "issue-create-labeled", + _title_file(policy, secret), + str(body), + '["needs triage"]', + ] + ) + captured = capsys.readouterr() + assert "hunter2" not in captured.out + captured.err + + +def test_a_title_file_must_live_in_the_workspace( + policy: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + outside = tmp_path / "title.txt" + outside.write_text("Report\n") + body = policy.parent / "scratch" / "body.md" + body.write_text("Report\n") + code = cli.main( + [ + "--config", + str(policy), + "--caller", + "security-issue-import", + "--dry-run", + "issue-create-labeled", + str(outside), + str(body), + '["needs triage"]', + ] + ) + assert code != cli.EXIT_OK + assert "workspace" in capsys.readouterr().err.lower() + + +def test_github_failure_returns_command_error(policy: Path, monkeypatch: pytest.MonkeyPatch) -> None: + import subprocess + + body = policy.parent / "scratch" / "report.md" + body.write_text("Private security report") + + loaded = config.load(policy) + monkeypatch.setattr(cli, "load", lambda _path, *, approved_only: loaded) + + calls = [] + + def fake_run(argv: list[str], *, check: bool, input: bytes) -> subprocess.CompletedProcess[bytes]: + calls.append(argv) + return subprocess.CompletedProcess(argv, 1) + + monkeypatch.setattr(cli.subprocess, "run", fake_run) + + result = cli.main( + [ + "--caller", + "security-issue-import", + "issue-create-labeled", + _title_file(policy, "Private security report\n"), + str(body), + '["needs triage","security issue"]', + ] + ) + + assert result == cli.EXIT_COMMAND + assert len(calls) == 1 + assert calls[0][0] == "gh" diff --git a/tools/vetted-ops/tests/test_tracker_backends.py b/tools/vetted-ops/tests/test_tracker_backends.py index 60140be79..eb6112b0f 100644 --- a/tools/vetted-ops/tests/test_tracker_backends.py +++ b/tools/vetted-ops/tests/test_tracker_backends.py @@ -101,6 +101,7 @@ def _body(policy: Path, text: str = "hello\n") -> str: "login": "alice", "reason": "not planned", "title": "Path traversal in upload", + "labels": '["needs triage"]', "query": "upload traversal", "attachment": "CVE-2026-1.json", "action": "Sync", @@ -113,7 +114,7 @@ def _body(policy: Path, text: str = "hello\n") -> str: def _args(op: ops.Op, policy: Path) -> list[str]: - return [(_body(policy) if p in op.body_files else SAMPLE[p]) for p in op.params] + return [(_body(policy) if p in op.body_files + op.title_files else SAMPLE[p]) for p in op.params] # --- the mapping is complete ------------------------------------------------- @@ -133,7 +134,8 @@ def test_every_operation_that_addresses_the_tracker_is_mapped(tmp_path: Path) -> addressing = set() for name, op in ops.OPS.items(): params = { - p: (str(workspace / "b.md") if p in op.body_files else SAMPLE.get(p, "1")) for p in op.params + p: (str(workspace / "b.md") if p in op.body_files + op.title_files else SAMPLE.get(p, "1")) + for p in op.params } try: op.build(trackerless, **params) diff --git a/tools/vetted-ops/tests/test_vetted_ops.py b/tools/vetted-ops/tests/test_vetted_ops.py index 74956d113..611165eb0 100644 --- a/tools/vetted-ops/tests/test_vetted_ops.py +++ b/tools/vetted-ops/tests/test_vetted_ops.py @@ -104,6 +104,7 @@ def test_every_op_declares_validators_for_all_its_params() -> None: "item_id", "content_id", "title", + "labels", "query", "attachment", "vuln_id", @@ -142,6 +143,7 @@ def test_every_builder_produces_a_gh_argv(policy: config.Config) -> None: "item_id": "PVTI_abc", "content_id": "I_abc", "title": "A tracker title", + "labels": '["needs triage"]', "query": "path traversal", "attachment": "cve.json", "label": "needs triage", @@ -652,6 +654,7 @@ def test_no_read_operation_sends_fields_without_an_explicit_get(policy: config.C "ghsa": "GHSA-aaaa-bbbb-cccc", "item_id": "PVTI_abc", "title": "A tracker title", + "labels": '["needs triage"]', "label": "needs triage", "milestone": "1.2.3", "state": "open", @@ -1001,6 +1004,7 @@ def test_tracker_and_upstream_operations_never_cross(policy: config.Config) -> N "item_id": "PVTI_abc", "content_id": "I_abc", "title": "A tracker title", + "labels": '["needs triage"]', "query": "path traversal", "attachment": "cve.json", "label": "needs triage", @@ -1087,6 +1091,7 @@ def test_no_operation_interpolates_a_traversing_ref(policy: config.Config) -> No "item_id": "PVTI_abc", "content_id": "I_abc", "title": "A tracker title", + "labels": '["needs triage"]', "query": "path traversal", "attachment": "cve.json", "body": "unused", @@ -1425,6 +1430,7 @@ def args_for(op: ops.Op) -> dict[str, str]: "item_id": "PVTI_abc", "content_id": "I_abc", "title": "A tracker title", + "labels": '["needs triage"]', "query": "path traversal", "attachment": "cve.json", }