mirror of
https://github.com/barkeser2002/turkanime-gui.git
synced 2026-11-24 21:06:09 +03:00
Asama A-C sonrasi denetimde bulunan dokuz sorunun dokuzu da dogrulandi ve
duzeltildi; her biri icin eski kodda kirmizi olan regresyon testi eklendi.
1. Bolum slug'i 80'de kesiliyordu (adapter._slugify). Arsivde 633 bolum
slug'i daha uzun, 394'u ayni serinin baska bolumuyle cakisiyordu: slug
gecmis anahtari ve indirme dosya adi oldugu icin butun bolumler ayni
dosyaya iniyor, biri izlenince hepsi "izlendi" gorunuyordu. Kaynagin
verdigi slug artik kesilmiyor (azami=None; sitenin slug'i aynen, eski
gecmis korunuyor). Basliktan uretilen slug 80'de kaliyor ama kesilince
sona tam slug'in sha1 ozeti ekleniyor (ayrik ve kararli). Ayni cakisma
dosya adi sinirinda (guvenli_ad, 120) da vardi (36 slug, 29 cakisma);
orada da ozet ekleniyor. Gercek arsivde: 71.675 bolum, 0 yol cakismasi.
2. sifirla() GUI thread'inden cagriliyor ama dizin() ayni kilidi uzak
okumanin tamami boyunca (3 ayna x 10 sn) tutuyordu; konum kilidi de
dizin.json ayristirmasi boyunca. Artik yukleme/cozme kilitleri ayri,
sifirla yalnizca G/C'siz _durum_kilidi'ni aliyor ve bir nesil sayacini
artiriyor; surmekte olan okumanin sonucu nesil degistiyse onbellege
girmiyor.
3. tam_arsiv_indir her hatada yedege geciyordu: disk dolunca GitLab'in
~230 MB'indan sonra GitHub'in ~231 MB'i da iniyordu; guvenli_ac her
OSError'u "paket bozuk" diyordu. Yeni arsiv_paketi.YerelDiskHatasi:
dosya acma/yazma/kapama, klasor kurma, takas (yerine_koy) hatalari buna
cevriliyor (ENOSPC -> "diskte yer kalmadi"), yedege gecirmiyor. Okuma
tarafi (kesik gzip, bozuk tar) ayri kaliyor.
4. conftest._arsiv_yalitimi ayarlar.json'daki animedepo_dizin /
animedepo_url'yi yalitmiyordu; depodan calisinca veri koku depo koku.
Ayar dosyasi artik yalnizca pytest'in gecici koku altindaysa okunuyor
(ayari sinayan testler zaten tmp_path'e chdir ediyor). Denetcinin
senaryosu (gelistirici koku + iki ayar) 31 hata yerine 226 passed.
5. arsiv_senkron hedefi hic denetlemiyordu: --hedef "" / . / bos $HEDEF
calisma dizinindeki .git disindaki her seyi silerdi. hedef_denetle:
calisma dizini ve ustleri, kok/ev, proje koku (.git, pyproject.toml...),
arsiv olmayan dolu klasor reddediliyor, klonlamadan once. --zorla atlar.
6. yerine_koy sembolik bagli hedefte bagin kendisini tasiyordu: yeni arsiv
veri kokunun diskine iniyor, eski veri obur diskte kaliyordu. Bag artik
izleniyor (bag_hedefi); gecici klasor ve takas bagin gosterdigi yerde,
bag korunuyor. Kopuk bag ag'a cikmadan YerelDiskHatasi. Eski kopya
silme hatasi yutulmuyor (agaci_sil silinemeyenleri donduruyor);
arsiv_durumu().kalintilar ve Ayarlar uyarisi .cevrimdisi_arsiv-eski-*
kalintilarini gosteriyor.
7. Arsiv okunamayinca (aynalar kapali, onbellek bos) arama sessizce 0
sonuc veriyordu. Yeni animedepo.ArsivOkunamadi / dizin_ya_da_hata:
search_animedepo sebebiyle firlatiyor (bos arsiv hata degil; dizin()
eski sozlesmesiyle {} donmeye devam ediyor). KaynakAdaptoru hatayi
artik yutmuyor; SearchEngine kaynak basina yakalayip
AramaSonuclari.hatalar'a yaziyor (dict alt sinifi, eski cagiranlar
ayni). Arama sayfasi "sonuc bulunamadi. Aranamayan kaynak: TurkAnime
(arsiv) - sebep" diyor; CLI "Arama yapilirken bir hata olustu" ve
sebebi basiyor, acilis hazirligi da sebebi gosteriyor.
8. Iptal yalnizca parcalar arasinda denetleniyordu; get() baglanirken ya
da ilk bayt beklenirken 15-75 sn "Iptal ediliyor..." kaliyordu.
paket.iptal_edilebilir istegi yardimci thread'de yurutup 0,1 sn'de bir
iptale bakiyor (gec gelen yanit kapatiliyor); govdeyi_indir parcalari
yardimci thread + kuyrukla aliyor, takilan akista da iptal isliyor.
Iptalde yanit arka planda kapatiliyor (curl kapanirken bekliyor).
9. ANIME_PROVIDER_GUIDE "import aninda ValueError" diyordu ama indeks ilk
bul()'da kuruluyordu. kayit.py tabloyu artik import aninda
_indeks_kur ile dogruluyor; iki belge kopyasi da bunu anlatiyor.
Testler (+33): test_cevrimdisi_arsiv.py (+22), test_kaynak_kaydi.py (+6),
test_qt_arsiv_ayarlari.py (+2), test_qt_search.py (+2),
test_indirme_yolu_guvenligi.py (+1). Hepsi eski kaynakla calistirildi ve
kirmizi oldugu goruldu. Mevcut hicbir testin iddiasi degismedi; yalnizca
conftest'in yalitim fixture'i genisledi. Ag yok, 500 MB'lik arsiv/
okunmuyor.
Belgeler: README.md = docs/README.md (Ayarlar maddeleri, okunamayan arsiv,
test sayisi 1.238, kapsam tablosu), arsiv/README.md (hedef denetimi,
--zorla).
Kalite kapisi: 1238 passed, 0 failed, 0 error; pylint -E temiz.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015orra9NXZHpRa7PJyxoyR2
267 lines
12 KiB
Python
267 lines
12 KiB
Python
"""İndirme yolu güvenliği — kaynaktan gelen slug dizin dolaşımı yapamaz.
|
||
|
||
Saldırı senaryosu (denetimden): AnimeDepo arşivinin `dizin.json`'ına ya da ele
|
||
geçirilmiş bir kaynak siteye `"../../../../evil-dir"` gibi bir anime slug'ı
|
||
konur. Kullanıcı o animenin bir bölümünü indirdiğinde yt-dlp'ye verilen
|
||
`outtmpl` indirme klasörünün DIŞINA çözülür ve dosya oraya yazılır.
|
||
|
||
Testler yt-dlp'yi sahteliyor ama **davranışını taklit ediyor**: verilen
|
||
`outtmpl`'in klasörlerini yaratıp dosyayı açıyor. Yani "yol güvenli mi"
|
||
sorusunu yolun metnine bakarak değil, diske gerçekten yazarak yanıtlıyoruz.
|
||
|
||
Hiçbiri gerçek kullanıcı dosyasına dokunmaz — hepsi `tmp_path` altında.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
|
||
import pytest
|
||
|
||
from turkanime_api.common.dosya_adi import (
|
||
AYRILMIS_ADLAR, alt_yolda_mi, guvenli_ad, guvenli_alt_yol,
|
||
)
|
||
|
||
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
# Yardımcı: yt-dlp'nin outtmpl davranışını taklit eden sahte
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
class SahteYDL:
|
||
"""`outtmpl` neredeyse oraya yazar — gerçek yt-dlp de bunu yapıyor."""
|
||
|
||
yazilanlar: list = []
|
||
|
||
def __init__(self, opts):
|
||
self.opts = opts
|
||
|
||
def __enter__(self):
|
||
return self
|
||
|
||
def __exit__(self, *_a):
|
||
return False
|
||
|
||
def download_with_info_file(self, _info_yolu):
|
||
hedef = self.opts["outtmpl"]["default"].replace(".%(ext)s", ".mp4")
|
||
os.makedirs(os.path.dirname(hedef) or ".", exist_ok=True)
|
||
with open(hedef, "w", encoding="utf-8") as fp:
|
||
fp.write("video")
|
||
SahteYDL.yazilanlar.append(os.path.abspath(hedef))
|
||
|
||
|
||
@pytest.fixture
|
||
def sahte_ydl(monkeypatch):
|
||
"""`adapter` ve `objects` modüllerindeki YoutubeDL'i sahteyle değiştir."""
|
||
from turkanime_api import objects as objects_mod
|
||
from turkanime_api.sources import adapter as adapter_mod
|
||
|
||
SahteYDL.yazilanlar = []
|
||
monkeypatch.setattr(adapter_mod, "YoutubeDL", SahteYDL)
|
||
monkeypatch.setattr(objects_mod, "YoutubeDL", SahteYDL)
|
||
return SahteYDL
|
||
|
||
|
||
def _dosyalar(kok) -> list:
|
||
return [os.path.join(k, d) for k, _, ds in os.walk(str(kok)) for d in ds]
|
||
|
||
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
# 1) Dosya adı temizliği
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
@pytest.mark.parametrize("ham", [
|
||
"../../../../evil-dir",
|
||
"..\\..\\..\\evil-dir",
|
||
"/etc/passwd",
|
||
"C:\\Windows\\System32",
|
||
"..",
|
||
".",
|
||
" ",
|
||
"",
|
||
None,
|
||
])
|
||
def test_guvenli_ad_ayirici_ve_dolasim_birakmaz(ham):
|
||
ad = guvenli_ad(ham, yedek="yedek")
|
||
assert ad, "ad boş kalamaz"
|
||
assert "/" not in ad and "\\" not in ad
|
||
assert ad not in (".", "..")
|
||
assert os.path.basename(ad) == ad, "ad tek bir bileşen olmalı"
|
||
assert not os.path.isabs(ad)
|
||
|
||
|
||
@pytest.mark.parametrize("ayrilmis", sorted(AYRILMIS_ADLAR))
|
||
def test_windows_ayrilmis_adlari_kacisliyor(ayrilmis):
|
||
"""CON/NUL/COM1... Windows'ta dosya değil aygıt adıdır; uzantılısı da."""
|
||
assert guvenli_ad(ayrilmis) != ayrilmis
|
||
assert guvenli_ad(ayrilmis.lower() + ".mp4") != ayrilmis.lower() + ".mp4"
|
||
|
||
|
||
def test_bosluk_ve_nokta_ile_biten_ad_duzeltiliyor():
|
||
"""Windows "ad." ve "ad " dosyasını yaratamaz/açamaz."""
|
||
for ham in ("bolum.", "bolum ", "bolum..", "bolum . "):
|
||
ad = guvenli_ad(ham)
|
||
assert not ad.endswith((".", " ")), ad
|
||
|
||
|
||
def test_yasak_karakterler_temizleniyor():
|
||
ad = guvenli_ad('bo<lum>:"1"|?*\x00')
|
||
assert not set(ad) & set('<>:"/\\|?*')
|
||
assert all(ord(c) >= 32 for c in ad)
|
||
|
||
|
||
def test_uzun_ad_kirpiliyor():
|
||
assert len(guvenli_ad("a" * 500)) <= 120
|
||
|
||
|
||
def test_kirpilan_uzun_adlar_ayrik_ve_kararli():
|
||
"""ESKİ HATA: düz kesme, ilk 120 karakteri ortak iki adı AYNI dosyaya
|
||
çeviriyordu. Arşivde 29 bölüm böyle: ikinci bölüm birincinin üstüne
|
||
iniyor ya da yt-dlp "zaten var" deyip atlıyordu."""
|
||
ortak = "tatoeba-last-dungeon-" * 8
|
||
birinci, ikinci = guvenli_ad(ortak + "1-bolum"), guvenli_ad(ortak + "2-bolum")
|
||
assert birinci != ikinci
|
||
assert len(birinci) <= 120 and len(ikinci) <= 120
|
||
assert guvenli_ad(ortak + "1-bolum") == birinci, "aynı ad hep aynı sonucu vermeli"
|
||
assert guvenli_ad("naruto-1-bolum") == "naruto-1-bolum", "kısa ad değişmemeli"
|
||
|
||
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
# 2) Sınır denetimi (temizliğe ek ikinci katman)
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
def test_guvenli_alt_yol_daima_kokun_altinda(tmp_path):
|
||
for slug in ("../../evil", "..\\..\\evil", "/etc", "C:\\Windows", ".."):
|
||
yol = guvenli_alt_yol(tmp_path, slug, "bolum-1")
|
||
assert alt_yolda_mi(tmp_path, yol), f"{slug!r} kökten kaçtı: {yol}"
|
||
|
||
|
||
def test_alt_yolda_mi_farkli_surucude_false(tmp_path):
|
||
"""Windows'ta farklı sürücüler ortak kök paylaşmaz; `commonpath` patlar."""
|
||
assert alt_yolda_mi(tmp_path, tmp_path / "alt") is True
|
||
assert alt_yolda_mi(tmp_path, os.path.join(str(tmp_path) + "-komsu", "x")) is False
|
||
|
||
|
||
def test_bos_kok_calisma_dizinine_cozuluyor(tmp_path, monkeypatch):
|
||
"""`Video.indir(output="")` varsayılanı: eskiden göreli yol üretiyordu."""
|
||
monkeypatch.chdir(tmp_path)
|
||
yol = guvenli_alt_yol("", "naruto", "naruto-1-bolum")
|
||
assert os.path.isabs(yol)
|
||
assert alt_yolda_mi(tmp_path, yol)
|
||
|
||
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
# 3) Uçtan uca: AdapterVideo.indir (AnimeDepo/AnimeciX yolu)
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
def _adapter_video(slug: str, indirilenler):
|
||
from turkanime_api.sources.adapter import (
|
||
AdapterAnime, AdapterBolum, AdapterVideo,
|
||
)
|
||
anime = AdapterAnime(slug=slug, title="Naruto")
|
||
bolum = AdapterBolum(url="https://x.test/1", title="1. Bölüm", anime=anime)
|
||
video = AdapterVideo(bolum, "https://x.test/v.mp4")
|
||
video.is_working = True
|
||
video._info = {"url": "https://x.test/v.mp4", "ext": "mp4"}
|
||
return video
|
||
|
||
|
||
def test_adapter_indir_kotu_slugla_klasor_disina_yazmiyor(tmp_path, sahte_ydl):
|
||
"""Denetim senaryosunun birebir kendisi."""
|
||
indirilenler = tmp_path / "a" / "b" / "c" / "d" / "Downloads"
|
||
indirilenler.mkdir(parents=True)
|
||
|
||
_adapter_video("../../../../evil-dir", indirilenler).indir(
|
||
output=str(indirilenler))
|
||
|
||
assert sahte_ydl.yazilanlar, "hiç indirme yapılmadı, test anlamsız"
|
||
for yazilan in sahte_ydl.yazilanlar:
|
||
assert alt_yolda_mi(indirilenler, yazilan), f"klasör dışına yazıldı: {yazilan}"
|
||
assert not (tmp_path / "evil-dir").exists()
|
||
assert not (tmp_path / "a" / "evil-dir").exists()
|
||
assert len(_dosyalar(indirilenler)) == 1
|
||
|
||
|
||
def test_adapter_indir_normal_slug_davranisi_bozulmadi(tmp_path, sahte_ydl):
|
||
"""Temizlik meşru slug'ları değiştirmemeli — dosya adları kaymasın."""
|
||
indirilenler = tmp_path / "Downloads"
|
||
indirilenler.mkdir()
|
||
|
||
_adapter_video("naruto-shippuuden", indirilenler).indir(output=str(indirilenler))
|
||
|
||
beklenen = indirilenler / "naruto-shippuuden" / "naruto-1-bolum.mp4"
|
||
assert beklenen.is_file(), _dosyalar(indirilenler)
|
||
|
||
|
||
def test_adapter_indir_mutlak_slug_ile_disari_yazmiyor(tmp_path, sahte_ydl):
|
||
"""Sürücü harfi / mutlak yol da bir kaçış vektörü."""
|
||
indirilenler = tmp_path / "Downloads"
|
||
indirilenler.mkdir()
|
||
hedef = tmp_path / "kacak"
|
||
|
||
_adapter_video(str(hedef), indirilenler).indir(output=str(indirilenler))
|
||
|
||
assert not hedef.exists(), "mutlak slug indirme klasörünü atladı"
|
||
assert all(alt_yolda_mi(indirilenler, y) for y in sahte_ydl.yazilanlar)
|
||
|
||
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
# 4) Uçtan uca: objects.Video.indir (TürkAnime yolu)
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
def test_objects_video_indir_dolasim_yapmiyor(tmp_path, sahte_ydl):
|
||
"""Aynı sınıf kusur: seri/bölüm slug'ı site HTML'inden regex ile geliyor."""
|
||
from turkanime_api.objects import Video
|
||
|
||
class SahteAnime:
|
||
slug = "../../../evil"
|
||
|
||
class SahteBolum:
|
||
slug = "../../kotu-bolum"
|
||
anime = SahteAnime()
|
||
|
||
video = Video.__new__(Video) # __init__ ağa/ayara dokunuyor
|
||
video.bolum = SahteBolum()
|
||
video.ydl_opts = {}
|
||
video._is_working = True
|
||
video._info = {"url": "https://x.test/v.mp4", "ext": "mp4"}
|
||
video.is_supported = True
|
||
video.player = "YADISK"
|
||
|
||
indirilenler = tmp_path / "Downloads"
|
||
indirilenler.mkdir()
|
||
video.indir(output=str(indirilenler))
|
||
|
||
assert sahte_ydl.yazilanlar
|
||
for yazilan in sahte_ydl.yazilanlar:
|
||
assert alt_yolda_mi(indirilenler, yazilan), yazilan
|
||
assert not (tmp_path / "evil").exists()
|
||
|
||
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
# 5) Arşiv yazıcısı (sunucu tarafı) — aynı sınıf kusur
|
||
# ─────────────────────────────────────────────────────────────────────────────
|
||
def test_arsiv_yazici_kok_disina_yazmiyor(tmp_path):
|
||
"""Slug bugün `[a-z0-9-]`; yazıcı yine de çağıranına güvenmemeli."""
|
||
from turkanime_server.crawler.yazici import ArsivYazici
|
||
|
||
kok = tmp_path / "arsiv"
|
||
yazici = ArsivYazici(kok)
|
||
yazici.info_yaz("../../evil", {"slug": "x"})
|
||
yazici.bolumler_yaz("../../evil", [("s01e01", "1. Bölüm")])
|
||
yazici.akis_yaz("naruto", "../../../kacak", [{"url": "https://x.test/a.mp4"}])
|
||
|
||
for yazilan in _dosyalar(kok):
|
||
assert alt_yolda_mi(kok, yazilan), f"arşiv kökünün dışına yazıldı: {yazilan}"
|
||
assert not (tmp_path / "evil").exists()
|
||
assert not (tmp_path / "kacak").exists()
|
||
|
||
|
||
def test_arsiv_yazici_normal_slug_yolu_degistirmiyor(tmp_path):
|
||
"""Mevcut arşiv düzeni kaymamalı: slug yolun parçası, kayması kırık link."""
|
||
from turkanime_server.crawler.yazici import ArsivYazici
|
||
|
||
kok = tmp_path / "arsiv"
|
||
yazici = ArsivYazici(kok)
|
||
yazici.anime_yaz("naruto", {"slug": "naruto"}, [("s01e01", "1. Bölüm")],
|
||
{"s01e01": [{"url": "https://x.test/a.mp4"}]})
|
||
yazici.dizin_yaz([("naruto", "Naruto")])
|
||
|
||
assert (kok / "dizin.json").is_file()
|
||
assert (kok / "animeler" / "naruto" / "info.json").is_file()
|
||
assert (kok / "animeler" / "naruto" / "bolumler.json").is_file()
|
||
assert (kok / "animeler" / "naruto" / "s01e01.json").is_file()
|