Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(analysis): track brace depth in C# interpolated strings during masking (#4625)

ANO34572d504be026c7
diff --git a/packages/core/src/repowise/core/analysis/security/masking.py b/packages/core/src/repowise/core/analysis/security/masking.py
index 329c5589a..7d147ad59 100644
--- a/packages/core/src/repowise/core/analysis/security/masking.py
+++ b/packages/core/src/repowise/core/analysis/security/masking.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import re
+from typing import Any
# Where each masking state can change. Every other character keeps the state,
# so the scan jumps from one of these to the next instead of walking each one.
@@ -14,6 +15,8 @@ _STRING_STOP = {
_NOT_NEWLINE = re.compile(r"[^\n]")
_BLOCK_STOP = re.compile(r"/\*|\*/")
_RAW_BACKTICK_STOP = re.compile("`")
+_INTERPOLATED_STOP = re.compile(r'[{}"\\]')
+_INTERPOLATED_VERBATIM_STOP = re.compile(r'[{}]|"')
# Languages whose block comments nest, and Go, whose backtick string is raw: a
# backslash there is a character, not an escape.
_NESTED_COMMENT_SUFFIXES = (".kt", ".kts", ".scala", ".sc", ".swift", ".rs", ".dart")
@@ -74,7 +77,8 @@ def mask_comments_and_strings(
state = "code"
quote = ""
triple = False
- template_depth = 0
+ verbatim = False
+ stack: list[dict[str, Any]] = []
while i < size:
if state == "line_comment":
stop = source.find("\n", i)
@@ -103,24 +107,105 @@ def mask_comments_and_strings(
i = stop
if match is not None and match.group() != "\\":
state = "code"
- template_depth = 1 if match.group() == "${" else template_depth
+ if match.group() == "${":
+ stack.append({"kind": "template", "depth": 1})
continue
+ if state == "interpolated":
+ pattern = _INTERPOLATED_VERBATIM_STOP if verbatim else _INTERPOLATED_STOP
+ match = pattern.search(source, i)
+ if match is None:
+ if strings:
+ blank(i, size)
+ break
+ matched = match.group()
+ pos = match.start()
+ if matched == "\\":
+ stop = min(match.end() + 1, size)
+ if strings:
+ blank(i, stop)
+ i = stop
+ continue
+ if matched == "{":
+ if source.startswith("{{", pos):
+ stop = pos + 2
+ if strings:
+ blank(i, stop)
+ i = stop
+ continue
+ stop = pos + 1
+ if strings:
+ blank(i, stop)
+ i = stop
+ stack.append(
+ {
+ "kind": "interpolated",
+ "depth": 1,
+ "quote": quote,
+ "triple": triple,
+ "verbatim": verbatim,
+ }
+ )
+ state = "code"
+ continue
+ if matched == "}":
+ if source.startswith("}}", pos):
+ stop = pos + 2
+ if strings:
+ blank(i, stop)
+ i = stop
+ continue
+ stop = pos + 1
+ if strings:
+ blank(i, stop)
+ i = stop
+ continue
+ if matched == quote:
+ if triple:
+ if source.startswith(quote * 3, pos):
+ stop = pos + 3
+ if strings:
+ blank(i, stop)
+ i = stop
+ state = "code"
+ continue
+ stop = pos + 1
+ if strings:
+ blank(i, stop)
+ i = stop
+ continue
+ if verbatim and source.startswith(quote * 2, pos):
+ stop = pos + 2
+ if strings:
+ blank(i, stop)
+ i = stop
+ continue
+ stop = pos + 1
+ if strings:
+ blank(i, stop)
+ i = stop
+ state = "code"
+ continue
+
match = _CODE_STOP.search(source, i)
if match is None:
break
i = match.start()
char = source[i]
- if template_depth and char == "{":
- template_depth += 1
+ if stack and char == "{":
+ stack[-1]["depth"] += 1
i += 1
- elif template_depth and char == "}":
+ elif stack and char == "}":
if strings:
blank(i, i + 1)
- template_depth -= 1
+ stack[-1]["depth"] -= 1
i += 1
- if template_depth == 0:
- state = "template"
+ if stack[-1]["depth"] == 0:
+ frame = stack.pop()
+ state = frame["kind"]
+ quote = frame.get("quote", "")
+ triple = frame.get("triple", False)
+ verbatim = frame.get("verbatim", False)
elif (hash_comments and char == "#") or source.startswith("//", i):
width = 1 if char == "#" else 2
blank(i, i + width)
@@ -139,10 +224,18 @@ def mask_comments_and_strings(
quote = char
triple = source.startswith(quote * 3, i)
width = 3 if triple else 1
+ is_interpolated = False
+ verbatim = False
+ if char == '"' and i > 0:
+ if source.endswith(("$@", "@$"), 0, i):
+ is_interpolated = True
+ verbatim = True
+ elif source.endswith("$", 0, i):
+ is_interpolated = True
if strings:
blank(i, i + width)
i += width
- state = "string"
+ state = "interpolated" if is_interpolated else "string"
else:
i += 1
out.append(source[copied:])
diff --git a/tests/unit/analysis/test_security_scan.py b/tests/unit/analysis/test_security_scan.py
index acaddea51..c8882226b 100644
--- a/tests/unit/analysis/test_security_scan.py
+++ b/tests/unit/analysis/test_security_scan.py
@@ -1723,3 +1723,61 @@ class TestNoAlarmOnCodeThatDoesNotShip:
from repowise.core.analysis.security_scan import mask_comments_and_strings
assert mask_comments_and_strings("a /* b /* c */ d */ e", **options) == masked
+
+ def test_csharp_interpolated_string_quotes_inside_hole_are_masked(self) -> None:
+ from repowise.core.analysis.security.masking import mask_comments_and_strings, mask_dialect
+
+ src = 'var u = $"{b}items/by?ids={string.Join("&ids=", ids)}";\nvar x = 1;\n'
+ masked = mask_comments_and_strings(
+ src, strings=True, hash_comments=False, **mask_dialect("a.cs")
+ )
+ assert masked == "var u = $ b string.Join( , ids) ;\nvar x = 1;\n"
+ assert (
+ mask_comments_and_strings(
+ src, strings=False, hash_comments=False, **mask_dialect("a.cs")
+ )
+ == src
+ )
+
+ def test_csharp_interpolated_string_comment_inside_hole_does_not_mask_line(self) -> None:
+ from repowise.core.analysis.security.masking import mask_comments_and_strings, mask_dialect
+
+ src = 'var u = $"{b}items/by?ids={string.Join("//x", ids)}";\nvar x = 1;\n'
+ masked = mask_comments_and_strings(
+ src, strings=True, hash_comments=False, **mask_dialect("a.cs")
+ )
+ assert masked == "var u = $ b string.Join( , ids) ;\nvar x = 1;\n"
+
+ def test_csharp_interpolated_string_verbatim_and_escaped_braces(self) -> None:
+ from repowise.core.analysis.security.masking import mask_comments_and_strings, mask_dialect
+
+ src = 'var u = $@"c:\\dir\\{sub}\""name""";\nvar x = 1;\n'
+ masked = mask_comments_and_strings(
+ src, strings=True, hash_comments=False, **mask_dialect("a.cs")
+ )
+ assert masked == "var u = $@ sub ;\nvar x = 1;\n"
+
+ src_braces = 'var u = $"escaped {{literal}} and {hole}";\n'
+ masked_braces = mask_comments_and_strings(
+ src_braces, strings=True, hash_comments=False, **mask_dialect("a.cs")
+ )
+ assert masked_braces == "var u = $ hole ;\n"
+
[email protected]("prefix", ["$@", "@$"])
[email protected]("strings", [False, True])
+def test_verbatim_interpolation_trailing_backslash_preserves_following_code(prefix, strings):
+ from repowise.core.analysis.security.masking import mask_dialect
+ from repowise.core.analysis.security_scan import mask_comments_and_strings
+
+ literal = r'"c:\dir\"'
+ source = f"var p = {prefix}{literal}; DangerousCall(); // real comment\nNext();\n"
+ masked = mask_comments_and_strings(
+ source, strings=strings, hash_comments=False, **mask_dialect("a.cs")
+ )
+ expected_literal = " " * len(literal) if strings else literal
+ assert masked == (
+ f"var p = {prefix}{expected_literal}; DangerousCall(); "
+ + " " * len("// real comment")
+ + "\nNext();\n"
+ )
+ assert len(masked) == len(source)