Commit 2ba54201 authored by Mickaël Desfrênes's avatar Mickaël Desfrênes
Browse files

fix upload races

parent 5d7e37e6
Loading
Loading
Loading
Loading
+7 −3
Changes for src/rpc/methods.py: 7 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -1337,6 +1337,12 @@ def project_items(
    )


def _partial_upload_dir(user: User, project: Project, file_hash: str) -> str:
    return "{}/{}-{}-{}".format(
        settings.PARTIAL_UPLOADS_DIR, user.pk, project.pk, file_hash
    )


@_rpc_groups(["Utilities"])
def upload_infos(user: User, sha256_hash: str, project_id: int) -> Dict:
    """
@@ -1367,9 +1373,7 @@ def upload_infos(user: User, sha256_hash: str, project_id: int) -> Dict:
            infos["status"] = "available"
            infos["id"] = file_instance.pk
        except File.DoesNotExist:
            partials_dir = "{}/{}-{}".format(
                settings.PARTIAL_UPLOADS_DIR, user.pk, sha256_hash
            )
            partials_dir = _partial_upload_dir(user, project, sha256_hash)
            if os.path.isdir(partials_dir):
                infos["status"] = "incomplete"
                for path in _glob("{}/*.part".format(partials_dir)):
+72
Changes for src/rpc/tests.py: 72 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -389,6 +389,78 @@ class ServiceTestCase(TestCase):

        self.assertEqual(response.status_code, 403)

    def test_upload_lock_creation_is_exclusive(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            lock_file_path = os.path.join(tmpdir, ".lock")

            self.assertTrue(views._try_create_upload_lock(lock_file_path))
            self.assertFalse(views._try_create_upload_lock(lock_file_path))

    def test_write_request_body_uses_unique_temporary_file(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            destination = os.path.join(tmpdir, "1-1.part")
            old_shared_tmp = f"{destination}.uploading"
            with open(old_shared_tmp, "wb") as f:
                f.write(b"old upload")
            request = self.factory.post(
                "/rpc/upload/partial/",
                data=b"new upload",
                content_type="application/octet-stream",
                CONTENT_LENGTH="10",
            )

            self.assertTrue(views._write_request_body_to_file(request, destination, 10))

            with open(destination, "rb") as f:
                self.assertEqual(f.read(), b"new upload")
            with open(old_shared_tmp, "rb") as f:
                self.assertEqual(f.read(), b"old upload")
            self.assertEqual(
                [name for name in os.listdir(tmpdir) if name.endswith(".uploading")],
                ["1-1.part.uploading"],
            )

    def test_partial_upload_dir_is_scoped_by_project(self):
        other_project = models.Project.objects.create(label="other")
        file_hash = "4" * 64

        self.assertNotEqual(
            views._partial_upload_dir(self.test_user, self.test_project, file_hash),
            views._partial_upload_dir(self.test_user, other_project, file_hash),
        )

    def test_upload_infos_uses_project_scoped_partial_dir(self):
        other_project = models.Project.objects.create(label="other")
        file_hash = "5" * 64

        with tempfile.TemporaryDirectory() as tmpdir:
            with patch.object(methods.settings, "PARTIAL_UPLOADS_DIR", tmpdir):
                partials_dir = methods._partial_upload_dir(
                    self.test_user, self.test_project, file_hash
                )
                other_partials_dir = methods._partial_upload_dir(
                    self.test_user, other_project, file_hash
                )
                os.makedirs(partials_dir)
                with open(os.path.join(partials_dir, "2-1.part"), "wb") as f:
                    f.write(b"chunk")

                self.assertEqual(
                    methods.upload_infos(
                        self.test_user, file_hash, self.test_project.pk
                    ),
                    {
                        "status": "incomplete",
                        "id": None,
                        "available_chunks": ["2-1.part"],
                    },
                )
                self.assertFalse(os.path.exists(other_partials_dir))
                self.assertEqual(
                    methods.upload_infos(self.test_user, file_hash, other_project.pk),
                    {"status": "not available", "id": None, "available_chunks": []},
                )

    def test_upload_partial_origin_dir_requires_collection_create_access(self):
        file_instance = self._public_download_test_file()
        models.ObjectPermission.objects.filter(
+29 −4
Changes for src/rpc/views.py: 29 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -142,6 +142,12 @@ def _add_file_to_origin_collection(
    return collection


def _partial_upload_dir(user: User, project: models.Project, file_hash: str) -> str:
    return "{}/{}-{}-{}".format(
        settings.PARTIAL_UPLOADS_DIR, user.pk, project.pk, file_hash
    )


def _join_parts(
    parts_dir: str, destination: str, sha256sum: str, total_parts: int
) -> bool:
@@ -266,10 +272,18 @@ def _request_content_length(request: HttpRequest) -> int:
def _write_request_body_to_file(
    request: HttpRequest, destination: str, expected_size: int
) -> bool:
    tmp_destination = "{}.uploading".format(destination)
    destination_path = Path(destination)
    tmp_destination = None
    bytes_written = 0
    try:
        with open(tmp_destination, "wb") as f:
        with tempfile.NamedTemporaryFile(
            mode="wb",
            dir=destination_path.parent,
            prefix=f"{destination_path.name}.",
            suffix=".uploading",
            delete=False,
        ) as f:
            tmp_destination = f.name
            while True:
                chunk = request.read(1024 * 1024)
                if not chunk:
@@ -283,9 +297,19 @@ def _write_request_body_to_file(
        os.replace(tmp_destination, destination)
        return True
    finally:
        if tmp_destination:
            _silent_remove(tmp_destination)


def _try_create_upload_lock(lock_file_path: str) -> bool:
    try:
        fd = os.open(lock_file_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except FileExistsError:
        return False
    os.close(fd)
    return True


@lru_cache(None, typed=True)
def _get_rpc_methods() -> dict:
    methods = {}
@@ -470,7 +494,7 @@ def upload_partial(request: HttpRequest) -> HttpResponse:
    except models.File.DoesNotExist:
        pass

    partials_dir = "{}/{}-{}".format(settings.PARTIAL_UPLOADS_DIR, user.pk, file_hash)
    partials_dir = _partial_upload_dir(user, project, file_hash)
    lock_file_path = "{}/.lock".format(partials_dir)
    if os.path.isfile(lock_file_path):
        return HttpResponse(status=202)
@@ -501,7 +525,8 @@ def upload_partial(request: HttpRequest) -> HttpResponse:
    if len(glob("{}/{}-*.part".format(partials_dir, total_chunks))) == int(
        total_chunks
    ) or os.path.exists(f_name):
        Path(lock_file_path).touch()  # lock dir
        if not _try_create_upload_lock(lock_file_path):
            return HttpResponse(status=202)

        if not os.path.exists(f_name):
            checksum_ok = _join_parts(partials_dir, f_name, file_hash, total_chunks)