Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-24
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Design

## Context

See `proposal.md` for background and rationale. Secret masking runs on source excerpts sent to model providers, error logs, and telemetry payloads. Currently, `CONST_CODE_EXEMPTION_RECEIVERS` checks 14 hardcoded identifiers on the LHS of dotted expressions, leading to incorrect masking in code and secret leakage in config.

## Goals / Non-Goals

**Goals:**
- Provide syntax-aware masking in `mask_secrets` via `syntax: Literal["code", "data"] = "data"`.
- In `code` syntax, preserve unquoted expressions composed of names, calls, or indexing.
- In `data` syntax, mask all assigned credential values.
- Completely remove `CONST_CODE_EXEMPTION_RECEIVERS`.
- Drop `<` from lookbehinds for GitHub and LLM token regexes.
- Update review and analysis single-file callers to pass the detected file syntax.

**Non-Goals:**
- Do not retain backward compatibility shims or keep `CONST_CODE_EXEMPTION_RECEIVERS`.
- Do not modify URL credential masking rules.
- Do not parse full ASTs during masking; regex with syntactic expression structure checks maintains high throughput.

## Decisions

### 1. Syntax parameter on `mask_secrets` defaulting to `data`
`mask_secrets` and `redact_text` take `syntax: Literal["code", "data"] = "data"`.
- *Rationale*: Callers handling error messages, logs, telemetry, and unclassified files default to `data`, guaranteeing aggressive secret masking without leakage.
- *Rejected Alternative*: Heuristic content sniffing inside `mask_secrets`. Rejected because detecting code vs data from arbitrary text snippets is unreliable and creates circular dependencies between `security` and `ai`.

### 2. Closed language set in `ai.analyze.scanner`
`ai.analyze.scanner` defines `CODE_LANGUAGES`, `syntax_from_language`, and `detect_syntax`.
- *Rationale*: The scanner owns the project's language taxonomy (`_EXT_LANG_FALLBACK`, `_MANIFEST_LANG_MAP`). Review callers import syntax detection from `scanner` and pass the resulting syntax to `mask_secrets`.
- *Rejected Alternative*: Defining language taxonomy in `devops_cli.security.sanitizer`. Rejected because `security` is a low-level foundation layer that should not duplicate scanner file classifications.

### 3. Pre-compiled pattern tables for syntax modes
`sanitizer.py` pre-compiles `_SECRET_PATTERNS_CODE` and `_SECRET_PATTERNS_DATA` (or parameterizes literal maskers) at module import time.
- *Rationale*: Pre-compiling static patterns avoids dynamic regex re-compilation or per-call function instantiation in high-volume masking loops.
- *Rejected Alternative*: Inspecting call stack or dynamic global state. Rejected because global state is thread-unsafe and violates hermetic execution.

### 4. Remove `<` from lookbehinds
Drop `<` from `(?<![A-Za-z0-9_<])` and `(?<![a-zA-Z0-9/\\<])`.
- *Rationale*: Tokens enclosed in angle brackets (`<ghs_...>`) must be masked. Existing length quantifiers (`{10,}`, `{36,}`, `{19,}`) ensure placeholders like `<ghp_token>` remain intact.
- *Rejected Alternative*: Adding separate regexes for bracketed tokens. Rejected because removing `<` from the negative lookbehind addresses the root cause directly without regex duplication.

## Risks / Trade-offs

- [Risk] Unquoted identifier in code syntax could be a hardcoded credential. → Mitigation: Hardcoded credentials in source code are typically string literals (quoted) or numeric, which are masked. Unquoted identifiers represent variables, constants, or attributes that reviewers need to inspect.
- [Risk] Review callers failing to pass syntax. → Mitigation: Default `data` syntax masks strictly, ensuring no sensitive data leaks if a caller omits the argument.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Proposal

## Why

Issue #889 shows that `mask_secrets` distinguishes code expressions from credential literals using an arbitrary receiver allowlist (`CONST_CODE_EXEMPTION_RECEIVERS`). This causes false redactions in valid code expressions (`password=cfg.db_password`) and leaks secrets in configuration files (`password=settings.Hunter22` in an env file). In addition, token patterns containing `<` in lookbehinds fail to mask tokens in bracketed contexts (`<ghs_...>`).

## What Changes

This change replaces receiver-name filtering with syntax-aware secret masking:
- `mask_secrets` accepts a `syntax` parameter (`code` vs `data`, defaulting to `data`).
- In `code` syntax, unquoted right-hand side expressions consisting of names, calls, or indexing are preserved as code. In `data` syntax, credential assignments are unconditionally masked.
- `ai.analyze.scanner` defines programming language classification (`syntax_from_language`, `detect_syntax`) mapping scanner languages to `code` or `data`.
- Review callers (`review.analysis`, `ai.review.cited_code`, `ai.analyze.outlines`) detect and pass file syntax per reviewed file.
- Delete `CONST_CODE_EXEMPTION_RECEIVERS` from constants and sanitizer logic.
- Drop `<` from lookbehinds for GitHub tokens and OpenAI / Anthropic key patterns while preserving length bounds, ensuring tokens in brackets are masked while placeholders remain intact.

This change fits one pull request.

## Capabilities

### New Capabilities
- `secret-masking`: Mask credentials and secret patterns in source code excerpts, logs, and telemetry based on file syntax.

### Modified Capabilities
None.

## Impact

- Security sanitizer: Updates `mask_secrets`, `redact_text`, and `mask_dict_secrets` signatures and literal masking logic.
- Config constants: Deletes `CONST_CODE_EXEMPTION_RECEIVERS`.
- File analysis: Adds syntax detection helpers in `devops_cli.ai.analyze.scanner`.
- Review pipeline & analysis: Single-file review callers pass file syntax into `mask_secrets`.

## Feasibility

I confirmed the premise against the real system:
- Verified `mask_secrets("password=cfg.db_password")` currently masks `password=<masked-password>` because `cfg` is not in `CONST_CODE_EXEMPTION_RECEIVERS`.
- Verified `mask_secrets("password=settings.Hunter22")` currently fails to mask `settings.Hunter22` because `settings` is in `CONST_CODE_EXEMPTION_RECEIVERS`.
- Verified `<ghs_...>` installation tokens are unmasked due to `(?<![A-Za-z0-9_<])` lookbehinds in `_SECRET_PATTERNS`.
- Verified `detect_language` in `ai/analyze/scanner.py` reliably identifies `.py` as `python` and `.env` as `env`.

## Existing Tool Considered

Libraries such as TruffleHog and detect-secrets do not support context-sensitive in-flight redaction for AST / LLM prompt construction with syntax distinction between programming languages and configuration files. Building syntax-aware masking internally requires approximately 80 lines of code, 3,500 tokens of agent context, and 15 minutes of elapsed time. This change deletes `CONST_CODE_EXEMPTION_RECEIVERS` and eliminates arbitrary identifier lists.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Spec Delta

## Purpose

Masks credentials and secret patterns in source code excerpts, configuration files, and telemetry payloads based on syntactic context.

## ADDED Requirements

### Requirement: Syntax-aware secret masking
The secret masking system SHALL evaluate assignments against the syntax of the input text, preserving unquoted code expressions in programming language files and masking assigned credential values in data and configuration files.

#### Scenario: Unquoted expression in code syntax
- **WHEN** secret masking processes an unquoted right-hand side expression such as `password=cfg.db_password` with code syntax
- **THEN** the expression remains unmasked as written

#### Scenario: Dotted identifier in data syntax
- **WHEN** secret masking processes a dotted assignment such as `password=settings.Hunter22` with data syntax
- **THEN** the value is masked with `password=<masked-password>`

#### Scenario: Default masking syntax
- **WHEN** secret masking processes text without an explicit syntax argument
- **THEN** the text is processed using data syntax and credentials are unconditionally masked

### Requirement: Token masking in bracketed boundaries
The secret masking system SHALL detect and mask GitHub tokens, Anthropic API keys, and OpenAI API keys when enclosed in angle brackets, while preserving short documentation placeholders.

#### Scenario: Real token inside angle brackets
- **WHEN** secret masking encounters `<ghs_...>` or `<sk-proj-...>` with valid token length
- **THEN** the token within the brackets is redacted with the corresponding masked token indicator

#### Scenario: Placeholder inside angle brackets
- **WHEN** secret masking encounters a shortened placeholder such as `<ghp_token>`
- **THEN** the text is left unmodified
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Tasks

## 1. Syntax-aware secret masking core and token lookbehinds

- [x] 1.1 Add failing tests for syntax-aware secret masking (`cfg.db_password` in code vs data, `settings.Hunter22` in code vs data), enclosed bracket tokens (`<ghs_...>`, `<sk-...>`) and placeholder preservation (`<ghp_token>`), and verify with `uv run devops ci test tests/test_consolidation_security_sanitizer.py`.
- [x] 1.2 Implement syntax-aware masking in `src/devops_cli/security/sanitizer.py`, delete `CONST_CODE_EXEMPTION_RECEIVERS` from `src/devops_cli/config/constants.py` and `sanitizer.py`, remove `<` from lookbehinds in `_SECRET_PATTERNS`, and verify with `uv run devops ci test tests/test_consolidation_security_sanitizer.py` and `grep -rn CONST_CODE_EXEMPTION_RECEIVERS src tests`.
- [x] 1.3 Regenerate documentation with `uv run devops docs generate --sync-readme`.

## 2. Review and analysis callers integration

- [x] 2.1 Add failing tests for file syntax detection and multi-file review masking across Python and env files without a model, and verify with `uv run devops ci test tests/test_review_syntax_masking.py`.
- [x] 2.2 Add `CODE_LANGUAGES`, `syntax_from_language`, and `detect_syntax` in `src/devops_cli/ai/analyze/scanner.py`, wire syntax into `src/devops_cli/review/analysis.py`, `src/devops_cli/ai/review/cited_code.py`, and `src/devops_cli/ai/analyze/outlines.py`, and verify with `uv run devops ci test tests/test_review_syntax_masking.py`.
- [x] 2.3 Regenerate documentation with `uv run devops docs generate --sync-readme`.

## Workflow follow-up

- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD).
32 changes: 32 additions & 0 deletions openspec/specs/secret-masking/spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# secret-masking Specification

## Purpose
Masks credentials and secret patterns in source code excerpts, configuration files, and telemetry payloads based on syntactic context.

## Requirements

### Requirement: Syntax-aware secret masking
The secret masking system SHALL evaluate assignments against the syntax of the input text, preserving unquoted code expressions in programming language files and masking assigned credential values in data and configuration files.

#### Scenario: Unquoted expression in code syntax
- **WHEN** secret masking processes an unquoted right-hand side expression such as `password=cfg.db_password` with code syntax
- **THEN** the expression remains unmasked as written

#### Scenario: Dotted identifier in data syntax
- **WHEN** secret masking processes a dotted assignment such as `password=settings.Hunter22` with data syntax
- **THEN** the value is masked with `password=<masked-password>`

#### Scenario: Default masking syntax
- **WHEN** secret masking processes text without an explicit syntax argument
- **THEN** the text is processed using data syntax and credentials are unconditionally masked

### Requirement: Token masking in bracketed boundaries
The secret masking system SHALL detect and mask GitHub tokens, Anthropic API keys, and OpenAI API keys when enclosed in angle brackets, while preserving short documentation placeholders.

#### Scenario: Real token inside angle brackets
- **WHEN** secret masking encounters `<ghs_...>` or `<sk-proj-...>` with valid token length
- **THEN** the token within the brackets is redacted with the corresponding masked token indicator

#### Scenario: Placeholder inside angle brackets
- **WHEN** secret masking encounters a shortened placeholder such as `<ghp_token>`
- **THEN** the text is left unmodified
6 changes: 6 additions & 0 deletions src/devops_cli/ai/analyze/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,22 @@
)
from devops_cli.ai.analyze.outlines import analyze_single_file
from devops_cli.ai.analyze.scanner import (
CODE_LANGUAGES,
detect_language,
detect_syntax,
sanitize_reference,
scan_directory,
syntax_from_language,
)

__all__ = [
"CODE_LANGUAGES",
"analyze_single_file",
"detect_language",
"detect_syntax",
"load_cached_analysis",
"sanitize_reference",
"save_analysis_metadata",
"scan_directory",
"syntax_from_language",
]
11 changes: 7 additions & 4 deletions src/devops_cli/ai/analyze/outlines.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
_extract_file_purpose,
_extract_file_symbols,
detect_language,
syntax_from_language,
)
from devops_cli.ai.personas import (
ANALYZE_PSEUDOCODE_SYSTEM_PROMPT,
Expand Down Expand Up @@ -74,11 +75,11 @@ def _validate_enhanced_metadata(
return parsed, None


def _mask_sensitive_data(text: str) -> str:
def _mask_sensitive_data(text: str, syntax: str = "data") -> str:
"""Mask credentials and secrets before transmitting code to external LLM services."""
from devops_cli.security.sanitizer import mask_secrets

return mask_secrets(text)
return mask_secrets(text, syntax=syntax)


def _enhance_file_metadata_with_ai(
Expand All @@ -94,7 +95,7 @@ def _enhance_file_metadata_with_ai(
from devops_cli.ai.review_schema import extract_json_block
from devops_cli.models.ai import ChatMessage

sanitized_content = _mask_sensitive_data(content[:150000])
sanitized_content = _mask_sensitive_data(content[:150000], syntax=syntax_from_language(lang))
rag_context = ""
try:
from devops_cli.ai.rag.investigator import (
Expand Down Expand Up @@ -300,7 +301,9 @@ def _generate_ai_pseudocode(
)
from devops_cli.models.ai import ChatMessage

sanitized_content = _mask_sensitive_data(content[:150000])
sanitized_content = _mask_sensitive_data(
content[:150000], syntax=syntax_from_language(lang)
)
rag_ctx = investigate_rag_context(f"{rel_path} {' '.join(symbols[:3])}", top_k=2)
rag_info = format_rag_investigation_for_prompt(rag_ctx, "Interface & Module Context")

Expand Down
39 changes: 38 additions & 1 deletion src/devops_cli/ai/analyze/scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import re
import sys
from pathlib import Path
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Literal

from devops_cli.ai.ast.engine import _header_language
from devops_cli.config.defaults import (
Expand Down Expand Up @@ -231,6 +231,43 @@ def detect_language(filepath: Path | str, content: str | None = None) -> str:
return _EXT_LANG_FALLBACK.get(ext, "plaintext")


CODE_LANGUAGES: frozenset[str] = frozenset(
{
"bash",
"c",
"cpp",
"csharp",
"go",
"java",
"javascript",
"kotlin",
"lua",
"php",
"powershell",
"python",
"ruby",
"rust",
"scala",
"shell",
"swift",
"tsx",
"typescript",
}
)


def syntax_from_language(lang: str | None) -> Literal["code", "data"]:
"""Return whether a detected language has 'code' or 'data' syntax."""
if not lang:
return "data"
return "code" if lang.strip().lower() in CODE_LANGUAGES else "data"


def detect_syntax(filepath: Path | str, content: str | None = None) -> Literal["code", "data"]:
"""Detect whether a file path has 'code' or 'data' syntax based on its language."""
return syntax_from_language(detect_language(filepath, content))


def _extract_ast_symbols(body: list[ast.stmt]) -> list[str]:
"""Extract class, function, and constant symbol names from Python AST body."""
symbols: list[str] = []
Expand Down
4 changes: 3 additions & 1 deletion src/devops_cli/ai/review/cited_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from collections.abc import Callable, Iterable
from pathlib import Path

from devops_cli.ai.analyze.scanner import detect_syntax
from devops_cli.ai.review_schema import CitedCode, DefectClass, SavedFinding, _parse_location
from devops_cli.config.defaults import (
DEFAULT_CITED_EXCERPT_MAX_LINES,
Expand Down Expand Up @@ -41,11 +42,12 @@ def cited_code(location: str, file_path: Path, checkout: Path) -> CitedCode | No
if start > len(lines):
return None
last = min(end or start, len(lines), start + DEFAULT_CITED_EXCERPT_MAX_LINES - 1)
syntax = detect_syntax(resolved)
return CitedCode(
project=main_worktree_root(root).name,
file=resolved.relative_to(root).as_posix(),
line=start,
excerpt=mask_secrets("\n".join(lines[start - 1 : last])),
excerpt=mask_secrets("\n".join(lines[start - 1 : last]), syntax=syntax),
)


Expand Down
20 changes: 0 additions & 20 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -4474,26 +4474,6 @@ class WebhookExposure(StrEnum):
# to prevent resource exhaustion and unbounded range vectors (CWE-400).
CONST_MAX_PROMETHEUS_WINDOW_SECONDS: Final[int] = 30 * 86400

# Receiver objects and prefixes permitted for code expression exemptions in secret masking.
CONST_CODE_EXEMPTION_RECEIVERS: Final[frozenset[str]] = frozenset(
{
"req",
"request",
"res",
"response",
"params",
"props",
"self",
"this",
"process",
"config",
"settings",
"context",
"ctx",
"session",
}
)

# No library finds arbitrary URLs embedded inside prose. linkify-it-py 2.2.0
# misses non-http schemes (mysql://, postgres://) and fails on passwords with '@'.
# Candidate URLs are located by RFC 3986 scheme grammar capped at 32 chars and
Expand Down
4 changes: 3 additions & 1 deletion src/devops_cli/review/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from pydantic import ValidationError as PydanticValidationError

from devops_cli.ai.analyze.scanner import detect_syntax
from devops_cli.ai.client.models import ReplyRejectedError
from devops_cli.ai.kb import (
DriftManual,
Expand Down Expand Up @@ -511,11 +512,12 @@ def _build_anchor_excerpt(
start_idx = max(1, line_no - context_lines)
end_idx = min(len(lines), end_no + context_lines)
raw_slice = "\n".join(lines[start_idx - 1 : end_idx])
syntax = detect_syntax(finding.path, content)
return AnchorExcerpt(
path=finding.path,
start_line=start_idx,
end_line=end_idx,
excerpt=mask_secrets(raw_slice),
excerpt=mask_secrets(raw_slice, syntax=syntax),
)


Expand Down
Loading
Loading