Skip to content

Commit

Permalink
feat(debug): allow files and folder deletion inside debug view
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinBelthle committed Sep 19, 2024
1 parent 6a4bc9c commit b9ec2a9
Show file tree
Hide file tree
Showing 4 changed files with 103 additions and 0 deletions.
10 changes: 10 additions & 0 deletions antarest/core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,16 @@ def __init__(self, is_variant: bool) -> None:
super().__init__(HTTPStatus.EXPECTATION_FAILED, "Upgrade not supported for parent of variants")


class FileDeletionNotAllowed(HTTPException):
"""
Exception raised when deleting a file or a folder which isn't inside the 'User' folder.
"""

def __init__(self, message: str) -> None:
msg = f"Raw deletion failed because {message}"
super().__init__(HTTPStatus.FORBIDDEN, msg)


class ReferencedObjectDeletionNotAllowed(HTTPException):
"""
Exception raised when a binding constraint is not allowed to be deleted because it references
Expand Down
30 changes: 30 additions & 0 deletions antarest/study/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
BadEditInstructionException,
ChildNotFoundError,
CommandApplicationError,
FileDeletionNotAllowed,
IncorrectPathError,
NotAManagedStudyException,
ReferencedObjectDeletionNotAllowed,
Expand Down Expand Up @@ -2639,3 +2640,32 @@ def asserts_no_thermal_in_binding_constraints(
if ref_bcs:
binding_ids = [bc.id for bc in ref_bcs]
raise ReferencedObjectDeletionNotAllowed(cluster_id, binding_ids, object_type="Cluster")

def delete_file_or_folder(self, study_id: str, path: str, current_user: JWTUser) -> None:
"""
Deletes a file or a folder of the study.
The data must be located inside the 'User' folder.
Also, it can not be inside the 'expansion' folder.
Args:
study_id: UUID of the concerned study
path: Path corresponding to the resource to be deleted
current_user: User that called the endpoint
Raises:
FileDeletionNotAllowed: if the path does not comply with the above rules
"""
study = self.get_study(study_id)
assert_permission(current_user, study, StudyPermissionType.WRITE)

url = [item for item in path.split("/") if item]
if len(url) < 2 or url[0] != "user":
raise FileDeletionNotAllowed(f"the targeted data isn't inside the 'User' folder: {path}")
if url[1] == "expansion":
raise FileDeletionNotAllowed(f"you cannot delete a file/folder inside 'expansion' folder : {path}")

study_tree = self.storage_service.raw_study_service.get_raw(study, True).tree.build()
try:
study_tree["user"].delete(url[1:])
except ChildNotFoundError as e:
raise FileDeletionNotAllowed(f"the given path doesn't exist: {e.detail}")
15 changes: 15 additions & 0 deletions antarest/study/web/raw_studies_blueprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,21 @@ def get_study(
json_response = to_json(output)
return Response(content=json_response, media_type="application/json")

@bp.delete(
"/studies/{uuid}/raw",
tags=[APITag.study_raw_data],
summary="Delete files or folders located inside the 'User' folder",
response_model=None,
)
def delete_file(
uuid: str,
path: str = Param("/", examples=["user/wind_solar/synthesis_windSolar.xlsx"]), # type: ignore
current_user: JWTUser = Depends(auth.get_current_user),
) -> t.Any:
uuid = sanitize_uuid(uuid)
logger.info(f"Deleting some data for study {uuid}", extra={"user": current_user.id})
study_service.delete_file_or_folder(uuid, path, current_user)

@bp.get(
"/studies/{uuid}/areas/aggregate/mc-ind/{output_id}",
tags=[APITag.study_raw_data],
Expand Down
48 changes: 48 additions & 0 deletions tests/integration/raw_studies_blueprint/test_fetch_raw_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,3 +264,51 @@ def test_get_study(
headers=headers,
)
assert res.status_code == 200, f"Error for path={path} and depth={depth}"


def test_delete_raw(client: TestClient, user_access_token: str, internal_study_id: str) -> None:
client.headers = {"Authorization": f"Bearer {user_access_token}"}

# =============================
# SET UP + NOMINAL CASES
# =============================

content = io.BytesIO(b"This is the end!")
file_1_path = "user/file_1.txt"
file_2_path = "user/folder/file_2.txt"
for f in [file_1_path, file_2_path]:
# Creates a file / folder inside user folder.
res = client.put(
f"/v1/studies/{internal_study_id}/raw", params={"path": f, "create_missing": True}, files={"file": content}
)
assert res.status_code == 204, res.json()

# Deletes the file / folder
res = client.delete(f"/v1/studies/{internal_study_id}/raw?path={f}")
assert res.status_code == 200
# Asserts it doesn't exist anymore
res = client.get(f"/v1/studies/{internal_study_id}/raw?path={f}")
assert res.status_code == 404
assert "not a child of" in res.json()["description"]

# =============================
# ERRORS
# =============================

# try to delete expansion folder
res = client.delete(f"/v1/studies/{internal_study_id}/raw?path=/user/expansion")
assert res.status_code == 403
assert res.json()["exception"] == "FileDeletionNotAllowed"
assert "you cannot delete a file/folder inside 'expansion' folder" in res.json()["description"]

# try to delete a file which isn't inside the 'User' folder
res = client.delete(f"/v1/studies/{internal_study_id}/raw?path=/input/thermal")
assert res.status_code == 403
assert res.json()["exception"] == "FileDeletionNotAllowed"
assert "the targeted data isn't inside the 'User' folder" in res.json()["description"]

# With a path that doesn't exist
res = client.delete(f"/v1/studies/{internal_study_id}/raw?path=user/fake_folder/fake_file.txt")
assert res.status_code == 403
assert res.json()["exception"] == "FileDeletionNotAllowed"
assert "the given path doesn't exist" in res.json()["description"]

0 comments on commit b9ec2a9

Please sign in to comment.