devsecpac 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,129 @@
1
+ """Autonomous stack and target repository discovery with single-pass filesystem traversal."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from typing import List, Dict, Set
6
+
7
+
8
+ class TargetDiscovery:
9
+ IGNORE_DIRS = {
10
+ ".git", "node_modules", ".venv", "venv", "__pycache__",
11
+ ".idea", ".vscode", "dist", "build", ".tox", ".mypy_cache",
12
+ ".pytest_cache", ".scannerwork", "target", ".egg-info"
13
+ }
14
+
15
+ LANG_PATTERNS = {
16
+ "nodejs": {"package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml"},
17
+ "python": {"requirements.txt", "pyproject.toml", "pipfile", "setup.py", "manage.py", "wsgi.py", "asgi.py"},
18
+ "java": {"pom.xml", "build.gradle", "build.gradle.kts"},
19
+ "golang": {"go.mod", "go.sum"},
20
+ "rust": {"cargo.toml", "cargo.lock"},
21
+ "dotnet": {".csproj", ".fsproj", ".sln"},
22
+ "dart": {"pubspec.yaml", "pubspec.lock"},
23
+ "php": {"composer.json", "composer.lock"},
24
+ "ruby": {"gemfile", "gemfile.lock"}
25
+ }
26
+
27
+ def __init__(self, target_dir: Path):
28
+ self.target_dir = target_dir.resolve()
29
+ self._cached = False
30
+ self._scannable_files: List[Path] = []
31
+ self._dockerfiles: List[Path] = []
32
+ self._k8s_manifests: List[Path] = []
33
+ self._iac_files: List[Path] = []
34
+ self._compose_files: List[Path] = []
35
+ self._detected_languages: Dict[str, List[str]] = {}
36
+
37
+ def is_git_repo(self) -> bool:
38
+ return (self.target_dir / ".git").is_dir()
39
+
40
+ def _traverse(self):
41
+ """Single-pass top-down os.walk to discover all artifacts in sub-second time."""
42
+ if self._cached:
43
+ return
44
+
45
+ scannable = []
46
+ dockerfiles = []
47
+ k8s = []
48
+ iac = []
49
+ compose = []
50
+ lang_matches: Dict[str, Set[str]] = {k: set() for k in self.LANG_PATTERNS}
51
+
52
+ for root, dirs, files in os.walk(str(self.target_dir)):
53
+ # Prune ignored directories in-place so os.walk does not traverse inside them
54
+ dirs[:] = [
55
+ d for d in dirs
56
+ if d not in self.IGNORE_DIRS and not d.endswith(".egg-info")
57
+ ]
58
+
59
+ for f in files:
60
+ fpath = Path(root) / f
61
+ scannable.append(fpath)
62
+ f_lower = f.lower()
63
+
64
+ # Dockerfiles
65
+ if f_lower == "dockerfile" or f_lower.startswith("dockerfile.") or f_lower.endswith(".dockerfile"):
66
+ dockerfiles.append(fpath)
67
+
68
+ # Compose files
69
+ if ("compose" in f_lower) and (f_lower.endswith(".yml") or f_lower.endswith(".yaml")):
70
+ compose.append(fpath)
71
+
72
+ # IaC files
73
+ if f_lower.endswith((".tf", ".tfvars", ".bicep")):
74
+ iac.append(fpath)
75
+
76
+ # Kubernetes manifests
77
+ if f_lower.endswith((".yml", ".yaml")):
78
+ try:
79
+ # Quick prefix read for k8s markers
80
+ with open(fpath, "r", encoding="utf-8", errors="ignore") as fh:
81
+ chunk = fh.read(4096)
82
+ if "apiVersion:" in chunk and "kind:" in chunk:
83
+ k8s.append(fpath)
84
+ except Exception:
85
+ pass
86
+
87
+ # Language runtime detection
88
+ for lang, patterns in self.LANG_PATTERNS.items():
89
+ if lang == "dotnet":
90
+ if any(f_lower.endswith(ext) for ext in patterns):
91
+ lang_matches[lang].add(f)
92
+ elif f_lower in patterns:
93
+ lang_matches[lang].add(f)
94
+
95
+ self._scannable_files = sorted(scannable)
96
+ self._dockerfiles = dockerfiles
97
+ self._k8s_manifests = k8s
98
+ self._iac_files = iac
99
+ self._compose_files = compose
100
+ self._detected_languages = {
101
+ lang: sorted(list(files))
102
+ for lang, files in lang_matches.items()
103
+ if files
104
+ }
105
+ self._cached = True
106
+
107
+ def discover_dockerfiles(self) -> List[Path]:
108
+ self._traverse()
109
+ return self._dockerfiles
110
+
111
+ def discover_k8s_manifests(self) -> List[Path]:
112
+ self._traverse()
113
+ return self._k8s_manifests
114
+
115
+ def discover_iac_files(self) -> List[Path]:
116
+ self._traverse()
117
+ return self._iac_files
118
+
119
+ def discover_compose_files(self) -> List[Path]:
120
+ self._traverse()
121
+ return self._compose_files
122
+
123
+ def detect_languages(self) -> Dict[str, List[str]]:
124
+ self._traverse()
125
+ return self._detected_languages
126
+
127
+ def discover_scannable_files(self) -> List[Path]:
128
+ self._traverse()
129
+ return self._scannable_files
@@ -0,0 +1,140 @@
1
+ """Universal Remote Git Ingestion Engine for devsecpac.
2
+
3
+ Securely clones any Git repository (GitHub, GitLab, Azure DevOps, Bitbucket, self-hosted)
4
+ via HTTPS or SSH with complete commit history across all branches without leaking credentials.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import shutil
10
+ import tempfile
11
+ import stat
12
+ from pathlib import Path
13
+ from typing import Optional, Tuple
14
+ from rich.console import Console
15
+ from .runner import ProcessRunner
16
+
17
+ console = Console()
18
+
19
+
20
+ class RepoIngestion:
21
+ def __init__(self, repo_url: str, token: Optional[str] = None, branch: Optional[str] = None, keep_repo: bool = False):
22
+ self.repo_url = repo_url.strip()
23
+ self.token = token or os.environ.get("GIT_TOKEN") or os.environ.get("GITHUB_TOKEN") or os.environ.get("AZURE_DEVOPS_EXT_PAT") or os.environ.get("GITLAB_TOKEN")
24
+ self.branch = branch
25
+ self.keep_repo = keep_repo
26
+ self.temp_dir: Optional[Path] = None
27
+
28
+ def clone_repository(self) -> Tuple[bool, Optional[Path], str]:
29
+ """
30
+ Clones the remote repository with full history across all branches.
31
+ Returns: (success: bool, target_path: Optional[Path], error_message: str)
32
+ """
33
+ git_bin = ProcessRunner.find_binary("git")
34
+ if not git_bin:
35
+ return False, None, "git executable not found in PATH"
36
+
37
+ # Create temporary isolated directory
38
+ self.temp_dir = Path(tempfile.mkdtemp(prefix="devsec_target_"))
39
+ clone_target = self.temp_dir / "repo"
40
+
41
+ console.print(f"[bold cyan]Ingesting Remote Repository:[/bold cyan] [bold white]{self.repo_url}[/bold white]")
42
+ if self.token:
43
+ console.print(" * Auth: [green]Secure Ephemeral Credential Helper (GIT_ASKPASS)[/green]")
44
+ else:
45
+ console.print(" * Auth: [yellow]Anonymous / SSH Agent Auth[/yellow]")
46
+
47
+ askpass_path: Optional[Path] = None
48
+ env = os.environ.copy()
49
+ # Strictly disable interactive terminal prompts across all Git/SSH operations
50
+ env["GIT_TERMINAL_PROMPT"] = "0"
51
+ env["GIT_SSH_COMMAND"] = "ssh -o BatchMode=yes"
52
+
53
+ try:
54
+ # Configure GIT_ASKPASS if token provided to prevent process table sniffing (ps aux)
55
+ if self.token:
56
+ askpass_path = self._create_askpass_helper(self.token)
57
+ env["GIT_ASKPASS"] = str(askpass_path)
58
+ env["DEVSEC_EPHEMERAL_PAT"] = self.token
59
+
60
+ # Full un-shallow clone command with all branches
61
+ clone_cmd = [
62
+ git_bin,
63
+ "clone",
64
+ "--no-single-branch", # Fetch all branches
65
+ self.repo_url,
66
+ str(clone_target)
67
+ ]
68
+
69
+ console.print(" * Fetching complete commit history (all branches & full depth)...")
70
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(clone_cmd, timeout=900, env=env)
71
+
72
+ if code != 0:
73
+ # Sanitized error message (strip token if inadvertently output)
74
+ sanitized_err = stderr
75
+ if self.token:
76
+ sanitized_err = sanitized_err.replace(self.token, "********")
77
+
78
+ auth_hint = ""
79
+ lower_err = sanitized_err.lower()
80
+ if "could not read password" in lower_err or "terminal prompts disabled" in lower_err or "authentication failed" in lower_err or "permission denied" in lower_err:
81
+ auth_hint = (
82
+ "\n\n[bold yellow]Authentication Required / Failed:[/bold yellow]\n"
83
+ "This repository is private or requires authentication.\n"
84
+ "Provide your token or PAT using one of the following methods:\n"
85
+ " 1. [bold cyan]--token <PAT_OR_PASSWORD>[/bold cyan]\n"
86
+ " Example: [dim]devsec scan -r \"<URL>\" --token \"YOUR_TOKEN_HERE\"[/dim]\n"
87
+ " 2. [bold cyan]Environment Variable:[/bold cyan]\n"
88
+ " Example: [dim]export GIT_TOKEN=\"YOUR_TOKEN_HERE\"[/dim] (or GITHUB_TOKEN / AZURE_DEVOPS_EXT_PAT)\n"
89
+ " 3. [bold cyan]SSH Key Auth:[/bold cyan]\n"
90
+ " Example: [dim]devsec scan -r \"git@ssh.dev.azure.com:v3/...\"[/dim] or [dim]\"git@github.com:...\"[/dim]"
91
+ )
92
+ return False, None, f"Git clone failed (exit {code}): {sanitized_err.strip()}{auth_hint}"
93
+
94
+ # Fetch all remote refs explicitly to guarantee full visibility
95
+ fetch_cmd = [git_bin, "fetch", "--all", "--tags"]
96
+ ProcessRunner.run_command(fetch_cmd, cwd=str(clone_target), timeout=300, env=env)
97
+
98
+ # If a specific branch was requested, checkout to it
99
+ if self.branch:
100
+ checkout_cmd = [git_bin, "checkout", self.branch]
101
+ ProcessRunner.run_command(checkout_cmd, cwd=str(clone_target), timeout=60, env=env)
102
+ console.print(f" * Switched to target branch: [bold cyan]{self.branch}[/bold cyan]")
103
+
104
+ console.print(f" * [bold green][OK][/bold green] Repository ingested successfully into: [dim]{clone_target}[/dim] ({elapsed}s)\n")
105
+ return True, clone_target, ""
106
+
107
+ except Exception as e:
108
+ return False, None, f"Unexpected ingestion error: {str(e)}"
109
+ finally:
110
+ # Clean up the askpass helper immediately
111
+ if askpass_path and askpass_path.exists():
112
+ askpass_path.unlink(missing_ok=True)
113
+
114
+ def cleanup(self):
115
+ """Scrubs the ingested repository unless keep_repo is set."""
116
+ if self.keep_repo:
117
+ console.print(f"[dim]Preserved cloned repository at: {self.temp_dir}[/dim]")
118
+ return
119
+
120
+ if self.temp_dir and self.temp_dir.exists():
121
+ try:
122
+ # Handle git read-only files on Windows/Linux during rmtree
123
+ def on_rm_error(func, path, exc_info):
124
+ os.chmod(path, stat.S_IWRITE)
125
+ func(path)
126
+
127
+ shutil.rmtree(self.temp_dir, onerror=on_rm_error)
128
+ except Exception:
129
+ pass
130
+
131
+ def _create_askpass_helper(self, token: str) -> Path:
132
+ """Creates an ephemeral executable script that provides the PAT to Git."""
133
+ if sys.platform == "win32":
134
+ helper_path = self.temp_dir / "askpass.bat"
135
+ helper_path.write_text(f"@echo {token}\n", encoding="utf-8")
136
+ else:
137
+ helper_path = self.temp_dir / "askpass.sh"
138
+ helper_path.write_text(f'#!/bin/sh\necho "$DEVSEC_EPHEMERAL_PAT"\n', encoding="utf-8")
139
+ helper_path.chmod(0o700)
140
+ return helper_path