Skip to content

Commit ebbc3e7

Browse files
Merge pull request #1 from dev-bricks/claude/determined-mayer-marfcu
fix(library,editor): block snippet path traversal, preserve line endings on save
2 parents b78680e + 60e3bea commit ebbc3e7

5 files changed

Lines changed: 256 additions & 21 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ Format basiert auf [Keep a Changelog](https://keepachangelog.com/de/1.1.0/).
1919
- Neue automatisierte Vertragstests in `tests/test_metadata.py` zur Verifikation von NOTICE, bilingualer 18-Punkte-Parität, dualen Mermaid-Diagrammen, 20/20 Keywords und Version Freeze (`1.0.1`).
2020

2121
### Behoben / Fixed
22+
- Kein Snippet-Verlust mehr beim Umbenennen: `edit_library_item` löschte den alten Eintrag, bevor der neue gespeichert war, und ignorierte das Speicherergebnis. Lehnt die Namensprüfung den neuen Namen ab (z. B. `Regex: Gruppen` oder `Kap. 1.`), war das Snippet weg. `LibraryManager.rename_snippet` speichert jetzt zuerst und entfernt den alten Eintrag erst nach Erfolg; ein Fehler wird im Dialog gemeldet.
23+
- Sicherheit: Snippet-Bibliothek akzeptiert nur noch einzelne, harmlose Pfadbestandteile als Themen- und Snippet-Namen (`LibraryManager._snippet_path`). Zuvor konnte eine importierte `pythonbox-snippets-v1`-Datei über Namen wie `../../ordner` oder absolute Pfade beliebige `.py`-Dateien außerhalb der Bibliothek überschreiben; solche Einträge werden jetzt übersprungen und als `skipped` gezählt.
24+
- Zeilenenden bleiben beim Speichern erhalten: `MultiTabEditor.open_file` merkt sich das Zeilenende der Datei (`detect_newline`), `save_tab` schreibt es zurück (Dateien mit gemischten Zeilenenden werden auf das häufigere vereinheitlicht; ein UTF-8-BOM bleibt wie bisher nicht erhalten). Zuvor wurden LF-Dateien unter Windows beim Speichern still nach CRLF umgeschrieben, wodurch Git jede Zeile als geändert meldete. Neue, noch nie gespeicherte Dateien verwenden weiterhin den Plattformstandard.
25+
- Keine `libpyside: Failed to disconnect`-Warnung mehr bei jedem Tab-Wechsel: `on_editor_changed` verbindet `cursorPositionInfo` jetzt mit `Qt.ConnectionType.UniqueConnection` statt vorab zu trennen.
2226
- Sichere Literalersetzung in `SearchReplaceBar.replace_all`: Case-insensitive Textersetzung verwendet jetzt einen Callable-Ersatz (`lambda _m: replace_text`) in `re.sub()`. Dies verhindert Abstürze mit `re.error: bad escape \u` bei Pfadangaben mit Backslashes (z. B. Windows-Pfade wie `C:\Users\...`) sowie Fehlinterpretationen von Regex-Gruppenreferenzen und stellt identisches Literal-Verhalten wie bei case-sensitiver Ersetzung sicher.
2327

2428
## [1.0.1] - 2026-09-18

‎PythonBox_v8.py‎

Lines changed: 97 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,19 @@ def build_external_python_command(script_path: Path) -> List[str]:
107107
)
108108

109109

110+
def detect_newline(text: str) -> Optional[str]:
111+
"""Ermittelt das vorherrschende Zeilenende eines Textes.
112+
113+
Gibt ``"\r\n"`` oder ``"\n"`` zurück, bzw. ``None``, wenn der Text keinen
114+
Zeilenumbruch enthält (dann gilt beim Speichern der Plattformstandard).
115+
"""
116+
crlf = text.count('\r\n')
117+
lf = text.count('\n') - crlf
118+
if crlf == 0 and lf == 0:
119+
return None
120+
return '\r\n' if crlf >= lf else '\n'
121+
122+
110123
def _utc_export_timestamp() -> str:
111124
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
112125

@@ -2608,6 +2621,8 @@ def __init__(self, editor: CodeEditor, highlighter: PythonSyntaxHighlighter,
26082621
self.highlighter = highlighter
26092622
self.file_path = file_path
26102623
self.is_modified = False
2624+
# Zeilenende der geöffneten Datei ("\n" oder "\r\n"); None = Plattformstandard.
2625+
self.newline: Optional[str] = None
26112626

26122627

26132628
class MultiTabEditor(QWidget):
@@ -2754,7 +2769,14 @@ def save_tab(self, index: int) -> bool:
27542769
tab.file_path = file_path
27552770

27562771
try:
2757-
Path(tab.file_path).write_text(tab.editor.toPlainText(), encoding='utf-8')
2772+
text = tab.editor.toPlainText()
2773+
if tab.newline:
2774+
# Zeilenenden der Originaldatei beibehalten (kein stilles LF -> CRLF).
2775+
Path(tab.file_path).write_text(
2776+
text.replace('\n', tab.newline), encoding='utf-8', newline=''
2777+
)
2778+
else:
2779+
Path(tab.file_path).write_text(text, encoding='utf-8')
27582780
tab.editor.document().setModified(False)
27592781
self.tab_widget.setTabText(index, Path(tab.file_path).name)
27602782
return True
@@ -2771,7 +2793,10 @@ def open_file(self, file_path: str, replace_current_untitled: bool = False) -> i
27712793
return idx
27722794

27732795
try:
2774-
content = Path(file_path).read_text(encoding='utf-8')
2796+
with open(file_path, 'r', encoding='utf-8', newline='') as handle:
2797+
raw = handle.read()
2798+
newline = detect_newline(raw)
2799+
content = raw.replace('\r\n', '\n').replace('\r', '\n')
27752800
if replace_current_untitled and self.tab_widget.count() == 1:
27762801
current_index = self.tab_widget.currentIndex()
27772802
current_tab = self.tabs.get(current_index)
@@ -2784,11 +2809,15 @@ def open_file(self, file_path: str, replace_current_untitled: bool = False) -> i
27842809
current_tab.editor.setPlainText(content)
27852810
current_tab.editor.document().setModified(False)
27862811
current_tab.file_path = file_path
2812+
current_tab.newline = newline
27872813
self.tab_widget.setTabText(current_index, Path(file_path).name)
27882814
self.tab_widget.setCurrentIndex(current_index)
27892815
return current_index
27902816

2791-
return self.new_tab(file_path, content)
2817+
index = self.new_tab(file_path, content)
2818+
if index in self.tabs:
2819+
self.tabs[index].newline = newline
2820+
return index
27922821
except Exception as e:
27932822
QMessageBox.critical(self, "Fehler", f"Öffnen fehlgeschlagen: {e}")
27942823
return -1
@@ -2913,6 +2942,31 @@ def _save_locks(self):
29132942
json.dump(list(self.locked_items), f)
29142943
os.replace(tmp, self.lock_file)
29152944

2945+
@staticmethod
2946+
def _is_safe_component(value) -> bool:
2947+
"""Prüft, ob ``value`` ein einzelner, harmloser Pfadbestandteil ist.
2948+
2949+
Themen- und Snippet-Namen stammen aus Dialogen und aus importierten
2950+
JSON-Dateien. Ohne diese Prüfung könnte ein Name wie ``../../x`` oder
2951+
ein absoluter Pfad Dateien außerhalb der Bibliothek überschreiben.
2952+
"""
2953+
if not isinstance(value, str) or not value or value != value.strip():
2954+
return False
2955+
if value in (".", "..") or value.endswith("."):
2956+
return False
2957+
return not any(ch in '/\\:' or ch < ' ' for ch in value)
2958+
2959+
def _snippet_path(self, topic, name) -> Optional[Path]:
2960+
"""Liefert den Snippet-Pfad oder ``None``, wenn er die Bibliothek verließe."""
2961+
if not (self._is_safe_component(topic) and self._is_safe_component(name)):
2962+
return None
2963+
path = self.root / topic / f"{name}.py"
2964+
try:
2965+
path.resolve().relative_to(self.root.resolve())
2966+
except (OSError, ValueError):
2967+
return None
2968+
return path
2969+
29162970
def is_locked(self, topic, name):
29172971
return f"{topic}/{name}" in self.locked_items
29182972

@@ -2934,26 +2988,49 @@ def get_items(self, topic):
29342988
return sorted([f.stem for f in path.glob("*.py")])
29352989

29362990
def get_content(self, topic, name):
2937-
path = self.root / topic / f"{name}.py"
2938-
if path.exists(): return path.read_text(encoding='utf-8')
2991+
path = self._snippet_path(topic, name)
2992+
if path is not None and path.exists(): return path.read_text(encoding='utf-8')
29392993
return ""
29402994

29412995
def save_snippet(self, topic, name, content):
29422996
if self.is_locked(topic, name):
29432997
return False, "Eintrag ist gesperrt."
2998+
path = self._snippet_path(topic, name)
2999+
if path is None:
3000+
return False, "Ungültiger Themen- oder Snippet-Name."
29443001
try:
2945-
topic_dir = self.root / topic
2946-
topic_dir.mkdir(exist_ok=True)
2947-
(topic_dir / f"{name}.py").write_text(content, encoding='utf-8')
3002+
path.parent.mkdir(exist_ok=True)
3003+
path.write_text(content, encoding='utf-8')
29483004
return True, "Gespeichert."
29493005
except Exception as e:
29503006
return False, str(e)
29513007

3008+
def rename_snippet(self, old_topic, old_name, topic, name, content):
3009+
"""Speichert unter dem neuen Namen und entfernt erst danach den alten Eintrag.
3010+
3011+
Scheitert das Speichern (ungültiger Name, gesperrtes Ziel, Schreibfehler),
3012+
bleibt der alte Eintrag unverändert erhalten.
3013+
"""
3014+
old_path = self._snippet_path(old_topic, old_name)
3015+
ok, msg = self.save_snippet(topic, name, content)
3016+
if not ok:
3017+
return False, msg
3018+
new_path = self._snippet_path(topic, name)
3019+
same_file = False
3020+
if old_path is not None and new_path is not None and old_path.exists():
3021+
try:
3022+
same_file = os.path.samefile(old_path, new_path)
3023+
except OSError:
3024+
same_file = False
3025+
if not same_file:
3026+
self.delete_item(old_topic, old_name)
3027+
return True, msg
3028+
29523029
def delete_item(self, topic, name):
29533030
if self.is_locked(topic, name):
29543031
return False
2955-
path = self.root / topic / f"{name}.py"
2956-
if path.exists():
3032+
path = self._snippet_path(topic, name)
3033+
if path is not None and path.exists():
29573034
os.remove(path)
29583035
key = f"{topic}/{name}"
29593036
if key in self.locked_items:
@@ -3439,12 +3516,11 @@ def on_editor_changed(self, editor: CodeEditor):
34393516
"""Wird aufgerufen wenn der aktive Editor wechselt"""
34403517
if editor:
34413518
self.search_bar.set_editor(editor)
3442-
# Disconnect first to avoid duplicate connections when switching back
3443-
try:
3444-
editor.cursorPositionInfo.disconnect(self.update_cursor_position)
3445-
except RuntimeError:
3446-
pass
3447-
editor.cursorPositionInfo.connect(self.update_cursor_position)
3519+
# UniqueConnection verhindert Doppelverbindungen beim Zurückwechseln,
3520+
# ohne die libpyside-Warnung eines fehlgeschlagenen disconnect().
3521+
editor.cursorPositionInfo.connect(
3522+
self.update_cursor_position, Qt.ConnectionType.UniqueConnection
3523+
)
34483524

34493525
# NEU v7: Git-Status aktualisieren (nur wenn git_label existiert)
34503526
if hasattr(self, 'git_label'):
@@ -4142,9 +4218,11 @@ def edit_library_item(self, item):
41424218
if data['locked']:
41434219
QMessageBox.warning(self, "Gesperrt", "Namen ändern bei gesperrten Items nicht erlaubt.")
41444220
return
4145-
self.lib_manager.delete_item(data['topic'], data['name'])
4146-
4147-
self.lib_manager.save_snippet(t, n, c)
4221+
ok, msg = self.lib_manager.rename_snippet(data['topic'], data['name'], t, n, c)
4222+
else:
4223+
ok, msg = self.lib_manager.save_snippet(t, n, c)
4224+
if not ok:
4225+
QMessageBox.warning(self, "Fehler", msg)
41484226
self.load_library_tree()
41494227

41504228
def delete_library_item(self, item):

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
[![Python](https://img.shields.io/badge/Python-3.10+-blue.svg)](https://www.python.org/)
1111
[![PySide6](https://img.shields.io/badge/PySide6-6.5+-green.svg)](https://pypi.org/project/PySide6/)
1212
[![PythonBox tests](https://github.com/dev-bricks/pythonbox/actions/workflows/tests.yml/badge.svg)](https://github.com/dev-bricks/pythonbox/actions/workflows/tests.yml)
13-
[![Tests](https://img.shields.io/badge/Tests-121%20passed%20%7C%20100%25%20green-brightgreen.svg)](tests/)
13+
[![Tests](https://img.shields.io/badge/Tests-131%20passed%20%7C%20100%25%20green-brightgreen.svg)](tests/)
1414
[![Security](https://img.shields.io/badge/Security-RunAsInvoker-success.svg)](SECURITY.md)
1515
[![Zero-Egress](https://img.shields.io/badge/Zero--Egress-100%25%20Offline-success.svg)](SECURITY.md)
1616
[![SLA](https://img.shields.io/badge/SLA-48h%20Response-blue.svg)](SECURITY.md)

‎README_de.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
[![Python](https://img.shields.io/badge/Python-3.10+-blue.svg)](https://www.python.org/)
1111
[![PySide6](https://img.shields.io/badge/PySide6-6.5+-green.svg)](https://pypi.org/project/PySide6/)
1212
[![PythonBox tests](https://github.com/dev-bricks/pythonbox/actions/workflows/tests.yml/badge.svg)](https://github.com/dev-bricks/pythonbox/actions/workflows/tests.yml)
13-
[![Tests](https://img.shields.io/badge/Tests-121%20passed%20%7C%20100%25%20green-brightgreen.svg)](tests/)
13+
[![Tests](https://img.shields.io/badge/Tests-131%20passed%20%7C%20100%25%20green-brightgreen.svg)](tests/)
1414
[![Security](https://img.shields.io/badge/Security-RunAsInvoker-success.svg)](SECURITY.md)
1515
[![Zero-Egress](https://img.shields.io/badge/Zero--Egress-100%25%20Offline-success.svg)](SECURITY.md)
1616
[![SLA](https://img.shields.io/badge/SLA-48h%20Response-blue.svg)](SECURITY.md)

0 commit comments

Comments
 (0)