2222import re
2323import sys
2424from bisect import bisect_right
25+ from contextvars import ContextVar
2526
2627from skillspector .logging_config import get_logger
2728from skillspector .models import AnalyzerFinding , Location , Severity
28- from skillspector .python_ast import parse_python_source
29+ from skillspector .python_ast import ParsedPythonFile , parse_python_source , peek_python_ast
2930from skillspector .state import AnalyzerNodeResponse , SkillspectorState
3031
3132from . import static_runner
4546
4647ANALYZER_ID = "static_patterns_privilege_escalation"
4748
49+ # Scan-scoped handle on the runner's shared Python AST cache, published by
50+ # node() for the analyze() calls the runner makes on its behalf. This module
51+ # stays lexical (no USES_PYTHON_AST opt-in) so its windowed and normalized
52+ # views keep running; the constructed-path analysis below consults the shared
53+ # cache through this key instead of reparsing.
54+ _scan_python_ast_cache_key : ContextVar [str | None ] = ContextVar (
55+ "privilege_escalation_python_ast_cache_key" , default = None
56+ )
57+
4858PE1_CODE_PATTERNS = [
4959 (r"permissions?\s*:\s*\[?\s*['\"]?\*['\"]?\s*\]?" , 0.8 ),
5060 (
@@ -663,32 +673,71 @@ def _is_qualified_benign_access_requirement(
663673 return heading_index >= 0 and lines [heading_index ].strip () == "## Access Requirements"
664674
665675
666- # Cheap pre-check before parsing for constructed join calls: the AST walk
676+ # Cheap pre-check before walking for constructed join calls: the AST walk
667677# below is only worthwhile when the text plausibly contains a join() call.
668- # This keeps the module lexical (windowed and normalized-view scans keep
669- # working for every file type) while preserving the runner's parse-once
678+ # The gate covers spelling aliases collected from the imports (``from
679+ # os.path import join as j`` binds ``j`` to ``os.path.join``, so the call
680+ # site reads ``j(`` with no literal ``join`` in sight). Keeping the module
681+ # lexical plus this alias-aware gate preserves the runner's parse-once
670682# invariant for files without any join call.
671- _JOIN_CALL_HINT = re .compile (r"\bjoin\s*\(" )
683+ _JOIN_CALL_BASE_NAMES = {"join" }
684+ _JOIN_CALL_ALIAS_TARGETS = {"os.path" , "os.path.join" }
685+
686+
687+ def _join_call_hint (aliases : dict [str , str ]) -> re .Pattern [str ]:
688+ """Return a pre-check pattern matching ``join(`` and imported join aliases.
689+
690+ Every local name the file binds to ``os.path`` or ``os.path.join`` is a
691+ possible call spelling (``j(`` for ``from os.path import join as j``),
692+ alongside the plain ``join(`` used by ``os.path.join(``, ``p.join(``,
693+ and direct ``join(`` imports.
694+ """
695+ names = set (_JOIN_CALL_BASE_NAMES )
696+ for local , qualified in aliases .items ():
697+ if qualified in _JOIN_CALL_ALIAS_TARGETS :
698+ names .add (local )
699+ return re .compile (r"\b(?:" + "|" .join (sorted (re .escape (name ) for name in names )) + r")\s*\(" )
672700
673701
674- def _constructed_sensitive_paths (content : str , file_path : str ) -> list [tuple [int , str , float ]]:
702+ def _constructed_sensitive_paths (
703+ content : str ,
704+ file_path : str ,
705+ python_ast : ParsedPythonFile | None = None ,
706+ ) -> list [tuple [int , int , str , float ]]:
675707 """Return literal sensitive paths assembled with ``os.path.join`` in Python.
676708
709+ Each hit is a ``(start_line, end_line, path, confidence)`` tuple anchored
710+ to the call's source span so callers can deduplicate raw findings across
711+ the whole occurrence, including calls wrapped over several lines.
677712 Resolved from the Python AST so calls split across lines and supported
678713 import spellings (``import os.path as p``, ``from os.path import join``,
679- ``from os import path``) are recognized without reparsing tricks. Only
680- fully-literal positional argument lists are resolved; anything dynamic is
681- left to the existing pattern loop. Unparseable content simply yields no
682- findings here.
714+ ``from os.path import join as j``, ``from os import path``) are recognized
715+ without reparsing tricks. The scan's shared parse is reused whenever this
716+ runs inside the runner (the cache key published by node()); standalone
717+ callers get a single on-demand parse, while windowed view fragments under
718+ a scan are skipped because the shared tree only covers whole files.
719+ Only fully-literal positional argument lists are resolved; anything
720+ dynamic is left to the existing pattern loop. Unparseable content simply
721+ yields no findings here.
683722 """
684- if not _JOIN_CALL_HINT .search (content ):
685- return []
686- parsed = parse_python_source (content , file_path )
687- tree = parsed .tree
723+ if python_ast is None :
724+ cache_key = _scan_python_ast_cache_key .get ()
725+ if cache_key is not None :
726+ python_ast = peek_python_ast (cache_key , content , file_path )
727+ if python_ast is None :
728+ # A windowed view fragment, not the scan's whole file: the
729+ # shared tree does not cover it, and parsing fragments here
730+ # would break the runner's parse-once invariant.
731+ return []
732+ else :
733+ python_ast = parse_python_source (content , file_path )
734+ tree = python_ast .tree
688735 if tree is None :
689736 return []
690- aliases = parsed .import_aliases
691- resolved : list [tuple [int , str , float ]] = []
737+ aliases = python_ast .import_aliases
738+ if not _join_call_hint (aliases ).search (content ):
739+ return []
740+ resolved : list [tuple [int , int , str , float ]] = []
692741 for node in ast .walk (tree ):
693742 if not isinstance (node , ast .Call ):
694743 continue
@@ -702,12 +751,17 @@ def _constructed_sensitive_paths(content: str, file_path: str) -> list[tuple[int
702751 value = posixpath .join (* parts )
703752 for pattern , confidence in PE3_PATTERNS :
704753 if re .search (pattern , value , re .IGNORECASE ):
705- resolved .append ((node .lineno , value , confidence ))
754+ resolved .append ((node .lineno , node . end_lineno or node . lineno , value , confidence ))
706755 break
707756 return resolved
708757
709758
710- def analyze (content : str , file_path : str , file_type : str ) -> list [AnalyzerFinding ]:
759+ def analyze (
760+ content : str ,
761+ file_path : str ,
762+ file_type : str ,
763+ python_ast : ParsedPythonFile | None = None ,
764+ ) -> list [AnalyzerFinding ]:
711765 """Analyze content for privilege escalation patterns (PE1–PE5)."""
712766 findings : list [AnalyzerFinding ] = []
713767 line_starts , line_ends = _source_line_metadata (content )
@@ -857,26 +911,32 @@ def context_at(offset: int) -> str:
857911 )
858912 )
859913 if file_type == "python" :
860- for line_num , path , confidence in _constructed_sensitive_paths (content , file_path ):
914+ for start_line , end_line , path , confidence in _constructed_sensitive_paths (
915+ content , file_path , python_ast
916+ ):
861917 constructed = AnalyzerFinding (
862918 rule_id = "PE3" ,
863919 message = "Credential Access" ,
864920 severity = Severity .HIGH ,
865- location = loc (line_num ),
921+ location = loc (start_line ),
866922 confidence = confidence ,
867923 tags = list (tag ),
868- context = get_context (content , line_starts [line_num - 1 ]),
924+ context = get_context (content , line_starts [start_line - 1 ]),
869925 matched_text = path ,
870926 )
871927 # One PE3 per source occurrence: the pattern loop above may already
872- # have fired on this line's raw text (for example the literal
873- # '.ssh/id_rsa' inside the join call). Keep the best-confidence
874- # finding, mirroring the PE4/PE5 per-line aggregation below.
928+ # have fired inside the join call's line span (for example the
929+ # literal '.ssh/id_rsa' on a wrapped argument line, while this
930+ # finding anchors to the call's first line). Keep the
931+ # best-confidence finding per call span, mirroring the PE4/PE5
932+ # per-line aggregation below; unrelated occurrences on other
933+ # lines are preserved.
875934 duplicate = next (
876935 (
877936 existing
878937 for existing in findings
879- if existing .rule_id == "PE3" and existing .location .start_line == line_num
938+ if existing .rule_id == "PE3"
939+ and start_line <= existing .location .start_line <= end_line
880940 ),
881941 None ,
882942 )
@@ -1031,6 +1091,10 @@ def _is_negated_safety_constraint(
10311091
10321092def node (state : SkillspectorState ) -> AnalyzerNodeResponse :
10331093 """Run privilege_escalation patterns and return findings."""
1034- response = static_runner .run_static_patterns_with_ledger (state , [sys .modules [__name__ ]])
1094+ token = _scan_python_ast_cache_key .set (state .get ("python_ast_cache_key" ))
1095+ try :
1096+ response = static_runner .run_static_patterns_with_ledger (state , [sys .modules [__name__ ]])
1097+ finally :
1098+ _scan_python_ast_cache_key .reset (token )
10351099 logger .info ("%s: %d findings" , ANALYZER_ID , len (response ["findings" ]))
10361100 return response
0 commit comments