Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

41.3 KB
Raw Blame
"""Test the queued download facility"""

import re
import socket
import time
from contextlib import contextmanager
from pathlib import Path
from threading import Event, Thread
from typing import Any, Generator, Optional
from unittest.mock import MagicMock, patch

import pytest
from pydantic.networks import AnyHttpUrl
from requests import Response
from requests.sessions import Session
from requests_testadapter import TestAdapter, TestSession

from invokeai.app.services.config import InvokeAIAppConfig, get_config
from invokeai.app.services.config.config_default import URLRegexTokenPair
from invokeai.app.services.download import (
    DownloadJob,
    DownloadJobStatus,
    DownloadQueueService,
    MultiFileDownloadJob,
    download_default,
)
from invokeai.app.services.events.events_common import (
    DownloadCancelledEvent,
    DownloadCompleteEvent,
    DownloadErrorEvent,
    DownloadProgressEvent,
    DownloadStartedEvent,
)
from invokeai.app.util import ssrf
from invokeai.app.util.ssrf import UnsafeDownloadURLException
from invokeai.backend.model_manager.metadata import HuggingFaceMetadataFetch, ModelMetadataWithFiles, RemoteModelFile
from tests.test_nodes import TestEventService

# Prevent pytest deprecation warnings
TestAdapter.__test__ = False


@pytest.mark.timeout(timeout=10, method="thread")
def test_basic_queue_download(tmp_path: Path, mm2_session: Session) -> None:
    events = set()

    def event_handler(job: DownloadJob, excp: Optional[Exception] = None) -> None:
        events.add(job.status)

    queue = DownloadQueueService(
        requests_session=mm2_session,
        requests_session_is_trusted=True,
    )
    queue.start()
    job = queue.download(
        source=AnyHttpUrl("http://www.civitai.com/models/12345"),
        dest=tmp_path,
        on_start=event_handler,
        on_progress=event_handler,
        on_complete=event_handler,
        on_error=event_handler,
    )
    assert isinstance(job, DownloadJob), "expected the job to be of type DownloadJobBase"
    assert isinstance(job.id, int), "expected the job id to be numeric"
    queue.join()

    assert job.status == DownloadJobStatus("completed"), "expected job status to be completed"
    assert job.download_path == tmp_path / "mock12345.safetensors"
    assert Path(tmp_path, "mock12345.safetensors").exists(), f"expected {tmp_path}/mock12345.safetensors to exist"

    assert events == {DownloadJobStatus.RUNNING, DownloadJobStatus.COMPLETED}
    queue.stop()


@pytest.mark.timeout(timeout=10, method="thread")
def test_errors(tmp_path: Path, mm2_session: Session) -> None:
    queue = DownloadQueueService(
        requests_session=mm2_session,
        requests_session_is_trusted=True,
    )
    queue.start()

    for bad_url in ["http://www.civitai.com/models/broken", "http://www.civitai.com/models/missing"]:
        queue.download(AnyHttpUrl(bad_url), dest=tmp_path)

    queue.join()
    jobs = queue.list_jobs()
    print(jobs)
    assert len(jobs) == 2
    jobs_dict = {str(x.source): x for x in jobs}
    assert jobs_dict["http://www.civitai.com/models/broken"].status == DownloadJobStatus.ERROR
    assert jobs_dict["http://www.civitai.com/models/broken"].error_type == "HTTPError(NOT FOUND)"
    assert jobs_dict["http://www.civitai.com/models/missing"].status == DownloadJobStatus.COMPLETED
    assert jobs_dict["http://www.civitai.com/models/missing"].total_bytes == 0
    queue.stop()


@pytest.mark.timeout(timeout=10, method="thread")
def test_completed_resume_with_416_promotes_in_progress_file(tmp_path: Path) -> None:
    source = AnyHttpUrl("https://test.com/complete.safetensors")
    content = b"complete"
    destination = tmp_path / "complete.safetensors"
    in_progress_path = destination.with_name(destination.name + ".downloading")
    in_progress_path.write_bytes(content)

    session = TestSession()
    session.mount(
        str(source),
        TestAdapter(b"", status=416, headers={"Content-Range": f"bytes */{len(content)}"}),
    )
    completed_files: list[bool] = []
    queue = DownloadQueueService(requests_session=session, requests_session_is_trusted=True)
    queue.start()
    try:
        job = queue.download(
            source=source,
            dest=destination,
            on_complete=lambda completed_job: completed_files.append(completed_job.download_path.exists()),
        )
        queue.join()
    finally:
        queue.stop()

    assert job.status == DownloadJobStatus.COMPLETED
    assert destination.read_bytes() == content
    assert not in_progress_path.exists()
    assert completed_files == [True]


@pytest.mark.timeout(timeout=10, method="thread")
def test_headerless_416_falls_back_to_recorded_size(tmp_path: Path) -> None:
    source = AnyHttpUrl("https://test.com/headerless.safetensors")
    content = b"complete"
    destination = tmp_path / "headerless.safetensors"
    in_progress_path = destination.with_name(destination.name + ".downloading")
    in_progress_path.write_bytes(content)

    session = TestSession()
    session.mount(str(source), TestAdapter(b"", status=416))
    queue = DownloadQueueService(requests_session=session, requests_session_is_trusted=True)
    queue.start()
    try:
        job = DownloadJob(source=source, dest=destination, expected_total_bytes=len(content))
        queue.submit_download_job(job)
        queue.join()
    finally:
        queue.stop()

    assert job.status == DownloadJobStatus.COMPLETED
    assert destination.read_bytes() == content
    assert not in_progress_path.exists()


@pytest.mark.timeout(timeout=10, method="thread")
def test_headerless_416_without_recorded_size_pauses(tmp_path: Path) -> None:
    source = AnyHttpUrl("https://test.com/unknown.safetensors")
    destination = tmp_path / "unknown.safetensors"
    in_progress_path = destination.with_name(destination.name + ".downloading")
    in_progress_path.write_bytes(b"who knows")

    session = TestSession()
    session.mount(str(source), TestAdapter(b"", status=416))
    queue = DownloadQueueService(requests_session=session, requests_session_is_trusted=True)
    queue.start()
    try:
        job = queue.download(source=source, dest=destination)
        queue.join()
    finally:
        queue.stop()

    assert job.status == DownloadJobStatus.PAUSED
    assert job.resume_required
    assert not destination.exists()
    assert in_progress_path.exists()


@pytest.mark.timeout(timeout=10, method="thread")
def test_mismatched_416_resume_keeps_in_progress_file(tmp_path: Path) -> None:
    source = AnyHttpUrl("https://test.com/stale.safetensors")
    destination = tmp_path / "stale.safetensors"
    in_progress_path = destination.with_name(destination.name + ".downloading")
    in_progress_path.write_bytes(b"stale data")

    session = TestSession()
    session.mount(
        str(source),
        TestAdapter(b"", status=416, headers={"Content-Range": "bytes */8"}),
    )
    queue = DownloadQueueService(requests_session=session, requests_session_is_trusted=True)
    queue.start()
    try:
        job = queue.download(source=source, dest=destination)
        queue.join()
    finally:
        queue.stop()

    assert job.status == DownloadJobStatus.PAUSED
    assert job.resume_required
    assert not destination.exists()
    assert in_progress_path.exists()


@pytest.mark.timeout(timeout=10, method="thread")
def test_refused_resume_keeps_the_partials_validator(tmp_path: Path) -> None:
    # The server ignores If-Range "v1" and sends the whole of a newer revision. Its ETag describes that revision,
    # not the partial on disk, so a later resume must not send it.
    source = AnyHttpUrl("https://test.com/changed.safetensors")
    destination = tmp_path / "changed.safetensors"
    in_progress_path = destination.with_name(destination.name + ".downloading")
    in_progress_path.write_bytes(b"old revision, first half")

    session = TestSession()
    new_revision = b"new revision"
    session.mount(
        str(source),
        TestAdapter(new_revision, headers={"ETag": '"v2"', "Content-Length": str(len(new_revision))}),
    )
    queue = DownloadQueueService(requests_session=session, requests_session_is_trusted=True)
    queue.start()
    try:
        job = DownloadJob(source=source, dest=destination, etag='"v1"')
        queue.submit_download_job(job)
        queue.join()
    finally:
        queue.stop()

    assert job.status == DownloadJobStatus.PAUSED
    assert job.resume_required and job.resume_refused
    assert job.etag == '"v1"'
    assert in_progress_path.read_bytes() == b"old revision, first half"
    assert not destination.exists()


class _RangeAdapter(TestAdapter):
    """Serves `data` under a Content-Disposition file name, honoring Range with HTTP 206 and If-Range by ETag."""

    def __init__(self, data: bytes, file_name: str, etag: str) -> None:
        super().__init__(data)
        self.data = data
        self.headers = {"Content-Disposition": f'attachment; filename="{file_name}"', "ETag": etag}

    def send(self, request, stream=False, **kwargs):
        headers = {**self.headers, "Content-Length": str(len(self.data))}
        byte_range = request.headers.get("Range")
        if byte_range and request.headers.get("If-Range") in (None, self.headers["ETag"]):
            start = int(byte_range.removeprefix("bytes=").removesuffix("-"))
            headers["Content-Length"] = str(len(self.data) - start)
            headers["Content-Range"] = f"bytes {start}-{len(self.data) - 1}/{len(self.data)}"
            return TestAdapter(self.data[start:], status=206, headers=headers).send(request, stream=stream, **kwargs)
        return TestAdapter(self.data, headers=headers).send(request, stream=stream, **kwargs)


@pytest.mark.parametrize("etag", ['"v1"', None], ids=["validated", "unvalidated"])
@pytest.mark.timeout(timeout=10, method="thread")
def test_directory_resume_never_appends_to_a_file_the_response_does_not_name(tmp_path: Path, etag: str | None) -> None:
    # A directory download resumes its only partial file, but the response names the file. When it names another,
    # the range it sends continues nothing on disk.
    source = AnyHttpUrl("https://test.com/download/model")
    data = b"0123456789abcdefghij"
    partial = tmp_path / "old_name.safetensors.downloading"
    partial.write_bytes(data[:10])
    session = TestSession()
    session.mount(str(source), _RangeAdapter(data, "new_name.safetensors", '"v1"'))
    queue = DownloadQueueService(requests_session=session, requests_session_is_trusted=True)
    queue.start()
    try:
        job = DownloadJob(source=source, dest=tmp_path, etag=etag)
        queue.submit_download_job(job)
        queue.join()
    finally:
        queue.stop()

    assert not (tmp_path / "new_name.safetensors").exists()
    assert not (tmp_path / "new_name.safetensors.downloading").exists()
    assert job.status == DownloadJobStatus.PAUSED
    assert job.resume_required and job.resume_refused
    # The pause records the partial it kept, so a restart can find and remove it.
    assert job.download_path == tmp_path / "old_name.safetensors"
    assert job.etag == etag  # the response's ETag describes the file it named, not this partial
    assert partial.read_bytes() == data[:10]


@pytest.mark.timeout(timeout=10, method="thread")
def test_event_bus(tmp_path: Path, mm2_session: Session) -> None:
    event_bus = TestEventService()

    queue = DownloadQueueService(requests_session=mm2_session, requests_session_is_trusted=True, event_bus=event_bus)
    queue.start()
    queue.download(
        source=AnyHttpUrl("http://www.civitai.com/models/12345"),
        dest=tmp_path,
    )
    queue.join()
    events = event_bus.events
    assert len(events) == 3
    assert isinstance(events[0], DownloadStartedEvent)
    assert isinstance(events[1], DownloadProgressEvent)
    assert isinstance(events[2], DownloadCompleteEvent)
    assert events[0].timestamp <= events[1].timestamp
    assert events[1].timestamp <= events[2].timestamp
    assert events[1].total_bytes > 0
    assert events[1].current_bytes <= events[1].total_bytes
    assert events[2].total_bytes == 32029

    # test a failure
    event_bus.events = []  # reset our accumulator
    queue.download(source=AnyHttpUrl("http://www.civitai.com/models/broken"), dest=tmp_path)
    queue.join()
    events = event_bus.events
    print("\n".join([x.model_dump_json() for x in events]))
    assert len(events) == 1
    assert isinstance(events[0], DownloadErrorEvent)
    assert events[0].error_type == "HTTPError(NOT FOUND)"
    assert events[0].error is not None
    assert re.search(r"requests.exceptions.HTTPError: NOT FOUND", events[0].error)
    queue.stop()


@pytest.mark.timeout(timeout=10, method="thread")
def test_broken_callbacks(tmp_path: Path, mm2_session: Session, capsys) -> None:
    queue = DownloadQueueService(
        requests_session=mm2_session,
        requests_session_is_trusted=True,
    )
    queue.start()

    callback_ran = False

    def broken_callback(job: DownloadJob) -> None:
        nonlocal callback_ran
        callback_ran = True
        print(1 / 0)  # deliberate error here

    job = queue.download(
        source=AnyHttpUrl("http://www.civitai.com/models/12345"),
        dest=tmp_path,
        on_progress=broken_callback,
    )

    queue.join()
    assert job.status == DownloadJobStatus.COMPLETED  # should complete even though the callback is borked
    assert Path(tmp_path, "mock12345.safetensors").exists()
    assert callback_ran
    # LS: The pytest capsys fixture does not seem to be working. I can see the
    # correct stderr message in the pytest log, but it is not appearing in
    # capsys.readouterr().
    # captured = capsys.readouterr()
    # assert re.search("division by zero", captured.err)
    queue.stop()


@pytest.mark.timeout(timeout=10, method="thread")
def test_cancel(tmp_path: Path, mm2_session: Session) -> None:
    event_bus = TestEventService()

    queue = DownloadQueueService(requests_session=mm2_session, requests_session_is_trusted=True, event_bus=event_bus)
    queue.start()

    cancelled = False

    def slow_callback(job: DownloadJob) -> None:
        time.sleep(2)

    def cancelled_callback(job: DownloadJob) -> None:
        nonlocal cancelled
        cancelled = True

    job = queue.download(
        source=AnyHttpUrl("http://www.civitai.com/models/12345"),
        dest=tmp_path,
        on_start=slow_callback,
        on_cancelled=cancelled_callback,
    )
    queue.cancel_job(job)
    queue.join()

    assert job.status == DownloadJobStatus.CANCELLED
    assert cancelled
    events = event_bus.events
    assert isinstance(events[-1], DownloadCancelledEvent)
    assert events[-1].source == "http://www.civitai.com/models/12345"
    queue.stop()


@pytest.mark.timeout(timeout=10, method="thread")
def test_multifile_download(tmp_path: Path, mm2_session: Session) -> None:
    fetcher = HuggingFaceMetadataFetch(mm2_session)
    metadata = fetcher.from_id("stabilityai/sdxl-turbo")
    assert isinstance(metadata, ModelMetadataWithFiles)
    events = set()

    def event_handler(job: DownloadJob | MultiFileDownloadJob, excp: Optional[Exception] = None) -> None:
        events.add(job.status)

    queue = DownloadQueueService(
        requests_session=mm2_session,
        requests_session_is_trusted=True,
    )
    queue.start()
    job = queue.multifile_download(
        parts=metadata.download_urls(session=mm2_session),
        dest=tmp_path,
        on_start=event_handler,
        on_progress=event_handler,
        on_complete=event_handler,
        on_error=event_handler,
    )
    assert isinstance(job, MultiFileDownloadJob), "expected the job to be of type MultiFileDownloadJobBase"
    queue.join()

    assert job.status == DownloadJobStatus("completed"), "expected job status to be completed"
    assert job.bytes > 0, "expected download bytes to be positive"
    assert job.bytes == job.total_bytes, "expected download bytes to equal total bytes"
    assert job.download_path == tmp_path / "sdxl-turbo"
    assert Path(tmp_path, "sdxl-turbo/model_index.json").exists(), (
        f"expected {tmp_path}/sdxl-turbo/model_inded.json to exist"
    )
    assert Path(tmp_path, "sdxl-turbo/text_encoder/config.json").exists(), (
        f"expected {tmp_path}/sdxl-turbo/text_encoder/config.json to exist"
    )

    assert events == {DownloadJobStatus.RUNNING, DownloadJobStatus.COMPLETED}
    queue.stop()


@pytest.mark.timeout(timeout=10, method="thread")
def test_multifile_error_worker_releases_paused_running_sibling_parent_reference(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    sibling_source = AnyHttpUrl("https://example.com/paused.safetensors")
    failed_source = AnyHttpUrl("https://example.com/failed.safetensors")
    sibling_path = tmp_path / "paused.safetensors"
    partial_path = sibling_path.with_name(f"{sibling_path.name}.downloading")
    sibling_at_pause = Event()
    release_sibling = Event()
    parent_failed = Event()
    parent_errors: list[str] = []

    class ControlledResponse(Response):
        def iter_content(self, chunk_size: int = 1, decode_unicode: bool = False):
            yield b"paused partial"
            sibling_at_pause.set()
            assert release_sibling.wait(timeout=5)
            yield b"discarded after pause"

    sibling_response = ControlledResponse()
    sibling_response.status_code = 200
    sibling_response.url = str(sibling_source)
    sibling_response.headers["content-length"] = "36"
    failed_response = Response()
    failed_response.status_code = 500
    failed_response.url = str(failed_source)
    failed_response.reason = "server error"

    session = Session()

    def controlled_get(url: str, **kwargs: Any) -> Response:
        return sibling_response if url == str(sibling_source) else failed_response

    monkeypatch.setattr(session, "get", controlled_get)
    queue = DownloadQueueService(
        max_parallel_dl=2,
        requests_session=session,
        requests_session_is_trusted=True,
    )
    monkeypatch.setattr(queue, "_validate_url", lambda url: None)
    queue.start()

    failed_part = DownloadJob(id=10, source=failed_source, dest=tmp_path / "failed.safetensors", priority=1)
    paused_sibling = DownloadJob(id=11, source=sibling_source, dest=sibling_path, priority=0)
    parent = MultiFileDownloadJob(
        id=12,
        dest=tmp_path,
        download_parts={failed_part, paused_sibling},
    )
    parent.set_callbacks(on_error=lambda job, excp=None: (parent_errors.append(job.status.value), parent_failed.set()))
    queue._download_part2parent[failed_part.id] = parent
    queue._download_part2parent[paused_sibling.id] = parent

    callbacks = {
        "on_start": queue._mfd_started,
        "on_progress": queue._mfd_progress,
        "on_complete": queue._mfd_complete,
        "on_cancelled": queue._mfd_cancelled,
        "on_error": queue._mfd_error,
    }
    try:
        queue.submit_download_job(paused_sibling, **callbacks)
        assert sibling_at_pause.wait(timeout=5)
        queue.pause_job(paused_sibling)
        queue.submit_download_job(failed_part, **callbacks)

        assert parent_failed.wait(timeout=5)
        assert parent.status == DownloadJobStatus.ERROR
        assert paused_sibling.status == DownloadJobStatus.RUNNING
        assert paused_sibling.id in queue._download_part2parent

        release_sibling.set()
        queue.join()

        assert paused_sibling.status == DownloadJobStatus.PAUSED
        assert partial_path.read_bytes() == b"paused partial"
        assert paused_sibling.id not in queue._download_part2parent
        assert parent_errors == [DownloadJobStatus.ERROR.value]
    finally:
        release_sibling.set()
        queue.stop()


@pytest.mark.timeout(timeout=10, method="thread")
def test_multifile_download_error(tmp_path: Path, mm2_session: Session) -> None:
    fetcher = HuggingFaceMetadataFetch(mm2_session)
    metadata = fetcher.from_id("stabilityai/sdxl-turbo")
    assert isinstance(metadata, ModelMetadataWithFiles)
    events = set()

    def event_handler(job: DownloadJob | MultiFileDownloadJob, excp: Optional[Exception] = None) -> None:
        events.add(job.status)

    queue = DownloadQueueService(
        requests_session=mm2_session,
        requests_session_is_trusted=True,
    )
    queue.start()
    files = metadata.download_urls(session=mm2_session)
    # this will give a 404 error
    files.append(RemoteModelFile(url="https://test.com/missing_model.safetensors", path=Path("sdxl-turbo/broken")))
    job = queue.multifile_download(
        parts=files,
        dest=tmp_path,
        on_start=event_handler,
        on_progress=event_handler,
        on_complete=event_handler,
        on_error=event_handler,
    )
    queue.join()

    assert job.status == DownloadJobStatus("error"), "expected job status to be errored"
    assert job.error_type is not None
    assert "HTTPError(NOT FOUND)" in job.error_type
    assert DownloadJobStatus.ERROR in events
    queue.stop()


@pytest.mark.timeout(timeout=10, method="thread")
def test_multifile_cancel(tmp_path: Path, mm2_session: Session, monkeypatch: Any) -> None:
    event_bus = TestEventService()

    queue = DownloadQueueService(requests_session=mm2_session, requests_session_is_trusted=True, event_bus=event_bus)
    queue.start()

    cancelled = False

    def cancelled_callback(job: DownloadJob) -> None:
        nonlocal cancelled
        cancelled = True

    fetcher = HuggingFaceMetadataFetch(mm2_session)
    metadata = fetcher.from_id("stabilityai/sdxl-turbo")
    assert isinstance(metadata, ModelMetadataWithFiles)

    job = queue.multifile_download(
        parts=metadata.download_urls(session=mm2_session),
        dest=tmp_path,
        on_cancelled=cancelled_callback,
    )
    queue.cancel_job(job)
    queue.join()

    assert job.status == DownloadJobStatus.CANCELLED
    assert cancelled
    events = event_bus.events
    assert DownloadCancelledEvent in [type(x) for x in events]
    queue.stop()


def test_multifile_onefile(tmp_path: Path, mm2_session: Session) -> None:
    queue = DownloadQueueService(
        requests_session=mm2_session,
        requests_session_is_trusted=True,
    )
    queue.start()
    job = queue.multifile_download(
        parts=[
            RemoteModelFile(url=AnyHttpUrl("http://www.civitai.com/models/12345"), path=Path("mock12345.safetensors"))
        ],
        dest=tmp_path,
    )
    assert isinstance(job, MultiFileDownloadJob), "expected the job to be of type MultiFileDownloadJobBase"
    queue.join()

    assert job.status == DownloadJobStatus("completed"), "expected job status to be completed"
    assert job.bytes > 0, "expected download bytes to be positive"
    assert job.bytes == job.total_bytes, "expected download bytes to equal total bytes"
    assert job.download_path == tmp_path / "mock12345.safetensors"
    assert Path(tmp_path, "mock12345.safetensors").exists(), f"expected {tmp_path}/mock12345.safetensors to exist"
    queue.stop()


def test_multifile_download_with_relative_dest(tmp_path: Path, mm2_session: Session, monkeypatch: Any) -> None:
    started_paths: list[Path | None] = []
    monkeypatch.chdir(tmp_path)
    queue = DownloadQueueService(
        requests_session=mm2_session,
        requests_session_is_trusted=True,
    )
    queue.start()
    job = queue.multifile_download(
        parts=[
            RemoteModelFile(
                url=AnyHttpUrl("http://www.civitai.com/models/12345"),
                path=Path("nested/mock12345.safetensors"),
            )
        ],
        dest=Path("relative-downloads"),
        on_start=lambda job: started_paths.append(job.download_path),
    )
    queue.join()

    assert job.status == DownloadJobStatus("completed"), "expected job status to be completed"
    assert job.download_path == tmp_path / "relative-downloads/nested"
    assert started_paths == [tmp_path / "relative-downloads/nested"]
    assert Path(tmp_path, "relative-downloads/nested/mock12345.safetensors").exists()
    queue.stop()


def test_multifile_no_rel_paths(tmp_path: Path, mm2_session: Session) -> None:
    queue = DownloadQueueService(
        requests_session=mm2_session,
        requests_session_is_trusted=True,
    )

    with pytest.raises(ValueError) as error:
        queue.multifile_download(
            parts=[RemoteModelFile(url=AnyHttpUrl("http://www.civitai.com/models/12345"), path=Path("/etc/passwd"))],
            dest=tmp_path,
        )
    assert str(error.value) == "only relative download paths accepted"


def test_multifile_no_parent_traversal_paths(tmp_path: Path, mm2_session: Session) -> None:
    queue = DownloadQueueService(
        requests_session=mm2_session,
        requests_session_is_trusted=True,
    )

    with pytest.raises(ValueError) as error:
        queue.multifile_download(
            parts=[
                RemoteModelFile(
                    url=AnyHttpUrl("http://www.civitai.com/models/12345"),
                    path=Path("../outside.safetensors"),
                )
            ],
            dest=tmp_path,
        )
    assert str(error.value) == "only relative download paths accepted"


@contextmanager
def clear_config() -> Generator[None, None, None]:
    try:
        yield None
    finally:
        get_config.cache_clear()


def test_tokens(tmp_path: Path, mm2_session: Session):
    with clear_config():
        config = get_config()
        config.remote_api_tokens = [URLRegexTokenPair(url_regex="civitai", token="cv_12345")]
        queue = DownloadQueueService(requests_session=mm2_session, requests_session_is_trusted=True)
        queue.start()
        # this one has an access token assigned
        job1 = queue.download(
            source=AnyHttpUrl("http://www.civitai.com/models/12345"),
            dest=tmp_path,
        )
        # this one doesn't
        job2 = queue.download(
            source=AnyHttpUrl(
                "http://www.huggingface.co/foo.txt",
            ),
            dest=tmp_path,
        )
        queue.join()
        # this token is defined in the temporary root invokeai.yaml
        # see tests/backend/model_manager/data/invokeai_root/invokeai.yaml
        assert job1.access_token == "cv_12345"
        assert job2.access_token is None
        queue.stop()


# ---------------- Advisory regression: SSRF guard in the download worker ----------------


def test_production_queue_uses_guarded_session_by_default() -> None:
    queue = DownloadQueueService(app_config=InvokeAIAppConfig(allow_private_download_urls=False))
    try:
        assert isinstance(queue._requests.get_adapter("https://example.com"), ssrf.SsrfGuardedAdapter)
        assert queue._requests.trust_env is True
    finally:
        queue._requests.close()


def test_caller_supplied_session_requires_explicit_trust() -> None:
    config = InvokeAIAppConfig(allow_private_download_urls=False)
    session = Session()
    try:
        with pytest.raises(ValueError, match="requests_session_is_trusted=True"):
            DownloadQueueService(
                app_config=config,
                requests_session=session,
            )
    finally:
        session.close()


def test_caller_supplied_guarded_session_does_not_require_attestation() -> None:
    session = ssrf.build_guarded_session()
    try:
        queue = DownloadQueueService(
            app_config=InvokeAIAppConfig(allow_private_download_urls=False),
            requests_session=session,
        )
        assert queue._requests is session
    finally:
        session.close()


def test_caller_supplied_session_accepts_explicit_trust() -> None:
    session = Session()
    try:
        queue = DownloadQueueService(
            app_config=InvokeAIAppConfig(allow_private_download_urls=False),
            requests_session=session,
            requests_session_is_trusted=True,
        )
        assert queue._requests is session
    finally:
        session.close()


def test_production_queue_allows_explicit_private_download_opt_in() -> None:
    queue = DownloadQueueService(app_config=InvokeAIAppConfig(allow_private_download_urls=True))
    try:
        assert not isinstance(queue._requests.get_adapter("https://example.com"), ssrf.SsrfGuardedAdapter)
    finally:
        queue._requests.close()


def test_production_queue_accepts_explicit_download_proxy() -> None:
    queue = DownloadQueueService(
        app_config=InvokeAIAppConfig(
            allow_private_download_urls=False,
            download_proxy="http://proxy.internal:3128",
        )
    )
    try:
        assert ssrf.proxies_in_effect(queue._requests) == {
            "http": "http://proxy.internal:3128",
            "https": "http://proxy.internal:3128",
        }
    finally:
        queue._requests.close()


def test_private_opt_in_still_honors_explicit_download_proxy(monkeypatch: Any) -> None:
    """allow_private_download_urls=True must not silently drop an explicitly configured
    download_proxy: the two settings are independent. The proxy is applied at request
    level because that is the only level that beats ambient *_PROXY variables in a
    plain (unguarded) Session."""
    monkeypatch.setenv("HTTP_PROXY", "http://ambient.invalid:9")
    monkeypatch.setenv("HTTPS_PROXY", "http://ambient.invalid:9")
    queue = DownloadQueueService(
        app_config=InvokeAIAppConfig(
            allow_private_download_urls=True,
            download_proxy="http://proxy.internal:3128",
        )
    )
    try:
        assert queue._request_proxies == {
            "http": "http://proxy.internal:3128",
            "https": "http://proxy.internal:3128",
        }
        # The explicit proxy must win over the ambient variables in requests' merge order.
        merged = queue._requests.merge_environment_settings(
            "https://example.com/x", queue._request_proxies, None, None, None
        )
        assert merged["proxies"]["https"] == "http://proxy.internal:3128"
    finally:
        queue._requests.close()


def test_head_request_is_sent_like_a_download(monkeypatch: Any) -> None:
    """The installer asks a host for a file's commit with `head()`; it must take the downloads' address policy and
    explicit download proxy, and must not follow redirects."""
    session = TestSession()
    session.mount(
        "https://hub.example/file", TestAdapter(b"", status=302, headers={"Location": "https://cdn.example/x"})
    )
    queue = DownloadQueueService(
        app_config=InvokeAIAppConfig(allow_private_download_urls=True, download_proxy="http://proxy.internal:3128"),
        requests_session=session,
        requests_session_is_trusted=True,
    )
    queue._request_proxies = {"http": "http://proxy.internal:3128", "https": "http://proxy.internal:3128"}
    sent: list[dict[str, Any]] = []
    real_send = session.send
    monkeypatch.setattr(session, "send", lambda request, **kwargs: sent.append(kwargs) or real_send(request, **kwargs))

    response = queue.head("https://hub.example/file", headers={"Authorization": "Bearer t"})

    assert response.status_code == 302
    assert sent[0]["proxies"]["https"] == "http://proxy.internal:3128"
    assert sent[0]["allow_redirects"] is False

    guarded = DownloadQueueService(
        app_config=InvokeAIAppConfig(allow_private_download_urls=False),
        requests_session=TestSession(),
        requests_session_is_trusted=True,
    )
    with pytest.raises(UnsafeDownloadURLException):
        guarded.head("http://127.0.0.1:19191/file")


@pytest.mark.timeout(timeout=10, method="thread")
def test_download_from_a_server_that_stalls_mid_body_errors_instead_of_hanging(
    tmp_path: Path, monkeypatch: Any
) -> None:
    """A server that sends part of the body and then goes silent must not hold the worker forever."""
    monkeypatch.setattr(download_default, "DOWNLOAD_TIMEOUT", (2, 0.5))
    # Talk to the local server directly: an ambient proxy would fail the request for an unrelated reason.
    monkeypatch.setenv("NO_PROXY", "*")
    monkeypatch.setenv("no_proxy", "*")
    release = Event()
    listener = socket.create_server(("127.0.0.1", 0))
    port = listener.getsockname()[1]

    def stall() -> None:
        conn, _ = listener.accept()
        with conn:
            conn.recv(65536)
            conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 1000000\r\n\r\n" + b"x" * 1000)
            release.wait(timeout=10)

    server = Thread(target=stall, daemon=True)
    server.start()
    queue = DownloadQueueService(app_config=InvokeAIAppConfig(allow_private_download_urls=True))
    queue.start()
    try:
        job = queue.download(source=AnyHttpUrl(f"http://127.0.0.1:{port}/model.safetensors"), dest=tmp_path)
        queue.wait_for_job(job, timeout=5)
        assert job.status == DownloadJobStatus.ERROR
        assert "Read timed out" in (job.error_type or "")
    finally:
        release.set()
        queue.stop()
        server.join(timeout=5)
        listener.close()


@pytest.mark.timeout(timeout=10, method="thread")
def test_download_refuses_non_public_source(tmp_path: Path) -> None:
    """A job whose source points at loopback errors out without issuing the request."""
    source = AnyHttpUrl("http://127.0.0.1:19191/proof.txt")
    session = TestSession()
    session.mount(str(source), TestAdapter(b"secret", status=200))

    queue = DownloadQueueService(requests_session=session, requests_session_is_trusted=True)
    queue.start()
    try:
        job = queue.download(source=source, dest=tmp_path)
        queue.join()
    finally:
        queue.stop()

    assert job.status == DownloadJobStatus.ERROR
    assert "UnsafeDownloadURLException" in (job.error_type or "")
    assert not any(tmp_path.iterdir())


@pytest.mark.timeout(timeout=10, method="thread")
def test_download_refuses_redirect_to_non_public_address(tmp_path: Path) -> None:
    """A public URL must not be able to bounce the worker onto a private address."""
    source = AnyHttpUrl("https://test.com/redirector")
    session = TestSession()
    session.mount(
        str(source),
        TestAdapter(b"", status=302, headers={"Location": "http://169.254.169.254/latest/meta-data/"}),
    )
    session.mount("http://169.254.169.254/", TestAdapter(b"cloud-credentials", status=200))

    queue = DownloadQueueService(requests_session=session, requests_session_is_trusted=True)
    queue.start()
    try:
        job = queue.download(source=source, dest=tmp_path)
        queue.join()
    finally:
        queue.stop()

    assert job.status == DownloadJobStatus.ERROR
    assert "UnsafeDownloadURLException" in (job.error_type or "")
    assert not any(tmp_path.iterdir())


def test_rejected_redirect_closes_streamed_response() -> None:
    queue = DownloadQueueService(requests_session=TestSession(), requests_session_is_trusted=True)
    response = Response()
    response.status_code = 302
    response.url = "https://public.example/redirect"
    response.headers["Location"] = "http://127.0.0.1/private"
    response.raw = MagicMock()

    with pytest.raises(UnsafeDownloadURLException):
        queue._reject_unsafe_redirect(response)

    response.raw.close.assert_called_once()


@pytest.mark.timeout(timeout=10, method="thread")
def test_download_refuses_multi_hop_redirect_to_non_public_address(tmp_path: Path) -> None:
    """Every redirect response must be checked, not only the first hop."""
    source = AnyHttpUrl("https://test.com/redirector-1")
    second_hop = "https://test.com/redirector-2"
    session = TestSession()
    session.mount(
        str(source),
        TestAdapter(b"", status=302, headers={"Location": second_hop}),
    )
    session.mount(
        second_hop,
        TestAdapter(b"", status=302, headers={"Location": "http://169.254.169.254/latest/meta-data/"}),
    )

    queue = DownloadQueueService(requests_session=session, requests_session_is_trusted=True)
    queue.start()
    try:
        job = queue.download(source=source, dest=tmp_path)
        queue.join()
    finally:
        queue.stop()

    assert job.status == DownloadJobStatus.ERROR
    assert "UnsafeDownloadURLException" in (job.error_type or "")
    assert not any(tmp_path.iterdir())


@pytest.mark.timeout(timeout=10, method="thread")
def test_download_allows_non_public_source_when_opted_in(tmp_path: Path) -> None:
    source = AnyHttpUrl("http://127.0.0.1:19191/mirror.safetensors")
    session = TestSession()
    session.mount(str(source), TestAdapter(b"model-bytes", status=200))

    config = get_config()
    with patch.object(config, "allow_private_download_urls", True):
        queue = DownloadQueueService(app_config=config, requests_session=session)
        queue.start()
        try:
            job = queue.download(source=source, dest=tmp_path / "mirror.safetensors")
            queue.join()
        finally:
            queue.stop()

    assert job.status == DownloadJobStatus.COMPLETED
    assert (tmp_path / "mirror.safetensors").read_bytes() == b"model-bytes"


@pytest.mark.parametrize(
    "filename",
    ["../evil", "..\\evil", "sub/evil", "sub\\evil", "C:\\evil", "C:evil", "/evil", ".", "..", ""],
)
def test_content_disposition_filename_must_be_one_safe_component(filename: str) -> None:
    """The remote server picks this name; it must never be able to leave `dest`."""
    queue = DownloadQueueService()
    assert queue._validate_filename("/tmp", filename) is False


@pytest.mark.timeout(timeout=10, method="thread")
def test_multifile_cancel_callback_runs_after_partial_cleanup(tmp_path: Path, monkeypatch: Any) -> None:
    import threading

    from invokeai.app.services.download.download_base import DownloadJobCancelledException

    queue = DownloadQueueService(max_parallel_dl=1)
    download_started = threading.Event()
    release_download = threading.Event()
    in_progress = tmp_path / "model.safetensors.downloading"
    callback_saw_partial: list[bool] = []

    def fake_download(job: DownloadJob) -> None:
        job.download_path = job.dest
        in_progress.write_bytes(b"partial")
        queue._signal_job_started(job)
        download_started.set()
        assert release_download.wait(timeout=5)
        raise DownloadJobCancelledException("cancelled for test")

    monkeypatch.setattr(queue, "_do_download", fake_download)
    queue.start()
    try:
        job = queue.multifile_download(
            parts=[RemoteModelFile(url="https://example.com/model.safetensors", path=Path("model.safetensors"))],
            dest=tmp_path,
            on_cancelled=lambda _job: callback_saw_partial.append(in_progress.exists()),
        )
        assert download_started.wait(timeout=5)
        queue.cancel_job(job)
        part_cancelled = next(iter(job.download_parts)).cancelled
        release_download.set()
        queue.join()
    finally:
        queue.stop()

    assert part_cancelled
    assert callback_saw_partial == [False]
    assert job.status == DownloadJobStatus.CANCELLED


@pytest.mark.timeout(timeout=10, method="thread")
def test_stop_notifies_paused_queued_multifile_download(tmp_path: Path, monkeypatch: Any) -> None:
    import threading

    from invokeai.app.services.download.download_base import DownloadJobCancelledException

    queue = DownloadQueueService(max_parallel_dl=1)
    blocker_started = threading.Event()
    pause_callback_statuses: list[DownloadJobStatus] = []

    def fake_download(job: DownloadJob) -> None:
        queue._signal_job_started(job)
        blocker_started.set()
        while not job.cancelled:
            time.sleep(0.005)
        raise DownloadJobCancelledException("cancelled for test")

    monkeypatch.setattr(queue, "_do_download", fake_download)
    queue.start()
    try:
        queue.download(source=AnyHttpUrl("https://example.com/blocker"), dest=tmp_path / "blocker")
        assert blocker_started.wait(timeout=5)
        job = queue.multifile_download(
            parts=[RemoteModelFile(url="https://example.com/model.safetensors", path=Path("model.safetensors"))],
            dest=tmp_path / "staging",
            on_cancelled=lambda paused_job: pause_callback_statuses.append(paused_job.status),
        )
        part = next(iter(job.download_parts))
        queue.pause_job(part)
        queue.stop()
    finally:
        queue.stop()

    assert job.status == DownloadJobStatus.PAUSED
    assert pause_callback_statuses == [DownloadJobStatus.PAUSED]


@pytest.mark.timeout(timeout=10, method="thread")
def test_stop_pauses_multifile_download_after_current_part_completes(tmp_path: Path, monkeypatch: Any) -> None:
    import threading

    queue = DownloadQueueService(max_parallel_dl=1)
    part_started = threading.Event()
    release_part = threading.Event()
    callback_statuses: list[DownloadJobStatus] = []

    def fake_download(job: DownloadJob) -> None:
        job.download_path = job.dest
        queue._signal_job_started(job)
        part_started.set()
        assert release_part.wait(timeout=5)
        job.dest.parent.mkdir(parents=True, exist_ok=True)
        job.dest.write_bytes(b"complete part")

    monkeypatch.setattr(queue, "_do_download", fake_download)
    queue.start()
    stop_thread: threading.Thread | None = None
    try:
        job = queue.multifile_download(
            parts=[
                RemoteModelFile(url="https://example.com/part-1", path=Path("model/part-1")),
                RemoteModelFile(url="https://example.com/part-2", path=Path("model/part-2")),
            ],
            dest=tmp_path / "staging",
            on_cancelled=lambda paused_job: callback_statuses.append(paused_job.status),
        )
        parts = {str(part.source): part for part in job.download_parts}
        assert part_started.wait(timeout=5)
        for part in parts.values():
            queue.pause_job(part)

        stop_thread = threading.Thread(target=queue.stop)
        stop_thread.start()
        assert queue._stop_event.wait(timeout=5)
        release_part.set()
        stop_thread.join(timeout=5)
    finally:
        release_part.set()
        if stop_thread is not None:
            stop_thread.join(timeout=5)
        queue.stop()

    assert stop_thread is not None and not stop_thread.is_alive()
    assert job.status == DownloadJobStatus.PAUSED
    assert callback_statuses == [DownloadJobStatus.PAUSED]