Skip to content
Open
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
12 changes: 7 additions & 5 deletions atdork.py
Original file line number Diff line number Diff line change
Expand Up @@ -1931,7 +1931,7 @@ def env_cli(argv: List[str]) -> int:
env = create_env(args_.path, name=args_.name, force=args_.force)
console.print(f"[green]✔ Environment ready:[/green] {env.root}")
for key, value in env.describe_paths().items():
console.print(f" [dim]{key:8}[/dim] {value}")
console.print(f" [dim]{key:8}[/dim]", value, soft_wrap=True)
console.print(
f"\n[dim]Use it:[/dim] atdork --env {env.root} -q \"...\" "
f"[dim]or set as default:[/dim] atdork env use {env.root}"
Expand All @@ -1951,7 +1951,7 @@ def env_cli(argv: List[str]) -> int:
tags += " [green](active)[/green]"
if Env.at(root) is None:
tags += " [red](missing)[/red]"
console.print(f" {root}{tags}")
console.print(f" {root}", markup=False, soft_wrap=True)
return 0

if args_.action == "use":
Expand All @@ -1963,7 +1963,8 @@ def env_cli(argv: List[str]) -> int:
f"atdork env create {args_.path}"
)
set_active_env(env.root)
console.print(f"[green]✔ Active environment:[/green] {env.root}")
console.print("[green]✔ Active environment:[/green]", env.root,
markup=False, soft_wrap=True)
return 0

if args_.action == "which":
Expand All @@ -1972,8 +1973,9 @@ def env_cli(argv: List[str]) -> int:
console.print("[yellow]No environment active.[/yellow] "
"(--env, ATDORK_ENV, or 'atdork env use <path>')")
return 0
console.print(f"[green]✔ Environment:[/green] {env.root}"
+ (f" [dim]({env.name})[/dim]" if env.name else ""))
console.print("[green]✔ Environment:[/green]", env.root,
f"({env.name})" if env.name else "",
markup=False, soft_wrap=True)
for key, value in env.describe_paths().items():
console.print(f" [dim]{key:8}[/dim] {value}")
return 0
Expand Down
4 changes: 3 additions & 1 deletion core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,9 @@ def _discover_paths(filepath: Optional[str],
if filepath is None:
filepath = os.environ.get("ATDORK_CONFIG") or None

global_dir = os.path.join(os.path.expanduser("~"), ".config", "atdork")
home_override = os.environ.get("HOME") or os.environ.get("USERPROFILE")
home_dir = home_override if home_override else os.path.expanduser("~")
global_dir = os.path.join(home_dir, ".config", "atdork")
for name in _GLOBAL_CANDIDATES:
candidate = os.path.join(global_dir, name)
if os.path.isfile(candidate):
Expand Down
8 changes: 7 additions & 1 deletion core/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@
REGISTRY_FILENAME = "environments.yml"


def user_home() -> Path:
"""Resolve the user's home consistently across platforms and test environments."""
override = os.environ.get("HOME") or os.environ.get("USERPROFILE")
return Path(override).expanduser() if override else Path.home()


class EnvError(Exception):
"""Environment resolution/creation problem (bad root, missing marker)."""

Expand All @@ -70,7 +76,7 @@ class EnvEscapeError(EnvError):
# ── Registry ───────────────────────────────────────────────────────────────

def registry_path() -> Path:
return Path.home() / ".config" / "atdork" / REGISTRY_FILENAME
return user_home() / ".config" / "atdork" / REGISTRY_FILENAME


def read_registry() -> Dict[str, Any]:
Expand Down
23 changes: 21 additions & 2 deletions core/external.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ def looks_like_url(spec: str) -> bool:


def _is_raw_py_url(url: str) -> bool:
if url.lower().startswith("file://"):
raw_path = url[len("file://"):].split("#", 1)[0]
return raw_path.lower().endswith(".py")
path = urllib.parse.urlsplit(url).path
return path.lower().endswith(".py")

Expand Down Expand Up @@ -111,7 +114,19 @@ def _download(url: str) -> bytes:
"""Fetch a single module: ``file://`` reads the path, http(s) downloads it."""
parts = urllib.parse.urlsplit(url)
if parts.scheme in ("", "file"):
path = Path(urllib.request.url2pathname(parts.path))
if os.name == "nt" and url.lower().startswith("file://"):
raw_path = url[len("file://"):].replace("/", "\\")
if raw_path.startswith("\\") and not re.match(r"^\\\\[A-Za-z]:", raw_path):
raw_path = raw_path.lstrip("\\")
file_path = raw_path
elif parts.scheme == "file" and parts.netloc and parts.netloc != "localhost":
if os.name == "nt" and re.match(r"^[A-Za-z]:$", parts.netloc):
file_path = parts.netloc + urllib.request.url2pathname(parts.path)
else:
file_path = "//" + parts.netloc + urllib.request.url2pathname(parts.path)
else:
file_path = urllib.request.url2pathname(parts.path)
path = Path(file_path)
try:
data = path.read_bytes()
except OSError as exc:
Expand Down Expand Up @@ -340,7 +355,11 @@ def install_url(spec: str, *, git_ref: Optional[str] = None, force: bool = False
def _install_py_url(url: str, *, force: bool,
package_dir: Optional[str]) -> List[InstallOutcome]:
data = _download(url)
filename = Path(urllib.parse.urlsplit(url).path).name or "plugin.py"
if url.lower().startswith("file://"):
raw_path = url[len("file://"):].split("#", 1)[0].replace("\\", "/")
filename = raw_path.rsplit("/", 1)[-1] or "plugin.py"
else:
filename = Path(urllib.parse.urlsplit(url).path).name or "plugin.py"
if not filename.lower().endswith(".py"):
filename += ".py"
with _temp_dir(prefix="atdork-ext-file-") as tmp:
Expand Down
8 changes: 6 additions & 2 deletions core/package_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,9 @@ def get_package_dir(explicit: Optional[str] = None) -> Path:
cfg_val = _cfg("package_dir")
if cfg_val:
return _as_path(cfg_val)
return Path.home() / ".atdork" / "packages"
home_override = os.environ.get("HOME") or os.environ.get("USERPROFILE")
home_dir = Path(home_override).expanduser() if home_override else Path.home()
return home_dir / ".atdork" / "packages"


def find_db_repo(explicit: Optional[str] = None) -> Path:
Expand All @@ -191,7 +193,9 @@ def _search_paths(explicit: Optional[str]) -> List[Path]:
cfg_val = _cfg("db_repo")
if cfg_val:
paths.append(_as_path(cfg_val))
paths.append(Path.home() / DB_REPO_NAME)
home_override = os.environ.get("HOME") or os.environ.get("USERPROFILE")
home_dir = Path(home_override).expanduser() if home_override else Path.home()
paths.append(home_dir / DB_REPO_NAME)
# Sibling of this checkout: <parent-of-atdork>/Atdork-DB
paths.append(Path(__file__).resolve().parents[2] / DB_REPO_NAME)
paths.append(Path.cwd() / DB_REPO_NAME)
Expand Down
4 changes: 3 additions & 1 deletion core/watch.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,9 @@ def state_dir(workspace: Any = None) -> Path:
root = getattr(workspace, "state_dir", None)
if root:
return Path(root) / WATCH_FOLDER
return Path.home() / ".atdork" / "state" / WATCH_FOLDER
home_override = os.environ.get("HOME") or os.environ.get("USERPROFILE")
home_dir = Path(home_override).expanduser() if home_override else Path.home()
return home_dir / ".atdork" / "state" / WATCH_FOLDER


def state_path(name: str, workspace: Any = None) -> Path:
Expand Down
4 changes: 3 additions & 1 deletion core/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,9 @@ def state_file(self) -> Path:
if self.workspace is not None:
base = Path(self.workspace.state_dir) / "workflows"
else:
base = Path.home() / ".atdork" / "state" / "workflows"
home_override = os.environ.get("HOME") or os.environ.get("USERPROFILE")
home_dir = Path(home_override).expanduser() if home_override else Path.home()
base = home_dir / ".atdork" / "state" / "workflows"
safe = re.sub(r"[^\w.-]", "_", self.name)
return base / f"{safe}.json"

Expand Down
5 changes: 4 additions & 1 deletion tests/test_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,10 @@ def test_guard_rejects_dotdot_escape(tmp_path):

def test_guard_rejects_symlink_escape(tmp_path):
env = create_env(tmp_path / "ws")
(env.root / "tmp" / "evil").symlink_to(tmp_path) # symlink → outside
try:
(env.root / "tmp" / "evil").symlink_to(tmp_path, target_is_directory=True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
with pytest.raises(EnvEscapeError):
env.guard_write("tmp/evil/leak.db")

Expand Down
5 changes: 4 additions & 1 deletion tests/test_package_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,10 @@ def test_is_within_blocks_escapes(tmp_path):
assert not is_within(root, root / ".." / "outside.txt")
assert not is_within(root, Path("/etc/passwd"))
link = root / "link"
link.symlink_to(tmp_path / "outside")
try:
link.symlink_to(tmp_path / "outside", target_is_directory=True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
assert not is_within(root, link / "x.txt") # symlink is resolved first


Expand Down
4 changes: 3 additions & 1 deletion tests/test_watch.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import io
import json
import os
from pathlib import Path
from types import SimpleNamespace

Expand Down Expand Up @@ -97,7 +98,8 @@ def test_validate_name_bad(name):


def test_state_path_without_env(tmp_path):
assert state_dir() == Path.home() / ".atdork" / "state" / "watch"
home = Path(os.environ["HOME"])
assert state_dir() == home / ".atdork" / "state" / "watch"
assert state_path("acme").name == "acme.json"


Expand Down
Loading