snoopdave commented on code in PR #401: URL: https://github.com/apache/roller/pull/401#discussion_r4712517529
########## skills/roller-security/src/roller_security/graph.py: ########## @@ -0,0 +1,1272 @@ +# 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 +# +# https://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. + +"""LangGraph StateGraph implementing the Apache Roller security triage workflow.""" + +from __future__ import annotations + +import datetime +from pathlib import Path +from typing import Any, Literal + +from langgraph.graph import END, StateGraph +from langgraph.types import interrupt + +from roller_security.markdown_views import write_case_markdown, write_summary_board +from roller_security.models import ModelTier, invoke_structured +from roller_security.state import ( + DisclosureAudit, + EmailDraft, + InvestigationReport, + ProvenanceExtract, + PublicBrief, + PublicPrDraft, + SecurityCaseState, + SeverityAssessment, +) +from roller_security.store import CaseStore +from roller_security.tools import ( + guard_private_workspace, + read_skill_ref, + run_check_private, + run_maven_tests, + scaffold_case_dir, + verify_archive_urls, + verify_fix_commit_ancestor, +) + + +def _today_iso() -> str: + return datetime.date.today().isoformat() + + +def _append_history( + state: SecurityCaseState, + step: str, + detail: str, + *, + stage: str | None = None, +) -> list[dict[str, Any]]: + hist = list(state.get("history") or []) + hist.append( + { + "step": step, + "stage": stage or state.get("stage", "new"), + "detail": detail, + } + ) + return hist + + +def _format_email(draft: EmailDraft) -> str: + return f"Subject: {draft.subject}\n\n{draft.body}" + + +def _case_record_from_state( + state: SecurityCaseState, + overrides: dict[str, Any] | None = None, +) -> dict[str, Any]: + merged: dict[str, Any] = dict(state) + if overrides: + merged.update(overrides) + + fields = ( + "case_key", + "case_id", + "slug", + "title", + "owner", + "reporter", + "reported_on", + "forwarded_on", + "thread_url", + "verified_against", + "decision", + "actor", + "preconditions", + "affected", + "severity", + "cvss", + "cvss_score", + "cve_id", + "branch", + "fix_commit", + "tests", + "target_release", + "credit", + "announcement_url", + "related", + "duplicates", + "shares_code_with", + "blocks", + "stage", + "blocked_reason", + "reporter_deadline", + "triage_dir", + "case_dir", + "public_brief", + ) + return {k: merged[k] for k in fields if k in merged} + + +def _sync_store( + state: SecurityCaseState, + *, + overrides: dict[str, Any] | None = None, + milestone: str | None = None, + milestone_status: str = "done", + extra_milestones: list[tuple[str, str]] | None = None, + note: str | None = None, + mark_na_exclude: set[str] | None = None, +) -> None: + """Persist current state to SQLite and refresh Markdown views when not in dry-run.""" + db_path = state.get("db_path") + case_key = (overrides or {}).get("case_key") or state.get("case_key") + if not db_path or not case_key: + return + + store = CaseStore(db_path) + record = _case_record_from_state(state, overrides) + store.upsert_case(record) + + today = _today_iso() + if milestone: + store.set_milestone( + case_key, + milestone, + milestone_status, + completed_on=today if milestone_status == "done" else None, + note=note or "", + ) + if extra_milestones: + for ms_name, ms_status in extra_milestones: + store.set_milestone( + case_key, + ms_name, + ms_status, + completed_on=today if ms_status == "done" else None, + ) + if mark_na_exclude is not None: + store.mark_remaining_na(case_key, exclude=mark_na_exclude) + if note: + store.add_activity_note(case_key, note, noted_on=today) + + if state.get("dry_run"): + return + + case = store.get_case(case_key) + if case: + write_case_markdown(case) + + triage_dir = state.get("triage_dir") + if triage_dir and Path(triage_dir).is_dir(): + cases = store.list_cases(triage_dir=triage_dir) + warnings = store.check_consistency(cases) + write_summary_board(triage_dir, cases, warnings) + + +# =========================================================================== +# Node 1: Tier 0 — Guard private workspace +# =========================================================================== + + +def guard_workspace_node(state: SecurityCaseState) -> dict[str, Any]: + safe, report = guard_private_workspace( + state["repo_dir"], + state["triage_dir"], + dry_run=state.get("dry_run", False), + ) + return { + "workspace_safe": safe, + "workspace_report": report, + "stage": state.get("stage") or "new", + "status": "workspace_safe" if safe else "workspace_unsafe", + "history": _append_history( + state, + "guard_workspace", + "passed" if safe else "; ".join(report), + stage="new", + ), + } + + +def _route_after_guard(state: SecurityCaseState) -> Literal["safe", "unsafe"]: + return "safe" if state.get("workspace_safe") else "unsafe" + + +# =========================================================================== +# Node 2: Tier 0 scaffold + Tier 1 provenance extract & ack email draft +# =========================================================================== + + +def ingest_and_ack_node(state: SecurityCaseState) -> dict[str, Any]: + repo_dir = state["repo_dir"] + case_dir = state.get("case_dir", "") + dry_run = state.get("dry_run", False) + mock_llm = state.get("mock_llm", False) + local_only = state.get("local_llm_only", False) + + if case_dir: + scaffold_case_dir(repo_dir, case_dir, dry_run=dry_run) + + raw_text = state.get("raw_report_text", "") + report_path = state.get("raw_report_path", "") + if not raw_text and report_path and Path(report_path).is_file(): + raw_text = Path(report_path).read_text(encoding="utf-8") + + extract_prompt = ( + "Extract structured provenance facts from this private Apache Roller security report.\n" + "Only report facts explicitly stated in the text; leave missing fields empty.\n\n" + f"Case key: {state.get('case_key', '')}\n" + f"Slug: {state.get('slug', '')}\n" + f"Raw report:\n{raw_text[:12000]}" + ) + + def _mock_provenance() -> ProvenanceExtract: + slug_title = (state.get("slug") or "security-report").replace("-", " ").title() + return ProvenanceExtract( + title=state.get("title") or slug_title, + reporter=state.get("reporter") or "Security Researcher <[email protected]>", + reported_on=state.get("reported_on") or _today_iso(), + affected=state.get("affected") or "Apache Roller <= 6.1.5", + claimed_entry_points=["app/src/main/java/org/apache/roller/weblogger/ui/struts2/"], + ) + + provenance, used_extract = invoke_structured( + ModelTier.CHEAP, + ProvenanceExtract, + extract_prompt, + mock_llm=mock_llm, + mock_factory=_mock_provenance, + local_llm_only=local_only, + private_context=True, + ) + + title = state.get("title") or provenance.title + reporter = state.get("reporter") or provenance.reporter + reported_on = state.get("reported_on") or provenance.reported_on + affected = state.get("affected") or provenance.affected + + comms_ref = read_skill_ref(repo_dir, "comms-templates.md") + ack_prompt = ( + "Draft a concise, polite Apache Roller PMC security report acknowledgement email.\n" + "Do NOT confirm validity or promise a CVE yet.\n\n" + f"Reference templates:\n{comms_ref[:4000]}\n\n" + f"Case: {state.get('case_key', '')}\n" + f"Title: {title}\n" + f"Reporter: {reporter}\n" + f"Reported on: {reported_on}\n" + ) + + def _mock_ack() -> EmailDraft: + return EmailDraft( + subject=f"Re: Security report: {title}", + body=( + f"Hello,\n\n" + f"Thank you for reporting this issue to the Apache Roller security team. " + f"We have received your report regarding \"{title}\" and are investigating.\n\n" + f"We will follow up once the PMC has completed its initial assessment.\n\n" + f"Best regards,\nApache Roller PMC" + ), + ) + + ack_draft, used_ack = invoke_structured( + ModelTier.CHEAP, + EmailDraft, + ack_prompt, + mock_llm=mock_llm, + mock_factory=_mock_ack, + local_llm_only=local_only, + private_context=True, + ) + + updates: dict[str, Any] = { + "title": title, + "reporter": reporter, + "reported_on": reported_on, + "affected": affected, + "decision": state.get("decision") or "pending", + "raw_report_text": raw_text, + "ack_email_draft": _format_email(ack_draft), + "stage": "new", + "status": "ack_drafted", + "history": _append_history( + state, + "ingest_and_ack", + f"extract={used_extract}, ack={used_ack}", + stage="new", + ), + } + _sync_store(state, overrides=updates, note="Ingested report and drafted acknowledgement") + return updates + + +# =========================================================================== +# Node 3: Gate 1 — Human acknowledgement confirmation +# =========================================================================== + + +def gate_acknowledge_node(state: SecurityCaseState) -> dict[str, Any]: + response = interrupt( + { + "gate": "acknowledge", + "case_key": state.get("case_key"), + "title": state.get("title"), + "reporter": state.get("reporter"), + "ack_email_draft": state.get("ack_email_draft"), + "instructions": ( + "Send the acknowledgement email via [email protected] / security@ " + "and resume with thread metadata." + ), + "expected_resume_schema": { + "acknowledged": True, + "thread_url": "https://lists.apache.org/thread/...", + "forwarded_on": "YYYY-MM-DD (optional)", + "owner": "optional PMC owner handle", + "credit": "optional reporter credit string", + }, + } + ) + payload = response if isinstance(response, dict) else {} + updates: dict[str, Any] = { + "thread_url": payload.get("thread_url", state.get("thread_url", "")), + "forwarded_on": payload.get("forwarded_on", state.get("forwarded_on", "")), + "owner": payload.get("owner", state.get("owner", "")), + "credit": payload.get("credit", state.get("credit", "")), + "stage": "acknowledged", + "status": "acknowledged", + "history": _append_history( + state, + "gate_acknowledge", + f"acknowledged={payload.get('acknowledged', True)}", + stage="acknowledged", + ), + } + _sync_store( + state, + overrides=updates, + milestone="acknowledged", + milestone_status="done", + note="Acknowledgement sent to reporter", + ) + return updates + + +# =========================================================================== +# Node 4: Tier 2 — Investigate codebase & build air-gapped PublicBrief +# =========================================================================== + + +def investigate_codebase_node(state: SecurityCaseState) -> dict[str, Any]: + codebase_map = read_skill_ref(state["repo_dir"], "roller-codebase-map.md") + prompt = ( + "Investigate this private Apache Roller security report against the codebase architecture.\n" + "Strictly separate verified evidence from unverified inferences.\n" + "Also produce a strictly leak-safe neutral_change_summary suitable for public commits/PRs " + "(no CVE, no vulnerability or exploit wording).\n\n" + f"Codebase map:\n{codebase_map[:8000]}\n\n" + f"Case: {state.get('case_key', '')} — {state.get('title', '')}\n" + f"Claimed affected: {state.get('affected', '')}\n" + f"Raw report:\n{(state.get('raw_report_text') or '')[:12000]}" + ) + + def _mock_investigation() -> InvestigationReport: + return InvestigationReport( + verified_evidence=( + "Verified request handling path in Roller Struts2 action layer and " + "confirmed missing server-side validation on the reported parameter." + ), + inference_notes="Further testing needed on legacy 6.1.x branch compatibility.", + minimum_actor="authenticated", + preconditions="Requires a logged-in user with weblog authoring permissions.", + affected_versions=state.get("affected") or "Apache Roller <= 6.1.5", + recommended_decision="accept", + neutral_change_summary=( + "Harden request parameter validation and normalization in weblog action handlers." + ), + affected_modules=["app"], + ) + + report, used = invoke_structured( + ModelTier.FRONTIER, + InvestigationReport, + prompt, + mock_llm=state.get("mock_llm", False), + mock_factory=_mock_investigation, + local_llm_only=state.get("local_llm_only", False), + private_context=True, + ) + + public_brief: PublicBrief = { + "case_key": state.get("case_key", ""), + "branch_name": state.get("branch", ""), + "neutral_change_summary": report.neutral_change_summary, Review Comment: 🤖Claude: fixed by showing `public_brief` at the PMC decision and CVE request gates, and accepting `public_brief` edits there. Only `neutral_change_summary`, `affected_modules` and `upgrade_guidance` can change. Test: `test_public_brief_is_shown_and_editable_at_the_decision`. ########## skills/roller-security/src/roller_security/graph.py: ########## @@ -0,0 +1,1272 @@ +# 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 +# +# https://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. + +"""LangGraph StateGraph implementing the Apache Roller security triage workflow.""" + +from __future__ import annotations + +import datetime +from pathlib import Path +from typing import Any, Literal + +from langgraph.graph import END, StateGraph +from langgraph.types import interrupt + +from roller_security.markdown_views import write_case_markdown, write_summary_board +from roller_security.models import ModelTier, invoke_structured +from roller_security.state import ( + DisclosureAudit, + EmailDraft, + InvestigationReport, + ProvenanceExtract, + PublicBrief, + PublicPrDraft, + SecurityCaseState, + SeverityAssessment, +) +from roller_security.store import CaseStore +from roller_security.tools import ( + guard_private_workspace, + read_skill_ref, + run_check_private, + run_maven_tests, + scaffold_case_dir, + verify_archive_urls, + verify_fix_commit_ancestor, +) + + +def _today_iso() -> str: + return datetime.date.today().isoformat() + + +def _append_history( + state: SecurityCaseState, + step: str, + detail: str, + *, + stage: str | None = None, +) -> list[dict[str, Any]]: + hist = list(state.get("history") or []) + hist.append( + { + "step": step, + "stage": stage or state.get("stage", "new"), + "detail": detail, + } + ) + return hist + + +def _format_email(draft: EmailDraft) -> str: + return f"Subject: {draft.subject}\n\n{draft.body}" + + +def _case_record_from_state( + state: SecurityCaseState, + overrides: dict[str, Any] | None = None, +) -> dict[str, Any]: + merged: dict[str, Any] = dict(state) + if overrides: + merged.update(overrides) + + fields = ( + "case_key", + "case_id", + "slug", + "title", + "owner", + "reporter", + "reported_on", + "forwarded_on", + "thread_url", + "verified_against", + "decision", + "actor", + "preconditions", + "affected", + "severity", + "cvss", + "cvss_score", + "cve_id", + "branch", + "fix_commit", + "tests", + "target_release", + "credit", + "announcement_url", + "related", + "duplicates", + "shares_code_with", + "blocks", + "stage", + "blocked_reason", + "reporter_deadline", + "triage_dir", + "case_dir", + "public_brief", + ) + return {k: merged[k] for k in fields if k in merged} + + +def _sync_store( + state: SecurityCaseState, + *, + overrides: dict[str, Any] | None = None, + milestone: str | None = None, + milestone_status: str = "done", + extra_milestones: list[tuple[str, str]] | None = None, + note: str | None = None, + mark_na_exclude: set[str] | None = None, +) -> None: + """Persist current state to SQLite and refresh Markdown views when not in dry-run.""" + db_path = state.get("db_path") + case_key = (overrides or {}).get("case_key") or state.get("case_key") + if not db_path or not case_key: + return + + store = CaseStore(db_path) + record = _case_record_from_state(state, overrides) + store.upsert_case(record) + + today = _today_iso() + if milestone: + store.set_milestone( + case_key, + milestone, + milestone_status, + completed_on=today if milestone_status == "done" else None, + note=note or "", + ) + if extra_milestones: + for ms_name, ms_status in extra_milestones: + store.set_milestone( + case_key, + ms_name, + ms_status, + completed_on=today if ms_status == "done" else None, + ) + if mark_na_exclude is not None: + store.mark_remaining_na(case_key, exclude=mark_na_exclude) + if note: + store.add_activity_note(case_key, note, noted_on=today) + + if state.get("dry_run"): + return + + case = store.get_case(case_key) + if case: + write_case_markdown(case) + + triage_dir = state.get("triage_dir") + if triage_dir and Path(triage_dir).is_dir(): + cases = store.list_cases(triage_dir=triage_dir) + warnings = store.check_consistency(cases) + write_summary_board(triage_dir, cases, warnings) + + +# =========================================================================== +# Node 1: Tier 0 — Guard private workspace +# =========================================================================== + + +def guard_workspace_node(state: SecurityCaseState) -> dict[str, Any]: + safe, report = guard_private_workspace( + state["repo_dir"], + state["triage_dir"], + dry_run=state.get("dry_run", False), + ) + return { + "workspace_safe": safe, + "workspace_report": report, + "stage": state.get("stage") or "new", + "status": "workspace_safe" if safe else "workspace_unsafe", + "history": _append_history( + state, + "guard_workspace", + "passed" if safe else "; ".join(report), + stage="new", + ), + } + + +def _route_after_guard(state: SecurityCaseState) -> Literal["safe", "unsafe"]: + return "safe" if state.get("workspace_safe") else "unsafe" + + +# =========================================================================== +# Node 2: Tier 0 scaffold + Tier 1 provenance extract & ack email draft +# =========================================================================== + + +def ingest_and_ack_node(state: SecurityCaseState) -> dict[str, Any]: + repo_dir = state["repo_dir"] + case_dir = state.get("case_dir", "") + dry_run = state.get("dry_run", False) + mock_llm = state.get("mock_llm", False) + local_only = state.get("local_llm_only", False) + + if case_dir: + scaffold_case_dir(repo_dir, case_dir, dry_run=dry_run) + + raw_text = state.get("raw_report_text", "") + report_path = state.get("raw_report_path", "") + if not raw_text and report_path and Path(report_path).is_file(): + raw_text = Path(report_path).read_text(encoding="utf-8") + + extract_prompt = ( + "Extract structured provenance facts from this private Apache Roller security report.\n" + "Only report facts explicitly stated in the text; leave missing fields empty.\n\n" + f"Case key: {state.get('case_key', '')}\n" + f"Slug: {state.get('slug', '')}\n" + f"Raw report:\n{raw_text[:12000]}" + ) + + def _mock_provenance() -> ProvenanceExtract: + slug_title = (state.get("slug") or "security-report").replace("-", " ").title() + return ProvenanceExtract( + title=state.get("title") or slug_title, + reporter=state.get("reporter") or "Security Researcher <[email protected]>", + reported_on=state.get("reported_on") or _today_iso(), + affected=state.get("affected") or "Apache Roller <= 6.1.5", + claimed_entry_points=["app/src/main/java/org/apache/roller/weblogger/ui/struts2/"], + ) + + provenance, used_extract = invoke_structured( + ModelTier.CHEAP, + ProvenanceExtract, + extract_prompt, + mock_llm=mock_llm, + mock_factory=_mock_provenance, + local_llm_only=local_only, + private_context=True, + ) + + title = state.get("title") or provenance.title + reporter = state.get("reporter") or provenance.reporter + reported_on = state.get("reported_on") or provenance.reported_on + affected = state.get("affected") or provenance.affected + + comms_ref = read_skill_ref(repo_dir, "comms-templates.md") + ack_prompt = ( + "Draft a concise, polite Apache Roller PMC security report acknowledgement email.\n" + "Do NOT confirm validity or promise a CVE yet.\n\n" + f"Reference templates:\n{comms_ref[:4000]}\n\n" + f"Case: {state.get('case_key', '')}\n" + f"Title: {title}\n" + f"Reporter: {reporter}\n" + f"Reported on: {reported_on}\n" + ) + + def _mock_ack() -> EmailDraft: + return EmailDraft( + subject=f"Re: Security report: {title}", + body=( + f"Hello,\n\n" + f"Thank you for reporting this issue to the Apache Roller security team. " + f"We have received your report regarding \"{title}\" and are investigating.\n\n" + f"We will follow up once the PMC has completed its initial assessment.\n\n" + f"Best regards,\nApache Roller PMC" + ), + ) + + ack_draft, used_ack = invoke_structured( + ModelTier.CHEAP, + EmailDraft, + ack_prompt, + mock_llm=mock_llm, + mock_factory=_mock_ack, + local_llm_only=local_only, + private_context=True, + ) + + updates: dict[str, Any] = { + "title": title, + "reporter": reporter, + "reported_on": reported_on, + "affected": affected, + "decision": state.get("decision") or "pending", + "raw_report_text": raw_text, + "ack_email_draft": _format_email(ack_draft), + "stage": "new", + "status": "ack_drafted", + "history": _append_history( + state, + "ingest_and_ack", + f"extract={used_extract}, ack={used_ack}", + stage="new", + ), + } + _sync_store(state, overrides=updates, note="Ingested report and drafted acknowledgement") + return updates + + +# =========================================================================== +# Node 3: Gate 1 — Human acknowledgement confirmation +# =========================================================================== + + +def gate_acknowledge_node(state: SecurityCaseState) -> dict[str, Any]: + response = interrupt( + { + "gate": "acknowledge", + "case_key": state.get("case_key"), + "title": state.get("title"), + "reporter": state.get("reporter"), + "ack_email_draft": state.get("ack_email_draft"), + "instructions": ( + "Send the acknowledgement email via [email protected] / security@ " + "and resume with thread metadata." + ), + "expected_resume_schema": { + "acknowledged": True, + "thread_url": "https://lists.apache.org/thread/...", + "forwarded_on": "YYYY-MM-DD (optional)", + "owner": "optional PMC owner handle", + "credit": "optional reporter credit string", + }, + } + ) + payload = response if isinstance(response, dict) else {} + updates: dict[str, Any] = { + "thread_url": payload.get("thread_url", state.get("thread_url", "")), + "forwarded_on": payload.get("forwarded_on", state.get("forwarded_on", "")), + "owner": payload.get("owner", state.get("owner", "")), + "credit": payload.get("credit", state.get("credit", "")), + "stage": "acknowledged", + "status": "acknowledged", + "history": _append_history( + state, + "gate_acknowledge", + f"acknowledged={payload.get('acknowledged', True)}", + stage="acknowledged", + ), + } + _sync_store( + state, + overrides=updates, + milestone="acknowledged", + milestone_status="done", + note="Acknowledgement sent to reporter", + ) + return updates + + +# =========================================================================== +# Node 4: Tier 2 — Investigate codebase & build air-gapped PublicBrief +# =========================================================================== + + +def investigate_codebase_node(state: SecurityCaseState) -> dict[str, Any]: + codebase_map = read_skill_ref(state["repo_dir"], "roller-codebase-map.md") + prompt = ( + "Investigate this private Apache Roller security report against the codebase architecture.\n" + "Strictly separate verified evidence from unverified inferences.\n" + "Also produce a strictly leak-safe neutral_change_summary suitable for public commits/PRs " + "(no CVE, no vulnerability or exploit wording).\n\n" + f"Codebase map:\n{codebase_map[:8000]}\n\n" + f"Case: {state.get('case_key', '')} — {state.get('title', '')}\n" + f"Claimed affected: {state.get('affected', '')}\n" + f"Raw report:\n{(state.get('raw_report_text') or '')[:12000]}" + ) + + def _mock_investigation() -> InvestigationReport: + return InvestigationReport( + verified_evidence=( + "Verified request handling path in Roller Struts2 action layer and " + "confirmed missing server-side validation on the reported parameter." + ), + inference_notes="Further testing needed on legacy 6.1.x branch compatibility.", + minimum_actor="authenticated", + preconditions="Requires a logged-in user with weblog authoring permissions.", + affected_versions=state.get("affected") or "Apache Roller <= 6.1.5", + recommended_decision="accept", + neutral_change_summary=( + "Harden request parameter validation and normalization in weblog action handlers." + ), + affected_modules=["app"], + ) + + report, used = invoke_structured( + ModelTier.FRONTIER, + InvestigationReport, + prompt, + mock_llm=state.get("mock_llm", False), + mock_factory=_mock_investigation, + local_llm_only=state.get("local_llm_only", False), + private_context=True, + ) + + public_brief: PublicBrief = { + "case_key": state.get("case_key", ""), + "branch_name": state.get("branch", ""), + "neutral_change_summary": report.neutral_change_summary, + "affected_modules": list(report.affected_modules), + "upgrade_guidance": "", + } + + updates: dict[str, Any] = { + "evidence_summary": report.verified_evidence, + "inference_notes": report.inference_notes, + "actor": report.minimum_actor, + "preconditions": report.preconditions, + "affected": report.affected_versions or state.get("affected", ""), + "public_brief": public_brief, + "stage": "investigating", + "status": "investigation_complete", + "history": _append_history( + state, + "investigate_codebase", + f"model={used}, recommended={report.recommended_decision}", + stage="investigating", + ), + } + _sync_store( + state, + overrides=updates, + milestone="investigating", + milestone_status="done", + note=f"Investigation complete (actor={report.minimum_actor}, recommended={report.recommended_decision})", + ) + return updates + + +# =========================================================================== +# Node 5: Gate 2 — PMC decision (accept | reject | duplicate | wont-fix) +# =========================================================================== + + +def gate_pmc_decision_node(state: SecurityCaseState) -> dict[str, Any]: + response = interrupt( + { + "gate": "pmc_decision", + "case_key": state.get("case_key"), + "evidence_summary": state.get("evidence_summary"), + "inference_notes": state.get("inference_notes"), + "actor": state.get("actor"), + "preconditions": state.get("preconditions"), + "affected": state.get("affected"), + "instructions": ( + "Record the Apache Roller PMC decision on this report. " + "Use 'accept' to proceed to severity/CVE assessment, or " + "'reject' / 'duplicate' / 'wont-fix' to draft a closing response." + ), + "expected_resume_schema": { + "decision": "accept | reject | duplicate | wont-fix", + "target_release": "e.g. 7.0.0 (required when accepting)", + "owner": "PMC owner handle", + "verified_against": "optional git commit or tag", + "related": ["optional case_key list"], + "duplicates": ["optional case_key list"], + "shares_code_with": ["optional case_key list"], + "blocks": ["optional case_key list"], + }, + } + ) + payload = response if isinstance(response, dict) else {} + raw_decision = str(payload.get("decision", "reject")).strip().lower() + decision: Literal["accept", "reject", "duplicate", "wont-fix"] = ( + raw_decision if raw_decision in ("accept", "reject", "duplicate", "wont-fix") else "reject" # type: ignore[assignment] + ) + + updates: dict[str, Any] = { + "decision": decision, + "target_release": payload.get("target_release", state.get("target_release", "")), + "owner": payload.get("owner", state.get("owner", "")), + "verified_against": payload.get("verified_against", state.get("verified_against", "")), + "related": payload.get("related", state.get("related", [])), + "duplicates": payload.get("duplicates", state.get("duplicates", [])), + "shares_code_with": payload.get("shares_code_with", state.get("shares_code_with", [])), + "blocks": payload.get("blocks", state.get("blocks", [])), + "status": f"pmc_decision_{decision}", + "history": _append_history( + state, + "gate_pmc_decision", + f"decision={decision}, target_release={payload.get('target_release', '')}", + ), + } + _sync_store(state, overrides=updates, note=f"PMC decision recorded: {decision}") + return updates + + +def _route_after_pmc_decision(state: SecurityCaseState) -> Literal["accept", "close_rejected"]: + return "accept" if state.get("decision") == "accept" else "close_rejected" + + +# =========================================================================== +# Node 6: Tier 1 — Handle rejection / duplicate / wont-fix -> END +# =========================================================================== + + +def handle_rejection_node(state: SecurityCaseState) -> dict[str, Any]: + comms_ref = read_skill_ref(state["repo_dir"], "comms-templates.md") + decision = state.get("decision", "reject") + prompt = ( + f"Draft a clear, respectful Apache Roller PMC response closing this report as '{decision}'.\n\n" + f"Reference templates:\n{comms_ref[:4000]}\n\n" + f"Title: {state.get('title', '')}\n" + f"Reporter: {state.get('reporter', '')}\n" + f"Verified evidence: {state.get('evidence_summary', '')}\n" + f"Duplicates: {state.get('duplicates', [])}\n" + ) + + def _mock_reject_email() -> EmailDraft: + return EmailDraft( + subject=f"Re: Security report: {state.get('title', '')}", + body=( + f"Hello,\n\n" + f"Thank you again for your report. After reviewing the codebase, the Apache Roller PMC " + f"has concluded that this report will be closed as '{decision}'.\n\n" + f"Summary: {state.get('evidence_summary', 'Does not cross a Roller security boundary.')}\n\n" + f"Best regards,\nApache Roller PMC" + ), + ) + + draft, used = invoke_structured( + ModelTier.CHEAP, + EmailDraft, + prompt, + mock_llm=state.get("mock_llm", False), + mock_factory=_mock_reject_email, + local_llm_only=state.get("local_llm_only", False), + private_context=True, + ) + + updates: dict[str, Any] = { + "decision_email_draft": _format_email(draft), + "stage": "rejected", + "status": "closed_rejected", + "history": _append_history( + state, + "handle_rejection", + f"decision={decision}, model={used}", + stage="rejected", + ), + } + _sync_store( + state, + overrides=updates, + milestone="rejected", + milestone_status="done", + mark_na_exclude={"acknowledged", "investigating", "rejected"}, + note=f"Case closed as {decision}", + ) + return updates + + +# =========================================================================== +# Node 7: Tier 2 Severity & CVE form + Tier 1 Acceptance email +# =========================================================================== + + +def _render_cve_form_markdown(state: SecurityCaseState, assessment: SeverityAssessment) -> str: + return ( + f"# CVE Portal Draft — {state.get('case_key', '')}\n\n" + f"- **Title**: {assessment.cve_title}\n" + f"- **ASF Severity**: {assessment.asf_severity}\n" + f"- **CVSS**: {assessment.cvss_vector or 'N/A'} ({assessment.cvss_score or 'N/A'})\n" + f"- **Problem Type**: {assessment.cwe_problem_type}\n" + f"- **Affected Versions**: {state.get('affected', '')}\n" + f"- **Fixed In**: {state.get('target_release', '')}\n" + f"- **Credit**: {state.get('credit') or state.get('reporter', '')}\n\n" Review Comment: 🤖Claude: fixed by using `TBD (ask the reporter how to be credited)` when no credit was given, instead of the reporter string. ########## skills/roller-security/src/roller_security/graph.py: ########## @@ -0,0 +1,1272 @@ +# 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 +# +# https://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. + +"""LangGraph StateGraph implementing the Apache Roller security triage workflow.""" + +from __future__ import annotations + +import datetime +from pathlib import Path +from typing import Any, Literal + +from langgraph.graph import END, StateGraph +from langgraph.types import interrupt + +from roller_security.markdown_views import write_case_markdown, write_summary_board +from roller_security.models import ModelTier, invoke_structured +from roller_security.state import ( + DisclosureAudit, + EmailDraft, + InvestigationReport, + ProvenanceExtract, + PublicBrief, + PublicPrDraft, + SecurityCaseState, + SeverityAssessment, +) +from roller_security.store import CaseStore +from roller_security.tools import ( + guard_private_workspace, + read_skill_ref, + run_check_private, + run_maven_tests, + scaffold_case_dir, + verify_archive_urls, + verify_fix_commit_ancestor, +) + + +def _today_iso() -> str: + return datetime.date.today().isoformat() + + +def _append_history( + state: SecurityCaseState, + step: str, + detail: str, + *, + stage: str | None = None, +) -> list[dict[str, Any]]: + hist = list(state.get("history") or []) + hist.append( + { + "step": step, + "stage": stage or state.get("stage", "new"), + "detail": detail, + } + ) + return hist + + +def _format_email(draft: EmailDraft) -> str: + return f"Subject: {draft.subject}\n\n{draft.body}" + + +def _case_record_from_state( + state: SecurityCaseState, + overrides: dict[str, Any] | None = None, +) -> dict[str, Any]: + merged: dict[str, Any] = dict(state) + if overrides: + merged.update(overrides) + + fields = ( + "case_key", + "case_id", + "slug", + "title", + "owner", + "reporter", + "reported_on", + "forwarded_on", + "thread_url", + "verified_against", + "decision", + "actor", + "preconditions", + "affected", + "severity", + "cvss", + "cvss_score", + "cve_id", + "branch", + "fix_commit", + "tests", + "target_release", + "credit", + "announcement_url", + "related", + "duplicates", + "shares_code_with", + "blocks", + "stage", + "blocked_reason", + "reporter_deadline", + "triage_dir", + "case_dir", + "public_brief", + ) + return {k: merged[k] for k in fields if k in merged} + + +def _sync_store( + state: SecurityCaseState, + *, + overrides: dict[str, Any] | None = None, + milestone: str | None = None, + milestone_status: str = "done", + extra_milestones: list[tuple[str, str]] | None = None, + note: str | None = None, + mark_na_exclude: set[str] | None = None, +) -> None: + """Persist current state to SQLite and refresh Markdown views when not in dry-run.""" + db_path = state.get("db_path") + case_key = (overrides or {}).get("case_key") or state.get("case_key") + if not db_path or not case_key: + return + + store = CaseStore(db_path) + record = _case_record_from_state(state, overrides) + store.upsert_case(record) + + today = _today_iso() + if milestone: + store.set_milestone( + case_key, + milestone, + milestone_status, + completed_on=today if milestone_status == "done" else None, + note=note or "", + ) + if extra_milestones: + for ms_name, ms_status in extra_milestones: + store.set_milestone( + case_key, + ms_name, + ms_status, + completed_on=today if ms_status == "done" else None, + ) + if mark_na_exclude is not None: + store.mark_remaining_na(case_key, exclude=mark_na_exclude) + if note: + store.add_activity_note(case_key, note, noted_on=today) + + if state.get("dry_run"): + return + + case = store.get_case(case_key) + if case: + write_case_markdown(case) + + triage_dir = state.get("triage_dir") + if triage_dir and Path(triage_dir).is_dir(): + cases = store.list_cases(triage_dir=triage_dir) + warnings = store.check_consistency(cases) + write_summary_board(triage_dir, cases, warnings) + + +# =========================================================================== +# Node 1: Tier 0 — Guard private workspace +# =========================================================================== + + +def guard_workspace_node(state: SecurityCaseState) -> dict[str, Any]: + safe, report = guard_private_workspace( + state["repo_dir"], + state["triage_dir"], + dry_run=state.get("dry_run", False), + ) + return { + "workspace_safe": safe, + "workspace_report": report, + "stage": state.get("stage") or "new", + "status": "workspace_safe" if safe else "workspace_unsafe", + "history": _append_history( + state, + "guard_workspace", + "passed" if safe else "; ".join(report), + stage="new", + ), + } + + +def _route_after_guard(state: SecurityCaseState) -> Literal["safe", "unsafe"]: + return "safe" if state.get("workspace_safe") else "unsafe" + + +# =========================================================================== +# Node 2: Tier 0 scaffold + Tier 1 provenance extract & ack email draft +# =========================================================================== + + +def ingest_and_ack_node(state: SecurityCaseState) -> dict[str, Any]: + repo_dir = state["repo_dir"] + case_dir = state.get("case_dir", "") + dry_run = state.get("dry_run", False) + mock_llm = state.get("mock_llm", False) + local_only = state.get("local_llm_only", False) + + if case_dir: + scaffold_case_dir(repo_dir, case_dir, dry_run=dry_run) + + raw_text = state.get("raw_report_text", "") + report_path = state.get("raw_report_path", "") + if not raw_text and report_path and Path(report_path).is_file(): + raw_text = Path(report_path).read_text(encoding="utf-8") + + extract_prompt = ( + "Extract structured provenance facts from this private Apache Roller security report.\n" + "Only report facts explicitly stated in the text; leave missing fields empty.\n\n" + f"Case key: {state.get('case_key', '')}\n" + f"Slug: {state.get('slug', '')}\n" + f"Raw report:\n{raw_text[:12000]}" + ) + + def _mock_provenance() -> ProvenanceExtract: + slug_title = (state.get("slug") or "security-report").replace("-", " ").title() + return ProvenanceExtract( + title=state.get("title") or slug_title, + reporter=state.get("reporter") or "Security Researcher <[email protected]>", + reported_on=state.get("reported_on") or _today_iso(), + affected=state.get("affected") or "Apache Roller <= 6.1.5", + claimed_entry_points=["app/src/main/java/org/apache/roller/weblogger/ui/struts2/"], + ) + + provenance, used_extract = invoke_structured( + ModelTier.CHEAP, + ProvenanceExtract, + extract_prompt, + mock_llm=mock_llm, + mock_factory=_mock_provenance, + local_llm_only=local_only, + private_context=True, + ) + + title = state.get("title") or provenance.title + reporter = state.get("reporter") or provenance.reporter + reported_on = state.get("reported_on") or provenance.reported_on + affected = state.get("affected") or provenance.affected + + comms_ref = read_skill_ref(repo_dir, "comms-templates.md") + ack_prompt = ( + "Draft a concise, polite Apache Roller PMC security report acknowledgement email.\n" + "Do NOT confirm validity or promise a CVE yet.\n\n" + f"Reference templates:\n{comms_ref[:4000]}\n\n" + f"Case: {state.get('case_key', '')}\n" + f"Title: {title}\n" + f"Reporter: {reporter}\n" + f"Reported on: {reported_on}\n" + ) + + def _mock_ack() -> EmailDraft: + return EmailDraft( + subject=f"Re: Security report: {title}", + body=( + f"Hello,\n\n" + f"Thank you for reporting this issue to the Apache Roller security team. " + f"We have received your report regarding \"{title}\" and are investigating.\n\n" + f"We will follow up once the PMC has completed its initial assessment.\n\n" + f"Best regards,\nApache Roller PMC" + ), + ) + + ack_draft, used_ack = invoke_structured( + ModelTier.CHEAP, + EmailDraft, + ack_prompt, + mock_llm=mock_llm, + mock_factory=_mock_ack, + local_llm_only=local_only, + private_context=True, + ) + + updates: dict[str, Any] = { + "title": title, + "reporter": reporter, + "reported_on": reported_on, + "affected": affected, + "decision": state.get("decision") or "pending", + "raw_report_text": raw_text, + "ack_email_draft": _format_email(ack_draft), + "stage": "new", + "status": "ack_drafted", + "history": _append_history( + state, + "ingest_and_ack", + f"extract={used_extract}, ack={used_ack}", + stage="new", + ), + } + _sync_store(state, overrides=updates, note="Ingested report and drafted acknowledgement") + return updates + + +# =========================================================================== +# Node 3: Gate 1 — Human acknowledgement confirmation +# =========================================================================== + + +def gate_acknowledge_node(state: SecurityCaseState) -> dict[str, Any]: + response = interrupt( + { + "gate": "acknowledge", + "case_key": state.get("case_key"), + "title": state.get("title"), + "reporter": state.get("reporter"), + "ack_email_draft": state.get("ack_email_draft"), + "instructions": ( + "Send the acknowledgement email via [email protected] / security@ " + "and resume with thread metadata." + ), + "expected_resume_schema": { + "acknowledged": True, + "thread_url": "https://lists.apache.org/thread/...", + "forwarded_on": "YYYY-MM-DD (optional)", + "owner": "optional PMC owner handle", + "credit": "optional reporter credit string", + }, + } + ) + payload = response if isinstance(response, dict) else {} + updates: dict[str, Any] = { + "thread_url": payload.get("thread_url", state.get("thread_url", "")), + "forwarded_on": payload.get("forwarded_on", state.get("forwarded_on", "")), + "owner": payload.get("owner", state.get("owner", "")), + "credit": payload.get("credit", state.get("credit", "")), + "stage": "acknowledged", + "status": "acknowledged", + "history": _append_history( + state, + "gate_acknowledge", + f"acknowledged={payload.get('acknowledged', True)}", + stage="acknowledged", + ), + } + _sync_store( + state, + overrides=updates, + milestone="acknowledged", + milestone_status="done", + note="Acknowledgement sent to reporter", + ) + return updates + + +# =========================================================================== +# Node 4: Tier 2 — Investigate codebase & build air-gapped PublicBrief +# =========================================================================== + + +def investigate_codebase_node(state: SecurityCaseState) -> dict[str, Any]: + codebase_map = read_skill_ref(state["repo_dir"], "roller-codebase-map.md") + prompt = ( + "Investigate this private Apache Roller security report against the codebase architecture.\n" + "Strictly separate verified evidence from unverified inferences.\n" + "Also produce a strictly leak-safe neutral_change_summary suitable for public commits/PRs " + "(no CVE, no vulnerability or exploit wording).\n\n" + f"Codebase map:\n{codebase_map[:8000]}\n\n" + f"Case: {state.get('case_key', '')} — {state.get('title', '')}\n" + f"Claimed affected: {state.get('affected', '')}\n" + f"Raw report:\n{(state.get('raw_report_text') or '')[:12000]}" + ) + + def _mock_investigation() -> InvestigationReport: + return InvestigationReport( + verified_evidence=( + "Verified request handling path in Roller Struts2 action layer and " + "confirmed missing server-side validation on the reported parameter." + ), + inference_notes="Further testing needed on legacy 6.1.x branch compatibility.", + minimum_actor="authenticated", + preconditions="Requires a logged-in user with weblog authoring permissions.", + affected_versions=state.get("affected") or "Apache Roller <= 6.1.5", + recommended_decision="accept", + neutral_change_summary=( + "Harden request parameter validation and normalization in weblog action handlers." + ), + affected_modules=["app"], + ) + + report, used = invoke_structured( + ModelTier.FRONTIER, + InvestigationReport, + prompt, + mock_llm=state.get("mock_llm", False), + mock_factory=_mock_investigation, + local_llm_only=state.get("local_llm_only", False), + private_context=True, + ) + + public_brief: PublicBrief = { + "case_key": state.get("case_key", ""), + "branch_name": state.get("branch", ""), + "neutral_change_summary": report.neutral_change_summary, + "affected_modules": list(report.affected_modules), + "upgrade_guidance": "", + } + + updates: dict[str, Any] = { + "evidence_summary": report.verified_evidence, + "inference_notes": report.inference_notes, + "actor": report.minimum_actor, + "preconditions": report.preconditions, + "affected": report.affected_versions or state.get("affected", ""), + "public_brief": public_brief, + "stage": "investigating", + "status": "investigation_complete", + "history": _append_history( + state, + "investigate_codebase", + f"model={used}, recommended={report.recommended_decision}", + stage="investigating", + ), + } + _sync_store( + state, + overrides=updates, + milestone="investigating", + milestone_status="done", + note=f"Investigation complete (actor={report.minimum_actor}, recommended={report.recommended_decision})", + ) + return updates + + +# =========================================================================== +# Node 5: Gate 2 — PMC decision (accept | reject | duplicate | wont-fix) +# =========================================================================== + + +def gate_pmc_decision_node(state: SecurityCaseState) -> dict[str, Any]: + response = interrupt( + { + "gate": "pmc_decision", + "case_key": state.get("case_key"), + "evidence_summary": state.get("evidence_summary"), + "inference_notes": state.get("inference_notes"), + "actor": state.get("actor"), + "preconditions": state.get("preconditions"), + "affected": state.get("affected"), + "instructions": ( + "Record the Apache Roller PMC decision on this report. " + "Use 'accept' to proceed to severity/CVE assessment, or " + "'reject' / 'duplicate' / 'wont-fix' to draft a closing response." + ), + "expected_resume_schema": { + "decision": "accept | reject | duplicate | wont-fix", + "target_release": "e.g. 7.0.0 (required when accepting)", + "owner": "PMC owner handle", + "verified_against": "optional git commit or tag", + "related": ["optional case_key list"], + "duplicates": ["optional case_key list"], + "shares_code_with": ["optional case_key list"], + "blocks": ["optional case_key list"], + }, + } + ) + payload = response if isinstance(response, dict) else {} + raw_decision = str(payload.get("decision", "reject")).strip().lower() + decision: Literal["accept", "reject", "duplicate", "wont-fix"] = ( + raw_decision if raw_decision in ("accept", "reject", "duplicate", "wont-fix") else "reject" # type: ignore[assignment] + ) + + updates: dict[str, Any] = { + "decision": decision, + "target_release": payload.get("target_release", state.get("target_release", "")), + "owner": payload.get("owner", state.get("owner", "")), + "verified_against": payload.get("verified_against", state.get("verified_against", "")), + "related": payload.get("related", state.get("related", [])), + "duplicates": payload.get("duplicates", state.get("duplicates", [])), + "shares_code_with": payload.get("shares_code_with", state.get("shares_code_with", [])), + "blocks": payload.get("blocks", state.get("blocks", [])), + "status": f"pmc_decision_{decision}", + "history": _append_history( + state, + "gate_pmc_decision", + f"decision={decision}, target_release={payload.get('target_release', '')}", + ), + } + _sync_store(state, overrides=updates, note=f"PMC decision recorded: {decision}") + return updates + + +def _route_after_pmc_decision(state: SecurityCaseState) -> Literal["accept", "close_rejected"]: + return "accept" if state.get("decision") == "accept" else "close_rejected" + + +# =========================================================================== +# Node 6: Tier 1 — Handle rejection / duplicate / wont-fix -> END +# =========================================================================== + + +def handle_rejection_node(state: SecurityCaseState) -> dict[str, Any]: + comms_ref = read_skill_ref(state["repo_dir"], "comms-templates.md") + decision = state.get("decision", "reject") + prompt = ( + f"Draft a clear, respectful Apache Roller PMC response closing this report as '{decision}'.\n\n" + f"Reference templates:\n{comms_ref[:4000]}\n\n" + f"Title: {state.get('title', '')}\n" + f"Reporter: {state.get('reporter', '')}\n" + f"Verified evidence: {state.get('evidence_summary', '')}\n" + f"Duplicates: {state.get('duplicates', [])}\n" + ) + + def _mock_reject_email() -> EmailDraft: + return EmailDraft( + subject=f"Re: Security report: {state.get('title', '')}", + body=( + f"Hello,\n\n" + f"Thank you again for your report. After reviewing the codebase, the Apache Roller PMC " + f"has concluded that this report will be closed as '{decision}'.\n\n" + f"Summary: {state.get('evidence_summary', 'Does not cross a Roller security boundary.')}\n\n" + f"Best regards,\nApache Roller PMC" + ), + ) + + draft, used = invoke_structured( + ModelTier.CHEAP, + EmailDraft, + prompt, + mock_llm=state.get("mock_llm", False), + mock_factory=_mock_reject_email, + local_llm_only=state.get("local_llm_only", False), + private_context=True, + ) + + updates: dict[str, Any] = { + "decision_email_draft": _format_email(draft), + "stage": "rejected", + "status": "closed_rejected", + "history": _append_history( + state, + "handle_rejection", + f"decision={decision}, model={used}", + stage="rejected", + ), + } + _sync_store( + state, + overrides=updates, + milestone="rejected", + milestone_status="done", + mark_na_exclude={"acknowledged", "investigating", "rejected"}, + note=f"Case closed as {decision}", + ) + return updates + + +# =========================================================================== +# Node 7: Tier 2 Severity & CVE form + Tier 1 Acceptance email +# =========================================================================== + + +def _render_cve_form_markdown(state: SecurityCaseState, assessment: SeverityAssessment) -> str: + return ( + f"# CVE Portal Draft — {state.get('case_key', '')}\n\n" + f"- **Title**: {assessment.cve_title}\n" + f"- **ASF Severity**: {assessment.asf_severity}\n" + f"- **CVSS**: {assessment.cvss_vector or 'N/A'} ({assessment.cvss_score or 'N/A'})\n" + f"- **Problem Type**: {assessment.cwe_problem_type}\n" + f"- **Affected Versions**: {state.get('affected', '')}\n" + f"- **Fixed In**: {state.get('target_release', '')}\n" + f"- **Credit**: {state.get('credit') or state.get('reporter', '')}\n\n" + f"## Description\n\n" + f"{assessment.cve_description}\n\n" + f"## Upgrade / Mitigation Guidance\n\n" + f"{assessment.upgrade_guidance or 'Upgrade to the fixed Apache Roller release.'}\n" + ) + + +def assess_severity_and_cve_node(state: SecurityCaseState) -> dict[str, Any]: + repo_dir = state["repo_dir"] + mock_llm = state.get("mock_llm", False) + local_only = state.get("local_llm_only", False) + + cve_ref = ( + read_skill_ref(repo_dir, "severity-and-cvss.md") + + "\n\n" + + read_skill_ref(repo_dir, "cve-portal.md") + ) + severity_prompt = ( + "Assess the ASF severity rating, optional CVSS vector/score, CWE problem type, " + "and draft the public ASF CVE portal description for this accepted Apache Roller vulnerability.\n\n" + f"Reference guide:\n{cve_ref[:5000]}\n\n" + f"Title: {state.get('title', '')}\n" + f"Actor: {state.get('actor', '')}\n" + f"Preconditions: {state.get('preconditions', '')}\n" + f"Affected: {state.get('affected', '')}\n" + f"Target release: {state.get('target_release', '')}\n" + f"Evidence: {state.get('evidence_summary', '')}\n" + ) + + def _mock_severity() -> SeverityAssessment: + target = state.get("target_release") or "7.0.0" + return SeverityAssessment( + asf_severity="moderate", + cvss_vector="CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", + cvss_score="5.4", + cwe_problem_type="CWE-20: Improper Input Validation", + cve_title=state.get("title") or "Improper Input Validation in Apache Roller", + cve_description=( + f"Improper input validation in Apache Roller ({state.get('affected', '<= 6.1.5')}) " + f"allows an authenticated user to trigger unintended behavior. " + f"Users are recommended to upgrade to Apache Roller {target}, which fixes the issue." + ), + upgrade_guidance=f"Upgrade to Apache Roller {target} or later.", + ) + + assessment, used_sev = invoke_structured( + ModelTier.FRONTIER, + SeverityAssessment, + severity_prompt, + mock_llm=mock_llm, + mock_factory=_mock_severity, + local_llm_only=local_only, + private_context=True, + ) + + cve_form_md = _render_cve_form_markdown(state, assessment) + + comms_ref = read_skill_ref(repo_dir, "comms-templates.md") + accept_prompt = ( + "Draft an Apache Roller PMC acceptance email notifying the reporter that their report " + "has been accepted, a CVE is being requested, and a fix is planned.\n\n" + f"Reference templates:\n{comms_ref[:4000]}\n\n" + f"Title: {state.get('title', '')}\n" + f"Severity: {assessment.asf_severity}\n" + f"Target release: {state.get('target_release', '')}\n" + ) + + def _mock_accept_email() -> EmailDraft: + return EmailDraft( + subject=f"Re: Security report: {state.get('title', '')}", + body=( + f"Hello,\n\n" + f"The Apache Roller PMC has confirmed and accepted your report as '{assessment.asf_severity}' severity. " + f"We are requesting a CVE identifier and preparing a fix targeted for Apache Roller " + f"{state.get('target_release') or 'the next release'}.\n\n" + f"Please let us know how you would like to be credited in the advisory.\n\n" + f"Best regards,\nApache Roller PMC" + ), + ) + + accept_draft, used_acc = invoke_structured( + ModelTier.CHEAP, + EmailDraft, + accept_prompt, + mock_llm=mock_llm, + mock_factory=_mock_accept_email, + local_llm_only=local_only, + private_context=True, + ) + + public_brief: PublicBrief = dict(state.get("public_brief") or {}) # type: ignore[assignment] + if assessment.upgrade_guidance: + public_brief["upgrade_guidance"] = assessment.upgrade_guidance + + updates: dict[str, Any] = { + "severity": assessment.asf_severity, + "cvss": assessment.cvss_vector, + "cvss_score": assessment.cvss_score, + "cve_form_markdown": cve_form_md, Review Comment: 🤖Claude: fixed by appending dated, generated sections below the templates: the investigation to `IMPLEMENTATION.md`, and the CVE draft to `CVE_FORM.md`, headed 'reconcile before using the portal'. Nothing is written in dry-run mode. ########## skills/roller-security/src/roller_security/markdown_views.py: ########## @@ -0,0 +1,357 @@ +# 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 +# +# https://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. + +"""Plain-Markdown (GFM) and terminal renderers for Roller security cases. + +Generated Markdown files are read-only projections of SQLite state and contain +zero Obsidian syntax (no emojis, no #roller-security tags, no ```tasks blocks). +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from roller_security.state import ALL_MILESTONES, PROGRESS_STAGES, TERMINAL_STAGES +from roller_security.store import derive_stage, stage_rank + +GENERATED_BANNER = "<!-- Generated from SQLite by roller-security; do not edit manually -->" +DISPLAY_STAGES: list[str] = PROGRESS_STAGES[:-1] + ["rejected", "complete"] + + +def _md_cell(value: Any) -> str: + if value is None: + return "-" + if isinstance(value, list): + text = ", ".join(str(item) for item in value if str(item).strip()) + else: + text = str(value).strip() + if not text: + return "-" + return text.replace("|", "\\|").replace("\n", " ") + + +def _term_cell(value: Any, width: int) -> str: + text = str(value or "-").strip() or "-" + if len(text) > width: + text = text[: width - 1] + "..." if width > 3 else text[:width] + return text.ljust(width) + + +def _next_open_milestone(case: dict[str, Any]) -> str | None: + milestones = case.get("milestones") or {} + stage = str(case.get("stage") or "").strip() or derive_stage(milestones) + if stage in TERMINAL_STAGES: + return None + for name in PROGRESS_STAGES[1:]: + info = milestones.get(name) + status = info.get("status", "open") if isinstance(info, dict) else "open" + if status == "open": + return name + return None + + +def render_case_markdown(case: dict[str, Any]) -> str: + """Render a single case as clean GitHub-Flavored Markdown.""" + milestones = case.get("milestones") or {} + stage = str(case.get("stage") or "").strip() or derive_stage(milestones) + case_key = str(case.get("case_key") or case.get("slug") or "case").strip() + title = str(case.get("title") or "").strip() + heading = f"# {case_key} -- {title}" if title else f"# {case_key}" + + lines: list[str] = [ + GENERATED_BANNER, + "", + heading, + "", + "> **PRIVATE.** Undisclosed vulnerability under the ASF security process. " + "Do not commit, paste into a public issue, or quote in a commit message.", + "", + "## Metadata", + "", + "| Field | Value |", + "| --- | --- |", + ] + + metadata_rows: list[tuple[str, Any]] = [ + ("Case key", case_key), + ("Case ID", case.get("case_id")), + ("Slug", case.get("slug")), + ("Stage", stage), + ("Owner", case.get("owner")), + ("Decision", case.get("decision")), + ("Severity", case.get("severity")), + ("CVSS", case.get("cvss")), + ("CVSS score", case.get("cvss_score")), + ("CVE ID", case.get("cve_id")), + ("Target release", case.get("target_release")), + ("Branch", case.get("branch")), + ("Fix commit", case.get("fix_commit")), + ("Tests", case.get("tests")), + ("Reporter", case.get("reporter")), + ("Reported on", case.get("reported_on")), + ("Forwarded on", case.get("forwarded_on")), + ("Thread URL", case.get("thread_url")), + ("Verified against", case.get("verified_against")), + ("Minimum actor", case.get("actor")), + ("Preconditions", case.get("preconditions")), + ("Affected", case.get("affected")), + ("Credit", case.get("credit")), + ("Announcement URL", case.get("announcement_url")), + ("Reporter deadline", case.get("reporter_deadline")), + ("Related", case.get("related")), + ("Duplicates", case.get("duplicates")), + ("Shares code with", case.get("shares_code_with")), + ("Blocks", case.get("blocks")), + ("Updated at", case.get("updated_at")), + ] + for label, value in metadata_rows: + lines.append(f"| {label} | {_md_cell(value)} |") + + lines.extend([ + "", + "## Milestones", + "", + "| Milestone | Status | Completed | Note |", + "| --- | --- | --- | --- |", + ]) + for name in ALL_MILESTONES: + info = milestones.get(name) if isinstance(milestones, dict) else None + status = info.get("status", "open") if isinstance(info, dict) else "open" + completed_on = info.get("completed_on") if isinstance(info, dict) else None + note = info.get("note", "") if isinstance(info, dict) else "" + lines.append( + f"| {name} | {_md_cell(status)} | {_md_cell(completed_on)} | {_md_cell(note)} |" + ) + + lines.extend(["", "## Blockers", ""]) + blocked_reason = str(case.get("blocked_reason") or "").strip() + deadline = str(case.get("reporter_deadline") or "").strip() + if blocked_reason or deadline: + if blocked_reason: + lines.append(f"- Blocked: {blocked_reason}") + if deadline: + lines.append(f"- Reporter deadline: {deadline}") + else: + lines.append("None.") + + lines.extend(["", "## Activity notes", ""]) + notes = case.get("activity_notes") or [] + if notes: + for entry in notes: + noted_on = str(entry.get("noted_on") or "").strip() + note_text = str(entry.get("note") or "").strip() + if not note_text: + continue + if noted_on: + lines.append(f"- {noted_on}: {note_text}") + else: + lines.append(f"- {note_text}") + else: + lines.append("None.") + + return "\n".join(lines) + "\n" + + +def write_case_markdown(case: dict[str, Any]) -> Path | None: + """Write <case_dir>/CASE.md if case_dir exists, returning the written path.""" + case_dir_raw = str(case.get("case_dir") or "").strip() + if not case_dir_raw: + return None + case_dir = Path(case_dir_raw) + if not case_dir.is_dir(): + return None + out_path = case_dir / "CASE.md" + out_path.write_text(render_case_markdown(case), encoding="utf-8") Review Comment: 🤖Claude: fixed by setting `os.umask(0o077)` in `main()`, which covers the database, the WAL/SHM files and everything the CLI writes. `CASE.md`, `SUMMARY_BOARD.md` and the copied templates are also chmod 0600, so they stay private when the graph runs from LangGraph Studio, and the case directory is created 0700. I checked the modes after a mock run. ########## skills/roller-security/src/roller_security/cli.py: ########## @@ -0,0 +1,263 @@ +# 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 +# +# https://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. + +"""CLI for managing Apache Roller security triage cases with LangGraph.""" + +from __future__ import annotations + +import argparse +import datetime +import json +import os +import sqlite3 +from pathlib import Path +from typing import Any + +from langgraph.checkpoint.sqlite import SqliteSaver +from langgraph.types import Command + +from roller_security.graph import build_security_case_graph +from roller_security.markdown_views import render_board_markdown, render_board_terminal +from roller_security.store import CaseStore, default_db_path + + +def _resolve_db(args: argparse.Namespace) -> Path: + if args.db: + db = Path(args.db).expanduser().resolve() + elif os.environ.get("ROLLER_SECURITY_DB"): + db = default_db_path() + elif getattr(args, "triage_dir", None): + db = Path(args.triage_dir).expanduser().resolve() / "cases.db" + else: + db = default_db_path() + db.parent.mkdir(parents=True, exist_ok=True) + return db + + +def _print_result(graph, thread_id: str) -> None: + cfg = {"configurable": {"thread_id": thread_id}} + snap = graph.get_state(cfg) + vals = snap.values or {} + + print(f"\n=== Thread: {thread_id} ===") + print(f"Case Key: {vals.get('case_key', 'unknown')}") + print(f"Stage: {vals.get('stage', 'unknown')}") + print(f"Status: {vals.get('status', 'unknown')}") + if vals.get("cve_id"): + print(f"CVE ID: {vals.get('cve_id')}") + if vals.get("target_release"): + print(f"Target Rel: {vals.get('target_release')}") + + if vals.get("workspace_report") and vals.get("status") in ("workspace_safe", "workspace_unsafe"): + print("\nWorkspace guard report:") + for line in vals["workspace_report"]: + print(f" {line}") + + interrupts = [] + for task in snap.tasks: + for intr in getattr(task, "interrupts", ()): + interrupts.append(intr.value) + + if interrupts: + print("\n--- PAUSED AT HUMAN GATE ---") + print(json.dumps(interrupts[0], indent=2)) + print(f"\nResume with:\n roller-security resume {thread_id} --json '<JSON payload>'") + elif not snap.next: + print("\n--- WORKFLOW FINISHED ---") + if vals.get("history"): + print("Execution trace:") + for item in vals["history"]: + print(f" [{item.get('stage', '-')}] {item.get('step')}: {item.get('detail')}") + + +def cmd_start(args: argparse.Namespace) -> None: + db = _resolve_db(args) + CaseStore(db) # Ensure case tables are initialized. + + repo_dir = str(Path(args.repo).resolve()) + triage_dir = str(Path(args.triage_dir).resolve()) + year = datetime.date.today().year + case_id = args.case_id + case_key = f"{year}-{case_id}-{args.slug}" + case_dir = str(Path(triage_dir) / case_key) + thread_id = args.thread_id or case_key + + raw_report_path = str(Path(args.report).resolve()) if args.report else "" + raw_report_text = "" + if raw_report_path and Path(raw_report_path).is_file(): + raw_report_text = Path(raw_report_path).read_text(encoding="utf-8") + + initial_state: dict[str, Any] = { + "db_path": str(db), + "repo_dir": repo_dir, + "triage_dir": triage_dir, + "case_dir": case_dir, + "case_key": case_key, + "case_id": case_id, + "slug": args.slug, + "owner": args.owner or "", + "decision": "pending", + "stage": "new", + "raw_report_path": raw_report_path, + "raw_report_text": raw_report_text, + "dry_run": args.dry_run, + "mock_llm": args.mock_llm, + "local_llm_only": args.local_llm, + "history": [], + } + + with SqliteSaver.from_conn_string(str(db)) as checkpointer: + graph = build_security_case_graph(checkpointer=checkpointer) + cfg = {"configurable": {"thread_id": thread_id}} + graph.invoke(initial_state, config=cfg) + _print_result(graph, thread_id) + + +def cmd_status(args: argparse.Namespace) -> None: + db = _resolve_db(args) + with SqliteSaver.from_conn_string(str(db)) as checkpointer: + graph = build_security_case_graph(checkpointer=checkpointer) + _print_result(graph, args.thread_id) + + +def cmd_resume(args: argparse.Namespace) -> None: + db = _resolve_db(args) + payload = json.loads(args.json) + with SqliteSaver.from_conn_string(str(db)) as checkpointer: + graph = build_security_case_graph(checkpointer=checkpointer) + cfg = {"configurable": {"thread_id": args.thread_id}} + graph.invoke(Command(resume=payload), config=cfg) + _print_result(graph, args.thread_id) + + +def cmd_board(args: argparse.Namespace) -> None: + db = _resolve_db(args) + store = CaseStore(db) + triage_dir = str(Path(args.triage_dir).resolve()) if args.triage_dir else None + cases = store.list_cases( + triage_dir=triage_dir, + target_release=args.release or None, + ) + warnings = store.check_consistency(cases) + if args.markdown: + print(render_board_markdown(cases, warnings)) + else: + print(render_board_terminal(cases, warnings, mine=args.mine or None)) + + +def cmd_export_briefs(args: argparse.Namespace) -> None: + db = _resolve_db(args) + store = CaseStore(db) + briefs = store.export_public_briefs(args.target_release) + print(json.dumps(briefs, indent=2)) + + +def cmd_graph(args: argparse.Namespace) -> None: + graph = build_security_case_graph().get_graph() + if args.format == "mermaid": + print(graph.draw_mermaid()) + elif args.format == "ascii": + print(graph.draw_ascii()) + elif args.format == "png": + out = Path(args.output or "roller-security-graph.png") + out.write_bytes(graph.draw_mermaid_png()) + print(f"Wrote {out.resolve()}") + + +def cmd_list(args: argparse.Namespace) -> None: + db = _resolve_db(args) + if not db.is_file(): + print(f"No security triage database yet at {db}") + return + conn = sqlite3.connect(str(db)) + try: + rows = conn.execute( + "SELECT DISTINCT thread_id FROM checkpoints ORDER BY thread_id" + ).fetchall() + except sqlite3.OperationalError: + rows = [] + finally: + conn.close() + if not rows: + print("No saved security triage threads.") + return + for (tid,) in rows: + print(tid) + + +def main() -> None: + p = argparse.ArgumentParser( + description="Apache Roller Security Triage Runner (LangGraph, Obsidian-free)" + ) + p.add_argument( + "--db", + help="Path to SQLite DB (default: <triage-dir>/cases.db when --triage-dir is given, else ~/.local/state/roller-security/cases.db)", + ) + sub = p.add_subparsers(dest="command", required=True) + + st_start = sub.add_parser("start", help="Start a new security triage workflow") + st_start.add_argument("--repo", required=True, help="Path to Apache Roller git checkout") + st_start.add_argument("--triage-dir", required=True, help="Path to private triage directory") + st_start.add_argument("--slug", required=True, help="Short neutral case slug (e.g. feed-parser)") + st_start.add_argument("--case-id", default="01", help="Two-digit case sequence ID (default: 01)") + st_start.add_argument("--owner", default="", help="PMC owner handle") + st_start.add_argument("--report", default="", help="Path to raw vulnerability report file") + st_start.add_argument("--dry-run", action="store_true", help="Do not modify repo, triage dir, or hit network") Review Comment: 🤖Claude: fixed by changing the help text: dry runs don't modify the repo or case files, but the case is still recorded in `cases.db`. SKILL.md says the same. Moving dry runs to an in-memory store would break `resume` across commands, which the mock walkthrough needs. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
